openfox 1.6.64 → 1.6.65
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{auto-compaction-XYMFQXXX.js → auto-compaction-ASDCDWKT.js} +3 -2
- package/dist/{chat-handler-24P6R3SB.js → chat-handler-647QWEHP.js} +5 -4
- package/dist/{chunk-OXQGLKLE.js → chunk-2F2BUO46.js} +2 -2
- package/dist/{chunk-YF3ERP7E.js → chunk-7XO4OW2P.js} +2 -2
- package/dist/{chunk-JY7BGPTB.js → chunk-A2Q6JCPK.js} +26 -9
- package/dist/chunk-NRUMWHLX.js +294 -0
- package/dist/{chunk-7TMH3MPE.js → chunk-PU4AOT3E.js} +7 -280
- package/dist/cli/dev.js +1 -1
- package/dist/cli/index.js +1 -1
- package/dist/inspect-proxy-M5222JOC.js +10 -0
- package/dist/{orchestrator-TEL2CUIT.js → orchestrator-UEDPSWG6.js} +4 -3
- package/dist/package.json +1 -1
- package/dist/{processor-GSMNLIRM.js → processor-TSSCNWED.js} +2 -2
- package/dist/{serve-55UYT2JO.js → serve-NM33QHGG.js} +5 -4
- package/dist/server/index.js +4 -3
- package/dist/{tools-TSGPRFT2.js → tools-AQEL6ZJG.js} +3 -2
- package/dist/web/__inspect__.js +271 -0
- package/dist/web/assets/{index-BcXvYLYn.js → index-KbZgYzd8.js} +2 -2
- package/dist/web/index.html +1 -1
- package/dist/web/sw.js +1 -1
- package/package.json +1 -1
|
@@ -54,7 +54,7 @@ Error generating stack: `+p.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 Bx;function b1(){if(Bx)return Pd;Bx=1;var e=ac();function r(m,v){return m===v&&(m!==0||1/m===1/v)||m!==m&&v!==v}var s=typeof Object.is=="function"?Object.is:r,i=e.useState,c=e.useEffect,u=e.useLayoutEffect,h=e.useDebugValue;function l(m,v){var S=v(),k=i({inst:{value:S,getSnapshot:v}}),C=k[0].inst,y=k[1];return u(function(){C.value=S,C.getSnapshot=v,d(C)&&y({inst:C})},[m,S,v]),c(function(){return d(C)&&y({inst:C}),m(function(){d(C)&&y({inst:C})})},[m]),h(S),S}function d(m){var v=m.getSnapshot;m=m.value;try{var S=v();return!s(m,S)}catch{return!0}}function f(m,v){return v()}var g=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?f:l;return Pd.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:g,Pd}var zx;function v1(){return zx||(zx=1,zd.exports=b1()),zd.exports}var y1=v1();const _1=i1.useInsertionEffect,S1=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",w1=S1?P.useLayoutEffect:P.useEffect,C1=_1||w1,Av=e=>{const r=P.useRef([e,(...s)=>r[0](...s)]).current;return C1(()=>{r[0]=e}),r[1]},k1="popstate",Rh="pushState",Lh="replaceState",E1="hashchange",Px=[k1,Rh,Lh,E1],j1=e=>{for(const r of Px)addEventListener(r,e);return()=>{for(const r of Px)removeEventListener(r,e)}},Dv=(e,r)=>y1.useSyncExternalStore(j1,e,r),Hx=()=>location.search,N1=({ssrSearch:e}={})=>Dv(Hx,e!=null?()=>e:Hx),Fx=()=>location.pathname,T1=({ssrPath:e}={})=>Dv(Fx,e!=null?()=>e:Fx),A1=(e,{replace:r=!1,state:s=null}={})=>history[r?Lh:Rh](s,"",e),D1=(e={})=>[T1(e),A1],Ux=Symbol.for("wouter_v3");if(typeof history<"u"&&typeof window[Ux]>"u"){for(const e of[Rh,Lh]){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,Ux,{value:!0})}const R1=(e,r)=>r.toLowerCase().indexOf(e.toLowerCase())?"~"+r:r.slice(e.length)||"/",Rv=(e="")=>e==="/"?"":e,L1=(e,r)=>e[0]==="~"?e.slice(1):Rv(r)+e,O1=(e="",r)=>R1($x(Rv(e)),$x(r)),$x=e=>{try{return decodeURI(e)}catch{return e}},Lv={hook:D1,searchHook:N1,parser:x1,base:"",ssrPath:void 0,ssrSearch:void 0,ssrContext:void 0,hrefs:e=>e,aroundNav:(e,r,s)=>e(r,s)},Ov=P.createContext(Lv),Gi=()=>P.useContext(Ov),Mv={},Iv=P.createContext(Mv),M1=()=>P.useContext(Iv),oc=e=>{const[r,s]=e.hook(e);return[O1(e.base,r),Av((i,c)=>e.aroundNav(s,L1(i,e.base),c))]},lr=()=>oc(Gi()),Oh=(e,r,s,i)=>{const{pattern:c,keys:u}=r instanceof RegExp?{keys:!1,pattern:r}:e(r||"*",i),h=c.exec(s)||[],[l,...d]=h;return l!==void 0?[!0,(()=>{const f=u!==!1?Object.fromEntries(u.map((m,v)=>[m,d[v]])):h.groups;let g={...d};return f&&Object.assign(g,f),g})(),...i?[l]:[]]:[!1,null]},Mh=e=>Oh(Gi().parser,e,lr()[0]),I1=({children:e,...r})=>{var g,m,v;const s=Gi(),i=r.hook?Lv:s;let c=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??((v=r.hook)==null?void 0:v.searchHook);let l=P.useRef({}),d=l.current,f=d;for(let S in i){const k=S==="base"?i[S]+(r[S]??""):r[S]??i[S];d===f&&k!==f[S]&&(l.current=f={...f}),f[S]=k,(k!==i[S]||k!==c[S])&&(c=f)}return P.createElement(Ov.Provider,{value:c,children:e})},qx=({children:e,component:r},s)=>r?P.createElement(r,{params:s}):typeof e=="function"?e(s):e,B1=e=>{let r=P.useRef(Mv);const s=r.current;return r.current=Object.keys(e).length!==Object.keys(s).length||Object.entries(e).some(([i,c])=>c!==s[i])?e:s},Ua=({path:e,nest:r,match:s,...i})=>{const c=Gi(),[u]=oc(c),[h,l,d]=s??Oh(c.parser,e,u,r),f=B1({...M1(),...l});if(!h)return null;const g=d?P.createElement(I1,{base:d},qx(i,f)):qx(i,f);return P.createElement(Iv.Provider,{value:f,children:g})},Fn=P.forwardRef((e,r)=>{const s=Gi(),[i,c]=oc(s),{to:u="",href:h=u,onClick:l,asChild:d,children:f,className:g,replace:m,state:v,transition:S,...k}=e,C=Av(b=>{b.ctrlKey||b.metaKey||b.altKey||b.shiftKey||b.button!==0||(l==null||l(b),b.defaultPrevented||(b.preventDefault(),c(h,e)))}),y=s.hrefs(h[0]==="~"?h.slice(1):s.base+h,s);return d&&P.isValidElement(f)?P.cloneElement(f,{onClick:C,href:y}):P.createElement("a",{...k,onClick:C,href:y,className:g!=null&&g.call?g(i===h):g,children:f,ref:r})}),Bv=e=>Array.isArray(e)?e.flatMap(r=>Bv(r&&r.type===P.Fragment?r.props.children:r)):[e],z1=({children:e,location:r})=>{const s=Gi(),[i]=oc(s);for(const c of Bv(e)){let u=0;if(P.isValidElement(c)&&(u=Oh(s.parser,c.props.path,r||i,c.props.nest))[0])return P.cloneElement(c,{match:u})}return null};function P1(e){return typeof e=="object"&&e!==null&&"type"in e&&"payload"in e}function zv(){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 H1{constructor(r){fr(this,"ws",null);fr(this,"handlers",new Set);fr(this,"statusHandler",null);fr(this,"baseUrl");fr(this,"isReconnecting",!1);fr(this,"connectingPromise",null);fr(this,"lastCloseCode",0);fr(this,"reconnectAttempts",0);fr(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,c)=>{try{const u=this.getUrl();this.ws=new WebSocket(u);const h=setTimeout(()=>{var l;((l=this.ws)==null?void 0:l.readyState)===WebSocket.CONNECTING&&(this.ws.close(),c(new Error("Connection timeout")))},5e3);this.ws.onopen=()=>{var l;clearTimeout(h),this.isReconnecting=!1,this.connectingPromise=null,(l=this.statusHandler)==null||l.call(this,"connected"),i()},this.ws.onclose=l=>{var d,f,g;clearTimeout(h),this.lastCloseCode=l.code,((d=this.ws)==null?void 0:d.readyState)===WebSocket.CONNECTING?(this.connectingPromise=null,(f=this.statusHandler)==null||f.call(this,"disconnected"),c(new Error(`Connection closed: ${l.code}`))):(this.connectingPromise=null,(g=this.statusHandler)==null||g.call(this,"disconnected"),this.attemptReconnect())},this.ws.onerror=l=>{clearTimeout(h),console.error("WebSocket error:",l),this.connectingPromise=null,c(l)},this.ws.onmessage=l=>{try{const d=JSON.parse(l.data);P1(d)&&this.handlers.forEach(f=>f(d))}catch(d){console.error("Failed to parse WebSocket message:",d)}}}catch(u){this.connectingPromise=null,c(u)}}),this.connectingPromise))}attemptReconnect(){var c;if(([1e3,1005,1006,4e3].includes(this.lastCloseCode)||this.lastCloseCode===0)&&this.hasToken()){console.log("[WS] Auth failure or initial failure with token - not auto-reconnecting, awaiting user action");return}if(this.isReconnecting||this.manualReconnectScheduled)return;this.isReconnecting=!0,(c=this.statusHandler)==null||c.call(this,"reconnecting");const 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=zv(),c={id:i,type:r,payload:s};return this.ws.send(JSON.stringify(c)),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 F1=`ws://${window.location.hostname}:${window.location.port||"10469"}/ws`,Gt=new H1(F1),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 Pv(e){let r=null;function s(){r===null&&(r=requestAnimationFrame(()=>{r=null,e()}))}return s}let Bl=[];const gr=$n()((e,r)=>{function s(){if(Bl.length===0)return;const c=Bl;Bl=[],e(u=>({logs:[...u.logs,...c]}))}const i=Pv(s);return{workdir:null,status:null,logs:[],config:null,loading:!1,setWorkdir:c=>{r().workdir!==c&&(e({workdir:c,status:null,logs:[],config:null,loading:!0}),c&&(r().fetchStatus(),r().fetchConfig()))},fetchStatus:async()=>{const c=r().workdir;if(c)try{const h=await(await ke(`/api/dev-server?workdir=${encodeURIComponent(c)}`)).json();e({status:h,loading:!1})}catch{e({loading:!1})}},fetchConfig:async()=>{const c=r().workdir;if(c)try{const h=await(await ke(`/api/dev-server/config?workdir=${encodeURIComponent(c)}`)).json();e({config:h.config??null})}catch{}},fetchLogs:async()=>{const c=r().workdir;if(c)try{const l=(await(await ke(`/api/dev-server/logs?workdir=${encodeURIComponent(c)}`)).json()).logs.map(d=>({stream:d.stream,content:d.content}));e({logs:l})}catch{}},start:async()=>{const c=r().workdir;if(c)try{const h=await(await ke(`/api/dev-server/start?workdir=${encodeURIComponent(c)}`,{method:"POST"})).json();e({status:h,logs:[]})}catch{}},stop:async()=>{const c=r().workdir;if(c)try{const h=await(await ke(`/api/dev-server/stop?workdir=${encodeURIComponent(c)}`,{method:"POST"})).json();e({status:h})}catch{}},restart:async()=>{const c=r().workdir;if(c)try{const h=await(await ke(`/api/dev-server/restart?workdir=${encodeURIComponent(c)}`,{method:"POST"})).json();e({status:h,logs:[]})}catch{}},saveConfig:async c=>{const u=r().workdir;if(u)try{const l=await(await ke(`/api/dev-server/config?workdir=${encodeURIComponent(u)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)})).json();e({config:l.config??c}),r().fetchStatus()}catch{}},handleMessage:c=>{const u=r().workdir;if(u)switch(c.type){case"devServer.output":{const h=c.payload;if(h.workdir!==u)return;Bl.push({stream:h.stream,content:h.content}),i();break}case"devServer.state":{const h=c.payload;if(h.workdir!==u)return;e(l=>({status:l.status?{...l.status,state:h.state,errorMessage:h.errorMessage}:l.status}));break}}}}});function U1(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 Wx(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 c=await i.json();throw new Error(c.error??"Failed to update model")}return i.json()}function Vx(e,r,s,i){return e.map(c=>c.id===r?{...c,models:c.models.map(u=>u.id===s?{...u,...i,source:"user"}:u)}:c)}const $1=3e4;function q1(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 Rt=$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:c}=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 l=await u.json();throw new Error(l.error??"Failed to activate provider")}const h=await u.json();return e({activeProviderId:h.activeProviderId,model:h.model,backend:h.backend,providers:c.map(l=>({...l,isActive:l.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:c}=r();e({activeProviderId:s,model:i,defaultModelSelection:`${s}/${i}`,providers:c.map(u=>({...u,isActive:u.id===s}))})},updateModelContext:async(s,i,c)=>{e({activating:!0,error:null});try{const u=await Wx(s,i,{contextWindow:c}),{providers:h}=r();return e({providers:Vx(h,s,i,{contextWindow:c}),activating:!1}),u.contextState&&Ce.getState().updateContextState(u.contextState),!0}catch(u){return e({error:u instanceof Error?u.message:"Failed to update model context",activating:!1}),!1}},updateModelSettings:async(s,i,c)=>{e({activating:!0,error:null});try{const u=await Wx(s,i,c),{providers:h}=r(),l={...c.contextWindow!==void 0&&{contextWindow:c.contextWindow},...U1({temperature:c.temperature??void 0,topP:c.topP??void 0,topK:c.topK??void 0,maxTokens:c.maxTokens??void 0}),...c.supportsVision!==void 0&&{supportsVision:c.supportsVision}};return e({providers:Vx(h,s,i,l),activating:!1}),u.contextState&&Ce.getState().updateContextState(u.contextState),!0}catch(u){return e({error:u instanceof Error?u.message:"Failed to update model settings",activating:!1}),!1}},refreshProviderModels:async 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 c=await i.json(),{providers:u}=r();return e({providers:u.map(h=>h.id===s?{...h,models:c.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 c=setInterval(()=>{i()},$1);e({autoRefreshInterval:c})},stopAutoRefresh:()=>{const{autoRefreshInterval:s}=r();s&&(clearInterval(s),e({autoRefreshInterval:null}))},getActiveProvider:()=>{const{providers:s,activeProviderId:i}=r();return s.find(c=>c.id===i)},getModelContext:s=>{const{providers:i,activeProviderId:c}=r(),u=i.find(l=>l.id===c);if(!u)return 2e5;const h=u.models.find(l=>l.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 c=await ke("/api/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:s,workdir:i})});if(!c.ok)return null;const u=await c.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 c=await i.json();return e({currentProject:c.project}),r().projects.length===0&&await r().listProjects(),c.project}catch{return null}},updateProject:async(s,i)=>{var c;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((c=r().currentProject)==null?void 0:c.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 zl=[];const to=$n()((e,r)=>{function s(){if(zl.length===0)return;const c=zl;zl=[],e(u=>{const h={...u.logs};for(const l of c){const d=h[l.processId]??[];h[l.processId]=[...d,{offset:d.length,content:l.content,timestamp:Date.now(),stream:l.stream}]}return{logs:h}})}const i=Pv(s);return{processes:[],logs:{},loading:!1,setProcesses:c=>e({processes:c}),addProcess:c=>e(u=>({processes:[...u.processes,c]})),updateProcess:(c,u)=>e(h=>({processes:h.processes.map(l=>l.id===c?{...l,...u}:l)})),removeProcess:c=>e(u=>({processes:u.processes.filter(h=>h.id!==c),logs:Object.fromEntries(Object.entries(u.logs).filter(([h])=>h!==c))})),stopProcess:async(c,u)=>{try{(await ke(`/api/sessions/${u}/background-process/${c}/stop`,{method:"POST"})).ok&&r().removeProcess(c)}catch{}},appendLog:(c,u,h)=>{zl.push({processId:c,stream:u,content:h}),i()},setLogs:(c,u)=>e(h=>({logs:{...h.logs,[c]:u}})),clearLogs:c=>e(u=>({logs:{...u.logs,[c]:[]}})),handleMessage:(c,u)=>{switch(c){case"backgroundProcess.started":{const{processId:h,name:l,pid:d,status:f}=u;e(g=>({processes:[...g.processes,{id:h,sessionId:"",name:l,command:"",cwd:"",pid:d,status:f,exitCode:null,createdAt:Date.now(),startedAt:Date.now(),endedAt:null}]}));break}case"backgroundProcess.output":{const h=u.processId,l=u.stream,d=u.content;r().appendLog(h,l,d);break}case"backgroundProcess.exited":{const h=u.processId,l=u.exitCode;e(d=>({processes:d.processes.map(f=>f.id===h?{...f,status:"exited",exitCode:l}:f)}));break}case"backgroundProcess.removed":{const h=u.processId;r().removeProcess(h);break}}}}}),W1=[{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"}],V1=[{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"}],Hv={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},Fv={soundEnabled:!1,browserNotification:!1,customSoundUrl:null},hh={soundEnabled:!0,browserNotificationEnabled:!1,events:{complete:{...ms},waiting_for_user:{...ms},phase_done:{...ms},phase_blocked:{...ms},new_message:{...Fv}},agentOverrides:{}};function Uv(e,r,s){var u;const i=e.events[r];if(!s)return i;const c=(u=e.agentOverrides[s])==null?void 0:u[r];return c?{soundEnabled:c.soundEnabled??i.soundEnabled,browserNotification:c.browserNotification??i.browserNotification,customSoundUrl:c.customSoundUrl!==void 0?c.customSoundUrl:i.customSoundUrl}:i}const Fs=$n((e,r)=>({settings:hh,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 l=JSON.parse(h);e({settings:Gx(l),loaded:!0})}catch{e({loaded:!0})}}),c=Yt.getState().settings[ot.NOTIFICATION_SETTINGS];if(c)try{const u=JSON.parse(c);e({settings:Gx(u),loaded:!0})}catch{e({loaded:!0})}return i},update:s=>{e({settings:s}),Hd(s)},updateEvent:(s,i)=>{const c=r().settings,u={...c,events:{...c.events,[s]:{...c.events[s],...i}}};e({settings:u}),Hd(u)},updateAgentOverride:(s,i,c)=>{var d;const u=r().settings,h={...u.agentOverrides};if(c===null){if(h[s]){const f={...h[s]};delete f[i],Object.keys(f).length===0?delete h[s]:h[s]=f}}else h[s]={...h[s],[i]:{...((d=h[s])==null?void 0:d[i])??{},...c}};const l={...u,agentOverrides:h};e({settings:l}),Hd(l)}}));function Hd(e){Yt.getState().setSetting(ot.NOTIFICATION_SETTINGS,JSON.stringify(e))}function Gx(e){var r,s,i,c,u;return{soundEnabled:e.soundEnabled??hh.soundEnabled,browserNotificationEnabled:e.browserNotificationEnabled??hh.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,...(c=e.events)==null?void 0:c.phase_blocked},new_message:{...Fv,...(u=e.events)==null?void 0:u.new_message}},agentOverrides:e.agentOverrides??{}}}const Kx=new Map;function G1(e){let r=Kx.get(e);return r||(r=new Audio(e),r.volume=.5,Kx.set(e,r)),r}let $v=typeof Notification<"u"?Notification.permission:"denied";function K1(){return typeof Notification>"u"?Promise.resolve("denied"):Notification.requestPermission().then(e=>($v=e,e))}const Y1={complete:"Task Complete",waiting_for_user:"Waiting for Input",phase_done:"Phase Complete",phase_blocked:"Phase Blocked",new_message:"New Message"},X1={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 Z1(e){typeof Notification>"u"||$v==="granted"&&(document.hasFocus()||new Notification(Y1[e],{body:X1[e],icon:"/fox.svg",tag:`openfox-${e}`}))}function go(e,r){const{settings:s}=Fs.getState(),i=Uv(s,e,r);if(s.soundEnabled&&i.soundEnabled){const c=i.customSoundUrl??Hv[e],u=G1(c);u.currentTime=0,u.play().catch(()=>{})}s.browserNotificationEnabled&&i.browserNotification&&Z1(e)}const Q1=e=>go("complete",e),J1=e=>go("phase_done",e),ew=e=>go("phase_blocked",e),Yx=e=>go("waiting_for_user",e),tw=e=>go("new_message",e);let $a=!1,pr=null;const Fd=new Set,Vt={messageId:null,deltaContent:"",thinkingContent:"",toolOutput:[]};let Ui=null,mn=null;function Ud(){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 nw(e,r,s){return e.id!==void 0||Ht(e,r)||s===!0&&e.sessionId!==void 0}function rw(e,r){return e.includes(r)?e:[...e,r]}function qa(e,r){return e.filter(s=>s!==r)}function sw(e,r){const s=e.find(c=>c.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(c=>c.status.type==="passed").length}:{id:r.id,projectId:r.projectId,workdir:r.workdir,mode:r.mode,phase:r.phase,isRunning:r.isRunning,createdAt:"",updatedAt:"",criteriaCount:r.criteria.length,criteriaCompleted:r.criteria.filter(c=>c.status.type==="passed").length,messageCount:r.messages.length};return s?e.map(c=>c.id===r.id?i:c):[i,...e]}function Xx(e,r,s){return e.map(i=>{const c=(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:(c==null?void 0:c.mode)??(u==null?void 0:u.mode)??i.mode,phase:(c==null?void 0:c.phase)??(u==null?void 0:u.phase)??i.phase,isRunning:i.isRunning&&(u==null?void 0:u.isRunning)!==!1,messageCount:i.messageCount,recentUserPrompts:i.recentUserPrompts}})}const Zx=new Map;function Ja(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),c=(s==null?void 0:s.mode)??(i==null?void 0:i.mode);return c==="planner"?"planner":c==="builder"?"build":"planner"}function iw(e,r){if(e.type==="chat.done"){const s=e.payload,i=Ja(r,e.sessionId),c=s.agentType??i;s.reason==="complete"&&Q1(c),s.reason==="waiting_for_user"&&Yx(c);return}if(e.type==="chat.path_confirmation"){const s=Ja(r,e.sessionId);Yx(s);return}if(e.type==="task.completed"){const s=Ja(r,e.sessionId);J1(s);return}if(e.type==="phase.changed"&&e.sessionId){const s=e.payload,i=Zx.get(e.sessionId)??null;if(Zx.set(e.sessionId,s.phase),i===s.phase)return;const c=Ja(r,e.sessionId);s.phase==="blocked"&&ew(c)}}const Ce=$n((e,r)=>(mn=()=>{const s=Vt;if(!s.messageId)return;const i=s.deltaContent.length>0,c=s.thinkingContent.length>0,u=s.toolOutput.length>0;if(!i&&!c&&!u)return;const h=s.deltaContent,l=s.thinkingContent,d=s.toolOutput;s.deltaContent="",s.thinkingContent="",s.toolOutput=[],e(f=>{var m;const g=f.streamingMessage;if(g&&g.id===s.messageId){let v={...g};if(i&&(v.content=v.content+h),c&&(v.thinkingContent=(v.thinkingContent??"")+l),u){const S=new Set;v.toolCalls=(m=v.toolCalls)==null?void 0:m.map(C=>{const y=d.filter(b=>b.callId===C.id);return y.length===0?C:(S.add(C.id),{...C,streamingOutput:[...C.streamingOutput??[],...y.map(b=>({stream:b.stream,content:b.content,timestamp:Date.now()}))]})});const k=d.filter(C=>!S.has(C.callId));k.length>0&&Vt.toolOutput.push(...k)}return{streamingMessage:v}}if(u){const v=new Set,S=f.messages.map(C=>{var b;if(C.id!==s.messageId)return C;const y=(b=C.toolCalls)==null?void 0:b.map(x=>{const _=d.filter(j=>j.callId===x.id);return _.length===0?x:(v.add(x.id),{...x,streamingOutput:[...x.streamingOutput??[],..._.map(j=>({stream:j.stream,content:j.content,timestamp:Date.now()}))]})});return{...C,toolCalls:y}}),k=d.filter(C=>!v.has(C.callId));return k.length>0&&Vt.toolOutput.push(...k),{messages:S}}return f})},{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(c=>{var u;if(e({connectionStatus:c}),c==="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(),!$a){$a=!0;const c=r().handleServerMessage;pr=Gt.subscribe(c)}}catch(c){console.error("Failed to connect:",c);const u=Gt.getLastCloseCode();if(!Gt.hasToken()&&(u===1006||u===4e3)){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}pr&&(pr(),pr=null),$a=!1,e({connectionStatus:"disconnected"})}},reconnect:()=>{Gt.disconnect(),pr&&(pr(),pr=null),$a=!1,e({connectionStatus:"disconnected"}),r().connect()},disconnect:()=>{Gt.disconnect(),pr&&(pr(),pr=null),$a=!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:c}=await i.json();Gt.setToken(c),e({showPasswordModal:!1}),r().connect();const{listProjects:u}=Ft.getState(),{fetchConfig:h}=Rt.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)=>{if(r().pendingSessionCreate)return null;try{e({pendingSessionCreate:!0});const u=await ke("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectId:s,title:i})});if(!u.ok)return e({pendingSessionCreate:!1}),null;const h=await u.json();return Gt.send("session.load",{sessionId:h.session.id}),h.session}catch{return e({pendingSessionCreate:!1}),null}},loadSession:async s=>{try{const i=r().currentSession;!i||i.id!==s?(Is(),e({currentSession:null,unreadSessionIds:qa(r().unreadSessionIds,s),subAgentContextStates:{},messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,pendingPathConfirmation:null,queuedMessages:[],abortInProgress:!1,error:null,pendingSessionCreate:!1})):e({unreadSessionIds:qa(r().unreadSessionIds,s)});const c=await ke(`/api/sessions/${s}`);if(!c.ok)return;const u=await c.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 l=await h.json();to.getState().setProcesses(l.processes??[])}}catch{}}catch{}},listSessions:async(s,i=20)=>{try{const c=new URLSearchParams;c.set("limit",String(i)),s&&c.set("projectId",s);const h=await(await ke(`/api/sessions?${c.toString()}`)).json(),l=h.sessions??[];e(d=>({sessions:Xx(l,d.sessions,d.currentSession),sessionsHasMore:s?h.hasMore??!1:!0}))}catch{}},loadMoreSessions:async s=>{const i=r();if(!(i.sessionsPaginationLoading||!i.sessionsHasMore)){e({sessionsPaginationLoading:!0});try{const c=new URLSearchParams;c.set("limit","20"),c.set("offset",String(i.sessions.length)),c.set("projectId",s);const h=await(await ke(`/api/sessions?${c.toString()}`)).json(),l=h.sessions??[];e(d=>({sessions:[...d.sessions,...l.map(f=>{const g=d.sessions.find(m=>m.id===f.id);return(g==null?void 0:g.isRunning)===!1?{...f,isRunning:!1}:f})],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?qa(s.unreadSessionIds,s.currentSession.id):s.unreadSessionIds}))},sendMessage:async(s,i,c)=>{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:c==null?void 0:c.messageKind})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(l){console.error("Error sending message:",l)}}},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(c){console.error("Error stopping generation:",c)}}},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(c){console.error("Error continuing generation:",c)}}},launchRunner:(s,i,c)=>{e({streamingMessageId:null});const u={};s!=null&&s.trim()&&(u.content=s),i&&i.length>0&&(u.attachments=i),c&&(u.workflowId=c),Gt.send("runner.launch",u)},switchMode:async s=>{var c;const i=(c=r().currentSession)==null?void 0:c.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 c;const i=(c=r().currentSession)==null?void 0:c.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,c)=>{var l;e({streamingMessageId:null});const u={};s&&(u.workflowId=s),i!=null&&i.trim()&&(u.content=i),c&&c.length>0&&(u.attachments=c);const h=(l=r().currentSession)==null?void 0:l.id;h&&ke(`/api/sessions/${h}/mode`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:"builder"})}).then(()=>{Gt.send("runner.launch",u)})},editCriteria:async s=>{var c;const i=(c=r().currentSession)==null?void 0:c.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 c;try{const u=(c=r().currentSession)==null?void 0:c.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 l=await h.json();return e({currentSession:l.session,messages:l.messages??[],contextState:l.contextState}),l.session}catch{return null}},updateContextState:s=>{e({contextState:s})},updateSubAgentContextState:(s,i)=>{e(c=>({subAgentContextStates:{...c.subAgentContextStates,[s]:i}}))},clearSubAgentContextState:s=>{e(i=>{const c={...i.subAgentContextStates};return delete c[s],{subAgentContextStates:c}})},confirmPath:async(s,i,c=!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:c})})}catch(l){console.error("Error confirming path:",l)}},answerQuestion:async(s,i)=>{var u;const c=(u=r().currentSession)==null?void 0:u.id;if(c){try{await ke(`/api/sessions/${c}/answer`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:s,answer:i})})}catch(h){console.error("Error answering question:",h)}e({pendingQuestion:null})}},queueAsap:async(s,i,c)=>{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:c})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(l){console.error("Error queueing ASAP message:",l)}},queueCompletion:async(s,i,c)=>{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:c})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(l){console.error("Error queueing completion message:",l)}},cancelQueued:async s=>{var c;const i=(c=r().currentSession)==null?void 0:c.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,l,d,f,g,m,v,S,k,C,y,b,x,_,j,A,N,D,T,z,O,q,G,W;const i=r();iw(s,i);const c=((h=i.currentSession)==null?void 0:h.id)??null,u=()=>{const I=s.sessionId;!I||I===c||e($=>({unreadSessionIds:rw($.unreadSessionIds,I)}))};switch(s.type){case"session.state":{const I=s.payload;if(!nw(s,c,i.pendingSessionCreate))break;Is();const $=I.messages.find(L=>L.isStreaming)??null,B=r().pendingSessionCreate===!0,X=I.pendingConfirmations??[],H=i.pendingPathConfirmation??(X.length>0?X[0]??null:null);if(e({currentSession:I.session,sessions:sw(r().sessions,I.session),unreadSessionIds:qa(r().unreadSessionIds,I.session.id),messages:I.messages,streamingMessageId:($==null?void 0:$.id)??null,streamingMessage:$,currentTodos:[],pendingPathConfirmation:H,error:null,...B?{pendingSessionCreate:I.session.id}:{}}),I.session.providerId&&I.session.providerModel){const L=Rt.getState();L.providers.find(U=>U.id===I.session.providerId)&&L.syncFromSession(I.session.providerId,I.session.providerModel)}break}case"session.list":{const I=s.payload;e($=>({sessions:Xx(I.sessions,$.sessions,$.currentSession)}));break}case"session.deleted":{const I=s.payload;e($=>({unreadSessionIds:qa($.unreadSessionIds,I.sessionId)})),r().listSessions();break}case"session.deletedAll":{r().listSessions();break}case"session.running":{const I=s.payload,$=s.sessionId,B=(l=r().currentSession)==null?void 0:l.id,X=$&&$!==B;e(Q=>({sessions:Q.sessions.map(H=>H.id===$?{...H,isRunning:I.isRunning}:H)})),X||e(Q=>({currentSession:Q.currentSession?{...Q.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,((f=r().currentSession)==null?void 0:f.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,Q=$;if(X&&X.id===I.messageId){const H={...X,...I.updates};return{messages:B.messages.map(L=>L.id===I.messageId?H:L),streamingMessageId:Q?null:B.streamingMessageId,streamingMessage:Q?null:{...X,...I.updates}}}return{messages:B.messages.map(H=>H.id===I.messageId?{...H,...I.updates}:H),streamingMessageId:Q?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(!Fd.has(I.messageId)){Fd.add(I.messageId);const $=Ja(r(),s.sessionId);tw($)}Vt.messageId=I.messageId,Vt.deltaContent+=I.content,Ud();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,Ud();break}case"chat.tool_preparing":{if(!Ht(s,((v=r().currentSession)==null?void 0:v.id)??null)){u();break}const I=s.payload;e($=>{const B=$.streamingMessage;return B&&B.id===I.messageId?{streamingMessage:{...B,preparingToolCalls:[...B.preparingToolCalls??[],{index:I.index,name:I.name}]}}:{messages:$.messages.map(X=>X.id===I.messageId?{...X,preparingToolCalls:[...X.preparingToolCalls??[],{index:I.index,name:I.name}]}:X)}});break}case"chat.tool_call":{if(!Ht(s,((S=r().currentSession)==null?void 0:S.id)??null)){u();break}const I=s.payload,$=B=>{var H;const X=(H=B.preparingToolCalls)==null?void 0:H.filter((L,R)=>{var U;return L.name===I.tool?(U=B.preparingToolCalls)==null?void 0:U.slice(0,R).some(ne=>ne.name===I.tool):!0}),Q=Vt.toolOutput.filter(L=>L.callId===I.callId);return Q.length>0&&(Vt.toolOutput=Vt.toolOutput.filter(L=>L.callId!==I.callId)),{...B,toolCalls:[...B.toolCalls??[],{id:I.callId,name:I.tool,arguments:I.args,startedAt:Date.now(),...Q.length>0?{streamingOutput:Q.map(L=>({stream:L.stream,content:L.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(Q=>Q.id===I.messageId?$(Q):Q)}});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}),Ud();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 Q;const X=(Q=B.toolCalls)==null?void 0:Q.map(H=>H.id===I.callId?{...H,result:I.result}:H);return{...B,toolCalls:X}};e(B=>{const X=B.streamingMessage;return X&&X.id===I.messageId?{streamingMessage:$(X)}:{messages:B.messages.map(Q=>Q.id===I.messageId?$(Q):Q)}});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,((b=r().currentSession)==null?void 0:b.id)??null)){u();break}const I=s.payload;e({currentTodos:I.todos});break}case"chat.summary":{if(!Ht(s,((x=r().currentSession)==null?void 0:x.id)??null)){u();break}const I=s.payload;e($=>({currentSession:$.currentSession?{...$.currentSession,summary:I.summary}:null}));break}case"chat.progress":{if(!Ht(s,((_=r().currentSession)==null?void 0:_.id)??null)){u();break}const I=s.payload;console.log("Progress:",I.message,I.phase);break}case"chat.format_retry":{if(!Ht(s,((j=r().currentSession)==null?void 0:j.id)??null)){u();break}const I=s.payload;console.log("Format retry:",I.attempt,"/",I.maxAttempts);break}case"chat.done":{if(!Ht(s,((A=r().currentSession)==null?void 0:A.id)??null)){u();break}Is(),mn==null||mn();const I=s.payload,$=I.stats;Vt.messageId=null,Vt.deltaContent="",Vt.thinkingContent="",Vt.toolOutput=[],Fd.delete(I.messageId),e(B=>{const X=B.streamingMessage,Q=X&&X.id===I.messageId?{...X,isStreaming:!1,stats:$??X.stats}:null;return{messages:B.messages.map(H=>H.id===I.messageId?Q??{...H,isStreaming:!1,stats:$??H.stats}:H),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,((T=r().currentSession)==null?void 0:T.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(Q=>({sessions:Q.sessions.map(H=>H.id===$?{...H,phase:I.phase}:H)})),X||e(Q=>({currentSession:Q.currentSession?{...Q.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 Q=X.sessions.map(L=>L.id===$?{...L,title:I.name,updatedAt:new Date().toISOString()}:L),H=B===$?X.currentSession?{...X.currentSession,title:I.name,updatedAt:new Date().toISOString()}:null:X.currentSession;return{sessions:Q,currentSession:H}});break}case"queue.state":{const I=s.payload;e({queuedMessages:I.messages});break}case"devServer.output":case"devServer.state":{gr.getState().handleMessage(s);break}case"backgroundProcess.started":case"backgroundProcess.output":case"backgroundProcess.exited":case"backgroundProcess.removed":{to.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 qv(){return Ce(e=>{var r;return((r=e.currentSession)==null?void 0:r.isRunning)??!1})}function aw(){return Ce(e=>e.queuedMessages)}function ow(){return Ce(e=>e.abortInProgress)}function lw(){const e=Ce(i=>i.connect),r=Ce(i=>i.connectionStatus),s=Fs(i=>i.load);return P.useEffect(()=>{e()},[e]),P.useEffect(()=>{r==="connected"&&s()},[r,s]),{connectionStatus:r}}const cw="modulepreload",uw=function(e){return"/"+e},Qx={},fh=function(r,s,i){let c=Promise.resolve();if(s&&s.length>0){let h=function(f){return Promise.all(f.map(g=>Promise.resolve(g).then(m=>({status:"fulfilled",value:m}),m=>({status:"rejected",reason:m}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),d=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));c=h(s.map(f=>{if(f=uw(f),f in Qx)return;Qx[f]=!0;const g=f.endsWith(".css"),m=g?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${m}`))return;const v=document.createElement("link");if(v.rel=g?"stylesheet":cw,g||(v.as="script"),v.crossOrigin="",v.href=f,d&&v.setAttribute("nonce",d),document.head.appendChild(v),g)return new Promise((S,k)=>{v.addEventListener("load",S),v.addEventListener("error",()=>k(new Error(`Unable to preload CSS for ${f}`)))})}))}function u(h){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=h,window.dispatchEvent(l),!l.defaultPrevented)throw h}return c.then(h=>{for(const l of h||[])l.status==="rejected"&&u(l.reason);return r().catch(u)})},Wv=[{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"}],xr=[{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 Jx(){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:Jx(),applySavedTheme:()=>{const{getSavedTheme:s,applyPreset:i,applyTokens:c}=r(),u=s();if(u)try{const h=JSON.parse(u);h.preset&&h.tokens?(i(h.preset),e({basePreset:h.preset}),c(h.tokens)):h.preset?i(h.preset):h.tokens&&c(h.tokens)}catch{i("dark")}else i("dark")},applyPreset:s=>{xr.find(c=>c.id===s)&&(e({currentPreset:s,basePreset:"",customTokens:{},isCustom:!1,isCustomizing:!1}),r().applyTheme())},startCustomizing:()=>{var c;const{currentPreset:s}=r(),i=((c=xr.find(u=>u.id===s))==null?void 0:c.tokens)??{};e({basePreset:s,customTokens:{...i},isCustom:!0,isCustomizing:!0})},setCustomToken:(s,i)=>{e(c=>({customTokens:{...c.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,l;const{basePreset:s,customTokens:i,isCustom:c}=r();if(c&&s)return{...((h=xr.find(f=>f.id===s))==null?void 0:h.tokens)??{},...i};if(c)return{...Wv.reduce((d,f)=>({...d,[f.key]:f.defaultValue}),{}),...i};const u=xr.find(d=>d.id===r().currentPreset);return(u==null?void 0:u.tokens)??((l=xr[0])==null?void 0:l.tokens)??{}},applyTheme:()=>{if(typeof document>"u")return;const s=r().getActiveTheme(),i=document.documentElement;Object.entries(s).forEach(([c,u])=>{i.style.setProperty(`--${c}`,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),fh(async()=>{const{useSettingsStore:i}=await Promise.resolve().then(()=>Ix);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:c,currentPreset:u}=r(),h={id:"custom-"+Date.now(),name:s,basePreset:i||u,tokens:{...c}},l=[...r().userPresets,h];e({userPresets:l}),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((c,u)=>u!==s);e({userPresets:i}),r().saveUserPresets()},loadUserPresets:()=>{e({userPresets:Jx()})},saveUserPresets:()=>{localStorage.setItem("openfox:userPresets",JSON.stringify(r().userPresets)),fh(async()=>{const{useSettingsStore:s}=await Promise.resolve().then(()=>Ix);return{useSettingsStore:s}},void 0).then(({useSettingsStore:s})=>{s.getState().setSetting(ot.DISPLAY_USER_PRESETS,JSON.stringify(r().userPresets)).catch(()=>{})})}}));function dw({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 Vv({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 hw({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 fw({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 pw({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 br({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 mw({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 Ih({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 gw({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 Bh({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,fill:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("circle",{cx:"12",cy:"5",r:"2"}),o.jsx("circle",{cx:"12",cy:"12",r:"2"}),o.jsx("circle",{cx:"12",cy:"19",r:"2"})]})}function lc({className:e="w-3.5 h-3.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"})})}function zh({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 xw({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 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:"M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"})})}function vw({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 yw({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 _w({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 eb({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 Gv({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 Sw({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 ww({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 qi({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 Cw({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 kw({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 Ew({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 jw({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 Nw({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 Tw({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 Aw({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("polyline",{points:"4 17 10 11 4 5"}),o.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function Ph({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 Hh(){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 Dw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}function Kv({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 Fh({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 Rw({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 ph(){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 tb(e,r){const s=Gt.ws;!s||s.readyState!==WebSocket.OPEN||s.send(JSON.stringify({id:ph(),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 c=await i.json();e({sessions:c});const u=Gt.ws;if(u&&u.readyState===WebSocket.OPEN)for(const h of c)u.send(JSON.stringify({id:ph(),type:"terminal.subscribe",payload:{sessionId:h.id}}))}}catch(i){console.error("Failed to fetch terminals:",i)}},createSession:async(s,i)=>{try{const c=await ke("/api/terminals",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workdir:s??r().workdir??void 0,projectId:i})});if(c.ok){const u=await c.json();e(l=>({sessions:[...l.sessions,u]}));const h=Gt.ws;h&&h.readyState===WebSocket.OPEN&&h.send(JSON.stringify({id:ph(),type:"terminal.subscribe",payload:{sessionId:u.id}}))}}catch(c){console.error("Failed to create terminal:",c)}},writeSession:(s,i)=>{tb("terminal.write",{sessionId:s,data:i})},resizeSession:(s,i,c)=>{tb("terminal.resize",{sessionId:s,cols:i,rows:c})},killSession:async s=>{try{(await ke(`/api/terminals/${s}`,{method:"DELETE"})).ok&&e(c=>({sessions:c.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(c=>{const u=c.sessions.filter(h=>h.id!==i);return u.length===0&&c.isOpen?{sessions:[],isOpen:!1}:{sessions:u}});break}}}}));Gt.subscribe(e=>{var r;(r=e.type)!=null&&r.startsWith("terminal.")&&ir.getState().handleMessage(e)});var xo=Nv();const cc=P.forwardRef(({icon:e,iconSize:r="w-3.5 h-3.5",className:s="",...i},c)=>o.jsx("button",{ref:c,type:"button",className:`p-1 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors ${s}`,...i,children:o.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:e})})}));cc.displayName="IconButton";const Lw="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",Wi=P.forwardRef((e,r)=>o.jsx(cc,{ref:r,icon:Lw,title:"Edit",...e}));Wi.displayName="EditButton";const Ow="M6 18L18 6M6 6l12 12",Uh=P.forwardRef((e,r)=>o.jsx(cc,{ref:r,icon:Ow,...e}));Uh.displayName="CloseButton";const Mw={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:c,footer:u,className:h,onClose:l,isOpen:d,closeOnBackdropClick:f=!0,closeOnEscape:g=!0,showCloseButton:m=!0}){const[v,S]=P.useState(!1),k=d!==void 0,C=k?d:v,y=P.useCallback(()=>{k||S(!0)},[k]),b=P.useCallback(()=>{k||S(!1),l==null||l()},[k,l]);P.useEffect(()=>{if(!C||!g)return;const _=j=>{j.key==="Escape"&&b()};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[C,b,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"?xo.createPortal(o.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:[o.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:f?b:void 0}),o.jsxs("div",{className:`relative w-full ${Mw[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(Uh,{onClick:b,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:c}),u&&o.jsx("div",{className:"px-4 py-3 border-t border-border",children:u})]})]}),document.body):null)]})}const nt=P.forwardRef(({variant:e="secondary",size:r="md",className:s="",children:i,...c},u)=>{const h="rounded font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed",l={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} ${l[e]} ${d[r]} ${s}`,...c,children:i})});nt.displayName="Button";function Iw({value:e,defaultUrl:r,disabled:s,onChange:i}){const c=e??r;return o.jsxs("div",{className:"relative",children:[o.jsx("select",{value:c,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:V1.map(({url:u,label:h})=>o.jsx("option",{value:u,title:h,children:h.split(" ")[0]},u))}),o.jsx(br,{className:"absolute right-0.5 top-1/2 -translate-y-1/2 w-3 h-3 pointer-events-none text-text-muted"})]})}const nb=[{key:"general",label:"General"},{key:"build",label:"Agent"},{key:"sub-agent",label:"Sub-agent"}];function Bw(){const e=Fs(d=>d.settings),r=Fs(d=>d.update),s=Fs(d=>d.updateEvent),i=Fs(d=>d.updateAgentOverride),c=Fs(d=>d.load);P.useEffect(()=>{c()},[c]);const u=async()=>{await K1()==="granted"&&r({...e,browserNotificationEnabled:!0})},h=(d,f,g,m)=>{d==="general"?s(f,{[g]:m}):i(d,f,{[g]:m})},l=(d,f,g)=>{d==="general"?s(f,{customSoundUrl:g}):i(d,f,{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(rb,{label:"Sound notifications",description:"Play sounds when events occur",checked:e.soundEnabled,onChange:d=>r({...e,soundEnabled:d})}),o.jsx(rb,{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"}),nb.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:W1.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})}),nb.map(f=>{const g=Uv(e,d.key,f.key==="general"?void 0:f.key),m=Hv[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:v=>h(f.key,d.key,"soundEnabled",v.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:v=>h(f.key,d.key,"browserNotification",v.target.checked),disabled:!e.browserNotificationEnabled,className:"rounded border-border",title:"Browser"})})]}),g.soundEnabled&&e.soundEnabled&&o.jsx(Iw,{value:g.customSoundUrl,defaultUrl:m,disabled:!e.soundEnabled,onChange:v=>l(f.key,d.key,v)})]})},f.key)})]},d.key))})]})})]})]})}function rb({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:c=>{c.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 $h(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 $h("/api/skills",e)},toggleSkill:async s=>{try{const c=await(await ke(`/api/skills/${s}/toggle`,{method:"POST"})).json();e(u=>({defaults:u.defaults.map(h=>h.id===s?{...h,enabled:c.enabled}:h),userItems:u.userItems.map(h=>h.id===s?{...h,enabled:c.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 c=await xs("PUT",`/api/skills/${s}`,i);return c.success&&await r().fetchSkills(),c},deleteSkill:async s=>{try{const i=await ke(`/api/skills/${s}`,{method:"DELETE"}),c=await i.json();return i.ok?(e(u=>({userItems:u.userItems.filter(h=>h.id!==s)})),{success:!0}):{success:!1,error:c.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"}),c=await i.json();return i.ok?(await r().fetchSkills(),{success:!0}):{success:!1,error:c.error??"Failed to duplicate"}}catch{return{success:!1,error:"Network error"}}}}));function qh(){const[e,r]=P.useState({id:null,type:null}),s=P.useCallback(u=>r({id:u,type:"delete"}),[]),i=P.useCallback(()=>r({id:null,type:null}),[]),c=P.useCallback((u,h)=>e.id===u&&e.type===h,[e.id,e.type]);return{requestDelete:s,clearConfirm:i,isConfirming:c}}function Wh({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 Vh({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(Ph,{})})}function ao({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(Ih,{})})}function Us({label:e,value:r,onChange:s,placeholder:i,readOnly:c,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:l=>s(l.target.value),readOnly:c,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":""} ${c?"opacity-60":""}`})]})}function zw({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(nt,{variant:"secondary",onClick:e,children:"Cancel"}),o.jsx(nt,{variant:"primary",onClick:r,disabled:s||i,children:s?"Saving...":"Save"})]})}function Gh({message:e}){return o.jsx("div",{className:"text-accent-error text-sm px-3 py-2 bg-accent-error/10 rounded",children:e})}function Yv({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(nt,{variant:"primary",size:"sm",onClick:r,children:s})})]})}function Xv({isBuiltIn:e,isConfirmingDelete:r,onView:s,onEdit:i,onDuplicate:c,onDelete:u,children:h}){return o.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[o.jsx("div",{className:"min-w-0 flex-1 mr-3",children:h}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[e&&s&&o.jsx("button",{onClick:s,className:"p-1.5 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors",title:"View",children:o.jsx(lc,{})}),o.jsx(ao,{onClick:c}),!e&&i&&o.jsx(Wi,{onClick:i}),!e&&(r?o.jsx(Wh,{onConfirm:()=>{u==null||u()},onCancel:()=>{}}):o.jsx(Vh,{onClick:()=>u==null?void 0:u()}))]})]})}function Pw({id:e,name:r,description:s,isBuiltIn:i,isConfirmingDelete:c,onView:u,onEdit:h,onDuplicate:l,onDelete:d}){return o.jsxs(Xv,{isBuiltIn:i,isConfirmingDelete:c,onView:u,onEdit:h,onDuplicate:l,onDelete:d,children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-text-primary text-sm font-medium",children:r}),o.jsx("span",{className:"text-text-muted text-xs font-mono",children:e})]}),s&&o.jsx("p",{className:"text-text-muted text-xs truncate",children:s})]})}function Zv({loading:e,hasItems:r,loadingLabel:s,emptyLabel:i,children:c}){return e&&!r?o.jsx("div",{className:"text-text-muted text-sm",children:s}):r?o.jsx("div",{className:"space-y-4",children:c}):i?o.jsx("div",{className:"text-text-muted text-sm",children:i}):null}function Qv({name:e,id:r,nameLabel:s="Name",idLabel:i="ID",namePlaceholder:c="My Item",idPlaceholder:u="my-item",nameHint:h,readOnlyId:l=!1,readOnlyHint:d="(read-only)",onNameChange:f,onIdChange:g}){return o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(Us,{label:s,value:e,onChange:f,placeholder:c,hint:h}),o.jsx(Us,{label:i,value:r,onChange:g,readOnly:l,placeholder:u,hint:l?d:void 0,mono:!0})]})}function Jv(e={}){const{initialData:r={}}=e,[s,i]=P.useState("list"),[c,u]=P.useState(null),[h,l]=P.useState(""),[d,f]=P.useState(!1),[g,m]=P.useState(r),v=P.useCallback(()=>{m(r),l(""),u(null)},[r]),S=P.useCallback(b=>{i(b),b==="list"&&v()},[v]),k=P.useCallback(b=>{m(x=>typeof b=="function"?b(x):b)},[]),C=P.useCallback((b,x={})=>{u(b),i("edit"),m({...x}),l("")},[]),y=P.useCallback(()=>{u(null),i("edit"),m(r),l("")},[r]);return{view:s,editingId:c,formError:h,saving:d,formData:g,setView:S,setEditingId:u,setFormError:l,setFormData:k,setSaving:f,resetForm:v,startEditing:C,startNew:y}}function Kh(){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 sb({skill:e,isBuiltIn:r,isConfirmingDelete:s,onView:i,onEdit:c,onDuplicate:u,onDelete:h}){return o.jsx(Pw,{id:e.id,name:e.name,description:e.description,isBuiltIn:r,isConfirmingDelete:s,onView:i,onEdit:c,onDuplicate:u,onDelete:h})}function Hw({isOpen:e}){const r=Pr(I=>I.defaults),s=Pr(I=>I.userItems),i=Pr(I=>I.loading),c=Pr(I=>I.fetchSkills),u=Pr(I=>I.fetchSkill),h=Pr(I=>I.fetchDefaultContent),l=Pr(I=>I.createSkill),d=Pr(I=>I.updateSkill),f=Pr(I=>I.deleteSkill),{view:g,editingId:m,formError:v,saving:S,formData:k,setView:C,setEditingId:y,setFormError:b,setFormData:x,setSaving:_}=Jv(),{clearConfirm:j}=qh();P.useEffect(()=>{e&&(c(),C("list"),y(null),j())},[e,c,j]);const A=(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;A(B,!0),y(I),b(""),C("edit")}else{const B=await u(I);if(!B)return;A(B,!0),y(I),b(""),C("edit")}},D=async I=>{const B=r.some(Q=>Q.id===I)?await h(I):await u(I);if(!B)return;const X=`${I}-copy-${Date.now()}`;A(B,!1,X,`${B.metadata.name} (copy)`),y(null),b(""),C("edit")},T=()=>{x({name:"",id:"",description:"",version:"1.0.0",prompt:"",isReadOnly:!1}),C("edit")},z=async I=>{const $=await u(I);$&&(A($,!1),y(I),b(""),C("edit"))},O=async I=>{await f(I),j()},q=async()=>{const I=m??k.id;if(!I||!k.name||!k.prompt){b("Name, ID, and prompt are required.");return}_(!0),b("");const $={metadata:{id:I,name:k.name,description:k.description,version:k.version},prompt:k.prompt},B=m?await d(m,$):await l($);if(_(!1),!B.success){b(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"})]}),v&&o.jsx(Gh,{message:v}),o.jsxs("div",{className:"space-y-3 mb-3",children:[o.jsx(Qv,{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(Kh,{}),o.jsxs("div",{className:"flex justify-end gap-2 pt-3 border-t border-border flex-shrink-0",children:[o.jsx(nt,{variant:"secondary",onClick:()=>C("list"),children:"Cancel"}),W?o.jsx(nt,{variant:"primary",onClick:()=>{x(I=>({...I,name:I.name+" (copy)",id:`${m}-copy-${Date.now()}`,isReadOnly:!1})),y(null)},children:"Duplicate & Customize"}):o.jsx(nt,{variant:"primary",onClick:q,disabled:S||!k.name||!k.id||!k.prompt,children:S?"Saving...":"Save"})]})]}):o.jsxs("div",{children:[o.jsx(Yv,{description:"Skills provide domain-specific knowledge that agents can load on demand.",onNew:T}),o.jsxs(Zv,{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(sb,{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(sb,{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 Fw(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),c=parseInt(r[3]??"0",16);return`${s} ${i} ${c}`}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 Uw({isOpen:e,isNew:r,basePresetId:s,presetName:i,initialTokens:c,onClose:u,onSave:h}){const[l,d]=P.useState(c),[f,g]=P.useState(i);P.useEffect(()=>{d(c),g(i)},[c,i]);const m=(y,b)=>{const x=b.startsWith("#")?Fw(b):b;d(_=>({..._,[y]:x}))},v=()=>{h(f.trim()||"Untitled",{...l})},S=Wv.reduce((y,b)=>{const x=b.category;return y[x]||(y[x]=[]),y[x].push(b),y},{}),k={background:"Backgrounds",surface:"Surfaces",text:"Text",accent:"Accents",border:"Border"},C=xr.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:v,className:"px-4 py-2 bg-accent-primary text-white rounded hover:bg-accent-primary/80 transition-colors text-sm",children:"Save"})]}),children:o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-muted block mb-1",children:"Name"}),o.jsx("input",{type:"text",value:f,onChange:y=>g(y.target.value),className:"w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-accent-primary"})]}),!r&&o.jsxs("div",{className:"text-xs text-text-muted",children:["Based on ",o.jsx("span",{className:"text-text-primary",children:C==null?void 0:C.name})]}),Object.entries(S).map(([y,b])=>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:b.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(l[x.key]??x.defaultValue),onChange:_=>m(x.key,_.target.value),className:"w-8 h-8 rounded cursor-pointer border border-border bg-transparent"}),o.jsx("input",{type:"text",value:l[x.key]??x.defaultValue,onChange:_=>m(x.key,_.target.value),className:"flex-1 px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary font-mono focus:outline-none focus:ring-1 focus:ring-accent-primary"})]})]},x.key))})]},y))]})})}function $w(){const[e,r]=P.useState(null),s=dn(x=>x.currentPreset),i=dn(x=>x.isCustom),c=dn(x=>x.basePreset),u=dn(x=>x.userPresets),h=dn(x=>x.applyPreset),l=dn(x=>x.applyUserPreset),d=dn(x=>x.deleteUserPreset),f=dn(x=>x.saveTheme),g=x=>{h(x),f(JSON.stringify({preset:x}))},m=x=>{l(x)},v=x=>{const _=xr.find(j=>j.id===x);_&&r({type:"new",presetIndex:u.length,basePresetId:x,presetName:_.name+" Copy",tokens:{..._.tokens}})},S=x=>{const _=u[x];if(!_)return;const j=xr.find(N=>N.id===_.basePreset),A=j?{...j.tokens,..._.tokens}:_.tokens;r({type:"edit",presetIndex:x,basePresetId:_.basePreset,presetName:_.name,tokens:A})},k=(x,_)=>{if(!e)return;const j=[...u];if(e.type==="new"){const A={id:"custom-"+Date.now(),name:x,basePreset:e.basePresetId,tokens:_};j.push(A);const N=j.length-1;dn.setState({userPresets:j}),dn.getState().saveUserPresets(),dn.getState().applyUserPreset(N)}else{const A=j[e.presetIndex];A&&(j[e.presetIndex]={...A,name:x,tokens:_}),dn.setState({userPresets:j}),dn.getState().saveUserPresets(),dn.getState().applyUserPreset(e.presetIndex)}r(null)},C=()=>{r(null)},y=(x,_)=>{x.stopPropagation(),d(_)},b=i?c: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:xr.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 ${b===x.id&&!i?"border-accent-primary bg-bg-tertiary text-text-primary":"border-border bg-bg-secondary text-text-muted hover:border-text-muted"}`,children:[o.jsx("div",{className:"w-8 h-8 rounded border flex items-center justify-center",style:{backgroundColor:Hs(x.tokens["color-bg-primary"]??"#000"),borderColor:Hs(x.tokens["color-border"]??"#000")},children:o.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:Hs(x.tokens["color-text-primary"]??"#fff")}})}),o.jsx("span",{className:"text-xs",children:x.name})]}),o.jsx("button",{type:"button",onClick:_=>{_.stopPropagation(),v(x.id)},className:"absolute top-1 right-1 w-6 h-6 rounded bg-bg-tertiary border border-border flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:border-text-muted",title:"Create custom theme based on this",children:o.jsx("span",{className:"text-xs",children:"✎"})})]},x.id))}),u.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("h4",{className:"text-xs font-medium text-text-muted uppercase",children:"My Themes"}),o.jsx("div",{className:"grid grid-cols-5 gap-2",children:u.map((x,_)=>{const j=xr.find(N=>N.id===x.basePreset),A=j?{...j.tokens,...x.tokens}:x.tokens;return o.jsxs("div",{className:"relative group",children:[o.jsxs("button",{type:"button",onClick:()=>m(_),className:`w-full flex flex-col items-center gap-2 px-3 py-3 rounded-lg border transition-colors ${i&&c===x.basePreset&&b===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(A["color-bg-primary"]??"#000"),borderColor:Hs(A["color-border"]??"#000")},children:o.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:Hs(A["color-text-primary"]??"#fff")}})}),o.jsx("span",{className:"text-xs truncate w-full text-center",children:x.name})]}),o.jsx("button",{type:"button",onClick:N=>{N.stopPropagation(),S(_)},className:"absolute top-1 right-1 w-6 h-6 rounded bg-bg-tertiary border border-border flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:border-text-muted",title:"Edit",children:o.jsx("span",{className:"text-xs",children:"✎"})}),o.jsx("button",{type:"button",onClick:N=>y(N,_),className:"absolute -top-1 -left-1 w-5 h-5 rounded-full bg-accent-error text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-20",children:o.jsx(Fh,{className:"w-3 h-3"})})]},x.id)})})]}),e&&o.jsx(Uw,{isOpen:!0,isNew:e.type==="new",presetIndex:e.presetIndex,basePresetId:e.basePresetId,presetName:e.presetName,initialTokens:e.tokens,onClose:C,onSave:k})]})}function qw({isOpen:e,onClose:r}){const[s,i]=P.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(Wa,{label:"Instructions",active:s==="instructions",onClick:()=>i("instructions")}),o.jsx(Wa,{label:"Skills",active:s==="skills",onClick:()=>i("skills")}),o.jsx(Wa,{label:"Notifications",active:s==="notifications",onClick:()=>i("notifications")}),o.jsx(Wa,{label:"Display",active:s==="display",onClick:()=>i("display")}),o.jsx(Wa,{label:"Advanced",active:s==="advanced",onClick:()=>i("advanced")})]}),s==="instructions"&&o.jsx(Kw,{isOpen:e}),s==="skills"&&o.jsx(Hw,{isOpen:e}),s==="notifications"&&o.jsx("div",{className:"max-h-[60vh] overflow-y-auto",children:o.jsx(Bw,{})}),s==="display"&&o.jsx(Gw,{}),s==="advanced"&&o.jsx(Ww,{onClose:r})]})})}function Ww({onClose:e}){const[,r]=lr();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(nt,{variant:"secondary",onClick:s,children:"Launch Onboarding"})]})})}function Vw(){return o.jsx($w,{})}function Gw(){const e=Yt(g=>g.settings),r=Yt(g=>g.loading),s=Yt(g=>g.getSetting),i=Yt(g=>g.setSetting),c=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"])),[l,d]=P.useState(()=>Object.fromEntries(u.map(g=>[g.key,h[g.key]==="true"])));P.useEffect(()=>{u.forEach(g=>s(g.key))},[s]),P.useEffect(()=>{d(Object.fromEntries(u.map(g=>[g.key,h[g.key]==="true"])))},[JSON.stringify(h)]);const f=async g=>{const m=String(!l[g]);d(v=>({...v,[g]:!v[g]})),await i(g,m)};return c?o.jsx("div",{className:"text-sm text-text-muted",children:"Loading..."}):o.jsxs("div",{className:"space-y-6",children:[o.jsx(Vw,{}),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:v})=>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:v})]}),o.jsx("button",{type:"button",onClick:()=>f(g),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${l[g]?"bg-accent-primary":"bg-bg-tertiary"}`,children:o.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${l[g]?"translate-x-6":"translate-x-1"}`})})]},g))})]})]})}function Wa({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 Kw({isOpen:e}){const r=Yt(y=>y.settings),s=Yt(y=>y.loading),i=Yt(y=>y.getSetting),c=Yt(y=>y.setSetting),u=r[ot.GLOBAL_INSTRUCTIONS]??"",h=s[ot.GLOBAL_INSTRUCTIONS]??!1,[l,d]=P.useState(u),[f,g]=P.useState(!1),[m,v]=P.useState(!1);P.useEffect(()=>{e&&i(ot.GLOBAL_INSTRUCTIONS)},[e,i]),P.useEffect(()=>{d(u),g(!1)},[u]);const S=async()=>{v(!0),c(ot.GLOBAL_INSTRUCTIONS,l),v(!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:l,onChange:y=>{d(y.target.value),g(!0)},placeholder:"Enter global instructions that apply to all projects...",className:"w-full min-h-80 px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-y focus:outline-none focus:ring-1 focus:ring-accent-primary",disabled:C})]}),f&&o.jsx(Kh,{}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(nt,{variant:"secondary",onClick:k,disabled:!f,children:"Discard"}),o.jsx(nt,{variant:"primary",onClick:S,disabled:!f||C,children:m?"Saving...":"Save"})]})]})}var $d={exports:{}},ib;function Yw(){return ib||(ib=1,(function(e,r){(function(s,i){e.exports=i()})(globalThis,(()=>(()=>{var s={4567:function(h,l,d){var f=this&&this.__decorate||function(x,_,j,A){var N,D=arguments.length,T=D<3?_:A===null?A=Object.getOwnPropertyDescriptor(_,j):A;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")T=Reflect.decorate(x,_,j,A);else for(var z=x.length-1;z>=0;z--)(N=x[z])&&(T=(D<3?N(T):D>3?N(_,j,T):N(_,j))||T);return D>3&&T&&Object.defineProperty(_,j,T),T},g=this&&this.__param||function(x,_){return function(j,A){_(j,A,x)}};Object.defineProperty(l,"__esModule",{value:!0}),l.AccessibilityManager=void 0;const m=d(9042),v=d(9924),S=d(844),k=d(4725),C=d(2585),y=d(3656);let b=l.AccessibilityManager=class extends S.Disposable{constructor(x,_,j,A){super(),this._terminal=x,this._coreBrowserService=j,this._renderService=A,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 v.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 Bx;function b1(){if(Bx)return Pd;Bx=1;var e=ac();function r(m,v){return m===v&&(m!==0||1/m===1/v)||m!==m&&v!==v}var s=typeof Object.is=="function"?Object.is:r,i=e.useState,c=e.useEffect,u=e.useLayoutEffect,h=e.useDebugValue;function l(m,v){var S=v(),k=i({inst:{value:S,getSnapshot:v}}),C=k[0].inst,y=k[1];return u(function(){C.value=S,C.getSnapshot=v,d(C)&&y({inst:C})},[m,S,v]),c(function(){return d(C)&&y({inst:C}),m(function(){d(C)&&y({inst:C})})},[m]),h(S),S}function d(m){var v=m.getSnapshot;m=m.value;try{var S=v();return!s(m,S)}catch{return!0}}function f(m,v){return v()}var g=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?f:l;return Pd.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:g,Pd}var zx;function v1(){return zx||(zx=1,zd.exports=b1()),zd.exports}var y1=v1();const _1=i1.useInsertionEffect,S1=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",w1=S1?P.useLayoutEffect:P.useEffect,C1=_1||w1,Av=e=>{const r=P.useRef([e,(...s)=>r[0](...s)]).current;return C1(()=>{r[0]=e}),r[1]},k1="popstate",Rh="pushState",Lh="replaceState",E1="hashchange",Px=[k1,Rh,Lh,E1],j1=e=>{for(const r of Px)addEventListener(r,e);return()=>{for(const r of Px)removeEventListener(r,e)}},Dv=(e,r)=>y1.useSyncExternalStore(j1,e,r),Hx=()=>location.search,N1=({ssrSearch:e}={})=>Dv(Hx,e!=null?()=>e:Hx),Fx=()=>location.pathname,T1=({ssrPath:e}={})=>Dv(Fx,e!=null?()=>e:Fx),A1=(e,{replace:r=!1,state:s=null}={})=>history[r?Lh:Rh](s,"",e),D1=(e={})=>[T1(e),A1],Ux=Symbol.for("wouter_v3");if(typeof history<"u"&&typeof window[Ux]>"u"){for(const e of[Rh,Lh]){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,Ux,{value:!0})}const R1=(e,r)=>r.toLowerCase().indexOf(e.toLowerCase())?"~"+r:r.slice(e.length)||"/",Rv=(e="")=>e==="/"?"":e,L1=(e,r)=>e[0]==="~"?e.slice(1):Rv(r)+e,O1=(e="",r)=>R1($x(Rv(e)),$x(r)),$x=e=>{try{return decodeURI(e)}catch{return e}},Lv={hook:D1,searchHook:N1,parser:x1,base:"",ssrPath:void 0,ssrSearch:void 0,ssrContext:void 0,hrefs:e=>e,aroundNav:(e,r,s)=>e(r,s)},Ov=P.createContext(Lv),Gi=()=>P.useContext(Ov),Mv={},Iv=P.createContext(Mv),M1=()=>P.useContext(Iv),oc=e=>{const[r,s]=e.hook(e);return[O1(e.base,r),Av((i,c)=>e.aroundNav(s,L1(i,e.base),c))]},lr=()=>oc(Gi()),Oh=(e,r,s,i)=>{const{pattern:c,keys:u}=r instanceof RegExp?{keys:!1,pattern:r}:e(r||"*",i),h=c.exec(s)||[],[l,...d]=h;return l!==void 0?[!0,(()=>{const f=u!==!1?Object.fromEntries(u.map((m,v)=>[m,d[v]])):h.groups;let g={...d};return f&&Object.assign(g,f),g})(),...i?[l]:[]]:[!1,null]},Mh=e=>Oh(Gi().parser,e,lr()[0]),I1=({children:e,...r})=>{var g,m,v;const s=Gi(),i=r.hook?Lv:s;let c=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??((v=r.hook)==null?void 0:v.searchHook);let l=P.useRef({}),d=l.current,f=d;for(let S in i){const k=S==="base"?i[S]+(r[S]??""):r[S]??i[S];d===f&&k!==f[S]&&(l.current=f={...f}),f[S]=k,(k!==i[S]||k!==c[S])&&(c=f)}return P.createElement(Ov.Provider,{value:c,children:e})},qx=({children:e,component:r},s)=>r?P.createElement(r,{params:s}):typeof e=="function"?e(s):e,B1=e=>{let r=P.useRef(Mv);const s=r.current;return r.current=Object.keys(e).length!==Object.keys(s).length||Object.entries(e).some(([i,c])=>c!==s[i])?e:s},Ua=({path:e,nest:r,match:s,...i})=>{const c=Gi(),[u]=oc(c),[h,l,d]=s??Oh(c.parser,e,u,r),f=B1({...M1(),...l});if(!h)return null;const g=d?P.createElement(I1,{base:d},qx(i,f)):qx(i,f);return P.createElement(Iv.Provider,{value:f,children:g})},Fn=P.forwardRef((e,r)=>{const s=Gi(),[i,c]=oc(s),{to:u="",href:h=u,onClick:l,asChild:d,children:f,className:g,replace:m,state:v,transition:S,...k}=e,C=Av(b=>{b.ctrlKey||b.metaKey||b.altKey||b.shiftKey||b.button!==0||(l==null||l(b),b.defaultPrevented||(b.preventDefault(),c(h,e)))}),y=s.hrefs(h[0]==="~"?h.slice(1):s.base+h,s);return d&&P.isValidElement(f)?P.cloneElement(f,{onClick:C,href:y}):P.createElement("a",{...k,onClick:C,href:y,className:g!=null&&g.call?g(i===h):g,children:f,ref:r})}),Bv=e=>Array.isArray(e)?e.flatMap(r=>Bv(r&&r.type===P.Fragment?r.props.children:r)):[e],z1=({children:e,location:r})=>{const s=Gi(),[i]=oc(s);for(const c of Bv(e)){let u=0;if(P.isValidElement(c)&&(u=Oh(s.parser,c.props.path,r||i,c.props.nest))[0])return P.cloneElement(c,{match:u})}return null};function P1(e){return typeof e=="object"&&e!==null&&"type"in e&&"payload"in e}function zv(){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 H1{constructor(r){fr(this,"ws",null);fr(this,"handlers",new Set);fr(this,"statusHandler",null);fr(this,"baseUrl");fr(this,"isReconnecting",!1);fr(this,"connectingPromise",null);fr(this,"lastCloseCode",0);fr(this,"reconnectAttempts",0);fr(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,c)=>{try{const u=this.getUrl();this.ws=new WebSocket(u);const h=setTimeout(()=>{var l;((l=this.ws)==null?void 0:l.readyState)===WebSocket.CONNECTING&&(this.ws.close(),c(new Error("Connection timeout")))},5e3);this.ws.onopen=()=>{var l;clearTimeout(h),this.isReconnecting=!1,this.connectingPromise=null,(l=this.statusHandler)==null||l.call(this,"connected"),i()},this.ws.onclose=l=>{var d,f,g;clearTimeout(h),this.lastCloseCode=l.code,((d=this.ws)==null?void 0:d.readyState)===WebSocket.CONNECTING?(this.connectingPromise=null,(f=this.statusHandler)==null||f.call(this,"disconnected"),c(new Error(`Connection closed: ${l.code}`))):(this.connectingPromise=null,(g=this.statusHandler)==null||g.call(this,"disconnected"),this.attemptReconnect())},this.ws.onerror=l=>{clearTimeout(h),console.error("WebSocket error:",l),this.connectingPromise=null,c(l)},this.ws.onmessage=l=>{try{const d=JSON.parse(l.data);P1(d)&&this.handlers.forEach(f=>f(d))}catch(d){console.error("Failed to parse WebSocket message:",d)}}}catch(u){this.connectingPromise=null,c(u)}}),this.connectingPromise))}attemptReconnect(){var c;if(([1e3,1005,1006,4e3].includes(this.lastCloseCode)||this.lastCloseCode===0)&&this.hasToken()){console.log("[WS] Auth failure or initial failure with token - not auto-reconnecting, awaiting user action");return}if(this.isReconnecting||this.manualReconnectScheduled)return;this.isReconnecting=!0,(c=this.statusHandler)==null||c.call(this,"reconnecting");const 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=zv(),c={id:i,type:r,payload:s};return this.ws.send(JSON.stringify(c)),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 F1=`ws://${window.location.hostname}:${window.location.port||"10469"}/ws`,Gt=new H1(F1),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 Pv(e){let r=null;function s(){r===null&&(r=requestAnimationFrame(()=>{r=null,e()}))}return s}let Bl=[];const gr=$n()((e,r)=>{function s(){if(Bl.length===0)return;const c=Bl;Bl=[],e(u=>({logs:[...u.logs,...c]}))}const i=Pv(s);return{workdir:null,status:null,logs:[],config:null,loading:!1,setWorkdir:c=>{r().workdir!==c&&(e({workdir:c,status:null,logs:[],config:null,loading:!0}),c&&(r().fetchStatus(),r().fetchConfig()))},fetchStatus:async()=>{const c=r().workdir;if(c)try{const h=await(await ke(`/api/dev-server?workdir=${encodeURIComponent(c)}`)).json();e({status:h,loading:!1})}catch{e({loading:!1})}},fetchConfig:async()=>{const c=r().workdir;if(c)try{const h=await(await ke(`/api/dev-server/config?workdir=${encodeURIComponent(c)}`)).json();e({config:h.config??null})}catch{}},fetchLogs:async()=>{const c=r().workdir;if(c)try{const l=(await(await ke(`/api/dev-server/logs?workdir=${encodeURIComponent(c)}`)).json()).logs.map(d=>({stream:d.stream,content:d.content}));e({logs:l})}catch{}},start:async()=>{const c=r().workdir;if(c)try{const h=await(await ke(`/api/dev-server/start?workdir=${encodeURIComponent(c)}`,{method:"POST"})).json();e({status:h,logs:[]})}catch{}},stop:async()=>{const c=r().workdir;if(c)try{const h=await(await ke(`/api/dev-server/stop?workdir=${encodeURIComponent(c)}`,{method:"POST"})).json();e({status:h})}catch{}},restart:async()=>{const c=r().workdir;if(c)try{const h=await(await ke(`/api/dev-server/restart?workdir=${encodeURIComponent(c)}`,{method:"POST"})).json();e({status:h,logs:[]})}catch{}},saveConfig:async c=>{const u=r().workdir;if(u)try{const l=await(await ke(`/api/dev-server/config?workdir=${encodeURIComponent(u)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c)})).json();e({config:l.config??c}),r().fetchStatus()}catch{}},handleMessage:c=>{const u=r().workdir;if(u)switch(c.type){case"devServer.output":{const h=c.payload;if(h.workdir!==u)return;Bl.push({stream:h.stream,content:h.content}),i();break}case"devServer.state":{const h=c.payload;if(h.workdir!==u)return;e(l=>({status:l.status?{...l.status,state:h.state,errorMessage:h.errorMessage}:l.status}));break}}}}});function U1(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 Wx(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 c=await i.json();throw new Error(c.error??"Failed to update model")}return i.json()}function Vx(e,r,s,i){return e.map(c=>c.id===r?{...c,models:c.models.map(u=>u.id===s?{...u,...i,source:"user"}:u)}:c)}const $1=3e4;function q1(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 Rt=$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:c}=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 l=await u.json();throw new Error(l.error??"Failed to activate provider")}const h=await u.json();return e({activeProviderId:h.activeProviderId,model:h.model,backend:h.backend,providers:c.map(l=>({...l,isActive:l.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:c}=r();e({activeProviderId:s,model:i,defaultModelSelection:`${s}/${i}`,providers:c.map(u=>({...u,isActive:u.id===s}))})},updateModelContext:async(s,i,c)=>{e({activating:!0,error:null});try{const u=await Wx(s,i,{contextWindow:c}),{providers:h}=r();return e({providers:Vx(h,s,i,{contextWindow:c}),activating:!1}),u.contextState&&Ce.getState().updateContextState(u.contextState),!0}catch(u){return e({error:u instanceof Error?u.message:"Failed to update model context",activating:!1}),!1}},updateModelSettings:async(s,i,c)=>{e({activating:!0,error:null});try{const u=await Wx(s,i,c),{providers:h}=r(),l={...c.contextWindow!==void 0&&{contextWindow:c.contextWindow},...U1({temperature:c.temperature??void 0,topP:c.topP??void 0,topK:c.topK??void 0,maxTokens:c.maxTokens??void 0}),...c.supportsVision!==void 0&&{supportsVision:c.supportsVision}};return e({providers:Vx(h,s,i,l),activating:!1}),u.contextState&&Ce.getState().updateContextState(u.contextState),!0}catch(u){return e({error:u instanceof Error?u.message:"Failed to update model settings",activating:!1}),!1}},refreshProviderModels:async 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 c=await i.json(),{providers:u}=r();return e({providers:u.map(h=>h.id===s?{...h,models:c.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 c=setInterval(()=>{i()},$1);e({autoRefreshInterval:c})},stopAutoRefresh:()=>{const{autoRefreshInterval:s}=r();s&&(clearInterval(s),e({autoRefreshInterval:null}))},getActiveProvider:()=>{const{providers:s,activeProviderId:i}=r();return s.find(c=>c.id===i)},getModelContext:s=>{const{providers:i,activeProviderId:c}=r(),u=i.find(l=>l.id===c);if(!u)return 2e5;const h=u.models.find(l=>l.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 c=await ke("/api/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:s,workdir:i})});if(!c.ok)return null;const u=await c.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 c=await i.json();return e({currentProject:c.project}),r().projects.length===0&&await r().listProjects(),c.project}catch{return null}},updateProject:async(s,i)=>{var c;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((c=r().currentProject)==null?void 0:c.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 zl=[];const to=$n()((e,r)=>{function s(){if(zl.length===0)return;const c=zl;zl=[],e(u=>{const h={...u.logs};for(const l of c){const d=h[l.processId]??[];h[l.processId]=[...d,{offset:d.length,content:l.content,timestamp:Date.now(),stream:l.stream}]}return{logs:h}})}const i=Pv(s);return{processes:[],logs:{},loading:!1,setProcesses:c=>e({processes:c}),addProcess:c=>e(u=>({processes:[...u.processes,c]})),updateProcess:(c,u)=>e(h=>({processes:h.processes.map(l=>l.id===c?{...l,...u}:l)})),removeProcess:c=>e(u=>({processes:u.processes.filter(h=>h.id!==c),logs:Object.fromEntries(Object.entries(u.logs).filter(([h])=>h!==c))})),stopProcess:async(c,u)=>{try{(await ke(`/api/sessions/${u}/background-process/${c}/stop`,{method:"POST"})).ok&&r().removeProcess(c)}catch{}},appendLog:(c,u,h)=>{zl.push({processId:c,stream:u,content:h}),i()},setLogs:(c,u)=>e(h=>({logs:{...h.logs,[c]:u}})),clearLogs:c=>e(u=>({logs:{...u.logs,[c]:[]}})),handleMessage:(c,u)=>{switch(c){case"backgroundProcess.started":{const{processId:h,name:l,pid:d,status:f}=u;e(g=>({processes:[...g.processes,{id:h,sessionId:"",name:l,command:"",cwd:"",pid:d,status:f,exitCode:null,createdAt:Date.now(),startedAt:Date.now(),endedAt:null}]}));break}case"backgroundProcess.output":{const h=u.processId,l=u.stream,d=u.content;r().appendLog(h,l,d);break}case"backgroundProcess.exited":{const h=u.processId,l=u.exitCode;e(d=>({processes:d.processes.map(f=>f.id===h?{...f,status:"exited",exitCode:l}:f)}));break}case"backgroundProcess.removed":{const h=u.processId;r().removeProcess(h);break}}}}}),W1=[{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"}],V1=[{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"}],Hv={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},Fv={soundEnabled:!1,browserNotification:!1,customSoundUrl:null},hh={soundEnabled:!0,browserNotificationEnabled:!1,events:{complete:{...ms},waiting_for_user:{...ms},phase_done:{...ms},phase_blocked:{...ms},new_message:{...Fv}},agentOverrides:{}};function Uv(e,r,s){var u;const i=e.events[r];if(!s)return i;const c=(u=e.agentOverrides[s])==null?void 0:u[r];return c?{soundEnabled:c.soundEnabled??i.soundEnabled,browserNotification:c.browserNotification??i.browserNotification,customSoundUrl:c.customSoundUrl!==void 0?c.customSoundUrl:i.customSoundUrl}:i}const Fs=$n((e,r)=>({settings:hh,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 l=JSON.parse(h);e({settings:Gx(l),loaded:!0})}catch{e({loaded:!0})}}),c=Yt.getState().settings[ot.NOTIFICATION_SETTINGS];if(c)try{const u=JSON.parse(c);e({settings:Gx(u),loaded:!0})}catch{e({loaded:!0})}return i},update:s=>{e({settings:s}),Hd(s)},updateEvent:(s,i)=>{const c=r().settings,u={...c,events:{...c.events,[s]:{...c.events[s],...i}}};e({settings:u}),Hd(u)},updateAgentOverride:(s,i,c)=>{var d;const u=r().settings,h={...u.agentOverrides};if(c===null){if(h[s]){const f={...h[s]};delete f[i],Object.keys(f).length===0?delete h[s]:h[s]=f}}else h[s]={...h[s],[i]:{...((d=h[s])==null?void 0:d[i])??{},...c}};const l={...u,agentOverrides:h};e({settings:l}),Hd(l)}}));function Hd(e){Yt.getState().setSetting(ot.NOTIFICATION_SETTINGS,JSON.stringify(e))}function Gx(e){var r,s,i,c,u;return{soundEnabled:e.soundEnabled??hh.soundEnabled,browserNotificationEnabled:e.browserNotificationEnabled??hh.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,...(c=e.events)==null?void 0:c.phase_blocked},new_message:{...Fv,...(u=e.events)==null?void 0:u.new_message}},agentOverrides:e.agentOverrides??{}}}const Kx=new Map;function G1(e){let r=Kx.get(e);return r||(r=new Audio(e),r.volume=.5,Kx.set(e,r)),r}let $v=typeof Notification<"u"?Notification.permission:"denied";function K1(){return typeof Notification>"u"?Promise.resolve("denied"):Notification.requestPermission().then(e=>($v=e,e))}const Y1={complete:"Task Complete",waiting_for_user:"Waiting for Input",phase_done:"Phase Complete",phase_blocked:"Phase Blocked",new_message:"New Message"},X1={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 Z1(e){typeof Notification>"u"||$v==="granted"&&(document.hasFocus()||new Notification(Y1[e],{body:X1[e],icon:"/fox.svg",tag:`openfox-${e}`}))}function go(e,r){const{settings:s}=Fs.getState(),i=Uv(s,e,r);if(s.soundEnabled&&i.soundEnabled){const c=i.customSoundUrl??Hv[e],u=G1(c);u.currentTime=0,u.play().catch(()=>{})}s.browserNotificationEnabled&&i.browserNotification&&Z1(e)}const Q1=e=>go("complete",e),J1=e=>go("phase_done",e),ew=e=>go("phase_blocked",e),Yx=e=>go("waiting_for_user",e),tw=e=>go("new_message",e);let $a=!1,pr=null;const Fd=new Set,Vt={messageId:null,deltaContent:"",thinkingContent:"",toolOutput:[]};let Ui=null,mn=null;function Ud(){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 nw(e,r,s){return e.id!==void 0||Ht(e,r)||s===!0&&e.sessionId!==void 0}function rw(e,r){return e.includes(r)?e:[...e,r]}function qa(e,r){return e.filter(s=>s!==r)}function sw(e,r){const s=e.find(c=>c.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(c=>c.status.type==="passed").length}:{id:r.id,projectId:r.projectId,workdir:r.workdir,mode:r.mode,phase:r.phase,isRunning:r.isRunning,createdAt:"",updatedAt:"",criteriaCount:r.criteria.length,criteriaCompleted:r.criteria.filter(c=>c.status.type==="passed").length,messageCount:r.messages.length};return s?e.map(c=>c.id===r.id?i:c):[i,...e]}function Xx(e,r,s){return e.map(i=>{const c=(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:(c==null?void 0:c.mode)??(u==null?void 0:u.mode)??i.mode,phase:(c==null?void 0:c.phase)??(u==null?void 0:u.phase)??i.phase,isRunning:i.isRunning&&(u==null?void 0:u.isRunning)!==!1,messageCount:i.messageCount,recentUserPrompts:i.recentUserPrompts}})}const Zx=new Map;function Ja(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),c=(s==null?void 0:s.mode)??(i==null?void 0:i.mode);return c==="planner"?"planner":c==="builder"?"build":"planner"}function iw(e,r){if(e.type==="chat.done"){const s=e.payload,i=Ja(r,e.sessionId),c=s.agentType??i;s.reason==="complete"&&Q1(c),s.reason==="waiting_for_user"&&Yx(c);return}if(e.type==="chat.path_confirmation"){const s=Ja(r,e.sessionId);Yx(s);return}if(e.type==="task.completed"){const s=Ja(r,e.sessionId);J1(s);return}if(e.type==="phase.changed"&&e.sessionId){const s=e.payload,i=Zx.get(e.sessionId)??null;if(Zx.set(e.sessionId,s.phase),i===s.phase)return;const c=Ja(r,e.sessionId);s.phase==="blocked"&&ew(c)}}const Ce=$n((e,r)=>(mn=()=>{const s=Vt;if(!s.messageId)return;const i=s.deltaContent.length>0,c=s.thinkingContent.length>0,u=s.toolOutput.length>0;if(!i&&!c&&!u)return;const h=s.deltaContent,l=s.thinkingContent,d=s.toolOutput;s.deltaContent="",s.thinkingContent="",s.toolOutput=[],e(f=>{var m;const g=f.streamingMessage;if(g&&g.id===s.messageId){let v={...g};if(i&&(v.content=v.content+h),c&&(v.thinkingContent=(v.thinkingContent??"")+l),u){const S=new Set;v.toolCalls=(m=v.toolCalls)==null?void 0:m.map(C=>{const y=d.filter(b=>b.callId===C.id);return y.length===0?C:(S.add(C.id),{...C,streamingOutput:[...C.streamingOutput??[],...y.map(b=>({stream:b.stream,content:b.content,timestamp:Date.now()}))]})});const k=d.filter(C=>!S.has(C.callId));k.length>0&&Vt.toolOutput.push(...k)}return{streamingMessage:v}}if(u){const v=new Set,S=f.messages.map(C=>{var b;if(C.id!==s.messageId)return C;const y=(b=C.toolCalls)==null?void 0:b.map(x=>{const _=d.filter(j=>j.callId===x.id);return _.length===0?x:(v.add(x.id),{...x,streamingOutput:[...x.streamingOutput??[],..._.map(j=>({stream:j.stream,content:j.content,timestamp:Date.now()}))]})});return{...C,toolCalls:y}}),k=d.filter(C=>!v.has(C.callId));return k.length>0&&Vt.toolOutput.push(...k),{messages:S}}return f})},{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(c=>{var u;if(e({connectionStatus:c}),c==="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(),!$a){$a=!0;const c=r().handleServerMessage;pr=Gt.subscribe(c)}}catch(c){console.error("Failed to connect:",c);const u=Gt.getLastCloseCode();if(!Gt.hasToken()&&(u===1006||u===4e3)){e({showPasswordModal:!0,passwordModalRetry:!0,connectionStatus:"reconnecting"});return}pr&&(pr(),pr=null),$a=!1,e({connectionStatus:"disconnected"})}},reconnect:()=>{Gt.disconnect(),pr&&(pr(),pr=null),$a=!1,e({connectionStatus:"disconnected"}),r().connect()},disconnect:()=>{Gt.disconnect(),pr&&(pr(),pr=null),$a=!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:c}=await i.json();Gt.setToken(c),e({showPasswordModal:!1}),r().connect();const{listProjects:u}=Ft.getState(),{fetchConfig:h}=Rt.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)=>{if(r().pendingSessionCreate)return null;try{e({pendingSessionCreate:!0});const u=await ke("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectId:s,title:i})});if(!u.ok)return e({pendingSessionCreate:!1}),null;const h=await u.json();return Gt.send("session.load",{sessionId:h.session.id}),h.session}catch{return e({pendingSessionCreate:!1}),null}},loadSession:async s=>{try{const i=r().currentSession;!i||i.id!==s?(Is(),e({currentSession:null,unreadSessionIds:qa(r().unreadSessionIds,s),subAgentContextStates:{},messages:[],streamingMessageId:null,streamingMessage:null,currentTodos:[],contextState:null,pendingPathConfirmation:null,queuedMessages:[],abortInProgress:!1,error:null,pendingSessionCreate:!1})):e({unreadSessionIds:qa(r().unreadSessionIds,s)});const c=await ke(`/api/sessions/${s}`);if(!c.ok)return;const u=await c.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 l=await h.json();to.getState().setProcesses(l.processes??[])}}catch{}}catch{}},listSessions:async(s,i=20)=>{try{const c=new URLSearchParams;c.set("limit",String(i)),s&&c.set("projectId",s);const h=await(await ke(`/api/sessions?${c.toString()}`)).json(),l=h.sessions??[];e(d=>({sessions:Xx(l,d.sessions,d.currentSession),sessionsHasMore:s?h.hasMore??!1:!0}))}catch{}},loadMoreSessions:async s=>{const i=r();if(!(i.sessionsPaginationLoading||!i.sessionsHasMore)){e({sessionsPaginationLoading:!0});try{const c=new URLSearchParams;c.set("limit","20"),c.set("offset",String(i.sessions.length)),c.set("projectId",s);const h=await(await ke(`/api/sessions?${c.toString()}`)).json(),l=h.sessions??[];e(d=>({sessions:[...d.sessions,...l.map(f=>{const g=d.sessions.find(m=>m.id===f.id);return(g==null?void 0:g.isRunning)===!1?{...f,isRunning:!1}:f})],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,pendingSessionCreate:!1,unreadSessionIds:s.currentSession?qa(s.unreadSessionIds,s.currentSession.id):s.unreadSessionIds}))},sendMessage:async(s,i,c)=>{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:c==null?void 0:c.messageKind})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(l){console.error("Error sending message:",l)}}},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(c){console.error("Error stopping generation:",c)}}},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(c){console.error("Error continuing generation:",c)}}},launchRunner:(s,i,c)=>{e({streamingMessageId:null});const u={};s!=null&&s.trim()&&(u.content=s),i&&i.length>0&&(u.attachments=i),c&&(u.workflowId=c),Gt.send("runner.launch",u)},switchMode:async s=>{var c;const i=(c=r().currentSession)==null?void 0:c.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 c;const i=(c=r().currentSession)==null?void 0:c.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,c)=>{var l;e({streamingMessageId:null});const u={};s&&(u.workflowId=s),i!=null&&i.trim()&&(u.content=i),c&&c.length>0&&(u.attachments=c);const h=(l=r().currentSession)==null?void 0:l.id;h&&ke(`/api/sessions/${h}/mode`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:"builder"})}).then(()=>{Gt.send("runner.launch",u)})},editCriteria:async s=>{var c;const i=(c=r().currentSession)==null?void 0:c.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 c;try{const u=(c=r().currentSession)==null?void 0:c.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 l=await h.json();return e({currentSession:l.session,messages:l.messages??[],contextState:l.contextState}),l.session}catch{return null}},updateContextState:s=>{e({contextState:s})},updateSubAgentContextState:(s,i)=>{e(c=>({subAgentContextStates:{...c.subAgentContextStates,[s]:i}}))},clearSubAgentContextState:s=>{e(i=>{const c={...i.subAgentContextStates};return delete c[s],{subAgentContextStates:c}})},confirmPath:async(s,i,c=!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:c})})}catch(l){console.error("Error confirming path:",l)}},answerQuestion:async(s,i)=>{var u;const c=(u=r().currentSession)==null?void 0:u.id;if(c){try{await ke(`/api/sessions/${c}/answer`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({callId:s,answer:i})})}catch(h){console.error("Error answering question:",h)}e({pendingQuestion:null})}},queueAsap:async(s,i,c)=>{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:c})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(l){console.error("Error queueing ASAP message:",l)}},queueCompletion:async(s,i,c)=>{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:c})})).json();d.queueState&&e({queuedMessages:d.queueState})}catch(l){console.error("Error queueing completion message:",l)}},cancelQueued:async s=>{var c;const i=(c=r().currentSession)==null?void 0:c.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,l,d,f,g,m,v,S,k,C,y,b,x,_,j,A,N,D,T,z,O,q,G,W;const i=r();iw(s,i);const c=((h=i.currentSession)==null?void 0:h.id)??null,u=()=>{const I=s.sessionId;!I||I===c||e($=>({unreadSessionIds:rw($.unreadSessionIds,I)}))};switch(s.type){case"session.state":{const I=s.payload;if(!nw(s,c,i.pendingSessionCreate))break;Is();const $=I.messages.find(L=>L.isStreaming)??null,B=r().pendingSessionCreate===!0,X=I.pendingConfirmations??[],H=i.pendingPathConfirmation??(X.length>0?X[0]??null:null);if(e({currentSession:I.session,sessions:sw(r().sessions,I.session),unreadSessionIds:qa(r().unreadSessionIds,I.session.id),messages:I.messages,streamingMessageId:($==null?void 0:$.id)??null,streamingMessage:$,currentTodos:[],pendingPathConfirmation:H,error:null,...B?{pendingSessionCreate:I.session.id}:{}}),I.session.providerId&&I.session.providerModel){const L=Rt.getState();L.providers.find(U=>U.id===I.session.providerId)&&L.syncFromSession(I.session.providerId,I.session.providerModel)}break}case"session.list":{const I=s.payload;e($=>({sessions:Xx(I.sessions,$.sessions,$.currentSession)}));break}case"session.deleted":{const I=s.payload;e($=>({unreadSessionIds:qa($.unreadSessionIds,I.sessionId)})),r().listSessions();break}case"session.deletedAll":{r().listSessions();break}case"session.running":{const I=s.payload,$=s.sessionId,B=(l=r().currentSession)==null?void 0:l.id,X=$&&$!==B;e(Q=>({sessions:Q.sessions.map(H=>H.id===$?{...H,isRunning:I.isRunning}:H)})),X||e(Q=>({currentSession:Q.currentSession?{...Q.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,((f=r().currentSession)==null?void 0:f.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,Q=$;if(X&&X.id===I.messageId){const H={...X,...I.updates};return{messages:B.messages.map(L=>L.id===I.messageId?H:L),streamingMessageId:Q?null:B.streamingMessageId,streamingMessage:Q?null:{...X,...I.updates}}}return{messages:B.messages.map(H=>H.id===I.messageId?{...H,...I.updates}:H),streamingMessageId:Q?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(!Fd.has(I.messageId)){Fd.add(I.messageId);const $=Ja(r(),s.sessionId);tw($)}Vt.messageId=I.messageId,Vt.deltaContent+=I.content,Ud();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,Ud();break}case"chat.tool_preparing":{if(!Ht(s,((v=r().currentSession)==null?void 0:v.id)??null)){u();break}const I=s.payload;e($=>{const B=$.streamingMessage;return B&&B.id===I.messageId?{streamingMessage:{...B,preparingToolCalls:[...B.preparingToolCalls??[],{index:I.index,name:I.name}]}}:{messages:$.messages.map(X=>X.id===I.messageId?{...X,preparingToolCalls:[...X.preparingToolCalls??[],{index:I.index,name:I.name}]}:X)}});break}case"chat.tool_call":{if(!Ht(s,((S=r().currentSession)==null?void 0:S.id)??null)){u();break}const I=s.payload,$=B=>{var H;const X=(H=B.preparingToolCalls)==null?void 0:H.filter((L,R)=>{var U;return L.name===I.tool?(U=B.preparingToolCalls)==null?void 0:U.slice(0,R).some(ne=>ne.name===I.tool):!0}),Q=Vt.toolOutput.filter(L=>L.callId===I.callId);return Q.length>0&&(Vt.toolOutput=Vt.toolOutput.filter(L=>L.callId!==I.callId)),{...B,toolCalls:[...B.toolCalls??[],{id:I.callId,name:I.tool,arguments:I.args,startedAt:Date.now(),...Q.length>0?{streamingOutput:Q.map(L=>({stream:L.stream,content:L.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(Q=>Q.id===I.messageId?$(Q):Q)}});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}),Ud();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 Q;const X=(Q=B.toolCalls)==null?void 0:Q.map(H=>H.id===I.callId?{...H,result:I.result}:H);return{...B,toolCalls:X}};e(B=>{const X=B.streamingMessage;return X&&X.id===I.messageId?{streamingMessage:$(X)}:{messages:B.messages.map(Q=>Q.id===I.messageId?$(Q):Q)}});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,((b=r().currentSession)==null?void 0:b.id)??null)){u();break}const I=s.payload;e({currentTodos:I.todos});break}case"chat.summary":{if(!Ht(s,((x=r().currentSession)==null?void 0:x.id)??null)){u();break}const I=s.payload;e($=>({currentSession:$.currentSession?{...$.currentSession,summary:I.summary}:null}));break}case"chat.progress":{if(!Ht(s,((_=r().currentSession)==null?void 0:_.id)??null)){u();break}const I=s.payload;console.log("Progress:",I.message,I.phase);break}case"chat.format_retry":{if(!Ht(s,((j=r().currentSession)==null?void 0:j.id)??null)){u();break}const I=s.payload;console.log("Format retry:",I.attempt,"/",I.maxAttempts);break}case"chat.done":{if(!Ht(s,((A=r().currentSession)==null?void 0:A.id)??null)){u();break}Is(),mn==null||mn();const I=s.payload,$=I.stats;Vt.messageId=null,Vt.deltaContent="",Vt.thinkingContent="",Vt.toolOutput=[],Fd.delete(I.messageId),e(B=>{const X=B.streamingMessage,Q=X&&X.id===I.messageId?{...X,isStreaming:!1,stats:$??X.stats}:null;return{messages:B.messages.map(H=>H.id===I.messageId?Q??{...H,isStreaming:!1,stats:$??H.stats}:H),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,((T=r().currentSession)==null?void 0:T.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(Q=>({sessions:Q.sessions.map(H=>H.id===$?{...H,phase:I.phase}:H)})),X||e(Q=>({currentSession:Q.currentSession?{...Q.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 Q=X.sessions.map(L=>L.id===$?{...L,title:I.name,updatedAt:new Date().toISOString()}:L),H=B===$?X.currentSession?{...X.currentSession,title:I.name,updatedAt:new Date().toISOString()}:null:X.currentSession;return{sessions:Q,currentSession:H}});break}case"queue.state":{const I=s.payload;e({queuedMessages:I.messages});break}case"devServer.output":case"devServer.state":{gr.getState().handleMessage(s);break}case"backgroundProcess.started":case"backgroundProcess.output":case"backgroundProcess.exited":case"backgroundProcess.removed":{to.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 qv(){return Ce(e=>{var r;return((r=e.currentSession)==null?void 0:r.isRunning)??!1})}function aw(){return Ce(e=>e.queuedMessages)}function ow(){return Ce(e=>e.abortInProgress)}function lw(){const e=Ce(i=>i.connect),r=Ce(i=>i.connectionStatus),s=Fs(i=>i.load);return P.useEffect(()=>{e()},[e]),P.useEffect(()=>{r==="connected"&&s()},[r,s]),{connectionStatus:r}}const cw="modulepreload",uw=function(e){return"/"+e},Qx={},fh=function(r,s,i){let c=Promise.resolve();if(s&&s.length>0){let h=function(f){return Promise.all(f.map(g=>Promise.resolve(g).then(m=>({status:"fulfilled",value:m}),m=>({status:"rejected",reason:m}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),d=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));c=h(s.map(f=>{if(f=uw(f),f in Qx)return;Qx[f]=!0;const g=f.endsWith(".css"),m=g?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${m}`))return;const v=document.createElement("link");if(v.rel=g?"stylesheet":cw,g||(v.as="script"),v.crossOrigin="",v.href=f,d&&v.setAttribute("nonce",d),document.head.appendChild(v),g)return new Promise((S,k)=>{v.addEventListener("load",S),v.addEventListener("error",()=>k(new Error(`Unable to preload CSS for ${f}`)))})}))}function u(h){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=h,window.dispatchEvent(l),!l.defaultPrevented)throw h}return c.then(h=>{for(const l of h||[])l.status==="rejected"&&u(l.reason);return r().catch(u)})},Wv=[{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"}],xr=[{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 Jx(){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:Jx(),applySavedTheme:()=>{const{getSavedTheme:s,applyPreset:i,applyTokens:c}=r(),u=s();if(u)try{const h=JSON.parse(u);h.preset&&h.tokens?(i(h.preset),e({basePreset:h.preset}),c(h.tokens)):h.preset?i(h.preset):h.tokens&&c(h.tokens)}catch{i("dark")}else i("dark")},applyPreset:s=>{xr.find(c=>c.id===s)&&(e({currentPreset:s,basePreset:"",customTokens:{},isCustom:!1,isCustomizing:!1}),r().applyTheme())},startCustomizing:()=>{var c;const{currentPreset:s}=r(),i=((c=xr.find(u=>u.id===s))==null?void 0:c.tokens)??{};e({basePreset:s,customTokens:{...i},isCustom:!0,isCustomizing:!0})},setCustomToken:(s,i)=>{e(c=>({customTokens:{...c.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,l;const{basePreset:s,customTokens:i,isCustom:c}=r();if(c&&s)return{...((h=xr.find(f=>f.id===s))==null?void 0:h.tokens)??{},...i};if(c)return{...Wv.reduce((d,f)=>({...d,[f.key]:f.defaultValue}),{}),...i};const u=xr.find(d=>d.id===r().currentPreset);return(u==null?void 0:u.tokens)??((l=xr[0])==null?void 0:l.tokens)??{}},applyTheme:()=>{if(typeof document>"u")return;const s=r().getActiveTheme(),i=document.documentElement;Object.entries(s).forEach(([c,u])=>{i.style.setProperty(`--${c}`,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),fh(async()=>{const{useSettingsStore:i}=await Promise.resolve().then(()=>Ix);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:c,currentPreset:u}=r(),h={id:"custom-"+Date.now(),name:s,basePreset:i||u,tokens:{...c}},l=[...r().userPresets,h];e({userPresets:l}),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((c,u)=>u!==s);e({userPresets:i}),r().saveUserPresets()},loadUserPresets:()=>{e({userPresets:Jx()})},saveUserPresets:()=>{localStorage.setItem("openfox:userPresets",JSON.stringify(r().userPresets)),fh(async()=>{const{useSettingsStore:s}=await Promise.resolve().then(()=>Ix);return{useSettingsStore:s}},void 0).then(({useSettingsStore:s})=>{s.getState().setSetting(ot.DISPLAY_USER_PRESETS,JSON.stringify(r().userPresets)).catch(()=>{})})}}));function dw({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 Vv({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 hw({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 fw({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 pw({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 br({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 mw({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 Ih({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 gw({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 Bh({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,fill:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("circle",{cx:"12",cy:"5",r:"2"}),o.jsx("circle",{cx:"12",cy:"12",r:"2"}),o.jsx("circle",{cx:"12",cy:"19",r:"2"})]})}function lc({className:e="w-3.5 h-3.5"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"})})}function zh({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 xw({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 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:"M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"})})}function vw({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 yw({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 _w({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 eb({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 Gv({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 Sw({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 ww({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 qi({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 Cw({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 kw({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 Ew({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 jw({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 Nw({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 Tw({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 Aw({className:e="w-4 h-4"}){return o.jsxs("svg",{className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("polyline",{points:"4 17 10 11 4 5"}),o.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function Ph({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 Hh(){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 Dw({className:e="w-4 h-4"}){return o.jsx("svg",{className:e,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})})}function Kv({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 Fh({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 Rw({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 ph(){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 tb(e,r){const s=Gt.ws;!s||s.readyState!==WebSocket.OPEN||s.send(JSON.stringify({id:ph(),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 c=await i.json();e({sessions:c});const u=Gt.ws;if(u&&u.readyState===WebSocket.OPEN)for(const h of c)u.send(JSON.stringify({id:ph(),type:"terminal.subscribe",payload:{sessionId:h.id}}))}}catch(i){console.error("Failed to fetch terminals:",i)}},createSession:async(s,i)=>{try{const c=await ke("/api/terminals",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workdir:s??r().workdir??void 0,projectId:i})});if(c.ok){const u=await c.json();e(l=>({sessions:[...l.sessions,u]}));const h=Gt.ws;h&&h.readyState===WebSocket.OPEN&&h.send(JSON.stringify({id:ph(),type:"terminal.subscribe",payload:{sessionId:u.id}}))}}catch(c){console.error("Failed to create terminal:",c)}},writeSession:(s,i)=>{tb("terminal.write",{sessionId:s,data:i})},resizeSession:(s,i,c)=>{tb("terminal.resize",{sessionId:s,cols:i,rows:c})},killSession:async s=>{try{(await ke(`/api/terminals/${s}`,{method:"DELETE"})).ok&&e(c=>({sessions:c.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(c=>{const u=c.sessions.filter(h=>h.id!==i);return u.length===0&&c.isOpen?{sessions:[],isOpen:!1}:{sessions:u}});break}}}}));Gt.subscribe(e=>{var r;(r=e.type)!=null&&r.startsWith("terminal.")&&ir.getState().handleMessage(e)});var xo=Nv();const cc=P.forwardRef(({icon:e,iconSize:r="w-3.5 h-3.5",className:s="",...i},c)=>o.jsx("button",{ref:c,type:"button",className:`p-1 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors ${s}`,...i,children:o.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:e})})}));cc.displayName="IconButton";const Lw="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",Wi=P.forwardRef((e,r)=>o.jsx(cc,{ref:r,icon:Lw,title:"Edit",...e}));Wi.displayName="EditButton";const Ow="M6 18L18 6M6 6l12 12",Uh=P.forwardRef((e,r)=>o.jsx(cc,{ref:r,icon:Ow,...e}));Uh.displayName="CloseButton";const Mw={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:c,footer:u,className:h,onClose:l,isOpen:d,closeOnBackdropClick:f=!0,closeOnEscape:g=!0,showCloseButton:m=!0}){const[v,S]=P.useState(!1),k=d!==void 0,C=k?d:v,y=P.useCallback(()=>{k||S(!0)},[k]),b=P.useCallback(()=>{k||S(!1),l==null||l()},[k,l]);P.useEffect(()=>{if(!C||!g)return;const _=j=>{j.key==="Escape"&&b()};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[C,b,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"?xo.createPortal(o.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",children:[o.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:f?b:void 0}),o.jsxs("div",{className:`relative w-full ${Mw[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(Uh,{onClick:b,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:c}),u&&o.jsx("div",{className:"px-4 py-3 border-t border-border",children:u})]})]}),document.body):null)]})}const nt=P.forwardRef(({variant:e="secondary",size:r="md",className:s="",children:i,...c},u)=>{const h="rounded font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed",l={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} ${l[e]} ${d[r]} ${s}`,...c,children:i})});nt.displayName="Button";function Iw({value:e,defaultUrl:r,disabled:s,onChange:i}){const c=e??r;return o.jsxs("div",{className:"relative",children:[o.jsx("select",{value:c,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:V1.map(({url:u,label:h})=>o.jsx("option",{value:u,title:h,children:h.split(" ")[0]},u))}),o.jsx(br,{className:"absolute right-0.5 top-1/2 -translate-y-1/2 w-3 h-3 pointer-events-none text-text-muted"})]})}const nb=[{key:"general",label:"General"},{key:"build",label:"Agent"},{key:"sub-agent",label:"Sub-agent"}];function Bw(){const e=Fs(d=>d.settings),r=Fs(d=>d.update),s=Fs(d=>d.updateEvent),i=Fs(d=>d.updateAgentOverride),c=Fs(d=>d.load);P.useEffect(()=>{c()},[c]);const u=async()=>{await K1()==="granted"&&r({...e,browserNotificationEnabled:!0})},h=(d,f,g,m)=>{d==="general"?s(f,{[g]:m}):i(d,f,{[g]:m})},l=(d,f,g)=>{d==="general"?s(f,{customSoundUrl:g}):i(d,f,{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(rb,{label:"Sound notifications",description:"Play sounds when events occur",checked:e.soundEnabled,onChange:d=>r({...e,soundEnabled:d})}),o.jsx(rb,{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"}),nb.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:W1.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})}),nb.map(f=>{const g=Uv(e,d.key,f.key==="general"?void 0:f.key),m=Hv[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:v=>h(f.key,d.key,"soundEnabled",v.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:v=>h(f.key,d.key,"browserNotification",v.target.checked),disabled:!e.browserNotificationEnabled,className:"rounded border-border",title:"Browser"})})]}),g.soundEnabled&&e.soundEnabled&&o.jsx(Iw,{value:g.customSoundUrl,defaultUrl:m,disabled:!e.soundEnabled,onChange:v=>l(f.key,d.key,v)})]})},f.key)})]},d.key))})]})})]})]})}function rb({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:c=>{c.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 $h(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 $h("/api/skills",e)},toggleSkill:async s=>{try{const c=await(await ke(`/api/skills/${s}/toggle`,{method:"POST"})).json();e(u=>({defaults:u.defaults.map(h=>h.id===s?{...h,enabled:c.enabled}:h),userItems:u.userItems.map(h=>h.id===s?{...h,enabled:c.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 c=await xs("PUT",`/api/skills/${s}`,i);return c.success&&await r().fetchSkills(),c},deleteSkill:async s=>{try{const i=await ke(`/api/skills/${s}`,{method:"DELETE"}),c=await i.json();return i.ok?(e(u=>({userItems:u.userItems.filter(h=>h.id!==s)})),{success:!0}):{success:!1,error:c.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"}),c=await i.json();return i.ok?(await r().fetchSkills(),{success:!0}):{success:!1,error:c.error??"Failed to duplicate"}}catch{return{success:!1,error:"Network error"}}}}));function qh(){const[e,r]=P.useState({id:null,type:null}),s=P.useCallback(u=>r({id:u,type:"delete"}),[]),i=P.useCallback(()=>r({id:null,type:null}),[]),c=P.useCallback((u,h)=>e.id===u&&e.type===h,[e.id,e.type]);return{requestDelete:s,clearConfirm:i,isConfirming:c}}function Wh({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 Vh({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(Ph,{})})}function ao({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(Ih,{})})}function Us({label:e,value:r,onChange:s,placeholder:i,readOnly:c,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:l=>s(l.target.value),readOnly:c,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":""} ${c?"opacity-60":""}`})]})}function zw({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(nt,{variant:"secondary",onClick:e,children:"Cancel"}),o.jsx(nt,{variant:"primary",onClick:r,disabled:s||i,children:s?"Saving...":"Save"})]})}function Gh({message:e}){return o.jsx("div",{className:"text-accent-error text-sm px-3 py-2 bg-accent-error/10 rounded",children:e})}function Yv({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(nt,{variant:"primary",size:"sm",onClick:r,children:s})})]})}function Xv({isBuiltIn:e,isConfirmingDelete:r,onView:s,onEdit:i,onDuplicate:c,onDelete:u,children:h}){return o.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border bg-bg-tertiary",children:[o.jsx("div",{className:"min-w-0 flex-1 mr-3",children:h}),o.jsxs("div",{className:"flex items-center gap-1.5 flex-shrink-0",children:[e&&s&&o.jsx("button",{onClick:s,className:"p-1.5 rounded text-text-muted hover:text-text-primary hover:bg-bg-primary transition-colors",title:"View",children:o.jsx(lc,{})}),o.jsx(ao,{onClick:c}),!e&&i&&o.jsx(Wi,{onClick:i}),!e&&(r?o.jsx(Wh,{onConfirm:()=>{u==null||u()},onCancel:()=>{}}):o.jsx(Vh,{onClick:()=>u==null?void 0:u()}))]})]})}function Pw({id:e,name:r,description:s,isBuiltIn:i,isConfirmingDelete:c,onView:u,onEdit:h,onDuplicate:l,onDelete:d}){return o.jsxs(Xv,{isBuiltIn:i,isConfirmingDelete:c,onView:u,onEdit:h,onDuplicate:l,onDelete:d,children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-text-primary text-sm font-medium",children:r}),o.jsx("span",{className:"text-text-muted text-xs font-mono",children:e})]}),s&&o.jsx("p",{className:"text-text-muted text-xs truncate",children:s})]})}function Zv({loading:e,hasItems:r,loadingLabel:s,emptyLabel:i,children:c}){return e&&!r?o.jsx("div",{className:"text-text-muted text-sm",children:s}):r?o.jsx("div",{className:"space-y-4",children:c}):i?o.jsx("div",{className:"text-text-muted text-sm",children:i}):null}function Qv({name:e,id:r,nameLabel:s="Name",idLabel:i="ID",namePlaceholder:c="My Item",idPlaceholder:u="my-item",nameHint:h,readOnlyId:l=!1,readOnlyHint:d="(read-only)",onNameChange:f,onIdChange:g}){return o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsx(Us,{label:s,value:e,onChange:f,placeholder:c,hint:h}),o.jsx(Us,{label:i,value:r,onChange:g,readOnly:l,placeholder:u,hint:l?d:void 0,mono:!0})]})}function Jv(e={}){const{initialData:r={}}=e,[s,i]=P.useState("list"),[c,u]=P.useState(null),[h,l]=P.useState(""),[d,f]=P.useState(!1),[g,m]=P.useState(r),v=P.useCallback(()=>{m(r),l(""),u(null)},[r]),S=P.useCallback(b=>{i(b),b==="list"&&v()},[v]),k=P.useCallback(b=>{m(x=>typeof b=="function"?b(x):b)},[]),C=P.useCallback((b,x={})=>{u(b),i("edit"),m({...x}),l("")},[]),y=P.useCallback(()=>{u(null),i("edit"),m(r),l("")},[r]);return{view:s,editingId:c,formError:h,saving:d,formData:g,setView:S,setEditingId:u,setFormError:l,setFormData:k,setSaving:f,resetForm:v,startEditing:C,startNew:y}}function Kh(){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 sb({skill:e,isBuiltIn:r,isConfirmingDelete:s,onView:i,onEdit:c,onDuplicate:u,onDelete:h}){return o.jsx(Pw,{id:e.id,name:e.name,description:e.description,isBuiltIn:r,isConfirmingDelete:s,onView:i,onEdit:c,onDuplicate:u,onDelete:h})}function Hw({isOpen:e}){const r=Pr(I=>I.defaults),s=Pr(I=>I.userItems),i=Pr(I=>I.loading),c=Pr(I=>I.fetchSkills),u=Pr(I=>I.fetchSkill),h=Pr(I=>I.fetchDefaultContent),l=Pr(I=>I.createSkill),d=Pr(I=>I.updateSkill),f=Pr(I=>I.deleteSkill),{view:g,editingId:m,formError:v,saving:S,formData:k,setView:C,setEditingId:y,setFormError:b,setFormData:x,setSaving:_}=Jv(),{clearConfirm:j}=qh();P.useEffect(()=>{e&&(c(),C("list"),y(null),j())},[e,c,j]);const A=(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;A(B,!0),y(I),b(""),C("edit")}else{const B=await u(I);if(!B)return;A(B,!0),y(I),b(""),C("edit")}},D=async I=>{const B=r.some(Q=>Q.id===I)?await h(I):await u(I);if(!B)return;const X=`${I}-copy-${Date.now()}`;A(B,!1,X,`${B.metadata.name} (copy)`),y(null),b(""),C("edit")},T=()=>{x({name:"",id:"",description:"",version:"1.0.0",prompt:"",isReadOnly:!1}),C("edit")},z=async I=>{const $=await u(I);$&&(A($,!1),y(I),b(""),C("edit"))},O=async I=>{await f(I),j()},q=async()=>{const I=m??k.id;if(!I||!k.name||!k.prompt){b("Name, ID, and prompt are required.");return}_(!0),b("");const $={metadata:{id:I,name:k.name,description:k.description,version:k.version},prompt:k.prompt},B=m?await d(m,$):await l($);if(_(!1),!B.success){b(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"})]}),v&&o.jsx(Gh,{message:v}),o.jsxs("div",{className:"space-y-3 mb-3",children:[o.jsx(Qv,{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(Kh,{}),o.jsxs("div",{className:"flex justify-end gap-2 pt-3 border-t border-border flex-shrink-0",children:[o.jsx(nt,{variant:"secondary",onClick:()=>C("list"),children:"Cancel"}),W?o.jsx(nt,{variant:"primary",onClick:()=>{x(I=>({...I,name:I.name+" (copy)",id:`${m}-copy-${Date.now()}`,isReadOnly:!1})),y(null)},children:"Duplicate & Customize"}):o.jsx(nt,{variant:"primary",onClick:q,disabled:S||!k.name||!k.id||!k.prompt,children:S?"Saving...":"Save"})]})]}):o.jsxs("div",{children:[o.jsx(Yv,{description:"Skills provide domain-specific knowledge that agents can load on demand.",onNew:T}),o.jsxs(Zv,{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(sb,{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(sb,{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 Fw(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),c=parseInt(r[3]??"0",16);return`${s} ${i} ${c}`}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 Uw({isOpen:e,isNew:r,basePresetId:s,presetName:i,initialTokens:c,onClose:u,onSave:h}){const[l,d]=P.useState(c),[f,g]=P.useState(i);P.useEffect(()=>{d(c),g(i)},[c,i]);const m=(y,b)=>{const x=b.startsWith("#")?Fw(b):b;d(_=>({..._,[y]:x}))},v=()=>{h(f.trim()||"Untitled",{...l})},S=Wv.reduce((y,b)=>{const x=b.category;return y[x]||(y[x]=[]),y[x].push(b),y},{}),k={background:"Backgrounds",surface:"Surfaces",text:"Text",accent:"Accents",border:"Border"},C=xr.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:v,className:"px-4 py-2 bg-accent-primary text-white rounded hover:bg-accent-primary/80 transition-colors text-sm",children:"Save"})]}),children:o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-text-muted block mb-1",children:"Name"}),o.jsx("input",{type:"text",value:f,onChange:y=>g(y.target.value),className:"w-full px-3 py-2 bg-bg-tertiary border border-border rounded text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-accent-primary"})]}),!r&&o.jsxs("div",{className:"text-xs text-text-muted",children:["Based on ",o.jsx("span",{className:"text-text-primary",children:C==null?void 0:C.name})]}),Object.entries(S).map(([y,b])=>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:b.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(l[x.key]??x.defaultValue),onChange:_=>m(x.key,_.target.value),className:"w-8 h-8 rounded cursor-pointer border border-border bg-transparent"}),o.jsx("input",{type:"text",value:l[x.key]??x.defaultValue,onChange:_=>m(x.key,_.target.value),className:"flex-1 px-2 py-1 bg-bg-tertiary border border-border rounded text-xs text-text-primary font-mono focus:outline-none focus:ring-1 focus:ring-accent-primary"})]})]},x.key))})]},y))]})})}function $w(){const[e,r]=P.useState(null),s=dn(x=>x.currentPreset),i=dn(x=>x.isCustom),c=dn(x=>x.basePreset),u=dn(x=>x.userPresets),h=dn(x=>x.applyPreset),l=dn(x=>x.applyUserPreset),d=dn(x=>x.deleteUserPreset),f=dn(x=>x.saveTheme),g=x=>{h(x),f(JSON.stringify({preset:x}))},m=x=>{l(x)},v=x=>{const _=xr.find(j=>j.id===x);_&&r({type:"new",presetIndex:u.length,basePresetId:x,presetName:_.name+" Copy",tokens:{..._.tokens}})},S=x=>{const _=u[x];if(!_)return;const j=xr.find(N=>N.id===_.basePreset),A=j?{...j.tokens,..._.tokens}:_.tokens;r({type:"edit",presetIndex:x,basePresetId:_.basePreset,presetName:_.name,tokens:A})},k=(x,_)=>{if(!e)return;const j=[...u];if(e.type==="new"){const A={id:"custom-"+Date.now(),name:x,basePreset:e.basePresetId,tokens:_};j.push(A);const N=j.length-1;dn.setState({userPresets:j}),dn.getState().saveUserPresets(),dn.getState().applyUserPreset(N)}else{const A=j[e.presetIndex];A&&(j[e.presetIndex]={...A,name:x,tokens:_}),dn.setState({userPresets:j}),dn.getState().saveUserPresets(),dn.getState().applyUserPreset(e.presetIndex)}r(null)},C=()=>{r(null)},y=(x,_)=>{x.stopPropagation(),d(_)},b=i?c: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:xr.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 ${b===x.id&&!i?"border-accent-primary bg-bg-tertiary text-text-primary":"border-border bg-bg-secondary text-text-muted hover:border-text-muted"}`,children:[o.jsx("div",{className:"w-8 h-8 rounded border flex items-center justify-center",style:{backgroundColor:Hs(x.tokens["color-bg-primary"]??"#000"),borderColor:Hs(x.tokens["color-border"]??"#000")},children:o.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:Hs(x.tokens["color-text-primary"]??"#fff")}})}),o.jsx("span",{className:"text-xs",children:x.name})]}),o.jsx("button",{type:"button",onClick:_=>{_.stopPropagation(),v(x.id)},className:"absolute top-1 right-1 w-6 h-6 rounded bg-bg-tertiary border border-border flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:border-text-muted",title:"Create custom theme based on this",children:o.jsx("span",{className:"text-xs",children:"✎"})})]},x.id))}),u.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("h4",{className:"text-xs font-medium text-text-muted uppercase",children:"My Themes"}),o.jsx("div",{className:"grid grid-cols-5 gap-2",children:u.map((x,_)=>{const j=xr.find(N=>N.id===x.basePreset),A=j?{...j.tokens,...x.tokens}:x.tokens;return o.jsxs("div",{className:"relative group",children:[o.jsxs("button",{type:"button",onClick:()=>m(_),className:`w-full flex flex-col items-center gap-2 px-3 py-3 rounded-lg border transition-colors ${i&&c===x.basePreset&&b===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(A["color-bg-primary"]??"#000"),borderColor:Hs(A["color-border"]??"#000")},children:o.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:Hs(A["color-text-primary"]??"#fff")}})}),o.jsx("span",{className:"text-xs truncate w-full text-center",children:x.name})]}),o.jsx("button",{type:"button",onClick:N=>{N.stopPropagation(),S(_)},className:"absolute top-1 right-1 w-6 h-6 rounded bg-bg-tertiary border border-border flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 hover:border-text-muted",title:"Edit",children:o.jsx("span",{className:"text-xs",children:"✎"})}),o.jsx("button",{type:"button",onClick:N=>y(N,_),className:"absolute -top-1 -left-1 w-5 h-5 rounded-full bg-accent-error text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-20",children:o.jsx(Fh,{className:"w-3 h-3"})})]},x.id)})})]}),e&&o.jsx(Uw,{isOpen:!0,isNew:e.type==="new",presetIndex:e.presetIndex,basePresetId:e.basePresetId,presetName:e.presetName,initialTokens:e.tokens,onClose:C,onSave:k})]})}function qw({isOpen:e,onClose:r}){const[s,i]=P.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(Wa,{label:"Instructions",active:s==="instructions",onClick:()=>i("instructions")}),o.jsx(Wa,{label:"Skills",active:s==="skills",onClick:()=>i("skills")}),o.jsx(Wa,{label:"Notifications",active:s==="notifications",onClick:()=>i("notifications")}),o.jsx(Wa,{label:"Display",active:s==="display",onClick:()=>i("display")}),o.jsx(Wa,{label:"Advanced",active:s==="advanced",onClick:()=>i("advanced")})]}),s==="instructions"&&o.jsx(Kw,{isOpen:e}),s==="skills"&&o.jsx(Hw,{isOpen:e}),s==="notifications"&&o.jsx("div",{className:"max-h-[60vh] overflow-y-auto",children:o.jsx(Bw,{})}),s==="display"&&o.jsx(Gw,{}),s==="advanced"&&o.jsx(Ww,{onClose:r})]})})}function Ww({onClose:e}){const[,r]=lr();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(nt,{variant:"secondary",onClick:s,children:"Launch Onboarding"})]})})}function Vw(){return o.jsx($w,{})}function Gw(){const e=Yt(g=>g.settings),r=Yt(g=>g.loading),s=Yt(g=>g.getSetting),i=Yt(g=>g.setSetting),c=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"])),[l,d]=P.useState(()=>Object.fromEntries(u.map(g=>[g.key,h[g.key]==="true"])));P.useEffect(()=>{u.forEach(g=>s(g.key))},[s]),P.useEffect(()=>{d(Object.fromEntries(u.map(g=>[g.key,h[g.key]==="true"])))},[JSON.stringify(h)]);const f=async g=>{const m=String(!l[g]);d(v=>({...v,[g]:!v[g]})),await i(g,m)};return c?o.jsx("div",{className:"text-sm text-text-muted",children:"Loading..."}):o.jsxs("div",{className:"space-y-6",children:[o.jsx(Vw,{}),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:v})=>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:v})]}),o.jsx("button",{type:"button",onClick:()=>f(g),className:`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${l[g]?"bg-accent-primary":"bg-bg-tertiary"}`,children:o.jsx("span",{className:`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${l[g]?"translate-x-6":"translate-x-1"}`})})]},g))})]})]})}function Wa({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 Kw({isOpen:e}){const r=Yt(y=>y.settings),s=Yt(y=>y.loading),i=Yt(y=>y.getSetting),c=Yt(y=>y.setSetting),u=r[ot.GLOBAL_INSTRUCTIONS]??"",h=s[ot.GLOBAL_INSTRUCTIONS]??!1,[l,d]=P.useState(u),[f,g]=P.useState(!1),[m,v]=P.useState(!1);P.useEffect(()=>{e&&i(ot.GLOBAL_INSTRUCTIONS)},[e,i]),P.useEffect(()=>{d(u),g(!1)},[u]);const S=async()=>{v(!0),c(ot.GLOBAL_INSTRUCTIONS,l),v(!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:l,onChange:y=>{d(y.target.value),g(!0)},placeholder:"Enter global instructions that apply to all projects...",className:"w-full min-h-80 px-3 py-2 bg-bg-tertiary border border-border rounded text-sm font-mono resize-y focus:outline-none focus:ring-1 focus:ring-accent-primary",disabled:C})]}),f&&o.jsx(Kh,{}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(nt,{variant:"secondary",onClick:k,disabled:!f,children:"Discard"}),o.jsx(nt,{variant:"primary",onClick:S,disabled:!f||C,children:m?"Saving...":"Save"})]})]})}var $d={exports:{}},ib;function Yw(){return ib||(ib=1,(function(e,r){(function(s,i){e.exports=i()})(globalThis,(()=>(()=>{var s={4567:function(h,l,d){var f=this&&this.__decorate||function(x,_,j,A){var N,D=arguments.length,T=D<3?_:A===null?A=Object.getOwnPropertyDescriptor(_,j):A;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")T=Reflect.decorate(x,_,j,A);else for(var z=x.length-1;z>=0;z--)(N=x[z])&&(T=(D<3?N(T):D>3?N(_,j,T):N(_,j))||T);return D>3&&T&&Object.defineProperty(_,j,T),T},g=this&&this.__param||function(x,_){return function(j,A){_(j,A,x)}};Object.defineProperty(l,"__esModule",{value:!0}),l.AccessibilityManager=void 0;const m=d(9042),v=d(9924),S=d(844),k=d(4725),C=d(2585),y=d(3656);let b=l.AccessibilityManager=class extends S.Disposable{constructor(x,_,j,A){super(),this._terminal=x,this._coreBrowserService=j,this._renderService=A,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 v.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((N=>this._handleResize(N.rows)))),this.register(this._terminal.onRender((N=>this._refreshRows(N.start,N.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((N=>this._handleChar(N)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
|
|
58
58
|
`)))),this.register(this._terminal.onA11yTab((N=>this._handleTab(N)))),this.register(this._terminal.onKey((N=>this._handleKey(N.key)))),this.register(this._terminal.onBlur((()=>this._clearLiveRegion()))),this.register(this._renderService.onDimensionsChange((()=>this._refreshRowsDimensions()))),this.register((0,y.addDisposableDomListener)(document,"selectionchange",(()=>this._handleSelectionChange()))),this.register(this._coreBrowserService.onDprChange((()=>this._refreshRowsDimensions()))),this._refreshRows(),this.register((0,S.toDisposable)((()=>{this._accessibilityContainer.remove(),this._rowElements.length=0})))}_handleTab(x){for(let _=0;_<x;_++)this._handleChar(" ")}_handleChar(x){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==x&&(this._charsToAnnounce+=x):this._charsToAnnounce+=x,x===`
|
|
59
59
|
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=m.tooMuchOutput)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(x){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(x)||this._charsToConsume.push(x)}_refreshRows(x,_){this._liveRegionDebouncer.refresh(x,_,this._terminal.rows)}_renderRows(x,_){const j=this._terminal.buffer,A=j.lines.length.toString();for(let N=x;N<=_;N++){const D=j.lines.get(j.ydisp+N),T=[],z=(D==null?void 0:D.translateToString(!0,void 0,void 0,T))||"",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,T)),q.setAttribute("aria-posinset",O),q.setAttribute("aria-setsize",A))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(x,_){const j=x.target,A=this._rowElements[_===0?1:this._rowElements.length-2];if(j.getAttribute("aria-posinset")===(_===0?"1":`${this._terminal.buffer.lines.length}`)||x.relatedTarget!==A)return;let N,D;if(_===0?(N=j,D=this._rowElements.pop(),this._rowContainer.removeChild(D)):(N=this._rowElements.shift(),D=j,this._rowContainer.removeChild(N)),N.removeEventListener("focus",this._topBoundaryFocusListener),D.removeEventListener("focus",this._bottomBoundaryFocusListener),_===0){const T=this._createAccessibilityTreeNode();this._rowElements.unshift(T),this._rowContainer.insertAdjacentElement("afterbegin",T)}else{const T=this._createAccessibilityTreeNode();this._rowElements.push(T),this._rowContainer.appendChild(T)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(_===0?-1:1),this._rowElements[_===0?1:this._rowElements.length-2].focus(),x.preventDefault(),x.stopImmediatePropagation()}_handleSelectionChange(){var z;if(this._rowElements.length===0)return;const x=document.getSelection();if(!x)return;if(x.isCollapsed)return void(this._rowContainer.contains(x.anchorNode)&&this._terminal.clearSelection());if(!x.anchorNode||!x.focusNode)return void console.error("anchorNode and/or focusNode are null");let _={node:x.anchorNode,offset:x.anchorOffset},j={node:x.focusNode,offset:x.focusOffset};if((_.node.compareDocumentPosition(j.node)&Node.DOCUMENT_POSITION_PRECEDING||_.node===j.node&&_.offset>j.offset)&&([_,j]=[j,_]),_.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(_={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(_.node))return;const A=this._rowElements.slice(-1)[0];if(j.node.compareDocumentPosition(A)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(j={node:A,offset:((z=A.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(_),T=N(j);if(D&&T){if(D.row>T.row||D.row===T.row&&D.column>=T.column)throw new Error("invalid range");this._terminal.select(D.column,D.row,(T.row-D.row)*this._terminal.cols-D.column+T.column)}}_handleResize(x){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let _=this._rowContainer.children.length;_<this._terminal.rows;_++)this._rowElements[_]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[_]);for(;this._rowElements.length>x;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const x=this._coreBrowserService.mainDocument.createElement("div");return x.setAttribute("role","listitem"),x.tabIndex=-1,this._refreshRowDimensions(x),x}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){this._accessibilityContainer.style.width=`${this._renderService.dimensions.css.canvas.width}px`,this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let x=0;x<this._terminal.rows;x++)this._refreshRowDimensions(this._rowElements[x])}}_refreshRowDimensions(x){x.style.height=`${this._renderService.dimensions.css.cell.height}px`}};l.AccessibilityManager=b=f([g(1,C.IInstantiationService),g(2,k.ICoreBrowserService),g(3,k.IRenderService)],b)},3614:(h,l)=>{function d(v){return v.replace(/\r?\n/g,"\r")}function f(v,S){return S?"\x1B[200~"+v+"\x1B[201~":v}function g(v,S,k,C){v=f(v=d(v),k.decPrivateModes.bracketedPasteMode&&C.rawOptions.ignoreBracketedPasteMode!==!0),k.triggerDataEvent(v,!0),S.value=""}function m(v,S,k){const C=k.getBoundingClientRect(),y=v.clientX-C.left-10,b=v.clientY-C.top-10;S.style.width="20px",S.style.height="20px",S.style.left=`${y}px`,S.style.top=`${b}px`,S.style.zIndex="1000",S.focus()}Object.defineProperty(l,"__esModule",{value:!0}),l.rightClickHandler=l.moveTextAreaUnderMouseCursor=l.paste=l.handlePasteEvent=l.copyHandler=l.bracketTextForPaste=l.prepareTextForTerminal=void 0,l.prepareTextForTerminal=d,l.bracketTextForPaste=f,l.copyHandler=function(v,S){v.clipboardData&&v.clipboardData.setData("text/plain",S.selectionText),v.preventDefault()},l.handlePasteEvent=function(v,S,k,C){v.stopPropagation(),v.clipboardData&&g(v.clipboardData.getData("text/plain"),S,k,C)},l.paste=g,l.moveTextAreaUnderMouseCursor=m,l.rightClickHandler=function(v,S,k,C,y){m(v,S,k),y&&C.rightClickSelect(v),S.value=C.selectionText,S.select()}},7239:(h,l,d)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.ColorContrastCache=void 0;const f=d(1505);l.ColorContrastCache=class{constructor(){this._color=new f.TwoKeyMap,this._css=new f.TwoKeyMap}setCss(g,m,v){this._css.set(g,m,v)}getCss(g,m){return this._css.get(g,m)}setColor(g,m,v){this._color.set(g,m,v)}getColor(g,m){return this._color.get(g,m)}clear(){this._color.clear(),this._css.clear()}}},3656:(h,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.addDisposableDomListener=void 0,l.addDisposableDomListener=function(d,f,g,m){d.addEventListener(f,g,m);let v=!1;return{dispose:()=>{v||(v=!0,d.removeEventListener(f,g,m))}}}},3551:function(h,l,d){var f=this&&this.__decorate||function(b,x,_,j){var A,N=arguments.length,D=N<3?x:j===null?j=Object.getOwnPropertyDescriptor(x,_):j;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")D=Reflect.decorate(b,x,_,j);else for(var T=b.length-1;T>=0;T--)(A=b[T])&&(D=(N<3?A(D):N>3?A(x,_,D):A(x,_))||D);return N>3&&D&&Object.defineProperty(x,_,D),D},g=this&&this.__param||function(b,x){return function(_,j){x(_,j,b)}};Object.defineProperty(l,"__esModule",{value:!0}),l.Linkifier=void 0;const m=d(3656),v=d(8460),S=d(844),k=d(2585),C=d(4725);let y=l.Linkifier=class extends S.Disposable{get currentLink(){return this._currentLink}constructor(b,x,_,j,A){super(),this._element=b,this._mouseService=x,this._renderService=_,this._bufferService=j,this._linkProviderService=A,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new v.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new v.EventEmitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this.register((0,S.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,S.toDisposable)((()=>{var N;this._lastMouseEvent=void 0,(N=this._activeProviderReplies)==null||N.clear()}))),this.register(this._bufferService.onResize((()=>{this._clearCurrentLink(),this._wasResized=!0}))),this.register((0,m.addDisposableDomListener)(this._element,"mouseleave",(()=>{this._isMouseOut=!0,this._clearCurrentLink()}))),this.register((0,m.addDisposableDomListener)(this._element,"mousemove",this._handleMouseMove.bind(this))),this.register((0,m.addDisposableDomListener)(this._element,"mousedown",this._handleMouseDown.bind(this))),this.register((0,m.addDisposableDomListener)(this._element,"mouseup",this._handleMouseUp.bind(this)))}_handleMouseMove(b){this._lastMouseEvent=b;const x=this._positionFromMouseEvent(b,this._element,this._mouseService);if(!x)return;this._isMouseOut=!1;const _=b.composedPath();for(let j=0;j<_.length;j++){const A=_[j];if(A.classList.contains("xterm"))break;if(A.classList.contains("xterm-hover"))return}this._lastBufferCell&&x.x===this._lastBufferCell.x&&x.y===this._lastBufferCell.y||(this._handleHover(x),this._lastBufferCell=x)}_handleHover(b){if(this._activeLine!==b.y||this._wasResized)return this._clearCurrentLink(),this._askForLink(b,!1),void(this._wasResized=!1);this._currentLink&&this._linkAtPosition(this._currentLink.link,b)||(this._clearCurrentLink(),this._askForLink(b,!0))}_askForLink(b,x){var j,A;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=b.y);let _=!1;for(const[N,D]of this._linkProviderService.linkProviders.entries())x?(A=this._activeProviderReplies)!=null&&A.get(N)&&(_=this._checkLinkProviderResult(N,b,_)):D.provideLinks(b.y,(T=>{var O,q;if(this._isMouseOut)return;const z=T==null?void 0:T.map((G=>({link:G})));(O=this._activeProviderReplies)==null||O.set(N,z),_=this._checkLinkProviderResult(N,b,_),((q=this._activeProviderReplies)==null?void 0:q.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(b.y,this._activeProviderReplies)}))}_removeIntersectingLinks(b,x){const _=new Set;for(let j=0;j<x.size;j++){const A=x.get(j);if(A)for(let N=0;N<A.length;N++){const D=A[N],T=D.link.range.start.y<b?0:D.link.range.start.x,z=D.link.range.end.y>b?this._bufferService.cols:D.link.range.end.x;for(let O=T;O<=z;O++){if(_.has(O)){A.splice(N--,1);break}_.add(O)}}}}_checkLinkProviderResult(b,x,_){var N;if(!this._activeProviderReplies)return _;const j=this._activeProviderReplies.get(b);let A=!1;for(let D=0;D<b;D++)this._activeProviderReplies.has(D)&&!this._activeProviderReplies.get(D)||(A=!0);if(!A&&j){const D=j.find((T=>this._linkAtPosition(T.link,x)));D&&(_=!0,this._handleNewLink(D))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!_)for(let D=0;D<this._activeProviderReplies.size;D++){const T=(N=this._activeProviderReplies.get(D))==null?void 0:N.find((z=>this._linkAtPosition(z.link,x)));if(T){_=!0,this._handleNewLink(T);break}}return _}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(b){if(!this._currentLink)return;const x=this._positionFromMouseEvent(b,this._element,this._mouseService);x&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,x)&&this._currentLink.link.activate(b,this._currentLink.link.text)}_clearCurrentLink(b,x){this._currentLink&&this._lastMouseEvent&&(!b||!x||this._currentLink.link.range.start.y>=b&&this._currentLink.link.range.end.y<=x)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,S.disposeArray)(this._linkCacheDisposables))}_handleNewLink(b){if(!this._lastMouseEvent)return;const x=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);x&&this._linkAtPosition(b.link,x)&&(this._currentLink=b,this._currentLink.state={decorations:{underline:b.link.decorations===void 0||b.link.decorations.underline,pointerCursor:b.link.decorations===void 0||b.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,b.link,this._lastMouseEvent),b.link.decorations={},Object.defineProperties(b.link.decorations,{pointerCursor:{get:()=>{var _,j;return(j=(_=this._currentLink)==null?void 0:_.state)==null?void 0:j.decorations.pointerCursor},set:_=>{var j;(j=this._currentLink)!=null&&j.state&&this._currentLink.state.decorations.pointerCursor!==_&&(this._currentLink.state.decorations.pointerCursor=_,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",_))}},underline:{get:()=>{var _,j;return(j=(_=this._currentLink)==null?void 0:_.state)==null?void 0:j.decorations.underline},set:_=>{var j,A,N;(j=this._currentLink)!=null&&j.state&&((N=(A=this._currentLink)==null?void 0:A.state)==null?void 0:N.decorations.underline)!==_&&(this._currentLink.state.decorations.underline=_,this._currentLink.state.isHovered&&this._fireUnderlineEvent(b.link,_))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange((_=>{if(!this._currentLink)return;const j=_.start===0?0:_.start+1+this._bufferService.buffer.ydisp,A=this._bufferService.buffer.ydisp+1+_.end;if(this._currentLink.link.range.start.y>=j&&this._currentLink.link.range.end.y<=A&&(this._clearCurrentLink(j,A),this._lastMouseEvent)){const N=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);N&&this._askForLink(N,!1)}}))))}_linkHover(b,x,_){var j;(j=this._currentLink)!=null&&j.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(x,!0),this._currentLink.state.decorations.pointerCursor&&b.classList.add("xterm-cursor-pointer")),x.hover&&x.hover(_,x.text)}_fireUnderlineEvent(b,x){const _=b.range,j=this._bufferService.buffer.ydisp,A=this._createLinkUnderlineEvent(_.start.x-1,_.start.y-j-1,_.end.x,_.end.y-j-1,void 0);(x?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(A)}_linkLeave(b,x,_){var j;(j=this._currentLink)!=null&&j.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(x,!1),this._currentLink.state.decorations.pointerCursor&&b.classList.remove("xterm-cursor-pointer")),x.leave&&x.leave(_,x.text)}_linkAtPosition(b,x){const _=b.range.start.y*this._bufferService.cols+b.range.start.x,j=b.range.end.y*this._bufferService.cols+b.range.end.x,A=x.y*this._bufferService.cols+x.x;return _<=A&&A<=j}_positionFromMouseEvent(b,x,_){const j=_.getCoords(b,x,this._bufferService.cols,this._bufferService.rows);if(j)return{x:j[0],y:j[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(b,x,_,j,A){return{x1:b,y1:x,x2:_,y2:j,cols:this._bufferService.cols,fg:A}}};l.Linkifier=y=f([g(1,C.IMouseService),g(2,C.IRenderService),g(3,k.IBufferService),g(4,C.ILinkProviderService)],y)},9042:(h,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.tooMuchOutput=l.promptLabel=void 0,l.promptLabel="Terminal input",l.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},3730:function(h,l,d){var f=this&&this.__decorate||function(C,y,b,x){var _,j=arguments.length,A=j<3?y:x===null?x=Object.getOwnPropertyDescriptor(y,b):x;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")A=Reflect.decorate(C,y,b,x);else for(var N=C.length-1;N>=0;N--)(_=C[N])&&(A=(j<3?_(A):j>3?_(y,b,A):_(y,b))||A);return j>3&&A&&Object.defineProperty(y,b,A),A},g=this&&this.__param||function(C,y){return function(b,x){y(b,x,C)}};Object.defineProperty(l,"__esModule",{value:!0}),l.OscLinkProvider=void 0;const m=d(511),v=d(2585);let S=l.OscLinkProvider=class{constructor(C,y,b){this._bufferService=C,this._optionsService=y,this._oscLinkService=b}provideLinks(C,y){var z;const b=this._bufferService.buffer.lines.get(C-1);if(!b)return void y(void 0);const x=[],_=this._optionsService.rawOptions.linkHandler,j=new m.CellData,A=b.getTrimmedLength();let N=-1,D=-1,T=!1;for(let O=0;O<A;O++)if(D!==-1||b.hasContent(O)){if(b.loadCell(O,j),j.hasExtendedAttrs()&&j.extended.urlId){if(D===-1){D=O,N=j.extended.urlId;continue}T=j.extended.urlId!==N}else D!==-1&&(T=!0);if(T||D!==-1&&O===A-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+(T||O!==A-1?0:1),y:C}};let W=!1;if(!(_!=null&&_.allowNonHttpProtocols))try{const I=new URL(q);["http:","https:"].includes(I.protocol)||(W=!0)}catch{W=!0}W||x.push({text:q,range:G,activate:(I,$)=>_?_.activate(I,$,G):k(0,$),hover:(I,$)=>{var B;return(B=_==null?void 0:_.hover)==null?void 0:B.call(_,I,$,G)},leave:(I,$)=>{var B;return(B=_==null?void 0:_.leave)==null?void 0:B.call(_,I,$,G)}})}T=!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
|
|
|
@@ -82,7 +82,7 @@ WARNING: This link could potentially be dangerous`)){const b=window.open();if(b)
|
|
|
82
82
|
transition-all duration-300 ease-in-out
|
|
83
83
|
${r?"translate-x-0":"-translate-x-full"}
|
|
84
84
|
`,children:[o.jsxs("div",{className:"p-4 border-b border-border flex gap-2",children:[o.jsx(Fn,{href:`/p/${e}/new`,className:"flex-1 block text-center rounded font-medium transition-colors bg-accent-primary/25 text-text-primary hover:bg-accent-primary/40 px-3 py-1.5 text-sm","data-testid":"sidebar-new-session-button",children:"+ New Session"}),o.jsx(bo,{items:[{label:"Edit project settings",onClick:()=>u(!0)},{label:"Delete all sessions",onClick:_,danger:!0}],trigger:o.jsx("button",{className:"flex-shrink-0 p-2.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-colors",title:"Options",children:o.jsx(Bh,{})})}),s&&o.jsx(oo,{onClick:s,className:"md:hidden",variant:"sidebar",size:"md"})]}),k&&o.jsx(dC,{isOpen:c,onClose:()=>u(!1),project:k}),o.jsx("div",{className:"flex-1 overflow-y-auto",children:b.length===0?o.jsx("div",{className:"p-4 text-center text-text-muted text-xs",children:"No sessions"}):o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"divide-y divide-border",children:pC(b,l,d,x,e)}),S&&o.jsx("div",{className:"p-4 text-center text-text-muted text-xs",children:"Loading more..."}),o.jsx("div",{ref:C,className:"h-px"})]})})]})]})}function pC(e,r,s,i,c){const u=iy(e);return Array.from(u).map(([h,l])=>{const d=l[0];return d?o.jsxs("div",{children:[o.jsx("div",{className:"px-4 py-2 bg-bg-tertiary/30 text-text-muted text-xs font-medium",children:ry(d.updatedAt)}),l.map(f=>{const g=(r==null?void 0:r.id)===f.id,m=s.includes(f.id),v=f.isRunning;return o.jsx("div",{className:`w-full px-4 py-3 text-left hover:bg-bg-tertiary/50 transition-colors group ${g?"bg-bg-tertiary":""}`,children:o.jsxs(Fn,{href:`/p/${c}/s/${f.id}`,className:`block ${g?"text-accent-primary":"text-text-primary"} hover:text-accent-primary`,children:[o.jsxs("div",{className:"flex justify-between items-center mb-1",children:[o.jsx("span",{className:`font-medium truncate text-sm ${g?"text-accent-primary":"text-text-primary"}`,children:f.title??f.id.slice(0,6)}),o.jsx(bo,{items:[{label:"Delete session",onClick:S=>i(f.id,S),danger:!0}],trigger:o.jsx("button",{onClick:S=>S.preventDefault(),className:"p-1.5 rounded hover:bg-bg-tertiary text-text-muted hover:text-text-primary transition-all",title:"Options",children:o.jsx(Bh,{})})})]}),o.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[v?o.jsx(jw,{}):m&&!g?o.jsx("span",{"aria-label":"Unread activity",title:"Unread activity",className:"w-2 h-2 rounded-full bg-amber-400 flex-shrink-0"}):null,o.jsx("span",{className:"text-text-muted text-xs flex-shrink-0",children:uc(f.updatedAt)}),o.jsxs("span",{className:"text-text-muted text-xs flex-shrink-0",children:[f.messageCount," messages"]})]})]})},f.id)})]},h):null})}const ab=["⠋","⠙","⠹","⠸","⠼","⠴"];function mC(){var l;const e=Ft(d=>d.currentProject),r=Ce(d=>d.currentSession),s=qv(),i=!1,c=P.useRef(0),u=P.useRef(null);P.useEffect(()=>(s?(u.current=window.setInterval(()=>{c.current=(c.current+1)%ab.length,h()},150),h()):(u.current&&(clearInterval(u.current),u.current=null),h()),()=>{u.current&&(clearInterval(u.current),u.current=null)}),[s,e,r,i]);const h=()=>{var m;const f=(m=r==null?void 0:r.metadata)==null?void 0:m.title,g=s?`${ab[c.current]} `:"";e&&f?document.title=`${g}${e.name} - ${f} | OpenFox`:e?document.title=`${g}${e.name} | OpenFox`:document.title=`${g}OpenFox`};return typeof window<"u"&&((l=r==null?void 0:r.metadata)!=null&&l.title)&&window.document.documentElement.setAttribute("data-session-title",r.metadata.title),null}function gC({isOpen:e,onClose:r,projectName:s,onConfirm:i}){const c=()=>{i(),r()};return o.jsx(jt,{isOpen:e,onClose:r,title:"Delete Project",size:"sm",children:o.jsxs("div",{className:"space-y-4",children:[o.jsxs("p",{className:"text-text-secondary",children:["This will permanently delete the project ",o.jsx("span",{className:"font-semibold text-text-primary",children:s})," and all its sessions from OpenFox. The project files on disk will remain untouched."]}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(nt,{variant:"secondary",onClick:r,children:"Cancel"}),o.jsx(nt,{variant:"danger",onClick:c,children:"Delete"})]})]})})}const dc=P.forwardRef(({className:e="",...r},s)=>o.jsx("input",{ref:s,className:`bg-bg-tertiary border border-border rounded px-3 py-2 text-text-primary placeholder-text-muted focus:outline-none focus:ring-2 focus:ring-accent-primary/50 focus:border-accent-primary ${e}`,...r}));dc.displayName="Input";function xC(e){return!e||e.trim()===""?{valid:!1,error:"Project name cannot be empty"}:/^[a-zA-Z0-9._-]+$/.test(e)?{valid:!0}:{valid:!1,error:"Project name can only contain letters, numbers, hyphens, underscores, and dots"}}function bC({isOpen:e,onClose:r}){const[,s]=lr(),[i,c]=P.useState(""),[u,h]=P.useState(null),[l,d]=P.useState(!1),[f,g]=P.useState(""),m=P.useRef(null);P.useEffect(()=>{e&&(ke("/api/config").then(C=>C.json()).then(C=>{C.workdir&&g(C.workdir)}),c(""),h(null),d(!1),setTimeout(()=>{var C;(C=m.current)==null||C.focus()},100))},[e]);const v=P.useCallback(async C=>{C.preventDefault();const y=xC(i);if(!y.valid){h(y.error);return}d(!0),h(null);const b=`${f}/${i}`;try{const x=await ke("/api/projects",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:i,workdir:b})});if(!x.ok){const A=await x.json().catch(()=>({}));throw new Error(A.error||"Failed to create project")}const j=(await x.json()).project;r(),s(`/p/${j.id}`)}catch(x){h(x instanceof Error?x.message:"Failed to create project"),d(!1)}},[i,s,r,f]),S=P.useCallback(()=>{c(""),h(null),r()},[r]),k=i?`${f}/${i}`:"";return o.jsx(jt,{isOpen:e,onClose:S,title:"Create New Project",size:"sm",children:o.jsxs("form",{onSubmit:v,className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{htmlFor:"project-name",className:"block text-sm font-medium text-text-secondary mb-2",children:"Project Name"}),o.jsx(dc,{ref:m,id:"project-name",value:i,onChange:C=>{c(C.target.value),h(null)},placeholder:"my-project",disabled:l,"data-testid":"create-project-name-input",className:"w-full"}),i&&o.jsxs("div",{className:"mt-2 text-xs text-text-muted",children:["Full path: ",o.jsx("span",{className:"font-mono",children:k})]}),u&&o.jsx("div",{className:"mt-3 p-3 bg-accent-error/10 border border-accent-error/30 rounded text-sm text-accent-error",children:u})]}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx(nt,{type:"button",variant:"secondary",onClick:S,disabled:l,children:"Cancel"}),o.jsx(nt,{type:"submit",variant:"primary",disabled:l||!i.trim(),"data-testid":"create-project-submit-button",className:"min-w-[100px]",children:l?o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(qi,{className:"h-4 w-4"}),"Creating..."]}):"Create"})]})]})})}const vC={sm:"w-4 h-4",md:"w-8 h-8",lg:"w-12 h-12"};function vo({size:e="md",className:r=""}){return o.jsx("div",{className:`animate-spin border-2 border-accent-primary border-t-transparent rounded-full ${vC[e]} ${r}`})}function yC({text:e,...r}){return o.jsxs("div",{className:"text-center",children:[o.jsx(vo,{...r,className:"mx-auto mb-4"}),e&&o.jsx("div",{className:"text-text-secondary",children:e})]})}function oy({onSelect:e,onClose:r,initialPath:s}){const[i,c]=P.useState(null),[u,h]=P.useState(!0),[l,d]=P.useState(""),[f,g]=P.useState(-1),m=P.useRef(null),v=P.useRef([]),S=P.useCallback(async x=>{h(!0),d(""),g(-1);try{const _=x?`/api/directories?path=${encodeURIComponent(x)}`:"/api/directories",A=await(await ke(_)).json();c(A)}catch(_){console.error("Failed to load directories:",_)}finally{h(!1)}},[]);P.useEffect(()=>{S(s)},[s,S]);const k=((i==null?void 0:i.current)??"").split("/").filter(Boolean).map((x,_,j)=>({name:x,path:"/"+j.slice(0,_+1).join("/")})),C=(i==null?void 0:i.directories.filter(x=>l===""||x.name.toLowerCase().includes(l.toLowerCase())))??[],y=[...i!=null&&i.parent?[{type:"parent",path:i.parent,name:".."}]:[],...C.map(x=>({type:"dir",path:x.path,name:x.name}))];P.useEffect(()=>{g(l?0:-1)},[l,C.length]),P.useEffect(()=>{var x;f>=0&&v.current[f]&&((x=v.current[f])==null||x.scrollIntoView({block:"nearest"}))},[f]);const b=x=>{var _;if(x.key==="ArrowDown")x.preventDefault(),g(j=>Math.min(j+1,y.length-1));else if(x.key==="ArrowUp")x.preventDefault(),g(j=>Math.max(j-1,0));else if(x.key==="Enter"){if(x.preventDefault(),f>=0&&y[f]){const j=y[f];j.type,S(j.path)}}else x.key==="Escape"&&(d(""),(_=m.current)==null||_.focus())};return o.jsxs(jt,{isOpen:!0,onClose:r,title:"Select Folder",size:"lg",children:[i&&o.jsx("div",{className:"px-3 py-2 bg-bg-tertiary/30 -mx-4 -mt-4 mb-4 border-b border-border",children:o.jsxs("div",{className:"flex items-center text-xs overflow-x-auto",children:[k.map((x,_)=>o.jsxs("span",{className:"flex items-center shrink-0",children:[o.jsx("span",{className:"text-text-muted",children:"/"}),o.jsx("button",{onClick:()=>S(x.path),className:`px-1 ${_===k.length-1?"text-accent-primary font-medium":"text-text-secondary hover:text-accent-primary"}`,children:x.name})]},x.path)),k.length===0&&o.jsx("button",{onClick:()=>S("/"),className:"text-text-muted hover:text-accent-primary",children:"/"})]})}),o.jsx("div",{className:"px-4 mb-3",children:o.jsxs("div",{className:"relative",children:[o.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-text-muted pointer-events-none flex items-center justify-center",children:o.jsx(Hh,{})}),o.jsx(dc,{autoFocus:!0,ref:m,value:l,onChange:x=>d(x.target.value),onKeyDown:b,placeholder:"Filter directories...",className:"w-full pl-9"})]})}),o.jsx("div",{className:"flex-1 overflow-y-auto -mx-4",children:u?o.jsx("div",{className:"p-8 text-center",children:o.jsx(vo,{size:"sm"})}):y.length===0?o.jsx("div",{className:"p-8 text-center text-text-muted text-sm",children:l?"No matching directories":"No subdirectories"}):o.jsx("div",{className:"divide-y divide-border",children:y.map((x,_)=>o.jsxs("button",{ref:j=>{v.current[_]=j},onClick:()=>S(x.path),onDoubleClick:()=>e(x.path),className:`w-full p-3 flex items-center gap-3 text-left transition-colors ${_===f?"bg-accent-primary/20 text-accent-primary":"hover:bg-bg-tertiary/50"}`,children:[x.type==="parent"?o.jsx(dw,{className:"w-5 h-5 text-text-muted"}):o.jsx(zh,{className:"w-5 h-5"}),o.jsx("span",{className:"flex-1",children:x.name}),_===f&&o.jsx("span",{className:"text-xs text-text-muted",children:"⏎ navigate · dbl-click select"})]},x.path))})}),o.jsxs("div",{className:"flex flex-col gap-2 pt-4 border-t border-border mt-4 -mx-4 -mb-4 p-4",children:[(i==null?void 0:i.current)&&o.jsx("button",{onClick:()=>e(i.current),className:"w-full px-4 py-2 bg-accent-primary text-text-primary rounded-lg font-medium hover:bg-accent-primary/90 transition-colors",children:"Select this folder"}),o.jsx("button",{onClick:r,className:"w-full text-center text-text-muted hover:text-text-secondary text-sm",children:"Cancel"})]})]})}function _C({isOpen:e,onClose:r}){const[,s]=lr(),[i,c]=P.useState(!1),[u,h]=P.useState(null),[l,d]=P.useState(!1),f=Ft(N=>N.projects),g=Ft(N=>N.createProject),m=Ft(N=>N.listProjects),v=Ft(N=>N.deleteProject),[S,k]=P.useState(null),[C,y]=P.useState(null),b=(N,D=32)=>{if(N.length<=D)return N;const T=N.split("/").filter(Boolean);if(T.length<=2)return N;const z=T[0],O=T[T.length-1],q=T.slice(1,-1).join("/"),G=D-z.length-O.length-3;if(G<0)return N;const W=q.slice(0,Math.floor(G/2)),I=q.slice(-Math.ceil(G/2));return`/${z}/${W}...${I}/${O}`};P.useEffect(()=>{ke("/api/config").then(N=>N.json()).then(N=>{N.workdir&&h(N.workdir)})},[]),P.useEffect(()=>{e&&m()},[e,m]);const x=N=>{s(`/p/${N}`),r()},_=(N,D)=>{D.stopPropagation(),k(N)},j=()=>{S&&(v(S.id),k(null))},A=N=>{const D=N.split("/").filter(Boolean).pop()??"";g(D,N),m(),y(N)};return P.useEffect(()=>{if(C){const N=f.find(D=>D.workdir===C);N&&(s(`/p/${N.id}`),r(),y(null))}},[f,C,s,r]),e?o.jsxs(jt,{isOpen:e,onClose:r,title:"Open Project",size:"xl",footer:o.jsx("div",{className:"flex justify-end gap-2",children:o.jsx(nt,{variant:"secondary",onClick:r,children:"Close"})}),children:[o.jsxs("div",{className:"flex flex-col sm:flex-row flex-1 -m-4",children:[o.jsxs("div",{className:"w-full sm:w-1/2 border-b sm:border-b-0 sm:border-r border-border flex flex-col max-h-[40vh] sm:max-h-[50vh]",children:[o.jsx("div",{className:"p-3 border-b border-border bg-bg-tertiary/30 shrink-0",children:o.jsx("h3",{className:"font-medium text-sm text-text-secondary",children:"Recent Projects"})}),o.jsx("div",{className:"flex-1 overflow-y-auto",children:f.length===0?o.jsxs("div",{className:"p-6 text-center text-text-muted text-sm",children:[o.jsx("p",{className:"mb-2",children:"No recent projects"}),o.jsx("p",{className:"text-xs",children:'Click "Create new project" to add one'})]}):o.jsx("div",{className:"divide-y divide-border",children:f.map(N=>o.jsxs("div",{className:"group flex items-center gap-3 p-3 hover:bg-bg-tertiary/50 transition-colors",children:[o.jsxs("button",{onClick:()=>x(N.id),className:"flex-1 flex items-center gap-3 text-left",children:[o.jsx(zh,{className:"w-5 h-5 text-accent-primary"}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("div",{className:"font-medium truncate",children:N.name}),o.jsx("div",{className:"text-xs text-text-muted truncate",children:b(N.workdir)})]})]}),o.jsx("button",{onClick:D=>_(N,D),className:"text-accent-error/70 hover:text-accent-error p-1",title:"Delete project",children:o.jsx(Ph,{className:"w-4 h-4"})})]},N.id))})})]}),o.jsx("div",{className:"w-full sm:w-1/2 flex flex-col items-center justify-center p-6 sm:p-8 text-center",children:o.jsxs("div",{className:"flex flex-col gap-3 w-full max-w-sm",children:[o.jsx(nt,{variant:"primary",onClick:()=>d(!0),children:"Select existing project"}),o.jsx(nt,{variant:"secondary",onClick:()=>c(!0),"data-testid":"open-project-create-button",children:"Create new project"})]})})]}),i&&o.jsx(bC,{isOpen:i,onClose:()=>c(!1)}),S&&o.jsx(gC,{isOpen:!0,onClose:()=>k(null),projectName:S.name,onConfirm:j}),l&&o.jsx(oy,{initialPath:u??void 0,onSelect:N=>{A(N),d(!1)},onClose:()=>d(!1)})]}):null}function SC(){const[e,r]=P.useState(!1),s=Ce(m=>m.sessions),i=Ft(m=>m.projects),c=Ft(m=>m.loading),u=Ft(m=>m.listProjects),h=Ce(m=>m.listSessions),l=Ce(m=>m.connectionStatus);P.useEffect(()=>{l==="connected"&&(u(),h())},[l,u,h]);const d=[...i].sort((m,v)=>{const S=s.filter(b=>b.workdir.startsWith(m.workdir)),k=s.filter(b=>b.workdir.startsWith(v.workdir)),C=S.length>0?new Date(S.reduce((b,x)=>new Date(x.updatedAt)>new Date(b.updatedAt)?x:b).updatedAt).getTime():new Date(m.updatedAt).getTime();return(k.length>0?new Date(k.reduce((b,x)=>new Date(x.updatedAt)>new Date(b.updatedAt)?x:b).updatedAt).getTime():new Date(v.updatedAt).getTime())-C}),f=m=>{const v=i.find(S=>S.id===m);return v?s.filter(S=>S.workdir.startsWith(v.workdir)).sort((S,k)=>new Date(k.updatedAt).getTime()-new Date(S.updatedAt).getTime()).slice(0,5):[]},g=()=>{r(!0)};return o.jsxs("div",{className:"flex-1 flex flex-col overflow-y-auto bg-primary",children:[o.jsxs("div",{className:"max-w-5xl mx-auto w-full p-4 md:p-8",children:[o.jsxs("div",{className:"mb-6 md:mb-8 flex items-center justify-between",children:[o.jsxs("div",{children:[o.jsx("h1",{className:"text-3xl font-bold text-accent-primary",children:"OpenFox"}),o.jsx("p",{className:"text-text-secondary",children:"Local LLM-powered coding assistant with contract-driven execution"})]}),o.jsx(nt,{variant:"primary",onClick:g,children:"Open Project"})]}),d.map(m=>{const v=f(m.id);return o.jsx("div",{className:"mb-6 md:mb-8",children:o.jsxs("div",{className:"bg-bg-secondary border border-border rounded-lg overflow-hidden",children:[o.jsxs("div",{className:"p-3 md:p-4 border-b border-border flex items-center justify-between gap-2",children:[o.jsxs(Fn,{href:`/p/${m.id}`,className:"flex items-center gap-2 cursor-pointer hover:opacity-80 transition-opacity flex-1",children:[o.jsx(zh,{className:"w-5 h-5 text-accent-primary flex-shrink-0"}),o.jsx("span",{className:"text-text-primary font-semibold",children:m.name})]}),o.jsx(Fn,{href:`/p/${m.id}/new`,className:"rounded font-medium transition-colors bg-accent-primary/25 text-text-primary hover:bg-accent-primary/40 px-1.5 py-1 text-xs",children:"+ New Session"})]}),o.jsx("div",{className:"divide-y divide-border",children:v.length>0?v.map(S=>{const k=i.find(y=>S.workdir.startsWith(y.workdir)),C=k?`/p/${k.id}/s/${S.id}`:"#";return o.jsx(Fn,{href:C,className:"block p-3 md:p-4 hover:bg-bg-tertiary/50 cursor-pointer transition-colors",children:o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsx("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:o.jsx("div",{className:"flex-1 min-w-0",children:o.jsx("div",{className:"text-sm text-text-muted truncate",children:S.title??S.id.slice(0,8)})})}),o.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[o.jsx("span",{className:"text-text-muted text-xs",children:rC(S.updatedAt)}),o.jsxs("span",{className:"text-text-muted text-xs",children:[S.messageCount," msgs"]})]})]})},S.id)}):o.jsx("div",{className:"p-3 md:p-4 text-text-muted text-sm",children:"No sessions yet"})})]})},m.id)}),d.length===0&&!c&&o.jsx("div",{className:"text-center py-12 text-text-muted",children:"No projects yet. Open a project to get started."}),c&&o.jsx("div",{className:"flex justify-center py-12",children:o.jsx(vo,{})})]}),e&&o.jsx(_C,{isOpen:e,onClose:()=>r(!1)})]})}function wC(){const[,e]=Mh("/p/:projectId/new"),[,r]=lr(),s=e==null?void 0:e.projectId,i=Ce(c=>c.createSession);return P.useEffect(()=>{s&&(async()=>{const u=await i(s);r(u?`/p/${s}/s/${u.id}`:`/p/${s}`)})()},[s,i,r]),o.jsx("div",{className:"flex-1 flex items-center justify-center",children:o.jsx(vo,{})})}function CC(){const e=Ft(r=>r.currentProject);return o.jsx("div",{className:"h-full flex flex-col items-center justify-center p-8 text-center",children:o.jsxs("div",{className:"max-w-md",children:[o.jsx("h2",{className:"text-xl font-semibold text-text-primary mb-2",children:(e==null?void 0:e.name)??"Project"}),o.jsx("p",{className:"text-text-secondary mb-6",children:"No session selected"}),o.jsxs("div",{className:"flex flex-col gap-3",children:[e&&o.jsx(Fn,{href:`/p/${e.id}/new`,"data-testid":"create-new-session-button",className:"block w-full rounded font-medium transition-colors bg-accent-primary/25 text-text-primary hover:bg-accent-primary/40 px-3 py-2 text-center",children:"Create New Session"}),o.jsx("p",{className:"text-sm text-text-muted",children:"Or select an existing session from the sidebar"})]})]})})}const Va=e=>Math.round(e*10)/10;function mh(e){return{providerId:e.providerId,providerName:e.providerName,backend:e.backend,model:e.model}}function kC(e){return`${e.providerId}::${e.model}`}function EC(e){return`${e.providerName} > ${e.model}`}function ob(e){let r=0,s=0,i=0,c=0,u=0,h=0;const l=[],d=[];let f=0;for(const[v,S]of e.entries()){const k=S.stats,C=mh(k);r+=k.totalTime,s+=k.toolTime,i+=k.prefillTokens,c+=k.generationTokens;const y=k.prefillSpeed>0?k.prefillTokens/k.prefillSpeed:0,b=k.generationSpeed>0?k.generationTokens/k.generationSpeed:0;u+=y,h+=b,l.push({messageId:S.id,timestamp:S.timestamp,...C,mode:k.mode,responseIndex:v+1,prefillTokens:k.prefillTokens,generationTokens:k.generationTokens,prefillSpeed:k.prefillSpeed,generationSpeed:k.generationSpeed,totalTime:k.totalTime,aiTime:k.totalTime-k.toolTime,toolTime:k.toolTime});const x=k.llmCalls??[];for(const _ of x)f+=1,d.push({messageId:S.id,timestamp:_.timestamp??S.timestamp,providerId:_.providerId,providerName:_.providerName,backend:_.backend,model:_.model,mode:k.mode,responseIndex:v+1,sessionCallIndex:f,callIndex:_.callIndex,promptTokens:_.promptTokens,completionTokens:_.completionTokens,ttft:_.ttft,completionTime:_.completionTime,prefillSpeed:_.prefillSpeed,generationSpeed:_.generationSpeed,totalTime:_.totalTime,..._.temperature!==void 0&&{temperature:_.temperature},..._.topP!==void 0&&{topP:_.topP},..._.topK!==void 0&&{topK:_.topK},..._.maxTokens!==void 0&&{maxTokens:_.maxTokens}})}const g=u>0?Va(i/u):0,m=h>0?Va(c/h):0;return{totalTime:Va(r),aiTime:Va(r-s),toolTime:Va(s),prefillTokens:i,generationTokens:c,avgPrefillSpeed:g,avgGenerationSpeed:m,responseCount:e.length,llmCallCount:d.length,dataPoints:l,callDataPoints:d}}function jC(e){const r=e.filter(c=>c.stats!==void 0&&c.stats!==null).sort((c,u)=>new Date(c.timestamp).getTime()-new Date(u.timestamp).getTime());if(r.length===0)return null;const s=new Map;for(const c of r){const u=kC(mh(c.stats)),h=s.get(u)??[];s.set(u,[...h,c])}const i=Array.from(s.entries()).map(([c,u])=>{const h=mh(u[0].stats),l=ob(u);return{...h,key:c,label:EC(h),...l}});return{...ob(r),modelGroups:i}}function NC(e){return P.useMemo(()=>jC(e),[e])}function TC(e){const[r,s]=P.useState(null),[i,c]=P.useState(!0),[u,h]=P.useState(null),l=e||"";return P.useEffect(()=>{if(!l){c(!1);return}let d=!0,f=null;const g=async()=>{try{const v=await(await ke(`/api/branch?workdir=${encodeURIComponent(l)}`)).json();d&&(s(v.branch),h(v.error||null),c(!1))}catch(m){d&&(h(m instanceof Error?m.message:"Failed to fetch branch"),c(!1))}};return g(),f=setInterval(g,3e3),()=>{d=!1,f&&clearInterval(f)}},[l]),{branch:r,loading:i,error:u}}function Zl(e){return e.toLocaleString("en-US").replace(/,/g," ")}function lb(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toFixed(1)}function AC(e){if(e<60)return`${e.toFixed(1)}s`;const r=Math.floor(e/60),s=Math.round(e%60);return`${r}m${s}s`}const cb=["▁","▂","▃","▄","▅","▆","▇","█"];function DC(e,r,s){if(s===r)return 4;const i=(e-r)/(s-r);return Math.min(7,Math.max(0,Math.round(i*7)))}function RC(e,r){if(e===r){const c=Math.max(Math.abs(e)*.05,1);return{minY:e-c,maxY:r+c}}const s=r-e,i=Math.max(s*.1,.1);return{minY:e-i,maxY:r+i}}function LC(e,r){if(e.length===0||r<=0)return{blocks:"",minX:0,maxX:0,minY:0,maxY:0};const s=[...e].sort((m,v)=>m.x-v.x),i=s[0].x,c=s[s.length-1].x,u=Math.min(...s.map(m=>m.y)),h=Math.max(...s.map(m=>m.y)),{minY:l,maxY:d}=RC(u,h),f=Array.from({length:r},()=>" "),g=new Map;for(const m of s){const v=c===i?0:Math.round((m.x-i)/(c-i)*(r-1)),S=g.get(v)??[];g.set(v,[...S,m.y])}for(const[m,v]of g){const S=Math.max(...v);f[m]=cb[DC(S,l,d)]??cb[0]}return{blocks:f.join(""),minX:i,maxX:c,minY:l,maxY:d}}function ub(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toFixed(1)}function db({data:e,width:r=60,height:s=78,label:i,xLabel:c,yLabel:u,showAxes:h=!0,formatY:l=ub,formatX:d=ub}){const f=P.useMemo(()=>{const g=LC(e,r),m=Math.max(r*6,240),v=10,S=8,C=[...e].sort((_,j)=>_.x-j.x).map(_=>{const j=g.maxX===g.minX?m/2:v+(_.x-g.minX)/(g.maxX-g.minX)*(m-v*2),A=g.maxY===g.minY?s/2:S+(g.maxY-_.y)/(g.maxY-g.minY)*(s-S*2);return{..._,cx:j,cy:A,leftPercent:j/m*100,topPercent:A/s*100}}),y=C.map((_,j)=>`${j===0?"M":"L"} ${_.cx.toFixed(1)} ${_.cy.toFixed(1)}`).join(" "),x=[g.maxY,(g.maxY+g.minY)/2,g.minY].map(_=>({value:_,y:g.maxY===g.minY?s/2:S+(g.maxY-_)/(g.maxY-g.minY)*(s-S*2)}));return{...g,chartWidth:m,points:C,path:y,gridLines:x}},[e,s,r]);return e.length===0?o.jsxs("div",{className:"font-mono text-text-muted text-xs",children:[i&&o.jsx("div",{className:"mb-1",children:i}),o.jsx("div",{children:"No data"})]}):o.jsxs("div",{className:"font-mono text-xs",children:[i&&o.jsx("div",{className:"text-text-secondary mb-2",children:i}),o.jsxs("div",{className:"flex gap-3",children:[h&&o.jsx("div",{className:"w-12 h-[78px] flex flex-col justify-between text-right text-text-muted",children:f.gridLines.map(g=>o.jsx("span",{children:l(g.value)},`${g.value}-${g.y}`))}),o.jsx("div",{className:"flex-1 min-w-0",children:o.jsxs("div",{className:"relative h-[78px]",children:[o.jsxs("svg",{viewBox:`0 0 ${f.chartWidth} ${s}`,className:"w-full h-[78px] overflow-visible",preserveAspectRatio:"none","aria-hidden":"true",children:[f.gridLines.map(g=>o.jsx("line",{x1:"0",x2:f.chartWidth,y1:g.y,y2:g.y,stroke:"currentColor",strokeDasharray:"3 4",className:"text-border/60"},`grid-${g.y}`)),f.points.map(g=>o.jsx("line",{x1:g.cx,x2:g.cx,y1:s-4,y2:g.cy,stroke:"currentColor",className:"text-border/40"},`guide-${g.cx}-${g.cy}`)),f.points.length>1&&o.jsx("path",{d:f.path,fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-accent-primary/45"})]}),f.points.map(g=>o.jsx("div",{className:"absolute -translate-x-1/2 -translate-y-1/2",style:{left:`${g.leftPercent}%`,top:`${g.topPercent}%`},title:`${d(g.x)} -> ${l(g.y)}`,children:o.jsx("div",{className:"w-2.5 h-2.5 rounded-full bg-accent-primary/20 flex items-center justify-center",children:o.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary"})})},`point-${g.x}-${g.y}`))]})})]}),h&&o.jsxs("div",{className:"flex items-start gap-3 text-text-muted mt-1",children:[o.jsx("span",{className:"w-12"}),o.jsxs("span",{className:"flex-1 flex justify-between",children:[o.jsx("span",{children:d(f.minX)}),o.jsx("span",{children:c}),o.jsx("span",{children:d(f.maxX)})]})]}),u&&h&&o.jsx("div",{className:"text-text-muted mt-1 text-center",children:u})]})}function OC({data:e,prefillLabel:r="Prefill Speed (tok/s) by Response",generationLabel:s="Generation Speed (tok/s) by Response",xLabel:i="response",width:c=60}){const u=e.map(l=>({x:l.x,y:l.ppSpeed})),h=e.map(l=>({x:l.x,y:l.tgSpeed}));return o.jsxs("div",{className:"space-y-5",children:[o.jsx(db,{data:u,width:c,label:r,xLabel:i}),o.jsx(db,{data:h,width:c,label:s,xLabel:i})]})}function MC(e){const r=new Map;for(const s of e.callDataPoints){const i=r.get(s.messageId)??[];r.set(s.messageId,[...i,s])}return e.dataPoints.map(s=>{const i=[...r.get(s.messageId)??[]].sort((c,u)=>c.callIndex-u.callIndex);return{...s,callCount:i.length,calls:i,isExpandable:i.length>1}})}function IC(e){return{mode:"responses",xLabel:"response",prefillLabel:"Prefill Speed (tok/s) by Response",generationLabel:"Generation Speed (tok/s) by Response",points:e.dataPoints.map(r=>({x:r.responseIndex,ppSpeed:r.prefillSpeed,tgSpeed:r.generationSpeed}))}}function BC(e){return{mode:"calls",xLabel:"context",prefillLabel:"Prefill Speed (tok/s) vs Context",generationLabel:"Generation Speed (tok/s) vs Context",points:e.callDataPoints.map(r=>({x:r.promptTokens,ppSpeed:r.prefillSpeed,tgSpeed:r.generationSpeed}))}}function zC(e){return e.callDataPoints.length>0?BC(e):IC(e)}function qd(e){if(e<60)return`${e.toFixed(1)}s`;const r=Math.floor(e/60),s=e%60;return`${r}m ${s.toFixed(0)}s`}function $s(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toString()}function eo(e){return e>=1e3?`${(e/1e3).toFixed(1)}k`:e.toFixed(1)}function PC(e){if(e.length===0)return"0 ctx";const r=Math.min(...e),s=Math.max(...e);return r===s?`${$s(r)} ctx`:`${$s(r)}-${$s(s)} ctx`}function Ql(e){return`${eo(e)} t/s`}function ly(e){try{return new Date(e).toLocaleTimeString("en-US",{hour12:!1})}catch{return e}}function HC(e){return{exportedAt:new Date().toISOString(),providerId:e.providerId,providerName:e.providerName,backend:e.backend,model:e.model,label:e.label,summary:{totalTime:e.totalTime,aiTime:e.aiTime,toolTime:e.toolTime,prefillTokens:e.prefillTokens,generationTokens:e.generationTokens,avgPrefillSpeed:e.avgPrefillSpeed,avgGenerationSpeed:e.avgGenerationSpeed,responseCount:e.responseCount,llmCallCount:e.llmCallCount},responses:e.dataPoints.map(r=>({responseIndex:r.responseIndex,timestamp:r.timestamp,mode:r.mode,prefillTokens:r.prefillTokens,generationTokens:r.generationTokens,prefillSpeed:r.prefillSpeed,generationSpeed:r.generationSpeed,totalTime:r.totalTime,aiTime:r.aiTime,toolTime:r.toolTime})),llmCalls:e.callDataPoints.map(r=>({sessionCallIndex:r.sessionCallIndex,responseIndex:r.responseIndex,callIndex:r.callIndex,timestamp:r.timestamp,mode:r.mode,promptTokens:r.promptTokens,completionTokens:r.completionTokens,ttft:r.ttft,completionTime:r.completionTime,prefillSpeed:r.prefillSpeed,generationSpeed:r.generationSpeed,totalTime:r.totalTime}))}}function FC({isOpen:e,onClose:r,stats:s}){const i=P.useRef(null),[c,u]=P.useState({}),[h,l]=P.useState(()=>{var k;return((k=s.modelGroups[0])==null?void 0:k.key)??""});P.useEffect(()=>{var k;s.modelGroups.some(C=>C.key===h)||l(((k=s.modelGroups[0])==null?void 0:k.key)??"")},[h,s.modelGroups]);const d=P.useMemo(()=>s.modelGroups.find(k=>k.key===h)??s.modelGroups[0],[h,s.modelGroups]),f=P.useMemo(()=>d?MC(d):[],[d]),g=P.useMemo(()=>d?zC(d):{mode:"responses",xLabel:"response",prefillLabel:"",generationLabel:"",points:[]},[d]),m=P.useCallback(k=>{u(C=>({...C,[k]:!C[k]}))},[]),v=P.useCallback(()=>{if(!d)return;const k=HC(d);navigator.clipboard.writeText(JSON.stringify(k,null,2)).catch(C=>console.error("Failed to copy:",C))},[d]),S=P.useCallback(async()=>{if(i.current)try{const k=(await fh(async()=>{const{default:b}=await import("./html2canvas.esm-QH1iLAAe.js");return{default:b}},[])).default,C=await k(i.current,{backgroundColor:"#1a1a1a",scale:2}),y=document.createElement("a");y.download=`openfox-stats-${new Date().toISOString().slice(0,10)}.png`,y.href=C.toDataURL("image/png"),y.click()}catch(k){console.error("Failed to export PNG:",k),v()}},[v]);return o.jsx(jt,{isOpen:e,onClose:r,title:"Session Stats",size:"lg",children:o.jsxs("div",{ref:i,className:"space-y-6",children:[o.jsx("section",{children:o.jsx("div",{className:"flex flex-wrap gap-2",children:s.modelGroups.map(k=>o.jsx("button",{onClick:()=>l(k.key),className:`px-3 py-1.5 rounded border text-xs transition-colors ${k.key===(d==null?void 0:d.key)?"border-accent-primary bg-accent-primary/10 text-accent-primary":"border-border text-text-muted hover:text-text-primary hover:bg-bg-tertiary/40"}`,title:k.label,children:k.label},k.key))})}),d&&o.jsxs("section",{children:[o.jsx("h3",{className:"text-sm font-semibold text-text-secondary mb-3 uppercase tracking-wide",children:"Summary"}),o.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:[o.jsx(Hr,{label:"AI Time",value:qd(d.aiTime)}),o.jsx(Hr,{label:"Total Time",value:qd(d.totalTime)}),o.jsx(Hr,{label:"Tool Time",value:qd(d.toolTime)}),o.jsx(Hr,{label:"Responses",value:d.responseCount.toString()}),o.jsx(Hr,{label:"LLM Calls",value:d.llmCallCount.toString()})]}),o.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mt-3",children:[o.jsx(Hr,{label:"Prefill Tokens",value:$s(d.prefillTokens),subValue:`@ ${eo(d.avgPrefillSpeed)} tok/s`}),o.jsx(Hr,{label:"Gen Tokens",value:$s(d.generationTokens),subValue:`@ ${eo(d.avgGenerationSpeed)} tok/s`}),o.jsx(Hr,{label:"Avg PP Speed",value:`${eo(d.avgPrefillSpeed)}`,subValue:"tok/s"}),o.jsx(Hr,{label:"Avg TG Speed",value:`${eo(d.avgGenerationSpeed)}`,subValue:"tok/s"})]})]}),d&&g.points.length>1&&o.jsxs("section",{children:[o.jsxs("div",{className:"flex items-center justify-between mb-3",children:[o.jsx("h3",{className:"text-sm font-semibold text-text-secondary uppercase tracking-wide",children:"Performance Progression"}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("button",{onClick:v,className:"px-2 py-1 text-xs text-text-muted hover:text-text-primary hover:bg-bg-tertiary rounded transition-colors",children:"Copy JSON"}),o.jsx("button",{onClick:S,className:"px-2 py-1 text-xs text-text-muted hover:text-text-primary hover:bg-bg-tertiary rounded transition-colors",children:"Save PNG"})]})]}),o.jsx("div",{className:"bg-bg-tertiary/50 rounded p-4",children:o.jsx(OC,{data:g.points,width:50,prefillLabel:g.prefillLabel,generationLabel:g.generationLabel,xLabel:g.xLabel})})]}),d&&o.jsxs("section",{children:[o.jsxs("h3",{className:"text-sm font-semibold text-text-secondary mb-3 uppercase tracking-wide",children:["Response Log (",d.responseCount," responses)"]}),o.jsx("div",{className:"overflow-y-auto bg-bg-tertiary/30 rounded",children:o.jsxs("table",{className:"w-full table-fixed border-separate border-spacing-0 text-xs",children:[o.jsxs("colgroup",{children:[o.jsx("col",{className:"w-[7%]"}),o.jsx("col",{className:"w-[14%]"}),o.jsx("col",{className:"w-[10%]"}),o.jsx("col",{className:"w-[14%]"}),o.jsx("col",{className:"w-[14%]"}),o.jsx("col",{className:"w-[14%]"}),o.jsx("col",{className:"w-[11%]"}),o.jsx("col",{className:"w-[2%]"})]}),o.jsx("thead",{children:o.jsxs("tr",{className:"text-[10px] uppercase tracking-wide text-text-muted/80",children:[o.jsx("th",{className:"px-3 py-2 text-center font-medium",children:"#"}),o.jsx("th",{className:"px-2 py-2 text-center font-medium",children:"At"}),o.jsx("th",{className:"px-2 py-2 text-center font-medium",children:"Time"}),o.jsx("th",{className:"px-2 py-2 text-center font-medium",children:"Context"}),o.jsx("th",{className:"px-2 py-2 text-center font-medium",children:"PP t/s"}),o.jsx("th",{className:"px-2 py-2 text-center font-medium",children:"TG t/s"}),o.jsx("th",{className:"px-2 py-2 text-center font-medium",children:"Calls"}),o.jsx("th",{className:"px-2 py-2"})]})}),o.jsx("tbody",{children:f.map((k,C)=>o.jsxs(P.Fragment,{children:[o.jsx(UC,{row:k,index:C,isExpanded:c[k.messageId]??!1,onToggle:k.isExpandable?()=>m(k.messageId):void 0}),(c[k.messageId]??!1)&&k.calls.map((y,b)=>o.jsx($C,{dataPoint:y,index:b},`${y.messageId}-${y.callIndex}`))]},k.messageId))})]})})]})]})})}function Hr({label:e,value:r,subValue:s}){return o.jsxs("div",{className:"bg-bg-tertiary/50 rounded p-3",children:[o.jsx("div",{className:"text-text-muted text-xs mb-1",children:e}),o.jsx("div",{className:"text-text-primary text-lg font-semibold",children:r}),s&&o.jsx("div",{className:"text-text-muted text-xs",children:s})]})}function UC({row:e,index:r,isExpanded:s,onToggle:i}){const c=e.calls.length>0?PC(e.calls.map(u=>u.promptTokens)):`${$s(e.prefillTokens)} ctx`;return o.jsxs("tr",{onClick:i,className:`${r%2===0?"bg-bg-tertiary/20":""} ${i?"cursor-pointer hover:bg-bg-tertiary/35 transition-colors":""}`,children:[o.jsx("td",{className:"px-3 py-2 text-center text-text-muted align-middle",children:e.responseIndex}),o.jsx("td",{className:"px-2 py-2 text-center text-text-muted font-mono align-middle whitespace-nowrap",children:ly(e.timestamp)}),o.jsxs("td",{className:"px-2 py-2 text-center text-text-muted align-middle whitespace-nowrap",children:[e.totalTime.toFixed(1),"s"]}),o.jsx("td",{className:"px-2 py-2 text-center text-text-primary font-mono align-middle whitespace-nowrap",children:c.replace(/ ctx$/,"")}),o.jsx("td",{className:"px-2 py-2 text-center text-text-primary font-mono align-middle whitespace-nowrap",children:Ql(e.prefillSpeed)}),o.jsx("td",{className:"px-2 py-2 text-center text-text-primary font-mono align-middle whitespace-nowrap",children:Ql(e.generationSpeed)}),o.jsx("td",{className:"px-2 py-2 text-center text-text-muted font-mono align-middle whitespace-nowrap",children:e.callCount}),o.jsx("td",{className:"px-2 py-2 text-center text-text-muted align-middle whitespace-nowrap",children:e.isExpandable?s?"v":">":""})]})}function $C({dataPoint:e,index:r}){const s=e.temperature!==void 0||e.topP!==void 0||e.topK!==void 0||e.maxTokens!==void 0;return o.jsxs(o.Fragment,{children:[o.jsxs("tr",{className:`${r%2===0?"bg-bg-tertiary/10":"bg-bg-tertiary/5"}`,children:[o.jsxs("td",{className:"px-3 py-2 pl-6 text-center text-text-muted align-middle border-l border-border/60",children:["c",e.callIndex]}),o.jsx("td",{className:"px-2 py-2 text-center text-text-muted font-mono align-middle whitespace-nowrap",children:ly(e.timestamp)}),o.jsxs("td",{className:"px-2 py-2 text-center text-text-muted align-middle whitespace-nowrap",children:[e.totalTime.toFixed(1),"s"]}),o.jsx("td",{className:"px-2 py-2 text-center text-text-primary font-mono align-middle whitespace-nowrap",children:$s(e.promptTokens)}),o.jsx("td",{className:"px-2 py-2 text-center text-text-primary font-mono align-middle whitespace-nowrap",children:Ql(e.prefillSpeed)}),o.jsx("td",{className:"px-2 py-2 text-center text-text-primary font-mono align-middle whitespace-nowrap",children:Ql(e.generationSpeed)}),o.jsx("td",{className:"px-2 py-2 text-center text-text-muted font-mono align-middle whitespace-nowrap",children:e.callIndex}),o.jsx("td",{className:"px-2 py-2"})]}),s&&o.jsx("tr",{className:`${r%2===0?"bg-bg-tertiary/5":"bg-bg-tertiary/[2.5%]"}`,children:o.jsx("td",{colSpan:8,className:"px-6 py-1.5 border-l border-border/60",children:o.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-[10px] text-text-muted",children:[e.temperature!==void 0&&o.jsxs("span",{children:["temp: ",e.temperature.toFixed(2)]}),e.topP!==void 0&&o.jsxs("span",{children:["topP: ",e.topP.toFixed(2)]}),e.topK!==void 0&&o.jsxs("span",{children:["topK: ",e.topK]}),e.maxTokens!==void 0&&o.jsxs("span",{children:["maxTok: ",e.maxTokens]})]})})})]})}const qC={pending:{icon:"○",color:"text-text-muted",label:"Pending"},in_progress:{icon:"●",color:"text-accent-warning",label:"In Progress",animate:!0},completed:{icon:"◉",color:"text-purple-400",label:"Completed"},passed:{icon:"✓",color:"text-accent-success",label:"Passed"},failed:{icon:"✗",color:"text-accent-error",label:"Failed"}},WC=P.memo(function({criteria:r}){if(r.length===0)return o.jsx("div",{className:"text-text-muted text-sm text-center py-2",children:"No criteria yet"});const s={pending:0,in_progress:0,completed:0,passed:0,failed:0};for(const c of r){const u=c.status.type;u in s&&s[u]++}const i=Object.keys(s).filter(c=>s[c]>0);return o.jsxs("div",{className:"space-y-1",children:[o.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[o.jsx("span",{className:"font-semibold text-text-primary",children:"Total:"}),o.jsx("span",{className:"text-text-secondary",children:r.length})]}),o.jsx("div",{className:"space-y-1",children:i.map(c=>{const u=qC[c];return o.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[o.jsx("span",{className:`${u.color} ${u.animate?"animate-pulse":""} text-sm leading-tight`,children:u.icon}),o.jsxs("span",{className:"text-text-muted",children:[u.label,":"]}),o.jsx("span",{className:"text-text-primary font-medium",children:s[c]})]},c)})})]})});function VC({isOpen:e,onClose:r}){const s=gr(C=>C.config),i=gr(C=>C.saveConfig),[c,u]=P.useState(""),[h,l]=P.useState(""),[d,f]=P.useState(!1),[g,m]=P.useState(!1),[v,S]=P.useState(!1);P.useEffect(()=>{e&&(u((s==null?void 0:s.command)??""),l((s==null?void 0:s.url)??""),f((s==null?void 0:s.hotReload)??!1),m((s==null?void 0:s.disableInspect)??!1))},[e,s]);const k=async()=>{!c.trim()||!h.trim()||(S(!0),await i({command:c.trim(),url:h.trim(),hotReload:d,disableInspect:g}),S(!1),r())};return o.jsx(jt,{isOpen:e,onClose:r,title:"Dev Server Config",size:"sm",children:o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Command"}),o.jsx("input",{className:"input w-full",type:"text",value:c,onChange:C=>u(C.target.value),placeholder:"npm run dev"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-text-secondary mb-1",children:"Dev URL"}),o.jsx("input",{className:"input w-full",type:"text",value:h,onChange:C=>l(C.target.value),placeholder:"http://localhost:3000"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"checkbox",id:"hotReload",checked:d,onChange:C=>f(C.target.checked),className:"rounded border-border bg-bg-tertiary"}),o.jsx("label",{htmlFor:"hotReload",className:"text-xs text-text-secondary",children:"Hot Reload"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"checkbox",id:"disableInspect",checked:g,onChange:C=>m(C.target.checked),className:"rounded border-border bg-bg-tertiary"}),o.jsx("label",{htmlFor:"disableInspect",className:"text-xs text-text-secondary",children:"Disable inspect feedback"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[o.jsx("button",{className:"btn btn-secondary",onClick:r,children:"Cancel"}),o.jsx("button",{className:"btn btn-primary",onClick:k,disabled:v||!c.trim()||!h.trim(),children:v?"Saving...":"Save"})]})]})})}const hb={30:"text-black",31:"text-red-400",32:"text-accent-success",33:"text-accent-warning",34:"text-blue-400",35:"text-purple-400",36:"text-cyan-400",37:"text-gray-300",90:"text-gray-500",91:"text-red-500",92:"text-green-500",93:"text-yellow-400",94:"text-blue-500",95:"text-pink-400",96:"text-cyan-500",97:"text-white"},GC={40:"bg-black",41:"bg-red-900",42:"bg-green-900",43:"bg-yellow-900",44:"bg-blue-900",45:"bg-purple-900",46:"bg-cyan-900",47:"bg-gray-700"},fb={1:"font-bold",2:"opacity-75",4:"underline",7:"bg-bg-secondary"},KC="text-text-primary";function YC(e){const r=[],s=/\x1b\[([0-9;]+)m/g;let i=0,c="text-text-primary",u;try{for(;(u=s.exec(e))!==null;){if(u.index>i){const f=e.slice(i,u.index);f&&r.push({text:f,className:c})}const h=u[1];if(!h)continue;const l=h.split(";").map(Number);if(l.length===0||l[0]===0){c="text-text-primary";continue}const d=[];for(const f of l)if(f>=30&&f<=37){const g=hb[f];g&&d.push(g)}else if(f>=40&&f<=47){const g=GC[f];g&&d.push(g)}else if(f>=90&&f<=97){const g=hb[f];g&&d.push(g)}else if(f in fb){const g=fb[f];g&&d.push(g)}else f===39?d.push(KC):f===49&&(c=c.split(" ").filter(g=>!g.startsWith("bg-")).join(" "));d.length>0&&(c=d.join(" ")),i=s.lastIndex}if(i<e.length){const h=e.slice(i);h&&r.push({text:h,className:c})}return r}catch(h){return console.warn("ANSI parsing failed, stripping codes:",h),[{text:XC(e),className:"text-text-primary"}]}}function XC(e){return e.replace(/\x1b\[([0-9;]+)m/g,"")}function lo(e){const r=YC(e),s=[];return r.forEach((i,c)=>{const u=i.text.split(`
|
|
85
|
-
`);u.forEach((h,l)=>{s.push(gn.createElement("span",{key:`${c}-${l}`,className:i.className,style:{display:"inline-block",whiteSpace:"pre-wrap"}},h)),l<u.length-1&&s.push(gn.createElement("br",{key:`${c}-${l}-br`}))})}),s.length===1?s[0]:s}const ZC=P.memo(function({title:r,logs:s,onClose:i,preClassName:c}){const u=P.useRef(null);return P.useEffect(()=>{u.current&&(u.current.scrollTop=u.current.scrollHeight)},[s]),o.jsx(jt,{isOpen:!0,onClose:i,title:r,size:"full",children:o.jsx("pre",{ref:u,className:c,children:s.length===0?o.jsx("span",{className:"text-text-muted",children:"No output yet"}):s.map((h,l)=>o.jsx("span",{className:h.stream==="stderr"?"text-accent-warning":"",children:lo(h.content)},l))})})}),QC=P.memo(function({logs:r,anchorRef:s,isHiding:i,onExpand:c,onClose:u}){const[h,l]=P.useState(null),d=P.useRef(null);return P.useEffect(()=>{var g;const f=(g=s.current)==null?void 0:g.getBoundingClientRect();f&&l({bottom:window.innerHeight-f.bottom,right:window.innerWidth-f.right,width:f.width,height:f.height})},[s]),P.useEffect(()=>{d.current&&(d.current.scrollTop=d.current.scrollHeight)},[r]),h?o.jsxs("div",{className:"relative",children:[o.jsx("pre",{ref:d,className:"fixed z-50 text-sm font-mono text-text-primary bg-bg-primary p-2 rounded border border-border overflow-auto transition-all duration-150 ease-out select-text",style:{bottom:h.bottom,right:h.right,width:h.width*2,maxHeight:h.height*3,transformOrigin:"bottom right",transform:i?"scale(0.01)":"scale(1)",opacity:i?0:1},children:r.map((f,g)=>o.jsx("span",{className:f.stream==="stderr"?"text-accent-warning":"",children:lo(f.content)},g))}),o.jsx("button",{onClick:()=>{u(),c()},className:"fixed z-50 px-2 py-1 rounded text-xs font-medium bg-accent-primary/30 text-text-primary hover:bg-accent-primary/50 transition-colors duration-150",style:{bottom:h.bottom+8,right:h.right+8},children:"Expand"})]}):null}),JC=P.memo(function({workdir:r}){const s=gr(G=>G.setWorkdir),i=gr(G=>G.status),c=gr(G=>G.config),u=gr(G=>G.logs),h=gr(G=>G.start),l=gr(G=>G.stop),d=gr(G=>G.fetchLogs),f=Ce(G=>G.currentSession),[g,m]=P.useState(!1),[v,S]=P.useState(!1),[k,C]=P.useState(!1),[y,b]=P.useState(!1),x=P.useRef(null),_=P.useRef(null),j=P.useRef(null),A=P.useRef(null),N=P.useRef(null),D=()=>{const G=i==null?void 0:i.inspectProxyPort;if(!G){i!=null&&i.url&&window.open(i.url,"_blank");return}const W=`${window.location.protocol}//${window.location.hostname}:${G}`,I=window.open(W,"openfox-inspect");if(I){N.current=I;const $=()=>{var X;!N.current||N.current.closed||(N.current.postMessage({type:"setFoxSessionId",sessionId:(f==null?void 0:f.id)??null},"*"),N.current.postMessage({type:"setFoxSessionTitle",sessionTitle:((X=f==null?void 0:f.metadata)==null?void 0:X.title)??null},"*"),N.current.postMessage({type:"setFoxInspectEnabled",enabled:!(c!=null&&c.disableInspect)},"*"))},B=setInterval(()=>{$(),(!N.current||N.current.closed)&&clearInterval(B)},500);setTimeout(()=>clearInterval(B),5e3)}},T=(i==null?void 0:i.state)??"off",z=c!==null,O=T==="running"||T==="warning";P.useEffect(()=>{s(r??null)},[r,s]),P.useEffect(()=>{O&&d()},[O,d]),P.useEffect(()=>{j.current&&O&&(j.current.scrollTop=j.current.scrollHeight)},[u,O]);const q=()=>{O?l():h()};return o.jsxs("div",{className:"mt-2 pt-3 border-t border-border space-y-3",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:`inline-block w-2.5 h-2.5 rounded-full flex-shrink-0 ${T==="running"?"bg-accent-success":T==="warning"?"bg-accent-warning":T==="error"?"bg-accent-error":"bg-text-muted"}`}),o.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:"Dev Server"})]}),o.jsx("button",{onClick:()=>m(!0),className:"p-1.5 rounded hover:bg-bg-tertiary transition-colors text-text-muted",title:"Configure dev server",children:o.jsx(vw,{})})]}),z?o.jsxs(o.Fragment,{children:[T==="running"||T==="warning"?o.jsxs("div",{className:"flex gap-2",children:[o.jsxs("button",{onClick:q,className:"flex-1 flex items-center justify-center gap-1.5 rounded font-medium text-sm px-3 py-1.5 bg-bg-tertiary text-text-primary hover:bg-border transition-colors",children:[o.jsx(Nw,{}),"Stop"]}),(i==null?void 0:i.url)&&o.jsxs("button",{onClick:()=>D(),className:"flex-1 flex items-center justify-center gap-1.5 rounded font-medium text-sm px-3 py-1.5 bg-accent-primary/25 text-text-primary hover:bg-accent-primary/40 transition-colors",title:i.url,children:[o.jsx(Sw,{}),"Open"]})]}):o.jsx("button",{onClick:q,className:"w-full rounded font-medium text-sm px-3 py-1.5 bg-accent-primary/25 text-text-primary hover:bg-accent-primary/40 transition-colors",children:"Start"}),O&&o.jsxs("div",{ref:A,className:"relative",onMouseEnter:()=>{_.current&&clearTimeout(_.current),x.current=setTimeout(()=>{C(!0),b(!1)},500)},onMouseLeave:()=>{x.current&&clearTimeout(x.current),b(!0),_.current=setTimeout(()=>C(!1),150)},children:[o.jsx("pre",{ref:j,className:"text-sm bg-bg-primary p-2 rounded overflow-auto max-h-[200px] border border-border",children:u.length===0?o.jsx("span",{className:"text-text-muted",children:"No output yet"}):u.map((G,W)=>o.jsx("span",{className:G.stream==="stderr"?"text-accent-warning":"",children:lo(G.content)},W))}),(k||y)&&A.current&&xo.createPortal(o.jsx(QC,{logs:u,anchorRef:A,isHiding:y,onExpand:()=>S(!0),onClose:()=>C(!1)}),document.body)]})]}):o.jsx("button",{onClick:()=>m(!0),className:"w-full rounded font-medium text-sm px-3 py-1.5 bg-bg-tertiary text-text-muted hover:bg-border transition-colors",children:"Configure"}),o.jsx(VC,{isOpen:g,onClose:()=>m(!1)}),v&&o.jsx(ZC,{title:"Dev Server Logs",logs:u,onClose:()=>S(!1)})]})});function e2({isOpen:e,onClose:r,processName:s,logs:i}){return e?o.jsx(jt,{isOpen:e,onClose:r,title:s,size:"lg",children:o.jsx("pre",{className:"flex-1 overflow-auto text-sm font-mono text-text-primary whitespace-pre-wrap",children:i.map((c,u)=>o.jsx("span",{className:c.stream==="stderr"?"text-accent-error":"",children:c.content},u))})}):null}const t2=P.memo(function({sessionId:r}){var S;const s=to(k=>k.processes),i=to(k=>k.stopProcess),[c,u]=P.useState(null),[h,l]=P.useState([]),d=s.filter(k=>k.status!=="exited"),f=d.filter(k=>k.status==="running").length;if(s.length===0)return null;const g=k=>{switch(k){case"running":return"bg-accent-success";case"starting":return"bg-accent-warning";case"stopping":return"bg-accent-warning";case"exited":return"bg-text-muted";default:return"bg-text-muted"}},m=k=>{const C=to.getState().logs[k]??[];l(C.map(y=>({content:y.content,stream:y.stream}))),u(k)},v=k=>{r&&i(k,r)};return o.jsxs("div",{className:"mt-2 pt-3 border-t border-border space-y-3",children:[o.jsx("div",{className:"flex items-center justify-between",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-full flex-shrink-0 bg-accent-primary"}),o.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:"Background"}),o.jsxs("span",{className:"text-xs text-text-muted",children:["(",f," running)"]})]})}),o.jsx("div",{className:"space-y-2",children:d.map(k=>o.jsx("div",{className:"border border-border rounded p-2",children:o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[o.jsx("span",{className:`inline-block w-2 h-2 rounded-full flex-shrink-0 ${g(k.status)}`}),o.jsx("span",{className:"text-sm text-text-primary truncate",title:k.name,children:k.name}),o.jsxs("span",{className:"text-xs text-text-muted",children:["[",k.status,"]"]})]}),o.jsxs("div",{className:"flex gap-1 ml-2",children:[o.jsx("button",{onClick:()=>m(k.id),className:"px-2 py-1 text-xs rounded bg-bg-tertiary hover:bg-border text-text-secondary transition-colors",title:"View logs",children:"Logs"}),o.jsx("button",{onClick:()=>v(k.id),className:"px-2 py-1 text-xs rounded bg-bg-tertiary hover:bg-accent-error/20 text-text-secondary hover:text-accent-error transition-colors",title:"Stop process",children:"Stop"})]})]})},k.id))}),c&&o.jsx(e2,{isOpen:!!c,onClose:()=>{u(null),l([])},processName:((S=d.find(k=>k.id===c))==null?void 0:S.name)??"",logs:h})]})});function pb({summary:e,messages:r,workdir:s}){const[i,c]=P.useState(!1),u=NC(r),{branch:h}=TC(s),l=Rt(f=>f.version),d=Ce(f=>f.currentSession);return o.jsxs("div",{className:"flex flex-col h-full",children:[u&&o.jsxs("div",{className:"mb-4",children:[o.jsx("button",{onClick:()=>c(!0),className:"w-full flex items-center justify-center px-3 py-2 rounded bg-bg-tertiary hover:bg-bg-secondary transition-colors",title:"View detailed response and call-level stats",children:o.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-muted",children:[o.jsx("span",{className:"text-text-secondary",children:AC(u.aiTime)}),o.jsx("span",{className:"w-px h-3 bg-border"}),o.jsx("span",{className:"text-text-secondary",children:lb(u.avgPrefillSpeed)}),o.jsx("span",{children:"pp"}),o.jsx("span",{className:"w-px h-3 bg-border"}),o.jsx("span",{className:"text-text-secondary",children:lb(u.avgGenerationSpeed)}),o.jsx("span",{children:"tg"})]})}),o.jsx(FC,{isOpen:i,onClose:()=>c(!1),stats:u})]}),o.jsxs("div",{className:"flex flex-col flex-1 overflow-y-auto",children:[o.jsx("div",{className:"flex items-center justify-between mb-2",children:o.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:"Summary"})}),e?o.jsx("p",{className:"text-sm text-text-primary leading-relaxed",children:e}):o.jsx("div",{className:"text-text-muted text-sm text-center py-2",children:"No summary yet"}),o.jsxs("div",{className:"mt-4",children:[o.jsx("h3",{className:"text-sm font-semibold text-text-primary mb-2",children:"Progress"}),o.jsx(WC,{criteria:(d==null?void 0:d.criteria)??[]})]})]}),h&&o.jsxs("div",{className:"mt-4 flex items-center gap-2 text-sm",children:[o.jsx(pw,{}),o.jsx("span",{className:"truncate text-text-secondary",title:h,children:h})]}),o.jsx(JC,{workdir:s}),o.jsx(t2,{sessionId:d==null?void 0:d.id}),l&&o.jsxs("div",{className:"mt-4 pt-4 border-t border-border text-center text-xs text-text-muted",children:[o.jsx("a",{href:"https://github.com/co-l/openfox",target:"_blank",rel:"noopener noreferrer",className:"hover:text-accent-primary transition-colors",children:"OpenFox"})," - ",o.jsxs("span",{children:["v",l]})]})]})}function n2({children:e,criteriaSidebarOpen:r=!0,onCriteriaSidebarToggle:s,messages:i}){const c=Ce(u=>u.currentSession);return o.jsxs("div",{className:"relative h-full overflow-hidden",children:[r&&o.jsx("div",{className:"fixed md:hidden inset-0 bg-secondary/50 z-40",onClick:s}),o.jsxs("div",{className:"flex h-full",children:[o.jsx("div",{className:"flex-1 min-w-0 flex flex-col overflow-hidden bg-secondary",children:e}),r?o.jsx("aside",{className:"hidden md:block w-[320px] shrink-0 border-l border-border p-4 overflow-y-auto bg-secondary",children:o.jsx(pb,{summary:(c==null?void 0:c.summary)??null,messages:i,workdir:c==null?void 0:c.workdir})}):o.jsx("aside",{className:"hidden md:block w-0 shrink-0 overflow-hidden border-l-0"}),o.jsx("aside",{className:`
|
|
85
|
+
`);u.forEach((h,l)=>{s.push(gn.createElement("span",{key:`${c}-${l}`,className:i.className,style:{display:"inline-block",whiteSpace:"pre-wrap"}},h)),l<u.length-1&&s.push(gn.createElement("br",{key:`${c}-${l}-br`}))})}),s.length===1?s[0]:s}const ZC=P.memo(function({title:r,logs:s,onClose:i,preClassName:c}){const u=P.useRef(null);return P.useEffect(()=>{u.current&&(u.current.scrollTop=u.current.scrollHeight)},[s]),o.jsx(jt,{isOpen:!0,onClose:i,title:r,size:"full",children:o.jsx("pre",{ref:u,className:c,children:s.length===0?o.jsx("span",{className:"text-text-muted",children:"No output yet"}):s.map((h,l)=>o.jsx("span",{className:h.stream==="stderr"?"text-accent-warning":"",children:lo(h.content)},l))})})}),QC=P.memo(function({logs:r,anchorRef:s,isHiding:i,onExpand:c,onClose:u}){const[h,l]=P.useState(null),d=P.useRef(null);return P.useEffect(()=>{var g;const f=(g=s.current)==null?void 0:g.getBoundingClientRect();f&&l({bottom:window.innerHeight-f.bottom,right:window.innerWidth-f.right,width:f.width,height:f.height})},[s]),P.useEffect(()=>{d.current&&(d.current.scrollTop=d.current.scrollHeight)},[r]),h?o.jsxs("div",{className:"relative",children:[o.jsx("pre",{ref:d,className:"fixed z-50 text-sm font-mono text-text-primary bg-bg-primary p-2 rounded border border-border overflow-auto transition-all duration-150 ease-out select-text",style:{bottom:h.bottom,right:h.right,width:h.width*2,maxHeight:h.height*3,transformOrigin:"bottom right",transform:i?"scale(0.01)":"scale(1)",opacity:i?0:1},children:r.map((f,g)=>o.jsx("span",{className:f.stream==="stderr"?"text-accent-warning":"",children:lo(f.content)},g))}),o.jsx("button",{onClick:()=>{u(),c()},className:"fixed z-50 px-2 py-1 rounded text-xs font-medium bg-accent-primary/30 text-text-primary hover:bg-accent-primary/50 transition-colors duration-150",style:{bottom:h.bottom+8,right:h.right+8},children:"Expand"})]}):null}),JC=P.memo(function({workdir:r}){const s=gr(G=>G.setWorkdir),i=gr(G=>G.status),c=gr(G=>G.config),u=gr(G=>G.logs),h=gr(G=>G.start),l=gr(G=>G.stop),d=gr(G=>G.fetchLogs),f=Ce(G=>G.currentSession),[g,m]=P.useState(!1),[v,S]=P.useState(!1),[k,C]=P.useState(!1),[y,b]=P.useState(!1),x=P.useRef(null),_=P.useRef(null),j=P.useRef(null),A=P.useRef(null),N=P.useRef(null),D=()=>{const G=i==null?void 0:i.inspectProxyPort;if(!G){i!=null&&i.url&&window.open(i.url,"_blank");return}const W=`${window.location.protocol}//${window.location.hostname}:${G}`,I=window.open(W,"_blank");if(I){N.current=I;const $=()=>{var X;!N.current||N.current.closed||(N.current.postMessage({type:"setFoxSessionId",sessionId:(f==null?void 0:f.id)??null},"*"),N.current.postMessage({type:"setFoxSessionTitle",sessionTitle:((X=f==null?void 0:f.metadata)==null?void 0:X.title)??null},"*"),N.current.postMessage({type:"setFoxInspectEnabled",enabled:!(c!=null&&c.disableInspect)},"*"))},B=setInterval(()=>{$(),(!N.current||N.current.closed)&&clearInterval(B)},500);setTimeout(()=>clearInterval(B),5e3)}},T=(i==null?void 0:i.state)??"off",z=c!==null,O=T==="running"||T==="warning";P.useEffect(()=>{s(r??null)},[r,s]),P.useEffect(()=>{O&&d()},[O,d]),P.useEffect(()=>{j.current&&O&&(j.current.scrollTop=j.current.scrollHeight)},[u,O]);const q=()=>{O?l():h()};return o.jsxs("div",{className:"mt-2 pt-3 border-t border-border space-y-3",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:`inline-block w-2.5 h-2.5 rounded-full flex-shrink-0 ${T==="running"?"bg-accent-success":T==="warning"?"bg-accent-warning":T==="error"?"bg-accent-error":"bg-text-muted"}`}),o.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:"Dev Server"})]}),o.jsx("button",{onClick:()=>m(!0),className:"p-1.5 rounded hover:bg-bg-tertiary transition-colors text-text-muted",title:"Configure dev server",children:o.jsx(vw,{})})]}),z?o.jsxs(o.Fragment,{children:[T==="running"||T==="warning"?o.jsxs("div",{className:"flex gap-2",children:[o.jsxs("button",{onClick:q,className:"flex-1 flex items-center justify-center gap-1.5 rounded font-medium text-sm px-3 py-1.5 bg-bg-tertiary text-text-primary hover:bg-border transition-colors",children:[o.jsx(Nw,{}),"Stop"]}),(i==null?void 0:i.url)&&o.jsxs("button",{onClick:()=>D(),className:"flex-1 flex items-center justify-center gap-1.5 rounded font-medium text-sm px-3 py-1.5 bg-accent-primary/25 text-text-primary hover:bg-accent-primary/40 transition-colors",title:i.url,children:[o.jsx(Sw,{}),"Open"]})]}):o.jsx("button",{onClick:q,className:"w-full rounded font-medium text-sm px-3 py-1.5 bg-accent-primary/25 text-text-primary hover:bg-accent-primary/40 transition-colors",children:"Start"}),O&&o.jsxs("div",{ref:A,className:"relative",onMouseEnter:()=>{_.current&&clearTimeout(_.current),x.current=setTimeout(()=>{C(!0),b(!1)},500)},onMouseLeave:()=>{x.current&&clearTimeout(x.current),b(!0),_.current=setTimeout(()=>C(!1),150)},children:[o.jsx("pre",{ref:j,className:"text-sm bg-bg-primary p-2 rounded overflow-auto max-h-[200px] border border-border",children:u.length===0?o.jsx("span",{className:"text-text-muted",children:"No output yet"}):u.map((G,W)=>o.jsx("span",{className:G.stream==="stderr"?"text-accent-warning":"",children:lo(G.content)},W))}),(k||y)&&A.current&&xo.createPortal(o.jsx(QC,{logs:u,anchorRef:A,isHiding:y,onExpand:()=>S(!0),onClose:()=>C(!1)}),document.body)]})]}):o.jsx("button",{onClick:()=>m(!0),className:"w-full rounded font-medium text-sm px-3 py-1.5 bg-bg-tertiary text-text-muted hover:bg-border transition-colors",children:"Configure"}),o.jsx(VC,{isOpen:g,onClose:()=>m(!1)}),v&&o.jsx(ZC,{title:"Dev Server Logs",logs:u,onClose:()=>S(!1)})]})});function e2({isOpen:e,onClose:r,processName:s,logs:i}){return e?o.jsx(jt,{isOpen:e,onClose:r,title:s,size:"lg",children:o.jsx("pre",{className:"flex-1 overflow-auto text-sm font-mono text-text-primary whitespace-pre-wrap",children:i.map((c,u)=>o.jsx("span",{className:c.stream==="stderr"?"text-accent-error":"",children:c.content},u))})}):null}const t2=P.memo(function({sessionId:r}){var S;const s=to(k=>k.processes),i=to(k=>k.stopProcess),[c,u]=P.useState(null),[h,l]=P.useState([]),d=s.filter(k=>k.status!=="exited"),f=d.filter(k=>k.status==="running").length;if(s.length===0)return null;const g=k=>{switch(k){case"running":return"bg-accent-success";case"starting":return"bg-accent-warning";case"stopping":return"bg-accent-warning";case"exited":return"bg-text-muted";default:return"bg-text-muted"}},m=k=>{const C=to.getState().logs[k]??[];l(C.map(y=>({content:y.content,stream:y.stream}))),u(k)},v=k=>{r&&i(k,r)};return o.jsxs("div",{className:"mt-2 pt-3 border-t border-border space-y-3",children:[o.jsx("div",{className:"flex items-center justify-between",children:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-full flex-shrink-0 bg-accent-primary"}),o.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:"Background"}),o.jsxs("span",{className:"text-xs text-text-muted",children:["(",f," running)"]})]})}),o.jsx("div",{className:"space-y-2",children:d.map(k=>o.jsx("div",{className:"border border-border rounded p-2",children:o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[o.jsx("span",{className:`inline-block w-2 h-2 rounded-full flex-shrink-0 ${g(k.status)}`}),o.jsx("span",{className:"text-sm text-text-primary truncate",title:k.name,children:k.name}),o.jsxs("span",{className:"text-xs text-text-muted",children:["[",k.status,"]"]})]}),o.jsxs("div",{className:"flex gap-1 ml-2",children:[o.jsx("button",{onClick:()=>m(k.id),className:"px-2 py-1 text-xs rounded bg-bg-tertiary hover:bg-border text-text-secondary transition-colors",title:"View logs",children:"Logs"}),o.jsx("button",{onClick:()=>v(k.id),className:"px-2 py-1 text-xs rounded bg-bg-tertiary hover:bg-accent-error/20 text-text-secondary hover:text-accent-error transition-colors",title:"Stop process",children:"Stop"})]})]})},k.id))}),c&&o.jsx(e2,{isOpen:!!c,onClose:()=>{u(null),l([])},processName:((S=d.find(k=>k.id===c))==null?void 0:S.name)??"",logs:h})]})});function pb({summary:e,messages:r,workdir:s}){const[i,c]=P.useState(!1),u=NC(r),{branch:h}=TC(s),l=Rt(f=>f.version),d=Ce(f=>f.currentSession);return o.jsxs("div",{className:"flex flex-col h-full",children:[u&&o.jsxs("div",{className:"mb-4",children:[o.jsx("button",{onClick:()=>c(!0),className:"w-full flex items-center justify-center px-3 py-2 rounded bg-bg-tertiary hover:bg-bg-secondary transition-colors",title:"View detailed response and call-level stats",children:o.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-muted",children:[o.jsx("span",{className:"text-text-secondary",children:AC(u.aiTime)}),o.jsx("span",{className:"w-px h-3 bg-border"}),o.jsx("span",{className:"text-text-secondary",children:lb(u.avgPrefillSpeed)}),o.jsx("span",{children:"pp"}),o.jsx("span",{className:"w-px h-3 bg-border"}),o.jsx("span",{className:"text-text-secondary",children:lb(u.avgGenerationSpeed)}),o.jsx("span",{children:"tg"})]})}),o.jsx(FC,{isOpen:i,onClose:()=>c(!1),stats:u})]}),o.jsxs("div",{className:"flex flex-col flex-1 overflow-y-auto",children:[o.jsx("div",{className:"flex items-center justify-between mb-2",children:o.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:"Summary"})}),e?o.jsx("p",{className:"text-sm text-text-primary leading-relaxed",children:e}):o.jsx("div",{className:"text-text-muted text-sm text-center py-2",children:"No summary yet"}),o.jsxs("div",{className:"mt-4",children:[o.jsx("h3",{className:"text-sm font-semibold text-text-primary mb-2",children:"Progress"}),o.jsx(WC,{criteria:(d==null?void 0:d.criteria)??[]})]})]}),h&&o.jsxs("div",{className:"mt-4 flex items-center gap-2 text-sm",children:[o.jsx(pw,{}),o.jsx("span",{className:"truncate text-text-secondary",title:h,children:h})]}),o.jsx(JC,{workdir:s}),o.jsx(t2,{sessionId:d==null?void 0:d.id}),l&&o.jsxs("div",{className:"mt-4 pt-4 border-t border-border text-center text-xs text-text-muted",children:[o.jsx("a",{href:"https://github.com/co-l/openfox",target:"_blank",rel:"noopener noreferrer",className:"hover:text-accent-primary transition-colors",children:"OpenFox"})," - ",o.jsxs("span",{children:["v",l]})]})]})}function n2({children:e,criteriaSidebarOpen:r=!0,onCriteriaSidebarToggle:s,messages:i}){const c=Ce(u=>u.currentSession);return o.jsxs("div",{className:"relative h-full overflow-hidden",children:[r&&o.jsx("div",{className:"fixed md:hidden inset-0 bg-secondary/50 z-40",onClick:s}),o.jsxs("div",{className:"flex h-full",children:[o.jsx("div",{className:"flex-1 min-w-0 flex flex-col overflow-hidden bg-secondary",children:e}),r?o.jsx("aside",{className:"hidden md:block w-[320px] shrink-0 border-l border-border p-4 overflow-y-auto bg-secondary",children:o.jsx(pb,{summary:(c==null?void 0:c.summary)??null,messages:i,workdir:c==null?void 0:c.workdir})}):o.jsx("aside",{className:"hidden md:block w-0 shrink-0 overflow-hidden border-l-0"}),o.jsx("aside",{className:`
|
|
86
86
|
md:hidden
|
|
87
87
|
p-4 overflow-y-auto bg-secondary
|
|
88
88
|
transition-all duration-300 ease-in-out
|