@polderlabs/bizar 5.2.0 → 5.3.0
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/{MobileChat-TCputYzr.js → MobileChat-OidrxXR9.js} +1 -1
- package/bizar-dash/dist/assets/{MobileChat-TCputYzr.js.map → MobileChat-OidrxXR9.js.map} +1 -1
- package/bizar-dash/dist/assets/{MobileSettings-BxcbL5XT.js → MobileSettings-B91gVFii.js} +1 -1
- package/bizar-dash/dist/assets/{MobileSettings-BxcbL5XT.js.map → MobileSettings-B91gVFii.js.map} +1 -1
- package/bizar-dash/dist/assets/{icons-DRDXfbBP.js → icons-Bd8piSb2.js} +18 -13
- package/bizar-dash/dist/assets/icons-Bd8piSb2.js.map +1 -0
- package/bizar-dash/dist/assets/{main-xFpWMd32.css → main-3G6mOhiK.css} +1 -1
- package/bizar-dash/dist/assets/main-6YUZY968.js +19 -0
- package/bizar-dash/dist/assets/main-6YUZY968.js.map +1 -0
- package/bizar-dash/dist/assets/{mobile-j3rOZK6v.js → mobile-CSsp30lr.js} +2 -2
- package/bizar-dash/dist/assets/{mobile-j3rOZK6v.js.map → mobile-CSsp30lr.js.map} +1 -1
- package/bizar-dash/dist/assets/{mobile--17fkfrl.js → mobile-DtwK7DOV.js} +1 -1
- package/bizar-dash/dist/assets/{mobile--17fkfrl.js.map → mobile-DtwK7DOV.js.map} +1 -1
- package/bizar-dash/dist/assets/{useSlashCommands-BG-DhEck.js → useSlashCommands-DEkxEvOO.js} +2 -2
- package/bizar-dash/dist/assets/{useSlashCommands-BG-DhEck.js.map → useSlashCommands-DEkxEvOO.js.map} +1 -1
- package/bizar-dash/dist/index.html +5 -5
- package/bizar-dash/dist/mobile.html +3 -3
- package/bizar-dash/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -1
- package/bizar-dash/src/server/eval-store.mjs +55 -0
- package/bizar-dash/src/server/eval.mjs +63 -0
- package/bizar-dash/src/server/plugins/permission-audit.mjs +109 -0
- package/bizar-dash/src/server/plugins/sandbox.mjs +76 -2
- package/bizar-dash/src/server/plugins/store.mjs +4 -0
- package/bizar-dash/src/server/routes/eval.mjs +42 -2
- package/bizar-dash/src/server/routes/plugins.mjs +44 -4
- package/bizar-dash/src/server/schedules-runner.mjs +61 -0
- package/bizar-dash/src/web/components/EvalExportButton.tsx +27 -0
- package/bizar-dash/src/web/components/InstallConfirmDialog.tsx +62 -0
- package/bizar-dash/src/web/components/MarketplacePluginCard.tsx +51 -0
- package/bizar-dash/src/web/components/PluginCard.tsx +2 -2
- package/bizar-dash/src/web/components/PluginPermissions.tsx +1 -1
- package/bizar-dash/src/web/components/ScheduleTemplateCard.tsx +1 -0
- package/bizar-dash/src/web/components/Topbar.tsx +3 -0
- package/bizar-dash/src/web/components/VoiceNotesPanel.tsx +28 -0
- package/bizar-dash/src/web/styles/main.css +139 -0
- package/bizar-dash/src/web/views/Doctor.tsx +3 -3
- package/bizar-dash/src/web/views/Eval.tsx +225 -25
- package/bizar-dash/src/web/views/EvalReport.tsx +7 -3
- package/bizar-dash/src/web/views/Marketplace.tsx +135 -0
- package/bizar-dash/src/web/views/Plugins.tsx +9 -3
- package/bizar-dash/src/web/views/Schedules.tsx +1 -1
- package/bizar-dash/tests/a11y/components.test.tsx +149 -0
- package/bizar-dash/tests/a11y/forms.test.tsx +191 -0
- package/bizar-dash/tests/a11y/navigation.test.tsx +112 -0
- package/bizar-dash/tests/components/marketplace-plugin-card.test.tsx +144 -0
- package/bizar-dash/tests/eval-csv.test.mjs +67 -0
- package/bizar-dash/tests/eval-scheduled.test.mjs +84 -0
- package/bizar-dash/tests/plugins-permissions.test.mjs +525 -0
- package/package.json +1 -1
- package/bizar-dash/dist/assets/icons-DRDXfbBP.js.map +0 -1
- package/bizar-dash/dist/assets/main-D5Ditnrd.js +0 -19
- package/bizar-dash/dist/assets/main-D5Ditnrd.js.map +0 -1
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
var Ka=Object.defineProperty;var Ga=(s,t,a)=>t in s?Ka(s,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):s[t]=a;var Cs=(s,t,a)=>Ga(s,typeof t!="symbol"?t+"":t,a);import{a as R,c as V,f as ze,b as We,S as me,t as ra,e as Ya,p as Xa,W as Rt,_ as la,d as fs,g as As,A as Qa,M as Ja}from"./mobile-j3rOZK6v.js";import{r,j as e,a as oa,R as Le,b as Za}from"./react-vendor-Dn4wqh4Z.js";import{X as be,A as Tt,R as le,F as en,H as sn,a as tn,C as st,b as Oe,c as an,d as Be,e as Ge,L as ca,M as tt,B as Qe,f as Xs,S as Ms,g as $e,h as nn,i as He,j as Fe,P as is,k as Is,l as Ls,m as $t,n as as,o as da,p as At,q as pe,r as rn,s as Re,t as ma,u as _t,T as rs,v as ln,w as qs,G as on,x as ua,y as cn,z as ls,D as ke,E as Ve,I as at,J as ms,K as we,N as os,O as Qs,Q as cs,U as Je,V as Js,W as dn,Y as Se,Z as Mt,_ as nt,$ as js,a0 as mn,a1 as it,a2 as ys,a3 as un,a4 as Ns,a5 as Ke,a6 as ha,a7 as xa,a8 as Es,a9 as hn,aa as ks,ab as xn,ac as pn,ad as gn,ae as ns,af as fn,ag as jn,ah as vn,ai as yn,aj as bn,ak as Nn,al as Wt,am as pa,an as It,ao as kn,ap as wn,aq as ga,ar as Sn,as as Cn,at as zn,au as Rn,av as Tn,aw as $n,ax as An,ay as vs,az as Mn,aA as In,aB as Ds,aC as Ln,aD as Lt,aE as Os,aF as ds,aG as fa,aH as bs,aI as ja,aJ as En,aK as Dn,aL as Zs,aM as Pn,aN as va,aO as Ps,aP as Fn,aQ as On,aR as ya,aS as ba,aT as Fs,aU as kt,aV as Et,aW as Na,aX as xe,aY as Bn,aZ as Un,a_ as ka,a$ as _n,b0 as Wn,b1 as wa,b2 as lt,b3 as Sa,b4 as Dt,b5 as Vn,b6 as Hn,b7 as Ca,b8 as qn,b9 as Kn,ba as Gn,bb as Yn,bc as za}from"./icons-DRDXfbBP.js";import{u as re,V as Pt,C as Xn,a as Qn,b as Jn,c as Zn,d as ei,T as si}from"./useSlashCommands-BG-DhEck.js";import{M as Ra,r as Ta}from"./markdown-C6mXtQxD.js";import"./vendor-CeHGtduv.js";const $a=r.createContext(null),ti=["button:not([disabled])","[href]","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(", ");function Ae(){const s=r.useContext($a);return s||{open:()=>"",close:()=>{},isModalOpen:!1}}function ai({children:s}){const[t,a]=r.useState([]),i=r.useCallback(c=>{a(o=>{if(!c)return o.slice(0,-1);const l=o.findIndex(u=>u.id===c);return l===-1||l!==o.length-1?o:o.slice(0,-1)})},[]),n=r.useCallback(c=>{const o=`m${Math.random().toString(36).slice(2,9)}`;return a(l=>[...l,{...c,id:o}]),o},[]);return r.useEffect(()=>{if(t.length===0)return;const c=o=>{o.key==="Escape"&&(o.stopPropagation(),i())};return document.addEventListener("keydown",c),()=>document.removeEventListener("keydown",c)},[t.length,i]),e.jsxs($a.Provider,{value:{open:n,close:i,isModalOpen:t.length>0},children:[s,typeof document<"u"&&oa.createPortal(e.jsx("div",{className:"modal-stack","aria-hidden":t.length===0,children:t.map((c,o)=>e.jsx(ni,{modal:c,onClose:()=>{var l;(l=c.onClose)==null||l.call(c),i(c.id)},depth:o},c.id))}),document.body)]})}function ni({modal:s,onClose:t,depth:a}){const i=r.useRef(null),n=r.useRef(null),c=r.useId(),o=()=>{const l=i.current;return l?Array.from(l.querySelectorAll(ti)).filter(u=>!u.hasAttribute("disabled")&&u.tabIndex!==-1):[]};return r.useEffect(()=>{var x;n.current=document.activeElement instanceof HTMLElement?document.activeElement:null,(x=o()[0]??i.current)==null||x.focus();const u=h=>{var j,v,k;if(h.key!=="Tab")return;const d=o();if(d.length===0){h.preventDefault(),(j=i.current)==null||j.focus();return}const m=d[0],p=d[d.length-1],g=document.activeElement instanceof HTMLElement?document.activeElement:null;if(h.shiftKey){(!g||g===m||!((v=i.current)!=null&&v.contains(g)))&&(h.preventDefault(),p.focus());return}(!g||g===p||!((k=i.current)!=null&&k.contains(g)))&&(h.preventDefault(),m.focus())};return document.addEventListener("keydown",u),()=>{document.removeEventListener("keydown",u);const h=n.current;h&&h.isConnected&&h.focus()}},[]),e.jsx("div",{className:"modal-backdrop",onClick:l=>{l.stopPropagation(),l.target===l.currentTarget&&t()},style:a>0?{background:"rgba(0,0,0,0.4)"}:void 0,children:e.jsxs("div",{ref:i,className:"modal",role:"dialog","aria-modal":"true","aria-labelledby":s.title?c:void 0,tabIndex:-1,onClick:l=>l.stopPropagation(),style:s.width?{maxWidth:s.width}:void 0,children:[s.title&&e.jsxs("header",{className:"modal-header",children:[e.jsx("h2",{id:c,className:"modal-title",children:s.title}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Close",onClick:t,children:e.jsx(be,{size:16})})]}),e.jsx("div",{className:"modal-body",children:s.children}),s.footer&&e.jsx("footer",{className:"modal-footer",children:s.footer})]})})}const ii=200,ri=5*60*1e3,ts=new Map;function li(s){const t=ts.get(s);return t?Date.now()-t.ts>ri?(ts.delete(s),null):t.data:null}function ot(s,t){ts.size>=ii&&[...ts.entries()].sort((i,n)=>i[1].ts-n[1].ts).slice(0,50).map(([i])=>i).forEach(i=>ts.delete(i)),ts.set(s,{data:t,ts:Date.now()})}function oi(s){if(!s||s==="/")return[{label:"/",path:"/"}];const t=s.split("/").filter(Boolean),a=[];let i="";for(let n=0;n<t.length;n++)i+="/"+t[n],a.push({label:t[n],path:i});return a}function ci(s){return[...s].sort((t,a)=>t.isDir!==a.isDir?t.isDir?-1:1:t.name.localeCompare(a.name,void 0,{sensitivity:"base"}))}function di(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 Aa({value:s,onChange:t,initialPath:a,projectsDirectory:i,rootLabel:n="Home",height:c=360}){const[o,l]=r.useState(a??i??""),[u,x]=r.useState(new Set),[h,d]=r.useState(-1),[m,p]=r.useState(null),[g,j]=r.useState({}),[v,k]=r.useState(!1),[b,w]=r.useState(null),[E,y]=r.useState(!1),[z,C]=r.useState(""),[f,P]=r.useState(null),[$,N]=r.useState(!1),A=r.useRef(null),O=r.useCallback(async D=>{try{const se=li(D);if(se)return se;const W=await R.get("/fs?path="+encodeURIComponent(D));return ot(D,W),W}catch{return null}},[]),S=r.useCallback(async D=>{var se;k(!0),w(null);try{const W=await R.get("/fs?path="+encodeURIComponent(D));ot(D,W),p(W),d(-1)}catch(W){const ce=((se=W.data)==null?void 0:se.message)??W.message??"Failed to load directory";w(ce)}finally{k(!1)}},[]);r.useEffect(()=>{o?S(o):R.get("/fs").then(D=>{ot("",D),p(D),l(D.path),D.path!==s&&t(D.path)}).catch(()=>{w("Could not determine home directory."),k(!1)})},[o]),r.useEffect(()=>{s&&s!==o&&l(s)},[s]);const F=m?ci(m.entries):[],Y=F.filter(D=>D.isDir),L=F,X=D=>{D.isDir&&(l(D.path),t(D.path))},ie=()=>{m!=null&&m.parent&&(l(m.parent),t(m.parent))},te=D=>{D!==o&&(l(D),t(D))},B=async()=>{const D=await O("");D&&(l(D.path),t(D.path))},H=async()=>{if(!i)return;const D=await O(i);D&&(l(D.path),t(D.path))},Q=()=>{y(!0),C(""),P(null),setTimeout(()=>{var D;return(D=A.current)==null?void 0:D.focus()},0)},U=()=>{y(!1),C(""),P(null)},Z=async()=>{var se;const D=di(z);if(!D.ok){P(D.reason);return}N(!0),P(null);try{const W=await R.post("/fs/mkdir",{parent:o,name:z.trim()});ts.delete(o),await S(o),t(W.path),y(!1),C("")}catch(W){const ce=W;ce.status===409?P(`A folder named "${z.trim()}" already exists.`):P(((se=ce.data)==null?void 0:se.message)??W.message??"Failed to create folder.")}finally{N(!1)}},he=D=>{D.key==="Enter"?(D.preventDefault(),Z()):D.key==="Escape"&&(D.preventDefault(),U())},Ne=D=>{x(se=>{const W=new Set(se);return W.has(D)?W.delete(D):W.add(D),W}),g[D]||O(D).then(se=>{se&&j(W=>({...W,[D]:se.entries.filter(ce=>ce.isDir)}))})},I=D=>{if(!m)return;const se=L.filter(G=>G.isDir),W=L.filter(G=>!G.isDir),ce=[...se,...W];if(D.key==="ArrowDown")D.preventDefault(),d(G=>Math.min(G+1,ce.length-1));else if(D.key==="ArrowUp")D.preventDefault(),d(G=>Math.max(G-1,0));else if(D.key==="Enter"||D.key===" "){D.preventDefault();const G=ce[h];G&&(D.key==="Enter"&&G.isDir?X(G):G.isDir&&t(G.path))}else D.key==="Backspace"&&(D.preventDefault(),ie())},K=oi((m==null?void 0:m.path)??o??"/"),J=m==null?void 0:m.parent,oe=J!=null,_=o.split("/").filter(Boolean).at(-1)??"/";return e.jsxs("div",{className:"file-browser",onKeyDown:I,tabIndex:-1,children:[e.jsx("div",{className:"file-browser-breadcrumb",role:"navigation","aria-label":"Path breadcrumb",children:K.map((D,se)=>e.jsxs("span",{className:"file-browser-breadcrumb-item",children:[se>0&&e.jsx("span",{className:"file-browser-breadcrumb-sep","aria-hidden":!0,children:"/"}),e.jsx("button",{type:"button",className:"file-browser-breadcrumb-btn",onClick:()=>te(D.path),title:D.path,children:se===0?D.path==="/"?"/":n:D.label})]},D.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:ie,disabled:!oe,title:"Go up (Backspace)","aria-label":"Go up one level",children:e.jsx(Tt,{size:13})}),e.jsx("button",{type:"button",className:"file-browser-tool-btn",onClick:()=>S(o),disabled:v,title:"Refresh","aria-label":"Refresh",children:e.jsx(le,{size:13,className:v?"spin":""})}),e.jsx("button",{type:"button",className:"file-browser-tool-btn",onClick:Q,title:"New folder","aria-label":"Create new folder",children:e.jsx(en,{size:13})}),e.jsxs("div",{className:"file-browser-chips",children:[e.jsxs("button",{type:"button",className:"file-browser-chip",onClick:B,children:[e.jsx(sn,{size:11})," ",n]}),i&&e.jsxs("button",{type:"button",className:"file-browser-chip",onClick:H,title:i,children:[e.jsx(tn,{size:11})," ",i.split("/").filter(Boolean).at(-1)??"Projects"]})]})]}),E?e.jsxs("div",{className:"file-browser-mkdir",children:[e.jsx("input",{ref:A,type:"text",className:"file-browser-mkdir-input",placeholder:"Folder name",value:z,onChange:D=>{C(D.target.value),P(null)},onKeyDown:he,"aria-label":"New folder name","aria-invalid":f?"true":void 0,"aria-describedby":f?"mkdir-error":void 0,disabled:$,maxLength:255}),f?e.jsx("span",{id:"mkdir-error",className:"file-browser-mkdir-error",role:"alert",children:f}):e.jsx("span",{className:"file-browser-mkdir-hint",children:"Enter to create, Esc to cancel"})]}):e.jsx("span",{className:"file-browser-count-hint",children:v?"…":`${F.length} in ${_}`})]}),b&&e.jsxs("div",{className:"file-browser-error",children:[e.jsx(st,{size:13}),e.jsx("span",{children:b}),e.jsx("button",{type:"button",className:"file-browser-retry",onClick:()=>S(o),children:"Retry"})]}),e.jsxs("div",{className:"file-browser-body",style:{height:c},children:[e.jsx("div",{className:"file-browser-pane file-browser-tree","aria-label":"Folder tree",children:v&&!m?e.jsx(mi,{}):e.jsx(Ma,{path:o,entries:Y,expanded:u,childrenMap:g,onToggle:Ne,onNavigate:X,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"})]}),v&&!m?e.jsx(ui,{}):e.jsxs(e.Fragment,{children:[(m==null?void 0:m.truncated)&&e.jsxs("div",{className:"file-browser-truncated-banner",role:"status",children:["Showing first 500 of ",m.totalEntries," entries. Navigate into a subfolder to see more."]}),L.length===0?e.jsx("div",{className:"file-browser-empty",children:"This folder is empty"}):e.jsx("div",{className:"file-browser-flat-list",children:L.map((D,se)=>{const W=D.isDir,ce=se===h,G=D.path===s;return e.jsxs("div",{role:"option","aria-selected":G,className:["file-browser-row",W?"file-browser-row--dir":"file-browser-row--file",ce&&"file-browser-row--selected",G&&W&&"file-browser-row--active",!W&&"file-browser-row--disabled"].filter(Boolean).join(" "),onClick:()=>{W&&(d(se),t(D.path))},onDoubleClick:()=>{W&&X(D)},title:D.path,children:[e.jsx("span",{className:"file-browser-row-icon",children:W?e.jsx(Oe,{size:13}):e.jsx(an,{size:13})}),e.jsx("span",{className:"file-browser-row-name",children:D.name}),e.jsx("span",{className:"file-browser-row-type",children:W?"Folder":""})]},D.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 Ma({path:s,entries:t,expanded:a,childrenMap:i,onToggle:n,onNavigate:c,level:o}){return e.jsx("ul",{className:"file-browser-tree-list",role:"group",children:t.map(l=>{const u=a.has(l.path),x=i[l.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(),n(l.path)},"aria-label":u?"Collapse":"Expand",children:(x.length>0,u?e.jsx(Be,{size:11}):e.jsx(Ge,{size:11}))}),e.jsxs("button",{type:"button",className:"file-browser-tree-name",onClick:()=>c(l),title:l.path,children:[e.jsx(Oe,{size:12}),e.jsx("span",{children:l.name})]})]}),u&&x.length>0&&e.jsx(Ma,{path:l.path,entries:x,expanded:a,childrenMap:i,onToggle:n,onNavigate:c,level:o+1})]},l.path)})})}function mi(){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 ui(){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 T=r.forwardRef(function({variant:t="secondary",size:a="md",iconOnly:i=!1,loading:n=!1,disabled:c,className:o,children:l,...u},x){return e.jsxs("button",{ref:x,type:u.type??"button",disabled:c||n,className:V("btn",`btn-${t}`,`btn-size-${a}`,i&&"btn-icon",n&&"btn-loading",o),...u,children:[n?e.jsx("span",{className:"btn-spinner","aria-hidden":!0}):null,l]})}),wt=[{id:"overview",label:"Overview",icon:ca},{id:"chat",label:"Chat",icon:tt},{id:"agents",label:"Agents",icon:Qe},{id:"artifacts",label:"Glyphs",icon:Xs},{id:"tasks",label:"Tasks",icon:Ms},{id:"activity",label:"Activity",icon:$e},{id:"background",label:"Active",icon:nn},{id:"skills",label:"Skills",icon:He},{id:"memory",label:"Memory",icon:Fe},{id:"mods",label:"Mods",icon:is},{id:"schedules",label:"Schedules",icon:Is},{id:"plugins",label:"Plugins",icon:is},{id:"history",label:"History",icon:Ls},{id:"minimax",label:"Usage",icon:$t},{id:"eval",label:"Eval",icon:as},{id:"doctor",label:"Doctor",icon:da},{id:"settings",label:"Settings",icon:At}];function hi({activeTab:s,onTabChange:t,wsStatus:a,version:i,activeProject:n,projects:c,onProjectChange:o,onProjectsRefresh:l,onOpenSearch:u,settings:x,rightSlot:h,notificationsSlot:d,showTabs:m=!0,extraTabs:p}){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:i})]}),e.jsx(xi,{activeProject:n,projects:c,onChange:o,onRefresh:l,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(pe,{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:[d,h,e.jsxs("div",{className:V("ws-status",`ws-${a}`),title:`WebSocket: ${a}`,children:[e.jsx("span",{className:"ws-dot"}),e.jsx("span",{className:"ws-label",children:a})]})]})]}),m&&e.jsxs("nav",{className:"tabs-row",role:"tablist","aria-label":"Primary tabs",children:[wt.map(g=>{const j=g.icon,v=g.id===s;return e.jsxs("button",{type:"button",role:"tab","aria-selected":v,className:V("tab",v&&"tab-active"),onClick:()=>t(g.id),title:g.label,children:[e.jsx(j,{size:14,className:"tab-icon"}),e.jsx("span",{className:"tab-label",children:g.label}),g.id==="settings"&&v&&e.jsx("span",{className:"settings-mode-indicator",title:"Settings mode active",children:e.jsx(rn,{size:12})})]},g.id)}),p&&p.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"tab-separator","aria-hidden":"true"}),p.map(g=>{const j=g.icon,v=g.id===s;return e.jsxs("button",{type:"button",role:"tab","aria-selected":v,className:V("tab","tab-mod",v&&"tab-active"),onClick:()=>t(g.id),title:`${g.label} (mod)`,children:[e.jsx(j,{size:14,className:"tab-icon"}),e.jsx("span",{className:"tab-label",children:g.label}),e.jsx("span",{className:"tab-badge",children:"mod"})]},g.id)})]})]})]})}function xi({activeProject:s,projects:t,onChange:a,onRefresh:i,settings:n}){const[c,o]=r.useState(!1),l=Ae();r.useEffect(()=>{if(!c)return;const x=()=>o(!1);return document.addEventListener("click",x),()=>document.removeEventListener("click",x)},[c]);const u=()=>{l.open({title:"Add project",children:e.jsx(pi,{settings:n,onAdd:async(x,h)=>{try{await R.post("/projects",{path:x,name:h}),i(),o(!1),l.close()}catch(d){alert(`Add failed: ${d.message}`)}}}),footer:e.jsx("div",{className:"modal-footer-actions",children:e.jsx(T,{variant:"ghost",onClick:()=>l.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":c,children:[e.jsx(Oe,{size:14}),e.jsx("span",{className:"project-selector-name",children:(s==null?void 0:s.name)||"(no project)"}),e.jsx(Be,{size:12})]}),c&&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:i,title:"Refresh","aria-label":"Refresh projects",children:e.jsx(le,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn",onClick:u,title:"Add project","aria-label":"Add project",children:e.jsx(Re,{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:V("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 pi({settings:s,onAdd:t}){var d,m;const[a,i]=r.useState(((d=s==null?void 0:s.dashboard)==null?void 0:d.projectsDirectory)??""),[n,c]=r.useState(""),[o,l]=r.useState(!1),[u,x]=r.useState(null),h=async()=>{var p;if(a){l(!0),x(null);try{await R.get("/fs?path="+encodeURIComponent(a)),t(a,n||null)}catch(g){const j=g;j.status===404?x("That folder no longer exists. Pick another."):x(((p=j.data)==null?void 0:p.message)??g.message??"Validation failed.")}finally{l(!1)}}};return e.jsxs("div",{children:[e.jsx("label",{className:"field-label",children:"Folder"}),e.jsx(Aa,{value:a,onChange:p=>{i(p),x(null)},projectsDirectory:(m=s==null?void 0:s.dashboard)==null?void 0:m.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:n,onChange:p=>c(p.target.value)})]}),e.jsx("div",{style:{marginTop:"var(--space-3)",display:"flex",justifyContent:"flex-end"},children:e.jsxs(T,{variant:"primary",onClick:h,disabled:!a||o,children:[o?e.jsx("span",{className:"btn-spinner"}):null,o?"Checking…":"Add"]})})]})}const gi=[{label:"General",sections:[{id:"theme",label:"Theme",icon:ma},{id:"layout",label:"Layout",icon:_t},{id:"general",label:"General",icon:_t}]},{label:"Core",sections:[{id:"env-vars",label:"Env Vars",icon:rs},{id:"providers",label:"Providers",icon:ln},{id:"memory",label:"Memory",icon:Fe},{id:"system-llm",label:"System LLM",icon:qs}]},{label:"Experience",sections:[{id:"updates",label:"Updates",icon:le},{id:"skills",label:"Skills",icon:He},{id:"headroom",label:"Headroom",icon:on}]},{label:"Data",sections:[{id:"backup",label:"Backup",icon:ua}]}];function fi({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:"settings-nav-back",onClick:a,"aria-label":"Exit settings",children:[e.jsx(Tt,{size:14}),e.jsx("span",{children:"Back"})]}),e.jsx("div",{className:"settings-nav-divider","aria-hidden":"true"}),gi.map(i=>e.jsxs("div",{className:"settings-nav-group",children:[e.jsx("div",{className:"settings-nav-group-label",children:i.label}),i.sections.map(n=>{const c=n.icon,o=s===n.id;return e.jsxs("button",{type:"button",className:V("settings-nav-item",o&&"settings-nav-item-active"),onClick:()=>t(o?null:n.id),"aria-current":o?"page":void 0,children:[c&&e.jsx(c,{size:14,className:"settings-nav-item-icon","aria-hidden":!0}),e.jsx("span",{className:"settings-nav-item-label",children:n.label}),o&&e.jsx(Ge,{size:12,className:"settings-nav-item-chevron","aria-hidden":!0})]},n.id)})]},i.label))]})}function ji({tabs:s,activeTab:t,onTabChange:a,settingsMode:i,settingsActiveSection:n,onSettingsSectionChange:c,onExitSettings:o}){if(i)return e.jsx("aside",{className:"sidebar sidebar-settings-mode","aria-label":"Settings navigation",children:e.jsx(fi,{activeSection:n??null,onSectionChange:c??(()=>{}),onExitSettings:o??(()=>{})})});const l=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:[l.map(x=>{const h=x.icon,d=x.id===t;return e.jsxs("button",{type:"button",role:"tab","aria-selected":d,className:V("sidebar-tab",d&&"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,d=x.id===t;return e.jsxs("button",{type:"button",role:"tab","aria-selected":d,className:V("sidebar-tab","sidebar-tab-mod",d&&"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"}],Vt={all:null,projects:"project",agents:"agent",tasks:"task",mods:"mod",schedules:"schedule",commands:"command",settings:"setting"};function vi({open:s,onClose:t,onSelect:a}){const i=re(),[n,c]=r.useState(""),[o,l]=r.useState("all"),[u,x]=r.useState([]),[h,d]=r.useState(!1),[m,p]=r.useState(0),g=r.useRef(null),j=r.useRef(null);if(r.useEffect(()=>{let w;return s&&(j.current=document.activeElement instanceof HTMLElement?document.activeElement:null,c(""),x([]),p(0),w=window.setTimeout(()=>{var E;return(E=g.current)==null?void 0:E.focus()},30)),()=>{if(w&&window.clearTimeout(w),!s)return;const E=j.current;E&&E.isConnected&&E.focus()}},[s]),r.useEffect(()=>{if(!s)return;if(!n.trim()){x([]),p(0);return}let w=!1;d(!0);const E=setTimeout(()=>{R.get(`/search?q=${encodeURIComponent(n)}&scope=${o}`).then(y=>{w||(x(y.results||[]),p(0))}).catch(y=>{w||i.error(`Search failed: ${y.message}`)}).finally(()=>!w&&d(!1))},150);return()=>{w=!0,clearTimeout(E)}},[n,o,s,i]),!s)return null;const v={};for(const w of u){const E=w.type.toLowerCase();v[E]=v[E]||[],v[E].push(w)}const k=[];for(const w of ct.map(E=>E.id)){const E=Vt[w];E&&v[E]&&k.push(...v[E])}const b=w=>{if(w.key==="Escape")t();else if(w.key==="ArrowDown"){if(w.preventDefault(),k.length===0)return;p(E=>Math.min(E+1,k.length-1))}else if(w.key==="ArrowUp"){if(w.preventDefault(),k.length===0)return;p(E=>Math.max(E-1,0))}else w.key==="Enter"&&k[m]&&(w.preventDefault(),a(k[m]),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:w=>w.stopPropagation(),children:[e.jsxs("div",{className:"search-modal-head",role:"search",children:[e.jsx(pe,{size:14,"aria-hidden":!0}),e.jsx("span",{id:"search-modal-title",className:"sr-only",children:"Search"}),e.jsx("input",{ref:g,className:"search-modal-input",placeholder:"Search tasks, agents, settings, projects…",value:n,onChange:w=>c(w.target.value),onKeyDown:b,"aria-label":"Search"}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Close",onClick:t,children:e.jsx(be,{size:14})})]}),e.jsx("div",{className:"search-modal-scopes",role:"tablist","aria-label":"Search scope",children:ct.map(w=>e.jsx("button",{type:"button",role:"tab","aria-selected":o===w.id,className:V("search-scope",o===w.id&&"search-scope-active"),onClick:()=>l(w.id),children:w.label},w.id))}),e.jsxs("div",{className:"search-modal-body",children:[h&&e.jsx("div",{className:"muted",children:"Searching…"}),!h&&n&&k.length===0&&e.jsx("div",{className:"muted",children:"No results."}),!h&&!n&&e.jsx("div",{className:"muted",children:"Type to search…"}),ct.map(w=>{const E=Vt[w.id];if(!E)return null;const y=v[E];return!y||y.length===0?null:e.jsxs("div",{className:"search-group",children:[e.jsx("div",{className:"search-group-head",children:w.label}),y.map(z=>{const C=k.indexOf(z);return e.jsxs("button",{type:"button",className:V("search-result",C===m&&"search-result-active"),onMouseEnter:()=>p(C),onClick:()=>{a(z),t()},children:[e.jsx("span",{className:"search-result-type",children:z.type}),e.jsx("span",{className:"search-result-label",children:yi(z)})]},`${z.type}-${C}`)})]},w.id)})]}),e.jsx("div",{className:"search-modal-foot",children:e.jsx("span",{className:"muted",children:"↑↓ navigate · ↵ open · esc close"})})]})})}function yi(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 bi={info:at,success:Ve,warning:ke,error:st};function Ni({onCountChange:s,wsSubscribe:t}){const a=re(),[i,n]=r.useState(!1),[c,o]=r.useState([]),[l,u]=r.useState(null),[x,h]=r.useState(!1),d=r.useRef(null),m=r.useRef(0),p=async()=>{var b;try{h(!0);const w=await R.get("/notifications?limit=200");o(w.notifications||[]),u(w.stats||null),m.current=((b=w.stats)==null?void 0:b.unread)||0,s==null||s(m.current)}catch(w){console.warn("[notifications] reload failed:",w.message)}finally{h(!1)}};r.useEffect(()=>{p()},[]),r.useEffect(()=>t?t(w=>{if(w.type==="notification:new"){const E=w.notification;o(y=>[E,...y.filter(z=>z.id!==E.id)]),E.read||(m.current+=1,u(y=>y?{...y,unread:(y.unread||0)+1}:{total:1,unread:1,lastTs:E.ts,counts:{[E.severity||"info"]:1}}),s==null||s(m.current))}else w.type==="notifications:change"&&p()}):void 0,[t]),r.useEffect(()=>{if(!i)return;const b=E=>{d.current&&(d.current.contains(E.target)||n(!1))},w=E=>{E.key==="Escape"&&n(!1)};return document.addEventListener("mousedown",b),document.addEventListener("keydown",w),()=>{document.removeEventListener("mousedown",b),document.removeEventListener("keydown",w)}},[i]);const g=async()=>{try{await R.post("/notifications/read-all",{}),o(b=>b.map(w=>({...w,read:!0}))),u(b=>b&&{...b,unread:0}),m.current=0,s==null||s(0),a.success("All notifications marked as read.",1500)}catch(b){a.error(`Failed: ${b.message}`)}},j=async b=>{try{await R.post(`/notifications/${encodeURIComponent(b)}/read`,{}),o(w=>w.map(E=>E.id===b?{...E,read:!0}:E)),u(w=>w&&{...w,unread:Math.max(0,(w.unread||1)-1)}),m.current=Math.max(0,m.current-1),s==null||s(m.current)}catch(w){a.error(`Failed: ${w.message}`)}},v=async b=>{try{await R.del(`/notifications/${encodeURIComponent(b)}`),o(w=>{const E=w.find(y=>y.id===b);return E&&!E.read&&(m.current=Math.max(0,m.current-1),u(y=>y&&{...y,unread:Math.max(0,y.unread-1)}),s==null||s(m.current)),w.filter(y=>y.id!==b)})}catch(w){a.error(`Failed: ${w.message}`)}},k=(l==null?void 0:l.unread)||0;return e.jsxs("div",{className:"notifications-root",ref:d,children:[e.jsxs("button",{type:"button",className:V("topbar-icon-btn notifications-bell",i&&"is-open"),onClick:()=>n(b=>!b),title:"Notifications","aria-label":"Notifications","aria-haspopup":"true","aria-expanded":i,children:[e.jsx(cn,{size:16}),k>0&&e.jsx("span",{className:"notifications-badge",children:k>99?"99+":k})]}),i&&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"}),k>0&&e.jsxs("span",{className:"muted text-sm",children:[" · ",k," unread"]})]}),e.jsxs("div",{className:"notifications-panel-head-actions",children:[e.jsxs(T,{size:"sm",variant:"ghost",onClick:g,disabled:k===0,children:[e.jsx(ls,{size:12})," Mark all read"]}),e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>n(!1),"aria-label":"Close",title:"Close",children:e.jsx(be,{size:14})})]})]}),e.jsx("div",{className:"notifications-list",children:x&&c.length===0?e.jsx("div",{className:"notifications-empty muted",children:"Loading…"}):c.length===0?e.jsx("div",{className:"notifications-empty muted",children:"No notifications yet."}):c.map(b=>{const w=bi[b.severity]||at;return e.jsxs("div",{className:V("notification-item",!b.read&&"is-unread",`severity-${b.severity}`),children:[e.jsx(w,{size:14,className:`notification-icon severity-${b.severity}`}),e.jsxs("div",{className:"notification-body",children:[b.title&&e.jsx("div",{className:"notification-title",children:b.title}),e.jsx("div",{className:"notification-msg",children:b.message}),e.jsxs("div",{className:"notification-meta muted",children:[e.jsx("span",{className:"mono",children:b.source}),e.jsx("span",{children:"·"}),e.jsx("span",{children:ze(b.ts)})]})]}),e.jsxs("div",{className:"notification-actions",children:[!b.read&&e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>j(b.id),title:"Mark as read","aria-label":"Mark as read",children:e.jsx(ls,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger",onClick:()=>v(b.id),title:"Remove","aria-label":"Remove",children:e.jsx(be,{size:12})})]})]},b.id)})}),e.jsx("footer",{className:"notifications-panel-foot",children:e.jsx("span",{className:"muted text-sm",children:l?`${l.total} total · last ${ze(l.lastTs||new Date().toISOString())}`:""})})]})]})}function ki({data:s,onClose:t}){const a=s==null?void 0:s.enabled;s==null||s.previousEnabled;const i=s==null?void 0:s.mode,n=s==null?void 0:s.defaultTemplate,c=s==null?void 0:s.lastUsedSlug,o=i==="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."}),n&&e.jsxs("p",{style:{marginTop:8,fontSize:13,color:"var(--color-muted)"},children:["Default template: ",e.jsx("code",{children:n})]}),c&&e.jsxs("p",{style:{fontSize:13,color:"var(--color-muted)"},children:["Last used plan: ",e.jsx("code",{children:c})]}),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(T,{variant:"ghost",onClick:t,children:"Close"})})]})}const wi=["blank","feature-design","bug-investigation","decision-record","horizontal","vertical"];function Si({data:s,onClose:t}){const a=(s==null?void 0:s.templates)??wi,i=(s==null?void 0:s.defaultTemplate)??"blank",[n,c]=r.useState(""),[o,l]=r.useState(i),[u,x]=r.useState(!1),[h,d]=r.useState(null),m=async()=>{if(!n.trim()){d("Slug is required.");return}if(!/^[a-z0-9][a-z0-9-]{0,63}$/.test(n)){d("Invalid slug. Use lowercase letters, numbers, and hyphens. Must start with an alphanumeric character.");return}x(!0),d(null);try{await R.post("/artifacts",{slug:n,template:o}),t()}catch(p){d(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:n,onChange:p=>{c(p.target.value),d(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=>l(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(T,{variant:"ghost",onClick:t,disabled:u,children:"Cancel"}),e.jsx(T,{variant:"primary",onClick:m,disabled:u||!n.trim(),children:u?"Creating…":"Create"})]})]})}function Ci({data:s,onClose:t}){const a=(s==null?void 0:s.plans)??[],i=(s==null?void 0:s.count)??a.length,n=c=>{window.open(`/artifacts/${c}/`,"_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:[i," plan",i!==1?"s":""," in this worktree:"]}),e.jsx("ul",{style:{listStyle:"none",padding:0,margin:0},children:a.map(c=>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:c}),e.jsx(T,{variant:"ghost",size:"sm",onClick:()=>n(c),children:"Open"})]},c))})]}),e.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:e.jsx(T,{variant:"ghost",onClick:t,children:"Close"})})]})}function zi({data:s,onClose:t}){const a=(s==null?void 0:s.commands)??[],i=(s==null?void 0:s.templates)??[],n=(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(c=>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:c.cmd})}),e.jsx("td",{style:{padding:"5px 0",color:"var(--color-muted)"},children:c.desc})]},c.cmd))})}):e.jsx("p",{style:{marginBottom:16,color:"var(--color-muted)"},children:"No commands available."}),i.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:i.join(", ")})]}),n.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:n.join(", ")})]}),e.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:e.jsx(T,{variant:"ghost",onClick:t,children:"Close"})})]})}function Ri({data:s,onClose:t}){const[a,i]=r.useState(!1),[n,c]=r.useState(null),o=async()=>{i(!0),c(null);try{const l=await R.post("/chat/audit",{});c(l)}catch(l){c({ok:!1,findings:[],error:l.message})}finally{i(!1)}};return e.jsx("div",{children:n===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(T,{variant:"ghost",onClick:t,children:"Cancel"}),e.jsx(T,{variant:"primary",onClick:o,disabled:a,children:a?"Running…":"Run Audit"})]})]}):e.jsxs(e.Fragment,{children:[n.ok?e.jsxs("div",{children:[e.jsx("p",{style:{marginBottom:12,fontWeight:600,color:"var(--color-success)"},children:"Audit passed — no issues found."}),n.findings.length>0&&e.jsx("ul",{style:{marginBottom:16,paddingLeft:20},children:n.findings.map((l,u)=>e.jsx("li",{style:{marginBottom:4,fontSize:13},children:l},u))})]}):e.jsxs("p",{style:{marginBottom:16,color:"var(--color-danger)"},children:["Audit failed: ",n.error??"unknown error"]}),e.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:e.jsx(T,{variant:"ghost",onClick:t,children:"Close"})})]})})}function Ti({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:i,url:n}=s.data;return e.jsxs("div",{children:[e.jsx("p",{style:{marginBottom:16,lineHeight:1.6},children:a??`Command: ${s.command}`}),i&&e.jsx("p",{style:{marginBottom:16,color:"var(--color-muted)",fontSize:13},children:i}),n&&e.jsx("p",{style:{marginBottom:16},children:e.jsx("a",{href:n,target:"_blank",rel:"noopener noreferrer",children:n})}),e.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:e.jsx("button",{type:"button",className:"btn",onClick:t,children:"Close"})})]})}function $i({dialog:s,onClose:t}){switch(s.component){case"visual-artifact":return e.jsx(ki,{data:s.data,onClose:t});case"artifact-create":return e.jsx(Si,{data:s.data,onClose:t});case"artifact-list":return e.jsx(Ci,{data:s.data,onClose:t});case"help":return e.jsx(zi,{data:s.data,onClose:t});case"audit":return e.jsx(Ri,{data:s.data,onClose:t});default:return e.jsx(Ti,{dialog:s,onClose:t})}}function q({variant:s="elevated",interactive:t=!1,className:a,children:i,...n}){return e.jsx("div",{className:V("card",`card-${s}`,t&&"card-interactive",a),...n,children:i})}function ae({children:s,className:t}){return e.jsx("h3",{className:V("card-title",t),children:s})}function ne({children:s,className:t}){return e.jsx("div",{className:V("card-meta",t),children:s})}function Ai({setActiveTab:s,refreshKey:t=0}){var x;const[a,i]=r.useState(null),[n,c]=r.useState(!0),o=async()=>{c(!0);try{const[h,d,m]=await Promise.all([R.get("/memory/status").catch(()=>null),R.get("/memory/health").catch(()=>null),R.get("/memory/lightrag/stats").catch(()=>null)]);i({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:d==null?void 0:d.score,healthStatus:d==null?void 0:d.status,lightrag:m?{running:m.running,indexedApprox:m.indexedApprox}:void 0})}catch{i({initialized:!1})}finally{c(!1)}};r.useEffect(()=>{o()},[t]);const l=()=>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(q,{className:"memory-overview-card",children:[e.jsxs(ae,{children:[e.jsx(Fe,{size:14})," Memory",e.jsxs(T,{variant:"ghost",size:"sm",style:{marginLeft:"auto"},onClick:l,children:["Open Memory ",e.jsx(ms,{size:12})]}),e.jsx(T,{variant:"ghost",size:"sm",onClick:o,"aria-label":"Refresh",title:"Refresh",children:e.jsx(le,{size:12})})]}),e.jsx(ne,{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($e,{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(Fe,{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(we,{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(os,{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}`:We(a.branch||"")||"—"})]})]}):e.jsxs("div",{className:"muted",children:["Memory not initialised. Click ",e.jsx("strong",{children:"Open Memory"})," to set it up."]}),n&&!a&&e.jsx("div",{className:"muted text-sm",children:"Loading…"})]})}function ge({icon:s,title:t,message:a,action:i,className:n}){return e.jsxs("div",{className:V("empty-state",n),children:[e.jsx("div",{className:"empty-icon",children:s??e.jsx(Qs,{size:32})}),e.jsx("div",{className:"empty-title",children:t}),a&&e.jsx("div",{className:"empty-message",children:a}),i&&e.jsx("div",{className:"empty-action",children:i})]})}function Mi({snapshot:s,settings:t,setActiveTab:a,refreshSnapshot:i}){var X,ie,te;const n=re(),c=Ae(),o=r.useRef(null),[l,u]=r.useState(s.overview??null),[x,h]=r.useState(!s.overview),[d,m]=r.useState(s.projects||[]),[p,g]=r.useState(((X=s.activeProject)==null?void 0:X.id)||null),[j,v]=r.useState(s.mods||[]),[k,b]=r.useState(!1),[w,E]=r.useState(((ie=s.overview)==null?void 0:ie.recentActivity)??[]),[y,z]=r.useState(!1),[C,f]=r.useState(new Set);r.useEffect(()=>{let B=!1;return(async()=>{try{const H=await R.get("/activity/hidden");B||f(new Set(H.hidden||[]))}catch{}})(),()=>{B=!0}},[]);const P=(B,H)=>{const Q=`${B.kind||""}|${B.ts||""}|${B.slug||B.title||""}|${H}`;let U=0;for(let Z=0;Z<Q.length;Z++)U=(U<<5)-U+Q.charCodeAt(Z)|0;return Math.abs(U).toString(16).padStart(8,"0").slice(0,16)},$=async B=>{const H=new Set(C);H.add(B),f(H);try{await R.post("/activity/hide",{keys:[B]})}catch(Q){const U=new Set(C);f(U),n.error(`Hide failed: ${Q.message}`)}},N=async()=>{if(!confirm("Hide every recent activity item from the overview? The full log stays in Settings → Activity Log."))return;const B=w.map((Q,U)=>P(Q,U)),H=new Set(C);B.forEach(Q=>H.add(Q)),f(H);try{await R.post("/activity/hide",{keys:B}),n.success(`Hidden ${B.length} item(s). Restore them in Settings → Activity Log.`)}catch(Q){n.error(`Clear failed: ${Q.message}`)}},A=async()=>{f(new Set);try{await R.del("/activity/hide"),n.success("All hidden activity restored to the overview.")}catch(B){n.error(`Restore failed: ${B.message}`)}};r.useEffect(()=>{var B;s.overview&&(u(s.overview),E(s.overview.recentActivity??[]),h(!1)),m(s.projects||[]),g(((B=s.activeProject)==null?void 0:B.id)||null),v(s.mods||[])},[s.overview,s.projects,s.activeProject,s.mods]),r.useEffect(()=>{let B;try{const H=R.getToken(),Q=H?`/api/activity/stream?token=${encodeURIComponent(H)}`:"/api/activity/stream";B=new EventSource(Q),B.addEventListener("snapshot",U=>{try{const Z=JSON.parse(U.data);E(Array.isArray(Z.events)?Z.events.slice(0,50):[])}catch{}}),B.addEventListener("activity",U=>{try{const Z=JSON.parse(U.data);E(he=>[Z,...he].slice(0,50))}catch{}})}catch{}return()=>{try{B==null||B.close()}catch{}}},[]);const O=async()=>{n.info("Refreshing…",1500),await i();try{const B=await R.get("/projects");m(B.projects||[]),g(B.active||null)}catch{}},S=()=>{c.open({title:"Add project",children:e.jsx(Ii,{settings:t,onAdd:async(B,H)=>{try{const Q=await R.post("/projects",{path:B,name:H});m(U=>[...U.filter(Z=>Z.id!==Q.id),Q]),n.success("Project added."),c.close()}catch(Q){n.error(`Add failed: ${Q.message}`)}}}),footer:e.jsx("div",{className:"modal-footer-actions",children:e.jsx(T,{variant:"ghost",onClick:()=>c.close(),children:"Cancel"})})})},F=async()=>{var B;try{const H=await R.post("/projects/auto-detect");m(H.projects||[]),g(H.active||null);const Q=(B=H.projects)==null?void 0:B.find(U=>U.id===H.active);n.success(Q?`Active: ${Q.name}`:"Projects refreshed."),await i()}catch(H){n.error(`Auto-detect failed: ${H.message}`)}},Y=async B=>{try{await R.post(`/projects/${encodeURIComponent(B)}/activate`),g(B),n.success("Project activated."),await i()}catch(H){n.error(`Activate failed: ${H.message}`)}},L=async B=>{if(confirm(`Remove project "${B}" from the registry?`))try{await R.del(`/projects/${encodeURIComponent(B)}`),m(H=>H.filter(Q=>Q.id!==B)),p===B&&g(null),n.success("Project removed.")}catch(H){n.error(`Remove failed: ${H.message}`)}};return x||!l?e.jsxs("div",{className:"view-loading",children:[e.jsx(me,{size:"lg"}),e.jsx("p",{children:"Loading overview…"})]}):e.jsxs("div",{className:"view view-overview",children:[e.jsxs("div",{className:"overview-hero-noframe",children:[e.jsx("h1",{children:"What do you want to do?"}),e.jsx("p",{className:"overview-hero-subtitle",children:"Describe what you want — Odin will split it into tasks, create a plan, delegate to background agents, and track progress in real time."}),e.jsxs("form",{className:"overview-hero-form-noframe",onSubmit:async B=>{var Q,U;B.preventDefault();const H=(((Q=o.current)==null?void 0:Q.value)||"").trim();if(H){b(!0);try{const Z=await R.post("/tasks/submit",{title:H});n.success(`Odin split it into ${((U=Z.subtasks)==null?void 0:U.length)||1} task(s)`),o.current&&(o.current.value=""),await i()}catch(Z){n.error(`Failed: ${Z.message}`)}finally{b(!1)}}},children:[e.jsx("label",{htmlFor:"overview-hero-input",className:"sr-only",children:"Describe what you want Odin to do"}),e.jsx("textarea",{id:"overview-hero-input",ref:o,className:"overview-input-hero",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.",disabled:k,"aria-label":"Describe what you want Odin to do"}),e.jsxs("div",{style:{display:"flex",gap:"var(--space-2)",alignItems:"center",flexWrap:"wrap"},children:[e.jsxs(T,{type:"submit",variant:"primary",size:"lg",disabled:k,children:[k?e.jsx(me,{size:"sm"}):e.jsx(cs,{size:16}),"Submit to Odin"]}),e.jsxs("span",{className:"muted",style:{fontSize:12},children:[e.jsx(He,{size:12,style:{display:"inline",verticalAlign:-2,color:"var(--accent)"}})," ","Odin + 12 specialist agents available"]})]})]}),e.jsx("div",{className:"overview-quick-actions-row",children:["Implement feature","Fix bug","Refactor","Investigate","Add tests","Document","Optimize","Deploy"].map(B=>e.jsx("button",{type:"button",className:"overview-quick-chip",onClick:()=>{o.current&&(o.current.value=B,o.current.focus())},children:B},B))})]}),e.jsxs("div",{className:"overview-feed",children:[e.jsxs("div",{className:"overview-feed-head",children:[e.jsx("h2",{children:"Recent activity"}),e.jsxs("div",{className:"overview-feed-head-actions",children:[C.size>0&&e.jsxs(T,{variant:"ghost",size:"sm",onClick:A,title:"Restore hidden items to this overview",children:[e.jsx(Je,{size:12})," Show ",C.size," hidden"]}),w.length>8&&e.jsx(T,{variant:"ghost",size:"sm",onClick:()=>z(B=>!B),children:y?"Show less":"Show all"}),w.length>0&&e.jsxs(T,{variant:"ghost",size:"sm",onClick:N,title:"Hide every item from the overview (full log kept)",children:[e.jsx(Js,{size:12})," Hide all"]})]})]}),C.size>0&&e.jsxs("div",{className:"activity-hidden-banner",role:"status",children:[e.jsxs("span",{children:[e.jsx(Js,{size:12,style:{verticalAlign:-2,marginRight:6}}),C.size," item",C.size===1?"":"s"," hidden from the overview."]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:A,children:[e.jsx(Je,{size:12})," Show them again"]})]}),w.length===0?e.jsx("div",{className:"muted",style:{padding:"24px 0",fontSize:13},children:"No activity yet. Use the chat above or invoke a Bizar command to start a feed."}):e.jsxs("div",{className:V("activity-feed-list-wrap",!y&&"activity-feed-list-wrap-collapsed"),"aria-live":"polite","aria-relevant":"additions",children:[e.jsx(Pt,{items:w.slice(0,30).filter((B,H)=>!C.has(P(B,H))),itemHeight:60,height:Math.min(w.filter((B,H)=>!C.has(P(B,H))).length*60,480),className:"activity-feed-list",renderItem:(B,H)=>{const Q=w.slice(0,30).findIndex(U=>U===B);return e.jsx(_i,{item:B,activityKey:P(B,Q),onNavigate:a,onHide:$})}}),!y&&w.length>8&&e.jsx("div",{className:"activity-feed-fade","aria-hidden":"true"})]})]}),e.jsxs(q,{className:"project-picker",children:[e.jsxs(ae,{children:[e.jsx(Oe,{size:14})," Projects",e.jsxs(T,{variant:"ghost",size:"sm",style:{marginLeft:"auto"},onClick:S,children:[e.jsx(Re,{size:12})," Add"]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:F,title:"Use the server's working directory",children:[e.jsx(Re,{size:12})," Auto-detect"]}),((te=t==null?void 0:t.dashboard)==null?void 0:te.projectsDirectory)&&e.jsxs(T,{variant:"ghost",size:"sm",title:`Scan ${t.dashboard.projectsDirectory} for projects`,onClick:async()=>{try{const B=await R.post("/projects/scan");B.error?n.error(B.error):n.success(`Added ${B.added.length}, skipped ${B.skipped}.`),await i();const H=await R.get("/projects");m(H.projects||[]),g(H.active||null)}catch(B){n.error(`Scan failed: ${B.message}`)}},children:[e.jsx(dn,{size:12})," Scan"]}),e.jsx(T,{variant:"ghost",size:"sm",onClick:O,title:"Refresh",children:e.jsx(le,{size:12})})]}),e.jsxs(ne,{children:[d.length," project",d.length===1?"":"s"," ·"," ",l.counts.agents," agents ·"," ",l.counts.sessions," session",l.counts.sessions===1?"":"s"]}),d.length===0?e.jsx(ge,{icon:e.jsx(Oe,{size:32}),title:"No projects yet",message:"Add a project to start tracking its tasks, plans, and schedules.",action:e.jsxs("div",{className:"empty-state-actions",children:[e.jsxs(T,{variant:"primary",onClick:F,children:[e.jsx(Re,{size:14})," Use current directory"]}),e.jsx(T,{variant:"secondary",onClick:S,children:"Add by path…"})]})}):e.jsx("div",{className:"project-grid",children:d.map(B=>e.jsx(Li,{project:B,active:p===B.id,onOpen:()=>Y(B.id),onRemove:()=>L(B.id)},B.id))})]}),e.jsx(Ai,{setActiveTab:a}),e.jsxs("div",{className:"overview-cols",children:[e.jsxs(q,{children:[e.jsx(ae,{children:"Mods"}),e.jsxs(ne,{children:["Extensions installed under ",e.jsx("code",{children:"~/.config/bizar/mods/"})]}),j.length===0?e.jsx("div",{className:"muted",children:"No mods installed."}):e.jsx("ul",{className:"mod-mini-list",children:j.map(B=>e.jsxs("li",{className:"mod-mini",children:[e.jsx("span",{className:"mod-mini-name",children:B.name}),e.jsxs("span",{className:"mod-mini-meta",children:["v",B.version," · ",B.type]}),e.jsx("span",{className:`mod-mini-pill ${B.enabled?"mod-mini-pill-on":"mod-mini-pill-off"}`,children:B.enabled?"on":"off"})]},B.id))})]}),e.jsxs(q,{children:[e.jsx(ae,{children:"Environment"}),e.jsx(ne,{children:"Runtime + paths"}),e.jsxs("dl",{className:"env-table",children:[e.jsx("dt",{children:"Node"}),e.jsx("dd",{className:"mono",children:l.versions.node}),e.jsx("dt",{children:"Platform"}),e.jsx("dd",{className:"mono",children:l.versions.platform}),e.jsx("dt",{children:"Project root"}),e.jsx("dd",{className:"mono ellipsis",title:l.versions.projectRoot,children:l.versions.projectRoot}),e.jsx("dt",{children:"Bizar root"}),e.jsx("dd",{className:"mono ellipsis",title:l.versions.bizarRoot,children:l.versions.bizarRoot}),e.jsx("dt",{children:"Generated"}),e.jsx("dd",{className:"mono tabular-nums",children:We(l.generatedAt)})]})]})]})]})}function Ii({settings:s,onAdd:t}){var d,m;const[a,i]=r.useState(((d=s==null?void 0:s.dashboard)==null?void 0:d.projectsDirectory)??""),[n,c]=r.useState(""),[o,l]=r.useState(!1),[u,x]=r.useState(null),h=async()=>{var p;if(a){l(!0),x(null);try{await R.get("/fs?path="+encodeURIComponent(a)),t(a,n||null)}catch(g){const j=g;j.status===404?x("That folder no longer exists. Pick another."):x(((p=j.data)==null?void 0:p.message)??g.message??"Validation failed.")}finally{l(!1)}}};return e.jsxs("div",{children:[e.jsx("label",{className:"field-label",children:"Folder"}),e.jsx(Aa,{value:a,onChange:p=>{i(p),x(null)},projectsDirectory:(m=s==null?void 0:s.dashboard)==null?void 0:m.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:"add-project-name",children:"Name (optional)"}),e.jsx("input",{id:"add-project-name",className:"input",type:"text",placeholder:"My App",value:n,onChange:p=>c(p.target.value)}),e.jsx("p",{className:"field-help",style:{marginTop:4},children:"Display name for this project. Defaults to the folder name."})]}),e.jsx("div",{style:{marginTop:"var(--space-3)",display:"flex",justifyContent:"flex-end"},children:e.jsxs(T,{variant:"primary",onClick:h,disabled:!a||o,children:[o?e.jsx("span",{className:"btn-spinner"}):null,o?"Checking…":"Add"]})})]})}function Li({project:s,active:t,onOpen:a,onRemove:i}){const n={active:"status-on",inactive:"status-neutral",error:"status-error"}[s.status]||"status-neutral";return e.jsxs("div",{className:`project-card ${t?"project-card-active":""}`,children:[e.jsxs("div",{className:"project-card-head",children:[e.jsx("span",{className:`project-card-status ${n}`,children:s.status}),e.jsx("div",{className:"project-card-name",children:s.name}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Remove project",title:"Remove",onClick:c=>{c.stopPropagation(),i()},children:e.jsx(Se,{size:12})})]}),e.jsx("div",{className:"project-card-path mono ellipsis",title:s.path,children:s.path}),e.jsx("div",{className:"project-card-meta",children:s.lastAccessed&&e.jsxs("span",{className:"muted",children:["Last opened ",ze(s.lastAccessed)]})}),e.jsx("div",{className:"project-card-actions",children:e.jsx(T,{variant:t?"ghost":"primary",size:"sm",onClick:a,children:t?e.jsxs(e.Fragment,{children:[e.jsx(Mt,{size:12})," Active"]}):e.jsx(e.Fragment,{children:"Open"})})})]})}function Ei(s){return s&&s.charAt(0).toUpperCase()+s.slice(1)}function Di(s){const t=s.trim().toLowerCase().replace(/[:_]/g,"."),[a,i="updated"]=t.split("."),n={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"},c={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=n[a]||Ei(a.replace(/-/g," ")),l=c[i]||i.replace(/-/g," ");return`${o} ${l}`.trim()}function _s(s,t){for(const a of t){const i=s[a];if(typeof i=="string"&&i.trim())return i.trim()}return""}function Pi(s){const t=_s(s,["message","text","prompt","title","name"]);if(t)return t;const a=[],i=_s(s,["slug"]),n=_s(s,["agent","author"]),c=_s(s,["status"]);return i&&a.push(`Plan ${i}`),n&&a.push(n),c&&a.push(c),a.length?a.join(" · "):"No additional details."}function Fi(s){return ze(s)}function Oi(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 Bi(s){const t=s.toLowerCase();return t==="task"?Ms:t==="agent"?Qe:t==="plan"?Xs:t.includes("bg")||t.includes("background")||t.includes("job")?nt:t==="mod"?is:t==="skill"?He:t.includes("error")||t.includes("failure")?js:t.includes("warn")?ke:$e}function Ui(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 _i({item:s,activityKey:t,onNavigate:a,onHide:i}){const n=Oi(s),c=Bi(s.kind||""),o=Di(s.kind||"activity"),l=Pi(s),u=Ui(s.kind||""),x=n==="error"?"var(--error)":n==="warning"?"var(--warning)":n==="success"?"var(--success)":"var(--accent)";return e.jsxs("div",{className:V("activity-feed-row",`activity-feed-row-${n}`),children:[e.jsxs("button",{type:"button",className:"activity-feed-row-main",onClick:()=>{u&&a(u)},title:u?`Open ${u}`:o,children:[e.jsx("div",{className:"activity-feed-icon",style:{color:x},children:e.jsx(c,{size:14})}),e.jsxs("div",{className:"activity-feed-body",children:[e.jsxs("div",{className:"activity-feed-title-row",children:[e.jsx("div",{className:"activity-feed-title",children:o}),e.jsx("div",{className:"activity-feed-time text-xs muted tabular-nums",children:Fi(s.ts)})]}),e.jsx("div",{className:"activity-feed-summary text-sm",children:l})]})]}),e.jsx("button",{type:"button",className:"activity-feed-hide-btn",onClick:()=>i(t),title:"Hide this from the overview (kept in Settings → Activity Log)","aria-label":"Hide from overview",children:e.jsx(be,{size:12})})]})}const Wi=Le.memo(Mi);function Vi({icon:s,title:t,message:a,action:i}){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}),i&&e.jsx("div",{className:"chat-empty-state-action",children:i})]})}function Hi({session:s,mode:t,anchor:a,renameDraft:i,setRenameDraft:n,onEdit:c,onDeleteRequest:o,onConfirmDelete:l,onConfirmRename:u,onClose:x}){const h=r.useRef(null),d=Math.round(a.rect.bottom+2),m=Math.max(8,Math.round(window.innerWidth-a.rect.right));r.useEffect(()=>{const g=k=>{const b=k.target;!h.current||!b||h.current.contains(b)||x()},j=k=>{k.key==="Escape"&&x()},v=window.setTimeout(()=>{document.addEventListener("mousedown",g),document.addEventListener("keydown",j)},0);return()=>{window.clearTimeout(v),document.removeEventListener("mousedown",g),document.removeEventListener("keydown",j)}},[x]),r.useEffect(()=>{if(t!=="rename")return;const g=window.setTimeout(()=>{var v;const j=(v=h.current)==null?void 0:v.querySelector("input.session-row-menu-input");j==null||j.focus(),j==null||j.select()},0);return()=>window.clearTimeout(g)},[t]);const p=e.jsxs("div",{ref:h,className:"session-row-menu",role:"menu","aria-label":`Options for ${s.title}`,style:{position:"fixed",top:d,right:m},onClick:g=>g.stopPropagation(),children:[t==="main"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",className:"session-row-menu-item",role:"menuitem",onClick:g=>{g.stopPropagation(),c()},children:[e.jsx(mn,{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:g=>{g.stopPropagation(),o()},children:[e.jsx(Se,{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:i,onChange:g=>n(g.target.value),onKeyDown:g=>{g.key==="Enter"?(g.preventDefault(),u()):g.key==="Escape"&&(g.preventDefault(),x())},onClick:g=>g.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:g=>{g.stopPropagation(),x()},children:"Cancel"}),e.jsx("button",{type:"button",className:"btn btn-primary",onClick:g=>{g.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:g=>{g.stopPropagation(),x()},children:"Cancel"}),e.jsx("button",{type:"button",className:"btn btn-danger",onClick:g=>{g.stopPropagation(),l()},children:"Delete"})]})]})]});return oa.createPortal(p,document.body)}function St({node:s,depth:t=0,collapsible:a=!1,isLast:i=!0,open:n,onToggle:c}){var p;const[o,l]=r.useState(a),u=n!==void 0,x=u?n:o,h=g=>{u||l(g),c==null||c(g)},d=(((p=s.children)==null?void 0:p.length)??0)>0,m=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",i?"last":""].filter(Boolean).join(" "),children:[a?e.jsx("button",{type:"button",className:`agent-node-head status-${s.status} collapsible`,onClick:g=>{g.stopPropagation(),h(!x)},"aria-expanded":x,children:m}):e.jsx("div",{className:`agent-node-head status-${s.status}`,children:m}),x&&e.jsxs(e.Fragment,{children:[s.summary&&e.jsx("div",{className:"agent-node-summary",children:s.summary}),d&&e.jsx("div",{className:"agent-node-children",children:s.children.map((g,j)=>e.jsx(St,{node:g,depth:t+1,collapsible:!1,isLast:j===s.children.length-1},g.id))})]})]})}function qi(s){return s.tree!==void 0}function Ki(s){const t=s.open??!0;if(qi(s))return e.jsx("div",{className:`agent-tree variant-${s.variant??"full"}`,children:e.jsx(St,{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((i,n)=>e.jsx(r.Fragment,{children:e.jsx(St,{node:i,depth:0,collapsible:!1,open:t,isLast:n===a.length-1})},i.id))})})}function Gi({children:s,variant:t="rail",open:a=!0}){return a?e.jsx(Ki,{variant:t,open:a,children:s}):null}const Yi=["Today","Yesterday","This week","Earlier"];function Ht(s,t){return s.getFullYear()===t.getFullYear()&&s.getMonth()===t.getMonth()&&s.getDate()===t.getDate()}function Xi(s,t){const a=s.getTime()-t.getTime();return Math.floor(a/(1e3*60*60*24))}function Qi(s){const t=new Date,a=new Date(t);a.setDate(a.getDate()-1);const i=new Date(t);i.setDate(i.getDate()-7);const n={Today:[],Yesterday:[],"This week":[],Earlier:[]};for(const c of s){const o=new Date(Number(c.mtime)||Date.now());Ht(o,t)?n.Today.push(c):Ht(o,a)?n.Yesterday.push(c):Xi(t,o)<7?n["This week"].push(c):n.Earlier.push(c)}return n}function Ji(s){return new Date(Number(s)||Date.now()).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1})}function Zi({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 er({sessions:s,opencodeSessions:t=[],activeSessionId:a,activeOpencodeSessionId:i,activeProject:n,creating:c,onCreateSession:o,onSelectSession:l,onSelectOpencodeSession:u,onRenameSession:x,onDeleteSession:h,groupBy:d}){var L;const m=r.useMemo(()=>[...s,...t],[s,t]),p=r.useMemo(()=>[...m].sort((X,ie)=>Number(ie.mtime??0)-Number(X.mtime??0)),[m]),g=r.useMemo(()=>d?d(p):Qi(p),[d,p]),[j,v]=r.useState({}),k=X=>j[X]===!0,[b,w]=r.useState(null),[E,y]=r.useState("main"),[z,C]=r.useState(""),[f,P]=r.useState(null),$=r.useRef({}),N=(X,ie="main")=>{const te=$.current[X];if(!te)return;const B=ie==="main"?te:te.querySelector(".chat-rail-item-menu-trigger")??te;if(P({id:X,rect:B.getBoundingClientRect()}),w(X),y(ie),ie==="rename"){const H=[...s,...t].find(Q=>Q.id===X);C((H==null?void 0:H.title)??(H==null?void 0:H.id)??"")}},A=()=>{w(null),y("main"),C(""),P(null)},O=X=>{if(X.source==="opencode"){u(X);return}l(X.id)},S=()=>{if(!f)return;const X=f.id,ie=z.trim();if(!ie){A();return}x==null||x(X,ie),A()},F=()=>{f&&(h==null||h(f.id),A())},Y=d?Object.entries(g):Yi.filter(X=>{var ie;return(ie=g[X])==null?void 0:ie.length}).map(X=>[X,g[X]]);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:c||!n,title:n?"Create new session":"Pick a project first","aria-label":"Create new session",children:[e.jsx(Re,{size:14,"aria-hidden":!0}),e.jsx("span",{children:c?"Creating…":"New session"})]})}),p.length===0?e.jsx("div",{className:"chat-sessions-empty",children:e.jsx(Vi,{icon:e.jsx(Re,{size:20,"aria-hidden":!0}),title:n?"No sessions yet":"No project",message:n?"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(([X,ie])=>e.jsxs("div",{className:"chat-rail-group",children:[e.jsx("div",{className:"chat-rail-group-label",children:X}),ie.map(te=>{var he,Ne;const B=te.source==="opencode",H=B?i===te.id:a===te.id,Q=te.tree,U=!!((he=Q==null?void 0:Q.root)!=null&&he.children&&Q.root.children.length>0),Z=k(te.id);return e.jsxs(r.Fragment,{children:[e.jsxs("div",{ref:I=>{$.current[te.id]=I},role:"button",tabIndex:0,className:`chat-rail-item state-${te.state??"idle"}${H?" active":""}`,onClick:()=>O(te),onKeyDown:I=>{(I.key==="Enter"||I.key===" ")&&(I.preventDefault(),O(te))},"aria-current":H?"true":void 0,children:[e.jsx(Zi,{state:te.state??"idle",agent:te.agent}),e.jsxs("div",{className:"chat-rail-item-title",children:[te.pinned&&e.jsx("span",{className:"chat-rail-pin","aria-hidden":!0,children:"★"}),B&&e.jsx(ms,{size:11,style:{color:"var(--text-muted)",flexShrink:0},"aria-hidden":!0}),e.jsx("span",{className:"chat-ellipsis",children:te.title||te.id})]}),e.jsxs("div",{className:"chat-rail-item-meta",children:[e.jsx("span",{className:"chat-rail-item-meta-time",children:te.time??Ji(te.mtime)}),(te.unread??0)>0&&e.jsx("span",{className:"chat-rail-badge",children:te.unread})]}),e.jsx("button",{type:"button",className:`chat-rail-item-menu-trigger${b===te.id?" open":""}`,"aria-label":`Session options for ${te.title||te.id}`,"aria-haspopup":"menu","aria-expanded":b===te.id,onClick:I=>{I.stopPropagation(),b===te.id?A():N(te.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"})]})}),H&&U&&e.jsx("button",{type:"button",className:`chat-rail-tree-chevron${Z?" open":""}`,"aria-label":Z?"Collapse sub-agents":"Expand sub-agents","aria-expanded":Z,onClick:I=>{I.stopPropagation(),v(K=>({...K,[te.id]:!K[te.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"})})})]}),H&&U&&Z&&((Ne=Q==null?void 0:Q.root)==null?void 0:Ne.children)&&e.jsx(Gi,{children:Q.root.children,variant:"rail",open:!0})]},B?`oc-${te.id}`:te.id)})]},X))}),b&&f&&e.jsx(Hi,{session:{id:f.id,title:((L=[...s,...t].find(X=>X.id===f.id))==null?void 0:L.title)??f.id},mode:E,anchor:f,renameDraft:z,setRenameDraft:C,onEdit:()=>N(b,"rename"),onDeleteRequest:()=>N(b,"confirm-delete"),onConfirmDelete:F,onConfirmRename:S,onClose:A})]})}function sr(s){const{text:t,sending:a,onSend:i,activeSource:n}=s,[c,o]=r.useState(!1),l=()=>{!t.trim()||a||(o(!0),i(),window.setTimeout(()=>o(!1),320))};return e.jsxs("div",{className:`chat-composer-wrap chat-composer-source-${n??"none"}`,children:[e.jsx("div",{className:`chat-composer-pill${c?" takeoff":""}`,children:e.jsx(Xn,{...s,onSend:l})}),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"]}),n==="opencode"&&e.jsx("span",{className:"chat-composer-source-hint",children:"→ opencode"}),n==="bizar"&&e.jsx("span",{className:"chat-composer-source-hint",children:"→ bizar chat"}),a&&e.jsx("span",{className:"chat-composer-source-hint",children:"sending…"})]})]})}function dt(s){return s.toLocaleString()}function tr(s){return!s||!s.includes("/")?"":s.split("/")[0]}function ar(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 nr({sessionId:s,messages:t,pinned:a,agent:i,model:n,agents:c,mcps:o,allCommands:l,activeSource:u="bizar",onRename:x,onDelete:h,onExport:d,busy:m,error:p,onRetry:g}){const[j,v]=r.useState(null);r.useEffect(()=>{let N=!1;return(async()=>{try{const A=await fetch("/api/usage?range=24h",{headers:{Accept:"application/json"}});if(!A.ok)return;const O=await A.json();N||v(O)}catch{}})(),()=>{N=!0}},[s]);const k=(t==null?void 0:t.length)??0,b=(a==null?void 0:a.size)??0,w=t.reduce((N,A)=>N+(A.content||A.message||"").length,0),E=Math.round(w/4),y=ar(n),z=E/1e6*y,C=(j==null?void 0:j.totalTokens)??E,f=(j==null?void 0:j.costUsd)??z,P=128e3,$=tr(n);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(ke,{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&&g?e.jsxs("button",{type:"button",className:"btn btn-ghost btn-sm chat-info-retry",onClick:g,title:"Retry loading the session",children:[e.jsx(it,{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(tt,{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==="opencode"?"opencode":"bizar chat"})]}),e.jsx("div",{className:"chat-info-mono chat-ellipsis",title:s,children:s||"Live"}),e.jsxs("div",{className:"chat-info-mono",children:[dt(k)," message",k===1?"":"s",b>0&&` · ${b} 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:i||"—"})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("h4",{children:[e.jsx(ys,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Model"]}),e.jsx("div",{className:"chat-mono chat-ellipsis",title:n,children:n||"—"}),$&&e.jsxs("div",{className:"chat-info-mono",children:["provider · ",$]})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsx("h4",{children:"Tokens"}),e.jsxs("div",{className:"chat-mono",children:[dt(C)," / ",dt(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,C/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:["$",f.toFixed(4)]}),!j&&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"]}),c!=null&&c.length?e.jsx("div",{className:"chat-info-agents",children:c.map(N=>e.jsx("span",{className:"chat-info-agent",children:N.name},N.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(ys,{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(N=>e.jsx("span",{className:"chat-info-agent",children:N.id},N.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(rs,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Slash commands"]}),e.jsxs("div",{className:"chat-info-mono",children:[(l==null?void 0:l.length)??0," available"]})]}),(x||h||d)&&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:m==null?void 0:m.rename,title:"Rename session",children:[e.jsx(Ns,{size:12,"aria-hidden":!0})," Rename"]}),d&&e.jsxs("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:d,title:"Export transcript",children:[e.jsx(Ke,{size:12,"aria-hidden":!0})," Export"]}),h&&e.jsxs("button",{type:"button",className:"btn btn-ghost btn-sm btn-danger",onClick:h,disabled:m==null?void 0:m.delete,title:"Delete session",children:[e.jsx(Se,{size:12,"aria-hidden":!0})," Delete"]})]})]})]})}function ir({streaming:s,newMessageCount:t,onClick:a,streamingLabel:i="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:i}),t>0&&e.jsx("span",{className:"jump-badge jump-badge-live",children:"live"})]}):e.jsxs(e.Fragment,{children:[e.jsx(ha,{size:14,"aria-hidden":!0}),e.jsx("span",{children:"Jump to latest"}),t>0&&e.jsxs("span",{className:"jump-badge",children:[t," new"]})]})})}function rr({snapshot:s,settings:t,setActiveTab:a,initialTaskId:i,onClearTaskId:n}){const c=re(),o=Ae(),l=Qn(s,t,i??"");r.useEffect(()=>{l.setToast({error:L=>c.error(L),success:L=>c.success(L),info:L=>c.info(L),warning:L=>c.warning(L)})},[l,c]);const[u,x]=r.useState(""),[h,d]=r.useState(t.defaultAgent||"odin"),[m,p]=r.useState(t.defaultModel||""),[g,j]=r.useState([]),v=r.useRef(null),{allCommands:k,suggestions:b,setQuery:w}=Jn(s);r.useEffect(()=>{w(u)},[u,w]);const E=()=>{var L;return(L=v.current)==null?void 0:L.click()},y=L=>{const X=L.target.files;if(!X)return;const ie=[];for(let te=0;te<X.length;te++)ie.push(X[te].name);j(te=>{const B=ie.filter(H=>!te.includes(H));return[...te,...B]}),v.current&&(v.current.value="")},z=async()=>{const L=u.trim();if(!L)return;x(""),w(""),(await l.onSend(L,h,m,g)).ok&&l.jumpToLatest()},C=async()=>{l.busy.create||await l.onCreateSession()},f=L=>{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(T,{variant:"secondary",size:"sm",onClick:()=>o.close(),children:"Cancel"}),e.jsx(T,{variant:"danger",size:"sm",onClick:()=>{o.close(),l.deleteMessage(L)},children:"Delete"})]})})},P=(L,X)=>{let ie="";o.open({title:"Rename session",children:e.jsx("input",{id:"rename-session-input",autoFocus:!0,defaultValue:X,"aria-label":"Session title",onChange:te=>{ie=te.target.value},onKeyDown:te=>{te.key==="Enter"&&(te.preventDefault(),o.close(),l.renameSession(L,ie).then(B=>{B&&c.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(T,{variant:"secondary",size:"sm",onClick:()=>o.close(),children:"Cancel"}),e.jsx(T,{variant:"primary",size:"sm",onClick:()=>{o.close(),l.renameSession(L,ie)},children:"Save"})]})})},$=(L,X)=>{o.open({title:"Delete session?",children:e.jsxs("p",{style:{margin:0},children:["Delete ",e.jsx("strong",{children:X}),"? Messages on the opencode serve will be removed. This cannot be undone."]}),footer:e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx(T,{variant:"secondary",size:"sm",onClick:()=>o.close(),children:"Cancel"}),e.jsx(T,{variant:"danger",size:"sm",onClick:async()=>{o.close(),await l.deleteSession(L)},children:"Delete"})]})})},N=()=>{const L=l.activeSource==="opencode"?l.activeOpencodeSessionId:l.sessionId;if(!L)return;const ie=(l.activeSource==="opencode"?l.opencodeMessages:l.bizarMessages).map(Q=>{const U=Q.ts??"",Z=(Q.role||"unknown").toUpperCase(),he=Q.content||Q.message||"";return`[${U}] ${Z}: ${he}`}).join(`
|
|
2
|
-
|
|
3
|
-
`),te=new Blob([ie],{type:"text/plain;charset=utf-8"}),B=URL.createObjectURL(te),H=document.createElement("a");H.href=B,H.download=`${L}.txt`,document.body.appendChild(H),H.click(),document.body.removeChild(H),URL.revokeObjectURL(B)},A=r.useMemo(()=>l.sessions.map(L=>l.getSessionDisplay(L)),[l.sessions,l.getSessionDisplay]),O=r.useMemo(()=>l.opencodeSessions.map(L=>l.getSessionDisplay(L)),[l.opencodeSessions,l.getSessionDisplay]),S=r.useMemo(()=>{const L=l.activeSource==="opencode"?l.activeOpencodeSessionId??"":l.sessionId;return L?A.find(X=>X.id===L)??O.find(X=>X.id===L)??null:null},[l.activeSource,l.activeOpencodeSessionId,l.sessionId,A,O]),F=(()=>{var ie;const L=`${h||"Odin"} · ${((ie=s.activeProject)==null?void 0:ie.name)??"no project"}`,X=(S==null?void 0:S.state)??"idle";return X==="streaming"?`Replying · ${L}`:X==="awaiting"?`Your turn · ${L}`:`${L} · idle`})(),Y=l.activeSource==="opencode"?"opencode":"bizar chat";return e.jsxs("div",{className:"chat-shell",children:[e.jsx(Zn,{activeProject:s.activeProject,sessionCount:l.sessions.length,sessionsOpen:!0,infoOpen:!0,onToggleSessions:()=>{},onToggleInfo:()=>{},onOpenOverview:()=>a==null?void 0:a("overview")}),e.jsxs("div",{className:"chat-page",children:[e.jsx(er,{sessions:A,opencodeSessions:O,activeSessionId:l.sessionId,activeOpencodeSessionId:l.activeOpencodeSessionId,activeProject:s.activeProject,creating:l.busy.create,onCreateSession:C,onSelectSession:l.selectBizarSession,onSelectOpencodeSession:L=>l.loadOpencodeSession(L.id),onRenameSession:P,onDeleteSession:L=>{const X=l.sessions.find(ie=>ie.id===L)??l.opencodeSessions.find(ie=>ie.id===L);$(L,(X==null?void 0:X.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:(S==null?void 0:S.title)??l.sessionId??"New chat"}),e.jsx("span",{className:`chat-source-badge chat-source-${l.activeSource??"none"}`,title:l.activeSource==="opencode"?"Messages go to the opencode serve child":"Messages go to the local chat store",children:Y})]}),e.jsxs("div",{className:`chat-thread-sub chat-muted state-${(S==null?void 0:S.state)??"idle"}`,children:[e.jsx("span",{className:"chat-thread-dot"}),F]}),l.opencodeError&&e.jsxs("div",{className:"chat-thread-error",role:"alert",children:[e.jsx("p",{className:"chat-error-message",children:l.opencodeError}),l.opencodeSuggestion&&e.jsx("p",{className:"chat-error-suggestion",children:l.opencodeSuggestion}),l.activeOpencodeSessionId&&e.jsx("button",{className:"btn btn-sm",type:"button",onClick:()=>l.loadOpencodeSession(l.activeOpencodeSessionId),children:"Retry"})]})]}),e.jsxs("div",{className:"chat-thread-actions",children:[S&&e.jsxs("button",{className:"btn btn-ghost",title:"Rename session",type:"button",disabled:l.busy.rename,onClick:()=>P(S.id,S.title??""),children:[e.jsx(Ns,{size:12,"aria-hidden":!0})," ",e.jsx("span",{className:"mono",children:"rename"})]}),S&&e.jsxs("button",{className:"btn btn-ghost btn-danger",title:"Delete session",type:"button",disabled:l.busy.delete,onClick:()=>$(S.id,S.title??S.id),children:[e.jsx(Se,{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:N,children:e.jsx("span",{className:"mono",children:"export"})})]})]}),e.jsx("div",{className:"chat-thread-scroll",ref:l.listRef,onScroll:l.handleScroll,role:"log","aria-live":"polite","aria-relevant":"additions","aria-label":"Chat message thread",children:e.jsx(ei,{messages:l.activeSource==="opencode"?l.opencodeMessages:l.bizarMessages,loading:l.loading,activeProject:s.activeProject,sessionId:l.activeSource==="opencode"?l.activeOpencodeSessionId??l.sessionId:l.sessionId,pinned:l.pinned,activeSource:l.activeSource,onPickSuggestion:L=>x(L),onCopy:L=>l.copyMessage(L),onDelete:f,onTogglePin:l.togglePin,onRegenerate:l.onRegenerate})}),!l.stickToBottom&&e.jsx(ir,{streaming:(S==null?void 0:S.state)==="streaming",newMessageCount:l.newMessageCount,onClick:l.jumpToLatest}),e.jsx(sr,{agent:h,setAgent:d,model:m,setModel:p,text:u,setText:x,sending:l.sending,activeSource:l.activeSource,onSend:z,attachments:g,setAttachments:j,suggestions:b,onPickSuggestion:L=>x(`${L.split(" ")[0]} `),agents:s.agents||[],onAttach:E}),e.jsx("input",{ref:v,type:"file",multiple:!0,style:{display:"none"},onChange:y,"aria-label":"Attach files to message",tabIndex:-1})]}),e.jsx(nr,{sessionId:l.activeSource==="opencode"?l.activeOpencodeSessionId??l.sessionId:l.sessionId,messages:l.activeSource==="opencode"?l.opencodeMessages:l.bizarMessages,pinned:l.pinned,agent:h,model:m,agents:s.agents||[],mcps:s.mcps||[],allCommands:k,activeSource:l.activeSource,onRename:()=>{S&&P(S.id,S.title??"")},onDelete:()=>{S&&$(S.id,S.title??S.id)},onExport:N,busy:l.busy})]})]})}function lr(s){return s==="ok"?"success":s==="warn"?"warning":s==="fail"?"error":s}function Ze({kind:s="neutral",children:t,className:a,dot:i=!1}){const n=lr(s);return e.jsxs("span",{className:V("badge",`badge-${n}`,a),title:`status: ${s}`,children:[i&&e.jsx("span",{className:"badge-dot"}),t]})}const qt=["bash","read","edit","write","webfetch","websearch","task","glob","grep"],Kt=["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"],Ks=[{id:"reasoning",label:"Reasoning",color:"var(--accent)"},{id:"code",label:"Code",color:"var(--info)"},{id:"design",label:"Design",color:"var(--success)"},{id:"planning",label:"Planning",color:"var(--warning)"},{id:"gitops",label:"GitOps",color:"var(--error)"},{id:"analysis",label:"Analysis",color:"var(--text-dim)"}];function or(s){var t;return((t=Ks.find(a=>a.id===s))==null?void 0:t.color)||"var(--text-dim)"}function cr({status:s,isStuck:t}){const a=t?"var(--error)":s==="working"?"var(--info)":s==="error"?"var(--error)":"var(--text-dim)";return e.jsx("span",{className:"agent-status-dot",style:{background:a}})}function dr({agent:s}){if(s.isStuck)return e.jsx(Ze,{kind:"error",dot:!0,children:"stuck"});const t=s.status||"idle";return t==="working"?e.jsx(Ze,{kind:"info",dot:!0,children:"working"}):t==="error"?e.jsx(Ze,{kind:"error",dot:!0,children:"error"}):e.jsx(Ze,{kind:"neutral",dot:!0,children:"idle"})}function mr({snapshot:s,refreshSnapshot:t}){const a=re(),i=Ae(),[n,c]=r.useState(s.agents||[]),[o,l]=r.useState(!s.agents),[u,x]=r.useState(""),[h,d]=r.useState("");r.useEffect(()=>{c(s.agents||[]),l(!s.agents)},[s.agents]);const m=async()=>{try{const y=await R.get("/agents");c(y.agents||[])}catch(y){a.error(`Agents load failed: ${y.message}`)}finally{l(!1)}},p=r.useMemo(()=>{let y=[...n];if(u&&(y=y.filter(z=>u==="__none__"?!z.category:(z.category||"")===u)),h){const z=h.toLowerCase();y=y.filter(C=>C.name.toLowerCase().includes(z)||(C.description||"").toLowerCase().includes(z)||(C.tags||[]).some(f=>f.toLowerCase().includes(z)))}return y.sort((z,C)=>z.name.localeCompare(C.name))},[n,u,h]),g=r.useMemo(()=>{const y=new Set;for(const z of n)for(const C of z.tags||[])y.add(C);return Array.from(y).sort()},[n]),j=()=>{let y=null,z=null,C=null,f=null,P=null,$=null,N=null,A=null,O=null;i.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:S=>y=S,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:S=>{z=S},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:S=>C=S,className:"select",defaultValue:"",children:[e.jsx("option",{value:"",children:"(provider default)"}),Kt.map(S=>e.jsx("option",{value:S,children:S},S))]})]}),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:S=>f=S,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:S=>P=S,className:"input",type:"color",defaultValue:"#8b5cf6"})]})]}),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:S=>O=S,className:"select",defaultValue:"",children:[e.jsx("option",{value:"",children:"(none)"}),Ks.map(S=>e.jsx("option",{value:S.id,children:S.label},S.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:S=>A=S,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:S=>N=S,className:"agent-tools",children:qt.map(S=>e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{type:"checkbox",value:S,"aria-label":S}),e.jsx("span",{children:S})]},S))})]}),e.jsx("label",{className:"field-label",htmlFor:"agent-new-prompt",children:"System prompt"}),e.jsx("textarea",{id:"agent-new-prompt",ref:S=>$=S,className:"textarea",rows:6,placeholder:"You are a..."})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx(T,{variant:"ghost",onClick:()=>i.close(),children:"Cancel"}),e.jsxs(T,{variant:"primary",onClick:async()=>{const S=((y==null?void 0:y.value)||"").trim();if(!/^[a-z0-9][a-z0-9-]{0,63}$/i.test(S)){a.warning("Invalid name (a-z, 0-9, dashes).");return}const F=[];N&&N.querySelectorAll('input[type="checkbox"]:checked').forEach(L=>{F.push(L.value)});const Y=((A==null?void 0:A.value)||"").split(",").map(L=>L.trim()).filter(Boolean);try{const L=await R.post("/agents",{name:S,description:((z==null?void 0:z.value)||"").trim(),model:(C==null?void 0:C.value)||"",mode:(f==null?void 0:f.value)||"subagent",color:(P==null?void 0:P.value)||"",tools:F,tags:Y,category:(O==null?void 0:O.value)||"",prompt:($==null?void 0:$.value)||""});c(X=>[...X,L]),a.success("Agent created."),i.close(),await t()}catch(L){a.error(`Create failed: ${L.message}`)}},children:[e.jsx(Es,{size:12})," Create"]})]})})},v=async y=>{let z=null,C=null,f=null,P=null,$=null,N=null,A=null,O=null;try{const S=await R.get(`/agents/${encodeURIComponent(y.name)}`);i.open({title:`Edit ${y.name}`,width:640,children:e.jsxs("div",{className:"agent-form",children:[e.jsxs("div",{className:"muted",children:["File: ",e.jsx("code",{children:S.path})]}),e.jsx("label",{className:"field-label",htmlFor:"agent-edit-desc",children:"Description"}),e.jsx("input",{id:"agent-edit-desc",ref:F=>{z=F},className:"input",type:"text",defaultValue:S.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:F=>C=F,className:"select",defaultValue:S.model,children:[e.jsx("option",{value:"",children:"(provider default)"}),Kt.map(F=>e.jsx("option",{value:F,children:F},F))]})]}),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=>f=F,className:"select",defaultValue:S.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:F=>P=F,className:"input",type:"color",defaultValue:S.color||"#8b5cf6"})]})]}),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:F=>O=F,className:"select",defaultValue:S.category||"",children:[e.jsx("option",{value:"",children:"(none)"}),Ks.map(F=>e.jsx("option",{value:F.id,children:F.label},F.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:F=>A=F,className:"input",type:"text",defaultValue:(S.tags||[]).join(", ")})]})]}),e.jsxs("fieldset",{children:[e.jsx("legend",{className:"field-label",style:{padding:0},children:"Tools"}),e.jsx("div",{ref:F=>N=F,className:"agent-tools",children:qt.map(F=>{var Y;return e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{type:"checkbox",value:F,"aria-label":F,defaultChecked:(Y=S.tools)==null?void 0:Y.includes(F)}),e.jsx("span",{children:F})]},F)})})]}),e.jsx("label",{className:"field-label",htmlFor:"agent-edit-prompt",children:"System prompt"}),e.jsx("textarea",{id:"agent-edit-prompt",ref:F=>$=F,className:"textarea",rows:8,defaultValue:S.prompt||""})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx(T,{variant:"ghost",onClick:()=>i.close(),children:"Cancel"}),e.jsxs(T,{variant:"primary",onClick:async()=>{const F=[];N&&N.querySelectorAll('input[type="checkbox"]:checked').forEach(L=>{F.push(L.value)});const Y=((A==null?void 0:A.value)||"").split(",").map(L=>L.trim()).filter(Boolean);try{const L=await R.put(`/agents/${encodeURIComponent(y.name)}`,{description:((z==null?void 0:z.value)||"").trim(),model:(C==null?void 0:C.value)||"",mode:(f==null?void 0:f.value)||"subagent",color:(P==null?void 0:P.value)||"",tools:F,tags:Y,category:(O==null?void 0:O.value)||"",prompt:($==null?void 0:$.value)||""});c(X=>X.map(ie=>ie.name===y.name?L:ie)),a.success("Agent saved."),i.close(),await t()}catch(L){a.error(`Save failed: ${L.message}`)}},children:[e.jsx(Es,{size:12})," Save"]})]})})}catch(S){a.error(`Load failed: ${S.message}`)}},k=async y=>{if(confirm(`Delete agent "${y.name}"? This removes ${y.path}.`))try{await R.del(`/agents/${encodeURIComponent(y.name)}`),c(z=>z.filter(C=>C.name!==y.name)),a.success("Agent deleted.")}catch(z){a.error(`Delete failed: ${z.message}`)}},b=async y=>{let z=null;i.open({title:`Invoke ${y.name}`,children:e.jsxs("div",{className:"invoke-form",children:[e.jsxs("p",{className:"muted invoke-form-meta mono",children:[y.model||"—"," · ",y.path]}),e.jsx("p",{className:"invoke-form-desc",children:y.description}),e.jsx("label",{className:"field-label",htmlFor:"invoke-prompt",children:"Prompt"}),e.jsx("textarea",{ref:C=>z=C,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(T,{variant:"ghost",onClick:()=>i.close(),children:"Cancel"}),e.jsxs(T,{variant:"primary",onClick:async()=>{const C=((z==null?void 0:z.value)||"").trim();if(!C){a.warning("Prompt is required.");return}try{await R.post(`/agents/${encodeURIComponent(y.name)}/invoke`,{prompt:C}),a.success(`Invoked ${y.name}.`),i.close()}catch(f){a.error(`Invoke failed: ${f.message}`)}},children:[e.jsx(ks,{size:14})," Invoke"]})]})})},w=async y=>{try{const z=await R.post(`/agents/${encodeURIComponent(y.name)}/restart`);c(C=>C.map(f=>f.name===y.name?z:f)),a.success(`${y.name} restarted.`)}catch(z){a.error(`Restart failed: ${z.message}`)}},E=async(y,z)=>{try{const C=await R.post(`/agents/${encodeURIComponent(y.name)}/status`,{status:z});c(f=>f.map(P=>P.name===y.name?C:P))}catch(C){a.error(`Status update failed: ${C.message}`)}};return e.jsxs("div",{className:"view view-agents",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(Qe,{size:18})," Agents (",p.length,")"]}),e.jsxs("p",{className:"view-subtitle",children:["The Norse pantheon — click ",e.jsx("kbd",{children:"Edit"})," to modify or ",e.jsx("kbd",{children:"Invoke"})," to dispatch."]})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs("div",{className:"search-input",children:[e.jsx("label",{htmlFor:"agents-search",className:"sr-only",children:"Search agents"}),e.jsx("input",{id:"agents-search",className:"input",type:"text",placeholder:"Search…",value:h,onChange:y=>d(y.target.value),"aria-label":"Search agents"})]}),e.jsx("label",{htmlFor:"agents-category-filter",className:"sr-only",children:"Filter by category"}),e.jsxs("select",{id:"agents-category-filter",className:"select select-sm",value:u,onChange:y=>x(y.target.value),children:[e.jsx("option",{value:"",children:"All categories"}),Ks.map(y=>e.jsx("option",{value:y.id,children:y.label},y.id)),e.jsx("option",{value:"__none__",children:"(no category)"})]}),e.jsxs(T,{variant:"secondary",size:"sm",onClick:m,children:[e.jsx(le,{size:14})," Refresh"]}),e.jsxs(T,{variant:"primary",size:"sm",onClick:j,children:[e.jsx(Re,{size:14})," New agent"]})]})]}),g.length>0&&e.jsxs("div",{className:"agent-tags-row",children:[e.jsx(xa,{size:12}),g.map(y=>e.jsx("span",{className:"tag",children:y},y))]}),o?e.jsx("div",{className:"view-loading",children:e.jsx(me,{size:"lg"})}):p.length===0?e.jsx(ge,{icon:e.jsx(Qe,{size:32}),title:"No agents found",message:"Run bizar in the terminal to install Bizar."}):e.jsx("div",{className:"agent-grid",children:p.map(y=>e.jsx(ur,{agent:y,onInvoke:()=>b(y),onEdit:()=>v(y),onDelete:()=>k(y),onRestart:()=>w(y),onSetStatus:z=>E(y,z)},y.name))})]})}function ur({agent:s,onInvoke:t,onEdit:a,onDelete:i,onRestart:n,onSetStatus:c}){const[o,l]=r.useState(!1),u=or(s.category),x=(s.status==="working"||!!s.currentTaskId)&&!s.isStuck;return e.jsxs(q,{variant:"elevated",interactive:!0,className:V("agent-card",x&&"is-working",s.isStuck&&"is-stuck"),children:[e.jsxs("div",{className:"agent-card-head",children:[e.jsxs("div",{className:"agent-card-name",children:[e.jsx(cr,{status:s.status,isStuck:s.isStuck}),s.name]}),e.jsxs("div",{className:"agent-card-badges",children:[s.category&&e.jsx("span",{className:"agent-card-category",style:{background:`color-mix(in srgb, ${u} 18%, transparent)`,color:u},children:s.category}),e.jsx(dr,{agent:s})]})]}),e.jsx("p",{className:"agent-card-desc",children:ra(s.description,200)}),e.jsxs("div",{className:"agent-card-meta",children:[e.jsx("span",{className:"mono",title:s.model||"",children:s.model||"—"}),e.jsx("span",{className:"tabular-nums muted",children:ze(s.mtime)})]}),s.tags&&s.tags.length>0&&e.jsx("div",{className:"agent-card-tags",children:s.tags.map(h=>e.jsx("span",{className:"agent-card-tag",children:h},h))}),(x||s.lastTask)&&e.jsxs("div",{className:"agent-card-activity",children:[s.currentTaskId&&e.jsxs("div",{className:"agent-card-row",children:[e.jsx($e,{size:12}),e.jsx("span",{className:"muted",children:"Working on"}),e.jsx("code",{className:"mono",children:s.currentTaskId})]}),s.lastTask&&!s.currentTaskId&&e.jsxs("div",{className:"agent-card-row",children:[e.jsx(Ve,{size:12}),e.jsx("span",{className:"muted",children:"Last"}),e.jsx("code",{className:"mono",children:s.lastTask.id}),e.jsx("span",{className:"muted tabular-nums",children:ze(s.lastTask.finishedAt)})]}),s.tasksTotal!=null&&s.tasksTotal>0&&e.jsxs("div",{className:"agent-card-row",children:[e.jsx(hn,{size:12}),e.jsx("span",{className:"muted",children:"Success rate"}),e.jsxs("span",{className:"tabular-nums",children:[Math.round((s.successRate||0)*100),"%"]}),e.jsxs("span",{className:"muted tabular-nums",children:["(",s.tasksSucceeded,"/",s.tasksTotal,")"]})]})]}),s.lastError&&e.jsxs("div",{className:"agent-card-error",children:[e.jsx(ke,{size:12}),e.jsxs("span",{className:"muted",children:["Last error: ",s.lastError.message]})]}),e.jsxs("div",{className:"agent-card-actions",children:[e.jsxs(T,{variant:"primary",size:"sm",onClick:t,children:[e.jsx(ks,{size:12})," Invoke"]}),e.jsxs(T,{variant:"secondary",size:"sm",onClick:a,children:[e.jsx(Ns,{size:12})," Edit"]}),(s.isStuck||s.status==="working"||s.status==="error")&&e.jsxs(T,{variant:"ghost",size:"sm",onClick:n,title:"Reset agent status",children:[e.jsx(it,{size:12})," Restart"]}),e.jsx(T,{variant:"ghost",size:"sm",onClick:i,children:e.jsx(Se,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":o?"Collapse":"Expand",onClick:()=>l(h=>!h),style:{marginLeft:"auto"},children:o?e.jsx(Be,{size:12}):e.jsx(Ge,{size:12})})]}),o&&e.jsxs("div",{className:"agent-card-expanded",children:[e.jsxs("div",{className:"agent-card-status-actions",children:[e.jsx("span",{className:"muted text-sm",children:"Set status:"}),e.jsx(T,{variant:s.status==="idle"?"primary":"ghost",size:"sm",onClick:()=>c("idle"),children:"Idle"}),e.jsx(T,{variant:s.status==="working"?"primary":"ghost",size:"sm",onClick:()=>c("working"),children:"Working"}),e.jsx(T,{variant:s.status==="error"?"primary":"ghost",size:"sm",onClick:()=>c("error"),children:"Error"})]}),e.jsxs("div",{className:"agent-card-meta",children:[e.jsx(Oe,{size:11}),e.jsx("code",{className:"mono agent-card-path",children:s.path})]})]})]})}function hr({id:s,children:t}){return e.jsx("div",{id:s,"data-block-id":s,className:V("glyph-richtext"),style:Ia,children:e.jsx(Ra,{remarkPlugins:[Ta],children:t})})}const xr={info:{bg:"var(--info-soft, rgba(96, 165, 250, 0.12))",border:"var(--info)",fg:"var(--info)",icon:at,label:"Note"},warn:{bg:"var(--warning-soft, rgba(251, 191, 36, 0.15))",border:"var(--warning)",fg:"var(--warning)",icon:ke,label:"Warning"},success:{bg:"var(--success-soft, rgba(52, 211, 153, 0.15))",border:"var(--success)",fg:"var(--success)",icon:Ve,label:"Success"},danger:{bg:"var(--error-soft, rgba(248, 113, 113, 0.12))",border:"var(--error)",fg:"var(--error)",icon:ns,label:"Danger"}};function pr({id:s,tone:t="info",children:a}){const i=xr[t],n=i.icon;return e.jsxs("div",{id:s,"data-block-id":s,className:V("glyph-callout",`glyph-callout-${t}`),style:{display:"flex",gap:12,padding:"12px 16px",margin:"12px 0",borderLeft:`3px solid ${i.border}`,background:i.bg,borderRadius:8,color:"var(--text)"},role:t==="danger"||t==="warn"?"alert":void 0,children:[e.jsx("div",{style:{flexShrink:0,color:i.fg,paddingTop:2},children:e.jsx(n,{size:18})}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontWeight:600,fontSize:13,color:i.fg,marginBottom:4},children:i.label}),e.jsx("div",{className:"glyph-richtext",style:{...Ia,fontSize:14},children:e.jsx(Ra,{remarkPlugins:[Ta],children:a})})]})]})}function gr({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(ls,{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 fr({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((i,n)=>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:i},n))})}),e.jsx("tbody",{children:a.map((i,n)=>e.jsx("tr",{style:{borderTop:n===0?"none":"1px solid var(--border)"},children:i.map((c,o)=>e.jsx("td",{style:{padding:"8px 12px",color:"var(--text)",verticalAlign:"top",wordBreak:"break-word"},children:c},o))},n))})]})})}function jr({id:s,tabs:t}){var c;const[a,i]=r.useState(((c=t[0])==null?void 0:c.id)??""),n=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 l=o.id===(n==null?void 0:n.id);return e.jsxs("button",{type:"button",role:"tab","aria-selected":l,onClick:()=>i(o.id),style:{padding:"6px 12px",fontSize:12,fontFamily:"var(--font-mono)",borderRadius:6,border:"none",cursor:"pointer",background:l?"var(--bg-elev)":"transparent",color:l?"var(--text-strong)":"var(--text-dim)",boxShadow:l?"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)})}),n&&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:n.code})}),n.caption&&e.jsx("div",{style:{padding:"8px 14px",borderTop:"1px solid var(--border)",fontSize:12,color:"var(--text-dim)",background:"var(--bg)"},children:n.caption})]})]})}function vr({id:s,title:t,question:a,options:i}){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:i.map(n=>{const c=!!n.recommended;return e.jsxs("div",{style:{position:"relative",padding:12,borderRadius:8,border:c?"2px solid var(--success)":"1px solid var(--border)",background:c?"var(--success-soft)":"var(--bg)"},children:[c&&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:n.label}),e.jsx("div",{style:{fontSize:13,color:"var(--text)"},children:n.detail})]},n.id)})})]})}function yr({id:s,questions:t}){const[a,i]=r.useState({});function n(c,o){i(l=>({...l,[c]: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(c=>e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[e.jsx("label",{htmlFor:`oq-${c.id}`,style:{fontSize:13,color:"var(--text)",fontWeight:500},children:c.label}),c.kind==="choice"&&e.jsxs("select",{id:`oq-${c.id}`,value:a[c.id]??"",onChange:o=>n(c.id,o.target.value),style:Gt,children:[e.jsx("option",{value:"",children:"— select —"}),(c.options??[]).map(o=>e.jsx("option",{value:o,children:o},o))]}),c.kind==="text"&&e.jsx("input",{id:`oq-${c.id}`,type:"text",value:a[c.id]??"",onChange:o=>n(c.id,o.target.value),style:Gt}),c.kind==="multi"&&e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4},children:(c.options??[]).map(o=>{const l=a[c.id]??[],u=l.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?l.filter(h=>h!==o):[...l,o];n(c.id,x)}}),e.jsx("span",{children:o})]},o)})})]},c.id))]})}const Gt={padding:"6px 10px",fontSize:13,borderRadius:6,border:"1px solid var(--border-strong)",background:"var(--bg)",color:"var(--text)",fontFamily:"inherit"},br={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 Nr({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(i=>{const n=br[i.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":i.change,title:i.change,style:{flexShrink:0,width:22,height:18,borderRadius:4,background:n.bg,color:n.fg,display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:10,fontWeight:700,fontFamily:"var(--font-mono)"},children:n.label}),e.jsx("span",{style:{fontFamily:"var(--font-mono)",color:"var(--text)",wordBreak:"break-all",flex:1},children:i.path}),i.note&&e.jsx("span",{style:{fontSize:12,color:"var(--text-dim)"},children:i.note})]},i.path)})})]})}function kr({id:s,filename:t,language:a,mode:i="unified",before:n,after:c}){const o=n.split(`
|
|
4
|
-
`),l=c.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(fn,{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:i})]}),x={margin:0,padding:0,fontFamily:"var(--font-mono)",fontSize:12.5,lineHeight:1.55,color:"var(--text)",background:"var(--bg-elev)"},h=(d,m,p)=>{const g={del:"var(--error-soft)",add:"var(--success-soft)",ctx:"transparent"},j={del:"var(--error)",add:"var(--success)",ctx:"var(--text-dim)"};return e.jsxs("div",{style:{display:"flex",padding:"0 12px",background:g[p]},children:[e.jsx("span",{style:{width:18,color:j[p],userSelect:"none",flexShrink:0},children:d}),e.jsx("span",{style:{whiteSpace:"pre",flex:1,overflowX:"auto"},children:m||" "})]})};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,i==="unified"?e.jsxs("pre",{style:x,children:[o.map((d,m)=>e.jsx("div",{children:h("-",d,"del")},`b${m}`)),l.map((d,m)=>e.jsx("div",{children:h("+",d,"add")},`a${m}`))]}):e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr"},children:[e.jsx("pre",{style:{...x,borderRight:"1px solid var(--border)"},children:o.map((d,m)=>e.jsx("div",{children:h("-",d,"del")},m))}),e.jsx("pre",{style:x,children:l.map((d,m)=>e.jsx("div",{children:h("+",d,"add")},m))})]})]})}const wr={up:{fg:"var(--success)",Icon:Be,label:"trending up"},down:{fg:"var(--error)",Icon:Be,label:"trending down"},flat:{fg:"var(--text-dim)",Icon:gn,label:"flat"}};function Sr({id:s,label:t,value:a,trend:i,hint:n}){const c=i?wr[i]: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}),c&&e.jsx("span",{"aria-label":c.label,style:{display:"inline-flex",alignItems:"center",color:c.fg,transform:c.Icon===Be&&i==="up"?"rotate(180deg)":void 0},children:e.jsx(c.Icon,{size:14})})]}),n&&e.jsx("div",{style:{fontSize:12,color:"var(--text-dim)"},children:n})]})}const Cr={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)"}},Me=160,Pe=56,hs=60,xs=80;function zr({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(Rr,{id:s})});const i=new Map(t.map(h=>[h.id,h])),n=Tr(t),c=Math.max(...n.map(h=>h.col))+1,o=Math.max(...n.map(h=>h.row))+1,l=c*(Me+hs)+hs,u=o*(Pe+xs)+xs;function x(h){if(!i.get(h))return null;const m=n.find(p=>p.id===h);return m?{x:hs+m.col*(Me+hs)+Me/2,y:xs+m.row*(Pe+xs)+Pe/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:l,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,d)=>{const m=x(h.from),p=x(h.to);if(!m||!p)return null;const g=p.x-m.x,j=p.y-m.y,v=g>=0?m.x+Me/2:m.x-Me/2,k=g>=0?p.x-Me/2:p.x+Me/2,b=j>=0?m.y+Pe/2:m.y-Pe/2,w=j>=0?p.y-Pe/2:p.y+Pe/2,E=(v+k)/2,y=(b+w)/2;return e.jsxs("g",{children:[e.jsx("line",{x1:v,y1:b,x2:k,y2:w,stroke:"var(--text-dim)",strokeWidth:1.5,markerEnd:`url(#arrow-${s})`}),h.label&&e.jsx("text",{x:E,y:y-4,fontSize:10,fill:"var(--text-dim)",textAnchor:"middle",fontFamily:"var(--font-mono)",children:h.label})]},d)}),t.map(h=>{const d=n.find(v=>v.id===h.id);if(!d)return null;const m=hs+d.col*(Me+hs),p=xs+d.row*(Pe+xs),g=Cr[h.type];if(h.type==="decision"){const v=m+Me/2,k=p+Pe/2,b=[[v,p],[m+Me,k],[v,p+Pe],[m,k]].map(w=>w.join(",")).join(" ");return e.jsxs("g",{children:[e.jsx("polygon",{points:b,fill:g.fill,stroke:g.stroke,strokeWidth:2}),e.jsx("foreignObject",{x:m+8,y:k-14,width:Me-16,height:28,children:e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,fontSize:12,color:g.fg,textAlign:"center",lineHeight:1.2,fontStyle:"italic",height:"100%"},children:[e.jsx(xn,{size:11}),h.label]})})]},h.id)}const j=h.type==="note";return e.jsxs("g",{children:[e.jsx("rect",{x:m,y:p,width:Me,height:Pe,rx:8,fill:g.fill,stroke:g.stroke,strokeWidth:j?1:2,strokeDasharray:j?"4 3":void 0}),e.jsx("foreignObject",{x:m+6,y:p+6,width:Me-12,height:Pe-12,children:e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,fontSize:12,color:g.fg,textAlign:"center",lineHeight:1.25,fontStyle:j?"italic":"normal",height:"100%"},children:[j&&e.jsx(pn,{size:11}),h.label]})})]},h.id)})]})})}function Rr({id:s}){return e.jsx("div",{id:s,style:{padding:20,textAlign:"center",color:"var(--text-dim)",fontSize:13},children:"No workflow steps."})}function Tr(s){return s.length===0?[]:s.map((t,a)=>({id:t.id,col:a,row:0}))}const Ia={fontSize:14,lineHeight:1.6,color:"var(--text)"};function $r({id:s,title:t,x:a,y:i,w:n,h:c,html:o}){return e.jsxs("figure",{id:s,"data-block-id":s,className:"glyph-mockup",style:{width:n,minHeight:c},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 Ar extends Le.Component{constructor(){super(...arguments);Cs(this,"state",{err:null})}static getDerivedStateFromError(a){return{err:a}}componentDidCatch(a,i){try{this.props.onError(this.props.blockId,this.props.blockType,a,i)}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 Mr(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 Ir={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 Lr(s){const t=[];let a={heading:null,blocks:[]};for(const i of s){const n=Ir[i.id]??null;n?((a.blocks.length>0||a.heading!==null)&&t.push(a),a={heading:n,blocks:[i]}):a.blocks.push(i)}return(a.blocks.length>0||a.heading!==null)&&t.push(a),t}function Er({slug:s,onClose:t,onCommentAdded:a}){var U,Z,he,Ne;const i=re(),[n,c]=r.useState(null),[o,l]=r.useState([]),[u,x]=r.useState(!0),[h,d]=r.useState(null),[m,p]=r.useState(null),[g,j]=r.useState(!1),[v,k]=r.useState(!1),[b,w]=r.useState(null),[E,y]=r.useState(null),[z,C]=r.useState(""),[f,P]=r.useState(null),[$,N]=r.useState([]),A=Le.useCallback((I,K,J)=>{N(oe=>oe.some(_=>_.blockId===I)?oe:[...oe,{blockId:I,blockType:K,message:J.message||String(J)}])},[]),O=r.useRef(null),S=r.useMemo(()=>n?Lr(n.blocks):[],[n]);r.useEffect(()=>{let I=!1;const K=5e3;return(async()=>{x(!0),d(null);try{const J=new Promise((se,W)=>setTimeout(()=>W(new Error("Request timed out after 5s")),K)),[oe,_]=await Promise.race([Promise.all([R.get(`/artifacts/${encodeURIComponent(s)}/render`),R.get(`/artifacts/${encodeURIComponent(s)}`)]),J]);if(I)return;c(oe);const D=(_==null?void 0:_.comments)??[];l(Array.isArray(D)?D:[])}catch(J){if(!I){const oe=J.message;d(oe),p(oe)}}finally{I||x(!1)}})(),()=>{I=!0}},[s]);function F(I){if(!O.current)return;I.preventDefault();const K=O.current.getBoundingClientRect();w({x:I.clientX,y:I.clientY,worldX:I.clientX-K.left,worldY:I.clientY-K.top})}async function Y(){if(!(!E||!z.trim()))try{const I=await R.post(`/artifacts/${encodeURIComponent(s)}/comments`,{x:E.worldX,y:E.worldY,text:z.trim(),author:"drb0rk"});l(K=>[...K,{id:I.id??`cmt_${Date.now()}`,x:E.worldX,y:E.worldY,text:z.trim(),author:"drb0rk",created:new Date().toISOString()}]),y(null),C(""),w(null),a==null||a(),i.success("Comment added")}catch(I){i.error(`Failed to add comment: ${I.message}`)}}async function L(){if(!g){j(!0);try{const I=await R.post(`/artifacts/${encodeURIComponent(s)}/submit`,{answers:[],submitter:"drb0rk"});I!=null&&I.ok?(i.success("Sent to agent — feedback.md written, status=review"),a==null||a()):i.error("Submit failed: server did not return ok=true")}catch(I){i.error(`Submit failed: ${I.message}`)}finally{j(!1)}}}function X(){k(I=>!I)}const ie=I=>{const K=I.id,J=I.data??{},oe=Mr(I);return oe.ok?e.jsx(Ar,{blockId:K,blockType:I.type,onError:A,children:te(I,K,J)},K):e.jsxs("div",{id:K,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:[I.type," block invalid"]}),e.jsxs("div",{style:{color:"var(--text-muted)",marginBottom:6},children:["block id: ",e.jsx("code",{children:K})]}),e.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:oe.error})]},K)},te=(I,K,J)=>{switch(I.type){case"RichText":return e.jsx(hr,{id:K,children:I.childrenMarkdown??""},K);case"Callout":return e.jsx(pr,{id:K,tone:J.tone??"info",children:I.childrenMarkdown??""},K);case"Checklist":return e.jsx(gr,{id:K,items:J.items??[]},K);case"Table":return e.jsx(fr,{id:K,columns:J.columns??[],rows:J.rows??[]},K);case"CodeTabs":return e.jsx(jr,{id:K,tabs:J.tabs??[]},K);case"Decision":return e.jsx(vr,{id:K,title:J.title,question:J.question,options:J.options??[]},K);case"OpenQuestions":return e.jsx(yr,{id:K,questions:J.questions??[]},K);case"FileTree":return e.jsx(Nr,{id:K,title:J.title,entries:J.entries??[]},K);case"Diff":return e.jsx(kr,{id:K,filename:J.filename,language:J.language,mode:J.mode??"unified",before:J.before??"",after:J.after??""},K);case"Stat":return e.jsx(Sr,{id:K,label:J.label??"",value:J.value,trend:J.trend,hint:J.hint},K);case"Workflow":return e.jsx(zr,{id:K,steps:J.steps??[],connections:J.connections},K);case"Mockup":return e.jsx($r,{id:K,title:J.title,x:J.x,y:J.y,w:J.w,h:J.h,html:J.html??""},K);case"Diagram":return e.jsx("div",{id:K,className:"glyph-block-placeholder",children:e.jsxs("em",{children:["[Diagram] ",K]})},K)}};if(u)return e.jsx("div",{className:"glyph-renderer glyph-renderer--loading",children:m?e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:"Failed to load glyph."}),e.jsx("pre",{children:m})]}):e.jsxs(e.Fragment,{children:[e.jsx(Dr,{})," Loading glyph…"]})});if(h||!n)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 B=((U=n.frontmatter)==null?void 0:U.title)??s,H=((Z=n.frontmatter)==null?void 0:Z.status)??"draft",Q=o.length;return e.jsxs("div",{className:`glyph-canvas ${v?"glyph-canvas--fullscreen":""}`,ref:O,onContextMenu:F,children:[e.jsxs("div",{className:"glyph-toolbar-floating",children:[e.jsxs("button",{className:"glyph-btn glyph-btn--primary glyph-btn--send",onClick:L,disabled:g,title:"Send comments + question answers to the agent — writes feedback.md, status=review",children:[e.jsx(cs,{size:14}),e.jsx("span",{children:"Send to agent"}),e.jsx("span",{className:"glyph-btn-badge",children:Q})]}),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(()=>{}),i.success("Link copied"))},children:e.jsx(jn,{size:15})}),e.jsx("button",{className:"glyph-icon-btn",title:"Undo",disabled:!0,children:e.jsx(vn,{size:15})}),e.jsx("button",{className:"glyph-icon-btn",title:"Redo",disabled:!0,children:e.jsx(yn,{size:15})}),e.jsx("button",{className:"glyph-icon-btn",title:v?"Exit fullscreen":"Fullscreen",onClick:X,children:e.jsx(bn,{size:15})}),e.jsx("button",{className:"glyph-icon-btn",title:"More",children:e.jsx(Nn,{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(tt,{size:15}),e.jsx("span",{className:"glyph-icon-btn-count",children:Q})]}),t&&e.jsx("button",{className:"glyph-icon-btn glyph-icon-btn--close",title:"Close",onClick:t,"aria-label":"Close",children:e.jsx(be,{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:B}),e.jsxs("div",{className:"glyph-meta",children:[e.jsx("span",{className:`glyph-status glyph-status--${H}`,children:H}),e.jsx("span",{className:"glyph-slug",children:s})]})]}),($.length>0||((he=n.errors)==null?void 0:he.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:$.length>0?`${$.length} block${$.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:[$.map((I,K)=>e.jsxs("li",{children:[e.jsx("strong",{children:I.blockType})," (",e.jsx("code",{children:I.blockId}),"): ",I.message]},`be-${K}`)),(Ne=n.errors)==null?void 0:Ne.map((I,K)=>e.jsxs("li",{children:[I.line?`line ${I.line}: `:"",I.message]},`ce-${K}`))]})]}),e.jsx("div",{className:"glyph-sections",children:S.map((I,K)=>e.jsxs("section",{className:`glyph-section ${I.heading?"glyph-section--headed":"glyph-section--plain"}`,children:[I.heading&&e.jsx("h2",{className:"glyph-section-heading",children:I.heading}),e.jsx("div",{className:"glyph-section-blocks",children:I.blocks.map(ie)})]},`sec-${K}-${I.heading??"ungrouped"}`))})]}),o.map(I=>e.jsxs("button",{className:`glyph-pin ${f===I.id?"glyph-pin--active":""}`,style:{left:I.x,top:I.y},onClick:K=>{K.stopPropagation(),P(f===I.id?null:I.id)},title:I.text,children:[e.jsx(Wt,{size:14}),f===I.id&&e.jsxs("div",{className:"glyph-pin-thread",children:[e.jsx("div",{className:"glyph-pin-text",children:I.text}),e.jsxs("div",{className:"glyph-pin-meta",children:[I.author??"anonymous"," · ",I.created?new Date(I.created).toLocaleString():""]})]})]},I.id)),b&&e.jsx("div",{className:"glyph-ctx-menu",style:{left:b.x,top:b.y},onClick:I=>I.stopPropagation(),children:e.jsxs("button",{className:"glyph-ctx-item",onClick:()=>{y({worldX:b.worldX,worldY:b.worldY}),w(null)},children:[e.jsx(Wt,{size:14})," Add comment here"]})}),E&&e.jsx("div",{className:"glyph-modal-overlay",onClick:()=>y(null),children:e.jsxs("div",{className:"glyph-modal",onClick:I=>I.stopPropagation(),children:[e.jsxs("h3",{children:["Add comment at (",Math.round(E.worldX),", ",Math.round(E.worldY),")"]}),e.jsx("textarea",{autoFocus:!0,value:z,onChange:I=>C(I.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:!z.trim(),children:"Add comment"})]})]})})]})}function Dr(){return e.jsx("span",{className:"glyph-spinner","aria-label":"loading",children:"…"})}function Pr(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 Fr({snapshot:s,refreshSnapshot:t}){const a=re(),[i,n]=r.useState(s.artifacts||[]),[c,o]=r.useState(!s.artifacts),[l,u]=r.useState(null),[x,h]=r.useState(""),[d,m]=r.useState(!1);r.useEffect(()=>{s.artifacts&&(n(s.artifacts),o(!1))},[s.artifacts]);const p=async()=>{try{const k=await R.get("/artifacts");n(k.artifacts||[]),o(!1)}catch(k){a.error(`Artifacts load failed: ${k.message}`),o(!1)}},g=r.useMemo(()=>{let k=i;if(x){const b=x.toLowerCase();k=k.filter(w=>(w.slug||"").toLowerCase().includes(b)||(w.title||"").toLowerCase().includes(b))}return d||(k=k.filter(b=>b.status!=="archived")),k},[i,x,d]),j=async(k,b)=>{try{const w=await R.post("/artifacts",{slug:k,title:b});a.success(`Artifact "${w.slug}" created.`),u(w.slug),await p()}catch(w){a.error(`Create failed: ${w.message}`)}},v=async k=>{if(confirm(`Delete artifact "${k}"? This removes the directory permanently.`))try{await R.del(`/artifacts/${encodeURIComponent(k)}`),a.success("Artifact deleted."),l===k&&u(null),await p()}catch(b){a.error(`Delete failed: ${b.message}`)}};return l?e.jsxs("div",{className:"artifact-glyph-overlay",children:[e.jsx("div",{className:"artifact-glyph-toolbar",children:e.jsxs(T,{variant:"ghost",onClick:()=>{u(null),p()},children:[e.jsx(Tt,{size:14})," Back to artifacts"]})}),e.jsx(Er,{slug:l,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(Xs,{size:18})," Glyphs (",i.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(pe,{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:k=>h(k.target.value),"aria-label":"Search artifacts"})]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:()=>m(k=>!k),title:d?"Hide archived":"Show archived",children:[d?e.jsx(pa,{size:14}):e.jsx(ua,{size:14}),d?"Hide archived":"Show archived"]}),e.jsxs(T,{variant:"secondary",size:"sm",onClick:p,children:[e.jsx(le,{size:14})," Refresh"]})]})]}),e.jsx(Or,{onCreate:j}),c?e.jsx("div",{className:"view-loading",children:e.jsx(me,{size:"lg"})}):g.length===0?e.jsx(ge,{icon:e.jsx(Xs,{size:32}),title:d?"No artifacts":"No artifacts yet",message:d?"No artifacts match your filter (try Show archived off).":"Create one above to get started."}):e.jsx("div",{className:"artifacts-grid",children:g.map(k=>e.jsx(Br,{artifact:k,onOpen:()=>u(k.slug),onDelete:()=>v(k.slug)},k.slug))})]})}function Or({onCreate:s}){const[t,a]=r.useState(""),[i,n]=r.useState("");return e.jsxs(q,{className:"new-artifact",children:[e.jsxs(ae,{children:[e.jsx(Re,{size:14})," New artifact"]}),e.jsx(ne,{children:"Slug must be lowercase, may contain hyphens, 1–64 chars."}),e.jsxs("form",{className:"new-artifact-form",onSubmit:c=>{c.preventDefault(),t.trim()&&(s(t.trim(),i.trim()||void 0),a(""),n(""))},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:c=>a(c.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:i,onChange:c=>n(c.target.value)}),e.jsx(T,{variant:"primary",type:"submit",children:"Create"})]})]})}function Br({artifact:s,onOpen:t,onDelete:a}){const i=Pr(s.status||"draft");return e.jsxs(q,{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(Ze,{kind:i,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 ",ze(s.mtime)]})]}),e.jsxs("div",{className:"artifact-card-actions",children:[e.jsxs(T,{variant:"primary",size:"sm",onClick:n=>{n.stopPropagation(),t()},children:["Open",e.jsx(Ge,{size:12})]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:n=>{n.stopPropagation(),a()},children:[e.jsx(Se,{size:12})," Delete"]})]})]})}function Ur({children:s,className:t,onRemove:a}){return e.jsxs("span",{className:V("tag",t),children:[s,a&&e.jsx("button",{type:"button",className:"tag-remove","aria-label":`Remove ${typeof s=="string"?s:"tag"}`,onClick:a,children:"×"})]})}function _r({task:s,agents:t,onPromote:a,onDelete:i,onEdit:n,onRefresh:c}){var h;const o=re(),l=async()=>{try{await R.post(`/tasks/${encodeURIComponent(s.id)}/promote`),o.success("Promoted to queued.",1500),a(s.id)}catch(d){o.error(`Promote failed: ${d.message}`)}},u=async()=>{if(confirm("Delete this task?"))try{await R.del(`/tasks/${encodeURIComponent(s.id)}`),o.success("Deleted.",1500),i(s.id)}catch(d){o.error(`Delete failed: ${d.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:ze(s.createdAt)}),e.jsxs("div",{className:"backlog-item-actions",children:[e.jsx("button",{type:"button",className:"icon-btn",title:"Promote to queued",onClick:l,children:e.jsx(It,{size:13})}),e.jsx("button",{type:"button",className:"icon-btn",title:"Edit",onClick:()=>n(s),children:e.jsx(He,{size:13})}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger",title:"Delete",onClick:u,children:e.jsx(Se,{size:13})})]})]})]})}function Wr({agents:s,onRefresh:t}){const a=re(),[i,n]=r.useState([]),[c,o]=r.useState(!1),l=async()=>{try{o(!0);const m=await R.get("/tasks/backlog");n(Array.isArray(m.tasks)?m.tasks:[])}catch(m){a.error(`Backlog load failed: ${m.message}`)}finally{o(!1)}};r.useEffect(()=>{l()},[]);const u=async m=>{n(p=>p.filter(g=>g.id!==m)),await t()},x=async m=>{n(p=>p.filter(g=>g.id!==m)),await t()},h=m=>{},d=async()=>{var m;if(i.length!==0)try{const g=((m=(await R.post("/tasks/promote-batch",{ids:i.map(j=>j.id)})).affected)==null?void 0:m.filter(j=>j.ok).length)??0;a.success(`Promoted ${g} task(s).`,2e3),n([]),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(Qs,{size:15}),"Backlog (",i.length,")"]}),e.jsxs("div",{className:"backlog-panel-header-actions",children:[i.length>0&&e.jsxs(T,{variant:"ghost",size:"sm",onClick:d,title:"Promote all to queued",children:[e.jsx(It,{size:12})," Promote all"]}),e.jsx(T,{variant:"ghost",size:"sm",onClick:l,title:"Refresh backlog","aria-label":"Refresh backlog",children:e.jsx(le,{size:12,className:c?"animate-spin":""})})]})]}),c?e.jsx("div",{className:"backlog-empty",children:"Loading…"}):i.length===0?e.jsxs("div",{className:"backlog-empty",children:[e.jsx(Qs,{size:28}),e.jsx("span",{children:"Backlog is empty."})]}):e.jsx("div",{className:"backlog-list",children:i.map(m=>e.jsx(_r,{task:m,agents:s,onPromote:u,onDelete:x,onEdit:h,onRefresh:t},m.id))})]})}const Gs=[{id:"queued",label:"Todo",kind:"info"},{id:"doing",label:"In progress",kind:"accent"},{id:"done",label:"Done",kind:"success"},{id:"blocked",label:"Failed",kind:"error"}],Ft=["low","normal","high"];function Vr({snapshot:s,refreshSnapshot:t,setActiveTab:a}){const i=re(),n=Ae(),[c,o]=r.useState(s.tasks||[]),[l,u]=r.useState(!s.tasks),[x,h]=r.useState(""),[d,m]=r.useState(""),[p,g]=r.useState(!1),[j,v]=r.useState(0),[k,b]=r.useState(""),w=async()=>{try{const N=await R.get("/tasks");o(Array.isArray(N)?N:[])}catch(N){i.error(`Tasks load failed: ${N.message}`)}finally{u(!1)}};r.useEffect(()=>{s.tasks&&(o(s.tasks),u(!1))},[s.tasks]),r.useEffect(()=>{const N=setInterval(()=>v(A=>A+1),3e4);return()=>clearInterval(N)},[]);const E=r.useMemo(()=>{let N=c.filter(A=>A.status!=="backlog");if(d&&(N=N.filter(A=>(A.priority||"normal")===d)),x.trim()){const A=x.toLowerCase();N=N.filter(O=>(O.title||"").toLowerCase().includes(A)||(O.description||"").toLowerCase().includes(A))}return N},[c,x,d]),y=r.useMemo(()=>{const N={high:0,normal:1,low:2};return[...E].sort((A,O)=>{const S=N[A.priority]??1,F=N[O.priority]??1;return S!==F?S-F:new Date(O.createdAt).getTime()-new Date(A.createdAt).getTime()})},[E]),z=c.filter(N=>N.status==="backlog").length,C=async(N,A)=>{const O=c.find(F=>F.id===N);if(!O)return;const S=O.status;o(F=>F.map(Y=>Y.id===N?{...Y,status:A}:Y)),b(`Task ${O.title} moved to ${A}.`);try{await R.patch(`/tasks/${encodeURIComponent(N)}/status`,{status:A}),i.success(`Moved to ${A}.`,1200)}catch(F){o(Y=>Y.map(L=>L.id===N?{...L,status:S}:L)),b(`Failed to move task ${O.title}: ${F.message}`),i.error(`Move failed: ${F.message}`)}},f=async N=>{if(confirm("Delete this task?"))try{await R.del(`/tasks/${encodeURIComponent(N)}`),o(A=>A.filter(O=>O.id!==N)),i.success("Task deleted.",1200)}catch(A){i.error(`Delete failed: ${A.message}`)}},P=async N=>{try{const A=await R.post(`/tasks/${encodeURIComponent(N)}/start`);A&&A.task&&o(O=>O.map(S=>S.id===N?A.task:S)),i.success("Retry dispatched.",1200)}catch(A){i.error(`Retry failed: ${A.message}`)}},$=async N=>{const A=c.find(O=>O.id===N);if(A)try{const O=await R.post("/tasks/submit",{title:A.title,description:A.description,priority:A.priority,tags:A.tags}),S=(O.subtasks||[]).length;i.success(S>1?`Odin split it into ${S} subtasks.`:"Sent to Odin.",1500),O.subtasks&&O.subtasks.length>0&&o(F=>[O.main,...O.subtasks,...F.filter(Y=>Y.id!==A.id)]),await t()}catch(O){i.error(`Submit failed: ${O.message}`)}};return e.jsxs("div",{className:"view view-tasks",children:[e.jsx("div",{className:"sr-only",role:"status","aria-live":"polite",children:k}),e.jsx("header",{className:"view-header",children:e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(Ms,{size:18})," Tasks (",y.length,")"]}),e.jsx("p",{className:"view-subtitle",children:"Add a task — title and description is all you need. Odin picks the agent and priority."})]})}),e.jsxs("div",{className:"tasks-toolbar",children:[e.jsx("div",{className:"tasks-toolbar-group",children:e.jsxs("div",{className:"search-input",style:{width:200},children:[e.jsx(pe,{size:12,"aria-hidden":!0}),e.jsx("input",{className:"input",type:"text",placeholder:"Search…",value:x,onChange:N=>h(N.target.value),"aria-label":"Search tasks"}),x&&e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Clear search",onClick:()=>h(""),children:e.jsx(be,{size:12})})]})}),e.jsx("div",{className:"tasks-toolbar-divider"}),e.jsxs("div",{className:"tasks-toolbar-group",children:[e.jsx("label",{className:"tasks-toolbar-label",htmlFor:"tasks-priority-filter",children:"Priority"}),e.jsxs("select",{id:"tasks-priority-filter",className:"select select-sm",value:d,onChange:N=>m(N.target.value),title:"Filter by priority",children:[e.jsx("option",{value:"",children:"All"}),Ft.map(N=>e.jsx("option",{value:N,children:N},N))]})]}),e.jsx("div",{className:"tasks-toolbar-spacer"}),e.jsxs("div",{className:"tasks-toolbar-group",children:[e.jsx(T,{variant:"ghost",size:"sm",onClick:w,title:"Refresh","aria-label":"Refresh tasks",children:e.jsx(le,{size:14})}),z>0&&e.jsxs(T,{variant:p?"accent":"ghost",size:"sm",onClick:()=>g(N=>!N),title:p?"Hide backlog":"Show backlog",children:[e.jsx(Qs,{size:14}),"Backlog",e.jsx("span",{className:"badge",children:z})]}),e.jsxs(T,{variant:"primary",size:"sm",onClick:()=>Kr(n,i,o,w,t),children:[e.jsx(Re,{size:14})," New task"]})]})]}),p&&z>0&&e.jsx(Wr,{agents:s.agents||[],onRefresh:t}),l?e.jsx("div",{className:"view-loading",children:e.jsx(me,{size:"lg"})}):e.jsx("div",{className:"kanban",children:Gs.map(N=>e.jsx(Hr,{column:N,tasks:y.filter(A=>A.status===N.id),onMove:C,onDelete:f,onRetry:P,onEdit:A=>Gr(n,i,A,o,w,t),onSubmitToOdin:$,tick:j},N.id))})]})}function Hr({column:s,tasks:t,onMove:a,onDelete:i,onRetry:n,onEdit:c,onSubmitToOdin:o,tick:l}){const[u,x]=r.useState(!1);return e.jsxs("div",{className:V("kanban-column",u&&"kanban-column-drop"),"data-column":s.id,onDragOver:h=>{h.preventDefault(),x(!0)},onDragLeave:()=>x(!1),onDrop:h=>{h.preventDefault(),x(!1);const d=h.dataTransfer.getData("text/task-id");d&&a(d,s.id)},children:[e.jsxs("div",{className:"kanban-col-header",children:[e.jsxs(ae,{children:[e.jsx("span",{className:V("status-dot",`status-${s.kind}`)}),s.label]}),e.jsx("span",{className:"kanban-col-count tabular-nums",children:t.length})]}),e.jsx("div",{className:"kanban-col-body",children:t.length===0?e.jsx("div",{className:"kanban-empty",children:"No tasks"}):t.map(h=>e.jsx(qr,{task:h,onMove:d=>{const p=Gs.findIndex(g=>g.id===h.status)+d;p>=0&&p<Gs.length&&a(h.id,Gs[p].id)},onEdit:()=>c(h),onDelete:()=>i(h.id),onRetry:()=>n(h.id),onSubmitToOdin:()=>o(h.id),tick:l},h.id))})]})}function qr({task:s,onMove:t,onEdit:a,onDelete:i,onRetry:n,onSubmitToOdin:c,tick:o}){const l=s.workedBy||s.assignee||null;return e.jsxs("div",{className:V("task-card",`priority-${s.priority}`),"data-task-id":s.id,draggable:!0,onDragStart:u=>{u.dataTransfer.setData("text/task-id",s.id),u.dataTransfer.effectAllowed="move"},"data-tick":o,children:[e.jsxs("div",{className:"task-card-head",children:[e.jsx("span",{className:"priority-dot",style:{background:Xa[s.priority]||"var(--info)"}}),e.jsx("div",{className:"task-card-title",children:s.title})]}),s.description&&e.jsx("div",{className:"task-card-desc",children:s.description.slice(0,160)}),e.jsxs("div",{className:"task-card-badges",children:[l&&e.jsxs("span",{className:"task-card-badge",title:`Auto-assigned to @${l}`,children:[e.jsx(Qe,{size:10})," @",l]}),s.timeSpent?e.jsxs("span",{className:"task-card-badge",children:[e.jsx(Is,{size:10})," ",Math.round((s.timeSpent||0)/60),"m"]}):null,s.tags&&s.tags.length>0&&s.tags.slice(0,3).map(u=>e.jsx(Ur,{children:u},u))]}),e.jsxs("div",{className:"task-card-footer",children:[e.jsx("span",{className:"task-card-time tabular-nums muted",children:ze(s.createdAt)}),e.jsxs("div",{className:"task-card-actions",onClick:u=>u.stopPropagation(),children:[e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Move left",title:"Move left",onClick:()=>t(-1),children:e.jsx(kn,{size:14})}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Edit",title:"Edit",onClick:a,children:e.jsx(wn,{size:14})}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Submit to Odin",title:"Re-delegate to Odin",onClick:c,children:e.jsx(cs,{size:14})}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Retry",title:"Retry",onClick:n,children:e.jsx(it,{size:14})}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger","aria-label":"Delete",title:"Delete",onClick:i,children:e.jsx(Se,{size:14})}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Move right",title:"Move right",onClick:()=>t(1),children:e.jsx(Ge,{size:14})})]})]})]})}function Kr(s,t,a,i,n){let c=null,o=null,l=null,u=null;const x=async d=>{d&&typeof d.preventDefault=="function"&&d.preventDefault();const m=((c==null?void 0:c.value)||"").trim(),p=((o==null?void 0:o.value)||"").trim();if(!m){t.warning("Title is required."),c==null||c.focus();return}const g=(u==null?void 0:u.value)||"normal",j=((l==null?void 0:l.value)||"").split(",").map(v=>v.trim()).filter(Boolean);try{const v=await R.post("/tasks",{title:m,description:p,priority:g,tags:j});s.close(),typeof window<"u"&&window.dispatchEvent(new MouseEvent("mousedown")),a(k=>[v,...k]),t.success("Task created.",1200),await n()}catch(v){t.error(`Create failed: ${v.message}`)}},h=d=>{d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),x(d))};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:d=>{c=d},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:d=>{o=d},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 m;if(!((m=o==null?void 0:o.value)!=null&&m.trim()))return;const d=await Ya(o.value);d!==o.value&&(o.value=d)},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:d=>{u=d},id:"task-priority",className:"select",defaultValue:"normal",children:Ft.map(d=>e.jsx("option",{value:d,children:d},d))})]}),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:d=>{l=d},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(T,{variant:"ghost",onClick:()=>s.close(),children:"Cancel"}),e.jsxs(T,{variant:"primary",type:"button",onClick:d=>x(d),children:[e.jsx(Re,{size:14})," Create task"]})]})})}function Gr(s,t,a,i,n,c){let o=null,l=null,u=null,x=null;const h=async()=>{const d=((o==null?void 0:o.value)||"").trim(),m=((l==null?void 0:l.value)||"").trim();if(!d){t.warning("Title is required."),o==null||o.focus();return}const p=(x==null?void 0:x.value)||"normal",g=((u==null?void 0:u.value)||"").split(",").map(j=>j.trim()).filter(Boolean);try{const j=await R.put(`/tasks/${encodeURIComponent(a.id)}`,{title:d,description:m,priority:p,tags:g});s.close(),typeof window<"u"&&window.dispatchEvent(new MouseEvent("mousedown")),i(v=>v.map(k=>k.id===a.id?j:k)),t.success("Task updated.",1200),await c()}catch(j){t.error(`Save failed: ${j.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:d=>{o=d},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:d=>{l=d},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:d=>{x=d},id:"edit-task-priority",className:"select",defaultValue:a.priority||"normal",children:Ft.map(d=>e.jsx("option",{value:d,children:d},d))})]}),e.jsxs("label",{htmlFor:"edit-task-tags",className:"task-form-field",style:{flex:2},children:["Tags",e.jsx("input",{ref:d=>{u=d},id:"edit-task-tags",className:"input",type:"text",defaultValue:(a.tags||[]).join(", "),placeholder:"comma-separated"})]})]}),e.jsxs(q,{children:[e.jsxs(ae,{children:[e.jsx(xa,{size:12})," Status"]}),e.jsxs(ne,{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(T,{variant:"ghost",onClick:()=>s.close(),children:"Cancel"}),e.jsxs(T,{variant:"primary",onClick:h,children:[e.jsx(pa,{size:14})," Save"]})]})})}const Yr=Le.memo(Vr);function Xr(s){return R.urlWithToken(`/artifacts/${encodeURIComponent(s)}/content`)}function Qr(s,t){const a=Xr(t);window.open(a,"_blank","noopener,noreferrer")}const Yt={"1m":60*1e3,"5m":5*60*1e3,"30m":30*60*1e3,"1h":60*60*1e3},Ie=56,qe=32,ps=22,Jr=4,Zr=.9,mt={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 ut(s){return s&&mt[s]||mt.idle}function Ws(s,t=24){return s?s.length<=t?s:s.slice(0,t-1)+"…":""}function et(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 ht(s){const t=s._timerStart;return typeof t=="number"&&t>0?t:et(s.createdAt)||Date.now()}function el(s,t){return(s.status==="done"||s.status==="archived"||s.status==="failed"||s.status==="killed")&&(et(s.completedAt)||et(s.updatedAt))||t}function sl(s){return typeof s.startedAt=="number"&&s.startedAt>0?s.startedAt:Date.now()}function tl(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 al(s){return s<=6e4?1e4:s<=3e5?3e4:s<=18e5?3e5:6e5}function nl(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 il({snapshot:s,refreshSnapshot:t}){const a=re(),i=r.useRef(null),[n,c]=r.useState("live"),[o,l]=r.useState("5m"),[u,x]=r.useState(()=>typeof window>"u"?!0:window.innerWidth>900),[h,d]=r.useState([]),[m,p]=r.useState([]),[g,j]=r.useState(!0),[v,k]=r.useState(0),[b,w]=r.useState(Date.now()),[E,y]=r.useState(()=>Date.now()-Yt["5m"]*.1),[z,C]=r.useState({width:800,height:400}),[f,P]=r.useState(null),[$,N]=r.useState(""),[A,O]=r.useState([]),[S,F]=r.useState(""),[Y,L]=r.useState("normal"),[X,ie]=r.useState(""),[te,B]=r.useState(""),[H,Q]=r.useState(!1),[U,Z]=r.useState(!1),[he,Ne]=r.useState([]),I=Ae(),K=s.agents||[],J=s.tasks||[],oe=Yt[o],_=E,D=E+oe,se=r.useCallback(async()=>{try{const[M,ee]=await Promise.all([R.get("/background").catch(()=>({instances:[]})),R.get("/activity?limit=200").catch(()=>({events:[]}))]);d(M.instances||[]),p(ee.events||[])}catch(M){console.warn("activity reload failed:",M)}finally{j(!1)}},[]);r.useEffect(()=>{se();const M=setInterval(se,3e3);return()=>clearInterval(M)},[se]),r.useEffect(()=>{k(M=>M+1)},[J.length,K.length]),r.useEffect(()=>{if(n==="pause")return;w(Date.now());const M=setInterval(()=>w(Date.now()),1e3);return()=>clearInterval(M)},[n,v]),r.useEffect(()=>{if(n==="pause")return;(b-E)/oe>Zr&&y(b-oe*.1)},[b,E,oe,n]),r.useEffect(()=>{y(Date.now()-oe*.1)},[o]),r.useEffect(()=>{n==="live"&&y(Date.now()-oe*.1)},[n]),r.useLayoutEffect(()=>{const M=i.current;if(!M)return;const ee=new ResizeObserver(fe=>{for(const je of fe){const{width:ue,height:ve}=je.contentRect;C({width:Math.max(200,Math.floor(ue)),height:Math.max(120,Math.floor(ve))})}});return ee.observe(M),()=>ee.disconnect()},[]);const W=r.useMemo(()=>{const M=[];let ee=0;for(const ue of h){const ve=sl(ue),De=tl(ue,b);De<_||ve>D||M.push({kind:"bg",id:`bg:${ue.instanceId}`,index:ee++,label:`BG ${Ws(ue.promptPreview,20)||ue.instanceId.slice(0,10)}`,sub:ue.status||"pending",start:ve,end:De,data:ue})}const fe=[...J].sort((ue,ve)=>ht(ue)-ht(ve)),je=[];for(const ue of fe){const ve=ht(ue),De=el(ue,b);if(De<_||ve>D)continue;let us=-1;for(let es=0;es<je.length;es++)if(je[es]<=ve){je[es]=De,us=es;break}us===-1&&(je.push(De),us=je.length-1),M.push({kind:"task",id:`task:${ue.id}`,index:ee+us,label:Ws(ue.title,32),sub:ue.status,start:ve,end:De,data:ue})}return M},[h,J,b,_,D]),ce=r.useMemo(()=>{const M=new Map;for(const ee of W)M.set(ee.id,ee);return M},[W]),G=r.useCallback(M=>oe<=0?0:(M-_)/oe*z.width,[_,oe,z.width]),de=r.useMemo(()=>{const M=al(oe),ee=[],fe=Math.floor(_/M)*M;for(let je=fe;je<=D+M;je+=M){if(je<_-M)continue;if(je>D)break;const ue=G(je);ue<-40||ue>z.width+40||ee.push({t:je,x:ue,label:nl(je,oe)})}return ee},[_,D,oe,z.width,G]),Te=r.useMemo(()=>{const M=[];for(const ee of W){if(ee.kind==="events")continue;const fe=Math.max(ee.start,_),je=Math.min(ee.end,D);if(je<_||fe>D)continue;const ue=G(fe),ve=G(je),De=Math.max(Jr,ve-ue),us=qe+ps+ee.index*Ie+8,es=Ie-16;let _e="doing";if(ee.kind==="bg"){const Ce=ee.data.status||"pending";Ce==="done"||Ce==="success"?_e="done":Ce==="failed"||Ce==="killed"||Ce==="error"?_e="failed":Ce==="queued"||Ce==="pending"?_e="queued":Ce==="blocked"||Ce==="stuck"?_e="blocked":_e="doing"}else{const Ce=ee.data.status;Ce==="done"||Ce==="archived"?_e="done":Ce==="failed"||Ce==="killed"?_e="failed":Ce==="queued"?_e="queued":Ce==="blocked"?_e="blocked":_e="doing"}const qa=(f==null?void 0:f.id)===ee.id;M.push({id:ee.id,laneIndex:ee.index,x:ue,y:us,w:De,h:es,label:ee.label,statusClass:_e,selected:qa,data:ee.data,kind:ee.kind,start:ee.start,end:ee.end})}return M},[W,G,f,_,D]),Ee=r.useMemo(()=>{const M=[];for(const ee of m){const fe=et(ee.ts);if(fe<_-5e3||fe>D+5e3)continue;const je=G(fe);let ue=qe+12;if(ee.taskId){const ve=ce.get(`task:${ee.taskId}`);ve&&(ue=qe+ps+ve.index*Ie+Ie/2)}else if(ee.nodeId){const ve=String(ee.nodeId),De=ce.get(ve.startsWith("task:")||ve.startsWith("bg:")?ve:`task:${ve}`);De&&(ue=qe+ps+De.index*Ie+Ie/2)}M.push({id:`${ee.ts}-${ee.kind}-${ee.author??""}-${ee.taskId??""}`,x:je,y:ue,kind:ee.kind||"event",ts:fe,text:String(ee.text||ee.kind||""),author:ee.author})}return M},[m,_,D,G,ce]),Ue=r.useMemo(()=>W.map(M=>({id:M.id,y:qe+ps+M.index*Ie,h:Ie})),[W]),Ye=r.useMemo(()=>{const M=G(b);return Math.max(0,Math.min(z.width,M))},[G,b,z.width]),Bs=r.useCallback(M=>{const fe={id:M.id,kind:M.kind,label:M.label,status:M.statusClass,data:M.data};P(fe)},[]);r.useEffect(()=>{if(!f){O([]),B(""),Ne([]);return}N(""),F(""),ie(""),Ne([]),(async()=>{try{const M=await R.get(`/activity?nodeId=${encodeURIComponent(f.id)}&limit=50`);O(M.events||[])}catch{O([])}if(f.kind==="bg"){const M=f.data;try{const ee=await R.get(`/background/${encodeURIComponent(M.instanceId)}/output?lines=80`);B(ee.output||"")}catch{B("")}if(M.taskId)try{const ee=await R.get(`/tasks/${encodeURIComponent(M.taskId)}/artifacts`);Ne((ee.artifacts||[]).map(fe=>fe.id))}catch{Ne([])}}})()},[f]);const ws=async()=>{if(!(!f||!$.trim())){Z(!0);try{await R.post("/comments",{nodeId:f.id,text:$,author:"user"}),N("");const M=await R.get(`/activity?nodeId=${encodeURIComponent(f.id)}&limit=50`);O(M.events||[]),a.success("Comment added.")}catch(M){a.error(`Comment failed: ${M.message}`)}finally{Z(!1)}}},Us=async()=>{if(!(!f||!S.trim())){Q(!0);try{await R.post(`/nodes/${encodeURIComponent(f.id)}/tasks`,{title:S,description:`Created from timeline selection ${f.id}.`,priority:Y}),F(""),a.success("Task created."),await t()}catch(M){a.error(`Task create failed: ${M.message}`)}finally{Q(!1)}}},Ss=async()=>{if(!f||f.kind!=="bg"||!X.trim())return;const M=f.data;try{const ee=await R.post(`/background/${encodeURIComponent(M.instanceId)}/message`,{message:X});ee.ok?(a.success("Message sent."),ie("")):a.warning(ee.error||"Send failed")}catch(ee){a.error(`Send failed: ${ee.message}`)}},Wa=async()=>{if(!f||f.kind!=="bg"||!confirm("Kill this bg instance session?"))return;const M=f.data;try{const ee=await R.del(`/background/${encodeURIComponent(M.instanceId)}`);ee.ok?a.success("Session killed."):a.warning(ee.error||"Kill failed"),await se()}catch(ee){a.error(`Kill failed: ${ee.message}`)}},Va=async()=>{if(!f||f.kind!=="bg")return;const M=f.data;try{const ee=await R.get(`/background/${encodeURIComponent(M.instanceId)}/output?lines=80`);B(ee.output||"")}catch{}};r.useEffect(()=>{const M=ee=>{ee.key==="Escape"&&P(null)};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[]);const Ha=()=>{k(M=>M+1),se()},rt=qe+ps+W.length*Ie;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($e,{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(T,{variant:n==="live"?"primary":"secondary",size:"sm",onClick:()=>c(n==="live"?"pause":"live"),title:n==="live"?"Pause timeline":"Resume timeline",children:[n==="live"?e.jsx(ga,{size:14}):e.jsx(ks,{size:14}),n==="live"?"Live":"Paused"]}),e.jsx("div",{className:"tl-zoom-group",children:["1m","5m","30m","1h"].map(M=>e.jsx("button",{type:"button",className:V("tl-zoom-btn",o===M&&"tl-zoom-btn-active"),onClick:()=>l(M),title:`Zoom to ${M}`,children:M},M))}),e.jsxs(T,{variant:"secondary",size:"sm",onClick:Ha,title:"Refresh",children:[e.jsx(le,{size:14})," Refresh"]})]})})]}),g&&e.jsx("div",{className:"view-loading",children:e.jsx(me,{size:"lg"})}),!g&&K.length===0&&J.length===0&&h.length===0&&m.length===0?e.jsx(ge,{icon:e.jsx($e,{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:V("tl-view",f&&"tl-view-detail-open"),children:e.jsxs("div",{className:V("tl-body",!u&&"tl-body-stream-collapsed"),children:[e.jsxs("aside",{className:V("tl-stream",!u&&"tl-stream-collapsed"),children:[e.jsxs("div",{className:"tl-stream-head",children:[e.jsxs("h3",{children:[e.jsx(Ls,{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(Sn,{size:14})})]}),e.jsx("div",{className:"tl-stream-list",children:m.length===0?e.jsx("div",{className:"tl-stream-empty",children:e.jsx("p",{children:"No events yet."})}):e.jsx(Pt,{items:[...m].reverse(),itemHeight:40,height:400,className:"tl-stream-virtual",renderItem:M=>{const ee=M.author?Qe:M.kind==="task"?Ms:M.kind==="bg"?qs:$e;return e.jsxs("div",{className:"tl-stream-event",children:[e.jsx("span",{className:"tl-stream-event-time",children:new Date(M.ts).toLocaleTimeString("en-GB",{hour12:!1})}),e.jsx("span",{className:"tl-stream-event-icon",style:{color:ut(M.kind)},children:e.jsx(ee,{size:12})}),e.jsx("span",{className:"tl-stream-event-text",children:M.author||M.text||M.kind})]})}})})]}),e.jsxs("div",{className:"tl-canvas-wrap",ref:i,children:[e.jsxs("div",{className:"tl-canvas-toolbar",children:[e.jsxs("div",{className:"tl-canvas-toolbar-left",children:[!u&&e.jsxs(T,{variant:"ghost",size:"sm",onClick:()=>x(!0),title:"Show event stream",children:[e.jsx(Cn,{size:14})," Events"]}),e.jsx("span",{className:"tl-canvas-mode",children:n==="live"?"● Live":"⏸ Paused"}),e.jsxs("span",{className:"tl-canvas-range",children:[new Date(_).toLocaleTimeString("en-GB",{hour12:!1})," →"," ",new Date(D).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(zn,{size:11})," agent"]}),e.jsxs("span",{className:"tl-legend-item",children:[e.jsx(Rn,{size:11})," task"]}),e.jsxs("span",{className:"tl-legend-item",children:[e.jsx(qs,{size:11})," bg"]})]})]}),e.jsx("div",{className:"tl-canvas-scroll",children:e.jsxs("svg",{className:"tl-canvas",width:z.width,height:Math.max(z.height,rt),role:"application","aria-label":"Activity timeline",children:[e.jsx("defs",{children:e.jsx("pattern",{id:"tl-canvas-grid",width:z.width,height:Ie,patternUnits:"userSpaceOnUse",children:e.jsx("path",{d:`M 0 0 L 0 ${Ie}`,fill:"none",stroke:"var(--border)",strokeWidth:.5,opacity:.35})})}),e.jsx("rect",{width:"100%",height:"100%",fill:"url(#tl-canvas-grid)"}),Ue.map(M=>e.jsx("rect",{className:"tl-lane-bg",x:0,y:M.y,width:z.width,height:M.h,fill:M.id.charCodeAt(M.id.length-1)%2===0?"var(--bg-elev-2)":"var(--bg-elev)",opacity:.4},`bg-${M.id}`)),e.jsx("g",{className:"tl-time-axis",children:de.map(M=>e.jsxs("g",{children:[e.jsx("line",{x1:M.x,y1:0,x2:M.x,y2:rt,stroke:"var(--border)",strokeWidth:.5,strokeDasharray:"2,4",opacity:.5}),e.jsx("text",{x:M.x+4,y:qe-8,fontSize:10,fontFamily:"var(--font-mono)",fill:"var(--text-dim)",children:M.label})]},`tick-${M.t}`))}),W.map(M=>{const ee=qe+ps+M.index*Ie+Ie/2;return e.jsxs("g",{className:"tl-lane-label-group",children:[e.jsx("text",{x:6,y:ee-2,className:"tl-lane-label",textAnchor:"start",children:Ws(M.label,28)}),e.jsx("text",{x:6,y:ee+10,className:"tl-lane-label-sub",textAnchor:"start",children:M.sub})]},`label-${M.id}`)}),Te.map(M=>{const ee=ut(M.statusClass),fe=M.id===(f==null?void 0:f.id);return e.jsxs("g",{className:V("tl-task-bar",`tl-task-bar-${M.statusClass}`,fe&&"tl-task-bar-selected"),onClick:()=>Bs(M),children:[e.jsx("rect",{x:M.x,y:M.y,width:M.w,height:M.h,rx:6,fill:ee,fillOpacity:M.statusClass==="done"?.35:M.statusClass==="queued"?.18:.85,stroke:ee,strokeWidth:fe?2.5:1.5,strokeOpacity:M.statusClass==="done"?.5:1,strokeDasharray:M.statusClass==="queued"?"4 4":void 0,style:{cursor:"pointer"}}),M.w>36&&e.jsx("text",{x:M.x+8,y:M.y+M.h/2+4,fontSize:11,fontFamily:"var(--font-sans)",fontWeight:500,fill:"var(--text-strong)",style:{pointerEvents:"none"},opacity:M.statusClass==="done"?.7:1,children:Ws(M.label,Math.max(4,Math.floor(M.w/7)))})]},`bar-${M.id}`)}),Ee.map(M=>{const ee=ut(M.kind);return e.jsxs("g",{className:"tl-event-marker-group",children:[e.jsx("line",{x1:M.x,y1:M.y-6,x2:M.x,y2:M.y+6,stroke:ee,strokeWidth:1.2,opacity:.7}),e.jsx("circle",{cx:M.x,cy:M.y,r:4,fill:ee,opacity:.9,children:e.jsx("title",{children:`${M.kind}${M.author?` · ${M.author}`:""} · ${new Date(M.ts).toLocaleTimeString("en-GB",{hour12:!1})}`})})]},`ev-${M.id}`)}),e.jsx("line",{className:"tl-now-line",x1:Ye,y1:0,x2:Ye,y2:rt,stroke:"var(--error)",strokeWidth:1.5,opacity:.9}),e.jsxs("g",{className:"tl-now-marker",children:[e.jsx("circle",{cx:Ye,cy:qe-4,r:4,fill:"var(--error)"}),e.jsx("text",{x:Ye+6,y:qe-4,fontSize:10,fontWeight:700,fill:"var(--error)",fontFamily:"var(--font-mono)",children:"now"})]})]})})]}),f&&e.jsx("aside",{className:"tl-detail tl-detail-enter",children:e.jsxs(q,{children:[e.jsxs(ae,{children:[f.kind==="agent"&&e.jsx(Qe,{size:14}),f.kind==="task"&&e.jsx(Ms,{size:14}),f.kind==="bg"&&e.jsx(qs,{size:14}),f.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(be,{size:14})})]}),e.jsxs("div",{className:"tl-detail-meta",children:[e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"type"})," ",f.kind]}),e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"status"})," ",e.jsx("code",{children:f.status})]}),f.kind==="agent"&&(()=>{const M=f.data;return e.jsxs(e.Fragment,{children:[M.role&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"role"})," ",M.role]}),M.model&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"model"})," ",M.model]})]})})(),f.kind==="task"&&(()=>{const M=f.data;return e.jsxs(e.Fragment,{children:[M.assignee&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"assignee"})," @",M.assignee]}),M.priority&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"priority"})," ",M.priority]}),M.createdAt&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"created"})," ",new Date(M.createdAt).toLocaleString()]})]})})(),f.kind==="bg"&&(()=>{const M=f.data;return e.jsxs(e.Fragment,{children:[M.startedAt&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"started"})," ",new Date(M.startedAt).toLocaleString()]}),M.tmuxSession&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"tmux"})," ",e.jsx("code",{children:M.tmuxSession})," ",M.tmuxActive?e.jsx("span",{className:"tag tag-success",children:"active"}):e.jsx("span",{className:"tag",children:"inactive"})]})]})})()]}),f.kind==="task"&&f.data.description&&e.jsx("div",{className:"tl-detail-desc",children:f.data.description}),f.kind==="bg"&&f.data.promptPreview&&e.jsx("div",{className:"tl-detail-desc",children:f.data.promptPreview}),f.kind==="bg"&&e.jsxs("div",{className:"tl-detail-bg",children:[e.jsx("pre",{className:"tl-bg-output",children:te||"(no output — start the session via tmux attach)"}),e.jsxs("div",{className:"tl-bg-output-actions",children:[e.jsxs(T,{variant:"ghost",size:"sm",onClick:Va,children:[e.jsx(le,{size:12})," Refresh output"]}),he.length>0&&e.jsxs(T,{variant:"secondary",size:"sm",onClick:()=>Qr(I,he[0]),children:[e.jsx(we,{size:12})," Open artifact"]}),e.jsxs(T,{variant:"danger",size:"sm",onClick:Wa,children:[e.jsx(Se,{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:X,onChange:M=>ie(M.target.value),onKeyDown:M=>{M.key==="Enter"&&Ss()},"aria-label":"Send a message to this bg session"}),e.jsxs(T,{variant:"primary",size:"sm",disabled:!X.trim(),onClick:Ss,children:[e.jsx(cs,{size:12})," Send"]})]})]}),f.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:S,onChange:M=>F(M.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:M=>L(M.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(T,{variant:"primary",size:"sm",disabled:!S.trim()||H,onClick:Us,children:[e.jsx(Re,{size:12})," Add task"]})]})]}),e.jsxs("div",{className:"tl-detail-comments",children:[e.jsxs("div",{className:"field-label",children:[e.jsx(tt,{size:12})," Comments & activity"]}),e.jsxs("ul",{className:"comment-list",children:[A.length===0&&e.jsx("li",{className:"muted",children:"No comments yet."}),A.map((M,ee)=>e.jsxs("li",{className:"comment-item",children:[e.jsxs("div",{className:"comment-head",children:[e.jsx("strong",{children:M.author||"system"}),e.jsxs("span",{className:"muted",children:[M.kind," · ",new Date(M.ts).toLocaleString()]})]}),M.text&&e.jsx("div",{className:"comment-text",children:M.text}),M.taskId&&e.jsxs("div",{className:"muted",children:["→ task ",e.jsx("code",{children:String(M.taskId)})]})]},`c-${ee}`))]}),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:$,onChange:M=>N(M.target.value),onKeyDown:M=>{M.key==="Enter"&&!M.shiftKey&&ws()},"aria-label":"Add a comment"}),e.jsxs(T,{variant:"secondary",size:"sm",disabled:!$.trim()||U,onClick:ws,children:[e.jsx(cs,{size:12})," Post"]})]})]})]})},f.id)]})})]})}function rl(s,t){const a=s.length,i=t.length,n=Array.from({length:i+1},()=>Array(a+1).fill(0));for(let c=0;c<=a;c++)n[0][c]=c;for(let c=0;c<=i;c++)n[c][0]=c;for(let c=1;c<=i;c++)for(let o=1;o<=a;o++){const l=s[o-1]===t[c-1]?0:1;n[c][o]=Math.min(n[c][o-1]+1,n[c-1][o]+1,n[c-1][o-1]+l)}return n[i][a]}function xt(s,t){if(t===s)return 100;if(t.startsWith(s))return 90;const a=t.split(/\s+/);for(const c of a)if(c.startsWith(s))return 80;const i=Math.min(s.length,t.length);return rl(s,t.substring(0,i))<=2?40:t.includes(s)?30:0}function ll(s,t){const a=s.toLowerCase().trim();return a?t.map(i=>{const n=xt(a,i.label.toLowerCase()),c=i.value?xt(a,String(i.value).toLowerCase()):0,o=i.description?xt(a,i.description.toLowerCase()):0,l=Math.max(n,c,o);if(l===0)return null;const u=n>=c&&n>=o?"label":c>=n&&c>=o?"value":"description",x=u==="label"?i.label:u==="value"?String(i.value):i.description;return{...i,score:l,matchedField:u,matchedTerm:x}}).filter(i=>i!==null).sort((i,n)=>n.score-i.score):[]}const Ot="bizar_settings_recent";function La(){try{const s=localStorage.getItem(Ot);return s?JSON.parse(s):[]}catch{return[]}}function ol(s){if(s)try{const t=La().filter(a=>a!==s);t.unshift(s),localStorage.setItem(Ot,JSON.stringify(t.slice(0,5)))}catch{}}function cl(s,t){if(!t)return s;const a=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`(${a})`,"gi");return s.split(i).map((c,o)=>i.test(c)?e.jsx("mark",{children:c},o):e.jsx("span",{children:c},o))}function dl(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 i of a.fields)t.push({key:i.key,label:i.label,section:a.id,value:i.value})}return t}function ml({sections:s,onJump:t}){const[a,i]=r.useState(""),[n,c]=r.useState([]),[o,l]=r.useState(0),[u,x]=r.useState(null),[h,d]=r.useState(!1),m=r.useRef(null),p=r.useRef(null),g=r.useRef(null),j=r.useRef([]);r.useEffect(()=>{j.current=dl(s)},[s]);const v=r.useCallback(($,N=!1)=>{if(p.current&&clearTimeout(p.current),!$.trim()){c([]),l(0);return}const A=()=>{const O=ll($,j.current);c(O),l(0)};N?A():p.current=setTimeout(A,150)},[]);r.useEffect(()=>{v(a)},[a,v]),r.useEffect(()=>()=>{p.current&&clearTimeout(p.current),g.current&&clearTimeout(g.current)},[]);const k=($,N)=>{const A=document.querySelector(`[data-section="${$}"] [data-setting-id="${N}"]`);A&&(A.scrollIntoView({behavior:"smooth",block:"center"}),A.classList.add("setting-flash"),setTimeout(()=>A.classList.remove("setting-flash"),2e3));const O=document.querySelector(`[data-section="${$}"]`);O&&O.scrollIntoView({behavior:"smooth",block:A?"nearest":"start"})},b=$=>{x($),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>x(null),1500);const N=document.querySelector(`[data-section="${$}"]`);N&&N.scrollIntoView({behavior:"smooth",block:"start"})},w=$=>{var N;ol(a),$.key===$.section?(b($.section),t($.section)):(b($.section),t($.section,$.key),k($.section,$.key)),i(""),(N=m.current)==null||N.blur()},E=$=>{var N;$.key==="Escape"?(i(""),(N=m.current)==null||N.blur()):$.key==="ArrowDown"?($.preventDefault(),l(A=>Math.min(A+1,n.length-1))):$.key==="ArrowUp"?($.preventDefault(),l(A=>Math.max(A-1,0))):$.key==="Enter"&&($.preventDefault(),n.length===0&&a.trim()&&v(a,!0),n[o]&&w(n[o]))},y=$=>{w($)},z=La(),C=$=>{var N;i($),(N=m.current)==null||N.focus()},f=()=>{try{localStorage.removeItem(Ot)}catch{}d($=>$)},P=h&&!a.trim()&&z.length>0;return e.jsxs("div",{className:"settings-search",children:[e.jsxs("div",{className:"settings-search-input-wrap",children:[e.jsx(pe,{size:13,className:"settings-search-icon"}),e.jsx("input",{ref:m,className:"settings-search-input",placeholder:"Search settings…",value:a,onChange:$=>i($.target.value),onKeyDown:E,onFocus:()=>d(!0),onBlur:()=>setTimeout(()=>d(!1),150),"aria-label":"Search settings"}),a&&e.jsx("button",{type:"button",className:"icon-btn settings-search-clear",onClick:()=>i(""),"aria-label":"Clear search",children:e.jsx(be,{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:f,tabIndex:-1,children:"Clear"})]}),z.map($=>e.jsxs("button",{type:"button",className:"settings-search-recent-item",onMouseDown:N=>{N.preventDefault(),C($)},children:[e.jsx(pe,{size:11}),e.jsx("span",{children:$})]},$))]}),a&&n.length>0&&e.jsx("div",{className:"settings-search-results",children:n.map(($,N)=>e.jsxs("button",{type:"button",className:V("settings-search-result",N===o&&"settings-search-result-active"),onClick:()=>y($),onMouseEnter:()=>l(N),children:[e.jsx("span",{className:V("settings-search-result-type",$.key===$.section&&"settings-search-result-type-section"),children:$.key===$.section?"section":"field"}),e.jsx("span",{className:"settings-search-result-label",children:cl($.label,a)}),$.key!==$.section&&e.jsx("span",{className:"settings-search-result-key mono muted",children:$.key})]},`${$.section}::${$.key}`))}),a&&n.length===0&&e.jsx("div",{className:"settings-search-empty muted",children:"No matching settings."})]})}const ul=[{id:"dark",label:"Dark",Icon:Tn},{id:"light",label:"Light",Icon:$n},{id:"system",label:"System",Icon:An}],hl=[{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"}],xl=["Inter","system-ui","Segoe UI","Roboto","JetBrains Mono","SF Mono","Cascadia Code"];function pl({settings:s,patchTheme:t,patchUi:a}){return e.jsxs(q,{id:"settings-theme","data-section":"theme",children:[e.jsxs(ae,{children:[e.jsx(ma,{size:14})," Theme"]}),e.jsx(ne,{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:hl.map(i=>e.jsxs("button",{type:"button",className:V("theme-preset",s.theme.accent===i.accent&&"theme-preset-active"),onClick:()=>t({accent:i.accent}),title:i.name,children:[e.jsx("span",{className:"theme-preset-swatch",style:{background:i.accent}}),e.jsx("span",{className:"theme-preset-name",children:i.name})]},i.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:ul.map(({id:i,label:n,Icon:c})=>{const o=s.theme.mode===i;return e.jsxs("button",{type:"button",className:V("theme-card",o&&"theme-card-active"),onClick:()=>t({mode:i}),children:[e.jsx(c,{size:16}),e.jsx("span",{className:"theme-card-label",children:n}),e.jsx("span",{className:V("theme-card-swatch",`theme-card-swatch-${i}`)})]},i)})})]}),e.jsx("div",{className:"theme-colors",children:["accent","success","warning","error","info"].map(i=>e.jsxs("div",{className:"field","data-setting-id":`theme.${i}`,children:[e.jsx("label",{className:"field-label",children:i.charAt(0).toUpperCase()+i.slice(1)}),e.jsxs("div",{className:"color-row",children:[e.jsx("input",{type:"color",className:"input color-input",value:s.theme[i],onChange:n=>t({[i]:n.target.value}),"aria-label":`${i} color`}),e.jsx("input",{type:"text",className:"input",value:s.theme[i],onChange:n=>t({[i]:n.target.value}),"aria-label":`${i} color hex`})]})]},i))}),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:i=>t({fontFamily:i.target.value}),children:xl.map(i=>e.jsx("option",{value:i,children:i},i))})]}),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:i=>t({fontSize:Number(i.target.value)})})]}),e.jsxs("label",{className:"checkbox-row","data-setting-id":"theme.compactMode",children:[e.jsx("input",{type:"checkbox",checked:s.theme.compactMode,onChange:i=>t({compactMode:i.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:i=>t({animations:i.target.checked})}),e.jsx("span",{children:"Enable animations"})]})]})}const pt=[{id:"bizar",name:"Bizar CLI"},{id:"bizar-dash",name:"Dashboard"},{id:"bizar-plugin",name:"Opencode Plugin"}];function gl(){const s=re(),[t,a]=r.useState({current:{},latest:null,checking:!1,updating:!1,hasUpdates:!1,requiresRestart:!1,perPackage:{}});r.useEffect(()=>{const l=new Rt;return l.on(u=>{(u.type==="update:progress"||u.type==="update:log"||u.type==="update:complete")&&a(x=>{if(u.type==="update:complete")return{...x,updating:!1,requiresRestart:!!u.requiresRestart};if(u.type==="update:log"){const d=u,m=x.perPackage[d.pkg]||{logs:[]};return{...x,perPackage:{...x.perPackage,[d.pkg]:{...m,logs:[...(m.logs||[]).slice(-50),d.line]}}}}const h=u;return{...x,perPackage:{...x.perPackage,[h.pkg]:{...x.perPackage[h.pkg],status:h.status,error:h.error,newVersion:h.newVersion}}}})}),()=>l.close()},[]),r.useEffect(()=>{R.get("/updates/status").then(l=>a(u=>({...u,current:l.current}))).catch(l=>a(u=>({...u,error:l.message})))},[]);const i=async()=>{a(l=>({...l,checking:!0,error:void 0}));try{const l=await R.get("/updates/check");a(u=>({...u,checking:!1,current:l.current,latest:l.latest,hasUpdates:l.hasUpdates}))}catch(l){a(u=>({...u,checking:!1,error:l.message}))}},n=async()=>{if(confirm("Update Bizar packages? The dashboard will restart automatically.")){a(l=>({...l,updating:!0,requiresRestart:!1,perPackage:{},error:void 0}));try{await R.post("/updates/apply",{packages:["bizar","bizar-dash","bizar-plugin"]})}catch(l){a(u=>({...u,updating:!1,error:l.message}))}}},c=async()=>{if(confirm("Restart the dashboard? You will be disconnected briefly."))try{await R.post("/restart"),s.info("Restarting…",3e3),setTimeout(()=>window.location.reload(),3e3)}catch{s.error("Restart failed")}},o=t.checking||t.updating;return e.jsxs(q,{id:"settings-updates","data-section":"updates",children:[e.jsxs(ae,{children:[e.jsx(Ke,{size:14})," Updates"]}),e.jsx(ne,{children:"Check installed Bizar packages and apply dashboard updates."}),e.jsxs("div",{className:"updates-current",children:[e.jsx("h4",{children:"Installed versions"}),e.jsx("ul",{children:pt.map(l=>e.jsxs("li",{children:[e.jsx("span",{children:l.name}),e.jsx("code",{className:"mono",children:t.current[l.id]||"—"})]},l.id))})]}),t.latest&&e.jsxs("div",{className:"updates-latest",children:[e.jsx("h4",{children:"Latest available"}),e.jsx("ul",{children:pt.map(l=>{var d;const u=t.current[l.id],x=(d=t.latest)==null?void 0:d[l.id],h=u&&x&&u!==x;return e.jsxs("li",{className:h?"updates-outdated":"updates-current-version",children:[e.jsx("span",{children:l.name}),e.jsxs("code",{className:"mono",children:[x||"—",h&&e.jsx("span",{className:"updates-badge",children:"update available"})]})]},l.id)})})]}),t.updating&&e.jsx("div",{className:"updates-progress-rows",children:pt.map(l=>{const u=t.perPackage[l.id]||{status:"idle",logs:[]};return e.jsxs("div",{className:"updates-pkg-row",children:[e.jsxs("div",{className:"updates-pkg-row-header",children:[e.jsx("span",{className:"updates-pkg-name",children:l.name}),e.jsxs("div",{className:"updates-pkg-status",children:[u.status==="starting"&&e.jsx("span",{className:"btn-spinner"}),u.status==="installing"&&e.jsx("span",{className:"btn-spinner"}),u.status==="done"&&e.jsx(vs,{size:14,className:"icon-success"}),u.status==="error"&&e.jsx(st,{size:14,className:"icon-error"}),e.jsx("span",{children:u.status}),u.newVersion&&e.jsxs("code",{className:"mono",style:{fontSize:11},children:["→ ",u.newVersion]})]})]}),u.logs.length>0&&e.jsxs("details",{className:"updates-pkg-logs",children:[e.jsxs("summary",{children:["npm output (",u.logs.length," lines)"]}),e.jsx("pre",{children:u.logs.join(`
|
|
6
|
-
`)})]}),u.status==="error"&&u.error&&e.jsxs("div",{className:"updates-pkg-error",children:[e.jsx(ke,{size:12})," ",u.error]})]},l.id)})}),e.jsxs("div",{className:"updates-actions",children:[e.jsxs(T,{onClick:i,disabled:o,children:[t.checking?e.jsx("span",{className:"btn-spinner"}):e.jsx(le,{size:14}),"Check for updates"]}),e.jsxs(T,{variant:"primary",onClick:n,disabled:!t.hasUpdates||t.updating,children:[t.updating?e.jsx("span",{className:"btn-spinner"}):e.jsx(Ke,{size:14}),t.updating?"Updating…":t.hasUpdates?"Update now":"Up to date"]}),t.requiresRestart&&e.jsxs(T,{variant:"danger",onClick:c,children:[e.jsx(le,{size:14})," Restart Dashboard"]})]}),t.error&&e.jsxs("div",{className:"updates-error",children:[e.jsx(ke,{size:14}),e.jsx("span",{children:t.error})]})]})}function fl(s,t,{delay:a=800,onSaved:i,onError:n}={}){const[c,o]=r.useState(s),[l,u]=r.useState("idle"),x=r.useRef(null),h=r.useRef(null),d=r.useRef(s),m=r.useRef(!1),p=r.useCallback(async k=>{u("saving");try{await t(k),d.current=k,h.current=null,u("saved"),i==null||i(),setTimeout(()=>u("idle"),2e3)}catch(b){u("error"),n==null||n(b)}},[t,i,n]),g=r.useCallback(k=>{o(k),h.current=k,m.current=!0,x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{x.current=null,m.current=!1;const b=h.current;h.current=null,b!==null&&p(b)},a)},[a,p]),j=r.useCallback(()=>{x.current&&(clearTimeout(x.current),x.current=null,m.current=!1)},[]),v=r.useCallback(async()=>{if(x.current){clearTimeout(x.current),x.current=null,m.current=!1;const k=h.current;h.current=null,k!==null&&await p(k)}},[p]);return r.useEffect(()=>()=>{if(x.current){clearTimeout(x.current),x.current=null;const k=h.current;h.current=null,k!==null&&(u("saving"),t(k).then(()=>{d.current=k,u("saved"),i==null||i()}).catch(b=>{u("error"),n==null||n(b)}).finally(()=>{setTimeout(()=>u("idle"),2e3)}))}},[t,i,n]),{value:c,setValue:g,status:l,save:p,flush:v,clearDebounce:j,hasPendingDebounceRef:m,pendingValueRef:h}}function Ct({initialValue:s,saveFn:t,delay:a=800,render:i,className:n}){const{value:c,setValue:o,status:l,save:u,clearDebounce:x,hasPendingDebounceRef:h,pendingValueRef:d}=fl(s,t,{delay:a}),m=Le.useCallback(()=>{h.current&&(x(),d.current!==null&&u(d.current))},[x,h,u,d]);return e.jsxs("div",{className:`autosave-field ${n||""} ${l}`,children:[i({value:c,onChange:o,onBlur:m}),e.jsxs("span",{className:"autosave-status",role:"status","aria-live":"polite",children:[l==="saving"&&e.jsx(Mn,{className:"spinning",size:12}),l==="saved"&&e.jsx(ls,{size:12}),l==="error"&&e.jsx(st,{size:12})]})]})}const jl=[{id:"topnav",label:"Top nav"},{id:"sidebar",label:"Sidebar"},{id:"both",label:"Both"}];function vl({settings:s,patchUi:t,patchTop:a,autoSave:i}){return e.jsxs(e.Fragment,{children:[e.jsxs(q,{id:"settings-layout","data-section":"layout",children:[e.jsxs(ae,{children:[e.jsx(In,{size:14})," UI layout"]}),e.jsx(ne,{children:"Choose how the dashboard's navigation is presented."}),e.jsx("div",{className:"layout-row","data-setting-id":"ui.layout",children:jl.map(n=>e.jsx("button",{type:"button",className:V("layout-card",s.ui.layout===n.id&&"layout-card-active"),onClick:()=>t({layout:n.id}),children:e.jsx("span",{className:"layout-card-label",children:n.label})},n.id))}),e.jsxs("label",{className:"checkbox-row","data-setting-id":"ui.showHeader",children:[e.jsx("input",{type:"checkbox",checked:s.ui.showHeader,onChange:n=>t({showHeader:n.target.checked})}),e.jsx("span",{children:"Show header"})]}),e.jsxs("label",{className:"checkbox-row","data-setting-id":"ui.showStatusBar",children:[e.jsx("input",{type:"checkbox",checked:s.ui.showStatusBar,onChange:n=>t({showStatusBar:n.target.checked})}),e.jsx("span",{children:"Show status bar"})]}),e.jsxs("div",{className:"field","data-setting-id":"ui.defaultTab",children:[e.jsx("label",{className:"field-label",children:"Default tab"}),e.jsxs("select",{className:"select",value:s.ui.defaultTab,onChange:n=>t({defaultTab:n.target.value}),children:[e.jsx("option",{value:"overview",children:"Overview"}),e.jsx("option",{value:"chat",children:"Chat"}),e.jsx("option",{value:"agents",children:"Agents"}),e.jsx("option",{value:"artifacts",children:"Plans"}),e.jsx("option",{value:"projects",children:"Projects"}),e.jsx("option",{value:"tasks",children:"Tasks"}),e.jsx("option",{value:"config",children:"Config"}),e.jsx("option",{value:"settings",children:"Settings"}),e.jsx("option",{value:"mods",children:"Mods"}),e.jsx("option",{value:"schedules",children:"Schedules"})]})]})]}),e.jsxs(q,{id:"settings-general","data-section":"general",children:[e.jsx(ae,{children:"General"}),e.jsx(ne,{children:"Default agent + model override."}),e.jsxs("div",{className:"field","data-setting-id":"defaultAgent",children:[e.jsx("label",{className:"field-label",htmlFor:"set-default-agent",children:"Default agent"}),e.jsx(Ct,{initialValue:s.defaultAgent||"",saveFn:async n=>{a("defaultAgent",n),i==null||i("defaultAgent",n)},render:({value:n,onChange:c,onBlur:o})=>e.jsx("input",{id:"set-default-agent",className:"input",type:"text",placeholder:"e.g. odin",value:n,onChange:l=>c(l.target.value),onBlur:o})})]}),e.jsxs("div",{className:"field","data-setting-id":"defaultModel",children:[e.jsx("label",{className:"field-label",htmlFor:"set-default-model",children:"Model override"}),e.jsx(Ct,{initialValue:s.defaultModel||"",saveFn:async n=>{a("defaultModel",n),i==null||i("defaultModel",n)},render:({value:n,onChange:c,onBlur:o})=>e.jsx("input",{id:"set-default-model",className:"input",type:"text",placeholder:"(leave empty for provider default)",value:n,onChange:l=>c(l.target.value),onBlur:o})})]})]})]})}function yl({tailscale:s,tailscaleDraft:t,setTailscaleDraft:a,onTailscaleToggle:i}){return e.jsxs(e.Fragment,{children:[e.jsxs(q,{id:"settings-service","data-section":"service",children:[e.jsxs(ae,{children:[e.jsx(ys,{size:14})," Service"]}),e.jsx(ne,{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(q,{id:"settings-tailscale","data-section":"tailscale",children:[e.jsxs(ae,{children:[e.jsx(Ds,{size:14})," Tailscale serve"]}),e.jsx(ne,{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:n=>a(c=>({...c,port:Number(n.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:n=>a(c=>({...c,https:n.target.checked}))})]})]}),e.jsx(T,{variant:"primary",onClick:i,children:s.settings.enabled?"Disable serve":"Enable serve"})]}):e.jsx("p",{className:"muted",children:"Loading Tailscale status…"})]})]})}function bl({initialStatus:s}){var k;const[t,a]=r.useState(s??null),[i,n]=r.useState(""),[c,o]=r.useState(!1),[l,u]=r.useState(null);r.useEffect(()=>{t===null&&R.get("/tailscale/status").then(b=>a(b)).catch(()=>a(null))},[]);const x=async()=>{try{const b=await R.get("/tailscale/status");a(b)}catch{u("Failed to load Tailscale status")}},h=async()=>{if(i.trim()){o(!0),u(null);try{await R.post("/tailscale/setup",{authKey:i.trim()}),await x(),n("")}catch(b){u(b.message||"Authentication failed")}finally{o(!1)}}},d=async()=>{var b,w,E;if(t){o(!0),u(null);try{await R.post("/tailscale/setup",{port:((b=t.settings)==null?void 0:b.port)||4321,https:((w=t.settings)==null?void 0:w.https)!==!1,hostname:((E=t.settings)==null?void 0:E.hostname)||""}),await x()}catch(y){u(y.message||"Setup failed")}finally{o(!1)}}},m=async()=>{o(!0),u(null);try{await R.post("/tailscale/unserve"),await x()}catch(b){u(b.message||"Remove failed")}finally{o(!1)}},p=(t==null?void 0:t.installed)??!1,g=(t==null?void 0:t.authenticated)??!1,j=((k=t==null?void 0:t.settings)==null?void 0:k.enabled)??!1,v=j?`https://${(t==null?void 0:t.hostname)||"bizar-dash"}`:null;return p?e.jsxs(q,{id:"settings-tailscale-auth","data-section":"tailscale",children:[e.jsxs(ae,{children:[e.jsx(Ds,{size:14})," Tailscale Integration"]}),e.jsx(ne,{children:"Expose the dashboard over your Tailscale network using an auth key."}),l&&e.jsx("p",{style:{color:"var(--color-error, #f85149)",fontSize:"0.85rem"},children:l}),g?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"status-row",style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.75rem"},children:[e.jsx(vs,{size:16,style:{color:"var(--color-success, #3fb950)"}}),e.jsxs("span",{children:["Authenticated as ",e.jsx("strong",{children:(t==null?void 0:t.hostname)||"unknown"})]})]}),j&&v?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"status-row",style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.75rem"},children:[e.jsx(Ln,{size:16}),e.jsx("a",{href:v,target:"_blank",rel:"noreferrer",children:v})]}),e.jsx(T,{variant:"secondary",size:"sm",onClick:m,disabled:c,children:"Remove serve"})]}):e.jsx(T,{variant:"primary",size:"sm",onClick:d,disabled:c,children:"Set up Tailscale serve"})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"muted",style:{marginBottom:"0.75rem"},children:"Not authenticated with Tailscale."}),e.jsxs("div",{style:{display:"flex",gap:"0.5rem",flexWrap:"wrap"},children:[e.jsx("input",{type:"text",className:"input",placeholder:"tskey-...",value:i,onChange:b=>n(b.target.value),style:{flex:1,minWidth:"200px"},disabled:c}),e.jsx(T,{variant:"primary",size:"sm",onClick:h,disabled:c||!i.trim(),children:"Authenticate"})]})]})]}):e.jsxs(q,{id:"settings-tailscale-auth","data-section":"tailscale",children:[e.jsxs(ae,{children:[e.jsx(Ds,{size:14})," Tailscale Integration"]}),e.jsx(ne,{children:"Tailscale is not installed on this machine."}),e.jsxs("p",{className:"muted",children:["Install from"," ",e.jsx("a",{href:"https://tailscale.com/download",target:"_blank",rel:"noreferrer",children:"tailscale.com/download"})]})]})}function Nl({settings:s,patchNotifications:t}){return e.jsxs(q,{id:"settings-notifications","data-section":"notifications",children:[e.jsx(ae,{children:"Notifications"}),e.jsx(ne,{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 kl({authStatus:s,setAuthStatus:t}){const a=re(),[i,n]=r.useState(R.getToken()),[c,o]=r.useState("");r.useEffect(()=>{let h=!1;return(async()=>{try{const d=await R.probeAuthStatus();h||t(d)}catch{h||t({required:!0,loopback:!1,peer:""})}})(),()=>{h=!0}},[]);const l=async()=>{try{const h=await R.get("/auth/reveal");o(h.token),n(h.token),R.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 R.post("/auth/regenerate");o(h.token),n(h.token),R.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=()=>{R.setToken(i.trim()),a.success("Token saved. The dashboard will use it on the next request.")};return e.jsxs(q,{id:"settings-auth","data-section":"auth",children:[e.jsxs(ae,{children:[e.jsx(Lt,{size:14})," Authentication"]}),e.jsx(ne,{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:i,onChange:h=>n(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(T,{variant:"secondary",size:"sm",onClick:x,children:[e.jsx(Os,{size:14})," Save token"]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:l,children:[e.jsx(ds,{size:14})," Reveal & copy server token"]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:u,children:[e.jsx(fa,{size:14})," Regenerate"]})]}),c?e.jsxs("p",{className:"muted",style:{fontSize:12,marginTop:8},children:["Last revealed token (one-time): ",e.jsx("code",{className:"mono",children:c})]}):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 wl({settings:s,patchAgents:t,patchDashboard:a,autoSave:i}){var x,h,d,m;const n=re(),[c,o]=r.useState({});r.useEffect(()=>{R.get("/settings/plugin-options").then(o).catch(()=>{})},[]);const l=async()=>{try{await R.put("/settings/plugin-options",c),n.success("Saved — restart opencode for changes to take effect.")}catch(p){n.error(`Save failed: ${p.message}`)}},u=async()=>{try{const g=await(await fetch("/api/background/cleanup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({maxAgeDays:7})})).json();n.success(`Cleaned up ${g.deleted} old instances.`)}catch(p){n.error(`Cleanup failed: ${p.message}`)}};return e.jsxs(e.Fragment,{children:[e.jsxs(q,{id:"settings-agents","data-section":"agents",children:[e.jsxs(ae,{children:[e.jsx(ys,{size:14})," Agent Behavior"]}),e.jsx(ne,{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:!!((d=s.agents)!=null&&d.autoRestart),onChange:p=>t({autoRestart:p.target.checked})}),e.jsx("span",{children:"Auto-restart stuck agents"})]})]}),e.jsxs(q,{id:"settings-dashboard","data-section":"dashboard",children:[e.jsxs(ae,{children:[e.jsx(bs,{size:14})," Dashboard"]}),e.jsxs(ne,{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(Ct,{initialValue:(s.dashboard.allowedRoots??[]).join(`
|
|
7
|
-
`),delay:1500,saveFn:async p=>{const g=p.split(`
|
|
8
|
-
`).map(j=>j.trim()).filter(Boolean);a({allowedRoots:g}),i==null||i("dashboard",{allowedRoots:g})},render:({value:p,onChange:g,onBlur:j})=>e.jsx("textarea",{id:"set-allowed-roots",className:"textarea",rows:4,placeholder:`/workspace
|
|
9
|
-
/srv/projects`,value:p,onChange:v=>g(v.target.value),onBlur:j})},(m=s.dashboard.allowedRoots)==null?void 0:m.join(`
|
|
10
|
-
`)),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(`
|
|
11
|
-
`).split(`
|
|
12
|
-
`),g=[];return p.forEach((j,v)=>{j.trim()&&(/^\/|^[A-Za-z]:/.test(j)||g.push({key:`noabs-${v}`,msg:e.jsxs("p",{style:{color:"var(--warning)",fontSize:11,marginTop:2},children:["Line ",v+1,': "',j,'" — should be absolute (start with / or a drive letter).']})}),j.includes("..")&&g.push({key:`dots-${v}`,msg:e.jsxs("p",{style:{color:"var(--error)",fontSize:11,marginTop:2},children:["Line ",v+1,': "',j,`" — contains '..' (server will reject this).`]})}))}),g.map(j=>j.msg)})()]})]}),e.jsxs(q,{id:"settings-background","data-section":"background",children:[e.jsxs(ae,{children:[e.jsx(ys,{size:14})," Background Agents"]}),e.jsx(ne,{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:c.maxConcurrentInstances??8,onChange:p=>o(g=>({...g,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:c.backgroundToolCallCap??500,onChange:p=>o(g=>({...g,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:c.backgroundStallTimeoutMs??18e4,onChange:p=>o(g=>({...g,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:c.backgroundThinkingLoopTimeoutMs??3e5,onChange:p=>o(g=>({...g,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:c.backgroundMaxInterventions??1,onChange:p=>o(g=>({...g,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(T,{variant:"secondary",size:"sm",onClick:l,children:[e.jsx(Es,{size:14})," Save plugin options"]}),e.jsx(T,{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 Sl({settings:s,patchTop:t}){var a,i,n;return e.jsxs(q,{id:"settings-system-llm","data-section":"system-llm",children:[e.jsxs(ae,{children:[e.jsx(He,{size:14})," System LLM API"]}),e.jsx(ne,{children:"Configures the LLM used for automatic title generation, prompt enhancement, summarization, and other system-level calls."}),e.jsxs("label",{className:"checkbox-row","data-setting-id":"systemLlm.enabled",children:[e.jsx("input",{type:"checkbox",checked:!!((a=s.systemLlm)!=null&&a.enabled),onChange:c=>{const o=s.systemLlm||{enabled:!0,provider:"opencode",model:"opencode/deepseek-v4-flash-free"};t("systemLlm",{...o,enabled:c.target.checked})}}),e.jsx("span",{children:"Enable system LLM calls"})]}),e.jsxs("div",{className:"field","data-setting-id":"systemLlm.provider",style:{marginTop:"var(--space-3)"},children:[e.jsx("label",{className:"field-label",htmlFor:"set-system-llm-provider",children:"Provider"}),e.jsxs("select",{id:"set-system-llm-provider",className:"select",value:((i=s.systemLlm)==null?void 0:i.provider)||"opencode",onChange:c=>{const o=s.systemLlm||{enabled:!0,provider:"opencode",model:"opencode/deepseek-v4-flash-free"};t("systemLlm",{...o,provider:c.target.value})},children:[e.jsx("option",{value:"opencode",children:"Opencode"}),e.jsx("option",{value:"openrouter",children:"OpenRouter"}),e.jsx("option",{value:"minimax",children:"MiniMax"})]})]}),e.jsxs("div",{className:"field","data-setting-id":"systemLlm.model",children:[e.jsx("label",{className:"field-label",htmlFor:"set-system-llm-model",children:"Model"}),e.jsx("input",{id:"set-system-llm-model",className:"input mono",type:"text",placeholder:"opencode/deepseek-v4-flash-free",value:((n=s.systemLlm)==null?void 0:n.model)||"opencode/deepseek-v4-flash-free",onChange:c=>{const o=s.systemLlm||{enabled:!0,provider:"opencode",model:"opencode/deepseek-v4-flash-free"};t("systemLlm",{...o,model:c.target.value})}}),e.jsxs("p",{className:"field-help",children:["The API key is read from ",e.jsx("code",{children:"auth.json"})," for the selected provider. Leave the default model for best results."]})]}),e.jsxs("div",{style:{marginTop:"var(--space-4)"},children:[e.jsx("h4",{style:{margin:"0 0 var(--space-2)"},children:"Features using this API"}),e.jsxs("ul",{className:"settings-feature-list",style:{margin:0,paddingLeft:"var(--space-4)",lineHeight:1.8},children:[e.jsx("li",{children:"Auto-title generation for new chat sessions"}),e.jsx("li",{children:"Auto-title generation for new tasks"}),e.jsx("li",{children:'"Enhance prompt" button in the task input'}),e.jsx("li",{children:'"Enhance prompt" button in the chat composer'}),e.jsx("li",{className:"muted",style:{fontSize:12},children:"Future: summarization, name generation, and more"})]})]})]})}const Cl=[{value:"anthropic",label:"Anthropic"},{value:"anyllm",label:"AnyLLM"},{value:"litellm-anthropic",label:"LiteLLM (Anthropic)"},{value:"litellm-openai",label:"LiteLLM (OpenAI)"}];function zl({settings:s,onPatch:t}){const a=re(),[i,n]=r.useState(null),[c,o]=r.useState(null),[l,u]=r.useState(!1),[x,h]=r.useState(!1),[d,m]=r.useState(!1),[p,g]=r.useState(!1),[j,v]=r.useState(!1),[k,b]=r.useState(!1),w=r.useCallback(async()=>{u(!0);try{const[L,X]=await Promise.all([R.get("/headroom/status"),R.get("/headroom/stats?hours=24").catch(()=>({error:"no stats"}))]);n(L),X.error||o(X)}catch(L){a.error(`Failed to load Headroom status: ${L.message}`)}finally{u(!1)}},[a]);r.useEffect(()=>{w()},[w]);const E=async()=>{h(!0);try{const L=await R.post("/headroom/install",{force:!0});L.installed?(a.success(`Headroom installed via ${L.method}.`),await w()):a.error('Headroom install failed. Try: pip install "headroom-ai[all]"')}catch(L){a.error(`Install failed: ${L.message}`)}finally{h(!1)}},y=async()=>{m(!0);try{(await R.post("/headroom/wrap",{port:s.port})).ok?(a.success("opencode wrapped with Headroom."),await w()):a.error("Wrap failed.")}catch(L){a.error(`Wrap failed: ${L.message}`)}finally{m(!1)}},z=async()=>{g(!0);try{(await R.post("/headroom/unwrap")).ok?(a.success("opencode unwrapped from Headroom."),await w()):a.error("Unwrap failed.")}catch(L){a.error(`Unwrap failed: ${L.message}`)}finally{g(!1)}},C=async()=>{v(!0);try{(await R.post("/headroom/proxy/start",{port:s.port,host:s.host})).ok?(a.success(`Headroom proxy started on ${s.host}:${s.port}.`),await w()):a.error("Proxy start failed.")}catch(L){a.error(`Proxy start failed: ${L.message}`)}finally{v(!1)}},f=async()=>{b(!0);try{(await R.post("/headroom/proxy/stop")).ok?(a.success("Headroom proxy stopped."),await w()):a.error("Proxy stop failed.")}catch(L){a.error(`Proxy stop failed: ${L.message}`)}finally{b(!1)}},P=async()=>{try{const{spawn:L}=await la(async()=>{const{spawn:X}=await import("./__vite-browser-external-BIHI7g3E.js");return{spawn:X}},[]);L("headroom",["dashboard"],{detached:!0,stdio:"ignore"})}catch{a.error("Could not open Headroom dashboard. Run `headroom dashboard` manually.")}},{installed:$,version:N,proxyRunning:A,proxyPort:O,wrapped:S}=i||{},F=(c==null?void 0:c.compressionRatio)??0,Y=(c==null?void 0:c.tokensSaved)??0;return e.jsx("div",{id:"settings-headroom","data-section":"headroom",children:e.jsxs(q,{children:[e.jsxs(ae,{children:[e.jsx($e,{size:14,style:{color:A?"var(--success)":"var(--text-dim)"}}),"Headroom",$&&N&&e.jsxs("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:6},children:["v",N," ",A?"✓":"✗"]}),!$&&e.jsx("span",{style:{fontSize:11,color:"var(--error)",marginLeft:6},children:"not installed"})]}),e.jsx(ne,{children:"Context compression for token efficiency. Compresses tool outputs, logs, and conversation history by 60–95% before they reach the model."}),e.jsxs("div",{style:{display:"flex",gap:16,flexWrap:"wrap",marginTop:12,marginBottom:12},children:[e.jsxs("div",{className:"headroom-status-item",children:[$?e.jsx(vs,{size:12,style:{color:"var(--success)"}}):e.jsx(ns,{size:12,style:{color:"var(--error)"}}),e.jsx("span",{children:$?"Installed":"Not installed"})]}),e.jsxs("div",{className:"headroom-status-item",children:[A?e.jsx(vs,{size:12,style:{color:"var(--success)"}}):e.jsx(ns,{size:12,style:{color:"var(--text-dim)"}}),e.jsxs("span",{children:["Proxy ",A?`${O} ✓`:"stopped"]})]}),e.jsxs("div",{className:"headroom-status-item",children:[S?e.jsx(vs,{size:12,style:{color:"var(--success)"}}):e.jsx(ns,{size:12,style:{color:"var(--text-dim)"}}),e.jsxs("span",{children:["opencode ",S?"wrapped":"not wrapped"]})]})]}),(Y>0||F>0)&&e.jsxs("div",{style:{display:"flex",gap:24,marginBottom:12},children:[e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:20,fontWeight:700,color:"var(--success)"},children:F>0?`${Math.round(F*100)}%`:"—"}),e.jsx("div",{className:"muted",style:{fontSize:11},children:"Compression ratio"})]}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:20,fontWeight:700,color:"var(--accent)"},children:Y>0?Y.toLocaleString():"—"}),e.jsx("div",{className:"muted",style:{fontSize:11},children:"Tokens saved (24h)"})]})]}),e.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap",marginBottom:8},children:[$?e.jsxs(e.Fragment,{children:[e.jsxs(T,{variant:"secondary",size:"sm",onClick:y,disabled:d||S,title:S?"opencode is already wrapped":"Wrap opencode to route through Headroom proxy",children:[d?e.jsx("span",{className:"btn-spinner"}):e.jsx(nt,{size:13}),d?"Wrapping…":S?"Wrapped ✓":"Wrap opencode"]}),S&&e.jsxs(T,{variant:"ghost",size:"sm",onClick:z,disabled:p,children:[p?e.jsx("span",{className:"btn-spinner"}):e.jsx(le,{size:13}),p?"Unwrapping…":"Unwrap"]})]}):e.jsxs(T,{variant:"primary",size:"sm",onClick:E,disabled:x,children:[x?e.jsx("span",{className:"btn-spinner"}):e.jsx(Ke,{size:13}),x?"Installing…":"Install Headroom"]}),$&&e.jsxs(e.Fragment,{children:[A?e.jsxs(T,{variant:"secondary",size:"sm",onClick:f,disabled:k,children:[k?e.jsx("span",{className:"btn-spinner"}):e.jsx(ja,{size:13}),k?"Stopping…":"Stop proxy"]}):e.jsxs(T,{variant:"secondary",size:"sm",onClick:C,disabled:j,children:[j?e.jsx("span",{className:"btn-spinner"}):e.jsx(ks,{size:13}),j?"Starting…":"Start proxy"]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:P,children:[e.jsx(ms,{size:13}),"Dashboard"]})]}),e.jsx(T,{variant:"ghost",size:"sm",onClick:w,disabled:l,children:e.jsx(le,{size:13,className:l?"spin":""})})]}),e.jsxs("div",{style:{marginTop:16},children:[e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{type:"checkbox",checked:s.enabled,onChange:L=>t({enabled:L.target.checked})}),e.jsx("span",{children:"Enable Headroom"})]}),e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{type:"checkbox",checked:s.autoInstall,onChange:L=>t({autoInstall:L.target.checked})}),e.jsx("span",{children:"Auto-install if missing on dashboard startup"})]}),e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{type:"checkbox",checked:s.autoStart,onChange:L=>t({autoStart:L.target.checked})}),e.jsx("span",{children:"Auto-start proxy on dashboard startup"})]}),e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{type:"checkbox",checked:s.autoWrap,onChange:L=>t({autoWrap:L.target.checked})}),e.jsx("span",{children:"Auto-wrap opencode on dashboard startup"})]}),e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{type:"checkbox",checked:s.routeAllProviders,onChange:L=>t({routeAllProviders:L.target.checked})}),e.jsx("span",{children:"Route all providers through Headroom proxy"})]}),e.jsxs("div",{className:"task-form-row",style:{marginTop:12},children:[e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",children:"Proxy port"}),e.jsx("input",{type:"number",className:"input",value:s.port,min:1,max:65535,onChange:L=>t({port:Math.max(1,Math.min(65535,parseInt(L.target.value,10)||8787))})})]}),e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",children:"Proxy host"}),e.jsx("input",{type:"text",className:"input",value:s.host,onChange:L=>t({host:L.target.value})})]})]}),e.jsxs("div",{className:"task-form-row",children:[e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",children:"Backend"}),e.jsx("select",{className:"select",value:s.backend,onChange:L=>t({backend:L.target.value}),children:Cl.map(L=>e.jsx("option",{value:L.value,children:L.label},L.value))})]}),e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",children:"Monthly budget (USD)"}),e.jsx("input",{type:"number",className:"input",value:s.budget,min:0,step:1,onChange:L=>t({budget:Math.max(0,parseFloat(L.target.value)||0)})}),e.jsx("span",{className:"field-help",children:"0 = unlimited"})]})]}),e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{type:"checkbox",checked:s.outputShaper,onChange:L=>t({outputShaper:L.target.checked})}),e.jsx("span",{children:"Enable output shaper"})]}),e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{type:"checkbox",checked:s.telemetry,onChange:L=>t({telemetry:L.target.checked})}),e.jsx("span",{children:"Enable telemetry"})]})]})]})})}const Xt={enabled:!0,autoInstall:!0,port:8787,host:"127.0.0.1",outputShaper:!1,telemetry:!1,budget:0,backend:"anthropic",autoStart:!0,autoWrap:!0,routeAllProviders:!0};function Rl({settings:s,setSettings:t,setDirty:a}){return e.jsx(zl,{settings:s.headroom||Xt,onPatch:i=>{t(n=>({...n,headroom:{...n.headroom||Xt,...i}})),a(!0)}})}function Tl(){const s=re(),[t,a]=r.useState([]),[i,n]=r.useState(new Set),[c,o]=r.useState(!0),[l,u]=r.useState(""),[x,h]=r.useState(!0),d=r.useCallback(async()=>{o(!0);try{const[v,k]=await Promise.all([R.get("/activity"),R.get("/activity/hidden")]);a(Array.isArray(v.items)?v.items:[]),n(new Set(k.hidden||[]))}catch(v){s.error(`Load failed: ${v.message}`)}finally{o(!1)}},[s]);r.useEffect(()=>{d()},[d]);const m=(v,k)=>{const b=`${v.kind||""}|${v.ts||""}|${v.slug||""}|${k}`;let w=0;for(let E=0;E<b.length;E++)w=(w<<5)-w+b.charCodeAt(E)|0;return Math.abs(w).toString(16).padStart(8,"0").slice(0,16)},p=async()=>{try{await R.del("/activity/hide"),n(new Set),s.success("All hidden activity restored.")}catch(v){s.error(`Restore failed: ${v.message}`)}},g=async v=>{try{await R.del(`/activity/hide/${encodeURIComponent(v)}`);const k=new Set(i);k.delete(v),n(k)}catch(k){s.error(`Restore failed: ${k.message}`)}},j=t.filter((v,k)=>{const b=m(v,k);if(!x&&i.has(b))return!1;if(!l)return!0;const w=l.toLowerCase();return[v.kind,v.slug,v.message].some(E=>typeof E=="string"&&E.toLowerCase().includes(w))});return e.jsxs(q,{id:"settings-activity-log","data-section":"activity-log",children:[e.jsxs(ae,{children:[e.jsx($e,{size:14})," Activity log",e.jsxs("span",{className:"muted",style:{fontWeight:400,marginLeft:8,fontSize:12},children:[t.length," total · ",i.size," hidden"]}),e.jsx(T,{variant:"ghost",size:"sm",style:{marginLeft:"auto"},onClick:d,title:"Reload",children:e.jsx(le,{size:12})})]}),e.jsxs(ne,{children:["Full history from ",e.jsx("code",{children:"~/.bizar/activity.log"}),". Hiding an item in the Overview only hides it there — the entry stays here."]}),e.jsxs("div",{className:"activity-log-toolbar",children:[e.jsxs("div",{className:"activity-log-search",children:[e.jsx(pe,{size:12}),e.jsx("input",{type:"text",className:"input",placeholder:"Filter by kind, slug, or message…",value:l,onChange:v=>u(v.target.value)})]}),e.jsxs("label",{className:"activity-log-toggle",children:[e.jsx("input",{type:"checkbox",checked:x,onChange:v=>h(v.target.checked)}),"Show hidden"]}),e.jsxs(T,{variant:"ghost",size:"sm",disabled:i.size===0,onClick:p,title:"Restore all hidden items to the Overview",children:[e.jsx(Je,{size:12})," Restore all"]})]}),c?e.jsx("div",{className:"muted",style:{padding:"12px 0",fontSize:12},children:"Loading…"}):j.length===0?e.jsx("div",{className:"muted",style:{padding:"12px 0",fontSize:12},children:t.length===0?"No activity yet.":"No items match the current filter."}):e.jsxs("div",{className:"activity-log-table-wrap",children:[e.jsxs("table",{className:"activity-log-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Kind"}),e.jsx("th",{children:"Detail"}),e.jsx("th",{children:"Time"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:j.slice(0,200).map((v,k)=>{const b=m(v,k),w=i.has(b);return e.jsxs("tr",{className:V(w&&"activity-log-row-hidden"),children:[e.jsx("td",{className:"activity-log-kind",children:v.kind||"activity"}),e.jsx("td",{className:"activity-log-detail",children:v.message||v.slug||"—"}),e.jsx("td",{className:"activity-log-time mono",children:v.ts?new Date(v.ts).toLocaleString():"—"}),e.jsx("td",{children:w?e.jsx(T,{variant:"ghost",size:"sm",onClick:()=>g(b),title:"Restore to Overview",children:e.jsx(Je,{size:12})}):e.jsx("span",{className:"activity-log-state-tag",children:"shown"})})]},`${v.ts}-${k}`)})})]}),j.length>200&&e.jsxs("div",{className:"muted",style:{fontSize:11,padding:"8px 0"},children:["Showing first 200 of ",j.length,"."]})]})]})}function $l({about:s}){return e.jsxs(q,{id:"settings-about","data-section":"about",children:[e.jsxs(ae,{children:[e.jsx(at,{size:14})," About"]}),e.jsx(ne,{children:"Build metadata."}),e.jsxs("dl",{className:"about-table",children:[e.jsx("dt",{children:"Version"}),e.jsx("dd",{className:"mono",children:(s==null?void 0:s.version)||"—"}),e.jsx("dt",{children:"Homepage"}),e.jsx("dd",{children:e.jsx("a",{href:(s==null?void 0:s.homepage)||"https://github.com/DrB0rk/BizarHarness",target:"_blank",rel:"noopener noreferrer",children:(s==null?void 0:s.homepage)||"https://github.com/DrB0rk/BizarHarness"})}),e.jsx("dt",{children:"License"}),e.jsx("dd",{children:(s==null?void 0:s.license)||"MIT"})]})]})}function Al({about:s}){return e.jsxs(e.Fragment,{children:[e.jsx(Tl,{}),e.jsx($l,{about:s})]})}function Ml({workspaceId:s,onInviteCreated:t}){const a=Ae(),[i,n]=r.useState(""),[c,o]=r.useState("editor"),[l,u]=r.useState([]),[x,h]=r.useState(!1),[d,m]=r.useState(!1),[p,g]=r.useState(null),[j,v]=r.useState(null);r.useEffect(()=>{k()},[s]);async function k(){h(!0);try{const z=await R.get(`/workspaces/${s}/invites`);u(z.invites||[])}catch{}finally{h(!1)}}async function b(z){if(z.preventDefault(),!!i.trim()){m(!0),v(null);try{const C=await R.post(`/workspaces/${s}/invites`,{email:i.trim(),role:c});n(""),await k(),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:i})," to invite them as ",e.jsx("strong",{children:c}),":"]}),e.jsxs("div",{className:"invite-url-box",children:[e.jsx(Dn,{size:14}),e.jsx("input",{type:"text",readOnly:!0,value:C.url,onClick:f=>f.target.select()}),e.jsx("button",{type:"button",className:"invite-copy-btn",onClick:()=>{navigator.clipboard.writeText(C.url).catch(()=>{}),g(C.token),setTimeout(()=>g(null),2e3)},children:p===C.token?e.jsx(ls,{size:14}):e.jsx(ds,{size:14})})]}),e.jsx("p",{className:"invite-url-note",children:"This link expires in 7 days."})]}),footer:e.jsx(T,{variant:"primary",size:"sm",onClick:()=>a.close(),children:"Done"})})}catch(C){v(C.message||"Failed to create invite")}finally{m(!1)}}}async function w(z){if(confirm("Revoke this invite?"))try{await R.del(`/workspaces/${s}/invites/${z}`),await k()}catch(C){v(C.message||"Failed to revoke invite")}}function E(z,C){navigator.clipboard.writeText(z).catch(()=>{}),g(C),setTimeout(()=>g(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:b,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:i,onChange:z=>n(z.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:c,onChange:z=>o(z.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(T,{type:"submit",variant:"primary",size:"sm",loading:d,disabled:!i.trim(),children:[e.jsx(En,{size:13}),"Invite"]})]}),j&&e.jsx("p",{className:"invite-error",children:j})]}),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&&l.length===0&&e.jsx("p",{className:"invite-empty",children:"No pending invites"}),l.map(z=>e.jsxs("div",{className:"invite-item",children:[e.jsxs("div",{className:"invite-item-info",children:[e.jsx("span",{className:"invite-item-email",children:z.email}),e.jsx("span",{className:V("invite-item-role",y[z.role]),children:z.role})]}),e.jsxs("div",{className:"invite-item-actions",children:[e.jsx("button",{type:"button",className:"invite-action-btn",title:"Copy invite link",onClick:()=>{const C=`${window.location.origin}/accept-invite?token=${z.token}`;E(C,z.token)},children:p===z.token?e.jsx(ls,{size:13}):e.jsx(ds,{size:13})}),e.jsx("button",{type:"button",className:"invite-action-btn invite-action-revoke",title:"Revoke invite",onClick:()=>w(z.token),children:e.jsx(Se,{size:13})})]})]},z.token))]})]})}const Il={admin:Pn,editor:Lt,viewer:Je},Ll={admin:"role-admin",editor:"role-editor",viewer:"role-viewer"};function El(){const[s,t]=r.useState([]),[a,i]=r.useState(!0),[n,c]=r.useState(!1),[o,l]=r.useState(""),[u,x]=r.useState(null),[h,d]=r.useState(null),m=Ae();r.useEffect(()=>{p()},[]);async function p(){i(!0);try{const k=await R.get("/workspaces");t(k.workspaces||[])}catch{x("Failed to load workspaces")}finally{i(!1)}}async function g(k){if(k.preventDefault(),!!o.trim()){c(!0);try{await R.post("/workspaces",{name:o.trim()}),l(""),await p()}catch(b){x(b.message||"Failed to create workspace")}finally{c(!1)}}}async function j(k,b){if(confirm(`Delete workspace "${b}"?`)&&confirm("This cannot be undone."))try{await R.del(`/workspaces/${k}`),await p()}catch(w){x(w.message||"Failed to delete workspace")}}function v(k){navigator.clipboard.writeText(`${window.location.origin}/accept-invite?workspace=${k}`).catch(()=>{}),d(k),setTimeout(()=>d(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:g,children:[e.jsx("input",{type:"text",placeholder:"New workspace name",value:o,onChange:k=>l(k.target.value),maxLength:64}),e.jsxs(T,{type:"submit",variant:"primary",size:"sm",loading:n,disabled:!o.trim(),children:[e.jsx(Re,{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:k,role:b})=>{const w=Il[b]||Je;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(Zs,{size:16})}),e.jsxs("div",{className:"workspace-item-details",children:[e.jsx("span",{className:"workspace-item-name",children:k.name}),e.jsxs("span",{className:V("workspace-item-role",Ll[b]),children:[e.jsx(w,{size:11}),b]})]})]}),e.jsxs("div",{className:"workspace-item-actions",children:[e.jsx(T,{variant:"ghost",size:"sm",iconOnly:!0,title:"Copy invite link",onClick:()=>v(k.id),children:h===k.id?e.jsx(ls,{size:13}):e.jsx(ds,{size:13})}),b==="admin"&&e.jsx(T,{variant:"ghost",size:"sm",iconOnly:!0,title:"Manage members",onClick:()=>{m.open({title:`Manage "${k.name}"`,children:e.jsx(Ml,{workspaceId:k.id,onInviteCreated:()=>p()}),width:520})},children:e.jsx(Zs,{size:13})}),b==="admin"&&s.length>1&&e.jsx(T,{variant:"ghost",size:"sm",iconOnly:!0,title:"Delete workspace",onClick:()=>j(k.id,k.name),children:e.jsx(Se,{size:13})})]})]},k.id)})]})]})}function Dl({onError:s}){const t=re(),[a,i]=r.useState([]),[n,c]=r.useState(!1),[o,l]=r.useState(!1),[u,x]=r.useState(new Set),[h,d]=r.useState(null),[m,p]=r.useState(""),[g,j]=r.useState(!1),[v,k]=r.useState(""),[b,w]=r.useState(""),[E,y]=r.useState(!1),[z,C]=r.useState(""),[f,P]=r.useState(!1),[$,N]=r.useState(""),[A,O]=r.useState(new Set),S=r.useCallback(async()=>{c(!0);try{const I=await R.get("/env-vars");i(I)}catch(I){t.error(`Load failed: ${I.message}`),s==null||s(I.message)}finally{c(!1)}},[t,s]);r.useEffect(()=>{S()},[S]);const F=I=>{x(K=>{const J=new Set(K);return J.has(I)?J.delete(I):J.add(I),J})},Y=async()=>{const I=v.trim().toUpperCase(),K=b.trim();if(!I||!/^BIZAR_[A-Z0-9_]+$/.test(I)){t.warning("Name must match BIZAR_<NAME> (e.g. BIZAR_MINIMAX_KEY)");return}if(!K){t.warning("Value is required.");return}if(a.some(J=>J.name===I)){t.warning(`${I} already exists.`);return}l(!0);try{await R.post("/env-vars",{name:I,value:K}),t.success(`${I} created.`),j(!1),k(""),w(""),await S()}catch(J){t.error(`Create failed: ${J.message}`)}finally{l(!1)}},L=I=>{d(I.name),p(I.value===I.value.replace(/\*/g,"")?I.value:""),x(K=>{const J=new Set(K);return J.add(I.name),J})},X=async I=>{if(!m.trim()){t.warning("Value cannot be empty.");return}l(!0);try{await R.put(`/env-vars/${encodeURIComponent(I)}`,{value:m.trim()}),t.success(`${I} updated.`),d(null),await S()}catch(K){t.error(`Update failed: ${K.message}`)}finally{l(!1)}},ie=async I=>{if(confirm(`Delete ${I}? This cannot be undone.`))try{await R.del(`/env-vars/${encodeURIComponent(I)}`),t.success(`${I} deleted.`),await S()}catch(K){t.error(`Delete failed: ${K.message}`)}},te=async()=>{if(!z.trim()){t.warning("Nothing to import.");return}P(!0);try{const I=await R.post("/env-vars/bulk-import",{envContent:z});t.success(`Imported ${I.imported}, skipped ${I.skipped}.`),I.errors.length>0&&t.warning(`${I.errors.length} lines had errors: ${I.errors.slice(0,3).join("; ")}${I.errors.length>3?"…":""}`),C(""),y(!1),await S()}catch(I){t.error(`Bulk import failed: ${I.message}`)}finally{P(!1)}},B=async()=>{try{const I=await R.get("/env-vars/export"),K=new Blob([I],{type:"text/plain"}),J=URL.createObjectURL(K),oe=document.createElement("a");oe.href=J,oe.download=".env",oe.click(),URL.revokeObjectURL(J),t.success("Exported .env file.")}catch(I){t.error(`Export failed: ${I.message}`)}},H=r.useMemo(()=>{if(!$.trim())return a;const I=$.toLowerCase();return a.filter(K=>K.name.toLowerCase().includes(I))},[a,$]),Q=r.useMemo(()=>{const I={};for(const K of H){const J=K.name.split("_")[0]+"_";(I[J]??(I[J]=[])).push(K)}return I},[H]),U=I=>{O(K=>{const J=new Set(K);return J.has(I)?J.delete(I):J.add(I),J})},Z=r.useMemo(()=>{const I=["BIZAR_","PROVIDER_","MODEL_","API_"];return Object.keys(Q).sort((J,oe)=>{const _=I.indexOf(J),D=I.indexOf(oe);return _===-1&&D===-1?J.localeCompare(oe):_===-1?1:D===-1?-1:_-D})},[Q]);if(n)return e.jsx("div",{className:"muted",style:{padding:"16px 0",fontSize:13},children:"Loading env vars…"});const Ne=Z.length>1;return e.jsxs("div",{className:"env-var-manager",children:[e.jsxs("div",{className:"env-var-toolbar",children:[e.jsxs(T,{variant:"primary",size:"sm",onClick:()=>j(!0),children:[e.jsx(Re,{size:12})," New variable"]}),e.jsxs(T,{variant:"secondary",size:"sm",onClick:()=>y(I=>!I),className:E?"active":"",children:[e.jsx(va,{size:12})," Bulk import"]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:B,title:"Export as .env",children:[e.jsx(Ke,{size:12})," Export"]}),e.jsxs("div",{className:"env-var-search-wrap",children:[e.jsx(pe,{size:12,className:"env-var-search-icon"}),e.jsx("input",{className:"env-var-search input",placeholder:"Filter…",value:$,onChange:I=>N(I.target.value)})]}),e.jsx(T,{variant:"ghost",size:"sm",onClick:S,title:"Reload",children:e.jsx(le,{size:12})})]}),E&&e.jsxs("div",{className:"env-var-bulk-panel",children:[e.jsxs("div",{className:"env-var-bulk-header",children:[e.jsxs("span",{children:["Paste ",e.jsx("code",{children:"KEY=value"})," lines (one per line):"]}),e.jsx(T,{variant:"ghost",size:"sm",onClick:()=>y(!1),children:e.jsx(be,{size:12})})]}),e.jsx("textarea",{className:"input mono env-var-bulk-textarea",placeholder:`BIZAR_API_KEY=your-key-here
|
|
13
|
-
PROVIDER_OPENAI_KEY=sk-...
|
|
14
|
-
MODEL_KEY=gem-...`,value:z,onChange:I=>C(I.target.value),rows:6}),e.jsxs("div",{className:"env-var-bulk-footer",children:[e.jsx(T,{variant:"primary",size:"sm",onClick:te,disabled:f||!z.trim(),children:f?"Importing…":"Import"}),e.jsx("span",{className:"muted",style:{fontSize:11},children:"Existing keys are skipped unless re-created individually. Invalid lines are reported."})]})]}),a.length===0&&!g&&e.jsxs("div",{className:"env-var-empty",children:[e.jsx(Os,{size:20}),e.jsx("span",{children:"No BIZAR_* env vars yet."}),e.jsx("span",{style:{fontSize:11},children:"Create one to store API keys securely."})]}),g&&e.jsxs("div",{className:"env-var-add-form",children:[e.jsxs("div",{className:"env-var-add-row",children:[e.jsx("input",{className:"input mono",style:{width:240},placeholder:"BIZAR_NAME",value:v,onChange:I=>k(I.target.value.toUpperCase()),onKeyDown:I=>{I.key==="Enter"&&Y(),I.key==="Escape"&&j(!1)},autoFocus:!0}),e.jsx("input",{className:"input mono",type:"password",placeholder:"value (API key, token, etc.)",value:b,onChange:I=>w(I.target.value),onKeyDown:I=>{I.key==="Enter"&&Y(),I.key==="Escape"&&j(!1)}}),e.jsxs(T,{variant:"primary",size:"sm",onClick:Y,disabled:o,children:[e.jsx(vs,{size:12})," Create"]}),e.jsx(T,{variant:"ghost",size:"sm",onClick:()=>{j(!1),k(""),w("")},children:e.jsx(be,{size:12})})]}),e.jsxs("p",{style:{fontSize:11,color:"var(--text-dim)",margin:0},children:["Names must match ",e.jsxs("code",{children:["BIZAR_",e.jsx("var",{children:"NAME"})]})," (uppercase letters, digits, underscores)."]})]}),H.length>0&&(Ne?e.jsx("div",{className:"env-var-groups",children:Z.map(I=>{const K=Q[I],J=A.has(I);return e.jsxs("div",{className:"env-var-group",children:[e.jsxs("button",{type:"button",className:"env-var-group-header",onClick:()=>U(I),children:[J?e.jsx(Ge,{size:12}):e.jsx(Be,{size:12}),e.jsx("span",{className:"env-var-group-prefix mono",children:I}),e.jsxs("span",{className:"env-var-group-count muted",children:["(",K.length,")"]})]}),!J&&e.jsx("div",{className:"env-var-list",children:K.map(oe=>e.jsx(Qt,{v:oe,editing:h,editValue:m,isRevealed:u.has(oe.name),onToggleReveal:F,onStartEdit:L,onEditValueChange:p,onHandleUpdate:X,onCancelEdit:()=>d(null),onDelete:ie,saving:o},oe.name))})]},I)})}):e.jsx("div",{className:"env-var-list",children:H.map(I=>e.jsx(Qt,{v:I,editing:h,editValue:m,isRevealed:u.has(I.name),onToggleReveal:F,onStartEdit:L,onEditValueChange:p,onHandleUpdate:X,onCancelEdit:()=>d(null),onDelete:ie,saving:o},I.name))})),H.length===0&&a.length>0&&e.jsxs("div",{className:"env-var-empty",children:[e.jsx(pe,{size:16}),e.jsxs("span",{children:['No env vars match "',$,'"']})]})]})}function Qt({v:s,editing:t,editValue:a,isRevealed:i,onToggleReveal:n,onStartEdit:c,onEditValueChange:o,onHandleUpdate:l,onCancelEdit:u,onDelete:x,saving:h}){const d=t===s.name;return e.jsxs("div",{className:V("env-var-row",d&&"env-var-row-editing"),children:[e.jsx("span",{className:"env-var-name mono",children:s.name}),d?e.jsx("input",{className:"input mono",type:"password",style:{flex:1,minWidth:200},value:a,onChange:m=>o(m.target.value),onKeyDown:m=>{m.key==="Enter"&&l(s.name),m.key==="Escape"&&u()},autoFocus:!0}):e.jsx("span",{className:V("env-var-value mono",!i&&"env-var-value-masked"),children:s.value}),e.jsx("span",{className:"env-var-source muted",children:s.source}),e.jsxs("div",{className:"env-var-actions",children:[!d&&e.jsx("button",{type:"button",className:"icon-btn",title:i?"Hide":"Reveal",onClick:()=>n(s.name),children:i?e.jsx(Js,{size:12}):e.jsx(Je,{size:12})}),d?e.jsxs(e.Fragment,{children:[e.jsx(T,{variant:"primary",size:"sm",onClick:()=>l(s.name),disabled:h,children:"Save"}),e.jsx(T,{variant:"ghost",size:"sm",onClick:u,children:"Cancel"})]}):e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"icon-btn",title:"Edit",onClick:()=>c(s),children:e.jsx(Ns,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger",title:"Delete",onClick:()=>x(s.name),children:e.jsx(Se,{size:12})})]})]})]})}function Pl(){return e.jsxs(q,{id:"settings-env-vars","data-section":"env-vars",children:[e.jsxs(ae,{children:[e.jsx(Os,{size:14})," Environment Variables"]}),e.jsxs(ne,{children:["Manage BIZAR_* env vars (API keys, secrets). Values are stored in ",e.jsx("code",{children:"~/.config/bizar/env.json"})," (mode 0600)."]}),e.jsx(Dl,{})]})}const Fl=[{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"}],Ol=[{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 Bl({settings:s,refreshSnapshot:t,settingsMode:a,settingsActiveSection:i,setSettingsActiveSection:n,setActiveTab:c}){const o=re(),[l,u]=r.useState(s),[x,h]=r.useState(!1),[d,m]=r.useState(!1),[p,g]=r.useState(null),[j,v]=r.useState({port:4321,https:!0,hostname:""}),[k,b]=r.useState(null),w=()=>{c("overview")};r.useEffect(()=>{u(s),h(!1),s.theme&&fs(s.theme)},[s]),r.useEffect(()=>{p&&v({port:p.settings.port,https:p.settings.https!==!1,hostname:p.settings.hostname||""})},[p]),r.useEffect(()=>{R.get("/tailscale/status").then(g).catch(()=>{})},[]);const E=r.useRef(null),y=r.useCallback(async(U,Z)=>{u(he=>({...he,[U]:Z})),E.current&&clearTimeout(E.current),E.current=setTimeout(async()=>{try{await R.put("/settings",{...l,[U]:Z})}catch(he){console.error("autoSave failed",he)}},300)},[l]);r.useEffect(()=>()=>{E.current&&clearTimeout(E.current)},[]);const z=U=>{u(Z=>{const he={...Z,theme:{...Z.theme,...U}};return fs(he.theme),he}),h(!0)},C=U=>{u(Z=>({...Z,ui:{...Z.ui,...U}})),h(!0)},f=(U,Z)=>{u(he=>({...he,[U]:Z})),h(!0)},P=U=>{u(Z=>({...Z,notifications:{...Z.notifications,...U}})),h(!0)},$=U=>{u(Z=>({...Z,agents:{...Z.agents,...U}})),h(!0)},N=U=>{u(Z=>({...Z,dashboard:{...Z.dashboard,...U}})),h(!0)},[A,O]=r.useState(()=>{if(typeof window>"u")return null;const U=window.location.hash.replace(/^#settings-/,"");return Fl.some(Z=>Z.id===U)?U:null}),S=a?i??null:A,F=U=>{if(a)n==null||n(U);else{O(U);try{if(history.replaceState(null,"",U?`#settings-${U}`:window.location.pathname),U){const Z=document.getElementById(`settings-${U}`);Z&&Z.scrollIntoView({behavior:"smooth",block:"start"})}else window.scrollTo({top:0,behavior:"smooth"})}catch{}}if(U){const Z=document.getElementById(`settings-${U}`);Z&&Z.scrollIntoView({behavior:"smooth",block:"start"})}else window.scrollTo({top:0,behavior:"smooth"})},Y=async()=>{try{p!=null&&p.settings.enabled?(await R.post("/tailscale/disable"),o.success("Tailscale serve disabled.")):(await R.post("/tailscale/enable",{port:j.port||4321,https:j.https,hostname:j.hostname||""}),o.success("Tailscale serve enabled.")),g(await R.get("/tailscale/status"))}catch(U){o.error(`Tailscale failed: ${U.message}`)}},L=async()=>{m(!0);try{const U=await R.put("/settings",l);u(U.data),h(!1),As(U.data.theme),fs(U.data.theme),o.success("Settings saved."),await t()}catch(U){o.error(`Save failed: ${U.message}`)}finally{m(!1)}},X=async()=>{try{const U=await R.get("/settings");u(U.data),h(!1),As(U.data.theme),fs(U.data.theme),o.info("Settings reloaded.",1500)}catch(U){o.error(`Reload failed: ${U.message}`)}},ie=async()=>{if(confirm("Reset all settings to defaults?"))try{const U=await R.post("/settings/reset");u(U.data),h(!1),As(U.data.theme),fs(U.data.theme),o.success("Settings reset."),await t()}catch(U){o.error(`Reset failed: ${U.message}`)}},te={settings:l,patchTheme:z,patchUi:C,patchTop:f,patchNotifications:P,patchAgents:$,patchDashboard:N},B=l.about||{version:"3.0.4",homepage:"https://github.com/DrB0rk/BizarHarness",license:"MIT"},H=S===null,Q=U=>S===U;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(At,{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(T,{variant:"ghost",size:"sm",onClick:ie,children:[e.jsx(fa,{size:14})," Reset"]}),e.jsxs(T,{variant:"secondary",size:"sm",onClick:X,children:[e.jsx(le,{size:14})," Reload"]}),e.jsxs(T,{variant:"primary",size:"sm",disabled:!x||d,onClick:L,children:[d?e.jsx("span",{className:"btn-spinner"}):e.jsx(Es,{size:14}),d?"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(T,{variant:"secondary",size:"sm",onClick:w,children:"← Back to main view"})]}),e.jsx(ml,{sections:Ol,onJump:F}),e.jsxs("div",{className:V("settings-grid",S&&"settings-grid-filtered"),"data-active-section":S||void 0,children:[(H||Q("theme"))&&e.jsx(pl,{...te}),(H||Q("updates"))&&e.jsx(gl,{}),(H||Q("layout")||Q("general"))&&e.jsx(vl,{...te,autoSave:y}),(H||Q("env-vars"))&&e.jsx(Pl,{}),(H||Q("network")||Q("service")||Q("tailscale"))&&e.jsx(yl,{tailscale:p,tailscaleDraft:j,setTailscaleDraft:v,onTailscaleToggle:Y}),(H||Q("network")||Q("tailscale"))&&e.jsx(bl,{initialStatus:p}),(H||Q("notifications"))&&e.jsx(Nl,{...te}),(H||Q("auth"))&&e.jsx(kl,{settings:l,authStatus:k,setAuthStatus:b}),(H||Q("agents")||Q("dashboard")||Q("background"))&&e.jsx(wl,{...te,autoSave:y}),(H||Q("system-llm"))&&e.jsx(Sl,{...te}),(H||Q("headroom"))&&e.jsx(Rl,{settings:l,setSettings:u,setDirty:h}),(H||Q("activity-log")||Q("about"))&&e.jsx(Al,{about:B}),(H||Q("workspaces"))&&e.jsx(El,{})]})]})}const Jt=Le.memo(Bl);function Ul({snapshot:s,refreshSnapshot:t}){const a=re(),i=Ae(),[n,c]=r.useState(Array.isArray(s.mods)?s.mods:[]),[o,l]=r.useState(!0),[u,x]=r.useState(null),[h,d]=r.useState([]),[m,p]=r.useState(null),[g,j]=r.useState(!1),[v,k]=r.useState(null),[b,w]=r.useState(!1),[E,y]=r.useState({}),z=async()=>{var S,F,Y;w(!0);try{const L=await R.get("/mods/registry");k({source:((S=L.registry)==null?void 0:S.source)||"",version:(F=L.registry)==null?void 0:F.version,updatedAt:(Y=L.registry)==null?void 0:Y.updatedAt,mods:L.mods||[]})}catch(L){k({source:"",mods:[],error:L.message})}finally{w(!1)}},C=async S=>{y(F=>({...F,[S]:!0}));try{const F=await R.post("/mods",{id:S});c(Y=>[...Y.filter(L=>L.id!==F.id),F]),a.success(`Mod "${F.id}" installed from registry.`),await t()}catch(F){a.error(`Install failed: ${F.message}`)}finally{y(F=>({...F,[S]:!1}))}},f=async(S,F=!1)=>{y(Y=>({...Y,[S]:!0}));try{const Y=await R.post(`/mods/${encodeURIComponent(S)}/upgrade`,{backup:F});c(X=>[...X.filter(ie=>ie.id!==Y.mod.id),Y.mod]);const L=Y.backupPath?` (backup at ${Y.backupPath})`:"";a.success(`Mod "${S}" upgraded v${Y.from} → v${Y.to}${L}.`),await t()}catch(Y){a.error(`Upgrade failed: ${Y.message}`)}finally{y(Y=>({...Y,[S]:!1}))}},P=async()=>{try{const S=await R.get("/mods");c(S.mods||[]);try{const F=await R.get("/mods/views");d(F.views||[])}catch{d([])}}catch(S){a.error(`Mods load failed: ${S.message}`)}finally{l(!1)}};r.useEffect(()=>{P()},[]),r.useEffect(()=>{Array.isArray(s.mods)&&s.mods!==n&&c(s.mods)},[s.mods]);const $=()=>{let S=null;i.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:F=>S=F,className:"input",type:"text",placeholder:"/path/to/my-mod",autoFocus:!0})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx(T,{variant:"ghost",onClick:()=>i.close(),children:"Cancel"}),e.jsx(T,{variant:"primary",onClick:async()=>{const F=((S==null?void 0:S.value)||"").trim();if(!F){a.warning("Path is required.");return}try{const Y=await R.post("/mods",{path:F});c(L=>[...L,Y]),a.success(`Mod "${Y.id}" installed.`),i.close(),await t()}catch(Y){a.error(`Install failed: ${Y.message}`)}},children:"Install"})]})})},N=async S=>{if(confirm(`Uninstall mod "${S}"? This removes the folder from ~/.config/bizar/mods/.`))try{await R.del(`/mods/${encodeURIComponent(S)}`),c(F=>F.filter(Y=>Y.id!==S)),u===S&&x(null),a.success("Mod uninstalled.")}catch(F){a.error(`Uninstall failed: ${F.message}`)}},A=async S=>{try{const F=await R.put(`/mods/${encodeURIComponent(S.id)}`,{enabled:!S.enabled});c(Y=>Y.map(L=>L.id===S.id?F:L)),a.success(`Mod ${F.enabled?"enabled":"disabled"}.`)}catch(F){a.error(`Toggle failed: ${F.message}`)}},O=n.find(S=>S.id===u)||null;return o?e.jsx("div",{className:"view-loading",children:e.jsx(me,{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(is,{size:18})," Mods (",n.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(T,{variant:"secondary",size:"sm",onClick:P,children:[e.jsx(le,{size:14})," Refresh"]}),e.jsxs(T,{variant:"primary",size:"sm",onClick:$,children:[e.jsx(Re,{size:14})," Install mod"]})]})]}),n.length===0?e.jsx(ge,{icon:e.jsx(is,{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:n.map(S=>e.jsxs("div",{className:V("mod-list-item",u===S.id&&"mod-list-item-active"),onClick:()=>x(S.id),children:[e.jsxs("div",{className:"mod-list-item-head",children:[e.jsxs("div",{children:[e.jsx("div",{className:"mod-list-item-name",children:S.name}),e.jsxs("div",{className:"mod-list-item-meta",children:["v",S.version," · ",S.type," · ",S.author]})]}),e.jsxs("div",{className:"mod-list-item-actions",onClick:F=>F.stopPropagation(),children:[e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Toggle enabled",title:S.enabled?"Disable":"Enable",onClick:()=>A(S),children:e.jsx(Mt,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger","aria-label":"Uninstall",title:"Uninstall",onClick:()=>N(S.id),children:e.jsx(Se,{size:12})})]})]}),e.jsx("div",{className:"mod-list-item-desc ellipsis-2",title:S.description,children:S.description}),e.jsx("div",{className:"mod-list-item-status",children:e.jsx("span",{className:`mod-mini-pill ${S.enabled?"mod-mini-pill-on":"mod-mini-pill-off"}`,children:S.enabled?"enabled":"disabled"})})]},S.id))}),O&&e.jsx(_l,{mod:O})]}),e.jsxs(q,{className:"mods-registry-card",children:[e.jsxs("button",{type:"button",className:"mods-registry-head","aria-expanded":g,"aria-controls":"mods-registry-body",onClick:()=>{!v&&!b&&z(),j(S=>!S)},children:[e.jsx(bs,{size:14,"aria-hidden":!0}),e.jsx("span",{className:"mods-registry-title",children:"Mod registry"}),e.jsx("span",{className:"muted",style:{fontSize:11},children:v!=null&&v.mods?`${v.mods.length} available`:"click to browse"}),e.jsx("span",{className:"mods-registry-spacer"}),g?e.jsx(Be,{size:14,"aria-hidden":!0}):e.jsx(Ge,{size:14,"aria-hidden":!0})]}),g&&e.jsx("div",{id:"mods-registry-body",className:"mods-registry-body",children:b?e.jsx("div",{className:"muted",style:{padding:12,fontSize:12},children:"Loading registry…"}):v!=null&&v.error?e.jsxs("div",{className:"mods-registry-error",children:[e.jsx(Ps,{size:12})," Could not load registry: ",v.error]}):!v||v.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:[v.source&&e.jsxs("div",{className:"muted",style:{fontSize:11,marginBottom:8},children:["Source: ",e.jsx("code",{children:v.source})]}),e.jsx("div",{className:"mods-registry-grid",children:v.mods.map(S=>{const F=n.some(L=>L.id===S.id),Y=!!E[S.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:S.name}),S.latest&&e.jsxs("span",{className:V("mod-registry-version",S.upgradeAvailable&&"mod-registry-version-upgrade"),children:["v",S.latest,S.upgradeAvailable?" ↑":""]})]}),S.description&&e.jsx("div",{className:"mod-registry-card-desc",children:S.description}),e.jsxs("div",{className:"mod-registry-card-meta",children:[S.author&&e.jsxs("span",{className:"muted",children:["by ",S.author]}),S.homepage&&e.jsx("a",{href:S.homepage,target:"_blank",rel:"noopener noreferrer",className:"mod-registry-link",children:"homepage"})]}),(S.permissions||[]).length>0&&e.jsxs("div",{className:"mod-registry-perms",children:[e.jsx(Ps,{size:10}),(S.permissions||[]).slice(0,4).map(L=>e.jsx("span",{className:"mod-registry-perm",children:L},L)),(S.permissions||[]).length>4&&e.jsxs("span",{className:"mod-registry-perm-more",children:["+",S.permissions.length-4]})]}),e.jsxs("div",{className:"mod-registry-card-actions",children:[!F&&e.jsx(T,{variant:"primary",size:"sm",disabled:Y,onClick:()=>C(S.id),title:"Install from registry",children:Y?e.jsx(me,{size:"sm"}):e.jsxs(e.Fragment,{children:[e.jsx(Ke,{size:12})," Install"]})}),F&&S.upgradeAvailable&&e.jsx(T,{variant:"primary",size:"sm",disabled:Y,onClick:()=>f(S.id),title:`Upgrade from v${S.installedVersion||"?"} to v${S.upgradeAvailable}`,children:Y?e.jsx(me,{size:"sm"}):e.jsxs(e.Fragment,{children:[e.jsx(Ke,{size:12})," Upgrade to v",S.upgradeAvailable]})}),F&&!S.upgradeAvailable&&e.jsxs(T,{variant:"ghost",size:"sm",disabled:!0,title:`Installed v${S.installedVersion||"?"}`,children:["Installed v",S.installedVersion||"?"]})]})]},S.id)})})]})})]}),h.length>0&&e.jsxs(q,{className:"mod-views-hint",children:[e.jsxs(ae,{children:[e.jsx(bs,{size:14})," Mod views"]}),e.jsxs(ne,{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."]})]}),m&&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:m,target:"_blank",rel:"noreferrer",children:m})]}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Close iframe",onClick:()=>p(null),children:e.jsx(be,{size:14})})]}),e.jsx("iframe",{src:m,className:"mod-iframe",title:"Mod view",sandbox:"allow-scripts allow-same-origin allow-forms allow-popups"})]})]})}function _l({mod:s}){const t=re(),[a,i]=r.useState(null),[n,c]=r.useState(!1),[o,l]=r.useState(!1),[u,x]=r.useState(null),h=async()=>{c(!0);try{const m=await R.get(`/mods/${s.id}/instructions`);i(m),l(!0)}catch(m){t.error(`Failed to load instructions: ${m.message}`)}finally{c(!1)}},d=async()=>{try{const m=await R.post(`/mods/${s.id}/instructions/reinstall`,{});t.success(`Reinstalled: ${m.counts.agents} agents, ${m.counts.commands} commands, ${m.counts.skills} skills, ${m.counts.instructions} instructions.`),await h()}catch(m){t.error(`Reinstall failed: ${m.message}`)}};return e.jsxs(q,{className:"mod-details",children:[e.jsxs(ae,{children:[e.jsx(we,{size:14})," Mod details — ",s.name]}),e.jsx(ne,{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(m=>e.jsx("span",{className:"tag",children:m},m)),(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(m=>e.jsxs("li",{children:[e.jsx("span",{className:"mod-file-cat",children:m.category}),e.jsx("span",{className:"mono",children:m.path})]},m.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&&!n&&h(),l(m=>!m)},children:[e.jsx(Fn,{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(Be,{size:14,"aria-hidden":!0}):e.jsx(Ge,{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(On,{size:11})," Agents (",a.agents.length,")"]}),a.agents.map(m=>e.jsxs("div",{className:"mod-instructions-file",children:[e.jsxs("div",{className:"mod-instructions-file-head",onClick:()=>x(p=>p===m.filename?null:m.filename),children:[e.jsx("span",{className:"mono",children:m.filename}),e.jsxs("span",{className:"muted",style:{fontSize:10},children:["installed at ",m.fullPath]})]}),u===m.filename&&e.jsx("pre",{className:"mod-instructions-content",children:m.content||e.jsx("em",{className:"muted",children:"(file missing on disk)"})})]},m.filename))]}),a.commands.length>0&&e.jsxs("div",{className:"mod-instructions-section",children:[e.jsxs("div",{className:"mod-instructions-section-title",children:[e.jsx(rs,{size:11})," Commands (",a.commands.length,")"]}),a.commands.map(m=>e.jsxs("div",{className:"mod-instructions-file",children:[e.jsxs("div",{className:"mod-instructions-file-head",onClick:()=>x(p=>p===m.filename?null:m.filename),children:[e.jsx("span",{className:"mono",children:m.filename}),e.jsxs("span",{className:"muted",style:{fontSize:10},children:["installed at ",m.fullPath]})]}),u===m.filename&&e.jsx("pre",{className:"mod-instructions-content",children:m.content||e.jsx("em",{className:"muted",children:"(file missing on disk)"})})]},m.filename))]}),a.skills.length>0&&e.jsxs("div",{className:"mod-instructions-section",children:[e.jsxs("div",{className:"mod-instructions-section-title",children:[e.jsx(ya,{size:11})," Skills (",a.skills.length,")"]}),a.skills.map(m=>e.jsxs("div",{className:"mod-instructions-file",children:[e.jsxs("div",{className:"mod-instructions-file-head",onClick:()=>x(p=>p===m.name?null:m.name),children:[e.jsx("span",{className:"mono",children:m.name}),e.jsxs("span",{className:"muted",style:{fontSize:10},children:["installed at ",m.fullPath]})]}),u===m.name&&e.jsx("pre",{className:"mod-instructions-content",children:m.content||e.jsx("em",{className:"muted",children:"(file missing on disk)"})})]},m.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(T,{variant:"ghost",size:"sm",onClick:d,children:[e.jsx(le,{size:11})," Reinstall from mod folder"]})})]})]})]})}const Wl=r.forwardRef(function({className:t,checked:a,onChange:i,onClick:n,...c},o){return e.jsxs("label",{className:V("toggle",t),children:[e.jsx("input",{ref:o,type:"checkbox",role:"switch","aria-checked":a,checked:a,onChange:l=>i==null?void 0:i(l.target.checked),onClick:l=>{n==null||n(l)},...c}),e.jsx("span",{className:"toggle-slider","aria-hidden":!0})]})}),Vl={net:{label:"Network access",icon:bs,color:"blue",description:"Can make HTTP requests to external services"},fs:{label:"Filesystem",icon:we,color:"yellow",description:"Can read and write files"},config:{label:"Config access",icon:ba,color:"gray",description:"Can read and write Bizar config"},log:{label:"Logging",icon:we,color:"gray",description:"Can write to the structured log"},exec:{label:"Shell execution",icon:rs,color:"red",description:"Can run shell commands"}};function Hl({permissions:s}){return e.jsx("div",{className:"plugin-permissions",children:s.map(t=>{const a=Vl[t]??{label:t,icon:Lt,color:"gray",description:""},i=a.icon;return e.jsxs("div",{className:`permission-chip is-${a.color}`,title:a.description,children:[e.jsx(i,{size:12,"aria-hidden":!0}),e.jsx("span",{children:a.label})]},t)})})}function ql({plugin:s,onToggle:t,onUninstall:a,onConfigure:i}){return e.jsxs(q,{children:[e.jsxs("div",{className:"plugin-card-head",children:[e.jsxs("div",{children:[e.jsx(ae,{children:s.name}),e.jsxs(ne,{children:["v",s.version," · ",s.id]})]}),e.jsx(Wl,{checked:s.enabled??!0,onChange:()=>t(s.id),"aria-label":`Toggle ${s.name} enabled`})]}),s.description&&e.jsx("p",{className:"plugin-description",children:s.description}),e.jsx(Hl,{permissions:s.permissions??[]}),e.jsxs("div",{className:"plugin-card-actions",children:[e.jsx(T,{size:"sm",onClick:()=>i(s.id),children:"Configure"}),e.jsx(T,{size:"sm",variant:"danger",onClick:()=>a(s.id),children:"Uninstall"})]}),e.jsxs("div",{className:"plugin-card-stats",children:[s.invocations??0," invocations",s.lastInvokedAt?` · last used ${s.lastInvokedAt}`:" · never used"]})]})}function Kl(s){const t=re(),[a,i]=r.useState([]),[n,c]=r.useState(!0),[o,l]=r.useState(""),u=async()=>{try{const p=await R.get("/plugins/installed");i(p.plugins)}catch(p){t.error(`Failed to load plugins: ${p.message}`)}finally{c(!1)}};r.useEffect(()=>{u()},[]);const x=async p=>{try{await R.post(`/plugins/${p}/toggle`).catch(()=>{}),await u(),t.success("Plugin toggled.")}catch(g){t.error(`Toggle failed: ${g.message}`)}},h=async p=>{if(confirm("Uninstall this plugin?"))try{await R.del(`/plugins/${p}`),await u(),t.success("Plugin uninstalled.")}catch(g){t.error(`Uninstall failed: ${g.message}`)}},d=p=>{};if(n)return e.jsx("div",{className:"view-loading",children:e.jsx(me,{size:"lg"})});const m=a.filter(p=>p.name.toLowerCase().includes(o.toLowerCase()));return e.jsxs("div",{className:"view view-plugins",children:[e.jsx("header",{className:"view-header",children:e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(is,{size:18,"aria-hidden":!0}),"Plugins (",a.length,")"]}),e.jsx("p",{className:"view-subtitle",children:"Manage plugins installed via the marketplace."})]})}),a.length===0?e.jsx(ge,{icon:e.jsx(is,{size:32}),title:"No plugins installed",message:"Install plugins from the marketplace using the CLI."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"plugins-toolbar",children:e.jsx("input",{className:"input",type:"search",placeholder:"Filter plugins…",value:o,onChange:p=>l(p.target.value),style:{maxWidth:320}})}),e.jsx("div",{className:"plugin-grid",children:m.map(p=>e.jsx(ql,{plugin:p,onToggle:x,onUninstall:h,onConfigure:d},p.id))})]})]})}function Gl({viewId:s,reloadKey:t,setActiveTab:a}){const i=re(),[n,c]=r.useState(null),[o,l]=r.useState(!0),[u,x]=r.useState(0);if(r.useEffect(()=>{let h=!1;return(async()=>{try{const d=await R.get("/mods/views");if(h)return;const m=(d.views||[]).find(p=>p.id===s);c(m||null)}catch(d){i.error(`Failed to load mod view: ${d.message}`)}finally{h||l(!1)}})(),()=>{h=!0}},[s,i]),o)return e.jsx(ge,{title:"Loading mod view…"});if(!n)return e.jsx(ge,{title:"Mod view not found",message:`No view with id "${s}" is currently installed.`,action:e.jsx(T,{onClick:()=>a("mods"),variant:"primary",size:"sm",children:"Open Mods"})});if(n.kind==="iframe"){const h=`/api/mods/${n.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(bs,{size:14}),n.label,e.jsxs("span",{className:"muted",style:{fontSize:11,fontWeight:400},children:["by ",n.modId]})]}),e.jsxs("div",{className:"mod-view-iframe-actions",children:[e.jsxs(T,{variant:"ghost",size:"sm",onClick:()=>x(d=>d+1),title:"Reload this view",children:[e.jsx(le,{size:11})," Reload"]}),e.jsx("a",{href:h,target:"_blank",rel:"noopener noreferrer",className:"icon-btn",title:"Open in new tab",children:e.jsx(ms,{size:12})})]})]}),e.jsx("iframe",{src:h,className:"mod-view-iframe",title:n.label},u+(t||0))]})}if(n.component){const h=n.component,d=n.modId,m=r.lazy(()=>la(()=>import(`/api/mods/${encodeURIComponent(d)}/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(Fs,{size:14}),n.label,e.jsxs("span",{className:"muted",style:{fontSize:11,fontWeight:400},children:["by ",n.modId]})]})}),e.jsx("div",{className:"mod-view-tab-body",children:e.jsx(Yl,{modId:n.modId,component:n.component,children:e.jsx(r.Suspense,{fallback:e.jsxs("div",{style:{padding:24},children:[e.jsx(me,{size:"md"})," ",e.jsx("span",{className:"muted",children:"Loading mod view…"})]}),children:e.jsx(m,{})})})})]})}return e.jsxs(q,{children:[e.jsxs(ae,{children:[e.jsx(Fs,{size:14})," ",n.label]}),e.jsxs(ne,{children:["by ",n.modId]}),n.description&&e.jsx("p",{className:"muted",style:{marginTop:8},children:n.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(T,{variant:"secondary",size:"sm",onClick:()=>a("mods"),children:"Open Mods page"})})]})}class Yl extends r.Component{constructor(){super(...arguments);Cs(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(ke,{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 Xl(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 Ql({template:s,onUse:t}){return e.jsxs(q,{className:"schedule-template-card",children:[e.jsxs("div",{className:"schedule-template-header",children:[e.jsx(ae,{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(ne,{children:s.description}),e.jsxs("div",{className:"schedule-template-summary",children:[e.jsx("code",{children:Xl(s)})," · ",e.jsx("code",{children:s.action.type})]}),e.jsx(T,{variant:"secondary",size:"sm",onClick:()=>t(s),children:"Use this template"})]})}const Jl=["interval","cron","once"],Zl=["command","agent","webhook"],zt=[{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)"}],eo=Array.from({length:12},(s,t)=>t*5),Bt=Array.from({length:24},(s,t)=>({value:t,label:t===0?"12 AM":t<12?`${t} AM`:t===12?"12 PM":`${t-12} PM`})),Ut=[{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"}],Ea=[{value:"s",label:"seconds"},{value:"m",label:"minutes"},{value:"h",label:"hours"},{value:"d",label:"days"}];function Da(s){if(typeof s!="string")return null;const t=s.trim().split(/\s+/);if(t.length!==5)return null;const[a,i,,,n]=t,c=parseInt(a,10),o=parseInt(i,10);if(!Number.isFinite(c)||!Number.isFinite(o)||a!==String(c)||i!==String(o))return null;const l=n==="*"?"*":parseInt(n,10);return l===null||n!=="*"&&!Number.isFinite(l)?null:{minute:c,hour:o,dow:n==="*"?"*":String(l)}}function so(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 to(s){var c,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"?Da(s.schedule):null,a=s.type==="interval"?so(s.schedule):null,i=s.timezone||"UTC",n=zt.some(l=>l.value===i);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"?ao(s.schedule):"",timezone:n?i:"Other…",customTimezone:n?"":i,actionType:s.action.type,actionTarget:s.action.target||"",actionPrompt:s.action.prompt||"",skipIfBudgetLow:!!((c=s.budgetCheck)!=null&&c.skipIfBudgetLow),maxConcurrent:Number.isFinite((o=s.budgetCheck)==null?void 0:o.maxConcurrent)?s.budgetCheck.maxConcurrent:6,enabled:s.enabled!==!1,humanLabel:""}}function ao(s){if(!s)return"";try{const t=new Date(s);if(Number.isNaN(t.getTime()))return"";const a=i=>String(i).padStart(2,"0");return`${t.getFullYear()}-${a(t.getMonth()+1)}-${a(t.getDate())}T${a(t.getHours())}:${a(t.getMinutes())}`}catch{return""}}function no(s){var a,i,n;if(s.type==="cron"){if(s.showAdvanced)return{schedule:s.rawCron.trim(),humanLabel:s.humanLabel||s.rawCron.trim()};const c=`${s.cronMinute} ${s.cronHour} * * ${s.cronDow}`,o=((a=Ut.find(h=>h.value===s.cronDow))==null?void 0:a.label)||"",l=((i=Bt.find(h=>h.value===s.cronHour))==null?void 0:i.label)||`${s.cronHour}`,u=String(s.cronMinute).padStart(2,"0"),x=o==="Every day"?`Every day at ${l.replace(" ","")} (min ${u})`:`Every ${o} at ${l.replace(" ","")} (min ${u})`;return{schedule:c,humanLabel:s.humanLabel||x}}if(s.type==="interval"){const c=((n=Ea.find(l=>l.value===s.intervalUnit))==null?void 0:n.label)||s.intervalUnit;return{schedule:`${s.intervalN}${s.intervalUnit}`,humanLabel:s.humanLabel||`Every ${s.intervalN} ${c}`}}return s.onceAt?{schedule:new Date(s.onceAt).toISOString(),humanLabel:s.humanLabel||new Date(s.onceAt).toLocaleString()}:{schedule:"",humanLabel:s.humanLabel||""}}function io({snapshot:s,refreshSnapshot:t}){var E;const a=re(),i=Ae(),[n,c]=r.useState(s.schedules||[]),[o,l]=r.useState(!s.schedules),[u,x]=r.useState("schedules"),[h,d]=r.useState([]),[m,p]=r.useState(!1),g=async()=>{try{const y=await R.get("/projects/active/schedules");c(y.schedules||[])}catch(y){a.error(`Schedules load failed: ${y.message}`)}finally{l(!1)}},j=async()=>{p(!0);try{const y=await R.get("/schedules/templates");d(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){c(s.schedules||[]),l(!1);return}g()},[s.schedules]),r.useEffect(()=>{u==="templates"&&h.length===0&&j()},[u]);const v=y=>{i.open({title:y?`Edit schedule: ${y.name}`:"New schedule",width:640,children:e.jsx(ro,{initial:y,onClose:i.close,onSubmitted:async z=>{c(C=>{const f=C.findIndex($=>$.id===z.id);if(f===-1)return[...C,z];const P=C.slice();return P[f]=z,P}),a.success(y?"Schedule updated.":"Schedule created."),i.close(),await t()},onError:z=>a.error(z)})})},k=async y=>{var z;try{const C=await R.post(`/schedules/${encodeURIComponent(y.id)}/run`);a.success(C.ok?"Schedule ran.":`Run failed: ${((z=C.runResult)==null?void 0:z.error)||"unknown"}`),await g()}catch(C){a.error(`Run failed: ${C.message}`)}},b=async y=>{if(confirm(`Delete schedule "${y.name}"?`))try{await R.del(`/schedules/${encodeURIComponent(y.id)}`),c(z=>z.filter(C=>C.id!==y.id)),a.success("Schedule deleted.")}catch(z){a.error(`Delete failed: ${z.message}`)}},w=async y=>{try{const z=await R.post("/schedules/from-template",{templateId:y.id});c(C=>[...C,z]),x("schedules"),a.success(`Schedule "${z.name}" created from template.`),await t()}catch(z){a.error(`Failed to create schedule: ${z.message}`)}};return o?e.jsx("div",{className:"view-loading",children:e.jsx(me,{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(Is,{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 (",n.length,")"]}),e.jsxs("button",{type:"button",className:`tab-btn ${u==="templates"?"tab-btn-active":""}`,onClick:()=>x("templates"),children:[e.jsx(Fs,{size:14})," Templates"]})]})]}),e.jsx("p",{className:"view-subtitle",children:u==="schedules"?e.jsxs(e.Fragment,{children:["Recurring tasks for ",e.jsx("strong",{children:((E=s.activeProject)==null?void 0:E.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(T,{variant:"secondary",size:"sm",onClick:g,children:[e.jsx(le,{size:14})," Refresh"]}),e.jsxs(T,{variant:"primary",size:"sm",onClick:()=>v(),children:[e.jsx(Re,{size:14})," New schedule"]})]}),u==="templates"&&e.jsxs(T,{variant:"secondary",size:"sm",onClick:j,disabled:m,children:[e.jsx(le,{size:14})," Refresh"]})]})]}),u==="templates"?m?e.jsx("div",{className:"view-loading",children:e.jsx(me,{size:"lg"})}):h.length===0?e.jsx(ge,{icon:e.jsx(Fs,{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(Ql,{template:y,onUse:w},y.id))}):n.length===0?e.jsx(ge,{icon:e.jsx(Is,{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:n.map(y=>{var z;return e.jsxs(q,{className:"schedule-card",children:[e.jsxs("div",{className:"schedule-card-head",children:[e.jsxs("div",{children:[e.jsx(ae,{children:y.name}),e.jsxs(ne,{children:[e.jsx("code",{children:y.type})," ·"," ",e.jsx("span",{title:y.schedule,children:lo(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(T,{variant:"secondary",size:"sm",onClick:()=>v(y),children:[e.jsx(Ns,{size:12})," Edit"]}),e.jsxs(T,{variant:"secondary",size:"sm",onClick:()=>k(y),children:[e.jsx(kt,{size:12})," Run now"]}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger","aria-label":"Delete",title:"Delete",onClick:()=>b(y),children:e.jsx(Se,{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]})]}),((z=y.budgetCheck)==null?void 0:z.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?ze(y.lastRun):"—",y.lastResult&&e.jsx("span",{className:`tag ${Zt(y.lastResult)}`,children:y.lastResult}),y.lastError&&e.jsxs("span",{className:"muted schedule-card-error",title:y.lastError,children:[" ","— ",ea(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:oo(y.nextRun,y.timezone)}):"—",y.nextRun&&e.jsxs("span",{className:"muted",children:[" · ",ze(y.nextRun)]})]})]}),y.history&&y.history.length>0&&e.jsxs("details",{className:"schedule-card-history",children:[e.jsxs("summary",{children:[e.jsx(Ls,{size:12})," ",y.history.length," run",y.history.length===1?"":"s"]}),e.jsx("ul",{children:y.history.slice(-10).reverse().map((C,f)=>e.jsxs("li",{children:[e.jsx("span",{className:"tabular-nums muted",children:ze(C.ts)})," ",e.jsx("span",{className:`tag ${Zt(C.result)}`,children:C.result}),C.error&&e.jsxs("span",{className:"muted",children:[" — ",ea(C.error,80)]})]},f))})]})]},y.id)})})]})}function ro({initial:s,onClose:t,onSubmitted:a,onError:i}){const[n,c]=r.useState(()=>to(s)),[o,l]=r.useState(!1),u=r.useMemo(()=>zt.some(d=>d.value===n.timezone)?n.timezone:"Other…",[n.timezone]),x=(d,m)=>{c(p=>({...p,[d]:m}))},h=async d=>{d.preventDefault();const m=n.name.trim();if(!m){i("Name is required.");return}const p=no(n);if(!p.schedule){i("Schedule value is required.");return}if(!n.actionTarget.trim()){i("Action target is required.");return}const g=n.timezone==="Other…"?n.customTimezone.trim():n.timezone,j={type:n.actionType,target:n.actionTarget.trim()};n.actionType==="agent"&&n.actionPrompt.trim()&&(j.prompt=n.actionPrompt.trim());const v={name:m,type:n.type,schedule:p.schedule,timezone:g||"UTC",action:j,budgetCheck:{maxConcurrent:n.maxConcurrent,skipIfBudgetLow:n.skipIfBudgetLow},enabled:n.enabled};l(!0);try{const k=s?await R.put(`/schedules/${encodeURIComponent(s.id)}`,v):await R.post("/schedules",v);await a(k)}catch(k){i(`${s?"Update":"Create"} failed: ${k.message}`)}finally{l(!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:n.name,onChange:d=>x("name",d.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:n.type,onChange:d=>x("type",d.target.value),children:Jl.map(d=>e.jsx("option",{value:d,children:d},d))})]})}),n.type==="cron"&&e.jsxs("div",{className:"schedule-cron-group",children:[!n.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:n.cronDow,onChange:d=>x("cronDow",d.target.value),children:Ut.map(d=>e.jsx("option",{value:d.value,children:d.label},d.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(n.cronHour),onChange:d=>x("cronHour",parseInt(d.target.value,10)),children:Bt.map(d=>e.jsx("option",{value:String(d.value),children:d.label},d.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(n.cronMinute),onChange:d=>x("cronMinute",parseInt(d.target.value,10)),children:eo.map(d=>e.jsx("option",{value:String(d),children:String(d).padStart(2,"0")},d))})]})]})}),n.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:n.rawCron,onChange:d=>x("rawCron",d.target.value),placeholder:"0 13 * * 0"})]}),e.jsxs("button",{type:"button",className:"link-btn",onClick:()=>x("showAdvanced",!n.showAdvanced),"aria-expanded":n.showAdvanced,children:[e.jsx(Be,{size:12,style:{transform:n.showAdvanced?"rotate(180deg)":"none",transition:"transform 0.15s"}}),n.showAdvanced?"Hide advanced":"Advanced (raw cron)"]})]}),n.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:n.intervalN,onChange:d=>x("intervalN",parseInt(d.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:n.intervalUnit,onChange:d=>x("intervalUnit",d.target.value),children:Ea.map(d=>e.jsx("option",{value:d.value,children:d.label},d.value))})]})]}),n.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:n.onceAt,onChange:d=>x("onceAt",d.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:d=>x("timezone",d.target.value),children:[zt.map(d=>e.jsx("option",{value:d.value,children:d.label},d.value)),e.jsx("option",{value:"Other…",children:"Other…"})]})]}),n.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:n.customTimezone,onChange:d=>x("customTimezone",d.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:n.actionType,onChange:d=>x("actionType",d.target.value),children:Zl.map(d=>e.jsx("option",{value:d,children:d},d))})]}),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:n.actionType==="webhook"?"https://...":n.actionType==="agent"?"agent name or task ref":"echo hi",value:n.actionTarget,onChange:d=>x("actionTarget",d.target.value)})]})]}),n.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:n.actionPrompt,onChange:d=>x("actionPrompt",d.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:n.skipIfBudgetLow,onChange:d=>x("skipIfBudgetLow",d.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:n.maxConcurrent,onChange:d=>x("maxConcurrent",parseInt(d.target.value,10)||6),disabled:!n.skipIfBudgetLow})]})]}),e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{id:"schedule-enabled",type:"checkbox",checked:n.enabled,onChange:d=>x("enabled",d.target.checked)}),e.jsx("span",{children:"Enabled"})]}),e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx(T,{variant:"ghost",type:"button",onClick:t,disabled:o,children:"Cancel"}),e.jsx(T,{variant:"primary",type:"submit",disabled:o,children:s?"Save":"Create"})]})]})}function lo(s){var c,o;if(s.type!=="cron")return s.schedule;const t=Da(s.schedule);if(!t)return s.schedule;const a=((c=Ut.find(l=>l.value===t.dow))==null?void 0:c.label)||"",i=((o=Bt.find(l=>l.value===t.hour))==null?void 0:o.label)||`${t.hour}`,n=String(t.minute).padStart(2,"0");return a==="Every day"?`Every day at ${i} :${n}`:`Every ${a} at ${i} :${n}`}function oo(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 Zt(s){return s==="success"?"tag-success":s==="skipped"?"tag-warning":"tag-error"}function ea(s,t){return s.length<=t?s:s.slice(0,t-1)+"…"}const co=[{id:"all",label:"All",icon:He},{id:"shipped",label:"Shipped",icon:Et},{id:"user",label:"User",icon:Zs},{id:"project",label:"Project",icon:Oe}],Ys={shipped:"Shipped",user:"User",project:"Project"},mo={shipped:Et,user:Zs,project:Oe};function uo({snapshot:s,refreshSnapshot:t}){const a=re(),i=Ae(),[n,c]=r.useState([]),[o,l]=r.useState({shipped:0,user:0,project:0,all:0}),[u,x]=r.useState(!0),[h,d]=r.useState("all"),[m,p]=r.useState(""),[g,j]=r.useState(null),[v,k]=r.useState(!1),b=async()=>{var z,C,f;x(!0);try{const P=await R.get("/skills");c(P.skills||[]),l({shipped:((z=P.counts)==null?void 0:z.shipped)??0,user:((C=P.counts)==null?void 0:C.user)??0,project:((f=P.counts)==null?void 0:f.project)??0,all:(P.skills||[]).length})}catch(P){a.error(`Skills load failed: ${P.message}`)}finally{x(!1)}};r.useEffect(()=>{b()},[]),r.useEffect(()=>{if(!m.trim()){j(null);return}k(!0);const z=setTimeout(async()=>{try{const C=await R.get(`/skills/search?q=${encodeURIComponent(m.trim())}`);j(C.results||[])}catch(C){a.error(`Search failed: ${C.message}`)}finally{k(!1)}},280);return()=>clearTimeout(z)},[m]);const w=r.useMemo(()=>g!==null?g:h==="all"?n:n.filter(z=>z.source===h),[n,h,g]),E=async()=>{try{await R.post("/skills/refresh",{}),a.success("Skills refreshed."),await b()}catch(z){a.error(`Refresh failed: ${z.message}`)}},y=async z=>{try{const C=await R.get(`/skills/${encodeURIComponent(z.source)}/${encodeURIComponent(z.name)}`);i.open({title:C.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":C.source,children:Ys[C.source]||C.source}),e.jsx("code",{className:"mono text-sm muted",children:C.path})]}),C.description&&e.jsx("p",{className:"skill-detail-desc",children:C.description}),C.body&&e.jsx("div",{className:"skill-detail-body",children:e.jsx("pre",{className:"skill-body-pre",children:C.body})})]}),footer:e.jsx(T,{variant:"ghost",onClick:()=>i.close(),children:"Close"})})}catch{i.open({title:z.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":z.source,children:Ys[z.source]||z.source}),e.jsx("code",{className:"mono text-sm muted",children:z.path})]}),z.description&&e.jsx("p",{className:"skill-detail-desc",children:z.description})]}),footer:e.jsx(T,{variant:"ghost",onClick:()=>i.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(He,{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(pe,{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:m,onChange:z=>p(z.target.value),"aria-label":"Search skills"}),m&&e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Clear search",onClick:()=>p(""),children:e.jsx(ns,{size:12})})]}),e.jsxs(T,{variant:"secondary",size:"sm",onClick:E,children:[e.jsx(le,{size:14})," Refresh"]})]})]}),!m.trim()&&e.jsx("div",{className:"skills-tabs",children:co.map(z=>{const C=z.icon,f=z.id==="all"?o.all:o[z.id]??0;return e.jsxs("button",{type:"button",className:V("skills-tab",h===z.id&&"skills-tab-active"),onClick:()=>d(z.id),children:[e.jsx(C,{size:14}),e.jsx("span",{children:z.label}),e.jsx("span",{className:"skills-tab-count",children:f})]},z.id)})}),m.trim()&&e.jsxs("section",{className:"skills-section",children:[e.jsxs("h3",{className:"skills-section-title",children:[e.jsx(pe,{size:14})," Search results",v&&e.jsx(me,{size:"sm"})]}),v?e.jsx("div",{className:"skills-grid",children:[0,1,2].map(z=>e.jsx("div",{className:"skill-card skill-card-skeleton"},z))}):g&&g.length===0?e.jsx(ge,{icon:e.jsx(pe,{size:28}),title:"No matches",message:`No skills match "${m}".`}):e.jsx("div",{className:"skills-grid",children:(g||[]).map((z,C)=>e.jsx(sa,{skill:z,onShow:()=>y(z),searchQ:m},`search-${C}`))})]}),!m.trim()&&e.jsx("section",{className:"skills-section",children:u?e.jsx("div",{className:"view-loading",children:e.jsx(me,{size:"lg"})}):w.length===0?e.jsx(ge,{icon:e.jsx(ya,{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 ${Ys[h]} tab.`}):e.jsx("div",{className:"skills-grid",children:w.map((z,C)=>e.jsx(sa,{skill:z,onShow:()=>y(z)},`${z.source}-${z.name}-${C}`))})}),!m.trim()&&e.jsx("footer",{className:"view-footer",children:e.jsxs("span",{className:"text-sm muted",children:["Skills are discovered from"," ",e.jsx("code",{children:"~/.opencode/skills/"}),","," ",e.jsx("code",{children:"~/.agents/skills/"}),","," ",e.jsx("code",{children:"bizar-dash/skills/"}),", and project-local directories."]})})]})}function sa({skill:s,onShow:t,searchQ:a=""}){const i=mo[s.source]||Et,n=s.description?s.description.length>200?s.description.slice(0,200)+"…":s.description:"No description.";return e.jsxs(q,{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(i,{size:18})}),e.jsxs("div",{className:"skill-card-title-area",children:[e.jsx("div",{className:"skill-card-title",children:ho(s.name,a)}),e.jsx("span",{className:"skill-source-badge","data-source":s.source,children:Ys[s.source]||s.source})]})]}),e.jsx("p",{className:"skill-card-desc",children:n}),e.jsx("div",{className:"skill-card-actions",children:e.jsxs(T,{variant:"ghost",size:"sm",onClick:t,children:[e.jsx(ms,{size:12})," View"]})})]})}function ho(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 xo=Le.memo(uo);function po({refreshKey:s,onRefresh:t,setActiveSubPanel:a}){const i=re(),[n,c]=r.useState(null),[o,l]=r.useState(!0),u=async g=>{l(!0);try{const[j,v,k,b]=await Promise.all([R.get("/memory/health",g).catch(()=>null),R.get("/memory/status",g).catch(()=>null),R.get("/memory/lightrag/stats",g).catch(()=>null),R.get("/memory/storage",g).catch(()=>null)]);c({health:j||{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:(b==null?void 0:b.total)||0,folderCount:0,folders:[],lastModified:null,gitClean:(v==null?void 0:v.gitClean)??null,gitBranch:(v==null?void 0:v.branch)||null},lightrag:k||{running:!1,pid:null,host:"127.0.0.1",port:9621,indexedApprox:0,queryCountLast24h:0,lastReindexAt:null},storage:b||{total:0,breakdown:[]}})}catch(j){i.error(`Memory overview failed: ${j.message}`)}finally{l(!1)}};if(r.useEffect(()=>{const g=new AbortController;return u(g.signal),()=>g.abort()},[s]),o&&!n)return e.jsxs("div",{className:"view-loading",children:[e.jsx(me,{size:"lg"}),e.jsx("p",{children:"Loading memory overview…"})]});if(!n)return e.jsx("div",{className:"muted",children:"No memory data available."});const{health:x,vault:h,lightrag:d,storage:m}=n,p=x.score>=80?"var(--success)":x.score>=50?"var(--warning)":"var(--error)";return e.jsxs("div",{className:"memory-overview",children:[e.jsxs(q,{variant:"elevated",className:"memory-health-hero",children:[e.jsxs("div",{className:"memory-health-score",style:{borderColor:p},children:[e.jsx("span",{className:"memory-health-score-value",style:{color:p},children:x.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($e,{size:16}),"Memory health ·"," ",e.jsx("span",{style:{color:p},children:x.status})]}),e.jsx("p",{className:"memory-health-message",children:x.message}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:t,children:[e.jsx(le,{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(Fe,{size:14}),e.jsx("span",{children:"LightRAG"}),e.jsx("span",{className:V("memory-source-pill-status",d.running?"on":"off"),children:d.running?"running":"stopped"})]}),e.jsxs("button",{type:"button",className:"memory-source-pill",onClick:()=>a("obsidian"),children:[e.jsx(we,{size:14}),e.jsx("span",{children:"Obsidian Vault"}),e.jsxs("span",{className:V("memory-source-pill-status",h.exists?"on":"off"),children:[h.noteCount," notes"]})]}),e.jsxs("button",{type:"button",className:"memory-source-pill",onClick:()=>a("git"),children:[e.jsx(os,{size:14}),e.jsx("span",{children:"Git Sync"}),e.jsx("span",{className:V("memory-source-pill-status",h.gitClean===null?"na":h.gitClean?"on":"warn"),children:h.gitClean===null?"—":h.gitClean?"clean":"dirty"})]}),e.jsxs("button",{type:"button",className:"memory-source-pill",onClick:()=>a("semantic"),children:[e.jsx(pe,{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(gs,{icon:e.jsx(Fe,{size:16}),label:"LightRAG",value:d.running?`running · ${d.queryCountLast24h} q/24h`:"stopped",sub:d.running?`${d.indexedApprox} indexed chunks`:"start from the LightRAG panel",onClick:()=>a("lightrag")}),e.jsx(gs,{icon:e.jsx(we,{size:16}),label:"Obsidian",value:`${h.noteCount} notes`,sub:h.folderCount>0?`${h.folderCount} folders`:"no folders yet",onClick:()=>a("obsidian")}),e.jsx(gs,{icon:e.jsx(os,{size:16}),label:"Git",value:h.gitBranch?`branch ${h.gitBranch}`:"local-only",sub:h.gitClean===null?"not configured":h.gitClean?"clean working tree":"dirty — commit or pull",onClick:()=>a("git")}),e.jsx(gs,{icon:e.jsx(Na,{size:16}),label:"Storage",value:go(m.total),sub:m.breakdown.length>0?`${m.breakdown.length} dirs tracked`:"no memory data on disk"}),e.jsx(gs,{icon:e.jsx(He,{size:16}),label:"Last reindex",value:d.lastReindexAt?We(d.lastReindexAt):"never",sub:"lightrag ingest",onClick:()=>a("lightrag")}),e.jsx(gs,{icon:e.jsx(Ps,{size:16}),label:"Health",value:`${x.score}/100`,sub:x.status,onClick:()=>a("config")})]}),x.checks.length>0&&e.jsxs(q,{children:[e.jsx(ae,{children:"Health checks"}),e.jsx(ne,{children:"Composite score across all memory subsystems"}),e.jsx("ul",{className:"memory-check-list",children:x.checks.map(g=>e.jsxs("li",{className:"memory-check-row",children:[e.jsx("span",{className:"memory-check-icon",children:g.pass?e.jsx(Ve,{size:14,style:{color:"var(--success)"}}):g.name.includes("secrets")||g.name.includes("schema")?e.jsx(ke,{size:14,style:{color:"var(--warning)"}}):e.jsx(ns,{size:14,style:{color:"var(--error)"}})}),e.jsx("span",{className:"memory-check-name",children:g.name}),e.jsx("span",{className:"memory-check-detail muted",children:g.detail})]},g.name))})]})]})}function gs({icon:s,label:t,value:a,sub:i,onClick:n}){const c=n?"button":"div";return e.jsxs(c,{type:n?"button":void 0,onClick:n,className:V("memory-stat-card",n&&"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:i})]})]})}function go(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 fo({refreshKey:s}){const t=re(),[a,i]=r.useState(null),[n,c]=r.useState(null),[o,l]=r.useState([]),[u,x]=r.useState(!0),[h,d]=r.useState(null),[m,p]=r.useState(""),[g,j]=r.useState(null),v=async()=>{x(!0);try{const[f,P,$]=await Promise.all([R.get("/memory/lightrag/stats").catch(()=>null),R.get("/memory/config").then(N=>(N==null?void 0:N.lightrag)||null).catch(()=>null),R.get("/memory/lightrag/log").catch(()=>({lines:[]}))]);i(f),c(P),l(($==null?void 0:$.lines)||[])}catch(f){t.error(`LightRAG status failed: ${f.message}`)}finally{x(!1)}};r.useEffect(()=>{v()},[s]);const k=async(f,P,$)=>{d(f);try{await P(),t.success($),await v()}catch(N){t.error(`${f} failed: ${N.message}`)}finally{d(null)}},b=()=>k("start",()=>R.post("/memory/lightrag/start",{}),"LightRAG starting…"),w=()=>k("stop",()=>R.post("/memory/lightrag/stop",{}),"LightRAG stopping…"),E=async()=>{d("restart");try{await R.post("/memory/lightrag/stop",{}).catch(()=>{}),await new Promise(f=>setTimeout(f,600)),await R.post("/memory/lightrag/start",{}),t.success("LightRAG restarted."),await v()}catch(f){t.error(`Restart failed: ${f.message}`)}finally{d(null)}},y=()=>k("reindex",()=>R.post("/memory/lightrag/reindex",{}),"Reindex complete."),z=()=>k("rebuild",()=>R.post("/memory/lightrag/rebuild-graph",{}),"Graph rebuilt."),C=async()=>{var f,P,$;if(m.trim()){d("query");try{const N=await R.get(`/memory/query?q=${encodeURIComponent(m)}&topK=8`),A=(f=N==null?void 0:N.semantic)!=null&&f.response?typeof N.semantic.response=="string"?N.semantic.response:JSON.stringify(N.semantic.response):((P=N==null?void 0:N.semantic)==null?void 0:P.error)||"No response";j({ok:!!(($=N==null?void 0:N.semantic)!=null&&$.ok),text:A})}catch(N){j({ok:!1,text:N.message})}finally{d(null)}}};return u&&!a?e.jsxs("div",{className:"view-loading",children:[e.jsx(me,{size:"lg"}),e.jsx("p",{children:"Loading LightRAG status…"})]}):a?e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(q,{variant:"elevated",children:[e.jsxs(ae,{children:[e.jsx(Fe,{size:14}),"LightRAG",e.jsx("span",{className:V("memory-source-pill-status",a.running?"on":"off"),children:a.running?"running":"stopped"})]}),e.jsx(ne,{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(T,{variant:"primary",size:"sm",onClick:b,disabled:!!h||a.running,children:[h==="start"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(ks,{size:12}),"Start"]}),e.jsxs(T,{variant:"secondary",size:"sm",onClick:w,disabled:!!h||!a.running,children:[h==="stop"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(Bn,{size:12}),"Stop"]}),e.jsxs(T,{variant:"secondary",size:"sm",onClick:E,disabled:!!h,children:[h==="restart"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(Mt,{size:12}),"Restart"]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:y,disabled:!!h,children:[h==="reindex"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(le,{size:12}),"Reindex all"]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:z,disabled:!!h,title:"Wipe working dir + reindex from scratch",children:[h==="rebuild"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(it,{size:12}),"Rebuild graph"]})]})]}),e.jsxs("div",{className:"memory-stat-grid",children:[e.jsx(zs,{icon:e.jsx(Na,{size:14}),label:"Indexed chunks (approx)",value:String(a.indexedApprox)}),e.jsx(zs,{icon:e.jsx(jo,{n:a.noteCount}),label:"Notes in vault",value:String(a.noteCount)}),e.jsx(zs,{icon:e.jsx(nt,{size:14}),label:"Queries last 24h",value:String(a.queryCountLast24h)}),e.jsx(zs,{icon:e.jsx(He,{size:14}),label:"Avg response",value:a.avgResponseMs!==null?`${a.avgResponseMs} ms`:"—"}),e.jsx(zs,{icon:a.lastReindexOk?e.jsx(Ve,{size:14}):a.lastReindexOk===!1?e.jsx(ns,{size:14}):e.jsx(le,{size:14}),label:"Last reindex",value:a.lastReindexAt?We(a.lastReindexAt):"never",sub:a.lastReindexInserted!==null?`${a.lastReindexInserted} inserted${a.lastReindexFailed?`, ${a.lastReindexFailed} failed`:""}`:void 0})]}),e.jsxs(q,{children:[e.jsxs(ae,{children:[e.jsx(pe,{size:14})," Quick search"]}),e.jsx(ne,{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:m,onChange:f=>p(f.target.value),onKeyDown:f=>{f.key==="Enter"&&C()},disabled:h==="query","aria-label":"Search LightRAG"}),e.jsxs(T,{variant:"primary",onClick:C,disabled:h==="query"||!m.trim(),children:[h==="query"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(pe,{size:12}),"Query"]})]}),g&&e.jsx("div",{className:V("memory-query-result",g.ok?"ok":"err"),children:e.jsx("pre",{className:"mono text-sm",children:g.text})})]}),n&&e.jsxs(q,{children:[e.jsx(ae,{children:"Configuration"}),e.jsxs(ne,{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:n.llmBinding})," · ",e.jsx("code",{children:n.llmModel})]}),e.jsx("dt",{children:"Embedding"}),e.jsxs("dd",{children:[e.jsx("code",{children:n.embeddingBinding})," · ",e.jsx("code",{children:n.embeddingModel})]}),e.jsx("dt",{children:"Host"}),e.jsx("dd",{children:e.jsxs("code",{children:[n.host,":",n.port]})}),e.jsx("dt",{children:"Working dir"}),e.jsx("dd",{className:"mono ellipsis",title:n.workingDir,children:n.workingDir})]})]}),o.length>0&&e.jsxs(q,{children:[e.jsxs(ae,{children:[e.jsx(le,{size:14})," Server log (tail)"]}),e.jsxs(ne,{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(`
|
|
15
|
-
`)})]})]}):e.jsx("div",{className:"muted",children:"No LightRAG data available."})}function zs({icon:s,label:t,value:a,sub:i}){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}),i&&e.jsx("div",{className:"memory-stat-sub muted",children:i})]})]})}function jo({n:s}){return e.jsxs("span",{style:{position:"relative",display:"inline-block"},children:[e.jsx(pe,{size:14}),e.jsx("span",{className:"memory-mini-badge",children:s})]})}function vo({refreshKey:s}){const t=re(),a=Ae(),[i,n]=r.useState([]),[c,o]=r.useState(null),[l,u]=r.useState(!0),[x,h]=r.useState(""),[d,m]=r.useState(null),[p,g]=r.useState(!1),[j,v]=r.useState(null),[k,b]=r.useState([]),w=async()=>{var $;u(!0);try{const[N,A]=await Promise.all([R.get("/memory/notes").catch(()=>({notes:[]})),R.get("/memory/obsidian/tree").catch(()=>({tree:null}))]);n(N.notes||[]),o(A.tree),j&&!(($=N.notes)!=null&&$.find(O=>O.relPath===j))&&(v(null),b([]))}catch(N){t.error(`Vault load failed: ${N.message}`)}finally{u(!1)}};r.useEffect(()=>{w()},[s]),r.useEffect(()=>{if(!x.trim()){m(null);return}g(!0);const $=setTimeout(async()=>{try{const N=await R.get(`/memory/search?q=${encodeURIComponent(x)}&limit=50`),A=new Set((N.results||[]).map(O=>O.relPath));m(i.filter(O=>A.has(O.relPath)))}catch(N){t.error(`Search failed: ${N.message}`)}finally{g(!1)}},240);return()=>clearTimeout($)},[x,i,t]);const E=async $=>{v($);try{const N=await R.get(`/memory/obsidian/backlinks?note=${encodeURIComponent($)}`);b(N.backlinks||[])}catch{b([])}},y=()=>{a.open({title:"New note",width:720,children:e.jsx(ta,{mode:"create",onSave:async($,N,A)=>{try{await R.post("/memory/notes",{path:$,frontmatter:N,body:A}),t.success(`Created ${$}.`),a.close(),await w(),E($)}catch(O){t.error(`Create failed: ${O.message}`)}},onCancel:()=>a.close()})})},z=async $=>{try{const N=await R.get(`/memory/notes/${$.split("/").map(encodeURIComponent).join("/")}`);a.open({title:`Edit ${$}`,width:720,children:e.jsx(ta,{mode:"edit",initial:{relPath:N.relPath,frontmatter:N.frontmatter,body:N.body},onSave:async(A,O,S)=>{try{await R.put(`/memory/notes/${A.split("/").map(encodeURIComponent).join("/")}`,{frontmatter:O,body:S}),t.success(`Saved ${A}.`),a.close(),await w(),E(A)}catch(F){t.error(`Save failed: ${F.message}`)}},onCancel:()=>a.close()})})}catch(N){t.error(`Load failed: ${N.message}`)}},C=async $=>{if(confirm(`Delete ${$}? This cannot be undone.`))try{await R.del(`/memory/notes/${$.split("/").map(encodeURIComponent).join("/")}`),t.success(`Deleted ${$}.`),j===$&&v(null),await w()}catch(N){t.error(`Delete failed: ${N.message}`)}},f=r.useMemo(()=>[...i].sort(($,N)=>N.mtime-$.mtime),[i]),P=d??f;return l&&!i.length?e.jsxs("div",{className:"view-loading",children:[e.jsx(me,{size:"lg"}),e.jsx("p",{children:"Loading vault…"})]}):e.jsxs("div",{className:"memory-panel-content memory-obsidian-grid",children:[e.jsxs(q,{variant:"outlined",className:"memory-tree-card",children:[e.jsxs(ae,{children:[e.jsx(Oe,{size:14})," Folders"]}),e.jsx(ne,{children:c?`${Oa(c)} folder(s)`:"no vault"}),e.jsx("div",{className:"memory-tree-body",children:c?e.jsx(Fa,{node:c,depth:0,onSelect:E,selected:j}):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(pe,{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:$=>h($.target.value),"aria-label":"Search notes"}),x&&e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>h(""),"aria-label":"Clear search",children:e.jsx(be,{size:12})})]}),e.jsxs(T,{variant:"primary",size:"sm",onClick:y,children:[e.jsx(Un,{size:12})," New note"]}),e.jsx(T,{variant:"ghost",size:"sm",onClick:w,title:"Refresh",children:e.jsx(le,{size:12})})]}),p&&e.jsx("div",{className:"muted text-sm",children:"Searching…"}),P.length===0?e.jsx(ge,{icon:e.jsx(we,{size:28}),title:"No notes",message:i.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($=>e.jsxs("li",{className:V("memory-note-card",j===$.relPath&&"memory-note-card-active"),children:[e.jsxs("button",{type:"button",className:"memory-note-card-main",onClick:()=>E($.relPath),children:[e.jsxs("div",{className:"memory-note-card-title",children:[e.jsx(we,{size:12}),e.jsx("span",{children:Pa($)})]}),e.jsxs("div",{className:"memory-note-card-meta",children:[e.jsx("code",{className:"muted",children:$.relPath}),e.jsxs("span",{className:"muted",children:["· ",ze($.mtime)]}),!$.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:()=>z($.relPath),"aria-label":`Edit ${$.relPath}`,title:"Edit",children:e.jsx(Ns,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>C($.relPath),"aria-label":`Delete ${$.relPath}`,title:"Delete",children:e.jsx(Se,{size:12})})]})]},$.relPath))})]}),e.jsx("div",{className:"memory-obsidian-detail-col",children:j?e.jsx(yo,{relPath:j,onClose:()=>v(null)}):e.jsx(ge,{icon:e.jsx(we,{size:28}),title:"Pick a note",message:"Select a note from the list to view its content, frontmatter, and backlinks."})})]})}function Pa(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 Fa({node:s,depth:t,onSelect:a,selected:i}){const[n,c]=r.useState(t<2);return s.type==="note"?e.jsxs("button",{type:"button",className:V("memory-tree-node memory-tree-node-note",i===s.path&&"memory-tree-node-active"),style:{paddingLeft:6+t*12},onClick:()=>a(s.path),children:[e.jsx(we,{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:()=>c(o=>!o),children:[n?e.jsx(Be,{size:11}):e.jsx(Ge,{size:11}),e.jsx(Oe,{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})]}),n&&s.children&&e.jsx("div",{className:"memory-tree-children",children:s.children.map((o,l)=>e.jsx(Fa,{node:o,depth:t+1,onSelect:a,selected:i},`${o.path}-${l}`))})]})}function Oa(s){return s.type==="note"?0:1+(s.children||[]).reduce((t,a)=>t+Oa(a),0)}function yo({relPath:s,onClose:t}){var h,d;const[a,i]=r.useState(null),[n,c]=r.useState([]),[o,l]=r.useState(!0);if(r.useEffect(()=>{let m=!1;return l(!0),(async()=>{try{const[p,g]=await Promise.all([R.get(`/memory/notes/${s.split("/").map(encodeURIComponent).join("/")}`),R.get(`/memory/obsidian/backlinks?note=${encodeURIComponent(s)}`)]);if(m)return;i(p),c(g.backlinks||[])}catch{m||i(null)}finally{m||l(!1)}})(),()=>{m=!0}},[s]),o)return e.jsx("div",{className:"view-loading",children:e.jsx(me,{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((d=a.frontmatter)==null?void 0:d.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:Pa(a)}),e.jsx("button",{type:"button",className:"icon-btn",onClick:t,"aria-label":"Close",children:e.jsx(be,{size:12})})]}),e.jsxs("div",{className:"memory-note-detail-meta",children:[e.jsx("code",{children:s}),e.jsxs("span",{className:"muted",children:["· modified ",We(a.mtime)]})]}),u.length>0&&e.jsx("div",{className:"memory-tag-row",children:u.map((m,p)=>e.jsx("span",{className:"memory-tag",children:String(m)},p))}),e.jsx("pre",{className:"memory-note-body mono text-sm",children:a.body}),n.length>0&&e.jsxs("div",{className:"memory-backlinks",children:[e.jsx("h4",{children:"Backlinks"}),e.jsx("ul",{children:n.map(m=>e.jsxs("li",{children:[e.jsx("code",{children:m.fromRelPath}),e.jsx("p",{className:"muted text-sm",children:m.snippet})]},m.fromRelPath))})]}),x.length>0&&e.jsxs("div",{className:"memory-backlinks",children:[e.jsx("h4",{children:"Forward links"}),e.jsx("ul",{children:x.map((m,p)=>e.jsx("li",{children:e.jsx("code",{children:String(m)})},p))})]})]})}function ta({mode:s,initial:t,onSave:a,onCancel:i}){const[n,c]=r.useState((t==null?void 0:t.relPath)||"untitled.md"),[o,l]=r.useState(t!=null&&t.frontmatter?bo(t.frontmatter):`title: ""
|
|
16
|
-
tags: []
|
|
17
|
-
`),[u,x]=r.useState((t==null?void 0:t.body)||""),[h,d]=r.useState(!1),m=re(),p=async()=>{if(!n.endsWith(".md")){m.error("Path must end in .md");return}let g;try{g=No(o)||{}}catch(j){m.error(`Frontmatter parse failed: ${j.message}`);return}d(!0);try{await a(n,g,u)}finally{d(!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:n,onChange:g=>c(g.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:g=>l(g.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:g=>x(g.target.value),"aria-label":"Body markdown"}),e.jsxs("div",{className:"modal-footer-actions",style:{marginTop:12},children:[e.jsx(T,{variant:"ghost",onClick:i,disabled:h,children:"Cancel"}),e.jsxs(T,{variant:"primary",onClick:p,disabled:h,children:[h&&e.jsx(xe,{size:12,className:"memory-spin"}),s==="create"?"Create":"Save"]})]})]})}function bo(s){const t=[];for(const[a,i]of Object.entries(s))if(i!=null)if(Array.isArray(i)){if(i.length===0){t.push(`${a}: []`);continue}t.push(`${a}:`);for(const n of i)t.push(` - ${gt(n)}`)}else if(typeof i=="object"){t.push(`${a}:`);for(const[n,c]of Object.entries(i))t.push(` ${n}: ${gt(c)}`)}else t.push(`${a}: ${gt(i)}`);return t.join(`
|
|
18
|
-
`)}function gt(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 No(s){const t={},a=s.split(/\r?\n/);let i=0;for(;i<a.length;){const n=a[i];if(!n.trim()||n.trim().startsWith("#")){i++;continue}const c=n.match(/^([A-Za-z_][\w-]*):\s*(.*)$/);if(!c){i++;continue}const[,o,l]=c;if(l===""){const u={},x=[];let h=!1,d=!1;for(;i+1<a.length;){const m=a[i+1];if(!m.startsWith(" "))break;if(m.startsWith(" - "))h=!0,x.push(ft(m.slice(4))),i++;else{d=!0;const p=m.match(/^ ([A-Za-z_][\w-]*):\s*(.*)$/);p&&(u[p[1]]=ft(p[2])),i++}}t[o]=h&&!d?x:d?u:{}}else t[o]=ft(l);i++}return t}function ft(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 ko({refreshKey:s}){var w,E,y,z;const t=re(),[a,i]=r.useState(null),[n,c]=r.useState(null),[o,l]=r.useState(!0),[u,x]=r.useState(null),[h,d]=r.useState(null),m=async()=>{var C;l(!0);try{const[f,P,$]=await Promise.all([R.get("/memory/git/status").catch(()=>null),R.get("/memory/git/diff").catch(()=>null),R.get("/memory/config/global").catch(()=>null)]);i(f),c(P),d(((C=$==null?void 0:$.config)==null?void 0:C.git)||null)}catch(f){t.error(`Git status failed: ${f.message}`)}finally{l(!1)}};r.useEffect(()=>{m()},[s]);const p=async(C,f,P)=>{x(C);try{await f(),t.success(P),await m()}catch($){t.error(`${C} failed: ${$.message}`)}finally{x(null)}},g=()=>p("pull",()=>R.post("/memory/git/pull",{}),"Pull complete."),j=()=>p("push",()=>R.post("/memory/git/push",{}),"Push complete."),v=()=>{const C=prompt("Commit message:",`[memory-sync] ${new Date().toISOString().slice(0,10)} vault sync`);C&&p("commit",()=>R.post("/memory/git/commit",{message:C}),"Committed.")},k=()=>p("fetch",()=>R.post("/memory/git/sync",{push:!1}),"Fetch complete.");if(o&&!a)return e.jsxs("div",{className:"view-loading",children:[e.jsx(me,{size:"lg"}),e.jsx("p",{children:"Loading git status…"})]});if(!a)return e.jsx("div",{className:"muted",children:"No git data available."});const b=a.mode==="local-only";return e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(q,{variant:"elevated",children:[e.jsxs(ae,{children:[e.jsx(os,{size:14})," Git sync",b?e.jsx("span",{className:"memory-source-pill-status na",children:"local-only"}):e.jsx("span",{className:V("memory-source-pill-status",a.clean?"on":"warn"),children:a.clean?"clean":"dirty"})]}),e.jsx(ne,{children:b?"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]})}),!b&&e.jsxs("div",{className:"memory-git-status-row",children:[e.jsx(Rs,{ok:a.clean??!1,label:"Working tree"}),e.jsx(Rs,{ok:(a.ahead??0)===0,label:`Ahead: ${a.ahead??0}`}),e.jsx(Rs,{ok:(a.behind??0)===0,label:`Behind: ${a.behind??0}`}),e.jsx(Rs,{ok:(((w=a.modified)==null?void 0:w.length)??0)===0,label:`Modified: ${((E=a.modified)==null?void 0:E.length)??0}`}),e.jsx(Rs,{ok:(((y=a.untracked)==null?void 0:y.length)??0)===0,label:`Untracked: ${((z=a.untracked)==null?void 0:z.length)??0}`})]}),e.jsxs("div",{className:"memory-action-row",children:[e.jsxs(T,{variant:"secondary",size:"sm",onClick:g,disabled:!!u||b,children:[u==="pull"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(ha,{size:12}),"Pull"]}),e.jsxs(T,{variant:"secondary",size:"sm",onClick:j,disabled:!!u||b,children:[u==="push"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(It,{size:12}),"Push"]}),e.jsxs(T,{variant:"secondary",size:"sm",onClick:v,disabled:!!u||b,children:[u==="commit"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(ka,{size:12}),"Commit"]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:k,disabled:!!u||b,children:[u==="fetch"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(_n,{size:12}),"Fetch + sync"]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:m,disabled:!!u,children:[e.jsx(le,{size:12})," Refresh"]})]})]}),h&&e.jsxs(q,{children:[e.jsxs(ae,{children:[e.jsx(ba,{size:14})," Repository"]}),e.jsxs(ne,{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(q,{children:[e.jsxs(ae,{children:[e.jsx(Wn,{size:14})," Working-tree diff"]}),e.jsx(ne,{children:n!=null&&n.hasDiff?`${n.files.length} file(s) changed`:"no working-tree changes"}),n&&n.files.length>0&&e.jsx("ul",{className:"memory-diff-files",children:n.files.map(C=>e.jsx("li",{children:e.jsx("code",{children:C})},C))}),n&&n.lines.length>1&&e.jsx("pre",{className:"memory-log-tail mono text-xs",children:n.lines.slice(0,400).join(`
|
|
19
|
-
`)})]})]})}function Rs({ok:s,label:t}){return e.jsxs("span",{className:V("memory-git-status-pill",s?"ok":"warn"),children:[s?e.jsx(Ve,{size:11}):e.jsx(xe,{size:11,className:"memory-spin"}),t]})}function wo({refreshKey:s}){const t=re(),[a,i]=r.useState(""),[n,c]=r.useState({lightrag:!0,obsidian:!0}),[o,l]=r.useState(null),[u,x]=r.useState(!1),[h,d]=r.useState(""),m=async g=>{if(g.trim()){x(!0),d(g);try{const j=[...n.lightrag?["lightrag"]:[],...n.obsidian?["obsidian"]:[]],v=await R.post("/memory/semantic-search",{query:g,limit:20,sources:j});l(v.results||[])}catch(j){t.error(`Search failed: ${j.message}`),l([])}finally{x(!1)}}};r.useEffect(()=>{h&&m(h)},[n]),r.useEffect(()=>{h&&m(h)},[s]);const p=r.useMemo(()=>{const g=(o||[]).filter(v=>v.source==="obsidian"),j=(o||[]).filter(v=>v.source==="lightrag");return{obs:g,lr:j}},[o]);return e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(q,{variant:"elevated",children:[e.jsxs(ae,{children:[e.jsx(pe,{size:14})," Semantic search"]}),e.jsx(ne,{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:g=>i(g.target.value),onKeyDown:g=>{g.key==="Enter"&&m(a)},disabled:u,"aria-label":"Semantic search query"}),e.jsxs(T,{variant:"primary",onClick:()=>m(a),disabled:u||!a.trim(),children:[u?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(pe,{size:12}),"Search"]})]}),e.jsxs("div",{className:"memory-source-toggle-row",children:[e.jsx(aa,{active:n.obsidian,onToggle:()=>c(g=>({...g,obsidian:!g.obsidian})),label:"Obsidian",icon:e.jsx(we,{size:11})}),e.jsx(aa,{active:n.lightrag,onToggle:()=>c(g=>({...g,lightrag:!g.lightrag})),label:"LightRAG",icon:e.jsx(Fe,{size:11})}),a&&e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>{i(""),l(null),d("")},"aria-label":"Clear",children:e.jsx(be,{size:12})})]})]}),u&&e.jsx("div",{className:"view-loading",children:e.jsx(me,{size:"md"})}),!u&&o&&o.length===0&&e.jsx(ge,{icon:e.jsx(pe,{size:28}),title:"No matches",message:`Nothing in scope matched "${h}".`}),p.obs.length>0&&e.jsxs(q,{children:[e.jsxs(ae,{children:[e.jsx(we,{size:14})," Obsidian (",p.obs.length,")"]}),e.jsx("ul",{className:"memory-search-result-list",children:p.obs.map((g,j)=>e.jsxs("li",{className:"memory-search-result",children:[e.jsxs("div",{className:"memory-search-result-head",children:[e.jsx("code",{children:g.relPath}),e.jsxs("span",{className:"muted text-xs",children:["score ",g.score.toFixed(1)]})]}),e.jsx("p",{className:"muted text-sm",children:g.snippet})]},`obs-${j}`))})]}),p.lr.length>0&&e.jsxs(q,{children:[e.jsxs(ae,{children:[e.jsx(Fe,{size:14})," LightRAG (",p.lr.length,")"]}),e.jsx("div",{className:"memory-search-result-list",children:p.lr.map((g,j)=>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(Fe,{size:11})," LightRAG"]}),g.error&&e.jsxs("span",{className:"muted text-xs",children:["error: ",g.error]})]}),e.jsx("p",{className:"text-sm",children:g.snippet})]},`lr-${j}`))})]})]})}function aa({active:s,onToggle:t,label:a,icon:i}){return e.jsxs("button",{type:"button",className:V("memory-toggle-chip",s&&"memory-toggle-chip-active"),onClick:t,"aria-pressed":s,children:[i,e.jsx("span",{children:a})]})}function So({refreshKey:s}){const t=re(),[a,i]=r.useState(null),[n,c]=r.useState(!0),[o,l]=r.useState(!1),[u,x]=r.useState(""),[h]=r.useState(""),[d,m]=r.useState(null),[p,g]=r.useState(null),[j,v]=r.useState(null),[k,b]=r.useState(!1),w=async()=>{var f,P;c(!0);try{const $=await R.get("/memory/config/global");i($.config),x(((P=(f=$.config)==null?void 0:f.git)==null?void 0:P.remoteUrl)||""),await E()}catch($){t.error(`Config load failed: ${$.message}`)}finally{c(!1)}},E=async()=>{try{const f=await R.get("/memory/git/status");f.ok&&m({clean:f.clean,branch:f.branch,modified:f.modified,untracked:f.untracked})}catch{}};r.useEffect(()=>{w()},[s]);const y=async()=>{if(a){l(!0);try{await R.put("/memory/config/global",{git:{remoteUrl:u}}),t.success("Config saved.")}catch(f){t.error(`Save failed: ${f.message}`)}finally{l(!1)}}},z=async f=>{g(f);try{if(f==="pull"){const P=await R.post("/memory/git/pull",{});P.ok?t.success("Pull successful."):t.error(`Pull failed: ${P.output||"unknown error"}`)}else if(f==="push")(await R.post("/memory/git/push",{})).ok?t.success("Push successful."):t.error("Push failed.");else if(f==="commit"){const P=await R.post("/memory/git/commit",{});P.ok?t.success(`Committed: ${P.message}`):t.error("Commit failed.")}await E()}catch(P){t.error(`${f} failed: ${P.message}`)}finally{g(null)}},C=async()=>{b(!0);try{const f=await R.post("/memory/test-git",{});v(f.checks)}catch(f){t.error(`Test failed: ${f.message}`)}finally{b(!1)}};return n&&!a?e.jsxs("div",{className:"view-loading",children:[e.jsx(me,{size:"md"}),e.jsx("p",{children:"Loading config…"})]}):a?e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(q,{children:[e.jsxs(ae,{children:[e.jsx(os,{size:14})," Git sync"]}),e.jsx(ne,{children:"Configure the git remote and sync your memory vault."}),e.jsxs("div",{className:"memory-config-form",children:[e.jsx(jt,{label:"Vault path",inline:!0,children:e.jsx("span",{className:"memory-vault-path mono muted",children:h||"(loading…)"})}),e.jsx(jt,{label:"Remote URL",children:e.jsx("input",{type:"text",className:"input mono",value:u,onChange:f=>x(f.target.value),placeholder:"git@github.com:org/repo.git"})}),d&&e.jsxs(jt,{label:"Status",inline:!0,children:[e.jsx("span",{className:V("memory-pill",d.clean?"memory-pill-ok":"memory-pill-warn"),children:d.clean?"clean":"dirty"}),d.branch&&e.jsxs("span",{className:"muted",style:{marginLeft:8},children:[e.jsx(os,{size:12,style:{display:"inline"}})," ",d.branch]}),!d.clean&&d.modified!==void 0&&e.jsxs("span",{className:"muted",style:{marginLeft:8},children:[d.modified," modified, ",d.untracked," untracked"]})]})]}),e.jsxs("div",{className:"memory-action-row",style:{marginTop:12},children:[e.jsxs(T,{variant:"secondary",onClick:()=>z("pull"),disabled:p!==null,children:[p==="pull"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(Ke,{size:12}),"Pull"]}),e.jsxs(T,{variant:"secondary",onClick:()=>z("commit"),disabled:p!==null,children:[p==="commit"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(ka,{size:12}),"Commit"]}),e.jsxs(T,{variant:"secondary",onClick:()=>z("push"),disabled:p!==null,children:[p==="push"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(va,{size:12}),"Push"]})]})]}),e.jsxs(q,{children:[e.jsxs(ae,{children:[e.jsx(Ds,{size:14})," Connection tests"]}),e.jsx(ne,{children:"Verify the configured git remote is reachable."}),e.jsxs("div",{className:"memory-action-row",children:[e.jsxs(T,{variant:"secondary",onClick:C,disabled:k,children:[k?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(Ds,{size:12}),"Test git connection"]}),e.jsxs(T,{variant:"primary",onClick:y,disabled:o,children:[o?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(Es,{size:12}),"Save config"]})]}),j&&j.length>0&&e.jsx("ul",{className:"memory-check-list",style:{marginTop:12},children:j.map((f,P)=>e.jsxs("li",{className:"memory-check-row",children:[e.jsx("span",{className:"memory-check-icon",children:e.jsx("span",{className:V("memory-pill",f.pass?"memory-pill-ok":"memory-pill-warn"),children:f.pass?"OK":"FAIL"})}),e.jsx("span",{className:"memory-check-name",children:f.name}),e.jsx("span",{className:"memory-check-detail muted",children:f.detail})]},P))})]})]}):e.jsx("div",{className:"muted",children:"No config available."})}function jt({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 Xe=800,na=60,vt={default:"#8b5cf6",note:"#8b5cf6",entity:"#34d399",concept:"#fbbf24",root:"#f87171"};function Co(s,t){return vt[s]||vt[t]||vt.default}function zo(s){return 6+Math.min(s.size*2,10)}function Ro(s,t){var c,o;if(s.length===0)return[];const a=new Map;for(const l of s)a.set(l.id,new Set);for(const l of t)(c=a.get(l.source))==null||c.add(l.target),(o=a.get(l.target))==null||o.add(l.source);const i=s.map((l,u)=>{const x=u/s.length*Math.PI*2,h=Xe*.28;return{...l,x:Xe/2+h*Math.cos(x)+(Math.random()-.5)*40,y:Xe/2+h*Math.sin(x)+(Math.random()-.5)*40,vx:0,vy:0}}),n=new Map;for(const l of i)n.set(l.id,l);for(let l=0;l<na;l++){const u=1-l/na;for(let d=0;d<i.length;d++)for(let m=d+1;m<i.length;m++){const p=i[d],g=i[m],j=g.x-p.x,v=g.y-p.y,k=Math.sqrt(j*j+v*v)||1,b=400*u/(k*k),w=j/k*b,E=v/k*b;p.vx-=w,p.vy-=E,g.vx+=w,g.vy+=E}for(const d of t){const m=n.get(d.source),p=n.get(d.target);if(!m||!p)continue;const g=p.x-m.x,j=p.y-m.y,v=Math.sqrt(g*g+j*j)||1,b=(v-80)*.08*u,w=g/v*b,E=j/v*b;m.vx+=w,m.vy+=E,p.vx-=w,p.vy-=E}const x=Xe/2,h=Xe/2;for(const d of i)d.vx+=(x-d.x)*.01*u,d.vy+=(h-d.y)*.01*u;for(const d of i)d.vx*=.85,d.vy*=.85,d.x+=d.vx,d.y+=d.vy,d.x=Math.max(20,Math.min(Xe-20,d.x)),d.y=Math.max(20,Math.min(Xe-20,d.y))}return i}function To({data:s,onNodeClick:t,className:a}){const i=r.useRef(null),[n,c]=r.useState({x:0,y:0,scale:1}),o=r.useRef(!1),l=r.useRef({x:0,y:0,tx:0,ty:0}),u=r.useRef(null),[x,h]=r.useState(null),[d,m]=r.useState(null),p=r.useMemo(()=>Ro(s.nodes,s.edges),[s.nodes,s.edges]),g=r.useMemo(()=>{const f=new Map;for(const P of p)f.set(P.id,P);return f},[p]),j=r.useCallback(f=>{f.target.closest(".memory-graph-node")||(o.current=!0,l.current={x:f.clientX,y:f.clientY,tx:n.x,ty:n.y})},[n]),v=r.useCallback(f=>{if(!o.current)return;const P=f.clientX-l.current.x,$=f.clientY-l.current.y;c(N=>({...N,x:l.current.tx+P,y:l.current.ty+$}))},[]),k=r.useCallback(()=>{o.current=!1},[]),b=r.useCallback(f=>{f.preventDefault();const P=f.deltaY<0?1.1:.9,$=i.current;if(!$)return;const N=$.getBoundingClientRect(),A=f.clientX-N.left,O=f.clientY-N.top;c(S=>{const F=Math.max(.2,Math.min(4,S.scale*P)),Y=F/S.scale;return{x:A-(A-S.x)*Y,y:O-(O-S.y)*Y,scale:F}})},[]),w=r.useCallback(f=>{const P=Array.from(f.touches);if(P.length===2){const[$,N]=P;u.current=Math.hypot(N.clientX-$.clientX,N.clientY-$.clientY)}else P.length===1&&(o.current=!0,l.current={x:P[0].clientX,y:P[0].clientY,tx:n.x,ty:n.y})},[n]),E=r.useCallback(f=>{const P=Array.from(f.touches);if(P.length===2&&u.current!==null){const[$,N]=P,A=Math.hypot(N.clientX-$.clientX,N.clientY-$.clientY),O=A/u.current;u.current=A,c(S=>({...S,scale:Math.max(.2,Math.min(4,S.scale*O))}))}else if(P.length===1&&o.current){const $=P[0].clientX-l.current.x,N=P[0].clientY-l.current.y;c(A=>({...A,x:l.current.tx+$,y:l.current.ty+N}))}},[]),y=r.useCallback(()=>{o.current=!1,u.current=null},[]),z=r.useCallback(f=>{h(f.id===x?null:f.id),t==null||t(f)},[x,t]),C=Math.max(.5,1/Math.log2(n.scale+1));return e.jsx("svg",{ref:i,className:V("memory-graph-canvas",a),viewBox:`0 0 ${Xe} ${Xe}`,style:{width:"100%",height:"100%",minHeight:400,cursor:o.current?"grabbing":"grab"},onMouseDown:j,onMouseMove:v,onMouseUp:k,onMouseLeave:k,onWheel:b,onTouchStart:w,onTouchMove:E,onTouchEnd:y,children:e.jsxs("g",{transform:`translate(${n.x},${n.y}) scale(${n.scale})`,children:[s.edges.map((f,P)=>{const $=g.get(f.source),N=g.get(f.target);if(!$||!N)return null;const A=d===f.source||d===f.target||x===f.source||x===f.target;return e.jsx("line",{x1:$.x,y1:$.y,x2:N.x,y2:N.y,stroke:A?"#8b5cf6":"#2d3648",strokeWidth:A?C*2:C,strokeOpacity:A?.9:.5},`e-${P}`)}),p.map(f=>{const P=zo(f),$=Co(f.group,f.type),N=x===f.id,A=d===f.id;return e.jsxs("g",{className:"memory-graph-node",transform:`translate(${f.x},${f.y})`,onClick:()=>z(f),onMouseEnter:()=>m(f.id),onMouseLeave:()=>m(null),style:{cursor:"pointer"},children:[e.jsx("circle",{r:P+6,fill:"transparent"}),(N||A)&&e.jsx("circle",{r:P+4,fill:$,fillOpacity:.2}),e.jsx("circle",{r:P,fill:$,fillOpacity:N?1:.75,stroke:N?"#fff":$,strokeWidth:N?2:1}),n.scale>.5&&e.jsx("text",{y:P+12,textAnchor:"middle",fontSize:Math.max(8,Math.min(11,10/Math.sqrt(n.scale))),fill:"var(--text-dim, #b4bcd0)",style:{pointerEvents:"none",userSelect:"none"},children:f.label.length>20?f.label.slice(0,18)+"…":f.label})]},f.id)})]})})}const $o=[{color:"#8b5cf6",label:"Note / Default"},{color:"#34d399",label:"Entity (LightRAG)"},{color:"#fbbf24",label:"Concept (LightRAG)"},{color:"#f87171",label:"Root / Ungrouped"}];function Ao({className:s}){return e.jsx("div",{className:V("memory-graph-legend",s),children:$o.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 Mo({refreshKey:s}){const t=re(),[a,i]=r.useState({nodes:[],edges:[]}),[n,c]=r.useState(!0),[o,l]=r.useState(null),[u,x]=r.useState(""),[h,d]=r.useState(2),[m,p]=r.useState(""),[g,j]=r.useState(null),[v,k]=r.useState(null),b=r.useCallback(async()=>{var y,z;c(!0),l(null);try{const C=new URLSearchParams({limit:"200"});m&&C.set("root",m),C.set("depth",String(h));const f=await R.get(`/memory/graph?${C}`);i({nodes:f.nodes||[],edges:f.edges||[]}),j({totalNodes:f.totalNodes??((y=f.nodes)==null?void 0:y.length)??0,totalEdges:f.totalEdges??((z=f.edges)==null?void 0:z.length)??0})}catch(C){l(C.message),t.error(`Graph load failed: ${C.message}`)}finally{c(!1)}},[m,h,t]);r.useEffect(()=>{b()},[b,s]);const w=r.useCallback(y=>{k(z=>(z==null?void 0:z.id)===y.id?null:y)},[]),E=u.trim()?{nodes:a.nodes.filter(y=>y.label.toLowerCase().includes(u.toLowerCase())),edges:a.edges.filter(y=>a.nodes.some(z=>z.id===y.source&&z.label.toLowerCase().includes(u.toLowerCase()))||a.nodes.some(z=>z.id===y.target&&z.label.toLowerCase().includes(u.toLowerCase())))}:a;return e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(q,{children:[e.jsxs(ae,{children:[e.jsx(wa,{size:14})," Memory Graph"]}),e.jsx(ne,{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:m,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=>d(parseInt(y.target.value,10)),style:{marginLeft:8,verticalAlign:"middle"}}),h]}),e.jsx("button",{type:"button",className:"icon-btn",onClick:b,title:"Refresh graph",disabled:n,children:e.jsx(le,{size:14,className:n?"memory-spin":""})})]}),e.jsx(Ao,{})]})]}),e.jsx(q,{children:n&&!a.nodes.length?e.jsxs("div",{className:"view-loading",children:[e.jsx(me,{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(To,{data:E,onNodeClick:w,className:"memory-graph-canvas-svg"}),u&&e.jsxs("div",{className:"text-xs muted",style:{marginTop:4},children:["Showing ",E.nodes.length," of ",a.nodes.length," nodes"]})]})}),v&&e.jsxs(q,{children:[e.jsx(ae,{children:v.label}),e.jsx(ne,{children:e.jsx("code",{children:v.id})}),e.jsxs("dl",{className:"memory-config-row",children:[e.jsx("dt",{children:"Type"}),e.jsx("dd",{children:e.jsx("code",{children:v.type})}),e.jsx("dt",{children:"Group"}),e.jsx("dd",{children:e.jsx("code",{children:v.group})}),e.jsx("dt",{children:"Size"}),e.jsx("dd",{children:v.size})]})]}),g&&e.jsx(q,{children:e.jsxs("div",{className:"memory-graph-stats",children:[e.jsxs("span",{children:[g.totalNodes," node",g.totalNodes!==1?"s":""]}),e.jsx("span",{className:"muted",children:"·"}),e.jsxs("span",{children:[g.totalEdges," edge",g.totalEdges!==1?"s":""]}),u&&e.jsxs("span",{className:"muted",children:["· ",E.nodes.length," shown"]})]})})]})}function Io({onTextExtracted:s}){const t=re(),[a,i]=r.useState(null),[n,c]=r.useState(!1),[o,l]=r.useState(!1),u=r.useCallback(async()=>{l(!0);try{const d=await navigator.mediaDevices.getDisplayMedia({video:{mediaSource:"screen"}}),m=document.createElement("video");m.srcObject=d,await m.play();const p=document.createElement("canvas");p.width=m.videoWidth,p.height=m.videoHeight;const g=p.getContext("2d");if(!g){t.error("Failed to get canvas context");return}g.drawImage(m,0,0),d.getTracks().forEach(j=>j.stop()),m.remove(),p.toBlob(async j=>{if(!j){t.error("Failed to capture screenshot");return}const v=URL.createObjectURL(j);i(v),await x(j)},"image/png")}catch(d){d.name!=="NotAllowedError"&&t.error(`Capture failed: ${d.message}`)}finally{l(!1)}},[t]),x=r.useCallback(async d=>{c(!0);try{const m=new FileReader,p=await new Promise((j,v)=>{m.onload=()=>{const k=m.result,b=k.includes(",")?k.split(",")[1]:k;j(b)},m.onerror=()=>v(new Error("FileReader failed")),m.readAsDataURL(d)}),g=await R.post("/ocr/process",{image:p,lang:"eng"});g.ok&&(t.success("Text extracted from screenshot"),s==null||s(g.text,g.notePath))}catch(m){t.error(`OCR failed: ${m.message}`)}finally{c(!1)}},[t,s]),h=r.useCallback(()=>{i(null)},[]);return e.jsxs(q,{variant:"outlined",className:"screenshot-capture-card",children:[e.jsxs(ae,{children:[e.jsx(lt,{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:[n&&e.jsxs("span",{className:"text-sm muted",children:[e.jsx(xe,{size:12,className:"spinner"})," Extracting text…"]}),e.jsx(T,{variant:"ghost",size:"sm",onClick:h,disabled:n,children:"Dismiss"})]})]}):e.jsxs("div",{className:"screenshot-capture-empty",children:[e.jsx(lt,{size:32,className:"muted"}),e.jsx("p",{className:"muted text-sm",children:"Capture your screen to extract text via OCR."}),e.jsxs(T,{variant:"primary",size:"sm",onClick:u,disabled:o,children:[o?e.jsx(xe,{size:12,className:"spinner"}):e.jsx(lt,{size:12}),o?"Selecting…":"Capture Screen"]})]})})]})}function Lo(){const[s,t]=r.useState(null),[a,i]=r.useState(null),n=(c,o)=>{t(c),i(o)};return e.jsxs("div",{className:"screenshot-ocr-panel",children:[e.jsx(Io,{onTextExtracted:n}),s!==null&&e.jsxs(q,{variant:"outlined",className:"screenshot-ocr-result-card",children:[e.jsxs(ae,{children:[e.jsx(we,{size:14})," Extracted Text"]}),a&&e.jsxs(ne,{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 Eo({refreshKey:s}){return e.jsx("div",{className:"memory-panel-content",children:e.jsx(q,{variant:"outlined",className:"memory-panel-card",children:e.jsx("div",{className:"memory-panel-body",children:e.jsx(Lo,{})})})})}function Do({refreshKey:s}){const t=re(),[a,i]=r.useState(""),[n,c]=r.useState(""),[o,l]=r.useState(""),[u,x]=r.useState(!1),h=async()=>{if(!o.trim()){t.error("Content is required");return}x(!0);try{const d=await R.post("/clipboard/save",{url:a.trim()||void 0,title:n.trim()||void 0,content:o,savedAt:new Date().toISOString()});d.ok&&(t.success(`Saved to ${d.notePath}`),i(""),c(""),l(""))}catch(d){t.error(`Save failed: ${d.message}`)}finally{x(!1)}};return e.jsx("div",{className:"memory-panel-content",children:e.jsx(q,{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(Sa,{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:d=>i(d.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:n,onChange:d=>c(d.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:d=>l(d.target.value)}),e.jsx("div",{className:"vault-clipboard-actions",style:{marginTop:12},children:e.jsxs(T,{variant:"primary",size:"sm",onClick:h,disabled:u||!o.trim(),children:[u&&e.jsx(xe,{size:12,className:"spinner"}),"Save to Vault"]})})]})})})})}function Po({vaultPath:s,onSaved:t}){const[a,i]=r.useState(!1),[n,c]=r.useState(!1),o=r.useRef(null),l=r.useRef([]),u=async()=>{try{const d=await navigator.mediaDevices.getUserMedia({audio:!0}),m=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm",p=new MediaRecorder(d,{mimeType:m});p.ondataavailable=g=>{g.data&&g.data.size>0&&l.current.push(g.data)},p.onstop=async()=>{const g=new Blob(l.current,{type:"audio/webm"});l.current=[],d.getTracks().forEach(j=>j.stop()),await h(g)},p.start(1e3),o.current=p,i(!0)}catch(d){console.error("[VoiceRecorder] failed to start recording:",d)}},x=()=>{const d=o.current;d&&(d.stop(),i(!1),c(!0))},h=async d=>{try{const m=new FormData;m.append("audio",d,"voice-note.webm"),m.append("vaultPath",s||"");const p=await fetch("/api/voice/upload",{method:"POST",body:m});if(!p.ok){console.error("[VoiceRecorder] upload failed:",p.status,await p.text()),c(!1);return}const{notePath:g,transcription:j}=await p.json();t==null||t(g,j)}catch(m){console.error("[VoiceRecorder] upload error:",m)}finally{c(!1)}};return e.jsxs("div",{className:"voice-recorder",children:[!a&&!n&&e.jsxs(T,{variant:"accent",size:"sm",onClick:u,"aria-label":"Start recording",children:[e.jsx(Dt,{size:14})," Record"]}),a&&e.jsxs(T,{variant:"danger",size:"sm",onClick:x,"aria-label":"Stop recording",children:[e.jsx(ja,{size:14})," Stop"]}),n&&e.jsxs(T,{variant:"secondary",size:"sm",disabled:!0,children:[e.jsx(xe,{size:14,className:"spinning"})," Transcribing…"]})]})}function Fo({note:s,onDelete:t}){const[a,i]=r.useState(!1),[n]=r.useState(()=>{if(!s.audioPath)return null;const l=new Audio(`/api/voice/${s.id}/audio`);return l.onended=()=>i(!1),l}),c=()=>{n&&(a?(n.pause(),n.currentTime=0,i(!1)):(n.play(),i(!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:[n&&e.jsx("button",{type:"button",className:"icon-btn",onClick:c,"aria-label":a?"Pause":"Play",title:a?"Pause":"Play",children:a?e.jsx(ga,{size:13}):e.jsx(ks,{size:13})}),e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>t(s.id),"aria-label":"Delete note",title:"Delete note",children:e.jsx(Se,{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 Oo({vaultPath:s,refreshKey:t=0}){const[a,i]=r.useState([]),[n,c]=r.useState(""),[o,l]=r.useState(!0),u=async()=>{l(!0);try{const d=s?`?vaultPath=${encodeURIComponent(s)}`:"",p=await(await fetch(`/api/voice/list${d}`)).json();i(p.notes||[])}catch(d){console.error("[VoiceNotesPanel] failed to load notes:",d)}finally{l(!1)}};r.useEffect(()=>{u()},[s,t]);const x=async d=>{try{const m=await fetch(`/api/voice/${d}`,{method:"DELETE"});(m.ok||m.status===204)&&i(p=>p.filter(g=>g.id!==d))}catch(m){console.error("[VoiceNotesPanel] delete failed:",m)}},h=a.filter(d=>{var m;return!n||(((m=d.transcript)==null?void 0:m.toLowerCase().includes(n.toLowerCase()))??!1)});return e.jsxs(q,{children:[e.jsxs(ae,{children:[e.jsx(Dt,{size:14})," Voice Notes"]}),e.jsx(ne,{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:n,onChange:d=>c(d.target.value),placeholder:"Search transcripts…","aria-label":"Search voice notes"})}),e.jsx("div",{className:"voice-recorder-row",children:e.jsx(Po,{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:n?"No notes match your search.":"No voice notes yet. Hit Record to add one."}):e.jsx("div",{className:"voice-note-list",children:h.map(d=>e.jsx(Fo,{note:d,onDelete:x},d.id))})]})}const Bo=[{id:"overview",label:"Overview",icon:ca},{id:"lightrag",label:"LightRAG",icon:Fe},{id:"obsidian",label:"Obsidian Vault",icon:we},{id:"git",label:"Git Sync",icon:os},{id:"semantic",label:"Semantic Search",icon:pe},{id:"config",label:"Config",icon:At},{id:"graph",label:"Memory Graph",icon:wa},{id:"webclip",label:"Web Clip",icon:Sa},{id:"screenshot",label:"Screenshot OCR",icon:Vn},{id:"voice",label:"Voice Notes",icon:Dt}];function Uo(s){const t=re(),[a,i]=r.useState("overview"),[n,c]=r.useState(0),o=r.useCallback(()=>{c(x=>x+1)},[]),l=r.useCallback(async()=>{o(),t.info("Refreshing memory…",1200)},[o,t]),u=()=>{switch(a){case"overview":return e.jsx(po,{refreshKey:n,onRefresh:o,setActiveSubPanel:i});case"lightrag":return e.jsx(fo,{refreshKey:n});case"obsidian":return e.jsx(vo,{refreshKey:n});case"git":return e.jsx(ko,{refreshKey:n});case"semantic":return e.jsx(wo,{refreshKey:n});case"config":return e.jsx(So,{refreshKey:n});case"graph":return e.jsx(Mo,{refreshKey:n});case"webclip":return e.jsx(Do,{refreshKey:n});case"screenshot":return e.jsx(Eo,{refreshKey:n});case"voice":return e.jsx(Oo,{refreshKey:n});default:return e.jsxs(q,{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(Fe,{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:l,"aria-label":"Refresh memory",title:"Refresh",children:e.jsx(le,{size:14})})})]}),e.jsxs("div",{className:"memory-tab-body",children:[e.jsx("nav",{className:"memory-source-rail","aria-label":"Memory sources",children:Bo.map(x=>{const h=x.icon,d=a===x.id;return e.jsxs("button",{type:"button",role:"tab","aria-selected":d,className:V("memory-source-button",d&&"memory-source-button-active"),onClick:()=>i(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 _o=Le.memo(Uo),Ts=[{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 Wo(s,t,a,i){const n=a.has(s.id);return e.jsxs(q,{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(Oe,{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(we,{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 ",ze(s.lastAccessed)]})})]}),e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>i(s.id),"aria-label":n?"Collapse":"Expand",children:n?e.jsx(Be,{size:14}):e.jsx(Ge,{size:14})})]}),n&&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((c,o)=>e.jsxs("div",{className:"history-timeline-row",children:[e.jsx("span",{className:"history-timeline-ts",children:new Date(c.ts).toLocaleTimeString()}),e.jsx("span",{className:"history-timeline-kind",children:c.kind||"event"}),e.jsxs("span",{className:"history-timeline-msg",title:String(c.text||c.title||""),children:[c.author?`@${c.author} `:"",String(c.text??c.title??c.name??"")]})]},o))})]},s.id)}function Vo({snapshot:s}){var v,k;const t=re(),[a,i]=r.useState(null),[n,c]=r.useState(!0),[o,l]=r.useState("1d"),[u,x]=r.useState(new Set),[h,d]=r.useState(0),m=async b=>{try{const w=b?`?since=${encodeURIComponent(b)}&limit=1000`:"?limit=1000",E=await R.get(`/history${w}`);i(E),x(new Set(E.projects.filter(y=>E.events.some(z=>z.projectId===y.id)).map(y=>y.id)))}catch(w){t.error(`History load failed: ${w.message}`)}finally{c(!1)}};r.useEffect(()=>{c(!0);const b=Ts.find(w=>w.id===o)||Ts[1];if(b.ms>0){const w=new Date(Date.now()-b.ms).toISOString();m(w)}else m()},[o]),r.useEffect(()=>{const b=setInterval(()=>d(w=>w+1),3e4);return()=>clearInterval(b)},[]);const p=new Map;for(const b of(a==null?void 0:a.events)||[]){const w=b.projectId||"global";p.has(w)||p.set(w,[]),p.get(w).push(b)}const g=b=>{x(w=>{const E=new Set(w);return E.has(b)?E.delete(b):E.add(b),E})},j=()=>{if(!a)return;const b=new Blob([JSON.stringify(a,null,2)],{type:"application/json"}),w=URL.createObjectURL(b),E=document.createElement("a");E.href=w,E.download=`bizar-history-${new Date().toISOString().replace(/[:.]/g,"-")}.json`,E.click(),URL.revokeObjectURL(w),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(Ls,{size:18})," History"]}),e.jsxs("p",{className:"view-subtitle",children:["Cross-project history of events, tasks, and plans.",((v=a==null?void 0:a.stats)==null?void 0:v.lastTs)&&e.jsxs(e.Fragment,{children:[" · last event ",ze(a.stats.lastTs)]})]})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs("div",{className:"tasks-toolbar-group",children:[e.jsx(Hn,{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:b=>l(b.target.value),title:"Time range","aria-label":"Time range",children:Ts.map(b=>e.jsx("option",{value:b.id,children:b.label},b.id))})]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:()=>{c(!0);const b=Ts.find(w=>w.id===o)||Ts[1];b.ms>0?m(new Date(Date.now()-b.ms).toISOString()):m()},children:[e.jsx(le,{size:14})," Refresh"]}),e.jsxs(T,{variant:"secondary",size:"sm",onClick:j,children:[e.jsx(Ke,{size:14})," Export"]})]})]}),n&&e.jsxs("div",{className:"view-loading",children:[e.jsx(me,{size:"lg"}),e.jsx("p",{children:"Loading history…"})]}),!n&&a&&e.jsxs("div",{className:"history-list",children:[a.projects.length===0&&e.jsxs(q,{children:[e.jsxs(ae,{children:[e.jsx(Oe,{size:14})," No projects"]}),e.jsx(ne,{children:"Register a project in Overview to start tracking history."})]}),a.projects.length>0&&e.jsx(Pt,{items:a.projects,itemHeight:70,height:Math.min(a.projects.length*70,500),className:"history-virtual-list",renderItem:b=>Wo(b,p.get(b.id)||[],u,g)}),p.has("global")&&e.jsxs(q,{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(Ls,{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((b,w)=>e.jsxs("div",{className:"history-timeline-row",children:[e.jsx("span",{className:"history-timeline-ts",children:new Date(b.ts).toLocaleTimeString()}),e.jsx("span",{className:"history-timeline-kind",children:b.kind||"event"}),e.jsxs("span",{className:"history-timeline-msg",title:String(b.text||b.title||""),children:[b.author?`@${b.author} `:"",String(b.text??b.title??b.name??"")]})]},w))})]}),((k=a.stats)==null?void 0:k.counts)&&Object.keys(a.stats.counts).length>0&&e.jsxs(q,{children:[e.jsx(ae,{children:"Event counts by kind"}),e.jsxs(ne,{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((b,w)=>w[1]-b[1]).slice(0,30).map(([b,w])=>e.jsxs("span",{className:V("tag","tag-neutral"),style:{fontFamily:"var(--font-mono)"},children:[b,": ",w]},b))})]})]})]})}const ye={top:16,right:20,bottom:40,left:52};function Ho({series:s,height:t=280,onHover:a,className:i}){const n=r.useRef(null),[c,o]=r.useState(null),{labels:l,requests:u,tokens:x}=s,h=l.length;if(h===0)return e.jsx("div",{className:V("usage-chart-empty",i),style:{height:t},children:e.jsx("span",{children:"No data for this range"})});const d=600-ye.left-ye.right,m=t-ye.top-ye.bottom,p=Math.max(...u,1),g=Math.max(...x,1),j=Math.max(4,Math.min(24,Math.floor(d/h)-4)),v=(d-j*h)/(h+1);function k(A){return ye.left+v+A*(j+v)}function b(A){return A/p*m*.75}function w(A){return ye.top+m-A/g*m*.75}const E=x.map((A,O)=>`${k(O)+j/2},${w(A)}`).join(" "),y=[0,.25,.5,.75,1].map(A=>({y:ye.top+m-A*m*.75,label:A===0?"0":`${Math.round(p*A).toLocaleString()}`})),z=[0,.25,.5,.75,1].map(A=>({y:ye.top+m-A*m*.75,label:A===0?"0":`${Math.round(g*A/1e3)}k`})),C=Math.max(1,Math.floor(h/7)),f=l.map((A,O)=>({i:O,l:A,x:k(O)+j/2})).filter((A,O)=>O%C===0),P=r.useCallback(A=>{if(!n.current)return;const O=n.current.getBoundingClientRect(),S=(A.clientX-O.left)*(600/O.width),F=(A.clientY-O.top)*(t/O.height),Y=S-ye.left,L=Math.round((Y-v/2)/(j+v)),X=Math.max(0,Math.min(h-1,L));o({index:X,x:A.clientX-O.left,y:A.clientY-O.top}),a==null||a(X,S,F)},[h,j,v,a,t]),$=r.useCallback(()=>{o(null),a==null||a(null,0,0)},[a]),N=c;return e.jsxs("div",{ref:n,className:V("usage-chart",i),style:{position:"relative"},children:[e.jsxs("svg",{viewBox:`0 0 600 ${t}`,width:"100%",height:t,style:{display:"block",overflow:"visible"},onMouseMove:P,onMouseLeave:$,children:[y.map((A,O)=>e.jsx("line",{x1:ye.left,y1:A.y,x2:600-ye.right,y2:A.y,stroke:"var(--border)",strokeWidth:1,strokeDasharray:"4,3",opacity:.5},`grid-${O}`)),y.map((A,O)=>e.jsx("text",{x:ye.left-6,y:A.y+4,textAnchor:"end",fontSize:10,fill:"var(--text-muted)",fontFamily:"var(--font-mono, ui-monospace, monospace)",children:A.label},`ly-${O}`)),z.map((A,O)=>e.jsx("text",{x:600-ye.right+6,y:A.y+4,textAnchor:"start",fontSize:10,fill:"var(--text-muted)",fontFamily:"var(--font-mono, ui-monospace, monospace)",children:A.label},`ry-${O}`)),u.map((A,O)=>{const S=b(A),F=k(O),Y=ye.top+m-S;return e.jsx("rect",{x:F,y:Y,width:j,height:S,rx:2,fill:((N==null?void 0:N.index)===O,"var(--accent)"),opacity:(N==null?void 0:N.index)===O?1:.75,style:{transition:"opacity 120ms ease"}},`bar-${O}`)}),e.jsx("polyline",{points:E,fill:"none",stroke:"var(--warning, #d29922)",strokeWidth:2,strokeLinejoin:"round",strokeLinecap:"round",opacity:.9}),x.map((A,O)=>e.jsx("circle",{cx:k(O)+j/2,cy:w(A),r:(N==null?void 0:N.index)===O?5:3,fill:"var(--warning, #d29922)",opacity:(N==null?void 0:N.index)===O?1:.7,style:{transition:"r 120ms ease"}},`dot-${O}`)),f.map(({i:A,l:O,x:S})=>e.jsx("text",{x:S,y:ye.top+m+18,textAnchor:"middle",fontSize:10,fill:"var(--text-muted)",fontFamily:"var(--font-mono, ui-monospace, monospace)",children:O},`xl-${A}`)),e.jsx("line",{x1:ye.left,y1:ye.top+m,x2:600-ye.right,y2:ye.top+m,stroke:"var(--border)",strokeWidth:1})]}),N!==null&&e.jsxs("div",{className:"usage-chart-tooltip",style:{left:Math.min(N.x+12,460),top:N.y-60},children:[e.jsx("div",{className:"usage-tooltip-date",children:l[N.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[N.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[N.index].toLocaleString()})]})]})]})}function ss({label:s,col:t,sortKey:a,sortDir:i,onSort:n}){const c=a===t;return e.jsxs("th",{className:V("usage-sort-header",c&&"is-active"),onClick:()=>n(t),"aria-sort":c?i==="asc"?"ascending":"descending":"none",children:[e.jsx("span",{children:s}),e.jsx("span",{className:"usage-sort-icon",children:c?i==="asc"?" ↑":" ↓":" ↕"})]})}function qo({rows:s,sortKey:t,sortDir:a,onSort:i}){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(ss,{label:"Model",col:"modelId",sortKey:t,sortDir:a,onSort:i}),e.jsx(ss,{label:"Requests",col:"requests",sortKey:t,sortDir:a,onSort:i}),e.jsx(ss,{label:"Prompt Tok",col:"promptTokens",sortKey:t,sortDir:a,onSort:i}),e.jsx(ss,{label:"Compl Tok",col:"completionTokens",sortKey:t,sortDir:a,onSort:i}),e.jsx(ss,{label:"Total Tok",col:"totalTokens",sortKey:t,sortDir:a,onSort:i}),e.jsx(ss,{label:"Avg Latency",col:"avgLatencyMs",sortKey:t,sortDir:a,onSort:i}),e.jsx(ss,{label:"Errors",col:"errors",sortKey:t,sortDir:a,onSort:i})]})}),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(n=>e.jsxs("tr",{children:[e.jsx("td",{className:"usage-table-model",children:e.jsx("code",{children:n.modelId})}),e.jsx("td",{className:"mono",children:n.requests.toLocaleString()}),e.jsx("td",{className:"mono",children:n.promptTokens.toLocaleString()}),e.jsx("td",{className:"mono",children:n.completionTokens.toLocaleString()}),e.jsx("td",{className:"mono",children:n.totalTokens.toLocaleString()}),e.jsxs("td",{className:"mono",children:[n.avgLatencyMs,"ms"]}),e.jsx("td",{className:V("mono",n.errors>0&&"is-err"),children:n.errors>0?n.errors:"—"})]},`${n.providerId}::${n.modelId}`))})]})})}function Ko({activeTab:s,setActiveTab:t}){const[a,i]=r.useState("quota"),n=re();return e.jsxs("div",{className:"view-container view-minimax-usage",children:[e.jsxs("div",{className:"minimax-sub-tabs",children:[e.jsxs("button",{className:V("minimax-sub-tab",a==="quota"&&"is-active"),onClick:()=>i("quota"),children:[e.jsx($t,{size:13})," Token Plan"]}),e.jsxs("button",{className:V("minimax-sub-tab",a==="analytics"&&"is-active"),onClick:()=>i("analytics"),children:[e.jsx(Ca,{size:13})," Usage Analytics"]})]}),a==="quota"?e.jsx(Go,{activeTab:s,setActiveTab:t}):e.jsx(Yo,{toast:n})]})}function Go({activeTab:s,setActiveTab:t}){var Q;const a=re(),[i,n]=r.useState(null),[c,o]=r.useState(null),[l,u]=r.useState(null),[x,h]=r.useState(!0),[d,m]=r.useState(!1),[p,g]=r.useState(null),[j,v]=r.useState(null),[k,b]=r.useState(!1),[w,E]=r.useState(0),[y,z]=r.useState(!1),[C,f]=r.useState(null),[P,$]=r.useState(""),[N,A]=r.useState(!1),[O,S]=r.useState(!1),F=r.useCallback(async()=>{h(!0),g(null);try{const[U,Z,he]=await Promise.all([R.get("/minimax/status"),R.get("/minimax/remains"),R.get("/minimax/onboarding")]);n(U),o(Z),u(he),U.configured&&E(4)}catch(U){g(U.message||"Failed to load MiniMax data")}finally{h(!1)}},[]);r.useEffect(()=>{F()},[F]);const Y=r.useCallback(async()=>{try{await R.post("/minimax/onboarding",{dismissedAt:Date.now()}),u(U=>U&&{...U,dismissedAt:Date.now()})}catch{}},[]),L=r.useCallback(async()=>{if(!P.trim()){a.error("Paste a Subscription Key first.");return}z(!0),f(null);try{const U=await R.post("/minimax/test",{prompt:"Reply with a single word: pong",model:"MiniMax-M3",maxTokens:16});if(f(U),U.ok){E(3),a.success("Key works. Saving…");try{await R.post("/minimax/onboarding/save-key",{key:P.trim(),groupId:"default"}),ie(),a.success("Subscription Key saved.")}catch(Z){a.error(`Save failed: ${Z.message}`)}F()}else a.error(`Verification failed: ${U.message??U.error??"unknown"}`)}catch(U){a.error(`Test request failed: ${U.message}`)}finally{z(!1)}},[P,a,F]),X=r.useCallback(async()=>{if(!P.trim()){a.error("Paste a Subscription Key first.");return}S(!0);try{const U=await R.post("/minimax/onboarding/save-key",{key:P.trim(),groupId:"default"});if(!U.ok){a.error(`Save failed: ${U.message??U.error??"unknown"}`);return}$(""),ie(),a.success("Subscription Key saved. Loading quota…"),F()}catch(U){a.error(`Save failed: ${U.message}`)}finally{S(!1)}},[P,a,F]),ie=r.useCallback(async()=>{try{await R.del("/minimax/cache")}catch{}},[]),te=r.useCallback(async()=>{m(!0),g(null);try{await R.post("/minimax/remains/refresh"),await F(),a.success("Refreshed")}catch(U){a.error(`Refresh failed: ${U.message}`)}finally{m(!1)}},[F,a]),B=r.useCallback(async()=>{var U;b(!0),v(null);try{const Z=await R.post("/minimax/test",{prompt:"Reply with a single word: pong",model:"MiniMax-M3",maxTokens:16});v(Z),Z.ok?a.success(`Test ok — used ${((U=Z.usage)==null?void 0:U.total_tokens)??"?"} tokens`):a.error(`Test failed: ${Z.message??Z.error??"unknown"}`)}catch(Z){a.error(`Test request failed: ${Z.message}`)}finally{b(!1)}},[a]);return x&&!i?e.jsxs("div",{className:"view-container",children:[e.jsx(me,{})," Loading MiniMax data…"]}):i?!i.configured&&(l==null?void 0:l.dismissedAt)==null&&w<4?e.jsx(Jo,{step:w,setStep:E,keyDraft:P,setKeyDraft:$,showKey:N,setShowKey:A,verifying:y,verifyResult:C,onVerify:L,onSkip:async()=>{await Y(),a.success("Skipped.")},onManualKeySave:X,savingKey:O,status:i}):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($t,{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(T,{variant:"secondary",size:"sm",onClick:()=>t("settings"),title:"Configure your Subscription Key",children:[e.jsx(Os,{size:14})," ",i.configured?`Key ${i.apiKeyHint}`:"Add key"]}),e.jsxs(T,{variant:"secondary",size:"sm",onClick:te,disabled:d,children:[d?e.jsx(xe,{size:14,className:"spin"}):e.jsx(le,{size:14})," Refresh"]})]})]}),c&&!c.ok&&e.jsxs("div",{className:"banner banner-err",children:[e.jsx(ke,{size:16}),e.jsxs("span",{children:[e.jsx("strong",{children:"Couldn't load quota"}),": ",c.message??c.error??"unknown error"]})]}),(c==null?void 0:c.ok)&&c.models&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"minimax-stats-row",children:[e.jsx(Vs,{label:"Models tracked",value:String(c.models.length),hint:"Distinct model quotas returned by the API"}),e.jsx(Vs,{label:"Last fetched",value:c.fetchedAt?Qo(c.fetchedAt):"—",hint:"Refreshed on demand + every 60s"}),e.jsx(Vs,{label:"Group",value:c.groupId??"—",hint:"Usually 'default' for an individual team"}),e.jsx(Vs,{label:"API key",value:c.apiKeyHint??"—",hint:"Masked; the real key never leaves auth.json"})]}),e.jsx("div",{className:"minimax-models-grid",children:c.models.map(U=>e.jsx(Xo,{model:U},U.model_name))})]}),i.configured&&e.jsxs(q,{id:"minimax-test",children:[e.jsxs(ae,{children:[e.jsx(cs,{size:14})," Test the API key"]}),e.jsxs(ne,{children:["One-shot chat completion to ",e.jsxs("code",{children:[i.chatBaseUrl,"/chat/completions"]}),"."]}),e.jsxs("div",{className:"minimax-test-actions",children:[e.jsxs(T,{onClick:B,disabled:k,variant:"primary",size:"sm",children:[k?e.jsx(xe,{size:14,className:"spin"}):e.jsx(cs,{size:14})," Send test prompt"]}),e.jsx("code",{className:"minimax-test-prompt",children:'"Reply with a single word: pong"'})]}),j&&e.jsxs("div",{className:V("minimax-test-result",j.ok?"ok":"err"),children:[j.ok?e.jsx(Ve,{size:14}):e.jsx(ke,{size:14}),e.jsx("div",{className:"minimax-test-body",children:j.ok?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"minimax-test-line",children:[e.jsx("strong",{children:"model:"})," ",e.jsx("code",{children:j.model})," ·"," ",e.jsx("strong",{children:"finish:"})," ",j.finishReason??"—"]}),j.content&&e.jsx("div",{className:"minimax-test-content",children:e.jsx("code",{children:j.content})}),j.usage&&e.jsxs("div",{className:"minimax-test-usage",children:[e.jsx("strong",{children:"usage:"})," total ",e.jsx("code",{children:j.usage.total_tokens??"?"})," · prompt"," ",e.jsx("code",{children:j.usage.prompt_tokens??"?"})," · completion"," ",e.jsx("code",{children:j.usage.completion_tokens??"?"}),((Q=j.usage.prompt_tokens_details)==null?void 0:Q.cached_tokens)!=null&&e.jsxs(e.Fragment,{children:[" · cached ",e.jsx("code",{children:j.usage.prompt_tokens_details.cached_tokens})]})]})]}):e.jsx("pre",{children:j.message??j.error??"unknown error"})})]})]})]}):e.jsx("div",{className:"view-container",children:e.jsxs("div",{className:"error-card",children:[e.jsx(ke,{size:20}),e.jsxs("div",{children:[e.jsx("strong",{children:"Couldn't load MiniMax status"}),e.jsx("pre",{children:p??"unknown error"})]})]})})}function Yo({toast:s}){const[t,a]=r.useState("24h"),[i,n]=r.useState(""),[c,o]=r.useState(""),[l,u]=r.useState(!0),[x,h]=r.useState(null),[d,m]=r.useState([]),[p,g]=r.useState("requests"),[j,v]=r.useState("desc"),[k,b]=r.useState(!1),w=r.useCallback(async(N,A,O)=>{u(!0);try{const S=new URLSearchParams({range:N});N==="custom"&&A&&O&&(S.set("from",String(A)),S.set("to",String(O)));const[F,Y]=await Promise.all([R.get(`/usage?${S.toString()}`),R.get("/usage/recent?limit=20")]);h(F),m(Y.records)}catch(S){s.error(`Failed to load usage data: ${S.message}`)}finally{u(!1)}},[s]);r.useEffect(()=>{if(t==="custom"){const N=i?new Date(i).getTime():Date.now()-6048e5,A=c?new Date(c).getTime():Date.now();w("custom",N,A)}else w(t)},[t,w]);const E=r.useCallback(N=>{p===N?v(A=>A==="asc"?"desc":"asc"):(g(N),v("desc"))},[p]),y=r.useMemo(()=>x!=null&&x.perModel?[...x.perModel].sort((N,A)=>{const O=N[p]??0,S=A[p]??0,F=typeof O=="number"&&typeof S=="number"?O-S:String(O).localeCompare(String(S));return j==="asc"?F:-F}):[],[x==null?void 0:x.perModel,p,j]),z=r.useMemo(()=>x!=null&&x.daily?{labels:x.daily.map(N=>N.date.slice(5)),requests:x.daily.map(N=>N.requests),tokens:x.daily.map(N=>N.totalTokens)}:{labels:[],requests:[],tokens:[]},[x==null?void 0:x.daily]),C=r.useCallback(async()=>{b(!0),await w(t==="custom"?"custom":t,t==="custom"&&i?new Date(i).getTime():void 0,t==="custom"&&c?new Date(c).getTime():void 0),b(!1)},[w,t,i,c]);if(l&&!x)return e.jsxs("div",{className:"view-container",children:[e.jsx(me,{})," Loading usage data…"]});const f=x==null?void 0:x.totals,P=(x==null?void 0:x.errors)??[],$=(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(Ca,{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(T,{variant:"secondary",size:"sm",onClick:C,disabled:k,children:[k?e.jsx(xe,{size:14,className:"spin"}):e.jsx(le,{size:14})," Refresh"]})})]}),e.jsxs("div",{className:"usage-time-range",children:[["24h","7d","30d","custom"].map(N=>e.jsx("button",{className:V("usage-range-chip",t===N&&"is-active"),onClick:()=>a(N),children:N==="custom"?"Custom":N.toUpperCase()},N)),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:i,onChange:N=>n(N.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:c,onChange:N=>o(N.target.value),"aria-label":"To date"})]})]}),e.jsxs("div",{className:"usage-kpi-row",children:[e.jsx($s,{label:"Total Requests",value:(f==null?void 0:f.requests.toLocaleString())??"—",sub:f?`${f.errors} errors`:void 0,tone:f&&f.errors>f.requests*.1?"warn":void 0}),e.jsx($s,{label:"Total Tokens",value:f?f.totalTokens>=1e3?`${Math.round(f.totalTokens/1e3)}k`:String(f.totalTokens):"—",sub:f?`${f.promptTokens.toLocaleString()} prompt · ${f.completionTokens.toLocaleString()} completion`:void 0}),e.jsx($s,{label:"Errors",value:String((f==null?void 0:f.errors)??"—"),sub:P.length>0?`${P[0].code}: ${P[0].count}`:void 0,tone:f&&f.errors>0?"err":void 0}),e.jsx($s,{label:"Avg Latency",value:(f==null?void 0:f.avgLatencyMs)!=null?`${f.avgLatencyMs}ms`:"—",sub:(f==null?void 0:f.p95LatencyMs)!=null?`p95 ${f.p95LatencyMs}ms`:void 0}),e.jsx($s,{label:"Est. Cost",value:(f==null?void 0:f.costEstimate)!=null&&f.costEstimate>0?`$${f.costEstimate.toFixed(4)}`:"—",sub:"approximate USD",tone:void 0})]}),e.jsxs(q,{className:"usage-chart-card",children:[e.jsx("div",{className:"usage-chart-wrap",children:e.jsx(Ho,{series:z,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(q,{children:[e.jsx(ae,{children:"Per-model breakdown"}),e.jsx(qo,{rows:y,sortKey:p,sortDir:j,onSort:E})]}),$.length>0&&e.jsxs(q,{children:[e.jsx(ae,{children:"API Keys"}),e.jsx("div",{className:"usage-key-row",children:$.map(N=>e.jsxs("span",{className:V("usage-key-badge",N.isBackup?"is-backup":"is-active"),children:[e.jsx("span",{className:"usage-key-dot"}),N.keyEnvVar,N.isBackup?" (backup)":" (active)"," · ",N.requests," req"]},N.keyEnvVar))})]}),d.length>0&&e.jsxs(q,{children:[e.jsx(ae,{children:"Recent activity"}),e.jsx("div",{className:"usage-recent-list",children:d.map((N,A)=>e.jsxs("div",{className:V("usage-recent-item",N.error&&"is-err"),children:[e.jsx("span",{className:"usage-recent-time",children:new Date(N.ts).toLocaleTimeString()}),e.jsx("span",{className:"usage-recent-model",children:e.jsx("code",{children:N.modelId})}),e.jsxs("span",{className:"usage-recent-tokens",children:[N.totalTokens.toLocaleString()," tok"]}),e.jsxs("span",{className:"usage-recent-latency",children:[N.latencyMs,"ms"]}),e.jsx("span",{className:"usage-recent-endpoint",children:N.endpoint})]},`${N.requestId}-${A}`))})]})]})}function $s({label:s,value:t,sub:a,tone:i}){return e.jsxs("div",{className:"usage-kpi-card",children:[e.jsx("div",{className:"usage-kpi-label",children:s}),e.jsx("div",{className:V("usage-kpi-value",i&&`is-${i}`),children:t}),a&&e.jsx("div",{className:"usage-kpi-sub",children:a})]})}function Vs({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 Xo({model:s}){const t=Hs(s.current_interval_remaining_percent??0,0,100),a=Hs(s.current_weekly_remaining_percent??0,0,100),i=Hs(100-t,0,100),n=Hs(100-a,0,100);return e.jsxs(q,{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:V("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(ia,{icon:e.jsx($e,{size:12}),label:"5-hour rolling",remainingPct:t,consumedPct:i,used:s.current_interval_usage_count??0,total:s.current_interval_total_count??0,resetIn:s.intervalResetInHuman,resetISO:s.endTimeISO}),e.jsx(ia,{icon:e.jsx(qn,{size:12}),label:"Weekly",remainingPct:a,consumedPct:n,used:s.current_weekly_usage_count??0,total:s.current_weekly_total_count??0,resetIn:s.weeklyResetInHuman,resetISO:s.weeklyEndTimeISO})]})]})}function ia({icon:s,label:t,remainingPct:a,consumedPct:i,used:n,total:c,resetIn:o,resetISO:l}){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:["· ",i,"% used"]})]}),e.jsx("div",{className:"minimax-bar",children:e.jsx("div",{className:"minimax-bar-fill",style:{width:`${i}%`},"aria-label":`${i}% consumed`})}),e.jsxs("div",{className:"minimax-quota-meta",children:[e.jsxs("span",{children:[e.jsx("strong",{children:n})," / ",c||"—"," requests"]}),e.jsx("span",{title:l,children:o?`resets in ${o}`:"—"})]})]})}function Hs(s,t,a){return Math.max(t,Math.min(a,s))}function Qo(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 Jo({step:s,setStep:t,keyDraft:a,setKeyDraft:i,showKey:n,setShowKey:c,verifying:o,verifyResult:l,onVerify:u,onSkip:x,onManualKeySave:h,savingKey:d,status:m}){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(He,{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(T,{variant:"ghost",size:"sm",onClick:x,children:[e.jsx(be,{size:14})," Skip for now"]})})]}),e.jsx("div",{className:"minimax-wizard-stepper",children:["Welcome","Get a key","Paste & test","Done"].map((p,g)=>e.jsxs("div",{className:V("minimax-wizard-step",g===s&&"is-current",g<s&&"is-done",g>s&&"is-todo"),children:[e.jsx("div",{className:"minimax-wizard-step-bullet",children:g<s?e.jsx(Ve,{size:14}):g+1}),e.jsx("div",{className:"minimax-wizard-step-label",children:p})]},p))}),e.jsxs(q,{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/opencode/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(T,{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(ms,{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(T,{variant:"secondary",size:"md",onClick:()=>t(0),children:"← Back"}),e.jsxs(T,{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(Os,{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:n?"text":"password",value:a,onChange:p=>i(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:()=>c(p=>!p),className:"minimax-key-toggle","aria-label":n?"Hide key":"Show key",children:n?e.jsx(Js,{size:13}):e.jsx(Je,{size:13})})]})}),l&&!l.ok&&e.jsxs("div",{className:"minimax-wizard-error",children:[e.jsx(ke,{size:14}),e.jsxs("span",{children:[e.jsx("strong",{children:"Verification failed:"})," ",l.message??l.error]})]}),e.jsxs("div",{className:"minimax-wizard-actions",children:[e.jsx(T,{variant:"secondary",size:"md",onClick:()=>t(1),children:"← Back"}),e.jsxs(T,{variant:"primary",size:"md",onClick:u,disabled:o||!a.trim(),children:[o?e.jsx(xe,{size:14,className:"spin"}):e.jsx(Ps,{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(Ve,{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(T,{variant:"primary",size:"md",onClick:()=>window.location.reload(),children:"View your quota →"})})]}),e.jsxs("div",{className:"minimax-wizard-footer",children:[e.jsx(Ps,{size:11}),e.jsxs("span",{children:["Key written to ",e.jsx("code",{children:"~/.local/share/opencode/auth.json"})," with mode 0600."]})]})]})]})}const Zo=Le.memo(Ko),ec={pending:"info",running:"accent",done:"success",failed:"error",killed:"neutral",timed_out:"warning"},sc={pending:"Pending",running:"Running",done:"Done",failed:"Failed",killed:"Killed",timed_out:"Timed out"};function tc({status:s,dot:t}){const a=ec[s]||"neutral",i=sc[s]||s;return e.jsx(Ze,{kind:a,dot:t,children:i})}function ac({instanceId:s,instanceName:t,onConfirm:a,onClose:i}){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(T,{variant:"ghost",onClick:i,children:"Cancel"}),e.jsx(T,{variant:"danger",onClick:async()=>{await a(),i()},children:"Kill"})]})]})}function nc(s,t,a,i,n){s.open({title:"Kill instance?",width:400,children:e.jsx(ac,{instanceId:a,instanceName:i,onConfirm:async()=>{try{const o=await(await fetch(`/api/background/${encodeURIComponent(a)}`,{method:"DELETE"})).json();o.ok?(t.success(`Instance ${a} killed.`),n==null||n()):t.error(`Kill failed: ${o.error||"unknown error"}`)}catch(c){t.error(`Kill failed: ${c.message}`)}},onClose:()=>s.close()})})}function ic({instance:s}){const t=re(),[a,i]=r.useState(!1),n=s.tmuxSession,c=n?`tmux attach -t ${n}`:null,o=async()=>{if(c)try{await navigator.clipboard.writeText(c),t.success("Attach command copied")}catch{t.error("Could not copy to clipboard")}},l=async()=>{if(!(!s.instanceId||!n)){i(!0);try{const u=await R.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"),c)try{await navigator.clipboard.writeText(c),t.success("Command copied to clipboard")}catch{}}catch(u){if(t.error(`Failed: ${u.message}`),c)try{await navigator.clipboard.writeText(c),t.success("Command copied to clipboard")}catch{}}finally{i(!1)}}};return n?e.jsxs(q,{variant:"outlined",className:"bg-tmux-card",children:[e.jsxs("div",{className:"bg-tmux-card-header",children:[e.jsx(rs,{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:n}),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(T,{variant:"ghost",size:"sm",onClick:o,title:"Copy attach command",children:[e.jsx(ds,{size:14})," Copy"]}),e.jsxs(T,{variant:"primary",size:"sm",onClick:l,loading:a,title:"Open in system terminal",children:[e.jsx(rs,{size:14})," Open terminal"]})]})]}):e.jsxs(q,{variant:"outlined",className:"bg-tmux-card bg-tmux-card-warn",children:[e.jsxs("div",{className:"bg-tmux-card-header",children:[e.jsx(ke,{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 rc=5e3,lc=2e3,oc=120;function cc(s){return s.status==="pending"||s.status==="running"}function dc(s){if(!Number.isFinite(s)||s<0)return"—";const t=Math.floor(s/1e3),a=Math.floor(t/3600),i=Math.floor(t%3600/60),n=t%60;return a>0?`${a}h ${i}m ${n}s`:i>0?`${i}m ${n}s`:`${n}s`}function mc(s){const t=re(),a=Ae(),[i,n]=r.useState([]),[c,o]=r.useState(!0),[l,u]=r.useState(null),[,x]=r.useState(0),h=r.useCallback(async()=>{try{const j=await R.get("/background");n(Array.isArray(j==null?void 0:j.instances)?j.instances:[]),u(null)}catch(j){u((j==null?void 0:j.message)||"Failed to load background agents.")}finally{o(!1)}},[]);r.useEffect(()=>{h();const j=setInterval(h,rc);return()=>clearInterval(j)},[h]),r.useEffect(()=>{const j=setInterval(()=>x(v=>(v+1)%1e6),1e3);return()=>clearInterval(j)},[]),r.useEffect(()=>{const j=new Rt,v=j.on(k=>{const b=k.type;(b==="background:change"||b==="background:cleanup")&&h()});return()=>{v(),j.close()}},[h]);const d=i.filter(cc),m=j=>{hc(a,j)},p=async j=>{try{const v=await R.get(`/background/${encodeURIComponent(j.instanceId)}/tmux`);pc(a,v)}catch(v){t.error(`Tmux info failed: ${v.message}`)}},g=j=>{nc(a,t,j.instanceId,j.agent||j.prompt,()=>{n(v=>v.filter(k=>k.instanceId!==j.instanceId))})};return c?e.jsx("div",{className:"bg-active-view",children:e.jsxs("div",{className:"bg-active-loading",children:[e.jsx(me,{size:"md"}),e.jsx("span",{children:"Loading background agents…"})]})}):l?e.jsx("div",{className:"bg-active-view",children:e.jsx(ge,{icon:e.jsx($e,{size:32}),title:"Couldn't load background agents",message:l,action:e.jsxs(T,{variant:"primary",onClick:h,children:[e.jsx(le,{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:[d.length," active · ",i.length," total in store"]})]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:h,title:"Refresh now",children:[e.jsx(le,{size:14})," Refresh"]})]}),d.length===0?e.jsx(ge,{icon:e.jsx($e,{size:32}),title:"No active background agents",message:"Spawn one from the Agents tab or via the bizar_spawn_background tool."}):e.jsx("div",{className:"bg-active-list",children:d.map(j=>e.jsx(uc,{inst:j,onViewOutput:()=>m(j),onOpenTmux:()=>p(j),onKill:()=>g(j)},j.instanceId))})]})}function uc({inst:s,onViewOutput:t,onOpenTmux:a,onKill:i}){const n=typeof s.startedAt=="number"?s.startedAt:0,c=n?We(n):"—",o=n?Date.now()-n:0,l=ra(s.prompt,oc);return e.jsxs(q,{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(tc,{status:s.status||"pending",dot:!0})]}),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"})]})]}),l&&e.jsx("div",{className:"bg-active-prompt",children:l}),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})]}),typeof s.progress=="number"&&e.jsxs("div",{className:"progress-bar","aria-label":"Progress",children:[e.jsx("div",{className:"progress-fill",style:{width:`${Math.max(0,Math.min(100,s.progress))}%`}}),e.jsxs("span",{className:"progress-label",children:[Math.round(s.progress),"%"]})]}),e.jsxs("div",{className:"bg-active-meta",children:[e.jsxs("span",{title:c,children:[e.jsx("strong",{children:"Started:"})," ",c]}),e.jsxs("span",{children:[e.jsx("strong",{children:"Duration:"})," ",dc(o)]}),e.jsxs("span",{children:[e.jsx("strong",{children:"Tool calls:"})," ",s.toolCallCount??0]}),s.tmuxSession&&e.jsxs("span",{className:V(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(T,{variant:"secondary",size:"sm",onClick:t,children:[e.jsx(Je,{size:14})," View output"]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:a,children:[e.jsx(rs,{size:14})," Open in tmux"]}),e.jsxs(T,{variant:"danger",size:"sm",onClick:i,children:[e.jsx(Se,{size:14})," Kill"]})]}),e.jsx(ic,{instance:s})]})}function hc(s,t){s.open({title:`Output — ${t.agent||t.instanceId}`,width:720,children:e.jsx(xc,{instanceId:t.instanceId})})}function xc({instanceId:s}){const t=re(),[a,i]=r.useState(""),[n,c]=r.useState(!0),[o,l]=r.useState(null),[u,x]=r.useState(!0),h=r.useRef(null),d=r.useRef(!0),m=r.useCallback(async()=>{try{const j=await R.get(`/background/${encodeURIComponent(s)}/output?lines=200`);i((j==null?void 0:j.output)??""),x((j==null?void 0:j.available)!==!1),l(null)}catch(j){l((j==null?void 0:j.message)||"Failed to load output.")}finally{c(!1)}},[s]);r.useEffect(()=>{m();const j=setInterval(m,lc);return()=>clearInterval(j)},[m]),r.useEffect(()=>{var j;d.current&&((j=h.current)==null||j.scrollIntoView({behavior:"auto",block:"end"}))},[a]);const p=j=>{const v=j.currentTarget,k=v.scrollHeight-v.scrollTop-v.clientHeight<24;d.current=k},g=async()=>{try{await navigator.clipboard.writeText(a),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:u?`${a.length} chars · auto-refresh 2s`:"Output unavailable"}),e.jsxs("div",{className:"bg-output-toolbar-actions",children:[e.jsxs(T,{variant:"ghost",size:"sm",onClick:m,title:"Refresh now",children:[e.jsx(le,{size:14})," Refresh"]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:g,disabled:!a,children:[e.jsx(ds,{size:14})," Copy"]})]})]}),n&&!a?e.jsxs("div",{className:"bg-output-loading",children:[e.jsx(xe,{size:16,className:"spin"})," Loading…"]}):o?e.jsx("div",{className:"bg-output-error",children:o}):a?e.jsxs("div",{className:"bg-output-scroll",onScroll:p,children:[e.jsx("pre",{className:"bg-output-pre mono",children:e.jsx("code",{children:a})}),e.jsx("div",{ref:h})]}):e.jsx("div",{className:"bg-output-empty muted",children:"No output captured yet."})]})}function pc(s,t){const a=t.attachCommand||t.session||"";s.open({title:"Attach to tmux",width:520,children:e.jsx(gc,{info:t,cmd:a})})}function gc({info:s,cmd:t}){const[a,i]=r.useState(!1),n=async()=>{try{await navigator.clipboard.writeText(t),i(!0),window.setTimeout(()=>i(!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(T,{variant:"secondary",size:"sm",onClick:n,children:[e.jsx(ds,{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 fc={system:{title:"System health",icon:ys,emptyTitle:"No system checks",emptyMessage:"System checks did not return any rows."},services:{title:"Services",icon:nt,emptyTitle:"No service probes",emptyMessage:"Service probes did not return any rows."},counts:{title:"Counts",icon:$e,emptyTitle:"No counts",emptyMessage:"No counts reported by the dashboard stores."},errors:{title:"Recent errors",icon:js,emptyTitle:"No recent errors",emptyMessage:"No error lines in the service log within the last hour."},actions:{title:"Actions",icon:Kn,emptyTitle:"No actions",emptyMessage:"No actions available."}};function jc(s){return s==="ok"?Ve:s==="warn"?Gn:js}function vc(s){return s==="ok"?"ok":s==="warn"?"warn":"fail"}function yt({category:s,title:t,icon:a,checks:i,info:n,meta:c,children:o,className:l}){const u=fc[s],x=a??u.icon,h=t??u.title,d=i.length>0||n&&n.length>0||o;return e.jsxs(q,{className:V("doctor-panel",`doctor-panel-${s}`,l),children:[e.jsxs(ae,{children:[e.jsx(x,{size:14,"aria-hidden":!0}),e.jsx("span",{children:h}),c?e.jsx("span",{className:"card-meta-inline muted",children:c}):null]}),d?e.jsxs("div",{className:"doctor-panel-body",children:[o,i.length>0?e.jsx("ul",{className:"doctor-check-list",role:"list",children:i.map(m=>{const p=jc(m.status);return e.jsxs("li",{className:V("doctor-check-row",`doctor-check-${m.status}`),children:[e.jsx("span",{className:"doctor-check-icon","aria-hidden":!0,children:e.jsx(p,{size:14,className:V("doctor-check-icon-svg",m.status==="ok"&&"doctor-check-icon-ok",m.status==="warn"&&"doctor-check-icon-warn",m.status==="fail"&&"doctor-check-icon-fail")})}),e.jsx("span",{className:"doctor-check-name mono",children:m.name}),e.jsx("span",{className:"doctor-check-message",children:m.message}),e.jsx(Ze,{kind:m.status,dot:!0,children:vc(m.status)})]},m.name)})}):null,n&&n.length>0?e.jsx("dl",{className:"doctor-info-list",children:n.map(m=>e.jsxs(Le.Fragment,{children:[e.jsx("dt",{children:m.label}),e.jsx("dd",{className:"tabular-nums",children:m.value})]},m.label))}):null]}):e.jsx(ge,{icon:e.jsx(x,{size:28,"aria-hidden":!0}),title:u.emptyTitle,message:u.emptyMessage})]})}const yc=3e4;function bc({setActiveTab:s}){var z;const t=re(),[a,i]=r.useState(null),[n,c]=r.useState(!0),[o,l]=r.useState(!1),[u,x]=r.useState(null),[h,d]=r.useState(!0),m=r.useRef(!1),p=r.useCallback(async()=>{l(!0);try{const C=await R.get("/doctor");m.current||(i(C),x(Date.now()),c(!1))}catch(C){m.current||(c(!1),t.error(`Doctor refresh failed: ${C.message}`))}finally{m.current||l(!1)}},[t]);r.useEffect(()=>(m.current=!1,p(),()=>{m.current=!0}),[p]),r.useEffect(()=>{if(!h)return;const f=setInterval(async()=>{try{const P=await R.get("/doctor/health");i($=>$&&(($.health.status!==P.status||$.health.issues.length!==P.issues.length)&&p(),$))}catch{}},yc);return()=>clearInterval(f)},[h,p]);const g=async C=>{var f;try{const P=await R.post("/doctor/check",{checkName:C});t.info(`${P.name}: ${P.message}`,4e3),await p()}catch(P){const $=P;t.error(`Check failed: ${((f=$.data)==null?void 0:f.message)??P.message}`)}},j=()=>{if(a)try{const C=new Blob([JSON.stringify(a,null,2)],{type:"application/json"}),f=URL.createObjectURL(C),P=document.createElement("a");P.href=f,P.download=`doctor-snapshot-${new Date().toISOString().replace(/[:.]/g,"-")}.json`,document.body.appendChild(P),P.click(),document.body.removeChild(P),URL.revokeObjectURL(f)}catch(C){t.error(`Export failed: ${C.message}`)}},v=()=>{s("settings")},k=a==null?void 0:a.counts,b=r.useMemo(()=>k?[{label:"Tasks",value:k.tasks},{label:"Schedules",value:k.schedules},{label:"Mods",value:k.mods},{label:"Providers",value:k.providers},{label:"MCPs",value:k.mcps},{label:"Agents",value:k.agents},{label:"Projects",value:k.projects},{label:"Workspaces",value:k.workspaces},{label:"Voice notes",value:k.voiceNotes},{label:"Eval runs",value:k.evalRuns},{label:"Backups",value:k.backups}]:[],[k]);if(n)return e.jsxs("div",{className:"view view-doctor view-loading",children:[e.jsx(me,{size:"lg"}),e.jsx("p",{children:"Running health checks…"})]});if(!a)return e.jsx("div",{className:"view view-doctor",children:e.jsxs(q,{children:[e.jsxs(ae,{children:[e.jsx(js,{size:14})," Doctor unavailable"]}),e.jsx(ne,{children:"Could not reach /api/doctor."}),e.jsx("div",{className:"doctor-fallback-actions",children:e.jsxs(T,{variant:"primary",onClick:p,children:[e.jsx(le,{size:12})," Retry"]})})]})});const w=a.health.status,E=w==="ok"?Ve:w==="warn"?ke:js,y=w==="ok"?"Healthy":w==="warn"?"Warning":"Failed";return e.jsxs("div",{className:"view view-doctor","data-overall":w,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(da,{size:20,"aria-hidden":!0}),e.jsx("h1",{children:"Doctor"})]}),e.jsx("div",{className:"doctor-header-status",children:e.jsxs("span",{className:V("doctor-overall-pill",`doctor-overall-${w}`),children:[e.jsx(E,{size:14,"aria-hidden":!0}),e.jsx("span",{className:"doctor-overall-label",children:y}),e.jsxs(Ze,{kind:w,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(Is,{size:12,"aria-hidden":!0}),e.jsxs("span",{children:["v",a.bizarVersion," · ",a.platform,"/",a.arch," ·"," ","up ",Math.floor(a.uptime),"s",u?` · refreshed ${We(new Date(u))}`:""]})]})]}),e.jsxs("div",{className:"doctor-grid",children:[e.jsx(yt,{category:"system",checks:a.checks.system,meta:`${a.platform}/${a.arch}`}),e.jsx(yt,{category:"services",checks:a.checks.services,meta:(z=a.services.opencode)!=null&&z.reachable?`opencode on ${a.services.opencode.port??"?"}`:"opencode not connected"}),e.jsx(yt,{category:"counts",checks:[],info:b,meta:k!=null&&k.activeProject?`active: ${k.activeProject}`:"no active project"}),e.jsxs(q,{className:"doctor-errors-card",children:[e.jsxs(ae,{children:[e.jsx(js,{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((C,f)=>e.jsxs("li",{className:"doctor-error-row",children:[e.jsx("span",{className:"doctor-error-ts mono",children:C.ts?We(new Date(C.ts)):"??:??:??"}),e.jsx("span",{className:"doctor-error-line mono",children:C.line})]},`${C.tsMs??f}-${f}`))})]}),e.jsxs(q,{className:"doctor-actions-card",children:[e.jsxs(ae,{children:[e.jsx(kt,{size:14,"aria-hidden":!0})," Actions"]}),e.jsx(ne,{children:"Run a check, view logs, or export the snapshot."}),e.jsxs("div",{className:"doctor-actions-row",children:[e.jsxs(T,{variant:"primary",onClick:p,disabled:o,children:[o?e.jsx(me,{size:"sm"}):e.jsx(le,{size:12}),o?"Running…":"Run Health Check Now"]}),e.jsxs(T,{variant:"secondary",onClick:v,children:[e.jsx(we,{size:12})," View Full Logs"]}),e.jsxs(T,{variant:"secondary",onClick:j,children:[e.jsx(Ke,{size:12})," Export Diagnostics as JSON"]}),e.jsx(T,{variant:"ghost",onClick:()=>d(C=>!C),title:"Toggle auto-refresh",children:h?"Pause auto-refresh":"Resume auto-refresh"})]}),a.checks.services.some(C=>C.status!=="ok")||a.checks.config.some(C=>C.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(C=>C.status!=="ok").map(C=>e.jsxs(T,{variant:"ghost",size:"sm",onClick:()=>g(C.name),title:`Run check: ${C.name}`,children:[e.jsx(kt,{size:10})," ",C.name]},C.name))})]}):null]})]})]})}const Nc=Le.memo(bc);function kc(s){return s.total<=0?"fail":s.failed===0?"pass":s.passed/s.total>.8?"warn":"fail"}function Ba({run:s,onClick:t,selected:a,ariaLabel:i}){const n=kc(s),c=s.total>0?(s.passed/s.total*100).toFixed(1):"0.0",o=!!t;return e.jsxs(q,{onClick:t,interactive:o,"aria-label":i??`Eval run ${s.id}`,"aria-pressed":o?a:void 0,className:V("eval-run-card",a&&"eval-run-card-selected",`eval-run-${n}`),children:[e.jsxs("div",{className:"eval-run-head",children:[e.jsx(ae,{className:"eval-run-title",children:s.id}),e.jsxs("span",{className:V("eval-status",`is-${n}`),children:[s.passed,"/",s.total," (",c,"%)"]})]}),e.jsxs(ne,{className:"eval-run-meta",children:[We(s.startedAt)," · ",s.suitePath]})]})}const bt=8;function wc({setActiveTab:s}){const t=re(),[a,i]=r.useState([]),[n,c]=r.useState(!0),o=r.useRef(!1),l=r.useCallback(async()=>{c(!0);try{const d=await R.get(`/eval/runs?limit=${bt}`);o.current||i(d.runs||[])}catch(d){o.current||t.error(`Failed to load eval runs: ${d.message}`)}finally{o.current||c(!1)}},[t]);r.useEffect(()=>(o.current=!1,l(),()=>{o.current=!0}),[l]);const u=a.slice(0,bt),x=a.reduce((d,m)=>(d.total+=m.total,d.passed+=m.passed,d.failed+=m.failed,m.failed===0&&(d.fullPass+=1),d),{total:0,passed:0,failed:0,fullPass:0}),h=x.total>0?(x.passed/x.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(as,{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(T,{variant:"secondary",size:"sm",onClick:l,disabled:n,children:[n?e.jsx(me,{size:"sm"}):e.jsx(le,{size:12}),n?"Refreshing…":"Refresh"]}),e.jsxs(T,{variant:"primary",size:"sm",onClick:()=>s("evalReport"),title:"Open the full eval report",children:[e.jsx(ms,{size:12})," Open Eval Report"]})]})]}),e.jsxs("div",{className:"eval-summary-grid",children:[e.jsxs(q,{className:"eval-summary-card",children:[e.jsx(ae,{children:"Recent runs"}),e.jsx("div",{className:"eval-summary-value",children:a.length}),e.jsxs(ne,{className:"muted",children:["Latest ",bt," runs across all suites."]})]}),e.jsxs(q,{className:"eval-summary-card",children:[e.jsx(ae,{children:"Fixtures run"}),e.jsx("div",{className:"eval-summary-value",children:x.total}),e.jsx(ne,{className:"muted",children:e.jsxs("span",{className:V("eval-rate",x.failed===0?"is-pass":"is-fail"),children:[h,"% pass rate"]})})]}),e.jsxs(q,{className:"eval-summary-card",children:[e.jsx(ae,{children:"Clean runs"}),e.jsx("div",{className:"eval-summary-value",children:x.fullPass}),e.jsx(ne,{className:"muted",children:"Runs where every fixture passed."})]}),e.jsxs(q,{className:"eval-summary-card eval-summary-cta",children:[e.jsx(ae,{children:"Compare runs"}),e.jsx(ne,{children:"Open the detailed report to diff two runs side-by-side and spot regressions fixture by fixture."}),e.jsxs(T,{variant:"primary",size:"sm",onClick:()=>s("evalReport"),className:"eval-summary-cta-btn",children:["Open report ",e.jsx(Yn,{size:12})]})]})]}),e.jsxs("div",{className:"eval-recent-section",children:[e.jsx("h2",{className:"eval-section-title",children:"Recent runs"}),n&&u.length===0?e.jsxs("div",{className:"eval-runs-loading",children:[e.jsx(me,{size:"sm"}),e.jsx("span",{className:"muted",children:"Loading runs…"})]}):u.length===0?e.jsx(ge,{icon:e.jsx(as,{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:u.map(d=>e.jsx(Ba,{run:d},d.id))})]})]})}const Sc=Le.memo(wc);function Ua(s,t){const a=new Map(s.results.map(l=>[l.fixtureId,l])),i=new Map(t.results.map(l=>[l.fixtureId,l])),n=new Set([...a.keys(),...i.keys()]),c=[];for(const l of n){const u=a.get(l),x=i.get(l),h=u?u.ok:null,d=x?x.ok:null;let m;u&&x?h===d?m="same":h===!1&&d===!0?m="improved":m="regressed":x&&!u?m="added":m="removed",c.push({fixtureId:l,before:h,after:d,change:m})}const o={regressed:0,improved:1,added:2,removed:3,same:4};return c.sort((l,u)=>{const x=o[l.change]-o[u.change];return x!==0?x:l.fixtureId.localeCompare(u.fixtureId)}),c}function Cc({runA:s,runB:t,title:a="Regression Analysis"}){const i=Ua(s,t),n=i.filter(u=>u.change==="improved").length,c=i.filter(u=>u.change==="regressed").length,o=i.filter(u=>u.change==="same").length,l=i.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:"+"}),n," improved"]}),e.jsxs("span",{className:"eval-diff-stat regressed",children:[e.jsx("span",{className:"eval-diff-stat-icon","aria-hidden":!0,children:"−"}),c," regressed"]}),e.jsxs("span",{className:"eval-diff-stat unchanged muted",children:[o," unchanged"]})]}),l.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:l.map(u=>e.jsxs("li",{"data-fixture-id":u.fixtureId,className:V("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:V("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:V("eval-diff-state",u.after?"is-pass":"is-fail"),children:u.after===null?"—":u.after?"pass":"fail"})]})]},u.fixtureId))})]})}function zc({run:s,onClearCompare:t,compareRun:a,onClearSelection:i,runsForDiff:n}){const c=s.total>0?(s.passed/s.total*100).toFixed(1):"0.0",o=[...s.results].sort((l,u)=>l.ok!==u.ok?l.ok?1:-1:l.fixtureId.localeCompare(u.fixtureId));return e.jsxs("div",{className:"eval-run-detail","data-testid":"eval-run-detail",children:[e.jsxs(q,{className:"eval-run-detail-header",children:[e.jsxs("div",{className:"eval-run-detail-header-row",children:[e.jsxs(ae,{children:[e.jsx(as,{size:14,"aria-hidden":!0})," ",s.id]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:i,title:"Close detail",children:[e.jsx(be,{size:12})," Close"]})]}),e.jsxs(ne,{children:[We(s.startedAt),s.finishedAt?` → ${We(s.finishedAt)}`:""," · ",s.suitePath]}),e.jsxs("div",{className:"eval-run-detail-summary",children:[e.jsxs("span",{className:V("eval-status",s.failed===0?"is-pass":"is-fail"),children:[s.passed,"/",s.total," (",c,"%)"]}),e.jsxs("span",{className:"muted",children:[s.failed," failed · ",s.passed," passed"]})]})]}),a?e.jsx(q,{className:"eval-diff-card",children:(()=>{const l=n.find(d=>d.id===a);if(!l)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=Ua(l,s),x=u.filter(d=>d.change==="improved").length,h=u.filter(d=>d.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(za,{size:14,"aria-hidden":!0})," Comparing ",l.id," → ",s.id]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:t,children:[e.jsx(be,{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(Cc,{runA:l,runB:s})]})})()}):e.jsx(q,{className:"eval-baseline-hint",children:e.jsx(ne,{children:"Tip: click another run in the list to use it as a baseline for diffing."})}),e.jsxs(q,{className:"eval-fixtures-card",children:[e.jsxs(ae,{children:["Fixtures (",s.results.length,")"]}),o.length===0?e.jsx(ne,{className:"muted",children:"No fixture results in this run."}):e.jsx("ul",{className:"eval-fixtures-list",role:"list",children:o.map(l=>e.jsxs("li",{className:V("eval-fixture-row",l.ok?"is-pass":"is-fail"),children:[e.jsx("span",{className:V("eval-fixture-pill",l.ok?"is-pass":"is-fail"),"aria-label":l.ok?"pass":"fail",children:l.ok?"✓":"✗"}),e.jsx("span",{className:"eval-fixture-id mono",children:l.fixtureId}),!l.ok&&l.checks?e.jsx("span",{className:"eval-fixture-fails muted",children:l.checks.filter(u=>!u.ok).map(u=>u.message).filter(Boolean).join(" · ")}):null,l.latencyMs!=null?e.jsxs("span",{className:"eval-fixture-latency muted",children:[Math.round(l.latencyMs),"ms"]}):null]},l.fixtureId))})]})]})}function Rc({setActiveTab:s}){const t=re(),[a,i]=r.useState([]),[n,c]=r.useState(!0),[o,l]=r.useState(null),[u,x]=r.useState(null),[h,d]=r.useState(null),[m,p]=r.useState(!1),[g,j]=r.useState(null),v=r.useRef(!1),k=r.useCallback(async()=>{c(!0);try{const C=await R.get("/eval/runs");v.current||i(C.runs||[])}catch(C){v.current||t.error(`Failed to load eval runs: ${C.message}`)}finally{v.current||c(!1)}},[t]),b=r.useCallback(async C=>{p(!0);try{const f=await R.get(`/eval/runs/${encodeURIComponent(C)}`);v.current||d(f)}catch(f){v.current||(t.error(`Failed to load run ${C}: ${f.message}`),d(null))}finally{v.current||p(!1)}},[t]),w=r.useCallback(async C=>{try{const f=await R.get(`/eval/runs/${encodeURIComponent(C)}`);v.current||j(f)}catch(f){v.current||(t.error(`Failed to load run ${C}: ${f.message}`),j(null))}},[t]);r.useEffect(()=>(v.current=!1,k(),()=>{v.current=!0}),[k]);const E=async C=>{C!==o&&(l(C),x(null),j(null),await b(C))},y=async C=>{C!==o&&(x(C),await w(C))},z=[];return g&&z.push(g),h&&z.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(as,{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(T,{variant:"secondary",size:"sm",onClick:k,disabled:n,children:[n?e.jsx(me,{size:"sm"}):e.jsx(le,{size:12}),n?"Refreshing…":"Refresh"]})})]}),e.jsxs("div",{className:"eval-grid",children:[e.jsx("div",{className:"eval-runs-list",children:n&&a.length===0?e.jsxs("div",{className:"eval-runs-loading",children:[e.jsx(me,{size:"sm"}),e.jsx("span",{className:"muted",children:"Loading runs…"})]}):a.length===0?e.jsx(ge,{icon:e.jsx(as,{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(C=>e.jsxs("div",{className:"eval-run-card-wrap",children:[e.jsx(Ba,{run:C,selected:C.id===o,onClick:()=>E(C.id)}),o&&C.id!==o?e.jsxs("button",{type:"button",className:"eval-baseline-btn",onClick:()=>y(C.id),title:"Use this run as a baseline for diffing",children:[e.jsx(za,{size:10,"aria-hidden":!0}),"Use as baseline"]}):null]},C.id))}),e.jsx("div",{className:"eval-detail",children:m&&!h?e.jsxs("div",{className:"eval-detail-loading",children:[e.jsx(me,{size:"sm"}),e.jsx("span",{className:"muted",children:"Loading run details…"})]}):h?e.jsx(zc,{run:h,compareRun:u,runsForDiff:z,onClearCompare:()=>{x(null),j(null)},onClearSelection:()=>{l(null),d(null),x(null),j(null)}}):e.jsx(q,{className:"eval-detail-empty",children:e.jsx(ge,{icon:e.jsx(as,{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 Tc=Le.memo(Rc),Nt={overview:Wi,chat:rr,agents:mr,artifacts:Fr,memory:_o,tasks:Yr,activity:il,background:mc,config:Jt,settings:Jt,mods:Ul,schedules:io,skills:xo,history:Vo,minimax:Zo,plugins:Kl,doctor:Nc,eval:Sc,evalReport:Tc},$c="v4.5.0";function Ac(s,t,a,i){if(Nt[s]){const o=Nt[s];return e.jsx(o,{...t})}const n=a.find(o=>o.id===s);if(n)return e.jsx(Gl,{viewId:n.id,reloadKey:i,activeTab:t.activeTab,setActiveTab:t.setActiveTab});const c=Nt.overview;return e.jsx(c,{...t})}function Mc({onSaved:s}){const[t,a]=r.useState(""),i=r.useRef(null);r.useEffect(()=>{var o;(o=i.current)==null||o.focus()},[]);const n=()=>{const o=t.trim();o&&(R.setToken(o),s())},c=o=>{o.key==="Escape"&&(o.preventDefault(),s()),o.key==="Enter"&&(o.preventDefault(),n())};return e.jsxs("form",{className:"token-entry-form",onSubmit:o=>{o.preventDefault(),n()},children:[e.jsxs("div",{className:"token-entry-row",children:[e.jsx("input",{ref:i,type:"password",className:"input mono",value:t,onChange:o=>a(o.target.value),placeholder:"Paste auth token",spellCheck:!1,autoComplete:"off",onKeyDown:c}),e.jsx(T,{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 Ic(){return e.jsx(si,{children:e.jsx(ai,{children:e.jsx(Lc,{})})})}function Lc(){var K,J,oe;const s=re(),t=Ae(),{isModalOpen:a}=t,i=r.useRef(!1),[n,c]=r.useState("overview"),[o,l]=r.useState(null),[u,x]=r.useState(null),[h,d]=r.useState("connecting"),[m,p]=r.useState(null),[g,j]=r.useState(!1),[v,k]=r.useState(null),[b,w]=r.useState(!1),[E,y]=r.useState(!1),[z,C]=r.useState([]),[f,P]=r.useState(!1),[$,N]=r.useState([]),[A,O]=r.useState(0),S=r.useRef(null),[F,Y]=r.useState(null);r.useEffect(()=>{let _=!1;return(async()=>{try{const D=await R.get("/mods/views");if(_)return;N(D.views||[])}catch{_||N([])}})(),()=>{_=!0}},[A,o==null?void 0:o.mods]),r.useEffect(()=>{if(!F)return;const _=F.on(D=>{((D==null?void 0:D.type)==="mod:change"||(D==null?void 0:D.type)==="mod:enabled"||(D==null?void 0:D.type)==="mod:installed")&&O(se=>se+1)});return()=>_()},[F]),r.useEffect(()=>{u!=null&&u.theme&&(As(u.theme),fs(u.theme))},[u==null?void 0:u.theme]),r.useEffect(()=>{i.current=a},[a]),r.useEffect(()=>{var se;if(((se=u==null?void 0:u.theme)==null?void 0:se.mode)!=="system")return;const _=window.matchMedia("(prefers-color-scheme: light)"),D=()=>As(u.theme.mode);return _.addEventListener("change",D),()=>_.removeEventListener("change",D)},[(K=u==null?void 0:u.theme)==null?void 0:K.mode]);const L=r.useCallback(async()=>{let _=!1;const D=()=>Promise.all([R.get("/snapshot").catch(()=>null),R.get("/settings").catch(()=>null),R.get("/agents/stuck").catch(()=>null)]),se=(W,ce,G)=>{W&&l(W),ce!=null&&ce.data&&x(ce.data),G!=null&&G.stuck&&C(G.stuck)};try{const W=await R.probeAuthStatus(),[ce,G,de]=await D();if(se(ce,G,de),ce||G){p(null);return}if(!W.loopback){p("Dashboard server unreachable.");return}await new Promise(Ye=>setTimeout(Ye,1e3));const[Te,Ee,Ue]=await D();se(Te,Ee,Ue),!Te&&!Ee&&p("Dashboard server unreachable.")}catch(W){const ce=(W==null?void 0:W.message)??"unknown error";if(W instanceof Qa&&W.status===401){p(ce),w(!0),s.error(`Auth required: ${ce}`);return}p(ce),s.error(`Failed to load: ${ce}`)}},[s]);r.useEffect(()=>{let _=!1;const D=setTimeout(()=>{_||L()},0);return()=>{_=!0,clearTimeout(D)}},[L]),r.useEffect(()=>{let _=!1;return R.get("/settings").then(D=>{var W,ce;if(_)return;const se=(ce=(W=D==null?void 0:D.data)==null?void 0:W.ui)==null?void 0:ce.defaultTab;se&&c(se)}).catch(()=>{}),()=>{_=!0}},[]),r.useEffect(()=>{let _=!1;const D=async()=>{try{const W=await R.get("/agents/stuck");_||C(ce=>{const G=W.stuck||[];return ce.length===0&&G.length>0&&s.warning(`${G.length} agent${G.length===1?"":"s"} stuck`,5e3),G})}catch{}},se=setInterval(D,3e4);return D(),()=>{_=!0,clearInterval(se)}},[]),r.useEffect(()=>{const _=new Rt;S.current=_,Y(_);const D=_.onStatus(W=>d(W)),se=_.on(W=>{var ce;if(W.type==="snapshot"&&"data"in W&&W.data)l(G=>({...G??{},...W.data}));else if(W.type==="change"){const G=W,de=((ce=G.path)==null?void 0:ce.split("/").pop())||G.path||"";s.info(`File changed: ${de}`,2500)}else if(W.type==="tasks:change"){const G=W;l(de=>{if(!de)return de;const Te=(de.tasks||[]).map(Ue=>Ue.id===G.task.id?G.task:Ue),Ee=Te.some(Ue=>Ue.id===G.task.id);return{...de,tasks:Ee?Te:[G.task,...Te]}})}else if(W.type==="tasks:delete"){const G=W;l(de=>de&&{...de,tasks:(de.tasks||[]).filter(Te=>Te.id!==G.id)})}else if(W.type==="settings:change"){const G=W;G.settings&&x(G.settings)}else if(W.type==="project:change")R.get("/snapshot").then(G=>l(de=>({...de??{},...G}))).catch(()=>{});else if(W.type==="agents:change"||W.type==="schedules:change")R.get("/snapshot").then(G=>l(de=>({...de??{},...G}))).catch(()=>{});else if(W.type==="agent:status"||W.type==="agent:restarted"){const G=W;l(de=>{if(!de)return de;const Te=(de.agents||[]).map(Ee=>Ee.name===G.agent.name?G.agent:Ee);return{...de,agents:Te}})}else if(W.type==="artifact:change")R.get("/artifacts").then(G=>{l(de=>de&&{...de,artifacts:G.artifacts||[]})}).catch(()=>{});else if(W.type==="agent:stuck")C(W.agents||[]);else if(W.type==="dialog:show"){const G=W;G.dialog&&t.open({title:G.dialog.title,width:520,children:e.jsx($i,{dialog:G.dialog,onClose:()=>t.close()})})}});return()=>{D(),se(),_.close(),Y(null)}},[s]);const X=r.useCallback(_=>F?F.on(_):()=>{},[F]),ie=r.useRef(0);r.useEffect(()=>{const _=()=>{ie.current=Date.now()+1500};return document.addEventListener("mousedown",_,!0),document.addEventListener("click",_,!0),document.addEventListener("focusin",_,!0),document.addEventListener("keydown",_,!0),()=>{document.removeEventListener("mousedown",_,!0),document.removeEventListener("click",_,!0),document.removeEventListener("focusin",_,!0),document.removeEventListener("keydown",_,!0)}},[]),r.useEffect(()=>{const _={};wt.forEach((se,W)=>{_[String(W+1)]=se.id});const D=se=>{var Ye,Bs,ws,Us;if((se.metaKey||se.ctrlKey)&&se.key.toLowerCase()==="k"){se.preventDefault(),y(!0);return}if(se.key==="/"&&!se.metaKey&&!se.ctrlKey){const Ss=(Bs=(Ye=se.target)==null?void 0:Ye.tagName)==null?void 0:Bs.toLowerCase();if(Ss!=="input"&&Ss!=="textarea"&&!((ws=se.target)!=null&&ws.isContentEditable)){se.preventDefault(),y(!0);return}}const W=document.activeElement;if(!W||W===document.body||W===document.documentElement)return;const G=se.target,de=(Us=G==null?void 0:G.tagName)==null?void 0:Us.toLowerCase(),Te=de==="input"||de==="textarea"||de==="select"||de==="button"||de==="option"||de==="label"||!!(G!=null&&G.isContentEditable);let Ee=!1;if(G&&typeof G.closest=="function"&&(Ee=!!G.closest('form, [role="dialog"], [contenteditable], [data-no-key]')),se.repeat||i.current||Te||Ee||se.metaKey||se.ctrlKey||se.altKey||se.shiftKey||Date.now()<ie.current)return;const Ue=_[se.key];Ue&&(se.preventDefault(),B(Ue))};return document.addEventListener("keydown",D),()=>document.removeEventListener("keydown",D)},[]);const te=r.useMemo(()=>async()=>{try{const _=await R.get("/snapshot");l(D=>({...D??{},..._}))}catch(_){s.error(`Refresh failed: ${_.message}`)}},[s]),B=r.useCallback(_=>{c(_),j(_==="settings")},[]),H=r.useMemo(()=>{const _=$.map(D=>({id:D.id,label:D.label,icon:D.kind==="iframe"?bs:Fs,isMod:!0,modId:D.modId}));return[...wt,..._]},[$]),Q=r.useMemo(()=>o&&u?Ac(n,{snapshot:o,settings:u,activeTab:n,setActiveTab:B,refreshSnapshot:te,settingsMode:g,settingsActiveSection:v,setSettingsActiveSection:k},$,A):null,[n,o,u,$,A,te,g,v,k,B]),U=async()=>{try{const _=await R.get("/projects");l(D=>{var se;return D&&{...D,projects:_.projects||[],activeProject:((se=_.projects)==null?void 0:se.find(W=>W.id===_.active))||null}})}catch(_){s.error(`Projects refresh failed: ${_.message}`)}},Z=async _=>{try{await R.post(`/projects/${encodeURIComponent(_)}/activate`),l(D=>D&&{...D,activeProject:D.projects.find(se=>se.id===_)||null})}catch(D){s.error(`Activate failed: ${D.message}`)}},he=_=>{const D=_.type;if(D==="agent")B("agents");else if(D==="task")B("tasks");else if(D==="mod")B("mods");else if(D==="schedule")B("schedules");else if(D==="project"){const se=_.item.id;Z(se)}else if(D==="command")s.info(`/${_.item.name} — run from the TUI`,2500);else if(D==="setting"){const se=_.item.id||_.item.path||"";B("settings");const W=ce=>{if(ce<=0)return;const G=se?document.querySelector(`[data-setting-id="${CSS.escape(se)}"]`):null;G?(G.scrollIntoView({behavior:"smooth",block:"center"}),G.classList.remove("setting-flash"),G.offsetWidth,G.classList.add("setting-flash"),window.setTimeout(()=>G.classList.remove("setting-flash"),1500)):window.setTimeout(()=>W(ce-1),80)};window.setTimeout(()=>W(15),60)}},Ne=((J=u==null?void 0:u.ui)==null?void 0:J.layout)||"topnav",I=((oe=u==null?void 0:u.ui)==null?void 0:oe.showHeader)!==!1;return e.jsxs("div",{className:"app","data-layout":Ne,"data-active-tab":n,children:[e.jsx("a",{className:"skip-to-main",href:"#main-content",children:"Skip to main content"}),I&&e.jsx(hi,{activeTab:n,onTabChange:B,wsStatus:h,version:$c,activeProject:(o==null?void 0:o.activeProject)||null,projects:(o==null?void 0:o.projects)||[],onProjectChange:Z,onProjectsRefresh:U,onOpenSearch:()=>y(!0),settings:u,notificationsSlot:e.jsx(Ni,{wsSubscribe:X}),showTabs:Ne==="topnav",extraTabs:H}),z.length>0&&!f&&e.jsxs("div",{className:"stuck-banner",role:"alert",children:[e.jsx(ke,{size:16}),e.jsxs("span",{children:[e.jsx("strong",{children:z.length})," agent",z.length===1?"":"s"," stuck:"," ",e.jsx("span",{className:"mono",children:z.map(_=>_.name).join(", ")})]}),e.jsx(T,{variant:"secondary",size:"sm",onClick:()=>{B("agents"),P(!0)},children:"Review"}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Dismiss",onClick:()=>P(!0),children:e.jsx(be,{size:14})})]}),e.jsxs("div",{className:"layout-body",children:[Ne!=="topnav"&&e.jsx(ji,{tabs:H,activeTab:n,onTabChange:B,settingsMode:g,settingsActiveSection:v,onSettingsSectionChange:k,onExitSettings:()=>B("overview")}),e.jsxs("main",{className:"content",id:"main-content",tabIndex:-1,children:[m&&e.jsxs("div",{className:"boot-error",children:[e.jsx("h2",{children:"Dashboard unavailable"}),e.jsx("p",{children:m}),b&&e.jsx(Mc,{onSaved:()=>{w(!1),L()}}),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."]})]}),!m&&(!o||!u)&&e.jsxs("div",{className:"loading",children:[e.jsx(me,{size:"lg"}),e.jsx("p",{children:"Loading Bizar…"})]}),Q&&e.jsx(r.Suspense,{fallback:e.jsxs("div",{className:"loading",children:[e.jsx(me,{size:"lg"}),e.jsx("p",{children:"Loading…"})]}),children:e.jsx(Ec,{children:Q})})]})]}),e.jsx(vi,{open:E,onClose:()=>y(!1),onSelect:he})]})}class Ec extends r.Component{constructor(){super(...arguments);Cs(this,"state",{err:null});Cs(this,"reset",()=>this.setState({err:null}))}static getDerivedStateFromError(a){return{err:a}}componentDidCatch(a,i){console.error("[ViewErrorBoundary] caught render error:",a,i==null?void 0:i.componentStack)}render(){return this.state.err?e.jsxs("div",{className:"view-error-fallback",role:"alert",children:[e.jsx(ke,{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(T,{variant:"secondary",size:"sm",onClick:this.reset,children:"Retry"})]})]}):this.props.children}}function Dc(){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)"),i=n=>t(n.matches);return a.addEventListener("change",i),()=>a.removeEventListener("change",i)},[]),s?e.jsx(Ja,{}):e.jsx(Ic,{})}const _a=document.getElementById("root");if(!_a)throw new Error("Root element #root not found");Za(_a).render(e.jsx(r.StrictMode,{children:e.jsx(Dc,{})}));
|