openfox 1.6.47 → 1.6.50

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.
@@ -54,7 +54,7 @@ Error generating stack: `+f.message+`
54
54
  *
55
55
  * This source code is licensed under the MIT license found in the
56
56
  * LICENSE file in the root directory of this source tree.
57
- */var Mx;function b1(){if(Mx)return Hd;Mx=1;var e=ac();function r(m,b){return m===b&&(m!==0||1/m===1/b)||m!==m&&b!==b}var s=typeof Object.is=="function"?Object.is:r,i=e.useState,l=e.useEffect,u=e.useLayoutEffect,h=e.useDebugValue;function c(m,b){var _=b(),k=i({inst:{value:_,getSnapshot:b}}),C=k[0].inst,y=k[1];return u(function(){C.value=_,C.getSnapshot=b,d(C)&&y({inst:C})},[m,_,b]),l(function(){return d(C)&&y({inst:C}),m(function(){d(C)&&y({inst:C})})},[m]),h(_),_}function d(m){var b=m.getSnapshot;m=m.value;try{var _=b();return!s(m,_)}catch{return!0}}function p(m,b){return b()}var g=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?p:c;return Hd.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:g,Hd}var Ix;function y1(){return Ix||(Ix=1,Pd.exports=b1()),Pd.exports}var _1=y1();const S1=a1.useInsertionEffect,w1=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",C1=w1?H.useLayoutEffect:H.useEffect,k1=S1||C1,jb=e=>{const r=H.useRef([e,(...s)=>r[0](...s)]).current;return k1(()=>{r[0]=e}),r[1]},E1="popstate",Oh="pushState",Mh="replaceState",j1="hashchange",Bx=[E1,Oh,Mh,j1],N1=e=>{for(const r of Bx)addEventListener(r,e);return()=>{for(const r of Bx)removeEventListener(r,e)}},Nb=(e,r)=>_1.useSyncExternalStore(N1,e,r),zx=()=>location.search,T1=({ssrSearch:e}={})=>Nb(zx,e!=null?()=>e:zx),Px=()=>location.pathname,A1=({ssrPath:e}={})=>Nb(Px,e!=null?()=>e:Px),D1=(e,{replace:r=!1,state:s=null}={})=>history[r?Mh:Oh](s,"",e),L1=(e={})=>[A1(e),D1],Hx=Symbol.for("wouter_v3");if(typeof history<"u"&&typeof window[Hx]>"u"){for(const e of[Oh,Mh]){const r=history[e];history[e]=function(){const s=r.apply(this,arguments),i=new Event(e);return i.arguments=arguments,dispatchEvent(i),s}}Object.defineProperty(window,Hx,{value:!0})}const R1=(e,r)=>r.toLowerCase().indexOf(e.toLowerCase())?"~"+r:r.slice(e.length)||"/",Tb=(e="")=>e==="/"?"":e,O1=(e,r)=>e[0]==="~"?e.slice(1):Tb(r)+e,M1=(e="",r)=>R1(Fx(Tb(e)),Fx(r)),Fx=e=>{try{return decodeURI(e)}catch{return e}},Ab={hook:L1,searchHook:T1,parser:v1,base:"",ssrPath:void 0,ssrSearch:void 0,ssrContext:void 0,hrefs:e=>e,aroundNav:(e,r,s)=>e(r,s)},Db=H.createContext(Ab),Vi=()=>H.useContext(Db),Lb={},Rb=H.createContext(Lb),I1=()=>H.useContext(Rb),oc=e=>{const[r,s]=e.hook(e);return[M1(e.base,r),jb((i,l)=>e.aroundNav(s,O1(i,e.base),l))]},vr=()=>oc(Vi()),Ih=(e,r,s,i)=>{const{pattern:l,keys:u}=r instanceof RegExp?{keys:!1,pattern:r}:e(r||"*",i),h=l.exec(s)||[],[c,...d]=h;return c!==void 0?[!0,(()=>{const p=u!==!1?Object.fromEntries(u.map((m,b)=>[m,d[b]])):h.groups;let g={...d};return p&&Object.assign(g,p),g})(),...i?[c]:[]]:[!1,null]},Bh=e=>Ih(Vi().parser,e,vr()[0]),B1=({children:e,...r})=>{var g,m,b;const s=Vi(),i=r.hook?Ab:s;let l=i;const[u,h=r.ssrSearch??""]=((g=r.ssrPath)==null?void 0:g.split("?"))??[];u&&(r.ssrSearch=h,r.ssrPath=u),r.hrefs=r.hrefs??((m=r.hook)==null?void 0:m.hrefs),r.searchHook=r.searchHook??((b=r.hook)==null?void 0:b.searchHook);let c=H.useRef({}),d=c.current,p=d;for(let _ in i){const k=_==="base"?i[_]+(r[_]??""):r[_]??i[_];d===p&&k!==p[_]&&(c.current=p={...p}),p[_]=k,(k!==i[_]||k!==l[_])&&(l=p)}return H.createElement(Db.Provider,{value:l,children:e})},Ux=({children:e,component:r},s)=>r?H.createElement(r,{params:s}):typeof e=="function"?e(s):e,z1=e=>{let r=H.useRef(Lb);const s=r.current;return r.current=Object.keys(e).length!==Object.keys(s).length||Object.entries(e).some(([i,l])=>l!==s[i])?e:s},Fa=({path:e,nest:r,match:s,...i})=>{const l=Vi(),[u]=oc(l),[h,c,d]=s??Ih(l.parser,e,u,r),p=z1({...I1(),...c});if(!h)return null;const g=d?H.createElement(B1,{base:d},Ux(i,p)):Ux(i,p);return H.createElement(Rb.Provider,{value:p,children:g})},Fn=H.forwardRef((e,r)=>{const s=Vi(),[i,l]=oc(s),{to:u="",href:h=u,onClick:c,asChild:d,children:p,className:g,replace:m,state:b,transition:_,...k}=e,C=jb(v=>{v.ctrlKey||v.metaKey||v.altKey||v.shiftKey||v.button!==0||(c==null||c(v),v.defaultPrevented||(v.preventDefault(),l(h,e)))}),y=s.hrefs(h[0]==="~"?h.slice(1):s.base+h,s);return d&&H.isValidElement(p)?H.cloneElement(p,{onClick:C,href:y}):H.createElement("a",{...k,onClick:C,href:y,className:g!=null&&g.call?g(i===h):g,children:p,ref:r})}),Ob=e=>Array.isArray(e)?e.flatMap(r=>Ob(r&&r.type===H.Fragment?r.props.children:r)):[e],P1=({children:e,location:r})=>{const s=Vi(),[i]=oc(s);for(const l of Ob(e)){let u=0;if(H.isValidElement(l)&&(u=Ih(s.parser,l.props.path,r||i,l.props.nest))[0])return H.cloneElement(l,{match:u})}return null};function H1(e){return typeof e=="object"&&e!==null&&"type"in e&&"payload"in e}function Mb(){if(typeof crypto<"u"&&crypto.randomUUID)try{return crypto.randomUUID()}catch{}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const r=Math.random()*16|0;return(e==="x"?r:r&3|8).toString(16)})}class F1{constructor(r){hr(this,"ws",null);hr(this,"handlers",new Set);hr(this,"statusHandler",null);hr(this,"baseUrl");hr(this,"isReconnecting",!1);hr(this,"connectingPromise",null);hr(this,"lastCloseCode",0);hr(this,"reconnectAttempts",0);hr(this,"manualReconnectScheduled",!1);this.baseUrl=r}getUrl(){const r=localStorage.getItem("openfox_token");if(r){const s=this.baseUrl.includes("?")?"&":"?";return`${this.baseUrl}${s}token=${encodeURIComponent(r)}`}return this.baseUrl}setToken(r){localStorage.setItem("openfox_token",r)}clearToken(){localStorage.removeItem("openfox_token")}hasToken(){return!!localStorage.getItem("openfox_token")}getLastCloseCode(){return this.lastCloseCode}onStatusChange(r){this.statusHandler=r}connect(){var r,s;return((r=this.ws)==null?void 0:r.readyState)===WebSocket.OPEN?Promise.resolve():(this.lastCloseCode=0,this.isReconnecting=!1,this.connectingPromise&&((s=this.ws)==null?void 0:s.readyState)===WebSocket.CONNECTING?this.connectingPromise:(this.connectingPromise=new Promise((i,l)=>{try{const u=this.getUrl();this.ws=new WebSocket(u);const h=setTimeout(()=>{var c;((c=this.ws)==null?void 0:c.readyState)===WebSocket.CONNECTING&&(this.ws.close(),l(new Error("Connection timeout")))},5e3);this.ws.onopen=()=>{var c;clearTimeout(h),this.isReconnecting=!1,this.connectingPromise=null,(c=this.statusHandler)==null||c.call(this,"connected"),i()},this.ws.onclose=c=>{var d,p,g;clearTimeout(h),this.lastCloseCode=c.code,((d=this.ws)==null?void 0:d.readyState)===WebSocket.CONNECTING?(this.connectingPromise=null,(p=this.statusHandler)==null||p.call(this,"disconnected"),l(new Error(`Connection closed: ${c.code}`))):(this.connectingPromise=null,(g=this.statusHandler)==null||g.call(this,"disconnected"),this.attemptReconnect())},this.ws.onerror=c=>{clearTimeout(h),console.error("WebSocket error:",c),this.connectingPromise=null,l(c)},this.ws.onmessage=c=>{try{const d=JSON.parse(c.data);H1(d)&&this.handlers.forEach(p=>p(d))}catch(d){console.error("Failed to parse WebSocket message:",d)}}}catch(u){this.connectingPromise=null,l(u)}}),this.connectingPromise))}attemptReconnect(){var l;if(([1e3,1005,1006,4e3].includes(this.lastCloseCode)||this.lastCloseCode===0)&&this.hasToken()){console.log("[WS] Auth failure or initial failure with token - not auto-reconnecting, awaiting user action");return}if(this.isReconnecting||this.manualReconnectScheduled)return;this.isReconnecting=!0,(l=this.statusHandler)==null||l.call(this,"reconnecting");const i=Math.min(1e3*Math.pow(2,this.reconnectAttempts||0),3e4);this.reconnectAttempts=(this.reconnectAttempts||0)+1,setTimeout(()=>{this.isReconnecting=!1,this.manualReconnectScheduled=!1,this.connect().catch(()=>{})},i)}reconnect(){this.manualReconnectScheduled=!0,this.isReconnecting=!1,this.lastCloseCode=0,this.connectingPromise=null,this.connect().catch(()=>{})}disconnect(){this.isReconnecting=!1,this.reconnectAttempts=0,this.ws&&(this.ws.close(),this.ws=null)}resetReconnectAttempts(){this.reconnectAttempts=0}send(r,s){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket not connected");const i=Mb(),l={id:i,type:r,payload:s};return this.ws.send(JSON.stringify(l)),i}subscribe(r){return this.handlers.add(r),()=>this.handlers.delete(r)}get isConnected(){var r;return((r=this.ws)==null?void 0:r.readyState)===WebSocket.OPEN}}const U1=`ws://${window.location.hostname}:${window.location.port||"10469"}/ws`,Gt=new F1(U1),xs=async(e,r,s)=>{try{const i=await ke(r,{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return i.ok?{success:!0}:{success:!1,error:(await i.json()).error}}catch{return{success:!1,error:"Network error"}}};function Ib(e){let r=null;function s(){r===null&&(r=requestAnimationFrame(()=>{r=null,e()}))}return s}let Il=[];const mr=$n()((e,r)=>{function s(){if(Il.length===0)return;const l=Il;Il=[],e(u=>({logs:[...u.logs,...l]}))}const i=Ib(s);return{workdir:null,status:null,logs:[],config:null,loading:!1,setWorkdir:l=>{r().workdir!==l&&(e({workdir:l,status:null,logs:[],config:null,loading:!0}),l&&(r().fetchStatus(),r().fetchConfig()))},fetchStatus:async()=>{const l=r().workdir;if(l)try{const h=await(await ke(`/api/dev-server?workdir=${encodeURIComponent(l)}`)).json();e({status:h,loading:!1})}catch{e({loading:!1})}},fetchConfig:async()=>{const l=r().workdir;if(l)try{const h=await(await ke(`/api/dev-server/config?workdir=${encodeURIComponent(l)}`)).json();e({config:h.config??null})}catch{}},fetchLogs:async()=>{const l=r().workdir;if(l)try{const c=(await(await ke(`/api/dev-server/logs?workdir=${encodeURIComponent(l)}`)).json()).logs.map(d=>({stream:d.stream,content:d.content}));e({logs:c})}catch{}},start:async()=>{const l=r().workdir;if(l)try{const h=await(await ke(`/api/dev-server/start?workdir=${encodeURIComponent(l)}`,{method:"POST"})).json();e({status:h,logs:[]})}catch{}},stop:async()=>{const l=r().workdir;if(l)try{const h=await(await ke(`/api/dev-server/stop?workdir=${encodeURIComponent(l)}`,{method:"POST"})).json();e({status:h})}catch{}},restart:async()=>{const l=r().workdir;if(l)try{const h=await(await ke(`/api/dev-server/restart?workdir=${encodeURIComponent(l)}`,{method:"POST"})).json();e({status:h,logs:[]})}catch{}},saveConfig:async l=>{const u=r().workdir;if(u)try{const c=await(await ke(`/api/dev-server/config?workdir=${encodeURIComponent(u)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})).json();e({config:c.config??l}),r().fetchStatus()}catch{}},handleMessage:l=>{const u=r().workdir;if(u)switch(l.type){case"devServer.output":{const h=l.payload;if(h.workdir!==u)return;Il.push({stream:h.stream,content:h.content}),i();break}case"devServer.state":{const h=l.payload;if(h.workdir!==u)return;e(c=>({status:c.status?{...c.status,state:h.state,errorMessage:h.errorMessage}:c.status}));break}}}}});function $1(e){return{...e.temperature!=null&&{temperature:e.temperature},...e.topP!=null&&{topP:e.topP},...e.topK!=null&&{topK:e.topK},...e.maxTokens!=null&&{maxTokens:e.maxTokens}}}async function $x(e,r,s){const i=await ke(`/api/providers/${e}/models/${encodeURIComponent(r)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!i.ok){const l=await i.json();throw new Error(l.error??"Failed to update model")}return i.json()}function qx(e,r,s,i){return e.map(l=>l.id===r?{...l,models:l.models.map(u=>u.id===s?{...u,...i,source:"user"}:u)}:l)}const q1=3e4;function W1(e){switch(e){case"vllm":return"vLLM";case"sglang":return"SGLang";case"ollama":return"Ollama";case"llamacpp":return"llama.cpp";case"openai":return"OpenAI";case"anthropic":return"Anthropic";case"opencode-go":return"OpenCode Go";case"auto":return"Auto";case"unknown":return""}}const Lt=$n((e,r)=>({version:null,model:null,maxContext:2e5,llmUrl:null,llmStatus:"unknown",backend:"unknown",providers:[],activeProviderId:null,defaultModelSelection:null,loading:!1,activating:!1,error:null,autoRefreshInterval:null,fetchConfig:async()=>{e({loading:!0,error:null});try{const s=await ke("/api/config");if(!s.ok)throw new Error("Failed to fetch config");const i=await s.json();e({version:i.version,model:i.model,maxContext:i.maxContext,llmUrl:i.llmUrl,llmStatus:i.llmStatus,backend:i.backend,providers:i.providers??[],activeProviderId:i.activeProviderId??null,defaultModelSelection:i.defaultModelSelection??null,loading:!1})}catch(s){e({error:s instanceof Error?s.message:"Unknown error",loading:!1})}},refreshModel:async()=>{try{const s=await ke("/api/model/refresh",{method:"POST"});if(!s.ok)throw new Error("Failed to refresh model");const i=await s.json(),u=Ce.getState().currentSession;if(u!=null&&u.providerId&&u.providerModel){e({llmStatus:i.llmStatus,backend:i.backend});return}e({model:i.model,llmStatus:i.llmStatus,backend:i.backend})}catch(s){console.error("Failed to refresh model:",s)}},activateProvider:async s=>{const{activeProviderId:i,providers:l}=r();if(s===i)return!0;e({activating:!0,error:null});try{const u=await ke(`/api/providers/${s}/activate`,{method:"POST"});if(!u.ok){const c=await u.json();throw new Error(c.error??"Failed to activate provider")}const h=await u.json();return e({activeProviderId:h.activeProviderId,model:h.model,backend:h.backend,providers:l.map(c=>({...c,isActive:c.id===h.activeProviderId})),activating:!1}),!0}catch(u){return e({error:u instanceof Error?u.message:"Failed to switch provider",activating:!1}),!1}},syncFromSession:(s,i)=>{const{providers:l}=r();e({activeProviderId:s,model:i,defaultModelSelection:`${s}/${i}`,providers:l.map(u=>({...u,isActive:u.id===s}))})},updateModelContext:async(s,i,l)=>{e({activating:!0,error:null});try{const u=await $x(s,i,{contextWindow:l}),{providers:h}=r();return e({providers:qx(h,s,i,{contextWindow:l}),activating:!1}),u.contextState&&Ce.getState().updateContextState(u.contextState),!0}catch(u){return e({error:u instanceof Error?u.message:"Failed to update model context",activating:!1}),!1}},updateModelSettings:async(s,i,l)=>{e({activating:!0,error:null});try{const u=await $x(s,i,l),{providers:h}=r(),c={...l.contextWindow!==void 0&&{contextWindow:l.contextWindow},...$1({temperature:l.temperature??void 0,topP:l.topP??void 0,topK:l.topK??void 0,maxTokens:l.maxTokens??void 0}),...l.supportsVision!==void 0&&{supportsVision:l.supportsVision}};return e({providers:qx(h,s,i,c),activating:!1}),u.contextState&&Ce.getState().updateContextState(u.contextState),!0}catch(u){return e({error:u instanceof Error?u.message:"Failed to update model settings",activating:!1}),!1}},refreshProviderModels:async s=>{e({activating:!0,error:null});try{const i=await ke(`/api/providers/${s}/refresh`,{method:"POST"});if(!i.ok){const h=await i.json();throw new Error(h.error??"Failed to refresh models")}const l=await i.json(),{providers:u}=r();return e({providers:u.map(h=>h.id===s?{...h,models:l.models}:h),activating:!1}),!0}catch(i){return e({error:i instanceof Error?i.message:"Failed to refresh models",activating:!1}),!1}},startAutoRefresh:()=>{const{autoRefreshInterval:s,refreshModel:i}=r();if(s)return;const l=setInterval(()=>{i()},q1);e({autoRefreshInterval:l})},stopAutoRefresh:()=>{const{autoRefreshInterval:s}=r();s&&(clearInterval(s),e({autoRefreshInterval:null}))},getActiveProvider:()=>{const{providers:s,activeProviderId:i}=r();return s.find(l=>l.id===i)},getModelContext:s=>{const{providers:i,activeProviderId:l}=r(),u=i.find(c=>c.id===l);if(!u)return 2e5;const h=u.models.find(c=>c.id===s);return(h==null?void 0:h.contextWindow)??2e5}})),Ft=$n((e,r)=>({projects:[],currentProject:null,loading:!1,listProjects:async()=>{e({loading:!0});try{const i=await(await ke("/api/projects")).json();e({projects:i.projects??[],loading:!1})}catch(s){console.error("Failed to load projects:",s),e({loading:!1})}},createProject:async(s,i)=>{try{const l=await ke("/api/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:s,workdir:i})});if(!l.ok)return null;const u=await l.json();return await r().listProjects(),u.project}catch{return null}},loadProject:async s=>{try{const i=await ke(`/api/projects/${s}`);if(!i.ok)return null;const l=await i.json();return e({currentProject:l.project}),r().projects.length===0&&await r().listProjects(),l.project}catch{return null}},updateProject:async(s,i)=>{var l;try{const u=await ke(`/api/projects/${s}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!u.ok)return null;const h=await u.json();return((l=r().currentProject)==null?void 0:l.id)===s&&e({currentProject:h.project}),await r().listProjects(),h.project}catch{return null}},deleteProject:async s=>{var i;try{return(await ke(`/api/projects/${s}`,{method:"DELETE"})).ok?(await r().listProjects(),((i=r().currentProject)==null?void 0:i.id)===s&&e({currentProject:null}),!0):!1}catch{return!1}},clearProject:()=>{e({currentProject:null})}}));let Bl=[];const eo=$n()((e,r)=>{function s(){if(Bl.length===0)return;const l=Bl;Bl=[],e(u=>{const h={...u.logs};for(const c of l){const d=h[c.processId]??[];h[c.processId]=[...d,{offset:d.length,content:c.content,timestamp:Date.now(),stream:c.stream}]}return{logs:h}})}const i=Ib(s);return{processes:[],logs:{},loading:!1,setProcesses:l=>e({processes:l}),addProcess:l=>e(u=>({processes:[...u.processes,l]})),updateProcess:(l,u)=>e(h=>({processes:h.processes.map(c=>c.id===l?{...c,...u}:c)})),removeProcess:l=>e(u=>({processes:u.processes.filter(h=>h.id!==l),logs:Object.fromEntries(Object.entries(u.logs).filter(([h])=>h!==l))})),stopProcess:async(l,u)=>{try{(await ke(`/api/sessions/${u}/background-process/${l}/stop`,{method:"POST"})).ok&&r().removeProcess(l)}catch{}},appendLog:(l,u,h)=>{Bl.push({processId:l,stream:u,content:h}),i()},setLogs:(l,u)=>e(h=>({logs:{...h.logs,[l]:u}})),clearLogs:l=>e(u=>({logs:{...u.logs,[l]:[]}})),handleMessage:(l,u)=>{switch(l){case"backgroundProcess.started":{const{processId:h,name:c,pid:d,status:p}=u;e(g=>({processes:[...g.processes,{id:h,sessionId:"",name:c,command:"",cwd:"",pid:d,status:p,exitCode:null,createdAt:Date.now(),startedAt:Date.now(),endedAt:null}]}));break}case"backgroundProcess.output":{const h=u.processId,c=u.stream,d=u.content;r().appendLog(h,c,d);break}case"backgroundProcess.exited":{const h=u.processId,c=u.exitCode;e(d=>({processes:d.processes.map(p=>p.id===h?{...p,status:"exited",exitCode:c}:p)}));break}case"backgroundProcess.removed":{const h=u.processId;r().removeProcess(h);break}}}}}),V1=[{key:"complete",label:"Task Complete",description:"When an agent finishes its work"},{key:"waiting_for_user",label:"Waiting for Input",description:"When the agent needs your input"},{key:"phase_done",label:"Phase Done",description:"When a build phase completes successfully"},{key:"phase_blocked",label:"Phase Blocked",description:"When a build phase is blocked and needs intervention"},{key:"new_message",label:"New Message",description:"When a new assistant message starts arriving"}],G1=[{url:"/sounds/notification.mp3",label:"Notification"},{url:"/sounds/waiting-for-user.mp3",label:"Waiting for User"},{url:"/sounds/achievement.mp3",label:"Achievement"},{url:"/sounds/intervention.mp3",label:"Intervention"},{url:"/sounds/typing.mp3",label:"Typing"}],Bb={complete:"/sounds/notification.mp3",waiting_for_user:"/sounds/waiting-for-user.mp3",phase_done:"/sounds/achievement.mp3",phase_blocked:"/sounds/intervention.mp3",new_message:"/sounds/typing.mp3"},ms={soundEnabled:!0,browserNotification:!1,customSoundUrl:null},zb={soundEnabled:!1,browserNotification:!1,customSoundUrl:null},ph={soundEnabled:!0,browserNotificationEnabled:!1,events:{complete:{...ms},waiting_for_user:{...ms},phase_done:{...ms},phase_blocked:{...ms},new_message:{...zb}},agentOverrides:{}};function Pb(e,r,s){var u;const i=e.events[r];if(!s)return i;const l=(u=e.agentOverrides[s])==null?void 0:u[r];return l?{soundEnabled:l.soundEnabled??i.soundEnabled,browserNotification:l.browserNotification??i.browserNotification,customSoundUrl:l.customSoundUrl!==void 0?l.customSoundUrl:i.customSoundUrl}:i}const Fs=$n((e,r)=>({settings:ph,loaded:!1,load:()=>{Yt.getState().getSetting(ot.NOTIFICATION_SETTINGS);const i=Yt.subscribe(u=>{const h=u.settings[ot.NOTIFICATION_SETTINGS];if(h!==void 0)try{const c=JSON.parse(h);e({settings:Wx(c),loaded:!0})}catch{e({loaded:!0})}}),l=Yt.getState().settings[ot.NOTIFICATION_SETTINGS];if(l)try{const u=JSON.parse(l);e({settings:Wx(u),loaded:!0})}catch{e({loaded:!0})}return i},update:s=>{e({settings:s}),Fd(s)},updateEvent:(s,i)=>{const l=r().settings,u={...l,events:{...l.events,[s]:{...l.events[s],...i}}};e({settings:u}),Fd(u)},updateAgentOverride:(s,i,l)=>{var d;const u=r().settings,h={...u.agentOverrides};if(l===null){if(h[s]){const p={...h[s]};delete p[i],Object.keys(p).length===0?delete h[s]:h[s]=p}}else h[s]={...h[s],[i]:{...((d=h[s])==null?void 0:d[i])??{},...l}};const c={...u,agentOverrides:h};e({settings:c}),Fd(c)}}));function Fd(e){Yt.getState().setSetting(ot.NOTIFICATION_SETTINGS,JSON.stringify(e))}function Wx(e){var r,s,i,l,u;return{soundEnabled:e.soundEnabled??ph.soundEnabled,browserNotificationEnabled:e.browserNotificationEnabled??ph.browserNotificationEnabled,events:{complete:{...ms,...(r=e.events)==null?void 0:r.complete},waiting_for_user:{...ms,...(s=e.events)==null?void 0:s.waiting_for_user},phase_done:{...ms,...(i=e.events)==null?void 0:i.phase_done},phase_blocked:{...ms,...(l=e.events)==null?void 0:l.phase_blocked},new_message:{...zb,...(u=e.events)==null?void 0:u.new_message}},agentOverrides:e.agentOverrides??{}}}const Vx=new Map;function K1(e){let r=Vx.get(e);return r||(r=new Audio(e),r.volume=.5,Vx.set(e,r)),r}let Hb=typeof Notification<"u"?Notification.permission:"denied";function Y1(){return typeof Notification>"u"?Promise.resolve("denied"):Notification.requestPermission().then(e=>(Hb=e,e))}const X1={complete:"Task Complete",waiting_for_user:"Waiting for Input",phase_done:"Phase Complete",phase_blocked:"Phase Blocked",new_message:"New Message"},Z1={complete:"The agent has finished its work.",waiting_for_user:"The agent needs your input to continue.",phase_done:"The build phase completed successfully.",phase_blocked:"The build phase is blocked and needs intervention.",new_message:"A new assistant message is arriving."};function Q1(e){typeof Notification>"u"||Hb==="granted"&&(document.hasFocus()||new Notification(X1[e],{body:Z1[e],icon:"/fox.svg",tag:`openfox-${e}`}))}function mo(e,r){const{settings:s}=Fs.getState(),i=Pb(s,e,r);if(s.soundEnabled&&i.soundEnabled){const l=i.customSoundUrl??Bb[e],u=K1(l);u.currentTime=0,u.play().catch(()=>{})}s.browserNotificationEnabled&&i.browserNotification&&Q1(e)}const J1=e=>mo("complete",e),ew=e=>mo("phase_done",e),tw=e=>mo("phase_blocked",e),Gx=e=>mo("waiting_for_user",e),nw=e=>mo("new_message",e);let Ua=!1,fr=null;const Ud=new Set,Vt={messageId:null,deltaContent:"",thinkingContent:"",toolOutput:[]};let Ui=null,mn=null;function $d(){Ui===null&&(Ui=requestAnimationFrame(()=>{Ui=null,mn==null||mn()}))}function Is(){Ui!==null&&(cancelAnimationFrame(Ui),Ui=null)}function Ht(e,r){return r!==null&&e.sessionId===r}function rw(e,r,s){return e.id!==void 0||Ht(e,r)||s===!0&&e.sessionId!==void 0}function sw(e,r){return e.includes(r)?e:[...e,r]}function $a(e,r){return e.filter(s=>s!==r)}function iw(e,r){const s=e.find(l=>l.id===r.id),i=s?{...s,projectId:r.projectId,workdir:r.workdir,mode:r.mode,phase:r.phase,isRunning:r.isRunning,messageCount:r.messages.length,criteriaCount:r.criteria.length,criteriaCompleted:r.criteria.filter(l=>l.status.type==="passed").length}:{id:r.id,projectId:r.projectId,workdir:r.workdir,mode:r.mode,phase:r.phase,isRunning:r.isRunning,createdAt:"",updatedAt:"",criteriaCount:r.criteria.length,criteriaCompleted:r.criteria.filter(l=>l.status.type==="passed").length,messageCount:r.messages.length};return s?e.map(l=>l.id===r.id?i:l):[i,...e]}function aw(e,r,s){return e.map(i=>{const l=(s==null?void 0:s.id)===i.id?s:null,u=r.find(h=>h.id===i.id);return{...i,title:i.title??(u==null?void 0:u.title),mode:(l==null?void 0:l.mode)??(u==null?void 0:u.mode)??i.mode,phase:(l==null?void 0:l.phase)??(u==null?void 0:u.phase)??i.phase,isRunning:i.isRunning,messageCount:i.messageCount,recentUserPrompts:i.recentUserPrompts}})}const Kx=new Map;function Qa(e,r){var u;const s=r===((u=e.currentSession)==null?void 0:u.id)?e.currentSession:null,i=e.sessions.find(h=>h.id===r),l=(s==null?void 0:s.mode)??(i==null?void 0:i.mode);return l==="planner"?"planner":l==="builder"?"build":"planner"}function ow(e,r){if(e.type==="chat.done"){const s=e.payload,i=Qa(r,e.sessionId),l=s.agentType??i;s.reason==="complete"&&J1(l),s.reason==="waiting_for_user"&&Gx(l);return}if(e.type==="chat.path_confirmation"){const s=Qa(r,e.sessionId);Gx(s);return}if(e.type==="task.completed"){const s=Qa(r,e.sessionId);ew(s);return}if(e.type==="phase.changed"&&e.sessionId){const s=e.payload,i=Kx.get(e.sessionId)??null;if(Kx.set(e.sessionId,s.phase),i===s.phase)return;const l=Qa(r,e.sessionId);s.phase==="blocked"&&tw(l)}}const Ce=$n((e,r)=>(mn=()=>{const s=Vt;if(!s.messageId)return;const i=s.deltaContent.length>0,l=s.thinkingContent.length>0,u=s.toolOutput.length>0;if(!i&&!l&&!u)return;const h=s.deltaContent,c=s.thinkingContent,d=s.toolOutput;s.deltaContent="",s.thinkingContent="",s.toolOutput=[],e(p=>{var m;const g=p.streamingMessage;if(g&&g.id===s.messageId){let b={...g};if(i&&(b.content=b.content+h),l&&(b.thinkingContent=(b.thinkingContent??"")+c),u){const _=new Set;b.toolCalls=(m=b.toolCalls)==null?void 0:m.map(C=>{const y=d.filter(v=>v.callId===C.id);return y.length===0?C:(_.add(C.id),{...C,streamingOutput:[...C.streamingOutput??[],...y.map(v=>({stream:v.stream,content:v.content,timestamp:Date.now()}))]})});const k=d.filter(C=>!_.has(C.callId));k.length>0&&Vt.toolOutput.push(...k)}return{streamingMessage:b}}if(u){const b=new Set,_=p.messages.map(C=>{var v;if(C.id!==s.messageId)return C;const y=(v=C.toolCalls)==null?void 0:v.map(x=>{const S=d.filter(j=>j.callId===x.id);return S.length===0?x:(b.add(x.id),{...x,streamingOutput:[...x.streamingOutput??[],...S.map(j=>({stream:j.stream,content:j.content,timestamp:Date.now()}))]})});return{...C,toolCalls:y}}),k=d.filter(C=>!b.has(C.callId));return k.length>0&&Vt.toolOutput.push(...k),{messages:_}}return p})},{connectionStatus:"disconnected",showPasswordModal:!1,passwordModalRetry:!1,sessions:[],currentSession:null,unreadSessionIds:[],messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,subAgentContextStates:{},pendingPathConfirmation:null,pendingQuestion:null,visionFallbackByMessage:{},queuedMessages:[],abortInProgress:!1,error:null,sessionsHasMore:!0,sessionsPaginationLoading:!1,pendingSessionCreate:!1,connect:async()=>{if(r().connectionStatus==="connected")return;e({connectionStatus:"reconnecting"});let i=!1;try{i=(await(await ke("/api/auth")).json()).requiresAuth}catch{}if(i&&!Gt.hasToken()){e({showPasswordModal:!0,passwordModalRetry:!1,connectionStatus:"reconnecting"});return}Gt.onStatusChange(l=>{var u;if(e({connectionStatus:l}),l==="connected"){r().listSessions(void 0),Ft.getState().listProjects();const h=(u=r().currentSession)==null?void 0:u.id;h&&r().loadSession(h)}});try{if(await Gt.connect(),!Ua){Ua=!0;const l=r().handleServerMessage;fr=Gt.subscribe(l)}}catch(l){console.error("Failed to connect:",l);const u=Gt.getLastCloseCode();if(!Gt.hasToken()&&(u===1006||u===4e3)){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}fr&&(fr(),fr=null),Ua=!1,e({connectionStatus:"disconnected"})}},reconnect:()=>{Gt.disconnect(),fr&&(fr(),fr=null),Ua=!1,e({connectionStatus:"disconnected"}),r().connect()},disconnect:()=>{Gt.disconnect(),fr&&(fr(),fr=null),Ua=!1,e({connectionStatus:"disconnected",showPasswordModal:!1})},submitPassword:async s=>{try{const i=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:s})});if(!i.ok){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}const{token:l}=await i.json();Gt.setToken(l),e({showPasswordModal:!1}),r().connect();const{listProjects:u}=Ft.getState(),{fetchConfig:h}=Lt.getState();u(),h(),r().connect()}catch{e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"})}},cancelPassword:()=>{Gt.clearToken(),e({showPasswordModal:!1,connectionStatus:"disconnected"})},createSession:async(s,i)=>{try{e({pendingSessionCreate:!0});const l=await ke("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectId:s,title:i})});if(!l.ok)return e({pendingSessionCreate:!1}),null;const u=await l.json();return Gt.send("session.load",{sessionId:u.session.id}),u.session}catch{return e({pendingSessionCreate:!1}),null}},loadSession:async s=>{try{const i=r().currentSession;!i||i.id!==s?(Is(),e({currentSession:null,unreadSessionIds:$a(r().unreadSessionIds,s),subAgentContextStates:{},messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,pendingPathConfirmation:null,queuedMessages:[],abortInProgress:!1,error:null})):e({unreadSessionIds:$a(r().unreadSessionIds,s)});const l=await ke(`/api/sessions/${s}`);if(!l.ok)return;const u=await l.json();e({currentSession:u.session,messages:u.messages??[],contextState:u.contextState,queuedMessages:u.queueState??[]}),Gt.send("session.load",{sessionId:s});try{const h=await ke(`/api/sessions/${s}/background-processes`);if(h.ok){const c=await h.json();eo.getState().setProcesses(c.processes??[])}}catch{}}catch{}},listSessions:async(s,i=20)=>{try{const l=new URLSearchParams;l.set("limit",String(i)),s&&l.set("projectId",s);const h=await(await ke(`/api/sessions?${l.toString()}`)).json();e({sessions:h.sessions??[],sessionsHasMore:s?h.hasMore??!1:!0})}catch{}},loadMoreSessions:async s=>{const i=r();if(!(i.sessionsPaginationLoading||!i.sessionsHasMore)){e({sessionsPaginationLoading:!0});try{const l=new URLSearchParams;l.set("limit","20"),l.set("offset",String(i.sessions.length)),l.set("projectId",s);const h=await(await ke(`/api/sessions?${l.toString()}`)).json();e(c=>({sessions:[...c.sessions,...h.sessions??[]],sessionsHasMore:h.hasMore??!1,sessionsPaginationLoading:!1}))}catch{e({sessionsPaginationLoading:!1})}}},deleteSession:async s=>{var i;try{return(await ke(`/api/sessions/${s}`,{method:"DELETE"})).ok?(await r().listSessions(),((i=r().currentSession)==null?void 0:i.id)===s&&r().clearSession(),!0):!1}catch{return!1}},deleteAllSessions:async s=>{try{return(await ke(`/api/projects/${s}/sessions`,{method:"DELETE"})).ok?(await r().listSessions(),!0):!1}catch{return!1}},clearSession:()=>{Is(),e(s=>({currentSession:null,messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,unreadSessionIds:s.currentSession?$a(s.unreadSessionIds,s.currentSession.id):s.unreadSessionIds}))},sendMessage:async(s,i,l)=>{var h;const u=(h=r().currentSession)==null?void 0:h.id;if(u){e({streamingMessageId:null});try{const d=await(await ke(`/api/sessions/${u}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:s,attachments:i,messageKind:l==null?void 0:l.messageKind})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(c){console.error("Error sending message:",c)}}},stopGeneration:async()=>{var i;const s=(i=r().currentSession)==null?void 0:i.id;if(s&&!r().abortInProgress){Is(),mn==null||mn(),e({abortInProgress:!0});try{await ke(`/api/sessions/${s}/stop`,{method:"POST"})}catch(l){console.error("Error stopping generation:",l)}}},continueGeneration:async()=>{var i;const s=(i=r().currentSession)==null?void 0:i.id;if(s){e({streamingMessageId:null});try{await ke(`/api/sessions/${s}/continue`,{method:"POST"})}catch(l){console.error("Error continuing generation:",l)}}},launchRunner:(s,i,l)=>{e({streamingMessageId:null});const u={};s!=null&&s.trim()&&(u.content=s),i&&i.length>0&&(u.attachments=i),l&&(u.workflowId=l),Gt.send("runner.launch",u)},switchMode:async s=>{var l;const i=(l=r().currentSession)==null?void 0:l.id;if(i)try{const u=await ke(`/api/sessions/${i}/mode`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:s})});if(!u.ok){console.error("Failed to switch mode:",await u.json());return}const h=await u.json();h.session&&e({currentSession:h.session})}catch(u){console.error("Error switching mode:",u)}},switchDangerLevel:async s=>{var l;const i=(l=r().currentSession)==null?void 0:l.id;if(i)try{const u=await ke(`/api/sessions/${i}/danger-level`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({dangerLevel:s})});if(!u.ok){console.error("Failed to switch danger level:",await u.json());return}const h=await u.json();h.session&&e({currentSession:h.session})}catch(u){console.error("Error switching danger level:",u)}},acceptAndBuild:(s,i,l)=>{e({streamingMessageId:null});const u={};s&&(u.workflowId=s),i!=null&&i.trim()&&(u.content=i),l&&l.length>0&&(u.attachments=l),Gt.send("mode.accept",u)},editCriteria:async s=>{var l;const i=(l=r().currentSession)==null?void 0:l.id;if(i)try{const u=await ke(`/api/sessions/${i}/criteria`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({criteria:s})});u.ok||console.error("Failed to update criteria:",await u.json())}catch(u){console.error("Error updating criteria:",u)}},compactContext:()=>{Gt.send("context.compact",{})},setSessionProvider:async(s,i)=>{var l;try{const u=(l=r().currentSession)==null?void 0:l.id;if(!u)return null;const h=await ke(`/api/sessions/${u}/provider`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerId:s,...i?{model:i}:{}})});if(!h.ok)return null;const c=await h.json();return e({currentSession:c.session,messages:c.messages??[],contextState:c.contextState}),c.session}catch{return null}},updateContextState:s=>{e({contextState:s})},updateSubAgentContextState:(s,i)=>{e(l=>({subAgentContextStates:{...l.subAgentContextStates,[s]:i}}))},clearSubAgentContextState:s=>{e(i=>{const l={...i.subAgentContextStates};return delete l[s],{subAgentContextStates:l}})},confirmPath:async(s,i,l=!1)=>{var h;const u=(h=r().currentSession)==null?void 0:h.id;if(u)try{await ke(`/api/sessions/${u}/confirm-path`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:s,approved:i,alwaysAllow:l})})}catch(c){console.error("Error confirming path:",c)}},answerQuestion:async(s,i)=>{var u;const l=(u=r().currentSession)==null?void 0:u.id;if(l){try{await ke(`/api/sessions/${l}/answer`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:s,answer:i})})}catch(h){console.error("Error answering question:",h)}e({pendingQuestion:null})}},queueAsap:async(s,i,l)=>{var h;const u=(h=r().currentSession)==null?void 0:h.id;if(u)try{const d=await(await ke(`/api/sessions/${u}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:s,attachments:i,messageKind:l})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(c){console.error("Error queueing ASAP message:",c)}},queueCompletion:async(s,i,l)=>{var h;const u=(h=r().currentSession)==null?void 0:h.id;if(u)try{const d=await(await ke(`/api/sessions/${u}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:s,attachments:i,messageKind:l})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(c){console.error("Error queueing completion message:",c)}},cancelQueued:async s=>{var l;const i=(l=r().currentSession)==null?void 0:l.id;if(i)try{const h=await(await ke(`/api/sessions/${i}/queue/${s}`,{method:"DELETE"})).json();h.queueState&&e({queuedMessages:h.queueState})}catch(u){console.error("Error canceling queued message:",u)}},clearError:()=>{e({error:null})},resetPendingSessionCreate:()=>{e({pendingSessionCreate:!1})},handleServerMessage:s=>{var h,c,d,p,g,m,b,_,k,C,y,v,x,S,j,T,N,D,A,z,O,q,G,W;const i=r();ow(s,i);const l=((h=i.currentSession)==null?void 0:h.id)??null,u=()=>{const I=s.sessionId;!I||I===l||e($=>({unreadSessionIds:sw($.unreadSessionIds,I)}))};switch(s.type){case"session.state":{const I=s.payload;if(!rw(s,l,i.pendingSessionCreate))break;Is();const $=I.messages.find(R=>R.isStreaming)??null,B=r().pendingSessionCreate===!0,X=I.pendingConfirmations??[],P=i.pendingPathConfirmation??(X.length>0?X[0]??null:null);if(e({currentSession:I.session,sessions:iw(r().sessions,I.session),unreadSessionIds:$a(r().unreadSessionIds,I.session.id),messages:I.messages,streamingMessageId:($==null?void 0:$.id)??null,streamingMessage:$,currentTodos:[],pendingPathConfirmation:P,error:null,...B?{pendingSessionCreate:I.session.id}:{}}),I.session.providerId&&I.session.providerModel){const R=Lt.getState();R.providers.find(U=>U.id===I.session.providerId)&&R.syncFromSession(I.session.providerId,I.session.providerModel)}break}case"session.list":{const I=s.payload;e($=>({sessions:aw(I.sessions,$.sessions,$.currentSession)}));break}case"session.deleted":{const I=s.payload;e($=>({unreadSessionIds:$a($.unreadSessionIds,I.sessionId)})),r().listSessions();break}case"session.deletedAll":{r().listSessions();break}case"session.running":{const I=s.payload,$=s.sessionId,B=(c=r().currentSession)==null?void 0:c.id,X=$&&$!==B;e(Z=>({sessions:Z.sessions.map(P=>P.id===$?{...P,isRunning:I.isRunning}:P)})),X||e(Z=>({currentSession:Z.currentSession?{...Z.currentSession,isRunning:I.isRunning}:null,...I.isRunning?{}:{abortInProgress:!1,queuedMessages:[]}}));break}case"chat.message":{if(!Ht(s,((d=r().currentSession)==null?void 0:d.id)??null)){u();break}const I=s.payload;e($=>$.messages.some(B=>B.id===I.message.id)?$:{messages:[...$.messages,I.message],streamingMessageId:I.message.isStreaming?I.message.id:$.streamingMessageId,streamingMessage:I.message.isStreaming?I.message:$.streamingMessage});break}case"chat.message_updated":{if(!Ht(s,((p=r().currentSession)==null?void 0:p.id)??null)){u();break}const I=s.payload,$=I.updates.isStreaming===!1&&r().streamingMessageId===I.messageId;$&&(Is(),mn==null||mn()),e(B=>{const X=B.streamingMessage,Z=$;if(X&&X.id===I.messageId){const P={...X,...I.updates};return{messages:B.messages.map(R=>R.id===I.messageId?P:R),streamingMessageId:Z?null:B.streamingMessageId,streamingMessage:Z?null:{...X,...I.updates}}}return{messages:B.messages.map(P=>P.id===I.messageId?{...P,...I.updates}:P),streamingMessageId:Z?null:B.streamingMessageId}});break}case"chat.delta":{if(!Ht(s,((g=r().currentSession)==null?void 0:g.id)??null)){u();break}const I=s.payload;if(!Ud.has(I.messageId)){Ud.add(I.messageId);const $=Qa(r(),s.sessionId);nw($)}Vt.messageId=I.messageId,Vt.deltaContent+=I.content,$d();break}case"chat.thinking":{if(!Ht(s,((m=r().currentSession)==null?void 0:m.id)??null)){u();break}const I=s.payload;Vt.messageId=I.messageId,Vt.thinkingContent+=I.content,$d();break}case"chat.tool_preparing":{if(!Ht(s,((b=r().currentSession)==null?void 0:b.id)??null)){u();break}const I=s.payload;e($=>{const B=$.streamingMessage;return B&&B.id===I.messageId?{streamingMessage:{...B,preparingToolCalls:[...B.preparingToolCalls??[],{index:I.index,name:I.name}]}}:{messages:$.messages.map(X=>X.id===I.messageId?{...X,preparingToolCalls:[...X.preparingToolCalls??[],{index:I.index,name:I.name}]}:X)}});break}case"chat.tool_call":{if(!Ht(s,((_=r().currentSession)==null?void 0:_.id)??null)){u();break}const I=s.payload,$=B=>{var P;const X=(P=B.preparingToolCalls)==null?void 0:P.filter((R,L)=>{var U;return R.name===I.tool?(U=B.preparingToolCalls)==null?void 0:U.slice(0,L).some(ne=>ne.name===I.tool):!0}),Z=Vt.toolOutput.filter(R=>R.callId===I.callId);return Z.length>0&&(Vt.toolOutput=Vt.toolOutput.filter(R=>R.callId!==I.callId)),{...B,toolCalls:[...B.toolCalls??[],{id:I.callId,name:I.tool,arguments:I.args,startedAt:Date.now(),...Z.length>0?{streamingOutput:Z.map(R=>({stream:R.stream,content:R.content,timestamp:Date.now()}))}:{}}],...X&&X.length>0?{preparingToolCalls:X}:{preparingToolCalls:void 0}}};e(B=>{const X=B.streamingMessage;return X&&X.id===I.messageId?{streamingMessage:$(X)}:{messages:B.messages.map(Z=>Z.id===I.messageId?$(Z):Z)}});break}case"chat.tool_output":{if(!Ht(s,((k=r().currentSession)==null?void 0:k.id)??null)){u();break}const I=s.payload;Vt.messageId=I.messageId,Vt.toolOutput.push({messageId:I.messageId,callId:I.callId,stream:I.stream,content:I.output}),$d();break}case"chat.tool_result":{if(!Ht(s,((C=r().currentSession)==null?void 0:C.id)??null)){u();break}const I=s.payload,$=B=>{var Z;const X=(Z=B.toolCalls)==null?void 0:Z.map(P=>P.id===I.callId?{...P,result:I.result}:P);return{...B,toolCalls:X}};e(B=>{const X=B.streamingMessage;return X&&X.id===I.messageId?{streamingMessage:$(X)}:{messages:B.messages.map(Z=>Z.id===I.messageId?$(Z):Z)}});break}case"chat.vision_fallback":{if(!Ht(s,((y=r().currentSession)==null?void 0:y.id)??null)){u();break}const I=s.payload;e($=>{const B=`${I.messageId}-${I.attachmentId}`,X={...$.visionFallbackByMessage};return X[B]={type:I.type,attachmentId:I.attachmentId,filename:I.filename,description:I.description},{visionFallbackByMessage:X}});break}case"chat.todo":{if(!Ht(s,((v=r().currentSession)==null?void 0:v.id)??null)){u();break}const I=s.payload;e({currentTodos:I.todos});break}case"chat.summary":{if(!Ht(s,((x=r().currentSession)==null?void 0:x.id)??null)){u();break}const I=s.payload;e($=>({currentSession:$.currentSession?{...$.currentSession,summary:I.summary}:null}));break}case"chat.progress":{if(!Ht(s,((S=r().currentSession)==null?void 0:S.id)??null)){u();break}const I=s.payload;console.log("Progress:",I.message,I.phase);break}case"chat.format_retry":{if(!Ht(s,((j=r().currentSession)==null?void 0:j.id)??null)){u();break}const I=s.payload;console.log("Format retry:",I.attempt,"/",I.maxAttempts);break}case"chat.done":{if(!Ht(s,((T=r().currentSession)==null?void 0:T.id)??null)){u();break}Is(),mn==null||mn();const I=s.payload,$=I.stats;Vt.messageId=null,Vt.deltaContent="",Vt.thinkingContent="",Vt.toolOutput=[],Ud.delete(I.messageId),e(B=>{const X=B.streamingMessage,Z=X&&X.id===I.messageId?{...X,isStreaming:!1,stats:$??X.stats}:null;return{messages:B.messages.map(P=>P.id===I.messageId?Z??{...P,isStreaming:!1,stats:$??P.stats}:P),streamingMessageId:null,streamingMessage:null,visionFallbackByMessage:{}}});break}case"chat.error":{if(!Ht(s,((N=r().currentSession)==null?void 0:N.id)??null)){u();break}Is(),mn==null||mn();const I=s.payload;console.error("Chat error:",I.error,"recoverable:",I.recoverable),I.recoverable||(Vt.messageId=null,Vt.deltaContent="",Vt.thinkingContent="",Vt.toolOutput=[]),e($=>({error:{code:"CHAT_ERROR",message:I.error},streamingMessageId:I.recoverable?$.streamingMessageId:null,...I.recoverable?{}:{messages:$.streamingMessage?$.messages.map(B=>B.id===$.streamingMessage.id?$.streamingMessage:B):$.messages,streamingMessage:null}}));break}case"chat.path_confirmation":{if(!Ht(s,((D=r().currentSession)==null?void 0:D.id)??null)){u();break}const I=s.payload;e({pendingPathConfirmation:{callId:I.callId,tool:I.tool,paths:I.paths,workdir:I.workdir,reason:I.reason}});break}case"chat.ask_user":{if(!Ht(s,((A=r().currentSession)==null?void 0:A.id)??null)){u();return}const I=s.payload;e({pendingQuestion:{callId:I.callId,question:I.question}});break}case"mode.changed":{if(!Ht(s,((z=r().currentSession)==null?void 0:z.id)??null)){u();break}const I=s.payload;e($=>({currentSession:$.currentSession?{...$.currentSession,mode:I.mode}:null}));break}case"phase.changed":{const I=s.payload,$=s.sessionId,B=(O=r().currentSession)==null?void 0:O.id,X=$&&$!==B;e(Z=>({sessions:Z.sessions.map(P=>P.id===$?{...P,phase:I.phase}:P)})),X||e(Z=>({currentSession:Z.currentSession?{...Z.currentSession,phase:I.phase}:null}));break}case"criteria.updated":{if(!Ht(s,((q=r().currentSession)==null?void 0:q.id)??null)){u();break}const I=s.payload;e($=>({currentSession:$.currentSession?{...$.currentSession,criteria:I.criteria}:null}));break}case"context.state":{const I=s.payload,$=Ht(s,((G=r().currentSession)==null?void 0:G.id)??null);I.subAgentId?$&&r().updateSubAgentContextState(I.subAgentId,I.context):$?e({contextState:I.context}):u();break}case"session.name_generated":{const I=s.payload,$=s.sessionId,B=(W=r().currentSession)==null?void 0:W.id;e(X=>{const Z=X.sessions.map(R=>R.id===$?{...R,title:I.name,updatedAt:new Date().toISOString()}:R),P=B===$?X.currentSession?{...X.currentSession,title:I.name,updatedAt:new Date().toISOString()}:null:X.currentSession;return{sessions:Z,currentSession:P}});break}case"queue.state":{const I=s.payload;e({queuedMessages:I.messages});break}case"devServer.output":case"devServer.state":{mr.getState().handleMessage(s);break}case"backgroundProcess.started":case"backgroundProcess.output":case"backgroundProcess.exited":case"backgroundProcess.removed":{eo.getState().handleMessage(s.type,s.payload);break}case"error":{const I=s.payload;console.error("Server error:",I),e({error:{code:I.code,message:I.message},streamingMessageId:null});break}}}}));function Fb(){return Ce(e=>{var r;return((r=e.currentSession)==null?void 0:r.isRunning)??!1})}function lw(){return Ce(e=>e.queuedMessages)}function cw(){return Ce(e=>e.abortInProgress)}function uw(){const e=Ce(i=>i.connect),r=Ce(i=>i.connectionStatus),s=Fs(i=>i.load);return H.useEffect(()=>{e()},[e]),H.useEffect(()=>{r==="connected"&&s()},[r,s]),{connectionStatus:r}}const dw="modulepreload",hw=function(e){return"/"+e},Yx={},mh=function(r,s,i){let l=Promise.resolve();if(s&&s.length>0){let h=function(p){return Promise.all(p.map(g=>Promise.resolve(g).then(m=>({status:"fulfilled",value:m}),m=>({status:"rejected",reason:m}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),d=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));l=h(s.map(p=>{if(p=hw(p),p in Yx)return;Yx[p]=!0;const g=p.endsWith(".css"),m=g?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${m}`))return;const b=document.createElement("link");if(b.rel=g?"stylesheet":dw,g||(b.as="script"),b.crossOrigin="",b.href=p,d&&b.setAttribute("nonce",d),document.head.appendChild(b),g)return new Promise((_,k)=>{b.addEventListener("load",_),b.addEventListener("error",()=>k(new Error(`Unable to preload CSS for ${p}`)))})}))}function u(h){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=h,window.dispatchEvent(c),!c.defaultPrevented)throw h}return l.then(h=>{for(const c of h||[])c.status==="rejected"&&u(c.reason);return r().catch(u)})},Ub=[{key:"color-bg-primary",category:"background",label:"Primary Background",defaultValue:"13 17 23"},{key:"color-bg-secondary",category:"background",label:"Secondary Background",defaultValue:"22 27 34"},{key:"color-bg-tertiary",category:"background",label:"Tertiary Background",defaultValue:"33 38 45"},{key:"color-primary",category:"surface",label:"Primary Surface",defaultValue:"10 10 10"},{key:"color-secondary",category:"surface",label:"Secondary Surface",defaultValue:"20 20 20"},{key:"color-text-primary",category:"text",label:"Primary Text",defaultValue:"139 148 158"},{key:"color-text-secondary",category:"text",label:"Secondary Text",defaultValue:"139 148 158"},{key:"color-text-muted",category:"text",label:"Muted Text",defaultValue:"72 79 88"},{key:"color-accent-primary",category:"accent",label:"Primary Accent",defaultValue:"88 166 255"},{key:"color-accent-success",category:"accent",label:"Success Accent",defaultValue:"63 185 80"},{key:"color-accent-warning",category:"accent",label:"Warning Accent",defaultValue:"210 153 34"},{key:"color-accent-error",category:"accent",label:"Error Accent",defaultValue:"248 81 73"},{key:"color-border",category:"border",label:"Border",defaultValue:"48 53 60"}],gr=[{id:"dark",name:"Dark",tokens:{"color-bg-primary":"13 17 23","color-bg-secondary":"22 27 34","color-bg-tertiary":"33 38 45","color-primary":"10 10 10","color-secondary":"20 20 20","color-text-primary":"139 148 158","color-text-secondary":"139 148 158","color-text-muted":"72 79 88","color-accent-primary":"88 166 255","color-accent-success":"63 185 80","color-accent-warning":"210 153 34","color-accent-error":"248 81 73","color-border":"48 53 60"}},{id:"light",name:"Light",tokens:{"color-bg-primary":"255 255 255","color-bg-secondary":"250 251 252","color-bg-tertiary":"243 244 246","color-primary":"245 245 245","color-secondary":"229 229 229","color-text-primary":"15 23 42","color-text-secondary":"30 41 59","color-text-muted":"100 116 139","color-accent-primary":"37 99 235","color-accent-success":"22 163 74","color-accent-warning":"217 119 6","color-accent-error":"220 38 38","color-border":"203 213 225"}},{id:"monokai",name:"Monokai",tokens:{"color-bg-primary":"39 40 34","color-bg-secondary":"30 31 28","color-bg-tertiary":"62 61 50","color-primary":"30 31 28","color-secondary":"45 46 39","color-text-primary":"248 248 242","color-text-secondary":"207 207 194","color-text-muted":"117 113 94","color-accent-primary":"102 217 239","color-accent-success":"166 226 46","color-accent-warning":"230 219 116","color-accent-error":"249 38 114","color-border":"73 72 62"}},{id:"dracula",name:"Dracula",tokens:{"color-bg-primary":"40 42 54","color-bg-secondary":"33 34 44","color-bg-tertiary":"68 71 90","color-primary":"30 31 41","color-secondary":"44 46 61","color-text-primary":"248 248 242","color-text-secondary":"230 230 230","color-text-muted":"98 114 164","color-accent-primary":"189 147 249","color-accent-success":"80 250 123","color-accent-warning":"255 184 108","color-accent-error":"255 85 85","color-border":"68 71 90"}},{id:"nord",name:"Nord",tokens:{"color-bg-primary":"46 52 64","color-bg-secondary":"59 66 82","color-bg-tertiary":"67 76 94","color-primary":"46 52 64","color-secondary":"59 66 82","color-text-primary":"236 239 244","color-text-secondary":"229 233 240","color-text-muted":"76 86 106","color-accent-primary":"129 161 193","color-accent-success":"163 190 140","color-accent-warning":"235 203 139","color-accent-error":"191 97 106","color-border":"76 86 106"}}];function Xx(){try{const e=localStorage.getItem("openfox:userPresets");if(e)return JSON.parse(e)}catch{}return[]}const dn=$n((e,r)=>({currentPreset:"dark",basePreset:"",customTokens:{},isCustom:!1,isCustomizing:!1,userPresets:Xx(),applySavedTheme:()=>{const{getSavedTheme:s,applyPreset:i,applyTokens:l}=r(),u=s();if(u)try{const h=JSON.parse(u);h.preset?i(h.preset):h.tokens&&l(h.tokens)}catch{i("dark")}else i("dark")},applyPreset:s=>{gr.find(l=>l.id===s)&&(e({currentPreset:s,basePreset:"",customTokens:{},isCustom:!1,isCustomizing:!1}),r().applyTheme())},startCustomizing:()=>{var l;const{currentPreset:s}=r(),i=((l=gr.find(u=>u.id===s))==null?void 0:l.tokens)??{};e({basePreset:s,customTokens:{...i},isCustom:!0,isCustomizing:!0})},setCustomToken:(s,i)=>{e(l=>({customTokens:{...l.customTokens,[s]:i}})),r().applyTheme()},cancelCustomizing:()=>{r().applyPreset(r().basePreset||r().currentPreset)},saveCustomTheme:()=>{const{customTokens:s}=r();r().saveTheme(JSON.stringify({tokens:s})),e({isCustomizing:!1})},applyTokens:s=>{e({customTokens:s,isCustom:!0,isCustomizing:!1}),r().applyTheme()},getActiveTheme:()=>{var h,c;const{basePreset:s,customTokens:i,isCustom:l}=r();if(l&&s)return{...((h=gr.find(p=>p.id===s))==null?void 0:h.tokens)??{},...i};if(l)return{...Ub.reduce((d,p)=>({...d,[p.key]:p.defaultValue}),{}),...i};const u=gr.find(d=>d.id===r().currentPreset);return(u==null?void 0:u.tokens)??((c=gr[0])==null?void 0:c.tokens)??{}},applyTheme:()=>{if(typeof document>"u")return;const s=r().getActiveTheme(),i=document.documentElement;Object.entries(s).forEach(([l,u])=>{i.style.setProperty(`--${l}`,u)})},getSavedTheme:()=>{try{const s=localStorage.getItem("openfox:theme");if(s){const i=JSON.parse(s);if(i.preset)return JSON.stringify({preset:i.preset});if(i.tokens)return JSON.stringify({tokens:i.tokens})}}catch{return null}return null},saveTheme:s=>{localStorage.setItem("openfox:theme",s),mh(async()=>{const{useSettingsStore:i}=await Promise.resolve().then(()=>Ox);return{useSettingsStore:i}},void 0).then(({useSettingsStore:i})=>{i.getState().setSetting(ot.DISPLAY_THEME,s).catch(()=>{})})},clearCustomTheme:()=>{localStorage.removeItem("openfox:theme"),e({isCustom:!1,isCustomizing:!1,basePreset:""})},reset:()=>{e({currentPreset:"dark",basePreset:"",customTokens:{},isCustom:!1,isCustomizing:!1,userPresets:[]})},addUserPreset:s=>{const{basePreset:i,customTokens:l,currentPreset:u}=r(),h={id:"custom-"+Date.now(),name:s,basePreset:i||u,tokens:{...l}},c=[...r().userPresets,h];e({userPresets:c}),r().saveUserPresets()},applyUserPreset:s=>{const i=r().userPresets[s];i&&(e({currentPreset:i.basePreset,basePreset:i.basePreset,customTokens:{...i.tokens},isCustom:!0,isCustomizing:!1}),r().applyTheme(),r().saveTheme(JSON.stringify({tokens:i.tokens})))},deleteUserPreset:s=>{const i=r().userPresets.filter((l,u)=>u!==s);e({userPresets:i}),r().saveUserPresets()},loadUserPresets:()=>{e({userPresets:Xx()})},saveUserPresets:()=>{localStorage.setItem("openfox:userPresets",JSON.stringify(r().userPresets)),mh(async()=>{const{useSettingsStore:s}=await Promise.resolve().then(()=>Ox);return{useSettingsStore:s}},void 0).then(({useSettingsStore:s})=>{s.getState().setSetting(ot.DISPLAY_USER_PRESETS,JSON.stringify(r().userPresets)).catch(()=>{})})}}));function fw({className:e="w-5 h-5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}function $b({className:e="w-3.5 h-3.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M14 5l7 7m0 0l-7 7m7-7H3"})})}function pw({className:e="w-5 h-5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"})})}function mw({className:e="w-3 h-3 text-text-muted"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"})})}function gw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M9.5 3.25a2.25 2.25 0 1 1 3 2.122V6A2.5 2.5 0 0 1 10 8.5H6a1 1 0 0 0-1 1v1.128a2.251 2.251 0 1 1-1.5 0V5.372a2.25 2.25 0 1 1 1.5 0v1.836A2.493 2.493 0 0 1 6 7h4a1 1 0 0 0 1-1v-.628A2.25 2.25 0 0 1 9.5 3.25Zm-6 0a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Zm8.25-.75a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5ZM4.25 12a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Z"})})}function Ur({className:e="w-3.5 h-3.5 text-text-muted"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})})}function xr({className:e="w-3 h-3 text-text-muted",rotate:r}){return o.jsx("svg",{className:e,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,style:r!==void 0?{transform:`rotate(${r}deg)`}:void 0,children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 9l-7 7-7-7"})})}function xw({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",strokeWidth:"2"}),o.jsx("path",{d:"M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1",strokeWidth:"2"})]})}function lc({className:e="w-3.5 h-3.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})})}function vw({className:e="w-3 h-3"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"})})}function zh({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,fill:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("circle",{cx:"12",cy:"5",r:"2"}),o.jsx("circle",{cx:"12",cy:"12",r:"2"}),o.jsx("circle",{cx:"12",cy:"19",r:"2"})]})}function cc({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 Xl({className:e="w-5 h-5 text-accent-primary"}){return o.jsx("svg",{className:e,fill:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{d:"M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"})})}function bw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 9V4.5M9 9H4.5M9 9L3.75 3.75M9 15v4.5M9 15H4.5M9 15l-5.25 5.25M15 9h4.5M15 9V4.5M15 9l5.25-5.25M15 15h4.5M15 15v4.5m0-4.5l5.25 5.25"})})}function yw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"})})}function _w({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M8 0a8.2 8.2 0 0 1 .701.031C9.444.095 9.99.645 10.16 1.29l.288 1.107c.018.066.079.158.212.224.231.114.454.243.668.386.123.082.233.09.299.071l1.1-.303c.652-.18 1.37.008 1.755.653a8.043 8.043 0 0 1 .683 1.18c.227.568.096 1.26-.378 1.726l-.812.804a.312.312 0 0 0-.081.283c.024.166.04.335.04.507s-.016.341-.04.507a.312.312 0 0 0 .08.283l.813.804c.474.466.605 1.158.378 1.726a8.07 8.07 0 0 1-.683 1.18c-.385.645-1.103.833-1.755.653l-1.1-.303c-.066-.019-.176-.011-.299.071a5.1 5.1 0 0 1-.668.386c-.133.066-.194.158-.211.224l-.29 1.107c-.168.645-.714 1.196-1.458 1.26a8.094 8.094 0 0 1-1.402 0c-.744-.064-1.29-.615-1.458-1.26l-.29-1.107a.426.426 0 0 0-.211-.224 5.11 5.11 0 0 1-.668-.386c-.123-.082-.233-.09-.299-.071l-1.1.303c-.652.18-1.37-.008-1.755-.653a8.044 8.044 0 0 1-.683-1.18c-.227-.568-.096-1.26.378-1.726l.812-.804a.312.312 0 0 0 .081-.283A5.18 5.18 0 0 1 2.3 8c0-.172.016-.341.04-.507a.312.312 0 0 0-.08-.283l-.813-.804C.973 5.94.842 5.248 1.069 4.68c.181-.452.395-.882.683-1.18.385-.645 1.103-.833 1.755-.653l1.1.303c.066.019.176.011.299-.071.214-.143.437-.272.668-.386a.426.426 0 0 0 .211-.224l.29-1.107C6.009.645 6.556.095 7.299.03 7.53.01 7.764 0 8 0Zm0 5.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5Z"})})}function Sw({className:e="w-3 h-3"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}function ww({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"})})}function Zx({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h16"})})}function qb({className:e="w-[18px] h-[18px]"}){return o.jsxs("svg",{className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[o.jsx("circle",{cx:"12",cy:"5",r:"1.5",fill:"currentColor",stroke:"none"}),o.jsx("circle",{cx:"12",cy:"12",r:"1.5",fill:"currentColor",stroke:"none"}),o.jsx("circle",{cx:"12",cy:"19",r:"1.5",fill:"currentColor",stroke:"none"})]})}function Cw({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("path",{d:"M6.5 3.5H3a1 1 0 0 0-1 1V13a1 1 0 0 0 1 1h8.5a1 1 0 0 0 1-1V9.5"}),o.jsx("path",{d:"M9.5 2h4.5v4.5"}),o.jsx("path",{d:"M14 2L7.5 8.5"})]})}function kw({className:e="w-3 h-3",color:r}){return o.jsx("svg",{className:e,fill:r??"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{d:"M8 5v14l11-7z"})})}function Wb({className:e="w-3 h-3 text-accent-primary"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})})}function Vb({className:e="",size:r="md"}){const s=r==="sm"?"w-4 h-4":"w-6 h-6";return o.jsxs("svg",{className:`animate-spin ${s} ${e}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),o.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]})}const Gb=Vb,Kb=Vb;function Ew({className:e="w-5 h-5"}){return o.jsx("svg",{className:e,viewBox:"0 0 20 20",fill:"currentColor",children:o.jsx("path",{fillRule:"evenodd",d:"M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z",clipRule:"evenodd"})})}function jw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})})}function Nw({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]})}function Tw({className:e="w-3 h-3 text-blue-400 animate-spin flex-shrink-0"}){return o.jsxs("svg",{"aria-label":"Session running",className:e,viewBox:"0 0 24 24",fill:"none",children:[o.jsx("title",{children:"Running"}),o.jsx("circle",{className:"opacity-30",cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"3"}),o.jsx("path",{d:"M21 12a9 9 0 00-9-9",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round"})]})}function Aw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("rect",{x:"3",y:"3",width:"10",height:"10",rx:"1"})})}function Dw({className:e="w-3.5 h-3.5 shrink-0",color:r}){return o.jsx("svg",{className:e,fill:"none",stroke:r,viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})})}function Lw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 20 20",fill:"currentColor",children:o.jsx("path",{fillRule:"evenodd",d:"M2 5a2 2 0 012-2h12a2 2 0 012 2v10a2 2 0 01-2 2H4a2 2 0 01-2-2V5zm3 1h10v1H5V6zm10 7H5v1h10v-1zm-10 2H5v1h10v-1z",clipRule:"evenodd"})})}function Yb({className:e="w-3.5 h-3.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})})}function Xb(){return o.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})})}function Rw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}function Zb({className:e="w-2.5 h-2.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}function Ph({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 20 20",fill:"currentColor",children:o.jsx("path",{fillRule:"evenodd",d:"M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z",clipRule:"evenodd"})})}function Ow({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.55.55 0 0 1 0-.708z"})})}function gh(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const r=Math.random()*16|0;return(e==="x"?r:r&3|8).toString(16)})}function Qx(e,r){const s=Gt.ws;!s||s.readyState!==WebSocket.OPEN||s.send(JSON.stringify({id:gh(),type:e,payload:r}))}const ir=$n((e,r)=>({isOpen:!1,sessions:[],workdir:null,setOpen:s=>e({isOpen:s}),toggleOpen:()=>e(s=>({isOpen:!s.isOpen})),setWorkdir:s=>e({workdir:s}),fetchSessions:async()=>{try{const s=await ke("/api/terminals");if(s.ok){const i=await s.json();e({sessions:i});const l=Gt.ws;if(l&&l.readyState===WebSocket.OPEN)for(const u of i)l.send(JSON.stringify({id:gh(),type:"terminal.subscribe",payload:{sessionId:u.id}}))}}catch(s){console.error("Failed to fetch terminals:",s)}},createSession:async s=>{try{const i=await ke("/api/terminals",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workdir:s??r().workdir??void 0})});if(i.ok){const l=await i.json();e(h=>({sessions:[...h.sessions,l]}));const u=Gt.ws;u&&u.readyState===WebSocket.OPEN&&u.send(JSON.stringify({id:gh(),type:"terminal.subscribe",payload:{sessionId:l.id}}))}}catch(i){console.error("Failed to create terminal:",i)}},writeSession:(s,i)=>{Qx("terminal.write",{sessionId:s,data:i})},resizeSession:(s,i,l)=>{Qx("terminal.resize",{sessionId:s,cols:i,rows:l})},killSession:async s=>{try{(await ke(`/api/terminals/${s}`,{method:"DELETE"})).ok&&e(l=>({sessions:l.sessions.filter(u=>u.id!==s)}))}catch(i){console.error("Failed to kill terminal:",i)}},handleMessage:s=>{switch(s.type){case"terminal.exit":{const{sessionId:i}=s.payload||{};i&&e(l=>{const u=l.sessions.filter(h=>h.id!==i);return u.length===0&&l.isOpen?{sessions:[],isOpen:!1}:{sessions:u}});break}}}}));Gt.subscribe(e=>{var r;(r=e.type)!=null&&r.startsWith("terminal.")&&ir.getState().handleMessage(e)});var go=kb();const uc=H.forwardRef(({icon:e,iconSize:r="w-3.5 h-3.5",className:s="",...i},l)=>o.jsx("button",{ref:l,type:"button",className:`p-1 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors ${s}`,...i,children:o.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:e})})}));uc.displayName="IconButton";const Mw="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z",qi=H.forwardRef((e,r)=>o.jsx(uc,{ref:r,icon:Mw,title:"Edit",...e}));qi.displayName="EditButton";const Iw="M6 18L18 6M6 6l12 12",Hh=H.forwardRef((e,r)=>o.jsx(uc,{ref:r,icon:Iw,...e}));Hh.displayName="CloseButton";const Bw={sm:"max-w-sm",md:"max-w-md",lg:"max-w-2xl",xl:"max-w-4xl",full:"max-w-[95vw] h-[90vh] flex-1"};function jt({label:e,title:r,size:s="md",minHeight:i,children:l,footer:u,className:h,onClose:c,isOpen:d,closeOnBackdropClick:p=!0,closeOnEscape:g=!0,showCloseButton:m=!0}){const[b,_]=H.useState(!1),k=d!==void 0,C=k?d:b,y=H.useCallback(()=>{k||_(!0)},[k]),v=H.useCallback(()=>{k||_(!1),c==null||c()},[k,c]);H.useEffect(()=>{if(!C||!g)return;const S=j=>{j.key==="Escape"&&v()};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[C,v,g]);const x=e&&(typeof e=="string"?o.jsx("button",{type:"button",onClick:y,className:h,children:e}):o.jsx("span",{onClick:y,className:h,style:{cursor:"pointer"},children:e}));return o.jsxs(o.Fragment,{children:[x,C&&(typeof document<"u"?go.createPortal(o.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:[o.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:p?v:void 0}),o.jsxs("div",{className:`relative w-full ${Bw[s]} max-h-[90vh] bg-bg-secondary border border-border rounded shadow-xl flex flex-col`,children:[(r||m)&&o.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border",children:[r&&o.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:r}),m&&o.jsx(Hh,{onClick:v,className:"ml-auto","aria-label":"Close"})]}),o.jsx("div",{className:"p-4 overflow-y-auto flex-1 min-h-0",style:i?{minHeight:i}:void 0,children:l}),u&&o.jsx("div",{className:"px-4 py-3 border-t border-border",children:u})]})]}),document.body):null)]})}const st=H.forwardRef(({variant:e="secondary",size:r="md",className:s="",children:i,...l},u)=>{const h="rounded font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed",c={primary:"bg-accent-primary/25 text-text-primary hover:bg-accent-primary/40",secondary:"bg-bg-tertiary text-text-primary hover:bg-border",danger:"bg-accent-error text-white hover:bg-accent-error/80"},d={sm:"px-1.5 py-1 text-xs",md:"px-3 py-1.5 text-sm",lg:"px-4 py-2 text-base"};return o.jsx("button",{ref:u,className:`${h} ${c[e]} ${d[r]} ${s}`,...l,children:i})});st.displayName="Button";function zw({value:e,defaultUrl:r,disabled:s,onChange:i}){const l=e??r;return o.jsxs("div",{className:"relative",children:[o.jsx("select",{value:l,disabled:s,onChange:u=>{const h=u.target.value;i(h===r?null:h)},className:"appearance-none bg-bg-tertiary border border-border rounded px-1.5 pr-5 text-xs focus:outline-none focus:ring-1 focus:ring-accent-primary disabled:opacity-40 cursor-pointer",style:{width:"60px"},children:G1.map(({url:u,label:h})=>o.jsx("option",{value:u,title:h,children:h.split(" ")[0]},u))}),o.jsx(xr,{className:"absolute right-0.5 top-1/2 -translate-y-1/2 w-3 h-3 pointer-events-none text-text-muted"})]})}const Jx=[{key:"general",label:"General"},{key:"build",label:"Agent"},{key:"sub-agent",label:"Sub-agent"}];function Pw(){const e=Fs(d=>d.settings),r=Fs(d=>d.update),s=Fs(d=>d.updateEvent),i=Fs(d=>d.updateAgentOverride),l=Fs(d=>d.load);H.useEffect(()=>{l()},[l]);const u=async()=>{await Y1()==="granted"&&r({...e,browserNotificationEnabled:!0})},h=(d,p,g,m)=>{d==="general"?s(p,{[g]:m}):i(d,p,{[g]:m})},c=(d,p,g)=>{d==="general"?s(p,{customSoundUrl:g}):i(d,p,{customSoundUrl:g})};return o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"space-y-3",children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Master Controls"}),o.jsx(ev,{label:"Sound notifications",description:"Play sounds when events occur",checked:e.soundEnabled,onChange:d=>r({...e,soundEnabled:d})}),o.jsx(ev,{label:"Browser notifications",description:"Show desktop notifications when the window is not focused",checked:e.browserNotificationEnabled,onChange:d=>{d&&typeof Notification<"u"&&Notification.permission!=="granted"?u():r({...e,browserNotificationEnabled:d})}}),typeof Notification<"u"&&Notification.permission==="denied"&&e.browserNotificationEnabled&&o.jsx("p",{className:"text-xs text-accent-error ml-6",children:"Browser notifications are blocked. Please enable them in your browser settings."})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Notification Settings"}),o.jsx("div",{className:"border border-border rounded overflow-hidden",children:o.jsxs("table",{className:"w-full text-sm",children:[o.jsx("thead",{className:"sticky top-0 bg-bg-tertiary",children:o.jsxs("tr",{className:"border-b border-border",children:[o.jsx("th",{className:"text-left px-3 py-2 text-text-primary font-medium w-40",children:"Event"}),Jx.map(d=>o.jsx("th",{className:"text-center px-2 py-2 text-text-primary font-medium",children:d.label},d.key))]})}),o.jsx("tbody",{children:V1.map(d=>o.jsxs("tr",{className:"border-b border-border last:border-b-0 hover:bg-bg-secondary/50",children:[o.jsx("td",{className:"px-3 py-2",children:o.jsx("div",{className:"text-text-primary text-xs",children:d.label})}),Jx.map(p=>{const g=Pb(e,d.key,p.key==="general"?void 0:p.key),m=Bb[d.key];return o.jsx("td",{className:"px-2 py-2 align-top",children:o.jsxs("div",{className:"flex flex-col items-center gap-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("label",{className:"flex items-center gap-1 text-text-secondary",children:o.jsx("input",{type:"checkbox",checked:g.soundEnabled,onChange:b=>h(p.key,d.key,"soundEnabled",b.target.checked),disabled:!e.soundEnabled,className:"rounded border-border",title:"Sound"})}),o.jsx("label",{className:"flex items-center gap-1 text-text-secondary",children:o.jsx("input",{type:"checkbox",checked:g.browserNotification,onChange:b=>h(p.key,d.key,"browserNotification",b.target.checked),disabled:!e.browserNotificationEnabled,className:"rounded border-border",title:"Browser"})})]}),g.soundEnabled&&e.soundEnabled&&o.jsx(zw,{value:g.customSoundUrl,defaultUrl:m,disabled:!e.soundEnabled,onChange:b=>c(p.key,d.key,b)})]})},p.key)})]},d.key))})]})})]})]})}function ev({label:e,description:r,checked:s,onChange:i}){return o.jsxs("label",{className:"flex items-start gap-3 cursor-pointer group",children:[o.jsx("div",{className:"pt-0.5",children:o.jsx("div",{className:`relative w-9 h-5 rounded-full transition-colors ${s?"bg-accent-primary":"bg-bg-tertiary border border-border"}`,onClick:l=>{l.preventDefault(),i(!s)},children:o.jsx("div",{className:`absolute top-0.5 w-4 h-4 rounded-full bg-white shadow transition-transform ${s?"translate-x-4":"translate-x-0.5"}`})})}),o.jsxs("div",{children:[o.jsx("div",{className:"text-sm text-text-primary group-hover:text-accent-primary transition-colors",children:e}),o.jsx("div",{className:"text-xs text-text-muted",children:r})]})]})}async function Fh(e,r){r({loading:!0});try{const i=await(await ke(e)).json();r({defaults:i.defaults??[],userItems:i.userItems??[],loading:!1})}catch{r({loading:!1})}}const Pr=$n((e,r)=>({defaults:[],userItems:[],loading:!1,fetchSkills:async()=>{await Fh("/api/skills",e)},toggleSkill:async s=>{try{const l=await(await ke(`/api/skills/${s}/toggle`,{method:"POST"})).json();e(u=>({defaults:u.defaults.map(h=>h.id===s?{...h,enabled:l.enabled}:h),userItems:u.userItems.map(h=>h.id===s?{...h,enabled:l.enabled}:h)}))}catch{}},fetchSkill:async s=>{try{const i=await ke(`/api/skills/${s}`);return i.ok?await i.json():null}catch{return null}},fetchDefaultContent:async s=>{try{const i=await ke(`/api/skills/defaults/${s}`);return i.ok?await i.json():null}catch{return null}},createSkill:async s=>{const i=await xs("POST","/api/skills",s);return i.success&&await r().fetchSkills(),i},updateSkill:async(s,i)=>{const l=await xs("PUT",`/api/skills/${s}`,i);return l.success&&await r().fetchSkills(),l},deleteSkill:async s=>{try{const i=await ke(`/api/skills/${s}`,{method:"DELETE"}),l=await i.json();return i.ok?(e(u=>({userItems:u.userItems.filter(h=>h.id!==s)})),{success:!0}):{success:!1,error:l.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateSkill:async s=>{try{const i=await ke(`/api/skills/${s}/duplicate`,{method:"POST"}),l=await i.json();return i.ok?(await r().fetchSkills(),{success:!0}):{success:!1,error:l.error??"Failed to duplicate"}}catch{return{success:!1,error:"Network error"}}}}));function Uh(){const[e,r]=H.useState({id:null,type:null}),s=H.useCallback(u=>r({id:u,type:"delete"}),[]),i=H.useCallback(()=>r({id:null,type:null}),[]),l=H.useCallback((u,h)=>e.id===u&&e.type===h,[e.id,e.type]);return{requestDelete:s,clearConfirm:i,isConfirming:l}}function $h({onConfirm:e,onCancel:r}){return o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("button",{onClick:e,className:"px-1.5 py-0.5 rounded text-xs hover:opacity-90 transition-colors bg-accent-error/20 text-accent-error hover:bg-accent-error/30",children:"Delete"}),o.jsx("button",{onClick:r,className:"px-1.5 py-0.5 rounded text-text-muted text-xs hover:bg-bg-primary transition-colors",children:"Cancel"})]})}function qh({onClick:e}){return o.jsx("button",{onClick:e,className:"p-1.5 rounded hover:bg-bg-primary text-text-muted hover:text-accent-error transition-colors",title:"Delete",children:o.jsx(Yb,{})})}function io({onClick:e}){return o.jsx("button",{onClick:e,className:"p-1.5 rounded hover:bg-bg-primary text-text-muted hover:text-text-primary transition-colors",title:"Duplicate",children:o.jsx(lc,{})})}function Us({label:e,value:r,onChange:s,placeholder:i,readOnly:l,hint:u,mono:h}){return o.jsxs("div",{children:[o.jsxs("label",{className:"block text-xs text-text-secondary mb-1",children:[e,u&&o.jsx("span",{className:"text-text-muted ml-1",children:u})]}),o.jsx("input",{value:r,onChange:c=>s(c.target.value),readOnly:l,placeholder:i,className:`w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary ${h?"font-mono":""} ${l?"opacity-60":""}`})]})}function Hw({onCancel:e,onSave:r,saving:s,saveDisabled:i}){return o.jsxs("div",{className:"flex justify-end gap-2 pt-2 border-t border-border",children:[o.jsx(st,{variant:"secondary",onClick:e,children:"Cancel"}),o.jsx(st,{variant:"primary",onClick:r,disabled:s||i,children:s?"Saving...":"Save"})]})}function Wh({message:e}){return o.jsx("div",{className:"text-accent-error text-sm px-3 py-2 bg-accent-error/10 rounded",children:e})}function Qb({description:e,onNew:r,newLabel:s="+ New"}){return o.jsxs("div",{className:"flex items-center justify-between mb-4",children:[o.jsx("p",{className:"text-text-secondary text-sm",children:e}),o.jsx("div",{className:"flex items-center gap-2 flex-shrink-0 ml-3",children:o.jsx(st,{variant:"primary",size:"sm",onClick:r,children:s})})]})}function Jb({isBuiltIn:e,isConfirmingDelete:r,onView:s,onEdit:i,onDuplicate:l,onDelete:u,children:h}){return o.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[o.jsx("div",{className:"min-w-0 flex-1 mr-3",children:h}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[e&&s&&o.jsx("button",{onClick:s,className:"p-1.5 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors",title:"View",children:o.jsx(cc,{})}),o.jsx(io,{onClick:l}),!e&&i&&o.jsx(qi,{onClick:i}),!e&&(r?o.jsx($h,{onConfirm:()=>{u==null||u()},onCancel:()=>{}}):o.jsx(qh,{onClick:()=>u==null?void 0:u()}))]})]})}function Fw({id:e,name:r,description:s,isBuiltIn:i,isConfirmingDelete:l,onView:u,onEdit:h,onDuplicate:c,onDelete:d}){return o.jsxs(Jb,{isBuiltIn:i,isConfirmingDelete:l,onView:u,onEdit:h,onDuplicate:c,onDelete:d,children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-text-primary text-sm font-medium",children:r}),o.jsx("span",{className:"text-text-muted text-xs font-mono",children:e})]}),s&&o.jsx("p",{className:"text-text-muted text-xs truncate",children:s})]})}function ey({loading:e,hasItems:r,loadingLabel:s,emptyLabel:i,children:l}){return e&&!r?o.jsx("div",{className:"text-text-muted text-sm",children:s}):r?o.jsx("div",{className:"space-y-4",children:l}):i?o.jsx("div",{className:"text-text-muted text-sm",children:i}):null}function ty({name:e,id:r,nameLabel:s="Name",idLabel:i="ID",namePlaceholder:l="My Item",idPlaceholder:u="my-item",nameHint:h,readOnlyId:c=!1,readOnlyHint:d="(read-only)",onNameChange:p,onIdChange:g}){return o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(Us,{label:s,value:e,onChange:p,placeholder:l,hint:h}),o.jsx(Us,{label:i,value:r,onChange:g,readOnly:c,placeholder:u,hint:c?d:void 0,mono:!0})]})}function ny(e={}){const{initialData:r={}}=e,[s,i]=H.useState("list"),[l,u]=H.useState(null),[h,c]=H.useState(""),[d,p]=H.useState(!1),[g,m]=H.useState(r),b=H.useCallback(()=>{m(r),c(""),u(null)},[r]),_=H.useCallback(v=>{i(v),v==="list"&&b()},[b]),k=H.useCallback(v=>{m(x=>typeof v=="function"?v(x):v)},[]),C=H.useCallback((v,x={})=>{u(v),i("edit"),m({...x}),c("")},[]),y=H.useCallback(()=>{u(null),i("edit"),m(r),c("")},[r]);return{view:s,editingId:l,formError:h,saving:d,formData:g,setView:_,setEditingId:u,setFormError:c,setFormData:k,setSaving:p,resetForm:b,startEditing:C,startNew:y}}function Vh(){return o.jsxs("div",{className:"flex items-start gap-2 px-3 py-2 mt-3 bg-accent-warning/10 border border-accent-warning/30 rounded text-xs",children:[o.jsx("span",{children:"⚠️"}),o.jsx("p",{className:"text-text-secondary",children:"Editing this value now will have the side-effect of invalidating KV-cache, causing your next message in current sessions to take a long time to process. Consider doing this between sessions."})]})}function tv({skill:e,isBuiltIn:r,isConfirmingDelete:s,onView:i,onEdit:l,onDuplicate:u,onDelete:h}){return o.jsx(Fw,{id:e.id,name:e.name,description:e.description,isBuiltIn:r,isConfirmingDelete:s,onView:i,onEdit:l,onDuplicate:u,onDelete:h})}function Uw({isOpen:e}){const r=Pr(I=>I.defaults),s=Pr(I=>I.userItems),i=Pr(I=>I.loading),l=Pr(I=>I.fetchSkills),u=Pr(I=>I.fetchSkill),h=Pr(I=>I.fetchDefaultContent),c=Pr(I=>I.createSkill),d=Pr(I=>I.updateSkill),p=Pr(I=>I.deleteSkill),{view:g,editingId:m,formError:b,saving:_,formData:k,setView:C,setEditingId:y,setFormError:v,setFormData:x,setSaving:S}=ny(),{clearConfirm:j}=Uh();H.useEffect(()=>{e&&(l(),C("list"),y(null),j())},[e,l,j]);const T=(I,$,B,X)=>{x({name:X??I.metadata.name,id:B??I.metadata.id,description:I.metadata.description??"",version:I.metadata.version??"1.0.0",prompt:I.prompt,isReadOnly:$})},N=async I=>{if(r.some(B=>B.id===I)){const B=await h(I);if(!B)return;T(B,!0),y(I),v(""),C("edit")}else{const B=await u(I);if(!B)return;T(B,!0),y(I),v(""),C("edit")}},D=async I=>{const B=r.some(Z=>Z.id===I)?await h(I):await u(I);if(!B)return;const X=`${I}-copy-${Date.now()}`;T(B,!1,X,`${B.metadata.name} (copy)`),y(null),v(""),C("edit")},A=()=>{x({name:"",id:"",description:"",version:"1.0.0",prompt:"",isReadOnly:!1}),C("edit")},z=async I=>{const $=await u(I);$&&(T($,!1),y(I),v(""),C("edit"))},O=async I=>{await p(I),j()},q=async()=>{const I=m??k.id;if(!I||!k.name||!k.prompt){v("Name, ID, and prompt are required.");return}S(!0),v("");const $={metadata:{id:I,name:k.name,description:k.description,version:k.version},prompt:k.prompt},B=m?await d(m,$):await c($);if(S(!1),!B.success){v(B.error??"Failed to save skill.");return}C("list")},G=I=>{x($=>({...$,name:I})),m||x($=>({...$,id:I.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}))},W=k.isReadOnly;return g==="edit"?o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:"flex justify-between items-center mb-3",children:[o.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:W?k.name:m?"Edit Skill":"New Skill"}),o.jsx("button",{onClick:()=>C("list"),className:"text-text-muted hover:text-text-primary",children:"Cancel"})]}),b&&o.jsx(Wh,{message:b}),o.jsxs("div",{className:"space-y-3 mb-3",children:[o.jsx(ty,{name:k.name,id:k.id,nameLabel:"Name",idLabel:"ID",namePlaceholder:"My Skill",idPlaceholder:"my-skill",readOnlyId:!0,onNameChange:G,onIdChange:()=>{}}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(Us,{label:"Description",value:k.description,onChange:I=>x($=>({...$,description:I})),placeholder:"What this skill does...",readOnly:W}),o.jsx(Us,{label:"Version",value:k.version,onChange:I=>x($=>({...$,version:I})),placeholder:"1.0.0",readOnly:W})]})]}),o.jsxs("div",{className:"flex-1 min-h-[120px] border-t border-border pt-3 flex flex-col",children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Prompt"}),o.jsx("textarea",{value:k.prompt,onChange:I=>x($=>({...$,prompt:I.target.value})),readOnly:W,placeholder:"The system prompt for this skill...",className:"h-80 w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-y focus:outline-none focus:ring-1 focus:ring-accent-primary"})]}),o.jsx(Vh,{}),o.jsxs("div",{className:"flex justify-end gap-2 pt-3 border-t border-border flex-shrink-0",children:[o.jsx(st,{variant:"secondary",onClick:()=>C("list"),children:"Cancel"}),W?o.jsx(st,{variant:"primary",onClick:()=>{x(I=>({...I,name:I.name+" (copy)",id:`${m}-copy-${Date.now()}`,isReadOnly:!1})),y(null)},children:"Duplicate & Customize"}):o.jsx(st,{variant:"primary",onClick:q,disabled:_||!k.name||!k.id||!k.prompt,children:_?"Saving...":"Save"})]})]}):o.jsxs("div",{children:[o.jsx(Qb,{description:"Skills provide domain-specific knowledge that agents can load on demand.",onNew:A}),o.jsxs(ey,{loading:i,hasItems:r.length>0||s.length>0,loadingLabel:"Loading skills...",emptyLabel:"No skills created yet.",children:[r.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Built-in"}),o.jsx("div",{className:"space-y-2",children:r.map(I=>o.jsx(tv,{skill:I,isBuiltIn:!0,isConfirmingDelete:!1,onView:()=>N(I.id),onDuplicate:()=>D(I.id)},I.id))})]}),s.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Custom"}),o.jsx("div",{className:"space-y-2",children:s.map(I=>o.jsx(tv,{skill:I,isBuiltIn:!1,isConfirmingDelete:!1,onView:()=>N(I.id),onEdit:()=>z(I.id),onDuplicate:()=>D(I.id),onDelete:()=>O(I.id)},I.id))})]})]})]})}function $w(e){const r=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);if(r){const s=parseInt(r[1]??"0",16),i=parseInt(r[2]??"0",16),l=parseInt(r[3]??"0",16);return`${s} ${i} ${l}`}return e}function Hs(e){const r=e.split(" ").map(s=>parseInt(s,10));return r.length===3&&r.every(s=>!isNaN(s))?`#${r.map(s=>(s??0).toString(16).padStart(2,"0")).join("")}`:e}function qw({isOpen:e,isNew:r,basePresetId:s,presetName:i,initialTokens:l,onClose:u,onSave:h}){const[c,d]=H.useState(l),[p,g]=H.useState(i);H.useEffect(()=>{d(l),g(i)},[l,i]);const m=(y,v)=>{const x=v.startsWith("#")?$w(v):v;d(S=>({...S,[y]:x}))},b=()=>{h(p.trim()||"Untitled",{...c})},_=Ub.reduce((y,v)=>{const x=v.category;return y[x]||(y[x]=[]),y[x].push(v),y},{}),k={background:"Backgrounds",surface:"Surfaces",text:"Text",accent:"Accents",border:"Border"},C=gr.find(y=>y.id===s);return o.jsx(jt,{isOpen:e,onClose:u,size:"lg",title:r?"New Theme":"Edit Theme",closeOnBackdropClick:!0,closeOnEscape:!0,footer:o.jsxs("div",{className:"flex gap-2 justify-end",children:[o.jsx("button",{type:"button",onClick:u,className:"px-4 py-2 border border-border rounded text-sm text-text-primary hover:bg-bg-tertiary transition-colors",children:"Cancel"}),o.jsx("button",{type:"button",onClick:b,className:"px-4 py-2 bg-accent-primary text-white rounded hover:bg-accent-primary/80 transition-colors text-sm",children:"Save"})]}),children:o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-muted block mb-1",children:"Name"}),o.jsx("input",{type:"text",value:p,onChange:y=>g(y.target.value),className:"w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-accent-primary"})]}),!r&&o.jsxs("div",{className:"text-xs text-text-muted",children:["Based on ",o.jsx("span",{className:"text-text-primary",children:C==null?void 0:C.name})]}),Object.entries(_).map(([y,v])=>o.jsxs("div",{className:"space-y-3",children:[o.jsx("h4",{className:"text-xs font-medium text-text-muted uppercase",children:k[y]??y}),o.jsx("div",{className:"grid grid-cols-2 gap-3",children:v.map(x=>o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("label",{htmlFor:x.key,className:"text-xs text-text-muted",children:x.label}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"color",id:x.key,value:Hs(c[x.key]??x.defaultValue),onChange:S=>m(x.key,S.target.value),className:"w-8 h-8 rounded cursor-pointer border border-border bg-transparent"}),o.jsx("input",{type:"text",value:c[x.key]??x.defaultValue,onChange:S=>m(x.key,S.target.value),className:"flex-1 px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary font-mono focus:outline-none focus:ring-1 focus:ring-accent-primary"})]})]},x.key))})]},y))]})})}function Ww(){const[e,r]=H.useState(null),s=dn(x=>x.currentPreset),i=dn(x=>x.isCustom),l=dn(x=>x.basePreset),u=dn(x=>x.userPresets),h=dn(x=>x.applyPreset),c=dn(x=>x.applyUserPreset),d=dn(x=>x.deleteUserPreset),p=dn(x=>x.saveTheme),g=x=>{h(x),p(JSON.stringify({preset:x}))},m=x=>{c(x)},b=x=>{const S=gr.find(j=>j.id===x);S&&r({type:"new",presetIndex:u.length,basePresetId:x,presetName:S.name+" Copy",tokens:{...S.tokens}})},_=x=>{const S=u[x];if(!S)return;const j=gr.find(N=>N.id===S.basePreset),T=j?{...j.tokens,...S.tokens}:S.tokens;r({type:"edit",presetIndex:x,basePresetId:S.basePreset,presetName:S.name,tokens:T})},k=(x,S)=>{if(!e)return;const j=[...u];if(e.type==="new"){const T={id:"custom-"+Date.now(),name:x,basePreset:e.basePresetId,tokens:S};j.push(T);const N=j.length-1;dn.setState({userPresets:j}),dn.getState().saveUserPresets(),dn.getState().applyUserPreset(N)}else{const T=j[e.presetIndex];T&&(j[e.presetIndex]={...T,name:x,tokens:S}),dn.setState({userPresets:j}),dn.getState().saveUserPresets(),dn.getState().applyUserPreset(e.presetIndex)}r(null)},C=()=>{r(null)},y=(x,S)=>{x.stopPropagation(),d(S)},v=i?l:s;return o.jsxs("div",{className:"space-y-4",children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Theme"}),o.jsx("div",{className:"grid grid-cols-5 gap-2",children:gr.map(x=>o.jsxs("div",{className:"relative group",children:[o.jsxs("button",{type:"button",onClick:()=>g(x.id),className:`w-full flex flex-col items-center gap-2 px-3 py-3 rounded-lg border transition-colors ${v===x.id&&!i?"border-accent-primary bg-bg-tertiary text-text-primary":"border-border bg-bg-secondary text-text-muted hover:border-text-muted"}`,children:[o.jsx("div",{className:"w-8 h-8 rounded border flex items-center justify-center",style:{backgroundColor:Hs(x.tokens["color-bg-primary"]??"#000"),borderColor:Hs(x.tokens["color-border"]??"#000")},children:o.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:Hs(x.tokens["color-text-primary"]??"#fff")}})}),o.jsx("span",{className:"text-xs",children:x.name})]}),o.jsx("button",{type:"button",onClick:S=>{S.stopPropagation(),b(x.id)},className:"absolute top-1 right-1 w-6 h-6 rounded bg-bg-tertiary border border-border flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:border-text-muted",title:"Create custom theme based on this",children:o.jsx("span",{className:"text-xs",children:"✎"})})]},x.id))}),u.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("h4",{className:"text-xs font-medium text-text-muted uppercase",children:"My Themes"}),o.jsx("div",{className:"grid grid-cols-5 gap-2",children:u.map((x,S)=>{const j=gr.find(N=>N.id===x.basePreset),T=j?{...j.tokens,...x.tokens}:x.tokens;return o.jsxs("div",{className:"relative group",children:[o.jsxs("button",{type:"button",onClick:()=>m(S),className:`w-full flex flex-col items-center gap-2 px-3 py-3 rounded-lg border transition-colors ${i&&l===x.basePreset&&v===x.basePreset?"border-accent-primary bg-bg-tertiary text-text-primary":"border-border bg-bg-secondary text-text-muted hover:border-text-muted"}`,children:[o.jsx("div",{className:"w-8 h-8 rounded border flex items-center justify-center",style:{backgroundColor:Hs(T["color-bg-primary"]??"#000"),borderColor:Hs(T["color-border"]??"#000")},children:o.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:Hs(T["color-text-primary"]??"#fff")}})}),o.jsx("span",{className:"text-xs truncate w-full text-center",children:x.name})]}),o.jsx("button",{type:"button",onClick:N=>{N.stopPropagation(),_(S)},className:"absolute top-1 right-1 w-6 h-6 rounded bg-bg-tertiary border border-border flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:border-text-muted",title:"Edit",children:o.jsx("span",{className:"text-xs",children:"✎"})}),o.jsx("button",{type:"button",onClick:N=>y(N,S),className:"absolute -top-1 -left-1 w-5 h-5 rounded-full bg-accent-error text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-20",children:o.jsx(Ph,{className:"w-3 h-3"})})]},x.id)})})]}),e&&o.jsx(qw,{isOpen:!0,isNew:e.type==="new",presetIndex:e.presetIndex,basePresetId:e.basePresetId,presetName:e.presetName,initialTokens:e.tokens,onClose:C,onSave:k})]})}function Vw({isOpen:e,onClose:r}){const[s,i]=H.useState("instructions");return o.jsx(jt,{isOpen:e,onClose:r,title:"Settings",size:"xl",minHeight:"500px",children:o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:"flex border-b border-border mb-4 -mt-1",children:[o.jsx(qa,{label:"Instructions",active:s==="instructions",onClick:()=>i("instructions")}),o.jsx(qa,{label:"Skills",active:s==="skills",onClick:()=>i("skills")}),o.jsx(qa,{label:"Notifications",active:s==="notifications",onClick:()=>i("notifications")}),o.jsx(qa,{label:"Display",active:s==="display",onClick:()=>i("display")}),o.jsx(qa,{label:"Advanced",active:s==="advanced",onClick:()=>i("advanced")})]}),s==="instructions"&&o.jsx(Xw,{isOpen:e}),s==="skills"&&o.jsx(Uw,{isOpen:e}),s==="notifications"&&o.jsx("div",{className:"max-h-[60vh] overflow-y-auto",children:o.jsx(Pw,{})}),s==="display"&&o.jsx(Yw,{}),s==="advanced"&&o.jsx(Gw,{onClose:r})]})})}function Gw({onClose:e}){const[,r]=vr();function s(){e(),r("/onboarding")}return o.jsx("div",{className:"space-y-6",children:o.jsxs("div",{children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary mb-1",children:"Onboarding"}),o.jsx("p",{className:"text-sm text-text-muted mb-4",children:"Reset your OpenFox setup and go through the initial configuration again."}),o.jsx(st,{variant:"secondary",onClick:s,children:"Launch Onboarding"})]})})}function Kw(){return o.jsx(Ww,{})}function Yw(){const e=Yt(g=>g.settings),r=Yt(g=>g.loading),s=Yt(g=>g.getSetting),i=Yt(g=>g.setSetting),l=r[ot.DISPLAY_SHOW_THINKING]??!1,u=[{key:ot.DISPLAY_SHOW_THINKING,label:"Show thinking blocks",description:"Display AI reasoning content in the feed"},{key:ot.DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT,label:"Show expanded tool output",description:"Always show full tool call details instead of compact view"},{key:ot.DISPLAY_SHOW_STATS,label:"Show stats bar",description:"Display model, tokens, and timing information"},{key:ot.DISPLAY_SHOW_AGENT_DEFINITIONS,label:"Show agent definitions",description:"Display agent definition injections in the feed"},{key:ot.DISPLAY_SHOW_WORKFLOW_BARS,label:"Show workflow bars",description:"Display workflow start and end markers"}],h=Object.fromEntries(u.map(g=>[g.key,e[g.key]??"true"])),[c,d]=H.useState(()=>Object.fromEntries(u.map(g=>[g.key,h[g.key]==="true"])));H.useEffect(()=>{u.forEach(g=>s(g.key))},[s]),H.useEffect(()=>{d(Object.fromEntries(u.map(g=>[g.key,h[g.key]==="true"])))},[JSON.stringify(h)]);const p=async g=>{const m=String(!c[g]);d(b=>({...b,[g]:!b[g]})),await i(g,m)};return l?o.jsx("div",{className:"text-sm text-text-muted",children:"Loading..."}):o.jsxs("div",{className:"space-y-6",children:[o.jsx(Kw,{}),o.jsxs("div",{children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary mb-4",children:"Feed Display"}),o.jsx("div",{className:"space-y-4",children:u.map(({key:g,label:m,description:b})=>o.jsxs("label",{className:"flex items-center justify-between cursor-pointer",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-sm text-text-primary",children:m}),o.jsx("div",{className:"text-xs text-text-muted",children:b})]}),o.jsx("button",{type:"button",onClick:()=>p(g),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${c[g]?"bg-accent-primary":"bg-bg-tertiary"}`,children:o.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${c[g]?"translate-x-6":"translate-x-1"}`})})]},g))})]})]})}function qa({label:e,active:r,onClick:s}){return o.jsx("button",{onClick:s,className:`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${r?"border-accent-primary text-accent-primary":"border-transparent text-text-muted hover:text-text-secondary hover:border-border"}`,children:e})}function Xw({isOpen:e}){const r=Yt(y=>y.settings),s=Yt(y=>y.loading),i=Yt(y=>y.getSetting),l=Yt(y=>y.setSetting),u=r[ot.GLOBAL_INSTRUCTIONS]??"",h=s[ot.GLOBAL_INSTRUCTIONS]??!1,[c,d]=H.useState(u),[p,g]=H.useState(!1),[m,b]=H.useState(!1);H.useEffect(()=>{e&&i(ot.GLOBAL_INSTRUCTIONS)},[e,i]),H.useEffect(()=>{d(u),g(!1)},[u]);const _=async()=>{b(!0),l(ot.GLOBAL_INSTRUCTIONS,c),b(!1),g(!1)},k=()=>{d(u),g(!1)},C=h||m;return o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-text-primary mb-2",children:"Global Instructions"}),o.jsx("p",{className:"text-sm text-text-muted mb-2",children:"These instructions are injected into every prompt, regardless of project."}),o.jsx("textarea",{value:c,onChange:y=>{d(y.target.value),g(!0)},placeholder:"Enter global instructions that apply to all projects...",className:"w-full min-h-80 px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-y focus:outline-none focus:ring-1 focus:ring-accent-primary",disabled:C})]}),p&&o.jsx(Vh,{}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(st,{variant:"secondary",onClick:k,disabled:!p,children:"Discard"}),o.jsx(st,{variant:"primary",onClick:_,disabled:!p||C,children:m?"Saving...":"Save"})]})]})}var qd={exports:{}},nv;function Zw(){return nv||(nv=1,(function(e,r){(function(s,i){e.exports=i()})(globalThis,(()=>(()=>{var s={4567:function(h,c,d){var p=this&&this.__decorate||function(x,S,j,T){var N,D=arguments.length,A=D<3?S:T===null?T=Object.getOwnPropertyDescriptor(S,j):T;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")A=Reflect.decorate(x,S,j,T);else for(var z=x.length-1;z>=0;z--)(N=x[z])&&(A=(D<3?N(A):D>3?N(S,j,A):N(S,j))||A);return D>3&&A&&Object.defineProperty(S,j,A),A},g=this&&this.__param||function(x,S){return function(j,T){S(j,T,x)}};Object.defineProperty(c,"__esModule",{value:!0}),c.AccessibilityManager=void 0;const m=d(9042),b=d(9924),_=d(844),k=d(4725),C=d(2585),y=d(3656);let v=c.AccessibilityManager=class extends _.Disposable{constructor(x,S,j,T){super(),this._terminal=x,this._coreBrowserService=j,this._renderService=T,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let N=0;N<this._terminal.rows;N++)this._rowElements[N]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[N]);if(this._topBoundaryFocusListener=N=>this._handleBoundaryFocus(N,0),this._bottomBoundaryFocusListener=N=>this._handleBoundaryFocus(N,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new b.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((N=>this._handleResize(N.rows)))),this.register(this._terminal.onRender((N=>this._refreshRows(N.start,N.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((N=>this._handleChar(N)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
57
+ */var Mx;function b1(){if(Mx)return Hd;Mx=1;var e=ac();function r(m,b){return m===b&&(m!==0||1/m===1/b)||m!==m&&b!==b}var s=typeof Object.is=="function"?Object.is:r,i=e.useState,l=e.useEffect,u=e.useLayoutEffect,h=e.useDebugValue;function c(m,b){var _=b(),k=i({inst:{value:_,getSnapshot:b}}),C=k[0].inst,y=k[1];return u(function(){C.value=_,C.getSnapshot=b,d(C)&&y({inst:C})},[m,_,b]),l(function(){return d(C)&&y({inst:C}),m(function(){d(C)&&y({inst:C})})},[m]),h(_),_}function d(m){var b=m.getSnapshot;m=m.value;try{var _=b();return!s(m,_)}catch{return!0}}function p(m,b){return b()}var g=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?p:c;return Hd.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:g,Hd}var Ix;function y1(){return Ix||(Ix=1,Pd.exports=b1()),Pd.exports}var _1=y1();const S1=a1.useInsertionEffect,w1=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",C1=w1?H.useLayoutEffect:H.useEffect,k1=S1||C1,jb=e=>{const r=H.useRef([e,(...s)=>r[0](...s)]).current;return k1(()=>{r[0]=e}),r[1]},E1="popstate",Oh="pushState",Mh="replaceState",j1="hashchange",Bx=[E1,Oh,Mh,j1],N1=e=>{for(const r of Bx)addEventListener(r,e);return()=>{for(const r of Bx)removeEventListener(r,e)}},Nb=(e,r)=>_1.useSyncExternalStore(N1,e,r),zx=()=>location.search,T1=({ssrSearch:e}={})=>Nb(zx,e!=null?()=>e:zx),Px=()=>location.pathname,A1=({ssrPath:e}={})=>Nb(Px,e!=null?()=>e:Px),D1=(e,{replace:r=!1,state:s=null}={})=>history[r?Mh:Oh](s,"",e),L1=(e={})=>[A1(e),D1],Hx=Symbol.for("wouter_v3");if(typeof history<"u"&&typeof window[Hx]>"u"){for(const e of[Oh,Mh]){const r=history[e];history[e]=function(){const s=r.apply(this,arguments),i=new Event(e);return i.arguments=arguments,dispatchEvent(i),s}}Object.defineProperty(window,Hx,{value:!0})}const R1=(e,r)=>r.toLowerCase().indexOf(e.toLowerCase())?"~"+r:r.slice(e.length)||"/",Tb=(e="")=>e==="/"?"":e,O1=(e,r)=>e[0]==="~"?e.slice(1):Tb(r)+e,M1=(e="",r)=>R1(Fx(Tb(e)),Fx(r)),Fx=e=>{try{return decodeURI(e)}catch{return e}},Ab={hook:L1,searchHook:T1,parser:v1,base:"",ssrPath:void 0,ssrSearch:void 0,ssrContext:void 0,hrefs:e=>e,aroundNav:(e,r,s)=>e(r,s)},Db=H.createContext(Ab),Vi=()=>H.useContext(Db),Lb={},Rb=H.createContext(Lb),I1=()=>H.useContext(Rb),oc=e=>{const[r,s]=e.hook(e);return[M1(e.base,r),jb((i,l)=>e.aroundNav(s,O1(i,e.base),l))]},vr=()=>oc(Vi()),Ih=(e,r,s,i)=>{const{pattern:l,keys:u}=r instanceof RegExp?{keys:!1,pattern:r}:e(r||"*",i),h=l.exec(s)||[],[c,...d]=h;return c!==void 0?[!0,(()=>{const p=u!==!1?Object.fromEntries(u.map((m,b)=>[m,d[b]])):h.groups;let g={...d};return p&&Object.assign(g,p),g})(),...i?[c]:[]]:[!1,null]},Bh=e=>Ih(Vi().parser,e,vr()[0]),B1=({children:e,...r})=>{var g,m,b;const s=Vi(),i=r.hook?Ab:s;let l=i;const[u,h=r.ssrSearch??""]=((g=r.ssrPath)==null?void 0:g.split("?"))??[];u&&(r.ssrSearch=h,r.ssrPath=u),r.hrefs=r.hrefs??((m=r.hook)==null?void 0:m.hrefs),r.searchHook=r.searchHook??((b=r.hook)==null?void 0:b.searchHook);let c=H.useRef({}),d=c.current,p=d;for(let _ in i){const k=_==="base"?i[_]+(r[_]??""):r[_]??i[_];d===p&&k!==p[_]&&(c.current=p={...p}),p[_]=k,(k!==i[_]||k!==l[_])&&(l=p)}return H.createElement(Db.Provider,{value:l,children:e})},Ux=({children:e,component:r},s)=>r?H.createElement(r,{params:s}):typeof e=="function"?e(s):e,z1=e=>{let r=H.useRef(Lb);const s=r.current;return r.current=Object.keys(e).length!==Object.keys(s).length||Object.entries(e).some(([i,l])=>l!==s[i])?e:s},Fa=({path:e,nest:r,match:s,...i})=>{const l=Vi(),[u]=oc(l),[h,c,d]=s??Ih(l.parser,e,u,r),p=z1({...I1(),...c});if(!h)return null;const g=d?H.createElement(B1,{base:d},Ux(i,p)):Ux(i,p);return H.createElement(Rb.Provider,{value:p,children:g})},Fn=H.forwardRef((e,r)=>{const s=Vi(),[i,l]=oc(s),{to:u="",href:h=u,onClick:c,asChild:d,children:p,className:g,replace:m,state:b,transition:_,...k}=e,C=jb(v=>{v.ctrlKey||v.metaKey||v.altKey||v.shiftKey||v.button!==0||(c==null||c(v),v.defaultPrevented||(v.preventDefault(),l(h,e)))}),y=s.hrefs(h[0]==="~"?h.slice(1):s.base+h,s);return d&&H.isValidElement(p)?H.cloneElement(p,{onClick:C,href:y}):H.createElement("a",{...k,onClick:C,href:y,className:g!=null&&g.call?g(i===h):g,children:p,ref:r})}),Ob=e=>Array.isArray(e)?e.flatMap(r=>Ob(r&&r.type===H.Fragment?r.props.children:r)):[e],P1=({children:e,location:r})=>{const s=Vi(),[i]=oc(s);for(const l of Ob(e)){let u=0;if(H.isValidElement(l)&&(u=Ih(s.parser,l.props.path,r||i,l.props.nest))[0])return H.cloneElement(l,{match:u})}return null};function H1(e){return typeof e=="object"&&e!==null&&"type"in e&&"payload"in e}function Mb(){if(typeof crypto<"u"&&crypto.randomUUID)try{return crypto.randomUUID()}catch{}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){const r=Math.random()*16|0;return(e==="x"?r:r&3|8).toString(16)})}class F1{constructor(r){hr(this,"ws",null);hr(this,"handlers",new Set);hr(this,"statusHandler",null);hr(this,"baseUrl");hr(this,"isReconnecting",!1);hr(this,"connectingPromise",null);hr(this,"lastCloseCode",0);hr(this,"reconnectAttempts",0);hr(this,"manualReconnectScheduled",!1);this.baseUrl=r}getUrl(){const r=localStorage.getItem("openfox_token");if(r){const s=this.baseUrl.includes("?")?"&":"?";return`${this.baseUrl}${s}token=${encodeURIComponent(r)}`}return this.baseUrl}setToken(r){localStorage.setItem("openfox_token",r)}clearToken(){localStorage.removeItem("openfox_token")}hasToken(){return!!localStorage.getItem("openfox_token")}getLastCloseCode(){return this.lastCloseCode}onStatusChange(r){this.statusHandler=r}connect(){var r,s;return((r=this.ws)==null?void 0:r.readyState)===WebSocket.OPEN?Promise.resolve():(this.lastCloseCode=0,this.isReconnecting=!1,this.connectingPromise&&((s=this.ws)==null?void 0:s.readyState)===WebSocket.CONNECTING?this.connectingPromise:(this.connectingPromise=new Promise((i,l)=>{try{const u=this.getUrl();this.ws=new WebSocket(u);const h=setTimeout(()=>{var c;((c=this.ws)==null?void 0:c.readyState)===WebSocket.CONNECTING&&(this.ws.close(),l(new Error("Connection timeout")))},5e3);this.ws.onopen=()=>{var c;clearTimeout(h),this.isReconnecting=!1,this.connectingPromise=null,(c=this.statusHandler)==null||c.call(this,"connected"),i()},this.ws.onclose=c=>{var d,p,g;clearTimeout(h),this.lastCloseCode=c.code,((d=this.ws)==null?void 0:d.readyState)===WebSocket.CONNECTING?(this.connectingPromise=null,(p=this.statusHandler)==null||p.call(this,"disconnected"),l(new Error(`Connection closed: ${c.code}`))):(this.connectingPromise=null,(g=this.statusHandler)==null||g.call(this,"disconnected"),this.attemptReconnect())},this.ws.onerror=c=>{clearTimeout(h),console.error("WebSocket error:",c),this.connectingPromise=null,l(c)},this.ws.onmessage=c=>{try{const d=JSON.parse(c.data);H1(d)&&this.handlers.forEach(p=>p(d))}catch(d){console.error("Failed to parse WebSocket message:",d)}}}catch(u){this.connectingPromise=null,l(u)}}),this.connectingPromise))}attemptReconnect(){var l;if(([1e3,1005,1006,4e3].includes(this.lastCloseCode)||this.lastCloseCode===0)&&this.hasToken()){console.log("[WS] Auth failure or initial failure with token - not auto-reconnecting, awaiting user action");return}if(this.isReconnecting||this.manualReconnectScheduled)return;this.isReconnecting=!0,(l=this.statusHandler)==null||l.call(this,"reconnecting");const i=Math.min(1e3*Math.pow(2,this.reconnectAttempts||0),3e4);this.reconnectAttempts=(this.reconnectAttempts||0)+1,setTimeout(()=>{this.isReconnecting=!1,this.manualReconnectScheduled=!1,this.connect().catch(()=>{})},i)}reconnect(){this.manualReconnectScheduled=!0,this.isReconnecting=!1,this.lastCloseCode=0,this.connectingPromise=null,this.connect().catch(()=>{})}disconnect(){this.isReconnecting=!1,this.reconnectAttempts=0,this.ws&&(this.ws.close(),this.ws=null)}resetReconnectAttempts(){this.reconnectAttempts=0}send(r,s){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket not connected");const i=Mb(),l={id:i,type:r,payload:s};return this.ws.send(JSON.stringify(l)),i}subscribe(r){return this.handlers.add(r),()=>this.handlers.delete(r)}get isConnected(){var r;return((r=this.ws)==null?void 0:r.readyState)===WebSocket.OPEN}}const U1=`ws://${window.location.hostname}:${window.location.port||"10469"}/ws`,Gt=new F1(U1),xs=async(e,r,s)=>{try{const i=await ke(r,{method:e,headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return i.ok?{success:!0}:{success:!1,error:(await i.json()).error}}catch{return{success:!1,error:"Network error"}}};function Ib(e){let r=null;function s(){r===null&&(r=requestAnimationFrame(()=>{r=null,e()}))}return s}let Il=[];const mr=$n()((e,r)=>{function s(){if(Il.length===0)return;const l=Il;Il=[],e(u=>({logs:[...u.logs,...l]}))}const i=Ib(s);return{workdir:null,status:null,logs:[],config:null,loading:!1,setWorkdir:l=>{r().workdir!==l&&(e({workdir:l,status:null,logs:[],config:null,loading:!0}),l&&(r().fetchStatus(),r().fetchConfig()))},fetchStatus:async()=>{const l=r().workdir;if(l)try{const h=await(await ke(`/api/dev-server?workdir=${encodeURIComponent(l)}`)).json();e({status:h,loading:!1})}catch{e({loading:!1})}},fetchConfig:async()=>{const l=r().workdir;if(l)try{const h=await(await ke(`/api/dev-server/config?workdir=${encodeURIComponent(l)}`)).json();e({config:h.config??null})}catch{}},fetchLogs:async()=>{const l=r().workdir;if(l)try{const c=(await(await ke(`/api/dev-server/logs?workdir=${encodeURIComponent(l)}`)).json()).logs.map(d=>({stream:d.stream,content:d.content}));e({logs:c})}catch{}},start:async()=>{const l=r().workdir;if(l)try{const h=await(await ke(`/api/dev-server/start?workdir=${encodeURIComponent(l)}`,{method:"POST"})).json();e({status:h,logs:[]})}catch{}},stop:async()=>{const l=r().workdir;if(l)try{const h=await(await ke(`/api/dev-server/stop?workdir=${encodeURIComponent(l)}`,{method:"POST"})).json();e({status:h})}catch{}},restart:async()=>{const l=r().workdir;if(l)try{const h=await(await ke(`/api/dev-server/restart?workdir=${encodeURIComponent(l)}`,{method:"POST"})).json();e({status:h,logs:[]})}catch{}},saveConfig:async l=>{const u=r().workdir;if(u)try{const c=await(await ke(`/api/dev-server/config?workdir=${encodeURIComponent(u)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)})).json();e({config:c.config??l}),r().fetchStatus()}catch{}},handleMessage:l=>{const u=r().workdir;if(u)switch(l.type){case"devServer.output":{const h=l.payload;if(h.workdir!==u)return;Il.push({stream:h.stream,content:h.content}),i();break}case"devServer.state":{const h=l.payload;if(h.workdir!==u)return;e(c=>({status:c.status?{...c.status,state:h.state,errorMessage:h.errorMessage}:c.status}));break}}}}});function $1(e){return{...e.temperature!=null&&{temperature:e.temperature},...e.topP!=null&&{topP:e.topP},...e.topK!=null&&{topK:e.topK},...e.maxTokens!=null&&{maxTokens:e.maxTokens}}}async function $x(e,r,s){const i=await ke(`/api/providers/${e}/models/${encodeURIComponent(r)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!i.ok){const l=await i.json();throw new Error(l.error??"Failed to update model")}return i.json()}function qx(e,r,s,i){return e.map(l=>l.id===r?{...l,models:l.models.map(u=>u.id===s?{...u,...i,source:"user"}:u)}:l)}const q1=3e4;function W1(e){switch(e){case"vllm":return"vLLM";case"sglang":return"SGLang";case"ollama":return"Ollama";case"llamacpp":return"llama.cpp";case"openai":return"OpenAI";case"anthropic":return"Anthropic";case"opencode-go":return"OpenCode Go";case"auto":return"Auto";case"unknown":return""}}const Lt=$n((e,r)=>({version:null,model:null,maxContext:2e5,llmUrl:null,llmStatus:"unknown",backend:"unknown",providers:[],activeProviderId:null,defaultModelSelection:null,loading:!1,activating:!1,error:null,autoRefreshInterval:null,fetchConfig:async()=>{e({loading:!0,error:null});try{const s=await ke("/api/config");if(!s.ok)throw new Error("Failed to fetch config");const i=await s.json();e({version:i.version,model:i.model,maxContext:i.maxContext,llmUrl:i.llmUrl,llmStatus:i.llmStatus,backend:i.backend,providers:i.providers??[],activeProviderId:i.activeProviderId??null,defaultModelSelection:i.defaultModelSelection??null,loading:!1})}catch(s){e({error:s instanceof Error?s.message:"Unknown error",loading:!1})}},refreshModel:async()=>{try{const s=await ke("/api/model/refresh",{method:"POST"});if(!s.ok)throw new Error("Failed to refresh model");const i=await s.json(),u=Ce.getState().currentSession;if(u!=null&&u.providerId&&u.providerModel){e({llmStatus:i.llmStatus,backend:i.backend});return}e({model:i.model,llmStatus:i.llmStatus,backend:i.backend})}catch(s){console.error("Failed to refresh model:",s)}},activateProvider:async s=>{const{activeProviderId:i,providers:l}=r();if(s===i)return!0;e({activating:!0,error:null});try{const u=await ke(`/api/providers/${s}/activate`,{method:"POST"});if(!u.ok){const c=await u.json();throw new Error(c.error??"Failed to activate provider")}const h=await u.json();return e({activeProviderId:h.activeProviderId,model:h.model,backend:h.backend,providers:l.map(c=>({...c,isActive:c.id===h.activeProviderId})),activating:!1}),!0}catch(u){return e({error:u instanceof Error?u.message:"Failed to switch provider",activating:!1}),!1}},syncFromSession:(s,i)=>{const{providers:l}=r();e({activeProviderId:s,model:i,defaultModelSelection:`${s}/${i}`,providers:l.map(u=>({...u,isActive:u.id===s}))})},updateModelContext:async(s,i,l)=>{e({activating:!0,error:null});try{const u=await $x(s,i,{contextWindow:l}),{providers:h}=r();return e({providers:qx(h,s,i,{contextWindow:l}),activating:!1}),u.contextState&&Ce.getState().updateContextState(u.contextState),!0}catch(u){return e({error:u instanceof Error?u.message:"Failed to update model context",activating:!1}),!1}},updateModelSettings:async(s,i,l)=>{e({activating:!0,error:null});try{const u=await $x(s,i,l),{providers:h}=r(),c={...l.contextWindow!==void 0&&{contextWindow:l.contextWindow},...$1({temperature:l.temperature??void 0,topP:l.topP??void 0,topK:l.topK??void 0,maxTokens:l.maxTokens??void 0}),...l.supportsVision!==void 0&&{supportsVision:l.supportsVision}};return e({providers:qx(h,s,i,c),activating:!1}),u.contextState&&Ce.getState().updateContextState(u.contextState),!0}catch(u){return e({error:u instanceof Error?u.message:"Failed to update model settings",activating:!1}),!1}},refreshProviderModels:async s=>{e({activating:!0,error:null});try{const i=await ke(`/api/providers/${s}/refresh`,{method:"POST"});if(!i.ok){const h=await i.json();throw new Error(h.error??"Failed to refresh models")}const l=await i.json(),{providers:u}=r();return e({providers:u.map(h=>h.id===s?{...h,models:l.models}:h),activating:!1}),!0}catch(i){return e({error:i instanceof Error?i.message:"Failed to refresh models",activating:!1}),!1}},startAutoRefresh:()=>{const{autoRefreshInterval:s,refreshModel:i}=r();if(s)return;const l=setInterval(()=>{i()},q1);e({autoRefreshInterval:l})},stopAutoRefresh:()=>{const{autoRefreshInterval:s}=r();s&&(clearInterval(s),e({autoRefreshInterval:null}))},getActiveProvider:()=>{const{providers:s,activeProviderId:i}=r();return s.find(l=>l.id===i)},getModelContext:s=>{const{providers:i,activeProviderId:l}=r(),u=i.find(c=>c.id===l);if(!u)return 2e5;const h=u.models.find(c=>c.id===s);return(h==null?void 0:h.contextWindow)??2e5}})),Ft=$n((e,r)=>({projects:[],currentProject:null,loading:!1,listProjects:async()=>{e({loading:!0});try{const i=await(await ke("/api/projects")).json();e({projects:i.projects??[],loading:!1})}catch(s){console.error("Failed to load projects:",s),e({loading:!1})}},createProject:async(s,i)=>{try{const l=await ke("/api/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:s,workdir:i})});if(!l.ok)return null;const u=await l.json();return await r().listProjects(),u.project}catch{return null}},loadProject:async s=>{try{const i=await ke(`/api/projects/${s}`);if(!i.ok)return null;const l=await i.json();return e({currentProject:l.project}),r().projects.length===0&&await r().listProjects(),l.project}catch{return null}},updateProject:async(s,i)=>{var l;try{const u=await ke(`/api/projects/${s}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!u.ok)return null;const h=await u.json();return((l=r().currentProject)==null?void 0:l.id)===s&&e({currentProject:h.project}),await r().listProjects(),h.project}catch{return null}},deleteProject:async s=>{var i;try{return(await ke(`/api/projects/${s}`,{method:"DELETE"})).ok?(await r().listProjects(),((i=r().currentProject)==null?void 0:i.id)===s&&e({currentProject:null}),!0):!1}catch{return!1}},clearProject:()=>{e({currentProject:null})}}));let Bl=[];const eo=$n()((e,r)=>{function s(){if(Bl.length===0)return;const l=Bl;Bl=[],e(u=>{const h={...u.logs};for(const c of l){const d=h[c.processId]??[];h[c.processId]=[...d,{offset:d.length,content:c.content,timestamp:Date.now(),stream:c.stream}]}return{logs:h}})}const i=Ib(s);return{processes:[],logs:{},loading:!1,setProcesses:l=>e({processes:l}),addProcess:l=>e(u=>({processes:[...u.processes,l]})),updateProcess:(l,u)=>e(h=>({processes:h.processes.map(c=>c.id===l?{...c,...u}:c)})),removeProcess:l=>e(u=>({processes:u.processes.filter(h=>h.id!==l),logs:Object.fromEntries(Object.entries(u.logs).filter(([h])=>h!==l))})),stopProcess:async(l,u)=>{try{(await ke(`/api/sessions/${u}/background-process/${l}/stop`,{method:"POST"})).ok&&r().removeProcess(l)}catch{}},appendLog:(l,u,h)=>{Bl.push({processId:l,stream:u,content:h}),i()},setLogs:(l,u)=>e(h=>({logs:{...h.logs,[l]:u}})),clearLogs:l=>e(u=>({logs:{...u.logs,[l]:[]}})),handleMessage:(l,u)=>{switch(l){case"backgroundProcess.started":{const{processId:h,name:c,pid:d,status:p}=u;e(g=>({processes:[...g.processes,{id:h,sessionId:"",name:c,command:"",cwd:"",pid:d,status:p,exitCode:null,createdAt:Date.now(),startedAt:Date.now(),endedAt:null}]}));break}case"backgroundProcess.output":{const h=u.processId,c=u.stream,d=u.content;r().appendLog(h,c,d);break}case"backgroundProcess.exited":{const h=u.processId,c=u.exitCode;e(d=>({processes:d.processes.map(p=>p.id===h?{...p,status:"exited",exitCode:c}:p)}));break}case"backgroundProcess.removed":{const h=u.processId;r().removeProcess(h);break}}}}}),V1=[{key:"complete",label:"Task Complete",description:"When an agent finishes its work"},{key:"waiting_for_user",label:"Waiting for Input",description:"When the agent needs your input"},{key:"phase_done",label:"Phase Done",description:"When a build phase completes successfully"},{key:"phase_blocked",label:"Phase Blocked",description:"When a build phase is blocked and needs intervention"},{key:"new_message",label:"New Message",description:"When a new assistant message starts arriving"}],G1=[{url:"/sounds/notification.mp3",label:"Notification"},{url:"/sounds/waiting-for-user.mp3",label:"Waiting for User"},{url:"/sounds/achievement.mp3",label:"Achievement"},{url:"/sounds/intervention.mp3",label:"Intervention"},{url:"/sounds/typing.mp3",label:"Typing"}],Bb={complete:"/sounds/notification.mp3",waiting_for_user:"/sounds/waiting-for-user.mp3",phase_done:"/sounds/achievement.mp3",phase_blocked:"/sounds/intervention.mp3",new_message:"/sounds/typing.mp3"},ms={soundEnabled:!0,browserNotification:!1,customSoundUrl:null},zb={soundEnabled:!1,browserNotification:!1,customSoundUrl:null},ph={soundEnabled:!0,browserNotificationEnabled:!1,events:{complete:{...ms},waiting_for_user:{...ms},phase_done:{...ms},phase_blocked:{...ms},new_message:{...zb}},agentOverrides:{}};function Pb(e,r,s){var u;const i=e.events[r];if(!s)return i;const l=(u=e.agentOverrides[s])==null?void 0:u[r];return l?{soundEnabled:l.soundEnabled??i.soundEnabled,browserNotification:l.browserNotification??i.browserNotification,customSoundUrl:l.customSoundUrl!==void 0?l.customSoundUrl:i.customSoundUrl}:i}const Fs=$n((e,r)=>({settings:ph,loaded:!1,load:()=>{Yt.getState().getSetting(ot.NOTIFICATION_SETTINGS);const i=Yt.subscribe(u=>{const h=u.settings[ot.NOTIFICATION_SETTINGS];if(h!==void 0)try{const c=JSON.parse(h);e({settings:Wx(c),loaded:!0})}catch{e({loaded:!0})}}),l=Yt.getState().settings[ot.NOTIFICATION_SETTINGS];if(l)try{const u=JSON.parse(l);e({settings:Wx(u),loaded:!0})}catch{e({loaded:!0})}return i},update:s=>{e({settings:s}),Fd(s)},updateEvent:(s,i)=>{const l=r().settings,u={...l,events:{...l.events,[s]:{...l.events[s],...i}}};e({settings:u}),Fd(u)},updateAgentOverride:(s,i,l)=>{var d;const u=r().settings,h={...u.agentOverrides};if(l===null){if(h[s]){const p={...h[s]};delete p[i],Object.keys(p).length===0?delete h[s]:h[s]=p}}else h[s]={...h[s],[i]:{...((d=h[s])==null?void 0:d[i])??{},...l}};const c={...u,agentOverrides:h};e({settings:c}),Fd(c)}}));function Fd(e){Yt.getState().setSetting(ot.NOTIFICATION_SETTINGS,JSON.stringify(e))}function Wx(e){var r,s,i,l,u;return{soundEnabled:e.soundEnabled??ph.soundEnabled,browserNotificationEnabled:e.browserNotificationEnabled??ph.browserNotificationEnabled,events:{complete:{...ms,...(r=e.events)==null?void 0:r.complete},waiting_for_user:{...ms,...(s=e.events)==null?void 0:s.waiting_for_user},phase_done:{...ms,...(i=e.events)==null?void 0:i.phase_done},phase_blocked:{...ms,...(l=e.events)==null?void 0:l.phase_blocked},new_message:{...zb,...(u=e.events)==null?void 0:u.new_message}},agentOverrides:e.agentOverrides??{}}}const Vx=new Map;function K1(e){let r=Vx.get(e);return r||(r=new Audio(e),r.volume=.5,Vx.set(e,r)),r}let Hb=typeof Notification<"u"?Notification.permission:"denied";function Y1(){return typeof Notification>"u"?Promise.resolve("denied"):Notification.requestPermission().then(e=>(Hb=e,e))}const X1={complete:"Task Complete",waiting_for_user:"Waiting for Input",phase_done:"Phase Complete",phase_blocked:"Phase Blocked",new_message:"New Message"},Z1={complete:"The agent has finished its work.",waiting_for_user:"The agent needs your input to continue.",phase_done:"The build phase completed successfully.",phase_blocked:"The build phase is blocked and needs intervention.",new_message:"A new assistant message is arriving."};function Q1(e){typeof Notification>"u"||Hb==="granted"&&(document.hasFocus()||new Notification(X1[e],{body:Z1[e],icon:"/fox.svg",tag:`openfox-${e}`}))}function mo(e,r){const{settings:s}=Fs.getState(),i=Pb(s,e,r);if(s.soundEnabled&&i.soundEnabled){const l=i.customSoundUrl??Bb[e],u=K1(l);u.currentTime=0,u.play().catch(()=>{})}s.browserNotificationEnabled&&i.browserNotification&&Q1(e)}const J1=e=>mo("complete",e),ew=e=>mo("phase_done",e),tw=e=>mo("phase_blocked",e),Gx=e=>mo("waiting_for_user",e),nw=e=>mo("new_message",e);let Ua=!1,fr=null;const Ud=new Set,Vt={messageId:null,deltaContent:"",thinkingContent:"",toolOutput:[]};let Ui=null,mn=null;function $d(){Ui===null&&(Ui=requestAnimationFrame(()=>{Ui=null,mn==null||mn()}))}function Is(){Ui!==null&&(cancelAnimationFrame(Ui),Ui=null)}function Ht(e,r){return r!==null&&e.sessionId===r}function rw(e,r,s){return e.id!==void 0||Ht(e,r)||s===!0&&e.sessionId!==void 0}function sw(e,r){return e.includes(r)?e:[...e,r]}function $a(e,r){return e.filter(s=>s!==r)}function iw(e,r){const s=e.find(l=>l.id===r.id),i=s?{...s,projectId:r.projectId,workdir:r.workdir,mode:r.mode,phase:r.phase,isRunning:r.isRunning,messageCount:r.messages.length,criteriaCount:r.criteria.length,criteriaCompleted:r.criteria.filter(l=>l.status.type==="passed").length}:{id:r.id,projectId:r.projectId,workdir:r.workdir,mode:r.mode,phase:r.phase,isRunning:r.isRunning,createdAt:"",updatedAt:"",criteriaCount:r.criteria.length,criteriaCompleted:r.criteria.filter(l=>l.status.type==="passed").length,messageCount:r.messages.length};return s?e.map(l=>l.id===r.id?i:l):[i,...e]}function aw(e,r,s){return e.map(i=>{const l=(s==null?void 0:s.id)===i.id?s:null,u=r.find(h=>h.id===i.id);return{...i,title:i.title??(u==null?void 0:u.title),mode:(l==null?void 0:l.mode)??(u==null?void 0:u.mode)??i.mode,phase:(l==null?void 0:l.phase)??(u==null?void 0:u.phase)??i.phase,isRunning:i.isRunning,messageCount:i.messageCount,recentUserPrompts:i.recentUserPrompts}})}const Kx=new Map;function Qa(e,r){var u;const s=r===((u=e.currentSession)==null?void 0:u.id)?e.currentSession:null,i=e.sessions.find(h=>h.id===r),l=(s==null?void 0:s.mode)??(i==null?void 0:i.mode);return l==="planner"?"planner":l==="builder"?"build":"planner"}function ow(e,r){if(e.type==="chat.done"){const s=e.payload,i=Qa(r,e.sessionId),l=s.agentType??i;s.reason==="complete"&&J1(l),s.reason==="waiting_for_user"&&Gx(l);return}if(e.type==="chat.path_confirmation"){const s=Qa(r,e.sessionId);Gx(s);return}if(e.type==="task.completed"){const s=Qa(r,e.sessionId);ew(s);return}if(e.type==="phase.changed"&&e.sessionId){const s=e.payload,i=Kx.get(e.sessionId)??null;if(Kx.set(e.sessionId,s.phase),i===s.phase)return;const l=Qa(r,e.sessionId);s.phase==="blocked"&&tw(l)}}const Ce=$n((e,r)=>(mn=()=>{const s=Vt;if(!s.messageId)return;const i=s.deltaContent.length>0,l=s.thinkingContent.length>0,u=s.toolOutput.length>0;if(!i&&!l&&!u)return;const h=s.deltaContent,c=s.thinkingContent,d=s.toolOutput;s.deltaContent="",s.thinkingContent="",s.toolOutput=[],e(p=>{var m;const g=p.streamingMessage;if(g&&g.id===s.messageId){let b={...g};if(i&&(b.content=b.content+h),l&&(b.thinkingContent=(b.thinkingContent??"")+c),u){const _=new Set;b.toolCalls=(m=b.toolCalls)==null?void 0:m.map(C=>{const y=d.filter(v=>v.callId===C.id);return y.length===0?C:(_.add(C.id),{...C,streamingOutput:[...C.streamingOutput??[],...y.map(v=>({stream:v.stream,content:v.content,timestamp:Date.now()}))]})});const k=d.filter(C=>!_.has(C.callId));k.length>0&&Vt.toolOutput.push(...k)}return{streamingMessage:b}}if(u){const b=new Set,_=p.messages.map(C=>{var v;if(C.id!==s.messageId)return C;const y=(v=C.toolCalls)==null?void 0:v.map(x=>{const S=d.filter(j=>j.callId===x.id);return S.length===0?x:(b.add(x.id),{...x,streamingOutput:[...x.streamingOutput??[],...S.map(j=>({stream:j.stream,content:j.content,timestamp:Date.now()}))]})});return{...C,toolCalls:y}}),k=d.filter(C=>!b.has(C.callId));return k.length>0&&Vt.toolOutput.push(...k),{messages:_}}return p})},{connectionStatus:"disconnected",showPasswordModal:!1,passwordModalRetry:!1,sessions:[],currentSession:null,unreadSessionIds:[],messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,subAgentContextStates:{},pendingPathConfirmation:null,pendingQuestion:null,visionFallbackByMessage:{},queuedMessages:[],abortInProgress:!1,error:null,sessionsHasMore:!0,sessionsPaginationLoading:!1,pendingSessionCreate:!1,connect:async()=>{if(r().connectionStatus==="connected")return;e({connectionStatus:"reconnecting"});let i=!1;try{i=(await(await ke("/api/auth")).json()).requiresAuth}catch{}if(i&&!Gt.hasToken()){e({showPasswordModal:!0,passwordModalRetry:!1,connectionStatus:"reconnecting"});return}Gt.onStatusChange(l=>{var u;if(e({connectionStatus:l}),l==="connected"){r().listSessions(void 0),Ft.getState().listProjects();const h=(u=r().currentSession)==null?void 0:u.id;h&&r().loadSession(h)}});try{if(await Gt.connect(),!Ua){Ua=!0;const l=r().handleServerMessage;fr=Gt.subscribe(l)}}catch(l){console.error("Failed to connect:",l);const u=Gt.getLastCloseCode();if(!Gt.hasToken()&&(u===1006||u===4e3)){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}fr&&(fr(),fr=null),Ua=!1,e({connectionStatus:"disconnected"})}},reconnect:()=>{Gt.disconnect(),fr&&(fr(),fr=null),Ua=!1,e({connectionStatus:"disconnected"}),r().connect()},disconnect:()=>{Gt.disconnect(),fr&&(fr(),fr=null),Ua=!1,e({connectionStatus:"disconnected",showPasswordModal:!1})},submitPassword:async s=>{try{const i=await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:s})});if(!i.ok){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}const{token:l}=await i.json();Gt.setToken(l),e({showPasswordModal:!1}),r().connect();const{listProjects:u}=Ft.getState(),{fetchConfig:h}=Lt.getState();u(),h(),r().connect()}catch{e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"})}},cancelPassword:()=>{Gt.clearToken(),e({showPasswordModal:!1,connectionStatus:"disconnected"})},createSession:async(s,i)=>{try{e({pendingSessionCreate:!0});const l=await ke("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectId:s,title:i})});if(!l.ok)return e({pendingSessionCreate:!1}),null;const u=await l.json();return Gt.send("session.load",{sessionId:u.session.id}),u.session}catch{return e({pendingSessionCreate:!1}),null}},loadSession:async s=>{try{const i=r().currentSession;!i||i.id!==s?(Is(),e({currentSession:null,unreadSessionIds:$a(r().unreadSessionIds,s),subAgentContextStates:{},messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,pendingPathConfirmation:null,queuedMessages:[],abortInProgress:!1,error:null})):e({unreadSessionIds:$a(r().unreadSessionIds,s)});const l=await ke(`/api/sessions/${s}`);if(!l.ok)return;const u=await l.json();e({currentSession:u.session,messages:u.messages??[],contextState:u.contextState,queuedMessages:u.queueState??[]}),Gt.send("session.load",{sessionId:s});try{const h=await ke(`/api/sessions/${s}/background-processes`);if(h.ok){const c=await h.json();eo.getState().setProcesses(c.processes??[])}}catch{}}catch{}},listSessions:async(s,i=20)=>{try{const l=new URLSearchParams;l.set("limit",String(i)),s&&l.set("projectId",s);const h=await(await ke(`/api/sessions?${l.toString()}`)).json();e({sessions:h.sessions??[],sessionsHasMore:s?h.hasMore??!1:!0})}catch{}},loadMoreSessions:async s=>{const i=r();if(!(i.sessionsPaginationLoading||!i.sessionsHasMore)){e({sessionsPaginationLoading:!0});try{const l=new URLSearchParams;l.set("limit","20"),l.set("offset",String(i.sessions.length)),l.set("projectId",s);const h=await(await ke(`/api/sessions?${l.toString()}`)).json();e(c=>({sessions:[...c.sessions,...h.sessions??[]],sessionsHasMore:h.hasMore??!1,sessionsPaginationLoading:!1}))}catch{e({sessionsPaginationLoading:!1})}}},deleteSession:async s=>{var i;try{return(await ke(`/api/sessions/${s}`,{method:"DELETE"})).ok?(await r().listSessions(),((i=r().currentSession)==null?void 0:i.id)===s&&r().clearSession(),!0):!1}catch{return!1}},deleteAllSessions:async s=>{try{return(await ke(`/api/projects/${s}/sessions`,{method:"DELETE"})).ok?(await r().listSessions(),!0):!1}catch{return!1}},clearSession:()=>{Is(),e(s=>({currentSession:null,messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,unreadSessionIds:s.currentSession?$a(s.unreadSessionIds,s.currentSession.id):s.unreadSessionIds}))},sendMessage:async(s,i,l)=>{var h;const u=(h=r().currentSession)==null?void 0:h.id;if(u){e({streamingMessageId:null});try{const d=await(await ke(`/api/sessions/${u}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:s,attachments:i,messageKind:l==null?void 0:l.messageKind})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(c){console.error("Error sending message:",c)}}},stopGeneration:async()=>{var i;const s=(i=r().currentSession)==null?void 0:i.id;if(s&&!r().abortInProgress){Is(),mn==null||mn(),e({abortInProgress:!0});try{await ke(`/api/sessions/${s}/stop`,{method:"POST"})}catch(l){console.error("Error stopping generation:",l)}}},continueGeneration:async()=>{var i;const s=(i=r().currentSession)==null?void 0:i.id;if(s){e({streamingMessageId:null});try{await ke(`/api/sessions/${s}/continue`,{method:"POST"})}catch(l){console.error("Error continuing generation:",l)}}},launchRunner:(s,i,l)=>{e({streamingMessageId:null});const u={};s!=null&&s.trim()&&(u.content=s),i&&i.length>0&&(u.attachments=i),l&&(u.workflowId=l),Gt.send("runner.launch",u)},switchMode:async s=>{var l;const i=(l=r().currentSession)==null?void 0:l.id;if(i)try{const u=await ke(`/api/sessions/${i}/mode`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:s})});if(!u.ok){console.error("Failed to switch mode:",await u.json());return}const h=await u.json();h.session&&e({currentSession:h.session})}catch(u){console.error("Error switching mode:",u)}},switchDangerLevel:async s=>{var l;const i=(l=r().currentSession)==null?void 0:l.id;if(i)try{const u=await ke(`/api/sessions/${i}/danger-level`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({dangerLevel:s})});if(!u.ok){console.error("Failed to switch danger level:",await u.json());return}const h=await u.json();h.session&&e({currentSession:h.session})}catch(u){console.error("Error switching danger level:",u)}},acceptAndBuild:(s,i,l)=>{e({streamingMessageId:null});const u={};s&&(u.workflowId=s),i!=null&&i.trim()&&(u.content=i),l&&l.length>0&&(u.attachments=l),Gt.send("mode.accept",u)},editCriteria:async s=>{var l;const i=(l=r().currentSession)==null?void 0:l.id;if(i)try{const u=await ke(`/api/sessions/${i}/criteria`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({criteria:s})});u.ok||console.error("Failed to update criteria:",await u.json())}catch(u){console.error("Error updating criteria:",u)}},compactContext:()=>{Gt.send("context.compact",{})},setSessionProvider:async(s,i)=>{var l;try{const u=(l=r().currentSession)==null?void 0:l.id;if(!u)return null;const h=await ke(`/api/sessions/${u}/provider`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerId:s,...i?{model:i}:{}})});if(!h.ok)return null;const c=await h.json();return e({currentSession:c.session,messages:c.messages??[],contextState:c.contextState}),c.session}catch{return null}},updateContextState:s=>{e({contextState:s})},updateSubAgentContextState:(s,i)=>{e(l=>({subAgentContextStates:{...l.subAgentContextStates,[s]:i}}))},clearSubAgentContextState:s=>{e(i=>{const l={...i.subAgentContextStates};return delete l[s],{subAgentContextStates:l}})},confirmPath:async(s,i,l=!1)=>{var h;const u=(h=r().currentSession)==null?void 0:h.id;if(u)try{await ke(`/api/sessions/${u}/confirm-path`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:s,approved:i,alwaysAllow:l})})}catch(c){console.error("Error confirming path:",c)}},answerQuestion:async(s,i)=>{var u;const l=(u=r().currentSession)==null?void 0:u.id;if(l){try{await ke(`/api/sessions/${l}/answer`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:s,answer:i})})}catch(h){console.error("Error answering question:",h)}e({pendingQuestion:null})}},queueAsap:async(s,i,l)=>{var h;const u=(h=r().currentSession)==null?void 0:h.id;if(u)try{const d=await(await ke(`/api/sessions/${u}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:s,attachments:i,messageKind:l})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(c){console.error("Error queueing ASAP message:",c)}},queueCompletion:async(s,i,l)=>{var h;const u=(h=r().currentSession)==null?void 0:h.id;if(u)try{const d=await(await ke(`/api/sessions/${u}/message`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:s,attachments:i,messageKind:l})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(c){console.error("Error queueing completion message:",c)}},cancelQueued:async s=>{var l;const i=(l=r().currentSession)==null?void 0:l.id;if(i)try{const h=await(await ke(`/api/sessions/${i}/queue/${s}`,{method:"DELETE"})).json();h.queueState&&e({queuedMessages:h.queueState})}catch(u){console.error("Error canceling queued message:",u)}},clearError:()=>{e({error:null})},resetPendingSessionCreate:()=>{e({pendingSessionCreate:!1})},handleServerMessage:s=>{var h,c,d,p,g,m,b,_,k,C,y,v,x,S,j,T,N,D,A,z,O,q,G,W;const i=r();ow(s,i);const l=((h=i.currentSession)==null?void 0:h.id)??null,u=()=>{const I=s.sessionId;!I||I===l||e($=>({unreadSessionIds:sw($.unreadSessionIds,I)}))};switch(s.type){case"session.state":{const I=s.payload;if(!rw(s,l,i.pendingSessionCreate))break;Is();const $=I.messages.find(R=>R.isStreaming)??null,B=r().pendingSessionCreate===!0,X=I.pendingConfirmations??[],P=i.pendingPathConfirmation??(X.length>0?X[0]??null:null);if(e({currentSession:I.session,sessions:iw(r().sessions,I.session),unreadSessionIds:$a(r().unreadSessionIds,I.session.id),messages:I.messages,streamingMessageId:($==null?void 0:$.id)??null,streamingMessage:$,currentTodos:[],pendingPathConfirmation:P,error:null,...B?{pendingSessionCreate:I.session.id}:{}}),I.session.providerId&&I.session.providerModel){const R=Lt.getState();R.providers.find(U=>U.id===I.session.providerId)&&R.syncFromSession(I.session.providerId,I.session.providerModel)}break}case"session.list":{const I=s.payload;e($=>({sessions:aw(I.sessions,$.sessions,$.currentSession)}));break}case"session.deleted":{const I=s.payload;e($=>({unreadSessionIds:$a($.unreadSessionIds,I.sessionId)})),r().listSessions();break}case"session.deletedAll":{r().listSessions();break}case"session.running":{const I=s.payload,$=s.sessionId,B=(c=r().currentSession)==null?void 0:c.id,X=$&&$!==B;e(Z=>({sessions:Z.sessions.map(P=>P.id===$?{...P,isRunning:I.isRunning}:P)})),X||e(Z=>({currentSession:Z.currentSession?{...Z.currentSession,isRunning:I.isRunning}:null,...I.isRunning?{}:{abortInProgress:!1,queuedMessages:[]}}));break}case"chat.message":{if(!Ht(s,((d=r().currentSession)==null?void 0:d.id)??null)){u();break}const I=s.payload;e($=>$.messages.some(B=>B.id===I.message.id)?$:{messages:[...$.messages,I.message],streamingMessageId:I.message.isStreaming?I.message.id:$.streamingMessageId,streamingMessage:I.message.isStreaming?I.message:$.streamingMessage});break}case"chat.message_updated":{if(!Ht(s,((p=r().currentSession)==null?void 0:p.id)??null)){u();break}const I=s.payload,$=I.updates.isStreaming===!1&&r().streamingMessageId===I.messageId;$&&(Is(),mn==null||mn()),e(B=>{const X=B.streamingMessage,Z=$;if(X&&X.id===I.messageId){const P={...X,...I.updates};return{messages:B.messages.map(R=>R.id===I.messageId?P:R),streamingMessageId:Z?null:B.streamingMessageId,streamingMessage:Z?null:{...X,...I.updates}}}return{messages:B.messages.map(P=>P.id===I.messageId?{...P,...I.updates}:P),streamingMessageId:Z?null:B.streamingMessageId}});break}case"chat.delta":{if(!Ht(s,((g=r().currentSession)==null?void 0:g.id)??null)){u();break}const I=s.payload;if(!Ud.has(I.messageId)){Ud.add(I.messageId);const $=Qa(r(),s.sessionId);nw($)}Vt.messageId=I.messageId,Vt.deltaContent+=I.content,$d();break}case"chat.thinking":{if(!Ht(s,((m=r().currentSession)==null?void 0:m.id)??null)){u();break}const I=s.payload;Vt.messageId=I.messageId,Vt.thinkingContent+=I.content,$d();break}case"chat.tool_preparing":{if(!Ht(s,((b=r().currentSession)==null?void 0:b.id)??null)){u();break}const I=s.payload;e($=>{const B=$.streamingMessage;return B&&B.id===I.messageId?{streamingMessage:{...B,preparingToolCalls:[...B.preparingToolCalls??[],{index:I.index,name:I.name}]}}:{messages:$.messages.map(X=>X.id===I.messageId?{...X,preparingToolCalls:[...X.preparingToolCalls??[],{index:I.index,name:I.name}]}:X)}});break}case"chat.tool_call":{if(!Ht(s,((_=r().currentSession)==null?void 0:_.id)??null)){u();break}const I=s.payload,$=B=>{var P;const X=(P=B.preparingToolCalls)==null?void 0:P.filter((R,L)=>{var U;return R.name===I.tool?(U=B.preparingToolCalls)==null?void 0:U.slice(0,L).some(ne=>ne.name===I.tool):!0}),Z=Vt.toolOutput.filter(R=>R.callId===I.callId);return Z.length>0&&(Vt.toolOutput=Vt.toolOutput.filter(R=>R.callId!==I.callId)),{...B,toolCalls:[...B.toolCalls??[],{id:I.callId,name:I.tool,arguments:I.args,startedAt:Date.now(),...Z.length>0?{streamingOutput:Z.map(R=>({stream:R.stream,content:R.content,timestamp:Date.now()}))}:{}}],...X&&X.length>0?{preparingToolCalls:X}:{preparingToolCalls:void 0}}};e(B=>{const X=B.streamingMessage;return X&&X.id===I.messageId?{streamingMessage:$(X)}:{messages:B.messages.map(Z=>Z.id===I.messageId?$(Z):Z)}});break}case"chat.tool_output":{if(!Ht(s,((k=r().currentSession)==null?void 0:k.id)??null)){u();break}const I=s.payload;Vt.messageId=I.messageId,Vt.toolOutput.push({messageId:I.messageId,callId:I.callId,stream:I.stream,content:I.output}),$d();break}case"chat.tool_result":{if(!Ht(s,((C=r().currentSession)==null?void 0:C.id)??null)){u();break}const I=s.payload,$=B=>{var Z;const X=(Z=B.toolCalls)==null?void 0:Z.map(P=>P.id===I.callId?{...P,result:I.result}:P);return{...B,toolCalls:X}};e(B=>{const X=B.streamingMessage;return X&&X.id===I.messageId?{streamingMessage:$(X)}:{messages:B.messages.map(Z=>Z.id===I.messageId?$(Z):Z)}});break}case"chat.vision_fallback":{if(!Ht(s,((y=r().currentSession)==null?void 0:y.id)??null)){u();break}const I=s.payload;e($=>{const B=`${I.messageId}-${I.attachmentId}`,X={...$.visionFallbackByMessage};return X[B]={type:I.type,attachmentId:I.attachmentId,filename:I.filename,description:I.description},{visionFallbackByMessage:X}});break}case"chat.todo":{if(!Ht(s,((v=r().currentSession)==null?void 0:v.id)??null)){u();break}const I=s.payload;e({currentTodos:I.todos});break}case"chat.summary":{if(!Ht(s,((x=r().currentSession)==null?void 0:x.id)??null)){u();break}const I=s.payload;e($=>({currentSession:$.currentSession?{...$.currentSession,summary:I.summary}:null}));break}case"chat.progress":{if(!Ht(s,((S=r().currentSession)==null?void 0:S.id)??null)){u();break}const I=s.payload;console.log("Progress:",I.message,I.phase);break}case"chat.format_retry":{if(!Ht(s,((j=r().currentSession)==null?void 0:j.id)??null)){u();break}const I=s.payload;console.log("Format retry:",I.attempt,"/",I.maxAttempts);break}case"chat.done":{if(!Ht(s,((T=r().currentSession)==null?void 0:T.id)??null)){u();break}Is(),mn==null||mn();const I=s.payload,$=I.stats;Vt.messageId=null,Vt.deltaContent="",Vt.thinkingContent="",Vt.toolOutput=[],Ud.delete(I.messageId),e(B=>{const X=B.streamingMessage,Z=X&&X.id===I.messageId?{...X,isStreaming:!1,stats:$??X.stats}:null;return{messages:B.messages.map(P=>P.id===I.messageId?Z??{...P,isStreaming:!1,stats:$??P.stats}:P),streamingMessageId:null,streamingMessage:null,visionFallbackByMessage:{}}});break}case"chat.error":{if(!Ht(s,((N=r().currentSession)==null?void 0:N.id)??null)){u();break}Is(),mn==null||mn();const I=s.payload;console.error("Chat error:",I.error,"recoverable:",I.recoverable),I.recoverable||(Vt.messageId=null,Vt.deltaContent="",Vt.thinkingContent="",Vt.toolOutput=[]),e($=>({error:{code:"CHAT_ERROR",message:I.error},streamingMessageId:I.recoverable?$.streamingMessageId:null,...I.recoverable?{}:{messages:$.streamingMessage?$.messages.map(B=>B.id===$.streamingMessage.id?$.streamingMessage:B):$.messages,streamingMessage:null}}));break}case"chat.path_confirmation":{if(!Ht(s,((D=r().currentSession)==null?void 0:D.id)??null)){u();break}const I=s.payload;e({pendingPathConfirmation:{callId:I.callId,tool:I.tool,paths:I.paths,workdir:I.workdir,reason:I.reason}});break}case"chat.ask_user":{if(!Ht(s,((A=r().currentSession)==null?void 0:A.id)??null)){u();return}const I=s.payload;e({pendingQuestion:{callId:I.callId,question:I.question}});break}case"mode.changed":{if(!Ht(s,((z=r().currentSession)==null?void 0:z.id)??null)){u();break}const I=s.payload;e($=>({currentSession:$.currentSession?{...$.currentSession,mode:I.mode}:null}));break}case"phase.changed":{const I=s.payload,$=s.sessionId,B=(O=r().currentSession)==null?void 0:O.id,X=$&&$!==B;e(Z=>({sessions:Z.sessions.map(P=>P.id===$?{...P,phase:I.phase}:P)})),X||e(Z=>({currentSession:Z.currentSession?{...Z.currentSession,phase:I.phase}:null}));break}case"criteria.updated":{if(!Ht(s,((q=r().currentSession)==null?void 0:q.id)??null)){u();break}const I=s.payload;e($=>({currentSession:$.currentSession?{...$.currentSession,criteria:I.criteria}:null}));break}case"context.state":{const I=s.payload,$=Ht(s,((G=r().currentSession)==null?void 0:G.id)??null);I.subAgentId?$&&r().updateSubAgentContextState(I.subAgentId,I.context):$?e({contextState:I.context}):u();break}case"session.name_generated":{const I=s.payload,$=s.sessionId,B=(W=r().currentSession)==null?void 0:W.id;e(X=>{const Z=X.sessions.map(R=>R.id===$?{...R,title:I.name,updatedAt:new Date().toISOString()}:R),P=B===$?X.currentSession?{...X.currentSession,title:I.name,updatedAt:new Date().toISOString()}:null:X.currentSession;return{sessions:Z,currentSession:P}});break}case"queue.state":{const I=s.payload;e({queuedMessages:I.messages});break}case"devServer.output":case"devServer.state":{mr.getState().handleMessage(s);break}case"backgroundProcess.started":case"backgroundProcess.output":case"backgroundProcess.exited":case"backgroundProcess.removed":{eo.getState().handleMessage(s.type,s.payload);break}case"error":{const I=s.payload;console.error("Server error:",I),e({error:{code:I.code,message:I.message},streamingMessageId:null});break}}}}));function Fb(){return Ce(e=>{var r;return((r=e.currentSession)==null?void 0:r.isRunning)??!1})}function lw(){return Ce(e=>e.queuedMessages)}function cw(){return Ce(e=>e.abortInProgress)}function uw(){const e=Ce(i=>i.connect),r=Ce(i=>i.connectionStatus),s=Fs(i=>i.load);return H.useEffect(()=>{e()},[e]),H.useEffect(()=>{r==="connected"&&s()},[r,s]),{connectionStatus:r}}const dw="modulepreload",hw=function(e){return"/"+e},Yx={},mh=function(r,s,i){let l=Promise.resolve();if(s&&s.length>0){let h=function(p){return Promise.all(p.map(g=>Promise.resolve(g).then(m=>({status:"fulfilled",value:m}),m=>({status:"rejected",reason:m}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),d=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));l=h(s.map(p=>{if(p=hw(p),p in Yx)return;Yx[p]=!0;const g=p.endsWith(".css"),m=g?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${m}`))return;const b=document.createElement("link");if(b.rel=g?"stylesheet":dw,g||(b.as="script"),b.crossOrigin="",b.href=p,d&&b.setAttribute("nonce",d),document.head.appendChild(b),g)return new Promise((_,k)=>{b.addEventListener("load",_),b.addEventListener("error",()=>k(new Error(`Unable to preload CSS for ${p}`)))})}))}function u(h){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=h,window.dispatchEvent(c),!c.defaultPrevented)throw h}return l.then(h=>{for(const c of h||[])c.status==="rejected"&&u(c.reason);return r().catch(u)})},Ub=[{key:"color-bg-primary",category:"background",label:"Primary Background",defaultValue:"13 17 23"},{key:"color-bg-secondary",category:"background",label:"Secondary Background",defaultValue:"22 27 34"},{key:"color-bg-tertiary",category:"background",label:"Tertiary Background",defaultValue:"33 38 45"},{key:"color-primary",category:"surface",label:"Primary Surface",defaultValue:"10 10 10"},{key:"color-secondary",category:"surface",label:"Secondary Surface",defaultValue:"20 20 20"},{key:"color-text-primary",category:"text",label:"Primary Text",defaultValue:"139 148 158"},{key:"color-text-secondary",category:"text",label:"Secondary Text",defaultValue:"139 148 158"},{key:"color-text-muted",category:"text",label:"Muted Text",defaultValue:"72 79 88"},{key:"color-accent-primary",category:"accent",label:"Primary Accent",defaultValue:"88 166 255"},{key:"color-accent-success",category:"accent",label:"Success Accent",defaultValue:"63 185 80"},{key:"color-accent-warning",category:"accent",label:"Warning Accent",defaultValue:"210 153 34"},{key:"color-accent-error",category:"accent",label:"Error Accent",defaultValue:"248 81 73"},{key:"color-border",category:"border",label:"Border",defaultValue:"48 53 60"}],gr=[{id:"dark",name:"Dark",tokens:{"color-bg-primary":"13 17 23","color-bg-secondary":"22 27 34","color-bg-tertiary":"33 38 45","color-primary":"10 10 10","color-secondary":"20 20 20","color-text-primary":"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 Xx(){try{const e=localStorage.getItem("openfox:userPresets");if(e)return JSON.parse(e)}catch{}return[]}const dn=$n((e,r)=>({currentPreset:"dark",basePreset:"",customTokens:{},isCustom:!1,isCustomizing:!1,userPresets:Xx(),applySavedTheme:()=>{const{getSavedTheme:s,applyPreset:i,applyTokens:l}=r(),u=s();if(u)try{const h=JSON.parse(u);h.preset&&h.tokens?(i(h.preset),e({basePreset:h.preset}),l(h.tokens)):h.preset?i(h.preset):h.tokens&&l(h.tokens)}catch{i("dark")}else i("dark")},applyPreset:s=>{gr.find(l=>l.id===s)&&(e({currentPreset:s,basePreset:"",customTokens:{},isCustom:!1,isCustomizing:!1}),r().applyTheme())},startCustomizing:()=>{var l;const{currentPreset:s}=r(),i=((l=gr.find(u=>u.id===s))==null?void 0:l.tokens)??{};e({basePreset:s,customTokens:{...i},isCustom:!0,isCustomizing:!0})},setCustomToken:(s,i)=>{e(l=>({customTokens:{...l.customTokens,[s]:i}})),r().applyTheme()},cancelCustomizing:()=>{r().applyPreset(r().basePreset||r().currentPreset)},saveCustomTheme:()=>{const{customTokens:s}=r();r().saveTheme(JSON.stringify({tokens:s})),e({isCustomizing:!1})},applyTokens:s=>{e({customTokens:s,isCustom:!0,isCustomizing:!1}),r().applyTheme()},getActiveTheme:()=>{var h,c;const{basePreset:s,customTokens:i,isCustom:l}=r();if(l&&s)return{...((h=gr.find(p=>p.id===s))==null?void 0:h.tokens)??{},...i};if(l)return{...Ub.reduce((d,p)=>({...d,[p.key]:p.defaultValue}),{}),...i};const u=gr.find(d=>d.id===r().currentPreset);return(u==null?void 0:u.tokens)??((c=gr[0])==null?void 0:c.tokens)??{}},applyTheme:()=>{if(typeof document>"u")return;const s=r().getActiveTheme(),i=document.documentElement;Object.entries(s).forEach(([l,u])=>{i.style.setProperty(`--${l}`,u)})},getSavedTheme:()=>{try{const s=localStorage.getItem("openfox:theme");if(s){const i=JSON.parse(s);if(i.preset)return JSON.stringify({preset:i.preset});if(i.tokens)return JSON.stringify({tokens:i.tokens})}}catch{return null}return null},saveTheme:s=>{localStorage.setItem("openfox:theme",s),mh(async()=>{const{useSettingsStore:i}=await Promise.resolve().then(()=>Ox);return{useSettingsStore:i}},void 0).then(({useSettingsStore:i})=>{i.getState().setSetting(ot.DISPLAY_THEME,s).catch(()=>{})})},clearCustomTheme:()=>{localStorage.removeItem("openfox:theme"),e({isCustom:!1,isCustomizing:!1,basePreset:""})},reset:()=>{e({currentPreset:"dark",basePreset:"",customTokens:{},isCustom:!1,isCustomizing:!1,userPresets:[]})},addUserPreset:s=>{const{basePreset:i,customTokens:l,currentPreset:u}=r(),h={id:"custom-"+Date.now(),name:s,basePreset:i||u,tokens:{...l}},c=[...r().userPresets,h];e({userPresets:c}),r().saveUserPresets()},applyUserPreset:s=>{const i=r().userPresets[s];i&&(e({currentPreset:i.basePreset,basePreset:i.basePreset,customTokens:{...i.tokens},isCustom:!0,isCustomizing:!1}),r().applyTheme(),r().saveTheme(JSON.stringify({preset:i.basePreset,tokens:i.tokens})))},deleteUserPreset:s=>{const i=r().userPresets.filter((l,u)=>u!==s);e({userPresets:i}),r().saveUserPresets()},loadUserPresets:()=>{e({userPresets:Xx()})},saveUserPresets:()=>{localStorage.setItem("openfox:userPresets",JSON.stringify(r().userPresets)),mh(async()=>{const{useSettingsStore:s}=await Promise.resolve().then(()=>Ox);return{useSettingsStore:s}},void 0).then(({useSettingsStore:s})=>{s.getState().setSetting(ot.DISPLAY_USER_PRESETS,JSON.stringify(r().userPresets)).catch(()=>{})})}}));function fw({className:e="w-5 h-5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 19l-7-7 7-7"})})}function $b({className:e="w-3.5 h-3.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M14 5l7 7m0 0l-7 7m7-7H3"})})}function pw({className:e="w-5 h-5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"})})}function mw({className:e="w-3 h-3 text-text-muted"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"})})}function gw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M9.5 3.25a2.25 2.25 0 1 1 3 2.122V6A2.5 2.5 0 0 1 10 8.5H6a1 1 0 0 0-1 1v1.128a2.251 2.251 0 1 1-1.5 0V5.372a2.25 2.25 0 1 1 1.5 0v1.836A2.493 2.493 0 0 1 6 7h4a1 1 0 0 0 1-1v-.628A2.25 2.25 0 0 1 9.5 3.25Zm-6 0a.75.75 0 1 0 1.5 0 .75.75 0 0 0-1.5 0Zm8.25-.75a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5ZM4.25 12a.75.75 0 1 0 0 1.5.75.75 0 0 0 0-1.5Z"})})}function Ur({className:e="w-3.5 h-3.5 text-text-muted"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})})}function xr({className:e="w-3 h-3 text-text-muted",rotate:r}){return o.jsx("svg",{className:e,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,style:r!==void 0?{transform:`rotate(${r}deg)`}:void 0,children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19 9l-7 7-7-7"})})}function xw({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",strokeWidth:"2"}),o.jsx("path",{d:"M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1",strokeWidth:"2"})]})}function lc({className:e="w-3.5 h-3.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})})}function vw({className:e="w-3 h-3"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"})})}function zh({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,fill:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("circle",{cx:"12",cy:"5",r:"2"}),o.jsx("circle",{cx:"12",cy:"12",r:"2"}),o.jsx("circle",{cx:"12",cy:"19",r:"2"})]})}function cc({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 Xl({className:e="w-5 h-5 text-accent-primary"}){return o.jsx("svg",{className:e,fill:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{d:"M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"})})}function bw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 9V4.5M9 9H4.5M9 9L3.75 3.75M9 15v4.5M9 15H4.5M9 15l-5.25 5.25M15 9h4.5M15 9V4.5M15 9l5.25-5.25M15 15h4.5M15 15v4.5m0-4.5l5.25 5.25"})})}function yw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"})})}function _w({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M8 0a8.2 8.2 0 0 1 .701.031C9.444.095 9.99.645 10.16 1.29l.288 1.107c.018.066.079.158.212.224.231.114.454.243.668.386.123.082.233.09.299.071l1.1-.303c.652-.18 1.37.008 1.755.653a8.043 8.043 0 0 1 .683 1.18c.227.568.096 1.26-.378 1.726l-.812.804a.312.312 0 0 0-.081.283c.024.166.04.335.04.507s-.016.341-.04.507a.312.312 0 0 0 .08.283l.813.804c.474.466.605 1.158.378 1.726a8.07 8.07 0 0 1-.683 1.18c-.385.645-1.103.833-1.755.653l-1.1-.303c-.066-.019-.176-.011-.299.071a5.1 5.1 0 0 1-.668.386c-.133.066-.194.158-.211.224l-.29 1.107c-.168.645-.714 1.196-1.458 1.26a8.094 8.094 0 0 1-1.402 0c-.744-.064-1.29-.615-1.458-1.26l-.29-1.107a.426.426 0 0 0-.211-.224 5.11 5.11 0 0 1-.668-.386c-.123-.082-.233-.09-.299-.071l-1.1.303c-.652.18-1.37-.008-1.755-.653a8.044 8.044 0 0 1-.683-1.18c-.227-.568-.096-1.26.378-1.726l.812-.804a.312.312 0 0 0 .081-.283A5.18 5.18 0 0 1 2.3 8c0-.172.016-.341.04-.507a.312.312 0 0 0-.08-.283l-.813-.804C.973 5.94.842 5.248 1.069 4.68c.181-.452.395-.882.683-1.18.385-.645 1.103-.833 1.755-.653l1.1.303c.066.019.176.011.299-.071.214-.143.437-.272.668-.386a.426.426 0 0 0 .211-.224l.29-1.107C6.009.645 6.556.095 7.299.03 7.53.01 7.764 0 8 0Zm0 5.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5Z"})})}function Sw({className:e="w-3 h-3"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}function ww({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"})})}function Zx({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 6h16M4 12h16M4 18h16"})})}function qb({className:e="w-[18px] h-[18px]"}){return o.jsxs("svg",{className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[o.jsx("circle",{cx:"12",cy:"5",r:"1.5",fill:"currentColor",stroke:"none"}),o.jsx("circle",{cx:"12",cy:"12",r:"1.5",fill:"currentColor",stroke:"none"}),o.jsx("circle",{cx:"12",cy:"19",r:"1.5",fill:"currentColor",stroke:"none"})]})}function Cw({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("path",{d:"M6.5 3.5H3a1 1 0 0 0-1 1V13a1 1 0 0 0 1 1h8.5a1 1 0 0 0 1-1V9.5"}),o.jsx("path",{d:"M9.5 2h4.5v4.5"}),o.jsx("path",{d:"M14 2L7.5 8.5"})]})}function kw({className:e="w-3 h-3",color:r}){return o.jsx("svg",{className:e,fill:r??"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{d:"M8 5v14l11-7z"})})}function Wb({className:e="w-3 h-3 text-accent-primary"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})})}function Vb({className:e="",size:r="md"}){const s=r==="sm"?"w-4 h-4":"w-6 h-6";return o.jsxs("svg",{className:`animate-spin ${s} ${e}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),o.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]})}const Gb=Vb,Kb=Vb;function Ew({className:e="w-5 h-5"}){return o.jsx("svg",{className:e,viewBox:"0 0 20 20",fill:"currentColor",children:o.jsx("path",{fillRule:"evenodd",d:"M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z",clipRule:"evenodd"})})}function jw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})})}function Nw({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]})}function Tw({className:e="w-3 h-3 text-blue-400 animate-spin flex-shrink-0"}){return o.jsxs("svg",{"aria-label":"Session running",className:e,viewBox:"0 0 24 24",fill:"none",children:[o.jsx("title",{children:"Running"}),o.jsx("circle",{className:"opacity-30",cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"3"}),o.jsx("path",{d:"M21 12a9 9 0 00-9-9",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round"})]})}function Aw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("rect",{x:"3",y:"3",width:"10",height:"10",rx:"1"})})}function Dw({className:e="w-3.5 h-3.5 shrink-0",color:r}){return o.jsx("svg",{className:e,fill:"none",stroke:r,viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})})}function Lw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 20 20",fill:"currentColor",children:o.jsx("path",{fillRule:"evenodd",d:"M2 5a2 2 0 012-2h12a2 2 0 012 2v10a2 2 0 01-2 2H4a2 2 0 01-2-2V5zm3 1h10v1H5V6zm10 7H5v1h10v-1zm-10 2H5v1h10v-1z",clipRule:"evenodd"})})}function Yb({className:e="w-3.5 h-3.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})})}function Xb(){return o.jsx("svg",{className:"w-3.5 h-3.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})})}function Rw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}function Zb({className:e="w-2.5 h-2.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})})}function Ph({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 20 20",fill:"currentColor",children:o.jsx("path",{fillRule:"evenodd",d:"M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z",clipRule:"evenodd"})})}function Ow({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,viewBox:"0 0 16 16",fill:"currentColor",children:o.jsx("path",{d:"M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.55.55 0 0 1 0-.708z"})})}function gh(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const r=Math.random()*16|0;return(e==="x"?r:r&3|8).toString(16)})}function Qx(e,r){const s=Gt.ws;!s||s.readyState!==WebSocket.OPEN||s.send(JSON.stringify({id:gh(),type:e,payload:r}))}const ir=$n((e,r)=>({isOpen:!1,sessions:[],workdir:null,setOpen:s=>e({isOpen:s}),toggleOpen:()=>e(s=>({isOpen:!s.isOpen})),setWorkdir:s=>e({workdir:s}),fetchSessions:async s=>{if(!s){e({sessions:[]});return}try{const i=await ke(`/api/terminals?projectId=${encodeURIComponent(s)}`);if(i.ok){const l=await i.json();e({sessions:l});const u=Gt.ws;if(u&&u.readyState===WebSocket.OPEN)for(const h of l)u.send(JSON.stringify({id:gh(),type:"terminal.subscribe",payload:{sessionId:h.id}}))}}catch(i){console.error("Failed to fetch terminals:",i)}},createSession:async(s,i)=>{try{const l=await ke("/api/terminals",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workdir:s??r().workdir??void 0,projectId:i})});if(l.ok){const u=await l.json();e(c=>({sessions:[...c.sessions,u]}));const h=Gt.ws;h&&h.readyState===WebSocket.OPEN&&h.send(JSON.stringify({id:gh(),type:"terminal.subscribe",payload:{sessionId:u.id}}))}}catch(l){console.error("Failed to create terminal:",l)}},writeSession:(s,i)=>{Qx("terminal.write",{sessionId:s,data:i})},resizeSession:(s,i,l)=>{Qx("terminal.resize",{sessionId:s,cols:i,rows:l})},killSession:async s=>{try{(await ke(`/api/terminals/${s}`,{method:"DELETE"})).ok&&e(l=>({sessions:l.sessions.filter(u=>u.id!==s)}))}catch(i){console.error("Failed to kill terminal:",i)}},handleMessage:s=>{switch(s.type){case"terminal.exit":{const{sessionId:i}=s.payload||{};i&&e(l=>{const u=l.sessions.filter(h=>h.id!==i);return u.length===0&&l.isOpen?{sessions:[],isOpen:!1}:{sessions:u}});break}}}}));Gt.subscribe(e=>{var r;(r=e.type)!=null&&r.startsWith("terminal.")&&ir.getState().handleMessage(e)});var go=kb();const uc=H.forwardRef(({icon:e,iconSize:r="w-3.5 h-3.5",className:s="",...i},l)=>o.jsx("button",{ref:l,type:"button",className:`p-1 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors ${s}`,...i,children:o.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:e})})}));uc.displayName="IconButton";const Mw="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z",qi=H.forwardRef((e,r)=>o.jsx(uc,{ref:r,icon:Mw,title:"Edit",...e}));qi.displayName="EditButton";const Iw="M6 18L18 6M6 6l12 12",Hh=H.forwardRef((e,r)=>o.jsx(uc,{ref:r,icon:Iw,...e}));Hh.displayName="CloseButton";const Bw={sm:"max-w-sm",md:"max-w-md",lg:"max-w-2xl",xl:"max-w-4xl",full:"max-w-[95vw] h-[90vh] flex-1"};function jt({label:e,title:r,size:s="md",minHeight:i,children:l,footer:u,className:h,onClose:c,isOpen:d,closeOnBackdropClick:p=!0,closeOnEscape:g=!0,showCloseButton:m=!0}){const[b,_]=H.useState(!1),k=d!==void 0,C=k?d:b,y=H.useCallback(()=>{k||_(!0)},[k]),v=H.useCallback(()=>{k||_(!1),c==null||c()},[k,c]);H.useEffect(()=>{if(!C||!g)return;const S=j=>{j.key==="Escape"&&v()};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[C,v,g]);const x=e&&(typeof e=="string"?o.jsx("button",{type:"button",onClick:y,className:h,children:e}):o.jsx("span",{onClick:y,className:h,style:{cursor:"pointer"},children:e}));return o.jsxs(o.Fragment,{children:[x,C&&(typeof document<"u"?go.createPortal(o.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:[o.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:p?v:void 0}),o.jsxs("div",{className:`relative w-full ${Bw[s]} max-h-[90vh] bg-bg-secondary border border-border rounded shadow-xl flex flex-col`,children:[(r||m)&&o.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border",children:[r&&o.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:r}),m&&o.jsx(Hh,{onClick:v,className:"ml-auto","aria-label":"Close"})]}),o.jsx("div",{className:"p-4 overflow-y-auto flex-1 min-h-0",style:i?{minHeight:i}:void 0,children:l}),u&&o.jsx("div",{className:"px-4 py-3 border-t border-border",children:u})]})]}),document.body):null)]})}const st=H.forwardRef(({variant:e="secondary",size:r="md",className:s="",children:i,...l},u)=>{const h="rounded font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed",c={primary:"bg-accent-primary/25 text-text-primary hover:bg-accent-primary/40",secondary:"bg-bg-tertiary text-text-primary hover:bg-border",danger:"bg-accent-error text-white hover:bg-accent-error/80"},d={sm:"px-1.5 py-1 text-xs",md:"px-3 py-1.5 text-sm",lg:"px-4 py-2 text-base"};return o.jsx("button",{ref:u,className:`${h} ${c[e]} ${d[r]} ${s}`,...l,children:i})});st.displayName="Button";function zw({value:e,defaultUrl:r,disabled:s,onChange:i}){const l=e??r;return o.jsxs("div",{className:"relative",children:[o.jsx("select",{value:l,disabled:s,onChange:u=>{const h=u.target.value;i(h===r?null:h)},className:"appearance-none bg-bg-tertiary border border-border rounded px-1.5 pr-5 text-xs focus:outline-none focus:ring-1 focus:ring-accent-primary disabled:opacity-40 cursor-pointer",style:{width:"60px"},children:G1.map(({url:u,label:h})=>o.jsx("option",{value:u,title:h,children:h.split(" ")[0]},u))}),o.jsx(xr,{className:"absolute right-0.5 top-1/2 -translate-y-1/2 w-3 h-3 pointer-events-none text-text-muted"})]})}const Jx=[{key:"general",label:"General"},{key:"build",label:"Agent"},{key:"sub-agent",label:"Sub-agent"}];function Pw(){const e=Fs(d=>d.settings),r=Fs(d=>d.update),s=Fs(d=>d.updateEvent),i=Fs(d=>d.updateAgentOverride),l=Fs(d=>d.load);H.useEffect(()=>{l()},[l]);const u=async()=>{await Y1()==="granted"&&r({...e,browserNotificationEnabled:!0})},h=(d,p,g,m)=>{d==="general"?s(p,{[g]:m}):i(d,p,{[g]:m})},c=(d,p,g)=>{d==="general"?s(p,{customSoundUrl:g}):i(d,p,{customSoundUrl:g})};return o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"space-y-3",children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Master Controls"}),o.jsx(ev,{label:"Sound notifications",description:"Play sounds when events occur",checked:e.soundEnabled,onChange:d=>r({...e,soundEnabled:d})}),o.jsx(ev,{label:"Browser notifications",description:"Show desktop notifications when the window is not focused",checked:e.browserNotificationEnabled,onChange:d=>{d&&typeof Notification<"u"&&Notification.permission!=="granted"?u():r({...e,browserNotificationEnabled:d})}}),typeof Notification<"u"&&Notification.permission==="denied"&&e.browserNotificationEnabled&&o.jsx("p",{className:"text-xs text-accent-error ml-6",children:"Browser notifications are blocked. Please enable them in your browser settings."})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Notification Settings"}),o.jsx("div",{className:"border border-border rounded overflow-hidden",children:o.jsxs("table",{className:"w-full text-sm",children:[o.jsx("thead",{className:"sticky top-0 bg-bg-tertiary",children:o.jsxs("tr",{className:"border-b border-border",children:[o.jsx("th",{className:"text-left px-3 py-2 text-text-primary font-medium w-40",children:"Event"}),Jx.map(d=>o.jsx("th",{className:"text-center px-2 py-2 text-text-primary font-medium",children:d.label},d.key))]})}),o.jsx("tbody",{children:V1.map(d=>o.jsxs("tr",{className:"border-b border-border last:border-b-0 hover:bg-bg-secondary/50",children:[o.jsx("td",{className:"px-3 py-2",children:o.jsx("div",{className:"text-text-primary text-xs",children:d.label})}),Jx.map(p=>{const g=Pb(e,d.key,p.key==="general"?void 0:p.key),m=Bb[d.key];return o.jsx("td",{className:"px-2 py-2 align-top",children:o.jsxs("div",{className:"flex flex-col items-center gap-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("label",{className:"flex items-center gap-1 text-text-secondary",children:o.jsx("input",{type:"checkbox",checked:g.soundEnabled,onChange:b=>h(p.key,d.key,"soundEnabled",b.target.checked),disabled:!e.soundEnabled,className:"rounded border-border",title:"Sound"})}),o.jsx("label",{className:"flex items-center gap-1 text-text-secondary",children:o.jsx("input",{type:"checkbox",checked:g.browserNotification,onChange:b=>h(p.key,d.key,"browserNotification",b.target.checked),disabled:!e.browserNotificationEnabled,className:"rounded border-border",title:"Browser"})})]}),g.soundEnabled&&e.soundEnabled&&o.jsx(zw,{value:g.customSoundUrl,defaultUrl:m,disabled:!e.soundEnabled,onChange:b=>c(p.key,d.key,b)})]})},p.key)})]},d.key))})]})})]})]})}function ev({label:e,description:r,checked:s,onChange:i}){return o.jsxs("label",{className:"flex items-start gap-3 cursor-pointer group",children:[o.jsx("div",{className:"pt-0.5",children:o.jsx("div",{className:`relative w-9 h-5 rounded-full transition-colors ${s?"bg-accent-primary":"bg-bg-tertiary border border-border"}`,onClick:l=>{l.preventDefault(),i(!s)},children:o.jsx("div",{className:`absolute top-0.5 w-4 h-4 rounded-full bg-white shadow transition-transform ${s?"translate-x-4":"translate-x-0.5"}`})})}),o.jsxs("div",{children:[o.jsx("div",{className:"text-sm text-text-primary group-hover:text-accent-primary transition-colors",children:e}),o.jsx("div",{className:"text-xs text-text-muted",children:r})]})]})}async function Fh(e,r){r({loading:!0});try{const i=await(await ke(e)).json();r({defaults:i.defaults??[],userItems:i.userItems??[],loading:!1})}catch{r({loading:!1})}}const Pr=$n((e,r)=>({defaults:[],userItems:[],loading:!1,fetchSkills:async()=>{await Fh("/api/skills",e)},toggleSkill:async s=>{try{const l=await(await ke(`/api/skills/${s}/toggle`,{method:"POST"})).json();e(u=>({defaults:u.defaults.map(h=>h.id===s?{...h,enabled:l.enabled}:h),userItems:u.userItems.map(h=>h.id===s?{...h,enabled:l.enabled}:h)}))}catch{}},fetchSkill:async s=>{try{const i=await ke(`/api/skills/${s}`);return i.ok?await i.json():null}catch{return null}},fetchDefaultContent:async s=>{try{const i=await ke(`/api/skills/defaults/${s}`);return i.ok?await i.json():null}catch{return null}},createSkill:async s=>{const i=await xs("POST","/api/skills",s);return i.success&&await r().fetchSkills(),i},updateSkill:async(s,i)=>{const l=await xs("PUT",`/api/skills/${s}`,i);return l.success&&await r().fetchSkills(),l},deleteSkill:async s=>{try{const i=await ke(`/api/skills/${s}`,{method:"DELETE"}),l=await i.json();return i.ok?(e(u=>({userItems:u.userItems.filter(h=>h.id!==s)})),{success:!0}):{success:!1,error:l.error??"Failed to delete"}}catch{return{success:!1,error:"Network error"}}},duplicateSkill:async s=>{try{const i=await ke(`/api/skills/${s}/duplicate`,{method:"POST"}),l=await i.json();return i.ok?(await r().fetchSkills(),{success:!0}):{success:!1,error:l.error??"Failed to duplicate"}}catch{return{success:!1,error:"Network error"}}}}));function Uh(){const[e,r]=H.useState({id:null,type:null}),s=H.useCallback(u=>r({id:u,type:"delete"}),[]),i=H.useCallback(()=>r({id:null,type:null}),[]),l=H.useCallback((u,h)=>e.id===u&&e.type===h,[e.id,e.type]);return{requestDelete:s,clearConfirm:i,isConfirming:l}}function $h({onConfirm:e,onCancel:r}){return o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("button",{onClick:e,className:"px-1.5 py-0.5 rounded text-xs hover:opacity-90 transition-colors bg-accent-error/20 text-accent-error hover:bg-accent-error/30",children:"Delete"}),o.jsx("button",{onClick:r,className:"px-1.5 py-0.5 rounded text-text-muted text-xs hover:bg-bg-primary transition-colors",children:"Cancel"})]})}function qh({onClick:e}){return o.jsx("button",{onClick:e,className:"p-1.5 rounded hover:bg-bg-primary text-text-muted hover:text-accent-error transition-colors",title:"Delete",children:o.jsx(Yb,{})})}function io({onClick:e}){return o.jsx("button",{onClick:e,className:"p-1.5 rounded hover:bg-bg-primary text-text-muted hover:text-text-primary transition-colors",title:"Duplicate",children:o.jsx(lc,{})})}function Us({label:e,value:r,onChange:s,placeholder:i,readOnly:l,hint:u,mono:h}){return o.jsxs("div",{children:[o.jsxs("label",{className:"block text-xs text-text-secondary mb-1",children:[e,u&&o.jsx("span",{className:"text-text-muted ml-1",children:u})]}),o.jsx("input",{value:r,onChange:c=>s(c.target.value),readOnly:l,placeholder:i,className:`w-full px-2 py-1.5 bg-bg-tertiary border border-border rounded text-sm focus:outline-none focus:ring-1 focus:ring-accent-primary ${h?"font-mono":""} ${l?"opacity-60":""}`})]})}function Hw({onCancel:e,onSave:r,saving:s,saveDisabled:i}){return o.jsxs("div",{className:"flex justify-end gap-2 pt-2 border-t border-border",children:[o.jsx(st,{variant:"secondary",onClick:e,children:"Cancel"}),o.jsx(st,{variant:"primary",onClick:r,disabled:s||i,children:s?"Saving...":"Save"})]})}function Wh({message:e}){return o.jsx("div",{className:"text-accent-error text-sm px-3 py-2 bg-accent-error/10 rounded",children:e})}function Qb({description:e,onNew:r,newLabel:s="+ New"}){return o.jsxs("div",{className:"flex items-center justify-between mb-4",children:[o.jsx("p",{className:"text-text-secondary text-sm",children:e}),o.jsx("div",{className:"flex items-center gap-2 flex-shrink-0 ml-3",children:o.jsx(st,{variant:"primary",size:"sm",onClick:r,children:s})})]})}function Jb({isBuiltIn:e,isConfirmingDelete:r,onView:s,onEdit:i,onDuplicate:l,onDelete:u,children:h}){return o.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[o.jsx("div",{className:"min-w-0 flex-1 mr-3",children:h}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[e&&s&&o.jsx("button",{onClick:s,className:"p-1.5 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors",title:"View",children:o.jsx(cc,{})}),o.jsx(io,{onClick:l}),!e&&i&&o.jsx(qi,{onClick:i}),!e&&(r?o.jsx($h,{onConfirm:()=>{u==null||u()},onCancel:()=>{}}):o.jsx(qh,{onClick:()=>u==null?void 0:u()}))]})]})}function Fw({id:e,name:r,description:s,isBuiltIn:i,isConfirmingDelete:l,onView:u,onEdit:h,onDuplicate:c,onDelete:d}){return o.jsxs(Jb,{isBuiltIn:i,isConfirmingDelete:l,onView:u,onEdit:h,onDuplicate:c,onDelete:d,children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-text-primary text-sm font-medium",children:r}),o.jsx("span",{className:"text-text-muted text-xs font-mono",children:e})]}),s&&o.jsx("p",{className:"text-text-muted text-xs truncate",children:s})]})}function ey({loading:e,hasItems:r,loadingLabel:s,emptyLabel:i,children:l}){return e&&!r?o.jsx("div",{className:"text-text-muted text-sm",children:s}):r?o.jsx("div",{className:"space-y-4",children:l}):i?o.jsx("div",{className:"text-text-muted text-sm",children:i}):null}function ty({name:e,id:r,nameLabel:s="Name",idLabel:i="ID",namePlaceholder:l="My Item",idPlaceholder:u="my-item",nameHint:h,readOnlyId:c=!1,readOnlyHint:d="(read-only)",onNameChange:p,onIdChange:g}){return o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(Us,{label:s,value:e,onChange:p,placeholder:l,hint:h}),o.jsx(Us,{label:i,value:r,onChange:g,readOnly:c,placeholder:u,hint:c?d:void 0,mono:!0})]})}function ny(e={}){const{initialData:r={}}=e,[s,i]=H.useState("list"),[l,u]=H.useState(null),[h,c]=H.useState(""),[d,p]=H.useState(!1),[g,m]=H.useState(r),b=H.useCallback(()=>{m(r),c(""),u(null)},[r]),_=H.useCallback(v=>{i(v),v==="list"&&b()},[b]),k=H.useCallback(v=>{m(x=>typeof v=="function"?v(x):v)},[]),C=H.useCallback((v,x={})=>{u(v),i("edit"),m({...x}),c("")},[]),y=H.useCallback(()=>{u(null),i("edit"),m(r),c("")},[r]);return{view:s,editingId:l,formError:h,saving:d,formData:g,setView:_,setEditingId:u,setFormError:c,setFormData:k,setSaving:p,resetForm:b,startEditing:C,startNew:y}}function Vh(){return o.jsxs("div",{className:"flex items-start gap-2 px-3 py-2 mt-3 bg-accent-warning/10 border border-accent-warning/30 rounded text-xs",children:[o.jsx("span",{children:"⚠️"}),o.jsx("p",{className:"text-text-secondary",children:"Editing this value now will have the side-effect of invalidating KV-cache, causing your next message in current sessions to take a long time to process. Consider doing this between sessions."})]})}function tv({skill:e,isBuiltIn:r,isConfirmingDelete:s,onView:i,onEdit:l,onDuplicate:u,onDelete:h}){return o.jsx(Fw,{id:e.id,name:e.name,description:e.description,isBuiltIn:r,isConfirmingDelete:s,onView:i,onEdit:l,onDuplicate:u,onDelete:h})}function Uw({isOpen:e}){const r=Pr(I=>I.defaults),s=Pr(I=>I.userItems),i=Pr(I=>I.loading),l=Pr(I=>I.fetchSkills),u=Pr(I=>I.fetchSkill),h=Pr(I=>I.fetchDefaultContent),c=Pr(I=>I.createSkill),d=Pr(I=>I.updateSkill),p=Pr(I=>I.deleteSkill),{view:g,editingId:m,formError:b,saving:_,formData:k,setView:C,setEditingId:y,setFormError:v,setFormData:x,setSaving:S}=ny(),{clearConfirm:j}=Uh();H.useEffect(()=>{e&&(l(),C("list"),y(null),j())},[e,l,j]);const T=(I,$,B,X)=>{x({name:X??I.metadata.name,id:B??I.metadata.id,description:I.metadata.description??"",version:I.metadata.version??"1.0.0",prompt:I.prompt,isReadOnly:$})},N=async I=>{if(r.some(B=>B.id===I)){const B=await h(I);if(!B)return;T(B,!0),y(I),v(""),C("edit")}else{const B=await u(I);if(!B)return;T(B,!0),y(I),v(""),C("edit")}},D=async I=>{const B=r.some(Z=>Z.id===I)?await h(I):await u(I);if(!B)return;const X=`${I}-copy-${Date.now()}`;T(B,!1,X,`${B.metadata.name} (copy)`),y(null),v(""),C("edit")},A=()=>{x({name:"",id:"",description:"",version:"1.0.0",prompt:"",isReadOnly:!1}),C("edit")},z=async I=>{const $=await u(I);$&&(T($,!1),y(I),v(""),C("edit"))},O=async I=>{await p(I),j()},q=async()=>{const I=m??k.id;if(!I||!k.name||!k.prompt){v("Name, ID, and prompt are required.");return}S(!0),v("");const $={metadata:{id:I,name:k.name,description:k.description,version:k.version},prompt:k.prompt},B=m?await d(m,$):await c($);if(S(!1),!B.success){v(B.error??"Failed to save skill.");return}C("list")},G=I=>{x($=>({...$,name:I})),m||x($=>({...$,id:I.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}))},W=k.isReadOnly;return g==="edit"?o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:"flex justify-between items-center mb-3",children:[o.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:W?k.name:m?"Edit Skill":"New Skill"}),o.jsx("button",{onClick:()=>C("list"),className:"text-text-muted hover:text-text-primary",children:"Cancel"})]}),b&&o.jsx(Wh,{message:b}),o.jsxs("div",{className:"space-y-3 mb-3",children:[o.jsx(ty,{name:k.name,id:k.id,nameLabel:"Name",idLabel:"ID",namePlaceholder:"My Skill",idPlaceholder:"my-skill",readOnlyId:!0,onNameChange:G,onIdChange:()=>{}}),o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(Us,{label:"Description",value:k.description,onChange:I=>x($=>({...$,description:I})),placeholder:"What this skill does...",readOnly:W}),o.jsx(Us,{label:"Version",value:k.version,onChange:I=>x($=>({...$,version:I})),placeholder:"1.0.0",readOnly:W})]})]}),o.jsxs("div",{className:"flex-1 min-h-[120px] border-t border-border pt-3 flex flex-col",children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Prompt"}),o.jsx("textarea",{value:k.prompt,onChange:I=>x($=>({...$,prompt:I.target.value})),readOnly:W,placeholder:"The system prompt for this skill...",className:"h-80 w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-y focus:outline-none focus:ring-1 focus:ring-accent-primary"})]}),o.jsx(Vh,{}),o.jsxs("div",{className:"flex justify-end gap-2 pt-3 border-t border-border flex-shrink-0",children:[o.jsx(st,{variant:"secondary",onClick:()=>C("list"),children:"Cancel"}),W?o.jsx(st,{variant:"primary",onClick:()=>{x(I=>({...I,name:I.name+" (copy)",id:`${m}-copy-${Date.now()}`,isReadOnly:!1})),y(null)},children:"Duplicate & Customize"}):o.jsx(st,{variant:"primary",onClick:q,disabled:_||!k.name||!k.id||!k.prompt,children:_?"Saving...":"Save"})]})]}):o.jsxs("div",{children:[o.jsx(Qb,{description:"Skills provide domain-specific knowledge that agents can load on demand.",onNew:A}),o.jsxs(ey,{loading:i,hasItems:r.length>0||s.length>0,loadingLabel:"Loading skills...",emptyLabel:"No skills created yet.",children:[r.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Built-in"}),o.jsx("div",{className:"space-y-2",children:r.map(I=>o.jsx(tv,{skill:I,isBuiltIn:!0,isConfirmingDelete:!1,onView:()=>N(I.id),onDuplicate:()=>D(I.id)},I.id))})]}),s.length>0&&o.jsxs("div",{children:[o.jsx("h3",{className:"text-xs font-medium text-text-secondary mb-2 uppercase tracking-wide",children:"Custom"}),o.jsx("div",{className:"space-y-2",children:s.map(I=>o.jsx(tv,{skill:I,isBuiltIn:!1,isConfirmingDelete:!1,onView:()=>N(I.id),onEdit:()=>z(I.id),onDuplicate:()=>D(I.id),onDelete:()=>O(I.id)},I.id))})]})]})]})}function $w(e){const r=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);if(r){const s=parseInt(r[1]??"0",16),i=parseInt(r[2]??"0",16),l=parseInt(r[3]??"0",16);return`${s} ${i} ${l}`}return e}function Hs(e){const r=e.split(" ").map(s=>parseInt(s,10));return r.length===3&&r.every(s=>!isNaN(s))?`#${r.map(s=>(s??0).toString(16).padStart(2,"0")).join("")}`:e}function qw({isOpen:e,isNew:r,basePresetId:s,presetName:i,initialTokens:l,onClose:u,onSave:h}){const[c,d]=H.useState(l),[p,g]=H.useState(i);H.useEffect(()=>{d(l),g(i)},[l,i]);const m=(y,v)=>{const x=v.startsWith("#")?$w(v):v;d(S=>({...S,[y]:x}))},b=()=>{h(p.trim()||"Untitled",{...c})},_=Ub.reduce((y,v)=>{const x=v.category;return y[x]||(y[x]=[]),y[x].push(v),y},{}),k={background:"Backgrounds",surface:"Surfaces",text:"Text",accent:"Accents",border:"Border"},C=gr.find(y=>y.id===s);return o.jsx(jt,{isOpen:e,onClose:u,size:"lg",title:r?"New Theme":"Edit Theme",closeOnBackdropClick:!0,closeOnEscape:!0,footer:o.jsxs("div",{className:"flex gap-2 justify-end",children:[o.jsx("button",{type:"button",onClick:u,className:"px-4 py-2 border border-border rounded text-sm text-text-primary hover:bg-bg-tertiary transition-colors",children:"Cancel"}),o.jsx("button",{type:"button",onClick:b,className:"px-4 py-2 bg-accent-primary text-white rounded hover:bg-accent-primary/80 transition-colors text-sm",children:"Save"})]}),children:o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-muted block mb-1",children:"Name"}),o.jsx("input",{type:"text",value:p,onChange:y=>g(y.target.value),className:"w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-accent-primary"})]}),!r&&o.jsxs("div",{className:"text-xs text-text-muted",children:["Based on ",o.jsx("span",{className:"text-text-primary",children:C==null?void 0:C.name})]}),Object.entries(_).map(([y,v])=>o.jsxs("div",{className:"space-y-3",children:[o.jsx("h4",{className:"text-xs font-medium text-text-muted uppercase",children:k[y]??y}),o.jsx("div",{className:"grid grid-cols-2 gap-3",children:v.map(x=>o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("label",{htmlFor:x.key,className:"text-xs text-text-muted",children:x.label}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"color",id:x.key,value:Hs(c[x.key]??x.defaultValue),onChange:S=>m(x.key,S.target.value),className:"w-8 h-8 rounded cursor-pointer border border-border bg-transparent"}),o.jsx("input",{type:"text",value:c[x.key]??x.defaultValue,onChange:S=>m(x.key,S.target.value),className:"flex-1 px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary font-mono focus:outline-none focus:ring-1 focus:ring-accent-primary"})]})]},x.key))})]},y))]})})}function Ww(){const[e,r]=H.useState(null),s=dn(x=>x.currentPreset),i=dn(x=>x.isCustom),l=dn(x=>x.basePreset),u=dn(x=>x.userPresets),h=dn(x=>x.applyPreset),c=dn(x=>x.applyUserPreset),d=dn(x=>x.deleteUserPreset),p=dn(x=>x.saveTheme),g=x=>{h(x),p(JSON.stringify({preset:x}))},m=x=>{c(x)},b=x=>{const S=gr.find(j=>j.id===x);S&&r({type:"new",presetIndex:u.length,basePresetId:x,presetName:S.name+" Copy",tokens:{...S.tokens}})},_=x=>{const S=u[x];if(!S)return;const j=gr.find(N=>N.id===S.basePreset),T=j?{...j.tokens,...S.tokens}:S.tokens;r({type:"edit",presetIndex:x,basePresetId:S.basePreset,presetName:S.name,tokens:T})},k=(x,S)=>{if(!e)return;const j=[...u];if(e.type==="new"){const T={id:"custom-"+Date.now(),name:x,basePreset:e.basePresetId,tokens:S};j.push(T);const N=j.length-1;dn.setState({userPresets:j}),dn.getState().saveUserPresets(),dn.getState().applyUserPreset(N)}else{const T=j[e.presetIndex];T&&(j[e.presetIndex]={...T,name:x,tokens:S}),dn.setState({userPresets:j}),dn.getState().saveUserPresets(),dn.getState().applyUserPreset(e.presetIndex)}r(null)},C=()=>{r(null)},y=(x,S)=>{x.stopPropagation(),d(S)},v=i?l:s;return o.jsxs("div",{className:"space-y-4",children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Theme"}),o.jsx("div",{className:"grid grid-cols-5 gap-2",children:gr.map(x=>o.jsxs("div",{className:"relative group",children:[o.jsxs("button",{type:"button",onClick:()=>g(x.id),className:`w-full flex flex-col items-center gap-2 px-3 py-3 rounded-lg border transition-colors ${v===x.id&&!i?"border-accent-primary bg-bg-tertiary text-text-primary":"border-border bg-bg-secondary text-text-muted hover:border-text-muted"}`,children:[o.jsx("div",{className:"w-8 h-8 rounded border flex items-center justify-center",style:{backgroundColor:Hs(x.tokens["color-bg-primary"]??"#000"),borderColor:Hs(x.tokens["color-border"]??"#000")},children:o.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:Hs(x.tokens["color-text-primary"]??"#fff")}})}),o.jsx("span",{className:"text-xs",children:x.name})]}),o.jsx("button",{type:"button",onClick:S=>{S.stopPropagation(),b(x.id)},className:"absolute top-1 right-1 w-6 h-6 rounded bg-bg-tertiary border border-border flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:border-text-muted",title:"Create custom theme based on this",children:o.jsx("span",{className:"text-xs",children:"✎"})})]},x.id))}),u.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("h4",{className:"text-xs font-medium text-text-muted uppercase",children:"My Themes"}),o.jsx("div",{className:"grid grid-cols-5 gap-2",children:u.map((x,S)=>{const j=gr.find(N=>N.id===x.basePreset),T=j?{...j.tokens,...x.tokens}:x.tokens;return o.jsxs("div",{className:"relative group",children:[o.jsxs("button",{type:"button",onClick:()=>m(S),className:`w-full flex flex-col items-center gap-2 px-3 py-3 rounded-lg border transition-colors ${i&&l===x.basePreset&&v===x.basePreset?"border-accent-primary bg-bg-tertiary text-text-primary":"border-border bg-bg-secondary text-text-muted hover:border-text-muted"}`,children:[o.jsx("div",{className:"w-8 h-8 rounded border flex items-center justify-center",style:{backgroundColor:Hs(T["color-bg-primary"]??"#000"),borderColor:Hs(T["color-border"]??"#000")},children:o.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:Hs(T["color-text-primary"]??"#fff")}})}),o.jsx("span",{className:"text-xs truncate w-full text-center",children:x.name})]}),o.jsx("button",{type:"button",onClick:N=>{N.stopPropagation(),_(S)},className:"absolute top-1 right-1 w-6 h-6 rounded bg-bg-tertiary border border-border flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:border-text-muted",title:"Edit",children:o.jsx("span",{className:"text-xs",children:"✎"})}),o.jsx("button",{type:"button",onClick:N=>y(N,S),className:"absolute -top-1 -left-1 w-5 h-5 rounded-full bg-accent-error text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-20",children:o.jsx(Ph,{className:"w-3 h-3"})})]},x.id)})})]}),e&&o.jsx(qw,{isOpen:!0,isNew:e.type==="new",presetIndex:e.presetIndex,basePresetId:e.basePresetId,presetName:e.presetName,initialTokens:e.tokens,onClose:C,onSave:k})]})}function Vw({isOpen:e,onClose:r}){const[s,i]=H.useState("instructions");return o.jsx(jt,{isOpen:e,onClose:r,title:"Settings",size:"xl",minHeight:"500px",children:o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:"flex border-b border-border mb-4 -mt-1",children:[o.jsx(qa,{label:"Instructions",active:s==="instructions",onClick:()=>i("instructions")}),o.jsx(qa,{label:"Skills",active:s==="skills",onClick:()=>i("skills")}),o.jsx(qa,{label:"Notifications",active:s==="notifications",onClick:()=>i("notifications")}),o.jsx(qa,{label:"Display",active:s==="display",onClick:()=>i("display")}),o.jsx(qa,{label:"Advanced",active:s==="advanced",onClick:()=>i("advanced")})]}),s==="instructions"&&o.jsx(Xw,{isOpen:e}),s==="skills"&&o.jsx(Uw,{isOpen:e}),s==="notifications"&&o.jsx("div",{className:"max-h-[60vh] overflow-y-auto",children:o.jsx(Pw,{})}),s==="display"&&o.jsx(Yw,{}),s==="advanced"&&o.jsx(Gw,{onClose:r})]})})}function Gw({onClose:e}){const[,r]=vr();function s(){e(),r("/onboarding")}return o.jsx("div",{className:"space-y-6",children:o.jsxs("div",{children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary mb-1",children:"Onboarding"}),o.jsx("p",{className:"text-sm text-text-muted mb-4",children:"Reset your OpenFox setup and go through the initial configuration again."}),o.jsx(st,{variant:"secondary",onClick:s,children:"Launch Onboarding"})]})})}function Kw(){return o.jsx(Ww,{})}function Yw(){const e=Yt(g=>g.settings),r=Yt(g=>g.loading),s=Yt(g=>g.getSetting),i=Yt(g=>g.setSetting),l=r[ot.DISPLAY_SHOW_THINKING]??!1,u=[{key:ot.DISPLAY_SHOW_THINKING,label:"Show thinking blocks",description:"Display AI reasoning content in the feed"},{key:ot.DISPLAY_SHOW_VERBOSE_TOOL_OUTPUT,label:"Show expanded tool output",description:"Always show full tool call details instead of compact view"},{key:ot.DISPLAY_SHOW_STATS,label:"Show stats bar",description:"Display model, tokens, and timing information"},{key:ot.DISPLAY_SHOW_AGENT_DEFINITIONS,label:"Show agent definitions",description:"Display agent definition injections in the feed"},{key:ot.DISPLAY_SHOW_WORKFLOW_BARS,label:"Show workflow bars",description:"Display workflow start and end markers"}],h=Object.fromEntries(u.map(g=>[g.key,e[g.key]??"true"])),[c,d]=H.useState(()=>Object.fromEntries(u.map(g=>[g.key,h[g.key]==="true"])));H.useEffect(()=>{u.forEach(g=>s(g.key))},[s]),H.useEffect(()=>{d(Object.fromEntries(u.map(g=>[g.key,h[g.key]==="true"])))},[JSON.stringify(h)]);const p=async g=>{const m=String(!c[g]);d(b=>({...b,[g]:!b[g]})),await i(g,m)};return l?o.jsx("div",{className:"text-sm text-text-muted",children:"Loading..."}):o.jsxs("div",{className:"space-y-6",children:[o.jsx(Kw,{}),o.jsxs("div",{children:[o.jsx("h3",{className:"text-sm font-medium text-text-primary mb-4",children:"Feed Display"}),o.jsx("div",{className:"space-y-4",children:u.map(({key:g,label:m,description:b})=>o.jsxs("label",{className:"flex items-center justify-between cursor-pointer",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-sm text-text-primary",children:m}),o.jsx("div",{className:"text-xs text-text-muted",children:b})]}),o.jsx("button",{type:"button",onClick:()=>p(g),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${c[g]?"bg-accent-primary":"bg-bg-tertiary"}`,children:o.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${c[g]?"translate-x-6":"translate-x-1"}`})})]},g))})]})]})}function qa({label:e,active:r,onClick:s}){return o.jsx("button",{onClick:s,className:`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${r?"border-accent-primary text-accent-primary":"border-transparent text-text-muted hover:text-text-secondary hover:border-border"}`,children:e})}function Xw({isOpen:e}){const r=Yt(y=>y.settings),s=Yt(y=>y.loading),i=Yt(y=>y.getSetting),l=Yt(y=>y.setSetting),u=r[ot.GLOBAL_INSTRUCTIONS]??"",h=s[ot.GLOBAL_INSTRUCTIONS]??!1,[c,d]=H.useState(u),[p,g]=H.useState(!1),[m,b]=H.useState(!1);H.useEffect(()=>{e&&i(ot.GLOBAL_INSTRUCTIONS)},[e,i]),H.useEffect(()=>{d(u),g(!1)},[u]);const _=async()=>{b(!0),l(ot.GLOBAL_INSTRUCTIONS,c),b(!1),g(!1)},k=()=>{d(u),g(!1)},C=h||m;return o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-text-primary mb-2",children:"Global Instructions"}),o.jsx("p",{className:"text-sm text-text-muted mb-2",children:"These instructions are injected into every prompt, regardless of project."}),o.jsx("textarea",{value:c,onChange:y=>{d(y.target.value),g(!0)},placeholder:"Enter global instructions that apply to all projects...",className:"w-full min-h-80 px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-y focus:outline-none focus:ring-1 focus:ring-accent-primary",disabled:C})]}),p&&o.jsx(Vh,{}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(st,{variant:"secondary",onClick:k,disabled:!p,children:"Discard"}),o.jsx(st,{variant:"primary",onClick:_,disabled:!p||C,children:m?"Saving...":"Save"})]})]})}var qd={exports:{}},nv;function Zw(){return nv||(nv=1,(function(e,r){(function(s,i){e.exports=i()})(globalThis,(()=>(()=>{var s={4567:function(h,c,d){var p=this&&this.__decorate||function(x,S,j,T){var N,D=arguments.length,A=D<3?S:T===null?T=Object.getOwnPropertyDescriptor(S,j):T;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")A=Reflect.decorate(x,S,j,T);else for(var z=x.length-1;z>=0;z--)(N=x[z])&&(A=(D<3?N(A):D>3?N(S,j,A):N(S,j))||A);return D>3&&A&&Object.defineProperty(S,j,A),A},g=this&&this.__param||function(x,S){return function(j,T){S(j,T,x)}};Object.defineProperty(c,"__esModule",{value:!0}),c.AccessibilityManager=void 0;const m=d(9042),b=d(9924),_=d(844),k=d(4725),C=d(2585),y=d(3656);let v=c.AccessibilityManager=class extends _.Disposable{constructor(x,S,j,T){super(),this._terminal=x,this._coreBrowserService=j,this._renderService=T,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let N=0;N<this._terminal.rows;N++)this._rowElements[N]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[N]);if(this._topBoundaryFocusListener=N=>this._handleBoundaryFocus(N,0),this._bottomBoundaryFocusListener=N=>this._handleBoundaryFocus(N,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new b.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((N=>this._handleResize(N.rows)))),this.register(this._terminal.onRender((N=>this._refreshRows(N.start,N.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((N=>this._handleChar(N)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
58
58
  `)))),this.register(this._terminal.onA11yTab((N=>this._handleTab(N)))),this.register(this._terminal.onKey((N=>this._handleKey(N.key)))),this.register(this._terminal.onBlur((()=>this._clearLiveRegion()))),this.register(this._renderService.onDimensionsChange((()=>this._refreshRowsDimensions()))),this.register((0,y.addDisposableDomListener)(document,"selectionchange",(()=>this._handleSelectionChange()))),this.register(this._coreBrowserService.onDprChange((()=>this._refreshRowsDimensions()))),this._refreshRows(),this.register((0,_.toDisposable)((()=>{this._accessibilityContainer.remove(),this._rowElements.length=0})))}_handleTab(x){for(let S=0;S<x;S++)this._handleChar(" ")}_handleChar(x){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==x&&(this._charsToAnnounce+=x):this._charsToAnnounce+=x,x===`
59
59
  `&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=m.tooMuchOutput)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(x){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(x)||this._charsToConsume.push(x)}_refreshRows(x,S){this._liveRegionDebouncer.refresh(x,S,this._terminal.rows)}_renderRows(x,S){const j=this._terminal.buffer,T=j.lines.length.toString();for(let N=x;N<=S;N++){const D=j.lines.get(j.ydisp+N),A=[],z=(D==null?void 0:D.translateToString(!0,void 0,void 0,A))||"",O=(j.ydisp+N+1).toString(),q=this._rowElements[N];q&&(z.length===0?(q.innerText=" ",this._rowColumns.set(q,[0,1])):(q.textContent=z,this._rowColumns.set(q,A)),q.setAttribute("aria-posinset",O),q.setAttribute("aria-setsize",T))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(x,S){const j=x.target,T=this._rowElements[S===0?1:this._rowElements.length-2];if(j.getAttribute("aria-posinset")===(S===0?"1":`${this._terminal.buffer.lines.length}`)||x.relatedTarget!==T)return;let N,D;if(S===0?(N=j,D=this._rowElements.pop(),this._rowContainer.removeChild(D)):(N=this._rowElements.shift(),D=j,this._rowContainer.removeChild(N)),N.removeEventListener("focus",this._topBoundaryFocusListener),D.removeEventListener("focus",this._bottomBoundaryFocusListener),S===0){const A=this._createAccessibilityTreeNode();this._rowElements.unshift(A),this._rowContainer.insertAdjacentElement("afterbegin",A)}else{const A=this._createAccessibilityTreeNode();this._rowElements.push(A),this._rowContainer.appendChild(A)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(S===0?-1:1),this._rowElements[S===0?1:this._rowElements.length-2].focus(),x.preventDefault(),x.stopImmediatePropagation()}_handleSelectionChange(){var z;if(this._rowElements.length===0)return;const x=document.getSelection();if(!x)return;if(x.isCollapsed)return void(this._rowContainer.contains(x.anchorNode)&&this._terminal.clearSelection());if(!x.anchorNode||!x.focusNode)return void console.error("anchorNode and/or focusNode are null");let S={node:x.anchorNode,offset:x.anchorOffset},j={node:x.focusNode,offset:x.focusOffset};if((S.node.compareDocumentPosition(j.node)&Node.DOCUMENT_POSITION_PRECEDING||S.node===j.node&&S.offset>j.offset)&&([S,j]=[j,S]),S.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(S={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(S.node))return;const T=this._rowElements.slice(-1)[0];if(j.node.compareDocumentPosition(T)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(j={node:T,offset:((z=T.textContent)==null?void 0:z.length)??0}),!this._rowContainer.contains(j.node))return;const N=({node:O,offset:q})=>{const G=O instanceof Text?O.parentNode:O;let W=parseInt(G==null?void 0:G.getAttribute("aria-posinset"),10)-1;if(isNaN(W))return console.warn("row is invalid. Race condition?"),null;const I=this._rowColumns.get(G);if(!I)return console.warn("columns is null. Race condition?"),null;let $=q<I.length?I[q]:I.slice(-1)[0]+1;return $>=this._terminal.cols&&(++W,$=0),{row:W,column:$}},D=N(S),A=N(j);if(D&&A){if(D.row>A.row||D.row===A.row&&D.column>=A.column)throw new Error("invalid range");this._terminal.select(D.column,D.row,(A.row-D.row)*this._terminal.cols-D.column+A.column)}}_handleResize(x){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let S=this._rowContainer.children.length;S<this._terminal.rows;S++)this._rowElements[S]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[S]);for(;this._rowElements.length>x;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const x=this._coreBrowserService.mainDocument.createElement("div");return x.setAttribute("role","listitem"),x.tabIndex=-1,this._refreshRowDimensions(x),x}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){this._accessibilityContainer.style.width=`${this._renderService.dimensions.css.canvas.width}px`,this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let x=0;x<this._terminal.rows;x++)this._refreshRowDimensions(this._rowElements[x])}}_refreshRowDimensions(x){x.style.height=`${this._renderService.dimensions.css.cell.height}px`}};c.AccessibilityManager=v=p([g(1,C.IInstantiationService),g(2,k.ICoreBrowserService),g(3,k.IRenderService)],v)},3614:(h,c)=>{function d(b){return b.replace(/\r?\n/g,"\r")}function p(b,_){return _?"\x1B[200~"+b+"\x1B[201~":b}function g(b,_,k,C){b=p(b=d(b),k.decPrivateModes.bracketedPasteMode&&C.rawOptions.ignoreBracketedPasteMode!==!0),k.triggerDataEvent(b,!0),_.value=""}function m(b,_,k){const C=k.getBoundingClientRect(),y=b.clientX-C.left-10,v=b.clientY-C.top-10;_.style.width="20px",_.style.height="20px",_.style.left=`${y}px`,_.style.top=`${v}px`,_.style.zIndex="1000",_.focus()}Object.defineProperty(c,"__esModule",{value:!0}),c.rightClickHandler=c.moveTextAreaUnderMouseCursor=c.paste=c.handlePasteEvent=c.copyHandler=c.bracketTextForPaste=c.prepareTextForTerminal=void 0,c.prepareTextForTerminal=d,c.bracketTextForPaste=p,c.copyHandler=function(b,_){b.clipboardData&&b.clipboardData.setData("text/plain",_.selectionText),b.preventDefault()},c.handlePasteEvent=function(b,_,k,C){b.stopPropagation(),b.clipboardData&&g(b.clipboardData.getData("text/plain"),_,k,C)},c.paste=g,c.moveTextAreaUnderMouseCursor=m,c.rightClickHandler=function(b,_,k,C,y){m(b,_,k),y&&C.rightClickSelect(b),_.value=C.selectionText,_.select()}},7239:(h,c,d)=>{Object.defineProperty(c,"__esModule",{value:!0}),c.ColorContrastCache=void 0;const p=d(1505);c.ColorContrastCache=class{constructor(){this._color=new p.TwoKeyMap,this._css=new p.TwoKeyMap}setCss(g,m,b){this._css.set(g,m,b)}getCss(g,m){return this._css.get(g,m)}setColor(g,m,b){this._color.set(g,m,b)}getColor(g,m){return this._color.get(g,m)}clear(){this._color.clear(),this._css.clear()}}},3656:(h,c)=>{Object.defineProperty(c,"__esModule",{value:!0}),c.addDisposableDomListener=void 0,c.addDisposableDomListener=function(d,p,g,m){d.addEventListener(p,g,m);let b=!1;return{dispose:()=>{b||(b=!0,d.removeEventListener(p,g,m))}}}},3551:function(h,c,d){var p=this&&this.__decorate||function(v,x,S,j){var T,N=arguments.length,D=N<3?x:j===null?j=Object.getOwnPropertyDescriptor(x,S):j;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")D=Reflect.decorate(v,x,S,j);else for(var A=v.length-1;A>=0;A--)(T=v[A])&&(D=(N<3?T(D):N>3?T(x,S,D):T(x,S))||D);return N>3&&D&&Object.defineProperty(x,S,D),D},g=this&&this.__param||function(v,x){return function(S,j){x(S,j,v)}};Object.defineProperty(c,"__esModule",{value:!0}),c.Linkifier=void 0;const m=d(3656),b=d(8460),_=d(844),k=d(2585),C=d(4725);let y=c.Linkifier=class extends _.Disposable{get currentLink(){return this._currentLink}constructor(v,x,S,j,T){super(),this._element=v,this._mouseService=x,this._renderService=S,this._bufferService=j,this._linkProviderService=T,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new b.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new b.EventEmitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this.register((0,_.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,_.toDisposable)((()=>{var N;this._lastMouseEvent=void 0,(N=this._activeProviderReplies)==null||N.clear()}))),this.register(this._bufferService.onResize((()=>{this._clearCurrentLink(),this._wasResized=!0}))),this.register((0,m.addDisposableDomListener)(this._element,"mouseleave",(()=>{this._isMouseOut=!0,this._clearCurrentLink()}))),this.register((0,m.addDisposableDomListener)(this._element,"mousemove",this._handleMouseMove.bind(this))),this.register((0,m.addDisposableDomListener)(this._element,"mousedown",this._handleMouseDown.bind(this))),this.register((0,m.addDisposableDomListener)(this._element,"mouseup",this._handleMouseUp.bind(this)))}_handleMouseMove(v){this._lastMouseEvent=v;const x=this._positionFromMouseEvent(v,this._element,this._mouseService);if(!x)return;this._isMouseOut=!1;const S=v.composedPath();for(let j=0;j<S.length;j++){const T=S[j];if(T.classList.contains("xterm"))break;if(T.classList.contains("xterm-hover"))return}this._lastBufferCell&&x.x===this._lastBufferCell.x&&x.y===this._lastBufferCell.y||(this._handleHover(x),this._lastBufferCell=x)}_handleHover(v){if(this._activeLine!==v.y||this._wasResized)return this._clearCurrentLink(),this._askForLink(v,!1),void(this._wasResized=!1);this._currentLink&&this._linkAtPosition(this._currentLink.link,v)||(this._clearCurrentLink(),this._askForLink(v,!0))}_askForLink(v,x){var j,T;this._activeProviderReplies&&x||((j=this._activeProviderReplies)==null||j.forEach((N=>{N==null||N.forEach((D=>{D.link.dispose&&D.link.dispose()}))})),this._activeProviderReplies=new Map,this._activeLine=v.y);let S=!1;for(const[N,D]of this._linkProviderService.linkProviders.entries())x?(T=this._activeProviderReplies)!=null&&T.get(N)&&(S=this._checkLinkProviderResult(N,v,S)):D.provideLinks(v.y,(A=>{var O,q;if(this._isMouseOut)return;const z=A==null?void 0:A.map((G=>({link:G})));(O=this._activeProviderReplies)==null||O.set(N,z),S=this._checkLinkProviderResult(N,v,S),((q=this._activeProviderReplies)==null?void 0:q.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(v.y,this._activeProviderReplies)}))}_removeIntersectingLinks(v,x){const S=new Set;for(let j=0;j<x.size;j++){const T=x.get(j);if(T)for(let N=0;N<T.length;N++){const D=T[N],A=D.link.range.start.y<v?0:D.link.range.start.x,z=D.link.range.end.y>v?this._bufferService.cols:D.link.range.end.x;for(let O=A;O<=z;O++){if(S.has(O)){T.splice(N--,1);break}S.add(O)}}}}_checkLinkProviderResult(v,x,S){var N;if(!this._activeProviderReplies)return S;const j=this._activeProviderReplies.get(v);let T=!1;for(let D=0;D<v;D++)this._activeProviderReplies.has(D)&&!this._activeProviderReplies.get(D)||(T=!0);if(!T&&j){const D=j.find((A=>this._linkAtPosition(A.link,x)));D&&(S=!0,this._handleNewLink(D))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!S)for(let D=0;D<this._activeProviderReplies.size;D++){const A=(N=this._activeProviderReplies.get(D))==null?void 0:N.find((z=>this._linkAtPosition(z.link,x)));if(A){S=!0,this._handleNewLink(A);break}}return S}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(v){if(!this._currentLink)return;const x=this._positionFromMouseEvent(v,this._element,this._mouseService);x&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,x)&&this._currentLink.link.activate(v,this._currentLink.link.text)}_clearCurrentLink(v,x){this._currentLink&&this._lastMouseEvent&&(!v||!x||this._currentLink.link.range.start.y>=v&&this._currentLink.link.range.end.y<=x)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,_.disposeArray)(this._linkCacheDisposables))}_handleNewLink(v){if(!this._lastMouseEvent)return;const x=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);x&&this._linkAtPosition(v.link,x)&&(this._currentLink=v,this._currentLink.state={decorations:{underline:v.link.decorations===void 0||v.link.decorations.underline,pointerCursor:v.link.decorations===void 0||v.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,v.link,this._lastMouseEvent),v.link.decorations={},Object.defineProperties(v.link.decorations,{pointerCursor:{get:()=>{var S,j;return(j=(S=this._currentLink)==null?void 0:S.state)==null?void 0:j.decorations.pointerCursor},set:S=>{var j;(j=this._currentLink)!=null&&j.state&&this._currentLink.state.decorations.pointerCursor!==S&&(this._currentLink.state.decorations.pointerCursor=S,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",S))}},underline:{get:()=>{var S,j;return(j=(S=this._currentLink)==null?void 0:S.state)==null?void 0:j.decorations.underline},set:S=>{var j,T,N;(j=this._currentLink)!=null&&j.state&&((N=(T=this._currentLink)==null?void 0:T.state)==null?void 0:N.decorations.underline)!==S&&(this._currentLink.state.decorations.underline=S,this._currentLink.state.isHovered&&this._fireUnderlineEvent(v.link,S))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange((S=>{if(!this._currentLink)return;const j=S.start===0?0:S.start+1+this._bufferService.buffer.ydisp,T=this._bufferService.buffer.ydisp+1+S.end;if(this._currentLink.link.range.start.y>=j&&this._currentLink.link.range.end.y<=T&&(this._clearCurrentLink(j,T),this._lastMouseEvent)){const N=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);N&&this._askForLink(N,!1)}}))))}_linkHover(v,x,S){var j;(j=this._currentLink)!=null&&j.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(x,!0),this._currentLink.state.decorations.pointerCursor&&v.classList.add("xterm-cursor-pointer")),x.hover&&x.hover(S,x.text)}_fireUnderlineEvent(v,x){const S=v.range,j=this._bufferService.buffer.ydisp,T=this._createLinkUnderlineEvent(S.start.x-1,S.start.y-j-1,S.end.x,S.end.y-j-1,void 0);(x?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(T)}_linkLeave(v,x,S){var j;(j=this._currentLink)!=null&&j.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(x,!1),this._currentLink.state.decorations.pointerCursor&&v.classList.remove("xterm-cursor-pointer")),x.leave&&x.leave(S,x.text)}_linkAtPosition(v,x){const S=v.range.start.y*this._bufferService.cols+v.range.start.x,j=v.range.end.y*this._bufferService.cols+v.range.end.x,T=x.y*this._bufferService.cols+x.x;return S<=T&&T<=j}_positionFromMouseEvent(v,x,S){const j=S.getCoords(v,x,this._bufferService.cols,this._bufferService.rows);if(j)return{x:j[0],y:j[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(v,x,S,j,T){return{x1:v,y1:x,x2:S,y2:j,cols:this._bufferService.cols,fg:T}}};c.Linkifier=y=p([g(1,C.IMouseService),g(2,C.IRenderService),g(3,k.IBufferService),g(4,C.ILinkProviderService)],y)},9042:(h,c)=>{Object.defineProperty(c,"__esModule",{value:!0}),c.tooMuchOutput=c.promptLabel=void 0,c.promptLabel="Terminal input",c.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},3730:function(h,c,d){var p=this&&this.__decorate||function(C,y,v,x){var S,j=arguments.length,T=j<3?y:x===null?x=Object.getOwnPropertyDescriptor(y,v):x;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")T=Reflect.decorate(C,y,v,x);else for(var N=C.length-1;N>=0;N--)(S=C[N])&&(T=(j<3?S(T):j>3?S(y,v,T):S(y,v))||T);return j>3&&T&&Object.defineProperty(y,v,T),T},g=this&&this.__param||function(C,y){return function(v,x){y(v,x,C)}};Object.defineProperty(c,"__esModule",{value:!0}),c.OscLinkProvider=void 0;const m=d(511),b=d(2585);let _=c.OscLinkProvider=class{constructor(C,y,v){this._bufferService=C,this._optionsService=y,this._oscLinkService=v}provideLinks(C,y){var z;const v=this._bufferService.buffer.lines.get(C-1);if(!v)return void y(void 0);const x=[],S=this._optionsService.rawOptions.linkHandler,j=new m.CellData,T=v.getTrimmedLength();let N=-1,D=-1,A=!1;for(let O=0;O<T;O++)if(D!==-1||v.hasContent(O)){if(v.loadCell(O,j),j.hasExtendedAttrs()&&j.extended.urlId){if(D===-1){D=O,N=j.extended.urlId;continue}A=j.extended.urlId!==N}else D!==-1&&(A=!0);if(A||D!==-1&&O===T-1){const q=(z=this._oscLinkService.getLinkData(N))==null?void 0:z.uri;if(q){const G={start:{x:D+1,y:C},end:{x:O+(A||O!==T-1?0:1),y:C}};let W=!1;if(!(S!=null&&S.allowNonHttpProtocols))try{const I=new URL(q);["http:","https:"].includes(I.protocol)||(W=!0)}catch{W=!0}W||x.push({text:q,range:G,activate:(I,$)=>S?S.activate(I,$,G):k(0,$),hover:(I,$)=>{var B;return(B=S==null?void 0:S.hover)==null?void 0:B.call(S,I,$,G)},leave:(I,$)=>{var B;return(B=S==null?void 0:S.leave)==null?void 0:B.call(S,I,$,G)}})}A=!1,j.hasExtendedAttrs()&&j.extended.urlId?(D=O,N=j.extended.urlId):(D=-1,N=-1)}}y(x)}};function k(C,y){if(confirm(`Do you want to navigate to ${y}?
60
60
 
@@ -73,7 +73,7 @@ WARNING: This link could potentially be dangerous`)){const v=window.open();if(v)
73
73
  * Fabrice Bellard's javascript vt100 for jslinux:
74
74
  * http://bellard.org/jslinux/
75
75
  * Copyright (c) 2011 Fabrice Bellard
76
- */var Jw=2,eC=1,tC=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let r=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(r._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){var m;if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let r=this._terminal.options.scrollback===0?0:((m=this._terminal.options.overviewRuler)==null?void 0:m.width)||14,s=window.getComputedStyle(this._terminal.element.parentElement),i=parseInt(s.getPropertyValue("height")),l=Math.max(0,parseInt(s.getPropertyValue("width"))),u=window.getComputedStyle(this._terminal.element),h={top:parseInt(u.getPropertyValue("padding-top")),bottom:parseInt(u.getPropertyValue("padding-bottom")),right:parseInt(u.getPropertyValue("padding-right")),left:parseInt(u.getPropertyValue("padding-left"))},c=h.top+h.bottom,d=h.right+h.left,p=i-c,g=l-d-r;return{cols:Math.max(Jw,Math.floor(g/e.css.cell.width)),rows:Math.max(eC,Math.floor(p/e.css.cell.height))}}};function nC({sessionId:e,onClose:r,onEscape:s,autoFocus:i}){const l=H.useRef(null),u=H.useRef(e),h=H.useRef(null),c=H.useRef(null),d=ir(g=>g.writeSession),p=ir(g=>g.resizeSession);return H.useEffect(()=>{u.current=e},[e]),H.useEffect(()=>{if(!s)return;const g=m=>{m.key==="Escape"&&(m.preventDefault(),m.stopPropagation(),s())};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[s]),H.useEffect(()=>{if(!l.current)return;const g=new Qw.Terminal({fontFamily:'"JetBrains Mono", monospace',fontSize:13,theme:{background:"#1a1a1a",foreground:"#e0e0e0",cursor:"#ffffff",cursorAccent:"#1a1a1a"},cursorBlink:!0,cursorStyle:"bar",convertEol:!0}),m=new tC;g.loadAddon(m),h.current={term:g,fitAddon:m},l.current.addEventListener("keydown",C=>{C.key==="Escape"&&s&&(C.preventDefault(),C.stopPropagation(),s())}),g.open(l.current);const b=l.current.querySelector(".xterm");b&&(b.style.padding="8px"),m.fit(),i&&setTimeout(()=>{g.focus()},150);const _=new ResizeObserver(()=>{c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{requestAnimationFrame(()=>{var y;m.fit&&m.fit();const C=(y=h.current)==null?void 0:y.term;C&&C.cols>0&&C.rows>0&&p(u.current,C.cols,C.rows)})},100)});_.observe(l.current),g.onData(C=>{if(C==="\x1B"&&s){s();return}d(u.current,C)}),g.onKey(C=>{C.key==="\x1B"&&s&&(C.domEvent.stopPropagation(),s())});const k=Gt.subscribe(C=>{var y,v;if(C.type==="terminal.output"&&((y=C.payload)==null?void 0:y.sessionId)===u.current){const x=(v=C.payload)==null?void 0:v.data;x&&g.write(x)}});return()=>{k(),_.disconnect(),c.current&&clearTimeout(c.current),g.dispose(),h.current=null}},[e,d,p]),o.jsxs("div",{className:"flex flex-col h-full bg-[#1a1a1a]",children:[o.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between px-2 py-1 bg-[#252525] border-b border-[#333]",children:[o.jsx("div",{}),o.jsx("button",{onClick:r,className:"p-1 rounded hover:bg-[#333] text-[#888] hover:text-[#ccc] transition-colors",title:"Close terminal",children:o.jsx(Ow,{})})]}),o.jsx("div",{ref:l,className:"flex-1 relative overflow-hidden",tabIndex:0,onKeyDown:g=>{g.key==="Escape"&&s&&(g.preventDefault(),g.stopPropagation(),s())}})]})}function rC(e){return e===1?"grid-cols-1":e===2?"grid-cols-1 lg:grid-cols-2":"grid-cols-1 lg:grid-cols-2 xl:grid-cols-3"}function sC({isOpen:e,onClose:r,onFocusChat:s}){const i=ir(C=>C.createSession),l=ir(C=>C.killSession),u=ir(C=>C.sessions),h=ir(C=>C.setWorkdir),c=ir(C=>C.fetchSessions),d=Ft(C=>C.currentProject),[p,g]=H.useState(!0),m=H.useRef(null),b=H.useRef(!1),_=H.useRef(!1),k=H.useCallback(()=>{r(),s()},[r,s]);return H.useEffect(()=>{d!=null&&d.workdir&&h(d.workdir)},[d==null?void 0:d.workdir,h]),H.useEffect(()=>{e&&(g(!0),c().finally(()=>g(!1)))},[e,c]),H.useEffect(()=>{e&&u.length===0&&!p&&!_.current&&(_.current=!0,i())},[e,u.length,p,i]),H.useEffect(()=>{e?(b.current=!0,setTimeout(()=>{var C;(C=m.current)==null||C.focus(),setTimeout(()=>{b.current=!1},200)},100)):_.current=!1},[e]),H.useEffect(()=>{if(!e)return;const C=y=>{b.current||y.key==="Escape"&&(y.preventDefault(),r(),s())};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[e,r,s]),e?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"fixed inset-x-0 top-[50vh] bottom-0 z-[100] bg-black/40",style:{pointerEvents:"auto"},onClick:k}),o.jsxs("div",{ref:m,tabIndex:-1,className:"fixed inset-x-0 top-0 z-[100] h-[50vh] bg-bg-primary border-b border-border flex flex-col animate-slide-down outline-none",onClick:C=>C.stopPropagation(),onKeyDown:C=>{C.key==="Escape"&&(C.preventDefault(),k())},children:[o.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-border",children:[o.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:"Terminal"}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("button",{onClick:()=>i(),className:"p-2 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:"New terminal",children:o.jsx(Ew,{})}),o.jsx("button",{onClick:()=>{r(),s()},className:"p-2 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:"Close (Esc)",children:o.jsx(Ph,{})})]})]}),o.jsx("div",{className:"flex-1 min-h-0 p-2 overflow-auto",children:p?o.jsx("div",{className:"flex items-center justify-center h-full text-text-muted",children:"Loading..."}):u.length===0?o.jsx("div",{className:"flex items-center justify-center h-full text-text-muted",children:o.jsxs("div",{className:"text-center",children:[o.jsx("p",{className:"mb-4",children:"No terminal sessions"}),o.jsx("button",{onClick:()=>i(),className:"px-4 py-2 bg-accent-primary/25 text-text-primary rounded hover:bg-accent-primary/40 transition-colors",children:"Create Terminal"})]})}):o.jsx("div",{className:`grid ${rC(u.length)} gap-2 h-full auto-rows-fr`,children:u.map(C=>o.jsx(nC,{sessionId:C.id,onClose:()=>l(C.id),onEscape:k,autoFocus:u.length===1},C.id))})})]})]}):null}function xo({items:e,trigger:r,minWidth:s="120px",isOpen:i,onOpenChange:l}){const[u,h]=H.useState(!1),c=i!==void 0,d=c?i:u,p=O=>{if(c){const q=typeof O=="function"?O(u):O;l==null||l(q)}else h(O)},[g,m]=H.useState(null),b=H.useRef(null),_=H.useRef(null),[k,C]=H.useState(0),y=H.useRef(0),v=H.useRef(e),x=H.useCallback(()=>{if(!b.current)return;const O=b.current.getBoundingClientRect(),q=200,W=window.innerHeight-O.bottom<q;m({top:W?O.top-q-4:O.bottom+4,left:O.left,alignToTop:W})},[]);H.useEffect(()=>{v.current=e},[e]),H.useEffect(()=>{function O(q){_.current&&!_.current.contains(q.target)&&p(!1)}return d&&document.addEventListener("mousedown",O),()=>{document.removeEventListener("mousedown",O)}},[d]),H.useEffect(()=>{d&&x()},[d,x]),H.useEffect(()=>{if(!d)return;setTimeout(()=>{var q;(q=_.current)==null||q.focus()},0);function O(q){const G=v.current,W=G.filter($=>!S($)),I=j(y.current,G);switch(q.key){case"ArrowDown":if(q.preventDefault(),q.stopPropagation(),I<W.length-1){const $=T(y.current+1,G);y.current=$,C($)}break;case"ArrowUp":if(q.preventDefault(),q.stopPropagation(),I>0){const $=N(y.current-1,G);y.current=$,C($)}break;case"Enter":q.preventDefault(),q.stopPropagation(),D(y.current,G);break;case"Escape":q.preventDefault(),q.stopPropagation(),p(!1);break}}return window.addEventListener("keydown",O,!0),()=>window.removeEventListener("keydown",O,!0)},[d,e]);function S(O){var W;const q=O.label;return q?String(((W=q.props)==null?void 0:W.className)??"").includes("cursor-default"):!1}function j(O,q){let G=0;for(let W=0;W<O;W++){const I=q[W];I&&!S(I)&&G++}return G}function T(O,q){for(let G=O;G<q.length;G++){const W=q[G];if(W&&!S(W))return G}return O}function N(O,q){for(let G=O;G>=0;G--){const W=q[G];if(W&&!S(W))return G}return O}function D(O,q){var W;const G=q[O];!G||S(G)||((W=G.onClick)==null||W.call(G),G.href&&(window.history.pushState(null,"",G.href),window.dispatchEvent(new PopStateEvent("popstate"))),p(!1))}H.useEffect(()=>{d&&(C(e.findIndex(O=>!S(O))),y.current=e.findIndex(O=>!S(O)))},[d,e]);const A=O=>{O.stopPropagation(),d||x(),p(!d)},z=g&&o.jsx("div",{ref:_,"data-testid":"session-dropdown-menu",className:`fixed bg-bg-secondary border border-border rounded shadow-lg z-50 ${g.alignToTop?"mb-1":"mt-1"}`,style:{top:g.top,left:g.left,minWidth:s},tabIndex:-1,children:e.map((O,q)=>{const W=!S(O)&&q===k,I=o.jsxs(o.Fragment,{children:[O.icon&&o.jsx("span",{className:"w-4 h-4 flex-shrink-0",children:O.icon}),O.label]});return O.href?o.jsx(Fn,{href:O.href,onClick:$=>{var B;(B=O.onClick)==null||B.call(O,$),p(!1)},className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 transition-colors ${O.danger?"text-accent-error hover:bg-accent-error/10":W?"bg-accent-primary/20 text-text-primary":"hover:bg-bg-tertiary text-text-primary"} ${q!==e.length-1?"border-b border-border":""}`,children:I},q):o.jsx("button",{onClick:$=>{var B;(B=O.onClick)==null||B.call(O,$),O.closeOnClick!==!1&&p(!1)},className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 transition-colors ${O.danger?"text-accent-error hover:bg-accent-error/10":W?"bg-accent-primary/20 text-text-primary":"hover:bg-bg-tertiary text-text-primary"} ${q!==e.length-1?"border-b border-border":""}`,children:I},q)})});return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"relative",children:o.jsx("div",{ref:b,onClick:A,children:r})}),d&&go.createPortal(z,document.body)]})}function sy(e){const r=new Date(e),i=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][r.getDay()],l=r.getFullYear(),u=String(r.getMonth()+1).padStart(2,"0"),h=String(r.getDate()).padStart(2,"0");return`${i} ${l}/${u}/${h}`}function dc(e){const r=new Date(e),s=String(r.getHours()).padStart(2,"0"),i=String(r.getMinutes()).padStart(2,"0");return`${s}:${i}`}function iC(e){const r=new Date(e),s=new Date,i=new Date(s.getFullYear(),s.getMonth(),s.getDate()),l=new Date(r.getFullYear(),r.getMonth(),r.getDate()),u=Math.floor((i.getTime()-l.getTime())/(1e3*60*60*24)),h=dc(e);if(u===0)return`today ${h}`;if(u===1)return`yesterday ${h}`;if(u<7)return`${u} days ago ${h}`;{const c=r.getFullYear(),d=String(r.getMonth()+1).padStart(2,"0"),p=String(r.getDate()).padStart(2,"0");return`${c}/${d}/${p} ${h}`}}function iy(e){const r=new Date(e);return{year:r.getFullYear(),month:String(r.getMonth()+1).padStart(2,"0"),day:String(r.getDate()).padStart(2,"0")}}function aC(e){const{year:r,month:s,day:i}=iy(e);return`${r}-${s}-${i}`}function ay(e){const r=new Map;for(const l of e){const u=aC(l.updatedAt);r.has(u)||r.set(u,[]),r.get(u).push(l)}for(const[l,u]of r)u.sort((h,c)=>{const d=new Date(h.updatedAt).getTime();return new Date(c.updatedAt).getTime()-d});const s=Array.from(r.keys()).sort((l,u)=>u.localeCompare(l)),i=new Map;for(const l of s)i.set(l,r.get(l));return i}function oC({items:e,trigger:r,isActive:s=!1}){const[i,l]=H.useState(!1),u=H.useRef(null);return H.useEffect(()=>{function h(c){u.current&&!u.current.contains(c.target)&&l(!1)}if(i)return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[i]),o.jsxs("div",{className:"relative",ref:u,children:[o.jsxs("button",{type:"button",onClick:()=>l(!i),className:`flex items-center gap-1 px-1.5 py-0.5 rounded transition-colors ${s?"bg-bg-tertiary":"hover:bg-bg-tertiary"}`,children:[typeof r=="string"?o.jsx("span",{className:"text-sm text-text-secondary font-medium",children:r}):r,o.jsx(xr,{className:"w-3 h-3 text-text-muted flex-shrink-0 transition-transform",rotate:i?180:0})]}),i&&e.length>0&&o.jsx("div",{className:"absolute top-full left-0 mt-1 w-56 bg-bg-secondary border border-border rounded-lg shadow-lg overflow-hidden z-50",children:e.map((h,c)=>{const d=h.label&&typeof h.label=="object"&&h.label.type===Fn?h.label:null;if(d){const p=d.props.href||"";return o.jsxs(Fn,{href:p,className:"flex items-center gap-2 px-3 py-2 text-sm border-b border-border hover:bg-bg-tertiary transition-colors",children:[h.icon,d.props.children]},c)}return h.href?o.jsxs("a",{href:h.href,className:"flex items-center gap-2 px-3 py-2 text-sm border-b border-border hover:bg-bg-tertiary transition-colors",children:[h.icon,h.label]},c):o.jsxs("button",{type:"button",onClick:()=>{var p;(p=h.onClick)==null||p.call(h),l(!1)},className:"flex items-center gap-2 px-3 py-2 text-sm w-full text-left border-b border-border hover:bg-bg-tertiary transition-colors",children:[h.icon,h.label]},c)})})]})}function lC({projects:e,currentProject:r}){const s=Ft(u=>u.loadProject),l=[...e].sort((u,h)=>u.name.localeCompare(h.name)).map(u=>({label:u.name,icon:u.id===r.id?o.jsx(Ur,{}):void 0,href:`/p/${u.id}`,onClick:()=>{s(u.id)}}));return o.jsx(xo,{items:l,trigger:o.jsxs("button",{className:"text-text-secondary hover:text-text-primary hover:underline text-sm truncate flex items-center gap-1",title:r.name,children:[r.name,o.jsx(xr,{})]}),minWidth:"250px"})}function cC({currentProject:e,sessions:r,currentSession:s,projectIdFromUrl:i}){if(!(e!=null&&e.id)||e.id!==i)return null;const l=r.filter(h=>h.projectId===e.id).sort((h,c)=>new Date(c.updatedAt).getTime()-new Date(h.updatedAt).getTime()).slice(0,5),u=[{label:o.jsxs(Fn,{href:`/p/${e.id}/new`,className:"flex items-center gap-2",children:[o.jsx(Wb,{className:"w-3 h-3 text-accent-primary"}),o.jsx("span",{className:"text-sm",children:"New Session"})]})},...l.map(h=>({label:o.jsx(Fn,{href:`/p/${e.id}/s/${h.id}`,className:"flex items-center gap-2 truncate text-sm",children:o.jsx("span",{children:h.title??h.id.slice(0,8)})}),icon:h.id===(s==null?void 0:s.id)?o.jsx(Ur,{className:"w-3 h-3"}):void 0})),{label:o.jsxs(Fn,{href:"/",className:"flex items-center gap-2 text-text-muted hover:text-text-primary",children:[o.jsx(mw,{className:"w-3 h-3"}),o.jsx("span",{className:"text-sm",children:"Projects"})]})}];return o.jsx(oC,{items:u,trigger:o.jsx("span",{className:"text-sm text-text-secondary font-medium",children:e.name})})}function uC({sessions:e,currentProject:r,currentSession:s,isOpen:i,onOpenChange:l}){var g;const u=Ce(m=>m.loadSession),h=e.filter(m=>m.projectId===r.id).slice(0,15),c=ay(h),d=H.useMemo(()=>{const m=[];m.push({label:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Wb,{className:"w-4 h-4 text-accent-primary"}),o.jsx("span",{className:"text-sm",children:"New session"})]}),href:`/p/${r.id}/new`,onClick:()=>{}});for(const[b,_]of c){const k=_[0];if(k){m.push({label:o.jsx("div",{className:"px-3 py-2 text-text-muted text-xs font-medium cursor-default",children:sy(k.updatedAt)}),onClick:()=>{}});for(const C of _)m.push({label:o.jsxs("div",{className:"min-w-[160px]",children:[o.jsx("div",{className:"truncate text-sm",children:C.title??C.id.slice(0,8)}),o.jsx("div",{className:"text-text-muted text-xs",children:dc(C.updatedAt)})]}),icon:C.id===(s==null?void 0:s.id)?o.jsx(Ur,{}):void 0,href:`/p/${r.id}/s/${C.id}`,onClick:()=>{u(C.id)}})}}return m},[r.id,c,s==null?void 0:s.id]),p=s?((g=s.metadata)==null?void 0:g.title)??s.id.slice(0,8):"No session selected";return o.jsx(xo,{items:d,isOpen:i,onOpenChange:l,trigger:o.jsxs("button",{className:"text-text-secondary hover:text-text-primary hover:underline text-sm truncate flex items-center gap-1",title:p,"data-testid":"header-session-dropdown",children:[p,o.jsx(xr,{})]}),minWidth:"280px"})}function dC({onMenuClick:e,onCriteriaToggle:r}){const[s,i]=H.useState(!1),[l,u]=H.useState(!1),[h,c]=H.useState(!!document.fullscreenElement);H.useEffect(()=>{const T=()=>c(!!document.fullscreenElement);return document.addEventListener("fullscreenchange",T),()=>document.removeEventListener("fullscreenchange",T)},[]);const[d]=vr(),p=d.startsWith("/p/"),g=/^\/p\/[^/]+\/s\/[^/]+$/.test(d),m=Ce(T=>T.currentSession),b=Ce(T=>T.sessions),_=Ft(T=>T.currentProject),k=Ft(T=>T.projects),C=Lt(T=>T.startAutoRefresh),y=Lt(T=>T.stopAutoRefresh),v=ir(T=>T.setOpen),x=ir(T=>T.isOpen);H.useEffect(()=>{const T=()=>u(!0);return window.addEventListener("open-session-dropdown",T),()=>window.removeEventListener("open-session-dropdown",T)},[]);const S=H.useCallback(()=>{const T=document.querySelector('textarea[placeholder*="What would you like to build"], textarea[placeholder*="Send a message"]');T&&T.focus()},[]),j=H.useRef(0);return H.useEffect(()=>{const T=N=>{if(N.key==="Control"&&!N.shiftKey&&!N.metaKey&&!N.altKey){const D=Date.now();D-j.current<300?(N.preventDefault(),N.stopPropagation(),ir.getState().toggleOpen(),j.current=0):j.current=D}};return window.addEventListener("keydown",T,!0),()=>window.removeEventListener("keydown",T,!0)},[]),H.useEffect(()=>(C(),()=>y()),[C,y]),o.jsxs("header",{className:"h-8 bg-secondary border-b border-border flex items-center justify-between px-2",children:[o.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[e&&p&&o.jsx("button",{onClick:e,className:"flex-shrink-0 p-2.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:"Toggle session list",children:o.jsx(Zx,{})}),o.jsx(Fn,{href:"/",className:"text-accent-primary font-semibold text-base hover:underline flex-shrink-0 hidden md:inline",children:"OpenFox"}),_&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"hidden md:inline text-text-muted flex-shrink-0",children:"/"}),o.jsx("span",{className:"hidden md:inline",children:o.jsx(lC,{projects:k,currentProject:_})}),o.jsx("span",{className:"md:hidden",children:o.jsx(cC,{currentProject:_,sessions:b,currentSession:m,projectIdFromUrl:p&&d.split("/")[2]||null},_==null?void 0:_.id)}),o.jsx("span",{className:"hidden md:inline text-text-muted flex-shrink-0",children:"/"}),o.jsx("span",{className:"hidden md:inline",children:o.jsx(uC,{sessions:b,currentProject:_,currentSession:m,isOpen:l,onOpenChange:u})})]})]}),o.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[g&&o.jsx("button",{onClick:()=>{var T,N,D;document.fullscreenElement?(T=document.exitFullscreen)==null||T.call(document):(D=(N=document.documentElement).requestFullscreen)==null||D.call(N)},className:"max-sm:block hidden p-2 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:h?"Exit fullscreen":"Enter fullscreen",children:h?o.jsx(bw,{}):o.jsx(yw,{})}),p&&o.jsx("button",{onClick:()=>v(!x),className:`p-2.5 rounded hover:bg-bg-tertiary transition-colors ${x?"text-accent-primary":"text-text-muted hover:text-text-primary"}`,title:"Toggle terminal (double Ctrl)",children:o.jsx(Lw,{})}),o.jsx("button",{onClick:()=>i(!0),className:"p-2.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:"Settings",children:o.jsx(Nw,{})}),o.jsx("button",{onClick:()=>{localStorage.removeItem("openfox_token"),window.location.reload()},className:"p-2.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:"Logout",children:o.jsx(ww,{})}),r&&g&&o.jsx("button",{onClick:r,className:"p-2.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:"Toggle summary sidebar",children:o.jsx(Zx,{})})]}),o.jsx(Vw,{isOpen:s,onClose:()=>i(!1)}),o.jsx(sC,{isOpen:x,onClose:()=>v(!1),onFocusChat:S})]})}function hC({isOpen:e,onClose:r,title:s,label:i,description:l,placeholder:u,value:h,isLoading:c=!1,onSave:d}){const[p,g]=H.useState(h),[m,b]=H.useState(!1),[_,k]=H.useState(!1);H.useEffect(()=>{g(h),b(!1)},[h]);const C=S=>{g(S.target.value),b(!0)},y=async()=>{k(!0),await d(p),k(!1),b(!1),r()},v=()=>{g(h),b(!1),r()},x=c||_;return o.jsx(jt,{isOpen:e,onClose:v,title:s,size:"lg",children:o.jsxs("div",{className:"flex flex-col h-full -mt-1",children:[o.jsx("label",{className:"block text-sm font-medium text-text-primary mb-1 flex-shrink-0",children:i}),o.jsx("p",{className:"text-sm text-text-muted mb-3 flex-shrink-0",children:l}),o.jsx("div",{className:"flex-1 min-h-[150px]",children:o.jsx("textarea",{value:p,onChange:C,placeholder:u,className:"w-full h-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-none focus:outline-none focus:ring-1 focus:ring-accent-primary",disabled:x})}),m&&o.jsx(Vh,{}),o.jsxs("div",{className:"flex justify-end gap-2 pt-2 border-t border-border flex-shrink-0",children:[o.jsx(st,{variant:"secondary",onClick:v,children:"Cancel"}),o.jsx(st,{variant:"primary",onClick:y,disabled:!m||x,children:_?"Saving...":"Save"})]})]})})}function fC({isOpen:e,onClose:r,project:s}){const i=Ft(u=>u.updateProject),l=async u=>{i(s.id,{customInstructions:u||null}),await new Promise(h=>setTimeout(h,100))};return o.jsx(hC,{isOpen:e,onClose:r,title:`${s.name} Settings`,label:"Project Instructions",description:"These instructions are injected into prompts when working in this project. They are applied after global instructions but before AGENTS.md files.",placeholder:"Enter project-specific instructions...",value:s.customInstructions??"",onSave:l})}const pC={sm:"w-3 h-3",md:"w-4 h-4",lg:"w-5 h-5",xl:"w-6 h-6"},mC="M6 18L18 6M6 6l12 12";function ao({onClick:e,className:r="",size:s="md",variant:i="default"}){const l=i==="overlay"?"bg-accent-error text-white rounded-full flex items-center justify-center hover:bg-accent-error/80 transition-colors":i==="sidebar"?"flex-shrink-0 p-2.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors":i==="modal"?"text-text-muted hover:text-text-primary transition-colors":"hover:text-white transition-colors";return o.jsx(uc,{onClick:e,icon:mC,iconSize:pC[s],className:`${l} ${r}`,title:"Close"})}function oy({projectId:e,isOpen:r=!0,onClose:s}){const[,i]=vr(),[l,u]=H.useState(!1),h=Ce(j=>j.sessions),c=Ce(j=>j.currentSession),d=Ce(j=>j.unreadSessionIds),p=Ce(j=>j.deleteSession),g=Ce(j=>j.deleteAllSessions),m=Ce(j=>j.loadMoreSessions),b=Ce(j=>j.sessionsHasMore),_=Ce(j=>j.sessionsPaginationLoading),k=Ft(j=>j.currentProject),C=H.useRef(null),y=H.useCallback(()=>{b&&!_&&k&&m(k.id)},[b,_,k,m]);H.useEffect(()=>{if(!C.current||!b)return;const j=new IntersectionObserver(T=>{const N=T[0];N&&N.isIntersecting&&y()},{threshold:.1});return j.observe(C.current),()=>j.disconnect()},[b,y]);const v=h.filter(j=>j.projectId===(k==null?void 0:k.id)),x=(j,T)=>{T==null||T.stopPropagation(),confirm("Delete this session?")&&(p(j),(c==null?void 0:c.id)===j&&i(`/p/${e}`))},S=()=>{confirm("Delete all sessions in this project? This cannot be undone.")&&(g(e),i(`/p/${e}`))};return o.jsxs(o.Fragment,{children:[r&&s&&o.jsx("div",{className:"md:hidden fixed inset-0 bg-black/50 z-40",onClick:s}),o.jsxs("aside",{className:`
76
+ */var Jw=2,eC=1,tC=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let r=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(r._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){var m;if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let r=this._terminal.options.scrollback===0?0:((m=this._terminal.options.overviewRuler)==null?void 0:m.width)||14,s=window.getComputedStyle(this._terminal.element.parentElement),i=parseInt(s.getPropertyValue("height")),l=Math.max(0,parseInt(s.getPropertyValue("width"))),u=window.getComputedStyle(this._terminal.element),h={top:parseInt(u.getPropertyValue("padding-top")),bottom:parseInt(u.getPropertyValue("padding-bottom")),right:parseInt(u.getPropertyValue("padding-right")),left:parseInt(u.getPropertyValue("padding-left"))},c=h.top+h.bottom,d=h.right+h.left,p=i-c,g=l-d-r;return{cols:Math.max(Jw,Math.floor(g/e.css.cell.width)),rows:Math.max(eC,Math.floor(p/e.css.cell.height))}}};function nC({sessionId:e,onClose:r,onEscape:s,autoFocus:i}){const l=H.useRef(null),u=H.useRef(e),h=H.useRef(null),c=H.useRef(null),d=ir(g=>g.writeSession),p=ir(g=>g.resizeSession);return H.useEffect(()=>{u.current=e},[e]),H.useEffect(()=>{if(!s)return;const g=m=>{m.key==="Escape"&&(m.preventDefault(),m.stopPropagation(),s())};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[s]),H.useEffect(()=>{if(!l.current)return;const g=new Qw.Terminal({fontFamily:'"JetBrains Mono", monospace',fontSize:13,theme:{background:"#1a1a1a",foreground:"#e0e0e0",cursor:"#ffffff",cursorAccent:"#1a1a1a"},cursorBlink:!0,cursorStyle:"bar",convertEol:!0}),m=new tC;g.loadAddon(m),h.current={term:g,fitAddon:m},l.current.addEventListener("keydown",C=>{C.key==="Escape"&&s&&(C.preventDefault(),C.stopPropagation(),s())}),g.open(l.current);const b=l.current.querySelector(".xterm");b&&(b.style.padding="8px"),m.fit(),i&&setTimeout(()=>{g.focus()},150);const _=new ResizeObserver(()=>{c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{requestAnimationFrame(()=>{var y;m.fit&&m.fit();const C=(y=h.current)==null?void 0:y.term;C&&C.cols>0&&C.rows>0&&p(u.current,C.cols,C.rows)})},100)});_.observe(l.current),g.onData(C=>{if(C==="\x1B"&&s){s();return}d(u.current,C)}),g.onKey(C=>{C.key==="\x1B"&&s&&(C.domEvent.stopPropagation(),s())});const k=Gt.subscribe(C=>{var y,v;if(C.type==="terminal.output"&&((y=C.payload)==null?void 0:y.sessionId)===u.current){const x=(v=C.payload)==null?void 0:v.data;x&&g.write(x)}});return()=>{k(),_.disconnect(),c.current&&clearTimeout(c.current),g.dispose(),h.current=null}},[e,d,p]),o.jsxs("div",{className:"flex flex-col h-full bg-[#1a1a1a]",children:[o.jsxs("div",{className:"flex-shrink-0 flex items-center justify-between px-2 py-1 bg-[#252525] border-b border-[#333]",children:[o.jsx("div",{}),o.jsx("button",{onClick:r,className:"p-1 rounded hover:bg-[#333] text-[#888] hover:text-[#ccc] transition-colors",title:"Close terminal",children:o.jsx(Ow,{})})]}),o.jsx("div",{ref:l,className:"flex-1 relative overflow-hidden",tabIndex:0,onKeyDown:g=>{g.key==="Escape"&&s&&(g.preventDefault(),g.stopPropagation(),s())}})]})}function rC(e){return e===1?"grid-cols-1":e===2?"grid-cols-1 lg:grid-cols-2":"grid-cols-1 lg:grid-cols-2 xl:grid-cols-3"}function sC({isOpen:e,onClose:r,onFocusChat:s}){const i=ir(C=>C.createSession),l=ir(C=>C.killSession),u=ir(C=>C.sessions),h=ir(C=>C.setWorkdir),c=ir(C=>C.fetchSessions),d=Ft(C=>C.currentProject),[p,g]=H.useState(!0),m=H.useRef(null),b=H.useRef(!1),_=H.useRef(!1),k=H.useCallback(()=>{r(),s()},[r,s]);return H.useEffect(()=>{d!=null&&d.workdir&&h(d.workdir)},[d==null?void 0:d.workdir,h]),H.useEffect(()=>{e&&(g(!0),c(d==null?void 0:d.id).finally(()=>g(!1)))},[e,c,d==null?void 0:d.id]),H.useEffect(()=>{e&&u.length===0&&!p&&!_.current&&(_.current=!0,i(void 0,d==null?void 0:d.id))},[e,u.length,p,i,d==null?void 0:d.id]),H.useEffect(()=>{e?(b.current=!0,setTimeout(()=>{var C;(C=m.current)==null||C.focus(),setTimeout(()=>{b.current=!1},200)},100)):_.current=!1},[e]),H.useEffect(()=>{if(!e)return;const C=y=>{b.current||y.key==="Escape"&&(y.preventDefault(),r(),s())};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[e,r,s]),e?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"fixed inset-x-0 top-[50vh] bottom-0 z-[100] bg-black/40",style:{pointerEvents:"auto"},onClick:k}),o.jsxs("div",{ref:m,tabIndex:-1,className:"fixed inset-x-0 top-0 z-[100] h-[50vh] bg-bg-primary border-b border-border flex flex-col animate-slide-down outline-none",onClick:C=>C.stopPropagation(),onKeyDown:C=>{C.key==="Escape"&&(C.preventDefault(),k())},children:[o.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-border",children:[o.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:"Terminal"}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("button",{onClick:()=>i(void 0,d==null?void 0:d.id),className:"p-2 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:"New terminal",children:o.jsx(Ew,{})}),o.jsx("button",{onClick:()=>{r(),s()},className:"p-2 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:"Close (Esc)",children:o.jsx(Ph,{})})]})]}),o.jsx("div",{className:"flex-1 min-h-0 p-2 overflow-auto",children:p?o.jsx("div",{className:"flex items-center justify-center h-full text-text-muted",children:"Loading..."}):u.length===0?o.jsx("div",{className:"flex items-center justify-center h-full text-text-muted",children:o.jsxs("div",{className:"text-center",children:[o.jsx("p",{className:"mb-4",children:"No terminal sessions"}),o.jsx("button",{onClick:()=>i(void 0,d==null?void 0:d.id),className:"px-4 py-2 bg-accent-primary/25 text-text-primary rounded hover:bg-accent-primary/40 transition-colors",children:"Create Terminal"})]})}):o.jsx("div",{className:`grid ${rC(u.length)} gap-2 h-full auto-rows-fr`,children:u.map(C=>o.jsx(nC,{sessionId:C.id,onClose:()=>l(C.id),onEscape:k,autoFocus:u.length===1},C.id))})})]})]}):null}function xo({items:e,trigger:r,minWidth:s="120px",isOpen:i,onOpenChange:l}){const[u,h]=H.useState(!1),c=i!==void 0,d=c?i:u,p=O=>{if(c){const q=typeof O=="function"?O(u):O;l==null||l(q)}else h(O)},[g,m]=H.useState(null),b=H.useRef(null),_=H.useRef(null),[k,C]=H.useState(0),y=H.useRef(0),v=H.useRef(e),x=H.useCallback(()=>{if(!b.current)return;const O=b.current.getBoundingClientRect(),q=200,W=window.innerHeight-O.bottom<q;m({top:W?O.top-q-4:O.bottom+4,left:O.left,alignToTop:W})},[]);H.useEffect(()=>{v.current=e},[e]),H.useEffect(()=>{function O(q){_.current&&!_.current.contains(q.target)&&p(!1)}return d&&document.addEventListener("mousedown",O),()=>{document.removeEventListener("mousedown",O)}},[d]),H.useEffect(()=>{d&&x()},[d,x]),H.useEffect(()=>{if(!d)return;setTimeout(()=>{var q;(q=_.current)==null||q.focus()},0);function O(q){const G=v.current,W=G.filter($=>!S($)),I=j(y.current,G);switch(q.key){case"ArrowDown":if(q.preventDefault(),q.stopPropagation(),I<W.length-1){const $=T(y.current+1,G);y.current=$,C($)}break;case"ArrowUp":if(q.preventDefault(),q.stopPropagation(),I>0){const $=N(y.current-1,G);y.current=$,C($)}break;case"Enter":q.preventDefault(),q.stopPropagation(),D(y.current,G);break;case"Escape":q.preventDefault(),q.stopPropagation(),p(!1);break}}return window.addEventListener("keydown",O,!0),()=>window.removeEventListener("keydown",O,!0)},[d,e]);function S(O){var W;const q=O.label;return q?String(((W=q.props)==null?void 0:W.className)??"").includes("cursor-default"):!1}function j(O,q){let G=0;for(let W=0;W<O;W++){const I=q[W];I&&!S(I)&&G++}return G}function T(O,q){for(let G=O;G<q.length;G++){const W=q[G];if(W&&!S(W))return G}return O}function N(O,q){for(let G=O;G>=0;G--){const W=q[G];if(W&&!S(W))return G}return O}function D(O,q){var W;const G=q[O];!G||S(G)||((W=G.onClick)==null||W.call(G),G.href&&(window.history.pushState(null,"",G.href),window.dispatchEvent(new PopStateEvent("popstate"))),p(!1))}H.useEffect(()=>{d&&(C(e.findIndex(O=>!S(O))),y.current=e.findIndex(O=>!S(O)))},[d,e]);const A=O=>{O.stopPropagation(),d||x(),p(!d)},z=g&&o.jsx("div",{ref:_,"data-testid":"session-dropdown-menu",className:`fixed bg-bg-secondary border border-border rounded shadow-lg z-50 ${g.alignToTop?"mb-1":"mt-1"}`,style:{top:g.top,left:g.left,minWidth:s},tabIndex:-1,children:e.map((O,q)=>{const W=!S(O)&&q===k,I=o.jsxs(o.Fragment,{children:[O.icon&&o.jsx("span",{className:"w-4 h-4 flex-shrink-0",children:O.icon}),O.label]});return O.href?o.jsx(Fn,{href:O.href,onClick:$=>{var B;(B=O.onClick)==null||B.call(O,$),p(!1)},className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 transition-colors ${O.danger?"text-accent-error hover:bg-accent-error/10":W?"bg-accent-primary/20 text-text-primary":"hover:bg-bg-tertiary text-text-primary"} ${q!==e.length-1?"border-b border-border":""}`,children:I},q):o.jsx("button",{onClick:$=>{var B;(B=O.onClick)==null||B.call(O,$),O.closeOnClick!==!1&&p(!1)},className:`w-full px-3 py-2 text-left text-sm flex items-center gap-2 transition-colors ${O.danger?"text-accent-error hover:bg-accent-error/10":W?"bg-accent-primary/20 text-text-primary":"hover:bg-bg-tertiary text-text-primary"} ${q!==e.length-1?"border-b border-border":""}`,children:I},q)})});return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"relative",children:o.jsx("div",{ref:b,onClick:A,children:r})}),d&&go.createPortal(z,document.body)]})}function sy(e){const r=new Date(e),i=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][r.getDay()],l=r.getFullYear(),u=String(r.getMonth()+1).padStart(2,"0"),h=String(r.getDate()).padStart(2,"0");return`${i} ${l}/${u}/${h}`}function dc(e){const r=new Date(e),s=String(r.getHours()).padStart(2,"0"),i=String(r.getMinutes()).padStart(2,"0");return`${s}:${i}`}function iC(e){const r=new Date(e),s=new Date,i=new Date(s.getFullYear(),s.getMonth(),s.getDate()),l=new Date(r.getFullYear(),r.getMonth(),r.getDate()),u=Math.floor((i.getTime()-l.getTime())/(1e3*60*60*24)),h=dc(e);if(u===0)return`today ${h}`;if(u===1)return`yesterday ${h}`;if(u<7)return`${u} days ago ${h}`;{const c=r.getFullYear(),d=String(r.getMonth()+1).padStart(2,"0"),p=String(r.getDate()).padStart(2,"0");return`${c}/${d}/${p} ${h}`}}function iy(e){const r=new Date(e);return{year:r.getFullYear(),month:String(r.getMonth()+1).padStart(2,"0"),day:String(r.getDate()).padStart(2,"0")}}function aC(e){const{year:r,month:s,day:i}=iy(e);return`${r}-${s}-${i}`}function ay(e){const r=new Map;for(const l of e){const u=aC(l.updatedAt);r.has(u)||r.set(u,[]),r.get(u).push(l)}for(const[l,u]of r)u.sort((h,c)=>{const d=new Date(h.updatedAt).getTime();return new Date(c.updatedAt).getTime()-d});const s=Array.from(r.keys()).sort((l,u)=>u.localeCompare(l)),i=new Map;for(const l of s)i.set(l,r.get(l));return i}function oC({items:e,trigger:r,isActive:s=!1}){const[i,l]=H.useState(!1),u=H.useRef(null);return H.useEffect(()=>{function h(c){u.current&&!u.current.contains(c.target)&&l(!1)}if(i)return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[i]),o.jsxs("div",{className:"relative",ref:u,children:[o.jsxs("button",{type:"button",onClick:()=>l(!i),className:`flex items-center gap-1 px-1.5 py-0.5 rounded transition-colors ${s?"bg-bg-tertiary":"hover:bg-bg-tertiary"}`,children:[typeof r=="string"?o.jsx("span",{className:"text-sm text-text-secondary font-medium",children:r}):r,o.jsx(xr,{className:"w-3 h-3 text-text-muted flex-shrink-0 transition-transform",rotate:i?180:0})]}),i&&e.length>0&&o.jsx("div",{className:"absolute top-full left-0 mt-1 w-56 bg-bg-secondary border border-border rounded-lg shadow-lg overflow-hidden z-50",children:e.map((h,c)=>{const d=h.label&&typeof h.label=="object"&&h.label.type===Fn?h.label:null;if(d){const p=d.props.href||"";return o.jsxs(Fn,{href:p,className:"flex items-center gap-2 px-3 py-2 text-sm border-b border-border hover:bg-bg-tertiary transition-colors",children:[h.icon,d.props.children]},c)}return h.href?o.jsxs("a",{href:h.href,className:"flex items-center gap-2 px-3 py-2 text-sm border-b border-border hover:bg-bg-tertiary transition-colors",children:[h.icon,h.label]},c):o.jsxs("button",{type:"button",onClick:()=>{var p;(p=h.onClick)==null||p.call(h),l(!1)},className:"flex items-center gap-2 px-3 py-2 text-sm w-full text-left border-b border-border hover:bg-bg-tertiary transition-colors",children:[h.icon,h.label]},c)})})]})}function lC({projects:e,currentProject:r}){const s=Ft(u=>u.loadProject),l=[...e].sort((u,h)=>u.name.localeCompare(h.name)).map(u=>({label:u.name,icon:u.id===r.id?o.jsx(Ur,{}):void 0,href:`/p/${u.id}`,onClick:()=>{s(u.id)}}));return o.jsx(xo,{items:l,trigger:o.jsxs("button",{className:"text-text-secondary hover:text-text-primary hover:underline text-sm truncate flex items-center gap-1",title:r.name,children:[r.name,o.jsx(xr,{})]}),minWidth:"250px"})}function cC({currentProject:e,sessions:r,currentSession:s,projectIdFromUrl:i}){if(!(e!=null&&e.id)||e.id!==i)return null;const l=r.filter(h=>h.projectId===e.id).sort((h,c)=>new Date(c.updatedAt).getTime()-new Date(h.updatedAt).getTime()).slice(0,5),u=[{label:o.jsxs(Fn,{href:`/p/${e.id}/new`,className:"flex items-center gap-2",children:[o.jsx(Wb,{className:"w-3 h-3 text-accent-primary"}),o.jsx("span",{className:"text-sm",children:"New Session"})]})},...l.map(h=>({label:o.jsx(Fn,{href:`/p/${e.id}/s/${h.id}`,className:"flex items-center gap-2 truncate text-sm",children:o.jsx("span",{children:h.title??h.id.slice(0,8)})}),icon:h.id===(s==null?void 0:s.id)?o.jsx(Ur,{className:"w-3 h-3"}):void 0})),{label:o.jsxs(Fn,{href:"/",className:"flex items-center gap-2 text-text-muted hover:text-text-primary",children:[o.jsx(mw,{className:"w-3 h-3"}),o.jsx("span",{className:"text-sm",children:"Projects"})]})}];return o.jsx(oC,{items:u,trigger:o.jsx("span",{className:"text-sm text-text-secondary font-medium",children:e.name})})}function uC({sessions:e,currentProject:r,currentSession:s,isOpen:i,onOpenChange:l}){var g;const u=Ce(m=>m.loadSession),h=e.filter(m=>m.projectId===r.id).slice(0,15),c=ay(h),d=H.useMemo(()=>{const m=[];m.push({label:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Wb,{className:"w-4 h-4 text-accent-primary"}),o.jsx("span",{className:"text-sm",children:"New session"})]}),href:`/p/${r.id}/new`,onClick:()=>{}});for(const[b,_]of c){const k=_[0];if(k){m.push({label:o.jsx("div",{className:"px-3 py-2 text-text-muted text-xs font-medium cursor-default",children:sy(k.updatedAt)}),onClick:()=>{}});for(const C of _)m.push({label:o.jsxs("div",{className:"min-w-[160px]",children:[o.jsx("div",{className:"truncate text-sm",children:C.title??C.id.slice(0,8)}),o.jsx("div",{className:"text-text-muted text-xs",children:dc(C.updatedAt)})]}),icon:C.id===(s==null?void 0:s.id)?o.jsx(Ur,{}):void 0,href:`/p/${r.id}/s/${C.id}`,onClick:()=>{u(C.id)}})}}return m},[r.id,c,s==null?void 0:s.id]),p=s?((g=s.metadata)==null?void 0:g.title)??s.id.slice(0,8):"No session selected";return o.jsx(xo,{items:d,isOpen:i,onOpenChange:l,trigger:o.jsxs("button",{className:"text-text-secondary hover:text-text-primary hover:underline text-sm truncate flex items-center gap-1",title:p,"data-testid":"header-session-dropdown",children:[p,o.jsx(xr,{})]}),minWidth:"280px"})}function dC({onMenuClick:e,onCriteriaToggle:r}){const[s,i]=H.useState(!1),[l,u]=H.useState(!1),[h,c]=H.useState(!!document.fullscreenElement);H.useEffect(()=>{const T=()=>c(!!document.fullscreenElement);return document.addEventListener("fullscreenchange",T),()=>document.removeEventListener("fullscreenchange",T)},[]);const[d]=vr(),p=d.startsWith("/p/"),g=/^\/p\/[^/]+\/s\/[^/]+$/.test(d),m=Ce(T=>T.currentSession),b=Ce(T=>T.sessions),_=Ft(T=>T.currentProject),k=Ft(T=>T.projects),C=Lt(T=>T.startAutoRefresh),y=Lt(T=>T.stopAutoRefresh),v=ir(T=>T.setOpen),x=ir(T=>T.isOpen);H.useEffect(()=>{const T=()=>u(!0);return window.addEventListener("open-session-dropdown",T),()=>window.removeEventListener("open-session-dropdown",T)},[]);const S=H.useCallback(()=>{const T=document.querySelector('textarea[placeholder*="What would you like to build"], textarea[placeholder*="Send a message"]');T&&T.focus()},[]),j=H.useRef(0);return H.useEffect(()=>{const T=N=>{if(N.key==="Control"&&!N.shiftKey&&!N.metaKey&&!N.altKey){const D=Date.now();D-j.current<300?(N.preventDefault(),N.stopPropagation(),ir.getState().toggleOpen(),j.current=0):j.current=D}};return window.addEventListener("keydown",T,!0),()=>window.removeEventListener("keydown",T,!0)},[]),H.useEffect(()=>(C(),()=>y()),[C,y]),o.jsxs("header",{className:"h-8 bg-secondary border-b border-border flex items-center justify-between px-2",children:[o.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[e&&p&&o.jsx("button",{onClick:e,className:"flex-shrink-0 p-2.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:"Toggle session list",children:o.jsx(Zx,{})}),o.jsx(Fn,{href:"/",className:"text-accent-primary font-semibold text-base hover:underline flex-shrink-0 hidden md:inline",children:"OpenFox"}),_&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"hidden md:inline text-text-muted flex-shrink-0",children:"/"}),o.jsx("span",{className:"hidden md:inline",children:o.jsx(lC,{projects:k,currentProject:_})}),o.jsx("span",{className:"md:hidden",children:o.jsx(cC,{currentProject:_,sessions:b,currentSession:m,projectIdFromUrl:p&&d.split("/")[2]||null},_==null?void 0:_.id)}),o.jsx("span",{className:"hidden md:inline text-text-muted flex-shrink-0",children:"/"}),o.jsx("span",{className:"hidden md:inline",children:o.jsx(uC,{sessions:b,currentProject:_,currentSession:m,isOpen:l,onOpenChange:u})})]})]}),o.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[g&&o.jsx("button",{onClick:()=>{var T,N,D;document.fullscreenElement?(T=document.exitFullscreen)==null||T.call(document):(D=(N=document.documentElement).requestFullscreen)==null||D.call(N)},className:"max-sm:block hidden p-2 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:h?"Exit fullscreen":"Enter fullscreen",children:h?o.jsx(bw,{}):o.jsx(yw,{})}),p&&o.jsx("button",{onClick:()=>v(!x),className:`p-2.5 rounded hover:bg-bg-tertiary transition-colors ${x?"text-accent-primary":"text-text-muted hover:text-text-primary"}`,title:"Toggle terminal (double Ctrl)",children:o.jsx(Lw,{})}),o.jsx("button",{onClick:()=>i(!0),className:"p-2.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:"Settings",children:o.jsx(Nw,{})}),o.jsx("button",{onClick:()=>{localStorage.removeItem("openfox_token"),window.location.reload()},className:"p-2.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:"Logout",children:o.jsx(ww,{})}),r&&g&&o.jsx("button",{onClick:r,className:"p-2.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:"Toggle summary sidebar",children:o.jsx(Zx,{})})]}),o.jsx(Vw,{isOpen:s,onClose:()=>i(!1)}),o.jsx(sC,{isOpen:x,onClose:()=>v(!1),onFocusChat:S})]})}function hC({isOpen:e,onClose:r,title:s,label:i,description:l,placeholder:u,value:h,isLoading:c=!1,onSave:d}){const[p,g]=H.useState(h),[m,b]=H.useState(!1),[_,k]=H.useState(!1);H.useEffect(()=>{g(h),b(!1)},[h]);const C=S=>{g(S.target.value),b(!0)},y=async()=>{k(!0),await d(p),k(!1),b(!1),r()},v=()=>{g(h),b(!1),r()},x=c||_;return o.jsx(jt,{isOpen:e,onClose:v,title:s,size:"lg",children:o.jsxs("div",{className:"flex flex-col h-full -mt-1",children:[o.jsx("label",{className:"block text-sm font-medium text-text-primary mb-1 flex-shrink-0",children:i}),o.jsx("p",{className:"text-sm text-text-muted mb-3 flex-shrink-0",children:l}),o.jsx("div",{className:"flex-1 min-h-[150px]",children:o.jsx("textarea",{value:p,onChange:C,placeholder:u,className:"w-full h-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-none focus:outline-none focus:ring-1 focus:ring-accent-primary",disabled:x})}),m&&o.jsx(Vh,{}),o.jsxs("div",{className:"flex justify-end gap-2 pt-2 border-t border-border flex-shrink-0",children:[o.jsx(st,{variant:"secondary",onClick:v,children:"Cancel"}),o.jsx(st,{variant:"primary",onClick:y,disabled:!m||x,children:_?"Saving...":"Save"})]})]})})}function fC({isOpen:e,onClose:r,project:s}){const i=Ft(u=>u.updateProject),l=async u=>{i(s.id,{customInstructions:u||null}),await new Promise(h=>setTimeout(h,100))};return o.jsx(hC,{isOpen:e,onClose:r,title:`${s.name} Settings`,label:"Project Instructions",description:"These instructions are injected into prompts when working in this project. They are applied after global instructions but before AGENTS.md files.",placeholder:"Enter project-specific instructions...",value:s.customInstructions??"",onSave:l})}const pC={sm:"w-3 h-3",md:"w-4 h-4",lg:"w-5 h-5",xl:"w-6 h-6"},mC="M6 18L18 6M6 6l12 12";function ao({onClick:e,className:r="",size:s="md",variant:i="default"}){const l=i==="overlay"?"bg-accent-error text-white rounded-full flex items-center justify-center hover:bg-accent-error/80 transition-colors":i==="sidebar"?"flex-shrink-0 p-2.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors":i==="modal"?"text-text-muted hover:text-text-primary transition-colors":"hover:text-white transition-colors";return o.jsx(uc,{onClick:e,icon:mC,iconSize:pC[s],className:`${l} ${r}`,title:"Close"})}function oy({projectId:e,isOpen:r=!0,onClose:s}){const[,i]=vr(),[l,u]=H.useState(!1),h=Ce(j=>j.sessions),c=Ce(j=>j.currentSession),d=Ce(j=>j.unreadSessionIds),p=Ce(j=>j.deleteSession),g=Ce(j=>j.deleteAllSessions),m=Ce(j=>j.loadMoreSessions),b=Ce(j=>j.sessionsHasMore),_=Ce(j=>j.sessionsPaginationLoading),k=Ft(j=>j.currentProject),C=H.useRef(null),y=H.useCallback(()=>{b&&!_&&k&&m(k.id)},[b,_,k,m]);H.useEffect(()=>{if(!C.current||!b)return;const j=new IntersectionObserver(T=>{const N=T[0];N&&N.isIntersecting&&y()},{threshold:.1});return j.observe(C.current),()=>j.disconnect()},[b,y]);const v=h.filter(j=>j.projectId===(k==null?void 0:k.id)),x=(j,T)=>{T==null||T.stopPropagation(),confirm("Delete this session?")&&(p(j),(c==null?void 0:c.id)===j&&i(`/p/${e}`))},S=()=>{confirm("Delete all sessions in this project? This cannot be undone.")&&(g(e),i(`/p/${e}`))};return o.jsxs(o.Fragment,{children:[r&&s&&o.jsx("div",{className:"md:hidden fixed inset-0 bg-black/50 z-40",onClick:s}),o.jsxs("aside",{className:`
77
77
  ${r?"md:w-[300px] md:shrink-0":"md:w-0 md:shrink-0 md:overflow-hidden"}
78
78
  md:relative md:h-auto md:translate-x-0
79
79