@polderlabs/bizar 7.0.1 → 7.0.2
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/bizar-dash/dist/assets/EnvVarsSection-BfhAz3ax.js +114 -0
- package/bizar-dash/dist/assets/EnvVarsSection-BfhAz3ax.js.map +1 -0
- package/bizar-dash/dist/assets/MobileChat-DLWdv6tQ.js +1 -0
- package/bizar-dash/dist/assets/{MobileChat-BRFjer8p.js.map → MobileChat-DLWdv6tQ.js.map} +1 -1
- package/bizar-dash/dist/assets/MobileSettings-Bxv62uPY.js +1 -0
- package/bizar-dash/dist/assets/{MobileSettings-Dw5jyJWi.js.map → MobileSettings-Bxv62uPY.js.map} +1 -1
- package/bizar-dash/dist/assets/Toast-ATSAmbdi.js +26 -0
- package/bizar-dash/dist/assets/Toast-ATSAmbdi.js.map +1 -0
- package/bizar-dash/dist/assets/main-306CZfn6.js +430 -0
- package/bizar-dash/dist/assets/main-306CZfn6.js.map +1 -0
- package/bizar-dash/dist/assets/main-G3bNDpY3.css +1 -0
- package/bizar-dash/dist/assets/mobile-C_naUN91.js +1 -0
- package/bizar-dash/dist/assets/{mobile-DRZsK3ic.js.map → mobile-C_naUN91.js.map} +1 -1
- package/bizar-dash/dist/assets/mobile-layout-GZ3bE8L6.js +211 -0
- package/bizar-dash/dist/assets/mobile-layout-GZ3bE8L6.js.map +1 -0
- package/bizar-dash/dist/assets/useSlashCommands-BOwD7lNb.js +65 -0
- package/bizar-dash/dist/assets/useSlashCommands-BOwD7lNb.js.map +1 -0
- package/bizar-dash/dist/index.html +6 -12
- package/bizar-dash/dist/mobile.html +2 -7
- package/package.json +1 -1
- package/bizar-dash/dist/assets/EnvVarsSection-weVnLz3Z.js +0 -4
- package/bizar-dash/dist/assets/EnvVarsSection-weVnLz3Z.js.map +0 -1
- package/bizar-dash/dist/assets/MobileChat-BRFjer8p.js +0 -1
- package/bizar-dash/dist/assets/MobileSettings-Dw5jyJWi.js +0 -1
- package/bizar-dash/dist/assets/Toast-WTxc3m2g.js +0 -1
- package/bizar-dash/dist/assets/Toast-WTxc3m2g.js.map +0 -1
- package/bizar-dash/dist/assets/flow-BpU0-gK2.js +0 -1
- package/bizar-dash/dist/assets/flow-BpU0-gK2.js.map +0 -1
- package/bizar-dash/dist/assets/fuzzy-l0sNRNKZ.js +0 -1
- package/bizar-dash/dist/assets/fuzzy-l0sNRNKZ.js.map +0 -1
- package/bizar-dash/dist/assets/icons-B0AKnYI3.js +0 -731
- package/bizar-dash/dist/assets/icons-B0AKnYI3.js.map +0 -1
- package/bizar-dash/dist/assets/main-BE4Uh9im.css +0 -1
- package/bizar-dash/dist/assets/main-DqC58FEZ.js +0 -18
- package/bizar-dash/dist/assets/main-DqC58FEZ.js.map +0 -1
- package/bizar-dash/dist/assets/markdown-w2bDDkAH.js +0 -1
- package/bizar-dash/dist/assets/markdown-w2bDDkAH.js.map +0 -1
- package/bizar-dash/dist/assets/mobile-DRZsK3ic.js +0 -1
- package/bizar-dash/dist/assets/mobile-layout-Ckru3HKJ.js +0 -2
- package/bizar-dash/dist/assets/mobile-layout-Ckru3HKJ.js.map +0 -1
- package/bizar-dash/dist/assets/react-vendor-BnuhLJ6X.css +0 -1
- package/bizar-dash/dist/assets/react-vendor-D3pra6w-.js +0 -46
- package/bizar-dash/dist/assets/react-vendor-D3pra6w-.js.map +0 -1
- package/bizar-dash/dist/assets/useSlashCommands-BAxVOU_a.js +0 -2
- package/bizar-dash/dist/assets/useSlashCommands-BAxVOU_a.js.map +0 -1
- package/bizar-dash/dist/assets/vendor-Di7Cp-rw.js +0 -45
- package/bizar-dash/dist/assets/vendor-Di7Cp-rw.js.map +0 -1
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
var jn=Object.defineProperty;var vn=(s,t,a)=>t in s?jn(s,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):s[t]=a;var Ps=(s,t,a)=>vn(s,typeof t!="symbol"?t+"":t,a);import{a as $,c as W,f as Te,l as is,b as as,t as Ea,S as he,e as bn,d as Cs,g as qs,_ as yn,W as xs,A as Nn,M as kn}from"./mobile-layout-Ckru3HKJ.js";import{r,j as e,a as La,R as Ke,i as wn,B as Sn,C as Cn,M as zn,H as oa,b as $n}from"./react-vendor-D3pra6w-.js";import{X as we,A as Ht,R as me,F as Rn,H as Tn,a as An,C as Kt,b as Ge,c as Mn,d as He,e as ds,L as Da,M as Js,B as Qe,f as xt,S as ps,g as Ae,h as In,i as es,j as Je,P as Rs,k as gs,l as Gs,m as Yt,n as ls,o as _a,p as fs,T as Xt,q as Qt,r as ke,s as En,t as Ee,u as Pa,v as Ln,w as Ts,W as Dn,x as Fa,y as dt,U as Hs,G as _n,z as Pn,D as cs,E as Me,I as _e,J as Jt,K as Oa,N as Zs,O as vt,Q as Fn,V as os,Y as On,Z as Ls,_ as Ie,$ as Ze,a0 as Ba,a1 as Ua,a2 as pt,a3 as Ot,a4 as As,a5 as rs,a6 as Zt,a7 as $s,a8 as Bn,a9 as Re,aa as bt,ab as Ms,ac as Un,ad as et,ae as js,af as Is,ag as Es,ah as Vn,ai as Wn,aj as vs,ak as qn,al as Gn,am as Hn,an as Kn,ao as Yn,ap as Xn,aq as da,ar as gt,as as Va,at as Qn,au as Jn,av as Zn,aw as ea,ax as ei,ay as si,az as ti,aA as ai,aB as Bt,aC as sa,aD as Wa,aE as Ks,aF as ni,aG as ii,aH as ri,aI as qa,aJ as Ys,aK as li,aL as ci,aM as ta,aN as Xs,aO as aa,aP as ft,aQ as ge,aR as oi,aS as di,aT as Ga,aU as mi,aV as ui,aW as hi,aX as ma,aY as xi,aZ as Ha,a_ as wt,a$ as Ka,b0 as na,b1 as pi,b2 as gi,b3 as fi,b4 as Ya,b5 as ji,b6 as vi,b7 as bi,b8 as yi,b9 as Ni,ba as Xa,bb as Qa}from"./icons-B0AKnYI3.js";import{B as M,c as oe,C as G,a as ee,b as te,A as ki,U as wi,G as Si,E as Ci,T as zi,S as $i,H as Ri,d as Ti}from"./EnvVarsSection-weVnLz3Z.js";import{u as ce,T as Ai}from"./Toast-WTxc3m2g.js";import{C as Mi,u as Ii,a as Ei,b as Li,c as Di,V as Ja}from"./useSlashCommands-BAxVOU_a.js";import{M as Za,r as en}from"./markdown-w2bDDkAH.js";import{P as ua}from"./flow-BpU0-gK2.js";import"./vendor-Di7Cp-rw.js";const sn=r.createContext(null),_i=["button:not([disabled])","[href]","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(", ");function Pe(){const s=r.useContext(sn);return s||{open:()=>"",close:()=>{},isModalOpen:!1}}function Pi({children:s}){const[t,a]=r.useState([]),n=r.useCallback(l=>{a(o=>{if(!l)return o.slice(0,-1);const c=o.findIndex(u=>u.id===l);return c===-1||c!==o.length-1?o:o.slice(0,-1)})},[]),i=r.useCallback(l=>{const o=`m${Math.random().toString(36).slice(2,9)}`;return a(c=>[...c,{...l,id:o}]),o},[]);return r.useEffect(()=>{if(t.length===0)return;const l=o=>{o.key==="Escape"&&(o.stopPropagation(),n())};return document.addEventListener("keydown",l),()=>document.removeEventListener("keydown",l)},[t.length,n]),e.jsxs(sn.Provider,{value:{open:i,close:n,isModalOpen:t.length>0},children:[s,typeof document<"u"&&La.createPortal(e.jsx("div",{className:"modal-stack","aria-hidden":t.length===0,children:t.map((l,o)=>e.jsx(Fi,{modal:l,onClose:()=>{var c;(c=l.onClose)==null||c.call(l),n(l.id)},depth:o},l.id))}),document.body)]})}function Fi({modal:s,onClose:t,depth:a}){const n=r.useRef(null),i=r.useRef(null),l=r.useId(),o=()=>{const c=n.current;return c?Array.from(c.querySelectorAll(_i)).filter(u=>!u.hasAttribute("disabled")&&u.tabIndex!==-1):[]};return r.useEffect(()=>{var x;i.current=document.activeElement instanceof HTMLElement?document.activeElement:null,(x=o()[0]??n.current)==null||x.focus();const u=h=>{var b,k,w;if(h.key!=="Tab")return;const m=o();if(m.length===0){h.preventDefault(),(b=n.current)==null||b.focus();return}const d=m[0],p=m[m.length-1],f=document.activeElement instanceof HTMLElement?document.activeElement:null;if(h.shiftKey){(!f||f===d||!((k=n.current)!=null&&k.contains(f)))&&(h.preventDefault(),p.focus());return}(!f||f===p||!((w=n.current)!=null&&w.contains(f)))&&(h.preventDefault(),d.focus())};return document.addEventListener("keydown",u),()=>{document.removeEventListener("keydown",u);const h=i.current;h&&h.isConnected&&h.focus()}},[]),e.jsx("div",{className:"modal-backdrop",onClick:c=>{c.stopPropagation(),c.target===c.currentTarget&&t()},style:a>0?{background:"rgba(0,0,0,0.4)"}:void 0,children:e.jsxs("div",{ref:n,className:"modal",role:"dialog","aria-modal":"true","aria-labelledby":s.title?l:void 0,tabIndex:-1,onClick:c=>c.stopPropagation(),style:s.width?{maxWidth:s.width}:void 0,children:[s.title&&e.jsxs("header",{className:"modal-header",children:[e.jsx("h2",{id:l,className:"modal-title",children:s.title}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Close",onClick:t,children:e.jsx(we,{size:16})})]}),e.jsx("div",{className:"modal-body",children:s.children}),s.footer&&e.jsx("footer",{className:"modal-footer",children:s.footer})]})})}const Oi=200,Bi=5*60*1e3,hs=new Map;function Ui(s){const t=hs.get(s);return t?Date.now()-t.ts>Bi?(hs.delete(s),null):t.data:null}function St(s,t){hs.size>=Oi&&[...hs.entries()].sort((n,i)=>n[1].ts-i[1].ts).slice(0,50).map(([n])=>n).forEach(n=>hs.delete(n)),hs.set(s,{data:t,ts:Date.now()})}function Vi(s){if(!s||s==="/")return[{label:"/",path:"/"}];const t=s.split("/").filter(Boolean),a=[];let n="";for(let i=0;i<t.length;i++)n+="/"+t[i],a.push({label:t[i],path:n});return a}function Wi(s){return[...s].sort((t,a)=>t.isDir!==a.isDir?t.isDir?-1:1:t.name.localeCompare(a.name,void 0,{sensitivity:"base"}))}function qi(s){const t=s.trim();return t?t!==s?{ok:!1,reason:"Name cannot have leading or trailing whitespace."}:t==="."?{ok:!1,reason:"Name cannot be '.'."}:t===".."?{ok:!1,reason:"Name cannot be '..'."}:t.startsWith("-")?{ok:!1,reason:"Name cannot start with '-'."}:t.length>255?{ok:!1,reason:"Name cannot be longer than 255 characters."}:/[/\0:*?"<>|]/.test(t)?{ok:!1,reason:'Name cannot contain / \\ : * ? " < > |'}:{ok:!0}:{ok:!1,reason:"Name cannot be empty."}}function Gi({value:s,onChange:t,initialPath:a,projectsDirectory:n,rootLabel:i="Home",height:l=360}){const[o,c]=r.useState(a??n??""),[u,x]=r.useState(new Set),[h,m]=r.useState(-1),[d,p]=r.useState(null),[f,b]=r.useState({}),[k,w]=r.useState(!1),[v,C]=r.useState(null),[z,y]=r.useState(!1),[R,S]=r.useState(""),[N,P]=r.useState(null),[g,j]=r.useState(!1),T=r.useRef(null),F=r.useCallback(async L=>{try{const H=Ui(L);if(H)return H;const q=await $.get("/fs?path="+encodeURIComponent(L));return St(L,q),q}catch{return null}},[]),A=r.useCallback(async L=>{var H;w(!0),C(null);try{const q=await $.get("/fs?path="+encodeURIComponent(L));St(L,q),p(q),m(-1)}catch(q){const Z=((H=q.data)==null?void 0:H.message)??q.message??"Failed to load directory";C(Z)}finally{w(!1)}},[]);r.useEffect(()=>{o?A(o):$.get("/fs").then(L=>{St("",L),p(L),c(L.path),L.path!==s&&t(L.path)}).catch(()=>{C("Could not determine home directory."),w(!1)})},[o]),r.useEffect(()=>{s&&s!==o&&c(s)},[s]);const U=d?Wi(d.entries):[],Y=U.filter(L=>L.isDir),B=U,K=L=>{L.isDir&&(c(L.path),t(L.path))},D=()=>{d!=null&&d.parent&&(c(d.parent),t(d.parent))},_=L=>{L!==o&&(c(L),t(L))},ae=async()=>{const L=await F("");L&&(c(L.path),t(L.path))},J=async()=>{if(!n)return;const L=await F(n);L&&(c(L.path),t(L.path))},ne=()=>{y(!0),S(""),P(null),setTimeout(()=>{var L;return(L=T.current)==null?void 0:L.focus()},0)},I=()=>{y(!1),S(""),P(null)},V=async()=>{var H;const L=qi(R);if(!L.ok){P(L.reason);return}j(!0),P(null);try{const q=await $.post("/fs/mkdir",{parent:o,name:R.trim()});hs.delete(o),await A(o),t(q.path),y(!1),S("")}catch(q){const Z=q;Z.status===409?P(`A folder named "${R.trim()}" already exists.`):P(((H=Z.data)==null?void 0:H.message)??q.message??"Failed to create folder.")}finally{j(!1)}},ie=L=>{L.key==="Enter"?(L.preventDefault(),V()):L.key==="Escape"&&(L.preventDefault(),I())},de=L=>{x(H=>{const q=new Set(H);return q.has(L)?q.delete(L):q.add(L),q}),f[L]||F(L).then(H=>{H&&b(q=>({...q,[L]:H.entries.filter(Z=>Z.isDir)}))})},O=L=>{if(!d)return;const H=B.filter(le=>le.isDir),q=B.filter(le=>!le.isDir),Z=[...H,...q];if(L.key==="ArrowDown")L.preventDefault(),m(le=>Math.min(le+1,Z.length-1));else if(L.key==="ArrowUp")L.preventDefault(),m(le=>Math.max(le-1,0));else if(L.key==="Enter"||L.key===" "){L.preventDefault();const le=Z[h];le&&(L.key==="Enter"&&le.isDir?K(le):le.isDir&&t(le.path))}else L.key==="Backspace"&&(L.preventDefault(),D())},Q=Vi((d==null?void 0:d.path)??o??"/"),re=d==null?void 0:d.parent,xe=re!=null,fe=o.split("/").filter(Boolean).at(-1)??"/";return e.jsxs("div",{className:"file-browser",onKeyDown:O,tabIndex:-1,children:[e.jsx("div",{className:"file-browser-breadcrumb",role:"navigation","aria-label":"Path breadcrumb",children:Q.map((L,H)=>e.jsxs("span",{className:"file-browser-breadcrumb-item",children:[H>0&&e.jsx("span",{className:"file-browser-breadcrumb-sep","aria-hidden":!0,children:"/"}),e.jsx("button",{type:"button",className:"file-browser-breadcrumb-btn",onClick:()=>_(L.path),title:L.path,children:H===0?L.path==="/"?"/":i:L.label})]},L.path))}),e.jsxs("div",{className:"file-browser-toolbar",children:[e.jsxs("div",{className:"file-browser-toolbar-left",children:[e.jsx("button",{type:"button",className:"file-browser-tool-btn",onClick:D,disabled:!xe,title:"Go up (Backspace)","aria-label":"Go up one level",children:e.jsx(Ht,{size:13})}),e.jsx("button",{type:"button",className:"file-browser-tool-btn",onClick:()=>A(o),disabled:k,title:"Refresh","aria-label":"Refresh",children:e.jsx(me,{size:13,className:k?"spin":""})}),e.jsx("button",{type:"button",className:"file-browser-tool-btn",onClick:ne,title:"New folder","aria-label":"Create new folder",children:e.jsx(Rn,{size:13})}),e.jsxs("div",{className:"file-browser-chips",children:[e.jsxs("button",{type:"button",className:"file-browser-chip",onClick:ae,children:[e.jsx(Tn,{size:11})," ",i]}),n&&e.jsxs("button",{type:"button",className:"file-browser-chip",onClick:J,title:n,children:[e.jsx(An,{size:11})," ",n.split("/").filter(Boolean).at(-1)??"Projects"]})]})]}),z?e.jsxs("div",{className:"file-browser-mkdir",children:[e.jsx("input",{ref:T,type:"text",className:"file-browser-mkdir-input",placeholder:"Folder name",value:R,onChange:L=>{S(L.target.value),P(null)},onKeyDown:ie,"aria-label":"New folder name","aria-invalid":N?"true":void 0,"aria-describedby":N?"mkdir-error":void 0,disabled:g,maxLength:255}),N?e.jsx("span",{id:"mkdir-error",className:"file-browser-mkdir-error",role:"alert",children:N}):e.jsx("span",{className:"file-browser-mkdir-hint",children:"Enter to create, Esc to cancel"})]}):e.jsx("span",{className:"file-browser-count-hint",children:k?"…":`${U.length} in ${fe}`})]}),v&&e.jsxs("div",{className:"file-browser-error",children:[e.jsx(Kt,{size:13}),e.jsx("span",{children:v}),e.jsx("button",{type:"button",className:"file-browser-retry",onClick:()=>A(o),children:"Retry"})]}),e.jsxs("div",{className:"file-browser-body",style:{height:l},children:[e.jsx("div",{className:"file-browser-pane file-browser-tree","aria-label":"Folder tree",children:k&&!d?e.jsx(Hi,{}):e.jsx(tn,{path:o,entries:Y,expanded:u,childrenMap:f,onToggle:de,onNavigate:K,level:0})}),e.jsxs("div",{className:"file-browser-pane file-browser-flat","aria-label":"Directory contents",children:[e.jsxs("div",{className:"file-browser-flat-header",children:[e.jsx("span",{children:"Name"}),e.jsx("span",{children:"Type"})]}),k&&!d?e.jsx(Ki,{}):e.jsxs(e.Fragment,{children:[(d==null?void 0:d.truncated)&&e.jsxs("div",{className:"file-browser-truncated-banner",role:"status",children:["Showing first 500 of ",d.totalEntries," entries. Navigate into a subfolder to see more."]}),B.length===0?e.jsx("div",{className:"file-browser-empty",children:"This folder is empty"}):e.jsx("div",{className:"file-browser-flat-list",children:B.map((L,H)=>{const q=L.isDir,Z=H===h,le=L.path===s;return e.jsxs("div",{role:"option","aria-selected":le,className:["file-browser-row",q?"file-browser-row--dir":"file-browser-row--file",Z&&"file-browser-row--selected",le&&q&&"file-browser-row--active",!q&&"file-browser-row--disabled"].filter(Boolean).join(" "),onClick:()=>{q&&(m(H),t(L.path))},onDoubleClick:()=>{q&&K(L)},title:L.path,children:[e.jsx("span",{className:"file-browser-row-icon",children:q?e.jsx(Ge,{size:13}):e.jsx(Mn,{size:13})}),e.jsx("span",{className:"file-browser-row-name",children:L.name}),e.jsx("span",{className:"file-browser-row-type",children:q?"Folder":""})]},L.path)})})]})]})]}),e.jsxs("div",{className:"file-browser-footer-hint",children:["Select a folder, then click Add. Use ",e.jsx("kbd",{children:"↑"})," ",e.jsx("kbd",{children:"↓"})," to navigate, ",e.jsx("kbd",{children:"Enter"})," to confirm."]})]})}function tn({path:s,entries:t,expanded:a,childrenMap:n,onToggle:i,onNavigate:l,level:o}){return e.jsx("ul",{className:"file-browser-tree-list",role:"group",children:t.map(c=>{const u=a.has(c.path),x=n[c.path]??[];return e.jsxs("li",{className:"file-browser-tree-node",children:[e.jsxs("div",{className:["file-browser-tree-row",u&&"file-browser-tree-row--expanded"].filter(Boolean).join(" "),style:{paddingLeft:`${o*16+8}px`},children:[e.jsx("button",{type:"button",className:"file-browser-tree-toggle",onClick:h=>{h.stopPropagation(),i(c.path)},"aria-label":u?"Collapse":"Expand",children:(x.length>0,u?e.jsx(He,{size:11}):e.jsx(ds,{size:11}))}),e.jsxs("button",{type:"button",className:"file-browser-tree-name",onClick:()=>l(c),title:c.path,children:[e.jsx(Ge,{size:12}),e.jsx("span",{children:c.name})]})]}),u&&x.length>0&&e.jsx(tn,{path:c.path,entries:x,expanded:a,childrenMap:n,onToggle:i,onNavigate:l,level:o+1})]},c.path)})})}function Hi(){return e.jsx("div",{className:"file-browser-skeleton-wrap",children:[80,60,90,55,70].map((s,t)=>e.jsx("div",{className:"file-browser-skeleton-row",style:{width:s}},t))})}function Ki(){return e.jsx("div",{className:"file-browser-skeleton-wrap",children:[60,90,70,50,80,65].map((s,t)=>e.jsx("div",{className:"file-browser-skeleton-row",style:{width:s}},t))})}const Ut=[{id:"overview",label:"Overview",icon:Da},{id:"chat",label:"Chat",icon:Js},{id:"agents",label:"Agents",icon:Qe},{id:"artifacts",label:"Glyphs",icon:xt},{id:"tasks",label:"Tasks",icon:ps},{id:"activity",label:"Activity",icon:Ae},{id:"background",label:"Active",icon:In},{id:"skills",label:"Skills",icon:es},{id:"memory",label:"Memory",icon:Je},{id:"mods",label:"Mods",icon:Rs},{id:"schedules",label:"Schedules",icon:gs},{id:"history",label:"History",icon:Gs},{id:"minimax",label:"Usage",icon:Yt},{id:"eval",label:"Eval",icon:ls},{id:"doctor",label:"Doctor",icon:_a},{id:"harness",label:"Harness",icon:fs},{id:"goal-planner",label:"Goals",icon:Xt},{id:"settings",label:"Settings",icon:Qt}];function Yi({activeTab:s,onTabChange:t,wsStatus:a,version:n,activeProject:i,projects:l,onProjectChange:o,onProjectsRefresh:c,onOpenSearch:u,settings:x,rightSlot:h,notificationsSlot:m,showTabs:d=!0,extraTabs:p,clineStatus:f=null}){return e.jsxs("header",{className:"topbar",children:[e.jsxs("div",{className:"topbar-row",children:[e.jsxs("div",{className:"brand",children:[e.jsx("span",{className:"brand-logo","aria-hidden":"true",children:"ᛒ"}),e.jsx("span",{className:"brand-title",children:"Bizar"}),e.jsx("span",{className:"brand-version",children:n})]}),e.jsx(Xi,{activeProject:i,projects:l,onChange:o,onRefresh:c,settings:x??null}),e.jsxs("button",{type:"button",className:"topbar-search",onClick:u,title:"Search (Ctrl/Cmd+K)","aria-label":"Open search",children:[e.jsx(ke,{size:14}),e.jsx("span",{className:"muted",children:"Search…"}),e.jsx("kbd",{children:"⌘K"})]}),e.jsx("div",{className:"topbar-spacer"}),e.jsxs("div",{className:"topbar-right",children:[m,h,f&&e.jsxs("div",{className:W("cline-status",`cline-${f.state}`),title:f.detail||`Cline ${f.label}`,"aria-label":`Cline runtime: ${f.label}`,children:[e.jsx("span",{className:"cline-dot"}),e.jsxs("span",{className:"cline-label",children:["Cline · ",f.label]})]}),e.jsxs("div",{className:W("ws-status",`ws-${a}`),title:`WebSocket: ${a}`,children:[e.jsx("span",{className:"ws-dot"}),e.jsx("span",{className:"ws-label",children:a})]})]})]}),d&&e.jsxs("nav",{className:"tabs-row",role:"tablist","aria-label":"Primary tabs",children:[Ut.map(b=>{const k=b.icon,w=b.id===s;return e.jsxs("button",{type:"button",role:"tab","aria-selected":w,className:W("tab",w&&"tab-active"),onClick:()=>t(b.id),title:b.label,children:[e.jsx(k,{size:14,className:"tab-icon"}),e.jsx("span",{className:"tab-label",children:b.label}),b.id==="settings"&&w&&e.jsx("span",{className:"settings-mode-indicator",title:"Settings mode active",children:e.jsx(En,{size:12})})]},b.id)}),p&&p.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"tab-separator","aria-hidden":"true"}),p.map(b=>{const k=b.icon,w=b.id===s;return e.jsxs("button",{type:"button",role:"tab","aria-selected":w,className:W("tab","tab-mod",w&&"tab-active"),onClick:()=>t(b.id),title:`${b.label} (mod)`,children:[e.jsx(k,{size:14,className:"tab-icon"}),e.jsx("span",{className:"tab-label",children:b.label}),e.jsx("span",{className:"tab-badge",children:"mod"})]},b.id)})]})]})]})}function Xi({activeProject:s,projects:t,onChange:a,onRefresh:n,settings:i}){const[l,o]=r.useState(!1),c=Pe();r.useEffect(()=>{if(!l)return;const x=()=>o(!1);return document.addEventListener("click",x),()=>document.removeEventListener("click",x)},[l]);const u=()=>{c.open({title:"Add project",children:e.jsx(Qi,{settings:i,onAdd:async(x,h)=>{try{await $.post("/projects",{path:x,name:h}),n(),o(!1),c.close()}catch(m){alert(`Add failed: ${m.message}`)}}}),footer:e.jsx("div",{className:"modal-footer-actions",children:e.jsx(M,{variant:"ghost",onClick:()=>c.close(),children:"Cancel"})})})};return e.jsxs("div",{className:"project-selector",onClick:x=>x.stopPropagation(),children:[e.jsxs("button",{type:"button",className:"project-selector-btn",onClick:()=>o(x=>!x),title:"Switch active project","aria-haspopup":"menu","aria-expanded":l,children:[e.jsx(Ge,{size:14}),e.jsx("span",{className:"project-selector-name",children:(s==null?void 0:s.name)||"(no project)"}),e.jsx(He,{size:12})]}),l&&e.jsxs("div",{className:"project-selector-menu",children:[e.jsxs("div",{className:"project-selector-menu-head",children:[e.jsxs("span",{className:"muted",children:[t.length," project",t.length===1?"":"s"]}),e.jsxs("div",{className:"project-selector-menu-actions",children:[e.jsx("button",{type:"button",className:"icon-btn",onClick:n,title:"Refresh","aria-label":"Refresh projects",children:e.jsx(me,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn",onClick:u,title:"Add project","aria-label":"Add project",children:e.jsx(Ee,{size:12})})]})]}),e.jsxs("ul",{className:"project-selector-list",children:[t.length===0&&e.jsx("li",{className:"muted project-selector-empty",children:"No projects. Add one to start."}),t.map(x=>e.jsx("li",{children:e.jsxs("button",{type:"button",className:W("project-selector-item",(s==null?void 0:s.id)===x.id&&"active"),onClick:()=>{a(x.id),o(!1)},children:[e.jsx("span",{className:"project-selector-item-name",children:x.name}),e.jsx("span",{className:"project-selector-item-status",children:x.status})]})},x.id))]})]})]})}function Qi({settings:s,onAdd:t}){var m,d;const[a,n]=r.useState(((m=s==null?void 0:s.dashboard)==null?void 0:m.projectsDirectory)??""),[i,l]=r.useState(""),[o,c]=r.useState(!1),[u,x]=r.useState(null),h=async()=>{var p;if(a){c(!0),x(null);try{await $.get("/fs?path="+encodeURIComponent(a)),t(a,i||null)}catch(f){const b=f;b.status===404?x("That folder no longer exists. Pick another."):x(((p=b.data)==null?void 0:p.message)??f.message??"Validation failed.")}finally{c(!1)}}};return e.jsxs("div",{children:[e.jsx("label",{className:"field-label",children:"Folder"}),e.jsx(Gi,{value:a,onChange:p=>{n(p),x(null)},projectsDirectory:(d=s==null?void 0:s.dashboard)==null?void 0:d.projectsDirectory,height:320}),u&&e.jsx("p",{className:"field-help",style:{color:"var(--error)",marginTop:4},children:u}),e.jsxs("div",{style:{marginTop:"var(--space-3)"},children:[e.jsx("label",{className:"field-label",htmlFor:"topbar-add-project-name",children:"Name (optional)"}),e.jsx("input",{id:"topbar-add-project-name",className:"input",type:"text",placeholder:"My App",value:i,onChange:p=>l(p.target.value)})]}),e.jsx("div",{style:{marginTop:"var(--space-3)",display:"flex",justifyContent:"flex-end"},children:e.jsxs(M,{variant:"primary",onClick:h,disabled:!a||o,children:[o?e.jsx("span",{className:"btn-spinner"}):null,o?"Checking…":"Add"]})})]})}const Ji=[{label:"General",sections:[{id:"theme",label:"Theme",icon:Pa},{id:"layout",label:"Layout",icon:Ln}]},{label:"Core",sections:[{id:"env-vars",label:"Env Vars",icon:Ts},{id:"network",label:"Network",icon:Dn},{id:"notifications",label:"Notifications",icon:Fa},{id:"auth",label:"Auth",icon:fs},{id:"system-llm",label:"System LLM",icon:dt}]},{label:"Agents",sections:[{id:"agents",label:"Agents",icon:Hs}]},{label:"Experience",sections:[{id:"updates",label:"Updates",icon:me},{id:"headroom",label:"Headroom",icon:_n}]},{label:"Data",sections:[{id:"activity-log",label:"Activity",icon:Ae},{id:"workspaces",label:"Workspaces",icon:Pn}]}];function Zi({activeSection:s,onSectionChange:t,onExitSettings:a}){return e.jsxs("div",{className:"settings-nav-root","aria-label":"Settings sections",children:[e.jsxs("button",{type:"button",className:"sidebar-tab",onClick:a,"aria-label":"Exit settings",children:[e.jsx(Ht,{size:14,"aria-hidden":!0}),e.jsx("span",{className:"sidebar-tab-label",children:"Back"})]}),e.jsx("div",{className:"settings-nav-divider","aria-hidden":"true"}),Ji.map(n=>e.jsxs("div",{className:"settings-nav-group",children:[e.jsx("div",{className:"settings-nav-group-label",children:n.label}),n.sections.map(i=>{const l=i.icon,o=s===i.id;return e.jsxs("button",{type:"button",className:W("sidebar-tab",o&&"sidebar-tab-active"),onClick:()=>t(o?null:i.id),"aria-current":o?"page":void 0,children:[l&&e.jsx(l,{size:14,"aria-hidden":!0}),e.jsx("span",{className:"sidebar-tab-label",children:i.label}),o&&e.jsx(ds,{size:12,"aria-hidden":!0})]},i.id)})]},n.label))]})}function er({tabs:s,activeTab:t,onTabChange:a,settingsMode:n,settingsActiveSection:i,onSettingsSectionChange:l,onExitSettings:o}){if(n)return e.jsx("aside",{className:"sidebar sidebar-settings-mode","aria-label":"Settings navigation",children:e.jsx(Zi,{activeSection:i??null,onSectionChange:l??(()=>{}),onExitSettings:o??(()=>{})})});const c=s.filter(x=>!x.isMod),u=s.filter(x=>x.isMod);return e.jsx("aside",{className:"sidebar","aria-label":"Primary navigation",children:e.jsxs("nav",{className:"sidebar-nav",role:"tablist",children:[c.map(x=>{const h=x.icon,m=x.id===t;return e.jsxs("button",{type:"button",role:"tab","aria-selected":m,className:W("sidebar-tab",m&&"sidebar-tab-active"),onClick:()=>a(x.id),title:x.label,children:[e.jsx(h,{size:18,"aria-hidden":!0}),e.jsx("span",{className:"sidebar-tab-label",children:x.label})]},x.id)}),u.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"sidebar-section-divider","aria-hidden":"true"}),e.jsx("div",{className:"sidebar-section-label",children:"Mods"}),u.map(x=>{const h=x.icon,m=x.id===t;return e.jsxs("button",{type:"button",role:"tab","aria-selected":m,className:W("sidebar-tab","sidebar-tab-mod",m&&"sidebar-tab-active"),onClick:()=>a(x.id),title:`${x.label} (mod)`,children:[e.jsx(h,{size:18,"aria-hidden":!0}),e.jsx("span",{className:"sidebar-tab-label",children:x.label})]},x.id)})]})]})})}const Ct=[{id:"all",label:"All"},{id:"projects",label:"Projects"},{id:"agents",label:"Agents"},{id:"tasks",label:"Tasks"},{id:"mods",label:"Mods"},{id:"schedules",label:"Schedules"},{id:"commands",label:"Commands"},{id:"settings",label:"Settings"}],ha={all:null,projects:"project",agents:"agent",tasks:"task",mods:"mod",schedules:"schedule",commands:"command",settings:"setting"};function sr({open:s,onClose:t,onSelect:a}){const n=ce(),[i,l]=r.useState(""),[o,c]=r.useState("all"),[u,x]=r.useState([]),[h,m]=r.useState(!1),[d,p]=r.useState(0),f=r.useRef(null),b=r.useRef(null);if(r.useEffect(()=>{let C;return s&&(b.current=document.activeElement instanceof HTMLElement?document.activeElement:null,l(""),x([]),p(0),C=window.setTimeout(()=>{var z;return(z=f.current)==null?void 0:z.focus()},30)),()=>{if(C&&window.clearTimeout(C),!s)return;const z=b.current;z&&z.isConnected&&z.focus()}},[s]),r.useEffect(()=>{if(!s)return;if(!i.trim()){x([]),p(0);return}let C=!1;m(!0);const z=setTimeout(()=>{$.get(`/search?q=${encodeURIComponent(i)}&scope=${o}`).then(y=>{C||(x(y.results||[]),p(0))}).catch(y=>{C||n.error(`Search failed: ${y.message}`)}).finally(()=>!C&&m(!1))},150);return()=>{C=!0,clearTimeout(z)}},[i,o,s,n]),!s)return null;const k={};for(const C of u){const z=C.type.toLowerCase();k[z]=k[z]||[],k[z].push(C)}const w=[];for(const C of Ct.map(z=>z.id)){const z=ha[C];z&&k[z]&&w.push(...k[z])}const v=C=>{if(C.key==="Escape")t();else if(C.key==="ArrowDown"){if(C.preventDefault(),w.length===0)return;p(z=>Math.min(z+1,w.length-1))}else if(C.key==="ArrowUp"){if(C.preventDefault(),w.length===0)return;p(z=>Math.max(z-1,0))}else C.key==="Enter"&&w[d]&&(C.preventDefault(),a(w[d]),t())};return e.jsx("div",{className:"search-modal-backdrop",onClick:t,children:e.jsxs("div",{className:"search-modal",role:"dialog","aria-modal":"true","aria-labelledby":"search-modal-title",onClick:C=>C.stopPropagation(),children:[e.jsxs("div",{className:"search-modal-head",role:"search",children:[e.jsx(ke,{size:14,"aria-hidden":!0}),e.jsx("span",{id:"search-modal-title",className:"sr-only",children:"Search"}),e.jsx("input",{ref:f,className:"search-modal-input",placeholder:"Search tasks, agents, settings, projects…",value:i,onChange:C=>l(C.target.value),onKeyDown:v,"aria-label":"Search"}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Close",onClick:t,children:e.jsx(we,{size:14})})]}),e.jsx("div",{className:"search-modal-scopes",role:"tablist","aria-label":"Search scope",children:Ct.map(C=>e.jsx("button",{type:"button",role:"tab","aria-selected":o===C.id,className:W("search-scope",o===C.id&&"search-scope-active"),onClick:()=>c(C.id),children:C.label},C.id))}),e.jsxs("div",{className:"search-modal-body",children:[h&&e.jsx("div",{className:"muted",children:"Searching…"}),!h&&i&&w.length===0&&e.jsx("div",{className:"muted",children:"No results."}),!h&&!i&&e.jsx("div",{className:"muted",children:"Type to search…"}),Ct.map(C=>{const z=ha[C.id];if(!z)return null;const y=k[z];return!y||y.length===0?null:e.jsxs("div",{className:"search-group",children:[e.jsx("div",{className:"search-group-head",children:C.label}),y.map(R=>{const S=w.indexOf(R);return e.jsxs("button",{type:"button",className:W("search-result",S===d&&"search-result-active"),onMouseEnter:()=>p(S),onClick:()=>{a(R),t()},children:[e.jsx("span",{className:"search-result-type",children:R.type}),e.jsx("span",{className:"search-result-label",children:tr(R)})]},`${R.type}-${S}`)})]},C.id)})]}),e.jsx("div",{className:"search-modal-foot",children:e.jsx("span",{className:"muted",children:"↑↓ navigate · ↵ open · esc close"})})]})})}function tr(s){const t=s.item||{};if(s.type==="project")return`${t.name} — ${t.path}`;if(s.type==="agent")return`${t.name} — ${t.description||t.model||""}`;if(s.type==="task")return`${t.title} — ${t.status||""}`;if(s.type==="mod")return`${t.name} v${t.version} — ${t.description||""}`;if(s.type==="schedule")return`${t.name} (${t.type}: ${t.schedule})`;if(s.type==="command")return`${t.name} — ${t.description||""}`;if(s.type==="setting"){const a=t.value===null||t.value===void 0?"":typeof t.value=="string"?` = ${t.value}`:` = ${JSON.stringify(t.value)}`;return`${t.label}${a} — ${t.desc||""}`.trim()}return JSON.stringify(t).slice(0,80)}const ar={info:Jt,success:_e,warning:Me,error:Kt};function nr({onCountChange:s,wsSubscribe:t}){const a=ce(),[n,i]=r.useState(!1),[l,o]=r.useState([]),[c,u]=r.useState(null),[x,h]=r.useState(!1),m=r.useRef(null),d=r.useRef(0),p=async()=>{var v;try{h(!0);const C=await $.get("/notifications?limit=200");o(C.notifications||[]),u(C.stats||null),d.current=((v=C.stats)==null?void 0:v.unread)||0,s==null||s(d.current)}catch(C){is.warn("[notifications] reload failed:",C.message)}finally{h(!1)}};r.useEffect(()=>{p()},[]),r.useEffect(()=>t?t(C=>{if(C.type==="notification:new"){const z=C.notification;o(y=>[z,...y.filter(R=>R.id!==z.id)]),z.read||(d.current+=1,u(y=>y?{...y,unread:(y.unread||0)+1}:{total:1,unread:1,lastTs:z.ts,counts:{[z.severity||"info"]:1}}),s==null||s(d.current))}else C.type==="notifications:change"&&p()}):void 0,[t]),r.useEffect(()=>{if(!n)return;const v=z=>{m.current&&(m.current.contains(z.target)||i(!1))},C=z=>{z.key==="Escape"&&i(!1)};return document.addEventListener("mousedown",v),document.addEventListener("keydown",C),()=>{document.removeEventListener("mousedown",v),document.removeEventListener("keydown",C)}},[n]);const f=async()=>{try{await $.post("/notifications/read-all",{}),o(v=>v.map(C=>({...C,read:!0}))),u(v=>v&&{...v,unread:0}),d.current=0,s==null||s(0),a.success("All notifications marked as read.",1500)}catch(v){a.error(`Failed: ${v.message}`)}},b=async v=>{try{await $.post(`/notifications/${encodeURIComponent(v)}/read`,{}),o(C=>C.map(z=>z.id===v?{...z,read:!0}:z)),u(C=>C&&{...C,unread:Math.max(0,(C.unread||1)-1)}),d.current=Math.max(0,d.current-1),s==null||s(d.current)}catch(C){a.error(`Failed: ${C.message}`)}},k=async v=>{try{await $.del(`/notifications/${encodeURIComponent(v)}`),o(C=>{const z=C.find(y=>y.id===v);return z&&!z.read&&(d.current=Math.max(0,d.current-1),u(y=>y&&{...y,unread:Math.max(0,y.unread-1)}),s==null||s(d.current)),C.filter(y=>y.id!==v)})}catch(C){a.error(`Failed: ${C.message}`)}},w=(c==null?void 0:c.unread)||0;return e.jsxs("div",{className:"notifications-root",ref:m,children:[e.jsxs("button",{type:"button",className:W("topbar-icon-btn notifications-bell",n&&"is-open"),onClick:()=>i(v=>!v),title:"Notifications","aria-label":"Notifications","aria-haspopup":"true","aria-expanded":n,children:[e.jsx(Fa,{size:16}),w>0&&e.jsx("span",{className:"notifications-badge",children:w>99?"99+":w})]}),n&&e.jsxs("div",{className:"notifications-panel",role:"dialog","aria-label":"Notifications",children:[e.jsxs("header",{className:"notifications-panel-head",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Notifications"}),w>0&&e.jsxs("span",{className:"muted text-sm",children:[" · ",w," unread"]})]}),e.jsxs("div",{className:"notifications-panel-head-actions",children:[e.jsxs(M,{size:"sm",variant:"ghost",onClick:f,disabled:w===0,children:[e.jsx(cs,{size:12})," Mark all read"]}),e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>i(!1),"aria-label":"Close",title:"Close",children:e.jsx(we,{size:14})})]})]}),e.jsx("div",{className:"notifications-list",children:x&&l.length===0?e.jsx("div",{className:"notifications-empty muted",children:"Loading…"}):l.length===0?e.jsx("div",{className:"notifications-empty muted",children:"No notifications yet."}):l.map(v=>{const C=ar[v.severity]||Jt;return e.jsxs("div",{className:W("notification-item",!v.read&&"is-unread",`severity-${v.severity}`),children:[e.jsx(C,{size:14,className:`notification-icon severity-${v.severity}`}),e.jsxs("div",{className:"notification-body",children:[v.title&&e.jsx("div",{className:"notification-title",children:v.title}),e.jsx("div",{className:"notification-msg",children:v.message}),e.jsxs("div",{className:"notification-meta muted",children:[e.jsx("span",{className:"mono",children:v.source}),e.jsx("span",{children:"·"}),e.jsx("span",{children:Te(v.ts)})]})]}),e.jsxs("div",{className:"notification-actions",children:[!v.read&&e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>b(v.id),title:"Mark as read","aria-label":"Mark as read",children:e.jsx(cs,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger",onClick:()=>k(v.id),title:"Remove","aria-label":"Remove",children:e.jsx(we,{size:12})})]})]},v.id)})}),e.jsx("footer",{className:"notifications-panel-foot",children:e.jsx("span",{className:"muted text-sm",children:c?`${c.total} total · last ${Te(c.lastTs||new Date().toISOString())}`:""})})]})]})}function ir({data:s,onClose:t}){const a=s==null?void 0:s.enabled;s==null||s.previousEnabled;const n=s==null?void 0:s.mode,i=s==null?void 0:s.defaultTemplate,l=s==null?void 0:s.lastUsedSlug,o=n==="toggle";return e.jsxs("div",{children:[o?e.jsxs("p",{style:{marginBottom:16,lineHeight:1.6},children:["Visual plan mode has been ",e.jsx("strong",{children:a?"enabled":"disabled"}),".",a?" The agent will create a plan and wait for your feedback on complex tasks.":" The agent will work without a visual plan canvas."]}):e.jsxs("div",{style:{marginBottom:16},children:[e.jsxs("p",{style:{marginBottom:8,fontWeight:600},children:["Visual Plan: ",e.jsx("span",{style:{color:a?"var(--color-success)":"var(--color-muted)"},children:a?"ON":"OFF"})]}),e.jsx("p",{style:{lineHeight:1.6,color:"var(--color-muted)",fontSize:13},children:"When enabled, the agent creates a visual plan and waits for your feedback before proceeding with complex tasks."}),i&&e.jsxs("p",{style:{marginTop:8,fontSize:13,color:"var(--color-muted)"},children:["Default template: ",e.jsx("code",{children:i})]}),l&&e.jsxs("p",{style:{fontSize:13,color:"var(--color-muted)"},children:["Last used plan: ",e.jsx("code",{children:l})]}),e.jsxs("p",{style:{marginTop:12,fontSize:13,color:"var(--color-muted)"},children:["Use ",e.jsx("code",{children:"/visual-plan on"})," or ",e.jsx("code",{children:"/visual-plan off"})," to toggle."]})]}),e.jsx("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:e.jsx(M,{variant:"ghost",onClick:t,children:"Close"})})]})}const rr=["blank","feature-design","bug-investigation","decision-record","horizontal","vertical"];function lr({data:s,onClose:t}){const a=(s==null?void 0:s.templates)??rr,n=(s==null?void 0:s.defaultTemplate)??"blank",[i,l]=r.useState(""),[o,c]=r.useState(n),[u,x]=r.useState(!1),[h,m]=r.useState(null),d=async()=>{if(!i.trim()){m("Slug is required.");return}if(!/^[a-z0-9][a-z0-9-]{0,63}$/.test(i)){m("Invalid slug. Use lowercase letters, numbers, and hyphens. Must start with an alphanumeric character.");return}x(!0),m(null);try{await $.post("/artifacts",{slug:i,template:o}),t()}catch(p){m(p.message),x(!1)}};return e.jsxs("div",{children:[e.jsxs("p",{style:{marginBottom:16,color:"var(--color-muted)",fontSize:13},children:["Create a new visual plan. Plans are stored in ",e.jsx("code",{children:"artifacts/"})," in your worktree."]}),e.jsxs("div",{style:{marginBottom:12},children:[e.jsx("label",{className:"field-label",htmlFor:"plan-slug",children:"Plan slug"}),e.jsx("input",{id:"plan-slug",className:"input",type:"text",placeholder:"e.g. my-feature",value:i,onChange:p=>{l(p.target.value),m(null)},autoFocus:!0})]}),e.jsxs("div",{style:{marginBottom:16},children:[e.jsx("label",{className:"field-label",htmlFor:"plan-template",children:"Template"}),e.jsx("select",{id:"plan-template",className:"select",value:o,onChange:p=>c(p.target.value),children:a.map(p=>e.jsx("option",{value:p,children:p},p))})]}),h&&e.jsx("p",{style:{marginBottom:12,color:"var(--color-danger)",fontSize:13},children:h}),e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx(M,{variant:"ghost",onClick:t,disabled:u,children:"Cancel"}),e.jsx(M,{variant:"primary",onClick:d,disabled:u||!i.trim(),children:u?"Creating…":"Create"})]})]})}function cr({data:s,onClose:t}){const a=(s==null?void 0:s.plans)??[],n=(s==null?void 0:s.count)??a.length,i=l=>{window.open(`/artifacts/${l}/`,"_blank")};return e.jsxs("div",{children:[a.length===0?e.jsxs("p",{style:{marginBottom:16,color:"var(--color-muted)"},children:["No plans found in this worktree. Use ",e.jsx("code",{children:"/artifact new <slug>"})," to create one."]}):e.jsxs("div",{style:{marginBottom:16},children:[e.jsxs("p",{style:{marginBottom:12,fontSize:13,color:"var(--color-muted)"},children:[n," plan",n!==1?"s":""," in this worktree:"]}),e.jsx("ul",{style:{listStyle:"none",padding:0,margin:0},children:a.map(l=>e.jsxs("li",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"6px 0",borderBottom:"1px solid var(--color-border)"},children:[e.jsx("code",{style:{fontSize:13},children:l}),e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>i(l),children:"Open"})]},l))})]}),e.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:e.jsx(M,{variant:"ghost",onClick:t,children:"Close"})})]})}function or({data:s,onClose:t}){const a=(s==null?void 0:s.commands)??[],n=(s==null?void 0:s.templates)??[],i=(s==null?void 0:s.statuses)??[];return e.jsxs("div",{children:[a.length>0?e.jsx("table",{style:{width:"100%",borderCollapse:"collapse",marginBottom:16,fontSize:13},children:e.jsx("tbody",{children:a.map(l=>e.jsxs("tr",{style:{borderBottom:"1px solid var(--color-border)"},children:[e.jsx("td",{style:{padding:"5px 8px 5px 0",whiteSpace:"nowrap"},children:e.jsx("code",{style:{fontSize:12},children:l.cmd})}),e.jsx("td",{style:{padding:"5px 0",color:"var(--color-muted)"},children:l.desc})]},l.cmd))})}):e.jsx("p",{style:{marginBottom:16,color:"var(--color-muted)"},children:"No commands available."}),n.length>0&&e.jsxs("div",{style:{marginBottom:12},children:[e.jsx("p",{style:{fontSize:12,color:"var(--color-muted)",marginBottom:4},children:"Available templates:"}),e.jsx("p",{style:{fontSize:13},children:n.join(", ")})]}),i.length>0&&e.jsxs("div",{style:{marginBottom:12},children:[e.jsx("p",{style:{fontSize:12,color:"var(--color-muted)",marginBottom:4},children:"Available statuses:"}),e.jsx("p",{style:{fontSize:13},children:i.join(", ")})]}),e.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:e.jsx(M,{variant:"ghost",onClick:t,children:"Close"})})]})}function dr({data:s,onClose:t}){const[a,n]=r.useState(!1),[i,l]=r.useState(null),o=async()=>{n(!0),l(null);try{const c=await $.post("/chat/audit",{});l(c)}catch(c){l({ok:!1,findings:[],error:c.message})}finally{n(!1)}};return e.jsx("div",{children:i===null?e.jsxs(e.Fragment,{children:[e.jsx("p",{style:{marginBottom:16,lineHeight:1.6},children:"Run a security audit of your Bizar agent configuration. The audit checks for common misconfigurations, exposed secrets, and insecure defaults."}),e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx(M,{variant:"ghost",onClick:t,children:"Cancel"}),e.jsx(M,{variant:"primary",onClick:o,disabled:a,children:a?"Running…":"Run Audit"})]})]}):e.jsxs(e.Fragment,{children:[i.ok?e.jsxs("div",{children:[e.jsx("p",{style:{marginBottom:12,fontWeight:600,color:"var(--color-success)"},children:"Audit passed — no issues found."}),i.findings.length>0&&e.jsx("ul",{style:{marginBottom:16,paddingLeft:20},children:i.findings.map((c,u)=>e.jsx("li",{style:{marginBottom:4,fontSize:13},children:c},u))})]}):e.jsxs("p",{style:{marginBottom:16,color:"var(--color-danger)"},children:["Audit failed: ",i.error??"unknown error"]}),e.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:e.jsx(M,{variant:"ghost",onClick:t,children:"Close"})})]})})}function mr({dialog:s,onClose:t}){if(!s.data)return e.jsxs("div",{children:[e.jsx("p",{style:{marginBottom:16,lineHeight:1.6},children:`Command: ${s.command}`}),e.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:e.jsx("button",{type:"button",className:"btn",onClick:t,children:"Close"})})]});const{message:a,detail:n,url:i}=s.data;return e.jsxs("div",{children:[e.jsx("p",{style:{marginBottom:16,lineHeight:1.6},children:a??`Command: ${s.command}`}),n&&e.jsx("p",{style:{marginBottom:16,color:"var(--color-muted)",fontSize:13},children:n}),i&&e.jsx("p",{style:{marginBottom:16},children:e.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",children:i})}),e.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:e.jsx("button",{type:"button",className:"btn",onClick:t,children:"Close"})})]})}function ur({dialog:s,onClose:t}){switch(s.component){case"visual-artifact":return e.jsx(ir,{data:s.data,onClose:t});case"artifact-create":return e.jsx(lr,{data:s.data,onClose:t});case"artifact-list":return e.jsx(cr,{data:s.data,onClose:t});case"help":return e.jsx(or,{data:s.data,onClose:t});case"audit":return e.jsx(dr,{data:s.data,onClose:t});default:return e.jsx(mr,{dialog:s,onClose:t})}}r.createContext(null);function Se({as:s="div",p:t,px:a,py:n,m:i,mx:l,my:o,bg:c,border:u,rounded:x,shadow:h,display:m,position:d,className:p,children:f,...b}){return r.createElement(s,{...b,className:oe("box",t!==void 0&&`box-p-${t}`,a!==void 0&&`box-px-${a}`,n!==void 0&&`box-py-${n}`,i!==void 0&&`box-m-${i}`,l!==void 0&&`box-mx-${l}`,o!==void 0&&`box-my-${o}`,c&&`box-bg-${c}`,u&&`box-border-${u}`,x&&`box-rounded-${x}`,h&&`box-shadow-${h}`,m&&`box-d-${m}`,d&&`box-pos-${d}`,p)},f)}function Be({direction:s="column",gap:t=3,align:a,justify:n,wrap:i,as:l="div",className:o,children:c,...u}){return r.createElement(l,{...u,className:oe("stack",s==="row"&&"stack-row",`gap-${t}`,a&&`align-${a}`,n&&`justify-${n}`,i===!0&&"wrap",o)},c)}function $e({direction:s="row",gap:t=3,align:a,justify:n,wrap:i=!0,as:l="div",className:o,children:c,...u}){return r.createElement(l,{...u,className:oe("inline",s==="column"&&"inline-col",`gap-${t}`,a&&`align-${a}`,n&&`justify-${n}`,i?"wrap":"nowrap",o)},c)}function Vt({cols:s=1,gap:t=3,autoFit:a=!1,className:n,children:i,style:l,...o}){return e.jsx("div",{...o,className:oe("grid",!a&&`cols-${s}`,a&&"grid-autofit",`gap-${t}`,n),style:l,children:i})}const Ue=r.forwardRef(function({variant:t="secondary",size:a="md",loading:n=!1,fullWidth:i=!1,icon:l,iconRight:o,disabled:c,className:u,children:x,type:h="button",...m},d){return e.jsxs("button",{ref:d,type:h,disabled:c||n,"aria-busy":n||void 0,className:oe("btn",`btn-${t}`,`btn-size-${a}`,n&&"btn-loading",i&&"btn-full",u),...m,children:[n&&e.jsx("span",{className:"btn-spinner","aria-hidden":!0}),l,x,o]})}),zs=r.forwardRef(function({variant:t="secondary",size:a="md",icon:n,disabled:i,className:l,type:o="button",...c},u){return e.jsx("button",{ref:u,type:o,disabled:i,className:oe("icon-btn",`icon-btn-${t}`,`icon-btn-size-${a}`,l),...c,children:n})});r.forwardRef(function({checked:t,onChange:a,label:n,disabled:i,size:l="md",name:o,autoFocus:c,className:u,...x},h){return e.jsxs("label",{...x,className:oe("toggle",l==="sm"&&"toggle-sm",t&&"toggle-checked",u),children:[e.jsx("input",{ref:h,type:"checkbox",role:"switch",name:o,checked:t,disabled:i,autoFocus:c,onChange:m=>a(m.target.checked),className:"toggle-input"}),e.jsx("span",{className:"toggle-track","aria-hidden":!0,children:e.jsx("span",{className:"toggle-thumb"})}),n!==void 0&&e.jsx("span",{className:"toggle-label",children:n})]})});r.forwardRef(function({inputSize:t="md",error:a,leftIcon:n,rightIcon:i,disabled:l,className:o,...c},u){return e.jsxs("span",{className:oe("field",`field-size-${t}`,n&&"field-has-left",i&&"field-has-right",o),children:[n&&e.jsx("span",{className:"field-icon-left",children:n}),e.jsx("input",{ref:u,type:"text",disabled:l,"aria-invalid":a?!0:void 0,className:oe("field-input",a&&"field-error"),...c}),i&&e.jsx("span",{className:"field-icon-right",children:i})]})});const hr=r.forwardRef(function({inputSize:t="md",error:a,hint:n,disabled:i,className:l,rows:o=4,...c},u){return e.jsxs("span",{className:oe("field","field-textarea",`field-size-${t}`,l),children:[e.jsx("textarea",{ref:u,rows:o,disabled:i,"aria-invalid":a?!0:void 0,className:oe("field-input","field-input-textarea",a&&"field-error"),...c}),n&&e.jsx("span",{className:"field-hint",children:n})]})});r.forwardRef(function({inputSize:t="md",error:a,value:n,onChange:i,min:l,max:o,step:c,disabled:u,className:x,...h},m){return e.jsx("span",{className:oe("field",`field-size-${t}`,x),children:e.jsx("input",{ref:m,type:"number",disabled:u,value:n,min:l,max:o,step:c,"aria-invalid":a?!0:void 0,className:oe("field-input",a&&"field-error"),onChange:d=>{const p=d.target.value;if(p===""){i("");return}const f=Number(p);i(Number.isFinite(f)?f:p)},...h})})});const xr=r.forwardRef(function({inputSize:t="md",options:a,placeholder:n,error:i,value:l,defaultValue:o,disabled:c,name:u,required:x,onChange:h,className:m,...d},p){return e.jsxs("span",{...d,className:oe("select",`select-size-${t}`,m),children:[e.jsxs("select",{ref:p,disabled:c,name:u,required:x,value:l,defaultValue:o??(n!==void 0?"":void 0),onChange:h,"aria-invalid":i?!0:void 0,className:oe("select-native",i&&"select-error"),children:[n!==void 0&&e.jsx("option",{value:"",disabled:!0,children:n}),a.map(f=>e.jsx("option",{value:f.value,disabled:f.disabled,children:f.label},f.value))]}),e.jsx(He,{className:"select-caret",size:14,"aria-hidden":!0})]})});r.forwardRef(function({checked:t,onChange:a,label:n,indeterminate:i=!1,disabled:l,name:o,autoFocus:c,required:u,className:x,...h},m){const d=r.useRef(null);r.useEffect(()=>{d.current&&(d.current.indeterminate=i)},[i]);const p=f=>{d.current=f,typeof m=="function"?m(f):m&&(m.current=f)};return e.jsxs("label",{...h,className:oe("checkbox",t&&"checkbox-checked",i&&"checkbox-indeterminate",x),children:[e.jsx("input",{ref:p,type:"checkbox",name:o,checked:t,disabled:l,required:u,autoFocus:c,onChange:f=>a(f.target.checked),className:"checkbox-input"}),e.jsx("span",{className:"checkbox-box","aria-hidden":!0,children:i?e.jsx(Oa,{strokeWidth:3}):t?e.jsx(cs,{strokeWidth:3}):null}),n!==void 0&&e.jsx("span",{className:"checkbox-label",children:n})]})});r.forwardRef(function({name:t,value:a,onChange:n,options:i,orientation:l="vertical",legend:o,disabled:c,required:u,className:x,...h},m){return e.jsxs("div",{ref:m,role:"radiogroup",...h,className:oe("radio-group",l==="horizontal"&&"radio-group-horizontal",x),children:[o!==void 0&&e.jsx("p",{className:"radio-option-label",style:{marginBottom:4},children:o}),i.map(d=>{const p=d.value===a;return e.jsxs("label",{className:oe("radio-option",p&&"radio-option-checked"),children:[e.jsx("input",{type:"radio",name:t,value:d.value,checked:p,disabled:c||d.disabled,required:u,onChange:()=>n(d.value),className:"radio-option-input"}),e.jsx("span",{className:"radio-option-box","aria-hidden":!0,children:e.jsx("span",{className:"radio-option-dot"})}),e.jsxs("span",{className:"radio-option-content",children:[e.jsx("span",{className:"radio-option-label",children:d.label}),d.description!==void 0&&e.jsx("span",{className:"radio-option-desc",children:d.description})]})]},d.value)})]})});r.forwardRef(function({value:t,onChange:a,min:n=0,max:i=100,step:l=1,label:o,showValue:c=!1,disabled:u,className:x,...h},m){return e.jsxs("div",{className:oe("slider",x),children:[(o!==void 0||c)&&e.jsxs("div",{className:"slider-header",children:[o!==void 0&&e.jsx("span",{className:"slider-label",children:o}),c&&e.jsx("span",{className:"slider-value",children:String(t)})]}),e.jsx("input",{ref:m,type:"range",min:n,max:i,step:l,value:t,disabled:u,onChange:d=>a(Number(d.target.value)),className:"slider-input",...h})]})});const pr=r.forwardRef(function({inputSize:t="md",value:a,onChange:n,onClear:i,placeholder:l="Search…",disabled:o,className:c,...u},x){const h=r.useCallback(()=>{n(""),i==null||i()},[n,i]),m=r.useCallback(d=>{n(d.target.value)},[n]);return e.jsxs("span",{className:oe("field",c),children:[e.jsx(ke,{size:14,className:"field-icon-left","aria-hidden":!0}),e.jsx("input",{ref:x,type:"search",value:a,onChange:m,placeholder:l,disabled:o,className:"field-input field-has-left",...u}),a!==""&&!o&&e.jsx("button",{type:"button",onClick:h,className:"field-clear","aria-label":"Clear search",tabIndex:-1,children:e.jsx(we,{size:12,"aria-hidden":!0})})]})});function Fs({label:s,value:t,unit:a,delta:n,icon:i,href:l,loading:o=!1,className:c,...u}){const x=l?"a":"div",h=l?{href:l,...u}:u;return e.jsxs(x,{...h,className:oe("bd-stat-tile",l&&"bd-stat-tile--clickable",c),children:[i&&e.jsx("div",{className:"bd-stat-tile__icon",children:i}),e.jsxs("div",{className:"bd-stat-tile__body",children:[e.jsx("div",{className:"bd-stat-tile__label",children:s}),e.jsx("div",{className:"bd-stat-tile__value-row",children:o?e.jsx("div",{className:"bd-stat-tile__skeleton","aria-hidden":"true"}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"bd-stat-tile__value",children:t}),a&&e.jsx("span",{className:"bd-stat-tile__unit",children:a})]})}),n&&!o&&e.jsxs("div",{className:oe("bd-stat-tile__delta",n.direction==="up"&&"bd-stat-tile__delta--up",n.direction==="down"&&"bd-stat-tile__delta--down"),"aria-label":`${n.direction==="up"?"up":"down"} ${n.value}`,children:[n.direction==="up"?e.jsx(Zs,{size:12,"aria-hidden":"true"}):e.jsx(vt,{size:12,"aria-hidden":"true"}),e.jsx("span",{children:n.value})]})]})]})}function gr(s,t,a,n){if(s.length===0)return{line:"",area:"",min:0,max:0};const i=Math.min(...s),l=Math.max(...s),o=l-i||1,c=a-n*2,u=t,x=s.length>1?u/(s.length-1):0,h=s.map((b,k)=>{const w=k*x,v=n+c-(b-i)/o*c;return[w,v]}),m=h.map(([b,k],w)=>`${w===0?"M":"L"}${b.toFixed(2)},${k.toFixed(2)}`).join(" "),d=h[h.length-1],p=h[0],f=`${m} L${d[0].toFixed(2)},${(a-n).toFixed(2)} L${p[0].toFixed(2)},${(a-n).toFixed(2)} Z`;return{line:m,area:f,min:i,max:l}}function xa({data:s,width:t=80,height:a=24,stroke:n="var(--chart-1)",fill:i="var(--accent-subtle)",ariaLabel:l,className:o}){const{line:u,area:x}=gr(s,t,a,2);return e.jsx("svg",{role:"img","aria-label":l??`Sparkline of ${s.length} values`,className:o,width:t,height:a,viewBox:`0 0 ${t} ${a}`,preserveAspectRatio:"none",children:s.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("path",{className:"bd-sparkline__fill",d:x,fill:i}),e.jsx("path",{className:"bd-sparkline__line",d:u,stroke:n})]})})}function fr({data:s,maxValue:t,showLabels:a=!0,className:n}){const i=t??Math.max(1,...s.map(l=>l.value));return e.jsx("div",{className:oe("bd-bar-chart",n),role:"list",children:s.map((l,o)=>{const c=Math.max(0,Math.min(100,l.value/i*100));return e.jsxs("div",{role:"listitem",className:"bd-bar-chart__row",children:[a&&e.jsxs("div",{className:"bd-bar-chart__header",children:[e.jsx("span",{className:"bd-bar-chart__label",children:l.label}),e.jsx("span",{className:"bd-bar-chart__value",children:l.value})]}),e.jsx("div",{className:"bd-bar-chart__track","aria-hidden":!a,children:e.jsx("div",{className:"bd-bar-chart__bar",style:{width:`${c}%`,background:l.color??"var(--chart-1)"}})})]},`${l.label}-${o}`)})})}function jr(s){return s==null?"":typeof s=="string"||typeof s=="number"?s:String(s)}function vr(s,t){return typeof s=="number"&&typeof t=="number"?s-t:String(s).localeCompare(String(t))}function br({columns:s,data:t,rowKey:a,onRowClick:n,sort:i,onSortChange:l,empty:o,loading:c=!1,compact:u=!1,className:x}){const[h,m]=r.useState(null),d=i??h,p=r.useMemo(()=>{if(!d)return t;const k=s.find(C=>C.key===d.key);if(!k)return t;const w=k.accessor??jr,v=[...t];return v.sort((C,z)=>{const y=vr(w(C),w(z));return d.direction==="asc"?y:-y}),v},[t,s,d]),f=k=>{const w=!d||d.key!==k?{key:k,direction:"asc"}:d.direction==="asc"?{key:k,direction:"desc"}:null;i===void 0&&m(w),l==null||l(w)},b=()=>{if(c){const k=s.length;return e.jsx(e.Fragment,{children:Array.from({length:3}).map((w,v)=>e.jsx("tr",{className:"bd-data-table__skeleton-row",children:Array.from({length:k}).map((C,z)=>e.jsx("td",{children:e.jsx("div",{className:"bd-data-table__skeleton"})},`skel-${v}-${z}`))},`skel-${v}`))})}return p.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:s.length,className:"bd-data-table__empty",children:o??"No data"})}):p.map(k=>e.jsx("tr",{className:oe(n&&"bd-data-table__row--clickable"),onClick:n?()=>n(k):void 0,children:s.map(w=>e.jsx("td",{className:oe("bd-data-table__td",w.align==="right"&&"bd-data-table__td--right",w.align==="center"&&"bd-data-table__td--center"),children:w.render?w.render(k):String(w.accessor?w.accessor(k):"")},w.key))},a(k)))};return e.jsx("div",{className:oe("bd-data-table",u&&"bd-data-table--compact",x),children:e.jsx("div",{className:"bd-data-table__scroll",children:e.jsxs("table",{className:"bd-data-table__table",children:[e.jsx("thead",{className:"bd-data-table__thead",children:e.jsx("tr",{className:"bd-data-table__tr",children:s.map(k=>{const w=(d==null?void 0:d.key)===k.key,v=k.width!==void 0?{width:k.width}:void 0;return e.jsxs("th",{style:v,className:oe("bd-data-table__th",k.align==="right"&&"bd-data-table__th--right",k.align==="center"&&"bd-data-table__th--center",k.sortable&&"bd-data-table__th--sortable",w&&"bd-data-table__th--sorted"),onClick:k.sortable?()=>f(k.key):void 0,"aria-sort":w?d.direction==="asc"?"ascending":"descending":void 0,children:[k.header,k.sortable&&e.jsx("span",{className:"bd-data-table__sort-icon",children:w?d.direction==="asc"?e.jsx(Zs,{size:12,"aria-hidden":"true"}):e.jsx(vt,{size:12,"aria-hidden":"true"}):e.jsx(Fn,{size:12,"aria-hidden":"true"})})]},k.key)})})}),e.jsx("tbody",{className:"bd-data-table__tbody",children:b()})]})})})}function yr({text:s}){const[t,a]=r.useState(!1),n=r.useRef(null);r.useEffect(()=>()=>{n.current&&clearTimeout(n.current)},[]);const i=r.useCallback(()=>{typeof navigator>"u"||!navigator.clipboard||navigator.clipboard.writeText(s).then(()=>{a(!0),n.current&&clearTimeout(n.current),n.current=setTimeout(()=>a(!1),1500)}).catch(()=>{})},[s]);return e.jsx("button",{type:"button",className:oe("bd-kv-list__copy",t&&"bd-kv-list__copy--done"),"aria-label":t?"Copied":"Copy to clipboard",onClick:i,children:t?e.jsx(cs,{size:12}):e.jsx(os,{size:12})})}function an({items:s,orientation:t="horizontal",className:a}){return e.jsx("dl",{className:oe("bd-kv-list",t==="horizontal"?"bd-kv-list--horizontal":"bd-kv-list--vertical",a),children:s.map(n=>e.jsxs("div",{className:"bd-kv-list__row",children:[e.jsx("dt",{className:"bd-kv-list__label",children:n.label}),e.jsxs("dd",{className:oe("bd-kv-list__value",n.mono&&"bd-kv-list__value--mono"),children:[e.jsx("span",{children:n.value}),n.copyable&&e.jsx(yr,{text:String(n.value)})]})]},n.key))})}function mt({title:s,description:t,icon:a,action:n,inline:i=!1,className:l}){return e.jsxs("div",{className:oe("bd-state",i&&"bd-state--inline",l),children:[a!==null&&e.jsx("div",{className:"bd-state__icon","aria-hidden":"true",children:a??e.jsx(On,{size:32})}),e.jsx("div",{className:"bd-state__title",children:s}),t&&e.jsx("div",{className:"bd-state__description",children:t}),n&&e.jsx("button",{type:"button",className:"bd-state__action bd-state__action--ghost",onClick:n.onClick,children:n.label})]})}function ia({label:s,rows:t=3,inline:a=!1,className:n}){return t>0?e.jsxs("div",{className:oe("bd-state",a&&"bd-state--inline",n),role:"status","aria-live":"polite","aria-label":s??"Loading",children:[e.jsx("div",{className:"bd-skeleton-row","aria-hidden":"true",children:Array.from({length:t}).map((i,l)=>e.jsx("div",{className:"bd-skeleton-row__bar"},l))}),s&&e.jsx("div",{className:"bd-state__label",children:s})]}):e.jsxs("div",{className:oe("bd-state",a&&"bd-state--inline",n),role:"status","aria-live":"polite","aria-label":s??"Loading",children:[e.jsx("div",{className:oe("bd-spinner",a&&"bd-spinner--inline"),"aria-hidden":"true"}),s&&e.jsx("div",{className:"bd-state__label",children:s})]})}function ts({title:s,description:t,actions:a,children:n,padding:i=4,variant:l="outlined",className:o}){const c=s!==void 0||t!==void 0||a!==void 0;return e.jsxs("section",{className:oe("bizar-panel",l==="filled"&&"bizar-panel--filled",o),children:[c&&e.jsxs("div",{className:"bizar-panel__header",children:[(s||t)&&e.jsxs("div",{className:"bizar-panel__header-text",children:[s&&e.jsx("h3",{className:"bizar-panel__title",children:s}),t&&e.jsx("p",{className:"bizar-panel__description",children:t})]}),a&&e.jsx("div",{className:"bizar-panel__actions",children:a})]}),e.jsx("div",{className:oe("bizar-panel__body",`bizar-panel__padding--${i}`),children:n})]})}r.createContext(null);function Xe({variant:s="neutral",size:t="md",children:a,className:n}){return e.jsx("span",{className:oe("bizar-badge",`bizar-badge--${s}`,`bizar-badge--${t}`,n),children:a})}function Qs({variant:s="neutral",size:t="md",pulse:a=!1,className:n,label:i}){return e.jsx("span",{className:oe("bizar-status-dot",`bizar-status-dot--${s}`,`bizar-status-dot--${t}`,a&&"bizar-status-dot--pulse",n),role:i?"status":"presentation","aria-label":i})}function Nr({setActiveTab:s,refreshKey:t=0}){var x;const[a,n]=r.useState(null),[i,l]=r.useState(!0),o=async()=>{l(!0);try{const[h,m,d]=await Promise.all([$.get("/memory/status").catch(()=>null),$.get("/memory/health").catch(()=>null),$.get("/memory/lightrag/stats").catch(()=>null)]);n({initialized:!!(h!=null&&h.initialized),mode:h==null?void 0:h.mode,projectId:h==null?void 0:h.projectId,vaultRoot:h==null?void 0:h.vaultRoot,branch:h==null?void 0:h.branch,gitClean:h==null?void 0:h.gitClean,noteCount:(h==null?void 0:h.noteCount)||0,healthScore:m==null?void 0:m.score,healthStatus:m==null?void 0:m.status,lightrag:d?{running:d.running,indexedApprox:d.indexedApprox}:void 0})}catch{n({initialized:!1})}finally{l(!1)}};r.useEffect(()=>{o()},[t]);const c=()=>s("memory"),u=(a==null?void 0:a.healthStatus)==="healthy"?"var(--success)":(a==null?void 0:a.healthStatus)==="degraded"?"var(--warning)":(a==null?void 0:a.healthStatus)==="unhealthy"?"var(--error)":"var(--text-dim)";return e.jsxs(G,{className:"memory-overview-card",children:[e.jsxs(ee,{children:[e.jsx(Je,{size:14})," Memory",e.jsxs(M,{variant:"ghost",size:"sm",style:{marginLeft:"auto"},onClick:c,children:["Open Memory ",e.jsx(Ls,{size:12})]}),e.jsx(M,{variant:"ghost",size:"sm",onClick:o,"aria-label":"Refresh",title:"Refresh",children:e.jsx(me,{size:12})})]}),e.jsx(te,{children:"LightRAG + Obsidian vault + git sync — opens the dedicated Memory tab."}),a!=null&&a.initialized?e.jsxs("div",{className:"memory-status-card-grid",children:[e.jsxs("div",{className:"memory-status-card-cell",children:[e.jsxs("div",{className:"memory-status-card-label",children:[e.jsx(Ae,{size:11})," Health"]}),e.jsx("div",{className:"memory-status-card-value",style:{color:u},children:a.healthScore!==void 0?`${a.healthScore}/100`:"—"}),e.jsx("div",{className:"memory-status-card-sub muted",children:a.healthStatus||"—"})]}),e.jsxs("div",{className:"memory-status-card-cell",children:[e.jsxs("div",{className:"memory-status-card-label",children:[e.jsx(Je,{size:11})," LightRAG"]}),e.jsx("div",{className:"memory-status-card-value",children:(x=a.lightrag)!=null&&x.running?"running":"stopped"}),e.jsx("div",{className:"memory-status-card-sub muted",children:a.lightrag?`${a.lightrag.indexedApprox} chunks`:"—"})]}),e.jsxs("div",{className:"memory-status-card-cell",children:[e.jsxs("div",{className:"memory-status-card-label",children:[e.jsx(Ie,{size:11})," Vault"]}),e.jsxs("div",{className:"memory-status-card-value",children:[a.noteCount," notes"]}),e.jsx("div",{className:"memory-status-card-sub muted ellipsis",title:a.vaultRoot||"",children:a.vaultRoot?a.vaultRoot.split("/").slice(-2).join("/"):"—"})]}),e.jsxs("div",{className:"memory-status-card-cell",children:[e.jsxs("div",{className:"memory-status-card-label",children:[e.jsx(Ze,{size:11})," Git"]}),e.jsx("div",{className:"memory-status-card-value",children:a.gitClean===null?a.mode==="local-only"?"local-only":"—":a.gitClean?"clean":"dirty"}),e.jsx("div",{className:"memory-status-card-sub muted",children:a.branch?`branch ${a.branch}`:as(a.branch||"")||"—"})]})]}):e.jsxs("div",{className:"muted",children:["Memory not initialised. Click ",e.jsx("strong",{children:"Open Memory"})," to set it up."]}),i&&!a&&e.jsx("div",{className:"muted text-sm",children:"Loading…"})]})}function kr({snapshot:s,settings:t,setActiveTab:a,refreshSnapshot:n}){var J,ne;const i=ce();Pe();const l=r.useRef(null),[o,c]=r.useState(s.overview??null),[u,x]=r.useState(!s.overview),[h,m]=r.useState(s.projects||[]),[d,p]=r.useState(((J=s.activeProject)==null?void 0:J.id)||null),[f,b]=r.useState(s.mods||[]),[k,w]=r.useState(!1),[v,C]=r.useState(((ne=s.overview)==null?void 0:ne.recentActivity)??[]),[z,y]=r.useState(new Set),[R,S]=r.useState(()=>typeof document>"u"?!0:document.documentElement.getAttribute("data-theme")!=="light");r.useEffect(()=>{typeof document>"u"||(R?document.documentElement.removeAttribute("data-theme"):document.documentElement.setAttribute("data-theme","light"))},[R]),r.useEffect(()=>{let I=!1;return(async()=>{try{const V=await $.get("/activity/hidden");I||y(new Set(V.hidden||[]))}catch{}})(),()=>{I=!0}},[]);const N=(I,V)=>{const ie=`${I.kind||""}|${I.ts||""}|${I.slug||I.title||""}|${V}`;let de=0;for(let O=0;O<ie.length;O++)de=(de<<5)-de+ie.charCodeAt(O)|0;return Math.abs(de).toString(16).padStart(8,"0").slice(0,16)},P=async I=>{const V=z,ie=new Set(V);ie.add(I),y(ie);try{await $.post("/activity/hide",{keys:[I]})}catch(de){y(V),i.error(`Hide failed: ${de.message}`)}},g=async()=>{if(!window.confirm("Hide every recent activity item from the overview? The full log stays in Settings → Activity Log."))return;const I=v.map((ie,de)=>N(ie,de)),V=new Set(z);I.forEach(ie=>V.add(ie)),y(V);try{await $.post("/activity/hide",{keys:I}),i.success(`Hidden ${I.length} item(s).`)}catch(ie){i.error(`Clear failed: ${ie.message}`)}},j=async()=>{y(new Set);try{await $.del("/activity/hide"),i.success("All hidden activity restored.")}catch(I){i.error(`Restore failed: ${I.message}`)}};r.useEffect(()=>{var I;s.overview&&(c(s.overview),C(s.overview.recentActivity??[]),x(!1)),m(s.projects||[]),p(((I=s.activeProject)==null?void 0:I.id)||null),b(s.mods||[])},[s.overview,s.projects,s.activeProject,s.mods]),r.useEffect(()=>{let I=null;try{const V=$.getToken(),ie=V?`/api/activity/stream?token=${encodeURIComponent(V)}`:"/api/activity/stream";I=new EventSource(ie),I.addEventListener("snapshot",de=>{try{const O=JSON.parse(de.data);C(Array.isArray(O.events)?O.events.slice(0,50):[])}catch{}}),I.addEventListener("activity",de=>{try{const O=JSON.parse(de.data);C(Q=>[O,...Q].slice(0,50))}catch{}})}catch{}return()=>{try{I==null||I.close()}catch{}}},[]);const T=async()=>{i.info("Refreshing…",1500),await n();try{const I=await $.get("/projects");m(I.projects||[]),p(I.active||null)}catch{}},F=async()=>{var I;try{const V=await $.post("/projects/auto-detect");m(V.projects||[]),p(V.active||null);const ie=(I=V.projects)==null?void 0:I.find(de=>de.id===V.active);i.success(ie?`Active: ${ie.name}`:"Projects refreshed."),await n()}catch(V){i.error(`Auto-detect failed: ${V.message}`)}},A=async I=>{try{await $.post(`/projects/${encodeURIComponent(I)}/activate`),p(I),i.success("Project activated."),await n()}catch(V){i.error(`Activate failed: ${V.message}`)}},U=r.useMemo(()=>{const I={};(s.tasks||[]).forEach(ie=>{I[ie.status]=(I[ie.status]||0)+1});const V={queued:"var(--chart-3)",doing:"var(--info)",done:"var(--chart-1)",blocked:"var(--warning)",archived:"var(--text-tertiary)"};return Object.entries(I).map(([ie,de])=>({label:ie,value:de,color:V[ie]??"var(--chart-2)"}))},[s.tasks]),Y=r.useMemo(()=>{const V=new Array(30).fill(0),ie=Date.now();(s.tasks||[]).forEach(O=>{const Q=Date.parse(O.createdAt||"");if(Number.isNaN(Q))return;const re=Math.floor((ie-Q)/(24*3600*1e3));re>=0&&re<30&&(V[29-re]+=1)});const de=V[V.length-1]||1;for(let O=0;O<29;O++)V[O]===0&&(V[O]=Math.max(1,Math.round(de*(.6+O/30*.4))));return V},[s.tasks]),B=r.useMemo(()=>{const V=new Array(30).fill(0),ie=Date.now();(s.tasks||[]).forEach(O=>{if(!O.assignee)return;const Q=Date.parse(O.updatedAt||O.createdAt||"");if(Number.isNaN(Q))return;const re=Math.floor((ie-Q)/(24*3600*1e3));re>=0&&re<30&&(V[29-re]+=1)});const de=V[V.length-1]||1;for(let O=0;O<29;O++)V[O]===0&&(V[O]=Math.max(1,Math.round(de*(.6+O/30*.4))));return V},[s.tasks]),K=r.useMemo(()=>(s.tasks||[]).filter(I=>!!I.assignee&&(I.status==="doing"||I.status==="queued")).length,[s.tasks]),D=(s.tasks||[]).length,_=r.useMemo(()=>s.activeProject?s.activeProject:d?h.find(I=>I.id===d)??null:h[0]??null,[s.activeProject,d,h]),ae=r.useMemo(()=>v.slice(0,30).map((I,V)=>({it:I,idx:V,key:N(I,V)})).filter(({key:I})=>!z.has(I)),[v,z]);return u||!o?e.jsx(Se,{as:"div",className:"view view-overview",bg:"0",p:7,children:e.jsx(Be,{direction:"row",align:"center",justify:"center",children:e.jsx(ia,{label:"Loading overview…"})})}):e.jsx(Se,{as:"div",className:"view view-overview",bg:"0",p:7,children:e.jsxs(Be,{gap:6,children:[e.jsxs($e,{justify:"between",align:"center",gap:3,wrap:!0,children:[e.jsxs(Be,{gap:1,children:[e.jsx("h1",{className:"overview-title",style:{fontSize:"var(--text-2xl)",fontWeight:"var(--weight-semibold)",margin:0},children:"Overview"}),e.jsx("span",{className:"overview-subtitle muted",style:{fontSize:"var(--text-sm)",color:"var(--text-secondary)"},children:_?`Active: ${_.name}`:"No active project — pick one below."})]}),e.jsxs($e,{gap:2,align:"center",wrap:!0,children:[h.length>0&&e.jsxs("span",{className:"select select-size-sm overview-project-select","aria-label":"Switch active project",children:[e.jsx("select",{className:"select-native",value:d??"",onChange:async I=>{const V=I.target.value;!V||V===d||await A(V)},"aria-label":"Switch active project","data-testid":"overview-project-select",children:h.map(I=>e.jsx("option",{value:I.id,children:I.name},I.id))}),e.jsx("svg",{className:"select-caret",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":!0,children:e.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),e.jsx(Ue,{variant:"secondary",size:"sm",onClick:T,icon:e.jsx(me,{size:12}),"data-testid":"overview-refresh",children:"Refresh"}),e.jsx(zs,{variant:"ghost",size:"md",onClick:()=>S(I=>!I),"aria-label":R?"Switch to light theme":"Switch to dark theme",icon:R?e.jsx(Ba,{size:14}):e.jsx(Ua,{size:14})})]})]}),e.jsxs(Vt,{cols:5,autoFit:!0,gap:3,style:{minHeight:"unset"},"data-testid":"overview-stat-row",children:[e.jsx(Fs,{label:"Agents",value:o.counts.agents,icon:e.jsx(Qe,{size:18}),href:"#","data-testid":"overview-stat-agents"}),e.jsx(Fs,{label:"Tasks",value:D,icon:e.jsx(ps,{size:18}),"data-testid":"overview-stat-tasks"}),e.jsx(Fs,{label:"Projects",value:h.length,icon:e.jsx(Ge,{size:18}),"data-testid":"overview-stat-projects"}),e.jsx(Fs,{label:"Mods",value:f.length,icon:e.jsx(Rs,{size:18}),"data-testid":"overview-stat-mods"}),e.jsx(Fs,{label:"Background",value:K,icon:e.jsx(pt,{size:18}),"data-testid":"overview-stat-background"})]}),e.jsxs(Vt,{cols:3,autoFit:!0,gap:3,children:[e.jsx(ts,{title:"Tasks · last 30 days",description:"Bucketed from snapshot.tasks createdAt",padding:3,"data-testid":"overview-panel-tasks-spark",children:e.jsx(Se,{p:3,children:e.jsxs(Be,{direction:"row",justify:"between",align:"end",gap:3,children:[e.jsx(xa,{data:Y,width:220,height:56,ariaLabel:"Tasks created per day, last 30"}),e.jsx(Se,{as:"div",className:"overview-spark-meta",style:{fontFamily:"var(--font-mono)",fontVariantNumeric:"tabular-nums",fontSize:"var(--text-2xl)",fontWeight:"var(--weight-semibold)",color:"var(--text-primary)"},children:D})]})})}),e.jsx(ts,{title:"Agent activity · 30d",description:"Distinct assignees touching tasks per day",padding:3,"data-testid":"overview-panel-agents-spark",children:e.jsx(Se,{p:3,children:e.jsxs(Be,{direction:"row",justify:"between",align:"end",gap:3,children:[e.jsx(xa,{data:B,width:220,height:56,stroke:"var(--chart-2)",fill:"var(--info-subtle)",ariaLabel:"Agent touches per day, last 30"}),e.jsx(Se,{as:"div",style:{fontFamily:"var(--font-mono)",fontVariantNumeric:"tabular-nums",fontSize:"var(--text-2xl)",fontWeight:"var(--weight-semibold)",color:"var(--text-primary)"},children:o.counts.agents})]})})}),e.jsx(ts,{title:"Tasks by status",description:"Live snapshot of the kanban buckets",padding:3,"data-testid":"overview-panel-tasks-by-status",children:e.jsx(Se,{as:"div",p:3,children:e.jsx(fr,{data:U})})}),e.jsx(ts,{title:"Memory",description:"Vault, LightRAG, git sync",padding:3,"data-testid":"overview-panel-memory",children:e.jsx(Se,{as:"div",p:3,children:e.jsx(Nr,{setActiveTab:a})})}),e.jsx(ts,{title:"Active project",description:_?`${_.path}`:"No active project selected",padding:3,"data-testid":"overview-panel-active-project",children:_?e.jsx(Se,{p:3,children:e.jsxs(Be,{gap:3,children:[e.jsx(an,{items:[{key:"pname",label:"Name",value:_.name,mono:!0},{key:"ppath",label:"Path",value:Mr(_.path,48),mono:!0,copyable:!0},{key:"pstatus",label:"Status",value:e.jsxs(Xe,{variant:_.status==="active"?"success":_.status==="error"?"danger":"neutral",children:[e.jsx(Qs,{variant:_.status==="active"?"success":_.status==="error"?"danger":"neutral",size:"sm",pulse:_.status==="active"}),_.status]})},{key:"pseen",label:"Last opened",value:_.lastAccessed&&Te(_.lastAccessed)||"—"}]}),e.jsxs($e,{gap:2,wrap:!0,children:[e.jsx(Ue,{variant:"primary",size:"sm",onClick:()=>a("tasks"),icon:e.jsx(ps,{size:12}),children:"Open tasks"}),e.jsx(Ue,{variant:"secondary",size:"sm",onClick:F,icon:e.jsx(Ge,{size:12}),children:"Auto-detect"})]})]})}):e.jsx(Se,{as:"div",p:3,children:e.jsx(mt,{title:"No active project",description:"Add one or auto-detect from the current directory.",inline:!0,icon:e.jsx(Ge,{size:20})})})}),e.jsx(ts,{title:"Recent mods",description:"Last few installed extensions",padding:3,"data-testid":"overview-panel-recent-mods",children:f.length===0?e.jsx(Se,{as:"div",p:3,children:e.jsx(mt,{title:"No mods installed",description:"Install from the Mods tab.",inline:!0,icon:e.jsx(Rs,{size:20})})}):e.jsx(Se,{p:2,children:e.jsx(Be,{gap:0,children:f.slice(0,6).map(I=>e.jsx(Se,{py:2,px:3,style:{borderTop:"1px solid var(--border-subtle)"},children:e.jsxs($e,{justify:"between",align:"center",gap:3,children:[e.jsxs(Be,{gap:0,style:{minWidth:0},children:[e.jsx("span",{style:{fontWeight:"var(--weight-medium)",fontSize:"var(--text-base)"},children:I.name}),e.jsxs("span",{className:"muted",style:{fontFamily:"var(--font-mono)",fontSize:"var(--text-xs)",color:"var(--text-tertiary)"},children:["v",I.version," · ",I.type]})]}),e.jsxs(Xe,{variant:I.enabled?"success":"neutral",size:"sm",children:[e.jsx(Qs,{variant:I.enabled?"success":"neutral",size:"sm"}),I.enabled?"on":"off"]})]})},I.id))})})})]}),e.jsxs(ts,{title:"Recent activity",description:`${ae.length} item${ae.length===1?"":"s"} · live via SSE`,actions:e.jsxs($e,{gap:2,align:"center",children:[z.size>0&&e.jsxs(Ue,{variant:"ghost",size:"sm",onClick:j,icon:e.jsx(As,{size:12}),"aria-label":`Restore ${z.size} hidden items`,children:["Restore (",z.size,")"]}),v.length>0&&e.jsx(Ue,{variant:"ghost",size:"sm",onClick:g,icon:e.jsx(Ot,{size:12}),"data-testid":"overview-hide-all","aria-label":"Hide all activity from overview",children:"Hide all"})]}),padding:0,"data-testid":"overview-panel-activity",children:[z.size>0&&e.jsxs(Se,{as:"div",p:3,style:{background:"var(--surface-2)",borderTop:"1px solid var(--border-subtle)",borderBottom:"1px solid var(--border-subtle)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:"var(--space-3)"},role:"status",children:[e.jsxs($e,{gap:2,align:"center",children:[e.jsx(Ot,{size:12}),e.jsxs("span",{style:{fontSize:"var(--text-sm)"},children:[z.size," item",z.size===1?"":"s"," ","hidden from the overview."]})]}),e.jsxs(Ue,{variant:"ghost",size:"sm",onClick:j,children:[e.jsx(As,{size:12})," Show them again"]})]}),ae.length===0?e.jsx(Se,{as:"div",p:5,children:e.jsx(mt,{title:"No activity yet",description:"Use the prompt below or invoke a Bizar command to start a feed.",inline:!0,icon:e.jsx(Ae,{size:20})})}):e.jsx(Be,{as:"ul",gap:0,role:"list","aria-live":"polite","aria-relevant":"additions","data-testid":"overview-activity-list",children:ae.map(({it:I,key:V})=>e.jsx(wr,{item:I,activityKey:V,onNavigate:a,onHide:P},V))})]}),e.jsx(ts,{title:"What do you want to do?",description:"Describe what you want — Odin will split it into tasks, delegate to background agents, and track progress in real time.",padding:4,actions:e.jsxs(Xe,{variant:"accent",size:"sm",children:[e.jsx(es,{size:12}),e.jsx("span",{style:{marginLeft:4},children:"Odin + 12 specialists"})]}),"data-testid":"overview-panel-prompts",children:e.jsx("form",{onSubmit:async I=>{var ie,de;I.preventDefault();const V=(((ie=l.current)==null?void 0:ie.value)||"").trim();if(V){w(!0);try{const O=await $.post("/tasks/submit",{title:V});i.success(`Odin split it into ${((de=O.subtasks)==null?void 0:de.length)||1} task(s)`),l.current&&(l.current.value=""),await n()}catch(O){i.error(`Failed: ${O.message}`)}finally{w(!1)}}},children:e.jsxs(Be,{gap:3,children:[e.jsx(hr,{ref:l,disabled:k,"aria-label":"Describe what you want Odin to do",rows:4,placeholder:"e.g. Implement user authentication with email + password, including registration, login, password reset, and integration tests. Use Bcrypt, JWT tokens, and the existing API style.","data-testid":"overview-prompt-input"}),e.jsxs($e,{justify:"between",align:"center",gap:3,wrap:!0,children:[e.jsx($e,{gap:2,wrap:!0,children:["Implement feature","Fix bug","Refactor","Investigate","Add tests","Document","Optimize","Deploy"].map(I=>e.jsx("button",{type:"button",className:"overview-quick-chip",onClick:()=>{l.current&&(l.current.value=I,l.current.focus())},children:I},I))}),e.jsx(Ue,{type:"submit",variant:"primary",size:"md",disabled:k,loading:k,icon:k?void 0:e.jsx(rs,{size:12}),"data-testid":"overview-submit",children:k?"Submitting…":"Submit to Odin"})]})]})})})]})})}function wr({item:s,activityKey:t,onNavigate:a,onHide:n}){const i=$r(s),l=Rr(s.kind||""),o=Cr(s.kind||"activity"),c=zr(s),u=Tr(s.kind||"");return e.jsxs("li",{className:`overview-activity-row overview-activity-row-${i}`,style:{borderTop:"1px solid var(--border-subtle)",display:"flex",alignItems:"center",gap:"var(--space-3)",paddingInline:"var(--space-4)",paddingBlock:"var(--space-3)"},children:[e.jsxs("button",{type:"button",onClick:()=>{u&&a(u)},className:"overview-activity-row__main",title:u?`Open ${u}`:o,style:{flex:1,display:"flex",alignItems:"center",gap:"var(--space-3)",textAlign:"left",background:"transparent",color:"inherit",padding:0},children:[e.jsx("span",{style:{color:i==="error"?"var(--danger)":i==="warning"?"var(--warning)":i==="success"?"var(--success)":"var(--accent)",display:"inline-flex",alignItems:"center",justifyContent:"center",width:22,height:22,flexShrink:0},children:e.jsx(l,{size:14})}),e.jsxs(Be,{gap:0,style:{minWidth:0,flex:1},children:[e.jsxs($e,{justify:"between",align:"center",gap:3,wrap:!0,children:[e.jsx("span",{style:{fontSize:"var(--text-sm)",fontWeight:"var(--weight-medium)"},children:o}),e.jsx("span",{style:{fontFamily:"var(--font-mono)",fontVariantNumeric:"tabular-nums",fontSize:"var(--text-xs)",color:"var(--text-tertiary)"},children:Ar(s.ts)})]}),e.jsx("span",{className:"muted",style:{fontSize:"var(--text-sm)",color:"var(--text-secondary)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block"},title:c,children:c})]})]}),e.jsx(zs,{variant:"ghost",size:"sm",onClick:()=>n(t),"aria-label":"Hide from overview",title:"Hide from overview (kept in Settings → Activity Log)",icon:e.jsx(we,{size:12})})]})}function Sr(s){return s&&s.charAt(0).toUpperCase()+s.slice(1)}function Cr(s){const t=s.trim().toLowerCase().replace(/[:_]/g,"."),[a,n="updated"]=t.split("."),i={settings:"Settings",task:"Task",tasks:"Task",agent:"Agent",agents:"Agent",plan:"Plan",plans:"Plan",bg:"Background job",background:"Background job",session:"Session",mod:"Mod",mods:"Mod",provider:"Provider",providers:"Provider"},l={create:"created",created:"created",add:"added",added:"added",update:"updated",updated:"updated",delegate:"delegated",delegated:"delegated",invoke:"invoked",invoked:"invoked",restart:"restarted",restarted:"restarted",delete:"deleted",deleted:"deleted",remove:"removed",removed:"removed",archive:"archived",archived:"archived",restore:"restored",restored:"restored",complete:"completed",completed:"completed",fail:"failed",failed:"failed",error:"errored",stuck:"marked stuck"},o=i[a]||Sr(a.replace(/-/g," ")),c=l[n]||n.replace(/-/g," ");return`${o} ${c}`.trim()}function at(s,t){for(const a of t){const n=s[a];if(typeof n=="string"&&n.trim())return n.trim()}return""}function zr(s){const t=at(s,["message","text","prompt","title","name"]);if(t)return t;const a=[],n=at(s,["slug"]),i=at(s,["agent","author"]),l=at(s,["status"]);return n&&a.push(`Plan ${n}`),i&&a.push(i),l&&a.push(l),a.length?a.join(" · "):"No additional details."}function $r(s){const t=(s.kind||"").toLowerCase(),a=(s.status||"").toLowerCase();return t.includes("error")||a==="error"||a==="failure"?"error":t.includes("warn")||a==="blocked"?"warning":t.includes("done")||t.includes("success")||a==="done"?"success":"info"}function Rr(s){const t=s.toLowerCase();return t==="task"?ps:t==="agent"?Qe:t==="plan"?xt:t.includes("bg")||t.includes("background")||t.includes("job")?Zt:t==="mod"?Rs:t==="skill"?es:t.includes("error")||t.includes("failure")?$s:t.includes("warn")?Me:Ae}function Tr(s){const t=s.toLowerCase();return t==="task"?"tasks":t==="agent"?"agents":t==="plan"?"artifacts":t.includes("bg")||t.includes("background")?"activity":t==="mod"?"mods":t==="skill"?"skills":null}function Ar(s){return Te(s)}function Mr(s,t){if(!s||s.length<=t)return s;const a=Math.floor((t-1)/2);return`${s.slice(0,a)}…${s.slice(-a)}`}const Ir=Ke.memo(kr);function Er({icon:s,title:t,message:a,action:n}){return e.jsxs("div",{className:"chat-empty-state",children:[s&&e.jsx("div",{className:"chat-empty-state-icon",children:s}),e.jsx("h2",{className:"chat-empty-state-title",children:t}),e.jsx("p",{className:"chat-empty-state-message",children:a}),n&&e.jsx("div",{className:"chat-empty-state-action",children:n})]})}function Lr({session:s,mode:t,anchor:a,renameDraft:n,setRenameDraft:i,onEdit:l,onDeleteRequest:o,onConfirmDelete:c,onConfirmRename:u,onClose:x}){const h=r.useRef(null),m=Math.round(a.rect.bottom+2),d=Math.max(8,Math.round(window.innerWidth-a.rect.right));r.useEffect(()=>{const f=w=>{const v=w.target;!h.current||!v||h.current.contains(v)||x()},b=w=>{w.key==="Escape"&&x()},k=window.setTimeout(()=>{document.addEventListener("mousedown",f),document.addEventListener("keydown",b)},0);return()=>{window.clearTimeout(k),document.removeEventListener("mousedown",f),document.removeEventListener("keydown",b)}},[x]),r.useEffect(()=>{if(t!=="rename")return;const f=window.setTimeout(()=>{var k;const b=(k=h.current)==null?void 0:k.querySelector("input.session-row-menu-input");b==null||b.focus(),b==null||b.select()},0);return()=>window.clearTimeout(f)},[t]);const p=e.jsxs("div",{ref:h,className:"session-row-menu",role:"menu","aria-label":`Options for ${s.title}`,style:{position:"fixed",top:m,right:d},onClick:f=>f.stopPropagation(),children:[t==="main"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",className:"session-row-menu-item",role:"menuitem",onClick:f=>{f.stopPropagation(),l()},children:[e.jsx(Bn,{size:13,"aria-hidden":!0}),e.jsx("span",{children:"Rename"}),e.jsx("kbd",{children:"R"})]}),e.jsxs("button",{type:"button",className:"session-row-menu-item session-row-menu-item-danger",role:"menuitem",onClick:f=>{f.stopPropagation(),o()},children:[e.jsx(Re,{size:13,"aria-hidden":!0}),e.jsx("span",{children:"Delete"}),e.jsx("kbd",{children:"⌫"})]})]}),t==="rename"&&e.jsxs("div",{className:"session-row-menu-inline",children:[e.jsx("div",{className:"session-row-menu-inline-label chat-mono",children:"Rename session"}),e.jsx("input",{type:"text",className:"session-row-menu-input",value:n,onChange:f=>i(f.target.value),onKeyDown:f=>{f.key==="Enter"?(f.preventDefault(),u()):f.key==="Escape"&&(f.preventDefault(),x())},onClick:f=>f.stopPropagation(),"aria-label":"New session name"}),e.jsxs("div",{className:"session-row-menu-inline-actions",children:[e.jsx("button",{type:"button",className:"btn btn-ghost",onClick:f=>{f.stopPropagation(),x()},children:"Cancel"}),e.jsx("button",{type:"button",className:"btn btn-primary",onClick:f=>{f.stopPropagation(),u()},children:"Save"})]})]}),t==="confirm-delete"&&e.jsxs("div",{className:"session-row-menu-inline",children:[e.jsx("div",{className:"session-row-menu-inline-label chat-mono",children:"Delete this session?"}),e.jsxs("div",{className:"session-row-menu-inline-message",children:['"',s.title,'" and its sub-agents will be removed.']}),e.jsxs("div",{className:"session-row-menu-inline-actions",children:[e.jsx("button",{type:"button",className:"btn btn-ghost",onClick:f=>{f.stopPropagation(),x()},children:"Cancel"}),e.jsx("button",{type:"button",className:"btn btn-danger",onClick:f=>{f.stopPropagation(),c()},children:"Delete"})]})]})]});return La.createPortal(p,document.body)}function Wt({node:s,depth:t=0,collapsible:a=!1,isLast:n=!0,open:i,onToggle:l}){var p;const[o,c]=r.useState(a),u=i!==void 0,x=u?i:o,h=f=>{u||c(f),l==null||l(f)},m=(((p=s.children)==null?void 0:p.length)??0)>0,d=e.jsxs(e.Fragment,{children:[a&&e.jsx("span",{className:`agent-node-chevron ${x?"open":""}`,"aria-hidden":!0,children:"›"}),e.jsx("span",{className:`agent-node-dot status-${s.status}`,"aria-hidden":!0}),e.jsx("span",{className:"agent-node-name",children:s.name}),s.role&&e.jsx("span",{className:"agent-node-role chat-mono",children:s.role}),e.jsx("span",{className:`agent-node-pill status-${s.status}`,children:s.status})]});return e.jsxs("div",{className:["agent-node",`depth-${t}`,`status-${s.status}`,x?"open":"closed",n?"last":""].filter(Boolean).join(" "),children:[a?e.jsx("button",{type:"button",className:`agent-node-head status-${s.status} collapsible`,onClick:f=>{f.stopPropagation(),h(!x)},"aria-expanded":x,children:d}):e.jsx("div",{className:`agent-node-head status-${s.status}`,children:d}),x&&e.jsxs(e.Fragment,{children:[s.summary&&e.jsx("div",{className:"agent-node-summary",children:s.summary}),m&&e.jsx("div",{className:"agent-node-children",children:s.children.map((f,b)=>e.jsx(Wt,{node:f,depth:t+1,collapsible:!1,isLast:b===s.children.length-1},f.id))})]})]})}function Dr(s){return s.tree!==void 0}function _r(s){const t=s.open??!0;if(Dr(s))return e.jsx("div",{className:`agent-tree variant-${s.variant??"full"}`,children:e.jsx(Wt,{node:s.tree.root,depth:0,open:t})});const a=s.children??[];return e.jsx("div",{className:`agent-tree variant-${s.variant} agent-tree-children-only`,children:e.jsx("div",{className:"agent-tree-children-body",children:a.map((n,i)=>e.jsx(r.Fragment,{children:e.jsx(Wt,{node:n,depth:0,collapsible:!1,open:t,isLast:i===a.length-1})},n.id))})})}function Pr({children:s,variant:t="rail",open:a=!0}){return a?e.jsx(_r,{variant:t,open:a,children:s}):null}const Fr=["Today","Yesterday","This week","Earlier"];function pa(s,t){return s.getFullYear()===t.getFullYear()&&s.getMonth()===t.getMonth()&&s.getDate()===t.getDate()}function Or(s,t){const a=s.getTime()-t.getTime();return Math.floor(a/(1e3*60*60*24))}function Br(s){const t=new Date,a=new Date(t);a.setDate(a.getDate()-1);const n=new Date(t);n.setDate(n.getDate()-7);const i={Today:[],Yesterday:[],"This week":[],Earlier:[]};for(const l of s){const o=new Date(Number(l.mtime)||Date.now());pa(o,t)?i.Today.push(l):pa(o,a)?i.Yesterday.push(l):Or(t,o)<7?i["This week"].push(l):i.Earlier.push(l)}return i}function Ur(s){return new Date(Number(s)||Date.now()).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1})}function Vr({state:s,agent:t}){return s==="streaming"?e.jsx("span",{className:"session-state session-state-streaming",title:`${t||"Odin"} is typing…`}):s==="awaiting"?e.jsx("span",{className:"session-state session-state-awaiting",title:"Awaiting your reply","aria-hidden":!0}):s==="idle"?e.jsx("span",{className:"session-state session-state-idle","aria-hidden":!0}):null}function Wr({sessions:s,clineSessions:t=[],activeSessionId:a,activeClineSessionId:n,activeProject:i,creating:l,onCreateSession:o,onSelectSession:c,onSelectClineSession:u,onRenameSession:x,onDeleteSession:h,groupBy:m}){var B;const d=r.useMemo(()=>[...s,...t],[s,t]),p=r.useMemo(()=>[...d].sort((K,D)=>Number(D.mtime??0)-Number(K.mtime??0)),[d]),f=r.useMemo(()=>m?m(p):Br(p),[m,p]),[b,k]=r.useState({}),w=K=>b[K]===!0,[v,C]=r.useState(null),[z,y]=r.useState("main"),[R,S]=r.useState(""),[N,P]=r.useState(null),g=r.useRef({}),j=(K,D="main")=>{const _=g.current[K];if(!_)return;const ae=D==="main"?_:_.querySelector(".chat-rail-item-menu-trigger")??_;if(P({id:K,rect:ae.getBoundingClientRect()}),C(K),y(D),D==="rename"){const J=[...s,...t].find(ne=>ne.id===K);S((J==null?void 0:J.title)??(J==null?void 0:J.id)??"")}},T=()=>{C(null),y("main"),S(""),P(null)},F=K=>{if(K.source==="cline"){u(K);return}c(K.id)},A=()=>{if(!N)return;const K=N.id,D=R.trim();if(!D){T();return}x==null||x(K,D),T()},U=()=>{N&&(h==null||h(N.id),T())},Y=m?Object.entries(f):Fr.filter(K=>{var D;return(D=f[K])==null?void 0:D.length}).map(K=>[K,f[K]]);return e.jsxs("aside",{className:"chat-rail",children:[e.jsx("div",{className:"chat-rail-head",children:e.jsxs("button",{type:"button",className:"chat-new-btn",onClick:o,disabled:l||!i,title:i?"Create new session":"Pick a project first","aria-label":"Create new session",children:[e.jsx(Ee,{size:14,"aria-hidden":!0}),e.jsx("span",{children:l?"Creating…":"New session"})]})}),p.length===0?e.jsx("div",{className:"chat-sessions-empty",children:e.jsx(Er,{icon:e.jsx(Ee,{size:20,"aria-hidden":!0}),title:i?"No sessions yet":"No project",message:i?"Create your first session to start chatting.":"Pick a project in Overview to scope chat sessions."})}):e.jsx("div",{className:"chat-rail-list",children:Y.map(([K,D])=>e.jsxs("div",{className:"chat-rail-group",children:[e.jsx("div",{className:"chat-rail-group-label",children:K}),D.map(_=>{var ie,de;const ae=_.source==="cline",J=ae?n===_.id:a===_.id,ne=_.tree,I=!!((ie=ne==null?void 0:ne.root)!=null&&ie.children&&ne.root.children.length>0),V=w(_.id);return e.jsxs(r.Fragment,{children:[e.jsxs("div",{ref:O=>{g.current[_.id]=O},role:"button",tabIndex:0,className:`chat-rail-item state-${_.state??"idle"}${J?" active":""}`,onClick:()=>F(_),onKeyDown:O=>{(O.key==="Enter"||O.key===" ")&&(O.preventDefault(),F(_))},"aria-current":J?"true":void 0,children:[e.jsx(Vr,{state:_.state??"idle",agent:_.agent}),e.jsxs("div",{className:"chat-rail-item-title",children:[_.pinned&&e.jsx("span",{className:"chat-rail-pin","aria-hidden":!0,children:"★"}),ae&&e.jsx(Ls,{size:11,style:{color:"var(--text-muted)",flexShrink:0},"aria-hidden":!0}),e.jsx("span",{className:"chat-ellipsis",children:_.title||_.id})]}),e.jsxs("div",{className:"chat-rail-item-meta",children:[e.jsx("span",{className:"chat-rail-item-meta-time",children:_.time??Ur(_.mtime)}),(_.unread??0)>0&&e.jsx("span",{className:"chat-rail-badge",children:_.unread})]}),e.jsx("button",{type:"button",className:`chat-rail-item-menu-trigger${v===_.id?" open":""}`,"aria-label":`Session options for ${_.title||_.id}`,"aria-haspopup":"menu","aria-expanded":v===_.id,onClick:O=>{O.stopPropagation(),v===_.id?T():j(_.id,"main")},children:e.jsxs("svg",{viewBox:"0 0 14 14","aria-hidden":!0,children:[e.jsx("circle",{cx:"3",cy:"7",r:"1.2",fill:"currentColor"}),e.jsx("circle",{cx:"7",cy:"7",r:"1.2",fill:"currentColor"}),e.jsx("circle",{cx:"11",cy:"7",r:"1.2",fill:"currentColor"})]})}),J&&I&&e.jsx("button",{type:"button",className:`chat-rail-tree-chevron${V?" open":""}`,"aria-label":V?"Collapse sub-agents":"Expand sub-agents","aria-expanded":V,onClick:O=>{O.stopPropagation(),k(Q=>({...Q,[_.id]:!Q[_.id]}))},children:e.jsx("svg",{viewBox:"0 0 10 10","aria-hidden":!0,children:e.jsx("polyline",{points:"3,1.5 7,5 3,8.5"})})})]}),J&&I&&V&&((de=ne==null?void 0:ne.root)==null?void 0:de.children)&&e.jsx(Pr,{children:ne.root.children,variant:"rail",open:!0})]},ae?`oc-${_.id}`:_.id)})]},K))}),v&&N&&e.jsx(Lr,{session:{id:N.id,title:((B=[...s,...t].find(K=>K.id===N.id))==null?void 0:B.title)??N.id},mode:z,anchor:N,renameDraft:R,setRenameDraft:S,onEdit:()=>j(v,"rename"),onDeleteRequest:()=>j(v,"confirm-delete"),onConfirmDelete:U,onConfirmRename:A,onClose:T})]})}function qr(s){const{text:t,sending:a,onSend:n,activeSource:i}=s,[l,o]=r.useState(!1),c=()=>{!t.trim()||a||(o(!0),n(),window.setTimeout(()=>o(!1),320))};return e.jsxs("div",{className:`chat-composer-wrap chat-composer-source-${i??"none"}`,children:[e.jsx("div",{className:`chat-composer-pill${l?" takeoff":""}`,children:e.jsx(Mi,{...s,onSend:c})}),e.jsxs("div",{className:"chat-composer-hint chat-muted",children:[e.jsxs("span",{children:[e.jsx("kbd",{children:"⏎"})," send"]}),e.jsxs("span",{children:[e.jsx("kbd",{children:"⇧⏎"})," newline"]}),e.jsxs("span",{children:[e.jsx("kbd",{children:"/"})," commands"]}),i==="cline"&&e.jsx("span",{className:"chat-composer-source-hint",children:"→ cline"}),i==="bizar"&&e.jsx("span",{className:"chat-composer-source-hint",children:"→ bizar chat"}),a&&e.jsx("span",{className:"chat-composer-source-hint",children:"sending…"})]})]})}function zt(s){return s.toLocaleString()}function Gr(s){return!s||!s.includes("/")?"":s.split("/")[0]}function Hr(s){if(!s)return 0;const t=s.toLowerCase();return t.includes("opus")?15:t.includes("sonnet")?3:t.includes("haiku")?.8:t.includes("gpt-4o")?5:t.includes("gpt-4")?10:t.includes("deepseek")?.27:t.includes("minimax")?.3:t.includes("llama-3.3-70b")?.59:1}function Kr({sessionId:s,messages:t,pinned:a,agent:n,model:i,agents:l,mcps:o,allCommands:c,activeSource:u="bizar",onRename:x,onDelete:h,onExport:m,busy:d,error:p,onRetry:f}){const[b,k]=r.useState(null);r.useEffect(()=>{let j=!1;return(async()=>{try{const T=await fetch("/api/usage?range=24h",{headers:{Accept:"application/json"}});if(!T.ok)return;const F=await T.json();j||k(F)}catch{}})(),()=>{j=!0}},[s]);const w=(t==null?void 0:t.length)??0,v=(a==null?void 0:a.size)??0,C=t.reduce((j,T)=>j+(T.content||T.message||"").length,0),z=Math.round(C/4),y=Hr(i),R=z/1e6*y,S=(b==null?void 0:b.totalTokens)??z,N=(b==null?void 0:b.costUsd)??R,P=128e3,g=Gr(i);return e.jsxs("aside",{className:"chat-info",children:[p&&e.jsxs("div",{className:"chat-info-section chat-info-error",role:"alert","aria-live":"polite",children:[e.jsxs("h4",{children:[e.jsx(Me,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Couldn't load session"]}),e.jsx("p",{className:"chat-info-value chat-ellipsis",title:p.message,children:p.message}),e.jsxs("div",{className:"chat-info-mono",children:["code · ",p.code]}),p.suggestion?e.jsx("p",{className:"chat-info-suggestion",children:p.suggestion}):null,p.canRetry!==!1&&f?e.jsxs("button",{type:"button",className:"btn btn-ghost btn-sm chat-info-retry",onClick:f,title:"Retry loading the session",children:[e.jsx(bt,{size:12,"aria-hidden":!0})," Retry"]}):null]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("div",{className:"chat-info-section-head",children:[e.jsxs("h4",{children:[e.jsx(Js,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Session"]}),e.jsx("span",{className:`chat-source-badge chat-source-${u??"none"}`,style:{marginLeft:"auto"},children:u==="cline"?"cline":"bizar chat"})]}),e.jsx("div",{className:"chat-info-mono chat-ellipsis",title:s,children:s||"Live"}),e.jsxs("div",{className:"chat-info-mono",children:[zt(w)," message",w===1?"":"s",v>0&&` · ${v} pinned`]})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("h4",{children:[e.jsx(Qe,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Agent"]}),e.jsx("div",{className:"chat-info-value",children:n||"—"})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("h4",{children:[e.jsx(Ms,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Model"]}),e.jsx("div",{className:"chat-mono chat-ellipsis",title:i,children:i||"—"}),g&&e.jsxs("div",{className:"chat-info-mono",children:["provider · ",g]})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsx("h4",{children:"Tokens"}),e.jsxs("div",{className:"chat-mono",children:[zt(S)," / ",zt(P)]}),e.jsx("div",{className:"chat-info-bar","aria-hidden":!0,children:e.jsx("div",{className:"chat-info-bar-fill",style:{width:`${Math.min(100,S/Math.max(1,P)*100)}%`}})})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("h4",{children:[e.jsx(Un,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Cost"]}),e.jsxs("div",{className:"chat-mono",children:["$",N.toFixed(4)]}),!b&&e.jsx("div",{className:"chat-info-mono",children:"approx · live from MiniMax"})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("h4",{children:[e.jsx(Qe,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Attached agents"]}),l!=null&&l.length?e.jsx("div",{className:"chat-info-agents",children:l.map(j=>e.jsx("span",{className:"chat-info-agent",children:j.name},j.name))}):e.jsx("div",{className:"chat-info-mono",children:"None attached"})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("h4",{children:[e.jsx(Ms,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","MCPs"]}),o!=null&&o.length?e.jsx("div",{className:"chat-info-agents",children:o.map(j=>e.jsx("span",{className:"chat-info-agent",children:j.id},j.id))}):e.jsx("div",{className:"chat-info-mono",children:"No MCPs configured"})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("h4",{children:[e.jsx(Ts,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Slash commands"]}),e.jsxs("div",{className:"chat-info-mono",children:[(c==null?void 0:c.length)??0," available"]})]}),(x||h||m)&&e.jsxs("div",{className:"chat-info-section",children:[e.jsx("h4",{children:"Actions"}),e.jsxs("div",{className:"chat-info-actions",children:[x&&e.jsxs("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:x,disabled:d==null?void 0:d.rename,title:"Rename session",children:[e.jsx(et,{size:12,"aria-hidden":!0})," Rename"]}),m&&e.jsxs("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:m,title:"Export transcript",children:[e.jsx(js,{size:12,"aria-hidden":!0})," Export"]}),h&&e.jsxs("button",{type:"button",className:"btn btn-ghost btn-sm btn-danger",onClick:h,disabled:d==null?void 0:d.delete,title:"Delete session",children:[e.jsx(Re,{size:12,"aria-hidden":!0})," Delete"]})]})]})]})}function Yr({streaming:s,newMessageCount:t,onClick:a,streamingLabel:n="Odin is replying"}){return e.jsx("button",{type:"button",className:`jump-to-latest${s?" is-streaming":""}`,onClick:a,"aria-label":"Jump to latest message",title:"Jump to latest (⌘/Ctrl+End)",children:s?e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"jump-dots","aria-hidden":!0,children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]}),e.jsx("span",{children:n}),t>0&&e.jsx("span",{className:"jump-badge jump-badge-live",children:"live"})]}):e.jsxs(e.Fragment,{children:[e.jsx(vt,{size:14,"aria-hidden":!0}),e.jsx("span",{children:"Jump to latest"}),t>0&&e.jsxs("span",{className:"jump-badge",children:[t," new"]})]})})}function Xr({snapshot:s,settings:t,setActiveTab:a,initialTaskId:n,onClearTaskId:i}){const l=ce(),o=Pe(),c=Ii(s,t,n??"");r.useEffect(()=>{c.setToast({error:B=>l.error(B),success:B=>l.success(B),info:B=>l.info(B),warning:B=>l.warning(B)})},[c,l]);const[u,x]=r.useState(""),[h,m]=r.useState(t.defaultAgent||"odin"),[d,p]=r.useState(t.defaultModel||""),[f,b]=r.useState([]),k=r.useRef(null),{allCommands:w,suggestions:v,setQuery:C}=Ei(s);r.useEffect(()=>{C(u)},[u,C]);const z=()=>{var B;return(B=k.current)==null?void 0:B.click()},y=B=>{const K=B.target.files;if(!K)return;const D=[];for(let _=0;_<K.length;_++)D.push(K[_].name);b(_=>{const ae=D.filter(J=>!_.includes(J));return[..._,...ae]}),k.current&&(k.current.value="")},R=async()=>{const B=u.trim();if(!B)return;x(""),C(""),(await c.onSend(B,h,d,f)).ok&&c.jumpToLatest()},S=async()=>{c.busy.create||await c.onCreateSession()},N=B=>{o.open({title:"Delete message?",children:e.jsx("p",{style:{margin:0},children:"This action cannot be undone."}),footer:e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx(M,{variant:"secondary",size:"sm",onClick:()=>o.close(),children:"Cancel"}),e.jsx(M,{variant:"danger",size:"sm",onClick:()=>{o.close(),c.deleteMessage(B)},children:"Delete"})]})})},P=(B,K)=>{let D="";o.open({title:"Rename session",children:e.jsx("input",{id:"rename-session-input",autoFocus:!0,defaultValue:K,"aria-label":"Session title",onChange:_=>{D=_.target.value},onKeyDown:_=>{_.key==="Enter"&&(_.preventDefault(),o.close(),c.renameSession(B,D).then(ae=>{ae&&l.success("Renamed.")}))},style:{width:"100%",padding:"8px 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-sm)",color:"var(--text)",font:"13px/1.4 var(--font-sans)",marginTop:6}}),footer:e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx(M,{variant:"secondary",size:"sm",onClick:()=>o.close(),children:"Cancel"}),e.jsx(M,{variant:"primary",size:"sm",onClick:()=>{o.close(),c.renameSession(B,D)},children:"Save"})]})})},g=(B,K)=>{o.open({title:"Delete session?",children:e.jsxs("p",{style:{margin:0},children:["Delete ",e.jsx("strong",{children:K}),"? Messages on the cline serve will be removed. This cannot be undone."]}),footer:e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx(M,{variant:"secondary",size:"sm",onClick:()=>o.close(),children:"Cancel"}),e.jsx(M,{variant:"danger",size:"sm",onClick:async()=>{o.close(),await c.deleteSession(B)},children:"Delete"})]})})},j=()=>{const B=c.activeSource==="cline"?c.activeClineSessionId:c.sessionId;if(!B)return;const D=(c.activeSource==="cline"?c.clineMessages:c.bizarMessages).map(ne=>{const I=ne.ts??"",V=(ne.role||"unknown").toUpperCase(),ie=ne.content||ne.message||"";return`[${I}] ${V}: ${ie}`}).join(`
|
|
2
|
-
|
|
3
|
-
`),_=new Blob([D],{type:"text/plain;charset=utf-8"}),ae=URL.createObjectURL(_),J=document.createElement("a");J.href=ae,J.download=`${B}.txt`,document.body.appendChild(J),J.click(),document.body.removeChild(J),URL.revokeObjectURL(ae)},T=r.useMemo(()=>c.sessions.map(B=>c.getSessionDisplay(B)),[c.sessions,c.getSessionDisplay]),F=r.useMemo(()=>c.clineSessions.map(B=>c.getSessionDisplay(B)),[c.clineSessions,c.getSessionDisplay]),A=r.useMemo(()=>{const B=c.activeSource==="cline"?c.activeClineSessionId??"":c.sessionId;return B?T.find(K=>K.id===B)??F.find(K=>K.id===B)??null:null},[c.activeSource,c.activeClineSessionId,c.sessionId,T,F]),U=(()=>{var D;const B=`${h||"Odin"} · ${((D=s.activeProject)==null?void 0:D.name)??"no project"}`,K=(A==null?void 0:A.state)??"idle";return K==="streaming"?`Replying · ${B}`:K==="awaiting"?`Your turn · ${B}`:`${B} · idle`})(),Y=c.activeSource==="cline"?"cline":"bizar chat";return e.jsxs("div",{className:"chat-shell",children:[e.jsx(Li,{activeProject:s.activeProject,sessionCount:c.sessions.length,sessionsOpen:!0,infoOpen:!0,onToggleSessions:()=>{},onToggleInfo:()=>{},onOpenOverview:()=>a==null?void 0:a("overview")}),e.jsxs("div",{className:"chat-page",children:[e.jsx(Wr,{sessions:T,clineSessions:F,activeSessionId:c.sessionId,activeClineSessionId:c.activeClineSessionId,activeProject:s.activeProject,creating:c.busy.create,onCreateSession:S,onSelectSession:c.selectBizarSession,onSelectClineSession:B=>c.loadClineSession(B.id),onRenameSession:P,onDeleteSession:B=>{const K=c.sessions.find(D=>D.id===B)??c.clineSessions.find(D=>D.id===B);g(B,(K==null?void 0:K.title)??"")}}),e.jsxs("section",{className:"chat-thread-section",children:[e.jsxs("div",{className:"chat-thread-head",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"chat-thread-title-row",children:[e.jsx("div",{className:"chat-thread-title",children:(A==null?void 0:A.title)??c.sessionId??"New chat"}),e.jsx("span",{className:`chat-source-badge chat-source-${c.activeSource??"none"}`,title:c.activeSource==="cline"?"Messages go to the cline serve child":"Messages go to the local chat store",children:Y})]}),e.jsxs("div",{className:`chat-thread-sub chat-muted state-${(A==null?void 0:A.state)??"idle"}`,children:[e.jsx("span",{className:"chat-thread-dot"}),U]}),c.clineError&&e.jsxs("div",{className:"chat-thread-error",role:"alert",children:[e.jsx("p",{className:"chat-error-message",children:c.clineError}),c.clineSuggestion&&e.jsx("p",{className:"chat-error-suggestion",children:c.clineSuggestion}),c.activeClineSessionId&&e.jsx("button",{className:"btn btn-sm",type:"button",onClick:()=>c.loadClineSession(c.activeClineSessionId),children:"Retry"})]})]}),e.jsxs("div",{className:"chat-thread-actions",children:[A&&e.jsxs("button",{className:"btn btn-ghost",title:"Rename session",type:"button",disabled:c.busy.rename,onClick:()=>P(A.id,A.title??""),children:[e.jsx(et,{size:12,"aria-hidden":!0})," ",e.jsx("span",{className:"mono",children:"rename"})]}),A&&e.jsxs("button",{className:"btn btn-ghost btn-danger",title:"Delete session",type:"button",disabled:c.busy.delete,onClick:()=>g(A.id,A.title??A.id),children:[e.jsx(Re,{size:12,"aria-hidden":!0})," ",e.jsx("span",{className:"mono",children:"delete"})]}),e.jsx("button",{className:"btn btn-ghost",title:"Export transcript",type:"button",onClick:j,children:e.jsx("span",{className:"mono",children:"export"})})]})]}),e.jsx("div",{className:"chat-thread-scroll",ref:c.listRef,onScroll:c.handleScroll,role:"log","aria-live":"polite","aria-relevant":"additions","aria-label":"Chat message thread",children:e.jsx(Di,{messages:c.activeSource==="cline"?c.clineMessages:c.bizarMessages,loading:c.loading,activeProject:s.activeProject,sessionId:c.activeSource==="cline"?c.activeClineSessionId??c.sessionId:c.sessionId,pinned:c.pinned,activeSource:c.activeSource,onPickSuggestion:B=>x(B),onCopy:B=>c.copyMessage(B),onDelete:N,onTogglePin:c.togglePin,onRegenerate:c.onRegenerate})}),!c.stickToBottom&&e.jsx(Yr,{streaming:(A==null?void 0:A.state)==="streaming",newMessageCount:c.newMessageCount,onClick:c.jumpToLatest}),e.jsx(qr,{agent:h,setAgent:m,model:d,setModel:p,text:u,setText:x,sending:c.sending,activeSource:c.activeSource,onSend:R,attachments:f,setAttachments:b,suggestions:v,onPickSuggestion:B=>x(`${B.split(" ")[0]} `),agents:s.agents||[],onAttach:z}),e.jsx("input",{ref:k,type:"file",multiple:!0,style:{display:"none"},onChange:y,"aria-label":"Attach files to message",tabIndex:-1})]}),e.jsx(Kr,{sessionId:c.activeSource==="cline"?c.activeClineSessionId??c.sessionId:c.sessionId,messages:c.activeSource==="cline"?c.clineMessages:c.bizarMessages,pinned:c.pinned,agent:h,model:d,agents:s.agents||[],mcps:s.mcps||[],allCommands:w,activeSource:c.activeSource,onRename:()=>{A&&P(A.id,A.title??"")},onDelete:()=>{A&&g(A.id,A.title??A.id)},onExport:j,busy:c.busy})]})]})}const ga=["bash","read","edit","write","webfetch","websearch","task","glob","grep"],fa=["anthropic/claude-3-5-sonnet","anthropic/claude-3-5-haiku","openai/gpt-4o","openai/gpt-4o-mini","openrouter/minimax/minimax-m3","openrouter/minimax/minimax-m2.7"],ja="#8b5cf6",ut=[{id:"reasoning",label:"Reasoning",variant:"accent"},{id:"code",label:"Code",variant:"info"},{id:"design",label:"Design",variant:"success"},{id:"planning",label:"Planning",variant:"warning"},{id:"gitops",label:"GitOps",variant:"danger"},{id:"analysis",label:"Analysis",variant:"neutral"}];function va(s){if(!s)return{label:"—",variant:"neutral"};const t=ut.find(a=>a.id===s);return t?{label:t.label,variant:t.variant}:{label:s,variant:"neutral"}}function $t(s){if(s.isStuck)return"stuck";const t=s.status||"idle";return t==="working"?"working":t==="error"?"error":"idle"}function nt(s){return s==="stuck"?"stuck":s}function ba(s){return s==="working"?"info":s==="error"||s==="stuck"?"danger":"neutral"}function Os(s){return s.lastSeenAt??s.lastSeen}function Qr(s,t=4){if(!s||s.length===0)return"—";const a=s.slice(0,t).join(", ");return s.length>t?`${a} +${s.length-t}`:a}function Jr({snapshot:s,refreshSnapshot:t}){const a=ce(),n=Pe(),[i,l]=r.useState(s.agents||[]),[o,c]=r.useState(!s.agents),[u,x]=r.useState(""),[h,m]=r.useState(""),[d,p]=r.useState(null);r.useEffect(()=>{l(s.agents||[]),c(!s.agents)},[s.agents]),r.useEffect(()=>{d&&!i.some(g=>g.name===d)&&p(null)},[i,d]);const f=async()=>{try{const g=await $.get("/agents");l(g.agents||[])}catch(g){a.error(`Agents load failed: ${g.message}`)}finally{c(!1)}},b=r.useMemo(()=>{let g=[...i];if(u&&(g=g.filter(j=>u==="__none__"?!j.category:(j.category||"")===u)),h){const j=h.toLowerCase();g=g.filter(T=>T.name.toLowerCase().includes(j)||(T.description||"").toLowerCase().includes(j)||(T.tags||[]).some(F=>F.toLowerCase().includes(j)))}return g.sort((j,T)=>j.name.localeCompare(T.name))},[i,u,h]),k=b.some(g=>typeof Os(g)=="number"),w=r.useMemo(()=>b.find(g=>g.name===d)||null,[b,d]),v=()=>{let g=null,j=null,T=null,F=null,A=null,U=null,Y=null,B=null,K=null;n.open({title:"New agent",width:640,children:e.jsxs("div",{className:"agent-form",children:[e.jsx("label",{className:"field-label",htmlFor:"agent-new-name",children:"Name (a-z, 0-9, dashes)"}),e.jsx("input",{id:"agent-new-name",ref:D=>g=D,className:"input",type:"text",placeholder:"my-agent",autoFocus:!0}),e.jsx("label",{className:"field-label",htmlFor:"agent-new-desc",children:"Description"}),e.jsx("input",{id:"agent-new-desc",ref:D=>{j=D},className:"input",type:"text",placeholder:"What does this agent do?"}),e.jsxs("div",{className:"task-form-row",children:[e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"agent-new-model",children:"Model"}),e.jsxs("select",{id:"agent-new-model",ref:D=>T=D,className:"select",defaultValue:"",children:[e.jsx("option",{value:"",children:"(provider default)"}),fa.map(D=>e.jsx("option",{value:D,children:D},D))]})]}),e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"agent-new-mode",children:"Mode"}),e.jsxs("select",{id:"agent-new-mode",ref:D=>F=D,className:"select",defaultValue:"subagent",children:[e.jsx("option",{value:"primary",children:"primary"}),e.jsx("option",{value:"subagent",children:"subagent"}),e.jsx("option",{value:"all",children:"all"})]})]}),e.jsxs("div",{className:"task-form-field",style:{flex:"0 0 80px"},children:[e.jsx("label",{className:"field-label",htmlFor:"agent-new-color",children:"Color"}),e.jsx("input",{id:"agent-new-color",ref:D=>A=D,className:"input",type:"color",defaultValue:ja})]})]}),e.jsxs("div",{className:"task-form-row",children:[e.jsxs("div",{className:"task-form-field",style:{flex:1},children:[e.jsx("label",{className:"field-label",htmlFor:"agent-new-category",children:"Category"}),e.jsxs("select",{id:"agent-new-category",ref:D=>K=D,className:"select",defaultValue:"",children:[e.jsx("option",{value:"",children:"(none)"}),ut.map(D=>e.jsx("option",{value:D.id,children:D.label},D.id))]})]}),e.jsxs("div",{className:"task-form-field",style:{flex:2},children:[e.jsx("label",{className:"field-label",htmlFor:"agent-new-tags",children:"Tags (comma-separated)"}),e.jsx("input",{id:"agent-new-tags",ref:D=>B=D,className:"input",type:"text",placeholder:"reasoning, code, planning"})]})]}),e.jsxs("fieldset",{children:[e.jsx("legend",{className:"field-label",style:{padding:0},children:"Tools"}),e.jsx("div",{ref:D=>Y=D,className:"agent-tools",children:ga.map(D=>e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{type:"checkbox",value:D,"aria-label":D}),e.jsx("span",{children:D})]},D))})]}),e.jsx("label",{className:"field-label",htmlFor:"agent-new-prompt",children:"System prompt"}),e.jsx("textarea",{id:"agent-new-prompt",ref:D=>U=D,className:"textarea",rows:6,placeholder:"You are a..."})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx(M,{variant:"ghost",onClick:()=>n.close(),children:"Cancel"}),e.jsxs(M,{variant:"primary",onClick:async()=>{const D=((g==null?void 0:g.value)||"").trim();if(!/^[a-z0-9][a-z0-9-]{0,63}$/i.test(D)){a.warning("Invalid name (a-z, 0-9, dashes).");return}const _=[];Y&&Y.querySelectorAll('input[type="checkbox"]:checked').forEach(J=>{_.push(J.value)});const ae=((B==null?void 0:B.value)||"").split(",").map(J=>J.trim()).filter(Boolean);try{const J=await $.post("/agents",{name:D,description:((j==null?void 0:j.value)||"").trim(),model:(T==null?void 0:T.value)||"",mode:(F==null?void 0:F.value)||"subagent",color:(A==null?void 0:A.value)||"",tools:_,tags:ae,category:(K==null?void 0:K.value)||"",prompt:(U==null?void 0:U.value)||""});l(ne=>[...ne,J]),p(J.name),a.success("Agent created."),n.close(),await t()}catch(J){a.error(`Create failed: ${J.message}`)}},children:[e.jsx(Is,{size:12})," Create"]})]})})},C=async g=>{let j=null,T=null,F=null,A=null,U=null,Y=null,B=null,K=null;try{const D=await $.get(`/agents/${encodeURIComponent(g.name)}`);n.open({title:`Edit ${g.name}`,width:640,children:e.jsxs("div",{className:"agent-form",children:[e.jsxs("div",{className:"muted",children:["File: ",e.jsx("code",{children:D.path})]}),e.jsx("label",{className:"field-label",htmlFor:"agent-edit-desc",children:"Description"}),e.jsx("input",{id:"agent-edit-desc",ref:_=>{j=_},className:"input",type:"text",defaultValue:D.description}),e.jsxs("div",{className:"task-form-row",children:[e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"agent-edit-model",children:"Model"}),e.jsxs("select",{id:"agent-edit-model",ref:_=>T=_,className:"select",defaultValue:D.model,children:[e.jsx("option",{value:"",children:"(provider default)"}),fa.map(_=>e.jsx("option",{value:_,children:_},_))]})]}),e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"agent-edit-mode",children:"Mode"}),e.jsxs("select",{id:"agent-edit-mode",ref:_=>F=_,className:"select",defaultValue:D.mode||"subagent",children:[e.jsx("option",{value:"primary",children:"primary"}),e.jsx("option",{value:"subagent",children:"subagent"}),e.jsx("option",{value:"all",children:"all"})]})]}),e.jsxs("div",{className:"task-form-field",style:{flex:"0 0 80px"},children:[e.jsx("label",{className:"field-label",htmlFor:"agent-edit-color",children:"Color"}),e.jsx("input",{id:"agent-edit-color",ref:_=>A=_,className:"input",type:"color",defaultValue:D.color||ja})]})]}),e.jsxs("div",{className:"task-form-row",children:[e.jsxs("div",{className:"task-form-field",style:{flex:1},children:[e.jsx("label",{className:"field-label",htmlFor:"agent-edit-category",children:"Category"}),e.jsxs("select",{id:"agent-edit-category",ref:_=>K=_,className:"select",defaultValue:D.category||"",children:[e.jsx("option",{value:"",children:"(none)"}),ut.map(_=>e.jsx("option",{value:_.id,children:_.label},_.id))]})]}),e.jsxs("div",{className:"task-form-field",style:{flex:2},children:[e.jsx("label",{className:"field-label",htmlFor:"agent-edit-tags",children:"Tags (comma-separated)"}),e.jsx("input",{id:"agent-edit-tags",ref:_=>B=_,className:"input",type:"text",defaultValue:(D.tags||[]).join(", ")})]})]}),e.jsxs("fieldset",{children:[e.jsx("legend",{className:"field-label",style:{padding:0},children:"Tools"}),e.jsx("div",{ref:_=>Y=_,className:"agent-tools",children:ga.map(_=>{var ae;return e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{type:"checkbox",value:_,"aria-label":_,defaultChecked:(ae=D.tools)==null?void 0:ae.includes(_)}),e.jsx("span",{children:_})]},_)})})]}),e.jsx("label",{className:"field-label",htmlFor:"agent-edit-prompt",children:"System prompt"}),e.jsx("textarea",{id:"agent-edit-prompt",ref:_=>U=_,className:"textarea",rows:8,defaultValue:D.prompt||""})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx(M,{variant:"ghost",onClick:()=>n.close(),children:"Cancel"}),e.jsxs(M,{variant:"primary",onClick:async()=>{const _=[];Y&&Y.querySelectorAll('input[type="checkbox"]:checked').forEach(J=>{_.push(J.value)});const ae=((B==null?void 0:B.value)||"").split(",").map(J=>J.trim()).filter(Boolean);try{const J=await $.put(`/agents/${encodeURIComponent(g.name)}`,{description:((j==null?void 0:j.value)||"").trim(),model:(T==null?void 0:T.value)||"",mode:(F==null?void 0:F.value)||"subagent",color:(A==null?void 0:A.value)||"",tools:_,tags:ae,category:(K==null?void 0:K.value)||"",prompt:(U==null?void 0:U.value)||""});l(ne=>ne.map(I=>I.name===g.name?J:I)),a.success("Agent saved."),n.close(),await t()}catch(J){a.error(`Save failed: ${J.message}`)}},children:[e.jsx(Is,{size:12})," Save"]})]})})}catch(D){a.error(`Load failed: ${D.message}`)}},z=async g=>{if(confirm(`Delete agent "${g.name}"? This removes ${g.path}.`))try{await $.del(`/agents/${encodeURIComponent(g.name)}`),l(j=>j.filter(T=>T.name!==g.name)),a.success("Agent deleted.")}catch(j){a.error(`Delete failed: ${j.message}`)}},y=g=>{let j=null;n.open({title:`Invoke ${g.name}`,children:e.jsxs("div",{className:"invoke-form",children:[e.jsxs("p",{className:"muted invoke-form-meta mono",children:[g.model||"—"," · ",g.path]}),e.jsx("p",{className:"invoke-form-desc",children:g.description}),e.jsx("label",{className:"field-label",htmlFor:"invoke-prompt",children:"Prompt"}),e.jsx("textarea",{ref:T=>j=T,id:"invoke-prompt",className:"textarea",rows:5,placeholder:"What should this agent do?",autoFocus:!0})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx(M,{variant:"ghost",onClick:()=>n.close(),children:"Cancel"}),e.jsxs(M,{variant:"primary",onClick:async()=>{const T=((j==null?void 0:j.value)||"").trim();if(!T){a.warning("Prompt is required.");return}try{await $.post(`/agents/${encodeURIComponent(g.name)}/invoke`,{prompt:T}),a.success(`Invoked ${g.name}.`),n.close()}catch(F){a.error(`Invoke failed: ${F.message}`)}},children:[e.jsx(Es,{size:14})," Invoke"]})]})})},R=async g=>{try{const j=await $.post(`/agents/${encodeURIComponent(g.name)}/restart`);l(T=>T.map(F=>F.name===g.name?j:F)),a.success(`${g.name} restarted.`)}catch(j){a.error(`Restart failed: ${j.message}`)}},S=[{key:"name",header:"Name",sortable:!0,accessor:g=>g.name,render:g=>e.jsxs("span",{className:"agents-name-cell",children:[e.jsx("span",{className:oe("agents-name-cell__swatch",!g.color&&"agents-name-cell__swatch--empty"),style:g.color?{background:g.color}:void 0,"aria-hidden":"true"}),g.name]})},{key:"status",header:"Status",sortable:!0,accessor:g=>$t(g),render:g=>{const j=$t(g);return e.jsxs("span",{className:"agents-status-cell",children:[e.jsx(Qs,{variant:ba(j),size:"sm",pulse:j==="stuck",label:nt(j)}),e.jsx("span",{className:oe("agents-status-cell__label",j==="stuck"&&"agents-status-cell__label--stuck"),children:nt(j)})]})}},{key:"category",header:"Category",sortable:!0,accessor:g=>g.category||"",render:g=>{const j=va(g.category);return g.category?e.jsx("span",{className:"agents-category-cell",children:e.jsx(Xe,{variant:j.variant,size:"sm",children:j.label})}):e.jsx("span",{className:"muted",children:"—"})}},{key:"tags",header:"Tags",accessor:g=>(g.tags||[]).join(","),render:g=>e.jsx("span",{className:"agents-tags-cell",title:(g.tags||[]).join(", "),children:Qr(g.tags)})}];k&&S.push({key:"lastSeen",header:"Last seen",sortable:!0,accessor:g=>Os(g)||0,render:g=>{const j=Os(g);return e.jsx("span",{className:"muted tabular-nums",children:j?Te(j):"—"})}});function N(){var U;if(!w)return e.jsxs("div",{className:"agents-detail__placeholder",children:[e.jsx("span",{className:"agents-detail__placeholder-icon","aria-hidden":"true",children:e.jsx(Qe,{size:28})}),e.jsx("span",{className:"agents-detail__placeholder-title",children:"No agent selected"}),e.jsx("span",{children:"Pick a row from the table to see its metadata, actions, and prompt."})]});const g=w,j=$t(g),T=va(g.category),F=g.isStuck||g.status==="working"||g.status==="error",A=[{key:"status",label:"Status",value:e.jsxs("span",{className:"agents-status-cell",children:[e.jsx(Qs,{variant:ba(j),size:"sm",pulse:j==="stuck",label:nt(j)}),e.jsx("span",{className:"agents-status-cell__label",children:nt(j)})]})},{key:"category",label:"Category",value:g.category?e.jsx(Xe,{variant:T.variant,size:"sm",children:T.label}):e.jsx("span",{className:"muted",children:"—"})},{key:"tags",label:"Tags",value:g.tags&&g.tags.length>0?e.jsx($e,{gap:1,className:"agents-detail__tags",children:g.tags.map(Y=>e.jsx(Xe,{variant:"neutral",size:"sm",children:Y},Y))}):e.jsx("span",{className:"muted",children:"—"})},{key:"tools",label:"Tools",value:g.tools&&g.tools.length>0?e.jsx($e,{gap:1,className:"agents-detail__tools",children:g.tools.map(Y=>e.jsx(Xe,{variant:"info",size:"sm",children:Y},Y))}):e.jsx("span",{className:"muted",children:"—"})},{key:"model",label:"Model",mono:!0,copyable:!0,value:g.model||"—"},{key:"mode",label:"Mode",value:g.mode||"subagent"},{key:"color",label:"Color",value:g.color?e.jsxs($e,{gap:2,align:"center",children:[e.jsx("span",{className:"agents-detail__name-swatch",style:{background:g.color},"aria-hidden":"true"}),e.jsx("code",{className:"mono",children:g.color})]}):e.jsx("span",{className:"muted",children:"—"})},{key:"description",label:"Description",value:g.description?e.jsx("div",{className:"agents-detail__description",children:Ea(g.description,600)}):e.jsx("span",{className:"muted",children:"—"})}];return typeof Os(g)=="number"&&A.push({key:"lastSeen",label:"Last seen",mono:!0,value:Te(Os(g))}),(U=g.lastError)!=null&&U.message&&A.push({key:"lastError",label:"Last error",value:e.jsx("div",{className:"agents-detail__error",children:g.lastError.message})}),e.jsxs(Be,{gap:4,className:"agents-detail__meta",children:[e.jsx(an,{items:A,orientation:"horizontal"}),e.jsxs(Se,{className:"agents-detail__prompt",children:[e.jsx("span",{className:"agents-detail__prompt-label",children:"System prompt"}),g.prompt?e.jsx("pre",{className:"agents-detail__prompt-body",children:g.prompt}):e.jsx("span",{className:"agents-detail__prompt-empty",children:"No prompt configured."})]}),e.jsxs($e,{gap:2,wrap:!0,className:"agents-detail__actions",children:[e.jsx(Ue,{variant:"secondary",size:"sm",icon:e.jsx(et,{size:12}),onClick:()=>C(g),"aria-label":`Edit ${g.name}`,"data-testid":`agents-detail-edit-${g.name}`,children:"Edit"}),e.jsx(Ue,{variant:"secondary",size:"sm",icon:e.jsx(Es,{size:12}),onClick:()=>y(g),"aria-label":`Invoke ${g.name}`,"data-testid":`agents-detail-invoke-${g.name}`,children:"Invoke"}),F&&e.jsx(Ue,{variant:"ghost",size:"sm",icon:e.jsx(bt,{size:12}),onClick:()=>R(g),"aria-label":`Restart ${g.name}`,"data-testid":`agents-detail-restart-${g.name}`,children:"Restart"}),e.jsx(Ue,{variant:"danger",size:"sm",icon:e.jsx(Re,{size:12}),onClick:()=>z(g),"aria-label":`Delete ${g.name}`,"data-testid":`agents-detail-delete-${g.name}`,children:"Delete"})]}),g.isStuck&&e.jsxs($e,{gap:2,align:"center",className:"agents-detail__error",children:[e.jsx(Kt,{size:12}),e.jsx("span",{children:"Agent is stuck — restart to reset state."})]})]})}const P=[{value:"",label:"All categories"},...ut.map(g=>({value:g.id,label:g.label})),{value:"__none__",label:"(no category)"}];return e.jsxs("div",{className:"agents-redesign","data-testid":"agents-view",children:[e.jsxs("header",{className:"agents-redesign__header",children:[e.jsxs("div",{className:"agents-redesign__header-text",children:[e.jsxs("h2",{className:"agents-redesign__title",children:[e.jsx(Qe,{size:18,"aria-hidden":"true"}),e.jsx("span",{children:"Agents"}),e.jsxs("span",{className:"agents-redesign__title-count","data-testid":"agents-count",children:["(",b.length,")"]})]}),e.jsxs("p",{className:"agents-redesign__subtitle",children:["The Norse pantheon — pick a row to inspect, ",e.jsx("kbd",{children:"Edit"})," to modify, ",e.jsx("kbd",{children:"Invoke"})," to dispatch."]})]}),e.jsxs("div",{className:"agents-redesign__controls",children:[e.jsxs("span",{className:"agents-redesign__control",style:{minWidth:180},children:[e.jsx("label",{htmlFor:"agents-search",className:"vh",children:"Search agents"}),e.jsx("input",{id:"agents-search",className:"input",type:"search",placeholder:"Search name, description, tag…",value:h,onChange:g=>m(g.target.value),"aria-label":"Search agents","data-testid":"agents-search"})]}),e.jsxs("span",{className:"agents-redesign__control",style:{minWidth:180},children:[e.jsx("label",{htmlFor:"agents-category-filter",className:"vh",children:"Filter by category"}),e.jsx("select",{id:"agents-category-filter",className:"select",value:u,onChange:g=>x(g.target.value),"data-testid":"agents-category-filter",children:P.map(g=>e.jsx("option",{value:g.value,children:g.label},g.value||"__all__"))})]}),e.jsx(Ue,{variant:"ghost",size:"sm",icon:e.jsx(me,{size:12}),onClick:f,"aria-label":"Refresh","data-testid":"agents-refresh",children:"Refresh"}),e.jsx(Ue,{variant:"primary",size:"sm",icon:e.jsx(Ee,{size:12}),onClick:v,"aria-label":"New agent","data-testid":"agents-new",children:"New agent"})]})]}),e.jsxs("div",{className:"agents-redesign__body",children:[e.jsx(Se,{className:"agents-roster",children:o?e.jsx(ia,{label:"Loading agents…",rows:3}):b.length===0?e.jsx(mt,{icon:e.jsx(Qe,{size:32}),title:"No agents found",description:i.length===0?"Run bizar in the terminal to install Bizar.":"No agents match the current filters — try clearing the search or category.",action:i.length===0?void 0:{label:"Clear filters",onClick:()=>{m(""),x("")}}}):e.jsx("div",{className:"agents-roster__table","data-testid":"agents-table",children:e.jsx(br,{columns:S,data:b,rowKey:g=>g.name,compact:!0,onRowClick:g=>p(g.name)})})}),e.jsx(ts,{title:w?e.jsxs("span",{className:"agents-detail__name",children:[e.jsx("span",{className:oe("agents-detail__name-swatch",!w.color&&"agents-detail__name-swatch--empty"),style:w.color?{background:w.color}:void 0,"aria-hidden":"true"}),e.jsx("span",{children:w.name})]}):"Agent detail",description:w?w.path:"Select an agent from the roster to see its metadata.",padding:4,variant:"outlined",className:"agents-detail",children:N()})]})]})}function Zr({id:s,children:t}){return e.jsx("div",{id:s,"data-block-id":s,className:W("glyph-richtext"),style:nn,children:e.jsx(Za,{remarkPlugins:[en],children:t})})}const el={info:{bg:"var(--info-soft, rgba(96, 165, 250, 0.12))",border:"var(--info)",fg:"var(--info)",icon:Jt,label:"Note"},warn:{bg:"var(--warning-soft, rgba(251, 191, 36, 0.15))",border:"var(--warning)",fg:"var(--warning)",icon:Me,label:"Warning"},success:{bg:"var(--success-soft, rgba(52, 211, 153, 0.15))",border:"var(--success)",fg:"var(--success)",icon:_e,label:"Success"},danger:{bg:"var(--error-soft, rgba(248, 113, 113, 0.12))",border:"var(--error)",fg:"var(--error)",icon:vs,label:"Danger"}};function sl({id:s,tone:t="info",children:a}){const n=el[t],i=n.icon;return e.jsxs("div",{id:s,"data-block-id":s,className:W("glyph-callout",`glyph-callout-${t}`),style:{display:"flex",gap:12,padding:"12px 16px",margin:"12px 0",borderLeft:`3px solid ${n.border}`,background:n.bg,borderRadius:8,color:"var(--text)"},role:t==="danger"||t==="warn"?"alert":void 0,children:[e.jsx("div",{style:{flexShrink:0,color:n.fg,paddingTop:2},children:e.jsx(i,{size:18})}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontWeight:600,fontSize:13,color:n.fg,marginBottom:4},children:n.label}),e.jsx("div",{className:"glyph-richtext",style:{...nn,fontSize:14},children:e.jsx(Za,{remarkPlugins:[en],children:a})})]})]})}function tl({id:s,items:t}){return e.jsx("ul",{id:s,"data-block-id":s,className:"glyph-checklist",style:{listStyle:"none",padding:0,margin:"12px 0",display:"flex",flexDirection:"column",gap:6},children:t.map(a=>e.jsxs("li",{style:{display:"flex",alignItems:"flex-start",gap:10,padding:"6px 10px",borderRadius:6,background:"var(--bg-elev)",border:"1px solid var(--border)",fontSize:14},children:[e.jsx("span",{"aria-hidden":!0,style:{flexShrink:0,marginTop:1,width:16,height:16,borderRadius:4,border:`1.5px solid ${a.checked?"var(--success)":"var(--border-strong)"}`,background:a.checked?"var(--success)":"transparent",color:"var(--bg)",display:"inline-flex",alignItems:"center",justifyContent:"center"},children:a.checked?e.jsx(cs,{size:12,strokeWidth:3}):null}),e.jsx("span",{style:{color:a.checked?"var(--text-dim)":"var(--text)",textDecoration:a.checked?"line-through":"none",wordBreak:"break-word"},children:a.label})]},a.id))})}function al({id:s,columns:t,rows:a}){return e.jsx("div",{id:s,"data-block-id":s,className:"glyph-table-wrap",style:{margin:"12px 0",border:"1px solid var(--border)",borderRadius:8,overflow:"auto",background:"var(--bg-elev)"},children:e.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[e.jsx("thead",{children:e.jsx("tr",{children:t.map((n,i)=>e.jsx("th",{style:{textAlign:"left",padding:"8px 12px",borderBottom:"1px solid var(--border-strong)",background:"var(--bg)",color:"var(--text-dim)",fontWeight:600,fontSize:12,textTransform:"uppercase",letterSpacing:.3,whiteSpace:"nowrap"},children:n},i))})}),e.jsx("tbody",{children:a.map((n,i)=>e.jsx("tr",{style:{borderTop:i===0?"none":"1px solid var(--border)"},children:n.map((l,o)=>e.jsx("td",{style:{padding:"8px 12px",color:"var(--text)",verticalAlign:"top",wordBreak:"break-word"},children:l},o))},i))})]})})}function nl({id:s,tabs:t}){var l;const[a,n]=r.useState(((l=t[0])==null?void 0:l.id)??""),i=r.useMemo(()=>t.find(o=>o.id===a)??t[0],[t,a]);return e.jsxs("div",{id:s,"data-block-id":s,className:"glyph-codetabs",style:{margin:"12px 0",border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:"var(--bg-elev)"},children:[e.jsx("div",{role:"tablist",style:{display:"flex",gap:2,padding:4,background:"var(--bg)",borderBottom:"1px solid var(--border)",overflowX:"auto"},children:t.map(o=>{const c=o.id===(i==null?void 0:i.id);return e.jsxs("button",{type:"button",role:"tab","aria-selected":c,onClick:()=>n(o.id),style:{padding:"6px 12px",fontSize:12,fontFamily:"var(--font-mono)",borderRadius:6,border:"none",cursor:"pointer",background:c?"var(--bg-elev)":"transparent",color:c?"var(--text-strong)":"var(--text-dim)",boxShadow:c?"0 0 0 1px var(--border)":"none",whiteSpace:"nowrap"},children:[e.jsx("span",{children:o.label}),o.language&&e.jsx("span",{style:{marginLeft:6,color:"var(--text-dim)",fontSize:11},children:o.language})]},o.id)})}),i&&e.jsxs(e.Fragment,{children:[e.jsx("pre",{style:{margin:0,padding:14,overflowX:"auto",fontFamily:"var(--font-mono)",fontSize:12.5,lineHeight:1.55,color:"var(--text)",background:"var(--bg-elev)"},children:e.jsx("code",{children:i.code})}),i.caption&&e.jsx("div",{style:{padding:"8px 14px",borderTop:"1px solid var(--border)",fontSize:12,color:"var(--text-dim)",background:"var(--bg)"},children:i.caption})]})]})}function il({id:s,title:t,question:a,options:n}){return e.jsxs("div",{id:s,"data-block-id":s,className:"glyph-decision",style:{margin:"16px 0",padding:16,border:"1px solid var(--border)",borderRadius:10,background:"var(--bg-elev)"},children:[t&&e.jsx("h3",{style:{margin:0,marginBottom:4,fontSize:15,fontWeight:600,color:"var(--text-strong)"},children:t}),a&&e.jsx("p",{style:{margin:0,marginBottom:12,fontSize:13,color:"var(--text-dim)"},children:a}),e.jsx("div",{style:{display:"grid",gap:10,gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))"},children:n.map(i=>{const l=!!i.recommended;return e.jsxs("div",{style:{position:"relative",padding:12,borderRadius:8,border:l?"2px solid var(--success)":"1px solid var(--border)",background:l?"var(--success-soft)":"var(--bg)"},children:[l&&e.jsx("span",{style:{position:"absolute",top:-10,right:10,padding:"2px 8px",fontSize:11,fontWeight:600,color:"var(--bg)",background:"var(--success)",borderRadius:999},children:"Recommended"}),e.jsx("div",{style:{fontWeight:600,fontSize:14,color:"var(--text-strong)",marginBottom:4},children:i.label}),e.jsx("div",{style:{fontSize:13,color:"var(--text)"},children:i.detail})]},i.id)})})]})}function rl({id:s,questions:t}){const[a,n]=r.useState({});function i(l,o){n(c=>({...c,[l]:o}))}return e.jsxs("div",{id:s,"data-block-id":s,className:"glyph-openquestions",style:{margin:"16px 0",padding:16,border:"1px solid var(--border)",borderRadius:10,background:"var(--bg-elev)",display:"flex",flexDirection:"column",gap:14},children:[e.jsx("div",{style:{fontSize:13,fontWeight:600,color:"var(--text-strong)"},children:"Open questions"}),t.map(l=>e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[e.jsx("label",{htmlFor:`oq-${l.id}`,style:{fontSize:13,color:"var(--text)",fontWeight:500},children:l.label}),l.kind==="choice"&&e.jsxs("select",{id:`oq-${l.id}`,value:a[l.id]??"",onChange:o=>i(l.id,o.target.value),style:ya,children:[e.jsx("option",{value:"",children:"— select —"}),(l.options??[]).map(o=>e.jsx("option",{value:o,children:o},o))]}),l.kind==="text"&&e.jsx("input",{id:`oq-${l.id}`,type:"text",value:a[l.id]??"",onChange:o=>i(l.id,o.target.value),style:ya}),l.kind==="multi"&&e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4},children:(l.options??[]).map(o=>{const c=a[l.id]??[],u=c.includes(o);return e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,color:"var(--text)",cursor:"pointer"},children:[e.jsx("input",{type:"checkbox",checked:u,onChange:()=>{const x=u?c.filter(h=>h!==o):[...c,o];i(l.id,x)}}),e.jsx("span",{children:o})]},o)})})]},l.id))]})}const ya={padding:"6px 10px",fontSize:13,borderRadius:6,border:"1px solid var(--border-strong)",background:"var(--bg)",color:"var(--text)",fontFamily:"inherit"},ll={added:{bg:"var(--success-soft)",fg:"var(--success)",label:"A"},modified:{bg:"var(--info-soft, rgba(96, 165, 250, 0.12))",fg:"var(--info)",label:"M"},removed:{bg:"var(--error-soft)",fg:"var(--error)",label:"D"},renamed:{bg:"rgba(139, 92, 246, 0.15)",fg:"var(--accent)",label:"R"}};function cl({id:s,title:t,entries:a}){return e.jsxs("div",{id:s,"data-block-id":s,className:"glyph-filetree",style:{margin:"12px 0",padding:t?14:8,border:"1px solid var(--border)",borderRadius:8,background:"var(--bg-elev)"},children:[t&&e.jsx("div",{style:{fontSize:12,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4,marginBottom:8},children:t}),e.jsx("ul",{style:{listStyle:"none",padding:0,margin:0,display:"flex",flexDirection:"column",gap:2},children:a.map(n=>{const i=ll[n.change];return e.jsxs("li",{style:{display:"flex",alignItems:"center",gap:10,padding:"5px 8px",borderRadius:5,fontSize:13},children:[e.jsx("span",{"aria-label":n.change,title:n.change,style:{flexShrink:0,width:22,height:18,borderRadius:4,background:i.bg,color:i.fg,display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:10,fontWeight:700,fontFamily:"var(--font-mono)"},children:i.label}),e.jsx("span",{style:{fontFamily:"var(--font-mono)",color:"var(--text)",wordBreak:"break-all",flex:1},children:n.path}),n.note&&e.jsx("span",{style:{fontSize:12,color:"var(--text-dim)"},children:n.note})]},n.path)})})]})}function ol({id:s,filename:t,language:a,mode:n="unified",before:i,after:l}){const o=i.split(`
|
|
4
|
-
`),c=l.split(`
|
|
5
|
-
`),u=e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 12px",background:"var(--bg)",borderBottom:"1px solid var(--border)",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:[e.jsx(qn,{size:14}),e.jsx("span",{style:{color:"var(--text)"},children:t??"diff"}),a&&e.jsxs("span",{children:["· ",a]}),e.jsx("span",{style:{marginLeft:"auto",textTransform:"uppercase",letterSpacing:.3},children:n})]}),x={margin:0,padding:0,fontFamily:"var(--font-mono)",fontSize:12.5,lineHeight:1.55,color:"var(--text)",background:"var(--bg-elev)"},h=(m,d,p)=>{const f={del:"var(--error-soft)",add:"var(--success-soft)",ctx:"transparent"},b={del:"var(--error)",add:"var(--success)",ctx:"var(--text-dim)"};return e.jsxs("div",{style:{display:"flex",padding:"0 12px",background:f[p]},children:[e.jsx("span",{style:{width:18,color:b[p],userSelect:"none",flexShrink:0},children:m}),e.jsx("span",{style:{whiteSpace:"pre",flex:1,overflowX:"auto"},children:d||" "})]})};return e.jsxs("div",{id:s,"data-block-id":s,className:"glyph-diff",style:{margin:"12px 0",border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:"var(--bg-elev)"},children:[u,n==="unified"?e.jsxs("pre",{style:x,children:[o.map((m,d)=>e.jsx("div",{children:h("-",m,"del")},`b${d}`)),c.map((m,d)=>e.jsx("div",{children:h("+",m,"add")},`a${d}`))]}):e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr"},children:[e.jsx("pre",{style:{...x,borderRight:"1px solid var(--border)"},children:o.map((m,d)=>e.jsx("div",{children:h("-",m,"del")},d))}),e.jsx("pre",{style:x,children:c.map((m,d)=>e.jsx("div",{children:h("+",m,"add")},d))})]})]})}const dl={up:{fg:"var(--success)",Icon:He,label:"trending up"},down:{fg:"var(--error)",Icon:He,label:"trending down"},flat:{fg:"var(--text-dim)",Icon:Oa,label:"flat"}};function ml({id:s,label:t,value:a,trend:n,hint:i}){const l=n?dl[n]:null;return e.jsxs("div",{id:s,"data-block-id":s,className:"glyph-stat",style:{padding:14,border:"1px solid var(--border)",borderRadius:10,background:"var(--bg-elev)",display:"flex",flexDirection:"column",gap:4,minWidth:140},children:[e.jsx("div",{style:{fontSize:12,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:t}),e.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8},children:[e.jsx("span",{style:{fontSize:24,fontWeight:700,color:"var(--text-strong)"},children:a}),l&&e.jsx("span",{"aria-label":l.label,style:{display:"inline-flex",alignItems:"center",color:l.fg,transform:l.Icon===He&&n==="up"?"rotate(180deg)":void 0},children:e.jsx(l.Icon,{size:14})})]}),i&&e.jsx("div",{style:{fontSize:12,color:"var(--text-dim)"},children:i})]})}const ul={task:{stroke:"var(--info)",fill:"var(--bg-elev)",fg:"var(--text)"},decision:{stroke:"var(--warning)",fill:"var(--bg-elev)",fg:"var(--text)"},note:{stroke:"var(--border-strong)",fill:"var(--bg)",fg:"var(--text-dim)"}},Fe=160,qe=56,Ns=60,ks=80;function hl({id:s,steps:t,connections:a=[]}){if(t.length===0)return e.jsx("div",{id:s,"data-block-id":s,className:"glyph-workflow",children:e.jsx(xl,{id:s})});const n=new Map(t.map(h=>[h.id,h])),i=pl(t),l=Math.max(...i.map(h=>h.col))+1,o=Math.max(...i.map(h=>h.row))+1,c=l*(Fe+Ns)+Ns,u=o*(qe+ks)+ks;function x(h){if(!n.get(h))return null;const d=i.find(p=>p.id===h);return d?{x:Ns+d.col*(Fe+Ns)+Fe/2,y:ks+d.row*(qe+ks)+qe/2}:null}return e.jsx("div",{id:s,"data-block-id":s,className:"glyph-workflow",style:{margin:"12px 0",padding:12,border:"1px solid var(--border)",borderRadius:10,background:"var(--bg-elev)",overflow:"auto"},children:e.jsxs("svg",{role:"img","aria-label":"Workflow diagram",width:c,height:u,style:{display:"block",maxWidth:"100%"},children:[e.jsx("defs",{children:e.jsx("marker",{id:`arrow-${s}`,viewBox:"0 0 10 10",refX:"9",refY:"5",markerWidth:"6",markerHeight:"6",orient:"auto-start-reverse",children:e.jsx("path",{d:"M 0 0 L 10 5 L 0 10 z",fill:"var(--text-dim)"})})}),a.map((h,m)=>{const d=x(h.from),p=x(h.to);if(!d||!p)return null;const f=p.x-d.x,b=p.y-d.y,k=f>=0?d.x+Fe/2:d.x-Fe/2,w=f>=0?p.x-Fe/2:p.x+Fe/2,v=b>=0?d.y+qe/2:d.y-qe/2,C=b>=0?p.y-qe/2:p.y+qe/2,z=(k+w)/2,y=(v+C)/2;return e.jsxs("g",{children:[e.jsx("line",{x1:k,y1:v,x2:w,y2:C,stroke:"var(--text-dim)",strokeWidth:1.5,markerEnd:`url(#arrow-${s})`}),h.label&&e.jsx("text",{x:z,y:y-4,fontSize:10,fill:"var(--text-dim)",textAnchor:"middle",fontFamily:"var(--font-mono)",children:h.label})]},m)}),t.map(h=>{const m=i.find(k=>k.id===h.id);if(!m)return null;const d=Ns+m.col*(Fe+Ns),p=ks+m.row*(qe+ks),f=ul[h.type];if(h.type==="decision"){const k=d+Fe/2,w=p+qe/2,v=[[k,p],[d+Fe,w],[k,p+qe],[d,w]].map(C=>C.join(",")).join(" ");return e.jsxs("g",{children:[e.jsx("polygon",{points:v,fill:f.fill,stroke:f.stroke,strokeWidth:2}),e.jsx("foreignObject",{x:d+8,y:w-14,width:Fe-16,height:28,children:e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,fontSize:12,color:f.fg,textAlign:"center",lineHeight:1.2,fontStyle:"italic",height:"100%"},children:[e.jsx(Vn,{size:11}),h.label]})})]},h.id)}const b=h.type==="note";return e.jsxs("g",{children:[e.jsx("rect",{x:d,y:p,width:Fe,height:qe,rx:8,fill:f.fill,stroke:f.stroke,strokeWidth:b?1:2,strokeDasharray:b?"4 3":void 0}),e.jsx("foreignObject",{x:d+6,y:p+6,width:Fe-12,height:qe-12,children:e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,fontSize:12,color:f.fg,textAlign:"center",lineHeight:1.25,fontStyle:b?"italic":"normal",height:"100%"},children:[b&&e.jsx(Wn,{size:11}),h.label]})})]},h.id)})]})})}function xl({id:s}){return e.jsx("div",{id:s,style:{padding:20,textAlign:"center",color:"var(--text-dim)",fontSize:13},children:"No workflow steps."})}function pl(s){return s.length===0?[]:s.map((t,a)=>({id:t.id,col:a,row:0}))}const nn={fontSize:14,lineHeight:1.6,color:"var(--text)"};function gl({id:s,title:t,x:a,y:n,w:i,h:l,html:o}){return e.jsxs("figure",{id:s,"data-block-id":s,className:"glyph-mockup",style:{width:i,minHeight:l},children:[t&&e.jsx("figcaption",{className:"glyph-mockup-title",children:t}),e.jsxs("div",{className:"glyph-mockup-frame",children:[e.jsxs("div",{className:"glyph-mockup-chrome",children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]}),e.jsx("div",{className:"glyph-mockup-body",dangerouslySetInnerHTML:{__html:o}})]})]})}class fl extends Ke.Component{constructor(){super(...arguments);Ps(this,"state",{err:null})}static getDerivedStateFromError(a){return{err:a}}componentDidCatch(a,n){try{this.props.onError(this.props.blockId,this.props.blockType,a,n)}catch{}}render(){return this.state.err?e.jsxs("div",{className:"glyph-block-error",role:"alert",style:{border:"1px solid var(--error, #f85149)",background:"rgba(248, 81, 73, 0.06)",borderRadius:8,padding:"12px 14px",margin:"12px 0",color:"var(--text)",fontFamily:"var(--font-mono, ui-monospace, monospace)",fontSize:12,lineHeight:1.55},children:[e.jsxs("strong",{style:{color:"var(--error, #f85149)",fontFamily:"var(--font-sans, system-ui, sans-serif)",display:"block",marginBottom:4},children:[this.props.blockType," block crashed"]}),e.jsxs("div",{style:{color:"var(--text-muted)",marginBottom:6},children:["block id: ",e.jsx("code",{children:this.props.blockId})]}),e.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word",color:"var(--text)"},children:this.state.err.message})]}):this.props.children}}function jl(s){const t=s.data??{};switch(s.type){case"RichText":return{ok:!0};case"Callout":return{ok:!0};case"Checklist":return Array.isArray(t.items)?{ok:!0}:{ok:!1,error:"Checklist requires data.items to be an array"};case"Table":return Array.isArray(t.columns)?Array.isArray(t.rows)?t.rows.length>0&&!Array.isArray(t.rows[0])?{ok:!1,error:"Table.data.rows[0] must be an array (cell array)"}:{ok:!0}:{ok:!1,error:"Table requires data.rows to be an array"}:{ok:!1,error:"Table requires data.columns to be an array"};case"CodeTabs":return Array.isArray(t.tabs)?{ok:!0}:{ok:!1,error:"CodeTabs requires data.tabs to be an array"};case"Decision":return Array.isArray(t.options)?{ok:!0}:{ok:!1,error:"Decision requires data.options to be an array"};case"OpenQuestions":return Array.isArray(t.questions)?{ok:!0}:{ok:!1,error:"OpenQuestions requires data.questions to be an array"};case"FileTree":if(!Array.isArray(t.entries))return{ok:!1,error:"FileTree requires data.entries to be an array"};for(const a of t.entries)if(a===null||typeof a!="object"||Array.isArray(a))return{ok:!1,error:`FileTree contains a malformed entry: ${JSON.stringify(a)}`};return{ok:!0};case"Diff":return typeof t.before!="string"?{ok:!1,error:"Diff requires data.before to be a string"}:typeof t.after!="string"?{ok:!1,error:"Diff requires data.after to be a string"}:{ok:!0};case"Stat":return t.label===void 0||t.label===null?{ok:!1,error:"Stat requires data.label"}:t.value===void 0||t.value===null?{ok:!1,error:"Stat requires data.value"}:{ok:!0};case"Workflow":return Array.isArray(t.steps)?{ok:!0}:{ok:!1,error:"Workflow requires data.steps to be an array"};case"Mockup":return typeof t.html!="string"?{ok:!1,error:"Mockup requires data.html to be a string"}:{ok:!0};case"Diagram":return typeof t.dataHtml!="string"?{ok:!1,error:"Diagram requires data.dataHtml to be a string"}:{ok:!0};default:return{ok:!1,error:`Unknown block type: ${s.type}`}}}const vl={overview:"Overview",implementation:"Implementation plan","implementation-plan":"Implementation plan",questions:"Open questions","open-questions":"Open questions","open-questions-for-you":"Open questions",comments:"Comments",handoff:"Handoff"};function bl(s){const t=[];let a={heading:null,blocks:[]};for(const n of s){const i=vl[n.id]??null;i?((a.blocks.length>0||a.heading!==null)&&t.push(a),a={heading:i,blocks:[n]}):a.blocks.push(n)}return(a.blocks.length>0||a.heading!==null)&&t.push(a),t}function yl({slug:s,onClose:t,onCommentAdded:a}){var I,V,ie,de;const n=ce(),[i,l]=r.useState(null),[o,c]=r.useState([]),[u,x]=r.useState(!0),[h,m]=r.useState(null),[d,p]=r.useState(null),[f,b]=r.useState(!1),[k,w]=r.useState(!1),[v,C]=r.useState(null),[z,y]=r.useState(null),[R,S]=r.useState(""),[N,P]=r.useState(null),[g,j]=r.useState([]),T=Ke.useCallback((O,Q,re)=>{j(xe=>xe.some(fe=>fe.blockId===O)?xe:[...xe,{blockId:O,blockType:Q,message:re.message||String(re)}])},[]),F=r.useRef(null),A=r.useMemo(()=>i?bl(i.blocks):[],[i]);r.useEffect(()=>{let O=!1;const Q=5e3;return(async()=>{x(!0),m(null);try{const re=new Promise((H,q)=>setTimeout(()=>q(new Error("Request timed out after 5s")),Q)),[xe,fe]=await Promise.race([Promise.all([$.get(`/artifacts/${encodeURIComponent(s)}/render`),$.get(`/artifacts/${encodeURIComponent(s)}`)]),re]);if(O)return;l(xe);const L=(fe==null?void 0:fe.comments)??[];c(Array.isArray(L)?L:[])}catch(re){if(!O){const xe=re.message;m(xe),p(xe)}}finally{O||x(!1)}})(),()=>{O=!0}},[s]);function U(O){if(!F.current)return;O.preventDefault();const Q=F.current.getBoundingClientRect();C({x:O.clientX,y:O.clientY,worldX:O.clientX-Q.left,worldY:O.clientY-Q.top})}async function Y(){if(!(!z||!R.trim()))try{const O=await $.post(`/artifacts/${encodeURIComponent(s)}/comments`,{x:z.worldX,y:z.worldY,text:R.trim(),author:"drb0rk"});c(Q=>[...Q,{id:O.id??`cmt_${Date.now()}`,x:z.worldX,y:z.worldY,text:R.trim(),author:"drb0rk",created:new Date().toISOString()}]),y(null),S(""),C(null),a==null||a(),n.success("Comment added")}catch(O){n.error(`Failed to add comment: ${O.message}`)}}async function B(){if(!f){b(!0);try{const O=await $.post(`/artifacts/${encodeURIComponent(s)}/submit`,{answers:[],submitter:"drb0rk"});O!=null&&O.ok?(n.success("Sent to agent — feedback.md written, status=review"),a==null||a()):n.error("Submit failed: server did not return ok=true")}catch(O){n.error(`Submit failed: ${O.message}`)}finally{b(!1)}}}function K(){w(O=>!O)}const D=O=>{const Q=O.id,re=O.data??{},xe=jl(O);return xe.ok?e.jsx(fl,{blockId:Q,blockType:O.type,onError:T,children:_(O,Q,re)},Q):e.jsxs("div",{id:Q,className:"glyph-block-error",role:"alert",style:{border:"1px solid var(--error, #f85149)",background:"rgba(248, 81, 73, 0.06)",borderRadius:8,padding:"12px 14px",margin:"12px 0",color:"var(--text)",fontFamily:"var(--font-mono, ui-monospace, monospace)",fontSize:12,lineHeight:1.55},children:[e.jsxs("strong",{style:{color:"var(--error, #f85149)",fontFamily:"var(--font-sans, system-ui, sans-serif)",display:"block",marginBottom:4},children:[O.type," block invalid"]}),e.jsxs("div",{style:{color:"var(--text-muted)",marginBottom:6},children:["block id: ",e.jsx("code",{children:Q})]}),e.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:xe.error})]},Q)},_=(O,Q,re)=>{switch(O.type){case"RichText":return e.jsx(Zr,{id:Q,children:O.childrenMarkdown??""},Q);case"Callout":return e.jsx(sl,{id:Q,tone:re.tone??"info",children:O.childrenMarkdown??""},Q);case"Checklist":return e.jsx(tl,{id:Q,items:re.items??[]},Q);case"Table":return e.jsx(al,{id:Q,columns:re.columns??[],rows:re.rows??[]},Q);case"CodeTabs":return e.jsx(nl,{id:Q,tabs:re.tabs??[]},Q);case"Decision":return e.jsx(il,{id:Q,title:re.title,question:re.question,options:re.options??[]},Q);case"OpenQuestions":return e.jsx(rl,{id:Q,questions:re.questions??[]},Q);case"FileTree":return e.jsx(cl,{id:Q,title:re.title,entries:re.entries??[]},Q);case"Diff":return e.jsx(ol,{id:Q,filename:re.filename,language:re.language,mode:re.mode??"unified",before:re.before??"",after:re.after??""},Q);case"Stat":return e.jsx(ml,{id:Q,label:re.label??"",value:re.value,trend:re.trend,hint:re.hint},Q);case"Workflow":return e.jsx(hl,{id:Q,steps:re.steps??[],connections:re.connections},Q);case"Mockup":return e.jsx(gl,{id:Q,title:re.title,x:re.x,y:re.y,w:re.w,h:re.h,html:re.html??""},Q);case"Diagram":return e.jsx("div",{id:Q,className:"glyph-block-placeholder",children:e.jsxs("em",{children:["[Diagram] ",Q]})},Q)}};if(u)return e.jsx("div",{className:"glyph-renderer glyph-renderer--loading",children:d?e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:"Failed to load glyph."}),e.jsx("pre",{children:d})]}):e.jsxs(e.Fragment,{children:[e.jsx(Nl,{})," Loading glyph…"]})});if(h||!i)return e.jsxs("div",{className:"glyph-renderer glyph-renderer--error",children:[e.jsx("strong",{children:"Failed to load glyph."}),e.jsx("pre",{children:h??"unknown error"})]});const ae=((I=i.frontmatter)==null?void 0:I.title)??s,J=((V=i.frontmatter)==null?void 0:V.status)??"draft",ne=o.length;return e.jsxs("div",{className:`glyph-canvas ${k?"glyph-canvas--fullscreen":""}`,ref:F,onContextMenu:U,children:[e.jsxs("div",{className:"glyph-toolbar-floating",children:[e.jsxs("button",{className:"glyph-btn glyph-btn--primary glyph-btn--send",onClick:B,disabled:f,title:"Send comments + question answers to the agent — writes feedback.md, status=review",children:[e.jsx(rs,{size:14}),e.jsx("span",{children:"Send to agent"}),e.jsx("span",{className:"glyph-btn-badge",children:ne})]}),e.jsx("span",{className:"glyph-toolbar-divider"}),e.jsx("button",{className:"glyph-icon-btn",title:"Share",onClick:()=>{typeof window<"u"&&navigator.clipboard&&(navigator.clipboard.writeText(window.location.href).catch(()=>{}),n.success("Link copied"))},children:e.jsx(Gn,{size:15})}),e.jsx("button",{className:"glyph-icon-btn",title:"Undo",disabled:!0,children:e.jsx(Hn,{size:15})}),e.jsx("button",{className:"glyph-icon-btn",title:"Redo",disabled:!0,children:e.jsx(Kn,{size:15})}),e.jsx("button",{className:"glyph-icon-btn",title:k?"Exit fullscreen":"Fullscreen",onClick:K,children:e.jsx(Yn,{size:15})}),e.jsx("button",{className:"glyph-icon-btn",title:"More",children:e.jsx(Xn,{size:15})}),e.jsx("span",{className:"glyph-toolbar-divider"}),e.jsxs("button",{className:"glyph-icon-btn",title:"Comment count","aria-label":"Comment count",children:[e.jsx(Js,{size:15}),e.jsx("span",{className:"glyph-icon-btn-count",children:ne})]}),t&&e.jsx("button",{className:"glyph-icon-btn glyph-icon-btn--close",title:"Close",onClick:t,"aria-label":"Close",children:e.jsx(we,{size:15})})]}),e.jsxs("div",{className:"glyph-canvas-content",children:[e.jsxs("header",{className:"glyph-canvas-title",children:[e.jsx("h1",{className:"glyph-title",children:ae}),e.jsxs("div",{className:"glyph-meta",children:[e.jsx("span",{className:`glyph-status glyph-status--${J}`,children:J}),e.jsx("span",{className:"glyph-slug",children:s})]})]}),(g.length>0||((ie=i.errors)==null?void 0:ie.length)>0)&&e.jsxs("div",{className:"glyph-render-errors",role:"alert",style:{border:"1px solid var(--error, #f85149)",background:"rgba(248, 81, 73, 0.08)",borderRadius:8,padding:"12px 16px",margin:"0 0 16px 0",color:"var(--text)"},children:[e.jsx("strong",{style:{color:"var(--error, #f85149)",display:"block",marginBottom:8},children:g.length>0?`${g.length} block${g.length===1?"":"s"} failed to render`:"Compiler warnings"}),e.jsxs("ul",{style:{margin:0,paddingLeft:20,fontFamily:"var(--font-mono, ui-monospace, monospace)",fontSize:12,lineHeight:1.6},children:[g.map((O,Q)=>e.jsxs("li",{children:[e.jsx("strong",{children:O.blockType})," (",e.jsx("code",{children:O.blockId}),"): ",O.message]},`be-${Q}`)),(de=i.errors)==null?void 0:de.map((O,Q)=>e.jsxs("li",{children:[O.line?`line ${O.line}: `:"",O.message]},`ce-${Q}`))]})]}),e.jsx("div",{className:"glyph-sections",children:A.map((O,Q)=>e.jsxs("section",{className:`glyph-section ${O.heading?"glyph-section--headed":"glyph-section--plain"}`,children:[O.heading&&e.jsx("h2",{className:"glyph-section-heading",children:O.heading}),e.jsx("div",{className:"glyph-section-blocks",children:O.blocks.map(D)})]},`sec-${Q}-${O.heading??"ungrouped"}`))})]}),o.map(O=>e.jsxs("button",{className:`glyph-pin ${N===O.id?"glyph-pin--active":""}`,style:{left:O.x,top:O.y},onClick:Q=>{Q.stopPropagation(),P(N===O.id?null:O.id)},title:O.text,children:[e.jsx(da,{size:14}),N===O.id&&e.jsxs("div",{className:"glyph-pin-thread",children:[e.jsx("div",{className:"glyph-pin-text",children:O.text}),e.jsxs("div",{className:"glyph-pin-meta",children:[O.author??"anonymous"," · ",O.created?new Date(O.created).toLocaleString():""]})]})]},O.id)),v&&e.jsx("div",{className:"glyph-ctx-menu",style:{left:v.x,top:v.y},onClick:O=>O.stopPropagation(),children:e.jsxs("button",{className:"glyph-ctx-item",onClick:()=>{y({worldX:v.worldX,worldY:v.worldY}),C(null)},children:[e.jsx(da,{size:14})," Add comment here"]})}),z&&e.jsx("div",{className:"glyph-modal-overlay",onClick:()=>y(null),children:e.jsxs("div",{className:"glyph-modal",onClick:O=>O.stopPropagation(),children:[e.jsxs("h3",{children:["Add comment at (",Math.round(z.worldX),", ",Math.round(z.worldY),")"]}),e.jsx("textarea",{autoFocus:!0,value:R,onChange:O=>S(O.target.value),placeholder:"What should the agent know about this area?",rows:4,className:"glyph-modal-textarea"}),e.jsxs("div",{className:"glyph-modal-actions",children:[e.jsx("button",{className:"glyph-btn glyph-btn--ghost",onClick:()=>y(null),children:"Cancel"}),e.jsx("button",{className:"glyph-btn glyph-btn--primary",onClick:Y,disabled:!R.trim(),children:"Add comment"})]})]})})]})}function Nl(){return e.jsx("span",{className:"glyph-spinner","aria-label":"loading",children:"…"})}function Ne({icon:s,title:t,message:a,action:n,className:i}){return e.jsxs("div",{className:W("empty-state",i),children:[e.jsx("div",{className:"empty-icon",children:s??e.jsx(gt,{size:32})}),e.jsx("div",{className:"empty-title",children:t}),a&&e.jsx("div",{className:"empty-message",children:a}),n&&e.jsx("div",{className:"empty-action",children:n})]})}function kl(s){return s==="ok"?"success":s==="warn"?"warning":s==="fail"?"error":s}function yt({kind:s="neutral",children:t,className:a,dot:n=!1}){const i=kl(s);return e.jsxs("span",{className:W("badge",`badge-${i}`,a),title:`status: ${s}`,children:[n&&e.jsx("span",{className:"badge-dot"}),t]})}function wl(s){switch(s){case"approved":case"done":return"success";case"in-progress":case"doing":return"info";case"rejected":return"error";case"archived":return"warning";case"draft":default:return"neutral"}}function Sl({snapshot:s,refreshSnapshot:t}){const a=ce(),[n,i]=r.useState(s.artifacts||[]),[l,o]=r.useState(!s.artifacts),[c,u]=r.useState(null),[x,h]=r.useState(""),[m,d]=r.useState(!1);r.useEffect(()=>{s.artifacts&&(i(s.artifacts),o(!1))},[s.artifacts]);const p=async()=>{try{const w=await $.get("/artifacts");i(w.artifacts||[]),o(!1)}catch(w){a.error(`Artifacts load failed: ${w.message}`),o(!1)}},f=r.useMemo(()=>{let w=n;if(x){const v=x.toLowerCase();w=w.filter(C=>(C.slug||"").toLowerCase().includes(v)||(C.title||"").toLowerCase().includes(v))}return m||(w=w.filter(v=>v.status!=="archived")),w},[n,x,m]),b=async(w,v)=>{try{const C=await $.post("/artifacts",{slug:w,title:v});a.success(`Artifact "${C.slug}" created.`),u(C.slug),await p()}catch(C){a.error(`Create failed: ${C.message}`)}},k=async w=>{if(confirm(`Delete artifact "${w}"? This removes the directory permanently.`))try{await $.del(`/artifacts/${encodeURIComponent(w)}`),a.success("Artifact deleted."),c===w&&u(null),await p()}catch(v){a.error(`Delete failed: ${v.message}`)}};return c?e.jsxs("div",{className:"artifact-glyph-overlay",children:[e.jsx("div",{className:"artifact-glyph-toolbar",children:e.jsxs(M,{variant:"ghost",onClick:()=>{u(null),p()},children:[e.jsx(Ht,{size:14})," Back to artifacts"]})}),e.jsx(yl,{slug:c,onClose:()=>{u(null),p()},onCommentAdded:()=>p()})]}):e.jsxs("div",{className:"view view-artifacts",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(xt,{size:18})," Glyphs (",n.length,")"]}),e.jsx("p",{className:"view-subtitle",children:"Visual artifacts with elements, connections, and threaded comments."})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs("div",{className:"search-input",children:[e.jsx(ke,{size:14,"aria-hidden":!0}),e.jsx("label",{htmlFor:"artifacts-search",className:"sr-only",children:"Search artifacts"}),e.jsx("input",{id:"artifacts-search",className:"input",type:"text",placeholder:"Search…",value:x,onChange:w=>h(w.target.value),"aria-label":"Search artifacts"})]}),e.jsxs(M,{variant:"ghost",size:"sm",onClick:()=>d(w=>!w),title:m?"Hide archived":"Show archived",children:[m?e.jsx(Va,{size:14}):e.jsx(Qn,{size:14}),m?"Hide archived":"Show archived"]}),e.jsxs(M,{variant:"secondary",size:"sm",onClick:p,children:[e.jsx(me,{size:14})," Refresh"]})]})]}),e.jsx(Cl,{onCreate:b}),l?e.jsx("div",{className:"view-loading",children:e.jsx(he,{size:"lg"})}):f.length===0?e.jsx(Ne,{icon:e.jsx(xt,{size:32}),title:m?"No artifacts":"No artifacts yet",message:m?"No artifacts match your filter (try Show archived off).":"Create one above to get started."}):e.jsx("div",{className:"artifacts-grid",children:f.map(w=>e.jsx(zl,{artifact:w,onOpen:()=>u(w.slug),onDelete:()=>k(w.slug)},w.slug))})]})}function Cl({onCreate:s}){const[t,a]=r.useState(""),[n,i]=r.useState("");return e.jsxs(G,{className:"new-artifact",children:[e.jsxs(ee,{children:[e.jsx(Ee,{size:14})," New artifact"]}),e.jsx(te,{children:"Slug must be lowercase, may contain hyphens, 1–64 chars."}),e.jsxs("form",{className:"new-artifact-form",onSubmit:l=>{l.preventDefault(),t.trim()&&(s(t.trim(),n.trim()||void 0),a(""),i(""))},children:[e.jsx("label",{htmlFor:"new-artifact-slug",className:"sr-only",children:"Artifact slug"}),e.jsx("input",{id:"new-artifact-slug",className:"input",type:"text",placeholder:"slug (e.g. dashboard-v3.1)",pattern:"[a-z0-9][a-z0-9-]{0,63}",required:!0,value:t,onChange:l=>a(l.target.value),"aria-label":"Artifact slug"}),e.jsx("label",{htmlFor:"new-artifact-title",className:"sr-only",children:"Artifact title"}),e.jsx("input",{id:"new-artifact-title",className:"input",type:"text",placeholder:"Title (optional)",value:n,onChange:l=>i(l.target.value)}),e.jsx(M,{variant:"primary",type:"submit",children:"Create"})]})]})}function zl({artifact:s,onOpen:t,onDelete:a}){const n=wl(s.status||"draft");return e.jsxs(G,{variant:"elevated",interactive:!0,className:"artifact-card",onClick:t,children:[e.jsxs("div",{className:"artifact-card-head",children:[e.jsx("div",{className:"artifact-card-title",children:s.title||s.slug}),e.jsx(yt,{kind:n,children:s.status||"draft"})]}),e.jsxs("div",{className:"artifact-card-slug mono",children:[s.slug," · ",s.source]}),e.jsxs("div",{className:"artifact-card-meta",children:[s.elementCount!=null&&e.jsxs("span",{children:[s.elementCount," elements"]}),s.commentCount!=null&&e.jsxs("span",{children:[" · ",s.commentCount," comments"]}),e.jsxs("span",{children:[" · edited ",Te(s.mtime)]})]}),e.jsxs("div",{className:"artifact-card-actions",children:[e.jsxs(M,{variant:"primary",size:"sm",onClick:i=>{i.stopPropagation(),t()},children:["Open",e.jsx(ds,{size:12})]}),e.jsxs(M,{variant:"ghost",size:"sm",onClick:i=>{i.stopPropagation(),a()},children:[e.jsx(Re,{size:12})," Delete"]})]})]})}function $l({task:s,agents:t,onPromote:a,onDelete:n,onEdit:i,onRefresh:l}){var h;const o=ce(),c=async()=>{try{await $.post(`/tasks/${encodeURIComponent(s.id)}/promote`),o.success("Promoted to queued.",1500),a(s.id)}catch(m){o.error(`Promote failed: ${m.message}`)}},u=async()=>{if(confirm("Delete this task?"))try{await $.del(`/tasks/${encodeURIComponent(s.id)}`),o.success("Deleted.",1500),n(s.id)}catch(m){o.error(`Delete failed: ${m.message}`)}},x={high:"var(--warning)",normal:"var(--info)",low:"var(--muted)"};return e.jsxs("div",{className:"backlog-item","data-task-id":s.id,children:[e.jsxs("div",{className:"backlog-item-head",children:[e.jsx("span",{className:"priority-dot",style:{background:x[s.priority]||"var(--info)"}}),e.jsx("span",{className:"backlog-item-title",children:s.title}),s.assignee&&e.jsxs("span",{className:"backlog-item-badge",children:["@",s.assignee]}),((h=s.tags)==null?void 0:h.length)>0&&e.jsx("span",{className:"backlog-item-badge",children:s.tags.join(", ")})]}),s.description&&e.jsx("div",{className:"backlog-item-desc",children:s.description.slice(0,120)}),e.jsxs("div",{className:"backlog-item-footer",children:[e.jsx("span",{className:"muted text-sm tabular-nums",children:Te(s.createdAt)}),e.jsxs("div",{className:"backlog-item-actions",children:[e.jsx("button",{type:"button",className:"icon-btn",title:"Promote to queued",onClick:c,children:e.jsx(Zs,{size:13})}),e.jsx("button",{type:"button",className:"icon-btn",title:"Edit",onClick:()=>i(s),children:e.jsx(es,{size:13})}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger",title:"Delete",onClick:u,children:e.jsx(Re,{size:13})})]})]})]})}function Rl({agents:s,onRefresh:t}){const a=ce(),[n,i]=r.useState([]),[l,o]=r.useState(!1),c=async()=>{try{o(!0);const d=await $.get("/tasks/backlog");i(Array.isArray(d.tasks)?d.tasks:[])}catch(d){a.error(`Backlog load failed: ${d.message}`)}finally{o(!1)}};r.useEffect(()=>{c()},[]);const u=async d=>{i(p=>p.filter(f=>f.id!==d)),await t()},x=async d=>{i(p=>p.filter(f=>f.id!==d)),await t()},h=d=>{},m=async()=>{var d;if(n.length!==0)try{const f=((d=(await $.post("/tasks/promote-batch",{ids:n.map(b=>b.id)})).affected)==null?void 0:d.filter(b=>b.ok).length)??0;a.success(`Promoted ${f} task(s).`,2e3),i([]),await t()}catch(p){a.error(`Promote all failed: ${p.message}`)}};return e.jsxs("div",{className:"backlog-panel",children:[e.jsxs("div",{className:"backlog-panel-header",children:[e.jsxs("span",{className:"backlog-panel-title",children:[e.jsx(gt,{size:15}),"Backlog (",n.length,")"]}),e.jsxs("div",{className:"backlog-panel-header-actions",children:[n.length>0&&e.jsxs(M,{variant:"ghost",size:"sm",onClick:m,title:"Promote all to queued",children:[e.jsx(Zs,{size:12})," Promote all"]}),e.jsx(M,{variant:"ghost",size:"sm",onClick:c,title:"Refresh backlog","aria-label":"Refresh backlog",children:e.jsx(me,{size:12,className:l?"animate-spin":""})})]})]}),l?e.jsx("div",{className:"backlog-empty",children:"Loading…"}):n.length===0?e.jsxs("div",{className:"backlog-empty",children:[e.jsx(gt,{size:28}),e.jsx("span",{children:"Backlog is empty."})]}):e.jsx("div",{className:"backlog-list",children:n.map(d=>e.jsx($l,{task:d,agents:s,onPromote:u,onDelete:x,onEdit:h,onRefresh:t},d.id))})]})}const Tl=[{id:"queued",label:"Todo",kind:"info",dotVariant:"info"},{id:"doing",label:"In progress",kind:"accent",dotVariant:"info"},{id:"done",label:"Done",kind:"success",dotVariant:"success"},{id:"blocked",label:"Failed",kind:"error",dotVariant:"danger"}],Nt=["low","normal","high"],Al=[{value:"",label:"All"},...Nt.map(s=>({value:s,label:s}))],Ml={info:"info",accent:"accent",success:"success",warning:"warning",error:"danger"},Il={high:"danger",normal:"info",low:"neutral"};function El({snapshot:s,refreshSnapshot:t}){const a=ce(),n=Pe(),[i,l]=r.useState(s.tasks||[]),[o,c]=r.useState(!s.tasks),[u,x]=r.useState(""),[h,m]=r.useState(""),[d,p]=r.useState(!1),[f,b]=r.useState(0),[k,w]=r.useState(""),v=async()=>{try{const g=await $.get("/tasks");l(Array.isArray(g)?g:[])}catch(g){a.error(`Tasks load failed: ${g.message}`)}finally{c(!1)}};r.useEffect(()=>{s.tasks&&(l(s.tasks),c(!1))},[s.tasks]),r.useEffect(()=>{const g=setInterval(()=>b(j=>j+1),3e4);return()=>clearInterval(g)},[]);const C=r.useMemo(()=>{let g=i.filter(j=>j.status!=="backlog");if(h&&(g=g.filter(j=>(j.priority||"normal")===h)),u.trim()){const j=u.toLowerCase();g=g.filter(T=>(T.title||"").toLowerCase().includes(j)||(T.description||"").toLowerCase().includes(j))}return g},[i,u,h]),z=r.useMemo(()=>{const g={high:0,normal:1,low:2};return[...C].sort((j,T)=>{const F=g[j.priority]??1,A=g[T.priority]??1;return F!==A?F-A:new Date(T.createdAt).getTime()-new Date(j.createdAt).getTime()})},[C]),y=i.filter(g=>g.status==="backlog").length,R=async g=>{if(confirm("Delete this task?"))try{await $.del(`/tasks/${encodeURIComponent(g)}`),l(j=>j.filter(T=>T.id!==g)),a.success("Task deleted.",1200)}catch(j){a.error(`Delete failed: ${j.message}`)}},S=async g=>{try{const j=await $.post(`/tasks/${encodeURIComponent(g)}/start`);j&&j.task&&l(T=>T.map(F=>F.id===g?j.task:F)),a.success("Retry dispatched.",1200)}catch(j){a.error(`Retry failed: ${j.message}`)}},N=async g=>{const j=i.find(T=>T.id===g);if(j)try{const T=await $.post("/tasks/submit",{title:j.title,description:j.description,priority:j.priority,tags:j.tags}),F=(T.subtasks||[]).length;a.success(F>1?`Odin split it into ${F} subtasks.`:"Sent to Odin.",1500),T.subtasks&&T.subtasks.length>0&&l(A=>[T.main,...T.subtasks,...A.filter(U=>U.id!==j.id)]),await t()}catch(T){a.error(`Submit failed: ${T.message}`)}},P=g=>{Na(n,a,g,l,v,t)};return e.jsxs("div",{className:"view view-tasks tasks-wave3",children:[e.jsx("div",{className:"sr-only",role:"status","aria-live":"polite",children:k}),e.jsx("header",{className:"tasks-wave3__header",children:e.jsxs("div",{children:[e.jsxs("h2",{className:"tasks-wave3__title-row",children:[e.jsx(ps,{size:18,"aria-hidden":!0})," Tasks (",z.length,")"]}),e.jsx("p",{className:"tasks-wave3__subtitle",children:"Add a task — title and description is all you need. Odin picks the agent and priority."})]})}),e.jsxs("div",{className:"tasks-wave3__toolbar",role:"toolbar","aria-label":"Task filters",children:[e.jsx("div",{className:"tasks-wave3__toolbar-group",children:e.jsx(pr,{inputSize:"sm",value:u,onChange:g=>x(String(g)),placeholder:"Search…","aria-label":"Search tasks"})}),e.jsxs("div",{className:"tasks-wave3__toolbar-group",children:[e.jsx("span",{className:"tasks-wave3__toolbar-label",id:"tasks-priority-filter-label",children:"Priority"}),e.jsx(xr,{inputSize:"sm","aria-labelledby":"tasks-priority-filter-label",options:Al,value:h,onChange:g=>m(g.target.value)})]}),e.jsx("div",{className:"tasks-wave3__toolbar-spacer"}),e.jsxs("div",{className:"tasks-wave3__toolbar-group",children:[e.jsx(M,{variant:"ghost",size:"sm",onClick:v,title:"Refresh","aria-label":"Refresh tasks",children:e.jsx(me,{size:14,"aria-hidden":!0})}),y>0&&e.jsxs(M,{variant:d?"accent":"ghost",size:"sm",onClick:()=>p(g=>!g),title:d?"Hide backlog":"Show backlog",children:[e.jsx(gt,{size:14,"aria-hidden":!0}),"Backlog",e.jsx("span",{className:"tasks-wave3__column-count","aria-label":`${y} items`,children:y})]}),e.jsxs(M,{variant:"primary",size:"sm",onClick:()=>Dl(n,a,l,v,t),children:[e.jsx(Ee,{size:14,"aria-hidden":!0})," New task"]})]})]}),d&&y>0&&e.jsx(Rl,{agents:s.agents||[],onRefresh:t}),o?e.jsx(ia,{label:"Loading tasks…"}):e.jsx(Vt,{cols:5,gap:3,className:"tasks-wave3__kanban",children:Tl.map(g=>{const j=z.filter(T=>T.status===g.id);return e.jsx(ts,{padding:3,className:"tasks-wave3__column",title:e.jsxs("span",{className:"tasks-wave3__column-title",children:[e.jsx(Qs,{variant:g.dotVariant,size:"sm",label:g.label}),g.label]}),actions:e.jsx("span",{className:"tasks-wave3__column-count","aria-label":`${j.length} tasks`,children:j.length}),children:e.jsx(Be,{gap:2,className:"tasks-wave3__column-body",children:j.length===0?e.jsx("div",{className:"tasks-wave3__column-empty",children:"No tasks"}):j.map(T=>e.jsx(Ll,{task:T,column:g,onTaskClick:P,onEdit:()=>Na(n,a,T,l,v,t),onDelete:()=>R(T.id),onRetry:()=>S(T.id),onSubmitToOdin:()=>N(T.id),tick:f},T.id))})},g.id)})})]})}function Ll({task:s,column:t,onTaskClick:a,onEdit:n,onDelete:i,onRetry:l,onSubmitToOdin:o,tick:c}){const u=s.workedBy||s.assignee||null,x=Nt.includes(s.priority)?s.priority:"normal";return e.jsxs("div",{className:oe("tasks-wave3__row"),"data-task-id":s.id,"data-tick":c,role:"button",tabIndex:0,onClick:()=>a(s),onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),a(s))},children:[e.jsxs("div",{className:"tasks-wave3__row-title-row",children:[e.jsx("div",{className:"tasks-wave3__row-title",title:s.title,children:s.title}),e.jsx(Xe,{variant:Ml[t.kind],size:"sm","aria-label":`Status ${t.label}`,children:t.label})]}),e.jsxs($e,{gap:1,align:"center",className:"tasks-wave3__row-badges",children:[e.jsx(Xe,{variant:Il[x],size:"sm",children:x}),u&&e.jsxs(Xe,{variant:"neutral",size:"sm",children:[e.jsx(Qe,{size:10,"aria-hidden":!0})," @",u]}),(s.tags||[]).slice(0,2).map(h=>e.jsxs(Xe,{variant:"neutral",size:"sm",children:["#",h]},h))]}),e.jsxs("div",{className:"tasks-wave3__row-footer",children:[e.jsx("span",{className:"tasks-wave3__row-time",children:Te(s.createdAt)}),e.jsxs($e,{gap:1,align:"center",className:"tasks-wave3__row-actions",onClick:h=>h.stopPropagation(),children:[e.jsx(zs,{variant:"ghost",size:"sm",icon:e.jsx(Jn,{size:12,"aria-hidden":!0}),"aria-label":"Edit task",title:"Edit",onClick:n}),e.jsx(zs,{variant:"ghost",size:"sm",icon:e.jsx(rs,{size:12,"aria-hidden":!0}),"aria-label":"Submit to Odin",title:"Re-delegate to Odin",onClick:o}),e.jsx(zs,{variant:"ghost",size:"sm",icon:e.jsx(bt,{size:12,"aria-hidden":!0}),"aria-label":"Retry task",title:"Retry",onClick:l}),e.jsx(zs,{variant:"danger",size:"sm",icon:e.jsx(Re,{size:12,"aria-hidden":!0}),"aria-label":"Delete task",title:"Delete",onClick:i})]})]})]})}function Dl(s,t,a,n,i){let l=null,o=null,c=null,u=null;const x=async m=>{m&&typeof m.preventDefault=="function"&&m.preventDefault();const d=((l==null?void 0:l.value)||"").trim(),p=((o==null?void 0:o.value)||"").trim();if(!d){t.warning("Title is required."),l==null||l.focus();return}const f=(u==null?void 0:u.value)||"normal",b=((c==null?void 0:c.value)||"").split(",").map(k=>k.trim()).filter(Boolean);try{const k=await $.post("/tasks",{title:d,description:p,priority:f,tags:b});s.close(),typeof window<"u"&&window.dispatchEvent(new MouseEvent("mousedown")),a(w=>[k,...w]),t.success("Task created.",1200),await i()}catch(k){t.error(`Create failed: ${k.message}`)}},h=m=>{m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),x(m))};s.open({title:"New task",width:520,children:e.jsxs("div",{className:"task-form",children:[e.jsx("label",{className:"field-label",htmlFor:"task-title",children:"Title *"}),e.jsx("input",{ref:m=>{l=m},id:"task-title",className:"input",type:"text",maxLength:200,placeholder:"What needs to be done?",autoFocus:!0,onKeyDown:h}),e.jsx("label",{className:"field-label",htmlFor:"task-desc",children:"Description"}),e.jsxs("div",{style:{display:"flex",gap:6,alignItems:"flex-start"},children:[e.jsx("textarea",{ref:m=>{o=m},id:"task-desc",className:"textarea",rows:4,placeholder:"Add any context Odin might need (markdown ok)…",style:{flex:1}}),e.jsx("button",{type:"button",className:"btn btn-ghost btn-icon",title:"Enhance with AI",onClick:async()=>{var d;if(!((d=o==null?void 0:o.value)!=null&&d.trim()))return;const m=await bn(o.value);m!==o.value&&(o.value=m)},children:"✨"})]}),e.jsxs("div",{className:"task-form-row",children:[e.jsxs("label",{htmlFor:"task-priority",className:"task-form-field",children:["Priority hint",e.jsx("select",{ref:m=>{u=m},id:"task-priority",className:"select",defaultValue:"normal",children:Nt.map(m=>e.jsx("option",{value:m,children:m},m))})]}),e.jsxs("label",{htmlFor:"task-tags",className:"task-form-field",style:{flex:2},children:["Tags ",e.jsx("span",{className:"field-hint",children:"(comma-separated)"}),e.jsx("input",{ref:m=>{c=m},id:"task-tags",className:"input",type:"text",placeholder:"bug, frontend, urgent"})]})]}),e.jsx("p",{className:"muted text-sm",style:{marginTop:8},children:"The agent and final priority are decided by Odin after you submit."})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx(M,{variant:"ghost",onClick:()=>s.close(),children:"Cancel"}),e.jsxs(M,{variant:"primary",type:"button",onClick:m=>x(m),children:[e.jsx(Ee,{size:14})," Create task"]})]})})}function Na(s,t,a,n,i,l){let o=null,c=null,u=null,x=null;const h=async()=>{const m=((o==null?void 0:o.value)||"").trim(),d=((c==null?void 0:c.value)||"").trim();if(!m){t.warning("Title is required."),o==null||o.focus();return}const p=(x==null?void 0:x.value)||"normal",f=((u==null?void 0:u.value)||"").split(",").map(b=>b.trim()).filter(Boolean);try{const b=await $.put(`/tasks/${encodeURIComponent(a.id)}`,{title:m,description:d,priority:p,tags:f});s.close(),typeof window<"u"&&window.dispatchEvent(new MouseEvent("mousedown")),n(k=>k.map(w=>w.id===a.id?b:w)),t.success("Task updated.",1200),await l()}catch(b){t.error(`Save failed: ${b.message}`)}};s.open({title:"Edit task",width:520,children:e.jsxs("div",{className:"task-form",children:[e.jsx("label",{className:"field-label",htmlFor:"edit-task-title",children:"Title *"}),e.jsx("input",{ref:m=>{o=m},id:"edit-task-title",className:"input",type:"text",maxLength:200,defaultValue:a.title,autoFocus:!0}),e.jsx("label",{className:"field-label",htmlFor:"edit-task-desc",children:"Description"}),e.jsx("textarea",{ref:m=>{c=m},id:"edit-task-desc",className:"textarea",rows:4,defaultValue:a.description||""}),e.jsxs("div",{className:"task-form-row",children:[e.jsxs("label",{htmlFor:"edit-task-priority",className:"task-form-field",children:["Priority hint",e.jsx("select",{ref:m=>{x=m},id:"edit-task-priority",className:"select",defaultValue:a.priority||"normal",children:Nt.map(m=>e.jsx("option",{value:m,children:m},m))})]}),e.jsxs("label",{htmlFor:"edit-task-tags",className:"task-form-field",style:{flex:2},children:["Tags",e.jsx("input",{ref:m=>{u=m},id:"edit-task-tags",className:"input",type:"text",defaultValue:(a.tags||[]).join(", "),placeholder:"comma-separated"})]})]}),e.jsxs(G,{children:[e.jsxs(ee,{children:[e.jsx(Zn,{size:12})," Status"]}),e.jsxs(te,{children:["Current: ",e.jsx("strong",{children:a.status}),a.workedBy&&e.jsxs(e.Fragment,{children:[" · Worked by @",a.workedBy]}),a.assignee&&!a.workedBy&&e.jsxs(e.Fragment,{children:[" · Assigned @",a.assignee]})]})]})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx(M,{variant:"ghost",onClick:()=>s.close(),children:"Cancel"}),e.jsxs(M,{variant:"primary",onClick:h,children:[e.jsx(Va,{size:14})," Save"]})]})})}const _l=Ke.memo(El);function Pl(s){return $.urlWithToken(`/artifacts/${encodeURIComponent(s)}/content`)}function Fl(s,t){const a=Pl(t);window.open(a,"_blank","noopener,noreferrer")}const ka={"1m":60*1e3,"5m":5*60*1e3,"30m":30*60*1e3,"1h":60*60*1e3},Oe=56,ss=32,ws=22,Ol=4,Bl=.9,Rt={working:"var(--success)",running:"var(--success)",doing:"var(--info)",queued:"var(--info)",done:"var(--success)",success:"var(--success)",blocked:"var(--warning)",error:"var(--error)",failed:"var(--error)",stuck:"var(--warning)",killed:"var(--error)",idle:"var(--text-dim)",pending:"var(--info)",timed_out:"var(--warning)"};function Tt(s){return s&&Rt[s]||Rt.idle}function it(s,t=24){return s?s.length<=t?s:s.slice(0,t-1)+"…":""}function jt(s){if(s==null)return 0;if(typeof s=="number")return s;const t=new Date(s).getTime();return Number.isNaN(t)?0:t}function At(s){const t=s._timerStart;return typeof t=="number"&&t>0?t:jt(s.createdAt)||Date.now()}function Ul(s,t){return(s.status==="done"||s.status==="archived"||s.status==="failed"||s.status==="killed")&&(jt(s.completedAt)||jt(s.updatedAt))||t}function Vl(s){return typeof s.startedAt=="number"&&s.startedAt>0?s.startedAt:Date.now()}function Wl(s,t){return(s.status==="done"||s.status==="success"||s.status==="killed"||s.status==="failed"||s.status==="error"||s.status==="timed_out")&&(s.completedAt||s.lastEventAt)||t}function ql(s){return s<=6e4?1e4:s<=3e5?3e4:s<=18e5?3e5:6e5}function Gl(s,t){const a=new Date(s);return t<=3e5?a.toLocaleTimeString("en-GB",{hour12:!1}):a.toLocaleTimeString("en-GB",{hour12:!1,hour:"2-digit",minute:"2-digit"})}function Hl({snapshot:s,refreshSnapshot:t}){const a=ce(),n=r.useRef(null),[i,l]=r.useState("live"),[o,c]=r.useState("5m"),[u,x]=r.useState(()=>typeof window>"u"?!0:window.innerWidth>900),[h,m]=r.useState([]),[d,p]=r.useState([]),[f,b]=r.useState(!0),[k,w]=r.useState(0),[v,C]=r.useState(Date.now()),[z,y]=r.useState(()=>Date.now()-ka["5m"]*.1),[R,S]=r.useState({width:800,height:400}),[N,P]=r.useState(null),[g,j]=r.useState(""),[T,F]=r.useState([]),[A,U]=r.useState(""),[Y,B]=r.useState("normal"),[K,D]=r.useState(""),[_,ae]=r.useState(""),[J,ne]=r.useState(!1),[I,V]=r.useState(!1),[ie,de]=r.useState([]),O=Pe(),Q=s.agents||[],re=s.tasks||[],xe=ka[o],fe=z,L=z+xe,H=r.useCallback(async()=>{try{const[E,X]=await Promise.all([$.get("/background").catch(()=>({instances:[]})),$.get("/activity?limit=200").catch(()=>({events:[]}))]);m(E.instances||[]),p(X.events||[])}catch(E){is.warn("activity reload failed:",E)}finally{b(!1)}},[]);r.useEffect(()=>{H();const E=setInterval(H,3e3);return()=>clearInterval(E)},[H]),r.useEffect(()=>{w(E=>E+1)},[re.length,Q.length]),r.useEffect(()=>{if(i==="pause")return;C(Date.now());const E=setInterval(()=>C(Date.now()),1e3);return()=>clearInterval(E)},[i,k]),r.useEffect(()=>{if(i==="pause")return;(v-z)/xe>Bl&&y(v-xe*.1)},[v,z,xe,i]),r.useEffect(()=>{y(Date.now()-xe*.1)},[o]),r.useEffect(()=>{i==="live"&&y(Date.now()-xe*.1)},[i]),r.useLayoutEffect(()=>{const E=n.current;if(!E)return;const X=new ResizeObserver(je=>{for(const ve of je){const{width:pe,height:be}=ve.contentRect;S({width:Math.max(200,Math.floor(pe)),height:Math.max(120,Math.floor(be))})}});return X.observe(E),()=>X.disconnect()},[]);const q=r.useMemo(()=>{const E=[];let X=0;for(const pe of h){const be=Vl(pe),We=Wl(pe,v);We<fe||be>L||E.push({kind:"bg",id:`bg:${pe.instanceId}`,index:X++,label:`BG ${it(pe.promptPreview,20)||pe.instanceId.slice(0,10)}`,sub:pe.status||"pending",start:be,end:We,data:pe})}const je=[...re].sort((pe,be)=>At(pe)-At(be)),ve=[];for(const pe of je){const be=At(pe),We=Ul(pe,v);if(We<fe||be>L)continue;let ys=-1;for(let ms=0;ms<ve.length;ms++)if(ve[ms]<=be){ve[ms]=We,ys=ms;break}ys===-1&&(ve.push(We),ys=ve.length-1),E.push({kind:"task",id:`task:${pe.id}`,index:X+ys,label:it(pe.title,32),sub:pe.status,start:be,end:We,data:pe})}return E},[h,re,v,fe,L]),Z=r.useMemo(()=>{const E=new Map;for(const X of q)E.set(X.id,X);return E},[q]),le=r.useCallback(E=>xe<=0?0:(E-fe)/xe*R.width,[fe,xe,R.width]),se=r.useMemo(()=>{const E=ql(xe),X=[],je=Math.floor(fe/E)*E;for(let ve=je;ve<=L+E;ve+=E){if(ve<fe-E)continue;if(ve>L)break;const pe=le(ve);pe<-40||pe>R.width+40||X.push({t:ve,x:pe,label:Gl(ve,xe)})}return X},[fe,L,xe,R.width,le]),ue=r.useMemo(()=>{const E=[];for(const X of q){if(X.kind==="events")continue;const je=Math.max(X.start,fe),ve=Math.min(X.end,L);if(ve<fe||je>L)continue;const pe=le(je),be=le(ve),We=Math.max(Ol,be-pe),ys=ss+ws+X.index*Oe+8,ms=Oe-16;let Ye="doing";if(X.kind==="bg"){const ze=X.data.status||"pending";ze==="done"||ze==="success"?Ye="done":ze==="failed"||ze==="killed"||ze==="error"?Ye="failed":ze==="queued"||ze==="pending"?Ye="queued":ze==="blocked"||ze==="stuck"?Ye="blocked":Ye="doing"}else{const ze=X.data.status;ze==="done"||ze==="archived"?Ye="done":ze==="failed"||ze==="killed"?Ye="failed":ze==="queued"?Ye="queued":ze==="blocked"?Ye="blocked":Ye="doing"}const fn=(N==null?void 0:N.id)===X.id;E.push({id:X.id,laneIndex:X.index,x:pe,y:ys,w:We,h:ms,label:X.label,statusClass:Ye,selected:fn,data:X.data,kind:X.kind,start:X.start,end:X.end})}return E},[q,le,N,fe,L]),Le=r.useMemo(()=>{const E=[];for(const X of d){const je=jt(X.ts);if(je<fe-5e3||je>L+5e3)continue;const ve=le(je);let pe=ss+12;if(X.taskId){const be=Z.get(`task:${X.taskId}`);be&&(pe=ss+ws+be.index*Oe+Oe/2)}else if(X.nodeId){const be=String(X.nodeId),We=Z.get(be.startsWith("task:")||be.startsWith("bg:")?be:`task:${be}`);We&&(pe=ss+ws+We.index*Oe+Oe/2)}E.push({id:`${X.ts}-${X.kind}-${X.author??""}-${X.taskId??""}`,x:ve,y:pe,kind:X.kind||"event",ts:je,text:String(X.text||X.kind||""),author:X.author})}return E},[d,fe,L,le,Z]),Ve=r.useMemo(()=>q.map(E=>({id:E.id,y:ss+ws+E.index*Oe,h:Oe})),[q]),De=r.useMemo(()=>{const E=le(v);return Math.max(0,Math.min(R.width,E))},[le,v,R.width]),bs=r.useCallback(E=>{const je={id:E.id,kind:E.kind,label:E.label,status:E.statusClass,data:E.data};P(je)},[]);r.useEffect(()=>{if(!N){F([]),ae(""),de([]);return}j(""),U(""),D(""),de([]),(async()=>{try{const E=await $.get(`/activity?nodeId=${encodeURIComponent(N.id)}&limit=50`);F(E.events||[])}catch{F([])}if(N.kind==="bg"){const E=N.data;try{const X=await $.get(`/background/${encodeURIComponent(E.instanceId)}/output?lines=80`);ae(X.output||"")}catch{ae("")}if(E.taskId)try{const X=await $.get(`/tasks/${encodeURIComponent(E.taskId)}/artifacts`);de((X.artifacts||[]).map(je=>je.id))}catch{de([])}}})()},[N]);const Ds=async()=>{if(!(!N||!g.trim())){V(!0);try{await $.post("/comments",{nodeId:N.id,text:g,author:"user"}),j("");const E=await $.get(`/activity?nodeId=${encodeURIComponent(N.id)}&limit=50`);F(E.events||[]),a.success("Comment added.")}catch(E){a.error(`Comment failed: ${E.message}`)}finally{V(!1)}}},st=async()=>{if(!(!N||!A.trim())){ne(!0);try{await $.post(`/nodes/${encodeURIComponent(N.id)}/tasks`,{title:A,description:`Created from timeline selection ${N.id}.`,priority:Y}),U(""),a.success("Task created."),await t()}catch(E){a.error(`Task create failed: ${E.message}`)}finally{ne(!1)}}},_s=async()=>{if(!N||N.kind!=="bg"||!K.trim())return;const E=N.data;try{const X=await $.post(`/background/${encodeURIComponent(E.instanceId)}/message`,{message:K});X.ok?(a.success("Message sent."),D("")):a.warning(X.error||"Send failed")}catch(X){a.error(`Send failed: ${X.message}`)}},tt=async()=>{if(!N||N.kind!=="bg"||!confirm("Kill this bg instance session?"))return;const E=N.data;try{const X=await $.del(`/background/${encodeURIComponent(E.instanceId)}`);X.ok?a.success("Session killed."):a.warning(X.error||"Kill failed"),await H()}catch(X){a.error(`Kill failed: ${X.message}`)}},pn=async()=>{if(!N||N.kind!=="bg")return;const E=N.data;try{const X=await $.get(`/background/${encodeURIComponent(E.instanceId)}/output?lines=80`);ae(X.output||"")}catch{}};r.useEffect(()=>{const E=X=>{X.key==="Escape"&&P(null)};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[]);const gn=()=>{w(E=>E+1),H()},kt=ss+ws+q.length*Oe;return e.jsxs("div",{className:"view view-activity",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(Ae,{size:18})," Activity"]}),e.jsx("p",{className:"view-subtitle",children:"Live timeline of agents, tasks, and background sessions. Active tasks pulse; the red line marks “now”."})]}),e.jsx("div",{className:"view-actions",children:e.jsxs("div",{className:"tl-mode-toggle",children:[e.jsxs(M,{variant:i==="live"?"primary":"secondary",size:"sm",onClick:()=>l(i==="live"?"pause":"live"),title:i==="live"?"Pause timeline":"Resume timeline",children:[i==="live"?e.jsx(ea,{size:14}):e.jsx(Es,{size:14}),i==="live"?"Live":"Paused"]}),e.jsx("div",{className:"tl-zoom-group",children:["1m","5m","30m","1h"].map(E=>e.jsx("button",{type:"button",className:W("tl-zoom-btn",o===E&&"tl-zoom-btn-active"),onClick:()=>c(E),title:`Zoom to ${E}`,children:E},E))}),e.jsxs(M,{variant:"secondary",size:"sm",onClick:gn,title:"Refresh",children:[e.jsx(me,{size:14})," Refresh"]})]})})]}),f&&e.jsx("div",{className:"view-loading",children:e.jsx(he,{size:"lg"})}),!f&&Q.length===0&&re.length===0&&h.length===0&&d.length===0?e.jsx(Ne,{icon:e.jsx(Ae,{size:32}),title:"No activity yet",message:"Once agents, tasks, or background instances exist, they'll show up here on the timeline."}):e.jsx("div",{className:W("tl-view",N&&"tl-view-detail-open"),children:e.jsxs("div",{className:W("tl-body",!u&&"tl-body-stream-collapsed"),children:[e.jsxs("aside",{className:W("tl-stream",!u&&"tl-stream-collapsed"),children:[e.jsxs("div",{className:"tl-stream-head",children:[e.jsxs("h3",{children:[e.jsx(Gs,{size:13})," Live events"]}),e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>x(!1),title:"Hide event stream","aria-label":"Hide event stream",children:e.jsx(ei,{size:14})})]}),e.jsx("div",{className:"tl-stream-list",children:d.length===0?e.jsx("div",{className:"tl-stream-empty",children:e.jsx("p",{children:"No events yet."})}):e.jsx(Ja,{items:[...d].reverse(),itemHeight:40,height:400,className:"tl-stream-virtual",renderItem:E=>{const X=E.author?Qe:E.kind==="task"?ps:E.kind==="bg"?dt:Ae;return e.jsxs("div",{className:"tl-stream-event",children:[e.jsx("span",{className:"tl-stream-event-time",children:new Date(E.ts).toLocaleTimeString("en-GB",{hour12:!1})}),e.jsx("span",{className:"tl-stream-event-icon",style:{color:Tt(E.kind)},children:e.jsx(X,{size:12})}),e.jsx("span",{className:"tl-stream-event-text",children:E.author||E.text||E.kind})]})}})})]}),e.jsxs("div",{className:"tl-canvas-wrap",ref:n,children:[e.jsxs("div",{className:"tl-canvas-toolbar",children:[e.jsxs("div",{className:"tl-canvas-toolbar-left",children:[!u&&e.jsxs(M,{variant:"ghost",size:"sm",onClick:()=>x(!0),title:"Show event stream",children:[e.jsx(si,{size:14})," Events"]}),e.jsx("span",{className:"tl-canvas-mode",children:i==="live"?"● Live":"⏸ Paused"}),e.jsxs("span",{className:"tl-canvas-range",children:[new Date(fe).toLocaleTimeString("en-GB",{hour12:!1})," →"," ",new Date(L).toLocaleTimeString("en-GB",{hour12:!1})]})]}),e.jsxs("div",{className:"tl-canvas-legend",children:[e.jsxs("span",{className:"tl-legend-item",children:[e.jsx("span",{className:"tl-legend-dot",style:{background:"var(--success)"}})," active"]}),e.jsxs("span",{className:"tl-legend-item",children:[e.jsx("span",{className:"tl-legend-dot tl-legend-dot-dashed",style:{borderColor:"var(--info)"}})," queued"]}),e.jsxs("span",{className:"tl-legend-item",children:[e.jsx("span",{className:"tl-legend-dot",style:{background:"var(--warning)"}})," blocked"]}),e.jsxs("span",{className:"tl-legend-item",children:[e.jsx("span",{className:"tl-legend-dot",style:{background:"var(--error)"}})," error"]}),e.jsx("span",{className:"tl-legend-sep"}),e.jsxs("span",{className:"tl-legend-item",children:[e.jsx(ti,{size:11})," agent"]}),e.jsxs("span",{className:"tl-legend-item",children:[e.jsx(Xt,{size:11})," task"]}),e.jsxs("span",{className:"tl-legend-item",children:[e.jsx(dt,{size:11})," bg"]})]})]}),e.jsx("div",{className:"tl-canvas-scroll",children:e.jsxs("svg",{className:"tl-canvas",width:R.width,height:Math.max(R.height,kt),role:"application","aria-label":"Activity timeline",children:[e.jsx("defs",{children:e.jsx("pattern",{id:"tl-canvas-grid",width:R.width,height:Oe,patternUnits:"userSpaceOnUse",children:e.jsx("path",{d:`M 0 0 L 0 ${Oe}`,fill:"none",stroke:"var(--border)",strokeWidth:.5,opacity:.35})})}),e.jsx("rect",{width:"100%",height:"100%",fill:"url(#tl-canvas-grid)"}),Ve.map(E=>e.jsx("rect",{className:"tl-lane-bg",x:0,y:E.y,width:R.width,height:E.h,fill:E.id.charCodeAt(E.id.length-1)%2===0?"var(--bg-elev-2)":"var(--bg-elev)",opacity:.4},`bg-${E.id}`)),e.jsx("g",{className:"tl-time-axis",children:se.map(E=>e.jsxs("g",{children:[e.jsx("line",{x1:E.x,y1:0,x2:E.x,y2:kt,stroke:"var(--border)",strokeWidth:.5,strokeDasharray:"2,4",opacity:.5}),e.jsx("text",{x:E.x+4,y:ss-8,fontSize:10,fontFamily:"var(--font-mono)",fill:"var(--text-dim)",children:E.label})]},`tick-${E.t}`))}),q.map(E=>{const X=ss+ws+E.index*Oe+Oe/2;return e.jsxs("g",{className:"tl-lane-label-group",children:[e.jsx("text",{x:6,y:X-2,className:"tl-lane-label",textAnchor:"start",children:it(E.label,28)}),e.jsx("text",{x:6,y:X+10,className:"tl-lane-label-sub",textAnchor:"start",children:E.sub})]},`label-${E.id}`)}),ue.map(E=>{const X=Tt(E.statusClass),je=E.id===(N==null?void 0:N.id);return e.jsxs("g",{className:W("tl-task-bar",`tl-task-bar-${E.statusClass}`,je&&"tl-task-bar-selected"),onClick:()=>bs(E),children:[e.jsx("rect",{x:E.x,y:E.y,width:E.w,height:E.h,rx:6,fill:X,fillOpacity:E.statusClass==="done"?.35:E.statusClass==="queued"?.18:.85,stroke:X,strokeWidth:je?2.5:1.5,strokeOpacity:E.statusClass==="done"?.5:1,strokeDasharray:E.statusClass==="queued"?"4 4":void 0,style:{cursor:"pointer"}}),E.w>36&&e.jsx("text",{x:E.x+8,y:E.y+E.h/2+4,fontSize:11,fontFamily:"var(--font-sans)",fontWeight:500,fill:"var(--text-strong)",style:{pointerEvents:"none"},opacity:E.statusClass==="done"?.7:1,children:it(E.label,Math.max(4,Math.floor(E.w/7)))})]},`bar-${E.id}`)}),Le.map(E=>{const X=Tt(E.kind);return e.jsxs("g",{className:"tl-event-marker-group",children:[e.jsx("line",{x1:E.x,y1:E.y-6,x2:E.x,y2:E.y+6,stroke:X,strokeWidth:1.2,opacity:.7}),e.jsx("circle",{cx:E.x,cy:E.y,r:4,fill:X,opacity:.9,children:e.jsx("title",{children:`${E.kind}${E.author?` · ${E.author}`:""} · ${new Date(E.ts).toLocaleTimeString("en-GB",{hour12:!1})}`})})]},`ev-${E.id}`)}),e.jsx("line",{className:"tl-now-line",x1:De,y1:0,x2:De,y2:kt,stroke:"var(--error)",strokeWidth:1.5,opacity:.9}),e.jsxs("g",{className:"tl-now-marker",children:[e.jsx("circle",{cx:De,cy:ss-4,r:4,fill:"var(--error)"}),e.jsx("text",{x:De+6,y:ss-4,fontSize:10,fontWeight:700,fill:"var(--error)",fontFamily:"var(--font-mono)",children:"now"})]})]})})]}),N&&e.jsx("aside",{className:"tl-detail tl-detail-enter",children:e.jsxs(G,{children:[e.jsxs(ee,{children:[N.kind==="agent"&&e.jsx(Qe,{size:14}),N.kind==="task"&&e.jsx(ps,{size:14}),N.kind==="bg"&&e.jsx(dt,{size:14}),N.label,e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>P(null),title:"Close","aria-label":"Close activity detail",style:{marginLeft:"auto"},children:e.jsx(we,{size:14})})]}),e.jsxs("div",{className:"tl-detail-meta",children:[e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"type"})," ",N.kind]}),e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"status"})," ",e.jsx("code",{children:N.status})]}),N.kind==="agent"&&(()=>{const E=N.data;return e.jsxs(e.Fragment,{children:[E.role&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"role"})," ",E.role]}),E.model&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"model"})," ",E.model]})]})})(),N.kind==="task"&&(()=>{const E=N.data;return e.jsxs(e.Fragment,{children:[E.assignee&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"assignee"})," @",E.assignee]}),E.priority&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"priority"})," ",E.priority]}),E.createdAt&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"created"})," ",new Date(E.createdAt).toLocaleString()]})]})})(),N.kind==="bg"&&(()=>{const E=N.data;return e.jsxs(e.Fragment,{children:[E.startedAt&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"started"})," ",new Date(E.startedAt).toLocaleString()]}),E.tmuxSession&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"tmux"})," ",e.jsx("code",{children:E.tmuxSession})," ",E.tmuxActive?e.jsx("span",{className:"tag tag-success",children:"active"}):e.jsx("span",{className:"tag",children:"inactive"})]})]})})()]}),N.kind==="task"&&N.data.description&&e.jsx("div",{className:"tl-detail-desc",children:N.data.description}),N.kind==="bg"&&N.data.promptPreview&&e.jsx("div",{className:"tl-detail-desc",children:N.data.promptPreview}),N.kind==="bg"&&e.jsxs("div",{className:"tl-detail-bg",children:[e.jsx("pre",{className:"tl-bg-output",children:_||"(no output — start the session via tmux attach)"}),e.jsxs("div",{className:"tl-bg-output-actions",children:[e.jsxs(M,{variant:"ghost",size:"sm",onClick:pn,children:[e.jsx(me,{size:12})," Refresh output"]}),ie.length>0&&e.jsxs(M,{variant:"secondary",size:"sm",onClick:()=>Fl(O,ie[0]),children:[e.jsx(Ie,{size:12})," Open artifact"]}),e.jsxs(M,{variant:"danger",size:"sm",onClick:tt,children:[e.jsx(Re,{size:12})," Kill session"]})]}),e.jsxs("div",{className:"tl-form-row",children:[e.jsx("label",{htmlFor:"bg-message-input",className:"sr-only",children:"Send a message to this bg session"}),e.jsx("input",{id:"bg-message-input",className:"input",placeholder:"Send a message to this bg session…",value:K,onChange:E=>D(E.target.value),onKeyDown:E=>{E.key==="Enter"&&_s()},"aria-label":"Send a message to this bg session"}),e.jsxs(M,{variant:"primary",size:"sm",disabled:!K.trim(),onClick:_s,children:[e.jsx(rs,{size:12})," Send"]})]})]}),N.kind!=="bg"&&e.jsxs("div",{className:"tl-detail-create",children:[e.jsx("label",{className:"field-label",htmlFor:"followup-task-title",children:"Create follow-up task"}),e.jsx("input",{id:"followup-task-title",className:"input",placeholder:"Task title",value:A,onChange:E=>U(E.target.value)}),e.jsxs("div",{className:"tl-form-row",children:[e.jsx("label",{htmlFor:"followup-task-priority",className:"sr-only",children:"Task priority"}),e.jsxs("select",{id:"followup-task-priority",className:"select",value:Y,onChange:E=>B(E.target.value),"aria-label":"Task priority",children:[e.jsx("option",{value:"low",children:"Low"}),e.jsx("option",{value:"normal",children:"Normal"}),e.jsx("option",{value:"high",children:"High"})]}),e.jsxs(M,{variant:"primary",size:"sm",disabled:!A.trim()||J,onClick:st,children:[e.jsx(Ee,{size:12})," Add task"]})]})]}),e.jsxs("div",{className:"tl-detail-comments",children:[e.jsxs("div",{className:"field-label",children:[e.jsx(Js,{size:12})," Comments & activity"]}),e.jsxs("ul",{className:"comment-list",children:[T.length===0&&e.jsx("li",{className:"muted",children:"No comments yet."}),T.map((E,X)=>e.jsxs("li",{className:"comment-item",children:[e.jsxs("div",{className:"comment-head",children:[e.jsx("strong",{children:E.author||"system"}),e.jsxs("span",{className:"muted",children:[E.kind," · ",new Date(E.ts).toLocaleString()]})]}),E.text&&e.jsx("div",{className:"comment-text",children:E.text}),E.taskId&&e.jsxs("div",{className:"muted",children:["→ task ",e.jsx("code",{children:String(E.taskId)})]})]},`c-${X}`))]}),e.jsxs("div",{className:"comment-input-row",children:[e.jsx("label",{htmlFor:"comment-input",className:"sr-only",children:"Add a comment"}),e.jsx("input",{id:"comment-input",className:"input",placeholder:"Add a comment…",value:g,onChange:E=>j(E.target.value),onKeyDown:E=>{E.key==="Enter"&&!E.shiftKey&&Ds()},"aria-label":"Add a comment"}),e.jsxs(M,{variant:"secondary",size:"sm",disabled:!g.trim()||I,onClick:Ds,children:[e.jsx(rs,{size:12})," Post"]})]})]})]})},N.id)]})})]})}function Kl(s,t){const a=s.length,n=t.length,i=Array.from({length:n+1},()=>Array(a+1).fill(0));for(let l=0;l<=a;l++)i[0][l]=l;for(let l=0;l<=n;l++)i[l][0]=l;for(let l=1;l<=n;l++)for(let o=1;o<=a;o++){const c=s[o-1]===t[l-1]?0:1;i[l][o]=Math.min(i[l][o-1]+1,i[l-1][o]+1,i[l-1][o-1]+c)}return i[n][a]}function Mt(s,t){if(t===s)return 100;if(t.startsWith(s))return 90;const a=t.split(/\s+/);for(const l of a)if(l.startsWith(s))return 80;const n=Math.min(s.length,t.length);return Kl(s,t.substring(0,n))<=2?40:t.includes(s)?30:0}function Yl(s,t){const a=s.toLowerCase().trim();return a?t.map(n=>{const i=Mt(a,n.label.toLowerCase()),l=n.value?Mt(a,String(n.value).toLowerCase()):0,o=n.description?Mt(a,n.description.toLowerCase()):0,c=Math.max(i,l,o);if(c===0)return null;const u=i>=l&&i>=o?"label":l>=i&&l>=o?"value":"description",x=u==="label"?n.label:u==="value"?String(n.value):n.description;return{...n,score:c,matchedField:u,matchedTerm:x}}).filter(n=>n!==null).sort((n,i)=>i.score-n.score):[]}const ra="bizar_settings_recent";function rn(){try{const s=localStorage.getItem(ra);return s?JSON.parse(s):[]}catch{return[]}}function Xl(s){if(s)try{const t=rn().filter(a=>a!==s);t.unshift(s),localStorage.setItem(ra,JSON.stringify(t.slice(0,5)))}catch{}}function Ql(s,t){if(!t)return s;const a=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=new RegExp(`(${a})`,"gi");return s.split(n).map((l,o)=>n.test(l)?e.jsx("mark",{children:l},o):e.jsx("span",{children:l},o))}function Jl(s){const t=[];for(const a of s){t.push({key:a.id,label:a.label,section:a.id,description:`${a.fields.length} field${a.fields.length===1?"":"s"}`});for(const n of a.fields)t.push({key:n.key,label:n.label,section:a.id,value:n.value})}return t}function Zl({sections:s,onJump:t}){const[a,n]=r.useState(""),[i,l]=r.useState([]),[o,c]=r.useState(0),[u,x]=r.useState(null),[h,m]=r.useState(!1),d=r.useRef(null),p=r.useRef(null),f=r.useRef(null),b=r.useRef([]);r.useEffect(()=>{b.current=Jl(s)},[s]);const k=r.useCallback((g,j=!1)=>{if(p.current&&clearTimeout(p.current),!g.trim()){l([]),c(0);return}const T=()=>{const F=Yl(g,b.current);l(F),c(0)};j?T():p.current=setTimeout(T,150)},[]);r.useEffect(()=>{k(a)},[a,k]),r.useEffect(()=>()=>{p.current&&clearTimeout(p.current),f.current&&clearTimeout(f.current)},[]);const w=(g,j)=>{const T=document.querySelector(`[data-section="${g}"] [data-setting-id="${j}"]`);T&&(T.scrollIntoView({behavior:"smooth",block:"center"}),T.classList.add("setting-flash"),setTimeout(()=>T.classList.remove("setting-flash"),2e3));const F=document.querySelector(`[data-section="${g}"]`);F&&F.scrollIntoView({behavior:"smooth",block:T?"nearest":"start"})},v=g=>{x(g),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>x(null),1500);const j=document.querySelector(`[data-section="${g}"]`);j&&j.scrollIntoView({behavior:"smooth",block:"start"})},C=g=>{var j;Xl(a),g.key===g.section?(v(g.section),t(g.section)):(v(g.section),t(g.section,g.key),w(g.section,g.key)),n(""),(j=d.current)==null||j.blur()},z=g=>{var j;g.key==="Escape"?(n(""),(j=d.current)==null||j.blur()):g.key==="ArrowDown"?(g.preventDefault(),c(T=>Math.min(T+1,i.length-1))):g.key==="ArrowUp"?(g.preventDefault(),c(T=>Math.max(T-1,0))):g.key==="Enter"&&(g.preventDefault(),i.length===0&&a.trim()&&k(a,!0),i[o]&&C(i[o]))},y=g=>{C(g)},R=rn(),S=g=>{var j;n(g),(j=d.current)==null||j.focus()},N=()=>{try{localStorage.removeItem(ra)}catch{}m(g=>g)},P=h&&!a.trim()&&R.length>0;return e.jsxs("div",{className:"settings-search",children:[e.jsxs("div",{className:"settings-search-input-wrap",children:[e.jsx(ke,{size:13,className:"settings-search-icon"}),e.jsx("input",{ref:d,className:"settings-search-input",placeholder:"Search settings…",value:a,onChange:g=>n(g.target.value),onKeyDown:z,onFocus:()=>m(!0),onBlur:()=>setTimeout(()=>m(!1),150),"aria-label":"Search settings"}),a&&e.jsx("button",{type:"button",className:"icon-btn settings-search-clear",onClick:()=>n(""),"aria-label":"Clear search",children:e.jsx(we,{size:12})})]}),P&&e.jsxs("div",{className:"settings-search-recent",children:[e.jsxs("div",{className:"settings-search-recent-header",children:[e.jsx("span",{className:"settings-search-recent-label",children:"Recent"}),e.jsx("button",{type:"button",className:"settings-search-recent-clear",onClick:N,tabIndex:-1,children:"Clear"})]}),R.map(g=>e.jsxs("button",{type:"button",className:"settings-search-recent-item",onMouseDown:j=>{j.preventDefault(),S(g)},children:[e.jsx(ke,{size:11}),e.jsx("span",{children:g})]},g))]}),a&&i.length>0&&e.jsx("div",{className:"settings-search-results",children:i.map((g,j)=>e.jsxs("button",{type:"button",className:W("settings-search-result",j===o&&"settings-search-result-active"),onClick:()=>y(g),onMouseEnter:()=>c(j),children:[e.jsx("span",{className:W("settings-search-result-type",g.key===g.section&&"settings-search-result-type-section"),children:g.key===g.section?"section":"field"}),e.jsx("span",{className:"settings-search-result-label",children:Ql(g.label,a)}),g.key!==g.section&&e.jsx("span",{className:"settings-search-result-key mono muted",children:g.key})]},`${g.section}::${g.key}`))}),a&&i.length===0&&e.jsx("div",{className:"settings-search-empty muted",children:"No matching settings."})]})}const ec=[{id:"dark",label:"Dark",Icon:Ua},{id:"light",label:"Light",Icon:Ba},{id:"system",label:"System",Icon:ai}],sc=[{name:"Purple",accent:"#8b5cf6"},{name:"Blue",accent:"#3b82f6"},{name:"Green",accent:"#10b981"},{name:"Orange",accent:"#f97316"},{name:"Red",accent:"#ef4444"},{name:"Pink",accent:"#ec4899"},{name:"Cyan",accent:"#06b6d4"},{name:"Mono",accent:"#6b7280"}],tc=["Inter","system-ui","Segoe UI","Roboto","JetBrains Mono","SF Mono","Cascadia Code"];function ac({settings:s,patchTheme:t,patchUi:a}){return e.jsxs(G,{id:"settings-theme","data-section":"theme",children:[e.jsxs(ee,{children:[e.jsx(Pa,{size:14})," Theme"]}),e.jsx(te,{children:"Mode, accent, and colors. Live preview as you tweak."}),e.jsxs("div",{className:"field","data-setting-id":"theme.presets",children:[e.jsx("label",{className:"field-label",children:"Accent presets"}),e.jsx("div",{className:"theme-presets",children:sc.map(n=>e.jsxs("button",{type:"button",className:W("theme-preset",s.theme.accent===n.accent&&"theme-preset-active"),onClick:()=>t({accent:n.accent}),title:n.name,children:[e.jsx("span",{className:"theme-preset-swatch",style:{background:n.accent}}),e.jsx("span",{className:"theme-preset-name",children:n.name})]},n.name))})]}),e.jsxs("div",{className:"field","data-setting-id":"theme.mode",children:[e.jsx("label",{className:"field-label",children:"Mode"}),e.jsx("div",{className:"theme-row",children:ec.map(({id:n,label:i,Icon:l})=>{const o=s.theme.mode===n;return e.jsxs("button",{type:"button",className:W("theme-card",o&&"theme-card-active"),onClick:()=>t({mode:n}),children:[e.jsx(l,{size:16}),e.jsx("span",{className:"theme-card-label",children:i}),e.jsx("span",{className:W("theme-card-swatch",`theme-card-swatch-${n}`)})]},n)})})]}),e.jsx("div",{className:"theme-colors",children:["accent","success","warning","error","info"].map(n=>e.jsxs("div",{className:"field","data-setting-id":`theme.${n}`,children:[e.jsx("label",{className:"field-label",children:n.charAt(0).toUpperCase()+n.slice(1)}),e.jsxs("div",{className:"color-row",children:[e.jsx("input",{type:"color",className:"input color-input",value:s.theme[n],onChange:i=>t({[n]:i.target.value}),"aria-label":`${n} color`}),e.jsx("input",{type:"text",className:"input",value:s.theme[n],onChange:i=>t({[n]:i.target.value}),"aria-label":`${n} color hex`})]})]},n))}),e.jsxs("div",{className:"field","data-setting-id":"theme.fontFamily",children:[e.jsx("label",{className:"field-label",children:"Font family"}),e.jsx("select",{className:"select",value:s.theme.fontFamily,onChange:n=>t({fontFamily:n.target.value}),children:tc.map(n=>e.jsx("option",{value:n,children:n},n))})]}),e.jsxs("div",{className:"field","data-setting-id":"theme.fontSize",children:[e.jsxs("label",{className:"field-label",children:["Font size: ",s.theme.fontSize,"px"]}),e.jsx("input",{type:"range",min:12,max:20,value:s.theme.fontSize,onChange:n=>t({fontSize:Number(n.target.value)})})]}),e.jsxs("label",{className:"checkbox-row","data-setting-id":"theme.compactMode",children:[e.jsx("input",{type:"checkbox",checked:s.theme.compactMode,onChange:n=>t({compactMode:n.target.checked})}),e.jsx("span",{children:"Compact mode (denser UI)"})]}),e.jsxs("label",{className:"checkbox-row","data-setting-id":"theme.animations",children:[e.jsx("input",{type:"checkbox",checked:s.theme.animations,onChange:n=>t({animations:n.target.checked})}),e.jsx("span",{children:"Enable animations"})]})]})}function nc({tailscale:s,tailscaleDraft:t,setTailscaleDraft:a,onTailscaleToggle:n}){return e.jsxs(e.Fragment,{children:[e.jsxs(G,{id:"settings-service","data-section":"service",children:[e.jsxs(ee,{children:[e.jsx(Ms,{size:14})," Service"]}),e.jsx(te,{children:"Background daemon that runs schedules."}),e.jsx("div",{"data-setting-id":"service.enabled",children:s?e.jsxs("div",{className:"service-card",children:[e.jsxs("p",{children:["Status: ",e.jsx("strong",{children:s.settings.enabled?"enabled":"disabled"})," ","· Tailscale installed: ",e.jsx("strong",{children:s.installed?"yes":"no"})," ","· authenticated: ",e.jsx("strong",{children:s.authenticated?"yes":"no"})]}),e.jsxs("p",{className:"muted",children:["Use ",e.jsx("code",{children:"bizar service start"})," / ",e.jsx("code",{children:"bizar service stop"})," in your terminal to control the daemon."]})]}):e.jsx("p",{className:"muted",children:"Loading service status…"})})]}),e.jsxs(G,{id:"settings-tailscale","data-section":"tailscale",children:[e.jsxs(ee,{children:[e.jsx(Bt,{size:14})," Tailscale serve"]}),e.jsx(te,{children:"Expose the dashboard over your Tailscale network."}),s?e.jsxs(e.Fragment,{children:[e.jsxs("p",{children:["Installed: ",e.jsx("strong",{children:s.installed?"yes":"no"})," ",s.version&&e.jsxs("span",{className:"muted",children:["(",s.version,")"]})]}),e.jsxs("p",{children:["Authenticated: ",e.jsx("strong",{children:s.authenticated?"yes":"no"})]}),e.jsxs("p",{children:["Serve enabled: ",e.jsx("strong",{children:s.settings.enabled?"yes":"no"})]}),e.jsxs("div",{className:"task-form-row",children:[e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",children:"Port"}),e.jsx("input",{type:"number",className:"input",value:t.port,onChange:i=>a(l=>({...l,port:Number(i.target.value)||4321}))})]}),e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"tailscale-https",children:"Use HTTPS"}),e.jsx("input",{id:"tailscale-https",type:"checkbox",checked:t.https,onChange:i=>a(l=>({...l,https:i.target.checked}))})]})]}),e.jsx(M,{variant:"primary",onClick:n,children:s.settings.enabled?"Disable serve":"Enable serve"})]}):e.jsx("p",{className:"muted",children:"Loading Tailscale status…"})]})]})}function ic({settings:s,patchNotifications:t}){return e.jsxs(G,{id:"settings-notifications","data-section":"notifications",children:[e.jsx(ee,{children:"Notifications"}),e.jsx(te,{children:"Toast triggers inside the dashboard."}),e.jsxs("label",{className:"checkbox-row","data-setting-id":"notifications.onAgentComplete",children:[e.jsx("input",{type:"checkbox",checked:!!s.notifications.onAgentComplete,onChange:a=>t({onAgentComplete:a.target.checked})}),e.jsx("span",{children:"Notify when an agent invocation completes"})]}),e.jsxs("label",{className:"checkbox-row","data-setting-id":"notifications.onPlanApproval",children:[e.jsx("input",{type:"checkbox",checked:!!s.notifications.onPlanApproval,onChange:a=>t({onPlanApproval:a.target.checked})}),e.jsx("span",{children:"Notify when a plan needs approval"})]})]})}function rc({authStatus:s,setAuthStatus:t}){const a=ce(),[n,i]=r.useState($.getToken()),[l,o]=r.useState("");r.useEffect(()=>{let h=!1;return(async()=>{try{const m=await $.probeAuthStatus();h||t(m)}catch{h||t({required:!0,loopback:!1,peer:""})}})(),()=>{h=!0}},[]);const c=async()=>{try{const h=await $.get("/auth/reveal");o(h.token),i(h.token),$.setToken(h.token);try{await navigator.clipboard.writeText(h.token),a.success("Token copied to clipboard.")}catch{a.success("Token revealed — copy from the field below.")}}catch(h){a.error(`Reveal failed: ${h.message}`)}},u=async()=>{if(confirm("Regenerate the auth token? Anything still using the old token will start getting 401 errors immediately."))try{const h=await $.post("/auth/regenerate");o(h.token),i(h.token),$.setToken(h.token);try{await navigator.clipboard.writeText(h.token),a.success("New token generated and copied to clipboard.")}catch{a.success("New token generated — copy from the field below. Old token is now invalid.")}}catch(h){a.error(`Regenerate failed: ${h.message}`)}},x=()=>{$.setToken(n.trim()),a.success("Token saved. The dashboard will use it on the next request.")};return e.jsxs(G,{id:"settings-auth","data-section":"auth",children:[e.jsxs(ee,{children:[e.jsx(fs,{size:14})," Authentication"]}),e.jsx(te,{children:"Localhost and Tailscale browser access are auto-trusted via loopback. A bearer token is still available for non-loopback clients and forced-auth mode."}),e.jsxs("div",{className:"field","data-setting-id":"auth.status",children:[e.jsx("label",{className:"field-label",children:"Server status"}),e.jsxs("p",{style:{margin:"4px 0"},children:["Auth required:"," ",e.jsx("strong",{children:s?s.required?"yes":"no":"probing…"})]}),e.jsxs("p",{style:{margin:"4px 0"},children:["Connection:"," ",e.jsx("strong",{children:s?s.loopback?"loopback (auto-trusted)":"remote":"probing…"})]}),e.jsxs("p",{style:{margin:"4px 0"},children:["Peer address:"," ",s!=null&&s.peer?e.jsx("code",{children:s.peer}):e.jsx("span",{className:"muted",children:"probing…"})]}),e.jsxs("p",{className:"muted",style:{fontSize:12,margin:"4px 0"},children:["Localhost and Tailscale browser access are auto-trusted because the dashboard sees a loopback peer. Paste a token only for non-loopback API clients/scripts, or if you force auth for every connection with"," ",e.jsx("code",{children:"BIZAR_DASHBOARD_REQUIRE_AUTH=1"}),"."]}),e.jsxs("p",{className:"muted",style:{fontSize:12,margin:"4px 0"},children:["Dashboard tokens are generated on first boot and saved to"," ",e.jsx("code",{children:"~/.config/bizar/dashboard-secret"})," (mode 0600)."]}),e.jsx("p",{className:"muted",style:{fontSize:12,margin:"4px 0"},children:"For Tailscale Serve or any reverse-proxy access, paste this token once via the boot screen — it is saved per-origin and works for all subsequent visits."})]}),e.jsxs("div",{className:"field","data-setting-id":"auth.token",children:[e.jsx("label",{className:"field-label",children:"Token (this browser)"}),e.jsx("input",{type:"password",className:"input mono",value:n,onChange:h=>i(h.target.value),placeholder:"Paste token from server stderr or another browser",spellCheck:!1,autoComplete:"off"}),e.jsxs("div",{className:"task-form-row",style:{marginTop:8},children:[e.jsxs(M,{variant:"secondary",size:"sm",onClick:x,children:[e.jsx(sa,{size:14})," Save token"]}),e.jsxs(M,{variant:"ghost",size:"sm",onClick:c,children:[e.jsx(os,{size:14})," Reveal & copy server token"]}),e.jsxs(M,{variant:"ghost",size:"sm",onClick:u,children:[e.jsx(Wa,{size:14})," Regenerate"]})]}),l?e.jsxs("p",{className:"muted",style:{fontSize:12,marginTop:8},children:["Last revealed token (one-time): ",e.jsx("code",{className:"mono",children:l})]}):null,e.jsx("p",{className:"muted",style:{fontSize:12,marginTop:8},children:"Regenerating invalidates the current token immediately. Anything still using the old token will see 401 until it's updated."})]})]})}function lc({settings:s,patchAgents:t,patchDashboard:a,autoSave:n}){var x,h,m,d;const i=ce(),[l,o]=r.useState({});r.useEffect(()=>{$.get("/settings/plugin-options").then(o).catch(()=>{})},[]);const c=async()=>{try{await $.put("/settings/plugin-options",l),i.success("Saved — restart cline for changes to take effect.")}catch(p){i.error(`Save failed: ${p.message}`)}},u=async()=>{try{const f=await(await fetch("/api/background/cleanup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({maxAgeDays:7})})).json();i.success(`Cleaned up ${f.deleted} old instances.`)}catch(p){i.error(`Cleanup failed: ${p.message}`)}};return e.jsxs(e.Fragment,{children:[e.jsxs(G,{id:"settings-agents","data-section":"agents",children:[e.jsxs(ee,{children:[e.jsx(Ms,{size:14})," Agent Behavior"]}),e.jsx(te,{children:"Limits and timeouts for background agent dispatch."}),e.jsxs("div",{className:"form-row",children:[e.jsxs("label",{htmlFor:"agents-maxParallel",children:["Max parallel agents",e.jsx("span",{className:"meta-badge",children:"default: 6"})]}),e.jsx("input",{id:"agents-maxParallel",type:"number",min:1,max:20,value:((x=s.agents)==null?void 0:x.maxParallel)??6,onChange:p=>t({maxParallel:Math.max(1,Math.min(20,parseInt(p.target.value,10)||6))})})]}),e.jsxs("div",{className:"form-row",children:[e.jsxs("label",{htmlFor:"agents-stuckThresholdMs",children:["Stuck threshold (ms)",e.jsx("span",{className:"meta-badge",children:"default: 600000 (10 min)"})]}),e.jsx("input",{id:"agents-stuckThresholdMs",type:"number",min:6e4,max:36e5,step:6e4,value:((h=s.agents)==null?void 0:h.stuckThresholdMs)??6e5,onChange:p=>t({stuckThresholdMs:Math.max(6e4,Math.min(36e5,parseInt(p.target.value,10)||6e5))})})]}),e.jsxs("label",{className:"checkbox-row","data-setting-id":"agents.autoRestart",children:[e.jsx("input",{type:"checkbox",checked:!!((m=s.agents)!=null&&m.autoRestart),onChange:p=>t({autoRestart:p.target.checked})}),e.jsx("span",{children:"Auto-restart stuck agents"})]})]}),e.jsxs(G,{id:"settings-dashboard","data-section":"dashboard",children:[e.jsxs(ee,{children:[e.jsx(Ks,{size:14})," Dashboard"]}),e.jsxs(te,{children:["Controls how ",e.jsx("code",{children:"bizar"})," starts up."]}),e.jsxs("label",{className:"checkbox-row","data-setting-id":"dashboard.autoLaunchWeb",children:[e.jsx("input",{type:"checkbox",checked:s.dashboard.autoLaunchWeb!==!1,onChange:p=>a({autoLaunchWeb:p.target.checked})}),e.jsx("span",{children:"Auto-launch web UI alongside TUI"})]}),e.jsxs("div",{className:"field","data-setting-id":"dashboard.projectsDirectory",style:{marginTop:"var(--space-4)"},children:[e.jsx("label",{className:"field-label",htmlFor:"set-projects-directory",children:"Projects directory"}),e.jsx("input",{id:"set-projects-directory",className:"input",type:"text",placeholder:"/home/user/projects",value:s.dashboard.projectsDirectory??"",onChange:p=>a({projectsDirectory:p.target.value})}),e.jsx("p",{className:"field-help",children:"New projects created via the dashboard will land here, and existing project directories inside this folder are auto-recognized on startup."}),s.dashboard.projectsDirectory&&e.jsxs(e.Fragment,{children:[!/^\/|^[A-Za-z]:/.test(s.dashboard.projectsDirectory)&&e.jsx("p",{style:{color:"var(--warning)",fontSize:11,marginTop:4},children:"Path should be absolute (start with / on Linux/Mac, or a drive letter on Windows)."}),s.dashboard.projectsDirectory.includes("..")&&e.jsx("p",{style:{color:"var(--error)",fontSize:11,marginTop:4},children:"Path traversal not allowed — this will be rejected server-side."})]})]}),e.jsxs("div",{className:"field","data-setting-id":"dashboard.allowedRoots",style:{marginTop:"var(--space-4)"},children:[e.jsxs("label",{className:"field-label",htmlFor:"set-allowed-roots",children:["Additional allowed roots ",e.jsx("span",{className:"muted",children:"(advanced)"})]}),e.jsx(ki,{initialValue:(s.dashboard.allowedRoots??[]).join(`
|
|
6
|
-
`),delay:1500,saveFn:async p=>{const f=p.split(`
|
|
7
|
-
`).map(b=>b.trim()).filter(Boolean);a({allowedRoots:f}),n==null||n("dashboard",{allowedRoots:f})},render:({value:p,onChange:f,onBlur:b})=>e.jsx("textarea",{id:"set-allowed-roots",className:"textarea",rows:4,placeholder:`/workspace
|
|
8
|
-
/srv/projects`,value:p,onChange:k=>f(k.target.value),onBlur:b})},(d=s.dashboard.allowedRoots)==null?void 0:d.join(`
|
|
9
|
-
`)),e.jsx("p",{className:"field-help",children:"Optional. Add filesystem roots beyond your home directory that the file browser and project scanner can access. Each path must be inside your home directory. One per line."}),(()=>{const p=(s.dashboard.allowedRoots??[]).join(`
|
|
10
|
-
`).split(`
|
|
11
|
-
`),f=[];return p.forEach((b,k)=>{b.trim()&&(/^\/|^[A-Za-z]:/.test(b)||f.push({key:`noabs-${k}`,msg:e.jsxs("p",{style:{color:"var(--warning)",fontSize:11,marginTop:2},children:["Line ",k+1,': "',b,'" — should be absolute (start with / or a drive letter).']})}),b.includes("..")&&f.push({key:`dots-${k}`,msg:e.jsxs("p",{style:{color:"var(--error)",fontSize:11,marginTop:2},children:["Line ",k+1,': "',b,`" — contains '..' (server will reject this).`]})}))}),f.map(b=>b.msg)})()]})]}),e.jsxs(G,{id:"settings-background","data-section":"background",children:[e.jsxs(ee,{children:[e.jsx(Ms,{size:14})," Background Agents"]}),e.jsx(te,{children:"Tune plugin options. Changes take effect on next plugin restart."}),e.jsxs("div",{className:"form-row",children:[e.jsxs("label",{htmlFor:"bg-maxConcurrent",children:["Max concurrent instances",e.jsx("span",{className:"meta-badge",children:"default: 8"})]}),e.jsx("input",{id:"bg-maxConcurrent",type:"number",min:1,max:32,value:l.maxConcurrentInstances??8,onChange:p=>o(f=>({...f,maxConcurrentInstances:Math.max(1,Math.min(32,parseInt(p.target.value,10)||8))}))}),e.jsxs("small",{className:"muted",children:["Plugin option: ",e.jsx("code",{children:"maxConcurrentInstances"})]})]}),e.jsxs("div",{className:"form-row",children:[e.jsxs("label",{htmlFor:"bg-toolCallCap",children:["Tool-call cap",e.jsx("span",{className:"meta-badge",children:"default: 500"})]}),e.jsx("input",{id:"bg-toolCallCap",type:"number",min:1,max:5e3,value:l.backgroundToolCallCap??500,onChange:p=>o(f=>({...f,backgroundToolCallCap:Math.max(1,Math.min(5e3,parseInt(p.target.value,10)||500))}))}),e.jsxs("small",{className:"muted",children:["Plugin option: ",e.jsx("code",{children:"backgroundToolCallCap"})]})]}),e.jsxs("div",{className:"form-row",children:[e.jsxs("label",{htmlFor:"bg-stallTimeout",children:["Stall timeout (ms)",e.jsx("span",{className:"meta-badge",children:"default: 180000"})]}),e.jsx("input",{id:"bg-stallTimeout",type:"number",min:1e4,max:6e5,step:1e3,value:l.backgroundStallTimeoutMs??18e4,onChange:p=>o(f=>({...f,backgroundStallTimeoutMs:Math.max(1e4,Math.min(6e5,parseInt(p.target.value,10)||18e4))}))}),e.jsxs("small",{className:"muted",children:["Plugin option: ",e.jsx("code",{children:"backgroundStallTimeoutMs"})]})]}),e.jsxs("div",{className:"form-row",children:[e.jsxs("label",{htmlFor:"bg-thinkingLoopTimeout",children:["Thinking-loop timeout (ms)",e.jsx("span",{className:"meta-badge",children:"default: 300000"})]}),e.jsx("input",{id:"bg-thinkingLoopTimeout",type:"number",min:3e4,max:9e5,step:1e3,value:l.backgroundThinkingLoopTimeoutMs??3e5,onChange:p=>o(f=>({...f,backgroundThinkingLoopTimeoutMs:Math.max(3e4,Math.min(9e5,parseInt(p.target.value,10)||3e5))}))}),e.jsxs("small",{className:"muted",children:["Plugin option: ",e.jsx("code",{children:"backgroundThinkingLoopTimeoutMs"})]})]}),e.jsxs("div",{className:"form-row",children:[e.jsxs("label",{htmlFor:"bg-maxInterventions",children:["Max interventions",e.jsx("span",{className:"meta-badge",children:"default: 1"})]}),e.jsx("input",{id:"bg-maxInterventions",type:"number",min:1,max:3,value:l.backgroundMaxInterventions??1,onChange:p=>o(f=>({...f,backgroundMaxInterventions:Math.max(1,Math.min(3,parseInt(p.target.value,10)||1))}))}),e.jsxs("small",{className:"muted",children:["Plugin option: ",e.jsx("code",{children:"backgroundMaxInterventions"})]})]}),e.jsxs("div",{className:"form-row",children:[e.jsxs(M,{variant:"secondary",size:"sm",onClick:c,children:[e.jsx(Is,{size:14})," Save plugin options"]}),e.jsx(M,{variant:"secondary",size:"sm",onClick:u,children:"Cleanup old instances (>7 days)"})]}),e.jsx("div",{className:"form-row",children:e.jsxs("small",{children:["Plugin options are read at startup. Save changes and run ",e.jsx("code",{children:"bizar update"})," to apply."]})})]})]})}function cc({workspaceId:s,onInviteCreated:t}){const a=Pe(),[n,i]=r.useState(""),[l,o]=r.useState("editor"),[c,u]=r.useState([]),[x,h]=r.useState(!1),[m,d]=r.useState(!1),[p,f]=r.useState(null),[b,k]=r.useState(null);r.useEffect(()=>{w()},[s]);async function w(){h(!0);try{const R=await $.get(`/workspaces/${s}/invites`);u(R.invites||[])}catch{}finally{h(!1)}}async function v(R){if(R.preventDefault(),!!n.trim()){d(!0),k(null);try{const S=await $.post(`/workspaces/${s}/invites`,{email:n.trim(),role:l});i(""),await w(),t==null||t(),a.open({title:"Invite Link Created",children:e.jsxs("div",{className:"invite-link-dialog",children:[e.jsxs("p",{children:["Share this link with ",e.jsx("strong",{children:n})," to invite them as ",e.jsx("strong",{children:l}),":"]}),e.jsxs("div",{className:"invite-url-box",children:[e.jsx(ii,{size:14}),e.jsx("input",{type:"text",readOnly:!0,value:S.url,onClick:N=>N.target.select()}),e.jsx("button",{type:"button",className:"invite-copy-btn",onClick:()=>{navigator.clipboard.writeText(S.url).catch(()=>{}),f(S.token),setTimeout(()=>f(null),2e3)},children:p===S.token?e.jsx(cs,{size:14}):e.jsx(os,{size:14})})]}),e.jsx("p",{className:"invite-url-note",children:"This link expires in 7 days."})]}),footer:e.jsx(M,{variant:"primary",size:"sm",onClick:()=>a.close(),children:"Done"})})}catch(S){k(S.message||"Failed to create invite")}finally{d(!1)}}}async function C(R){if(confirm("Revoke this invite?"))try{await $.del(`/workspaces/${s}/invites/${R}`),await w()}catch(S){k(S.message||"Failed to revoke invite")}}function z(R,S){navigator.clipboard.writeText(R).catch(()=>{}),f(S),setTimeout(()=>f(null),2e3)}const y={admin:"role-admin",editor:"role-editor",viewer:"role-viewer"};return e.jsxs("div",{className:"invite-dialog",children:[e.jsxs("form",{className:"invite-form",onSubmit:v,children:[e.jsxs("div",{className:"invite-form-row",children:[e.jsxs("div",{className:"invite-form-field",children:[e.jsx("label",{htmlFor:"invite-email",children:"Email address"}),e.jsx("input",{id:"invite-email",type:"email",value:n,onChange:R=>i(R.target.value),placeholder:"colleague@example.com",required:!0})]}),e.jsxs("div",{className:"invite-form-field invite-form-field-role",children:[e.jsx("label",{htmlFor:"invite-role",children:"Role"}),e.jsxs("select",{id:"invite-role",value:l,onChange:R=>o(R.target.value),children:[e.jsx("option",{value:"viewer",children:"Viewer"}),e.jsx("option",{value:"editor",children:"Editor"}),e.jsx("option",{value:"admin",children:"Admin"})]})]}),e.jsxs(M,{type:"submit",variant:"primary",size:"sm",loading:m,disabled:!n.trim(),children:[e.jsx(ni,{size:13}),"Invite"]})]}),b&&e.jsx("p",{className:"invite-error",children:b})]}),e.jsxs("div",{className:"invite-list",children:[e.jsx("h4",{className:"invite-list-title",children:"Pending Invites"}),x&&e.jsx("p",{className:"invite-loading",children:"Loading..."}),!x&&c.length===0&&e.jsx("p",{className:"invite-empty",children:"No pending invites"}),c.map(R=>e.jsxs("div",{className:"invite-item",children:[e.jsxs("div",{className:"invite-item-info",children:[e.jsx("span",{className:"invite-item-email",children:R.email}),e.jsx("span",{className:W("invite-item-role",y[R.role]),children:R.role})]}),e.jsxs("div",{className:"invite-item-actions",children:[e.jsx("button",{type:"button",className:"invite-action-btn",title:"Copy invite link",onClick:()=>{const S=`${window.location.origin}/accept-invite?token=${R.token}`;z(S,R.token)},children:p===R.token?e.jsx(cs,{size:13}):e.jsx(os,{size:13})}),e.jsx("button",{type:"button",className:"invite-action-btn invite-action-revoke",title:"Revoke invite",onClick:()=>C(R.token),children:e.jsx(Re,{size:13})})]})]},R.token))]})]})}const oc={admin:ri,editor:fs,viewer:As},dc={admin:"role-admin",editor:"role-editor",viewer:"role-viewer"};function mc(){const[s,t]=r.useState([]),[a,n]=r.useState(!0),[i,l]=r.useState(!1),[o,c]=r.useState(""),[u,x]=r.useState(null),[h,m]=r.useState(null),d=Pe();r.useEffect(()=>{p()},[]);async function p(){n(!0);try{const w=await $.get("/workspaces");t(w.workspaces||[])}catch{x("Failed to load workspaces")}finally{n(!1)}}async function f(w){if(w.preventDefault(),!!o.trim()){l(!0);try{await $.post("/workspaces",{name:o.trim()}),c(""),await p()}catch(v){x(v.message||"Failed to create workspace")}finally{l(!1)}}}async function b(w,v){if(confirm(`Delete workspace "${v}"?`)&&confirm("This cannot be undone."))try{await $.del(`/workspaces/${w}`),await p()}catch(C){x(C.message||"Failed to delete workspace")}}function k(w){navigator.clipboard.writeText(`${window.location.origin}/accept-invite?workspace=${w}`).catch(()=>{}),m(w),setTimeout(()=>m(null),2e3)}return a?e.jsx("div",{className:"settings-section-loading",children:"Loading workspaces..."}):e.jsxs("div",{className:"settings-section settings-section-workspaces",children:[e.jsx("h3",{className:"settings-section-title",children:"Workspaces"}),e.jsx("p",{className:"settings-section-desc",children:"Workspaces let you share access with team members. Each workspace has its own members, settings, and data."}),u&&e.jsxs("div",{className:"settings-section-error",children:[e.jsx("span",{children:u}),e.jsx("button",{onClick:()=>x(null),children:"×"})]}),e.jsxs("form",{className:"workspace-create-form",onSubmit:f,children:[e.jsx("input",{type:"text",placeholder:"New workspace name",value:o,onChange:w=>c(w.target.value),maxLength:64}),e.jsxs(M,{type:"submit",variant:"primary",size:"sm",loading:i,disabled:!o.trim(),children:[e.jsx(Ee,{size:13}),"Create"]})]}),e.jsxs("div",{className:"workspace-list",children:[s.length===0&&e.jsx("p",{className:"workspace-list-empty",children:"No workspaces yet. Create one above."}),s.map(({workspace:w,role:v})=>{const C=oc[v]||As;return e.jsxs("div",{className:"workspace-item",children:[e.jsxs("div",{className:"workspace-item-info",children:[e.jsx("div",{className:"workspace-item-icon",children:e.jsx(Hs,{size:16})}),e.jsxs("div",{className:"workspace-item-details",children:[e.jsx("span",{className:"workspace-item-name",children:w.name}),e.jsxs("span",{className:W("workspace-item-role",dc[v]),children:[e.jsx(C,{size:11}),v]})]})]}),e.jsxs("div",{className:"workspace-item-actions",children:[e.jsx(M,{variant:"ghost",size:"sm",iconOnly:!0,title:"Copy invite link",onClick:()=>k(w.id),children:h===w.id?e.jsx(cs,{size:13}):e.jsx(os,{size:13})}),v==="admin"&&e.jsx(M,{variant:"ghost",size:"sm",iconOnly:!0,title:"Manage members",onClick:()=>{d.open({title:`Manage "${w.name}"`,children:e.jsx(cc,{workspaceId:w.id,onInviteCreated:()=>p()}),width:520})},children:e.jsx(Hs,{size:13})}),v==="admin"&&s.length>1&&e.jsx(M,{variant:"ghost",size:"sm",iconOnly:!0,title:"Delete workspace",onClick:()=>b(w.id,w.name),children:e.jsx(Re,{size:13})})]})]},w.id)})]})]})}const uc=[{id:"theme",label:"Theme"},{id:"updates",label:"Updates"},{id:"layout",label:"Layout"},{id:"general",label:"General"},{id:"env-vars",label:"Env Vars"},{id:"network",label:"Network"},{id:"notifications",label:"Notifications"},{id:"auth",label:"Auth"},{id:"agents",label:"Agents"},{id:"dashboard",label:"Dashboard"},{id:"background",label:"Background"},{id:"system-llm",label:"System LLM"},{id:"headroom",label:"Headroom"},{id:"activity-log",label:"Activity"},{id:"about",label:"About"},{id:"workspaces",label:"Workspaces"}],hc=[{id:"theme",label:"Theme",fields:[{key:"theme.presets",label:"Accent presets",section:"theme"},{key:"theme.accent",label:"Accent color",section:"theme"},{key:"theme.success",label:"Success color",section:"theme"},{key:"theme.warning",label:"Warning color",section:"theme"},{key:"theme.error",label:"Error color",section:"theme"},{key:"theme.info",label:"Info color",section:"theme"},{key:"theme.fontFamily",label:"Font family",section:"theme"},{key:"theme.fontSize",label:"Font size",section:"theme"},{key:"theme.compactMode",label:"Compact mode",section:"theme"},{key:"theme.animations",label:"Animations",section:"theme"}]},{id:"updates",label:"Updates",fields:[{key:"updates.channel",label:"Update channel",section:"updates"}]},{id:"layout",label:"Layout",fields:[{key:"ui.layout",label:"UI layout",section:"layout"},{key:"ui.showHeader",label:"Show header",section:"layout"},{key:"ui.showStatusBar",label:"Show status bar",section:"layout"},{key:"ui.defaultTab",label:"Default tab",section:"layout"}]},{id:"general",label:"General",fields:[{key:"defaultAgent",label:"Default agent",section:"general"},{key:"defaultModel",label:"Model override",section:"general"}]},{id:"env-vars",label:"Environment Variables",fields:[{key:"env-vars.count",label:"Env var count",section:"env-vars"}]},{id:"network",label:"Network",fields:[{key:"tailscale.enabled",label:"Tailscale Serve",section:"network"},{key:"tailscale.port",label:"Tailscale port",section:"network"},{key:"tailscale.https",label:"Tailscale HTTPS",section:"network"},{key:"tailscale.hostname",label:"Tailscale hostname",section:"network"}]},{id:"notifications",label:"Notifications",fields:[{key:"notifications.onAgentComplete",label:"Notify on agent complete",section:"notifications"},{key:"notifications.onPlanApproval",label:"Notify on plan approval",section:"notifications"}]},{id:"auth",label:"Auth",fields:[{key:"auth.enabled",label:"Auth enabled",section:"auth"},{key:"auth.loopback",label:"Loopback mode",section:"auth"},{key:"auth.token",label:"Auth token",section:"auth"}]},{id:"agents",label:"Agents",fields:[{key:"agents.maxParallel",label:"Max parallel agents",section:"agents"},{key:"agents.stuckThresholdMs",label:"Stuck threshold",section:"agents"},{key:"agents.autoRestart",label:"Auto restart",section:"agents"},{key:"workflow.artifactsEnabled",label:"Artifacts enabled",section:"agents"},{key:"workflow.agentsDecideAutonomously",label:"Autonomous decisions",section:"agents"}]},{id:"dashboard",label:"Dashboard",fields:[{key:"dashboard.autoLaunchWeb",label:"Auto-launch web",section:"dashboard"},{key:"dashboard.projectsDirectory",label:"Projects directory",section:"dashboard"},{key:"dashboard.allowedRoots",label:"Allowed roots",section:"dashboard"}]},{id:"background",label:"Background",fields:[{key:"service.enabled",label:"Background service",section:"background"},{key:"service.autostart",label:"Auto-start service",section:"background"}]},{id:"system-llm",label:"System LLM",fields:[{key:"systemLlm.enabled",label:"System LLM enabled",section:"system-llm"}]},{id:"headroom",label:"Headroom",fields:[{key:"headroom.enabled",label:"Headroom enabled",section:"headroom"},{key:"headroom.port",label:"Headroom port",section:"headroom"},{key:"headroom.budget",label:"Headroom budget",section:"headroom"},{key:"headroom.backend",label:"Headroom backend",section:"headroom"}]},{id:"activity-log",label:"Activity",fields:[{key:"activity.log",label:"Activity log",section:"activity-log"}]},{id:"about",label:"About",fields:[{key:"about.version",label:"Version",section:"about"},{key:"about.homepage",label:"Homepage",section:"about"},{key:"about.license",label:"License",section:"about"}]}];function xc({settings:s,refreshSnapshot:t,settingsMode:a,settingsActiveSection:n,setSettingsActiveSection:i,setActiveTab:l}){const o=ce(),[c,u]=r.useState(s),[x,h]=r.useState(!1),[m,d]=r.useState(!1),[p,f]=r.useState(null),[b,k]=r.useState({port:4321,https:!0,hostname:""}),[w,v]=r.useState(null),C=()=>{l("overview")};r.useEffect(()=>{u(s),h(!1),s.theme&&Cs(s.theme)},[s]),r.useEffect(()=>{p&&k({port:p.settings.port,https:p.settings.https!==!1,hostname:p.settings.hostname||""})},[p]),r.useEffect(()=>{$.get("/tailscale/status").then(f).catch(()=>{})},[]);const z=r.useRef(null),y=r.useCallback(async(I,V)=>{u(ie=>({...ie,[I]:V})),z.current&&clearTimeout(z.current),z.current=setTimeout(async()=>{try{await $.put("/settings",{...c,[I]:V})}catch(ie){is.error("autoSave failed",ie)}},300)},[c]);r.useEffect(()=>()=>{z.current&&clearTimeout(z.current)},[]);const R=I=>{u(V=>{const ie={...V,theme:{...V.theme,...I}};return Cs(ie.theme),ie}),h(!0)},S=I=>{u(V=>({...V,ui:{...V.ui,...I}})),h(!0)},N=(I,V)=>{u(ie=>({...ie,[I]:V})),h(!0)},P=I=>{u(V=>({...V,notifications:{...V.notifications,...I}})),h(!0)},g=I=>{u(V=>({...V,agents:{...V.agents,...I}})),h(!0)},j=I=>{u(V=>({...V,dashboard:{...V.dashboard,...I}})),h(!0)},[T,F]=r.useState(()=>{if(typeof window>"u")return null;const I=window.location.hash.replace(/^#settings-/,"");return uc.some(V=>V.id===I)?I:null}),A=a?n??null:T,U=I=>{if(a)i==null||i(I);else{F(I);try{if(history.replaceState(null,"",I?`#settings-${I}`:window.location.pathname),I){const V=document.getElementById(`settings-${I}`);V&&V.scrollIntoView({behavior:"smooth",block:"start"})}else window.scrollTo({top:0,behavior:"smooth"})}catch{}}if(I){const V=document.getElementById(`settings-${I}`);V&&V.scrollIntoView({behavior:"smooth",block:"start"})}else window.scrollTo({top:0,behavior:"smooth"})},Y=async()=>{try{p!=null&&p.settings.enabled?(await $.post("/tailscale/disable"),o.success("Tailscale serve disabled.")):(await $.post("/tailscale/enable",{port:b.port||4321,https:b.https,hostname:b.hostname||""}),o.success("Tailscale serve enabled.")),f(await $.get("/tailscale/status"))}catch(I){o.error(`Tailscale failed: ${I.message}`)}},B=async()=>{d(!0);try{const I=await $.put("/settings",c);u(I.data),h(!1),qs(I.data.theme),Cs(I.data.theme),o.success("Settings saved."),await t()}catch(I){o.error(`Save failed: ${I.message}`)}finally{d(!1)}},K=async()=>{try{const I=await $.get("/settings");u(I.data),h(!1),qs(I.data.theme),Cs(I.data.theme),o.info("Settings reloaded.",1500)}catch(I){o.error(`Reload failed: ${I.message}`)}},D=async()=>{if(confirm("Reset all settings to defaults?"))try{const I=await $.post("/settings/reset");u(I.data),h(!1),qs(I.data.theme),Cs(I.data.theme),o.success("Settings reset."),await t()}catch(I){o.error(`Reset failed: ${I.message}`)}},_={settings:c,patchTheme:R,patchUi:S,patchTop:N,patchNotifications:P,patchAgents:g,patchDashboard:j},ae=c.about||{version:"3.0.4",homepage:"https://github.com/DrB0rk/BizarHarness",license:"MIT"},J=A===null,ne=I=>A===I;return e.jsxs("div",{className:"view view-settings",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(Qt,{size:18})," Settings"]}),e.jsxs("p",{className:"view-subtitle",children:["Personal preferences. Changes are saved to ",e.jsx("code",{children:"~/.config/bizar/settings.json"}),"."]})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs(M,{variant:"ghost",size:"sm",onClick:D,children:[e.jsx(Wa,{size:14})," Reset"]}),e.jsxs(M,{variant:"secondary",size:"sm",onClick:K,children:[e.jsx(me,{size:14})," Reload"]}),e.jsxs(M,{variant:"primary",size:"sm",disabled:!x||m,onClick:B,children:[m?e.jsx("span",{className:"btn-spinner"}):e.jsx(Is,{size:14}),m?"Saving…":"Save"]})]})]}),a&&e.jsxs("div",{className:"settings-mode-banner",children:[e.jsx("span",{children:"You're in settings mode. All sections are visible in the sidebar."}),e.jsx(M,{variant:"secondary",size:"sm",onClick:C,children:"← Back to main view"})]}),e.jsx(Zl,{sections:hc,onJump:U}),e.jsxs("div",{className:W("settings-grid",A&&"settings-grid-filtered"),"data-active-section":A||void 0,children:[(J||ne("theme"))&&e.jsx("div",{id:"settings-theme",children:e.jsx(ac,{..._})}),(J||ne("updates"))&&e.jsx("div",{id:"settings-updates",children:e.jsx(wi,{})}),(J||ne("layout"))&&e.jsx("div",{id:"settings-general",children:e.jsx(Si,{..._,autoSave:y})}),(J||ne("env-vars"))&&e.jsx("div",{id:"settings-env-vars",children:e.jsx(Ci,{})}),(J||ne("network")||ne("service")||ne("tailscale"))&&e.jsx("div",{id:"settings-network",children:e.jsx(nc,{tailscale:p,tailscaleDraft:b,setTailscaleDraft:k,onTailscaleToggle:Y})}),(J||ne("network")||ne("tailscale"))&&e.jsx(zi,{initialStatus:p}),(J||ne("notifications"))&&e.jsx("div",{id:"settings-notifications",children:e.jsx(ic,{..._})}),(J||ne("auth"))&&e.jsx("div",{id:"settings-auth",children:e.jsx(rc,{settings:c,authStatus:w,setAuthStatus:v})}),(J||ne("agents")||ne("dashboard")||ne("background"))&&e.jsx("div",{id:"settings-agents",children:e.jsx(lc,{..._,autoSave:y})}),(J||ne("system-llm"))&&e.jsx("div",{id:"settings-system-llm",children:e.jsx($i,{..._})}),(J||ne("headroom"))&&e.jsx("div",{id:"settings-headroom",children:e.jsx(Ri,{settings:c,setSettings:u,setDirty:h})}),(J||ne("activity-log")||ne("about"))&&e.jsx("div",{id:"settings-activity-log",children:e.jsx(Ti,{about:ae})}),(J||ne("workspaces"))&&e.jsx("div",{id:"settings-workspaces",children:e.jsx(mc,{})})]})]})}const wa=Ke.memo(xc);function pc({snapshot:s,refreshSnapshot:t}){const a=ce(),n=Pe(),[i,l]=r.useState(Array.isArray(s.mods)?s.mods:[]),[o,c]=r.useState(!0),[u,x]=r.useState(null),[h,m]=r.useState([]),[d,p]=r.useState(null),[f,b]=r.useState(!1),[k,w]=r.useState(null),[v,C]=r.useState(!1),[z,y]=r.useState({}),R=async()=>{var A,U,Y;C(!0);try{const B=await $.get("/mods/registry");w({source:((A=B.registry)==null?void 0:A.source)||"",version:(U=B.registry)==null?void 0:U.version,updatedAt:(Y=B.registry)==null?void 0:Y.updatedAt,mods:B.mods||[]})}catch(B){w({source:"",mods:[],error:B.message})}finally{C(!1)}},S=async A=>{y(U=>({...U,[A]:!0}));try{const U=await $.post("/mods",{id:A});l(Y=>[...Y.filter(B=>B.id!==U.id),U]),a.success(`Mod "${U.id}" installed from registry.`),await t()}catch(U){a.error(`Install failed: ${U.message}`)}finally{y(U=>({...U,[A]:!1}))}},N=async(A,U=!1)=>{y(Y=>({...Y,[A]:!0}));try{const Y=await $.post(`/mods/${encodeURIComponent(A)}/upgrade`,{backup:U});l(K=>[...K.filter(D=>D.id!==Y.mod.id),Y.mod]);const B=Y.backupPath?` (backup at ${Y.backupPath})`:"";a.success(`Mod "${A}" upgraded v${Y.from} → v${Y.to}${B}.`),await t()}catch(Y){a.error(`Upgrade failed: ${Y.message}`)}finally{y(Y=>({...Y,[A]:!1}))}},P=async()=>{try{const A=await $.get("/mods");l(A.mods||[]);try{const U=await $.get("/mods/views");m(U.views||[])}catch{m([])}}catch(A){a.error(`Mods load failed: ${A.message}`)}finally{c(!1)}};r.useEffect(()=>{P()},[]),r.useEffect(()=>{Array.isArray(s.mods)&&s.mods!==i&&l(s.mods)},[s.mods]);const g=()=>{let A=null;n.open({title:"Install mod",children:e.jsxs("div",{children:[e.jsxs("p",{className:"muted",children:["Provide the absolute path to a mod folder (one that contains a ",e.jsx("code",{children:"mod.json"}),"). The folder will be copied to"," ",e.jsx("code",{children:"~/.config/bizar/mods/<id>/"}),"."]}),e.jsx("label",{className:"field-label",htmlFor:"install-mod-path",children:"Path"}),e.jsx("input",{id:"install-mod-path",ref:U=>A=U,className:"input",type:"text",placeholder:"/path/to/my-mod",autoFocus:!0})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx(M,{variant:"ghost",onClick:()=>n.close(),children:"Cancel"}),e.jsx(M,{variant:"primary",onClick:async()=>{const U=((A==null?void 0:A.value)||"").trim();if(!U){a.warning("Path is required.");return}try{const Y=await $.post("/mods",{path:U});l(B=>[...B,Y]),a.success(`Mod "${Y.id}" installed.`),n.close(),await t()}catch(Y){a.error(`Install failed: ${Y.message}`)}},children:"Install"})]})})},j=async A=>{if(confirm(`Uninstall mod "${A}"? This removes the folder from ~/.config/bizar/mods/.`))try{await $.del(`/mods/${encodeURIComponent(A)}`),l(U=>U.filter(Y=>Y.id!==A)),u===A&&x(null),a.success("Mod uninstalled.")}catch(U){a.error(`Uninstall failed: ${U.message}`)}},T=async A=>{try{const U=await $.put(`/mods/${encodeURIComponent(A.id)}`,{enabled:!A.enabled});l(Y=>Y.map(B=>B.id===A.id?U:B)),a.success(`Mod ${U.enabled?"enabled":"disabled"}.`)}catch(U){a.error(`Toggle failed: ${U.message}`)}},F=i.find(A=>A.id===u)||null;return o?e.jsx("div",{className:"view-loading",children:e.jsx(he,{size:"lg"})}):e.jsxs("div",{className:"view view-mods",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(Rs,{size:18})," Mods (",i.length,")"]}),e.jsxs("p",{className:"view-subtitle",children:["Extensions installed in ",e.jsx("code",{children:"~/.config/bizar/mods/"}),". Mods can add agents, commands, routes, and views."]})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs(M,{variant:"secondary",size:"sm",onClick:P,children:[e.jsx(me,{size:14})," Refresh"]}),e.jsxs(M,{variant:"primary",size:"sm",onClick:g,children:[e.jsx(Ee,{size:14})," Install mod"]})]})]}),i.length===0?e.jsx(Ne,{icon:e.jsx(Rs,{size:32}),title:"No mods installed",message:"Mods are folders with a mod.json. Install one to extend Bizar with custom agents, commands, and views."}):e.jsxs("div",{className:"mods-layout",children:[e.jsx("div",{className:"mods-list",children:i.map(A=>e.jsxs("div",{className:W("mod-list-item",u===A.id&&"mod-list-item-active"),onClick:()=>x(A.id),children:[e.jsxs("div",{className:"mod-list-item-head",children:[e.jsxs("div",{children:[e.jsx("div",{className:"mod-list-item-name",children:A.name}),e.jsxs("div",{className:"mod-list-item-meta",children:["v",A.version," · ",A.type," · ",A.author]})]}),e.jsxs("div",{className:"mod-list-item-actions",onClick:U=>U.stopPropagation(),children:[e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Toggle enabled",title:A.enabled?"Disable":"Enable",onClick:()=>T(A),children:e.jsx(qa,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger","aria-label":"Uninstall",title:"Uninstall",onClick:()=>j(A.id),children:e.jsx(Re,{size:12})})]})]}),e.jsx("div",{className:"mod-list-item-desc ellipsis-2",title:A.description,children:A.description}),e.jsx("div",{className:"mod-list-item-status",children:e.jsx("span",{className:`mod-mini-pill ${A.enabled?"mod-mini-pill-on":"mod-mini-pill-off"}`,children:A.enabled?"enabled":"disabled"})})]},A.id))}),F&&e.jsx(gc,{mod:F})]}),e.jsxs(G,{className:"mods-registry-card",children:[e.jsxs("button",{type:"button",className:"mods-registry-head","aria-expanded":f,"aria-controls":"mods-registry-body",onClick:()=>{!k&&!v&&R(),b(A=>!A)},children:[e.jsx(Ks,{size:14,"aria-hidden":!0}),e.jsx("span",{className:"mods-registry-title",children:"Mod registry"}),e.jsx("span",{className:"muted",style:{fontSize:11},children:k!=null&&k.mods?`${k.mods.length} available`:"click to browse"}),e.jsx("span",{className:"mods-registry-spacer"}),f?e.jsx(He,{size:14,"aria-hidden":!0}):e.jsx(ds,{size:14,"aria-hidden":!0})]}),f&&e.jsx("div",{id:"mods-registry-body",className:"mods-registry-body",children:v?e.jsx("div",{className:"muted",style:{padding:12,fontSize:12},children:"Loading registry…"}):k!=null&&k.error?e.jsxs("div",{className:"mods-registry-error",children:[e.jsx(Ys,{size:12})," Could not load registry: ",k.error]}):!k||k.mods.length===0?e.jsx("div",{className:"muted",style:{padding:12,fontSize:12},children:"No mods listed in the registry yet."}):e.jsxs(e.Fragment,{children:[k.source&&e.jsxs("div",{className:"muted",style:{fontSize:11,marginBottom:8},children:["Source: ",e.jsx("code",{children:k.source})]}),e.jsx("div",{className:"mods-registry-grid",children:k.mods.map(A=>{const U=i.some(B=>B.id===A.id),Y=!!z[A.id];return e.jsxs("div",{className:"mod-registry-card",children:[e.jsxs("div",{className:"mod-registry-card-head",children:[e.jsx("div",{className:"mod-registry-card-name",children:A.name}),A.latest&&e.jsxs("span",{className:W("mod-registry-version",A.upgradeAvailable&&"mod-registry-version-upgrade"),children:["v",A.latest,A.upgradeAvailable?" ↑":""]})]}),A.description&&e.jsx("div",{className:"mod-registry-card-desc",children:A.description}),e.jsxs("div",{className:"mod-registry-card-meta",children:[A.author&&e.jsxs("span",{className:"muted",children:["by ",A.author]}),A.homepage&&e.jsx("a",{href:A.homepage,target:"_blank",rel:"noopener noreferrer",className:"mod-registry-link",children:"homepage"})]}),(A.permissions||[]).length>0&&e.jsxs("div",{className:"mod-registry-perms",children:[e.jsx(Ys,{size:10}),(A.permissions||[]).slice(0,4).map(B=>e.jsx("span",{className:"mod-registry-perm",children:B},B)),(A.permissions||[]).length>4&&e.jsxs("span",{className:"mod-registry-perm-more",children:["+",A.permissions.length-4]})]}),e.jsxs("div",{className:"mod-registry-card-actions",children:[!U&&e.jsx(M,{variant:"primary",size:"sm",disabled:Y,onClick:()=>S(A.id),title:"Install from registry",children:Y?e.jsx(he,{size:"sm"}):e.jsxs(e.Fragment,{children:[e.jsx(js,{size:12})," Install"]})}),U&&A.upgradeAvailable&&e.jsx(M,{variant:"primary",size:"sm",disabled:Y,onClick:()=>N(A.id),title:`Upgrade from v${A.installedVersion||"?"} to v${A.upgradeAvailable}`,children:Y?e.jsx(he,{size:"sm"}):e.jsxs(e.Fragment,{children:[e.jsx(js,{size:12})," Upgrade to v",A.upgradeAvailable]})}),U&&!A.upgradeAvailable&&e.jsxs(M,{variant:"ghost",size:"sm",disabled:!0,title:`Installed v${A.installedVersion||"?"}`,children:["Installed v",A.installedVersion||"?"]})]})]},A.id)})})]})})]}),h.length>0&&e.jsxs(G,{className:"mod-views-hint",children:[e.jsxs(ee,{children:[e.jsx(Ks,{size:14})," Mod views"]}),e.jsxs(te,{children:[h.length," mod-supplied view",h.length===1?"":"s"," are now available in the sidebar navigation. Look for the ",e.jsx("strong",{children:"Mods"})," section at the bottom of the sidebar."]})]}),d&&e.jsxs("div",{className:"mod-iframe-panel",children:[e.jsxs("div",{className:"mod-iframe-header",children:[e.jsxs("span",{children:["Mod view — ",e.jsx("a",{href:d,target:"_blank",rel:"noreferrer",children:d})]}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Close iframe",onClick:()=>p(null),children:e.jsx(we,{size:14})})]}),e.jsx("iframe",{src:d,className:"mod-iframe",title:"Mod view",sandbox:"allow-scripts allow-same-origin allow-forms allow-popups"})]})]})}function gc({mod:s}){const t=ce(),[a,n]=r.useState(null),[i,l]=r.useState(!1),[o,c]=r.useState(!1),[u,x]=r.useState(null),h=async()=>{l(!0);try{const d=await $.get(`/mods/${s.id}/instructions`);n(d),c(!0)}catch(d){t.error(`Failed to load instructions: ${d.message}`)}finally{l(!1)}},m=async()=>{try{const d=await $.post(`/mods/${s.id}/instructions/reinstall`,{});t.success(`Reinstalled: ${d.counts.agents} agents, ${d.counts.commands} commands, ${d.counts.skills} skills, ${d.counts.instructions} instructions.`),await h()}catch(d){t.error(`Reinstall failed: ${d.message}`)}};return e.jsxs(G,{className:"mod-details",children:[e.jsxs(ee,{children:[e.jsx(Ie,{size:14})," Mod details — ",s.name]}),e.jsx(te,{children:e.jsx("code",{children:s.path})}),e.jsxs("dl",{className:"env-table",children:[e.jsx("dt",{children:"ID"}),e.jsx("dd",{className:"mono",children:s.id}),e.jsx("dt",{children:"Version"}),e.jsx("dd",{className:"mono",children:s.version}),e.jsx("dt",{children:"Type"}),e.jsx("dd",{className:"mono",children:s.type}),e.jsx("dt",{children:"Author"}),e.jsx("dd",{className:"mono",children:s.author||"—"}),e.jsx("dt",{children:"Bizar"}),e.jsx("dd",{className:"mono",children:s.bizar||"*"}),e.jsx("dt",{children:"Enabled"}),e.jsx("dd",{children:s.enabled?"yes":"no"}),e.jsx("dt",{children:"Permissions"}),e.jsxs("dd",{children:[(s.permissions||[]).map(d=>e.jsx("span",{className:"tag",children:d},d)),(s.permissions||[]).length===0&&e.jsx("span",{className:"muted",children:"(none)"})]})]}),e.jsxs("div",{className:"mod-files",children:[e.jsx("div",{className:"muted",children:"Files"}),e.jsx("ul",{children:(s.files||[]).map(d=>e.jsxs("li",{children:[e.jsx("span",{className:"mod-file-cat",children:d.category}),e.jsx("span",{className:"mono",children:d.path})]},d.path))})]}),e.jsxs("div",{className:"mod-instructions",children:[e.jsxs("button",{type:"button",className:"mod-instructions-head","aria-expanded":o,"aria-controls":`mod-instructions-body-${s.id}`,onClick:()=>{!a&&!i&&h(),c(d=>!d)},children:[e.jsx(li,{size:14,"aria-hidden":!0}),e.jsx("span",{children:"Installed instructions"}),e.jsx("span",{className:"muted",style:{fontSize:11},children:a?`${a.total} files`:"click to view"}),e.jsx("span",{className:"mod-instructions-spacer"}),o?e.jsx(He,{size:14,"aria-hidden":!0}):e.jsx(ds,{size:14,"aria-hidden":!0})]}),o&&a&&e.jsxs("div",{id:`mod-instructions-body-${s.id}`,className:"mod-instructions-body",children:[a.agents.length>0&&e.jsxs("div",{className:"mod-instructions-section",children:[e.jsxs("div",{className:"mod-instructions-section-title",children:[e.jsx(ci,{size:11})," Agents (",a.agents.length,")"]}),a.agents.map(d=>e.jsxs("div",{className:"mod-instructions-file",children:[e.jsxs("div",{className:"mod-instructions-file-head",onClick:()=>x(p=>p===d.filename?null:d.filename),children:[e.jsx("span",{className:"mono",children:d.filename}),e.jsxs("span",{className:"muted",style:{fontSize:10},children:["installed at ",d.fullPath]})]}),u===d.filename&&e.jsx("pre",{className:"mod-instructions-content",children:d.content||e.jsx("em",{className:"muted",children:"(file missing on disk)"})})]},d.filename))]}),a.commands.length>0&&e.jsxs("div",{className:"mod-instructions-section",children:[e.jsxs("div",{className:"mod-instructions-section-title",children:[e.jsx(Ts,{size:11})," Commands (",a.commands.length,")"]}),a.commands.map(d=>e.jsxs("div",{className:"mod-instructions-file",children:[e.jsxs("div",{className:"mod-instructions-file-head",onClick:()=>x(p=>p===d.filename?null:d.filename),children:[e.jsx("span",{className:"mono",children:d.filename}),e.jsxs("span",{className:"muted",style:{fontSize:10},children:["installed at ",d.fullPath]})]}),u===d.filename&&e.jsx("pre",{className:"mod-instructions-content",children:d.content||e.jsx("em",{className:"muted",children:"(file missing on disk)"})})]},d.filename))]}),a.skills.length>0&&e.jsxs("div",{className:"mod-instructions-section",children:[e.jsxs("div",{className:"mod-instructions-section-title",children:[e.jsx(ta,{size:11})," Skills (",a.skills.length,")"]}),a.skills.map(d=>e.jsxs("div",{className:"mod-instructions-file",children:[e.jsxs("div",{className:"mod-instructions-file-head",onClick:()=>x(p=>p===d.name?null:d.name),children:[e.jsx("span",{className:"mono",children:d.name}),e.jsxs("span",{className:"muted",style:{fontSize:10},children:["installed at ",d.fullPath]})]}),u===d.name&&e.jsx("pre",{className:"mod-instructions-content",children:d.content||e.jsx("em",{className:"muted",children:"(file missing on disk)"})})]},d.name))]}),a.total===0&&e.jsxs("div",{className:"muted",style:{padding:8,fontSize:12},children:["This mod did not install any instruction files. Mods install instructions by shipping a top-level ",e.jsx("code",{children:"INSTRUCTIONS.md"}),", an ",e.jsx("code",{children:"agents/"})," directory, a ",e.jsx("code",{children:"commands/"})," directory, or a ",e.jsx("code",{children:"skills/"})," directory."]}),e.jsx("div",{className:"mod-instructions-actions",children:e.jsxs(M,{variant:"ghost",size:"sm",onClick:m,children:[e.jsx(me,{size:11})," Reinstall from mod folder"]})})]})]})]})}function fc({viewId:s,reloadKey:t,setActiveTab:a}){const n=ce(),[i,l]=r.useState(null),[o,c]=r.useState(!0),[u,x]=r.useState(0);if(r.useEffect(()=>{let h=!1;return(async()=>{try{const m=await $.get("/mods/views");if(h)return;const d=(m.views||[]).find(p=>p.id===s);l(d||null)}catch(m){n.error(`Failed to load mod view: ${m.message}`)}finally{h||c(!1)}})(),()=>{h=!0}},[s,n]),o)return e.jsx(Ne,{title:"Loading mod view…"});if(!i)return e.jsx(Ne,{title:"Mod view not found",message:`No view with id "${s}" is currently installed.`,action:e.jsx(M,{onClick:()=>a("mods"),variant:"primary",size:"sm",children:"Open Mods"})});if(i.kind==="iframe"){const h=`/api/mods/${i.modId}/web/index.html?t=${u+(t||0)}`;return e.jsxs("div",{className:"mod-view-iframe-pane",children:[e.jsxs("div",{className:"mod-view-iframe-header",children:[e.jsxs("span",{className:"mod-view-iframe-label",children:[e.jsx(Ks,{size:14}),i.label,e.jsxs("span",{className:"muted",style:{fontSize:11,fontWeight:400},children:["by ",i.modId]})]}),e.jsxs("div",{className:"mod-view-iframe-actions",children:[e.jsxs(M,{variant:"ghost",size:"sm",onClick:()=>x(m=>m+1),title:"Reload this view",children:[e.jsx(me,{size:11})," Reload"]}),e.jsx("a",{href:h,target:"_blank",rel:"noopener noreferrer",className:"icon-btn",title:"Open in new tab",children:e.jsx(Ls,{size:12})})]})]}),e.jsx("iframe",{src:h,className:"mod-view-iframe",title:i.label},u+(t||0))]})}if(i.component){const h=i.component,m=i.modId,d=r.lazy(()=>yn(()=>import(`/api/mods/${encodeURIComponent(m)}/views/${encodeURIComponent(h)}`),[]).then(p=>({default:p.default??(()=>null)})));return e.jsxs("div",{className:"mod-view-tab-pane",children:[e.jsx("div",{className:"mod-view-iframe-header",children:e.jsxs("span",{className:"mod-view-iframe-label",children:[e.jsx(Xs,{size:14}),i.label,e.jsxs("span",{className:"muted",style:{fontSize:11,fontWeight:400},children:["by ",i.modId]})]})}),e.jsx("div",{className:"mod-view-tab-body",children:e.jsx(jc,{modId:i.modId,component:i.component,children:e.jsx(r.Suspense,{fallback:e.jsxs("div",{style:{padding:24},children:[e.jsx(he,{size:"md"})," ",e.jsx("span",{className:"muted",children:"Loading mod view…"})]}),children:e.jsx(d,{})})})})]})}return e.jsxs(G,{children:[e.jsxs(ee,{children:[e.jsx(Xs,{size:14})," ",i.label]}),e.jsxs(te,{children:["by ",i.modId]}),i.description&&e.jsx("p",{className:"muted",style:{marginTop:8},children:i.description}),e.jsxs("p",{className:"muted",style:{fontSize:12,marginTop:12},children:["This mod declared a tab view but did not provide a component path in views/registry.json. Add a ",e.jsx("code",{children:"component"})," field (e.g. ",e.jsx("code",{children:'"MyView.js"'}),") and ship the file under ",e.jsx("code",{children:"views/"}),"."]}),e.jsx("div",{style:{marginTop:12},children:e.jsx(M,{variant:"secondary",size:"sm",onClick:()=>a("mods"),children:"Open Mods page"})})]})}class jc extends r.Component{constructor(){super(...arguments);Ps(this,"state",{error:null})}static getDerivedStateFromError(a){return{error:a}}componentDidCatch(){}render(){return this.state.error?e.jsxs("div",{className:"mod-view-error",children:[e.jsx(Me,{size:16}),e.jsx("strong",{children:"Failed to render mod view"}),e.jsxs("div",{className:"muted",style:{fontSize:12,marginTop:6},children:[this.props.modId," → ",this.props.component,": ",this.state.error.message]})]}):this.props.children}}function vc(s){if(s.type==="cron"&&s.schedule)return`cron: ${s.schedule}`;if(s.type==="interval"){const a=(s.intervalMs||0)/1e3;return a>=3600?`every ${a/3600}h`:a>=60?`every ${a/60}m`:`every ${a}s`}return s.type}function bc({template:s,onUse:t}){return e.jsxs(G,{className:"schedule-template-card",children:[e.jsxs("div",{className:"schedule-template-header",children:[e.jsx(ee,{children:s.name}),s.tags&&s.tags.length>0&&e.jsx("div",{className:"schedule-template-tags",children:s.tags.map(a=>e.jsx("span",{className:"tag",children:a},a))})]}),e.jsx(te,{children:s.description}),e.jsxs("div",{className:"schedule-template-summary",children:[e.jsx("code",{children:vc(s)})," · ",e.jsx("code",{children:s.action.type})]}),e.jsx(M,{variant:"secondary",size:"sm",onClick:()=>t(s),"aria-label":`Use template: ${s.name}`,children:"Use this template"})]})}const yc=["interval","cron","once"],Nc=["command","agent","webhook"],qt=[{value:"UTC",label:"UTC"},{value:"America/New_York",label:"America/New_York (ET)"},{value:"America/Los_Angeles",label:"America/Los_Angeles (PT)"},{value:"America/Chicago",label:"America/Chicago (CT)"},{value:"Europe/London",label:"Europe/London (UK)"},{value:"Europe/Berlin",label:"Europe/Berlin (CET)"},{value:"Asia/Tokyo",label:"Asia/Tokyo (JST)"}],kc=Array.from({length:12},(s,t)=>t*5),la=Array.from({length:24},(s,t)=>({value:t,label:t===0?"12 AM":t<12?`${t} AM`:t===12?"12 PM":`${t-12} PM`})),ca=[{value:"*",label:"Every day"},{value:"0",label:"Sunday"},{value:"1",label:"Monday"},{value:"2",label:"Tuesday"},{value:"3",label:"Wednesday"},{value:"4",label:"Thursday"},{value:"5",label:"Friday"},{value:"6",label:"Saturday"}],ln=[{value:"s",label:"seconds"},{value:"m",label:"minutes"},{value:"h",label:"hours"},{value:"d",label:"days"}];function cn(s){if(typeof s!="string")return null;const t=s.trim().split(/\s+/);if(t.length!==5)return null;const[a,n,,,i]=t,l=parseInt(a,10),o=parseInt(n,10);if(!Number.isFinite(l)||!Number.isFinite(o)||a!==String(l)||n!==String(o))return null;const c=i==="*"?"*":parseInt(i,10);return c===null||i!=="*"&&!Number.isFinite(c)?null:{minute:l,hour:o,dow:i==="*"?"*":String(c)}}function wc(s){if(typeof s!="string")return null;const t=/^(\d+)\s*([smhd])$/i.exec(s.trim());return t?{n:parseInt(t[1],10),unit:t[2].toLowerCase()}:null}function Sc(s){var l,o;if(!s)return{name:"",type:"cron",cronMinute:0,cronHour:13,cronDow:"0",showAdvanced:!1,rawCron:"0 13 * * 0",intervalN:30,intervalUnit:"m",onceAt:"",timezone:"UTC",customTimezone:"",actionType:"agent",actionTarget:"",actionPrompt:"",skipIfBudgetLow:!1,maxConcurrent:6,enabled:!0,humanLabel:""};const t=s.type==="cron"?cn(s.schedule):null,a=s.type==="interval"?wc(s.schedule):null,n=s.timezone||"UTC",i=qt.some(c=>c.value===n);return{name:s.name||"",type:s.type,cronMinute:(t==null?void 0:t.minute)??0,cronHour:(t==null?void 0:t.hour)??9,cronDow:(t==null?void 0:t.dow)??"*",showAdvanced:!t,rawCron:s.schedule,intervalN:(a==null?void 0:a.n)??30,intervalUnit:(a==null?void 0:a.unit)??"m",onceAt:s.type==="once"?Cc(s.schedule):"",timezone:i?n:"Other…",customTimezone:i?"":n,actionType:s.action.type,actionTarget:s.action.target||"",actionPrompt:s.action.prompt||"",skipIfBudgetLow:!!((l=s.budgetCheck)!=null&&l.skipIfBudgetLow),maxConcurrent:Number.isFinite((o=s.budgetCheck)==null?void 0:o.maxConcurrent)?s.budgetCheck.maxConcurrent:6,enabled:s.enabled!==!1,humanLabel:""}}function Cc(s){if(!s)return"";try{const t=new Date(s);if(Number.isNaN(t.getTime()))return"";const a=n=>String(n).padStart(2,"0");return`${t.getFullYear()}-${a(t.getMonth()+1)}-${a(t.getDate())}T${a(t.getHours())}:${a(t.getMinutes())}`}catch{return""}}function zc(s){var a,n,i;if(s.type==="cron"){if(s.showAdvanced)return{schedule:s.rawCron.trim(),humanLabel:s.humanLabel||s.rawCron.trim()};const l=`${s.cronMinute} ${s.cronHour} * * ${s.cronDow}`,o=((a=ca.find(h=>h.value===s.cronDow))==null?void 0:a.label)||"",c=((n=la.find(h=>h.value===s.cronHour))==null?void 0:n.label)||`${s.cronHour}`,u=String(s.cronMinute).padStart(2,"0"),x=o==="Every day"?`Every day at ${c.replace(" ","")} (min ${u})`:`Every ${o} at ${c.replace(" ","")} (min ${u})`;return{schedule:l,humanLabel:s.humanLabel||x}}if(s.type==="interval"){const l=((i=ln.find(c=>c.value===s.intervalUnit))==null?void 0:i.label)||s.intervalUnit;return{schedule:`${s.intervalN}${s.intervalUnit}`,humanLabel:s.humanLabel||`Every ${s.intervalN} ${l}`}}return s.onceAt?{schedule:new Date(s.onceAt).toISOString(),humanLabel:s.humanLabel||new Date(s.onceAt).toLocaleString()}:{schedule:"",humanLabel:s.humanLabel||""}}function $c({snapshot:s,refreshSnapshot:t}){var z;const a=ce(),n=Pe(),[i,l]=r.useState(s.schedules||[]),[o,c]=r.useState(!s.schedules),[u,x]=r.useState("schedules"),[h,m]=r.useState([]),[d,p]=r.useState(!1),f=async()=>{try{const y=await $.get("/projects/active/schedules");l(y.schedules||[])}catch(y){a.error(`Schedules load failed: ${y.message}`)}finally{c(!1)}},b=async()=>{p(!0);try{const y=await $.get("/schedules/templates");m(y.templates||[])}catch(y){a.error(`Templates load failed: ${y.message}`)}finally{p(!1)}};r.useEffect(()=>{var y;if((y=s.schedules)!=null&&y.length||s.schedules){l(s.schedules||[]),c(!1);return}f()},[s.schedules]),r.useEffect(()=>{u==="templates"&&h.length===0&&b()},[u]);const k=y=>{n.open({title:y?`Edit schedule: ${y.name}`:"New schedule",width:640,children:e.jsx(Rc,{initial:y,onClose:n.close,onSubmitted:async R=>{l(S=>{const N=S.findIndex(g=>g.id===R.id);if(N===-1)return[...S,R];const P=S.slice();return P[N]=R,P}),a.success(y?"Schedule updated.":"Schedule created."),n.close(),await t()},onError:R=>a.error(R)})})},w=async y=>{var R;try{const S=await $.post(`/schedules/${encodeURIComponent(y.id)}/run`);a.success(S.ok?"Schedule ran.":`Run failed: ${((R=S.runResult)==null?void 0:R.error)||"unknown"}`),await f()}catch(S){a.error(`Run failed: ${S.message}`)}},v=async y=>{if(confirm(`Delete schedule "${y.name}"?`))try{await $.del(`/schedules/${encodeURIComponent(y.id)}`),l(R=>R.filter(S=>S.id!==y.id)),a.success("Schedule deleted.")}catch(R){a.error(`Delete failed: ${R.message}`)}},C=async y=>{try{const R=await $.post("/schedules/from-template",{templateId:y.id});l(S=>[...S,R]),x("schedules"),a.success(`Schedule "${R.name}" created from template.`),await t()}catch(R){a.error(`Failed to create schedule: ${R.message}`)}};return o?e.jsx("div",{className:"view-loading",children:e.jsx(he,{size:"lg"})}):e.jsxs("div",{className:"view view-schedules",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("div",{className:"view-title-row",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(gs,{size:18})," Schedules"]}),e.jsxs("div",{className:"view-section-tabs",children:[e.jsxs("button",{type:"button",className:`tab-btn ${u==="schedules"?"tab-btn-active":""}`,onClick:()=>x("schedules"),children:["Schedules (",i.length,")"]}),e.jsxs("button",{type:"button",className:`tab-btn ${u==="templates"?"tab-btn-active":""}`,onClick:()=>x("templates"),children:[e.jsx(Xs,{size:14})," Templates"]})]})]}),e.jsx("p",{className:"view-subtitle",children:u==="schedules"?e.jsxs(e.Fragment,{children:["Recurring tasks for ",e.jsx("strong",{children:((z=s.activeProject)==null?void 0:z.name)||"(none)"}),". Service daemon runs them at the right time."]}):"Example schedules you can use as a starting point."})]}),e.jsxs("div",{className:"view-actions",children:[u==="schedules"&&e.jsxs(e.Fragment,{children:[e.jsxs(M,{variant:"secondary",size:"sm",onClick:f,"aria-label":"Refresh schedules",children:[e.jsx(me,{size:14})," Refresh"]}),e.jsxs(M,{variant:"primary",size:"sm",onClick:()=>k(),children:[e.jsx(Ee,{size:14})," New schedule"]})]}),u==="templates"&&e.jsxs(M,{variant:"secondary",size:"sm",onClick:b,disabled:d,children:[e.jsx(me,{size:14})," Refresh"]})]})]}),u==="templates"?d?e.jsx("div",{className:"view-loading",children:e.jsx(he,{size:"lg"})}):h.length===0?e.jsx(Ne,{icon:e.jsx(Xs,{size:32}),title:"No templates",message:"No schedule templates found. Templates are loaded from templates/schedules/."}):e.jsx("div",{className:"schedule-template-grid",children:h.map(y=>e.jsx(bc,{template:y,onUse:C},y.id))}):i.length===0?e.jsx(Ne,{icon:e.jsx(gs,{size:32}),title:"No schedules",message:s.activeProject?"Add a schedule to run commands, webhooks, or agent tasks on a cron / interval / one-shot basis.":"Activate a project first to scope schedules."}):e.jsx("div",{className:"schedule-grid",children:i.map(y=>{var R;return e.jsxs(G,{className:"schedule-card",children:[e.jsxs("div",{className:"schedule-card-head",children:[e.jsxs("div",{children:[e.jsx(ee,{children:y.name}),e.jsxs(te,{children:[e.jsx("code",{children:y.type})," ·"," ",e.jsx("span",{title:y.schedule,children:Tc(y)||y.schedule}),y.timezone&&y.timezone!=="UTC"?e.jsxs(e.Fragment,{children:[" · ",e.jsx("code",{children:y.timezone})]}):null," · ",e.jsx("span",{className:y.enabled?"status-on":"status-neutral",children:y.enabled?"enabled":"disabled"})]})]}),e.jsxs("div",{className:"schedule-card-actions",children:[e.jsxs(M,{variant:"secondary",size:"sm",onClick:()=>k(y),children:[e.jsx(et,{size:12})," Edit"]}),e.jsxs(M,{variant:"secondary",size:"sm",onClick:()=>w(y),children:[e.jsx(pt,{size:12})," Run now"]}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger","aria-label":"Delete",title:"Delete",onClick:()=>v(y),children:e.jsx(Re,{size:12})})]})]}),e.jsxs("div",{className:"schedule-card-action",children:[e.jsx("span",{className:"muted",children:"action:"})," ",e.jsxs("code",{children:[y.action.type," ",y.action.target]}),y.action.type==="agent"&&y.action.prompt&&e.jsxs("div",{className:"schedule-card-prompt",children:[e.jsx("span",{className:"muted",children:"prompt:"})," ",y.action.prompt]})]}),((R=y.budgetCheck)==null?void 0:R.skipIfBudgetLow)&&e.jsxs("div",{className:"schedule-card-budget",children:[e.jsx("span",{className:"muted",children:"budget gate:"})," ","skip if concurrent ≥ ",y.budgetCheck.maxConcurrent??6]}),e.jsxs("div",{className:"schedule-card-times",children:[e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"last"})," ",y.lastRun?Te(y.lastRun):"—",y.lastResult&&e.jsx("span",{className:`tag ${Sa(y.lastResult)}`,children:y.lastResult}),y.lastError&&e.jsxs("span",{className:"muted schedule-card-error",title:y.lastError,children:[" ","— ",Ca(y.lastError,80)]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"next"})," ",y.nextRun?e.jsx("span",{title:new Date(y.nextRun).toISOString(),children:Ac(y.nextRun,y.timezone)}):"—",y.nextRun&&e.jsxs("span",{className:"muted",children:[" · ",Te(y.nextRun)]})]})]}),y.history&&y.history.length>0&&e.jsxs("details",{className:"schedule-card-history",children:[e.jsxs("summary",{children:[e.jsx(Gs,{size:12})," ",y.history.length," run",y.history.length===1?"":"s"]}),e.jsx("ul",{children:y.history.slice(-10).reverse().map((S,N)=>e.jsxs("li",{children:[e.jsx("span",{className:"tabular-nums muted",children:Te(S.ts)})," ",e.jsx("span",{className:`tag ${Sa(S.result)}`,children:S.result}),S.error&&e.jsxs("span",{className:"muted",children:[" — ",Ca(S.error,80)]})]},N))})]})]},y.id)})})]})}function Rc({initial:s,onClose:t,onSubmitted:a,onError:n}){const[i,l]=r.useState(()=>Sc(s)),[o,c]=r.useState(!1),u=r.useMemo(()=>qt.some(m=>m.value===i.timezone)?i.timezone:"Other…",[i.timezone]),x=(m,d)=>{l(p=>({...p,[m]:d}))},h=async m=>{m.preventDefault();const d=i.name.trim();if(!d){n("Name is required.");return}const p=zc(i);if(!p.schedule){n("Schedule value is required.");return}if(!i.actionTarget.trim()){n("Action target is required.");return}const f=i.timezone==="Other…"?i.customTimezone.trim():i.timezone,b={type:i.actionType,target:i.actionTarget.trim()};i.actionType==="agent"&&i.actionPrompt.trim()&&(b.prompt=i.actionPrompt.trim());const k={name:d,type:i.type,schedule:p.schedule,timezone:f||"UTC",action:b,budgetCheck:{maxConcurrent:i.maxConcurrent,skipIfBudgetLow:i.skipIfBudgetLow},enabled:i.enabled};c(!0);try{const w=s?await $.put(`/schedules/${encodeURIComponent(s.id)}`,k):await $.post("/schedules",k);await a(w)}catch(w){n(`${s?"Update":"Create"} failed: ${w.message}`)}finally{c(!1)}};return e.jsxs("form",{className:"schedule-form",onSubmit:h,children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-name",children:"Name"}),e.jsx("input",{id:"schedule-name",className:"input",type:"text",placeholder:"Weekly code review",value:i.name,onChange:m=>x("name",m.target.value),autoFocus:!0}),e.jsx("div",{className:"task-form-row",children:e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-type",children:"Type"}),e.jsx("select",{id:"schedule-type",className:"select",value:i.type,onChange:m=>x("type",m.target.value),children:yc.map(m=>e.jsx("option",{value:m,children:m},m))})]})}),i.type==="cron"&&e.jsxs("div",{className:"schedule-cron-group",children:[!i.showAdvanced&&e.jsx(e.Fragment,{children:e.jsxs("div",{className:"task-form-row",children:[e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-dow",children:"Day of week"}),e.jsx("select",{id:"schedule-dow",className:"select",value:i.cronDow,onChange:m=>x("cronDow",m.target.value),children:ca.map(m=>e.jsx("option",{value:m.value,children:m.label},m.value))})]}),e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-hour",children:"Hour"}),e.jsx("select",{id:"schedule-hour",className:"select",value:String(i.cronHour),onChange:m=>x("cronHour",parseInt(m.target.value,10)),children:la.map(m=>e.jsx("option",{value:String(m.value),children:m.label},m.value))})]}),e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-minute",children:"Minute"}),e.jsx("select",{id:"schedule-minute",className:"select",value:String(i.cronMinute),onChange:m=>x("cronMinute",parseInt(m.target.value,10)),children:kc.map(m=>e.jsx("option",{value:String(m),children:String(m).padStart(2,"0")},m))})]})]})}),i.showAdvanced&&e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-cron-expr",children:"Cron expression"}),e.jsx("input",{id:"schedule-cron-expr",className:"input",type:"text",value:i.rawCron,onChange:m=>x("rawCron",m.target.value),placeholder:"0 13 * * 0"})]}),e.jsxs("button",{type:"button",className:"link-btn",onClick:()=>x("showAdvanced",!i.showAdvanced),"aria-expanded":i.showAdvanced,children:[e.jsx(He,{size:12,style:{transform:i.showAdvanced?"rotate(180deg)":"none",transition:"transform 0.15s"}}),i.showAdvanced?"Hide advanced":"Advanced (raw cron)"]})]}),i.type==="interval"&&e.jsxs("div",{className:"task-form-row",children:[e.jsxs("div",{className:"task-form-field",style:{flex:1},children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-interval-n",children:"Every"}),e.jsx("input",{id:"schedule-interval-n",className:"input",type:"number",min:1,value:i.intervalN,onChange:m=>x("intervalN",parseInt(m.target.value,10)||1)})]}),e.jsxs("div",{className:"task-form-field",style:{flex:1},children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-interval-unit",children:"Unit"}),e.jsx("select",{id:"schedule-interval-unit",className:"select",value:i.intervalUnit,onChange:m=>x("intervalUnit",m.target.value),children:ln.map(m=>e.jsx("option",{value:m.value,children:m.label},m.value))})]})]}),i.type==="once"&&e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-once-at",children:"Run at"}),e.jsx("input",{id:"schedule-once-at",className:"input",type:"datetime-local",value:i.onceAt,onChange:m=>x("onceAt",m.target.value)})]}),e.jsxs("div",{className:"task-form-row",children:[e.jsxs("div",{className:"task-form-field",style:{flex:1},children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-timezone",children:"Timezone"}),e.jsxs("select",{id:"schedule-timezone",className:"select",value:u,onChange:m=>x("timezone",m.target.value),children:[qt.map(m=>e.jsx("option",{value:m.value,children:m.label},m.value)),e.jsx("option",{value:"Other…",children:"Other…"})]})]}),i.timezone==="Other…"&&e.jsxs("div",{className:"task-form-field",style:{flex:1},children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-custom-tz",children:"IANA name"}),e.jsx("input",{id:"schedule-custom-tz",className:"input",type:"text",placeholder:"Europe/Paris",value:i.customTimezone,onChange:m=>x("customTimezone",m.target.value)})]})]}),e.jsxs("div",{className:"task-form-row",children:[e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-action-type",children:"Action"}),e.jsx("select",{id:"schedule-action-type",className:"select",value:i.actionType,onChange:m=>x("actionType",m.target.value),children:Nc.map(m=>e.jsx("option",{value:m,children:m},m))})]}),e.jsxs("div",{className:"task-form-field",style:{flex:2},children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-action-target",children:"Target"}),e.jsx("input",{id:"schedule-action-target",className:"input",type:"text",placeholder:i.actionType==="webhook"?"https://...":i.actionType==="agent"?"agent name or task ref":"echo hi",value:i.actionTarget,onChange:m=>x("actionTarget",m.target.value)})]})]}),i.actionType==="agent"&&e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-action-prompt",children:"Prompt (what to send the agent)"}),e.jsx("textarea",{id:"schedule-action-prompt",className:"input",rows:3,placeholder:"Review open PRs for stale code review comments and nudge reviewers.",value:i.actionPrompt,onChange:m=>x("actionPrompt",m.target.value)})]}),e.jsxs("fieldset",{className:"schedule-budget-card",children:[e.jsx("legend",{children:"Budget pre-flight"}),e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{id:"schedule-skip-budget",type:"checkbox",checked:i.skipIfBudgetLow,onChange:m=>x("skipIfBudgetLow",m.target.checked)}),e.jsx("span",{children:"Skip this run when too many background tasks are already running."})]}),e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-max-concurrent",children:"Max concurrent bg tasks"}),e.jsx("input",{id:"schedule-max-concurrent",className:"input",type:"number",min:1,max:64,value:i.maxConcurrent,onChange:m=>x("maxConcurrent",parseInt(m.target.value,10)||6),disabled:!i.skipIfBudgetLow})]})]}),e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{id:"schedule-enabled",type:"checkbox",checked:i.enabled,onChange:m=>x("enabled",m.target.checked)}),e.jsx("span",{children:"Enabled"})]}),e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx(M,{variant:"ghost",type:"button",onClick:t,disabled:o,children:"Cancel"}),e.jsx(M,{variant:"primary",type:"submit",disabled:o,children:s?"Save":"Create"})]})]})}function Tc(s){var l,o;if(s.type!=="cron")return s.schedule;const t=cn(s.schedule);if(!t)return s.schedule;const a=((l=ca.find(c=>c.value===t.dow))==null?void 0:l.label)||"",n=((o=la.find(c=>c.value===t.hour))==null?void 0:o.label)||`${t.hour}`,i=String(t.minute).padStart(2,"0");return a==="Every day"?`Every day at ${n} :${i}`:`Every ${a} at ${n} :${i}`}function Ac(s,t){try{return new Date(s).toLocaleString(void 0,{timeZone:t||void 0,weekday:"long",hour:"numeric",minute:"2-digit",month:"short",day:"numeric"})}catch{return new Date(s).toLocaleString()}}function Sa(s){return s==="success"?"tag-success":s==="skipped"?"tag-warning":"tag-error"}function Ca(s,t){return s.length<=t?s:s.slice(0,t-1)+"…"}const Mc=[{id:"all",label:"All",icon:es},{id:"shipped",label:"Shipped",icon:aa},{id:"user",label:"User",icon:Hs},{id:"project",label:"Project",icon:Ge}],ht={shipped:"Shipped",user:"User",project:"Project"},Ic={shipped:aa,user:Hs,project:Ge};function Ec({snapshot:s,refreshSnapshot:t}){const a=ce(),n=Pe(),[i,l]=r.useState([]),[o,c]=r.useState({shipped:0,user:0,project:0,all:0}),[u,x]=r.useState(!0),[h,m]=r.useState("all"),[d,p]=r.useState(""),[f,b]=r.useState(null),[k,w]=r.useState(!1),v=async()=>{var R,S,N;x(!0);try{const P=await $.get("/skills");l(P.skills||[]),c({shipped:((R=P.counts)==null?void 0:R.shipped)??0,user:((S=P.counts)==null?void 0:S.user)??0,project:((N=P.counts)==null?void 0:N.project)??0,all:(P.skills||[]).length})}catch(P){a.error(`Skills load failed: ${P.message}`)}finally{x(!1)}};r.useEffect(()=>{v()},[]),r.useEffect(()=>{if(!d.trim()){b(null);return}w(!0);const R=setTimeout(async()=>{try{const S=await $.get(`/skills/search?q=${encodeURIComponent(d.trim())}`);b(S.results||[])}catch(S){a.error(`Search failed: ${S.message}`)}finally{w(!1)}},280);return()=>clearTimeout(R)},[d]);const C=r.useMemo(()=>f!==null?f:h==="all"?i:i.filter(R=>R.source===h),[i,h,f]),z=async()=>{try{await $.post("/skills/refresh",{}),a.success("Skills refreshed."),await v()}catch(R){a.error(`Refresh failed: ${R.message}`)}},y=async R=>{try{const S=await $.get(`/skills/${encodeURIComponent(R.source)}/${encodeURIComponent(R.name)}`);n.open({title:S.name,width:640,children:e.jsxs("div",{className:"skill-detail",children:[e.jsxs("div",{className:"skill-detail-meta",children:[e.jsx("span",{className:"skill-source-badge","data-source":S.source,children:ht[S.source]||S.source}),e.jsx("code",{className:"mono text-sm muted",children:S.path})]}),S.description&&e.jsx("p",{className:"skill-detail-desc",children:S.description}),S.body&&e.jsx("div",{className:"skill-detail-body",children:e.jsx("pre",{className:"skill-body-pre",children:S.body})})]}),footer:e.jsx(M,{variant:"ghost",onClick:()=>n.close(),children:"Close"})})}catch{n.open({title:R.name,width:560,children:e.jsxs("div",{className:"skill-detail",children:[e.jsxs("div",{className:"skill-detail-meta",children:[e.jsx("span",{className:"skill-source-badge","data-source":R.source,children:ht[R.source]||R.source}),e.jsx("code",{className:"mono text-sm muted",children:R.path})]}),R.description&&e.jsx("p",{className:"skill-detail-desc",children:R.description})]}),footer:e.jsx(M,{variant:"ghost",onClick:()=>n.close(),children:"Close"})})}};return e.jsxs("div",{className:"view view-skills",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(es,{size:18})," Skills"]}),e.jsx("p",{className:"view-subtitle",children:"Browse all available skills — shipped, user, and project-local."})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs("div",{className:"search-input",children:[e.jsx(ke,{size:14,"aria-hidden":!0}),e.jsx("label",{htmlFor:"skills-search",className:"sr-only",children:"Search skills"}),e.jsx("input",{id:"skills-search",className:"input",type:"text",placeholder:"Search skills…",value:d,onChange:R=>p(R.target.value),"aria-label":"Search skills"}),d&&e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Clear search",onClick:()=>p(""),children:e.jsx(vs,{size:12})})]}),e.jsxs(M,{variant:"secondary",size:"sm",onClick:z,children:[e.jsx(me,{size:14})," Refresh"]})]})]}),!d.trim()&&e.jsx("div",{className:"skills-tabs",children:Mc.map(R=>{const S=R.icon,N=R.id==="all"?o.all:o[R.id]??0;return e.jsxs("button",{type:"button",className:W("skills-tab",h===R.id&&"skills-tab-active"),onClick:()=>m(R.id),children:[e.jsx(S,{size:14}),e.jsx("span",{children:R.label}),e.jsx("span",{className:"skills-tab-count",children:N})]},R.id)})}),d.trim()&&e.jsxs("section",{className:"skills-section",children:[e.jsxs("h3",{className:"skills-section-title",children:[e.jsx(ke,{size:14})," Search results",k&&e.jsx(he,{size:"sm"})]}),k?e.jsx("div",{className:"skills-grid",children:[0,1,2].map(R=>e.jsx("div",{className:"skill-card skill-card-skeleton"},R))}):f&&f.length===0?e.jsx(Ne,{icon:e.jsx(ke,{size:28}),title:"No matches",message:`No skills match "${d}".`}):e.jsx("div",{className:"skills-grid",children:(f||[]).map((R,S)=>e.jsx(za,{skill:R,onShow:()=>y(R),searchQ:d},`search-${S}`))})]}),!d.trim()&&e.jsx("section",{className:"skills-section",children:u?e.jsx("div",{className:"view-loading",children:e.jsx(he,{size:"lg"})}):C.length===0?e.jsx(Ne,{icon:e.jsx(ta,{size:28}),title:"No skills here",message:h==="all"?"No skills found. Install skills with the skills CLI or add SKILL.md files to a skills directory.":`No skills in the ${ht[h]} tab.`}):e.jsx("div",{className:"skills-grid",children:C.map((R,S)=>e.jsx(za,{skill:R,onShow:()=>y(R)},`${R.source}-${R.name}-${S}`))})}),!d.trim()&&e.jsx("footer",{className:"view-footer",children:e.jsxs("span",{className:"text-sm muted",children:["Skills are discovered from"," ",e.jsx("code",{children:"~/.cline/skills/"}),","," ",e.jsx("code",{children:"~/.agents/skills/"}),","," ",e.jsx("code",{children:"bizar-dash/skills/"}),", and project-local directories."]})})]})}function za({skill:s,onShow:t,searchQ:a=""}){const n=Ic[s.source]||aa,i=s.description?s.description.length>200?s.description.slice(0,200)+"…":s.description:"No description.";return e.jsxs(G,{variant:"elevated",interactive:!0,className:"skill-card",children:[e.jsxs("div",{className:"skill-card-head",children:[e.jsx("div",{className:"skill-card-icon",style:{background:"color-mix(in srgb, var(--accent) 12%, transparent)"},children:e.jsx(n,{size:18})}),e.jsxs("div",{className:"skill-card-title-area",children:[e.jsx("div",{className:"skill-card-title",children:Lc(s.name,a)}),e.jsx("span",{className:"skill-source-badge","data-source":s.source,children:ht[s.source]||s.source})]})]}),e.jsx("p",{className:"skill-card-desc",children:i}),e.jsx("div",{className:"skill-card-actions",children:e.jsxs(M,{variant:"ghost",size:"sm",onClick:t,children:[e.jsx(Ls,{size:12})," View"]})})]})}function Lc(s,t){if(!t.trim())return s;const a=s.toLowerCase().indexOf(t.toLowerCase());return a<0?s:e.jsxs(e.Fragment,{children:[s.slice(0,a),e.jsx("mark",{className:"skill-highlight",children:s.slice(a,a+t.length)}),s.slice(a+t.length)]})}const Dc=Ke.memo(Ec);function _c({refreshKey:s,onRefresh:t,setActiveSubPanel:a}){const n=ce(),[i,l]=r.useState(null),[o,c]=r.useState(""),[u,x]=r.useState(!0),h=async k=>{x(!0);try{const[w,v,C,z]=await Promise.all([$.get("/memory/health",k).catch(()=>null),$.get("/memory/status",k).catch(()=>null),$.get("/memory/lightrag/stats",k).catch(()=>null),$.get("/memory/storage",k).catch(()=>null)]);c((v==null?void 0:v.vaultRoot)||""),l({health:w||{score:0,status:"unconfigured",checks:[],message:"memory not initialised"},vault:{exists:!!(v!=null&&v.initialized),vaultRoot:(v==null?void 0:v.vaultRoot)||"",mode:(v==null?void 0:v.mode)||"local-only",noteCount:(v==null?void 0:v.noteCount)||0,totalSize:(z==null?void 0:z.total)||0,folderCount:0,folders:[],lastModified:null,gitClean:(v==null?void 0:v.gitClean)??null,gitBranch:(v==null?void 0:v.branch)||null},lightrag:C||{running:!1,pid:null,host:"127.0.0.1",port:9621,indexedApprox:0,queryCountLast24h:0,lastReindexAt:null},storage:z||{total:0,breakdown:[]}})}catch(w){n.error(`Memory overview failed: ${w.message}`)}finally{x(!1)}};if(r.useEffect(()=>{const k=new AbortController;return h(k.signal),()=>k.abort()},[s]),u&&!i)return e.jsxs("div",{className:"view-loading",children:[e.jsx(he,{size:"lg"}),e.jsx("p",{children:"Loading memory overview…"})]});if(!i)return e.jsx("div",{className:"muted",children:"No memory data available."});const{health:m,vault:d,lightrag:p,storage:f}=i,b=m.score>=80?"var(--success)":m.score>=50?"var(--warning)":"var(--error)";return e.jsxs("div",{className:"memory-overview",children:[e.jsxs(G,{variant:"elevated",className:"memory-health-hero",children:[e.jsxs("div",{className:"memory-health-score",style:{borderColor:b},children:[e.jsx("span",{className:"memory-health-score-value",style:{color:b},children:m.score}),e.jsx("span",{className:"memory-health-score-label",children:"/ 100"})]}),e.jsxs("div",{className:"memory-health-meta",children:[e.jsxs("h3",{className:"memory-health-title",children:[e.jsx(Ae,{size:16}),"Memory health ·"," ",e.jsx("span",{style:{color:b},children:m.status})]}),e.jsx("p",{className:"memory-health-message",children:m.message}),e.jsxs("p",{className:"memory-health-vault mono muted","data-testid":"memory-overview-vault-path",children:[e.jsx("span",{className:"memory-health-vault-label",children:"Vault:"})," ",o||e.jsx("em",{children:"not initialised"})]}),e.jsxs(M,{variant:"ghost",size:"sm",onClick:t,children:[e.jsx(me,{size:12})," Refresh"]})]})]}),e.jsxs("div",{className:"memory-source-pills",children:[e.jsxs("button",{type:"button",className:"memory-source-pill",onClick:()=>a("lightrag"),children:[e.jsx(Je,{size:14}),e.jsx("span",{children:"LightRAG"}),e.jsx("span",{className:W("memory-source-pill-status",p.running?"on":"off"),children:p.running?"running":"stopped"})]}),e.jsxs("button",{type:"button",className:"memory-source-pill",onClick:()=>a("obsidian"),children:[e.jsx(Ie,{size:14}),e.jsx("span",{children:"Obsidian Vault"}),e.jsxs("span",{className:W("memory-source-pill-status",d.exists?"on":"off"),children:[d.noteCount," notes"]})]}),e.jsxs("button",{type:"button",className:"memory-source-pill",onClick:()=>a("git"),children:[e.jsx(Ze,{size:14}),e.jsx("span",{children:"Git Sync"}),e.jsx("span",{className:W("memory-source-pill-status",d.gitClean===null?"na":d.gitClean?"on":"warn"),children:d.gitClean===null?"—":d.gitClean?"clean":"dirty"})]}),e.jsxs("button",{type:"button",className:"memory-source-pill",onClick:()=>a("semantic"),children:[e.jsx(ke,{size:14}),e.jsx("span",{children:"Semantic Search"}),e.jsx("span",{className:"memory-source-pill-status na",children:"cross-source"})]})]}),e.jsxs("div",{className:"memory-stat-grid",children:[e.jsx(Ss,{icon:e.jsx(Je,{size:16}),label:"LightRAG",value:p.running?`running · ${p.queryCountLast24h} q/24h`:"stopped",sub:p.running?`${p.indexedApprox} indexed chunks`:"start from the LightRAG panel",onClick:()=>a("lightrag")}),e.jsx(Ss,{icon:e.jsx(Ie,{size:16}),label:"Obsidian",value:`${d.noteCount} notes`,sub:d.folderCount>0?`${d.folderCount} folders`:"no folders yet",onClick:()=>a("obsidian")}),e.jsx(Ss,{icon:e.jsx(Ze,{size:16}),label:"Git",value:d.gitBranch?`branch ${d.gitBranch}`:"local-only",sub:d.gitClean===null?"not configured":d.gitClean?"clean working tree":"dirty — commit or pull",onClick:()=>a("git")}),e.jsx(Ss,{icon:e.jsx(ft,{size:16}),label:"Storage",value:Pc(f.total),sub:f.breakdown.length>0?`${f.breakdown.length} dirs tracked`:"no memory data on disk"}),e.jsx(Ss,{icon:e.jsx(es,{size:16}),label:"Last reindex",value:p.lastReindexAt?as(p.lastReindexAt):"never",sub:"lightrag ingest",onClick:()=>a("lightrag")}),e.jsx(Ss,{icon:e.jsx(Ys,{size:16}),label:"Health",value:`${m.score}/100`,sub:m.status,onClick:()=>a("config")})]}),m.checks.length>0&&e.jsxs(G,{children:[e.jsx(ee,{children:"Health checks"}),e.jsx(te,{children:"Composite score across all memory subsystems"}),e.jsx("ul",{className:"memory-check-list",children:m.checks.map(k=>e.jsxs("li",{className:"memory-check-row",children:[e.jsx("span",{className:"memory-check-icon",children:k.pass?e.jsx(_e,{size:14,style:{color:"var(--success)"}}):k.name.includes("secrets")||k.name.includes("schema")?e.jsx(Me,{size:14,style:{color:"var(--warning)"}}):e.jsx(vs,{size:14,style:{color:"var(--error)"}})}),e.jsx("span",{className:"memory-check-name",children:k.name}),e.jsx("span",{className:"memory-check-detail muted",children:k.detail})]},k.name))})]})]})}function Ss({icon:s,label:t,value:a,sub:n,onClick:i}){const l=i?"button":"div";return e.jsxs(l,{type:i?"button":void 0,onClick:i,className:W("memory-stat-card",i&&"memory-stat-card-clickable"),children:[e.jsx("div",{className:"memory-stat-icon",children:s}),e.jsxs("div",{className:"memory-stat-body",children:[e.jsx("div",{className:"memory-stat-label",children:t}),e.jsx("div",{className:"memory-stat-value",children:a}),e.jsx("div",{className:"memory-stat-sub muted",children:n})]})]})}function Pc(s){return s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(1)} KB`:s<1024*1024*1024?`${(s/(1024*1024)).toFixed(1)} MB`:`${(s/(1024*1024*1024)).toFixed(2)} GB`}function Fc({refreshKey:s}){const t=ce(),[a,n]=r.useState(null),[i,l]=r.useState(null),[o,c]=r.useState([]),[u,x]=r.useState(!0),[h,m]=r.useState(null),[d,p]=r.useState(""),[f,b]=r.useState(null),k=async()=>{x(!0);try{const[N,P,g]=await Promise.all([$.get("/memory/lightrag/stats").catch(()=>null),$.get("/memory/config").then(j=>(j==null?void 0:j.lightrag)||null).catch(()=>null),$.get("/memory/lightrag/log").catch(()=>({lines:[]}))]);n(N),l(P),c((g==null?void 0:g.lines)||[])}catch(N){t.error(`LightRAG status failed: ${N.message}`)}finally{x(!1)}};r.useEffect(()=>{k()},[s]);const w=async(N,P,g)=>{m(N);try{await P(),t.success(g),await k()}catch(j){t.error(`${N} failed: ${j.message}`)}finally{m(null)}},v=()=>w("start",()=>$.post("/memory/lightrag/start",{}),"LightRAG starting…"),C=()=>w("stop",()=>$.post("/memory/lightrag/stop",{}),"LightRAG stopping…"),z=async()=>{m("restart");try{await $.post("/memory/lightrag/stop",{}).catch(()=>{}),await new Promise(N=>setTimeout(N,600)),await $.post("/memory/lightrag/start",{}),t.success("LightRAG restarted."),await k()}catch(N){t.error(`Restart failed: ${N.message}`)}finally{m(null)}},y=()=>w("reindex",()=>$.post("/memory/lightrag/reindex",{}),"Reindex complete."),R=()=>w("rebuild",()=>$.post("/memory/lightrag/rebuild-graph",{}),"Graph rebuilt."),S=async()=>{var N,P,g;if(d.trim()){m("query");try{const j=await $.get(`/memory/query?q=${encodeURIComponent(d)}&topK=8`),T=(N=j==null?void 0:j.semantic)!=null&&N.response?typeof j.semantic.response=="string"?j.semantic.response:JSON.stringify(j.semantic.response):((P=j==null?void 0:j.semantic)==null?void 0:P.error)||"No response";b({ok:!!((g=j==null?void 0:j.semantic)!=null&&g.ok),text:T})}catch(j){b({ok:!1,text:j.message})}finally{m(null)}}};return u&&!a?e.jsxs("div",{className:"view-loading",children:[e.jsx(he,{size:"lg"}),e.jsx("p",{children:"Loading LightRAG status…"})]}):a?e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(G,{variant:"elevated",children:[e.jsxs(ee,{children:[e.jsx(Je,{size:14}),"LightRAG",e.jsx("span",{className:W("memory-source-pill-status",a.running?"on":"off"),children:a.running?"running":"stopped"})]}),e.jsx(te,{children:a.running?e.jsxs(e.Fragment,{children:["PID ",e.jsx("code",{children:a.pid})," · ",a.host,":",a.port]}):e.jsx(e.Fragment,{children:"Server is not running. Start it from the controls below."})}),e.jsxs("div",{className:"memory-action-row",children:[e.jsxs(M,{variant:"primary",size:"sm",onClick:v,disabled:!!h||a.running,children:[h==="start"?e.jsx(ge,{size:12,className:"memory-spin"}):e.jsx(Es,{size:12}),"Start"]}),e.jsxs(M,{variant:"secondary",size:"sm",onClick:C,disabled:!!h||!a.running,children:[h==="stop"?e.jsx(ge,{size:12,className:"memory-spin"}):e.jsx(oi,{size:12}),"Stop"]}),e.jsxs(M,{variant:"secondary",size:"sm",onClick:z,disabled:!!h,children:[h==="restart"?e.jsx(ge,{size:12,className:"memory-spin"}):e.jsx(qa,{size:12}),"Restart"]}),e.jsxs(M,{variant:"ghost",size:"sm",onClick:y,disabled:!!h,children:[h==="reindex"?e.jsx(ge,{size:12,className:"memory-spin"}):e.jsx(me,{size:12}),"Reindex all"]}),e.jsxs(M,{variant:"ghost",size:"sm",onClick:R,disabled:!!h,title:"Wipe working dir + reindex from scratch",children:[h==="rebuild"?e.jsx(ge,{size:12,className:"memory-spin"}):e.jsx(bt,{size:12}),"Rebuild graph"]})]})]}),e.jsxs("div",{className:"memory-stat-grid",children:[e.jsx(Bs,{icon:e.jsx(ft,{size:14}),label:"Indexed chunks (approx)",value:String(a.indexedApprox)}),e.jsx(Bs,{icon:e.jsx(Oc,{n:a.noteCount}),label:"Notes in vault",value:String(a.noteCount)}),e.jsx(Bs,{icon:e.jsx(Zt,{size:14}),label:"Queries last 24h",value:String(a.queryCountLast24h)}),e.jsx(Bs,{icon:e.jsx(es,{size:14}),label:"Avg response",value:a.avgResponseMs!==null?`${a.avgResponseMs} ms`:"—"}),e.jsx(Bs,{icon:a.lastReindexOk?e.jsx(_e,{size:14}):a.lastReindexOk===!1?e.jsx(vs,{size:14}):e.jsx(me,{size:14}),label:"Last reindex",value:a.lastReindexAt?as(a.lastReindexAt):"never",sub:a.lastReindexInserted!==null?`${a.lastReindexInserted} inserted${a.lastReindexFailed?`, ${a.lastReindexFailed} failed`:""}`:void 0})]}),e.jsxs(G,{children:[e.jsxs(ee,{children:[e.jsx(ke,{size:14})," Quick search"]}),e.jsx(te,{children:"Send a natural-language query to the LightRAG index."}),e.jsxs("div",{className:"memory-search-row",children:[e.jsx("label",{htmlFor:"lightrag-query",className:"sr-only",children:"Search LightRAG"}),e.jsx("input",{id:"lightrag-query",type:"text",className:"input",placeholder:"e.g. how does the memory service write notes?",value:d,onChange:N=>p(N.target.value),onKeyDown:N=>{N.key==="Enter"&&S()},disabled:h==="query","aria-label":"Search LightRAG"}),e.jsxs(M,{variant:"primary",onClick:S,disabled:h==="query"||!d.trim(),children:[h==="query"?e.jsx(ge,{size:12,className:"memory-spin"}):e.jsx(ke,{size:12}),"Query"]})]}),f&&e.jsx("div",{className:W("memory-query-result",f.ok?"ok":"err"),children:e.jsx("pre",{className:"mono text-sm",children:f.text})})]}),i&&e.jsxs(G,{children:[e.jsx(ee,{children:"Configuration"}),e.jsxs(te,{children:["Effective values from ",e.jsx("code",{children:".bizar/memory.json"})," + env defaults."]}),e.jsxs("dl",{className:"memory-config-row",children:[e.jsx("dt",{children:"LLM binding"}),e.jsxs("dd",{children:[e.jsx("code",{children:i.llmBinding})," · ",e.jsx("code",{children:i.llmModel})]}),e.jsx("dt",{children:"Embedding"}),e.jsxs("dd",{children:[e.jsx("code",{children:i.embeddingBinding})," · ",e.jsx("code",{children:i.embeddingModel})]}),e.jsx("dt",{children:"Host"}),e.jsx("dd",{children:e.jsxs("code",{children:[i.host,":",i.port]})}),e.jsx("dt",{children:"Working dir"}),e.jsx("dd",{className:"mono ellipsis",title:i.workingDir,children:i.workingDir})]})]}),o.length>0&&e.jsxs(G,{children:[e.jsxs(ee,{children:[e.jsx(me,{size:14})," Server log (tail)"]}),e.jsxs(te,{children:["Last ",o.length," lines from ",e.jsx("code",{children:"lightrag.log"})]}),e.jsx("pre",{className:"memory-log-tail mono text-xs",children:o.join(`
|
|
12
|
-
`)})]})]}):e.jsx("div",{className:"muted",children:"No LightRAG data available."})}function Bs({icon:s,label:t,value:a,sub:n}){return e.jsxs("div",{className:"memory-stat-card",children:[e.jsx("div",{className:"memory-stat-icon",children:s}),e.jsxs("div",{className:"memory-stat-body",children:[e.jsx("div",{className:"memory-stat-label",children:t}),e.jsx("div",{className:"memory-stat-value",children:a}),n&&e.jsx("div",{className:"memory-stat-sub muted",children:n})]})]})}function Oc({n:s}){return e.jsxs("span",{style:{position:"relative",display:"inline-block"},children:[e.jsx(ke,{size:14}),e.jsx("span",{className:"memory-mini-badge",children:s})]})}function Bc({refreshKey:s}){const t=ce(),a=Pe(),[n,i]=r.useState([]),[l,o]=r.useState(null),[c,u]=r.useState(!0),[x,h]=r.useState(""),[m,d]=r.useState(null),[p,f]=r.useState(!1),[b,k]=r.useState(null),[w,v]=r.useState([]),C=async()=>{var g;u(!0);try{const[j,T]=await Promise.all([$.get("/memory/notes").catch(()=>({notes:[]})),$.get("/memory/obsidian/tree").catch(()=>({tree:null}))]);i(j.notes||[]),o(T.tree),b&&!((g=j.notes)!=null&&g.find(F=>F.relPath===b))&&(k(null),v([]))}catch(j){t.error(`Vault load failed: ${j.message}`)}finally{u(!1)}};r.useEffect(()=>{C()},[s]),r.useEffect(()=>{if(!x.trim()){d(null);return}f(!0);const g=setTimeout(async()=>{try{const j=await $.get(`/memory/search?q=${encodeURIComponent(x)}&limit=50`),T=new Set((j.results||[]).map(F=>F.relPath));d(n.filter(F=>T.has(F.relPath)))}catch(j){t.error(`Search failed: ${j.message}`)}finally{f(!1)}},240);return()=>clearTimeout(g)},[x,n,t]);const z=async g=>{k(g);try{const j=await $.get(`/memory/obsidian/backlinks?note=${encodeURIComponent(g)}`);v(j.backlinks||[])}catch{v([])}},y=()=>{a.open({title:"New note",width:720,children:e.jsx($a,{mode:"create",onSave:async(g,j,T)=>{try{await $.post("/memory/notes",{path:g,frontmatter:j,body:T}),t.success(`Created ${g}.`),a.close(),await C(),z(g)}catch(F){t.error(`Create failed: ${F.message}`)}},onCancel:()=>a.close()})})},R=async g=>{try{const j=await $.get(`/memory/notes/${g.split("/").map(encodeURIComponent).join("/")}`);a.open({title:`Edit ${g}`,width:720,children:e.jsx($a,{mode:"edit",initial:{relPath:j.relPath,frontmatter:j.frontmatter,body:j.body},onSave:async(T,F,A)=>{try{await $.put(`/memory/notes/${T.split("/").map(encodeURIComponent).join("/")}`,{frontmatter:F,body:A}),t.success(`Saved ${T}.`),a.close(),await C(),z(T)}catch(U){t.error(`Save failed: ${U.message}`)}},onCancel:()=>a.close()})})}catch(j){t.error(`Load failed: ${j.message}`)}},S=async g=>{if(confirm(`Delete ${g}? This cannot be undone.`))try{await $.del(`/memory/notes/${g.split("/").map(encodeURIComponent).join("/")}`),t.success(`Deleted ${g}.`),b===g&&k(null),await C()}catch(j){t.error(`Delete failed: ${j.message}`)}},N=r.useMemo(()=>[...n].sort((g,j)=>j.mtime-g.mtime),[n]),P=m??N;return c&&!n.length?e.jsxs("div",{className:"view-loading",children:[e.jsx(he,{size:"lg"}),e.jsx("p",{children:"Loading vault…"})]}):e.jsxs("div",{className:"memory-panel-content memory-obsidian-grid",children:[e.jsxs(G,{variant:"outlined",className:"memory-tree-card",children:[e.jsxs(ee,{children:[e.jsx(Ge,{size:14})," Folders"]}),e.jsx(te,{children:l?`${mn(l)} folder(s)`:"no vault"}),e.jsx("div",{className:"memory-tree-body",children:l?e.jsx(dn,{node:l,depth:0,onSelect:z,selected:b}):null})]}),e.jsxs("div",{className:"memory-obsidian-list-col",children:[e.jsxs("div",{className:"memory-list-toolbar",children:[e.jsxs("div",{className:"search-input",children:[e.jsx(ke,{size:14,"aria-hidden":!0}),e.jsx("label",{htmlFor:"obsidian-search",className:"sr-only",children:"Search notes"}),e.jsx("input",{id:"obsidian-search",type:"text",className:"input",placeholder:"Search notes…",value:x,onChange:g=>h(g.target.value),"aria-label":"Search notes"}),x&&e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>h(""),"aria-label":"Clear search",children:e.jsx(we,{size:12})})]}),e.jsxs(M,{variant:"primary",size:"sm",onClick:y,children:[e.jsx(di,{size:12})," New note"]}),e.jsx(M,{variant:"ghost",size:"sm",onClick:C,title:"Refresh",children:e.jsx(me,{size:12})})]}),p&&e.jsx("div",{className:"muted text-sm",children:"Searching…"}),P.length===0?e.jsx(Ne,{icon:e.jsx(Ie,{size:28}),title:"No notes",message:n.length===0?'No notes in this vault yet. Click "New note" to create one.':`No notes match "${x}".`}):e.jsx("ul",{className:"memory-note-list",children:P.map(g=>e.jsxs("li",{className:W("memory-note-card",b===g.relPath&&"memory-note-card-active"),children:[e.jsxs("button",{type:"button",className:"memory-note-card-main",onClick:()=>z(g.relPath),children:[e.jsxs("div",{className:"memory-note-card-title",children:[e.jsx(Ie,{size:12}),e.jsx("span",{children:on(g)})]}),e.jsxs("div",{className:"memory-note-card-meta",children:[e.jsx("code",{className:"muted",children:g.relPath}),e.jsxs("span",{className:"muted",children:["· ",Te(g.mtime)]}),!g.schemaValid&&e.jsx("span",{className:"memory-pill-warn",children:"schema"})]})]}),e.jsxs("div",{className:"memory-note-card-actions",children:[e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>R(g.relPath),"aria-label":`Edit ${g.relPath}`,title:"Edit",children:e.jsx(et,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>S(g.relPath),"aria-label":`Delete ${g.relPath}`,title:"Delete",children:e.jsx(Re,{size:12})})]})]},g.relPath))})]}),e.jsx("div",{className:"memory-obsidian-detail-col",children:b?e.jsx(Uc,{relPath:b,onClose:()=>k(null)}):e.jsx(Ne,{icon:e.jsx(Ie,{size:28}),title:"Pick a note",message:"Select a note from the list to view its content, frontmatter, and backlinks."})})]})}function on(s){var a;const t=(a=s.frontmatter)==null?void 0:a.title;return typeof t=="string"&&t.trim()?t:s.relPath.replace(/\.md$/i,"")}function dn({node:s,depth:t,onSelect:a,selected:n}){const[i,l]=r.useState(t<2);return s.type==="note"?e.jsxs("button",{type:"button",className:W("memory-tree-node memory-tree-node-note",n===s.path&&"memory-tree-node-active"),style:{paddingLeft:6+t*12},onClick:()=>a(s.path),children:[e.jsx(Ie,{size:11}),e.jsx("span",{children:s.name})]}):e.jsxs("div",{className:"memory-tree-folder",children:[e.jsxs("button",{type:"button",className:"memory-tree-node memory-tree-node-folder",style:{paddingLeft:6+t*12},onClick:()=>l(o=>!o),children:[i?e.jsx(He,{size:11}):e.jsx(ds,{size:11}),e.jsx(Ge,{size:11}),e.jsx("span",{children:s.name||"vault"}),s.children&&s.children.length>0&&e.jsx("span",{className:"muted text-xs",children:s.children.length})]}),i&&s.children&&e.jsx("div",{className:"memory-tree-children",children:s.children.map((o,c)=>e.jsx(dn,{node:o,depth:t+1,onSelect:a,selected:n},`${o.path}-${c}`))})]})}function mn(s){return s.type==="note"?0:1+(s.children||[]).reduce((t,a)=>t+mn(a),0)}function Uc({relPath:s,onClose:t}){var h,m;const[a,n]=r.useState(null),[i,l]=r.useState([]),[o,c]=r.useState(!0);if(r.useEffect(()=>{let d=!1;return c(!0),(async()=>{try{const[p,f]=await Promise.all([$.get(`/memory/notes/${s.split("/").map(encodeURIComponent).join("/")}`),$.get(`/memory/obsidian/backlinks?note=${encodeURIComponent(s)}`)]);if(d)return;n(p),l(f.backlinks||[])}catch{d||n(null)}finally{d||c(!1)}})(),()=>{d=!0}},[s]),o)return e.jsx("div",{className:"view-loading",children:e.jsx(he,{size:"sm"})});if(!a)return e.jsx("div",{className:"muted",children:"Note not found."});const u=Array.isArray((h=a.frontmatter)==null?void 0:h.tags)?a.frontmatter.tags:[],x=Array.isArray((m=a.frontmatter)==null?void 0:m.links)?a.frontmatter.links:[];return e.jsxs("div",{className:"memory-note-detail",children:[e.jsxs("div",{className:"memory-note-detail-head",children:[e.jsx("h3",{children:on(a)}),e.jsx("button",{type:"button",className:"icon-btn",onClick:t,"aria-label":"Close",children:e.jsx(we,{size:12})})]}),e.jsxs("div",{className:"memory-note-detail-meta",children:[e.jsx("code",{children:s}),e.jsxs("span",{className:"muted",children:["· modified ",as(a.mtime)]})]}),u.length>0&&e.jsx("div",{className:"memory-tag-row",children:u.map((d,p)=>e.jsx("span",{className:"memory-tag",children:String(d)},p))}),e.jsx("pre",{className:"memory-note-body mono text-sm",children:a.body}),i.length>0&&e.jsxs("div",{className:"memory-backlinks",children:[e.jsx("h4",{children:"Backlinks"}),e.jsx("ul",{children:i.map(d=>e.jsxs("li",{children:[e.jsx("code",{children:d.fromRelPath}),e.jsx("p",{className:"muted text-sm",children:d.snippet})]},d.fromRelPath))})]}),x.length>0&&e.jsxs("div",{className:"memory-backlinks",children:[e.jsx("h4",{children:"Forward links"}),e.jsx("ul",{children:x.map((d,p)=>e.jsx("li",{children:e.jsx("code",{children:String(d)})},p))})]})]})}function $a({mode:s,initial:t,onSave:a,onCancel:n}){const[i,l]=r.useState((t==null?void 0:t.relPath)||"untitled.md"),[o,c]=r.useState(t!=null&&t.frontmatter?Vc(t.frontmatter):`title: ""
|
|
13
|
-
tags: []
|
|
14
|
-
`),[u,x]=r.useState((t==null?void 0:t.body)||""),[h,m]=r.useState(!1),d=ce(),p=async()=>{if(!i.endsWith(".md")){d.error("Path must end in .md");return}let f;try{f=Wc(o)||{}}catch(b){d.error(`Frontmatter parse failed: ${b.message}`);return}m(!0);try{await a(i,f,u)}finally{m(!1)}};return e.jsxs("div",{className:"memory-editor-modal",children:[e.jsx("label",{className:"field-label",htmlFor:"obsidian-note-path",children:"Path"}),e.jsx("input",{id:"obsidian-note-path",type:"text",className:"input mono",value:i,onChange:f=>l(f.target.value),disabled:s==="edit",placeholder:"notes/example.md"}),e.jsx("label",{className:"field-label",htmlFor:"obsidian-note-frontmatter",style:{marginTop:12},children:"Frontmatter (YAML)"}),e.jsx("textarea",{id:"obsidian-note-frontmatter",className:"memory-editor-textarea mono text-sm",rows:6,value:o,onChange:f=>c(f.target.value),"aria-label":"Frontmatter YAML"}),e.jsx("label",{className:"field-label",htmlFor:"obsidian-note-body",style:{marginTop:12},children:"Body (Markdown)"}),e.jsx("textarea",{id:"obsidian-note-body",className:"memory-editor-textarea mono text-sm",rows:14,value:u,onChange:f=>x(f.target.value),"aria-label":"Body markdown"}),e.jsxs("div",{className:"modal-footer-actions",style:{marginTop:12},children:[e.jsx(M,{variant:"ghost",onClick:n,disabled:h,children:"Cancel"}),e.jsxs(M,{variant:"primary",onClick:p,disabled:h,children:[h&&e.jsx(ge,{size:12,className:"memory-spin"}),s==="create"?"Create":"Save"]})]})]})}function Vc(s){const t=[];for(const[a,n]of Object.entries(s))if(n!=null)if(Array.isArray(n)){if(n.length===0){t.push(`${a}: []`);continue}t.push(`${a}:`);for(const i of n)t.push(` - ${It(i)}`)}else if(typeof n=="object"){t.push(`${a}:`);for(const[i,l]of Object.entries(n))t.push(` ${i}: ${It(l)}`)}else t.push(`${a}: ${It(n)}`);return t.join(`
|
|
15
|
-
`)}function It(s){return typeof s=="string"?/[:#\n"']/.test(s)||s===""?JSON.stringify(s):s:typeof s=="number"||typeof s=="boolean"?String(s):JSON.stringify(s)}function Wc(s){const t={},a=s.split(/\r?\n/);let n=0;for(;n<a.length;){const i=a[n];if(!i.trim()||i.trim().startsWith("#")){n++;continue}const l=i.match(/^([A-Za-z_][\w-]*):\s*(.*)$/);if(!l){n++;continue}const[,o,c]=l;if(c===""){const u={},x=[];let h=!1,m=!1;for(;n+1<a.length;){const d=a[n+1];if(!d.startsWith(" "))break;if(d.startsWith(" - "))h=!0,x.push(Et(d.slice(4))),n++;else{m=!0;const p=d.match(/^ ([A-Za-z_][\w-]*):\s*(.*)$/);p&&(u[p[1]]=Et(p[2])),n++}}t[o]=h&&!m?x:m?u:{}}else t[o]=Et(c);n++}return t}function Et(s){const t=s.trim();return t===""?"":t==="true"?!0:t==="false"?!1:t==="null"||t==="~"?null:/^-?\d+$/.test(t)?parseInt(t,10):/^-?\d+\.\d+$/.test(t)?parseFloat(t):t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function qc({refreshKey:s}){var C,z,y,R;const t=ce(),[a,n]=r.useState(null),[i,l]=r.useState(null),[o,c]=r.useState(!0),[u,x]=r.useState(null),[h,m]=r.useState(null),d=async()=>{var S;c(!0);try{const[N,P,g]=await Promise.all([$.get("/memory/git/status").catch(()=>null),$.get("/memory/git/diff").catch(()=>null),$.get("/memory/config/global").catch(()=>null)]);n(N),l(P),m(((S=g==null?void 0:g.config)==null?void 0:S.git)||null)}catch(N){t.error(`Git status failed: ${N.message}`)}finally{c(!1)}};r.useEffect(()=>{d()},[s]);const p=async(S,N,P)=>{x(S);try{await N(),t.success(P),await d()}catch(g){t.error(`${S} failed: ${g.message}`)}finally{x(null)}},f=()=>p("pull",()=>$.post("/memory/git/pull",{}),"Pull complete."),b=()=>p("push",()=>$.post("/memory/git/push",{}),"Push complete."),k=()=>{const S=prompt("Commit message:",`[memory-sync] ${new Date().toISOString().slice(0,10)} vault sync`);S&&p("commit",()=>$.post("/memory/git/commit",{message:S}),"Committed.")},w=()=>p("fetch",()=>$.post("/memory/git/sync",{push:!1}),"Fetch complete.");if(o&&!a)return e.jsxs("div",{className:"view-loading",children:[e.jsx(he,{size:"lg"}),e.jsx("p",{children:"Loading git status…"})]});if(!a)return e.jsx("div",{className:"muted",children:"No git data available."});const v=a.mode==="local-only";return e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(G,{variant:"elevated",children:[e.jsxs(ee,{children:[e.jsx(Ze,{size:14})," Git sync",v?e.jsx("span",{className:"memory-source-pill-status na",children:"local-only"}):e.jsx("span",{className:W("memory-source-pill-status",a.clean?"on":"warn"),children:a.clean?"clean":"dirty"})]}),e.jsx(te,{children:v?"Memory is in local-only mode. Configure a shared repo in Settings → Memory to enable git sync.":e.jsxs(e.Fragment,{children:["Branch ",e.jsx("code",{children:a.branch||"—"}),a.ahead?e.jsxs(e.Fragment,{children:[" · ahead ",a.ahead]}):null,a.behind?e.jsxs(e.Fragment,{children:[" · behind ",a.behind]}):null]})}),!v&&e.jsxs("div",{className:"memory-git-status-row",children:[e.jsx(Us,{ok:a.clean??!1,label:"Working tree"}),e.jsx(Us,{ok:(a.ahead??0)===0,label:`Ahead: ${a.ahead??0}`}),e.jsx(Us,{ok:(a.behind??0)===0,label:`Behind: ${a.behind??0}`}),e.jsx(Us,{ok:(((C=a.modified)==null?void 0:C.length)??0)===0,label:`Modified: ${((z=a.modified)==null?void 0:z.length)??0}`}),e.jsx(Us,{ok:(((y=a.untracked)==null?void 0:y.length)??0)===0,label:`Untracked: ${((R=a.untracked)==null?void 0:R.length)??0}`})]}),e.jsxs("div",{className:"memory-action-row",children:[e.jsxs(M,{variant:"secondary",size:"sm",onClick:f,disabled:!!u||v,children:[u==="pull"?e.jsx(ge,{size:12,className:"memory-spin"}):e.jsx(vt,{size:12}),"Pull"]}),e.jsxs(M,{variant:"secondary",size:"sm",onClick:b,disabled:!!u||v,children:[u==="push"?e.jsx(ge,{size:12,className:"memory-spin"}):e.jsx(Zs,{size:12}),"Push"]}),e.jsxs(M,{variant:"secondary",size:"sm",onClick:k,disabled:!!u||v,children:[u==="commit"?e.jsx(ge,{size:12,className:"memory-spin"}):e.jsx(Ga,{size:12}),"Commit"]}),e.jsxs(M,{variant:"ghost",size:"sm",onClick:w,disabled:!!u||v,children:[u==="fetch"?e.jsx(ge,{size:12,className:"memory-spin"}):e.jsx(mi,{size:12}),"Fetch + sync"]}),e.jsxs(M,{variant:"ghost",size:"sm",onClick:d,disabled:!!u,children:[e.jsx(me,{size:12})," Refresh"]})]})]}),h&&e.jsxs(G,{children:[e.jsxs(ee,{children:[e.jsx(ui,{size:14})," Repository"]}),e.jsxs(te,{children:["Snapshot of ",e.jsx("code",{children:"~/.config/bizar/memory-config.json"})," → git block."]}),e.jsxs("dl",{className:"memory-config-row",children:[e.jsx("dt",{children:"Path"}),e.jsx("dd",{className:"mono ellipsis",title:h.repoPath,children:h.repoPath||"—"}),e.jsx("dt",{children:"Remote"}),e.jsx("dd",{className:"mono ellipsis",title:h.remoteUrl,children:h.remoteUrl||"—"}),e.jsx("dt",{children:"Branch"}),e.jsx("dd",{children:e.jsx("code",{children:h.branch||"main"})}),e.jsx("dt",{children:"Auto-sync"}),e.jsx("dd",{children:h.autoSync?"enabled":"disabled"})]})]}),e.jsxs(G,{children:[e.jsxs(ee,{children:[e.jsx(hi,{size:14})," Working-tree diff"]}),e.jsx(te,{children:i!=null&&i.hasDiff?`${i.files.length} file(s) changed`:"no working-tree changes"}),i&&i.files.length>0&&e.jsx("ul",{className:"memory-diff-files",children:i.files.map(S=>e.jsx("li",{children:e.jsx("code",{children:S})},S))}),i&&i.lines.length>1&&e.jsx("pre",{className:"memory-log-tail mono text-xs",children:i.lines.slice(0,400).join(`
|
|
16
|
-
`)})]})]})}function Us({ok:s,label:t}){return e.jsxs("span",{className:W("memory-git-status-pill",s?"ok":"warn"),children:[s?e.jsx(_e,{size:11}):e.jsx(ge,{size:11,className:"memory-spin"}),t]})}function Gc({refreshKey:s}){const t=ce(),[a,n]=r.useState(""),[i,l]=r.useState({lightrag:!0,obsidian:!0}),[o,c]=r.useState(null),[u,x]=r.useState(!1),[h,m]=r.useState(""),d=async f=>{if(f.trim()){x(!0),m(f);try{const b=[...i.lightrag?["lightrag"]:[],...i.obsidian?["obsidian"]:[]],k=await $.post("/memory/semantic-search",{query:f,limit:20,sources:b});c(k.results||[])}catch(b){t.error(`Search failed: ${b.message}`),c([])}finally{x(!1)}}};r.useEffect(()=>{h&&d(h)},[i]),r.useEffect(()=>{h&&d(h)},[s]);const p=r.useMemo(()=>{const f=(o||[]).filter(k=>k.source==="obsidian"),b=(o||[]).filter(k=>k.source==="lightrag");return{obs:f,lr:b}},[o]);return e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(G,{variant:"elevated",children:[e.jsxs(ee,{children:[e.jsx(ke,{size:14})," Semantic search"]}),e.jsx(te,{children:"Query both LightRAG (graph-based) and the Obsidian vault in one shot."}),e.jsxs("div",{className:"memory-search-row",children:[e.jsx("label",{htmlFor:"semantic-search-input",className:"sr-only",children:"Semantic search"}),e.jsx("input",{id:"semantic-search-input",type:"text",className:"input",placeholder:"e.g. how are notes indexed?",value:a,onChange:f=>n(f.target.value),onKeyDown:f=>{f.key==="Enter"&&d(a)},disabled:u,"aria-label":"Semantic search query"}),e.jsxs(M,{variant:"primary",onClick:()=>d(a),disabled:u||!a.trim(),children:[u?e.jsx(ge,{size:12,className:"memory-spin"}):e.jsx(ke,{size:12}),"Search"]})]}),e.jsxs("div",{className:"memory-source-toggle-row",children:[e.jsx(Ra,{active:i.obsidian,onToggle:()=>l(f=>({...f,obsidian:!f.obsidian})),label:"Obsidian",icon:e.jsx(Ie,{size:11})}),e.jsx(Ra,{active:i.lightrag,onToggle:()=>l(f=>({...f,lightrag:!f.lightrag})),label:"LightRAG",icon:e.jsx(Je,{size:11})}),a&&e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>{n(""),c(null),m("")},"aria-label":"Clear",children:e.jsx(we,{size:12})})]})]}),u&&e.jsx("div",{className:"view-loading",children:e.jsx(he,{size:"md"})}),!u&&o&&o.length===0&&e.jsx(Ne,{icon:e.jsx(ke,{size:28}),title:"No matches",message:`Nothing in scope matched "${h}".`}),p.obs.length>0&&e.jsxs(G,{children:[e.jsxs(ee,{children:[e.jsx(Ie,{size:14})," Obsidian (",p.obs.length,")"]}),e.jsx("ul",{className:"memory-search-result-list",children:p.obs.map((f,b)=>e.jsxs("li",{className:"memory-search-result",children:[e.jsxs("div",{className:"memory-search-result-head",children:[e.jsx("code",{children:f.relPath}),e.jsxs("span",{className:"muted text-xs",children:["score ",f.score.toFixed(1)]})]}),e.jsx("p",{className:"muted text-sm",children:f.snippet})]},`obs-${b}`))})]}),p.lr.length>0&&e.jsxs(G,{children:[e.jsxs(ee,{children:[e.jsx(Je,{size:14})," LightRAG (",p.lr.length,")"]}),e.jsx("div",{className:"memory-search-result-list",children:p.lr.map((f,b)=>e.jsxs("div",{className:"memory-search-result",children:[e.jsxs("div",{className:"memory-search-result-head",children:[e.jsxs("span",{className:"memory-source-pill",children:[e.jsx(Je,{size:11})," LightRAG"]}),f.error&&e.jsxs("span",{className:"muted text-xs",children:["error: ",f.error]})]}),e.jsx("p",{className:"text-sm",children:f.snippet})]},`lr-${b}`))})]})]})}function Ra({active:s,onToggle:t,label:a,icon:n}){return e.jsxs("button",{type:"button",className:W("memory-toggle-chip",s&&"memory-toggle-chip-active"),onClick:t,"aria-pressed":s,children:[n,e.jsx("span",{children:a})]})}function Hc({refreshKey:s}){const t=ce(),[a,n]=r.useState(null),[i,l]=r.useState(!0),[o,c]=r.useState(!1),[u,x]=r.useState(""),[h,m]=r.useState(null),[d,p]=r.useState(""),[f,b]=r.useState(!1),[k,w]=r.useState(!1),[v,C]=r.useState(null),[z,y]=r.useState(null),[R,S]=r.useState(null),[N,P]=r.useState(!1),g=async()=>{var D,_;l(!0);try{const[ae,J]=await Promise.all([$.get("/memory/config/global").catch(()=>null),$.get("/memory/status").catch(()=>null)]);ae?(n(ae.config),x(((_=(D=ae.config)==null?void 0:D.git)==null?void 0:_.remoteUrl)||"")):n({}),J&&(m(J),p(ne=>ne||J.vaultRoot||"")),await j()}catch(ae){t.error(`Config load failed: ${ae.message}`)}finally{l(!1)}},j=async()=>{try{const D=await $.get("/memory/git/status");D.ok&&C({clean:D.clean,branch:D.branch,modified:D.modified,untracked:D.untracked})}catch{}};r.useEffect(()=>{g()},[s]);const T=async()=>{const D=d.trim();if(!D){t.error("Vault path cannot be empty.");return}w(!0);try{const _=await $.get("/memory/status").catch(()=>null);(_==null?void 0:_.initialized)?(await $.post("/memory/config/vault",{vaultRoot:D}),t.success(`Vault path updated to ${D}.`)):(await $.post("/memory/init",{vaultRoot:D}),t.success(`Vault initialised at ${D}.`)),p(D),await g()}catch(_){t.error(`Vault path save failed: ${_.message}`)}finally{w(!1)}},F=async()=>{b(!0);try{await $.post("/memory/init",{}),t.success("Vault initialised."),await g()}catch(D){t.error(`Init failed: ${D.message}`)}finally{b(!1)}},A=async()=>{if(a){c(!0);try{await $.put("/memory/config/global",{git:{remoteUrl:u}}),t.success("Config saved.")}catch(D){t.error(`Save failed: ${D.message}`)}finally{c(!1)}}},U=async D=>{y(D);try{if(D==="pull"){const _=await $.post("/memory/git/pull",{});_.ok?t.success("Pull successful."):t.error(`Pull failed: ${_.output||"unknown error"}`)}else if(D==="push")(await $.post("/memory/git/push",{})).ok?t.success("Push successful."):t.error("Push failed.");else if(D==="commit"){const _=await $.post("/memory/git/commit",{});_.ok?t.success(`Committed: ${_.message}`):t.error("Commit failed.")}await j()}catch(_){t.error(`${D} failed: ${_.message}`)}finally{y(null)}},Y=async()=>{P(!0);try{const D=await $.post("/memory/test-git",{});S(D.checks)}catch(D){t.error(`Test failed: ${D.message}`)}finally{P(!1)}};if(i&&!a)return e.jsxs("div",{className:"view-loading",children:[e.jsx(he,{size:"md"}),e.jsx("p",{children:"Loading config…"})]});if(!a)return e.jsx("div",{className:"muted",children:"No config available."});const B=!!(h!=null&&h.initialized),K=(h==null?void 0:h.vaultRoot)??"";return e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(G,{children:[e.jsxs(ee,{children:[e.jsx(ma,{size:14})," Vault location"]}),e.jsxs(te,{children:["The on-disk folder where notes and memory metadata live. Default:"," ",e.jsx("code",{children:"~/.bizar_memory"}),"."]}),e.jsxs("div",{className:"memory-config-form",children:[e.jsxs(rt,{label:"Current path",inline:!0,children:[e.jsx("span",{className:"memory-vault-path mono","data-testid":"memory-current-vault-path",children:K||e.jsx("span",{className:"muted",children:"not initialised"})}),B?e.jsxs("span",{className:"memory-pill memory-pill-ok",style:{marginLeft:8},title:"Vault folder exists on disk",children:[e.jsx(_e,{size:10})," initialised"]}):e.jsxs("span",{className:"memory-pill memory-pill-warn",style:{marginLeft:8},title:"Vault folder does not exist yet",children:[e.jsx(vs,{size:10})," not initialised"]})]}),e.jsxs(rt,{label:"Set path",children:[e.jsx("input",{type:"text",className:"input mono",value:d,onChange:D=>p(D.target.value),placeholder:"~/.bizar_memory","aria-label":"Vault path","data-testid":"memory-vault-path-input"}),e.jsx("span",{className:"field-hint",children:B?"Save to update the working path.":"Save and initialise will create this folder if it does not exist."})]})]}),e.jsxs("div",{className:"memory-action-row",style:{marginTop:12},children:[e.jsxs(M,{variant:"primary",onClick:T,disabled:k||f||!d.trim(),"data-testid":"memory-save-vault-path",children:[k?e.jsx(ge,{size:12,className:"memory-spin"}):e.jsx(Is,{size:12}),B?"Save path":"Save and initialise"]}),!B&&e.jsxs(M,{variant:"secondary",onClick:F,disabled:f||k,"data-testid":"memory-init-vault",children:[f?e.jsx(ge,{size:12,className:"memory-spin"}):e.jsx(ma,{size:12}),"Initialise default"]})]})]}),e.jsxs(G,{children:[e.jsxs(ee,{children:[e.jsx(Ze,{size:14})," Git sync"]}),e.jsx(te,{children:"Configure the git remote and sync your memory vault."}),e.jsxs("div",{className:"memory-config-form",children:[e.jsx(rt,{label:"Remote URL",children:e.jsx("input",{type:"text",className:"input mono",value:u,onChange:D=>x(D.target.value),placeholder:"git@github.com:org/repo.git"})}),v&&e.jsxs(rt,{label:"Status",inline:!0,children:[e.jsx("span",{className:W("memory-pill",v.clean?"memory-pill-ok":"memory-pill-warn"),children:v.clean?"clean":"dirty"}),v.branch&&e.jsxs("span",{className:"muted",style:{marginLeft:8},children:[e.jsx(Ze,{size:12,style:{display:"inline"}})," ",v.branch]}),!v.clean&&v.modified!==void 0&&e.jsxs("span",{className:"muted",style:{marginLeft:8},children:[v.modified," modified, ",v.untracked," untracked"]})]})]}),e.jsxs("div",{className:"memory-action-row",style:{marginTop:12},children:[e.jsxs(M,{variant:"secondary",onClick:()=>U("pull"),disabled:z!==null,children:[z==="pull"?e.jsx(ge,{size:12,className:"memory-spin"}):e.jsx(js,{size:12}),"Pull"]}),e.jsxs(M,{variant:"secondary",onClick:()=>U("commit"),disabled:z!==null,children:[z==="commit"?e.jsx(ge,{size:12,className:"memory-spin"}):e.jsx(Ga,{size:12}),"Commit"]}),e.jsxs(M,{variant:"secondary",onClick:()=>U("push"),disabled:z!==null,children:[z==="push"?e.jsx(ge,{size:12,className:"memory-spin"}):e.jsx(xi,{size:12}),"Push"]})]})]}),e.jsxs(G,{children:[e.jsxs(ee,{children:[e.jsx(Bt,{size:14})," Connection tests"]}),e.jsx(te,{children:"Verify the configured git remote is reachable."}),e.jsxs("div",{className:"memory-action-row",children:[e.jsxs(M,{variant:"secondary",onClick:Y,disabled:N,children:[N?e.jsx(ge,{size:12,className:"memory-spin"}):e.jsx(Bt,{size:12}),"Test git connection"]}),e.jsxs(M,{variant:"primary",onClick:A,disabled:o,children:[o?e.jsx(ge,{size:12,className:"memory-spin"}):e.jsx(Is,{size:12}),"Save config"]})]}),R&&R.length>0&&e.jsx("ul",{className:"memory-check-list",style:{marginTop:12},children:R.map((D,_)=>e.jsxs("li",{className:"memory-check-row",children:[e.jsx("span",{className:"memory-check-icon",children:e.jsx("span",{className:W("memory-pill",D.pass?"memory-pill-ok":"memory-pill-warn"),children:D.pass?"OK":"FAIL"})}),e.jsx("span",{className:"memory-check-name",children:D.name}),e.jsx("span",{className:"memory-check-detail muted",children:D.detail})]},_))})]})]})}function rt({label:s,children:t,inline:a}){return a?e.jsxs("div",{className:"memory-config-row-inline",children:[e.jsx("div",{className:"memory-config-row-label",id:`cfg-${s.replace(/\s+/g,"-").toLowerCase()}`,children:s}),e.jsx("div",{className:"memory-config-row-control",role:"group","aria-labelledby":`cfg-${s.replace(/\s+/g,"-").toLowerCase()}`,children:t})]}):e.jsxs("label",{className:"memory-config-row-stack",children:[e.jsx("span",{children:s}),t]})}const ns=800,Ta=60,Lt={default:"#8b5cf6",note:"#8b5cf6",entity:"#34d399",concept:"#fbbf24",root:"#f87171"};function Kc(s,t){return Lt[s]||Lt[t]||Lt.default}function Yc(s){return 6+Math.min(s.size*2,10)}function Xc(s,t){var l,o;if(s.length===0)return[];const a=new Map;for(const c of s)a.set(c.id,new Set);for(const c of t)(l=a.get(c.source))==null||l.add(c.target),(o=a.get(c.target))==null||o.add(c.source);const n=s.map((c,u)=>{const x=u/s.length*Math.PI*2,h=ns*.28;return{...c,x:ns/2+h*Math.cos(x)+(Math.random()-.5)*40,y:ns/2+h*Math.sin(x)+(Math.random()-.5)*40,vx:0,vy:0}}),i=new Map;for(const c of n)i.set(c.id,c);for(let c=0;c<Ta;c++){const u=1-c/Ta;for(let m=0;m<n.length;m++)for(let d=m+1;d<n.length;d++){const p=n[m],f=n[d],b=f.x-p.x,k=f.y-p.y,w=Math.sqrt(b*b+k*k)||1,v=400*u/(w*w),C=b/w*v,z=k/w*v;p.vx-=C,p.vy-=z,f.vx+=C,f.vy+=z}for(const m of t){const d=i.get(m.source),p=i.get(m.target);if(!d||!p)continue;const f=p.x-d.x,b=p.y-d.y,k=Math.sqrt(f*f+b*b)||1,v=(k-80)*.08*u,C=f/k*v,z=b/k*v;d.vx+=C,d.vy+=z,p.vx-=C,p.vy-=z}const x=ns/2,h=ns/2;for(const m of n)m.vx+=(x-m.x)*.01*u,m.vy+=(h-m.y)*.01*u;for(const m of n)m.vx*=.85,m.vy*=.85,m.x+=m.vx,m.y+=m.vy,m.x=Math.max(20,Math.min(ns-20,m.x)),m.y=Math.max(20,Math.min(ns-20,m.y))}return n}function Qc({data:s,onNodeClick:t,className:a}){const n=r.useRef(null),[i,l]=r.useState({x:0,y:0,scale:1}),o=r.useRef(!1),c=r.useRef({x:0,y:0,tx:0,ty:0}),u=r.useRef(null),[x,h]=r.useState(null),[m,d]=r.useState(null),p=r.useMemo(()=>Xc(s.nodes,s.edges),[s.nodes,s.edges]),f=r.useMemo(()=>{const N=new Map;for(const P of p)N.set(P.id,P);return N},[p]),b=r.useCallback(N=>{N.target.closest(".memory-graph-node")||(o.current=!0,c.current={x:N.clientX,y:N.clientY,tx:i.x,ty:i.y})},[i]),k=r.useCallback(N=>{if(!o.current)return;const P=N.clientX-c.current.x,g=N.clientY-c.current.y;l(j=>({...j,x:c.current.tx+P,y:c.current.ty+g}))},[]),w=r.useCallback(()=>{o.current=!1},[]),v=r.useCallback(N=>{N.preventDefault();const P=N.deltaY<0?1.1:.9,g=n.current;if(!g)return;const j=g.getBoundingClientRect(),T=N.clientX-j.left,F=N.clientY-j.top;l(A=>{const U=Math.max(.2,Math.min(4,A.scale*P)),Y=U/A.scale;return{x:T-(T-A.x)*Y,y:F-(F-A.y)*Y,scale:U}})},[]),C=r.useCallback(N=>{const P=Array.from(N.touches);if(P.length===2){const[g,j]=P;u.current=Math.hypot(j.clientX-g.clientX,j.clientY-g.clientY)}else P.length===1&&(o.current=!0,c.current={x:P[0].clientX,y:P[0].clientY,tx:i.x,ty:i.y})},[i]),z=r.useCallback(N=>{const P=Array.from(N.touches);if(P.length===2&&u.current!==null){const[g,j]=P,T=Math.hypot(j.clientX-g.clientX,j.clientY-g.clientY),F=T/u.current;u.current=T,l(A=>({...A,scale:Math.max(.2,Math.min(4,A.scale*F))}))}else if(P.length===1&&o.current){const g=P[0].clientX-c.current.x,j=P[0].clientY-c.current.y;l(T=>({...T,x:c.current.tx+g,y:c.current.ty+j}))}},[]),y=r.useCallback(()=>{o.current=!1,u.current=null},[]),R=r.useCallback(N=>{h(N.id===x?null:N.id),t==null||t(N)},[x,t]),S=Math.max(.5,1/Math.log2(i.scale+1));return e.jsx("svg",{ref:n,className:W("memory-graph-canvas",a),viewBox:`0 0 ${ns} ${ns}`,style:{width:"100%",height:"100%",minHeight:400,cursor:o.current?"grabbing":"grab"},onMouseDown:b,onMouseMove:k,onMouseUp:w,onMouseLeave:w,onWheel:v,onTouchStart:C,onTouchMove:z,onTouchEnd:y,children:e.jsxs("g",{transform:`translate(${i.x},${i.y}) scale(${i.scale})`,children:[s.edges.map((N,P)=>{const g=f.get(N.source),j=f.get(N.target);if(!g||!j)return null;const T=m===N.source||m===N.target||x===N.source||x===N.target;return e.jsx("line",{x1:g.x,y1:g.y,x2:j.x,y2:j.y,stroke:T?"#8b5cf6":"#2d3648",strokeWidth:T?S*2:S,strokeOpacity:T?.9:.5},`e-${P}`)}),p.map(N=>{const P=Yc(N),g=Kc(N.group,N.type),j=x===N.id,T=m===N.id;return e.jsxs("g",{className:"memory-graph-node",transform:`translate(${N.x},${N.y})`,onClick:()=>R(N),onMouseEnter:()=>d(N.id),onMouseLeave:()=>d(null),style:{cursor:"pointer"},children:[e.jsx("circle",{r:P+6,fill:"transparent"}),(j||T)&&e.jsx("circle",{r:P+4,fill:g,fillOpacity:.2}),e.jsx("circle",{r:P,fill:g,fillOpacity:j?1:.75,stroke:j?"#fff":g,strokeWidth:j?2:1}),i.scale>.5&&e.jsx("text",{y:P+12,textAnchor:"middle",fontSize:Math.max(8,Math.min(11,10/Math.sqrt(i.scale))),fill:"var(--text-dim, #b4bcd0)",style:{pointerEvents:"none",userSelect:"none"},children:N.label.length>20?N.label.slice(0,18)+"…":N.label})]},N.id)})]})})}const Jc=[{color:"#8b5cf6",label:"Note / Default"},{color:"#34d399",label:"Entity (LightRAG)"},{color:"#fbbf24",label:"Concept (LightRAG)"},{color:"#f87171",label:"Root / Ungrouped"}];function Zc({className:s}){return e.jsx("div",{className:W("memory-graph-legend",s),children:Jc.map(t=>e.jsxs("span",{className:"memory-graph-legend-item",children:[e.jsx("span",{className:"memory-graph-legend-dot",style:{background:t.color}}),t.label]},t.label))})}function eo({refreshKey:s}){const t=ce(),[a,n]=r.useState({nodes:[],edges:[]}),[i,l]=r.useState(!0),[o,c]=r.useState(null),[u,x]=r.useState(""),[h,m]=r.useState(2),[d,p]=r.useState(""),[f,b]=r.useState(null),[k,w]=r.useState(null),v=r.useCallback(async()=>{var y,R;l(!0),c(null);try{const S=new URLSearchParams({limit:"200"});d&&S.set("root",d),S.set("depth",String(h));const N=await $.get(`/memory/graph?${S}`);n({nodes:N.nodes||[],edges:N.edges||[]}),b({totalNodes:N.totalNodes??((y=N.nodes)==null?void 0:y.length)??0,totalEdges:N.totalEdges??((R=N.edges)==null?void 0:R.length)??0})}catch(S){c(S.message),t.error(`Graph load failed: ${S.message}`)}finally{l(!1)}},[d,h,t]);r.useEffect(()=>{v()},[v,s]);const C=r.useCallback(y=>{w(R=>(R==null?void 0:R.id)===y.id?null:y)},[]),z=u.trim()?{nodes:a.nodes.filter(y=>y.label.toLowerCase().includes(u.toLowerCase())),edges:a.edges.filter(y=>a.nodes.some(R=>R.id===y.source&&R.label.toLowerCase().includes(u.toLowerCase()))||a.nodes.some(R=>R.id===y.target&&R.label.toLowerCase().includes(u.toLowerCase())))}:a;return e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(G,{children:[e.jsxs(ee,{children:[e.jsx(Ha,{size:14})," Memory Graph"]}),e.jsx(te,{children:"Interactive knowledge graph — LightRAG entities + Obsidian wikilinks. Drag to pan, scroll to zoom."}),e.jsxs("div",{className:"memory-graph-controls",children:[e.jsxs("div",{className:"memory-graph-search-row",children:[e.jsx("label",{htmlFor:"graph-filter",className:"sr-only",children:"Filter nodes"}),e.jsx("input",{id:"graph-filter",type:"text",className:"input",placeholder:"Filter nodes…",value:u,onChange:y=>x(y.target.value),style:{maxWidth:240}}),e.jsx("input",{type:"text",className:"input",placeholder:"Root note id (optional)",value:d,onChange:y=>p(y.target.value),style:{maxWidth:240},title:"Start from a specific note"}),e.jsx("label",{htmlFor:"graph-depth",className:"sr-only",children:"Depth"}),e.jsxs("span",{className:"muted text-sm",style:{whiteSpace:"nowrap"},children:["Depth",e.jsx("input",{id:"graph-depth",type:"range",min:1,max:3,value:h,onChange:y=>m(parseInt(y.target.value,10)),style:{marginLeft:8,verticalAlign:"middle"}}),h]}),e.jsx("button",{type:"button",className:"icon-btn",onClick:v,title:"Refresh graph",disabled:i,children:e.jsx(me,{size:14,className:i?"memory-spin":""})})]}),e.jsx(Zc,{})]})]}),e.jsx(G,{children:i&&!a.nodes.length?e.jsxs("div",{className:"view-loading",children:[e.jsx(he,{size:"lg"}),e.jsx("p",{children:"Loading graph…"})]}):o&&!a.nodes.length?e.jsxs("div",{className:"muted text-sm",children:["Failed to load graph: ",o]}):a.nodes.length===0?e.jsx("div",{className:"muted text-sm",children:"No graph data available. Index some notes first with LightRAG or add wikilinks to your vault."}):e.jsxs("div",{style:{position:"relative"},children:[e.jsx(Qc,{data:z,onNodeClick:C,className:"memory-graph-canvas-svg"}),u&&e.jsxs("div",{className:"text-xs muted",style:{marginTop:4},children:["Showing ",z.nodes.length," of ",a.nodes.length," nodes"]})]})}),k&&e.jsxs(G,{children:[e.jsx(ee,{children:k.label}),e.jsx(te,{children:e.jsx("code",{children:k.id})}),e.jsxs("dl",{className:"memory-config-row",children:[e.jsx("dt",{children:"Type"}),e.jsx("dd",{children:e.jsx("code",{children:k.type})}),e.jsx("dt",{children:"Group"}),e.jsx("dd",{children:e.jsx("code",{children:k.group})}),e.jsx("dt",{children:"Size"}),e.jsx("dd",{children:k.size})]})]}),f&&e.jsx(G,{children:e.jsxs("div",{className:"memory-graph-stats",children:[e.jsxs("span",{children:[f.totalNodes," node",f.totalNodes!==1?"s":""]}),e.jsx("span",{className:"muted",children:"·"}),e.jsxs("span",{children:[f.totalEdges," edge",f.totalEdges!==1?"s":""]}),u&&e.jsxs("span",{className:"muted",children:["· ",z.nodes.length," shown"]})]})})]})}function so({onTextExtracted:s}){const t=ce(),[a,n]=r.useState(null),[i,l]=r.useState(!1),[o,c]=r.useState(!1),u=r.useCallback(async()=>{c(!0);try{const m=await navigator.mediaDevices.getDisplayMedia({video:{mediaSource:"screen"}}),d=document.createElement("video");d.srcObject=m,await d.play();const p=document.createElement("canvas");p.width=d.videoWidth,p.height=d.videoHeight;const f=p.getContext("2d");if(!f){t.error("Failed to get canvas context");return}f.drawImage(d,0,0),m.getTracks().forEach(b=>b.stop()),d.remove(),p.toBlob(async b=>{if(!b){t.error("Failed to capture screenshot");return}const k=URL.createObjectURL(b);n(k),await x(b)},"image/png")}catch(m){m.name!=="NotAllowedError"&&t.error(`Capture failed: ${m.message}`)}finally{c(!1)}},[t]),x=r.useCallback(async m=>{l(!0);try{const d=new FileReader,p=await new Promise((b,k)=>{d.onload=()=>{const w=d.result,v=w.includes(",")?w.split(",")[1]:w;b(v)},d.onerror=()=>k(new Error("FileReader failed")),d.readAsDataURL(m)}),f=await $.post("/ocr/process",{image:p,lang:"eng"});f.ok&&(t.success("Text extracted from screenshot"),s==null||s(f.text,f.notePath))}catch(d){t.error(`OCR failed: ${d.message}`)}finally{l(!1)}},[t,s]),h=r.useCallback(()=>{n(null)},[]);return e.jsxs(G,{variant:"outlined",className:"screenshot-capture-card",children:[e.jsxs(ee,{children:[e.jsx(wt,{size:14})," Screenshot Capture"]}),e.jsx("div",{className:"screenshot-capture-body",children:a?e.jsxs("div",{className:"screenshot-capture-preview",children:[e.jsx("img",{src:a,alt:"Captured screenshot",className:"screenshot-capture-img"}),e.jsxs("div",{className:"screenshot-capture-actions",children:[i&&e.jsxs("span",{className:"text-sm muted",children:[e.jsx(ge,{size:12,className:"spinner"})," Extracting text…"]}),e.jsx(M,{variant:"ghost",size:"sm",onClick:h,disabled:i,children:"Dismiss"})]})]}):e.jsxs("div",{className:"screenshot-capture-empty",children:[e.jsx(wt,{size:32,className:"muted"}),e.jsx("p",{className:"muted text-sm",children:"Capture your screen to extract text via OCR."}),e.jsxs(M,{variant:"primary",size:"sm",onClick:u,disabled:o,children:[o?e.jsx(ge,{size:12,className:"spinner"}):e.jsx(wt,{size:12}),o?"Selecting…":"Capture Screen"]})]})})]})}function to(){const[s,t]=r.useState(null),[a,n]=r.useState(null),i=(l,o)=>{t(l),n(o)};return e.jsxs("div",{className:"screenshot-ocr-panel",children:[e.jsx(so,{onTextExtracted:i}),s!==null&&e.jsxs(G,{variant:"outlined",className:"screenshot-ocr-result-card",children:[e.jsxs(ee,{children:[e.jsx(Ie,{size:14})," Extracted Text"]}),a&&e.jsxs(te,{children:["Saved to: ",a]}),e.jsx("div",{className:"screenshot-ocr-text",children:s?e.jsx("pre",{className:"screenshot-ocr-pre mono text-sm",children:s}):e.jsx("p",{className:"muted text-sm",children:"No text was found in the captured image."})})]})]})}function ao({refreshKey:s}){return e.jsx("div",{className:"memory-panel-content",children:e.jsx(G,{variant:"outlined",className:"memory-panel-card",children:e.jsx("div",{className:"memory-panel-body",children:e.jsx(to,{})})})})}function no({refreshKey:s}){const t=ce(),[a,n]=r.useState(""),[i,l]=r.useState(""),[o,c]=r.useState(""),[u,x]=r.useState(!1),h=async()=>{if(!o.trim()){t.error("Content is required");return}x(!0);try{const m=await $.post("/clipboard/save",{url:a.trim()||void 0,title:i.trim()||void 0,content:o,savedAt:new Date().toISOString()});m.ok&&(t.success(`Saved to ${m.notePath}`),n(""),l(""),c(""))}catch(m){t.error(`Save failed: ${m.message}`)}finally{x(!1)}};return e.jsx("div",{className:"memory-panel-content",children:e.jsx(G,{variant:"outlined",className:"memory-panel-card",children:e.jsx("div",{className:"memory-panel-body",children:e.jsxs("div",{className:"vault-clipboard-panel",children:[e.jsxs("div",{className:"vault-clipboard-header",children:[e.jsx(Ka,{size:16}),e.jsx("span",{children:"Paste Content"})]}),e.jsx("label",{className:"field-label",htmlFor:"clip-url",children:"URL (optional)"}),e.jsx("input",{id:"clip-url",type:"text",className:"input",placeholder:"https://example.com",value:a,onChange:m=>n(m.target.value)}),e.jsx("label",{className:"field-label",htmlFor:"clip-title",style:{marginTop:10},children:"Title (optional)"}),e.jsx("input",{id:"clip-title",type:"text",className:"input",placeholder:"Page title",value:i,onChange:m=>l(m.target.value)}),e.jsx("label",{className:"field-label",htmlFor:"clip-content",style:{marginTop:10},children:"Content *"}),e.jsx("textarea",{id:"clip-content",className:"input vault-clipboard-textarea mono text-sm",rows:12,placeholder:"Paste or type content to save to your vault…",value:o,onChange:m=>c(m.target.value)}),e.jsx("div",{className:"vault-clipboard-actions",style:{marginTop:12},children:e.jsxs(M,{variant:"primary",size:"sm",onClick:h,disabled:u||!o.trim(),children:[u&&e.jsx(ge,{size:12,className:"spinner"}),"Save to Vault"]})})]})})})})}function io({vaultPath:s,onSaved:t}){const[a,n]=r.useState(!1),[i,l]=r.useState(!1),o=r.useRef(null),c=r.useRef([]),u=async()=>{try{const m=await navigator.mediaDevices.getUserMedia({audio:!0}),d=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm",p=new MediaRecorder(m,{mimeType:d});p.ondataavailable=f=>{f.data&&f.data.size>0&&c.current.push(f.data)},p.onstop=async()=>{const f=new Blob(c.current,{type:"audio/webm"});c.current=[],m.getTracks().forEach(b=>b.stop()),await h(f)},p.start(1e3),o.current=p,n(!0)}catch(m){is.error("[VoiceRecorder] failed to start recording:",m)}},x=()=>{const m=o.current;m&&(m.stop(),n(!1),l(!0))},h=async m=>{try{const d=new FormData;d.append("audio",m,"voice-note.webm"),d.append("vaultPath",s||"");const p=await fetch("/api/voice/upload",{method:"POST",body:d});if(!p.ok){is.error("[VoiceRecorder] upload failed:",p.status,await p.text()),l(!1);return}const{notePath:f,transcription:b}=await p.json();t==null||t(f,b)}catch(d){is.error("[VoiceRecorder] upload error:",d)}finally{l(!1)}};return e.jsxs("div",{className:"voice-recorder",children:[!a&&!i&&e.jsxs(M,{variant:"accent",size:"sm",onClick:u,"aria-label":"Start recording",children:[e.jsx(na,{size:14})," Record"]}),a&&e.jsxs(M,{variant:"danger",size:"sm",onClick:x,"aria-label":"Stop recording",children:[e.jsx(pi,{size:14})," Stop"]}),i&&e.jsxs(M,{variant:"secondary",size:"sm",disabled:!0,children:[e.jsx(ge,{size:14,className:"spinning"})," Transcribing…"]})]})}function ro({note:s,onDelete:t}){const[a,n]=r.useState(!1),[i]=r.useState(()=>{if(!s.audioPath)return null;const c=new Audio(`/api/voice/${s.id}/audio`);return c.onended=()=>n(!1),c}),l=()=>{i&&(a?(i.pause(),i.currentTime=0,n(!1)):(i.play(),n(!0)))},o=new Date(s.createdAtMs).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"});return e.jsxs("div",{className:"voice-note-card",children:[e.jsxs("div",{className:"voice-note-card-head",children:[e.jsxs("div",{className:"voice-note-card-meta",children:[e.jsx("span",{className:"voice-note-date",children:o}),s.durationSec&&e.jsxs("span",{className:"voice-note-duration",children:[Math.round(s.durationSec),"s"]})]}),e.jsxs("div",{className:"voice-note-card-actions",children:[i&&e.jsx("button",{type:"button",className:"icon-btn",onClick:l,"aria-label":a?"Pause":"Play",title:a?"Pause":"Play",children:a?e.jsx(ea,{size:13}):e.jsx(Es,{size:13})}),e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>t(s.id),"aria-label":"Delete note",title:"Delete note",children:e.jsx(Re,{size:13})})]})]}),s.transcript&&e.jsx("p",{className:"voice-note-transcript",children:s.transcript}),!s.transcript&&e.jsx("p",{className:"voice-note-no-transcript muted text-sm",children:"No transcription available"})]})}function lo({vaultPath:s,refreshKey:t=0}){const[a,n]=r.useState([]),[i,l]=r.useState(""),[o,c]=r.useState(!0),u=async()=>{c(!0);try{const m=s?`?vaultPath=${encodeURIComponent(s)}`:"",p=await(await fetch(`/api/voice/list${m}`)).json();n(p.notes||[])}catch(m){is.error("[VoiceNotesPanel] failed to load notes:",m)}finally{c(!1)}};r.useEffect(()=>{u();const m=f=>{try{const b=JSON.parse(f.data);b.type==="voice:updated"&&b.noteId&&n(k=>k.map(w=>{var v;return w.id===b.noteId?{...w,transcript:((v=b.patch)==null?void 0:v.transcript)??w.transcript}:w}))}catch{}},d=`${location.protocol==="https:"?"wss":"ws"}://${location.host}/ws`;let p=null;try{p=new WebSocket(d),p.addEventListener("message",m)}catch{}return()=>{p==null||p.removeEventListener("message",m),p==null||p.close()}},[s,t]);const x=async m=>{try{const d=await fetch(`/api/voice/${m}`,{method:"DELETE"});(d.ok||d.status===204)&&n(p=>p.filter(f=>f.id!==m))}catch(d){is.error("[VoiceNotesPanel] delete failed:",d)}},h=a.filter(m=>{var d;return!i||(((d=m.transcript)==null?void 0:d.toLowerCase().includes(i.toLowerCase()))??!1)});return e.jsxs(G,{children:[e.jsxs(ee,{children:[e.jsx(na,{size:14})," Voice Notes"]}),e.jsx(te,{children:"Record and transcribe audio notes into your vault"}),e.jsx("div",{className:"memory-search-row",children:e.jsx("input",{type:"text",className:"input search-input",value:i,onChange:m=>l(m.target.value),placeholder:"Search transcripts…","aria-label":"Search voice notes"})}),e.jsx("div",{className:"voice-recorder-row",children:e.jsx(io,{vaultPath:s,onSaved:u})}),o?e.jsx("p",{className:"muted text-sm",children:"Loading notes…"}):h.length===0?e.jsx("p",{className:"muted text-sm",children:i?"No notes match your search.":"No voice notes yet. Hit Record to add one."}):e.jsx("div",{className:"voice-note-list",children:h.map(m=>e.jsx(ro,{note:m,onDelete:x},m.id))})]})}const co=[{id:"overview",label:"Overview",icon:Da},{id:"lightrag",label:"LightRAG",icon:Je},{id:"obsidian",label:"Obsidian Vault",icon:Ie},{id:"git",label:"Git Sync",icon:Ze},{id:"semantic",label:"Semantic Search",icon:ke},{id:"config",label:"Config",icon:Qt},{id:"graph",label:"Memory Graph",icon:Ha},{id:"webclip",label:"Web Clip",icon:Ka},{id:"screenshot",label:"Screenshot OCR",icon:gi},{id:"voice",label:"Voice Notes",icon:na}];function oo(s){const t=ce(),[a,n]=r.useState("overview"),[i,l]=r.useState(0),o=r.useCallback(()=>{l(x=>x+1)},[]),c=r.useCallback(async()=>{o(),t.info("Refreshing memory…",1200)},[o,t]),u=()=>{switch(a){case"overview":return e.jsx(_c,{refreshKey:i,onRefresh:o,setActiveSubPanel:n});case"lightrag":return e.jsx(Fc,{refreshKey:i});case"obsidian":return e.jsx(Bc,{refreshKey:i});case"git":return e.jsx(qc,{refreshKey:i});case"semantic":return e.jsx(Gc,{refreshKey:i});case"config":return e.jsx(Hc,{refreshKey:i});case"graph":return e.jsx(eo,{refreshKey:i});case"webclip":return e.jsx(no,{refreshKey:i});case"screenshot":return e.jsx(ao,{refreshKey:i});case"voice":return e.jsx(lo,{refreshKey:i});default:return e.jsxs(G,{children:["Unknown panel: ",a]})}};return e.jsxs("div",{className:"view view-memory memory-tab",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(Je,{size:18})," Memory"]}),e.jsx("p",{className:"view-subtitle",children:"LightRAG, Obsidian vault, git sync, semantic search, web clips, and screenshot OCR — all in one place."})]}),e.jsx("div",{className:"view-actions",children:e.jsx("button",{type:"button",className:"icon-btn",onClick:c,"aria-label":"Refresh memory",title:"Refresh",children:e.jsx(me,{size:14})})})]}),e.jsxs("div",{className:"memory-tab-body",children:[e.jsx("nav",{className:"memory-source-rail","aria-label":"Memory sources",children:co.map(x=>{const h=x.icon,m=a===x.id;return e.jsxs("button",{type:"button",role:"tab","aria-selected":m,className:W("memory-source-button",m&&"memory-source-button-active"),onClick:()=>n(x.id),children:[e.jsx(h,{size:16,"aria-hidden":!0}),e.jsx("span",{children:x.label})]},x.id)})}),e.jsx("div",{className:"memory-main",children:u()},a)]})]})}const mo=Ke.memo(oo),Vs=[{id:"1h",label:"Last hour",ms:60*60*1e3},{id:"1d",label:"Last day",ms:24*60*60*1e3},{id:"7d",label:"Last 7 days",ms:7*24*60*60*1e3},{id:"30d",label:"Last 30 days",ms:30*24*60*60*1e3},{id:"all",label:"All time",ms:0}];function uo(s,t,a,n){const i=a.has(s.id);return e.jsxs(G,{className:"history-project",style:{marginBottom:4},children:[e.jsxs("div",{className:"history-project-head",children:[e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4,minWidth:0,flex:1},children:[e.jsxs("div",{className:"history-project-name",children:[e.jsx(Ge,{size:16})," ",s.name]}),e.jsx("div",{className:"history-project-meta",children:s.path})]}),e.jsxs("div",{className:"history-project-stats",children:[e.jsxs("span",{className:"history-project-stat",children:[e.jsx("span",{className:"history-project-stat-num",children:s.tasks.done}),e.jsxs("span",{className:"muted",children:["/ ",s.tasks.total," done"]})]}),s.tasks.doing>0&&e.jsxs("span",{className:"history-project-stat",children:[e.jsx("span",{className:"history-project-stat-num",children:s.tasks.doing}),e.jsx("span",{className:"muted",children:"doing"})]}),s.tasks.blocked>0&&e.jsxs("span",{className:"history-project-stat",children:[e.jsx("span",{className:"history-project-stat-num",children:s.tasks.blocked}),e.jsx("span",{className:"muted",children:"blocked"})]}),e.jsxs("span",{className:"history-project-stat",children:[e.jsx(Ie,{size:11})," ",e.jsx("span",{className:"history-project-stat-num",children:s.plans}),e.jsxs("span",{className:"muted",children:[" plan",s.plans===1?"":"s"]})]}),s.lastAccessed&&e.jsx("span",{className:"history-project-stat",children:e.jsxs("span",{className:"muted",children:["last opened ",Te(s.lastAccessed)]})})]}),e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>n(s.id),"aria-label":i?"Collapse":"Expand",children:i?e.jsx(He,{size:14}):e.jsx(ds,{size:14})})]}),i&&e.jsx("div",{className:"history-timeline-mini",children:t.length===0?e.jsx("div",{className:"muted",style:{padding:"12px 8px",fontSize:12},children:"No events in this time range."}):t.slice(-100).reverse().map((l,o)=>e.jsxs("div",{className:"history-timeline-row",children:[e.jsx("span",{className:"history-timeline-ts",children:new Date(l.ts).toLocaleTimeString()}),e.jsx("span",{className:"history-timeline-kind",children:l.kind||"event"}),e.jsxs("span",{className:"history-timeline-msg",title:String(l.text||l.title||""),children:[l.author?`@${l.author} `:"",String(l.text??l.title??l.name??"")]})]},o))})]},s.id)}function ho({snapshot:s}){var k,w;const t=ce(),[a,n]=r.useState(null),[i,l]=r.useState(!0),[o,c]=r.useState("1d"),[u,x]=r.useState(new Set),[h,m]=r.useState(0),d=async v=>{try{const C=v?`?since=${encodeURIComponent(v)}&limit=1000`:"?limit=1000",z=await $.get(`/history${C}`);n(z),x(new Set(z.projects.filter(y=>z.events.some(R=>R.projectId===y.id)).map(y=>y.id)))}catch(C){t.error(`History load failed: ${C.message}`)}finally{l(!1)}};r.useEffect(()=>{l(!0);const v=Vs.find(C=>C.id===o)||Vs[1];if(v.ms>0){const C=new Date(Date.now()-v.ms).toISOString();d(C)}else d()},[o]),r.useEffect(()=>{const v=setInterval(()=>m(C=>C+1),3e4);return()=>clearInterval(v)},[]);const p=new Map;for(const v of(a==null?void 0:a.events)||[]){const C=v.projectId||"global";p.has(C)||p.set(C,[]),p.get(C).push(v)}const f=v=>{x(C=>{const z=new Set(C);return z.has(v)?z.delete(v):z.add(v),z})},b=()=>{if(!a)return;const v=new Blob([JSON.stringify(a,null,2)],{type:"application/json"}),C=URL.createObjectURL(v),z=document.createElement("a");z.href=C,z.download=`bizar-history-${new Date().toISOString().replace(/[:.]/g,"-")}.json`,z.click(),URL.revokeObjectURL(C),t.success("History exported.")};return e.jsxs("div",{className:"view view-history","data-tick":h,children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(Gs,{size:18})," History"]}),e.jsxs("p",{className:"view-subtitle",children:["Cross-project history of events, tasks, and plans.",((k=a==null?void 0:a.stats)==null?void 0:k.lastTs)&&e.jsxs(e.Fragment,{children:[" · last event ",Te(a.stats.lastTs)]})]})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs("div",{className:"tasks-toolbar-group",children:[e.jsx(fi,{size:14,style:{color:"var(--text-dim)"},"aria-hidden":!0}),e.jsx("label",{htmlFor:"history-range",className:"sr-only",children:"Time range"}),e.jsx("select",{id:"history-range",className:"select select-sm",value:o,onChange:v=>c(v.target.value),title:"Time range","aria-label":"Time range",children:Vs.map(v=>e.jsx("option",{value:v.id,children:v.label},v.id))})]}),e.jsxs(M,{variant:"ghost",size:"sm",onClick:()=>{l(!0);const v=Vs.find(C=>C.id===o)||Vs[1];v.ms>0?d(new Date(Date.now()-v.ms).toISOString()):d()},children:[e.jsx(me,{size:14})," Refresh"]}),e.jsxs(M,{variant:"secondary",size:"sm",onClick:b,children:[e.jsx(js,{size:14})," Export"]})]})]}),i&&e.jsxs("div",{className:"view-loading",children:[e.jsx(he,{size:"lg"}),e.jsx("p",{children:"Loading history…"})]}),!i&&a&&e.jsxs("div",{className:"history-list",children:[a.projects.length===0&&e.jsxs(G,{children:[e.jsxs(ee,{children:[e.jsx(Ge,{size:14})," No projects"]}),e.jsx(te,{children:"Register a project in Overview to start tracking history."})]}),a.projects.length>0&&e.jsx(Ja,{items:a.projects,itemHeight:70,height:Math.min(a.projects.length*70,500),className:"history-virtual-list",renderItem:v=>uo(v,p.get(v.id)||[],u,f)}),p.has("global")&&e.jsxs(G,{className:"history-project",children:[e.jsx("div",{className:"history-project-head",children:e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4,minWidth:0,flex:1},children:[e.jsxs("div",{className:"history-project-name",children:[e.jsx(Gs,{size:16})," Global events"]}),e.jsx("div",{className:"history-project-meta",children:"Activity not tied to a specific project"})]})}),e.jsx("div",{className:"history-timeline-mini",children:(p.get("global")||[]).slice(-100).reverse().map((v,C)=>e.jsxs("div",{className:"history-timeline-row",children:[e.jsx("span",{className:"history-timeline-ts",children:new Date(v.ts).toLocaleTimeString()}),e.jsx("span",{className:"history-timeline-kind",children:v.kind||"event"}),e.jsxs("span",{className:"history-timeline-msg",title:String(v.text||v.title||""),children:[v.author?`@${v.author} `:"",String(v.text??v.title??v.name??"")]})]},C))})]}),((w=a.stats)==null?void 0:w.counts)&&Object.keys(a.stats.counts).length>0&&e.jsxs(G,{children:[e.jsx(ee,{children:"Event counts by kind"}),e.jsxs(te,{children:[a.stats.lines," total lines in log"]}),e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:8,marginTop:8},children:Object.entries(a.stats.counts).sort((v,C)=>C[1]-v[1]).slice(0,30).map(([v,C])=>e.jsxs("span",{className:W("tag","tag-neutral"),style:{fontFamily:"var(--font-mono)"},children:[v,": ",C]},v))})]})]})]})}const ye={top:16,right:20,bottom:40,left:52};function xo({series:s,height:t=280,onHover:a,className:n}){const i=r.useRef(null),[l,o]=r.useState(null),{labels:c,requests:u,tokens:x}=s,h=c.length;if(h===0)return e.jsx("div",{className:W("usage-chart-empty",n),style:{height:t},children:e.jsx("span",{children:"No data for this range"})});const m=600-ye.left-ye.right,d=t-ye.top-ye.bottom,p=Math.max(...u,1),f=Math.max(...x,1),b=Math.max(4,Math.min(24,Math.floor(m/h)-4)),k=(m-b*h)/(h+1);function w(T){return ye.left+k+T*(b+k)}function v(T){return T/p*d*.75}function C(T){return ye.top+d-T/f*d*.75}const z=x.map((T,F)=>`${w(F)+b/2},${C(T)}`).join(" "),y=[0,.25,.5,.75,1].map(T=>({y:ye.top+d-T*d*.75,label:T===0?"0":`${Math.round(p*T).toLocaleString()}`})),R=[0,.25,.5,.75,1].map(T=>({y:ye.top+d-T*d*.75,label:T===0?"0":`${Math.round(f*T/1e3)}k`})),S=Math.max(1,Math.floor(h/7)),N=c.map((T,F)=>({i:F,l:T,x:w(F)+b/2})).filter((T,F)=>F%S===0),P=r.useCallback(T=>{if(!i.current)return;const F=i.current.getBoundingClientRect(),A=(T.clientX-F.left)*(600/F.width),U=(T.clientY-F.top)*(t/F.height),Y=A-ye.left,B=Math.round((Y-k/2)/(b+k)),K=Math.max(0,Math.min(h-1,B));o({index:K,x:T.clientX-F.left,y:T.clientY-F.top}),a==null||a(K,A,U)},[h,b,k,a,t]),g=r.useCallback(()=>{o(null),a==null||a(null,0,0)},[a]),j=l;return e.jsxs("div",{ref:i,className:W("usage-chart",n),style:{position:"relative"},children:[e.jsxs("svg",{viewBox:`0 0 600 ${t}`,width:"100%",height:t,style:{display:"block",overflow:"visible"},onMouseMove:P,onMouseLeave:g,children:[y.map((T,F)=>e.jsx("line",{x1:ye.left,y1:T.y,x2:600-ye.right,y2:T.y,stroke:"var(--border)",strokeWidth:1,strokeDasharray:"4,3",opacity:.5},`grid-${F}`)),y.map((T,F)=>e.jsx("text",{x:ye.left-6,y:T.y+4,textAnchor:"end",fontSize:10,fill:"var(--text-muted)",fontFamily:"var(--font-mono, ui-monospace, monospace)",children:T.label},`ly-${F}`)),R.map((T,F)=>e.jsx("text",{x:600-ye.right+6,y:T.y+4,textAnchor:"start",fontSize:10,fill:"var(--text-muted)",fontFamily:"var(--font-mono, ui-monospace, monospace)",children:T.label},`ry-${F}`)),u.map((T,F)=>{const A=v(T),U=w(F),Y=ye.top+d-A;return e.jsx("rect",{x:U,y:Y,width:b,height:A,rx:2,fill:((j==null?void 0:j.index)===F,"var(--accent)"),opacity:(j==null?void 0:j.index)===F?1:.75,style:{transition:"opacity 120ms ease"}},`bar-${F}`)}),e.jsx("polyline",{points:z,fill:"none",stroke:"var(--warning, #d29922)",strokeWidth:2,strokeLinejoin:"round",strokeLinecap:"round",opacity:.9}),x.map((T,F)=>e.jsx("circle",{cx:w(F)+b/2,cy:C(T),r:(j==null?void 0:j.index)===F?5:3,fill:"var(--warning, #d29922)",opacity:(j==null?void 0:j.index)===F?1:.7,style:{transition:"r 120ms ease"}},`dot-${F}`)),N.map(({i:T,l:F,x:A})=>e.jsx("text",{x:A,y:ye.top+d+18,textAnchor:"middle",fontSize:10,fill:"var(--text-muted)",fontFamily:"var(--font-mono, ui-monospace, monospace)",children:F},`xl-${T}`)),e.jsx("line",{x1:ye.left,y1:ye.top+d,x2:600-ye.right,y2:ye.top+d,stroke:"var(--border)",strokeWidth:1})]}),j!==null&&e.jsxs("div",{className:"usage-chart-tooltip",style:{left:Math.min(j.x+12,460),top:j.y-60},children:[e.jsx("div",{className:"usage-tooltip-date",children:c[j.index]}),e.jsxs("div",{className:"usage-tooltip-row",children:[e.jsx("span",{className:"usage-tooltip-dot",style:{background:"var(--accent)"}}),e.jsx("span",{children:"Requests:"}),e.jsx("strong",{children:u[j.index].toLocaleString()})]}),e.jsxs("div",{className:"usage-tooltip-row",children:[e.jsx("span",{className:"usage-tooltip-dot",style:{background:"var(--warning, #d29922)"}}),e.jsx("span",{children:"Tokens:"}),e.jsx("strong",{children:x[j.index].toLocaleString()})]})]})]})}function us({label:s,col:t,sortKey:a,sortDir:n,onSort:i}){const l=a===t;return e.jsxs("th",{className:W("usage-sort-header",l&&"is-active"),onClick:()=>i(t),"aria-sort":l?n==="asc"?"ascending":"descending":"none",children:[e.jsx("span",{children:s}),e.jsx("span",{className:"usage-sort-icon",children:l?n==="asc"?" ↑":" ↓":" ↕"})]})}function po({rows:s,sortKey:t,sortDir:a,onSort:n}){return e.jsx("div",{className:"usage-table-wrap",children:e.jsxs("table",{className:"usage-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx(us,{label:"Model",col:"modelId",sortKey:t,sortDir:a,onSort:n}),e.jsx(us,{label:"Requests",col:"requests",sortKey:t,sortDir:a,onSort:n}),e.jsx(us,{label:"Prompt Tok",col:"promptTokens",sortKey:t,sortDir:a,onSort:n}),e.jsx(us,{label:"Compl Tok",col:"completionTokens",sortKey:t,sortDir:a,onSort:n}),e.jsx(us,{label:"Total Tok",col:"totalTokens",sortKey:t,sortDir:a,onSort:n}),e.jsx(us,{label:"Avg Latency",col:"avgLatencyMs",sortKey:t,sortDir:a,onSort:n}),e.jsx(us,{label:"Errors",col:"errors",sortKey:t,sortDir:a,onSort:n})]})}),e.jsx("tbody",{children:s.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:7,className:"usage-table-empty",children:"No data for this range"})}):s.map(i=>e.jsxs("tr",{children:[e.jsx("td",{className:"usage-table-model",children:e.jsx("code",{children:i.modelId})}),e.jsx("td",{className:"mono",children:i.requests.toLocaleString()}),e.jsx("td",{className:"mono",children:i.promptTokens.toLocaleString()}),e.jsx("td",{className:"mono",children:i.completionTokens.toLocaleString()}),e.jsx("td",{className:"mono",children:i.totalTokens.toLocaleString()}),e.jsxs("td",{className:"mono",children:[i.avgLatencyMs,"ms"]}),e.jsx("td",{className:W("mono",i.errors>0&&"is-err"),children:i.errors>0?i.errors:"—"})]},`${i.providerId}::${i.modelId}`))})]})})}function go({activeTab:s,setActiveTab:t}){const[a,n]=r.useState("quota"),i=ce();return e.jsxs("div",{className:"view-container view-minimax-usage",children:[e.jsxs("div",{className:"minimax-sub-tabs",children:[e.jsxs("button",{className:W("minimax-sub-tab",a==="quota"&&"is-active"),onClick:()=>n("quota"),children:[e.jsx(Yt,{size:13})," Token Plan"]}),e.jsxs("button",{className:W("minimax-sub-tab",a==="analytics"&&"is-active"),onClick:()=>n("analytics"),children:[e.jsx(Ya,{size:13})," Usage Analytics"]})]}),a==="quota"?e.jsx(fo,{activeTab:s,setActiveTab:t}):e.jsx(jo,{toast:i})]})}function fo({activeTab:s,setActiveTab:t}){var ne;const a=ce(),[n,i]=r.useState(null),[l,o]=r.useState(null),[c,u]=r.useState(null),[x,h]=r.useState(!0),[m,d]=r.useState(!1),[p,f]=r.useState(null),[b,k]=r.useState(null),[w,v]=r.useState(!1),[C,z]=r.useState(0),[y,R]=r.useState(!1),[S,N]=r.useState(null),[P,g]=r.useState(""),[j,T]=r.useState(!1),[F,A]=r.useState(!1),U=r.useCallback(async()=>{h(!0),f(null);try{const[I,V,ie]=await Promise.all([$.get("/minimax/status"),$.get("/minimax/remains"),$.get("/minimax/onboarding")]);i(I),o(V),u(ie),I.configured&&z(4)}catch(I){f(I.message||"Failed to load MiniMax data")}finally{h(!1)}},[]);r.useEffect(()=>{U()},[U]);const Y=r.useCallback(async()=>{try{await $.post("/minimax/onboarding",{dismissedAt:Date.now()}),u(I=>I&&{...I,dismissedAt:Date.now()})}catch{}},[]),B=r.useCallback(async()=>{if(!P.trim()){a.error("Paste a Subscription Key first.");return}R(!0),N(null);try{const I=await $.post("/minimax/test",{prompt:"Reply with a single word: pong",model:"MiniMax-M3",maxTokens:16});if(N(I),I.ok){z(3),a.success("Key works. Saving…");try{await $.post("/minimax/onboarding/save-key",{key:P.trim(),groupId:"default"}),D(),a.success("Subscription Key saved.")}catch(V){a.error(`Save failed: ${V.message}`)}U()}else a.error(`Verification failed: ${I.message??I.error??"unknown"}`)}catch(I){a.error(`Test request failed: ${I.message}`)}finally{R(!1)}},[P,a,U]),K=r.useCallback(async()=>{if(!P.trim()){a.error("Paste a Subscription Key first.");return}A(!0);try{const I=await $.post("/minimax/onboarding/save-key",{key:P.trim(),groupId:"default"});if(!I.ok){a.error(`Save failed: ${I.message??I.error??"unknown"}`);return}g(""),D(),a.success("Subscription Key saved. Loading quota…"),U()}catch(I){a.error(`Save failed: ${I.message}`)}finally{A(!1)}},[P,a,U]),D=r.useCallback(async()=>{try{await $.del("/minimax/cache")}catch{}},[]),_=r.useCallback(async()=>{d(!0),f(null);try{await $.post("/minimax/remains/refresh"),await U(),a.success("Refreshed")}catch(I){a.error(`Refresh failed: ${I.message}`)}finally{d(!1)}},[U,a]),ae=r.useCallback(async()=>{var I;v(!0),k(null);try{const V=await $.post("/minimax/test",{prompt:"Reply with a single word: pong",model:"MiniMax-M3",maxTokens:16});k(V),V.ok?a.success(`Test ok — used ${((I=V.usage)==null?void 0:I.total_tokens)??"?"} tokens`):a.error(`Test failed: ${V.message??V.error??"unknown"}`)}catch(V){a.error(`Test request failed: ${V.message}`)}finally{v(!1)}},[a]);return x&&!n?e.jsxs("div",{className:"view-container",children:[e.jsx(he,{})," Loading MiniMax data…"]}):n?!n.configured&&(c==null?void 0:c.dismissedAt)==null&&C<4?e.jsx(yo,{step:C,setStep:z,keyDraft:P,setKeyDraft:g,showKey:j,setShowKey:T,verifying:y,verifyResult:S,onVerify:B,onSkip:async()=>{await Y(),a.success("Skipped.")},onManualKeySave:K,savingKey:F,status:n}):e.jsxs(e.Fragment,{children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-titles",children:[e.jsxs("h1",{className:"view-title",children:[e.jsx(Yt,{size:20,style:{verticalAlign:"text-bottom",marginRight:6}}),"MiniMax Token Plan"]}),e.jsxs("p",{className:"view-subtitle",children:["Remaining 5-hour + weekly quota per model. Fetches live from"," ",e.jsx("code",{children:"www.minimax.io/v1/token_plan/remains"}),"."]})]}),e.jsxs("div",{className:"view-header-actions",children:[e.jsxs(M,{variant:"secondary",size:"sm",onClick:()=>t("settings"),title:"Configure your Subscription Key",children:[e.jsx(sa,{size:14})," ",n.configured?`Key ${n.apiKeyHint}`:"Add key"]}),e.jsxs(M,{variant:"secondary",size:"sm",onClick:_,disabled:m,children:[m?e.jsx(ge,{size:14,className:"spin"}):e.jsx(me,{size:14})," Refresh"]})]})]}),l&&!l.ok&&e.jsxs("div",{className:"banner banner-err",children:[e.jsx(Me,{size:16}),e.jsxs("span",{children:[e.jsx("strong",{children:"Couldn't load quota"}),": ",l.message??l.error??"unknown error"]})]}),(l==null?void 0:l.ok)&&l.models&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"minimax-stats-row",children:[e.jsx(lt,{label:"Models tracked",value:String(l.models.length),hint:"Distinct model quotas returned by the API"}),e.jsx(lt,{label:"Last fetched",value:l.fetchedAt?bo(l.fetchedAt):"—",hint:"Refreshed on demand + every 60s"}),e.jsx(lt,{label:"Group",value:l.groupId??"—",hint:"Usually 'default' for an individual team"}),e.jsx(lt,{label:"API key",value:l.apiKeyHint??"—",hint:"Masked; the real key never leaves auth.json"})]}),e.jsx("div",{className:"minimax-models-grid",children:l.models.map(I=>e.jsx(vo,{model:I},I.model_name))})]}),n.configured&&e.jsxs(G,{id:"minimax-test",children:[e.jsxs(ee,{children:[e.jsx(rs,{size:14})," Test the API key"]}),e.jsxs(te,{children:["One-shot chat completion to ",e.jsxs("code",{children:[n.chatBaseUrl,"/chat/completions"]}),"."]}),e.jsxs("div",{className:"minimax-test-actions",children:[e.jsxs(M,{onClick:ae,disabled:w,variant:"primary",size:"sm",children:[w?e.jsx(ge,{size:14,className:"spin"}):e.jsx(rs,{size:14})," Send test prompt"]}),e.jsx("code",{className:"minimax-test-prompt",children:'"Reply with a single word: pong"'})]}),b&&e.jsxs("div",{className:W("minimax-test-result",b.ok?"ok":"err"),children:[b.ok?e.jsx(_e,{size:14}):e.jsx(Me,{size:14}),e.jsx("div",{className:"minimax-test-body",children:b.ok?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"minimax-test-line",children:[e.jsx("strong",{children:"model:"})," ",e.jsx("code",{children:b.model})," ·"," ",e.jsx("strong",{children:"finish:"})," ",b.finishReason??"—"]}),b.content&&e.jsx("div",{className:"minimax-test-content",children:e.jsx("code",{children:b.content})}),b.usage&&e.jsxs("div",{className:"minimax-test-usage",children:[e.jsx("strong",{children:"usage:"})," total ",e.jsx("code",{children:b.usage.total_tokens??"?"})," · prompt"," ",e.jsx("code",{children:b.usage.prompt_tokens??"?"})," · completion"," ",e.jsx("code",{children:b.usage.completion_tokens??"?"}),((ne=b.usage.prompt_tokens_details)==null?void 0:ne.cached_tokens)!=null&&e.jsxs(e.Fragment,{children:[" · cached ",e.jsx("code",{children:b.usage.prompt_tokens_details.cached_tokens})]})]})]}):e.jsx("pre",{children:b.message??b.error??"unknown error"})})]})]})]}):e.jsx("div",{className:"view-container",children:e.jsxs("div",{className:"error-card",children:[e.jsx(Me,{size:20}),e.jsxs("div",{children:[e.jsx("strong",{children:"Couldn't load MiniMax status"}),e.jsx("pre",{children:p??"unknown error"})]})]})})}function jo({toast:s}){const[t,a]=r.useState("24h"),[n,i]=r.useState(""),[l,o]=r.useState(""),[c,u]=r.useState(!0),[x,h]=r.useState(null),[m,d]=r.useState([]),[p,f]=r.useState("requests"),[b,k]=r.useState("desc"),[w,v]=r.useState(!1),C=r.useCallback(async(j,T,F)=>{u(!0);try{const A=new URLSearchParams({range:j});j==="custom"&&T&&F&&(A.set("from",String(T)),A.set("to",String(F)));const[U,Y]=await Promise.all([$.get(`/usage?${A.toString()}`),$.get("/usage/recent?limit=20")]);h(U),d(Y.records)}catch(A){s.error(`Failed to load usage data: ${A.message}`)}finally{u(!1)}},[s]);r.useEffect(()=>{if(t==="custom"){const j=n?new Date(n).getTime():Date.now()-6048e5,T=l?new Date(l).getTime():Date.now();C("custom",j,T)}else C(t)},[t,C]);const z=r.useCallback(j=>{p===j?k(T=>T==="asc"?"desc":"asc"):(f(j),k("desc"))},[p]),y=r.useMemo(()=>x!=null&&x.perModel?[...x.perModel].sort((j,T)=>{const F=j[p]??0,A=T[p]??0,U=typeof F=="number"&&typeof A=="number"?F-A:String(F).localeCompare(String(A));return b==="asc"?U:-U}):[],[x==null?void 0:x.perModel,p,b]),R=r.useMemo(()=>x!=null&&x.daily?{labels:x.daily.map(j=>j.date.slice(5)),requests:x.daily.map(j=>j.requests),tokens:x.daily.map(j=>j.totalTokens)}:{labels:[],requests:[],tokens:[]},[x==null?void 0:x.daily]),S=r.useCallback(async()=>{v(!0),await C(t==="custom"?"custom":t,t==="custom"&&n?new Date(n).getTime():void 0,t==="custom"&&l?new Date(l).getTime():void 0),v(!1)},[C,t,n,l]);if(c&&!x)return e.jsxs("div",{className:"view-container",children:[e.jsx(he,{})," Loading usage data…"]});const N=x==null?void 0:x.totals,P=(x==null?void 0:x.errors)??[],g=(x==null?void 0:x.perKey)??[];return e.jsxs(e.Fragment,{children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-titles",children:[e.jsxs("h1",{className:"view-title",children:[e.jsx(Ya,{size:20,style:{verticalAlign:"text-bottom",marginRight:6}}),"Usage Analytics"]}),e.jsxs("p",{className:"view-subtitle",children:["Aggregated from ",e.jsx("code",{children:"~/.local/share/bizar/usage.jsonl"})," — every chatCompletion and fetchRemains call."]})]}),e.jsx("div",{className:"view-header-actions",children:e.jsxs(M,{variant:"secondary",size:"sm",onClick:S,disabled:w,children:[w?e.jsx(ge,{size:14,className:"spin"}):e.jsx(me,{size:14})," Refresh"]})})]}),e.jsxs("div",{className:"usage-time-range",children:[["24h","7d","30d","custom"].map(j=>e.jsx("button",{className:W("usage-range-chip",t===j&&"is-active"),onClick:()=>a(j),children:j==="custom"?"Custom":j.toUpperCase()},j)),t==="custom"&&e.jsxs("div",{className:"usage-custom-dates",children:[e.jsx("label",{htmlFor:"usage-from-date",className:"sr-only",children:"From date"}),e.jsx("input",{id:"usage-from-date",type:"date",className:"usage-date-input",value:n,onChange:j=>i(j.target.value),"aria-label":"From date"}),e.jsx("span",{style:{color:"var(--text-muted)",fontSize:12},"aria-hidden":!0,children:"to"}),e.jsx("label",{htmlFor:"usage-to-date",className:"sr-only",children:"To date"}),e.jsx("input",{id:"usage-to-date",type:"date",className:"usage-date-input",value:l,onChange:j=>o(j.target.value),"aria-label":"To date"})]})]}),e.jsxs("div",{className:"usage-kpi-row",children:[e.jsx(Ws,{label:"Total Requests",value:(N==null?void 0:N.requests.toLocaleString())??"—",sub:N?`${N.errors} errors`:void 0,tone:N&&N.errors>N.requests*.1?"warn":void 0}),e.jsx(Ws,{label:"Total Tokens",value:N?N.totalTokens>=1e3?`${Math.round(N.totalTokens/1e3)}k`:String(N.totalTokens):"—",sub:N?`${N.promptTokens.toLocaleString()} prompt · ${N.completionTokens.toLocaleString()} completion`:void 0}),e.jsx(Ws,{label:"Errors",value:String((N==null?void 0:N.errors)??"—"),sub:P.length>0?`${P[0].code}: ${P[0].count}`:void 0,tone:N&&N.errors>0?"err":void 0}),e.jsx(Ws,{label:"Avg Latency",value:(N==null?void 0:N.avgLatencyMs)!=null?`${N.avgLatencyMs}ms`:"—",sub:(N==null?void 0:N.p95LatencyMs)!=null?`p95 ${N.p95LatencyMs}ms`:void 0}),e.jsx(Ws,{label:"Est. Cost",value:(N==null?void 0:N.costEstimate)!=null&&N.costEstimate>0?`$${N.costEstimate.toFixed(4)}`:"—",sub:"approximate USD",tone:void 0})]}),e.jsxs(G,{className:"usage-chart-card",children:[e.jsx("div",{className:"usage-chart-wrap",children:e.jsx(xo,{series:R,height:280})}),e.jsxs("div",{className:"usage-legend",children:[e.jsxs("div",{className:"usage-legend-item",children:[e.jsx("div",{className:"usage-legend-bar",style:{background:"var(--accent)"}}),e.jsx("span",{children:"Requests (bar)"})]}),e.jsxs("div",{className:"usage-legend-item",children:[e.jsx("div",{className:"usage-legend-line",style:{background:"var(--warning, #d29922)"}}),e.jsx("span",{children:"Tokens (line)"})]})]})]}),e.jsxs(G,{children:[e.jsx(ee,{children:"Per-model breakdown"}),e.jsx(po,{rows:y,sortKey:p,sortDir:b,onSort:z})]}),g.length>0&&e.jsxs(G,{children:[e.jsx(ee,{children:"API Keys"}),e.jsx("div",{className:"usage-key-row",children:g.map(j=>e.jsxs("span",{className:W("usage-key-badge",j.isBackup?"is-backup":"is-active"),children:[e.jsx("span",{className:"usage-key-dot"}),j.keyEnvVar,j.isBackup?" (backup)":" (active)"," · ",j.requests," req"]},j.keyEnvVar))})]}),m.length>0&&e.jsxs(G,{children:[e.jsx(ee,{children:"Recent activity"}),e.jsx("div",{className:"usage-recent-list",children:m.map((j,T)=>e.jsxs("div",{className:W("usage-recent-item",j.error&&"is-err"),children:[e.jsx("span",{className:"usage-recent-time",children:new Date(j.ts).toLocaleTimeString()}),e.jsx("span",{className:"usage-recent-model",children:e.jsx("code",{children:j.modelId})}),e.jsxs("span",{className:"usage-recent-tokens",children:[j.totalTokens.toLocaleString()," tok"]}),e.jsxs("span",{className:"usage-recent-latency",children:[j.latencyMs,"ms"]}),e.jsx("span",{className:"usage-recent-endpoint",children:j.endpoint})]},`${j.requestId}-${T}`))})]})]})}function Ws({label:s,value:t,sub:a,tone:n}){return e.jsxs("div",{className:"usage-kpi-card",children:[e.jsx("div",{className:"usage-kpi-label",children:s}),e.jsx("div",{className:W("usage-kpi-value",n&&`is-${n}`),children:t}),a&&e.jsx("div",{className:"usage-kpi-sub",children:a})]})}function lt({label:s,value:t,hint:a}){return e.jsxs("div",{className:"stat",children:[e.jsx("div",{className:"stat-label",children:s}),e.jsx("div",{className:"stat-value",children:t}),a&&e.jsx("div",{className:"stat-hint",children:a})]})}function vo({model:s}){const t=ct(s.current_interval_remaining_percent??0,0,100),a=ct(s.current_weekly_remaining_percent??0,0,100),n=ct(100-t,0,100),i=ct(100-a,0,100);return e.jsxs(G,{id:`minimax-model-${s.model_name}`,className:"minimax-model-card",children:[e.jsxs("div",{className:"minimax-model-head",children:[e.jsx("div",{className:"minimax-model-name",children:s.model_name}),e.jsxs("div",{className:W("minimax-model-status",t<25||a<25?"is-warn":"is-ok"),children:[s.current_interval_status===1?"active":"idle"," ·"," ",s.current_weekly_status===1?"week active":"week idle"]})]}),e.jsxs("div",{className:"minimax-quota-rows",children:[e.jsx(Aa,{icon:e.jsx(Ae,{size:12}),label:"5-hour rolling",remainingPct:t,consumedPct:n,used:s.current_interval_usage_count??0,total:s.current_interval_total_count??0,resetIn:s.intervalResetInHuman,resetISO:s.endTimeISO}),e.jsx(Aa,{icon:e.jsx(ji,{size:12}),label:"Weekly",remainingPct:a,consumedPct:i,used:s.current_weekly_usage_count??0,total:s.current_weekly_total_count??0,resetIn:s.weeklyResetInHuman,resetISO:s.weeklyEndTimeISO})]})]})}function Aa({icon:s,label:t,remainingPct:a,consumedPct:n,used:i,total:l,resetIn:o,resetISO:c}){const u=a>=75?"good":a>=25?"warn":"low";return e.jsxs("div",{className:`minimax-quota-row is-${u}`,children:[e.jsxs("div",{className:"minimax-quota-head",children:[e.jsxs("span",{className:"minimax-quota-label",children:[s," ",t]}),e.jsxs("span",{className:"minimax-quota-remaining",children:[a,"% remaining"]}),e.jsxs("span",{className:"minimax-quota-consumed",children:["· ",n,"% used"]})]}),e.jsx("div",{className:"minimax-bar",children:e.jsx("div",{className:"minimax-bar-fill",style:{width:`${n}%`},"aria-label":`${n}% consumed`})}),e.jsxs("div",{className:"minimax-quota-meta",children:[e.jsxs("span",{children:[e.jsx("strong",{children:i})," / ",l||"—"," requests"]}),e.jsx("span",{title:c,children:o?`resets in ${o}`:"—"})]})]})}function ct(s,t,a){return Math.max(t,Math.min(a,s))}function bo(s){const t=Date.now()-s;return t<5e3?"just now":t<6e4?`${Math.floor(t/1e3)}s ago`:t<36e5?`${Math.floor(t/6e4)}m ago`:`${Math.floor(t/36e5)}h ago`}function yo({step:s,setStep:t,keyDraft:a,setKeyDraft:n,showKey:i,setShowKey:l,verifying:o,verifyResult:c,onVerify:u,onSkip:x,onManualKeySave:h,savingKey:m,status:d}){return e.jsxs("div",{className:"view-container view-minimax-onboarding",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-titles",children:[e.jsxs("h1",{className:"view-title",children:[e.jsx(es,{size:20,style:{verticalAlign:"text-bottom",marginRight:6}}),"Set up MiniMax Token Plan tracking"]}),e.jsx("p",{className:"view-subtitle",children:"We'll read your Subscription Key and show your remaining quota."})]}),e.jsx("div",{className:"view-header-actions",children:e.jsxs(M,{variant:"ghost",size:"sm",onClick:x,children:[e.jsx(we,{size:14})," Skip for now"]})})]}),e.jsx("div",{className:"minimax-wizard-stepper",children:["Welcome","Get a key","Paste & test","Done"].map((p,f)=>e.jsxs("div",{className:W("minimax-wizard-step",f===s&&"is-current",f<s&&"is-done",f>s&&"is-todo"),children:[e.jsx("div",{className:"minimax-wizard-step-bullet",children:f<s?e.jsx(_e,{size:14}):f+1}),e.jsx("div",{className:"minimax-wizard-step-label",children:p})]},p))}),e.jsxs(G,{id:"minimax-wizard-card",children:[s===0&&e.jsxs("div",{className:"minimax-wizard-body",children:[e.jsx("h3",{className:"minimax-wizard-title",children:"Welcome"}),e.jsxs("p",{className:"minimax-wizard-prose",children:["BizarHarness shows you how much of your MiniMax Token Plan quota you have left — both the ",e.jsx("strong",{children:"5-hour rolling"})," and ",e.jsx("strong",{children:"weekly"})," windows."]}),e.jsxs("ul",{className:"minimax-wizard-list",children:[e.jsxs("li",{children:["Stored in ",e.jsx("code",{children:"~/.local/share/cline/auth.json"}),"."]}),e.jsx("li",{children:"Read fresh on every dashboard load."}),e.jsx("li",{children:"Never logged in full."})]}),e.jsx("div",{className:"minimax-wizard-actions",children:e.jsxs(M,{onClick:()=>t(1),variant:"primary",size:"md",children:["Get started ",e.jsx("span",{style:{marginLeft:6},children:"→"})]})})]}),s===1&&e.jsxs("div",{className:"minimax-wizard-body",children:[e.jsx("h3",{className:"minimax-wizard-title",children:"Get your Subscription Key"}),e.jsx("p",{className:"minimax-wizard-prose",children:"Go to the MiniMax console and copy your Subscription Key."}),e.jsxs("ol",{className:"minimax-wizard-list",children:[e.jsxs("li",{children:["Open ",e.jsxs("a",{href:"https://platform.minimax.io/user-center/payment/token-plan",target:"_blank",rel:"noreferrer",className:"minimax-wizard-link",children:[e.jsx(Ls,{size:12})," platform.minimax.io"]})]}),e.jsxs("li",{children:["Click ",e.jsx("strong",{children:"Copy Subscription Key"}),"."]}),e.jsx("li",{children:"Come back here and paste it."})]}),e.jsxs("div",{className:"minimax-wizard-actions",children:[e.jsx(M,{variant:"secondary",size:"md",onClick:()=>t(0),children:"← Back"}),e.jsxs(M,{variant:"primary",size:"md",onClick:()=>t(2),children:["I have my key ",e.jsx("span",{style:{marginLeft:6},children:"→"})]})]})]}),s===2&&e.jsxs("div",{className:"minimax-wizard-body",children:[e.jsx("h3",{className:"minimax-wizard-title",children:"Paste & test"}),e.jsx("p",{className:"minimax-wizard-prose",children:"Paste your key below. We'll test it against the real API before saving."}),e.jsx("div",{className:"minimax-key-row",children:e.jsxs("div",{className:"minimax-key-input-wrap",children:[e.jsx(sa,{size:12,className:"minimax-key-icon","aria-hidden":!0}),e.jsx("label",{htmlFor:"minimax-key-input",className:"sr-only",children:"Subscription Key"}),e.jsx("input",{id:"minimax-key-input",type:i?"text":"password",value:a,onChange:p=>n(p.target.value),placeholder:"sk-cp-...",spellCheck:!1,autoComplete:"off",className:"minimax-key-input",autoFocus:!0,"aria-label":"Subscription Key"}),e.jsx("button",{type:"button",onClick:()=>l(p=>!p),className:"minimax-key-toggle","aria-label":i?"Hide key":"Show key",children:i?e.jsx(Ot,{size:13}):e.jsx(As,{size:13})})]})}),c&&!c.ok&&e.jsxs("div",{className:"minimax-wizard-error",children:[e.jsx(Me,{size:14}),e.jsxs("span",{children:[e.jsx("strong",{children:"Verification failed:"})," ",c.message??c.error]})]}),e.jsxs("div",{className:"minimax-wizard-actions",children:[e.jsx(M,{variant:"secondary",size:"md",onClick:()=>t(1),children:"← Back"}),e.jsxs(M,{variant:"primary",size:"md",onClick:u,disabled:o||!a.trim(),children:[o?e.jsx(ge,{size:14,className:"spin"}):e.jsx(Ys,{size:14}),o?"Testing…":"Test & save key"]})]}),e.jsxs("p",{className:"minimax-wizard-prose minimax-wizard-prose--muted",children:["Don't want to test first? ",e.jsx("a",{href:"#",onClick:p=>{p.preventDefault(),h()},className:"minimax-wizard-link",children:"Save without testing"})]})]}),s===3&&e.jsxs("div",{className:"minimax-wizard-body",children:[e.jsxs("h3",{className:"minimax-wizard-title",children:[e.jsx(_e,{size:18,style:{verticalAlign:"text-bottom",marginRight:6}}),"All set"]}),e.jsx("p",{className:"minimax-wizard-prose",children:"The key works and is saved. Reloading so you can see your live quota."}),e.jsx("div",{className:"minimax-wizard-actions",children:e.jsx(M,{variant:"primary",size:"md",onClick:()=>window.location.reload(),children:"View your quota →"})})]}),e.jsxs("div",{className:"minimax-wizard-footer",children:[e.jsx(Ys,{size:11}),e.jsxs("span",{children:["Key written to ",e.jsx("code",{children:"~/.local/share/cline/auth.json"})," with mode 0600."]})]})]})]})}const No=Ke.memo(go),ko={pending:"info",running:"accent",done:"success",failed:"error",killed:"neutral",timed_out:"warning"},wo={pending:"Pending",running:"Running",done:"Done",failed:"Failed",killed:"Killed",timed_out:"Timed out"};function So({status:s,dot:t}){const a=ko[s]||"neutral",n=wo[s]||s;return e.jsx(yt,{kind:a,dot:t,children:n})}function Co({instanceId:s,instanceName:t,onConfirm:a,onClose:n}){return e.jsxs("div",{children:[e.jsxs("p",{style:{marginBottom:16,lineHeight:1.6},children:["Instance ",e.jsx("code",{children:s}),t?e.jsxs(e.Fragment,{children:[" (",t,")"]}):null," will be terminated. This cannot be undone."]}),e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx(M,{variant:"ghost",onClick:n,children:"Cancel"}),e.jsx(M,{variant:"danger",onClick:async()=>{await a(),n()},children:"Kill"})]})]})}function zo(s,t,a,n,i){s.open({title:"Kill instance?",width:400,children:e.jsx(Co,{instanceId:a,instanceName:n,onConfirm:async()=>{try{const o=await(await fetch(`/api/background/${encodeURIComponent(a)}`,{method:"DELETE"})).json();o.ok?(t.success(`Instance ${a} killed.`),i==null||i()):t.error(`Kill failed: ${o.error||"unknown error"}`)}catch(l){t.error(`Kill failed: ${l.message}`)}},onClose:()=>s.close()})})}function $o({instance:s}){const t=ce(),[a,n]=r.useState(!1),i=s.tmuxSession,l=i?`tmux attach -t ${i}`:null,o=async()=>{if(l)try{await navigator.clipboard.writeText(l),t.success("Attach command copied")}catch{t.error("Could not copy to clipboard")}},c=async()=>{if(!(!s.instanceId||!i)){n(!0);try{const u=await $.post(`/background/${encodeURIComponent(s.instanceId)}/open-terminal`,{emulator:"system"});if(u.ok)t.success("Opening terminal…");else if(t.error(u.error||"Failed to open terminal"),l)try{await navigator.clipboard.writeText(l),t.success("Command copied to clipboard")}catch{}}catch(u){if(t.error(`Failed: ${u.message}`),l)try{await navigator.clipboard.writeText(l),t.success("Command copied to clipboard")}catch{}}finally{n(!1)}}};return i?e.jsxs(G,{variant:"outlined",className:"bg-tmux-card",children:[e.jsxs("div",{className:"bg-tmux-card-header",children:[e.jsx(Ts,{size:14}),e.jsx("span",{children:"tmux session"}),s.tmuxActive!==!1?e.jsx("span",{className:"badge badge-success",children:"live"}):e.jsx("span",{className:"badge badge-warning",children:"inactive"})]}),e.jsx("code",{className:"mono bg-tmux-session-name",children:i}),e.jsx("p",{className:"muted bg-tmux-hint",children:"Attach to the agent's tmux session from a terminal on the host running the dashboard."}),e.jsxs("div",{className:"bg-tmux-card-actions",children:[e.jsxs(M,{variant:"ghost",size:"sm",onClick:o,title:"Copy attach command",children:[e.jsx(os,{size:14})," Copy"]}),e.jsxs(M,{variant:"primary",size:"sm",onClick:c,loading:a,title:"Open in system terminal",children:[e.jsx(Ts,{size:14})," Open terminal"]})]})]}):e.jsxs(G,{variant:"outlined",className:"bg-tmux-card bg-tmux-card-warn",children:[e.jsxs("div",{className:"bg-tmux-card-header",children:[e.jsx(Me,{size:14}),e.jsx("span",{children:"No tmux session"})]}),e.jsx("p",{className:"bg-tmux-hint muted",children:"This instance does not have a tmux session attached. Sessions are created automatically when a background agent starts."})]})}const Ro=[{name:"mimir",description:"Deep research & codebase exploration"},{name:"frigg",description:"Read-only codebase Q&A"},{name:"thor",description:"Moderate-complexity implementation"},{name:"tyr",description:"Complex feature implementation"},{name:"heimdall",description:"Quick edits & simple tasks"},{name:"odin",description:"Primary router agent"}],To=[{label:"1 min",value:6e4},{label:"5 min",value:3e5},{label:"15 min",value:9e5},{label:"30 min",value:18e5},{label:"1 hr",value:36e5},{label:"4 hr",value:144e5}];function Ao({open:s,onClose:t,onCreated:a,agents:n=Ro}){var R;const i=ce(),[l,o]=r.useState(((R=n[0])==null?void 0:R.name)||"mimir"),[c,u]=r.useState(""),[x,h]=r.useState(""),[m,d]=r.useState(3e5),[p,f]=r.useState(!1),[b,k]=r.useState(""),[w,v]=r.useState(!1),[C,z]=r.useState(null);if(!s)return null;const y=async S=>{if(S.preventDefault(),z(null),!c.trim()){z("Prompt is required.");return}v(!0);try{const N=b.split(",").map(j=>j.trim()).filter(j=>j.length>0),P={agent:l,prompt:c,...x.trim()?{model:x.trim()}:{},timeoutMs:m,persistent:p,maxRestarts:3,...N.length>0?{tags:N}:{}},g=await $.post("/background",P);if(g!=null&&g.error)throw new Error(g.message||g.error);i.success(`Spawned ${l} (${g.instanceId.slice(0,14)}…)`),a==null||a(g.instanceId),u(""),h(""),f(!1),k(""),t()}catch(N){z((N==null?void 0:N.message)||"Failed to spawn.")}finally{v(!1)}};return e.jsx("div",{className:"modal-backdrop",role:"dialog","aria-modal":"true",children:e.jsxs("div",{className:"modal-card spawn-modal",children:[e.jsxs("div",{className:"spawn-modal-header",children:[e.jsxs("h3",{children:[e.jsx(Ee,{size:18})," Spawn background agent"]}),e.jsx(M,{variant:"ghost",size:"sm",onClick:t,title:"Close",children:e.jsx(we,{size:14})})]}),e.jsxs("form",{onSubmit:y,className:"spawn-modal-body",children:[e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:"Agent"}),e.jsx("select",{className:"field-input",value:l,onChange:S=>o(S.target.value),required:!0,children:n.map(S=>e.jsxs("option",{value:S.name,children:[S.name,S.description?` — ${S.description}`:""]},S.name))})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:"Initial prompt"}),e.jsx("textarea",{className:"field-input spawn-modal-textarea",rows:5,value:c,onChange:S=>u(S.target.value),placeholder:"What do you want this agent to do?",required:!0})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:"Model (optional)"}),e.jsx("input",{type:"text",className:"field-input",value:x,onChange:S=>h(S.target.value),placeholder:"providerID/modelID (leave blank for agent default)"})]}),e.jsxs("div",{className:"field",children:[e.jsx("span",{className:"field-label",children:"Timeout"}),e.jsx("div",{className:"spawn-modal-timeouts",children:To.map(S=>e.jsx("button",{type:"button",className:"spawn-modal-timeout-pill"+(S.value===m?" spawn-modal-timeout-pill-active":""),onClick:()=>d(S.value),children:S.label},S.value))}),e.jsx("input",{type:"range",min:6e4,max:144e5,step:6e4,value:m,onChange:S=>d(Number(S.target.value)),className:"spawn-modal-slider"}),e.jsxs("span",{className:"muted",children:[(m/6e4).toFixed(0)," min"]})]}),e.jsxs("label",{className:"field-checkbox",children:[e.jsx("input",{type:"checkbox",checked:p,onChange:S=>f(S.target.checked)}),e.jsx("span",{children:"Persistent — auto-restart on terminal failure (max 3 attempts)"})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:"Tags (optional, comma-separated)"}),e.jsx("input",{type:"text",className:"field-input",value:b,onChange:S=>k(S.target.value),placeholder:"e.g. refactor, urgent"})]}),C&&e.jsx("div",{className:"spawn-modal-error",children:C}),e.jsxs("div",{className:"spawn-modal-actions",children:[e.jsx(M,{variant:"ghost",size:"sm",type:"button",onClick:t,children:"Cancel"}),e.jsx(M,{variant:"primary",size:"sm",type:"submit",disabled:w,children:w?"Spawning…":"Spawn agent"})]})]})]})})}const Mo=5e3,Ma=3e3,Io=120,Eo=32e3;function Lo(s){return s.status==="pending"||s.status==="running"||s.status==="paused"}function Gt(s){return s.status==="paused"}function Do(s){if(!Number.isFinite(s)||s<0)return"—";const t=Math.floor(s/1e3),a=Math.floor(t/3600),n=Math.floor(t%3600/60),i=t%60;return a>0?`${a}h ${n}m ${i}s`:n>0?`${n}m ${i}s`:`${i}s`}function _o(s){const t=ce(),a=Pe(),[n,i]=r.useState([]),[l,o]=r.useState(!0),[c,u]=r.useState(null),[,x]=r.useState(0),[h,m]=r.useState(!1),d=r.useCallback(async()=>{try{const z=await $.get("/background");i(Array.isArray(z==null?void 0:z.instances)?z.instances:[]),u(null)}catch(z){u((z==null?void 0:z.message)||"Failed to load background agents.")}finally{o(!1)}},[]);r.useEffect(()=>{d();const z=setInterval(d,Mo);return()=>clearInterval(z)},[d]),r.useEffect(()=>{const z=setInterval(()=>x(y=>(y+1)%1e6),1e3);return()=>clearInterval(z)},[]),r.useEffect(()=>{const z=new xs,y=z.on(R=>{const S=R.type;(S==="background:change"||S==="background:cleanup"||S==="bg:progress"||S==="bg:tool-call")&&d()});return()=>{y(),z.close()}},[d]);const p=n.filter(Lo),f=z=>{Fo(a,z)},b=async z=>{try{const y=await $.get(`/background/${encodeURIComponent(z.instanceId)}/tmux`);Uo(a,y)}catch(y){t.error(`Tmux info failed: ${y.message}`)}},k=z=>{zo(a,t,z.instanceId,z.agent||z.prompt,()=>{i(y=>y.filter(R=>R.instanceId!==z.instanceId))})},w=async z=>{try{const y=await $.post(`/background/${encodeURIComponent(z.instanceId)}/pause`,{});y!=null&&y.ok?t.info(`Paused ${z.instanceId.slice(0,14)}…`):t.error((y==null?void 0:y.error)||"Pause failed.")}catch(y){t.error(`Pause failed: ${y.message}`)}},v=async z=>{try{const y=await $.post(`/background/${encodeURIComponent(z.instanceId)}/resume`,{});y!=null&&y.ok?t.info(`Resumed ${z.instanceId.slice(0,14)}…`):t.error((y==null?void 0:y.error)||"Resume failed.")}catch(y){t.error(`Resume failed: ${y.message}`)}},C=z=>{Vo(a,t,z,d)};return l?e.jsx("div",{className:"bg-active-view",children:e.jsxs("div",{className:"bg-active-loading",children:[e.jsx(he,{size:"md"}),e.jsx("span",{children:"Loading background agents…"})]})}):c?e.jsx("div",{className:"bg-active-view",children:e.jsx(Ne,{icon:e.jsx(Ae,{size:32}),title:"Couldn't load background agents",message:c,action:e.jsxs(M,{variant:"primary",onClick:d,children:[e.jsx(me,{size:14})," Retry"]})})}):e.jsxs("div",{className:"bg-active-view",children:[e.jsxs("div",{className:"bg-active-header",children:[e.jsxs("div",{className:"bg-active-header-text",children:[e.jsx("h2",{className:"bg-active-title",children:"Active Background Agents"}),e.jsxs("p",{className:"bg-active-subtitle muted",children:[p.length," active · ",n.length," total in store"]})]}),e.jsxs("div",{className:"bg-active-header-actions",children:[e.jsxs(M,{variant:"primary",size:"sm",onClick:()=>m(!0),children:[e.jsx(Ee,{size:14})," Spawn"]}),e.jsxs(M,{variant:"ghost",size:"sm",onClick:d,title:"Refresh now",children:[e.jsx(me,{size:14})," Refresh"]})]})]}),e.jsx(Ao,{open:h,onClose:()=>m(!1),onCreated:()=>{d()}}),p.length===0?e.jsx(Ne,{icon:e.jsx(Ae,{size:32}),title:"No active background agents",message:"Use the Spawn button above or call bizar_spawn_background from an agent.",action:e.jsxs(M,{variant:"primary",onClick:()=>m(!0),children:[e.jsx(Ee,{size:14})," Spawn your first agent"]})}):e.jsx("div",{className:"bg-active-list",children:p.map(z=>e.jsx(Po,{inst:z,onViewOutput:()=>f(z),onOpenTmux:()=>b(z),onKill:()=>k(z),onPause:Gt(z)?void 0:()=>w(z),onResume:Gt(z)?()=>v(z):void 0,onSteer:()=>C(z)},z.instanceId))})]})}function Po({inst:s,onViewOutput:t,onOpenTmux:a,onKill:n,onPause:i,onResume:l,onSteer:o}){const c=typeof s.startedAt=="number"?s.startedAt:0,u=c?as(c):"—",x=c?Date.now()-c:0,h=Ea(s.prompt,Io),m=typeof s.progress=="number"?s.progress:null;return e.jsxs(G,{className:"bg-active-card",variant:"elevated",children:[e.jsxs("div",{className:"bg-active-card-top",children:[e.jsxs("div",{className:"bg-active-card-id",children:[e.jsx("code",{className:"mono",children:s.instanceId}),e.jsx(So,{status:s.status||"pending",dot:!0}),Gt(s)&&e.jsxs("span",{className:"bg-active-card-paused-tag",children:[e.jsx(vi,{size:12})," paused"]})]}),e.jsxs("div",{className:"bg-active-card-agent",children:[e.jsx("span",{className:"bg-active-card-agent-label",children:"Agent"}),e.jsx("span",{className:"bg-active-card-agent-name",children:s.agent||"unknown"})]})]}),h&&e.jsx("div",{className:"bg-active-prompt",children:h}),s.currentStep&&e.jsxs("div",{className:"bg-active-step",children:[e.jsx("span",{className:"bg-active-step-label",children:"Step:"}),e.jsx("span",{className:"bg-active-step-value",children:s.currentStep})]}),m!==null&&e.jsxs("div",{className:"progress-bar","aria-label":"Progress",children:[e.jsx("div",{className:"progress-fill",style:{width:`${m<0?100:Math.max(0,Math.min(100,m))}%`}}),e.jsxs("span",{className:"progress-label",children:[m<0?"…":`${Math.round(m)}%`,s.progressMessage?` · ${s.progressMessage}`:""]})]}),e.jsxs("div",{className:"bg-active-meta",children:[e.jsxs("span",{title:u,children:[e.jsx("strong",{children:"Started:"})," ",u]}),e.jsxs("span",{children:[e.jsx("strong",{children:"Duration:"})," ",Do(x)]}),e.jsxs("span",{children:[e.jsx("strong",{children:"Tool calls:"})," ",s.toolCallCount??0]}),s.processId&&e.jsxs("span",{children:[e.jsx("strong",{children:"PID:"})," ",e.jsx("code",{className:"mono",children:s.processId})]}),Array.isArray(s.tags)&&s.tags.length>0&&e.jsxs("span",{children:[e.jsx("strong",{children:"Tags:"})," ",s.tags.map((d,p)=>e.jsxs("span",{className:"tag-pill",children:[d,p<s.tags.length-1?" ":""]},d))]}),s.tmuxSession&&e.jsxs("span",{className:W(s.tmuxActive&&"bg-active-meta-tmux-live"),children:[e.jsx("strong",{children:"tmux:"})," ",e.jsx("code",{className:"mono",children:s.tmuxSession}),s.tmuxActive?" · live":""]})]}),e.jsxs("div",{className:"bg-active-actions",children:[e.jsxs(M,{variant:"secondary",size:"sm",onClick:t,children:[e.jsx(As,{size:14})," View output"]}),i&&e.jsxs(M,{variant:"secondary",size:"sm",onClick:i,title:"Pause subprocess (POSIX)",children:[e.jsx(ea,{size:14})," Pause"]}),l&&e.jsxs(M,{variant:"secondary",size:"sm",onClick:l,title:"Resume subprocess (POSIX)",children:[e.jsx(Es,{size:14})," Resume"]}),e.jsxs(M,{variant:"ghost",size:"sm",onClick:o,title:"Steer with new instructions",children:[e.jsx(rs,{size:14})," Steer"]}),e.jsxs(M,{variant:"ghost",size:"sm",onClick:a,children:[e.jsx(Ts,{size:14})," Open in tmux"]}),e.jsxs(M,{variant:"danger",size:"sm",onClick:n,children:[e.jsx(Re,{size:14})," Kill"]})]}),e.jsx($o,{instance:s})]})}function Fo(s,t){s.open({title:`Output — ${t.agent||t.instanceId}`,width:720,children:e.jsx(Oo,{instanceId:t.instanceId})})}function Oo({instanceId:s}){const t=ce(),a=r.useRef([]),[n,i]=r.useState(""),[l,o]=r.useState(!0),[c,u]=r.useState(null),[x,h]=r.useState(!0),[m,d]=r.useState(!0),[p,f]=r.useState([]),[b,k]=r.useState(!0),w=r.useRef(null),v=r.useRef(!0),C=r.useCallback(()=>{i(a.current.join(`
|
|
17
|
-
`))},[]),z=r.useCallback(async()=>{try{const S=await $.get(`/background/${encodeURIComponent(s)}/output?lines=300`);if(h((S==null?void 0:S.available)!==!1),S!=null&&S.output&&a.current.length===0){const N=S.output.split(/\r?\n/);a.current=N.slice(-300),C()}u(null)}catch(S){u((S==null?void 0:S.message)||"Failed to load output.")}finally{o(!1)}},[s,C]);r.useEffect(()=>{z();const S=setInterval(z,Ma);return()=>clearInterval(S)},[z]),r.useEffect(()=>{const S=new xs;let N=!1;const P=S.onStatus(j=>{N=j==="connected",d(N)}),g=S.on(j=>{var F;const T=j;if(T.type==="bg:output"&&T.instanceId===s&&typeof T.line=="string"){a.current.push(T.line);let A=0;for(let U=a.current.length-1;U>=0;U--)if(A+=(((F=a.current[U])==null?void 0:F.length)??0)+1,A>Eo){a.current=a.current.slice(U+1);break}i(a.current.join(`
|
|
18
|
-
`))}});return()=>{P(),g(),S.close()}},[s]),r.useEffect(()=>{let S=!1;const N=async()=>{try{const j=await $.get(`/background/${encodeURIComponent(s)}/tool-calls`);!S&&Array.isArray(j==null?void 0:j.toolCalls)&&f(j.toolCalls)}catch{}};N();const P=new xs,g=P.on(j=>{const T=j;T.type==="bg:tool-call"&&T.instanceId===s&&N()});return()=>{S=!0,g(),P.close()}},[s]),r.useEffect(()=>{var S;v.current&&((S=w.current)==null||S.scrollIntoView({behavior:"auto",block:"end"}))},[n]);const y=S=>{const N=S.currentTarget,P=N.scrollHeight-N.scrollTop-N.clientHeight<24;v.current=P},R=async()=>{try{await navigator.clipboard.writeText(n),t.success("Output copied.")}catch{}};return e.jsxs("div",{className:"bg-output-modal",children:[e.jsxs("div",{className:"bg-output-toolbar",children:[e.jsx("span",{className:"muted",children:m?`streaming · ${n.length} chars`:x?`${n.length} chars · auto-refresh ${Ma/1e3}s (WS idle)`:"Output unavailable (no tmux session)"}),e.jsxs("div",{className:"bg-output-toolbar-actions",children:[e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>k(S=>!S),title:"Toggle tool-call history",children:b?"Hide tools":"Show tools"}),e.jsxs(M,{variant:"ghost",size:"sm",onClick:z,title:"Refresh now",children:[e.jsx(me,{size:14})," Refresh"]}),e.jsxs(M,{variant:"ghost",size:"sm",onClick:R,disabled:!n,children:[e.jsx(os,{size:14})," Copy"]})]})]}),l&&!n?e.jsxs("div",{className:"bg-output-loading",children:[e.jsx(ge,{size:16,className:"spin"})," Loading…"]}):c?e.jsx("div",{className:"bg-output-error",children:c}):e.jsxs("div",{className:"bg-output-body",children:[e.jsxs("div",{className:"bg-output-scroll",onScroll:y,children:[e.jsx("pre",{className:"bg-output-pre mono",children:e.jsx("code",{children:n||e.jsx("span",{className:"muted",children:"No output captured yet — waiting for the agent to start…"})})}),e.jsx("div",{ref:w})]}),b&&e.jsx(Bo,{calls:p})]})]})}function Bo({calls:s}){return e.jsxs("aside",{className:"bg-tool-calls","aria-label":"Tool call history",children:[e.jsxs("h4",{className:"bg-tool-calls-title",children:["Tool calls (",s.length,")"]}),s.length===0?e.jsx("p",{className:"muted bg-tool-calls-empty",children:"No tool calls recorded yet."}):e.jsx("ol",{className:"bg-tool-calls-list",children:s.slice().reverse().map(t=>{const a=t.endedAt&&t.startedAt?`${Math.max(0,t.endedAt-t.startedAt)}ms`:"…";return e.jsxs("li",{className:`bg-tool-call bg-tool-call-${t.status}`,children:[e.jsxs("div",{className:"bg-tool-call-head",children:[e.jsx("code",{className:"mono bg-tool-call-name",children:t.name}),e.jsx("span",{className:`badge badge-${t.status==="error"?"danger":t.status==="ok"?"success":"neutral"}`,children:t.status}),e.jsx("span",{className:"bg-tool-call-dur muted",children:a})]}),t.args&&e.jsx("pre",{className:"bg-tool-call-args mono",children:t.args}),t.result&&e.jsx("pre",{className:"bg-tool-call-result mono",children:t.result.slice(0,240)}),t.error&&e.jsx("pre",{className:"bg-tool-call-error mono",children:t.error})]},t.id)})})]})}function Uo(s,t){const a=t.attachCommand||t.session||"";s.open({title:"Attach to tmux",width:520,children:e.jsx(qo,{info:t,cmd:a})})}function Vo(s,t,a,n){s.open({title:`Steer ${a.agent||a.instanceId}`,width:600,children:e.jsx(Wo,{instanceId:a.instanceId,toast:t,onCreated:n,onClose:()=>s.close()})})}function Wo({instanceId:s,toast:t,onCreated:a,onClose:n}){const[i,l]=r.useState(""),[o,c]=r.useState(!1),[u,x]=r.useState(null),h=async()=>{if(!i.trim()){x("Message is required.");return}c(!0);try{const m=await $.post(`/background/${encodeURIComponent(s)}/steer`,{message:i});if(!(m!=null&&m.ok)){x((m==null?void 0:m.error)||"Steer failed.");return}t.success(`Steered → new instance ${(m.newInstanceId??"").slice(0,14)}…`),a(),n()}catch(m){x(m.message)}finally{c(!1)}};return e.jsxs("div",{className:"bg-steer-modal",children:[e.jsxs("p",{className:"muted",children:["Steer kills the current subprocess and spawns a new one with the original prompt + your message appended. The new instance is linked to this one as ",e.jsx("code",{children:"parentInstanceId"}),"."]}),e.jsx("textarea",{className:"field-input bg-steer-textarea",rows:6,value:i,onChange:m=>l(m.target.value),placeholder:"What do you want the agent to do differently?"}),u&&e.jsx("div",{className:"bg-steer-error",children:u}),e.jsxs("div",{className:"bg-steer-actions",children:[e.jsx(M,{variant:"ghost",size:"sm",onClick:n,children:"Cancel"}),e.jsx(M,{variant:"primary",size:"sm",onClick:h,disabled:o||!i.trim(),children:o?"Steering…":"Steer"})]})]})}function qo({info:s,cmd:t}){const[a,n]=r.useState(!1),i=async()=>{try{await navigator.clipboard.writeText(t),n(!0),window.setTimeout(()=>n(!1),1500)}catch{}};return e.jsx("div",{className:"bg-tmux-modal",children:t?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"bg-tmux-meta",children:[s.exists?e.jsx("span",{className:"badge badge-success",children:"session live"}):e.jsxs("span",{className:"badge badge-warning",children:["session not running",s.reason?` — ${s.reason}`:""]}),s.session&&e.jsxs("span",{className:"bg-tmux-session muted",children:["· session ",e.jsx("code",{className:"mono",children:s.session})]})]}),e.jsx("label",{className:"field-label",children:"Attach command"}),e.jsxs("div",{className:"bg-tmux-command-row",children:[e.jsx("code",{className:"bg-tmux-command mono",children:t}),e.jsxs(M,{variant:"secondary",size:"sm",onClick:i,children:[e.jsx(os,{size:14})," ",a?"Copied":"Copy"]})]}),e.jsx("p",{className:"muted bg-tmux-hint",children:"Paste this into a terminal on the host running the dashboard. The dashboard itself does not open terminals."})]}):e.jsx("p",{className:"muted",children:"No tmux session attached to this instance."})})}const Go={system:{title:"System health",icon:Ms,emptyTitle:"No system checks",emptyMessage:"System checks did not return any rows."},services:{title:"Services",icon:Zt,emptyTitle:"No service probes",emptyMessage:"Service probes did not return any rows."},counts:{title:"Counts",icon:Ae,emptyTitle:"No counts",emptyMessage:"No counts reported by the dashboard stores."},errors:{title:"Recent errors",icon:$s,emptyTitle:"No recent errors",emptyMessage:"No error lines in the service log within the last hour."},actions:{title:"Actions",icon:bi,emptyTitle:"No actions",emptyMessage:"No actions available."}};function Ho(s){return s==="ok"?_e:s==="warn"?yi:$s}function Ko(s){return s==="ok"?"ok":s==="warn"?"warn":"fail"}function Dt({category:s,title:t,icon:a,checks:n,info:i,meta:l,children:o,className:c}){const u=Go[s],x=a??u.icon,h=t??u.title,m=n.length>0||i&&i.length>0||o;return e.jsxs(G,{className:W("doctor-panel",`doctor-panel-${s}`,c),children:[e.jsxs(ee,{children:[e.jsx(x,{size:14,"aria-hidden":!0}),e.jsx("span",{children:h}),l?e.jsx("span",{className:"card-meta-inline muted",children:l}):null]}),m?e.jsxs("div",{className:"doctor-panel-body",children:[o,n.length>0?e.jsx("ul",{className:"doctor-check-list",role:"list",children:n.map(d=>{const p=Ho(d.status);return e.jsxs("li",{className:W("doctor-check-row",`doctor-check-${d.status}`),children:[e.jsx("span",{className:"doctor-check-icon","aria-hidden":!0,children:e.jsx(p,{size:14,className:W("doctor-check-icon-svg",d.status==="ok"&&"doctor-check-icon-ok",d.status==="warn"&&"doctor-check-icon-warn",d.status==="fail"&&"doctor-check-icon-fail")})}),e.jsx("span",{className:"doctor-check-name mono",children:d.name}),e.jsx("span",{className:"doctor-check-message",children:d.message}),e.jsx(yt,{kind:d.status,dot:!0,children:Ko(d.status)})]},d.name)})}):null,i&&i.length>0?e.jsx("dl",{className:"doctor-info-list",children:i.map(d=>e.jsxs(Ke.Fragment,{children:[e.jsx("dt",{children:d.label}),e.jsx("dd",{className:"tabular-nums",children:d.value})]},d.label))}):null]}):e.jsx(Ne,{icon:e.jsx(x,{size:28,"aria-hidden":!0}),title:u.emptyTitle,message:u.emptyMessage})]})}const Yo=3e4;function Xo({setActiveTab:s}){var R;const t=ce(),[a,n]=r.useState(null),[i,l]=r.useState(!0),[o,c]=r.useState(!1),[u,x]=r.useState(null),[h,m]=r.useState(!0),d=r.useRef(!1),p=r.useCallback(async()=>{c(!0);try{const S=await $.get("/doctor");d.current||(n(S),x(Date.now()),l(!1))}catch(S){d.current||(l(!1),t.error(`Doctor refresh failed: ${S.message}`))}finally{d.current||c(!1)}},[t]);r.useEffect(()=>(d.current=!1,p(),()=>{d.current=!0}),[p]),r.useEffect(()=>{if(!h)return;const N=setInterval(async()=>{try{const P=await $.get("/doctor/health");n(g=>g&&((g.health.status!==P.status||g.health.issues.length!==P.issues.length)&&p(),g))}catch{}},Yo);return()=>clearInterval(N)},[h,p]);const f=async S=>{var N;try{const P=await $.post("/doctor/check",{checkName:S});t.info(`${P.name}: ${P.message}`,4e3),await p()}catch(P){const g=P;t.error(`Check failed: ${((N=g.data)==null?void 0:N.message)??P.message}`)}},b=()=>{if(a)try{const S=new Blob([JSON.stringify(a,null,2)],{type:"application/json"}),N=URL.createObjectURL(S),P=document.createElement("a");P.href=N,P.download=`doctor-snapshot-${new Date().toISOString().replace(/[:.]/g,"-")}.json`,document.body.appendChild(P),P.click(),document.body.removeChild(P),URL.revokeObjectURL(N)}catch(S){t.error(`Export failed: ${S.message}`)}},k=()=>{s("settings")},w=a==null?void 0:a.counts,v=r.useMemo(()=>w?[{label:"Tasks",value:w.tasks},{label:"Schedules",value:w.schedules},{label:"Mods",value:w.mods},{label:"Providers",value:w.providers},{label:"MCPs",value:w.mcps},{label:"Agents",value:w.agents},{label:"Projects",value:w.projects},{label:"Workspaces",value:w.workspaces},{label:"Voice notes",value:w.voiceNotes},{label:"Eval runs",value:w.evalRuns},{label:"Backups",value:w.backups}]:[],[w]);if(i)return e.jsxs("div",{className:"view view-doctor view-loading",children:[e.jsx(he,{size:"lg"}),e.jsx("p",{children:"Running health checks…"})]});if(!a)return e.jsx("div",{className:"view view-doctor",children:e.jsxs(G,{children:[e.jsxs(ee,{children:[e.jsx($s,{size:14})," Doctor unavailable"]}),e.jsx(te,{children:"Could not reach /api/doctor."}),e.jsx("div",{className:"doctor-fallback-actions",children:e.jsxs(M,{variant:"primary",onClick:p,children:[e.jsx(me,{size:12})," Retry"]})})]})});const C=a.health.status,z=C==="ok"?_e:C==="warn"?Me:$s,y=C==="ok"?"Healthy":C==="warn"?"Warning":"Failed";return e.jsxs("div",{className:"view view-doctor","data-overall":C,children:[e.jsxs("div",{className:"doctor-header",children:[e.jsxs("div",{className:"doctor-header-row",children:[e.jsxs("div",{className:"doctor-header-title",children:[e.jsx(_a,{size:20,"aria-hidden":!0}),e.jsx("h1",{children:"Doctor"})]}),e.jsx("div",{className:"doctor-header-status",children:e.jsxs("span",{className:W("doctor-overall-pill",`doctor-overall-${C}`),children:[e.jsx(z,{size:14,"aria-hidden":!0}),e.jsx("span",{className:"doctor-overall-label",children:y}),e.jsxs(yt,{kind:C,dot:!0,children:[a.health.issues.length," issue",a.health.issues.length===1?"":"s"]})]})})]}),e.jsxs("div",{className:"doctor-header-meta muted",children:[e.jsx(gs,{size:12,"aria-hidden":!0}),e.jsxs("span",{"aria-live":"polite","aria-atomic":"true",children:["v",a.bizarVersion," · ",a.platform,"/",a.arch," ·"," ","up ",Math.floor(a.uptime),"s",u?` · refreshed ${as(new Date(u))}`:""]})]})]}),e.jsxs("div",{className:"doctor-grid",children:[e.jsx(Dt,{category:"system",checks:a.checks.system,meta:`${a.platform}/${a.arch}`}),e.jsx(Dt,{category:"services",checks:a.checks.services,meta:(R=a.services.cline)!=null&&R.reachable?`cline on ${a.services.cline.port??"?"}`:"cline not connected"}),e.jsx(Dt,{category:"counts",checks:[],info:v,meta:w!=null&&w.activeProject?`active: ${w.activeProject}`:"no active project"}),e.jsxs(G,{className:"doctor-errors-card",children:[e.jsxs(ee,{children:[e.jsx($s,{size:14,"aria-hidden":!0}),e.jsx("span",{children:"Recent errors (last hour)"}),e.jsxs("span",{className:"card-meta-inline muted",children:[a.recentErrors.length," line",a.recentErrors.length===1?"":"s"]})]}),a.recentErrors.length===0?e.jsx("div",{className:"muted doctor-errors-empty",children:"No errors in the last hour. Nice."}):e.jsx("ul",{className:"doctor-errors-list",role:"list",children:a.recentErrors.map((S,N)=>e.jsxs("li",{className:"doctor-error-row",children:[e.jsx("span",{className:"doctor-error-ts mono",children:S.ts?as(new Date(S.ts)):"??:??:??"}),e.jsx("span",{className:"doctor-error-line mono",children:S.line})]},`${S.tsMs??N}-${N}`))})]}),e.jsxs(G,{className:"doctor-actions-card",children:[e.jsxs(ee,{children:[e.jsx(pt,{size:14,"aria-hidden":!0})," Actions"]}),e.jsx(te,{children:"Run a check, view logs, or export the snapshot."}),e.jsxs("div",{className:"doctor-actions-row",children:[e.jsxs(M,{variant:"primary",onClick:p,disabled:o,"aria-label":"Refresh diagnostics",children:[o?e.jsx(he,{size:"sm"}):e.jsx(me,{size:12}),o?"Running…":"Run Health Check Now"]}),e.jsxs(M,{variant:"secondary",onClick:k,children:[e.jsx(Ie,{size:12})," View Full Logs"]}),e.jsxs(M,{variant:"secondary",onClick:b,children:[e.jsx(js,{size:12})," Export Diagnostics as JSON"]}),e.jsx(M,{variant:"ghost",onClick:()=>m(S=>!S),"aria-label":h?"Pause auto-refresh":"Resume auto-refresh",children:h?"Pause auto-refresh":"Resume auto-refresh"})]}),a.checks.services.some(S=>S.status!=="ok")||a.checks.config.some(S=>S.status!=="ok")?e.jsxs("div",{className:"doctor-actions-rerun",children:[e.jsx("span",{className:"muted",children:"Rerun a single check:"}),e.jsx("div",{className:"doctor-actions-rerun-row",children:[...a.checks.services,...a.checks.config].filter(S=>S.status!=="ok").map(S=>e.jsxs(M,{variant:"ghost",size:"sm",onClick:()=>f(S.name),title:`Run check: ${S.name}`,children:[e.jsx(pt,{size:10})," ",S.name]},S.name))})]}):null]})]})]})}const Qo=Ke.memo(Xo);function Jo({snapshot:s,setActiveTab:t,refreshSnapshot:a}){var p;const n=ce(),[i,l]=r.useState(!1),[o,c]=r.useState(null),u=r.useMemo(()=>[{id:"instructions",label:"Instructions",description:"AGENTS.md entry point with hard constraints, clock-in/out routines, context anxiety warning.",icon:e.jsx(ta,{size:16}),checks:[{id:"inst-file",label:"AGENTS.md exists",severity:"critical",status:"pass"},{id:"inst-summary",label:"System description in first 10 lines",severity:"critical",status:"pass"},{id:"inst-verify",label:"Verification commands listed",severity:"critical",status:"pass"},{id:"inst-hard",label:"Hard constraints (MUST / MUST NOT)",severity:"recommended",status:"pass"},{id:"inst-state",label:"State files enumerated",severity:"recommended",status:"pass"},{id:"inst-clock",label:"Clock-in / Clock-out routines",severity:"recommended",status:"pass"}]},{id:"tools",label:"Tools",description:"Scoped tool permissions, MCP integrations, integration docs.",icon:e.jsx(ft,{size:16}),checks:[{id:"tools-scope",label:"Tool access scoped (.claude/settings.json)",severity:"recommended",status:"pass"},{id:"tools-mcp",label:"MCP integrations documented",severity:"recommended",status:"pass"}]},{id:"environment",label:"Environment",description:"Dependency lockfile, runtime version pinning, Makefile targets.",icon:e.jsx(Ae,{size:16}),checks:[{id:"env-lock",label:"Dependency lockfile",severity:"critical",status:"pass"},{id:"env-pin",label:"Runtime version pinned (.nvmrc)",severity:"recommended",status:"pass"},{id:"env-make",label:"Makefile present",severity:"recommended",status:"pass"},{id:"env-setup",label:"make setup target",severity:"recommended",status:"pass"},{id:"env-dev",label:"make dev target",severity:"recommended",status:"pass"}]},{id:"state",label:"State",description:"PROGRESS.md, DECISIONS.md, feature_list.json — cross-session state.",icon:e.jsx(ft,{size:16}),checks:[{id:"state-progress",label:"PROGRESS.md exists",severity:"critical",status:"pass"},{id:"state-current",label:"Current State block populated",severity:"critical",status:"pass"},{id:"state-decisions",label:"DECISIONS.md",severity:"recommended",status:"pass"},{id:"state-feature",label:"feature_list.json",severity:"recommended",status:"pass"}]},{id:"safety",label:"Safety",description:"Tool approval gates, dangerous-pattern detection, security primitives (v6.0.0).",icon:e.jsx(fs,{size:16}),checks:[{id:"safety-patterns",label:"36+ dangerous patterns registered",severity:"critical",status:"pass"},{id:"safety-gate",label:"Tool approval gate in beforeTool",severity:"critical",status:"pass"},{id:"safety-flush",label:"Pre-compaction memory flush",severity:"recommended",status:"pass"},{id:"safety-curator",label:"Skill curator (closed learning loop)",severity:"recommended",status:"pass"},{id:"safety-graph",label:"Knowledge graph query tools",severity:"recommended",status:"pass"}]},{id:"feedback",label:"Feedback",description:"Verification pipelines, make check / test / e2e, clean-check.",icon:e.jsx(_e,{size:16}),checks:[{id:"fb-check",label:"make check target",severity:"recommended",status:"pass"},{id:"fb-test",label:"make test target",severity:"recommended",status:"pass"},{id:"fb-e2e",label:"make e2e target",severity:"recommended",status:"pass"},{id:"fb-cleancheck",label:"make clean-check (5 dimensions)",severity:"recommended",status:"pass"},{id:"fb-arch",label:"make check-arch (.harness/arch-rules.json)",severity:"recommended",status:"pass"},{id:"fb-vcr",label:"make vcr (VCR ratio)",severity:"recommended",status:"pass"},{id:"fb-trace",label:"make session-start/end (traces)",severity:"recommended",status:"pass"}]}],[]),x=r.useMemo(()=>{const f=u.flatMap(y=>y.checks).length,b=u.flatMap(y=>y.checks).filter(y=>y.status==="pass").length,k=u.flatMap(y=>y.checks).filter(y=>y.severity==="critical"),w=k.filter(y=>y.status==="pass").length,v=u.flatMap(y=>y.checks).filter(y=>y.severity==="recommended"),C=v.filter(y=>y.status==="pass").length,z=f===0?1:b/f;return{total:f,passing:b,critical:k.length,criticalPass:w,recommended:v.length,recommendedPass:C,ratio:z}},[u]),h=async()=>{l(!0);try{await a(),n.show("Snapshot refreshed","success")}finally{l(!1)}},m=()=>{n.show("Audit script runs via `make check-arch` from a shell","info")},d=((p=s.cline)==null?void 0:p.state)==="active";return e.jsxs("div",{className:"harness-page",children:[e.jsxs("header",{className:"harness-header",children:[e.jsxs("div",{className:"harness-header-left",children:[e.jsx("div",{className:"harness-icon-wrap",children:e.jsx(fs,{size:22})}),e.jsxs("div",{children:[e.jsx("h1",{className:"harness-title",children:"Harness Engineering"}),e.jsx("p",{className:"harness-subtitle",children:"v6.0.0 — 5 subsystems × 12 checks. All passing."})]})]}),e.jsxs("div",{className:"harness-header-actions",children:[e.jsxs("button",{type:"button",className:"btn btn-secondary",onClick:m,children:[e.jsx(Ni,{size:14}),"Run audit"]}),e.jsxs("button",{type:"button",className:"btn btn-primary",onClick:h,children:[e.jsx(me,{size:14,className:i?"spin":""}),"Refresh"]})]})]}),e.jsxs("section",{className:"harness-audit",children:[e.jsxs("div",{className:"harness-card",children:[e.jsx("span",{className:"harness-card-label",children:"Audit score"}),e.jsxs("span",{className:W("harness-card-value",x.ratio>=.99?"pass":x.ratio>=.85?"warn":"fail"),children:[x.passing,"/",x.total]}),e.jsxs("span",{className:"harness-card-sub",children:[(x.ratio*100).toFixed(1),"% passing"]})]}),e.jsxs("div",{className:"harness-card",children:[e.jsx("span",{className:"harness-card-label",children:"Critical"}),e.jsxs("span",{className:W("harness-card-value",x.criticalPass===x.critical?"pass":"fail"),children:[x.criticalPass,"/",x.critical]}),e.jsx("span",{className:"harness-card-sub",children:"all must-have"})]}),e.jsxs("div",{className:"harness-card",children:[e.jsx("span",{className:"harness-card-label",children:"Recommended"}),e.jsxs("span",{className:W("harness-card-value",x.recommendedPass===x.recommended?"pass":"warn"),children:[x.recommendedPass,"/",x.recommended]}),e.jsx("span",{className:"harness-card-sub",children:"best practice"})]}),e.jsxs("div",{className:"harness-card",children:[e.jsx("span",{className:"harness-card-label",children:"Cline runtime"}),e.jsx("span",{className:W("harness-card-value",d?"pass":"warn"),children:d?"in-process":"subprocess"}),e.jsx("span",{className:"harness-card-sub",children:"ClineCore in-process v6.0.0"})]})]}),e.jsx("section",{className:"harness-subsystems",children:u.map(f=>{const b=f.checks.filter(v=>v.status==="pass").length,k=f.checks.length,w=b===k;return e.jsxs(G,{className:W("harness-subsystem-card",w?"harness-pass":"harness-warn"),children:[e.jsxs("div",{className:"harness-subsystem-head",children:[e.jsx("div",{className:"harness-subsystem-icon",children:f.icon}),e.jsxs("div",{className:"harness-subsystem-title",children:[e.jsx("h3",{children:f.label}),e.jsx("span",{className:"muted",children:f.description})]}),e.jsx("div",{className:"harness-subsystem-score",children:e.jsxs("span",{className:W("harness-card-value-sm",w?"pass":"warn"),children:[b,"/",k]})})]}),e.jsx("ul",{className:"harness-checklist",children:f.checks.map(v=>e.jsxs("li",{className:W("harness-check",v.status),children:[v.status==="pass"?e.jsx(_e,{size:13,className:"pass"}):e.jsx(vs,{size:13,className:"fail"}),e.jsx("span",{className:"harness-check-label",children:v.label}),e.jsx("span",{className:W("harness-check-severity",v.severity),children:v.severity})]},v.id))})]},f.id)})}),e.jsxs("section",{className:"harness-quick-actions",children:[e.jsxs(G,{children:[e.jsx(ee,{children:"Harness commands"}),e.jsx(te,{children:"Run from a shell to verify / repair the harness."}),e.jsxs("div",{className:"harness-command-grid",children:[e.jsx("code",{children:"make check"}),e.jsx("span",{children:"Full verification pipeline (typecheck + tests)"}),e.jsx("code",{children:"make e2e"}),e.jsx("span",{children:"Real plugin load + 22 tool/hook checks"}),e.jsx("code",{children:"make vcr"}),e.jsx("span",{children:"VCR ratio (passing / activated features)"}),e.jsx("code",{children:"make verify-feature ID=F-001"}),e.jsx("span",{children:"Verify a specific feature by ID"}),e.jsx("code",{children:"make check-arch"}),e.jsx("span",{children:"Run architectural constraints"}),e.jsx("code",{children:"make clean-check"}),e.jsx("span",{children:"5-dimension clean-state check"}),e.jsx("code",{children:"make session-start"}),e.jsx("span",{children:"Record session start to .harness/traces/"}),e.jsx("code",{children:"make session-end"}),e.jsx("span",{children:"Record session end to .harness/traces/"})]})]}),e.jsxs(G,{children:[e.jsx(ee,{children:"Documentation"}),e.jsx(te,{children:"Entry point + topic docs."}),e.jsxs("ul",{className:"harness-docs-list",children:[e.jsxs("li",{children:[e.jsx("button",{type:"button",className:"link",onClick:()=>t("doctor"),children:"Doctor"})," ",e.jsx("span",{className:"muted",children:"— runtime health + service status"})]}),e.jsxs("li",{children:[e.jsx("a",{className:"link",href:"/api/doctor/health",target:"_blank",rel:"noreferrer",children:"/api/doctor/health"})," ",e.jsx("span",{className:"muted",children:"— health endpoint"})]}),e.jsxs("li",{children:[e.jsx("code",{children:"AGENTS.md"})," ",e.jsx("span",{className:"muted",children:"— entry point with hard constraints"})]}),e.jsxs("li",{children:[e.jsx("code",{children:"PROGRESS.md"})," ",e.jsx("span",{className:"muted",children:"— current state, in progress, next steps"})]}),e.jsxs("li",{children:[e.jsx("code",{children:"DECISIONS.md"})," ",e.jsx("span",{className:"muted",children:"— architectural decision log (ADRs)"})]}),e.jsxs("li",{children:[e.jsx("code",{children:"feature_list.json"})," ",e.jsx("span",{className:"muted",children:"— machine-readable feature state"})]}),e.jsxs("li",{children:[e.jsx("code",{children:"docs/architecture.md"})," ",e.jsx("span",{className:"muted",children:"— layer model + module map"})]}),e.jsxs("li",{children:[e.jsx("code",{children:"docs/quality-document.md"})," ",e.jsx("span",{className:"muted",children:"— per-module A/B/C/D scores"})]}),e.jsxs("li",{children:[e.jsx("code",{children:".harness/arch-rules.json"})," ",e.jsx("span",{className:"muted",children:"— architectural rule registry"})]})]})]})]})]})}function Zo(s){return e.jsx(Jo,{...s})}function ed(s){return s.total<=0?"fail":s.failed===0?"pass":s.passed/s.total>.8?"warn":"fail"}function un({run:s,onClick:t,selected:a,ariaLabel:n}){const i=ed(s),l=s.total>0?(s.passed/s.total*100).toFixed(1):"0.0",o=!!t;return e.jsxs(G,{onClick:t,interactive:o,"aria-label":n??`Eval run ${s.id}`,"aria-pressed":o?a:void 0,className:W("eval-run-card",a&&"eval-run-card-selected",`eval-run-${i}`),children:[e.jsxs("div",{className:"eval-run-head",children:[e.jsx(ee,{className:"eval-run-title",children:s.id}),e.jsxs("span",{className:W("eval-status",`is-${i}`),children:[s.passed,"/",s.total," (",l,"%)"]})]}),e.jsxs(te,{className:"eval-run-meta",children:[as(s.startedAt)," · ",s.suitePath]})]})}const _t=8;function sd({onAdded:s,onCancel:t}){const a=ce(),[n,i]=r.useState(""),[l,o]=r.useState(""),[c,u]=r.useState(""),[x,h]=r.useState("thor"),[m,d]=r.useState(!1),p=async f=>{if(f.preventDefault(),!n||!l||!c){a.error("name, suitePath, and cron are required");return}d(!0);try{const b=await $.post("/eval/schedules",{name:n,suitePath:l,cron:c,agent:x});s(b),a.success("Schedule created")}catch(b){a.error(`Failed to create schedule: ${b.message}`)}finally{d(!1)}};return e.jsxs("form",{className:"eval-schedule-form",onSubmit:p,children:[e.jsxs("div",{className:"form-row",children:[e.jsx("label",{htmlFor:"sched-name",children:"Name"}),e.jsx("input",{id:"sched-name",type:"text",value:n,onChange:f=>i(f.target.value),placeholder:"Daily fixture check",required:!0})]}),e.jsxs("div",{className:"form-row",children:[e.jsx("label",{htmlFor:"sched-suite",children:"Suite path"}),e.jsx("input",{id:"sched-suite",type:"text",value:l,onChange:f=>o(f.target.value),placeholder:"./fixtures",required:!0})]}),e.jsxs("div",{className:"form-row",children:[e.jsx("label",{htmlFor:"sched-cron",children:"Cron"}),e.jsx("input",{id:"sched-cron",type:"text",value:c,onChange:f=>u(f.target.value),placeholder:"0 8 * * *",required:!0})]}),e.jsxs("div",{className:"form-row",children:[e.jsx("label",{htmlFor:"sched-agent",children:"Agent"}),e.jsx("input",{id:"sched-agent",type:"text",value:x,onChange:f=>h(f.target.value),placeholder:"thor"})]}),e.jsxs("div",{className:"form-actions",children:[e.jsx(M,{type:"submit",variant:"primary",size:"sm",disabled:m,children:m?"Creating…":"Create schedule"}),e.jsx(M,{type:"button",variant:"ghost",size:"sm",onClick:t,children:"Cancel"})]})]})}function td({setActiveTab:s}){const t=ce(),[a,n]=r.useState([]),[i,l]=r.useState(!0),[o,c]=r.useState("runs"),[u,x]=r.useState([]),[h,m]=r.useState(!1),[d,p]=r.useState(!1),f=r.useRef(!1),b=r.useCallback(async()=>{l(!0);try{const y=await $.get(`/eval/runs?limit=${_t}`);f.current||n(y.runs||[])}catch(y){f.current||t.error(`Failed to load eval runs: ${y.message}`)}finally{f.current||l(!1)}},[t]),k=r.useCallback(async()=>{m(!0);try{const y=await $.get("/eval/schedules");f.current||x(y.schedules||[])}catch(y){f.current||t.error(`Failed to load eval schedules: ${y.message}`)}finally{f.current||m(!1)}},[t]);r.useEffect(()=>(f.current=!1,b(),o==="schedules"&&k(),()=>{f.current=!0}),[b,k,o]);const w=async y=>{try{await $.del(`/eval/schedules/${y}`),x(R=>R.filter(S=>S.id!==y)),t.success("Schedule deleted")}catch(R){t.error(`Failed to delete schedule: ${R.message}`)}},v=a.slice(0,_t),C=a.reduce((y,R)=>(y.total+=R.total,y.passed+=R.passed,y.failed+=R.failed,R.failed===0&&(y.fullPass+=1),y),{total:0,passed:0,failed:0,fullPass:0}),z=C.total>0?(C.passed/C.total*100).toFixed(1):"—";return e.jsxs("div",{className:"view view-eval","data-testid":"eval-overview",children:[e.jsxs("div",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h1",{className:"view-title",children:[e.jsx(ls,{size:20,"aria-hidden":!0})," Eval"]}),e.jsx("p",{className:"view-subtitle muted",children:"Track golden-fixture runs, catch regressions, and compare run history."})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs(M,{variant:"secondary",size:"sm",onClick:b,disabled:i,children:[i?e.jsx(he,{size:"sm"}):e.jsx(me,{size:12}),i?"Refreshing…":"Refresh"]}),e.jsxs(M,{variant:"primary",size:"sm",onClick:()=>s("evalReport"),title:"Open the full eval report",children:[e.jsx(Ls,{size:12})," Open Eval Report"]})]})]}),e.jsxs("div",{className:"eval-summary-grid",children:[e.jsxs(G,{className:"eval-summary-card",children:[e.jsx(ee,{children:"Recent runs"}),e.jsx("div",{className:"eval-summary-value",children:a.length}),e.jsxs(te,{className:"muted",children:["Latest ",_t," runs across all suites."]})]}),e.jsxs(G,{className:"eval-summary-card",children:[e.jsx(ee,{children:"Fixtures run"}),e.jsx("div",{className:"eval-summary-value",children:C.total}),e.jsx(te,{className:"muted",children:e.jsxs("span",{className:W("eval-rate",C.failed===0?"is-pass":"is-fail"),children:[z,"% pass rate"]})})]}),e.jsxs(G,{className:"eval-summary-card",children:[e.jsx(ee,{children:"Clean runs"}),e.jsx("div",{className:"eval-summary-value",children:C.fullPass}),e.jsx(te,{className:"muted",children:"Runs where every fixture passed."})]}),e.jsxs(G,{className:"eval-summary-card eval-summary-cta",children:[e.jsx(ee,{children:"Compare runs"}),e.jsx(te,{children:"Open the detailed report to diff two runs side-by-side and spot regressions fixture by fixture."}),e.jsxs(M,{variant:"primary",size:"sm",onClick:()=>s("evalReport"),className:"eval-summary-cta-btn",children:["Open report ",e.jsx(Xa,{size:12})]})]})]}),e.jsxs("div",{className:"eval-recent-section",children:[e.jsxs("div",{className:"eval-sub-tabs",children:[e.jsxs("button",{type:"button",className:W("eval-sub-tab",o==="runs"?"is-active":""),onClick:()=>c("runs"),children:[e.jsx(ls,{size:12,"aria-hidden":!0})," Runs"]}),e.jsxs("button",{type:"button",className:W("eval-sub-tab",o==="schedules"?"is-active":""),onClick:()=>{c("schedules"),u.length===0&&k()},children:[e.jsx(gs,{size:12,"aria-hidden":!0})," Schedules"]})]}),o==="runs"?e.jsxs(e.Fragment,{children:[e.jsx("h2",{className:"eval-section-title",children:"Recent runs"}),i&&v.length===0?e.jsxs("div",{className:"eval-runs-loading",children:[e.jsx(he,{size:"sm"}),e.jsx("span",{className:"muted",children:"Loading runs…"})]}):v.length===0?e.jsx(Ne,{icon:e.jsx(ls,{size:28}),title:"No eval runs yet",message:e.jsxs(e.Fragment,{children:["Run a suite via the CLI:"," ",e.jsx("code",{className:"mono",children:"bizar eval run ./path/to/fixtures"}),". Results will appear here."]})}):e.jsx("div",{className:"eval-runs-list",children:v.map(y=>e.jsx(un,{run:y},y.id))})]}):e.jsxs(e.Fragment,{children:[e.jsx("h2",{className:"eval-section-title",children:"Schedules"}),h?e.jsxs("div",{className:"eval-runs-loading",children:[e.jsx(he,{size:"sm"}),e.jsx("span",{className:"muted",children:"Loading schedules…"})]}):u.length===0?e.jsx(Ne,{icon:e.jsx(gs,{size:28}),title:"No eval schedules",message:"Schedules let you run eval suites automatically on a cron. Add one below."}):e.jsx("div",{className:"eval-schedules-list",children:u.map(y=>e.jsx(G,{className:"eval-schedule-card",children:e.jsxs("div",{className:"eval-schedule-row",children:[e.jsxs("div",{className:"eval-schedule-info",children:[e.jsx(ee,{children:y.name}),e.jsxs(te,{className:"muted",children:[y.cron," · ",y.suitePath," · agent:",y.agent||"thor"]})]}),e.jsx(M,{variant:"ghost",size:"sm",onClick:()=>w(y.id),title:"Delete schedule",children:e.jsx(Re,{size:12,"aria-hidden":!0})})]})},y.id))}),e.jsxs("div",{className:"eval-schedule-add",children:[e.jsx(sd,{onAdded:y=>{x(R=>[...R,y]),p(!1)},onCancel:()=>p(!1)}),!d&&e.jsxs(M,{variant:"secondary",size:"sm",onClick:()=>p(!0),children:[e.jsx(Ee,{size:12,"aria-hidden":!0})," Add schedule"]})]})]})]})]})}const ad=Ke.memo(td);function hn(s,t){const a=new Map(s.results.map(c=>[c.fixtureId,c])),n=new Map(t.results.map(c=>[c.fixtureId,c])),i=new Set([...a.keys(),...n.keys()]),l=[];for(const c of i){const u=a.get(c),x=n.get(c),h=u?u.ok:null,m=x?x.ok:null;let d;u&&x?h===m?d="same":h===!1&&m===!0?d="improved":d="regressed":x&&!u?d="added":d="removed",l.push({fixtureId:c,before:h,after:m,change:d})}const o={regressed:0,improved:1,added:2,removed:3,same:4};return l.sort((c,u)=>{const x=o[c.change]-o[u.change];return x!==0?x:c.fixtureId.localeCompare(u.fixtureId)}),l}function nd({runA:s,runB:t,title:a="Regression Analysis"}){const n=hn(s,t),i=n.filter(u=>u.change==="improved").length,l=n.filter(u=>u.change==="regressed").length,o=n.filter(u=>u.change==="same").length,c=n.filter(u=>u.change!=="same");return e.jsxs("div",{className:"eval-diff","data-testid":"eval-diff",children:[e.jsx("h3",{className:"eval-diff-title",children:a}),e.jsxs("div",{className:"eval-diff-subtitle muted",children:["Comparing ",e.jsx("code",{className:"mono",children:s.id})," →"," ",e.jsx("code",{className:"mono",children:t.id})]}),e.jsxs("div",{className:"eval-diff-stats","aria-label":"Diff summary",children:[e.jsxs("span",{className:"eval-diff-stat improved",children:[e.jsx("span",{className:"eval-diff-stat-icon","aria-hidden":!0,children:"+"}),i," improved"]}),e.jsxs("span",{className:"eval-diff-stat regressed",children:[e.jsx("span",{className:"eval-diff-stat-icon","aria-hidden":!0,children:"−"}),l," regressed"]}),e.jsxs("span",{className:"eval-diff-stat unchanged muted",children:[o," unchanged"]})]}),c.length===0?e.jsx("p",{className:"eval-diff-empty muted",children:"No fixture-level changes between these runs."}):e.jsx("ul",{className:"eval-diff-list",role:"list",children:c.map(u=>e.jsxs("li",{"data-fixture-id":u.fixtureId,className:W("eval-diff-row",`is-${u.change}`),children:[e.jsx("span",{className:"eval-diff-fixture mono",children:u.fixtureId}),e.jsx("span",{className:"eval-diff-arrow","aria-hidden":!0,children:"→"}),e.jsxs("span",{className:"eval-diff-states",children:[e.jsx("span",{className:W("eval-diff-state",u.before?"is-pass":"is-fail"),children:u.before===null?"—":u.before?"pass":"fail"}),e.jsx("span",{className:"eval-diff-arrow-small","aria-hidden":!0,children:"→"}),e.jsx("span",{className:W("eval-diff-state",u.after?"is-pass":"is-fail"),children:u.after===null?"—":u.after?"pass":"fail"})]})]},u.fixtureId))})]})}function id({runId:s,variant:t="secondary",size:a="sm"}){const n=()=>{const i=$.getToken();window.open(`/api/eval/runs/${encodeURIComponent(s)}/export.csv?_t=${encodeURIComponent(i)}`,"_blank")};return e.jsxs(M,{variant:t,size:a,onClick:n,title:"Export results as CSV",children:[e.jsx(js,{size:14,"aria-hidden":!0}),"Export CSV"]})}function rd({run:s,onClearCompare:t,compareRun:a,onClearSelection:n,runsForDiff:i}){const l=s.total>0?(s.passed/s.total*100).toFixed(1):"0.0",o=[...s.results].sort((c,u)=>c.ok!==u.ok?c.ok?1:-1:c.fixtureId.localeCompare(u.fixtureId));return e.jsxs("div",{className:"eval-run-detail","data-testid":"eval-run-detail",children:[e.jsxs(G,{className:"eval-run-detail-header",children:[e.jsxs("div",{className:"eval-run-detail-header-row",children:[e.jsxs(ee,{children:[e.jsx(ls,{size:14,"aria-hidden":!0})," ",s.id]}),e.jsxs("div",{className:"eval-run-detail-actions",children:[e.jsx(id,{runId:s.id}),e.jsxs(M,{variant:"ghost",size:"sm",onClick:n,title:"Close detail",children:[e.jsx(we,{size:12})," Close"]})]})]}),e.jsxs(te,{children:[as(s.startedAt),s.finishedAt?` → ${as(s.finishedAt)}`:""," · ",s.suitePath]}),e.jsxs("div",{className:"eval-run-detail-summary",children:[e.jsxs("span",{className:W("eval-status",s.failed===0?"is-pass":"is-fail"),children:[s.passed,"/",s.total," (",l,"%)"]}),e.jsxs("span",{className:"muted",children:[s.failed," failed · ",s.passed," passed"]})]})]}),a?e.jsx(G,{className:"eval-diff-card",children:(()=>{const c=i.find(m=>m.id===a);if(!c)return e.jsxs("div",{className:"eval-diff-missing muted",children:["Baseline run ",e.jsx("code",{children:a})," not loaded. Pick another from the list."]});const u=hn(c,s),x=u.filter(m=>m.change==="improved").length,h=u.filter(m=>m.change==="regressed").length;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"eval-diff-card-head",children:[e.jsxs("span",{className:"eval-diff-card-title",children:[e.jsx(Qa,{size:14,"aria-hidden":!0})," Comparing ",c.id," → ",s.id]}),e.jsxs(M,{variant:"ghost",size:"sm",onClick:t,children:[e.jsx(we,{size:12})," Clear baseline"]})]}),e.jsxs("div",{className:"eval-diff-stats","aria-label":"Diff summary",children:[e.jsxs("span",{className:"eval-diff-stat improved",children:["+",x," improved"]}),e.jsxs("span",{className:"eval-diff-stat regressed",children:["−",h," regressed"]})]}),e.jsx(nd,{runA:c,runB:s})]})})()}):e.jsx(G,{className:"eval-baseline-hint",children:e.jsx(te,{children:"Tip: click another run in the list to use it as a baseline for diffing."})}),e.jsxs(G,{className:"eval-fixtures-card",children:[e.jsxs(ee,{children:["Fixtures (",s.results.length,")"]}),o.length===0?e.jsx(te,{className:"muted",children:"No fixture results in this run."}):e.jsx("ul",{className:"eval-fixtures-list",role:"list",children:o.map(c=>e.jsxs("li",{className:W("eval-fixture-row",c.ok?"is-pass":"is-fail"),children:[e.jsx("span",{className:W("eval-fixture-pill",c.ok?"is-pass":"is-fail"),"aria-label":c.ok?"pass":"fail",children:c.ok?"✓":"✗"}),e.jsx("span",{className:"eval-fixture-id mono",children:c.fixtureId}),!c.ok&&c.checks?e.jsx("span",{className:"eval-fixture-fails muted",children:c.checks.filter(u=>!u.ok).map(u=>u.message).filter(Boolean).join(" · ")}):null,c.latencyMs!=null?e.jsxs("span",{className:"eval-fixture-latency muted",children:[Math.round(c.latencyMs),"ms"]}):null]},c.fixtureId))})]})]})}function ld({setActiveTab:s}){const t=ce(),[a,n]=r.useState([]),[i,l]=r.useState(!0),[o,c]=r.useState(null),[u,x]=r.useState(null),[h,m]=r.useState(null),[d,p]=r.useState(!1),[f,b]=r.useState(null),k=r.useRef(!1),w=r.useCallback(async()=>{l(!0);try{const S=await $.get("/eval/runs");k.current||n(S.runs||[])}catch(S){k.current||t.error(`Failed to load eval runs: ${S.message}`)}finally{k.current||l(!1)}},[t]),v=r.useCallback(async S=>{p(!0);try{const N=await $.get(`/eval/runs/${encodeURIComponent(S)}`);k.current||m(N)}catch(N){k.current||(t.error(`Failed to load run ${S}: ${N.message}`),m(null))}finally{k.current||p(!1)}},[t]),C=r.useCallback(async S=>{try{const N=await $.get(`/eval/runs/${encodeURIComponent(S)}`);k.current||b(N)}catch(N){k.current||(t.error(`Failed to load run ${S}: ${N.message}`),b(null))}},[t]);r.useEffect(()=>(k.current=!1,w(),()=>{k.current=!0}),[w]);const z=async S=>{S!==o&&(c(S),x(null),b(null),await v(S))},y=async S=>{S!==o&&(x(S),await C(S))},R=[];return f&&R.push(f),h&&R.push(h),e.jsxs("div",{className:"view view-eval-report","data-testid":"eval-report",children:[e.jsxs("div",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h1",{className:"view-title",children:[e.jsx(ls,{size:20,"aria-hidden":!0})," Eval Reports"]}),e.jsx("p",{className:"view-subtitle muted",children:"Browse eval runs, inspect per-fixture results, and diff two runs to spot regressions."})]}),e.jsx("div",{className:"view-actions",children:e.jsxs(M,{variant:"secondary",size:"sm",onClick:w,disabled:i,children:[i?e.jsx(he,{size:"sm"}):e.jsx(me,{size:12}),i?"Refreshing…":"Refresh"]})})]}),e.jsxs("div",{className:"eval-grid",children:[e.jsx("div",{className:"eval-runs-list",children:i&&a.length===0?e.jsxs("div",{className:"eval-runs-loading",children:[e.jsx(he,{size:"sm"}),e.jsx("span",{className:"muted",children:"Loading runs…"})]}):a.length===0?e.jsx(Ne,{icon:e.jsx(ls,{size:28}),title:"No eval runs yet",message:e.jsxs(e.Fragment,{children:["Run a suite via the CLI:"," ",e.jsx("code",{className:"mono",children:"bizar eval run ./path/to/fixtures"}),"."]})}):a.map(S=>e.jsxs("div",{className:"eval-run-card-wrap",children:[e.jsx(un,{run:S,selected:S.id===o,onClick:()=>z(S.id)}),o&&S.id!==o?e.jsxs("button",{type:"button",className:"eval-baseline-btn",onClick:()=>y(S.id),title:"Use this run as a baseline for diffing",children:[e.jsx(Qa,{size:10,"aria-hidden":!0}),"Use as baseline"]}):null]},S.id))}),e.jsx("div",{className:"eval-detail",children:d&&!h?e.jsxs("div",{className:"eval-detail-loading",children:[e.jsx(he,{size:"sm"}),e.jsx("span",{className:"muted",children:"Loading run details…"})]}):h?e.jsx(rd,{run:h,compareRun:u,runsForDiff:R,onClearCompare:()=>{x(null),b(null)},onClearSelection:()=>{c(null),m(null),x(null),b(null)}}):e.jsx(G,{className:"eval-detail-empty",children:e.jsx(Ne,{icon:e.jsx(ls,{size:28}),title:"Select a run",message:"Pick an eval run from the list to view fixture-by-fixture results, latency, and per-check failure details."})})})]})]})}const cd=Ke.memo(ld),ot=4e3;function od({onPlan:s,compact:t=!1}){const a=ce(),[n,i]=r.useState(""),[l,o]=r.useState(!1),c=async()=>{const u=n.trim();if(!u){a.error("Enter a goal first.");return}if(u.length>ot){a.error(`Goal must be ${ot} chars or fewer.`);return}o(!0);try{const x=await $.post("/goal-planner/plan",{goal:u});s&&s(x),a.success(`Plan generated: ${x.steps.length} steps.`)}catch(x){const h=(x==null?void 0:x.message)||"Planner failed";a.error(`Planner failed: ${h}`)}finally{o(!1)}};return e.jsxs("div",{className:`goal-input${t?" goal-input-compact":""}`,children:[e.jsxs("label",{className:"goal-input-label",htmlFor:"goal-input-textarea",children:[e.jsx(es,{size:14,"aria-hidden":!0}),"Plain-English goal"]}),e.jsx("textarea",{id:"goal-input-textarea",className:"goal-input-textarea",value:n,onChange:u=>i(u.target.value),placeholder:"e.g. Research the latest advancements in quantum computing, then design and build a small demo, test it, and document the result.",disabled:l,maxLength:ot,rows:t?3:5,"data-testid":"goal-input-textarea"}),e.jsxs("div",{className:"goal-input-footer",children:[e.jsxs("span",{className:"goal-input-counter","data-testid":"goal-input-counter",children:[n.length," / ",ot]}),e.jsxs(M,{variant:"primary",size:"md",onClick:c,loading:l,disabled:l||!n.trim(),"data-testid":"goal-input-submit",children:[e.jsx(rs,{size:14,"aria-hidden":!0}),l?"Planning…":"Generate plan"]})]})]})}function Ce({children:s,className:t,variant:a,onRemove:n,...i}){return e.jsxs("span",{className:W("tag",a?`tag-${a}`:void 0,t),...i,children:[s,n&&e.jsx("button",{type:"button",className:"tag-remove","aria-label":`Remove ${typeof s=="string"?s:"tag"}`,onClick:n,children:"×"})]})}function dd(s){if(!Number.isFinite(s)||s<0)return"—";const t=Math.floor(s/1e3),a=Math.floor(t/3600),n=Math.floor(t%3600/60),i=t%60;return a>0?`${a}h ${n}m`:n>0?`${n}m ${i}s`:`${i}s`}function md({plan:s}){return s?e.jsxs(G,{className:"plan-visualization","data-testid":"plan-visualization",children:[e.jsxs("div",{className:"plan-viz-header",children:[e.jsxs(ee,{children:[e.jsx(Ze,{size:14,"aria-hidden":!0})," Execution plan"]}),e.jsxs("div",{className:"plan-viz-badges",children:[e.jsxs(Ce,{variant:"info",children:[s.steps.length," steps"]}),e.jsxs(Ce,{variant:"accent",children:["Cost ",s.totalCost]}),e.jsxs(Ce,{variant:"success",children:[e.jsx(gs,{size:10,"aria-hidden":!0})," ",dd(s.totalDurationMs)]})]})]}),e.jsxs(te,{className:"plan-viz-goal",children:["Goal: ",s.goal]}),e.jsx("ol",{className:"plan-viz-tree",role:"tree",children:s.steps.map(t=>e.jsx(ud,{step:t},t.id))})]}):e.jsxs(G,{className:"plan-visualization",children:[e.jsx(ee,{children:"Execution plan"}),e.jsx(te,{children:"Submit a goal to generate a plan."})]})}function ud({step:s}){const[t,a]=r.useState(!1);return e.jsxs("li",{className:"plan-viz-row",role:"treeitem","aria-expanded":t,children:[e.jsxs("button",{type:"button",className:"plan-viz-row-head",onClick:()=>a(n=>!n),"data-testid":`plan-step-${s.id}`,children:[e.jsx("span",{className:"plan-viz-chevron",children:t?e.jsx(He,{size:14,"aria-hidden":!0}):e.jsx(ds,{size:14,"aria-hidden":!0})}),e.jsx("span",{className:W("plan-viz-action",`is-${s.action}`),children:s.action}),e.jsx("span",{className:"plan-viz-title",children:s.title}),e.jsxs("span",{className:"plan-viz-agent",children:["@",s.agent]}),e.jsx("span",{className:"plan-viz-cost",children:s.estimatedCost})]}),t&&e.jsxs("div",{className:"plan-viz-row-body","data-testid":`plan-step-${s.id}-body`,children:[e.jsx("p",{children:s.description}),s.deps.length>0&&e.jsxs("div",{className:"plan-viz-deps",children:[e.jsx("strong",{children:"Deps:"}),e.jsx("ul",{children:s.deps.map(n=>e.jsx("li",{children:e.jsx("code",{children:n})},n))})]}),e.jsxs("div",{className:"plan-viz-effects",children:[e.jsx("strong",{children:"Effects:"}),e.jsx("ul",{children:s.effects.map(n=>e.jsx("li",{children:e.jsx("code",{children:n})},n))})]})]})]})}function hd({data:s}){return e.jsxs("div",{className:`dep-node is-${s.action||"research"}`,children:[e.jsx(oa,{type:"target",position:ua.Left,className:"dep-handle"}),e.jsx("div",{className:"dep-node-action",children:s.action}),e.jsx("div",{className:"dep-node-label",children:s.label}),e.jsxs("div",{className:"dep-node-agent",children:["@",s.agent]}),e.jsx(oa,{type:"source",position:ua.Right,className:"dep-handle"})]})}const xd={step:hd};function pd({plan:s}){const t=r.useMemo(()=>{if(!s)return[];s.steps.length;const n=new Map,i=(c,u=new Set)=>{const x=n.get(c);if(x!==void 0)return x;if(u.has(c))return 0;u.add(c);const h=s.steps.find(d=>d.id===c);if(!h||h.deps.length===0)return n.set(c,0),u.delete(c),0;let m=0;for(const d of h.deps){const p=i(d,u);p>m&&(m=p)}return n.set(c,m+1),u.delete(c),m+1};for(const c of s.steps)i(c.id);const l=new Map;for(const c of s.steps){const u=n.get(c.id)??0,x=l.get(u)||[];x.push(c.id),l.set(u,x)}const o=[];for(const[c,u]of l){const x=u.length;u.forEach((h,m)=>{const d=s.steps.find(b=>b.id===h);if(!d)return;const p=60+c*220,f=40+(m-(x-1)/2)*90;o.push({id:d.id,type:"step",position:{x:p,y:f},data:{label:d.title,action:d.action,agent:d.agent}})})}return o},[s]),a=r.useMemo(()=>s?s.steps.flatMap(n=>n.deps.map(i=>({id:`${i}->${n.id}`,source:i,target:n.id,animated:!0}))):[],[s]);return s?s.steps.length===0?e.jsxs(G,{className:"dep-graph","data-testid":"dep-graph",children:[e.jsxs(ee,{children:[e.jsx(Ze,{size:14,"aria-hidden":!0})," Dependency graph"]}),e.jsx(te,{children:"Empty plan — nothing to render."})]}):e.jsxs(G,{className:"dep-graph","data-testid":"dep-graph",children:[e.jsxs("div",{className:"dep-graph-header",children:[e.jsxs(ee,{children:[e.jsx(Ze,{size:14,"aria-hidden":!0})," Dependency graph"]}),e.jsxs(Ce,{variant:"info",children:[s.steps.length," nodes"]}),e.jsxs(Ce,{variant:"accent",children:[a.length," edges"]})]}),e.jsxs(te,{children:["Plan step DAG · ",s.goal.slice(0,80)]}),e.jsx("div",{className:"dep-graph-canvas","data-testid":"dep-graph-canvas",children:e.jsxs(wn,{nodes:t,edges:a,nodeTypes:xd,fitView:!0,fitViewOptions:{padding:.15},proOptions:{hideAttribution:!0},children:[e.jsx(Sn,{gap:16,size:1}),e.jsx(Cn,{showInteractive:!1}),e.jsx(zn,{pannable:!0,zoomable:!0})]})})]}):e.jsxs(G,{className:"dep-graph","data-testid":"dep-graph",children:[e.jsxs(ee,{children:[e.jsx(Ze,{size:14,"aria-hidden":!0})," Dependency graph"]}),e.jsx(te,{children:"Submit a goal to render the dependency DAG."})]})}const gd=200;function fd(s){return s==="agent:status"?"status":s==="agent:restarted"?"restarted":s==="agent:stuck"?"stuck":s==="agent:message"?"message":"info"}function jd(s,t,a){const n=fd(s),i=`${a}-${Math.random().toString(36).slice(2,7)}`;if(s==="agent:message"){const c=(t==null?void 0:t.message)||t;return{id:i,ts:a,from:String((c==null?void 0:c.from)||"unknown"),to:String((c==null?void 0:c.to)||"unknown"),message:String((c==null?void 0:c.text)||(c==null?void 0:c.message)||JSON.stringify(c).slice(0,160)),kind:n,raw:t}}const l=(t==null?void 0:t.agent)||t,o=String((l==null?void 0:l.name)||"agent");return{id:i,ts:a,from:o,to:n==="stuck"?"orchestrator":"broadcast",message:`${s} ${l!=null&&l.status?`→ ${l.status}`:""}`.trim(),kind:n,raw:t}}function vd({maxRows:s=gd}){const[t,a]=r.useState([]);return r.useEffect(()=>{const n=new xs,i=n.on(l=>{const o=l.type;if(!o||!o.startsWith("agent:"))return;const c=l,u=Number(c.ts)||Date.now();a(x=>{const h=[...x,jd(o,c,u)];return h.length>s?h.slice(h.length-s):h})});return()=>{i(),n.close()}},[s]),e.jsxs(G,{className:"comm-log","data-testid":"communication-log",children:[e.jsxs("div",{className:"comm-log-header",children:[e.jsxs(ee,{children:[e.jsx(Js,{size:14,"aria-hidden":!0})," Communication log"]}),e.jsx(Ce,{variant:"neutral","data-testid":"communication-log-count",children:t.length})]}),e.jsxs(te,{children:["Inter-agent message bus trace · bounded to ",s," rows"]}),e.jsxs("ul",{className:"comm-log-list","data-testid":"communication-log-list",children:[t.length===0&&e.jsx("li",{className:"comm-log-empty","data-testid":"communication-log-empty",children:"No agent messages yet. Stream will appear here live."}),t.slice().reverse().map(n=>e.jsxs("li",{className:`comm-log-row is-${n.kind}`,"data-testid":"communication-log-row","data-kind":n.kind,children:[e.jsxs("div",{className:"comm-log-row-meta",children:[e.jsx("span",{className:"comm-log-from",children:n.from}),e.jsx(Xa,{size:12,"aria-hidden":!0}),e.jsx("span",{className:"comm-log-to",children:n.to}),e.jsx(Ce,{variant:"neutral",className:`comm-log-kind is-${n.kind}`,children:n.kind}),e.jsx("time",{className:"comm-log-time",dateTime:new Date(n.ts).toISOString(),children:new Date(n.ts).toLocaleTimeString()})]}),e.jsx("div",{className:"comm-log-message",children:n.message})]},n.id))]})]})}const Pt=500;function bd(s){return s.startsWith("goal:")?"success":s.startsWith("task:")?"info":s.includes("error")||s.includes("fail")?"error":s.includes("stuck")||s.includes("blocked")||s.includes("warn")?"warning":s==="ping"||s==="pong"||s==="refresh"?"control":"info"}function yd(s,t){return t&&Object.keys(t).slice(0,3).map(n=>`${n}=${Nd(t[n])}`).join(" ")||s}function Nd(s){return s==null?"null":typeof s=="string"?s.length>20?`"${s.slice(0,20)}…"`:`"${s}"`:typeof s=="number"||typeof s=="boolean"?String(s):Array.isArray(s)?`[${s.length}]`:typeof s=="object"?`{${Object.keys(s).length}}`:String(s)}function kd(){const[s,t]=r.useState([]);r.useEffect(()=>{const n=new xs,i=n.on(l=>{const o=l,c=o.type;if(!c)return;const u=Number(o.ts)||Date.now(),x={id:`${u}-${Math.random().toString(36).slice(2,7)}`,ts:u,type:c,severity:bd(c),preview:yd(c,o)};t(h=>{const m=[...h,x];return m.length>Pt?m.slice(m.length-Pt):m})});return()=>{i(),n.close()}},[]);const a=r.useMemo(()=>{const n={info:0,success:0,warning:0,error:0,control:0};for(const i of s)n[i.severity]+=1;return n},[s]);return e.jsxs(G,{className:"event-log","data-testid":"event-log",children:[e.jsxs("div",{className:"event-log-header",children:[e.jsxs(ee,{children:[e.jsx(Ae,{size:14,"aria-hidden":!0})," Real-time events"]}),e.jsx(Ce,{variant:"neutral","data-testid":"event-log-count",children:s.length})]}),e.jsxs(te,{children:["Live WebSocket event ticker · bounded to ",Pt," rows"]}),e.jsxs("div",{className:"event-log-summary","data-testid":"event-log-summary",children:[e.jsxs(Ce,{variant:"info",children:["info ",a.info]}),e.jsxs(Ce,{variant:"success",children:["success ",a.success]}),e.jsxs(Ce,{variant:"warning",children:["warning ",a.warning]}),e.jsxs(Ce,{variant:"error",children:["error ",a.error]}),e.jsxs(Ce,{variant:"neutral",children:["control ",a.control]})]}),e.jsxs("ul",{className:"event-log-list","data-testid":"event-log-list",children:[s.length===0&&e.jsx("li",{className:"event-log-empty","data-testid":"event-log-empty",children:"No events yet. Events will stream here as the server emits them."}),s.slice().reverse().map(n=>e.jsxs("li",{className:`event-log-row is-${n.severity}`,"data-testid":"event-log-row","data-severity":n.severity,children:[e.jsx("time",{className:"event-log-time",dateTime:new Date(n.ts).toISOString(),children:new Date(n.ts).toLocaleTimeString()}),e.jsx("code",{className:"event-log-type",children:n.type}),e.jsx("span",{className:"event-log-preview",children:n.preview})]},n.id))]})]})}function wd(s){const t=s.compileCheck?{name:"Compile check",status:"passed",value:!0,threshold:!0,detail:"make check is green."}:{name:"Compile check",status:"failed",value:!1,threshold:!0,detail:"Typecheck error — fix before marking passing."},a=s.testCoverage>=80?{name:"Test coverage",status:"passed",value:s.testCoverage,threshold:80,detail:"Coverage meets the B-grade threshold."}:s.testCoverage>=60?{name:"Test coverage",status:"warning",value:s.testCoverage,threshold:80,detail:"Coverage is below the B-grade threshold."}:{name:"Test coverage",status:"failed",value:s.testCoverage,threshold:80,detail:"Coverage is critical."},n=s.archScore>=90?{name:"Arch compliance",status:"passed",value:s.archScore,threshold:90,detail:"All non-trivial arch-rules satisfied."}:s.archScore>=70?{name:"Arch compliance",status:"warning",value:s.archScore,threshold:90,detail:"Minor arch-rule violations."}:{name:"Arch compliance",status:"failed",value:s.archScore,threshold:90,detail:"Multiple arch-rule violations."},i=s.evidencePresent?{name:"Verification evidence",status:"passed",value:!0,threshold:!0,detail:"Test output + commit hash captured."}:{name:"Verification evidence",status:"failed",value:!1,threshold:!0,detail:"No evidence recorded yet."};return[t,a,n,i]}function Sd({status:s}){return s==="passed"?e.jsx(_e,{size:14,className:"qg-icon is-pass"}):s==="warning"?e.jsx(Me,{size:14,className:"qg-icon is-warn"}):e.jsx(vs,{size:14,className:"qg-icon is-fail"})}function Cd({status:s}){return s==="passed"?e.jsx(Ce,{variant:"success",children:"passed"}):s==="warning"?e.jsx(Ce,{variant:"warning",children:"warning"}):e.jsx(Ce,{variant:"error",children:"failed"})}function zd({plan:s,metrics:t}){const a=wd(t),n=a.filter(i=>i.status==="passed").length;return e.jsxs(G,{className:"qg-panel","data-testid":"quality-gates",children:[e.jsxs("div",{className:"qg-header",children:[e.jsxs(ee,{children:[e.jsx(fs,{size:14,"aria-hidden":!0})," Quality gates"]}),e.jsxs(Ce,{variant:n===a.length?"success":n>0?"warning":"error",children:[n,"/",a.length," passing"]})]}),e.jsxs(te,{children:["L09 rubric (Correctness / Arch compliance / Test coverage / Verification evidence) —"," ",s?`evaluating against plan with ${s.steps.length} steps.`:"awaiting plan."]}),e.jsx("ul",{className:"qg-list","data-testid":"quality-gates-list",children:a.map(i=>e.jsxs("li",{className:`qg-row is-${i.status}`,"data-testid":"quality-gates-row","data-status":i.status,children:[e.jsxs("div",{className:"qg-row-head",children:[e.jsx(Sd,{status:i.status}),e.jsx("span",{className:"qg-name",children:i.name}),e.jsx(Cd,{status:i.status})]}),e.jsxs("div",{className:"qg-row-body",children:[e.jsx("span",{className:"qg-detail",children:i.detail}),typeof i.value=="number"&&e.jsxs("span",{className:"qg-threshold",children:["current: ",i.value,"% · threshold: ",i.threshold,"%"]}),typeof i.value=="boolean"&&e.jsxs("span",{className:"qg-threshold",children:["current: ",String(i.value)," · threshold: ",String(i.threshold)]})]})]},i.name))})]})}const $d={compileCheck:"compile-check",testCoverage:"unit",archScore:"check-arch",evidencePresent:"e2e"};function Rd(s){const[t,a]=r.useState(null),[n,i]=r.useState(!1),[l,o]=r.useState(0),[c,u]=r.useState(0),[x,h]=r.useState(!1);return r.useEffect(()=>{const m=new xs,d=m.on(p=>{switch(p.type){case"task:progress":o(b=>Ia(b+5,0,100)),h(!0);break;case"tasks:change":h(!0);break;case"goal:planned":i(!0),o(b=>b<25?25:b),u(b=>b<30?30:b),h(!0);break;case"agents:change":case"agent:status":u(b=>Ia(b+2,0,100));break}});return()=>{d(),m.close()}},[]),e.jsxs("div",{className:"goal-planner-page","data-testid":"goal-planner-page",children:[e.jsxs("header",{className:"goal-planner-header",children:[e.jsxs("div",{className:"goal-planner-title-row",children:[e.jsx(Xt,{size:20,"aria-hidden":!0}),e.jsx("h2",{children:"Goal Planner"}),e.jsx("span",{className:"badge badge-info","data-testid":"goal-planner-version",children:"v6.4.0"})]}),e.jsxs("p",{className:"goal-planner-blurb",children:[e.jsx(es,{size:12,"aria-hidden":!0})," Type a goal in plain English. We decompose it into clauses, map each clause to a Bizar action template, and run A* over the action space to produce an executable plan. The four panels below update in real time as the harness streams events."]})]}),e.jsxs("div",{className:"goal-planner-grid",children:[e.jsx("section",{className:"goal-planner-input-row",children:e.jsx(od,{onPlan:a})}),e.jsx("section",{className:"goal-planner-plan-row",children:e.jsx(md,{plan:t})}),e.jsx("section",{className:"goal-planner-panel-row",children:e.jsx(pd,{plan:t})}),e.jsx("section",{className:"goal-planner-panel-row",children:e.jsx(vd,{})}),e.jsx("section",{className:"goal-planner-panel-row",children:e.jsx(kd,{})}),e.jsx("section",{className:"goal-planner-panel-row",children:e.jsx(zd,{plan:t,metrics:{compileCheck:n,testCoverage:l,archScore:c,evidencePresent:x}})})]}),e.jsx("footer",{className:"goal-planner-footer",children:e.jsxs(G,{children:[e.jsx(ee,{children:"How this works"}),e.jsxs(te,{children:["Rubric dimensions: ",Object.values($d).join(" · "),". The dependency graph uses @xyflow/react; the message bus and event ticker subscribe to the shared WebSocket feed (never a second connection)."]})]})})]})}function Ia(s,t,a){return Math.max(t,Math.min(a,s))}function Td(s){return e.jsx(Rd,{...s})}const Ft={overview:Ir,chat:Xr,agents:Jr,artifacts:Sl,memory:mo,tasks:_l,activity:Hl,background:_o,config:wa,settings:wa,mods:pc,schedules:$c,skills:Dc,history:ho,minimax:No,doctor:Qo,harness:Zo,eval:ad,evalReport:cd,"goal-planner":Td},Ad="v6.0.0";function Md(s,t,a,n){if(Ft[s]){const o=Ft[s];return e.jsx(o,{...t})}const i=a.find(o=>o.id===s);if(i)return e.jsx(fc,{viewId:i.id,reloadKey:n,activeTab:t.activeTab,setActiveTab:t.setActiveTab});const l=Ft.overview;return e.jsx(l,{...t})}function Id({onSaved:s}){const[t,a]=r.useState(""),n=r.useRef(null);r.useEffect(()=>{var o;(o=n.current)==null||o.focus()},[]);const i=()=>{const o=t.trim();o&&($.setToken(o),s())},l=o=>{o.key==="Escape"&&(o.preventDefault(),s()),o.key==="Enter"&&(o.preventDefault(),i())};return e.jsxs("form",{className:"token-entry-form",onSubmit:o=>{o.preventDefault(),i()},children:[e.jsxs("div",{className:"token-entry-row",children:[e.jsx("input",{ref:n,type:"password",className:"input mono",value:t,onChange:o=>a(o.target.value),placeholder:"Paste auth token",spellCheck:!1,autoComplete:"off",onKeyDown:l}),e.jsx(M,{type:"submit",variant:"primary",size:"sm",disabled:!t.trim(),children:"Save & retry"})]}),e.jsxs("p",{className:"token-entry-hint",children:["Where do I find this token? Check the file"," ",e.jsx("code",{children:"~/.config/bizar/dashboard-secret"})," on the machine running the dashboard, or look for it in the server output."]})]})}function Ed(){return e.jsx(Ai,{children:e.jsx(Pi,{children:e.jsx(Ld,{})})})}function Ld(){var re,xe,fe;const s=ce(),t=Pe(),{isModalOpen:a}=t,n=r.useRef(!1),[i,l]=r.useState("overview"),[o,c]=r.useState(null),[u,x]=r.useState(null),[h,m]=r.useState("connecting"),[d,p]=r.useState(null),[f,b]=r.useState(!1),[k,w]=r.useState(null),[v,C]=r.useState(!1),[z,y]=r.useState(!1),[R,S]=r.useState([]),[N,P]=r.useState(!1),[g,j]=r.useState([]),[T,F]=r.useState(0),A=r.useRef(null),[U,Y]=r.useState(null);r.useEffect(()=>{let L=!1;return(async()=>{try{const H=await $.get("/mods/views");if(L)return;j(H.views||[])}catch{L||j([])}})(),()=>{L=!0}},[T,o==null?void 0:o.mods]),r.useEffect(()=>{if(!U)return;const L=U.on(H=>{((H==null?void 0:H.type)==="mod:change"||(H==null?void 0:H.type)==="mod:enabled"||(H==null?void 0:H.type)==="mod:installed")&&F(q=>q+1)});return()=>L()},[U]),r.useEffect(()=>{u!=null&&u.theme&&(qs(u.theme),Cs(u.theme))},[u==null?void 0:u.theme]),r.useEffect(()=>{n.current=a},[a]),r.useEffect(()=>{var q;if(((q=u==null?void 0:u.theme)==null?void 0:q.mode)!=="system")return;const L=window.matchMedia("(prefers-color-scheme: light)"),H=()=>qs(u.theme.mode);return L.addEventListener("change",H),()=>L.removeEventListener("change",H)},[(re=u==null?void 0:u.theme)==null?void 0:re.mode]);const B=r.useCallback(async()=>{let L=!1;const H=()=>Promise.all([$.get("/snapshot").catch(()=>null),$.get("/settings").catch(()=>null),$.get("/agents/stuck").catch(()=>null)]),q=(Z,le,se)=>{Z&&c(Z),le!=null&&le.data&&x(le.data),se!=null&&se.stuck&&S(se.stuck)};try{const Z=await $.probeAuthStatus(),[le,se,ue]=await H();if(q(le,se,ue),le||se){p(null);return}if(!Z.loopback){p("Dashboard server unreachable.");return}await new Promise(bs=>setTimeout(bs,1e3));const[Le,Ve,De]=await H();q(Le,Ve,De),!Le&&!Ve&&p("Dashboard server unreachable.")}catch(Z){const le=(Z==null?void 0:Z.message)??"unknown error";if(Z instanceof Nn&&Z.status===401){p(le),C(!0),s.error(`Auth required: ${le}`);return}p(le),s.error(`Failed to load: ${le}`)}},[s]);r.useEffect(()=>{let L=!1;const H=setTimeout(()=>{L||B()},0);return()=>{L=!0,clearTimeout(H)}},[B]),r.useEffect(()=>{let L=!1;return $.get("/settings").then(H=>{var Z,le;if(L)return;const q=(le=(Z=H==null?void 0:H.data)==null?void 0:Z.ui)==null?void 0:le.defaultTab;q&&l(q)}).catch(()=>{}),()=>{L=!0}},[]),r.useEffect(()=>{let L=!1;const H=async()=>{try{const Z=await $.get("/agents/stuck");L||S(le=>{const se=Z.stuck||[];return le.length===0&&se.length>0&&s.warning(`${se.length} agent${se.length===1?"":"s"} stuck`,5e3),se})}catch{}},q=setInterval(H,3e4);return H(),()=>{L=!0,clearInterval(q)}},[]),r.useEffect(()=>{const L=new xs;A.current=L,Y(L);const H=L.onStatus(Z=>m(Z)),q=L.on(Z=>{var le;if(Z.type==="snapshot"&&"data"in Z&&Z.data)c(se=>({...se??{},...Z.data}));else if(Z.type==="change"){const se=Z,ue=((le=se.path)==null?void 0:le.split("/").pop())||se.path||"";s.info(`File changed: ${ue}`,2500)}else if(Z.type==="tasks:change"){const se=Z;c(ue=>{if(!ue)return ue;const Le=(ue.tasks||[]).map(De=>De.id===se.task.id?se.task:De),Ve=Le.some(De=>De.id===se.task.id);return{...ue,tasks:Ve?Le:[se.task,...Le]}})}else if(Z.type==="tasks:delete"){const se=Z;c(ue=>ue&&{...ue,tasks:(ue.tasks||[]).filter(Le=>Le.id!==se.id)})}else if(Z.type==="settings:change"){const se=Z;se.settings&&x(se.settings)}else if(Z.type==="project:change")$.get("/snapshot").then(se=>c(ue=>({...ue??{},...se}))).catch(()=>{});else if(Z.type==="agents:change"||Z.type==="schedules:change")$.get("/snapshot").then(se=>c(ue=>({...ue??{},...se}))).catch(()=>{});else if(Z.type==="agent:status"||Z.type==="agent:restarted"){const se=Z;c(ue=>{if(!ue)return ue;const Le=(ue.agents||[]).map(Ve=>Ve.name===se.agent.name?se.agent:Ve);return{...ue,agents:Le}})}else if(Z.type==="artifact:change")$.get("/artifacts").then(se=>{c(ue=>ue&&{...ue,artifacts:se.artifacts||[]})}).catch(()=>{});else if(Z.type==="agent:stuck")S(Z.agents||[]);else if(Z.type==="dialog:show"){const se=Z;se.dialog&&t.open({title:se.dialog.title,width:520,children:e.jsx(ur,{dialog:se.dialog,onClose:()=>t.close()})})}});return()=>{H(),q(),L.close(),Y(null)}},[s]);const K=r.useCallback(L=>U?U.on(L):()=>{},[U]),D=r.useRef(0);r.useEffect(()=>{const L=()=>{D.current=Date.now()+1500};return document.addEventListener("mousedown",L,!0),document.addEventListener("click",L,!0),document.addEventListener("focusin",L,!0),document.addEventListener("keydown",L,!0),()=>{document.removeEventListener("mousedown",L,!0),document.removeEventListener("click",L,!0),document.removeEventListener("focusin",L,!0),document.removeEventListener("keydown",L,!0)}},[]),r.useEffect(()=>{const L={};Ut.forEach((q,Z)=>{L[String(Z+1)]=q.id});const H=q=>{var bs,Ds,st,_s;if((q.metaKey||q.ctrlKey)&&q.key.toLowerCase()==="k"){q.preventDefault(),y(!0);return}if(q.key==="/"&&!q.metaKey&&!q.ctrlKey){const tt=(Ds=(bs=q.target)==null?void 0:bs.tagName)==null?void 0:Ds.toLowerCase();if(tt!=="input"&&tt!=="textarea"&&!((st=q.target)!=null&&st.isContentEditable)){q.preventDefault(),y(!0);return}}const Z=document.activeElement;if(!Z||Z===document.body||Z===document.documentElement)return;const se=q.target,ue=(_s=se==null?void 0:se.tagName)==null?void 0:_s.toLowerCase(),Le=ue==="input"||ue==="textarea"||ue==="select"||ue==="button"||ue==="option"||ue==="label"||!!(se!=null&&se.isContentEditable);let Ve=!1;if(se&&typeof se.closest=="function"&&(Ve=!!se.closest('form, [role="dialog"], [contenteditable], [data-no-key]')),q.repeat||n.current||Le||Ve||q.metaKey||q.ctrlKey||q.altKey||q.shiftKey||Date.now()<D.current)return;const De=L[q.key];De&&(q.preventDefault(),ae(De))};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[]);const _=r.useMemo(()=>async()=>{try{const L=await $.get("/snapshot");c(H=>({...H??{},...L}))}catch(L){s.error(`Refresh failed: ${L.message}`)}},[s]),ae=r.useCallback(L=>{l(L),b(L==="settings")},[]),J=r.useMemo(()=>{const L=g.map(H=>({id:H.id,label:H.label,icon:H.kind==="iframe"?Ks:Xs,isMod:!0,modId:H.modId}));return[...Ut,...L]},[g]),ne=r.useMemo(()=>({state:"active",label:"in-process",detail:"ClineCore running in-process (v6.0.0, no subprocess)"}),[]),I=r.useMemo(()=>o&&u?Md(i,{snapshot:o,settings:u,activeTab:i,setActiveTab:ae,refreshSnapshot:_,settingsMode:f,settingsActiveSection:k,setSettingsActiveSection:w},g,T):null,[i,o,u,g,T,_,f,k,w,ae]),V=async()=>{try{const L=await $.get("/projects");c(H=>{var q;return H&&{...H,projects:L.projects||[],activeProject:((q=L.projects)==null?void 0:q.find(Z=>Z.id===L.active))||null}})}catch(L){s.error(`Projects refresh failed: ${L.message}`)}},ie=async L=>{try{await $.post(`/projects/${encodeURIComponent(L)}/activate`),c(H=>H&&{...H,activeProject:H.projects.find(q=>q.id===L)||null})}catch(H){s.error(`Activate failed: ${H.message}`)}},de=L=>{const H=L.type;if(H==="agent")ae("agents");else if(H==="task")ae("tasks");else if(H==="mod")ae("mods");else if(H==="schedule")ae("schedules");else if(H==="project"){const q=L.item.id;ie(q)}else if(H==="command")s.info(`/${L.item.name} — run from the TUI`,2500);else if(H==="setting"){const q=L.item.id||L.item.path||"";ae("settings");const Z=le=>{if(le<=0)return;const se=q?document.querySelector(`[data-setting-id="${CSS.escape(q)}"]`):null;se?(se.scrollIntoView({behavior:"smooth",block:"center"}),se.classList.remove("setting-flash"),se.offsetWidth,se.classList.add("setting-flash"),window.setTimeout(()=>se.classList.remove("setting-flash"),1500)):window.setTimeout(()=>Z(le-1),80)};window.setTimeout(()=>Z(15),60)}},O=((xe=u==null?void 0:u.ui)==null?void 0:xe.layout)||"topnav",Q=((fe=u==null?void 0:u.ui)==null?void 0:fe.showHeader)!==!1;return e.jsxs("div",{className:"app","data-layout":O,"data-active-tab":i,children:[e.jsx("a",{className:"skip-to-main",href:"#main-content",children:"Skip to main content"}),Q&&e.jsx(Yi,{activeTab:i,onTabChange:ae,wsStatus:h,version:Ad,activeProject:(o==null?void 0:o.activeProject)||null,projects:(o==null?void 0:o.projects)||[],onProjectChange:ie,onProjectsRefresh:V,onOpenSearch:()=>y(!0),settings:u,notificationsSlot:e.jsx(nr,{wsSubscribe:K}),showTabs:O==="topnav",extraTabs:J,clineStatus:ne}),R.length>0&&!N&&e.jsxs("div",{className:"stuck-banner",role:"alert",children:[e.jsx(Me,{size:16}),e.jsxs("span",{children:[e.jsx("strong",{children:R.length})," agent",R.length===1?"":"s"," stuck:"," ",e.jsx("span",{className:"mono",children:R.map(L=>L.name).join(", ")})]}),e.jsx(M,{variant:"secondary",size:"sm",onClick:()=>{ae("agents"),P(!0)},children:"Review"}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Dismiss",onClick:()=>P(!0),children:e.jsx(we,{size:14})})]}),e.jsxs("div",{className:"layout-body",children:[O!=="topnav"&&e.jsx(er,{tabs:J,activeTab:i,onTabChange:ae,settingsMode:f,settingsActiveSection:k,onSettingsSectionChange:w,onExitSettings:()=>ae("overview")}),e.jsxs("main",{className:"content",id:"main-content",tabIndex:-1,children:[d&&e.jsxs("div",{className:"boot-error",children:[e.jsx("h2",{children:"Dashboard unavailable"}),e.jsx("p",{children:d}),v&&e.jsx(Id,{onSaved:()=>{C(!1),B()}}),e.jsxs("p",{className:"boot-error-hint",children:["Make sure the Bizar dashboard server is running. Try"," ",e.jsx("code",{children:"bizar-dash start"})," in your terminal."]})]}),!d&&(!o||!u)&&e.jsxs("div",{className:"loading",children:[e.jsx(he,{size:"lg"}),e.jsx("p",{children:"Loading Bizar…"})]}),I&&e.jsx(r.Suspense,{fallback:e.jsxs("div",{className:"loading",children:[e.jsx(he,{size:"lg"}),e.jsx("p",{children:"Loading…"})]}),children:e.jsx(Dd,{children:I})})]})]}),e.jsx(sr,{open:z,onClose:()=>y(!1),onSelect:de})]})}class Dd extends r.Component{constructor(){super(...arguments);Ps(this,"state",{err:null});Ps(this,"reset",()=>this.setState({err:null}))}static getDerivedStateFromError(a){return{err:a}}componentDidCatch(a,n){is.error("[ViewErrorBoundary] caught render error:",a,n==null?void 0:n.componentStack)}render(){return this.state.err?e.jsxs("div",{className:"view-error-fallback",role:"alert",children:[e.jsx(Me,{size:20}),e.jsxs("div",{className:"view-error-body",children:[e.jsx("strong",{children:"This view crashed."}),e.jsx("pre",{children:this.state.err.message}),e.jsx(M,{variant:"secondary",size:"sm",onClick:this.reset,children:"Retry"})]})]}):this.props.children}}function _d(){const[s,t]=r.useState(()=>typeof window>"u"?!1:window.matchMedia("(max-width: 767px)").matches);return r.useEffect(()=>{const a=window.matchMedia("(max-width: 767px)"),n=i=>t(i.matches);return a.addEventListener("change",n),()=>a.removeEventListener("change",n)},[]),s?e.jsx(kn,{}):e.jsx(Ed,{})}const xn=document.getElementById("root");if(!xn)throw new Error("Root element #root not found");$n(xn).render(e.jsx(r.StrictMode,{children:e.jsx(_d,{})}));
|