@polderlabs/bizar 5.5.0 → 5.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bizar-dash/dist/assets/{EnvVarsSection-L413CQEI.js → EnvVarsSection-DoIzqrlb.js} +3 -3
- package/bizar-dash/dist/assets/{EnvVarsSection-L413CQEI.js.map → EnvVarsSection-DoIzqrlb.js.map} +1 -1
- package/bizar-dash/dist/assets/{MobileChat-0kGQb1S6.js → MobileChat-CoUCUsbr.js} +1 -1
- package/bizar-dash/dist/assets/{MobileChat-0kGQb1S6.js.map → MobileChat-CoUCUsbr.js.map} +1 -1
- package/bizar-dash/dist/assets/MobileSettings-BeO04g52.js +1 -0
- package/bizar-dash/dist/assets/MobileSettings-BeO04g52.js.map +1 -0
- package/bizar-dash/dist/assets/{Toast-C6f1zFJ2.js → Toast-D9nv5N6m.js} +1 -1
- package/bizar-dash/dist/assets/{Toast-C6f1zFJ2.js.map → Toast-D9nv5N6m.js.map} +1 -1
- package/bizar-dash/dist/assets/{icons-BsWXWkEF.js → icons-Btipv2pp.js} +100 -90
- package/bizar-dash/dist/assets/icons-Btipv2pp.js.map +1 -0
- package/bizar-dash/dist/assets/main-DHXPuddY.js +18 -0
- package/bizar-dash/dist/assets/main-DHXPuddY.js.map +1 -0
- package/bizar-dash/dist/assets/{main-BklYy02e.css → main-UG4jKK-F.css} +1 -1
- package/bizar-dash/dist/assets/mobile-H5KH9cTL.js +1 -0
- package/bizar-dash/dist/assets/{mobile-CsaN4CxH.js.map → mobile-H5KH9cTL.js.map} +1 -1
- package/bizar-dash/dist/assets/{mobile-layout-iFBdjEE4.js → mobile-layout-BqHxVb6_.js} +2 -2
- package/bizar-dash/dist/assets/{mobile-layout-iFBdjEE4.js.map → mobile-layout-BqHxVb6_.js.map} +1 -1
- package/bizar-dash/dist/assets/{useSlashCommands-DGJcC9iQ.js → useSlashCommands-C24-O1e7.js} +2 -2
- package/bizar-dash/dist/assets/{useSlashCommands-DGJcC9iQ.js.map → useSlashCommands-C24-O1e7.js.map} +1 -1
- package/bizar-dash/dist/index.html +7 -7
- 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/bg-spawner.mjs +522 -305
- package/bizar-dash/src/server/headroom.mjs +3 -1
- package/bizar-dash/src/server/memory-lightrag.mjs +26 -2
- package/bizar-dash/src/server/memory-store.mjs +74 -28
- package/bizar-dash/src/server/opencode-sdk.mjs +63 -3
- package/bizar-dash/src/server/plugins/registry.mjs +1 -1
- package/bizar-dash/src/server/routes/activity.mjs +85 -0
- package/bizar-dash/src/server/routes/background.mjs +31 -13
- package/bizar-dash/src/server/routes/memory.mjs +91 -38
- package/bizar-dash/src/server/routes/opencode-session-detail.mjs +1 -1
- package/bizar-dash/src/server/server.mjs +4 -1
- package/bizar-dash/src/web/components/Sidebar.tsx +0 -1
- package/bizar-dash/src/web/styles/main.css +52 -13
- package/bizar-dash/src/web/styles/memory.css +17 -0
- package/bizar-dash/src/web/styles/settings.css +6 -56
- package/bizar-dash/src/web/views/Marketplace.tsx +192 -31
- package/bizar-dash/src/web/views/memory/ConfigPanel.tsx +157 -7
- package/bizar-dash/src/web/views/memory/MemoryOverview.tsx +11 -0
- package/bizar-dash/src/web/views/settings/MemorySection.tsx +65 -11
- package/bizar-dash/tests/background-sdk-session.test.mjs +94 -0
- package/bizar-dash/tests/background-session-events.test.mjs +74 -0
- package/bizar-dash/tests/background-steer-sdk.test.mjs +71 -0
- package/bizar-dash/tests/background-steer.test.mjs +25 -7
- package/bizar-dash/tests/memory-namespace.test.mjs +2 -2
- package/bizar-dash/tests/memory-status-root.test.mjs +144 -0
- package/bizar-dash/tests/memory-store.test.mjs +5 -4
- package/bizar-dash/tests/memory-vault-config-endpoint.test.mjs +173 -0
- package/bizar-dash/tests/settings-mode-wiring.test.tsx +1 -1
- package/bizar-dash/tests/settings-nav.test.tsx +0 -1
- package/bizar-dash/tests/views/Marketplace.test.tsx +200 -0
- package/bizar-dash/tests/views/Memory.test.tsx +274 -0
- package/bizar-dash/tests/views/sidebar.test.tsx +116 -0
- package/bizar-dash/tests/views/topbar.test.tsx +87 -0
- package/cli/commands/marketplace.mjs +1 -1
- package/cli/memory.mjs +1 -1
- package/package.json +1 -1
- package/plugins/bizar/src/background-state.ts +11 -0
- package/plugins/bizar/src/background.ts +212 -34
- package/plugins/bizar/src/opencode-runner.ts +80 -353
- package/plugins/bizar/src/tools/bg-send-message.ts +160 -61
- package/plugins/bizar/src/tools/bg-spawn.ts +235 -156
- package/plugins/bizar/tests/tools/bg-send-message.test.ts +84 -11
- package/plugins/bizar/tests/tools/bg-spawn-http.test.ts +223 -0
- package/bizar-dash/dist/assets/MobileSettings-Cq1oFIdO.js +0 -1
- package/bizar-dash/dist/assets/MobileSettings-Cq1oFIdO.js.map +0 -1
- package/bizar-dash/dist/assets/icons-BsWXWkEF.js.map +0 -1
- package/bizar-dash/dist/assets/main-CBTgYSeG.js +0 -18
- package/bizar-dash/dist/assets/main-CBTgYSeG.js.map +0 -1
- package/bizar-dash/dist/assets/mobile-CsaN4CxH.js +0 -1
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
var _a=Object.defineProperty;var Wa=(s,t,a)=>t in s?_a(s,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):s[t]=a;var ws=(s,t,a)=>Wa(s,typeof t!="symbol"?t+"":t,a);import{a as T,c as V,f as Te,b as _e,S as oe,t as ia,e as qa,p as Va,d as xs,g as Rs,_ as Ha,W as Hs,A as Ga,M as Ka}from"./mobile-layout-iFBdjEE4.js";import{r,j as e,a as ra,R as Fe,b as Ya}from"./react-vendor-Dn4wqh4Z.js";import{X as Ne,A as wt,R as de,F as Xa,H as Qa,a as Ja,C as la,b as Pe,c as Za,d as We,e as Ye,L as oa,M as Js,B as Ke,f as Gs,S as $s,g as De,h as en,i as Xe,j as Ue,P as as,k as Ks,l as ns,m as As,n as St,o as Je,p as ca,q as Ct,r as ye,s as sn,t as be,u as da,v as _t,T as is,w as _s,G as tn,x as an,y as gs,z as ze,D as qe,I as zt,E as ys,J as ke,K as rs,N as Ys,O as Ze,Q as fs,U as ft,V as nn,W as we,Y as Tt,Z as Rt,_ as ps,$ as rn,a0 as Zs,a1 as js,a2 as ln,a3 as Ls,a4 as ls,a5 as ma,a6 as ua,a7 as Ms,a8 as on,a9 as bs,aa as cn,ab as dn,ac as mn,ad as et,ae as un,af as hn,ag as xn,ah as pn,ai as gn,aj as fn,ak as Wt,al as ha,am as jn,an as $t,ao as vn,ap as yn,aq as At,ar as bn,as as Nn,at as kn,au as wn,av as Sn,aw as Cn,ax as zn,ay as jt,az as Mt,aA as It,aB as os,aC as xa,aD as vs,aE as Tn,aF as Rn,aG as Xs,aH as $n,aI as pa,aJ as Is,aK as An,aL as Mn,aM as ga,aN as Es,aO as vt,aP as Et,aQ as fa,aR as xe,aS as In,aT as En,aU as ja,aV as Ln,aW as Dn,aX as Pn,aY as va,aZ as tt,a_ as ya,a$ as Lt,b0 as Fn,b1 as On,b2 as Bn,b3 as ba,b4 as Un,b5 as _n,b6 as Wn,b7 as qn,b8 as Vn,b9 as Na}from"./icons-BsWXWkEF.js";import{B as $,C as G,a as te,b as ne,A as Hn,U as Gn,G as Kn,E as Yn,T as Xn,S as Qn,H as Jn,c as Zn}from"./EnvVarsSection-L413CQEI.js";import{u as re,T as ei}from"./Toast-C6f1zFJ2.js";import{V as Dt,C as si,u as ti,a as ai,b as ni,c as ii}from"./useSlashCommands-DGJcC9iQ.js";import{M as ka,r as wa}from"./markdown-C6mXtQxD.js";import"./vendor-CeHGtduv.js";const Sa=r.createContext(null),ri=["button:not([disabled])","[href]","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(", ");function Re(){const s=r.useContext(Sa);return s||{open:()=>"",close:()=>{},isModalOpen:!1}}function li({children:s}){const[t,a]=r.useState([]),i=r.useCallback(c=>{a(o=>{if(!c)return o.slice(0,-1);const l=o.findIndex(h=>h.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(Sa.Provider,{value:{open:n,close:i,isModalOpen:t.length>0},children:[s,typeof document<"u"&&ra.createPortal(e.jsx("div",{className:"modal-stack","aria-hidden":t.length===0,children:t.map((c,o)=>e.jsx(oi,{modal:c,onClose:()=>{var l;(l=c.onClose)==null||l.call(c),i(c.id)},depth:o},c.id))}),document.body)]})}function oi({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(ri)).filter(h=>!h.hasAttribute("disabled")&&h.tabIndex!==-1):[]};return r.useEffect(()=>{var p;n.current=document.activeElement instanceof HTMLElement?document.activeElement:null,(p=o()[0]??i.current)==null||p.focus();const h=u=>{var b,z,k;if(u.key!=="Tab")return;const d=o();if(d.length===0){u.preventDefault(),(b=i.current)==null||b.focus();return}const m=d[0],x=d[d.length-1],g=document.activeElement instanceof HTMLElement?document.activeElement:null;if(u.shiftKey){(!g||g===m||!((z=i.current)!=null&&z.contains(g)))&&(u.preventDefault(),x.focus());return}(!g||g===x||!((k=i.current)!=null&&k.contains(g)))&&(u.preventDefault(),m.focus())};return document.addEventListener("keydown",h),()=>{document.removeEventListener("keydown",h);const u=n.current;u&&u.isConnected&&u.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(Ne,{size:16})})]}),e.jsx("div",{className:"modal-body",children:s.children}),s.footer&&e.jsx("footer",{className:"modal-footer",children:s.footer})]})})}const ci=200,di=5*60*1e3,ts=new Map;function mi(s){const t=ts.get(s);return t?Date.now()-t.ts>di?(ts.delete(s),null):t.data:null}function at(s,t){ts.size>=ci&&[...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 ui(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 hi(s){return[...s].sort((t,a)=>t.isDir!==a.isDir?t.isDir?-1:1:t.name.localeCompare(a.name,void 0,{sensitivity:"base"}))}function xi(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 Ca({value:s,onChange:t,initialPath:a,projectsDirectory:i,rootLabel:n="Home",height:c=360}){const[o,l]=r.useState(a??i??""),[h,p]=r.useState(new Set),[u,d]=r.useState(-1),[m,x]=r.useState(null),[g,b]=r.useState({}),[z,k]=r.useState(!1),[w,S]=r.useState(null),[A,f]=r.useState(!1),[N,v]=r.useState(""),[j,E]=r.useState(null),[R,y]=r.useState(!1),M=r.useRef(null),P=r.useCallback(async L=>{try{const J=mi(L);if(J)return J;const U=await T.get("/fs?path="+encodeURIComponent(L));return at(L,U),U}catch{return null}},[]),C=r.useCallback(async L=>{var J;k(!0),S(null);try{const U=await T.get("/fs?path="+encodeURIComponent(L));at(L,U),x(U),d(-1)}catch(U){const le=((J=U.data)==null?void 0:J.message)??U.message??"Failed to load directory";S(le)}finally{k(!1)}},[]);r.useEffect(()=>{o?C(o):T.get("/fs").then(L=>{at("",L),x(L),l(L.path),L.path!==s&&t(L.path)}).catch(()=>{S("Could not determine home directory."),k(!1)})},[o]),r.useEffect(()=>{s&&s!==o&&l(s)},[s]);const D=m?hi(m.entries):[],Y=D.filter(L=>L.isDir),O=D,Q=L=>{L.isDir&&(l(L.path),t(L.path))},ae=()=>{m!=null&&m.parent&&(l(m.parent),t(m.parent))},ee=L=>{L!==o&&(l(L),t(L))},F=async()=>{const L=await P("");L&&(l(L.path),t(L.path))},H=async()=>{if(!i)return;const L=await P(i);L&&(l(L.path),t(L.path))},K=()=>{f(!0),v(""),E(null),setTimeout(()=>{var L;return(L=M.current)==null?void 0:L.focus()},0)},B=()=>{f(!1),v(""),E(null)},Z=async()=>{var J;const L=xi(N);if(!L.ok){E(L.reason);return}y(!0),E(null);try{const U=await T.post("/fs/mkdir",{parent:o,name:N.trim()});ts.delete(o),await C(o),t(U.path),f(!1),v("")}catch(U){const le=U;le.status===409?E(`A folder named "${N.trim()}" already exists.`):E(((J=le.data)==null?void 0:J.message)??U.message??"Failed to create folder.")}finally{y(!1)}},he=L=>{L.key==="Enter"?(L.preventDefault(),Z()):L.key==="Escape"&&(L.preventDefault(),B())},Se=L=>{p(J=>{const U=new Set(J);return U.has(L)?U.delete(L):U.add(L),U}),g[L]||P(L).then(J=>{J&&b(U=>({...U,[L]:J.entries.filter(le=>le.isDir)}))})},W=L=>{if(!m)return;const J=O.filter(q=>q.isDir),U=O.filter(q=>!q.isDir),le=[...J,...U];if(L.key==="ArrowDown")L.preventDefault(),d(q=>Math.min(q+1,le.length-1));else if(L.key==="ArrowUp")L.preventDefault(),d(q=>Math.max(q-1,0));else if(L.key==="Enter"||L.key===" "){L.preventDefault();const q=le[u];q&&(L.key==="Enter"&&q.isDir?Q(q):q.isDir&&t(q.path))}else L.key==="Backspace"&&(L.preventDefault(),ae())},se=ui((m==null?void 0:m.path)??o??"/"),ie=m==null?void 0:m.parent,me=ie!=null,_=o.split("/").filter(Boolean).at(-1)??"/";return e.jsxs("div",{className:"file-browser",onKeyDown:W,tabIndex:-1,children:[e.jsx("div",{className:"file-browser-breadcrumb",role:"navigation","aria-label":"Path breadcrumb",children:se.map((L,J)=>e.jsxs("span",{className:"file-browser-breadcrumb-item",children:[J>0&&e.jsx("span",{className:"file-browser-breadcrumb-sep","aria-hidden":!0,children:"/"}),e.jsx("button",{type:"button",className:"file-browser-breadcrumb-btn",onClick:()=>ee(L.path),title:L.path,children:J===0?L.path==="/"?"/":n:L.label})]},L.path))}),e.jsxs("div",{className:"file-browser-toolbar",children:[e.jsxs("div",{className:"file-browser-toolbar-left",children:[e.jsx("button",{type:"button",className:"file-browser-tool-btn",onClick:ae,disabled:!me,title:"Go up (Backspace)","aria-label":"Go up one level",children:e.jsx(wt,{size:13})}),e.jsx("button",{type:"button",className:"file-browser-tool-btn",onClick:()=>C(o),disabled:z,title:"Refresh","aria-label":"Refresh",children:e.jsx(de,{size:13,className:z?"spin":""})}),e.jsx("button",{type:"button",className:"file-browser-tool-btn",onClick:K,title:"New folder","aria-label":"Create new folder",children:e.jsx(Xa,{size:13})}),e.jsxs("div",{className:"file-browser-chips",children:[e.jsxs("button",{type:"button",className:"file-browser-chip",onClick:F,children:[e.jsx(Qa,{size:11})," ",n]}),i&&e.jsxs("button",{type:"button",className:"file-browser-chip",onClick:H,title:i,children:[e.jsx(Ja,{size:11})," ",i.split("/").filter(Boolean).at(-1)??"Projects"]})]})]}),A?e.jsxs("div",{className:"file-browser-mkdir",children:[e.jsx("input",{ref:M,type:"text",className:"file-browser-mkdir-input",placeholder:"Folder name",value:N,onChange:L=>{v(L.target.value),E(null)},onKeyDown:he,"aria-label":"New folder name","aria-invalid":j?"true":void 0,"aria-describedby":j?"mkdir-error":void 0,disabled:R,maxLength:255}),j?e.jsx("span",{id:"mkdir-error",className:"file-browser-mkdir-error",role:"alert",children:j}):e.jsx("span",{className:"file-browser-mkdir-hint",children:"Enter to create, Esc to cancel"})]}):e.jsx("span",{className:"file-browser-count-hint",children:z?"…":`${D.length} in ${_}`})]}),w&&e.jsxs("div",{className:"file-browser-error",children:[e.jsx(la,{size:13}),e.jsx("span",{children:w}),e.jsx("button",{type:"button",className:"file-browser-retry",onClick:()=>C(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:z&&!m?e.jsx(pi,{}):e.jsx(za,{path:o,entries:Y,expanded:h,childrenMap:g,onToggle:Se,onNavigate:Q,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"})]}),z&&!m?e.jsx(gi,{}):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."]}),O.length===0?e.jsx("div",{className:"file-browser-empty",children:"This folder is empty"}):e.jsx("div",{className:"file-browser-flat-list",children:O.map((L,J)=>{const U=L.isDir,le=J===u,q=L.path===s;return e.jsxs("div",{role:"option","aria-selected":q,className:["file-browser-row",U?"file-browser-row--dir":"file-browser-row--file",le&&"file-browser-row--selected",q&&U&&"file-browser-row--active",!U&&"file-browser-row--disabled"].filter(Boolean).join(" "),onClick:()=>{U&&(d(J),t(L.path))},onDoubleClick:()=>{U&&Q(L)},title:L.path,children:[e.jsx("span",{className:"file-browser-row-icon",children:U?e.jsx(Pe,{size:13}):e.jsx(Za,{size:13})}),e.jsx("span",{className:"file-browser-row-name",children:L.name}),e.jsx("span",{className:"file-browser-row-type",children:U?"Folder":""})]},L.path)})})]})]})]}),e.jsxs("div",{className:"file-browser-footer-hint",children:["Select a folder, then click Add. Use ",e.jsx("kbd",{children:"↑"})," ",e.jsx("kbd",{children:"↓"})," to navigate, ",e.jsx("kbd",{children:"Enter"})," to confirm."]})]})}function za({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 h=a.has(l.path),p=i[l.path]??[];return e.jsxs("li",{className:"file-browser-tree-node",children:[e.jsxs("div",{className:["file-browser-tree-row",h&&"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:u=>{u.stopPropagation(),n(l.path)},"aria-label":h?"Collapse":"Expand",children:(p.length>0,h?e.jsx(We,{size:11}):e.jsx(Ye,{size:11}))}),e.jsxs("button",{type:"button",className:"file-browser-tree-name",onClick:()=>c(l),title:l.path,children:[e.jsx(Pe,{size:12}),e.jsx("span",{children:l.name})]})]}),h&&p.length>0&&e.jsx(za,{path:l.path,entries:p,expanded:a,childrenMap:i,onToggle:n,onNavigate:c,level:o+1})]},l.path)})})}function pi(){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 gi(){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 yt=[{id:"overview",label:"Overview",icon:oa},{id:"chat",label:"Chat",icon:Js},{id:"agents",label:"Agents",icon:Ke},{id:"artifacts",label:"Glyphs",icon:Gs},{id:"tasks",label:"Tasks",icon:$s},{id:"activity",label:"Activity",icon:De},{id:"background",label:"Active",icon:en},{id:"skills",label:"Skills",icon:Xe},{id:"memory",label:"Memory",icon:Ue},{id:"mods",label:"Mods",icon:as},{id:"marketplace",label:"Marketplace",icon:Ks},{id:"schedules",label:"Schedules",icon:ns},{id:"plugins",label:"Plugins",icon:as},{id:"history",label:"History",icon:As},{id:"minimax",label:"Usage",icon:St},{id:"eval",label:"Eval",icon:Je},{id:"doctor",label:"Doctor",icon:ca},{id:"settings",label:"Settings",icon:Ct}];function fi({activeTab:s,onTabChange:t,wsStatus:a,version:i,activeProject:n,projects:c,onProjectChange:o,onProjectsRefresh:l,onOpenSearch:h,settings:p,rightSlot:u,notificationsSlot:d,showTabs:m=!0,extraTabs:x}){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(ji,{activeProject:n,projects:c,onChange:o,onRefresh:l,settings:p??null}),e.jsxs("button",{type:"button",className:"topbar-search",onClick:h,title:"Search (Ctrl/Cmd+K)","aria-label":"Open search",children:[e.jsx(ye,{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,u,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:[yt.map(g=>{const b=g.icon,z=g.id===s;return e.jsxs("button",{type:"button",role:"tab","aria-selected":z,className:V("tab",z&&"tab-active"),onClick:()=>t(g.id),title:g.label,children:[e.jsx(b,{size:14,className:"tab-icon"}),e.jsx("span",{className:"tab-label",children:g.label}),g.id==="settings"&&z&&e.jsx("span",{className:"settings-mode-indicator",title:"Settings mode active",children:e.jsx(sn,{size:12})})]},g.id)}),x&&x.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"tab-separator","aria-hidden":"true"}),x.map(g=>{const b=g.icon,z=g.id===s;return e.jsxs("button",{type:"button",role:"tab","aria-selected":z,className:V("tab","tab-mod",z&&"tab-active"),onClick:()=>t(g.id),title:`${g.label} (mod)`,children:[e.jsx(b,{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 ji({activeProject:s,projects:t,onChange:a,onRefresh:i,settings:n}){const[c,o]=r.useState(!1),l=Re();r.useEffect(()=>{if(!c)return;const p=()=>o(!1);return document.addEventListener("click",p),()=>document.removeEventListener("click",p)},[c]);const h=()=>{l.open({title:"Add project",children:e.jsx(vi,{settings:n,onAdd:async(p,u)=>{try{await T.post("/projects",{path:p,name:u}),i(),o(!1),l.close()}catch(d){alert(`Add failed: ${d.message}`)}}}),footer:e.jsx("div",{className:"modal-footer-actions",children:e.jsx($,{variant:"ghost",onClick:()=>l.close(),children:"Cancel"})})})};return e.jsxs("div",{className:"project-selector",onClick:p=>p.stopPropagation(),children:[e.jsxs("button",{type:"button",className:"project-selector-btn",onClick:()=>o(p=>!p),title:"Switch active project","aria-haspopup":"menu","aria-expanded":c,children:[e.jsx(Pe,{size:14}),e.jsx("span",{className:"project-selector-name",children:(s==null?void 0:s.name)||"(no project)"}),e.jsx(We,{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(de,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn",onClick:h,title:"Add project","aria-label":"Add project",children:e.jsx(be,{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(p=>e.jsx("li",{children:e.jsxs("button",{type:"button",className:V("project-selector-item",(s==null?void 0:s.id)===p.id&&"active"),onClick:()=>{a(p.id),o(!1)},children:[e.jsx("span",{className:"project-selector-item-name",children:p.name}),e.jsx("span",{className:"project-selector-item-status",children:p.status})]})},p.id))]})]})]})}function vi({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),[h,p]=r.useState(null),u=async()=>{var x;if(a){l(!0),p(null);try{await T.get("/fs?path="+encodeURIComponent(a)),t(a,n||null)}catch(g){const b=g;b.status===404?p("That folder no longer exists. Pick another."):p(((x=b.data)==null?void 0:x.message)??g.message??"Validation failed.")}finally{l(!1)}}};return e.jsxs("div",{children:[e.jsx("label",{className:"field-label",children:"Folder"}),e.jsx(Ca,{value:a,onChange:x=>{i(x),p(null)},projectsDirectory:(m=s==null?void 0:s.dashboard)==null?void 0:m.projectsDirectory,height:320}),h&&e.jsx("p",{className:"field-help",style:{color:"var(--error)",marginTop:4},children:h}),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:x=>c(x.target.value)})]}),e.jsx("div",{style:{marginTop:"var(--space-3)",display:"flex",justifyContent:"flex-end"},children:e.jsxs($,{variant:"primary",onClick:u,disabled:!a||o,children:[o?e.jsx("span",{className:"btn-spinner"}):null,o?"Checking…":"Add"]})})]})}const yi=[{label:"General",sections:[{id:"theme",label:"Theme",icon:da},{id:"layout",label:"Layout",icon:_t},{id:"general",label:"General",icon:_t}]},{label:"Core",sections:[{id:"env-vars",label:"Env Vars",icon:is},{id:"system-llm",label:"System LLM",icon:_s}]},{label:"Experience",sections:[{id:"updates",label:"Updates",icon:de},{id:"headroom",label:"Headroom",icon:tn}]}];function bi({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(wt,{size:14}),e.jsx("span",{children:"Back"})]}),e.jsx("div",{className:"settings-nav-divider","aria-hidden":"true"}),yi.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(Ye,{size:12,className:"settings-nav-item-chevron","aria-hidden":!0})]},n.id)})]},i.label))]})}function Ni({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(bi,{activeSection:n??null,onSectionChange:c??(()=>{}),onExitSettings:o??(()=>{})})});const l=s.filter(p=>!p.isMod),h=s.filter(p=>p.isMod);return e.jsx("aside",{className:"sidebar","aria-label":"Primary navigation",children:e.jsxs("nav",{className:"sidebar-nav",role:"tablist",children:[l.map(p=>{const u=p.icon,d=p.id===t;return e.jsxs("button",{type:"button",role:"tab","aria-selected":d,className:V("sidebar-tab",d&&"sidebar-tab-active"),onClick:()=>a(p.id),title:p.label,children:[e.jsx(u,{size:18,"aria-hidden":!0}),e.jsx("span",{className:"sidebar-tab-label",children:p.label})]},p.id)}),h.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"}),h.map(p=>{const u=p.icon,d=p.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(p.id),title:`${p.label} (mod)`,children:[e.jsx(u,{size:18,"aria-hidden":!0}),e.jsx("span",{className:"sidebar-tab-label",children:p.label})]},p.id)})]})]})})}const nt=[{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"}],qt={all:null,projects:"project",agents:"agent",tasks:"task",mods:"mod",schedules:"schedule",commands:"command",settings:"setting"};function ki({open:s,onClose:t,onSelect:a}){const i=re(),[n,c]=r.useState(""),[o,l]=r.useState("all"),[h,p]=r.useState([]),[u,d]=r.useState(!1),[m,x]=r.useState(0),g=r.useRef(null),b=r.useRef(null);if(r.useEffect(()=>{let S;return s&&(b.current=document.activeElement instanceof HTMLElement?document.activeElement:null,c(""),p([]),x(0),S=window.setTimeout(()=>{var A;return(A=g.current)==null?void 0:A.focus()},30)),()=>{if(S&&window.clearTimeout(S),!s)return;const A=b.current;A&&A.isConnected&&A.focus()}},[s]),r.useEffect(()=>{if(!s)return;if(!n.trim()){p([]),x(0);return}let S=!1;d(!0);const A=setTimeout(()=>{T.get(`/search?q=${encodeURIComponent(n)}&scope=${o}`).then(f=>{S||(p(f.results||[]),x(0))}).catch(f=>{S||i.error(`Search failed: ${f.message}`)}).finally(()=>!S&&d(!1))},150);return()=>{S=!0,clearTimeout(A)}},[n,o,s,i]),!s)return null;const z={};for(const S of h){const A=S.type.toLowerCase();z[A]=z[A]||[],z[A].push(S)}const k=[];for(const S of nt.map(A=>A.id)){const A=qt[S];A&&z[A]&&k.push(...z[A])}const w=S=>{if(S.key==="Escape")t();else if(S.key==="ArrowDown"){if(S.preventDefault(),k.length===0)return;x(A=>Math.min(A+1,k.length-1))}else if(S.key==="ArrowUp"){if(S.preventDefault(),k.length===0)return;x(A=>Math.max(A-1,0))}else S.key==="Enter"&&k[m]&&(S.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:S=>S.stopPropagation(),children:[e.jsxs("div",{className:"search-modal-head",role:"search",children:[e.jsx(ye,{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:S=>c(S.target.value),onKeyDown:w,"aria-label":"Search"}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Close",onClick:t,children:e.jsx(Ne,{size:14})})]}),e.jsx("div",{className:"search-modal-scopes",role:"tablist","aria-label":"Search scope",children:nt.map(S=>e.jsx("button",{type:"button",role:"tab","aria-selected":o===S.id,className:V("search-scope",o===S.id&&"search-scope-active"),onClick:()=>l(S.id),children:S.label},S.id))}),e.jsxs("div",{className:"search-modal-body",children:[u&&e.jsx("div",{className:"muted",children:"Searching…"}),!u&&n&&k.length===0&&e.jsx("div",{className:"muted",children:"No results."}),!u&&!n&&e.jsx("div",{className:"muted",children:"Type to search…"}),nt.map(S=>{const A=qt[S.id];if(!A)return null;const f=z[A];return!f||f.length===0?null:e.jsxs("div",{className:"search-group",children:[e.jsx("div",{className:"search-group-head",children:S.label}),f.map(N=>{const v=k.indexOf(N);return e.jsxs("button",{type:"button",className:V("search-result",v===m&&"search-result-active"),onMouseEnter:()=>x(v),onClick:()=>{a(N),t()},children:[e.jsx("span",{className:"search-result-type",children:N.type}),e.jsx("span",{className:"search-result-label",children:wi(N)})]},`${N.type}-${v}`)})]},S.id)})]}),e.jsx("div",{className:"search-modal-foot",children:e.jsx("span",{className:"muted",children:"↑↓ navigate · ↵ open · esc close"})})]})})}function wi(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 Si={info:zt,success:qe,warning:ze,error:la};function Ci({onCountChange:s,wsSubscribe:t}){const a=re(),[i,n]=r.useState(!1),[c,o]=r.useState([]),[l,h]=r.useState(null),[p,u]=r.useState(!1),d=r.useRef(null),m=r.useRef(0),x=async()=>{var w;try{u(!0);const S=await T.get("/notifications?limit=200");o(S.notifications||[]),h(S.stats||null),m.current=((w=S.stats)==null?void 0:w.unread)||0,s==null||s(m.current)}catch(S){console.warn("[notifications] reload failed:",S.message)}finally{u(!1)}};r.useEffect(()=>{x()},[]),r.useEffect(()=>t?t(S=>{if(S.type==="notification:new"){const A=S.notification;o(f=>[A,...f.filter(N=>N.id!==A.id)]),A.read||(m.current+=1,h(f=>f?{...f,unread:(f.unread||0)+1}:{total:1,unread:1,lastTs:A.ts,counts:{[A.severity||"info"]:1}}),s==null||s(m.current))}else S.type==="notifications:change"&&x()}):void 0,[t]),r.useEffect(()=>{if(!i)return;const w=A=>{d.current&&(d.current.contains(A.target)||n(!1))},S=A=>{A.key==="Escape"&&n(!1)};return document.addEventListener("mousedown",w),document.addEventListener("keydown",S),()=>{document.removeEventListener("mousedown",w),document.removeEventListener("keydown",S)}},[i]);const g=async()=>{try{await T.post("/notifications/read-all",{}),o(w=>w.map(S=>({...S,read:!0}))),h(w=>w&&{...w,unread:0}),m.current=0,s==null||s(0),a.success("All notifications marked as read.",1500)}catch(w){a.error(`Failed: ${w.message}`)}},b=async w=>{try{await T.post(`/notifications/${encodeURIComponent(w)}/read`,{}),o(S=>S.map(A=>A.id===w?{...A,read:!0}:A)),h(S=>S&&{...S,unread:Math.max(0,(S.unread||1)-1)}),m.current=Math.max(0,m.current-1),s==null||s(m.current)}catch(S){a.error(`Failed: ${S.message}`)}},z=async w=>{try{await T.del(`/notifications/${encodeURIComponent(w)}`),o(S=>{const A=S.find(f=>f.id===w);return A&&!A.read&&(m.current=Math.max(0,m.current-1),h(f=>f&&{...f,unread:Math.max(0,f.unread-1)}),s==null||s(m.current)),S.filter(f=>f.id!==w)})}catch(S){a.error(`Failed: ${S.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(w=>!w),title:"Notifications","aria-label":"Notifications","aria-haspopup":"true","aria-expanded":i,children:[e.jsx(an,{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($,{size:"sm",variant:"ghost",onClick:g,disabled:k===0,children:[e.jsx(gs,{size:12})," Mark all read"]}),e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>n(!1),"aria-label":"Close",title:"Close",children:e.jsx(Ne,{size:14})})]})]}),e.jsx("div",{className:"notifications-list",children:p&&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(w=>{const S=Si[w.severity]||zt;return e.jsxs("div",{className:V("notification-item",!w.read&&"is-unread",`severity-${w.severity}`),children:[e.jsx(S,{size:14,className:`notification-icon severity-${w.severity}`}),e.jsxs("div",{className:"notification-body",children:[w.title&&e.jsx("div",{className:"notification-title",children:w.title}),e.jsx("div",{className:"notification-msg",children:w.message}),e.jsxs("div",{className:"notification-meta muted",children:[e.jsx("span",{className:"mono",children:w.source}),e.jsx("span",{children:"·"}),e.jsx("span",{children:Te(w.ts)})]})]}),e.jsxs("div",{className:"notification-actions",children:[!w.read&&e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>b(w.id),title:"Mark as read","aria-label":"Mark as read",children:e.jsx(gs,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger",onClick:()=>z(w.id),title:"Remove","aria-label":"Remove",children:e.jsx(Ne,{size:12})})]})]},w.id)})}),e.jsx("footer",{className:"notifications-panel-foot",children:e.jsx("span",{className:"muted text-sm",children:l?`${l.total} total · last ${Te(l.lastTs||new Date().toISOString())}`:""})})]})]})}function zi({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($,{variant:"ghost",onClick:t,children:"Close"})})]})}const Ti=["blank","feature-design","bug-investigation","decision-record","horizontal","vertical"];function Ri({data:s,onClose:t}){const a=(s==null?void 0:s.templates)??Ti,i=(s==null?void 0:s.defaultTemplate)??"blank",[n,c]=r.useState(""),[o,l]=r.useState(i),[h,p]=r.useState(!1),[u,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}p(!0),d(null);try{await T.post("/artifacts",{slug:n,template:o}),t()}catch(x){d(x.message),p(!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:x=>{c(x.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:x=>l(x.target.value),children:a.map(x=>e.jsx("option",{value:x,children:x},x))})]}),u&&e.jsx("p",{style:{marginBottom:12,color:"var(--color-danger)",fontSize:13},children:u}),e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx($,{variant:"ghost",onClick:t,disabled:h,children:"Cancel"}),e.jsx($,{variant:"primary",onClick:m,disabled:h||!n.trim(),children:h?"Creating…":"Create"})]})]})}function $i({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($,{variant:"ghost",size:"sm",onClick:()=>n(c),children:"Open"})]},c))})]}),e.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:e.jsx($,{variant:"ghost",onClick:t,children:"Close"})})]})}function Ai({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($,{variant:"ghost",onClick:t,children:"Close"})})]})}function Mi({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 T.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($,{variant:"ghost",onClick:t,children:"Cancel"}),e.jsx($,{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,h)=>e.jsx("li",{style:{marginBottom:4,fontSize:13},children:l},h))})]}):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($,{variant:"ghost",onClick:t,children:"Close"})})]})})}function Ii({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 Ei({dialog:s,onClose:t}){switch(s.component){case"visual-artifact":return e.jsx(zi,{data:s.data,onClose:t});case"artifact-create":return e.jsx(Ri,{data:s.data,onClose:t});case"artifact-list":return e.jsx($i,{data:s.data,onClose:t});case"help":return e.jsx(Ai,{data:s.data,onClose:t});case"audit":return e.jsx(Mi,{data:s.data,onClose:t});default:return e.jsx(Ii,{dialog:s,onClose:t})}}function Li({setActiveTab:s,refreshKey:t=0}){var p;const[a,i]=r.useState(null),[n,c]=r.useState(!0),o=async()=>{c(!0);try{const[u,d,m]=await Promise.all([T.get("/memory/status").catch(()=>null),T.get("/memory/health").catch(()=>null),T.get("/memory/lightrag/stats").catch(()=>null)]);i({initialized:!!(u!=null&&u.initialized),mode:u==null?void 0:u.mode,projectId:u==null?void 0:u.projectId,vaultRoot:u==null?void 0:u.vaultRoot,branch:u==null?void 0:u.branch,gitClean:u==null?void 0:u.gitClean,noteCount:(u==null?void 0:u.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"),h=(a==null?void 0:a.healthStatus)==="healthy"?"var(--success)":(a==null?void 0:a.healthStatus)==="degraded"?"var(--warning)":(a==null?void 0:a.healthStatus)==="unhealthy"?"var(--error)":"var(--text-dim)";return e.jsxs(G,{className:"memory-overview-card",children:[e.jsxs(te,{children:[e.jsx(Ue,{size:14})," Memory",e.jsxs($,{variant:"ghost",size:"sm",style:{marginLeft:"auto"},onClick:l,children:["Open Memory ",e.jsx(ys,{size:12})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:o,"aria-label":"Refresh",title:"Refresh",children:e.jsx(de,{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(De,{size:11})," Health"]}),e.jsx("div",{className:"memory-status-card-value",style:{color:h},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(Ue,{size:11})," LightRAG"]}),e.jsx("div",{className:"memory-status-card-value",children:(p=a.lightrag)!=null&&p.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(ke,{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(rs,{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}`:_e(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 pe({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(Ys,{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 Di({snapshot:s,settings:t,setActiveTab:a,refreshSnapshot:i}){var Q,ae,ee;const n=re(),c=Re(),o=r.useRef(null),[l,h]=r.useState(s.overview??null),[p,u]=r.useState(!s.overview),[d,m]=r.useState(s.projects||[]),[x,g]=r.useState(((Q=s.activeProject)==null?void 0:Q.id)||null),[b,z]=r.useState(s.mods||[]),[k,w]=r.useState(!1),[S,A]=r.useState(((ae=s.overview)==null?void 0:ae.recentActivity)??[]),[f,N]=r.useState(!1),[v,j]=r.useState(new Set);r.useEffect(()=>{let F=!1;return(async()=>{try{const H=await T.get("/activity/hidden");F||j(new Set(H.hidden||[]))}catch{}})(),()=>{F=!0}},[]);const E=(F,H)=>{const K=`${F.kind||""}|${F.ts||""}|${F.slug||F.title||""}|${H}`;let B=0;for(let Z=0;Z<K.length;Z++)B=(B<<5)-B+K.charCodeAt(Z)|0;return Math.abs(B).toString(16).padStart(8,"0").slice(0,16)},R=async F=>{const H=new Set(v);H.add(F),j(H);try{await T.post("/activity/hide",{keys:[F]})}catch(K){const B=new Set(v);j(B),n.error(`Hide failed: ${K.message}`)}},y=async()=>{if(!confirm("Hide every recent activity item from the overview? The full log stays in Settings → Activity Log."))return;const F=S.map((K,B)=>E(K,B)),H=new Set(v);F.forEach(K=>H.add(K)),j(H);try{await T.post("/activity/hide",{keys:F}),n.success(`Hidden ${F.length} item(s). Restore them in Settings → Activity Log.`)}catch(K){n.error(`Clear failed: ${K.message}`)}},M=async()=>{j(new Set);try{await T.del("/activity/hide"),n.success("All hidden activity restored to the overview.")}catch(F){n.error(`Restore failed: ${F.message}`)}};r.useEffect(()=>{var F;s.overview&&(h(s.overview),A(s.overview.recentActivity??[]),u(!1)),m(s.projects||[]),g(((F=s.activeProject)==null?void 0:F.id)||null),z(s.mods||[])},[s.overview,s.projects,s.activeProject,s.mods]),r.useEffect(()=>{let F;try{const H=T.getToken(),K=H?`/api/activity/stream?token=${encodeURIComponent(H)}`:"/api/activity/stream";F=new EventSource(K),F.addEventListener("snapshot",B=>{try{const Z=JSON.parse(B.data);A(Array.isArray(Z.events)?Z.events.slice(0,50):[])}catch{}}),F.addEventListener("activity",B=>{try{const Z=JSON.parse(B.data);A(he=>[Z,...he].slice(0,50))}catch{}})}catch{}return()=>{try{F==null||F.close()}catch{}}},[]);const P=async()=>{n.info("Refreshing…",1500),await i();try{const F=await T.get("/projects");m(F.projects||[]),g(F.active||null)}catch{}},C=()=>{c.open({title:"Add project",children:e.jsx(Pi,{settings:t,onAdd:async(F,H)=>{try{const K=await T.post("/projects",{path:F,name:H});m(B=>[...B.filter(Z=>Z.id!==K.id),K]),n.success("Project added."),c.close()}catch(K){n.error(`Add failed: ${K.message}`)}}}),footer:e.jsx("div",{className:"modal-footer-actions",children:e.jsx($,{variant:"ghost",onClick:()=>c.close(),children:"Cancel"})})})},D=async()=>{var F;try{const H=await T.post("/projects/auto-detect");m(H.projects||[]),g(H.active||null);const K=(F=H.projects)==null?void 0:F.find(B=>B.id===H.active);n.success(K?`Active: ${K.name}`:"Projects refreshed."),await i()}catch(H){n.error(`Auto-detect failed: ${H.message}`)}},Y=async F=>{try{await T.post(`/projects/${encodeURIComponent(F)}/activate`),g(F),n.success("Project activated."),await i()}catch(H){n.error(`Activate failed: ${H.message}`)}},O=async F=>{if(confirm(`Remove project "${F}" from the registry?`))try{await T.del(`/projects/${encodeURIComponent(F)}`),m(H=>H.filter(K=>K.id!==F)),x===F&&g(null),n.success("Project removed.")}catch(H){n.error(`Remove failed: ${H.message}`)}};return p||!l?e.jsxs("div",{className:"view-loading",children:[e.jsx(oe,{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 F=>{var K,B;F.preventDefault();const H=(((K=o.current)==null?void 0:K.value)||"").trim();if(H){w(!0);try{const Z=await T.post("/tasks/submit",{title:H});n.success(`Odin split it into ${((B=Z.subtasks)==null?void 0:B.length)||1} task(s)`),o.current&&(o.current.value=""),await i()}catch(Z){n.error(`Failed: ${Z.message}`)}finally{w(!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($,{type:"submit",variant:"primary",size:"lg",disabled:k,children:[k?e.jsx(oe,{size:"sm"}):e.jsx(Ze,{size:16}),"Submit to Odin"]}),e.jsxs("span",{className:"muted",style:{fontSize:12},children:[e.jsx(Xe,{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(F=>e.jsx("button",{type:"button",className:"overview-quick-chip",onClick:()=>{o.current&&(o.current.value=F,o.current.focus())},children:F},F))})]}),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:[v.size>0&&e.jsxs($,{variant:"ghost",size:"sm",onClick:M,title:"Restore hidden items to this overview",children:[e.jsx(fs,{size:12})," Show ",v.size," hidden"]}),S.length>8&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>N(F=>!F),children:f?"Show less":"Show all"}),S.length>0&&e.jsxs($,{variant:"ghost",size:"sm",onClick:y,title:"Hide every item from the overview (full log kept)",children:[e.jsx(ft,{size:12})," Hide all"]})]})]}),v.size>0&&e.jsxs("div",{className:"activity-hidden-banner",role:"status",children:[e.jsxs("span",{children:[e.jsx(ft,{size:12,style:{verticalAlign:-2,marginRight:6}}),v.size," item",v.size===1?"":"s"," hidden from the overview."]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:M,children:[e.jsx(fs,{size:12})," Show them again"]})]}),S.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",!f&&"activity-feed-list-wrap-collapsed"),"aria-live":"polite","aria-relevant":"additions",children:[e.jsx(Dt,{items:S.slice(0,30).filter((F,H)=>!v.has(E(F,H))),itemHeight:60,height:Math.min(S.filter((F,H)=>!v.has(E(F,H))).length*60,480),className:"activity-feed-list",renderItem:(F,H)=>{const K=S.slice(0,30).findIndex(B=>B===F);return e.jsx(Hi,{item:F,activityKey:E(F,K),onNavigate:a,onHide:R})}}),!f&&S.length>8&&e.jsx("div",{className:"activity-feed-fade","aria-hidden":"true"})]})]}),e.jsxs(G,{className:"project-picker",children:[e.jsxs(te,{children:[e.jsx(Pe,{size:14})," Projects",e.jsxs($,{variant:"ghost",size:"sm",style:{marginLeft:"auto"},onClick:C,children:[e.jsx(be,{size:12})," Add"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:D,title:"Use the server's working directory",children:[e.jsx(be,{size:12})," Auto-detect"]}),((ee=t==null?void 0:t.dashboard)==null?void 0:ee.projectsDirectory)&&e.jsxs($,{variant:"ghost",size:"sm",title:`Scan ${t.dashboard.projectsDirectory} for projects`,onClick:async()=>{try{const F=await T.post("/projects/scan");F.error?n.error(F.error):n.success(`Added ${F.added.length}, skipped ${F.skipped}.`),await i();const H=await T.get("/projects");m(H.projects||[]),g(H.active||null)}catch(F){n.error(`Scan failed: ${F.message}`)}},children:[e.jsx(nn,{size:12})," Scan"]}),e.jsx($,{variant:"ghost",size:"sm",onClick:P,title:"Refresh",children:e.jsx(de,{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(pe,{icon:e.jsx(Pe,{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($,{variant:"primary",onClick:D,children:[e.jsx(be,{size:14})," Use current directory"]}),e.jsx($,{variant:"secondary",onClick:C,children:"Add by path…"})]})}):e.jsx("div",{className:"project-grid",children:d.map(F=>e.jsx(Fi,{project:F,active:x===F.id,onOpen:()=>Y(F.id),onRemove:()=>O(F.id)},F.id))})]}),e.jsx(Li,{setActiveTab:a}),e.jsxs("div",{className:"overview-cols",children:[e.jsxs(G,{children:[e.jsx(te,{children:"Mods"}),e.jsxs(ne,{children:["Extensions installed under ",e.jsx("code",{children:"~/.config/bizar/mods/"})]}),b.length===0?e.jsx("div",{className:"muted",children:"No mods installed."}):e.jsx("ul",{className:"mod-mini-list",children:b.map(F=>e.jsxs("li",{className:"mod-mini",children:[e.jsx("span",{className:"mod-mini-name",children:F.name}),e.jsxs("span",{className:"mod-mini-meta",children:["v",F.version," · ",F.type]}),e.jsx("span",{className:`mod-mini-pill ${F.enabled?"mod-mini-pill-on":"mod-mini-pill-off"}`,children:F.enabled?"on":"off"})]},F.id))})]}),e.jsxs(G,{children:[e.jsx(te,{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:_e(l.generatedAt)})]})]})]})]})}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),[h,p]=r.useState(null),u=async()=>{var x;if(a){l(!0),p(null);try{await T.get("/fs?path="+encodeURIComponent(a)),t(a,n||null)}catch(g){const b=g;b.status===404?p("That folder no longer exists. Pick another."):p(((x=b.data)==null?void 0:x.message)??g.message??"Validation failed.")}finally{l(!1)}}};return e.jsxs("div",{children:[e.jsx("label",{className:"field-label",children:"Folder"}),e.jsx(Ca,{value:a,onChange:x=>{i(x),p(null)},projectsDirectory:(m=s==null?void 0:s.dashboard)==null?void 0:m.projectsDirectory,height:320}),h&&e.jsx("p",{className:"field-help",style:{color:"var(--error)",marginTop:4},children:h}),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:x=>c(x.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($,{variant:"primary",onClick:u,disabled:!a||o,children:[o?e.jsx("span",{className:"btn-spinner"}):null,o?"Checking…":"Add"]})})]})}function Fi({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(we,{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 ",Te(s.lastAccessed)]})}),e.jsx("div",{className:"project-card-actions",children:e.jsx($,{variant:t?"ghost":"primary",size:"sm",onClick:a,children:t?e.jsxs(e.Fragment,{children:[e.jsx(Tt,{size:12})," Active"]}):e.jsx(e.Fragment,{children:"Open"})})})]})}function Oi(s){return s&&s.charAt(0).toUpperCase()+s.slice(1)}function Bi(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]||Oi(a.replace(/-/g," ")),l=c[i]||i.replace(/-/g," ");return`${o} ${l}`.trim()}function Fs(s,t){for(const a of t){const i=s[a];if(typeof i=="string"&&i.trim())return i.trim()}return""}function Ui(s){const t=Fs(s,["message","text","prompt","title","name"]);if(t)return t;const a=[],i=Fs(s,["slug"]),n=Fs(s,["agent","author"]),c=Fs(s,["status"]);return i&&a.push(`Plan ${i}`),n&&a.push(n),c&&a.push(c),a.length?a.join(" · "):"No additional details."}function _i(s){return Te(s)}function Wi(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 qi(s){const t=s.toLowerCase();return t==="task"?$s:t==="agent"?Ke:t==="plan"?Gs:t.includes("bg")||t.includes("background")||t.includes("job")?Rt:t==="mod"?as:t==="skill"?Xe:t.includes("error")||t.includes("failure")?ps:t.includes("warn")?ze:De}function Vi(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 Hi({item:s,activityKey:t,onNavigate:a,onHide:i}){const n=Wi(s),c=qi(s.kind||""),o=Bi(s.kind||"activity"),l=Ui(s),h=Vi(s.kind||""),p=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:()=>{h&&a(h)},title:h?`Open ${h}`:o,children:[e.jsx("div",{className:"activity-feed-icon",style:{color:p},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:_i(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(Ne,{size:12})})]})}const Gi=Fe.memo(Di);function Ki({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 Yi({session:s,mode:t,anchor:a,renameDraft:i,setRenameDraft:n,onEdit:c,onDeleteRequest:o,onConfirmDelete:l,onConfirmRename:h,onClose:p}){const u=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 w=k.target;!u.current||!w||u.current.contains(w)||p()},b=k=>{k.key==="Escape"&&p()},z=window.setTimeout(()=>{document.addEventListener("mousedown",g),document.addEventListener("keydown",b)},0);return()=>{window.clearTimeout(z),document.removeEventListener("mousedown",g),document.removeEventListener("keydown",b)}},[p]),r.useEffect(()=>{if(t!=="rename")return;const g=window.setTimeout(()=>{var z;const b=(z=u.current)==null?void 0:z.querySelector("input.session-row-menu-input");b==null||b.focus(),b==null||b.select()},0);return()=>window.clearTimeout(g)},[t]);const x=e.jsxs("div",{ref:u,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(rn,{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(we,{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(),h()):g.key==="Escape"&&(g.preventDefault(),p())},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(),p()},children:"Cancel"}),e.jsx("button",{type:"button",className:"btn btn-primary",onClick:g=>{g.stopPropagation(),h()},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(),p()},children:"Cancel"}),e.jsx("button",{type:"button",className:"btn btn-danger",onClick:g=>{g.stopPropagation(),l()},children:"Delete"})]})]})]});return ra.createPortal(x,document.body)}function bt({node:s,depth:t=0,collapsible:a=!1,isLast:i=!0,open:n,onToggle:c}){var x;const[o,l]=r.useState(a),h=n!==void 0,p=h?n:o,u=g=>{h||l(g),c==null||c(g)},d=(((x=s.children)==null?void 0:x.length)??0)>0,m=e.jsxs(e.Fragment,{children:[a&&e.jsx("span",{className:`agent-node-chevron ${p?"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}`,p?"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(),u(!p)},"aria-expanded":p,children:m}):e.jsx("div",{className:`agent-node-head status-${s.status}`,children:m}),p&&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,b)=>e.jsx(bt,{node:g,depth:t+1,collapsible:!1,isLast:b===s.children.length-1},g.id))})]})]})}function Xi(s){return s.tree!==void 0}function Qi(s){const t=s.open??!0;if(Xi(s))return e.jsx("div",{className:`agent-tree variant-${s.variant??"full"}`,children:e.jsx(bt,{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(bt,{node:i,depth:0,collapsible:!1,open:t,isLast:n===a.length-1})},i.id))})})}function Ji({children:s,variant:t="rail",open:a=!0}){return a?e.jsx(Qi,{variant:t,open:a,children:s}):null}const Zi=["Today","Yesterday","This week","Earlier"];function Vt(s,t){return s.getFullYear()===t.getFullYear()&&s.getMonth()===t.getMonth()&&s.getDate()===t.getDate()}function er(s,t){const a=s.getTime()-t.getTime();return Math.floor(a/(1e3*60*60*24))}function sr(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());Vt(o,t)?n.Today.push(c):Vt(o,a)?n.Yesterday.push(c):er(t,o)<7?n["This week"].push(c):n.Earlier.push(c)}return n}function tr(s){return new Date(Number(s)||Date.now()).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1})}function ar({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 nr({sessions:s,opencodeSessions:t=[],activeSessionId:a,activeOpencodeSessionId:i,activeProject:n,creating:c,onCreateSession:o,onSelectSession:l,onSelectOpencodeSession:h,onRenameSession:p,onDeleteSession:u,groupBy:d}){var O;const m=r.useMemo(()=>[...s,...t],[s,t]),x=r.useMemo(()=>[...m].sort((Q,ae)=>Number(ae.mtime??0)-Number(Q.mtime??0)),[m]),g=r.useMemo(()=>d?d(x):sr(x),[d,x]),[b,z]=r.useState({}),k=Q=>b[Q]===!0,[w,S]=r.useState(null),[A,f]=r.useState("main"),[N,v]=r.useState(""),[j,E]=r.useState(null),R=r.useRef({}),y=(Q,ae="main")=>{const ee=R.current[Q];if(!ee)return;const F=ae==="main"?ee:ee.querySelector(".chat-rail-item-menu-trigger")??ee;if(E({id:Q,rect:F.getBoundingClientRect()}),S(Q),f(ae),ae==="rename"){const H=[...s,...t].find(K=>K.id===Q);v((H==null?void 0:H.title)??(H==null?void 0:H.id)??"")}},M=()=>{S(null),f("main"),v(""),E(null)},P=Q=>{if(Q.source==="opencode"){h(Q);return}l(Q.id)},C=()=>{if(!j)return;const Q=j.id,ae=N.trim();if(!ae){M();return}p==null||p(Q,ae),M()},D=()=>{j&&(u==null||u(j.id),M())},Y=d?Object.entries(g):Zi.filter(Q=>{var ae;return(ae=g[Q])==null?void 0:ae.length}).map(Q=>[Q,g[Q]]);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(be,{size:14,"aria-hidden":!0}),e.jsx("span",{children:c?"Creating…":"New session"})]})}),x.length===0?e.jsx("div",{className:"chat-sessions-empty",children:e.jsx(Ki,{icon:e.jsx(be,{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(([Q,ae])=>e.jsxs("div",{className:"chat-rail-group",children:[e.jsx("div",{className:"chat-rail-group-label",children:Q}),ae.map(ee=>{var he,Se;const F=ee.source==="opencode",H=F?i===ee.id:a===ee.id,K=ee.tree,B=!!((he=K==null?void 0:K.root)!=null&&he.children&&K.root.children.length>0),Z=k(ee.id);return e.jsxs(r.Fragment,{children:[e.jsxs("div",{ref:W=>{R.current[ee.id]=W},role:"button",tabIndex:0,className:`chat-rail-item state-${ee.state??"idle"}${H?" active":""}`,onClick:()=>P(ee),onKeyDown:W=>{(W.key==="Enter"||W.key===" ")&&(W.preventDefault(),P(ee))},"aria-current":H?"true":void 0,children:[e.jsx(ar,{state:ee.state??"idle",agent:ee.agent}),e.jsxs("div",{className:"chat-rail-item-title",children:[ee.pinned&&e.jsx("span",{className:"chat-rail-pin","aria-hidden":!0,children:"★"}),F&&e.jsx(ys,{size:11,style:{color:"var(--text-muted)",flexShrink:0},"aria-hidden":!0}),e.jsx("span",{className:"chat-ellipsis",children:ee.title||ee.id})]}),e.jsxs("div",{className:"chat-rail-item-meta",children:[e.jsx("span",{className:"chat-rail-item-meta-time",children:ee.time??tr(ee.mtime)}),(ee.unread??0)>0&&e.jsx("span",{className:"chat-rail-badge",children:ee.unread})]}),e.jsx("button",{type:"button",className:`chat-rail-item-menu-trigger${w===ee.id?" open":""}`,"aria-label":`Session options for ${ee.title||ee.id}`,"aria-haspopup":"menu","aria-expanded":w===ee.id,onClick:W=>{W.stopPropagation(),w===ee.id?M():y(ee.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&&B&&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:W=>{W.stopPropagation(),z(se=>({...se,[ee.id]:!se[ee.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&&B&&Z&&((Se=K==null?void 0:K.root)==null?void 0:Se.children)&&e.jsx(Ji,{children:K.root.children,variant:"rail",open:!0})]},F?`oc-${ee.id}`:ee.id)})]},Q))}),w&&j&&e.jsx(Yi,{session:{id:j.id,title:((O=[...s,...t].find(Q=>Q.id===j.id))==null?void 0:O.title)??j.id},mode:A,anchor:j,renameDraft:N,setRenameDraft:v,onEdit:()=>y(w,"rename"),onDeleteRequest:()=>y(w,"confirm-delete"),onConfirmDelete:D,onConfirmRename:C,onClose:M})]})}function ir(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(si,{...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 it(s){return s.toLocaleString()}function rr(s){return!s||!s.includes("/")?"":s.split("/")[0]}function lr(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 or({sessionId:s,messages:t,pinned:a,agent:i,model:n,agents:c,mcps:o,allCommands:l,activeSource:h="bizar",onRename:p,onDelete:u,onExport:d,busy:m,error:x,onRetry:g}){const[b,z]=r.useState(null);r.useEffect(()=>{let y=!1;return(async()=>{try{const M=await fetch("/api/usage?range=24h",{headers:{Accept:"application/json"}});if(!M.ok)return;const P=await M.json();y||z(P)}catch{}})(),()=>{y=!0}},[s]);const k=(t==null?void 0:t.length)??0,w=(a==null?void 0:a.size)??0,S=t.reduce((y,M)=>y+(M.content||M.message||"").length,0),A=Math.round(S/4),f=lr(n),N=A/1e6*f,v=(b==null?void 0:b.totalTokens)??A,j=(b==null?void 0:b.costUsd)??N,E=128e3,R=rr(n);return e.jsxs("aside",{className:"chat-info",children:[x&&e.jsxs("div",{className:"chat-info-section chat-info-error",role:"alert","aria-live":"polite",children:[e.jsxs("h4",{children:[e.jsx(ze,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Couldn't load session"]}),e.jsx("p",{className:"chat-info-value chat-ellipsis",title:x.message,children:x.message}),e.jsxs("div",{className:"chat-info-mono",children:["code · ",x.code]}),x.suggestion?e.jsx("p",{className:"chat-info-suggestion",children:x.suggestion}):null,x.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(Zs,{size:12,"aria-hidden":!0})," Retry"]}):null]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("div",{className:"chat-info-section-head",children:[e.jsxs("h4",{children:[e.jsx(Js,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Session"]}),e.jsx("span",{className:`chat-source-badge chat-source-${h??"none"}`,style:{marginLeft:"auto"},children:h==="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:[it(k)," message",k===1?"":"s",w>0&&` · ${w} pinned`]})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("h4",{children:[e.jsx(Ke,{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(js,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Model"]}),e.jsx("div",{className:"chat-mono chat-ellipsis",title:n,children:n||"—"}),R&&e.jsxs("div",{className:"chat-info-mono",children:["provider · ",R]})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsx("h4",{children:"Tokens"}),e.jsxs("div",{className:"chat-mono",children:[it(v)," / ",it(E)]}),e.jsx("div",{className:"chat-info-bar","aria-hidden":!0,children:e.jsx("div",{className:"chat-info-bar-fill",style:{width:`${Math.min(100,v/Math.max(1,E)*100)}%`}})})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("h4",{children:[e.jsx(ln,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Cost"]}),e.jsxs("div",{className:"chat-mono",children:["$",j.toFixed(4)]}),!b&&e.jsx("div",{className:"chat-info-mono",children:"approx · live from MiniMax"})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("h4",{children:[e.jsx(Ke,{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(y=>e.jsx("span",{className:"chat-info-agent",children:y.name},y.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(js,{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(y=>e.jsx("span",{className:"chat-info-agent",children:y.id},y.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(is,{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"]})]}),(p||u||d)&&e.jsxs("div",{className:"chat-info-section",children:[e.jsx("h4",{children:"Actions"}),e.jsxs("div",{className:"chat-info-actions",children:[p&&e.jsxs("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:p,disabled:m==null?void 0:m.rename,title:"Rename session",children:[e.jsx(Ls,{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(ls,{size:12,"aria-hidden":!0})," Export"]}),u&&e.jsxs("button",{type:"button",className:"btn btn-ghost btn-sm btn-danger",onClick:u,disabled:m==null?void 0:m.delete,title:"Delete session",children:[e.jsx(we,{size:12,"aria-hidden":!0})," Delete"]})]})]})]})}function cr({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(ma,{size:14,"aria-hidden":!0}),e.jsx("span",{children:"Jump to latest"}),t>0&&e.jsxs("span",{className:"jump-badge",children:[t," new"]})]})})}function dr({snapshot:s,settings:t,setActiveTab:a,initialTaskId:i,onClearTaskId:n}){const c=re(),o=Re(),l=ti(s,t,i??"");r.useEffect(()=>{l.setToast({error:O=>c.error(O),success:O=>c.success(O),info:O=>c.info(O),warning:O=>c.warning(O)})},[l,c]);const[h,p]=r.useState(""),[u,d]=r.useState(t.defaultAgent||"odin"),[m,x]=r.useState(t.defaultModel||""),[g,b]=r.useState([]),z=r.useRef(null),{allCommands:k,suggestions:w,setQuery:S}=ai(s);r.useEffect(()=>{S(h)},[h,S]);const A=()=>{var O;return(O=z.current)==null?void 0:O.click()},f=O=>{const Q=O.target.files;if(!Q)return;const ae=[];for(let ee=0;ee<Q.length;ee++)ae.push(Q[ee].name);b(ee=>{const F=ae.filter(H=>!ee.includes(H));return[...ee,...F]}),z.current&&(z.current.value="")},N=async()=>{const O=h.trim();if(!O)return;p(""),S(""),(await l.onSend(O,u,m,g)).ok&&l.jumpToLatest()},v=async()=>{l.busy.create||await l.onCreateSession()},j=O=>{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($,{variant:"secondary",size:"sm",onClick:()=>o.close(),children:"Cancel"}),e.jsx($,{variant:"danger",size:"sm",onClick:()=>{o.close(),l.deleteMessage(O)},children:"Delete"})]})})},E=(O,Q)=>{let ae="";o.open({title:"Rename session",children:e.jsx("input",{id:"rename-session-input",autoFocus:!0,defaultValue:Q,"aria-label":"Session title",onChange:ee=>{ae=ee.target.value},onKeyDown:ee=>{ee.key==="Enter"&&(ee.preventDefault(),o.close(),l.renameSession(O,ae).then(F=>{F&&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($,{variant:"secondary",size:"sm",onClick:()=>o.close(),children:"Cancel"}),e.jsx($,{variant:"primary",size:"sm",onClick:()=>{o.close(),l.renameSession(O,ae)},children:"Save"})]})})},R=(O,Q)=>{o.open({title:"Delete session?",children:e.jsxs("p",{style:{margin:0},children:["Delete ",e.jsx("strong",{children:Q}),"? 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($,{variant:"secondary",size:"sm",onClick:()=>o.close(),children:"Cancel"}),e.jsx($,{variant:"danger",size:"sm",onClick:async()=>{o.close(),await l.deleteSession(O)},children:"Delete"})]})})},y=()=>{const O=l.activeSource==="opencode"?l.activeOpencodeSessionId:l.sessionId;if(!O)return;const ae=(l.activeSource==="opencode"?l.opencodeMessages:l.bizarMessages).map(K=>{const B=K.ts??"",Z=(K.role||"unknown").toUpperCase(),he=K.content||K.message||"";return`[${B}] ${Z}: ${he}`}).join(`
|
|
2
|
-
|
|
3
|
-
`),ee=new Blob([ae],{type:"text/plain;charset=utf-8"}),F=URL.createObjectURL(ee),H=document.createElement("a");H.href=F,H.download=`${O}.txt`,document.body.appendChild(H),H.click(),document.body.removeChild(H),URL.revokeObjectURL(F)},M=r.useMemo(()=>l.sessions.map(O=>l.getSessionDisplay(O)),[l.sessions,l.getSessionDisplay]),P=r.useMemo(()=>l.opencodeSessions.map(O=>l.getSessionDisplay(O)),[l.opencodeSessions,l.getSessionDisplay]),C=r.useMemo(()=>{const O=l.activeSource==="opencode"?l.activeOpencodeSessionId??"":l.sessionId;return O?M.find(Q=>Q.id===O)??P.find(Q=>Q.id===O)??null:null},[l.activeSource,l.activeOpencodeSessionId,l.sessionId,M,P]),D=(()=>{var ae;const O=`${u||"Odin"} · ${((ae=s.activeProject)==null?void 0:ae.name)??"no project"}`,Q=(C==null?void 0:C.state)??"idle";return Q==="streaming"?`Replying · ${O}`:Q==="awaiting"?`Your turn · ${O}`:`${O} · idle`})(),Y=l.activeSource==="opencode"?"opencode":"bizar chat";return e.jsxs("div",{className:"chat-shell",children:[e.jsx(ni,{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(nr,{sessions:M,opencodeSessions:P,activeSessionId:l.sessionId,activeOpencodeSessionId:l.activeOpencodeSessionId,activeProject:s.activeProject,creating:l.busy.create,onCreateSession:v,onSelectSession:l.selectBizarSession,onSelectOpencodeSession:O=>l.loadOpencodeSession(O.id),onRenameSession:E,onDeleteSession:O=>{const Q=l.sessions.find(ae=>ae.id===O)??l.opencodeSessions.find(ae=>ae.id===O);R(O,(Q==null?void 0:Q.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:(C==null?void 0:C.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-${(C==null?void 0:C.state)??"idle"}`,children:[e.jsx("span",{className:"chat-thread-dot"}),D]}),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:[C&&e.jsxs("button",{className:"btn btn-ghost",title:"Rename session",type:"button",disabled:l.busy.rename,onClick:()=>E(C.id,C.title??""),children:[e.jsx(Ls,{size:12,"aria-hidden":!0})," ",e.jsx("span",{className:"mono",children:"rename"})]}),C&&e.jsxs("button",{className:"btn btn-ghost btn-danger",title:"Delete session",type:"button",disabled:l.busy.delete,onClick:()=>R(C.id,C.title??C.id),children:[e.jsx(we,{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:y,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(ii,{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:O=>p(O),onCopy:O=>l.copyMessage(O),onDelete:j,onTogglePin:l.togglePin,onRegenerate:l.onRegenerate})}),!l.stickToBottom&&e.jsx(cr,{streaming:(C==null?void 0:C.state)==="streaming",newMessageCount:l.newMessageCount,onClick:l.jumpToLatest}),e.jsx(ir,{agent:u,setAgent:d,model:m,setModel:x,text:h,setText:p,sending:l.sending,activeSource:l.activeSource,onSend:N,attachments:g,setAttachments:b,suggestions:w,onPickSuggestion:O=>p(`${O.split(" ")[0]} `),agents:s.agents||[],onAttach:A}),e.jsx("input",{ref:z,type:"file",multiple:!0,style:{display:"none"},onChange:f,"aria-label":"Attach files to message",tabIndex:-1})]}),e.jsx(or,{sessionId:l.activeSource==="opencode"?l.activeOpencodeSessionId??l.sessionId:l.sessionId,messages:l.activeSource==="opencode"?l.opencodeMessages:l.bizarMessages,pinned:l.pinned,agent:u,model:m,agents:s.agents||[],mcps:s.mcps||[],allCommands:k,activeSource:l.activeSource,onRename:()=>{C&&E(C.id,C.title??"")},onDelete:()=>{C&&R(C.id,C.title??C.id)},onExport:y,busy:l.busy})]})]})}function mr(s){return s==="ok"?"success":s==="warn"?"warning":s==="fail"?"error":s}function Qe({kind:s="neutral",children:t,className:a,dot:i=!1}){const n=mr(s);return e.jsxs("span",{className:V("badge",`badge-${n}`,a),title:`status: ${s}`,children:[i&&e.jsx("span",{className:"badge-dot"}),t]})}const Ht=["bash","read","edit","write","webfetch","websearch","task","glob","grep"],Gt=["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"],Ws=[{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 ur(s){var t;return((t=Ws.find(a=>a.id===s))==null?void 0:t.color)||"var(--text-dim)"}function hr({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 xr({agent:s}){if(s.isStuck)return e.jsx(Qe,{kind:"error",dot:!0,children:"stuck"});const t=s.status||"idle";return t==="working"?e.jsx(Qe,{kind:"info",dot:!0,children:"working"}):t==="error"?e.jsx(Qe,{kind:"error",dot:!0,children:"error"}):e.jsx(Qe,{kind:"neutral",dot:!0,children:"idle"})}function pr({snapshot:s,refreshSnapshot:t}){const a=re(),i=Re(),[n,c]=r.useState(s.agents||[]),[o,l]=r.useState(!s.agents),[h,p]=r.useState(""),[u,d]=r.useState("");r.useEffect(()=>{c(s.agents||[]),l(!s.agents)},[s.agents]);const m=async()=>{try{const f=await T.get("/agents");c(f.agents||[])}catch(f){a.error(`Agents load failed: ${f.message}`)}finally{l(!1)}},x=r.useMemo(()=>{let f=[...n];if(h&&(f=f.filter(N=>h==="__none__"?!N.category:(N.category||"")===h)),u){const N=u.toLowerCase();f=f.filter(v=>v.name.toLowerCase().includes(N)||(v.description||"").toLowerCase().includes(N)||(v.tags||[]).some(j=>j.toLowerCase().includes(N)))}return f.sort((N,v)=>N.name.localeCompare(v.name))},[n,h,u]),g=r.useMemo(()=>{const f=new Set;for(const N of n)for(const v of N.tags||[])f.add(v);return Array.from(f).sort()},[n]),b=()=>{let f=null,N=null,v=null,j=null,E=null,R=null,y=null,M=null,P=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:C=>f=C,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:C=>{N=C},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:C=>v=C,className:"select",defaultValue:"",children:[e.jsx("option",{value:"",children:"(provider default)"}),Gt.map(C=>e.jsx("option",{value:C,children:C},C))]})]}),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:C=>j=C,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:C=>E=C,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:C=>P=C,className:"select",defaultValue:"",children:[e.jsx("option",{value:"",children:"(none)"}),Ws.map(C=>e.jsx("option",{value:C.id,children:C.label},C.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:C=>M=C,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:C=>y=C,className:"agent-tools",children:Ht.map(C=>e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{type:"checkbox",value:C,"aria-label":C}),e.jsx("span",{children:C})]},C))})]}),e.jsx("label",{className:"field-label",htmlFor:"agent-new-prompt",children:"System prompt"}),e.jsx("textarea",{id:"agent-new-prompt",ref:C=>R=C,className:"textarea",rows:6,placeholder:"You are a..."})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx($,{variant:"ghost",onClick:()=>i.close(),children:"Cancel"}),e.jsxs($,{variant:"primary",onClick:async()=>{const C=((f==null?void 0:f.value)||"").trim();if(!/^[a-z0-9][a-z0-9-]{0,63}$/i.test(C)){a.warning("Invalid name (a-z, 0-9, dashes).");return}const D=[];y&&y.querySelectorAll('input[type="checkbox"]:checked').forEach(O=>{D.push(O.value)});const Y=((M==null?void 0:M.value)||"").split(",").map(O=>O.trim()).filter(Boolean);try{const O=await T.post("/agents",{name:C,description:((N==null?void 0:N.value)||"").trim(),model:(v==null?void 0:v.value)||"",mode:(j==null?void 0:j.value)||"subagent",color:(E==null?void 0:E.value)||"",tools:D,tags:Y,category:(P==null?void 0:P.value)||"",prompt:(R==null?void 0:R.value)||""});c(Q=>[...Q,O]),a.success("Agent created."),i.close(),await t()}catch(O){a.error(`Create failed: ${O.message}`)}},children:[e.jsx(Ms,{size:12})," Create"]})]})})},z=async f=>{let N=null,v=null,j=null,E=null,R=null,y=null,M=null,P=null;try{const C=await T.get(`/agents/${encodeURIComponent(f.name)}`);i.open({title:`Edit ${f.name}`,width:640,children:e.jsxs("div",{className:"agent-form",children:[e.jsxs("div",{className:"muted",children:["File: ",e.jsx("code",{children:C.path})]}),e.jsx("label",{className:"field-label",htmlFor:"agent-edit-desc",children:"Description"}),e.jsx("input",{id:"agent-edit-desc",ref:D=>{N=D},className:"input",type:"text",defaultValue:C.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:D=>v=D,className:"select",defaultValue:C.model,children:[e.jsx("option",{value:"",children:"(provider default)"}),Gt.map(D=>e.jsx("option",{value:D,children:D},D))]})]}),e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"agent-edit-mode",children:"Mode"}),e.jsxs("select",{id:"agent-edit-mode",ref:D=>j=D,className:"select",defaultValue:C.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:D=>E=D,className:"input",type:"color",defaultValue:C.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:D=>P=D,className:"select",defaultValue:C.category||"",children:[e.jsx("option",{value:"",children:"(none)"}),Ws.map(D=>e.jsx("option",{value:D.id,children:D.label},D.id))]})]}),e.jsxs("div",{className:"task-form-field",style:{flex:2},children:[e.jsx("label",{className:"field-label",htmlFor:"agent-edit-tags",children:"Tags (comma-separated)"}),e.jsx("input",{id:"agent-edit-tags",ref:D=>M=D,className:"input",type:"text",defaultValue:(C.tags||[]).join(", ")})]})]}),e.jsxs("fieldset",{children:[e.jsx("legend",{className:"field-label",style:{padding:0},children:"Tools"}),e.jsx("div",{ref:D=>y=D,className:"agent-tools",children:Ht.map(D=>{var Y;return e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{type:"checkbox",value:D,"aria-label":D,defaultChecked:(Y=C.tools)==null?void 0:Y.includes(D)}),e.jsx("span",{children:D})]},D)})})]}),e.jsx("label",{className:"field-label",htmlFor:"agent-edit-prompt",children:"System prompt"}),e.jsx("textarea",{id:"agent-edit-prompt",ref:D=>R=D,className:"textarea",rows:8,defaultValue:C.prompt||""})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx($,{variant:"ghost",onClick:()=>i.close(),children:"Cancel"}),e.jsxs($,{variant:"primary",onClick:async()=>{const D=[];y&&y.querySelectorAll('input[type="checkbox"]:checked').forEach(O=>{D.push(O.value)});const Y=((M==null?void 0:M.value)||"").split(",").map(O=>O.trim()).filter(Boolean);try{const O=await T.put(`/agents/${encodeURIComponent(f.name)}`,{description:((N==null?void 0:N.value)||"").trim(),model:(v==null?void 0:v.value)||"",mode:(j==null?void 0:j.value)||"subagent",color:(E==null?void 0:E.value)||"",tools:D,tags:Y,category:(P==null?void 0:P.value)||"",prompt:(R==null?void 0:R.value)||""});c(Q=>Q.map(ae=>ae.name===f.name?O:ae)),a.success("Agent saved."),i.close(),await t()}catch(O){a.error(`Save failed: ${O.message}`)}},children:[e.jsx(Ms,{size:12})," Save"]})]})})}catch(C){a.error(`Load failed: ${C.message}`)}},k=async f=>{if(confirm(`Delete agent "${f.name}"? This removes ${f.path}.`))try{await T.del(`/agents/${encodeURIComponent(f.name)}`),c(N=>N.filter(v=>v.name!==f.name)),a.success("Agent deleted.")}catch(N){a.error(`Delete failed: ${N.message}`)}},w=async f=>{let N=null;i.open({title:`Invoke ${f.name}`,children:e.jsxs("div",{className:"invoke-form",children:[e.jsxs("p",{className:"muted invoke-form-meta mono",children:[f.model||"—"," · ",f.path]}),e.jsx("p",{className:"invoke-form-desc",children:f.description}),e.jsx("label",{className:"field-label",htmlFor:"invoke-prompt",children:"Prompt"}),e.jsx("textarea",{ref:v=>N=v,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($,{variant:"ghost",onClick:()=>i.close(),children:"Cancel"}),e.jsxs($,{variant:"primary",onClick:async()=>{const v=((N==null?void 0:N.value)||"").trim();if(!v){a.warning("Prompt is required.");return}try{await T.post(`/agents/${encodeURIComponent(f.name)}/invoke`,{prompt:v}),a.success(`Invoked ${f.name}.`),i.close()}catch(j){a.error(`Invoke failed: ${j.message}`)}},children:[e.jsx(bs,{size:14})," Invoke"]})]})})},S=async f=>{try{const N=await T.post(`/agents/${encodeURIComponent(f.name)}/restart`);c(v=>v.map(j=>j.name===f.name?N:j)),a.success(`${f.name} restarted.`)}catch(N){a.error(`Restart failed: ${N.message}`)}},A=async(f,N)=>{try{const v=await T.post(`/agents/${encodeURIComponent(f.name)}/status`,{status:N});c(j=>j.map(E=>E.name===f.name?v:E))}catch(v){a.error(`Status update failed: ${v.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(Ke,{size:18})," Agents (",x.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:u,onChange:f=>d(f.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:h,onChange:f=>p(f.target.value),children:[e.jsx("option",{value:"",children:"All categories"}),Ws.map(f=>e.jsx("option",{value:f.id,children:f.label},f.id)),e.jsx("option",{value:"__none__",children:"(no category)"})]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:m,children:[e.jsx(de,{size:14})," Refresh"]}),e.jsxs($,{variant:"primary",size:"sm",onClick:b,children:[e.jsx(be,{size:14})," New agent"]})]})]}),g.length>0&&e.jsxs("div",{className:"agent-tags-row",children:[e.jsx(ua,{size:12}),g.map(f=>e.jsx("span",{className:"tag",children:f},f))]}),o?e.jsx("div",{className:"view-loading",children:e.jsx(oe,{size:"lg"})}):x.length===0?e.jsx(pe,{icon:e.jsx(Ke,{size:32}),title:"No agents found",message:"Run bizar in the terminal to install Bizar."}):e.jsx("div",{className:"agent-grid",children:x.map(f=>e.jsx(gr,{agent:f,onInvoke:()=>w(f),onEdit:()=>z(f),onDelete:()=>k(f),onRestart:()=>S(f),onSetStatus:N=>A(f,N)},f.name))})]})}function gr({agent:s,onInvoke:t,onEdit:a,onDelete:i,onRestart:n,onSetStatus:c}){const[o,l]=r.useState(!1),h=ur(s.category),p=(s.status==="working"||!!s.currentTaskId)&&!s.isStuck;return e.jsxs(G,{variant:"elevated",interactive:!0,className:V("agent-card",p&&"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(hr,{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, ${h} 18%, transparent)`,color:h},children:s.category}),e.jsx(xr,{agent:s})]})]}),e.jsx("p",{className:"agent-card-desc",children:ia(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:Te(s.mtime)})]}),s.tags&&s.tags.length>0&&e.jsx("div",{className:"agent-card-tags",children:s.tags.map(u=>e.jsx("span",{className:"agent-card-tag",children:u},u))}),(p||s.lastTask)&&e.jsxs("div",{className:"agent-card-activity",children:[s.currentTaskId&&e.jsxs("div",{className:"agent-card-row",children:[e.jsx(De,{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(qe,{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:Te(s.lastTask.finishedAt)})]}),s.tasksTotal!=null&&s.tasksTotal>0&&e.jsxs("div",{className:"agent-card-row",children:[e.jsx(on,{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(ze,{size:12}),e.jsxs("span",{className:"muted",children:["Last error: ",s.lastError.message]})]}),e.jsxs("div",{className:"agent-card-actions",children:[e.jsxs($,{variant:"primary",size:"sm",onClick:t,children:[e.jsx(bs,{size:12})," Invoke"]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:a,children:[e.jsx(Ls,{size:12})," Edit"]}),(s.isStuck||s.status==="working"||s.status==="error")&&e.jsxs($,{variant:"ghost",size:"sm",onClick:n,title:"Reset agent status",children:[e.jsx(Zs,{size:12})," Restart"]}),e.jsx($,{variant:"ghost",size:"sm",onClick:i,children:e.jsx(we,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":o?"Collapse":"Expand",onClick:()=>l(u=>!u),style:{marginLeft:"auto"},children:o?e.jsx(We,{size:12}):e.jsx(Ye,{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($,{variant:s.status==="idle"?"primary":"ghost",size:"sm",onClick:()=>c("idle"),children:"Idle"}),e.jsx($,{variant:s.status==="working"?"primary":"ghost",size:"sm",onClick:()=>c("working"),children:"Working"}),e.jsx($,{variant:s.status==="error"?"primary":"ghost",size:"sm",onClick:()=>c("error"),children:"Error"})]}),e.jsxs("div",{className:"agent-card-meta",children:[e.jsx(Pe,{size:11}),e.jsx("code",{className:"mono agent-card-path",children:s.path})]})]})]})}function fr({id:s,children:t}){return e.jsx("div",{id:s,"data-block-id":s,className:V("glyph-richtext"),style:Ta,children:e.jsx(ka,{remarkPlugins:[wa],children:t})})}const jr={info:{bg:"var(--info-soft, rgba(96, 165, 250, 0.12))",border:"var(--info)",fg:"var(--info)",icon:zt,label:"Note"},warn:{bg:"var(--warning-soft, rgba(251, 191, 36, 0.15))",border:"var(--warning)",fg:"var(--warning)",icon:ze,label:"Warning"},success:{bg:"var(--success-soft, rgba(52, 211, 153, 0.15))",border:"var(--success)",fg:"var(--success)",icon:qe,label:"Success"},danger:{bg:"var(--error-soft, rgba(248, 113, 113, 0.12))",border:"var(--error)",fg:"var(--error)",icon:et,label:"Danger"}};function vr({id:s,tone:t="info",children:a}){const i=jr[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:{...Ta,fontSize:14},children:e.jsx(ka,{remarkPlugins:[wa],children:a})})]})]})}function yr({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(gs,{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 br({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 Nr({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 kr({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 wr({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:Kt,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:Kt}),c.kind==="multi"&&e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4},children:(c.options??[]).map(o=>{const l=a[c.id]??[],h=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:h,onChange:()=>{const p=h?l.filter(u=>u!==o):[...l,o];n(c.id,p)}}),e.jsx("span",{children:o})]},o)})})]},c.id))]})}const Kt={padding:"6px 10px",fontSize:13,borderRadius:6,border:"1px solid var(--border-strong)",background:"var(--bg)",color:"var(--text)",fontFamily:"inherit"},Sr={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 Cr({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=Sr[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 zr({id:s,filename:t,language:a,mode:i="unified",before:n,after:c}){const o=n.split(`
|
|
4
|
-
`),l=c.split(`
|
|
5
|
-
`),h=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(un,{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})]}),p={margin:0,padding:0,fontFamily:"var(--font-mono)",fontSize:12.5,lineHeight:1.55,color:"var(--text)",background:"var(--bg-elev)"},u=(d,m,x)=>{const g={del:"var(--error-soft)",add:"var(--success-soft)",ctx:"transparent"},b={del:"var(--error)",add:"var(--success)",ctx:"var(--text-dim)"};return e.jsxs("div",{style:{display:"flex",padding:"0 12px",background:g[x]},children:[e.jsx("span",{style:{width:18,color:b[x],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:[h,i==="unified"?e.jsxs("pre",{style:p,children:[o.map((d,m)=>e.jsx("div",{children:u("-",d,"del")},`b${m}`)),l.map((d,m)=>e.jsx("div",{children:u("+",d,"add")},`a${m}`))]}):e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr"},children:[e.jsx("pre",{style:{...p,borderRight:"1px solid var(--border)"},children:o.map((d,m)=>e.jsx("div",{children:u("-",d,"del")},m))}),e.jsx("pre",{style:p,children:l.map((d,m)=>e.jsx("div",{children:u("+",d,"add")},m))})]})]})}const Tr={up:{fg:"var(--success)",Icon:We,label:"trending up"},down:{fg:"var(--error)",Icon:We,label:"trending down"},flat:{fg:"var(--text-dim)",Icon:mn,label:"flat"}};function Rr({id:s,label:t,value:a,trend:i,hint:n}){const c=i?Tr[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===We&&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 $r={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)"}},Ae=160,Le=56,ds=60,ms=80;function Ar({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(Mr,{id:s})});const i=new Map(t.map(u=>[u.id,u])),n=Ir(t),c=Math.max(...n.map(u=>u.col))+1,o=Math.max(...n.map(u=>u.row))+1,l=c*(Ae+ds)+ds,h=o*(Le+ms)+ms;function p(u){if(!i.get(u))return null;const m=n.find(x=>x.id===u);return m?{x:ds+m.col*(Ae+ds)+Ae/2,y:ms+m.row*(Le+ms)+Le/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:h,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((u,d)=>{const m=p(u.from),x=p(u.to);if(!m||!x)return null;const g=x.x-m.x,b=x.y-m.y,z=g>=0?m.x+Ae/2:m.x-Ae/2,k=g>=0?x.x-Ae/2:x.x+Ae/2,w=b>=0?m.y+Le/2:m.y-Le/2,S=b>=0?x.y-Le/2:x.y+Le/2,A=(z+k)/2,f=(w+S)/2;return e.jsxs("g",{children:[e.jsx("line",{x1:z,y1:w,x2:k,y2:S,stroke:"var(--text-dim)",strokeWidth:1.5,markerEnd:`url(#arrow-${s})`}),u.label&&e.jsx("text",{x:A,y:f-4,fontSize:10,fill:"var(--text-dim)",textAnchor:"middle",fontFamily:"var(--font-mono)",children:u.label})]},d)}),t.map(u=>{const d=n.find(z=>z.id===u.id);if(!d)return null;const m=ds+d.col*(Ae+ds),x=ms+d.row*(Le+ms),g=$r[u.type];if(u.type==="decision"){const z=m+Ae/2,k=x+Le/2,w=[[z,x],[m+Ae,k],[z,x+Le],[m,k]].map(S=>S.join(",")).join(" ");return e.jsxs("g",{children:[e.jsx("polygon",{points:w,fill:g.fill,stroke:g.stroke,strokeWidth:2}),e.jsx("foreignObject",{x:m+8,y:k-14,width:Ae-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(cn,{size:11}),u.label]})})]},u.id)}const b=u.type==="note";return e.jsxs("g",{children:[e.jsx("rect",{x:m,y:x,width:Ae,height:Le,rx:8,fill:g.fill,stroke:g.stroke,strokeWidth:b?1:2,strokeDasharray:b?"4 3":void 0}),e.jsx("foreignObject",{x:m+6,y:x+6,width:Ae-12,height:Le-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:b?"italic":"normal",height:"100%"},children:[b&&e.jsx(dn,{size:11}),u.label]})})]},u.id)})]})})}function Mr({id:s}){return e.jsx("div",{id:s,style:{padding:20,textAlign:"center",color:"var(--text-dim)",fontSize:13},children:"No workflow steps."})}function Ir(s){return s.length===0?[]:s.map((t,a)=>({id:t.id,col:a,row:0}))}const Ta={fontSize:14,lineHeight:1.6,color:"var(--text)"};function Er({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 Lr extends Fe.Component{constructor(){super(...arguments);ws(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 Dr(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 Pr={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 Fr(s){const t=[];let a={heading:null,blocks:[]};for(const i of s){const n=Pr[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 Or({slug:s,onClose:t,onCommentAdded:a}){var B,Z,he,Se;const i=re(),[n,c]=r.useState(null),[o,l]=r.useState([]),[h,p]=r.useState(!0),[u,d]=r.useState(null),[m,x]=r.useState(null),[g,b]=r.useState(!1),[z,k]=r.useState(!1),[w,S]=r.useState(null),[A,f]=r.useState(null),[N,v]=r.useState(""),[j,E]=r.useState(null),[R,y]=r.useState([]),M=Fe.useCallback((W,se,ie)=>{y(me=>me.some(_=>_.blockId===W)?me:[...me,{blockId:W,blockType:se,message:ie.message||String(ie)}])},[]),P=r.useRef(null),C=r.useMemo(()=>n?Fr(n.blocks):[],[n]);r.useEffect(()=>{let W=!1;const se=5e3;return(async()=>{p(!0),d(null);try{const ie=new Promise((J,U)=>setTimeout(()=>U(new Error("Request timed out after 5s")),se)),[me,_]=await Promise.race([Promise.all([T.get(`/artifacts/${encodeURIComponent(s)}/render`),T.get(`/artifacts/${encodeURIComponent(s)}`)]),ie]);if(W)return;c(me);const L=(_==null?void 0:_.comments)??[];l(Array.isArray(L)?L:[])}catch(ie){if(!W){const me=ie.message;d(me),x(me)}}finally{W||p(!1)}})(),()=>{W=!0}},[s]);function D(W){if(!P.current)return;W.preventDefault();const se=P.current.getBoundingClientRect();S({x:W.clientX,y:W.clientY,worldX:W.clientX-se.left,worldY:W.clientY-se.top})}async function Y(){if(!(!A||!N.trim()))try{const W=await T.post(`/artifacts/${encodeURIComponent(s)}/comments`,{x:A.worldX,y:A.worldY,text:N.trim(),author:"drb0rk"});l(se=>[...se,{id:W.id??`cmt_${Date.now()}`,x:A.worldX,y:A.worldY,text:N.trim(),author:"drb0rk",created:new Date().toISOString()}]),f(null),v(""),S(null),a==null||a(),i.success("Comment added")}catch(W){i.error(`Failed to add comment: ${W.message}`)}}async function O(){if(!g){b(!0);try{const W=await T.post(`/artifacts/${encodeURIComponent(s)}/submit`,{answers:[],submitter:"drb0rk"});W!=null&&W.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(W){i.error(`Submit failed: ${W.message}`)}finally{b(!1)}}}function Q(){k(W=>!W)}const ae=W=>{const se=W.id,ie=W.data??{},me=Dr(W);return me.ok?e.jsx(Lr,{blockId:se,blockType:W.type,onError:M,children:ee(W,se,ie)},se):e.jsxs("div",{id:se,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:[W.type," block invalid"]}),e.jsxs("div",{style:{color:"var(--text-muted)",marginBottom:6},children:["block id: ",e.jsx("code",{children:se})]}),e.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:me.error})]},se)},ee=(W,se,ie)=>{switch(W.type){case"RichText":return e.jsx(fr,{id:se,children:W.childrenMarkdown??""},se);case"Callout":return e.jsx(vr,{id:se,tone:ie.tone??"info",children:W.childrenMarkdown??""},se);case"Checklist":return e.jsx(yr,{id:se,items:ie.items??[]},se);case"Table":return e.jsx(br,{id:se,columns:ie.columns??[],rows:ie.rows??[]},se);case"CodeTabs":return e.jsx(Nr,{id:se,tabs:ie.tabs??[]},se);case"Decision":return e.jsx(kr,{id:se,title:ie.title,question:ie.question,options:ie.options??[]},se);case"OpenQuestions":return e.jsx(wr,{id:se,questions:ie.questions??[]},se);case"FileTree":return e.jsx(Cr,{id:se,title:ie.title,entries:ie.entries??[]},se);case"Diff":return e.jsx(zr,{id:se,filename:ie.filename,language:ie.language,mode:ie.mode??"unified",before:ie.before??"",after:ie.after??""},se);case"Stat":return e.jsx(Rr,{id:se,label:ie.label??"",value:ie.value,trend:ie.trend,hint:ie.hint},se);case"Workflow":return e.jsx(Ar,{id:se,steps:ie.steps??[],connections:ie.connections},se);case"Mockup":return e.jsx(Er,{id:se,title:ie.title,x:ie.x,y:ie.y,w:ie.w,h:ie.h,html:ie.html??""},se);case"Diagram":return e.jsx("div",{id:se,className:"glyph-block-placeholder",children:e.jsxs("em",{children:["[Diagram] ",se]})},se)}};if(h)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(Br,{})," Loading glyph…"]})});if(u||!n)return e.jsxs("div",{className:"glyph-renderer glyph-renderer--error",children:[e.jsx("strong",{children:"Failed to load glyph."}),e.jsx("pre",{children:u??"unknown error"})]});const F=((B=n.frontmatter)==null?void 0:B.title)??s,H=((Z=n.frontmatter)==null?void 0:Z.status)??"draft",K=o.length;return e.jsxs("div",{className:`glyph-canvas ${z?"glyph-canvas--fullscreen":""}`,ref:P,onContextMenu:D,children:[e.jsxs("div",{className:"glyph-toolbar-floating",children:[e.jsxs("button",{className:"glyph-btn glyph-btn--primary glyph-btn--send",onClick:O,disabled:g,title:"Send comments + question answers to the agent — writes feedback.md, status=review",children:[e.jsx(Ze,{size:14}),e.jsx("span",{children:"Send to agent"}),e.jsx("span",{className:"glyph-btn-badge",children:K})]}),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(hn,{size:15})}),e.jsx("button",{className:"glyph-icon-btn",title:"Undo",disabled:!0,children:e.jsx(xn,{size:15})}),e.jsx("button",{className:"glyph-icon-btn",title:"Redo",disabled:!0,children:e.jsx(pn,{size:15})}),e.jsx("button",{className:"glyph-icon-btn",title:z?"Exit fullscreen":"Fullscreen",onClick:Q,children:e.jsx(gn,{size:15})}),e.jsx("button",{className:"glyph-icon-btn",title:"More",children:e.jsx(fn,{size:15})}),e.jsx("span",{className:"glyph-toolbar-divider"}),e.jsxs("button",{className:"glyph-icon-btn",title:"Comment count","aria-label":"Comment count",children:[e.jsx(Js,{size:15}),e.jsx("span",{className:"glyph-icon-btn-count",children:K})]}),t&&e.jsx("button",{className:"glyph-icon-btn glyph-icon-btn--close",title:"Close",onClick:t,"aria-label":"Close",children:e.jsx(Ne,{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:F}),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})]})]}),(R.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:R.length>0?`${R.length} block${R.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:[R.map((W,se)=>e.jsxs("li",{children:[e.jsx("strong",{children:W.blockType})," (",e.jsx("code",{children:W.blockId}),"): ",W.message]},`be-${se}`)),(Se=n.errors)==null?void 0:Se.map((W,se)=>e.jsxs("li",{children:[W.line?`line ${W.line}: `:"",W.message]},`ce-${se}`))]})]}),e.jsx("div",{className:"glyph-sections",children:C.map((W,se)=>e.jsxs("section",{className:`glyph-section ${W.heading?"glyph-section--headed":"glyph-section--plain"}`,children:[W.heading&&e.jsx("h2",{className:"glyph-section-heading",children:W.heading}),e.jsx("div",{className:"glyph-section-blocks",children:W.blocks.map(ae)})]},`sec-${se}-${W.heading??"ungrouped"}`))})]}),o.map(W=>e.jsxs("button",{className:`glyph-pin ${j===W.id?"glyph-pin--active":""}`,style:{left:W.x,top:W.y},onClick:se=>{se.stopPropagation(),E(j===W.id?null:W.id)},title:W.text,children:[e.jsx(Wt,{size:14}),j===W.id&&e.jsxs("div",{className:"glyph-pin-thread",children:[e.jsx("div",{className:"glyph-pin-text",children:W.text}),e.jsxs("div",{className:"glyph-pin-meta",children:[W.author??"anonymous"," · ",W.created?new Date(W.created).toLocaleString():""]})]})]},W.id)),w&&e.jsx("div",{className:"glyph-ctx-menu",style:{left:w.x,top:w.y},onClick:W=>W.stopPropagation(),children:e.jsxs("button",{className:"glyph-ctx-item",onClick:()=>{f({worldX:w.worldX,worldY:w.worldY}),S(null)},children:[e.jsx(Wt,{size:14})," Add comment here"]})}),A&&e.jsx("div",{className:"glyph-modal-overlay",onClick:()=>f(null),children:e.jsxs("div",{className:"glyph-modal",onClick:W=>W.stopPropagation(),children:[e.jsxs("h3",{children:["Add comment at (",Math.round(A.worldX),", ",Math.round(A.worldY),")"]}),e.jsx("textarea",{autoFocus:!0,value:N,onChange:W=>v(W.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:()=>f(null),children:"Cancel"}),e.jsx("button",{className:"glyph-btn glyph-btn--primary",onClick:Y,disabled:!N.trim(),children:"Add comment"})]})]})})]})}function Br(){return e.jsx("span",{className:"glyph-spinner","aria-label":"loading",children:"…"})}function Ur(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 _r({snapshot:s,refreshSnapshot:t}){const a=re(),[i,n]=r.useState(s.artifacts||[]),[c,o]=r.useState(!s.artifacts),[l,h]=r.useState(null),[p,u]=r.useState(""),[d,m]=r.useState(!1);r.useEffect(()=>{s.artifacts&&(n(s.artifacts),o(!1))},[s.artifacts]);const x=async()=>{try{const k=await T.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(p){const w=p.toLowerCase();k=k.filter(S=>(S.slug||"").toLowerCase().includes(w)||(S.title||"").toLowerCase().includes(w))}return d||(k=k.filter(w=>w.status!=="archived")),k},[i,p,d]),b=async(k,w)=>{try{const S=await T.post("/artifacts",{slug:k,title:w});a.success(`Artifact "${S.slug}" created.`),h(S.slug),await x()}catch(S){a.error(`Create failed: ${S.message}`)}},z=async k=>{if(confirm(`Delete artifact "${k}"? This removes the directory permanently.`))try{await T.del(`/artifacts/${encodeURIComponent(k)}`),a.success("Artifact deleted."),l===k&&h(null),await x()}catch(w){a.error(`Delete failed: ${w.message}`)}};return l?e.jsxs("div",{className:"artifact-glyph-overlay",children:[e.jsx("div",{className:"artifact-glyph-toolbar",children:e.jsxs($,{variant:"ghost",onClick:()=>{h(null),x()},children:[e.jsx(wt,{size:14})," Back to artifacts"]})}),e.jsx(Or,{slug:l,onClose:()=>{h(null),x()},onCommentAdded:()=>x()})]}):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(Gs,{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(ye,{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:p,onChange:k=>u(k.target.value),"aria-label":"Search artifacts"})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>m(k=>!k),title:d?"Hide archived":"Show archived",children:[d?e.jsx(ha,{size:14}):e.jsx(jn,{size:14}),d?"Hide archived":"Show archived"]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:x,children:[e.jsx(de,{size:14})," Refresh"]})]})]}),e.jsx(Wr,{onCreate:b}),c?e.jsx("div",{className:"view-loading",children:e.jsx(oe,{size:"lg"})}):g.length===0?e.jsx(pe,{icon:e.jsx(Gs,{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(qr,{artifact:k,onOpen:()=>h(k.slug),onDelete:()=>z(k.slug)},k.slug))})]})}function Wr({onCreate:s}){const[t,a]=r.useState(""),[i,n]=r.useState("");return e.jsxs(G,{className:"new-artifact",children:[e.jsxs(te,{children:[e.jsx(be,{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($,{variant:"primary",type:"submit",children:"Create"})]})]})}function qr({artifact:s,onOpen:t,onDelete:a}){const i=Ur(s.status||"draft");return e.jsxs(G,{variant:"elevated",interactive:!0,className:"artifact-card",onClick:t,children:[e.jsxs("div",{className:"artifact-card-head",children:[e.jsx("div",{className:"artifact-card-title",children:s.title||s.slug}),e.jsx(Qe,{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 ",Te(s.mtime)]})]}),e.jsxs("div",{className:"artifact-card-actions",children:[e.jsxs($,{variant:"primary",size:"sm",onClick:n=>{n.stopPropagation(),t()},children:["Open",e.jsx(Ye,{size:12})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:n=>{n.stopPropagation(),a()},children:[e.jsx(we,{size:12})," Delete"]})]})]})}function Vr({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 Hr({task:s,agents:t,onPromote:a,onDelete:i,onEdit:n,onRefresh:c}){var u;const o=re(),l=async()=>{try{await T.post(`/tasks/${encodeURIComponent(s.id)}/promote`),o.success("Promoted to queued.",1500),a(s.id)}catch(d){o.error(`Promote failed: ${d.message}`)}},h=async()=>{if(confirm("Delete this task?"))try{await T.del(`/tasks/${encodeURIComponent(s.id)}`),o.success("Deleted.",1500),i(s.id)}catch(d){o.error(`Delete failed: ${d.message}`)}},p={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:p[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]}),((u=s.tags)==null?void 0:u.length)>0&&e.jsx("span",{className:"backlog-item-badge",children:s.tags.join(", ")})]}),s.description&&e.jsx("div",{className:"backlog-item-desc",children:s.description.slice(0,120)}),e.jsxs("div",{className:"backlog-item-footer",children:[e.jsx("span",{className:"muted text-sm tabular-nums",children:Te(s.createdAt)}),e.jsxs("div",{className:"backlog-item-actions",children:[e.jsx("button",{type:"button",className:"icon-btn",title:"Promote to queued",onClick:l,children:e.jsx($t,{size:13})}),e.jsx("button",{type:"button",className:"icon-btn",title:"Edit",onClick:()=>n(s),children:e.jsx(Xe,{size:13})}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger",title:"Delete",onClick:h,children:e.jsx(we,{size:13})})]})]})]})}function Gr({agents:s,onRefresh:t}){const a=re(),[i,n]=r.useState([]),[c,o]=r.useState(!1),l=async()=>{try{o(!0);const m=await T.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 h=async m=>{n(x=>x.filter(g=>g.id!==m)),await t()},p=async m=>{n(x=>x.filter(g=>g.id!==m)),await t()},u=m=>{},d=async()=>{var m;if(i.length!==0)try{const g=((m=(await T.post("/tasks/promote-batch",{ids:i.map(b=>b.id)})).affected)==null?void 0:m.filter(b=>b.ok).length)??0;a.success(`Promoted ${g} task(s).`,2e3),n([]),await t()}catch(x){a.error(`Promote all failed: ${x.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(Ys,{size:15}),"Backlog (",i.length,")"]}),e.jsxs("div",{className:"backlog-panel-header-actions",children:[i.length>0&&e.jsxs($,{variant:"ghost",size:"sm",onClick:d,title:"Promote all to queued",children:[e.jsx($t,{size:12})," Promote all"]}),e.jsx($,{variant:"ghost",size:"sm",onClick:l,title:"Refresh backlog","aria-label":"Refresh backlog",children:e.jsx(de,{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(Ys,{size:28}),e.jsx("span",{children:"Backlog is empty."})]}):e.jsx("div",{className:"backlog-list",children:i.map(m=>e.jsx(Hr,{task:m,agents:s,onPromote:h,onDelete:p,onEdit:u,onRefresh:t},m.id))})]})}const qs=[{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"}],Pt=["low","normal","high"];function Kr({snapshot:s,refreshSnapshot:t,setActiveTab:a}){const i=re(),n=Re(),[c,o]=r.useState(s.tasks||[]),[l,h]=r.useState(!s.tasks),[p,u]=r.useState(""),[d,m]=r.useState(""),[x,g]=r.useState(!1),[b,z]=r.useState(0),[k,w]=r.useState(""),S=async()=>{try{const y=await T.get("/tasks");o(Array.isArray(y)?y:[])}catch(y){i.error(`Tasks load failed: ${y.message}`)}finally{h(!1)}};r.useEffect(()=>{s.tasks&&(o(s.tasks),h(!1))},[s.tasks]),r.useEffect(()=>{const y=setInterval(()=>z(M=>M+1),3e4);return()=>clearInterval(y)},[]);const A=r.useMemo(()=>{let y=c.filter(M=>M.status!=="backlog");if(d&&(y=y.filter(M=>(M.priority||"normal")===d)),p.trim()){const M=p.toLowerCase();y=y.filter(P=>(P.title||"").toLowerCase().includes(M)||(P.description||"").toLowerCase().includes(M))}return y},[c,p,d]),f=r.useMemo(()=>{const y={high:0,normal:1,low:2};return[...A].sort((M,P)=>{const C=y[M.priority]??1,D=y[P.priority]??1;return C!==D?C-D:new Date(P.createdAt).getTime()-new Date(M.createdAt).getTime()})},[A]),N=c.filter(y=>y.status==="backlog").length,v=async(y,M)=>{const P=c.find(D=>D.id===y);if(!P)return;const C=P.status;o(D=>D.map(Y=>Y.id===y?{...Y,status:M}:Y)),w(`Task ${P.title} moved to ${M}.`);try{await T.patch(`/tasks/${encodeURIComponent(y)}/status`,{status:M}),i.success(`Moved to ${M}.`,1200)}catch(D){o(Y=>Y.map(O=>O.id===y?{...O,status:C}:O)),w(`Failed to move task ${P.title}: ${D.message}`),i.error(`Move failed: ${D.message}`)}},j=async y=>{if(confirm("Delete this task?"))try{await T.del(`/tasks/${encodeURIComponent(y)}`),o(M=>M.filter(P=>P.id!==y)),i.success("Task deleted.",1200)}catch(M){i.error(`Delete failed: ${M.message}`)}},E=async y=>{try{const M=await T.post(`/tasks/${encodeURIComponent(y)}/start`);M&&M.task&&o(P=>P.map(C=>C.id===y?M.task:C)),i.success("Retry dispatched.",1200)}catch(M){i.error(`Retry failed: ${M.message}`)}},R=async y=>{const M=c.find(P=>P.id===y);if(M)try{const P=await T.post("/tasks/submit",{title:M.title,description:M.description,priority:M.priority,tags:M.tags}),C=(P.subtasks||[]).length;i.success(C>1?`Odin split it into ${C} subtasks.`:"Sent to Odin.",1500),P.subtasks&&P.subtasks.length>0&&o(D=>[P.main,...P.subtasks,...D.filter(Y=>Y.id!==M.id)]),await t()}catch(P){i.error(`Submit failed: ${P.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($s,{size:18})," Tasks (",f.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(ye,{size:12,"aria-hidden":!0}),e.jsx("input",{className:"input",type:"text",placeholder:"Search…",value:p,onChange:y=>u(y.target.value),"aria-label":"Search tasks"}),p&&e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Clear search",onClick:()=>u(""),children:e.jsx(Ne,{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:y=>m(y.target.value),title:"Filter by priority",children:[e.jsx("option",{value:"",children:"All"}),Pt.map(y=>e.jsx("option",{value:y,children:y},y))]})]}),e.jsx("div",{className:"tasks-toolbar-spacer"}),e.jsxs("div",{className:"tasks-toolbar-group",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:S,title:"Refresh","aria-label":"Refresh tasks",children:e.jsx(de,{size:14})}),N>0&&e.jsxs($,{variant:x?"accent":"ghost",size:"sm",onClick:()=>g(y=>!y),title:x?"Hide backlog":"Show backlog",children:[e.jsx(Ys,{size:14}),"Backlog",e.jsx("span",{className:"badge",children:N})]}),e.jsxs($,{variant:"primary",size:"sm",onClick:()=>Qr(n,i,o,S,t),children:[e.jsx(be,{size:14})," New task"]})]})]}),x&&N>0&&e.jsx(Gr,{agents:s.agents||[],onRefresh:t}),l?e.jsx("div",{className:"view-loading",children:e.jsx(oe,{size:"lg"})}):e.jsx("div",{className:"kanban",children:qs.map(y=>e.jsx(Yr,{column:y,tasks:f.filter(M=>M.status===y.id),onMove:v,onDelete:j,onRetry:E,onEdit:M=>Jr(n,i,M,o,S,t),onSubmitToOdin:R,tick:b},y.id))})]})}function Yr({column:s,tasks:t,onMove:a,onDelete:i,onRetry:n,onEdit:c,onSubmitToOdin:o,tick:l}){const[h,p]=r.useState(!1);return e.jsxs("div",{className:V("kanban-column",h&&"kanban-column-drop"),"data-column":s.id,onDragOver:u=>{u.preventDefault(),p(!0)},onDragLeave:()=>p(!1),onDrop:u=>{u.preventDefault(),p(!1);const d=u.dataTransfer.getData("text/task-id");d&&a(d,s.id)},children:[e.jsxs("div",{className:"kanban-col-header",children:[e.jsxs(te,{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(u=>e.jsx(Xr,{task:u,onMove:d=>{const x=qs.findIndex(g=>g.id===u.status)+d;x>=0&&x<qs.length&&a(u.id,qs[x].id)},onEdit:()=>c(u),onDelete:()=>i(u.id),onRetry:()=>n(u.id),onSubmitToOdin:()=>o(u.id),tick:l},u.id))})]})}function Xr({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:h=>{h.dataTransfer.setData("text/task-id",s.id),h.dataTransfer.effectAllowed="move"},"data-tick":o,children:[e.jsxs("div",{className:"task-card-head",children:[e.jsx("span",{className:"priority-dot",style:{background:Va[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(Ke,{size:10})," @",l]}),s.timeSpent?e.jsxs("span",{className:"task-card-badge",children:[e.jsx(ns,{size:10})," ",Math.round((s.timeSpent||0)/60),"m"]}):null,s.tags&&s.tags.length>0&&s.tags.slice(0,3).map(h=>e.jsx(Vr,{children:h},h))]}),e.jsxs("div",{className:"task-card-footer",children:[e.jsx("span",{className:"task-card-time tabular-nums muted",children:Te(s.createdAt)}),e.jsxs("div",{className:"task-card-actions",onClick:h=>h.stopPropagation(),children:[e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Move left",title:"Move left",onClick:()=>t(-1),children:e.jsx(vn,{size:14})}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Edit",title:"Edit",onClick:a,children:e.jsx(yn,{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(Ze,{size:14})}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Retry",title:"Retry",onClick:n,children:e.jsx(Zs,{size:14})}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger","aria-label":"Delete",title:"Delete",onClick:i,children:e.jsx(we,{size:14})}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Move right",title:"Move right",onClick:()=>t(1),children:e.jsx(Ye,{size:14})})]})]})]})}function Qr(s,t,a,i,n){let c=null,o=null,l=null,h=null;const p=async d=>{d&&typeof d.preventDefault=="function"&&d.preventDefault();const m=((c==null?void 0:c.value)||"").trim(),x=((o==null?void 0:o.value)||"").trim();if(!m){t.warning("Title is required."),c==null||c.focus();return}const g=(h==null?void 0:h.value)||"normal",b=((l==null?void 0:l.value)||"").split(",").map(z=>z.trim()).filter(Boolean);try{const z=await T.post("/tasks",{title:m,description:x,priority:g,tags:b});s.close(),typeof window<"u"&&window.dispatchEvent(new MouseEvent("mousedown")),a(k=>[z,...k]),t.success("Task created.",1200),await n()}catch(z){t.error(`Create failed: ${z.message}`)}},u=d=>{d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),p(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:u}),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 qa(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=>{h=d},id:"task-priority",className:"select",defaultValue:"normal",children:Pt.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($,{variant:"ghost",onClick:()=>s.close(),children:"Cancel"}),e.jsxs($,{variant:"primary",type:"button",onClick:d=>p(d),children:[e.jsx(be,{size:14})," Create task"]})]})})}function Jr(s,t,a,i,n,c){let o=null,l=null,h=null,p=null;const u=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 x=(p==null?void 0:p.value)||"normal",g=((h==null?void 0:h.value)||"").split(",").map(b=>b.trim()).filter(Boolean);try{const b=await T.put(`/tasks/${encodeURIComponent(a.id)}`,{title:d,description:m,priority:x,tags:g});s.close(),typeof window<"u"&&window.dispatchEvent(new MouseEvent("mousedown")),i(z=>z.map(k=>k.id===a.id?b:k)),t.success("Task updated.",1200),await c()}catch(b){t.error(`Save failed: ${b.message}`)}};s.open({title:"Edit task",width:520,children:e.jsxs("div",{className:"task-form",children:[e.jsx("label",{className:"field-label",htmlFor:"edit-task-title",children:"Title *"}),e.jsx("input",{ref: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=>{p=d},id:"edit-task-priority",className:"select",defaultValue:a.priority||"normal",children:Pt.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=>{h=d},id:"edit-task-tags",className:"input",type:"text",defaultValue:(a.tags||[]).join(", "),placeholder:"comma-separated"})]})]}),e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsx(ua,{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($,{variant:"ghost",onClick:()=>s.close(),children:"Cancel"}),e.jsxs($,{variant:"primary",onClick:u,children:[e.jsx(ha,{size:14})," Save"]})]})})}const Zr=Fe.memo(Kr);function el(s){return T.urlWithToken(`/artifacts/${encodeURIComponent(s)}/content`)}function sl(s,t){const a=el(t);window.open(a,"_blank","noopener,noreferrer")}const Yt={"1m":60*1e3,"5m":5*60*1e3,"30m":30*60*1e3,"1h":60*60*1e3},Me=56,Ve=32,us=22,tl=4,al=.9,rt={working:"var(--success)",running:"var(--success)",doing:"var(--info)",queued:"var(--info)",done:"var(--success)",success:"var(--success)",blocked:"var(--warning)",error:"var(--error)",failed:"var(--error)",stuck:"var(--warning)",killed:"var(--error)",idle:"var(--text-dim)",pending:"var(--info)",timed_out:"var(--warning)"};function lt(s){return s&&rt[s]||rt.idle}function Os(s,t=24){return s?s.length<=t?s:s.slice(0,t-1)+"…":""}function Qs(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 ot(s){const t=s._timerStart;return typeof t=="number"&&t>0?t:Qs(s.createdAt)||Date.now()}function nl(s,t){return(s.status==="done"||s.status==="archived"||s.status==="failed"||s.status==="killed")&&(Qs(s.completedAt)||Qs(s.updatedAt))||t}function il(s){return typeof s.startedAt=="number"&&s.startedAt>0?s.startedAt:Date.now()}function rl(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 ll(s){return s<=6e4?1e4:s<=3e5?3e4:s<=18e5?3e5:6e5}function ol(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 cl({snapshot:s,refreshSnapshot:t}){const a=re(),i=r.useRef(null),[n,c]=r.useState("live"),[o,l]=r.useState("5m"),[h,p]=r.useState(()=>typeof window>"u"?!0:window.innerWidth>900),[u,d]=r.useState([]),[m,x]=r.useState([]),[g,b]=r.useState(!0),[z,k]=r.useState(0),[w,S]=r.useState(Date.now()),[A,f]=r.useState(()=>Date.now()-Yt["5m"]*.1),[N,v]=r.useState({width:800,height:400}),[j,E]=r.useState(null),[R,y]=r.useState(""),[M,P]=r.useState([]),[C,D]=r.useState(""),[Y,O]=r.useState("normal"),[Q,ae]=r.useState(""),[ee,F]=r.useState(""),[H,K]=r.useState(!1),[B,Z]=r.useState(!1),[he,Se]=r.useState([]),W=Re(),se=s.agents||[],ie=s.tasks||[],me=Yt[o],_=A,L=A+me,J=r.useCallback(async()=>{try{const[I,X]=await Promise.all([T.get("/background").catch(()=>({instances:[]})),T.get("/activity?limit=200").catch(()=>({events:[]}))]);d(I.instances||[]),x(X.events||[])}catch(I){console.warn("activity reload failed:",I)}finally{b(!1)}},[]);r.useEffect(()=>{J();const I=setInterval(J,3e3);return()=>clearInterval(I)},[J]),r.useEffect(()=>{k(I=>I+1)},[ie.length,se.length]),r.useEffect(()=>{if(n==="pause")return;S(Date.now());const I=setInterval(()=>S(Date.now()),1e3);return()=>clearInterval(I)},[n,z]),r.useEffect(()=>{if(n==="pause")return;(w-A)/me>al&&f(w-me*.1)},[w,A,me,n]),r.useEffect(()=>{f(Date.now()-me*.1)},[o]),r.useEffect(()=>{n==="live"&&f(Date.now()-me*.1)},[n]),r.useLayoutEffect(()=>{const I=i.current;if(!I)return;const X=new ResizeObserver(ge=>{for(const fe of ge){const{width:ue,height:je}=fe.contentRect;v({width:Math.max(200,Math.floor(ue)),height:Math.max(120,Math.floor(je))})}});return X.observe(I),()=>X.disconnect()},[]);const U=r.useMemo(()=>{const I=[];let X=0;for(const ue of u){const je=il(ue),Ee=rl(ue,w);Ee<_||je>L||I.push({kind:"bg",id:`bg:${ue.instanceId}`,index:X++,label:`BG ${Os(ue.promptPreview,20)||ue.instanceId.slice(0,10)}`,sub:ue.status||"pending",start:je,end:Ee,data:ue})}const ge=[...ie].sort((ue,je)=>ot(ue)-ot(je)),fe=[];for(const ue of ge){const je=ot(ue),Ee=nl(ue,w);if(Ee<_||je>L)continue;let cs=-1;for(let es=0;es<fe.length;es++)if(fe[es]<=je){fe[es]=Ee,cs=es;break}cs===-1&&(fe.push(Ee),cs=fe.length-1),I.push({kind:"task",id:`task:${ue.id}`,index:X+cs,label:Os(ue.title,32),sub:ue.status,start:je,end:Ee,data:ue})}return I},[u,ie,w,_,L]),le=r.useMemo(()=>{const I=new Map;for(const X of U)I.set(X.id,X);return I},[U]),q=r.useCallback(I=>me<=0?0:(I-_)/me*N.width,[_,me,N.width]),ce=r.useMemo(()=>{const I=ll(me),X=[],ge=Math.floor(_/I)*I;for(let fe=ge;fe<=L+I;fe+=I){if(fe<_-I)continue;if(fe>L)break;const ue=q(fe);ue<-40||ue>N.width+40||X.push({t:fe,x:ue,label:ol(fe,me)})}return X},[_,L,me,N.width,q]),$e=r.useMemo(()=>{const I=[];for(const X of U){if(X.kind==="events")continue;const ge=Math.max(X.start,_),fe=Math.min(X.end,L);if(fe<_||ge>L)continue;const ue=q(ge),je=q(fe),Ee=Math.max(tl,je-ue),cs=Ve+us+X.index*Me+8,es=Me-16;let Be="doing";if(X.kind==="bg"){const Ce=X.data.status||"pending";Ce==="done"||Ce==="success"?Be="done":Ce==="failed"||Ce==="killed"||Ce==="error"?Be="failed":Ce==="queued"||Ce==="pending"?Be="queued":Ce==="blocked"||Ce==="stuck"?Be="blocked":Be="doing"}else{const Ce=X.data.status;Ce==="done"||Ce==="archived"?Be="done":Ce==="failed"||Ce==="killed"?Be="failed":Ce==="queued"?Be="queued":Ce==="blocked"?Be="blocked":Be="doing"}const Ua=(j==null?void 0:j.id)===X.id;I.push({id:X.id,laneIndex:X.index,x:ue,y:cs,w:Ee,h:es,label:X.label,statusClass:Be,selected:Ua,data:X.data,kind:X.kind,start:X.start,end:X.end})}return I},[U,q,j,_,L]),Ie=r.useMemo(()=>{const I=[];for(const X of m){const ge=Qs(X.ts);if(ge<_-5e3||ge>L+5e3)continue;const fe=q(ge);let ue=Ve+12;if(X.taskId){const je=le.get(`task:${X.taskId}`);je&&(ue=Ve+us+je.index*Me+Me/2)}else if(X.nodeId){const je=String(X.nodeId),Ee=le.get(je.startsWith("task:")||je.startsWith("bg:")?je:`task:${je}`);Ee&&(ue=Ve+us+Ee.index*Me+Me/2)}I.push({id:`${X.ts}-${X.kind}-${X.author??""}-${X.taskId??""}`,x:fe,y:ue,kind:X.kind||"event",ts:ge,text:String(X.text||X.kind||""),author:X.author})}return I},[m,_,L,q,le]),Oe=r.useMemo(()=>U.map(I=>({id:I.id,y:Ve+us+I.index*Me,h:Me})),[U]),He=r.useMemo(()=>{const I=q(w);return Math.max(0,Math.min(N.width,I))},[q,w,N.width]),Ds=r.useCallback(I=>{const ge={id:I.id,kind:I.kind,label:I.label,status:I.statusClass,data:I.data};E(ge)},[]);r.useEffect(()=>{if(!j){P([]),F(""),Se([]);return}y(""),D(""),ae(""),Se([]),(async()=>{try{const I=await T.get(`/activity?nodeId=${encodeURIComponent(j.id)}&limit=50`);P(I.events||[])}catch{P([])}if(j.kind==="bg"){const I=j.data;try{const X=await T.get(`/background/${encodeURIComponent(I.instanceId)}/output?lines=80`);F(X.output||"")}catch{F("")}if(I.taskId)try{const X=await T.get(`/tasks/${encodeURIComponent(I.taskId)}/artifacts`);Se((X.artifacts||[]).map(ge=>ge.id))}catch{Se([])}}})()},[j]);const Ns=async()=>{if(!(!j||!R.trim())){Z(!0);try{await T.post("/comments",{nodeId:j.id,text:R,author:"user"}),y("");const I=await T.get(`/activity?nodeId=${encodeURIComponent(j.id)}&limit=50`);P(I.events||[]),a.success("Comment added.")}catch(I){a.error(`Comment failed: ${I.message}`)}finally{Z(!1)}}},Ps=async()=>{if(!(!j||!C.trim())){K(!0);try{await T.post(`/nodes/${encodeURIComponent(j.id)}/tasks`,{title:C,description:`Created from timeline selection ${j.id}.`,priority:Y}),D(""),a.success("Task created."),await t()}catch(I){a.error(`Task create failed: ${I.message}`)}finally{K(!1)}}},ks=async()=>{if(!j||j.kind!=="bg"||!Q.trim())return;const I=j.data;try{const X=await T.post(`/background/${encodeURIComponent(I.instanceId)}/message`,{message:Q});X.ok?(a.success("Message sent."),ae("")):a.warning(X.error||"Send failed")}catch(X){a.error(`Send failed: ${X.message}`)}},Fa=async()=>{if(!j||j.kind!=="bg"||!confirm("Kill this bg instance session?"))return;const I=j.data;try{const X=await T.del(`/background/${encodeURIComponent(I.instanceId)}`);X.ok?a.success("Session killed."):a.warning(X.error||"Kill failed"),await J()}catch(X){a.error(`Kill failed: ${X.message}`)}},Oa=async()=>{if(!j||j.kind!=="bg")return;const I=j.data;try{const X=await T.get(`/background/${encodeURIComponent(I.instanceId)}/output?lines=80`);F(X.output||"")}catch{}};r.useEffect(()=>{const I=X=>{X.key==="Escape"&&E(null)};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[]);const Ba=()=>{k(I=>I+1),J()},st=Ve+us+U.length*Me;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(De,{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($,{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(At,{size:14}):e.jsx(bs,{size:14}),n==="live"?"Live":"Paused"]}),e.jsx("div",{className:"tl-zoom-group",children:["1m","5m","30m","1h"].map(I=>e.jsx("button",{type:"button",className:V("tl-zoom-btn",o===I&&"tl-zoom-btn-active"),onClick:()=>l(I),title:`Zoom to ${I}`,children:I},I))}),e.jsxs($,{variant:"secondary",size:"sm",onClick:Ba,title:"Refresh",children:[e.jsx(de,{size:14})," Refresh"]})]})})]}),g&&e.jsx("div",{className:"view-loading",children:e.jsx(oe,{size:"lg"})}),!g&&se.length===0&&ie.length===0&&u.length===0&&m.length===0?e.jsx(pe,{icon:e.jsx(De,{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",j&&"tl-view-detail-open"),children:e.jsxs("div",{className:V("tl-body",!h&&"tl-body-stream-collapsed"),children:[e.jsxs("aside",{className:V("tl-stream",!h&&"tl-stream-collapsed"),children:[e.jsxs("div",{className:"tl-stream-head",children:[e.jsxs("h3",{children:[e.jsx(As,{size:13})," Live events"]}),e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>p(!1),title:"Hide event stream","aria-label":"Hide event stream",children:e.jsx(bn,{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(Dt,{items:[...m].reverse(),itemHeight:40,height:400,className:"tl-stream-virtual",renderItem:I=>{const X=I.author?Ke:I.kind==="task"?$s:I.kind==="bg"?_s:De;return e.jsxs("div",{className:"tl-stream-event",children:[e.jsx("span",{className:"tl-stream-event-time",children:new Date(I.ts).toLocaleTimeString("en-GB",{hour12:!1})}),e.jsx("span",{className:"tl-stream-event-icon",style:{color:lt(I.kind)},children:e.jsx(X,{size:12})}),e.jsx("span",{className:"tl-stream-event-text",children:I.author||I.text||I.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:[!h&&e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>p(!0),title:"Show event stream",children:[e.jsx(Nn,{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(L).toLocaleTimeString("en-GB",{hour12:!1})]})]}),e.jsxs("div",{className:"tl-canvas-legend",children:[e.jsxs("span",{className:"tl-legend-item",children:[e.jsx("span",{className:"tl-legend-dot",style:{background:"var(--success)"}})," active"]}),e.jsxs("span",{className:"tl-legend-item",children:[e.jsx("span",{className:"tl-legend-dot tl-legend-dot-dashed",style:{borderColor:"var(--info)"}})," queued"]}),e.jsxs("span",{className:"tl-legend-item",children:[e.jsx("span",{className:"tl-legend-dot",style:{background:"var(--warning)"}})," blocked"]}),e.jsxs("span",{className:"tl-legend-item",children:[e.jsx("span",{className:"tl-legend-dot",style:{background:"var(--error)"}})," error"]}),e.jsx("span",{className:"tl-legend-sep"}),e.jsxs("span",{className:"tl-legend-item",children:[e.jsx(kn,{size:11})," agent"]}),e.jsxs("span",{className:"tl-legend-item",children:[e.jsx(wn,{size:11})," task"]}),e.jsxs("span",{className:"tl-legend-item",children:[e.jsx(_s,{size:11})," bg"]})]})]}),e.jsx("div",{className:"tl-canvas-scroll",children:e.jsxs("svg",{className:"tl-canvas",width:N.width,height:Math.max(N.height,st),role:"application","aria-label":"Activity timeline",children:[e.jsx("defs",{children:e.jsx("pattern",{id:"tl-canvas-grid",width:N.width,height:Me,patternUnits:"userSpaceOnUse",children:e.jsx("path",{d:`M 0 0 L 0 ${Me}`,fill:"none",stroke:"var(--border)",strokeWidth:.5,opacity:.35})})}),e.jsx("rect",{width:"100%",height:"100%",fill:"url(#tl-canvas-grid)"}),Oe.map(I=>e.jsx("rect",{className:"tl-lane-bg",x:0,y:I.y,width:N.width,height:I.h,fill:I.id.charCodeAt(I.id.length-1)%2===0?"var(--bg-elev-2)":"var(--bg-elev)",opacity:.4},`bg-${I.id}`)),e.jsx("g",{className:"tl-time-axis",children:ce.map(I=>e.jsxs("g",{children:[e.jsx("line",{x1:I.x,y1:0,x2:I.x,y2:st,stroke:"var(--border)",strokeWidth:.5,strokeDasharray:"2,4",opacity:.5}),e.jsx("text",{x:I.x+4,y:Ve-8,fontSize:10,fontFamily:"var(--font-mono)",fill:"var(--text-dim)",children:I.label})]},`tick-${I.t}`))}),U.map(I=>{const X=Ve+us+I.index*Me+Me/2;return e.jsxs("g",{className:"tl-lane-label-group",children:[e.jsx("text",{x:6,y:X-2,className:"tl-lane-label",textAnchor:"start",children:Os(I.label,28)}),e.jsx("text",{x:6,y:X+10,className:"tl-lane-label-sub",textAnchor:"start",children:I.sub})]},`label-${I.id}`)}),$e.map(I=>{const X=lt(I.statusClass),ge=I.id===(j==null?void 0:j.id);return e.jsxs("g",{className:V("tl-task-bar",`tl-task-bar-${I.statusClass}`,ge&&"tl-task-bar-selected"),onClick:()=>Ds(I),children:[e.jsx("rect",{x:I.x,y:I.y,width:I.w,height:I.h,rx:6,fill:X,fillOpacity:I.statusClass==="done"?.35:I.statusClass==="queued"?.18:.85,stroke:X,strokeWidth:ge?2.5:1.5,strokeOpacity:I.statusClass==="done"?.5:1,strokeDasharray:I.statusClass==="queued"?"4 4":void 0,style:{cursor:"pointer"}}),I.w>36&&e.jsx("text",{x:I.x+8,y:I.y+I.h/2+4,fontSize:11,fontFamily:"var(--font-sans)",fontWeight:500,fill:"var(--text-strong)",style:{pointerEvents:"none"},opacity:I.statusClass==="done"?.7:1,children:Os(I.label,Math.max(4,Math.floor(I.w/7)))})]},`bar-${I.id}`)}),Ie.map(I=>{const X=lt(I.kind);return e.jsxs("g",{className:"tl-event-marker-group",children:[e.jsx("line",{x1:I.x,y1:I.y-6,x2:I.x,y2:I.y+6,stroke:X,strokeWidth:1.2,opacity:.7}),e.jsx("circle",{cx:I.x,cy:I.y,r:4,fill:X,opacity:.9,children:e.jsx("title",{children:`${I.kind}${I.author?` · ${I.author}`:""} · ${new Date(I.ts).toLocaleTimeString("en-GB",{hour12:!1})}`})})]},`ev-${I.id}`)}),e.jsx("line",{className:"tl-now-line",x1:He,y1:0,x2:He,y2:st,stroke:"var(--error)",strokeWidth:1.5,opacity:.9}),e.jsxs("g",{className:"tl-now-marker",children:[e.jsx("circle",{cx:He,cy:Ve-4,r:4,fill:"var(--error)"}),e.jsx("text",{x:He+6,y:Ve-4,fontSize:10,fontWeight:700,fill:"var(--error)",fontFamily:"var(--font-mono)",children:"now"})]})]})})]}),j&&e.jsx("aside",{className:"tl-detail tl-detail-enter",children:e.jsxs(G,{children:[e.jsxs(te,{children:[j.kind==="agent"&&e.jsx(Ke,{size:14}),j.kind==="task"&&e.jsx($s,{size:14}),j.kind==="bg"&&e.jsx(_s,{size:14}),j.label,e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>E(null),title:"Close","aria-label":"Close activity detail",style:{marginLeft:"auto"},children:e.jsx(Ne,{size:14})})]}),e.jsxs("div",{className:"tl-detail-meta",children:[e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"type"})," ",j.kind]}),e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"status"})," ",e.jsx("code",{children:j.status})]}),j.kind==="agent"&&(()=>{const I=j.data;return e.jsxs(e.Fragment,{children:[I.role&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"role"})," ",I.role]}),I.model&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"model"})," ",I.model]})]})})(),j.kind==="task"&&(()=>{const I=j.data;return e.jsxs(e.Fragment,{children:[I.assignee&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"assignee"})," @",I.assignee]}),I.priority&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"priority"})," ",I.priority]}),I.createdAt&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"created"})," ",new Date(I.createdAt).toLocaleString()]})]})})(),j.kind==="bg"&&(()=>{const I=j.data;return e.jsxs(e.Fragment,{children:[I.startedAt&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"started"})," ",new Date(I.startedAt).toLocaleString()]}),I.tmuxSession&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"tmux"})," ",e.jsx("code",{children:I.tmuxSession})," ",I.tmuxActive?e.jsx("span",{className:"tag tag-success",children:"active"}):e.jsx("span",{className:"tag",children:"inactive"})]})]})})()]}),j.kind==="task"&&j.data.description&&e.jsx("div",{className:"tl-detail-desc",children:j.data.description}),j.kind==="bg"&&j.data.promptPreview&&e.jsx("div",{className:"tl-detail-desc",children:j.data.promptPreview}),j.kind==="bg"&&e.jsxs("div",{className:"tl-detail-bg",children:[e.jsx("pre",{className:"tl-bg-output",children:ee||"(no output — start the session via tmux attach)"}),e.jsxs("div",{className:"tl-bg-output-actions",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:Oa,children:[e.jsx(de,{size:12})," Refresh output"]}),he.length>0&&e.jsxs($,{variant:"secondary",size:"sm",onClick:()=>sl(W,he[0]),children:[e.jsx(ke,{size:12})," Open artifact"]}),e.jsxs($,{variant:"danger",size:"sm",onClick:Fa,children:[e.jsx(we,{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:Q,onChange:I=>ae(I.target.value),onKeyDown:I=>{I.key==="Enter"&&ks()},"aria-label":"Send a message to this bg session"}),e.jsxs($,{variant:"primary",size:"sm",disabled:!Q.trim(),onClick:ks,children:[e.jsx(Ze,{size:12})," Send"]})]})]}),j.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:C,onChange:I=>D(I.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:I=>O(I.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($,{variant:"primary",size:"sm",disabled:!C.trim()||H,onClick:Ps,children:[e.jsx(be,{size:12})," Add task"]})]})]}),e.jsxs("div",{className:"tl-detail-comments",children:[e.jsxs("div",{className:"field-label",children:[e.jsx(Js,{size:12})," Comments & activity"]}),e.jsxs("ul",{className:"comment-list",children:[M.length===0&&e.jsx("li",{className:"muted",children:"No comments yet."}),M.map((I,X)=>e.jsxs("li",{className:"comment-item",children:[e.jsxs("div",{className:"comment-head",children:[e.jsx("strong",{children:I.author||"system"}),e.jsxs("span",{className:"muted",children:[I.kind," · ",new Date(I.ts).toLocaleString()]})]}),I.text&&e.jsx("div",{className:"comment-text",children:I.text}),I.taskId&&e.jsxs("div",{className:"muted",children:["→ task ",e.jsx("code",{children:String(I.taskId)})]})]},`c-${X}`))]}),e.jsxs("div",{className:"comment-input-row",children:[e.jsx("label",{htmlFor:"comment-input",className:"sr-only",children:"Add a comment"}),e.jsx("input",{id:"comment-input",className:"input",placeholder:"Add a comment…",value:R,onChange:I=>y(I.target.value),onKeyDown:I=>{I.key==="Enter"&&!I.shiftKey&&Ns()},"aria-label":"Add a comment"}),e.jsxs($,{variant:"secondary",size:"sm",disabled:!R.trim()||B,onClick:Ns,children:[e.jsx(Ze,{size:12})," Post"]})]})]})]})},j.id)]})})]})}function dl(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 ct(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 dl(s,t.substring(0,i))<=2?40:t.includes(s)?30:0}function ml(s,t){const a=s.toLowerCase().trim();return a?t.map(i=>{const n=ct(a,i.label.toLowerCase()),c=i.value?ct(a,String(i.value).toLowerCase()):0,o=i.description?ct(a,i.description.toLowerCase()):0,l=Math.max(n,c,o);if(l===0)return null;const h=n>=c&&n>=o?"label":c>=n&&c>=o?"value":"description",p=h==="label"?i.label:h==="value"?String(i.value):i.description;return{...i,score:l,matchedField:h,matchedTerm:p}}).filter(i=>i!==null).sort((i,n)=>n.score-i.score):[]}const Ft="bizar_settings_recent";function Ra(){try{const s=localStorage.getItem(Ft);return s?JSON.parse(s):[]}catch{return[]}}function ul(s){if(s)try{const t=Ra().filter(a=>a!==s);t.unshift(s),localStorage.setItem(Ft,JSON.stringify(t.slice(0,5)))}catch{}}function hl(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 xl(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 pl({sections:s,onJump:t}){const[a,i]=r.useState(""),[n,c]=r.useState([]),[o,l]=r.useState(0),[h,p]=r.useState(null),[u,d]=r.useState(!1),m=r.useRef(null),x=r.useRef(null),g=r.useRef(null),b=r.useRef([]);r.useEffect(()=>{b.current=xl(s)},[s]);const z=r.useCallback((R,y=!1)=>{if(x.current&&clearTimeout(x.current),!R.trim()){c([]),l(0);return}const M=()=>{const P=ml(R,b.current);c(P),l(0)};y?M():x.current=setTimeout(M,150)},[]);r.useEffect(()=>{z(a)},[a,z]),r.useEffect(()=>()=>{x.current&&clearTimeout(x.current),g.current&&clearTimeout(g.current)},[]);const k=(R,y)=>{const M=document.querySelector(`[data-section="${R}"] [data-setting-id="${y}"]`);M&&(M.scrollIntoView({behavior:"smooth",block:"center"}),M.classList.add("setting-flash"),setTimeout(()=>M.classList.remove("setting-flash"),2e3));const P=document.querySelector(`[data-section="${R}"]`);P&&P.scrollIntoView({behavior:"smooth",block:M?"nearest":"start"})},w=R=>{p(R),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>p(null),1500);const y=document.querySelector(`[data-section="${R}"]`);y&&y.scrollIntoView({behavior:"smooth",block:"start"})},S=R=>{var y;ul(a),R.key===R.section?(w(R.section),t(R.section)):(w(R.section),t(R.section,R.key),k(R.section,R.key)),i(""),(y=m.current)==null||y.blur()},A=R=>{var y;R.key==="Escape"?(i(""),(y=m.current)==null||y.blur()):R.key==="ArrowDown"?(R.preventDefault(),l(M=>Math.min(M+1,n.length-1))):R.key==="ArrowUp"?(R.preventDefault(),l(M=>Math.max(M-1,0))):R.key==="Enter"&&(R.preventDefault(),n.length===0&&a.trim()&&z(a,!0),n[o]&&S(n[o]))},f=R=>{S(R)},N=Ra(),v=R=>{var y;i(R),(y=m.current)==null||y.focus()},j=()=>{try{localStorage.removeItem(Ft)}catch{}d(R=>R)},E=u&&!a.trim()&&N.length>0;return e.jsxs("div",{className:"settings-search",children:[e.jsxs("div",{className:"settings-search-input-wrap",children:[e.jsx(ye,{size:13,className:"settings-search-icon"}),e.jsx("input",{ref:m,className:"settings-search-input",placeholder:"Search settings…",value:a,onChange:R=>i(R.target.value),onKeyDown:A,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(Ne,{size:12})})]}),E&&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:j,tabIndex:-1,children:"Clear"})]}),N.map(R=>e.jsxs("button",{type:"button",className:"settings-search-recent-item",onMouseDown:y=>{y.preventDefault(),v(R)},children:[e.jsx(ye,{size:11}),e.jsx("span",{children:R})]},R))]}),a&&n.length>0&&e.jsx("div",{className:"settings-search-results",children:n.map((R,y)=>e.jsxs("button",{type:"button",className:V("settings-search-result",y===o&&"settings-search-result-active"),onClick:()=>f(R),onMouseEnter:()=>l(y),children:[e.jsx("span",{className:V("settings-search-result-type",R.key===R.section&&"settings-search-result-type-section"),children:R.key===R.section?"section":"field"}),e.jsx("span",{className:"settings-search-result-label",children:hl(R.label,a)}),R.key!==R.section&&e.jsx("span",{className:"settings-search-result-key mono muted",children:R.key})]},`${R.section}::${R.key}`))}),a&&n.length===0&&e.jsx("div",{className:"settings-search-empty muted",children:"No matching settings."})]})}const gl=[{id:"dark",label:"Dark",Icon:Sn},{id:"light",label:"Light",Icon:Cn},{id:"system",label:"System",Icon:zn}],fl=[{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"}],jl=["Inter","system-ui","Segoe UI","Roboto","JetBrains Mono","SF Mono","Cascadia Code"];function vl({settings:s,patchTheme:t,patchUi:a}){return e.jsxs(G,{id:"settings-theme","data-section":"theme",children:[e.jsxs(te,{children:[e.jsx(da,{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:fl.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:gl.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:jl.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"})]})]})}function yl({tailscale:s,tailscaleDraft:t,setTailscaleDraft:a,onTailscaleToggle:i}){return e.jsxs(e.Fragment,{children:[e.jsxs(G,{id:"settings-service","data-section":"service",children:[e.jsxs(te,{children:[e.jsx(js,{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(G,{id:"settings-tailscale","data-section":"tailscale",children:[e.jsxs(te,{children:[e.jsx(jt,{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($,{variant:"primary",onClick:i,children:s.settings.enabled?"Disable serve":"Enable serve"})]}):e.jsx("p",{className:"muted",children:"Loading Tailscale status…"})]})]})}function bl({settings:s,patchNotifications:t}){return e.jsxs(G,{id:"settings-notifications","data-section":"notifications",children:[e.jsx(te,{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 Nl({authStatus:s,setAuthStatus:t}){const a=re(),[i,n]=r.useState(T.getToken()),[c,o]=r.useState("");r.useEffect(()=>{let u=!1;return(async()=>{try{const d=await T.probeAuthStatus();u||t(d)}catch{u||t({required:!0,loopback:!1,peer:""})}})(),()=>{u=!0}},[]);const l=async()=>{try{const u=await T.get("/auth/reveal");o(u.token),n(u.token),T.setToken(u.token);try{await navigator.clipboard.writeText(u.token),a.success("Token copied to clipboard.")}catch{a.success("Token revealed — copy from the field below.")}}catch(u){a.error(`Reveal failed: ${u.message}`)}},h=async()=>{if(confirm("Regenerate the auth token? Anything still using the old token will start getting 401 errors immediately."))try{const u=await T.post("/auth/regenerate");o(u.token),n(u.token),T.setToken(u.token);try{await navigator.clipboard.writeText(u.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(u){a.error(`Regenerate failed: ${u.message}`)}},p=()=>{T.setToken(i.trim()),a.success("Token saved. The dashboard will use it on the next request.")};return e.jsxs(G,{id:"settings-auth","data-section":"auth",children:[e.jsxs(te,{children:[e.jsx(Mt,{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:u=>n(u.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($,{variant:"secondary",size:"sm",onClick:p,children:[e.jsx(It,{size:14})," Save token"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:l,children:[e.jsx(os,{size:14})," Reveal & copy server token"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:h,children:[e.jsx(xa,{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 kl({settings:s,patchAgents:t,patchDashboard:a,autoSave:i}){var p,u,d,m;const n=re(),[c,o]=r.useState({});r.useEffect(()=>{T.get("/settings/plugin-options").then(o).catch(()=>{})},[]);const l=async()=>{try{await T.put("/settings/plugin-options",c),n.success("Saved — restart opencode for changes to take effect.")}catch(x){n.error(`Save failed: ${x.message}`)}},h=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(x){n.error(`Cleanup failed: ${x.message}`)}};return e.jsxs(e.Fragment,{children:[e.jsxs(G,{id:"settings-agents","data-section":"agents",children:[e.jsxs(te,{children:[e.jsx(js,{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:((p=s.agents)==null?void 0:p.maxParallel)??6,onChange:x=>t({maxParallel:Math.max(1,Math.min(20,parseInt(x.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:((u=s.agents)==null?void 0:u.stuckThresholdMs)??6e5,onChange:x=>t({stuckThresholdMs:Math.max(6e4,Math.min(36e5,parseInt(x.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:x=>t({autoRestart:x.target.checked})}),e.jsx("span",{children:"Auto-restart stuck agents"})]})]}),e.jsxs(G,{id:"settings-dashboard","data-section":"dashboard",children:[e.jsxs(te,{children:[e.jsx(vs,{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:x=>a({autoLaunchWeb:x.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:x=>a({projectsDirectory:x.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(Hn,{initialValue:(s.dashboard.allowedRoots??[]).join(`
|
|
6
|
-
`),delay:1500,saveFn:async x=>{const g=x.split(`
|
|
7
|
-
`).map(b=>b.trim()).filter(Boolean);a({allowedRoots:g}),i==null||i("dashboard",{allowedRoots:g})},render:({value:x,onChange:g,onBlur:b})=>e.jsx("textarea",{id:"set-allowed-roots",className:"textarea",rows:4,placeholder:`/workspace
|
|
8
|
-
/srv/projects`,value:x,onChange:z=>g(z.target.value),onBlur:b})},(m=s.dashboard.allowedRoots)==null?void 0:m.join(`
|
|
9
|
-
`)),e.jsx("p",{className:"field-help",children:"Optional. Add filesystem roots beyond your home directory that the file browser and project scanner can access. Each path must be inside your home directory. One per line."}),(()=>{const x=(s.dashboard.allowedRoots??[]).join(`
|
|
10
|
-
`).split(`
|
|
11
|
-
`),g=[];return x.forEach((b,z)=>{b.trim()&&(/^\/|^[A-Za-z]:/.test(b)||g.push({key:`noabs-${z}`,msg:e.jsxs("p",{style:{color:"var(--warning)",fontSize:11,marginTop:2},children:["Line ",z+1,': "',b,'" — should be absolute (start with / or a drive letter).']})}),b.includes("..")&&g.push({key:`dots-${z}`,msg:e.jsxs("p",{style:{color:"var(--error)",fontSize:11,marginTop:2},children:["Line ",z+1,': "',b,`" — contains '..' (server will reject this).`]})}))}),g.map(b=>b.msg)})()]})]}),e.jsxs(G,{id:"settings-background","data-section":"background",children:[e.jsxs(te,{children:[e.jsx(js,{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:x=>o(g=>({...g,maxConcurrentInstances:Math.max(1,Math.min(32,parseInt(x.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:x=>o(g=>({...g,backgroundToolCallCap:Math.max(1,Math.min(5e3,parseInt(x.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:x=>o(g=>({...g,backgroundStallTimeoutMs:Math.max(1e4,Math.min(6e5,parseInt(x.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:x=>o(g=>({...g,backgroundThinkingLoopTimeoutMs:Math.max(3e4,Math.min(9e5,parseInt(x.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:x=>o(g=>({...g,backgroundMaxInterventions:Math.max(1,Math.min(3,parseInt(x.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($,{variant:"secondary",size:"sm",onClick:l,children:[e.jsx(Ms,{size:14})," Save plugin options"]}),e.jsx($,{variant:"secondary",size:"sm",onClick:h,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 wl({workspaceId:s,onInviteCreated:t}){const a=Re(),[i,n]=r.useState(""),[c,o]=r.useState("editor"),[l,h]=r.useState([]),[p,u]=r.useState(!1),[d,m]=r.useState(!1),[x,g]=r.useState(null),[b,z]=r.useState(null);r.useEffect(()=>{k()},[s]);async function k(){u(!0);try{const N=await T.get(`/workspaces/${s}/invites`);h(N.invites||[])}catch{}finally{u(!1)}}async function w(N){if(N.preventDefault(),!!i.trim()){m(!0),z(null);try{const v=await T.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(Rn,{size:14}),e.jsx("input",{type:"text",readOnly:!0,value:v.url,onClick:j=>j.target.select()}),e.jsx("button",{type:"button",className:"invite-copy-btn",onClick:()=>{navigator.clipboard.writeText(v.url).catch(()=>{}),g(v.token),setTimeout(()=>g(null),2e3)},children:x===v.token?e.jsx(gs,{size:14}):e.jsx(os,{size:14})})]}),e.jsx("p",{className:"invite-url-note",children:"This link expires in 7 days."})]}),footer:e.jsx($,{variant:"primary",size:"sm",onClick:()=>a.close(),children:"Done"})})}catch(v){z(v.message||"Failed to create invite")}finally{m(!1)}}}async function S(N){if(confirm("Revoke this invite?"))try{await T.del(`/workspaces/${s}/invites/${N}`),await k()}catch(v){z(v.message||"Failed to revoke invite")}}function A(N,v){navigator.clipboard.writeText(N).catch(()=>{}),g(v),setTimeout(()=>g(null),2e3)}const f={admin:"role-admin",editor:"role-editor",viewer:"role-viewer"};return e.jsxs("div",{className:"invite-dialog",children:[e.jsxs("form",{className:"invite-form",onSubmit:w,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:N=>n(N.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:N=>o(N.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($,{type:"submit",variant:"primary",size:"sm",loading:d,disabled:!i.trim(),children:[e.jsx(Tn,{size:13}),"Invite"]})]}),b&&e.jsx("p",{className:"invite-error",children:b})]}),e.jsxs("div",{className:"invite-list",children:[e.jsx("h4",{className:"invite-list-title",children:"Pending Invites"}),p&&e.jsx("p",{className:"invite-loading",children:"Loading..."}),!p&&l.length===0&&e.jsx("p",{className:"invite-empty",children:"No pending invites"}),l.map(N=>e.jsxs("div",{className:"invite-item",children:[e.jsxs("div",{className:"invite-item-info",children:[e.jsx("span",{className:"invite-item-email",children:N.email}),e.jsx("span",{className:V("invite-item-role",f[N.role]),children:N.role})]}),e.jsxs("div",{className:"invite-item-actions",children:[e.jsx("button",{type:"button",className:"invite-action-btn",title:"Copy invite link",onClick:()=>{const v=`${window.location.origin}/accept-invite?token=${N.token}`;A(v,N.token)},children:x===N.token?e.jsx(gs,{size:13}):e.jsx(os,{size:13})}),e.jsx("button",{type:"button",className:"invite-action-btn invite-action-revoke",title:"Revoke invite",onClick:()=>S(N.token),children:e.jsx(we,{size:13})})]})]},N.token))]})]})}const Sl={admin:$n,editor:Mt,viewer:fs},Cl={admin:"role-admin",editor:"role-editor",viewer:"role-viewer"};function zl(){const[s,t]=r.useState([]),[a,i]=r.useState(!0),[n,c]=r.useState(!1),[o,l]=r.useState(""),[h,p]=r.useState(null),[u,d]=r.useState(null),m=Re();r.useEffect(()=>{x()},[]);async function x(){i(!0);try{const k=await T.get("/workspaces");t(k.workspaces||[])}catch{p("Failed to load workspaces")}finally{i(!1)}}async function g(k){if(k.preventDefault(),!!o.trim()){c(!0);try{await T.post("/workspaces",{name:o.trim()}),l(""),await x()}catch(w){p(w.message||"Failed to create workspace")}finally{c(!1)}}}async function b(k,w){if(confirm(`Delete workspace "${w}"?`)&&confirm("This cannot be undone."))try{await T.del(`/workspaces/${k}`),await x()}catch(S){p(S.message||"Failed to delete workspace")}}function z(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."}),h&&e.jsxs("div",{className:"settings-section-error",children:[e.jsx("span",{children:h}),e.jsx("button",{onClick:()=>p(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($,{type:"submit",variant:"primary",size:"sm",loading:n,disabled:!o.trim(),children:[e.jsx(be,{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:w})=>{const S=Sl[w]||fs;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(Xs,{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",Cl[w]),children:[e.jsx(S,{size:11}),w]})]})]}),e.jsxs("div",{className:"workspace-item-actions",children:[e.jsx($,{variant:"ghost",size:"sm",iconOnly:!0,title:"Copy invite link",onClick:()=>z(k.id),children:u===k.id?e.jsx(gs,{size:13}):e.jsx(os,{size:13})}),w==="admin"&&e.jsx($,{variant:"ghost",size:"sm",iconOnly:!0,title:"Manage members",onClick:()=>{m.open({title:`Manage "${k.name}"`,children:e.jsx(wl,{workspaceId:k.id,onInviteCreated:()=>x()}),width:520})},children:e.jsx(Xs,{size:13})}),w==="admin"&&s.length>1&&e.jsx($,{variant:"ghost",size:"sm",iconOnly:!0,title:"Delete workspace",onClick:()=>b(k.id,k.name),children:e.jsx(we,{size:13})})]})]},k.id)})]})]})}const Tl=[{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"}],Rl=[{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 $l({settings:s,refreshSnapshot:t,settingsMode:a,settingsActiveSection:i,setSettingsActiveSection:n,setActiveTab:c}){const o=re(),[l,h]=r.useState(s),[p,u]=r.useState(!1),[d,m]=r.useState(!1),[x,g]=r.useState(null),[b,z]=r.useState({port:4321,https:!0,hostname:""}),[k,w]=r.useState(null),S=()=>{c("overview")};r.useEffect(()=>{h(s),u(!1),s.theme&&xs(s.theme)},[s]),r.useEffect(()=>{x&&z({port:x.settings.port,https:x.settings.https!==!1,hostname:x.settings.hostname||""})},[x]),r.useEffect(()=>{T.get("/tailscale/status").then(g).catch(()=>{})},[]);const A=r.useRef(null),f=r.useCallback(async(B,Z)=>{h(he=>({...he,[B]:Z})),A.current&&clearTimeout(A.current),A.current=setTimeout(async()=>{try{await T.put("/settings",{...l,[B]:Z})}catch(he){console.error("autoSave failed",he)}},300)},[l]);r.useEffect(()=>()=>{A.current&&clearTimeout(A.current)},[]);const N=B=>{h(Z=>{const he={...Z,theme:{...Z.theme,...B}};return xs(he.theme),he}),u(!0)},v=B=>{h(Z=>({...Z,ui:{...Z.ui,...B}})),u(!0)},j=(B,Z)=>{h(he=>({...he,[B]:Z})),u(!0)},E=B=>{h(Z=>({...Z,notifications:{...Z.notifications,...B}})),u(!0)},R=B=>{h(Z=>({...Z,agents:{...Z.agents,...B}})),u(!0)},y=B=>{h(Z=>({...Z,dashboard:{...Z.dashboard,...B}})),u(!0)},[M,P]=r.useState(()=>{if(typeof window>"u")return null;const B=window.location.hash.replace(/^#settings-/,"");return Tl.some(Z=>Z.id===B)?B:null}),C=a?i??null:M,D=B=>{if(a)n==null||n(B);else{P(B);try{if(history.replaceState(null,"",B?`#settings-${B}`:window.location.pathname),B){const Z=document.getElementById(`settings-${B}`);Z&&Z.scrollIntoView({behavior:"smooth",block:"start"})}else window.scrollTo({top:0,behavior:"smooth"})}catch{}}if(B){const Z=document.getElementById(`settings-${B}`);Z&&Z.scrollIntoView({behavior:"smooth",block:"start"})}else window.scrollTo({top:0,behavior:"smooth"})},Y=async()=>{try{x!=null&&x.settings.enabled?(await T.post("/tailscale/disable"),o.success("Tailscale serve disabled.")):(await T.post("/tailscale/enable",{port:b.port||4321,https:b.https,hostname:b.hostname||""}),o.success("Tailscale serve enabled.")),g(await T.get("/tailscale/status"))}catch(B){o.error(`Tailscale failed: ${B.message}`)}},O=async()=>{m(!0);try{const B=await T.put("/settings",l);h(B.data),u(!1),Rs(B.data.theme),xs(B.data.theme),o.success("Settings saved."),await t()}catch(B){o.error(`Save failed: ${B.message}`)}finally{m(!1)}},Q=async()=>{try{const B=await T.get("/settings");h(B.data),u(!1),Rs(B.data.theme),xs(B.data.theme),o.info("Settings reloaded.",1500)}catch(B){o.error(`Reload failed: ${B.message}`)}},ae=async()=>{if(confirm("Reset all settings to defaults?"))try{const B=await T.post("/settings/reset");h(B.data),u(!1),Rs(B.data.theme),xs(B.data.theme),o.success("Settings reset."),await t()}catch(B){o.error(`Reset failed: ${B.message}`)}},ee={settings:l,patchTheme:N,patchUi:v,patchTop:j,patchNotifications:E,patchAgents:R,patchDashboard:y},F=l.about||{version:"3.0.4",homepage:"https://github.com/DrB0rk/BizarHarness",license:"MIT"},H=C===null,K=B=>C===B;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(Ct,{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($,{variant:"ghost",size:"sm",onClick:ae,children:[e.jsx(xa,{size:14})," Reset"]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:Q,children:[e.jsx(de,{size:14})," Reload"]}),e.jsxs($,{variant:"primary",size:"sm",disabled:!p||d,onClick:O,children:[d?e.jsx("span",{className:"btn-spinner"}):e.jsx(Ms,{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($,{variant:"secondary",size:"sm",onClick:S,children:"← Back to main view"})]}),e.jsx(pl,{sections:Rl,onJump:D}),e.jsxs("div",{className:V("settings-grid",C&&"settings-grid-filtered"),"data-active-section":C||void 0,children:[(H||K("theme"))&&e.jsx("div",{id:"settings-theme",children:e.jsx(vl,{...ee})}),(H||K("updates"))&&e.jsx("div",{id:"settings-updates",children:e.jsx(Gn,{})}),(H||K("layout")||K("general"))&&e.jsx("div",{id:"settings-general",children:e.jsx(Kn,{...ee,autoSave:f})}),(H||K("env-vars"))&&e.jsx("div",{id:"settings-env-vars",children:e.jsx(Yn,{})}),(H||K("network")||K("service")||K("tailscale"))&&e.jsx("div",{id:"settings-network",children:e.jsx(yl,{tailscale:x,tailscaleDraft:b,setTailscaleDraft:z,onTailscaleToggle:Y})}),(H||K("network")||K("tailscale"))&&e.jsx(Xn,{initialStatus:x}),(H||K("notifications"))&&e.jsx("div",{id:"settings-notifications",children:e.jsx(bl,{...ee})}),(H||K("auth"))&&e.jsx("div",{id:"settings-auth",children:e.jsx(Nl,{settings:l,authStatus:k,setAuthStatus:w})}),(H||K("agents")||K("dashboard")||K("background"))&&e.jsx("div",{id:"settings-agents",children:e.jsx(kl,{...ee,autoSave:f})}),(H||K("system-llm"))&&e.jsx("div",{id:"settings-system-llm",children:e.jsx(Qn,{...ee})}),(H||K("headroom"))&&e.jsx("div",{id:"settings-headroom",children:e.jsx(Jn,{settings:l,setSettings:h,setDirty:u})}),(H||K("activity-log")||K("about"))&&e.jsx("div",{id:"settings-activity-log",children:e.jsx(Zn,{about:F})}),(H||K("workspaces"))&&e.jsx("div",{id:"settings-workspaces",children:e.jsx(zl,{})})]})]})}const Xt=Fe.memo($l),Al={net:{label:"Network access",icon:vs,color:"blue",description:"Can make HTTP requests to external services"},fs:{label:"Filesystem",icon:ke,color:"yellow",description:"Can read and write files"},config:{label:"Config access",icon:pa,color:"gray",description:"Can read and write Bizar config"},log:{label:"Logging",icon:ke,color:"gray",description:"Can write to the structured log"},exec:{label:"Shell execution",icon:is,color:"red",description:"Can run shell commands"}};function Ot({permissions:s}){return e.jsx("div",{className:"plugin-permissions","aria-label":"Required permissions",children:s.map(t=>{const a=Al[t]??{label:t,icon:Mt,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 Ml({plugin:s,onInstall:t,onView:a}){return e.jsxs(G,{className:"marketplace-plugin-card",children:[e.jsxs("div",{className:"marketplace-plugin-head",children:[e.jsxs("div",{children:[e.jsx(te,{children:s.name}),e.jsxs(ne,{children:["v",s.version," · ",s.category]})]}),e.jsx("div",{className:"marketplace-plugin-author",children:s.author})]}),s.description&&e.jsx("p",{className:"marketplace-plugin-description",children:s.description}),s.tags&&s.tags.length>0&&e.jsx("div",{className:"marketplace-plugin-tags",children:s.tags.map(i=>e.jsx("span",{className:"tag",children:i},i))}),e.jsx(Ot,{permissions:s.permissions??[]}),e.jsxs("div",{className:"marketplace-plugin-actions",children:[e.jsx($,{onClick:a,children:"Details"}),e.jsx($,{variant:"primary",onClick:t,children:"Install"})]})]})}function Il({plugin:s,onConfirm:t,onCancel:a,installing:i}){const n=Re(),c=r.useRef(null);return r.useEffect(()=>{s&&c.current!==s.id&&(c.current=s.id,n.open({title:`Install ${s.name}?`,width:560,onClose:()=>{c.current=null,a()},children:e.jsxs("div",{className:"install-confirm",children:[e.jsxs("h3",{children:[s.name," v",s.version]}),s.description&&e.jsx("p",{children:s.description}),e.jsxs("div",{className:"install-warning",children:[e.jsx(ze,{size:16}),e.jsx("p",{children:"This plugin will run code on your machine. It requests these permissions:"})]}),e.jsx(Ot,{permissions:s.permissions??[]}),e.jsxs("div",{className:"install-confirm-actions",children:[e.jsx($,{onClick:a,disabled:i,children:"Cancel"}),e.jsx($,{variant:"primary",onClick:t,disabled:i,children:i?"Installing...":"Install"})]})]})}))},[s,i]),null}function El(){const s=re(),[t,a]=r.useState(null),[i,n]=r.useState(""),[c,o]=r.useState(null),[l,h]=r.useState(null),[p,u]=r.useState(null),[d,m]=r.useState(!0);r.useEffect(()=>{T.get("/plugins/registry").then(k=>a(k)).catch(k=>s.error(`Failed to load marketplace: ${k.message}`)).finally(()=>m(!1))},[s]);const x=async k=>{h(k);try{await T.post("/plugins/install",{pluginId:k.id}),s.success(`${k.name} installed`),h(null),u(null)}catch(w){s.error(`Install failed: ${w.message}`),h(null)}},g=(t==null?void 0:t.plugins)??[],b=g.filter(k=>(!i||k.name.toLowerCase().includes(i.toLowerCase()))&&(!c||k.category===c)),z=[...new Set(g.map(k=>k.category))];return d?e.jsx("div",{className:"view-loading",children:e.jsx(oe,{size:"lg"})}):e.jsxs("div",{className:"view view-marketplace",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(Ks,{size:18,"aria-hidden":!0}),"Plugin Marketplace"]}),e.jsx("p",{className:"view-subtitle",children:"Discover and install plugins from the community registry."})]})}),e.jsx("div",{className:"marketplace-search-row",children:e.jsx("input",{className:"input",type:"search",placeholder:"Search plugins...",value:i,onChange:k=>n(k.target.value),style:{maxWidth:320}})}),e.jsxs("div",{className:"category-chips",children:[e.jsx("button",{type:"button",onClick:()=>o(null),className:c?"":"active",children:"All"}),z.map(k=>e.jsx("button",{type:"button",onClick:()=>o(k),className:c===k?"active":"",children:k},k))]}),b.length===0?e.jsx(pe,{icon:e.jsx(Ks,{size:32}),title:"No plugins found",message:i?`No plugins match "${i}".`:"The marketplace is empty."}):e.jsx("div",{className:"marketplace-grid",children:b.map(k=>e.jsx(Ml,{plugin:k,onInstall:()=>u(k),onView:()=>u(k)},k.id))}),p&&e.jsx(Il,{plugin:p,onConfirm:()=>x(p),onCancel:()=>u(null),installing:(l==null?void 0:l.id)===p.id||!1})]})}function Ll({snapshot:s,refreshSnapshot:t}){const a=re(),i=Re(),[n,c]=r.useState(Array.isArray(s.mods)?s.mods:[]),[o,l]=r.useState(!0),[h,p]=r.useState(null),[u,d]=r.useState([]),[m,x]=r.useState(null),[g,b]=r.useState(!1),[z,k]=r.useState(null),[w,S]=r.useState(!1),[A,f]=r.useState({}),N=async()=>{var C,D,Y;S(!0);try{const O=await T.get("/mods/registry");k({source:((C=O.registry)==null?void 0:C.source)||"",version:(D=O.registry)==null?void 0:D.version,updatedAt:(Y=O.registry)==null?void 0:Y.updatedAt,mods:O.mods||[]})}catch(O){k({source:"",mods:[],error:O.message})}finally{S(!1)}},v=async C=>{f(D=>({...D,[C]:!0}));try{const D=await T.post("/mods",{id:C});c(Y=>[...Y.filter(O=>O.id!==D.id),D]),a.success(`Mod "${D.id}" installed from registry.`),await t()}catch(D){a.error(`Install failed: ${D.message}`)}finally{f(D=>({...D,[C]:!1}))}},j=async(C,D=!1)=>{f(Y=>({...Y,[C]:!0}));try{const Y=await T.post(`/mods/${encodeURIComponent(C)}/upgrade`,{backup:D});c(Q=>[...Q.filter(ae=>ae.id!==Y.mod.id),Y.mod]);const O=Y.backupPath?` (backup at ${Y.backupPath})`:"";a.success(`Mod "${C}" upgraded v${Y.from} → v${Y.to}${O}.`),await t()}catch(Y){a.error(`Upgrade failed: ${Y.message}`)}finally{f(Y=>({...Y,[C]:!1}))}},E=async()=>{try{const C=await T.get("/mods");c(C.mods||[]);try{const D=await T.get("/mods/views");d(D.views||[])}catch{d([])}}catch(C){a.error(`Mods load failed: ${C.message}`)}finally{l(!1)}};r.useEffect(()=>{E()},[]),r.useEffect(()=>{Array.isArray(s.mods)&&s.mods!==n&&c(s.mods)},[s.mods]);const R=()=>{let C=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:D=>C=D,className:"input",type:"text",placeholder:"/path/to/my-mod",autoFocus:!0})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx($,{variant:"ghost",onClick:()=>i.close(),children:"Cancel"}),e.jsx($,{variant:"primary",onClick:async()=>{const D=((C==null?void 0:C.value)||"").trim();if(!D){a.warning("Path is required.");return}try{const Y=await T.post("/mods",{path:D});c(O=>[...O,Y]),a.success(`Mod "${Y.id}" installed.`),i.close(),await t()}catch(Y){a.error(`Install failed: ${Y.message}`)}},children:"Install"})]})})},y=async C=>{if(confirm(`Uninstall mod "${C}"? This removes the folder from ~/.config/bizar/mods/.`))try{await T.del(`/mods/${encodeURIComponent(C)}`),c(D=>D.filter(Y=>Y.id!==C)),h===C&&p(null),a.success("Mod uninstalled.")}catch(D){a.error(`Uninstall failed: ${D.message}`)}},M=async C=>{try{const D=await T.put(`/mods/${encodeURIComponent(C.id)}`,{enabled:!C.enabled});c(Y=>Y.map(O=>O.id===C.id?D:O)),a.success(`Mod ${D.enabled?"enabled":"disabled"}.`)}catch(D){a.error(`Toggle failed: ${D.message}`)}},P=n.find(C=>C.id===h)||null;return o?e.jsx("div",{className:"view-loading",children:e.jsx(oe,{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(as,{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($,{variant:"secondary",size:"sm",onClick:E,children:[e.jsx(de,{size:14})," Refresh"]}),e.jsxs($,{variant:"primary",size:"sm",onClick:R,children:[e.jsx(be,{size:14})," Install mod"]})]})]}),n.length===0?e.jsx(pe,{icon:e.jsx(as,{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(C=>e.jsxs("div",{className:V("mod-list-item",h===C.id&&"mod-list-item-active"),onClick:()=>p(C.id),children:[e.jsxs("div",{className:"mod-list-item-head",children:[e.jsxs("div",{children:[e.jsx("div",{className:"mod-list-item-name",children:C.name}),e.jsxs("div",{className:"mod-list-item-meta",children:["v",C.version," · ",C.type," · ",C.author]})]}),e.jsxs("div",{className:"mod-list-item-actions",onClick:D=>D.stopPropagation(),children:[e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Toggle enabled",title:C.enabled?"Disable":"Enable",onClick:()=>M(C),children:e.jsx(Tt,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger","aria-label":"Uninstall",title:"Uninstall",onClick:()=>y(C.id),children:e.jsx(we,{size:12})})]})]}),e.jsx("div",{className:"mod-list-item-desc ellipsis-2",title:C.description,children:C.description}),e.jsx("div",{className:"mod-list-item-status",children:e.jsx("span",{className:`mod-mini-pill ${C.enabled?"mod-mini-pill-on":"mod-mini-pill-off"}`,children:C.enabled?"enabled":"disabled"})})]},C.id))}),P&&e.jsx(Dl,{mod:P})]}),e.jsxs(G,{className:"mods-registry-card",children:[e.jsxs("button",{type:"button",className:"mods-registry-head","aria-expanded":g,"aria-controls":"mods-registry-body",onClick:()=>{!z&&!w&&N(),b(C=>!C)},children:[e.jsx(vs,{size:14,"aria-hidden":!0}),e.jsx("span",{className:"mods-registry-title",children:"Mod registry"}),e.jsx("span",{className:"muted",style:{fontSize:11},children:z!=null&&z.mods?`${z.mods.length} available`:"click to browse"}),e.jsx("span",{className:"mods-registry-spacer"}),g?e.jsx(We,{size:14,"aria-hidden":!0}):e.jsx(Ye,{size:14,"aria-hidden":!0})]}),g&&e.jsx("div",{id:"mods-registry-body",className:"mods-registry-body",children:w?e.jsx("div",{className:"muted",style:{padding:12,fontSize:12},children:"Loading registry…"}):z!=null&&z.error?e.jsxs("div",{className:"mods-registry-error",children:[e.jsx(Is,{size:12})," Could not load registry: ",z.error]}):!z||z.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:[z.source&&e.jsxs("div",{className:"muted",style:{fontSize:11,marginBottom:8},children:["Source: ",e.jsx("code",{children:z.source})]}),e.jsx("div",{className:"mods-registry-grid",children:z.mods.map(C=>{const D=n.some(O=>O.id===C.id),Y=!!A[C.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:C.name}),C.latest&&e.jsxs("span",{className:V("mod-registry-version",C.upgradeAvailable&&"mod-registry-version-upgrade"),children:["v",C.latest,C.upgradeAvailable?" ↑":""]})]}),C.description&&e.jsx("div",{className:"mod-registry-card-desc",children:C.description}),e.jsxs("div",{className:"mod-registry-card-meta",children:[C.author&&e.jsxs("span",{className:"muted",children:["by ",C.author]}),C.homepage&&e.jsx("a",{href:C.homepage,target:"_blank",rel:"noopener noreferrer",className:"mod-registry-link",children:"homepage"})]}),(C.permissions||[]).length>0&&e.jsxs("div",{className:"mod-registry-perms",children:[e.jsx(Is,{size:10}),(C.permissions||[]).slice(0,4).map(O=>e.jsx("span",{className:"mod-registry-perm",children:O},O)),(C.permissions||[]).length>4&&e.jsxs("span",{className:"mod-registry-perm-more",children:["+",C.permissions.length-4]})]}),e.jsxs("div",{className:"mod-registry-card-actions",children:[!D&&e.jsx($,{variant:"primary",size:"sm",disabled:Y,onClick:()=>v(C.id),title:"Install from registry",children:Y?e.jsx(oe,{size:"sm"}):e.jsxs(e.Fragment,{children:[e.jsx(ls,{size:12})," Install"]})}),D&&C.upgradeAvailable&&e.jsx($,{variant:"primary",size:"sm",disabled:Y,onClick:()=>j(C.id),title:`Upgrade from v${C.installedVersion||"?"} to v${C.upgradeAvailable}`,children:Y?e.jsx(oe,{size:"sm"}):e.jsxs(e.Fragment,{children:[e.jsx(ls,{size:12})," Upgrade to v",C.upgradeAvailable]})}),D&&!C.upgradeAvailable&&e.jsxs($,{variant:"ghost",size:"sm",disabled:!0,title:`Installed v${C.installedVersion||"?"}`,children:["Installed v",C.installedVersion||"?"]})]})]},C.id)})})]})})]}),u.length>0&&e.jsxs(G,{className:"mod-views-hint",children:[e.jsxs(te,{children:[e.jsx(vs,{size:14})," Mod views"]}),e.jsxs(ne,{children:[u.length," mod-supplied view",u.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:()=>x(null),children:e.jsx(Ne,{size:14})})]}),e.jsx("iframe",{src:m,className:"mod-iframe",title:"Mod view",sandbox:"allow-scripts allow-same-origin allow-forms allow-popups"})]})]})}function Dl({mod:s}){const t=re(),[a,i]=r.useState(null),[n,c]=r.useState(!1),[o,l]=r.useState(!1),[h,p]=r.useState(null),u=async()=>{c(!0);try{const m=await T.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 T.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 u()}catch(m){t.error(`Reinstall failed: ${m.message}`)}};return e.jsxs(G,{className:"mod-details",children:[e.jsxs(te,{children:[e.jsx(ke,{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&&u(),l(m=>!m)},children:[e.jsx(An,{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(We,{size:14,"aria-hidden":!0}):e.jsx(Ye,{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(Mn,{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:()=>p(x=>x===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]})]}),h===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(is,{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:()=>p(x=>x===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]})]}),h===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(ga,{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:()=>p(x=>x===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]})]}),h===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($,{variant:"ghost",size:"sm",onClick:d,children:[e.jsx(de,{size:11})," Reinstall from mod folder"]})})]})]})]})}const Pl=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})]})});function Fl({plugin:s,onToggle:t,onUninstall:a,onConfigure:i}){return e.jsxs(G,{children:[e.jsxs("div",{className:"plugin-card-head",children:[e.jsxs("div",{children:[e.jsx(te,{children:s.name}),e.jsxs(ne,{children:["v",s.version," · ",s.id]})]}),e.jsx(Pl,{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(Ot,{permissions:s.permissions??[]}),e.jsxs("div",{className:"plugin-card-actions",children:[e.jsx($,{size:"sm",onClick:()=>i(s.id),"aria-label":`Configure ${s.name}`,children:"Configure"}),e.jsx($,{size:"sm",variant:"danger",onClick:()=>a(s.id),"aria-label":`Uninstall ${s.name}`,children:"Uninstall"})]}),e.jsxs("div",{className:"plugin-card-stats",children:[s.invocations??0," invocations",s.lastInvokedAt?` · last used ${s.lastInvokedAt}`:" · never used"]})]})}function Ol({setActiveTab:s}){const t=re(),[a,i]=r.useState([]),[n,c]=r.useState(!0),[o,l]=r.useState(""),h=async()=>{try{const x=await T.get("/plugins/installed");i(x.plugins)}catch(x){t.error(`Failed to load plugins: ${x.message}`)}finally{c(!1)}};r.useEffect(()=>{h()},[]);const p=async x=>{try{await T.post(`/plugins/${x}/toggle`).catch(()=>{}),await h(),t.success("Plugin toggled.")}catch(g){t.error(`Toggle failed: ${g.message}`)}},u=async x=>{if(confirm("Uninstall this plugin?"))try{await T.del(`/plugins/${x}`),await h(),t.success("Plugin uninstalled.")}catch(g){t.error(`Uninstall failed: ${g.message}`)}},d=x=>{};if(n)return e.jsx("div",{className:"view-loading",children:e.jsx(oe,{size:"lg"})});const m=a.filter(x=>x.name.toLowerCase().includes(o.toLowerCase()));return e.jsxs("div",{className:"view view-plugins",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(as,{size:18,"aria-hidden":!0}),"Plugins (",a.length,")"]}),e.jsx("p",{className:"view-subtitle",children:"Manage plugins installed via the marketplace."})]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:()=>s("marketplace"),children:[e.jsx(Ks,{size:14,"aria-hidden":!0}),"Browse Marketplace"]})]}),a.length===0?e.jsx(pe,{icon:e.jsx(as,{size:32}),title:"No plugins installed",message:"Browse the marketplace to discover and install plugins."}):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:x=>l(x.target.value),"aria-label":"Filter plugins",style:{maxWidth:320}})}),e.jsx("div",{className:"plugin-grid",children:m.map(x=>e.jsx(Fl,{plugin:x,onToggle:p,onUninstall:u,onConfigure:d},x.id))})]})]})}function Bl({viewId:s,reloadKey:t,setActiveTab:a}){const i=re(),[n,c]=r.useState(null),[o,l]=r.useState(!0),[h,p]=r.useState(0);if(r.useEffect(()=>{let u=!1;return(async()=>{try{const d=await T.get("/mods/views");if(u)return;const m=(d.views||[]).find(x=>x.id===s);c(m||null)}catch(d){i.error(`Failed to load mod view: ${d.message}`)}finally{u||l(!1)}})(),()=>{u=!0}},[s,i]),o)return e.jsx(pe,{title:"Loading mod view…"});if(!n)return e.jsx(pe,{title:"Mod view not found",message:`No view with id "${s}" is currently installed.`,action:e.jsx($,{onClick:()=>a("mods"),variant:"primary",size:"sm",children:"Open Mods"})});if(n.kind==="iframe"){const u=`/api/mods/${n.modId}/web/index.html?t=${h+(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(vs,{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($,{variant:"ghost",size:"sm",onClick:()=>p(d=>d+1),title:"Reload this view",children:[e.jsx(de,{size:11})," Reload"]}),e.jsx("a",{href:u,target:"_blank",rel:"noopener noreferrer",className:"icon-btn",title:"Open in new tab",children:e.jsx(ys,{size:12})})]})]}),e.jsx("iframe",{src:u,className:"mod-view-iframe",title:n.label},h+(t||0))]})}if(n.component){const u=n.component,d=n.modId,m=r.lazy(()=>Ha(()=>import(`/api/mods/${encodeURIComponent(d)}/views/${encodeURIComponent(u)}`),[]).then(x=>({default:x.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(Es,{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(Ul,{modId:n.modId,component:n.component,children:e.jsx(r.Suspense,{fallback:e.jsxs("div",{style:{padding:24},children:[e.jsx(oe,{size:"md"})," ",e.jsx("span",{className:"muted",children:"Loading mod view…"})]}),children:e.jsx(m,{})})})})]})}return e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsx(Es,{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($,{variant:"secondary",size:"sm",onClick:()=>a("mods"),children:"Open Mods page"})})]})}class Ul extends r.Component{constructor(){super(...arguments);ws(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(ze,{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 _l(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 Wl({template:s,onUse:t}){return e.jsxs(G,{className:"schedule-template-card",children:[e.jsxs("div",{className:"schedule-template-header",children:[e.jsx(te,{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:_l(s)})," · ",e.jsx("code",{children:s.action.type})]}),e.jsx($,{variant:"secondary",size:"sm",onClick:()=>t(s),"aria-label":`Use template: ${s.name}`,children:"Use this template"})]})}const ql=["interval","cron","once"],Vl=["command","agent","webhook"],Nt=[{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)"}],Hl=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"}],$a=[{value:"s",label:"seconds"},{value:"m",label:"minutes"},{value:"h",label:"hours"},{value:"d",label:"days"}];function Aa(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 Gl(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 Kl(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"?Aa(s.schedule):null,a=s.type==="interval"?Gl(s.schedule):null,i=s.timezone||"UTC",n=Nt.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"?Yl(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 Yl(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 Xl(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(u=>u.value===s.cronDow))==null?void 0:a.label)||"",l=((i=Bt.find(u=>u.value===s.cronHour))==null?void 0:i.label)||`${s.cronHour}`,h=String(s.cronMinute).padStart(2,"0"),p=o==="Every day"?`Every day at ${l.replace(" ","")} (min ${h})`:`Every ${o} at ${l.replace(" ","")} (min ${h})`;return{schedule:c,humanLabel:s.humanLabel||p}}if(s.type==="interval"){const c=((n=$a.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 Ql({snapshot:s,refreshSnapshot:t}){var A;const a=re(),i=Re(),[n,c]=r.useState(s.schedules||[]),[o,l]=r.useState(!s.schedules),[h,p]=r.useState("schedules"),[u,d]=r.useState([]),[m,x]=r.useState(!1),g=async()=>{try{const f=await T.get("/projects/active/schedules");c(f.schedules||[])}catch(f){a.error(`Schedules load failed: ${f.message}`)}finally{l(!1)}},b=async()=>{x(!0);try{const f=await T.get("/schedules/templates");d(f.templates||[])}catch(f){a.error(`Templates load failed: ${f.message}`)}finally{x(!1)}};r.useEffect(()=>{var f;if((f=s.schedules)!=null&&f.length||s.schedules){c(s.schedules||[]),l(!1);return}g()},[s.schedules]),r.useEffect(()=>{h==="templates"&&u.length===0&&b()},[h]);const z=f=>{i.open({title:f?`Edit schedule: ${f.name}`:"New schedule",width:640,children:e.jsx(Jl,{initial:f,onClose:i.close,onSubmitted:async N=>{c(v=>{const j=v.findIndex(R=>R.id===N.id);if(j===-1)return[...v,N];const E=v.slice();return E[j]=N,E}),a.success(f?"Schedule updated.":"Schedule created."),i.close(),await t()},onError:N=>a.error(N)})})},k=async f=>{var N;try{const v=await T.post(`/schedules/${encodeURIComponent(f.id)}/run`);a.success(v.ok?"Schedule ran.":`Run failed: ${((N=v.runResult)==null?void 0:N.error)||"unknown"}`),await g()}catch(v){a.error(`Run failed: ${v.message}`)}},w=async f=>{if(confirm(`Delete schedule "${f.name}"?`))try{await T.del(`/schedules/${encodeURIComponent(f.id)}`),c(N=>N.filter(v=>v.id!==f.id)),a.success("Schedule deleted.")}catch(N){a.error(`Delete failed: ${N.message}`)}},S=async f=>{try{const N=await T.post("/schedules/from-template",{templateId:f.id});c(v=>[...v,N]),p("schedules"),a.success(`Schedule "${N.name}" created from template.`),await t()}catch(N){a.error(`Failed to create schedule: ${N.message}`)}};return o?e.jsx("div",{className:"view-loading",children:e.jsx(oe,{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(ns,{size:18})," Schedules"]}),e.jsxs("div",{className:"view-section-tabs",children:[e.jsxs("button",{type:"button",className:`tab-btn ${h==="schedules"?"tab-btn-active":""}`,onClick:()=>p("schedules"),children:["Schedules (",n.length,")"]}),e.jsxs("button",{type:"button",className:`tab-btn ${h==="templates"?"tab-btn-active":""}`,onClick:()=>p("templates"),children:[e.jsx(Es,{size:14})," Templates"]})]})]}),e.jsx("p",{className:"view-subtitle",children:h==="schedules"?e.jsxs(e.Fragment,{children:["Recurring tasks for ",e.jsx("strong",{children:((A=s.activeProject)==null?void 0:A.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:[h==="schedules"&&e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"secondary",size:"sm",onClick:g,"aria-label":"Refresh schedules",children:[e.jsx(de,{size:14})," Refresh"]}),e.jsxs($,{variant:"primary",size:"sm",onClick:()=>z(),children:[e.jsx(be,{size:14})," New schedule"]})]}),h==="templates"&&e.jsxs($,{variant:"secondary",size:"sm",onClick:b,disabled:m,children:[e.jsx(de,{size:14})," Refresh"]})]})]}),h==="templates"?m?e.jsx("div",{className:"view-loading",children:e.jsx(oe,{size:"lg"})}):u.length===0?e.jsx(pe,{icon:e.jsx(Es,{size:32}),title:"No templates",message:"No schedule templates found. Templates are loaded from templates/schedules/."}):e.jsx("div",{className:"schedule-template-grid",children:u.map(f=>e.jsx(Wl,{template:f,onUse:S},f.id))}):n.length===0?e.jsx(pe,{icon:e.jsx(ns,{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(f=>{var N;return e.jsxs(G,{className:"schedule-card",children:[e.jsxs("div",{className:"schedule-card-head",children:[e.jsxs("div",{children:[e.jsx(te,{children:f.name}),e.jsxs(ne,{children:[e.jsx("code",{children:f.type})," ·"," ",e.jsx("span",{title:f.schedule,children:Zl(f)||f.schedule}),f.timezone&&f.timezone!=="UTC"?e.jsxs(e.Fragment,{children:[" · ",e.jsx("code",{children:f.timezone})]}):null," · ",e.jsx("span",{className:f.enabled?"status-on":"status-neutral",children:f.enabled?"enabled":"disabled"})]})]}),e.jsxs("div",{className:"schedule-card-actions",children:[e.jsxs($,{variant:"secondary",size:"sm",onClick:()=>z(f),children:[e.jsx(Ls,{size:12})," Edit"]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:()=>k(f),children:[e.jsx(vt,{size:12})," Run now"]}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger","aria-label":"Delete",title:"Delete",onClick:()=>w(f),children:e.jsx(we,{size:12})})]})]}),e.jsxs("div",{className:"schedule-card-action",children:[e.jsx("span",{className:"muted",children:"action:"})," ",e.jsxs("code",{children:[f.action.type," ",f.action.target]}),f.action.type==="agent"&&f.action.prompt&&e.jsxs("div",{className:"schedule-card-prompt",children:[e.jsx("span",{className:"muted",children:"prompt:"})," ",f.action.prompt]})]}),((N=f.budgetCheck)==null?void 0:N.skipIfBudgetLow)&&e.jsxs("div",{className:"schedule-card-budget",children:[e.jsx("span",{className:"muted",children:"budget gate:"})," ","skip if concurrent ≥ ",f.budgetCheck.maxConcurrent??6]}),e.jsxs("div",{className:"schedule-card-times",children:[e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"last"})," ",f.lastRun?Te(f.lastRun):"—",f.lastResult&&e.jsx("span",{className:`tag ${Qt(f.lastResult)}`,children:f.lastResult}),f.lastError&&e.jsxs("span",{className:"muted schedule-card-error",title:f.lastError,children:[" ","— ",Jt(f.lastError,80)]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"next"})," ",f.nextRun?e.jsx("span",{title:new Date(f.nextRun).toISOString(),children:eo(f.nextRun,f.timezone)}):"—",f.nextRun&&e.jsxs("span",{className:"muted",children:[" · ",Te(f.nextRun)]})]})]}),f.history&&f.history.length>0&&e.jsxs("details",{className:"schedule-card-history",children:[e.jsxs("summary",{children:[e.jsx(As,{size:12})," ",f.history.length," run",f.history.length===1?"":"s"]}),e.jsx("ul",{children:f.history.slice(-10).reverse().map((v,j)=>e.jsxs("li",{children:[e.jsx("span",{className:"tabular-nums muted",children:Te(v.ts)})," ",e.jsx("span",{className:`tag ${Qt(v.result)}`,children:v.result}),v.error&&e.jsxs("span",{className:"muted",children:[" — ",Jt(v.error,80)]})]},j))})]})]},f.id)})})]})}function Jl({initial:s,onClose:t,onSubmitted:a,onError:i}){const[n,c]=r.useState(()=>Kl(s)),[o,l]=r.useState(!1),h=r.useMemo(()=>Nt.some(d=>d.value===n.timezone)?n.timezone:"Other…",[n.timezone]),p=(d,m)=>{c(x=>({...x,[d]:m}))},u=async d=>{d.preventDefault();const m=n.name.trim();if(!m){i("Name is required.");return}const x=Xl(n);if(!x.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,b={type:n.actionType,target:n.actionTarget.trim()};n.actionType==="agent"&&n.actionPrompt.trim()&&(b.prompt=n.actionPrompt.trim());const z={name:m,type:n.type,schedule:x.schedule,timezone:g||"UTC",action:b,budgetCheck:{maxConcurrent:n.maxConcurrent,skipIfBudgetLow:n.skipIfBudgetLow},enabled:n.enabled};l(!0);try{const k=s?await T.put(`/schedules/${encodeURIComponent(s.id)}`,z):await T.post("/schedules",z);await a(k)}catch(k){i(`${s?"Update":"Create"} failed: ${k.message}`)}finally{l(!1)}};return e.jsxs("form",{className:"schedule-form",onSubmit:u,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=>p("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=>p("type",d.target.value),children:ql.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=>p("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=>p("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=>p("cronMinute",parseInt(d.target.value,10)),children:Hl.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=>p("rawCron",d.target.value),placeholder:"0 13 * * 0"})]}),e.jsxs("button",{type:"button",className:"link-btn",onClick:()=>p("showAdvanced",!n.showAdvanced),"aria-expanded":n.showAdvanced,children:[e.jsx(We,{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=>p("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=>p("intervalUnit",d.target.value),children:$a.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=>p("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:h,onChange:d=>p("timezone",d.target.value),children:[Nt.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=>p("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=>p("actionType",d.target.value),children:Vl.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=>p("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=>p("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=>p("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=>p("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=>p("enabled",d.target.checked)}),e.jsx("span",{children:"Enabled"})]}),e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx($,{variant:"ghost",type:"button",onClick:t,disabled:o,children:"Cancel"}),e.jsx($,{variant:"primary",type:"submit",disabled:o,children:s?"Save":"Create"})]})]})}function Zl(s){var c,o;if(s.type!=="cron")return s.schedule;const t=Aa(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 eo(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 Qt(s){return s==="success"?"tag-success":s==="skipped"?"tag-warning":"tag-error"}function Jt(s,t){return s.length<=t?s:s.slice(0,t-1)+"…"}const so=[{id:"all",label:"All",icon:Xe},{id:"shipped",label:"Shipped",icon:Et},{id:"user",label:"User",icon:Xs},{id:"project",label:"Project",icon:Pe}],Vs={shipped:"Shipped",user:"User",project:"Project"},to={shipped:Et,user:Xs,project:Pe};function ao({snapshot:s,refreshSnapshot:t}){const a=re(),i=Re(),[n,c]=r.useState([]),[o,l]=r.useState({shipped:0,user:0,project:0,all:0}),[h,p]=r.useState(!0),[u,d]=r.useState("all"),[m,x]=r.useState(""),[g,b]=r.useState(null),[z,k]=r.useState(!1),w=async()=>{var N,v,j;p(!0);try{const E=await T.get("/skills");c(E.skills||[]),l({shipped:((N=E.counts)==null?void 0:N.shipped)??0,user:((v=E.counts)==null?void 0:v.user)??0,project:((j=E.counts)==null?void 0:j.project)??0,all:(E.skills||[]).length})}catch(E){a.error(`Skills load failed: ${E.message}`)}finally{p(!1)}};r.useEffect(()=>{w()},[]),r.useEffect(()=>{if(!m.trim()){b(null);return}k(!0);const N=setTimeout(async()=>{try{const v=await T.get(`/skills/search?q=${encodeURIComponent(m.trim())}`);b(v.results||[])}catch(v){a.error(`Search failed: ${v.message}`)}finally{k(!1)}},280);return()=>clearTimeout(N)},[m]);const S=r.useMemo(()=>g!==null?g:u==="all"?n:n.filter(N=>N.source===u),[n,u,g]),A=async()=>{try{await T.post("/skills/refresh",{}),a.success("Skills refreshed."),await w()}catch(N){a.error(`Refresh failed: ${N.message}`)}},f=async N=>{try{const v=await T.get(`/skills/${encodeURIComponent(N.source)}/${encodeURIComponent(N.name)}`);i.open({title:v.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":v.source,children:Vs[v.source]||v.source}),e.jsx("code",{className:"mono text-sm muted",children:v.path})]}),v.description&&e.jsx("p",{className:"skill-detail-desc",children:v.description}),v.body&&e.jsx("div",{className:"skill-detail-body",children:e.jsx("pre",{className:"skill-body-pre",children:v.body})})]}),footer:e.jsx($,{variant:"ghost",onClick:()=>i.close(),children:"Close"})})}catch{i.open({title:N.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":N.source,children:Vs[N.source]||N.source}),e.jsx("code",{className:"mono text-sm muted",children:N.path})]}),N.description&&e.jsx("p",{className:"skill-detail-desc",children:N.description})]}),footer:e.jsx($,{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(Xe,{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(ye,{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:N=>x(N.target.value),"aria-label":"Search skills"}),m&&e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Clear search",onClick:()=>x(""),children:e.jsx(et,{size:12})})]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:A,children:[e.jsx(de,{size:14})," Refresh"]})]})]}),!m.trim()&&e.jsx("div",{className:"skills-tabs",children:so.map(N=>{const v=N.icon,j=N.id==="all"?o.all:o[N.id]??0;return e.jsxs("button",{type:"button",className:V("skills-tab",u===N.id&&"skills-tab-active"),onClick:()=>d(N.id),children:[e.jsx(v,{size:14}),e.jsx("span",{children:N.label}),e.jsx("span",{className:"skills-tab-count",children:j})]},N.id)})}),m.trim()&&e.jsxs("section",{className:"skills-section",children:[e.jsxs("h3",{className:"skills-section-title",children:[e.jsx(ye,{size:14})," Search results",z&&e.jsx(oe,{size:"sm"})]}),z?e.jsx("div",{className:"skills-grid",children:[0,1,2].map(N=>e.jsx("div",{className:"skill-card skill-card-skeleton"},N))}):g&&g.length===0?e.jsx(pe,{icon:e.jsx(ye,{size:28}),title:"No matches",message:`No skills match "${m}".`}):e.jsx("div",{className:"skills-grid",children:(g||[]).map((N,v)=>e.jsx(Zt,{skill:N,onShow:()=>f(N),searchQ:m},`search-${v}`))})]}),!m.trim()&&e.jsx("section",{className:"skills-section",children:h?e.jsx("div",{className:"view-loading",children:e.jsx(oe,{size:"lg"})}):S.length===0?e.jsx(pe,{icon:e.jsx(ga,{size:28}),title:"No skills here",message:u==="all"?"No skills found. Install skills with the skills CLI or add SKILL.md files to a skills directory.":`No skills in the ${Vs[u]} tab.`}):e.jsx("div",{className:"skills-grid",children:S.map((N,v)=>e.jsx(Zt,{skill:N,onShow:()=>f(N)},`${N.source}-${N.name}-${v}`))})}),!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 Zt({skill:s,onShow:t,searchQ:a=""}){const i=to[s.source]||Et,n=s.description?s.description.length>200?s.description.slice(0,200)+"…":s.description:"No description.";return e.jsxs(G,{variant:"elevated",interactive:!0,className:"skill-card",children:[e.jsxs("div",{className:"skill-card-head",children:[e.jsx("div",{className:"skill-card-icon",style:{background:"color-mix(in srgb, var(--accent) 12%, transparent)"},children:e.jsx(i,{size:18})}),e.jsxs("div",{className:"skill-card-title-area",children:[e.jsx("div",{className:"skill-card-title",children:no(s.name,a)}),e.jsx("span",{className:"skill-source-badge","data-source":s.source,children:Vs[s.source]||s.source})]})]}),e.jsx("p",{className:"skill-card-desc",children:n}),e.jsx("div",{className:"skill-card-actions",children:e.jsxs($,{variant:"ghost",size:"sm",onClick:t,children:[e.jsx(ys,{size:12})," View"]})})]})}function no(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 io=Fe.memo(ao);function ro({refreshKey:s,onRefresh:t,setActiveSubPanel:a}){const i=re(),[n,c]=r.useState(null),[o,l]=r.useState(!0),h=async g=>{l(!0);try{const[b,z,k,w]=await Promise.all([T.get("/memory/health",g).catch(()=>null),T.get("/memory/status",g).catch(()=>null),T.get("/memory/lightrag/stats",g).catch(()=>null),T.get("/memory/storage",g).catch(()=>null)]);c({health:b||{score:0,status:"unconfigured",checks:[],message:"memory not initialised"},vault:{exists:!!(z!=null&&z.initialized),vaultRoot:(z==null?void 0:z.vaultRoot)||"",mode:(z==null?void 0:z.mode)||"local-only",noteCount:(z==null?void 0:z.noteCount)||0,totalSize:(w==null?void 0:w.total)||0,folderCount:0,folders:[],lastModified:null,gitClean:(z==null?void 0:z.gitClean)??null,gitBranch:(z==null?void 0:z.branch)||null},lightrag:k||{running:!1,pid:null,host:"127.0.0.1",port:9621,indexedApprox:0,queryCountLast24h:0,lastReindexAt:null},storage:w||{total:0,breakdown:[]}})}catch(b){i.error(`Memory overview failed: ${b.message}`)}finally{l(!1)}};if(r.useEffect(()=>{const g=new AbortController;return h(g.signal),()=>g.abort()},[s]),o&&!n)return e.jsxs("div",{className:"view-loading",children:[e.jsx(oe,{size:"lg"}),e.jsx("p",{children:"Loading memory overview…"})]});if(!n)return e.jsx("div",{className:"muted",children:"No memory data available."});const{health:p,vault:u,lightrag:d,storage:m}=n,x=p.score>=80?"var(--success)":p.score>=50?"var(--warning)":"var(--error)";return e.jsxs("div",{className:"memory-overview",children:[e.jsxs(G,{variant:"elevated",className:"memory-health-hero",children:[e.jsxs("div",{className:"memory-health-score",style:{borderColor:x},children:[e.jsx("span",{className:"memory-health-score-value",style:{color:x},children:p.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(De,{size:16}),"Memory health ·"," ",e.jsx("span",{style:{color:x},children:p.status})]}),e.jsx("p",{className:"memory-health-message",children:p.message}),e.jsxs($,{variant:"ghost",size:"sm",onClick:t,children:[e.jsx(de,{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(Ue,{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(ke,{size:14}),e.jsx("span",{children:"Obsidian Vault"}),e.jsxs("span",{className:V("memory-source-pill-status",u.exists?"on":"off"),children:[u.noteCount," notes"]})]}),e.jsxs("button",{type:"button",className:"memory-source-pill",onClick:()=>a("git"),children:[e.jsx(rs,{size:14}),e.jsx("span",{children:"Git Sync"}),e.jsx("span",{className:V("memory-source-pill-status",u.gitClean===null?"na":u.gitClean?"on":"warn"),children:u.gitClean===null?"—":u.gitClean?"clean":"dirty"})]}),e.jsxs("button",{type:"button",className:"memory-source-pill",onClick:()=>a("semantic"),children:[e.jsx(ye,{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(hs,{icon:e.jsx(Ue,{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(hs,{icon:e.jsx(ke,{size:16}),label:"Obsidian",value:`${u.noteCount} notes`,sub:u.folderCount>0?`${u.folderCount} folders`:"no folders yet",onClick:()=>a("obsidian")}),e.jsx(hs,{icon:e.jsx(rs,{size:16}),label:"Git",value:u.gitBranch?`branch ${u.gitBranch}`:"local-only",sub:u.gitClean===null?"not configured":u.gitClean?"clean working tree":"dirty — commit or pull",onClick:()=>a("git")}),e.jsx(hs,{icon:e.jsx(fa,{size:16}),label:"Storage",value:lo(m.total),sub:m.breakdown.length>0?`${m.breakdown.length} dirs tracked`:"no memory data on disk"}),e.jsx(hs,{icon:e.jsx(Xe,{size:16}),label:"Last reindex",value:d.lastReindexAt?_e(d.lastReindexAt):"never",sub:"lightrag ingest",onClick:()=>a("lightrag")}),e.jsx(hs,{icon:e.jsx(Is,{size:16}),label:"Health",value:`${p.score}/100`,sub:p.status,onClick:()=>a("config")})]}),p.checks.length>0&&e.jsxs(G,{children:[e.jsx(te,{children:"Health checks"}),e.jsx(ne,{children:"Composite score across all memory subsystems"}),e.jsx("ul",{className:"memory-check-list",children:p.checks.map(g=>e.jsxs("li",{className:"memory-check-row",children:[e.jsx("span",{className:"memory-check-icon",children:g.pass?e.jsx(qe,{size:14,style:{color:"var(--success)"}}):g.name.includes("secrets")||g.name.includes("schema")?e.jsx(ze,{size:14,style:{color:"var(--warning)"}}):e.jsx(et,{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 hs({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 lo(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 oo({refreshKey:s}){const t=re(),[a,i]=r.useState(null),[n,c]=r.useState(null),[o,l]=r.useState([]),[h,p]=r.useState(!0),[u,d]=r.useState(null),[m,x]=r.useState(""),[g,b]=r.useState(null),z=async()=>{p(!0);try{const[j,E,R]=await Promise.all([T.get("/memory/lightrag/stats").catch(()=>null),T.get("/memory/config").then(y=>(y==null?void 0:y.lightrag)||null).catch(()=>null),T.get("/memory/lightrag/log").catch(()=>({lines:[]}))]);i(j),c(E),l((R==null?void 0:R.lines)||[])}catch(j){t.error(`LightRAG status failed: ${j.message}`)}finally{p(!1)}};r.useEffect(()=>{z()},[s]);const k=async(j,E,R)=>{d(j);try{await E(),t.success(R),await z()}catch(y){t.error(`${j} failed: ${y.message}`)}finally{d(null)}},w=()=>k("start",()=>T.post("/memory/lightrag/start",{}),"LightRAG starting…"),S=()=>k("stop",()=>T.post("/memory/lightrag/stop",{}),"LightRAG stopping…"),A=async()=>{d("restart");try{await T.post("/memory/lightrag/stop",{}).catch(()=>{}),await new Promise(j=>setTimeout(j,600)),await T.post("/memory/lightrag/start",{}),t.success("LightRAG restarted."),await z()}catch(j){t.error(`Restart failed: ${j.message}`)}finally{d(null)}},f=()=>k("reindex",()=>T.post("/memory/lightrag/reindex",{}),"Reindex complete."),N=()=>k("rebuild",()=>T.post("/memory/lightrag/rebuild-graph",{}),"Graph rebuilt."),v=async()=>{var j,E,R;if(m.trim()){d("query");try{const y=await T.get(`/memory/query?q=${encodeURIComponent(m)}&topK=8`),M=(j=y==null?void 0:y.semantic)!=null&&j.response?typeof y.semantic.response=="string"?y.semantic.response:JSON.stringify(y.semantic.response):((E=y==null?void 0:y.semantic)==null?void 0:E.error)||"No response";b({ok:!!((R=y==null?void 0:y.semantic)!=null&&R.ok),text:M})}catch(y){b({ok:!1,text:y.message})}finally{d(null)}}};return h&&!a?e.jsxs("div",{className:"view-loading",children:[e.jsx(oe,{size:"lg"}),e.jsx("p",{children:"Loading LightRAG status…"})]}):a?e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(G,{variant:"elevated",children:[e.jsxs(te,{children:[e.jsx(Ue,{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($,{variant:"primary",size:"sm",onClick:w,disabled:!!u||a.running,children:[u==="start"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(bs,{size:12}),"Start"]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:S,disabled:!!u||!a.running,children:[u==="stop"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(In,{size:12}),"Stop"]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:A,disabled:!!u,children:[u==="restart"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(Tt,{size:12}),"Restart"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:f,disabled:!!u,children:[u==="reindex"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(de,{size:12}),"Reindex all"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:N,disabled:!!u,title:"Wipe working dir + reindex from scratch",children:[u==="rebuild"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(Zs,{size:12}),"Rebuild graph"]})]})]}),e.jsxs("div",{className:"memory-stat-grid",children:[e.jsx(Ss,{icon:e.jsx(fa,{size:14}),label:"Indexed chunks (approx)",value:String(a.indexedApprox)}),e.jsx(Ss,{icon:e.jsx(co,{n:a.noteCount}),label:"Notes in vault",value:String(a.noteCount)}),e.jsx(Ss,{icon:e.jsx(Rt,{size:14}),label:"Queries last 24h",value:String(a.queryCountLast24h)}),e.jsx(Ss,{icon:e.jsx(Xe,{size:14}),label:"Avg response",value:a.avgResponseMs!==null?`${a.avgResponseMs} ms`:"—"}),e.jsx(Ss,{icon:a.lastReindexOk?e.jsx(qe,{size:14}):a.lastReindexOk===!1?e.jsx(et,{size:14}):e.jsx(de,{size:14}),label:"Last reindex",value:a.lastReindexAt?_e(a.lastReindexAt):"never",sub:a.lastReindexInserted!==null?`${a.lastReindexInserted} inserted${a.lastReindexFailed?`, ${a.lastReindexFailed} failed`:""}`:void 0})]}),e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsx(ye,{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:j=>x(j.target.value),onKeyDown:j=>{j.key==="Enter"&&v()},disabled:u==="query","aria-label":"Search LightRAG"}),e.jsxs($,{variant:"primary",onClick:v,disabled:u==="query"||!m.trim(),children:[u==="query"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(ye,{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(G,{children:[e.jsx(te,{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(G,{children:[e.jsxs(te,{children:[e.jsx(de,{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(`
|
|
12
|
-
`)})]})]}):e.jsx("div",{className:"muted",children:"No LightRAG data available."})}function Ss({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 co({n:s}){return e.jsxs("span",{style:{position:"relative",display:"inline-block"},children:[e.jsx(ye,{size:14}),e.jsx("span",{className:"memory-mini-badge",children:s})]})}function mo({refreshKey:s}){const t=re(),a=Re(),[i,n]=r.useState([]),[c,o]=r.useState(null),[l,h]=r.useState(!0),[p,u]=r.useState(""),[d,m]=r.useState(null),[x,g]=r.useState(!1),[b,z]=r.useState(null),[k,w]=r.useState([]),S=async()=>{var R;h(!0);try{const[y,M]=await Promise.all([T.get("/memory/notes").catch(()=>({notes:[]})),T.get("/memory/obsidian/tree").catch(()=>({tree:null}))]);n(y.notes||[]),o(M.tree),b&&!((R=y.notes)!=null&&R.find(P=>P.relPath===b))&&(z(null),w([]))}catch(y){t.error(`Vault load failed: ${y.message}`)}finally{h(!1)}};r.useEffect(()=>{S()},[s]),r.useEffect(()=>{if(!p.trim()){m(null);return}g(!0);const R=setTimeout(async()=>{try{const y=await T.get(`/memory/search?q=${encodeURIComponent(p)}&limit=50`),M=new Set((y.results||[]).map(P=>P.relPath));m(i.filter(P=>M.has(P.relPath)))}catch(y){t.error(`Search failed: ${y.message}`)}finally{g(!1)}},240);return()=>clearTimeout(R)},[p,i,t]);const A=async R=>{z(R);try{const y=await T.get(`/memory/obsidian/backlinks?note=${encodeURIComponent(R)}`);w(y.backlinks||[])}catch{w([])}},f=()=>{a.open({title:"New note",width:720,children:e.jsx(ea,{mode:"create",onSave:async(R,y,M)=>{try{await T.post("/memory/notes",{path:R,frontmatter:y,body:M}),t.success(`Created ${R}.`),a.close(),await S(),A(R)}catch(P){t.error(`Create failed: ${P.message}`)}},onCancel:()=>a.close()})})},N=async R=>{try{const y=await T.get(`/memory/notes/${R.split("/").map(encodeURIComponent).join("/")}`);a.open({title:`Edit ${R}`,width:720,children:e.jsx(ea,{mode:"edit",initial:{relPath:y.relPath,frontmatter:y.frontmatter,body:y.body},onSave:async(M,P,C)=>{try{await T.put(`/memory/notes/${M.split("/").map(encodeURIComponent).join("/")}`,{frontmatter:P,body:C}),t.success(`Saved ${M}.`),a.close(),await S(),A(M)}catch(D){t.error(`Save failed: ${D.message}`)}},onCancel:()=>a.close()})})}catch(y){t.error(`Load failed: ${y.message}`)}},v=async R=>{if(confirm(`Delete ${R}? This cannot be undone.`))try{await T.del(`/memory/notes/${R.split("/").map(encodeURIComponent).join("/")}`),t.success(`Deleted ${R}.`),b===R&&z(null),await S()}catch(y){t.error(`Delete failed: ${y.message}`)}},j=r.useMemo(()=>[...i].sort((R,y)=>y.mtime-R.mtime),[i]),E=d??j;return l&&!i.length?e.jsxs("div",{className:"view-loading",children:[e.jsx(oe,{size:"lg"}),e.jsx("p",{children:"Loading vault…"})]}):e.jsxs("div",{className:"memory-panel-content memory-obsidian-grid",children:[e.jsxs(G,{variant:"outlined",className:"memory-tree-card",children:[e.jsxs(te,{children:[e.jsx(Pe,{size:14})," Folders"]}),e.jsx(ne,{children:c?`${Ea(c)} folder(s)`:"no vault"}),e.jsx("div",{className:"memory-tree-body",children:c?e.jsx(Ia,{node:c,depth:0,onSelect:A,selected:b}):null})]}),e.jsxs("div",{className:"memory-obsidian-list-col",children:[e.jsxs("div",{className:"memory-list-toolbar",children:[e.jsxs("div",{className:"search-input",children:[e.jsx(ye,{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:p,onChange:R=>u(R.target.value),"aria-label":"Search notes"}),p&&e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>u(""),"aria-label":"Clear search",children:e.jsx(Ne,{size:12})})]}),e.jsxs($,{variant:"primary",size:"sm",onClick:f,children:[e.jsx(En,{size:12})," New note"]}),e.jsx($,{variant:"ghost",size:"sm",onClick:S,title:"Refresh",children:e.jsx(de,{size:12})})]}),x&&e.jsx("div",{className:"muted text-sm",children:"Searching…"}),E.length===0?e.jsx(pe,{icon:e.jsx(ke,{size:28}),title:"No notes",message:i.length===0?'No notes in this vault yet. Click "New note" to create one.':`No notes match "${p}".`}):e.jsx("ul",{className:"memory-note-list",children:E.map(R=>e.jsxs("li",{className:V("memory-note-card",b===R.relPath&&"memory-note-card-active"),children:[e.jsxs("button",{type:"button",className:"memory-note-card-main",onClick:()=>A(R.relPath),children:[e.jsxs("div",{className:"memory-note-card-title",children:[e.jsx(ke,{size:12}),e.jsx("span",{children:Ma(R)})]}),e.jsxs("div",{className:"memory-note-card-meta",children:[e.jsx("code",{className:"muted",children:R.relPath}),e.jsxs("span",{className:"muted",children:["· ",Te(R.mtime)]}),!R.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:()=>N(R.relPath),"aria-label":`Edit ${R.relPath}`,title:"Edit",children:e.jsx(Ls,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>v(R.relPath),"aria-label":`Delete ${R.relPath}`,title:"Delete",children:e.jsx(we,{size:12})})]})]},R.relPath))})]}),e.jsx("div",{className:"memory-obsidian-detail-col",children:b?e.jsx(uo,{relPath:b,onClose:()=>z(null)}):e.jsx(pe,{icon:e.jsx(ke,{size:28}),title:"Pick a note",message:"Select a note from the list to view its content, frontmatter, and backlinks."})})]})}function Ma(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 Ia({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(ke,{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(We,{size:11}):e.jsx(Ye,{size:11}),e.jsx(Pe,{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(Ia,{node:o,depth:t+1,onSelect:a,selected:i},`${o.path}-${l}`))})]})}function Ea(s){return s.type==="note"?0:1+(s.children||[]).reduce((t,a)=>t+Ea(a),0)}function uo({relPath:s,onClose:t}){var u,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[x,g]=await Promise.all([T.get(`/memory/notes/${s.split("/").map(encodeURIComponent).join("/")}`),T.get(`/memory/obsidian/backlinks?note=${encodeURIComponent(s)}`)]);if(m)return;i(x),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(oe,{size:"sm"})});if(!a)return e.jsx("div",{className:"muted",children:"Note not found."});const h=Array.isArray((u=a.frontmatter)==null?void 0:u.tags)?a.frontmatter.tags:[],p=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:Ma(a)}),e.jsx("button",{type:"button",className:"icon-btn",onClick:t,"aria-label":"Close",children:e.jsx(Ne,{size:12})})]}),e.jsxs("div",{className:"memory-note-detail-meta",children:[e.jsx("code",{children:s}),e.jsxs("span",{className:"muted",children:["· modified ",_e(a.mtime)]})]}),h.length>0&&e.jsx("div",{className:"memory-tag-row",children:h.map((m,x)=>e.jsx("span",{className:"memory-tag",children:String(m)},x))}),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))})]}),p.length>0&&e.jsxs("div",{className:"memory-backlinks",children:[e.jsx("h4",{children:"Forward links"}),e.jsx("ul",{children:p.map((m,x)=>e.jsx("li",{children:e.jsx("code",{children:String(m)})},x))})]})]})}function ea({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?ho(t.frontmatter):`title: ""
|
|
13
|
-
tags: []
|
|
14
|
-
`),[h,p]=r.useState((t==null?void 0:t.body)||""),[u,d]=r.useState(!1),m=re(),x=async()=>{if(!n.endsWith(".md")){m.error("Path must end in .md");return}let g;try{g=xo(o)||{}}catch(b){m.error(`Frontmatter parse failed: ${b.message}`);return}d(!0);try{await a(n,g,h)}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:h,onChange:g=>p(g.target.value),"aria-label":"Body markdown"}),e.jsxs("div",{className:"modal-footer-actions",style:{marginTop:12},children:[e.jsx($,{variant:"ghost",onClick:i,disabled:u,children:"Cancel"}),e.jsxs($,{variant:"primary",onClick:x,disabled:u,children:[u&&e.jsx(xe,{size:12,className:"memory-spin"}),s==="create"?"Create":"Save"]})]})]})}function ho(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(` - ${dt(n)}`)}else if(typeof i=="object"){t.push(`${a}:`);for(const[n,c]of Object.entries(i))t.push(` ${n}: ${dt(c)}`)}else t.push(`${a}: ${dt(i)}`);return t.join(`
|
|
15
|
-
`)}function dt(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 xo(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 h={},p=[];let u=!1,d=!1;for(;i+1<a.length;){const m=a[i+1];if(!m.startsWith(" "))break;if(m.startsWith(" - "))u=!0,p.push(mt(m.slice(4))),i++;else{d=!0;const x=m.match(/^ ([A-Za-z_][\w-]*):\s*(.*)$/);x&&(h[x[1]]=mt(x[2])),i++}}t[o]=u&&!d?p:d?h:{}}else t[o]=mt(l);i++}return t}function mt(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 po({refreshKey:s}){var S,A,f,N;const t=re(),[a,i]=r.useState(null),[n,c]=r.useState(null),[o,l]=r.useState(!0),[h,p]=r.useState(null),[u,d]=r.useState(null),m=async()=>{var v;l(!0);try{const[j,E,R]=await Promise.all([T.get("/memory/git/status").catch(()=>null),T.get("/memory/git/diff").catch(()=>null),T.get("/memory/config/global").catch(()=>null)]);i(j),c(E),d(((v=R==null?void 0:R.config)==null?void 0:v.git)||null)}catch(j){t.error(`Git status failed: ${j.message}`)}finally{l(!1)}};r.useEffect(()=>{m()},[s]);const x=async(v,j,E)=>{p(v);try{await j(),t.success(E),await m()}catch(R){t.error(`${v} failed: ${R.message}`)}finally{p(null)}},g=()=>x("pull",()=>T.post("/memory/git/pull",{}),"Pull complete."),b=()=>x("push",()=>T.post("/memory/git/push",{}),"Push complete."),z=()=>{const v=prompt("Commit message:",`[memory-sync] ${new Date().toISOString().slice(0,10)} vault sync`);v&&x("commit",()=>T.post("/memory/git/commit",{message:v}),"Committed.")},k=()=>x("fetch",()=>T.post("/memory/git/sync",{push:!1}),"Fetch complete.");if(o&&!a)return e.jsxs("div",{className:"view-loading",children:[e.jsx(oe,{size:"lg"}),e.jsx("p",{children:"Loading git status…"})]});if(!a)return e.jsx("div",{className:"muted",children:"No git data available."});const w=a.mode==="local-only";return e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(G,{variant:"elevated",children:[e.jsxs(te,{children:[e.jsx(rs,{size:14})," Git sync",w?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:w?"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]})}),!w&&e.jsxs("div",{className:"memory-git-status-row",children:[e.jsx(Cs,{ok:a.clean??!1,label:"Working tree"}),e.jsx(Cs,{ok:(a.ahead??0)===0,label:`Ahead: ${a.ahead??0}`}),e.jsx(Cs,{ok:(a.behind??0)===0,label:`Behind: ${a.behind??0}`}),e.jsx(Cs,{ok:(((S=a.modified)==null?void 0:S.length)??0)===0,label:`Modified: ${((A=a.modified)==null?void 0:A.length)??0}`}),e.jsx(Cs,{ok:(((f=a.untracked)==null?void 0:f.length)??0)===0,label:`Untracked: ${((N=a.untracked)==null?void 0:N.length)??0}`})]}),e.jsxs("div",{className:"memory-action-row",children:[e.jsxs($,{variant:"secondary",size:"sm",onClick:g,disabled:!!h||w,children:[h==="pull"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(ma,{size:12}),"Pull"]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:b,disabled:!!h||w,children:[h==="push"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx($t,{size:12}),"Push"]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:z,disabled:!!h||w,children:[h==="commit"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(ja,{size:12}),"Commit"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:k,disabled:!!h||w,children:[h==="fetch"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(Ln,{size:12}),"Fetch + sync"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:m,disabled:!!h,children:[e.jsx(de,{size:12})," Refresh"]})]})]}),u&&e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsx(pa,{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:u.repoPath,children:u.repoPath||"—"}),e.jsx("dt",{children:"Remote"}),e.jsx("dd",{className:"mono ellipsis",title:u.remoteUrl,children:u.remoteUrl||"—"}),e.jsx("dt",{children:"Branch"}),e.jsx("dd",{children:e.jsx("code",{children:u.branch||"main"})}),e.jsx("dt",{children:"Auto-sync"}),e.jsx("dd",{children:u.autoSync?"enabled":"disabled"})]})]}),e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsx(Dn,{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(v=>e.jsx("li",{children:e.jsx("code",{children:v})},v))}),n&&n.lines.length>1&&e.jsx("pre",{className:"memory-log-tail mono text-xs",children:n.lines.slice(0,400).join(`
|
|
16
|
-
`)})]})]})}function Cs({ok:s,label:t}){return e.jsxs("span",{className:V("memory-git-status-pill",s?"ok":"warn"),children:[s?e.jsx(qe,{size:11}):e.jsx(xe,{size:11,className:"memory-spin"}),t]})}function go({refreshKey:s}){const t=re(),[a,i]=r.useState(""),[n,c]=r.useState({lightrag:!0,obsidian:!0}),[o,l]=r.useState(null),[h,p]=r.useState(!1),[u,d]=r.useState(""),m=async g=>{if(g.trim()){p(!0),d(g);try{const b=[...n.lightrag?["lightrag"]:[],...n.obsidian?["obsidian"]:[]],z=await T.post("/memory/semantic-search",{query:g,limit:20,sources:b});l(z.results||[])}catch(b){t.error(`Search failed: ${b.message}`),l([])}finally{p(!1)}}};r.useEffect(()=>{u&&m(u)},[n]),r.useEffect(()=>{u&&m(u)},[s]);const x=r.useMemo(()=>{const g=(o||[]).filter(z=>z.source==="obsidian"),b=(o||[]).filter(z=>z.source==="lightrag");return{obs:g,lr:b}},[o]);return e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(G,{variant:"elevated",children:[e.jsxs(te,{children:[e.jsx(ye,{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:h,"aria-label":"Semantic search query"}),e.jsxs($,{variant:"primary",onClick:()=>m(a),disabled:h||!a.trim(),children:[h?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(ye,{size:12}),"Search"]})]}),e.jsxs("div",{className:"memory-source-toggle-row",children:[e.jsx(sa,{active:n.obsidian,onToggle:()=>c(g=>({...g,obsidian:!g.obsidian})),label:"Obsidian",icon:e.jsx(ke,{size:11})}),e.jsx(sa,{active:n.lightrag,onToggle:()=>c(g=>({...g,lightrag:!g.lightrag})),label:"LightRAG",icon:e.jsx(Ue,{size:11})}),a&&e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>{i(""),l(null),d("")},"aria-label":"Clear",children:e.jsx(Ne,{size:12})})]})]}),h&&e.jsx("div",{className:"view-loading",children:e.jsx(oe,{size:"md"})}),!h&&o&&o.length===0&&e.jsx(pe,{icon:e.jsx(ye,{size:28}),title:"No matches",message:`Nothing in scope matched "${u}".`}),x.obs.length>0&&e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsx(ke,{size:14})," Obsidian (",x.obs.length,")"]}),e.jsx("ul",{className:"memory-search-result-list",children:x.obs.map((g,b)=>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-${b}`))})]}),x.lr.length>0&&e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsx(Ue,{size:14})," LightRAG (",x.lr.length,")"]}),e.jsx("div",{className:"memory-search-result-list",children:x.lr.map((g,b)=>e.jsxs("div",{className:"memory-search-result",children:[e.jsxs("div",{className:"memory-search-result-head",children:[e.jsxs("span",{className:"memory-source-pill",children:[e.jsx(Ue,{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-${b}`))})]})]})}function sa({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 fo({refreshKey:s}){const t=re(),[a,i]=r.useState(null),[n,c]=r.useState(!0),[o,l]=r.useState(!1),[h,p]=r.useState(""),[u]=r.useState(""),[d,m]=r.useState(null),[x,g]=r.useState(null),[b,z]=r.useState(null),[k,w]=r.useState(!1),S=async()=>{var j,E;c(!0);try{const R=await T.get("/memory/config/global");i(R.config),p(((E=(j=R.config)==null?void 0:j.git)==null?void 0:E.remoteUrl)||""),await A()}catch(R){t.error(`Config load failed: ${R.message}`)}finally{c(!1)}},A=async()=>{try{const j=await T.get("/memory/git/status");j.ok&&m({clean:j.clean,branch:j.branch,modified:j.modified,untracked:j.untracked})}catch{}};r.useEffect(()=>{S()},[s]);const f=async()=>{if(a){l(!0);try{await T.put("/memory/config/global",{git:{remoteUrl:h}}),t.success("Config saved.")}catch(j){t.error(`Save failed: ${j.message}`)}finally{l(!1)}}},N=async j=>{g(j);try{if(j==="pull"){const E=await T.post("/memory/git/pull",{});E.ok?t.success("Pull successful."):t.error(`Pull failed: ${E.output||"unknown error"}`)}else if(j==="push")(await T.post("/memory/git/push",{})).ok?t.success("Push successful."):t.error("Push failed.");else if(j==="commit"){const E=await T.post("/memory/git/commit",{});E.ok?t.success(`Committed: ${E.message}`):t.error("Commit failed.")}await A()}catch(E){t.error(`${j} failed: ${E.message}`)}finally{g(null)}},v=async()=>{w(!0);try{const j=await T.post("/memory/test-git",{});z(j.checks)}catch(j){t.error(`Test failed: ${j.message}`)}finally{w(!1)}};return n&&!a?e.jsxs("div",{className:"view-loading",children:[e.jsx(oe,{size:"md"}),e.jsx("p",{children:"Loading config…"})]}):a?e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsx(rs,{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(ut,{label:"Vault path",inline:!0,children:e.jsx("span",{className:"memory-vault-path mono muted",children:u||"(loading…)"})}),e.jsx(ut,{label:"Remote URL",children:e.jsx("input",{type:"text",className:"input mono",value:h,onChange:j=>p(j.target.value),placeholder:"git@github.com:org/repo.git"})}),d&&e.jsxs(ut,{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(rs,{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($,{variant:"secondary",onClick:()=>N("pull"),disabled:x!==null,children:[x==="pull"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(ls,{size:12}),"Pull"]}),e.jsxs($,{variant:"secondary",onClick:()=>N("commit"),disabled:x!==null,children:[x==="commit"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(ja,{size:12}),"Commit"]}),e.jsxs($,{variant:"secondary",onClick:()=>N("push"),disabled:x!==null,children:[x==="push"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(Pn,{size:12}),"Push"]})]})]}),e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsx(jt,{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($,{variant:"secondary",onClick:v,disabled:k,children:[k?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(jt,{size:12}),"Test git connection"]}),e.jsxs($,{variant:"primary",onClick:f,disabled:o,children:[o?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(Ms,{size:12}),"Save config"]})]}),b&&b.length>0&&e.jsx("ul",{className:"memory-check-list",style:{marginTop:12},children:b.map((j,E)=>e.jsxs("li",{className:"memory-check-row",children:[e.jsx("span",{className:"memory-check-icon",children:e.jsx("span",{className:V("memory-pill",j.pass?"memory-pill-ok":"memory-pill-warn"),children:j.pass?"OK":"FAIL"})}),e.jsx("span",{className:"memory-check-name",children:j.name}),e.jsx("span",{className:"memory-check-detail muted",children:j.detail})]},E))})]})]}):e.jsx("div",{className:"muted",children:"No config available."})}function ut({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 Ge=800,ta=60,ht={default:"#8b5cf6",note:"#8b5cf6",entity:"#34d399",concept:"#fbbf24",root:"#f87171"};function jo(s,t){return ht[s]||ht[t]||ht.default}function vo(s){return 6+Math.min(s.size*2,10)}function yo(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,h)=>{const p=h/s.length*Math.PI*2,u=Ge*.28;return{...l,x:Ge/2+u*Math.cos(p)+(Math.random()-.5)*40,y:Ge/2+u*Math.sin(p)+(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<ta;l++){const h=1-l/ta;for(let d=0;d<i.length;d++)for(let m=d+1;m<i.length;m++){const x=i[d],g=i[m],b=g.x-x.x,z=g.y-x.y,k=Math.sqrt(b*b+z*z)||1,w=400*h/(k*k),S=b/k*w,A=z/k*w;x.vx-=S,x.vy-=A,g.vx+=S,g.vy+=A}for(const d of t){const m=n.get(d.source),x=n.get(d.target);if(!m||!x)continue;const g=x.x-m.x,b=x.y-m.y,z=Math.sqrt(g*g+b*b)||1,w=(z-80)*.08*h,S=g/z*w,A=b/z*w;m.vx+=S,m.vy+=A,x.vx-=S,x.vy-=A}const p=Ge/2,u=Ge/2;for(const d of i)d.vx+=(p-d.x)*.01*h,d.vy+=(u-d.y)*.01*h;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(Ge-20,d.x)),d.y=Math.max(20,Math.min(Ge-20,d.y))}return i}function bo({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}),h=r.useRef(null),[p,u]=r.useState(null),[d,m]=r.useState(null),x=r.useMemo(()=>yo(s.nodes,s.edges),[s.nodes,s.edges]),g=r.useMemo(()=>{const j=new Map;for(const E of x)j.set(E.id,E);return j},[x]),b=r.useCallback(j=>{j.target.closest(".memory-graph-node")||(o.current=!0,l.current={x:j.clientX,y:j.clientY,tx:n.x,ty:n.y})},[n]),z=r.useCallback(j=>{if(!o.current)return;const E=j.clientX-l.current.x,R=j.clientY-l.current.y;c(y=>({...y,x:l.current.tx+E,y:l.current.ty+R}))},[]),k=r.useCallback(()=>{o.current=!1},[]),w=r.useCallback(j=>{j.preventDefault();const E=j.deltaY<0?1.1:.9,R=i.current;if(!R)return;const y=R.getBoundingClientRect(),M=j.clientX-y.left,P=j.clientY-y.top;c(C=>{const D=Math.max(.2,Math.min(4,C.scale*E)),Y=D/C.scale;return{x:M-(M-C.x)*Y,y:P-(P-C.y)*Y,scale:D}})},[]),S=r.useCallback(j=>{const E=Array.from(j.touches);if(E.length===2){const[R,y]=E;h.current=Math.hypot(y.clientX-R.clientX,y.clientY-R.clientY)}else E.length===1&&(o.current=!0,l.current={x:E[0].clientX,y:E[0].clientY,tx:n.x,ty:n.y})},[n]),A=r.useCallback(j=>{const E=Array.from(j.touches);if(E.length===2&&h.current!==null){const[R,y]=E,M=Math.hypot(y.clientX-R.clientX,y.clientY-R.clientY),P=M/h.current;h.current=M,c(C=>({...C,scale:Math.max(.2,Math.min(4,C.scale*P))}))}else if(E.length===1&&o.current){const R=E[0].clientX-l.current.x,y=E[0].clientY-l.current.y;c(M=>({...M,x:l.current.tx+R,y:l.current.ty+y}))}},[]),f=r.useCallback(()=>{o.current=!1,h.current=null},[]),N=r.useCallback(j=>{u(j.id===p?null:j.id),t==null||t(j)},[p,t]),v=Math.max(.5,1/Math.log2(n.scale+1));return e.jsx("svg",{ref:i,className:V("memory-graph-canvas",a),viewBox:`0 0 ${Ge} ${Ge}`,style:{width:"100%",height:"100%",minHeight:400,cursor:o.current?"grabbing":"grab"},onMouseDown:b,onMouseMove:z,onMouseUp:k,onMouseLeave:k,onWheel:w,onTouchStart:S,onTouchMove:A,onTouchEnd:f,children:e.jsxs("g",{transform:`translate(${n.x},${n.y}) scale(${n.scale})`,children:[s.edges.map((j,E)=>{const R=g.get(j.source),y=g.get(j.target);if(!R||!y)return null;const M=d===j.source||d===j.target||p===j.source||p===j.target;return e.jsx("line",{x1:R.x,y1:R.y,x2:y.x,y2:y.y,stroke:M?"#8b5cf6":"#2d3648",strokeWidth:M?v*2:v,strokeOpacity:M?.9:.5},`e-${E}`)}),x.map(j=>{const E=vo(j),R=jo(j.group,j.type),y=p===j.id,M=d===j.id;return e.jsxs("g",{className:"memory-graph-node",transform:`translate(${j.x},${j.y})`,onClick:()=>N(j),onMouseEnter:()=>m(j.id),onMouseLeave:()=>m(null),style:{cursor:"pointer"},children:[e.jsx("circle",{r:E+6,fill:"transparent"}),(y||M)&&e.jsx("circle",{r:E+4,fill:R,fillOpacity:.2}),e.jsx("circle",{r:E,fill:R,fillOpacity:y?1:.75,stroke:y?"#fff":R,strokeWidth:y?2:1}),n.scale>.5&&e.jsx("text",{y:E+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:j.label.length>20?j.label.slice(0,18)+"…":j.label})]},j.id)})]})})}const No=[{color:"#8b5cf6",label:"Note / Default"},{color:"#34d399",label:"Entity (LightRAG)"},{color:"#fbbf24",label:"Concept (LightRAG)"},{color:"#f87171",label:"Root / Ungrouped"}];function ko({className:s}){return e.jsx("div",{className:V("memory-graph-legend",s),children:No.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 wo({refreshKey:s}){const t=re(),[a,i]=r.useState({nodes:[],edges:[]}),[n,c]=r.useState(!0),[o,l]=r.useState(null),[h,p]=r.useState(""),[u,d]=r.useState(2),[m,x]=r.useState(""),[g,b]=r.useState(null),[z,k]=r.useState(null),w=r.useCallback(async()=>{var f,N;c(!0),l(null);try{const v=new URLSearchParams({limit:"200"});m&&v.set("root",m),v.set("depth",String(u));const j=await T.get(`/memory/graph?${v}`);i({nodes:j.nodes||[],edges:j.edges||[]}),b({totalNodes:j.totalNodes??((f=j.nodes)==null?void 0:f.length)??0,totalEdges:j.totalEdges??((N=j.edges)==null?void 0:N.length)??0})}catch(v){l(v.message),t.error(`Graph load failed: ${v.message}`)}finally{c(!1)}},[m,u,t]);r.useEffect(()=>{w()},[w,s]);const S=r.useCallback(f=>{k(N=>(N==null?void 0:N.id)===f.id?null:f)},[]),A=h.trim()?{nodes:a.nodes.filter(f=>f.label.toLowerCase().includes(h.toLowerCase())),edges:a.edges.filter(f=>a.nodes.some(N=>N.id===f.source&&N.label.toLowerCase().includes(h.toLowerCase()))||a.nodes.some(N=>N.id===f.target&&N.label.toLowerCase().includes(h.toLowerCase())))}:a;return e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsx(va,{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:h,onChange:f=>p(f.target.value),style:{maxWidth:240}}),e.jsx("input",{type:"text",className:"input",placeholder:"Root note id (optional)",value:m,onChange:f=>x(f.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:u,onChange:f=>d(parseInt(f.target.value,10)),style:{marginLeft:8,verticalAlign:"middle"}}),u]}),e.jsx("button",{type:"button",className:"icon-btn",onClick:w,title:"Refresh graph",disabled:n,children:e.jsx(de,{size:14,className:n?"memory-spin":""})})]}),e.jsx(ko,{})]})]}),e.jsx(G,{children:n&&!a.nodes.length?e.jsxs("div",{className:"view-loading",children:[e.jsx(oe,{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(bo,{data:A,onNodeClick:S,className:"memory-graph-canvas-svg"}),h&&e.jsxs("div",{className:"text-xs muted",style:{marginTop:4},children:["Showing ",A.nodes.length," of ",a.nodes.length," nodes"]})]})}),z&&e.jsxs(G,{children:[e.jsx(te,{children:z.label}),e.jsx(ne,{children:e.jsx("code",{children:z.id})}),e.jsxs("dl",{className:"memory-config-row",children:[e.jsx("dt",{children:"Type"}),e.jsx("dd",{children:e.jsx("code",{children:z.type})}),e.jsx("dt",{children:"Group"}),e.jsx("dd",{children:e.jsx("code",{children:z.group})}),e.jsx("dt",{children:"Size"}),e.jsx("dd",{children:z.size})]})]}),g&&e.jsx(G,{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":""]}),h&&e.jsxs("span",{className:"muted",children:["· ",A.nodes.length," shown"]})]})})]})}function So({onTextExtracted:s}){const t=re(),[a,i]=r.useState(null),[n,c]=r.useState(!1),[o,l]=r.useState(!1),h=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 x=document.createElement("canvas");x.width=m.videoWidth,x.height=m.videoHeight;const g=x.getContext("2d");if(!g){t.error("Failed to get canvas context");return}g.drawImage(m,0,0),d.getTracks().forEach(b=>b.stop()),m.remove(),x.toBlob(async b=>{if(!b){t.error("Failed to capture screenshot");return}const z=URL.createObjectURL(b);i(z),await p(b)},"image/png")}catch(d){d.name!=="NotAllowedError"&&t.error(`Capture failed: ${d.message}`)}finally{l(!1)}},[t]),p=r.useCallback(async d=>{c(!0);try{const m=new FileReader,x=await new Promise((b,z)=>{m.onload=()=>{const k=m.result,w=k.includes(",")?k.split(",")[1]:k;b(w)},m.onerror=()=>z(new Error("FileReader failed")),m.readAsDataURL(d)}),g=await T.post("/ocr/process",{image:x,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]),u=r.useCallback(()=>{i(null)},[]);return e.jsxs(G,{variant:"outlined",className:"screenshot-capture-card",children:[e.jsxs(te,{children:[e.jsx(tt,{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($,{variant:"ghost",size:"sm",onClick:u,disabled:n,children:"Dismiss"})]})]}):e.jsxs("div",{className:"screenshot-capture-empty",children:[e.jsx(tt,{size:32,className:"muted"}),e.jsx("p",{className:"muted text-sm",children:"Capture your screen to extract text via OCR."}),e.jsxs($,{variant:"primary",size:"sm",onClick:h,disabled:o,children:[o?e.jsx(xe,{size:12,className:"spinner"}):e.jsx(tt,{size:12}),o?"Selecting…":"Capture Screen"]})]})})]})}function Co(){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(So,{onTextExtracted:n}),s!==null&&e.jsxs(G,{variant:"outlined",className:"screenshot-ocr-result-card",children:[e.jsxs(te,{children:[e.jsx(ke,{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 zo({refreshKey:s}){return e.jsx("div",{className:"memory-panel-content",children:e.jsx(G,{variant:"outlined",className:"memory-panel-card",children:e.jsx("div",{className:"memory-panel-body",children:e.jsx(Co,{})})})})}function To({refreshKey:s}){const t=re(),[a,i]=r.useState(""),[n,c]=r.useState(""),[o,l]=r.useState(""),[h,p]=r.useState(!1),u=async()=>{if(!o.trim()){t.error("Content is required");return}p(!0);try{const d=await T.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{p(!1)}};return e.jsx("div",{className:"memory-panel-content",children:e.jsx(G,{variant:"outlined",className:"memory-panel-card",children:e.jsx("div",{className:"memory-panel-body",children:e.jsxs("div",{className:"vault-clipboard-panel",children:[e.jsxs("div",{className:"vault-clipboard-header",children:[e.jsx(ya,{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($,{variant:"primary",size:"sm",onClick:u,disabled:h||!o.trim(),children:[h&&e.jsx(xe,{size:12,className:"spinner"}),"Save to Vault"]})})]})})})})}function Ro({vaultPath:s,onSaved:t}){const[a,i]=r.useState(!1),[n,c]=r.useState(!1),o=r.useRef(null),l=r.useRef([]),h=async()=>{try{const d=await navigator.mediaDevices.getUserMedia({audio:!0}),m=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm",x=new MediaRecorder(d,{mimeType:m});x.ondataavailable=g=>{g.data&&g.data.size>0&&l.current.push(g.data)},x.onstop=async()=>{const g=new Blob(l.current,{type:"audio/webm"});l.current=[],d.getTracks().forEach(b=>b.stop()),await u(g)},x.start(1e3),o.current=x,i(!0)}catch(d){console.error("[VoiceRecorder] failed to start recording:",d)}},p=()=>{const d=o.current;d&&(d.stop(),i(!1),c(!0))},u=async d=>{try{const m=new FormData;m.append("audio",d,"voice-note.webm"),m.append("vaultPath",s||"");const x=await fetch("/api/voice/upload",{method:"POST",body:m});if(!x.ok){console.error("[VoiceRecorder] upload failed:",x.status,await x.text()),c(!1);return}const{notePath:g,transcription:b}=await x.json();t==null||t(g,b)}catch(m){console.error("[VoiceRecorder] upload error:",m)}finally{c(!1)}};return e.jsxs("div",{className:"voice-recorder",children:[!a&&!n&&e.jsxs($,{variant:"accent",size:"sm",onClick:h,"aria-label":"Start recording",children:[e.jsx(Lt,{size:14})," Record"]}),a&&e.jsxs($,{variant:"danger",size:"sm",onClick:p,"aria-label":"Stop recording",children:[e.jsx(Fn,{size:14})," Stop"]}),n&&e.jsxs($,{variant:"secondary",size:"sm",disabled:!0,children:[e.jsx(xe,{size:14,className:"spinning"})," Transcribing…"]})]})}function $o({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(At,{size:13}):e.jsx(bs,{size:13})}),e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>t(s.id),"aria-label":"Delete note",title:"Delete note",children:e.jsx(we,{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 Ao({vaultPath:s,refreshKey:t=0}){const[a,i]=r.useState([]),[n,c]=r.useState(""),[o,l]=r.useState(!0),h=async()=>{l(!0);try{const d=s?`?vaultPath=${encodeURIComponent(s)}`:"",x=await(await fetch(`/api/voice/list${d}`)).json();i(x.notes||[])}catch(d){console.error("[VoiceNotesPanel] failed to load notes:",d)}finally{l(!1)}};r.useEffect(()=>{h();const d=g=>{try{const b=JSON.parse(g.data);b.type==="voice:updated"&&b.noteId&&i(z=>z.map(k=>{var w;return k.id===b.noteId?{...k,transcript:((w=b.patch)==null?void 0:w.transcript)??k.transcript}:k}))}catch{}},m=`${location.protocol==="https:"?"wss":"ws"}://${location.host}/ws`;let x=null;try{x=new WebSocket(m),x.addEventListener("message",d)}catch{}return()=>{x==null||x.removeEventListener("message",d),x==null||x.close()}},[s,t]);const p=async d=>{try{const m=await fetch(`/api/voice/${d}`,{method:"DELETE"});(m.ok||m.status===204)&&i(x=>x.filter(g=>g.id!==d))}catch(m){console.error("[VoiceNotesPanel] delete failed:",m)}},u=a.filter(d=>{var m;return!n||(((m=d.transcript)==null?void 0:m.toLowerCase().includes(n.toLowerCase()))??!1)});return e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsx(Lt,{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(Ro,{vaultPath:s,onSaved:h})}),o?e.jsx("p",{className:"muted text-sm",children:"Loading notes…"}):u.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:u.map(d=>e.jsx($o,{note:d,onDelete:p},d.id))})]})}const Mo=[{id:"overview",label:"Overview",icon:oa},{id:"lightrag",label:"LightRAG",icon:Ue},{id:"obsidian",label:"Obsidian Vault",icon:ke},{id:"git",label:"Git Sync",icon:rs},{id:"semantic",label:"Semantic Search",icon:ye},{id:"config",label:"Config",icon:Ct},{id:"graph",label:"Memory Graph",icon:va},{id:"webclip",label:"Web Clip",icon:ya},{id:"screenshot",label:"Screenshot OCR",icon:On},{id:"voice",label:"Voice Notes",icon:Lt}];function Io(s){const t=re(),[a,i]=r.useState("overview"),[n,c]=r.useState(0),o=r.useCallback(()=>{c(p=>p+1)},[]),l=r.useCallback(async()=>{o(),t.info("Refreshing memory…",1200)},[o,t]),h=()=>{switch(a){case"overview":return e.jsx(ro,{refreshKey:n,onRefresh:o,setActiveSubPanel:i});case"lightrag":return e.jsx(oo,{refreshKey:n});case"obsidian":return e.jsx(mo,{refreshKey:n});case"git":return e.jsx(po,{refreshKey:n});case"semantic":return e.jsx(go,{refreshKey:n});case"config":return e.jsx(fo,{refreshKey:n});case"graph":return e.jsx(wo,{refreshKey:n});case"webclip":return e.jsx(To,{refreshKey:n});case"screenshot":return e.jsx(zo,{refreshKey:n});case"voice":return e.jsx(Ao,{refreshKey:n});default:return e.jsxs(G,{children:["Unknown panel: ",a]})}};return e.jsxs("div",{className:"view view-memory memory-tab",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(Ue,{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(de,{size:14})})})]}),e.jsxs("div",{className:"memory-tab-body",children:[e.jsx("nav",{className:"memory-source-rail","aria-label":"Memory sources",children:Mo.map(p=>{const u=p.icon,d=a===p.id;return e.jsxs("button",{type:"button",role:"tab","aria-selected":d,className:V("memory-source-button",d&&"memory-source-button-active"),onClick:()=>i(p.id),children:[e.jsx(u,{size:16,"aria-hidden":!0}),e.jsx("span",{children:p.label})]},p.id)})}),e.jsx("div",{className:"memory-main",children:h()},a)]})]})}const Eo=Fe.memo(Io),zs=[{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 Lo(s,t,a,i){const n=a.has(s.id);return e.jsxs(G,{className:"history-project",style:{marginBottom:4},children:[e.jsxs("div",{className:"history-project-head",children:[e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4,minWidth:0,flex:1},children:[e.jsxs("div",{className:"history-project-name",children:[e.jsx(Pe,{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(ke,{size:11})," ",e.jsx("span",{className:"history-project-stat-num",children:s.plans}),e.jsxs("span",{className:"muted",children:[" plan",s.plans===1?"":"s"]})]}),s.lastAccessed&&e.jsx("span",{className:"history-project-stat",children:e.jsxs("span",{className:"muted",children:["last opened ",Te(s.lastAccessed)]})})]}),e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>i(s.id),"aria-label":n?"Collapse":"Expand",children:n?e.jsx(We,{size:14}):e.jsx(Ye,{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 Do({snapshot:s}){var z,k;const t=re(),[a,i]=r.useState(null),[n,c]=r.useState(!0),[o,l]=r.useState("1d"),[h,p]=r.useState(new Set),[u,d]=r.useState(0),m=async w=>{try{const S=w?`?since=${encodeURIComponent(w)}&limit=1000`:"?limit=1000",A=await T.get(`/history${S}`);i(A),p(new Set(A.projects.filter(f=>A.events.some(N=>N.projectId===f.id)).map(f=>f.id)))}catch(S){t.error(`History load failed: ${S.message}`)}finally{c(!1)}};r.useEffect(()=>{c(!0);const w=zs.find(S=>S.id===o)||zs[1];if(w.ms>0){const S=new Date(Date.now()-w.ms).toISOString();m(S)}else m()},[o]),r.useEffect(()=>{const w=setInterval(()=>d(S=>S+1),3e4);return()=>clearInterval(w)},[]);const x=new Map;for(const w of(a==null?void 0:a.events)||[]){const S=w.projectId||"global";x.has(S)||x.set(S,[]),x.get(S).push(w)}const g=w=>{p(S=>{const A=new Set(S);return A.has(w)?A.delete(w):A.add(w),A})},b=()=>{if(!a)return;const w=new Blob([JSON.stringify(a,null,2)],{type:"application/json"}),S=URL.createObjectURL(w),A=document.createElement("a");A.href=S,A.download=`bizar-history-${new Date().toISOString().replace(/[:.]/g,"-")}.json`,A.click(),URL.revokeObjectURL(S),t.success("History exported.")};return e.jsxs("div",{className:"view view-history","data-tick":u,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(As,{size:18})," History"]}),e.jsxs("p",{className:"view-subtitle",children:["Cross-project history of events, tasks, and plans.",((z=a==null?void 0:a.stats)==null?void 0:z.lastTs)&&e.jsxs(e.Fragment,{children:[" · last event ",Te(a.stats.lastTs)]})]})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs("div",{className:"tasks-toolbar-group",children:[e.jsx(Bn,{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:w=>l(w.target.value),title:"Time range","aria-label":"Time range",children:zs.map(w=>e.jsx("option",{value:w.id,children:w.label},w.id))})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>{c(!0);const w=zs.find(S=>S.id===o)||zs[1];w.ms>0?m(new Date(Date.now()-w.ms).toISOString()):m()},children:[e.jsx(de,{size:14})," Refresh"]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:b,children:[e.jsx(ls,{size:14})," Export"]})]})]}),n&&e.jsxs("div",{className:"view-loading",children:[e.jsx(oe,{size:"lg"}),e.jsx("p",{children:"Loading history…"})]}),!n&&a&&e.jsxs("div",{className:"history-list",children:[a.projects.length===0&&e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsx(Pe,{size:14})," No projects"]}),e.jsx(ne,{children:"Register a project in Overview to start tracking history."})]}),a.projects.length>0&&e.jsx(Dt,{items:a.projects,itemHeight:70,height:Math.min(a.projects.length*70,500),className:"history-virtual-list",renderItem:w=>Lo(w,x.get(w.id)||[],h,g)}),x.has("global")&&e.jsxs(G,{className:"history-project",children:[e.jsx("div",{className:"history-project-head",children:e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4,minWidth:0,flex:1},children:[e.jsxs("div",{className:"history-project-name",children:[e.jsx(As,{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:(x.get("global")||[]).slice(-100).reverse().map((w,S)=>e.jsxs("div",{className:"history-timeline-row",children:[e.jsx("span",{className:"history-timeline-ts",children:new Date(w.ts).toLocaleTimeString()}),e.jsx("span",{className:"history-timeline-kind",children:w.kind||"event"}),e.jsxs("span",{className:"history-timeline-msg",title:String(w.text||w.title||""),children:[w.author?`@${w.author} `:"",String(w.text??w.title??w.name??"")]})]},S))})]}),((k=a.stats)==null?void 0:k.counts)&&Object.keys(a.stats.counts).length>0&&e.jsxs(G,{children:[e.jsx(te,{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((w,S)=>S[1]-w[1]).slice(0,30).map(([w,S])=>e.jsxs("span",{className:V("tag","tag-neutral"),style:{fontFamily:"var(--font-mono)"},children:[w,": ",S]},w))})]})]})]})}const ve={top:16,right:20,bottom:40,left:52};function Po({series:s,height:t=280,onHover:a,className:i}){const n=r.useRef(null),[c,o]=r.useState(null),{labels:l,requests:h,tokens:p}=s,u=l.length;if(u===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-ve.left-ve.right,m=t-ve.top-ve.bottom,x=Math.max(...h,1),g=Math.max(...p,1),b=Math.max(4,Math.min(24,Math.floor(d/u)-4)),z=(d-b*u)/(u+1);function k(M){return ve.left+z+M*(b+z)}function w(M){return M/x*m*.75}function S(M){return ve.top+m-M/g*m*.75}const A=p.map((M,P)=>`${k(P)+b/2},${S(M)}`).join(" "),f=[0,.25,.5,.75,1].map(M=>({y:ve.top+m-M*m*.75,label:M===0?"0":`${Math.round(x*M).toLocaleString()}`})),N=[0,.25,.5,.75,1].map(M=>({y:ve.top+m-M*m*.75,label:M===0?"0":`${Math.round(g*M/1e3)}k`})),v=Math.max(1,Math.floor(u/7)),j=l.map((M,P)=>({i:P,l:M,x:k(P)+b/2})).filter((M,P)=>P%v===0),E=r.useCallback(M=>{if(!n.current)return;const P=n.current.getBoundingClientRect(),C=(M.clientX-P.left)*(600/P.width),D=(M.clientY-P.top)*(t/P.height),Y=C-ve.left,O=Math.round((Y-z/2)/(b+z)),Q=Math.max(0,Math.min(u-1,O));o({index:Q,x:M.clientX-P.left,y:M.clientY-P.top}),a==null||a(Q,C,D)},[u,b,z,a,t]),R=r.useCallback(()=>{o(null),a==null||a(null,0,0)},[a]),y=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:E,onMouseLeave:R,children:[f.map((M,P)=>e.jsx("line",{x1:ve.left,y1:M.y,x2:600-ve.right,y2:M.y,stroke:"var(--border)",strokeWidth:1,strokeDasharray:"4,3",opacity:.5},`grid-${P}`)),f.map((M,P)=>e.jsx("text",{x:ve.left-6,y:M.y+4,textAnchor:"end",fontSize:10,fill:"var(--text-muted)",fontFamily:"var(--font-mono, ui-monospace, monospace)",children:M.label},`ly-${P}`)),N.map((M,P)=>e.jsx("text",{x:600-ve.right+6,y:M.y+4,textAnchor:"start",fontSize:10,fill:"var(--text-muted)",fontFamily:"var(--font-mono, ui-monospace, monospace)",children:M.label},`ry-${P}`)),h.map((M,P)=>{const C=w(M),D=k(P),Y=ve.top+m-C;return e.jsx("rect",{x:D,y:Y,width:b,height:C,rx:2,fill:((y==null?void 0:y.index)===P,"var(--accent)"),opacity:(y==null?void 0:y.index)===P?1:.75,style:{transition:"opacity 120ms ease"}},`bar-${P}`)}),e.jsx("polyline",{points:A,fill:"none",stroke:"var(--warning, #d29922)",strokeWidth:2,strokeLinejoin:"round",strokeLinecap:"round",opacity:.9}),p.map((M,P)=>e.jsx("circle",{cx:k(P)+b/2,cy:S(M),r:(y==null?void 0:y.index)===P?5:3,fill:"var(--warning, #d29922)",opacity:(y==null?void 0:y.index)===P?1:.7,style:{transition:"r 120ms ease"}},`dot-${P}`)),j.map(({i:M,l:P,x:C})=>e.jsx("text",{x:C,y:ve.top+m+18,textAnchor:"middle",fontSize:10,fill:"var(--text-muted)",fontFamily:"var(--font-mono, ui-monospace, monospace)",children:P},`xl-${M}`)),e.jsx("line",{x1:ve.left,y1:ve.top+m,x2:600-ve.right,y2:ve.top+m,stroke:"var(--border)",strokeWidth:1})]}),y!==null&&e.jsxs("div",{className:"usage-chart-tooltip",style:{left:Math.min(y.x+12,460),top:y.y-60},children:[e.jsx("div",{className:"usage-tooltip-date",children:l[y.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:h[y.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:p[y.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 Fo({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 Oo({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(St,{size:13})," Token Plan"]}),e.jsxs("button",{className:V("minimax-sub-tab",a==="analytics"&&"is-active"),onClick:()=>i("analytics"),children:[e.jsx(ba,{size:13})," Usage Analytics"]})]}),a==="quota"?e.jsx(Bo,{activeTab:s,setActiveTab:t}):e.jsx(Uo,{toast:n})]})}function Bo({activeTab:s,setActiveTab:t}){var K;const a=re(),[i,n]=r.useState(null),[c,o]=r.useState(null),[l,h]=r.useState(null),[p,u]=r.useState(!0),[d,m]=r.useState(!1),[x,g]=r.useState(null),[b,z]=r.useState(null),[k,w]=r.useState(!1),[S,A]=r.useState(0),[f,N]=r.useState(!1),[v,j]=r.useState(null),[E,R]=r.useState(""),[y,M]=r.useState(!1),[P,C]=r.useState(!1),D=r.useCallback(async()=>{u(!0),g(null);try{const[B,Z,he]=await Promise.all([T.get("/minimax/status"),T.get("/minimax/remains"),T.get("/minimax/onboarding")]);n(B),o(Z),h(he),B.configured&&A(4)}catch(B){g(B.message||"Failed to load MiniMax data")}finally{u(!1)}},[]);r.useEffect(()=>{D()},[D]);const Y=r.useCallback(async()=>{try{await T.post("/minimax/onboarding",{dismissedAt:Date.now()}),h(B=>B&&{...B,dismissedAt:Date.now()})}catch{}},[]),O=r.useCallback(async()=>{if(!E.trim()){a.error("Paste a Subscription Key first.");return}N(!0),j(null);try{const B=await T.post("/minimax/test",{prompt:"Reply with a single word: pong",model:"MiniMax-M3",maxTokens:16});if(j(B),B.ok){A(3),a.success("Key works. Saving…");try{await T.post("/minimax/onboarding/save-key",{key:E.trim(),groupId:"default"}),ae(),a.success("Subscription Key saved.")}catch(Z){a.error(`Save failed: ${Z.message}`)}D()}else a.error(`Verification failed: ${B.message??B.error??"unknown"}`)}catch(B){a.error(`Test request failed: ${B.message}`)}finally{N(!1)}},[E,a,D]),Q=r.useCallback(async()=>{if(!E.trim()){a.error("Paste a Subscription Key first.");return}C(!0);try{const B=await T.post("/minimax/onboarding/save-key",{key:E.trim(),groupId:"default"});if(!B.ok){a.error(`Save failed: ${B.message??B.error??"unknown"}`);return}R(""),ae(),a.success("Subscription Key saved. Loading quota…"),D()}catch(B){a.error(`Save failed: ${B.message}`)}finally{C(!1)}},[E,a,D]),ae=r.useCallback(async()=>{try{await T.del("/minimax/cache")}catch{}},[]),ee=r.useCallback(async()=>{m(!0),g(null);try{await T.post("/minimax/remains/refresh"),await D(),a.success("Refreshed")}catch(B){a.error(`Refresh failed: ${B.message}`)}finally{m(!1)}},[D,a]),F=r.useCallback(async()=>{var B;w(!0),z(null);try{const Z=await T.post("/minimax/test",{prompt:"Reply with a single word: pong",model:"MiniMax-M3",maxTokens:16});z(Z),Z.ok?a.success(`Test ok — used ${((B=Z.usage)==null?void 0:B.total_tokens)??"?"} tokens`):a.error(`Test failed: ${Z.message??Z.error??"unknown"}`)}catch(Z){a.error(`Test request failed: ${Z.message}`)}finally{w(!1)}},[a]);return p&&!i?e.jsxs("div",{className:"view-container",children:[e.jsx(oe,{})," Loading MiniMax data…"]}):i?!i.configured&&(l==null?void 0:l.dismissedAt)==null&&S<4?e.jsx(qo,{step:S,setStep:A,keyDraft:E,setKeyDraft:R,showKey:y,setShowKey:M,verifying:f,verifyResult:v,onVerify:O,onSkip:async()=>{await Y(),a.success("Skipped.")},onManualKeySave:Q,savingKey:P,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(St,{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($,{variant:"secondary",size:"sm",onClick:()=>t("settings"),title:"Configure your Subscription Key",children:[e.jsx(It,{size:14})," ",i.configured?`Key ${i.apiKeyHint}`:"Add key"]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:ee,disabled:d,children:[d?e.jsx(xe,{size:14,className:"spin"}):e.jsx(de,{size:14})," Refresh"]})]})]}),c&&!c.ok&&e.jsxs("div",{className:"banner banner-err",children:[e.jsx(ze,{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(Bs,{label:"Models tracked",value:String(c.models.length),hint:"Distinct model quotas returned by the API"}),e.jsx(Bs,{label:"Last fetched",value:c.fetchedAt?Wo(c.fetchedAt):"—",hint:"Refreshed on demand + every 60s"}),e.jsx(Bs,{label:"Group",value:c.groupId??"—",hint:"Usually 'default' for an individual team"}),e.jsx(Bs,{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(B=>e.jsx(_o,{model:B},B.model_name))})]}),i.configured&&e.jsxs(G,{id:"minimax-test",children:[e.jsxs(te,{children:[e.jsx(Ze,{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($,{onClick:F,disabled:k,variant:"primary",size:"sm",children:[k?e.jsx(xe,{size:14,className:"spin"}):e.jsx(Ze,{size:14})," Send test prompt"]}),e.jsx("code",{className:"minimax-test-prompt",children:'"Reply with a single word: pong"'})]}),b&&e.jsxs("div",{className:V("minimax-test-result",b.ok?"ok":"err"),children:[b.ok?e.jsx(qe,{size:14}):e.jsx(ze,{size:14}),e.jsx("div",{className:"minimax-test-body",children:b.ok?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"minimax-test-line",children:[e.jsx("strong",{children:"model:"})," ",e.jsx("code",{children:b.model})," ·"," ",e.jsx("strong",{children:"finish:"})," ",b.finishReason??"—"]}),b.content&&e.jsx("div",{className:"minimax-test-content",children:e.jsx("code",{children:b.content})}),b.usage&&e.jsxs("div",{className:"minimax-test-usage",children:[e.jsx("strong",{children:"usage:"})," total ",e.jsx("code",{children:b.usage.total_tokens??"?"})," · prompt"," ",e.jsx("code",{children:b.usage.prompt_tokens??"?"})," · completion"," ",e.jsx("code",{children:b.usage.completion_tokens??"?"}),((K=b.usage.prompt_tokens_details)==null?void 0:K.cached_tokens)!=null&&e.jsxs(e.Fragment,{children:[" · cached ",e.jsx("code",{children:b.usage.prompt_tokens_details.cached_tokens})]})]})]}):e.jsx("pre",{children:b.message??b.error??"unknown error"})})]})]})]}):e.jsx("div",{className:"view-container",children:e.jsxs("div",{className:"error-card",children:[e.jsx(ze,{size:20}),e.jsxs("div",{children:[e.jsx("strong",{children:"Couldn't load MiniMax status"}),e.jsx("pre",{children:x??"unknown error"})]})]})})}function Uo({toast:s}){const[t,a]=r.useState("24h"),[i,n]=r.useState(""),[c,o]=r.useState(""),[l,h]=r.useState(!0),[p,u]=r.useState(null),[d,m]=r.useState([]),[x,g]=r.useState("requests"),[b,z]=r.useState("desc"),[k,w]=r.useState(!1),S=r.useCallback(async(y,M,P)=>{h(!0);try{const C=new URLSearchParams({range:y});y==="custom"&&M&&P&&(C.set("from",String(M)),C.set("to",String(P)));const[D,Y]=await Promise.all([T.get(`/usage?${C.toString()}`),T.get("/usage/recent?limit=20")]);u(D),m(Y.records)}catch(C){s.error(`Failed to load usage data: ${C.message}`)}finally{h(!1)}},[s]);r.useEffect(()=>{if(t==="custom"){const y=i?new Date(i).getTime():Date.now()-6048e5,M=c?new Date(c).getTime():Date.now();S("custom",y,M)}else S(t)},[t,S]);const A=r.useCallback(y=>{x===y?z(M=>M==="asc"?"desc":"asc"):(g(y),z("desc"))},[x]),f=r.useMemo(()=>p!=null&&p.perModel?[...p.perModel].sort((y,M)=>{const P=y[x]??0,C=M[x]??0,D=typeof P=="number"&&typeof C=="number"?P-C:String(P).localeCompare(String(C));return b==="asc"?D:-D}):[],[p==null?void 0:p.perModel,x,b]),N=r.useMemo(()=>p!=null&&p.daily?{labels:p.daily.map(y=>y.date.slice(5)),requests:p.daily.map(y=>y.requests),tokens:p.daily.map(y=>y.totalTokens)}:{labels:[],requests:[],tokens:[]},[p==null?void 0:p.daily]),v=r.useCallback(async()=>{w(!0),await S(t==="custom"?"custom":t,t==="custom"&&i?new Date(i).getTime():void 0,t==="custom"&&c?new Date(c).getTime():void 0),w(!1)},[S,t,i,c]);if(l&&!p)return e.jsxs("div",{className:"view-container",children:[e.jsx(oe,{})," Loading usage data…"]});const j=p==null?void 0:p.totals,E=(p==null?void 0:p.errors)??[],R=(p==null?void 0:p.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(ba,{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($,{variant:"secondary",size:"sm",onClick:v,disabled:k,children:[k?e.jsx(xe,{size:14,className:"spin"}):e.jsx(de,{size:14})," Refresh"]})})]}),e.jsxs("div",{className:"usage-time-range",children:[["24h","7d","30d","custom"].map(y=>e.jsx("button",{className:V("usage-range-chip",t===y&&"is-active"),onClick:()=>a(y),children:y==="custom"?"Custom":y.toUpperCase()},y)),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:y=>n(y.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:y=>o(y.target.value),"aria-label":"To date"})]})]}),e.jsxs("div",{className:"usage-kpi-row",children:[e.jsx(Ts,{label:"Total Requests",value:(j==null?void 0:j.requests.toLocaleString())??"—",sub:j?`${j.errors} errors`:void 0,tone:j&&j.errors>j.requests*.1?"warn":void 0}),e.jsx(Ts,{label:"Total Tokens",value:j?j.totalTokens>=1e3?`${Math.round(j.totalTokens/1e3)}k`:String(j.totalTokens):"—",sub:j?`${j.promptTokens.toLocaleString()} prompt · ${j.completionTokens.toLocaleString()} completion`:void 0}),e.jsx(Ts,{label:"Errors",value:String((j==null?void 0:j.errors)??"—"),sub:E.length>0?`${E[0].code}: ${E[0].count}`:void 0,tone:j&&j.errors>0?"err":void 0}),e.jsx(Ts,{label:"Avg Latency",value:(j==null?void 0:j.avgLatencyMs)!=null?`${j.avgLatencyMs}ms`:"—",sub:(j==null?void 0:j.p95LatencyMs)!=null?`p95 ${j.p95LatencyMs}ms`:void 0}),e.jsx(Ts,{label:"Est. Cost",value:(j==null?void 0:j.costEstimate)!=null&&j.costEstimate>0?`$${j.costEstimate.toFixed(4)}`:"—",sub:"approximate USD",tone:void 0})]}),e.jsxs(G,{className:"usage-chart-card",children:[e.jsx("div",{className:"usage-chart-wrap",children:e.jsx(Po,{series:N,height:280})}),e.jsxs("div",{className:"usage-legend",children:[e.jsxs("div",{className:"usage-legend-item",children:[e.jsx("div",{className:"usage-legend-bar",style:{background:"var(--accent)"}}),e.jsx("span",{children:"Requests (bar)"})]}),e.jsxs("div",{className:"usage-legend-item",children:[e.jsx("div",{className:"usage-legend-line",style:{background:"var(--warning, #d29922)"}}),e.jsx("span",{children:"Tokens (line)"})]})]})]}),e.jsxs(G,{children:[e.jsx(te,{children:"Per-model breakdown"}),e.jsx(Fo,{rows:f,sortKey:x,sortDir:b,onSort:A})]}),R.length>0&&e.jsxs(G,{children:[e.jsx(te,{children:"API Keys"}),e.jsx("div",{className:"usage-key-row",children:R.map(y=>e.jsxs("span",{className:V("usage-key-badge",y.isBackup?"is-backup":"is-active"),children:[e.jsx("span",{className:"usage-key-dot"}),y.keyEnvVar,y.isBackup?" (backup)":" (active)"," · ",y.requests," req"]},y.keyEnvVar))})]}),d.length>0&&e.jsxs(G,{children:[e.jsx(te,{children:"Recent activity"}),e.jsx("div",{className:"usage-recent-list",children:d.map((y,M)=>e.jsxs("div",{className:V("usage-recent-item",y.error&&"is-err"),children:[e.jsx("span",{className:"usage-recent-time",children:new Date(y.ts).toLocaleTimeString()}),e.jsx("span",{className:"usage-recent-model",children:e.jsx("code",{children:y.modelId})}),e.jsxs("span",{className:"usage-recent-tokens",children:[y.totalTokens.toLocaleString()," tok"]}),e.jsxs("span",{className:"usage-recent-latency",children:[y.latencyMs,"ms"]}),e.jsx("span",{className:"usage-recent-endpoint",children:y.endpoint})]},`${y.requestId}-${M}`))})]})]})}function Ts({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 Bs({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 _o({model:s}){const t=Us(s.current_interval_remaining_percent??0,0,100),a=Us(s.current_weekly_remaining_percent??0,0,100),i=Us(100-t,0,100),n=Us(100-a,0,100);return e.jsxs(G,{id:`minimax-model-${s.model_name}`,className:"minimax-model-card",children:[e.jsxs("div",{className:"minimax-model-head",children:[e.jsx("div",{className:"minimax-model-name",children:s.model_name}),e.jsxs("div",{className: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(aa,{icon:e.jsx(De,{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(aa,{icon:e.jsx(Un,{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 aa({icon:s,label:t,remainingPct:a,consumedPct:i,used:n,total:c,resetIn:o,resetISO:l}){const h=a>=75?"good":a>=25?"warn":"low";return e.jsxs("div",{className:`minimax-quota-row is-${h}`,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 Us(s,t,a){return Math.max(t,Math.min(a,s))}function Wo(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 qo({step:s,setStep:t,keyDraft:a,setKeyDraft:i,showKey:n,setShowKey:c,verifying:o,verifyResult:l,onVerify:h,onSkip:p,onManualKeySave:u,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(Xe,{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($,{variant:"ghost",size:"sm",onClick:p,children:[e.jsx(Ne,{size:14})," Skip for now"]})})]}),e.jsx("div",{className:"minimax-wizard-stepper",children:["Welcome","Get a key","Paste & test","Done"].map((x,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(qe,{size:14}):g+1}),e.jsx("div",{className:"minimax-wizard-step-label",children:x})]},x))}),e.jsxs(G,{id:"minimax-wizard-card",children:[s===0&&e.jsxs("div",{className:"minimax-wizard-body",children:[e.jsx("h3",{className:"minimax-wizard-title",children:"Welcome"}),e.jsxs("p",{className:"minimax-wizard-prose",children:["BizarHarness shows you how much of your MiniMax Token Plan quota you have left — both the ",e.jsx("strong",{children:"5-hour rolling"})," and ",e.jsx("strong",{children:"weekly"})," windows."]}),e.jsxs("ul",{className:"minimax-wizard-list",children:[e.jsxs("li",{children:["Stored in ",e.jsx("code",{children:"~/.local/share/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($,{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(ys,{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($,{variant:"secondary",size:"md",onClick:()=>t(0),children:"← Back"}),e.jsxs($,{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(It,{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:x=>i(x.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(x=>!x),className:"minimax-key-toggle","aria-label":n?"Hide key":"Show key",children:n?e.jsx(ft,{size:13}):e.jsx(fs,{size:13})})]})}),l&&!l.ok&&e.jsxs("div",{className:"minimax-wizard-error",children:[e.jsx(ze,{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($,{variant:"secondary",size:"md",onClick:()=>t(1),children:"← Back"}),e.jsxs($,{variant:"primary",size:"md",onClick:h,disabled:o||!a.trim(),children:[o?e.jsx(xe,{size:14,className:"spin"}):e.jsx(Is,{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:x=>{x.preventDefault(),u()},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(qe,{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($,{variant:"primary",size:"md",onClick:()=>window.location.reload(),children:"View your quota →"})})]}),e.jsxs("div",{className:"minimax-wizard-footer",children:[e.jsx(Is,{size:11}),e.jsxs("span",{children:["Key written to ",e.jsx("code",{children:"~/.local/share/opencode/auth.json"})," with mode 0600."]})]})]})]})}const Vo=Fe.memo(Oo),Ho={pending:"info",running:"accent",done:"success",failed:"error",killed:"neutral",timed_out:"warning"},Go={pending:"Pending",running:"Running",done:"Done",failed:"Failed",killed:"Killed",timed_out:"Timed out"};function Ko({status:s,dot:t}){const a=Ho[s]||"neutral",i=Go[s]||s;return e.jsx(Qe,{kind:a,dot:t,children:i})}function Yo({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($,{variant:"ghost",onClick:i,children:"Cancel"}),e.jsx($,{variant:"danger",onClick:async()=>{await a(),i()},children:"Kill"})]})]})}function Xo(s,t,a,i,n){s.open({title:"Kill instance?",width:400,children:e.jsx(Yo,{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 Qo({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 h=await T.post(`/background/${encodeURIComponent(s.instanceId)}/open-terminal`,{emulator:"system"});if(h.ok)t.success("Opening terminal…");else if(t.error(h.error||"Failed to open terminal"),c)try{await navigator.clipboard.writeText(c),t.success("Command copied to clipboard")}catch{}}catch(h){if(t.error(`Failed: ${h.message}`),c)try{await navigator.clipboard.writeText(c),t.success("Command copied to clipboard")}catch{}}finally{i(!1)}}};return n?e.jsxs(G,{variant:"outlined",className:"bg-tmux-card",children:[e.jsxs("div",{className:"bg-tmux-card-header",children:[e.jsx(is,{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($,{variant:"ghost",size:"sm",onClick:o,title:"Copy attach command",children:[e.jsx(os,{size:14})," Copy"]}),e.jsxs($,{variant:"primary",size:"sm",onClick:l,loading:a,title:"Open in system terminal",children:[e.jsx(is,{size:14})," Open terminal"]})]})]}):e.jsxs(G,{variant:"outlined",className:"bg-tmux-card bg-tmux-card-warn",children:[e.jsxs("div",{className:"bg-tmux-card-header",children:[e.jsx(ze,{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 Jo=[{name:"mimir",description:"Deep research & codebase exploration"},{name:"frigg",description:"Read-only codebase Q&A"},{name:"thor",description:"Moderate-complexity implementation"},{name:"tyr",description:"Complex feature implementation"},{name:"heimdall",description:"Quick edits & simple tasks"},{name:"odin",description:"Primary router agent"}],Zo=[{label:"1 min",value:6e4},{label:"5 min",value:3e5},{label:"15 min",value:9e5},{label:"30 min",value:18e5},{label:"1 hr",value:36e5},{label:"4 hr",value:144e5}];function ec({open:s,onClose:t,onCreated:a,agents:i=Jo}){var N;const n=re(),[c,o]=r.useState(((N=i[0])==null?void 0:N.name)||"mimir"),[l,h]=r.useState(""),[p,u]=r.useState(""),[d,m]=r.useState(3e5),[x,g]=r.useState(!1),[b,z]=r.useState(""),[k,w]=r.useState(!1),[S,A]=r.useState(null);if(!s)return null;const f=async v=>{if(v.preventDefault(),A(null),!l.trim()){A("Prompt is required.");return}w(!0);try{const j=b.split(",").map(y=>y.trim()).filter(y=>y.length>0),E={agent:c,prompt:l,...p.trim()?{model:p.trim()}:{},timeoutMs:d,persistent:x,maxRestarts:3,...j.length>0?{tags:j}:{}},R=await T.post("/background",E);if(R!=null&&R.error)throw new Error(R.message||R.error);n.success(`Spawned ${c} (${R.instanceId.slice(0,14)}…)`),a==null||a(R.instanceId),h(""),u(""),g(!1),z(""),t()}catch(j){A((j==null?void 0:j.message)||"Failed to spawn.")}finally{w(!1)}};return e.jsx("div",{className:"modal-backdrop",role:"dialog","aria-modal":"true",children:e.jsxs("div",{className:"modal-card spawn-modal",children:[e.jsxs("div",{className:"spawn-modal-header",children:[e.jsxs("h3",{children:[e.jsx(be,{size:18})," Spawn background agent"]}),e.jsx($,{variant:"ghost",size:"sm",onClick:t,title:"Close",children:e.jsx(Ne,{size:14})})]}),e.jsxs("form",{onSubmit:f,className:"spawn-modal-body",children:[e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:"Agent"}),e.jsx("select",{className:"field-input",value:c,onChange:v=>o(v.target.value),required:!0,children:i.map(v=>e.jsxs("option",{value:v.name,children:[v.name,v.description?` — ${v.description}`:""]},v.name))})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:"Initial prompt"}),e.jsx("textarea",{className:"field-input spawn-modal-textarea",rows:5,value:l,onChange:v=>h(v.target.value),placeholder:"What do you want this agent to do?",required:!0})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:"Model (optional)"}),e.jsx("input",{type:"text",className:"field-input",value:p,onChange:v=>u(v.target.value),placeholder:"providerID/modelID (leave blank for agent default)"})]}),e.jsxs("div",{className:"field",children:[e.jsx("span",{className:"field-label",children:"Timeout"}),e.jsx("div",{className:"spawn-modal-timeouts",children:Zo.map(v=>e.jsx("button",{type:"button",className:"spawn-modal-timeout-pill"+(v.value===d?" spawn-modal-timeout-pill-active":""),onClick:()=>m(v.value),children:v.label},v.value))}),e.jsx("input",{type:"range",min:6e4,max:144e5,step:6e4,value:d,onChange:v=>m(Number(v.target.value)),className:"spawn-modal-slider"}),e.jsxs("span",{className:"muted",children:[(d/6e4).toFixed(0)," min"]})]}),e.jsxs("label",{className:"field-checkbox",children:[e.jsx("input",{type:"checkbox",checked:x,onChange:v=>g(v.target.checked)}),e.jsx("span",{children:"Persistent — auto-restart on terminal failure (max 3 attempts)"})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:"Tags (optional, comma-separated)"}),e.jsx("input",{type:"text",className:"field-input",value:b,onChange:v=>z(v.target.value),placeholder:"e.g. refactor, urgent"})]}),S&&e.jsx("div",{className:"spawn-modal-error",children:S}),e.jsxs("div",{className:"spawn-modal-actions",children:[e.jsx($,{variant:"ghost",size:"sm",type:"button",onClick:t,children:"Cancel"}),e.jsx($,{variant:"primary",size:"sm",type:"submit",disabled:k,children:k?"Spawning…":"Spawn agent"})]})]})]})})}const sc=5e3,na=3e3,tc=120,ac=32e3;function nc(s){return s.status==="pending"||s.status==="running"||s.status==="paused"}function kt(s){return s.status==="paused"}function ic(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 rc(s){const t=re(),a=Re(),[i,n]=r.useState([]),[c,o]=r.useState(!0),[l,h]=r.useState(null),[,p]=r.useState(0),[u,d]=r.useState(!1),m=r.useCallback(async()=>{try{const A=await T.get("/background");n(Array.isArray(A==null?void 0:A.instances)?A.instances:[]),h(null)}catch(A){h((A==null?void 0:A.message)||"Failed to load background agents.")}finally{o(!1)}},[]);r.useEffect(()=>{m();const A=setInterval(m,sc);return()=>clearInterval(A)},[m]),r.useEffect(()=>{const A=setInterval(()=>p(f=>(f+1)%1e6),1e3);return()=>clearInterval(A)},[]),r.useEffect(()=>{const A=new Hs,f=A.on(N=>{const v=N.type;(v==="background:change"||v==="background:cleanup"||v==="bg:progress"||v==="bg:tool-call")&&m()});return()=>{f(),A.close()}},[m]);const x=i.filter(nc),g=A=>{oc(a,A)},b=async A=>{try{const f=await T.get(`/background/${encodeURIComponent(A.instanceId)}/tmux`);mc(a,f)}catch(f){t.error(`Tmux info failed: ${f.message}`)}},z=A=>{Xo(a,t,A.instanceId,A.agent||A.prompt,()=>{n(f=>f.filter(N=>N.instanceId!==A.instanceId))})},k=async A=>{try{const f=await T.post(`/background/${encodeURIComponent(A.instanceId)}/pause`,{});f!=null&&f.ok?t.info(`Paused ${A.instanceId.slice(0,14)}…`):t.error((f==null?void 0:f.error)||"Pause failed.")}catch(f){t.error(`Pause failed: ${f.message}`)}},w=async A=>{try{const f=await T.post(`/background/${encodeURIComponent(A.instanceId)}/resume`,{});f!=null&&f.ok?t.info(`Resumed ${A.instanceId.slice(0,14)}…`):t.error((f==null?void 0:f.error)||"Resume failed.")}catch(f){t.error(`Resume failed: ${f.message}`)}},S=A=>{uc(a,t,A,m)};return c?e.jsx("div",{className:"bg-active-view",children:e.jsxs("div",{className:"bg-active-loading",children:[e.jsx(oe,{size:"md"}),e.jsx("span",{children:"Loading background agents…"})]})}):l?e.jsx("div",{className:"bg-active-view",children:e.jsx(pe,{icon:e.jsx(De,{size:32}),title:"Couldn't load background agents",message:l,action:e.jsxs($,{variant:"primary",onClick:m,children:[e.jsx(de,{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:[x.length," active · ",i.length," total in store"]})]}),e.jsxs("div",{className:"bg-active-header-actions",children:[e.jsxs($,{variant:"primary",size:"sm",onClick:()=>d(!0),children:[e.jsx(be,{size:14})," Spawn"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:m,title:"Refresh now",children:[e.jsx(de,{size:14})," Refresh"]})]})]}),e.jsx(ec,{open:u,onClose:()=>d(!1),onCreated:()=>{m()}}),x.length===0?e.jsx(pe,{icon:e.jsx(De,{size:32}),title:"No active background agents",message:"Use the Spawn button above or call bizar_spawn_background from an agent.",action:e.jsxs($,{variant:"primary",onClick:()=>d(!0),children:[e.jsx(be,{size:14})," Spawn your first agent"]})}):e.jsx("div",{className:"bg-active-list",children:x.map(A=>e.jsx(lc,{inst:A,onViewOutput:()=>g(A),onOpenTmux:()=>b(A),onKill:()=>z(A),onPause:kt(A)?void 0:()=>k(A),onResume:kt(A)?()=>w(A):void 0,onSteer:()=>S(A)},A.instanceId))})]})}function lc({inst:s,onViewOutput:t,onOpenTmux:a,onKill:i,onPause:n,onResume:c,onSteer:o}){const l=typeof s.startedAt=="number"?s.startedAt:0,h=l?_e(l):"—",p=l?Date.now()-l:0,u=ia(s.prompt,tc),d=typeof s.progress=="number"?s.progress:null;return e.jsxs(G,{className:"bg-active-card",variant:"elevated",children:[e.jsxs("div",{className:"bg-active-card-top",children:[e.jsxs("div",{className:"bg-active-card-id",children:[e.jsx("code",{className:"mono",children:s.instanceId}),e.jsx(Ko,{status:s.status||"pending",dot:!0}),kt(s)&&e.jsxs("span",{className:"bg-active-card-paused-tag",children:[e.jsx(_n,{size:12})," paused"]})]}),e.jsxs("div",{className:"bg-active-card-agent",children:[e.jsx("span",{className:"bg-active-card-agent-label",children:"Agent"}),e.jsx("span",{className:"bg-active-card-agent-name",children:s.agent||"unknown"})]})]}),u&&e.jsx("div",{className:"bg-active-prompt",children:u}),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})]}),d!==null&&e.jsxs("div",{className:"progress-bar","aria-label":"Progress",children:[e.jsx("div",{className:"progress-fill",style:{width:`${d<0?100:Math.max(0,Math.min(100,d))}%`}}),e.jsxs("span",{className:"progress-label",children:[d<0?"…":`${Math.round(d)}%`,s.progressMessage?` · ${s.progressMessage}`:""]})]}),e.jsxs("div",{className:"bg-active-meta",children:[e.jsxs("span",{title:h,children:[e.jsx("strong",{children:"Started:"})," ",h]}),e.jsxs("span",{children:[e.jsx("strong",{children:"Duration:"})," ",ic(p)]}),e.jsxs("span",{children:[e.jsx("strong",{children:"Tool calls:"})," ",s.toolCallCount??0]}),s.processId&&e.jsxs("span",{children:[e.jsx("strong",{children:"PID:"})," ",e.jsx("code",{className:"mono",children:s.processId})]}),Array.isArray(s.tags)&&s.tags.length>0&&e.jsxs("span",{children:[e.jsx("strong",{children:"Tags:"})," ",s.tags.map((m,x)=>e.jsxs("span",{className:"tag-pill",children:[m,x<s.tags.length-1?" ":""]},m))]}),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($,{variant:"secondary",size:"sm",onClick:t,children:[e.jsx(fs,{size:14})," View output"]}),n&&e.jsxs($,{variant:"secondary",size:"sm",onClick:n,title:"Pause subprocess (POSIX)",children:[e.jsx(At,{size:14})," Pause"]}),c&&e.jsxs($,{variant:"secondary",size:"sm",onClick:c,title:"Resume subprocess (POSIX)",children:[e.jsx(bs,{size:14})," Resume"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:o,title:"Steer with new instructions",children:[e.jsx(Ze,{size:14})," Steer"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:a,children:[e.jsx(is,{size:14})," Open in tmux"]}),e.jsxs($,{variant:"danger",size:"sm",onClick:i,children:[e.jsx(we,{size:14})," Kill"]})]}),e.jsx(Qo,{instance:s})]})}function oc(s,t){s.open({title:`Output — ${t.agent||t.instanceId}`,width:720,children:e.jsx(cc,{instanceId:t.instanceId})})}function cc({instanceId:s}){const t=re(),a=r.useRef([]),[i,n]=r.useState(""),[c,o]=r.useState(!0),[l,h]=r.useState(null),[p,u]=r.useState(!0),[d,m]=r.useState(!0),[x,g]=r.useState([]),[b,z]=r.useState(!0),k=r.useRef(null),w=r.useRef(!0),S=r.useCallback(()=>{n(a.current.join(`
|
|
17
|
-
`))},[]),A=r.useCallback(async()=>{try{const v=await T.get(`/background/${encodeURIComponent(s)}/output?lines=300`);if(u((v==null?void 0:v.available)!==!1),v!=null&&v.output&&a.current.length===0){const j=v.output.split(/\r?\n/);a.current=j.slice(-300),S()}h(null)}catch(v){h((v==null?void 0:v.message)||"Failed to load output.")}finally{o(!1)}},[s,S]);r.useEffect(()=>{A();const v=setInterval(A,na);return()=>clearInterval(v)},[A]),r.useEffect(()=>{const v=new Hs;let j=!1;const E=v.onStatus(y=>{j=y==="connected",m(j)}),R=v.on(y=>{var P;const M=y;if(M.type==="bg:output"&&M.instanceId===s&&typeof M.line=="string"){a.current.push(M.line);let C=0;for(let D=a.current.length-1;D>=0;D--)if(C+=(((P=a.current[D])==null?void 0:P.length)??0)+1,C>ac){a.current=a.current.slice(D+1);break}n(a.current.join(`
|
|
18
|
-
`))}});return()=>{E(),R(),v.close()}},[s]),r.useEffect(()=>{let v=!1;const j=async()=>{try{const y=await T.get(`/background/${encodeURIComponent(s)}/tool-calls`);!v&&Array.isArray(y==null?void 0:y.toolCalls)&&g(y.toolCalls)}catch{}};j();const E=new Hs,R=E.on(y=>{const M=y;M.type==="bg:tool-call"&&M.instanceId===s&&j()});return()=>{v=!0,R(),E.close()}},[s]),r.useEffect(()=>{var v;w.current&&((v=k.current)==null||v.scrollIntoView({behavior:"auto",block:"end"}))},[i]);const f=v=>{const j=v.currentTarget,E=j.scrollHeight-j.scrollTop-j.clientHeight<24;w.current=E},N=async()=>{try{await navigator.clipboard.writeText(i),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:d?`streaming · ${i.length} chars`:p?`${i.length} chars · auto-refresh ${na/1e3}s (WS idle)`:"Output unavailable (no tmux session)"}),e.jsxs("div",{className:"bg-output-toolbar-actions",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>z(v=>!v),title:"Toggle tool-call history",children:b?"Hide tools":"Show tools"}),e.jsxs($,{variant:"ghost",size:"sm",onClick:A,title:"Refresh now",children:[e.jsx(de,{size:14})," Refresh"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:N,disabled:!i,children:[e.jsx(os,{size:14})," Copy"]})]})]}),c&&!i?e.jsxs("div",{className:"bg-output-loading",children:[e.jsx(xe,{size:16,className:"spin"})," Loading…"]}):l?e.jsx("div",{className:"bg-output-error",children:l}):e.jsxs("div",{className:"bg-output-body",children:[e.jsxs("div",{className:"bg-output-scroll",onScroll:f,children:[e.jsx("pre",{className:"bg-output-pre mono",children:e.jsx("code",{children:i||e.jsx("span",{className:"muted",children:"No output captured yet — waiting for the agent to start…"})})}),e.jsx("div",{ref:k})]}),b&&e.jsx(dc,{calls:x})]})]})}function dc({calls:s}){return e.jsxs("aside",{className:"bg-tool-calls","aria-label":"Tool call history",children:[e.jsxs("h4",{className:"bg-tool-calls-title",children:["Tool calls (",s.length,")"]}),s.length===0?e.jsx("p",{className:"muted bg-tool-calls-empty",children:"No tool calls recorded yet."}):e.jsx("ol",{className:"bg-tool-calls-list",children:s.slice().reverse().map(t=>{const a=t.endedAt&&t.startedAt?`${Math.max(0,t.endedAt-t.startedAt)}ms`:"…";return e.jsxs("li",{className:`bg-tool-call bg-tool-call-${t.status}`,children:[e.jsxs("div",{className:"bg-tool-call-head",children:[e.jsx("code",{className:"mono bg-tool-call-name",children:t.name}),e.jsx("span",{className:`badge badge-${t.status==="error"?"danger":t.status==="ok"?"success":"neutral"}`,children:t.status}),e.jsx("span",{className:"bg-tool-call-dur muted",children:a})]}),t.args&&e.jsx("pre",{className:"bg-tool-call-args mono",children:t.args}),t.result&&e.jsx("pre",{className:"bg-tool-call-result mono",children:t.result.slice(0,240)}),t.error&&e.jsx("pre",{className:"bg-tool-call-error mono",children:t.error})]},t.id)})})]})}function mc(s,t){const a=t.attachCommand||t.session||"";s.open({title:"Attach to tmux",width:520,children:e.jsx(xc,{info:t,cmd:a})})}function uc(s,t,a,i){s.open({title:`Steer ${a.agent||a.instanceId}`,width:600,children:e.jsx(hc,{instanceId:a.instanceId,toast:t,onCreated:i,onClose:()=>s.close()})})}function hc({instanceId:s,toast:t,onCreated:a,onClose:i}){const[n,c]=r.useState(""),[o,l]=r.useState(!1),[h,p]=r.useState(null),u=async()=>{if(!n.trim()){p("Message is required.");return}l(!0);try{const d=await T.post(`/background/${encodeURIComponent(s)}/steer`,{message:n});if(!(d!=null&&d.ok)){p((d==null?void 0:d.error)||"Steer failed.");return}t.success(`Steered → new instance ${(d.newInstanceId??"").slice(0,14)}…`),a(),i()}catch(d){p(d.message)}finally{l(!1)}};return e.jsxs("div",{className:"bg-steer-modal",children:[e.jsxs("p",{className:"muted",children:["Steer kills the current subprocess and spawns a new one with the original prompt + your message appended. The new instance is linked to this one as ",e.jsx("code",{children:"parentInstanceId"}),"."]}),e.jsx("textarea",{className:"field-input bg-steer-textarea",rows:6,value:n,onChange:d=>c(d.target.value),placeholder:"What do you want the agent to do differently?"}),h&&e.jsx("div",{className:"bg-steer-error",children:h}),e.jsxs("div",{className:"bg-steer-actions",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:i,children:"Cancel"}),e.jsx($,{variant:"primary",size:"sm",onClick:u,disabled:o||!n.trim(),children:o?"Steering…":"Steer"})]})]})}function xc({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($,{variant:"secondary",size:"sm",onClick:n,children:[e.jsx(os,{size:14})," ",a?"Copied":"Copy"]})]}),e.jsx("p",{className:"muted bg-tmux-hint",children:"Paste this into a terminal on the host running the dashboard. The dashboard itself does not open terminals."})]}):e.jsx("p",{className:"muted",children:"No tmux session attached to this instance."})})}const pc={system:{title:"System health",icon:js,emptyTitle:"No system checks",emptyMessage:"System checks did not return any rows."},services:{title:"Services",icon:Rt,emptyTitle:"No service probes",emptyMessage:"Service probes did not return any rows."},counts:{title:"Counts",icon:De,emptyTitle:"No counts",emptyMessage:"No counts reported by the dashboard stores."},errors:{title:"Recent errors",icon:ps,emptyTitle:"No recent errors",emptyMessage:"No error lines in the service log within the last hour."},actions:{title:"Actions",icon:Wn,emptyTitle:"No actions",emptyMessage:"No actions available."}};function gc(s){return s==="ok"?qe:s==="warn"?qn:ps}function fc(s){return s==="ok"?"ok":s==="warn"?"warn":"fail"}function xt({category:s,title:t,icon:a,checks:i,info:n,meta:c,children:o,className:l}){const h=pc[s],p=a??h.icon,u=t??h.title,d=i.length>0||n&&n.length>0||o;return e.jsxs(G,{className:V("doctor-panel",`doctor-panel-${s}`,l),children:[e.jsxs(te,{children:[e.jsx(p,{size:14,"aria-hidden":!0}),e.jsx("span",{children:u}),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 x=gc(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(x,{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(Qe,{kind:m.status,dot:!0,children:fc(m.status)})]},m.name)})}):null,n&&n.length>0?e.jsx("dl",{className:"doctor-info-list",children:n.map(m=>e.jsxs(Fe.Fragment,{children:[e.jsx("dt",{children:m.label}),e.jsx("dd",{className:"tabular-nums",children:m.value})]},m.label))}):null]}):e.jsx(pe,{icon:e.jsx(p,{size:28,"aria-hidden":!0}),title:h.emptyTitle,message:h.emptyMessage})]})}const jc=3e4;function vc({setActiveTab:s}){var N;const t=re(),[a,i]=r.useState(null),[n,c]=r.useState(!0),[o,l]=r.useState(!1),[h,p]=r.useState(null),[u,d]=r.useState(!0),m=r.useRef(!1),x=r.useCallback(async()=>{l(!0);try{const v=await T.get("/doctor");m.current||(i(v),p(Date.now()),c(!1))}catch(v){m.current||(c(!1),t.error(`Doctor refresh failed: ${v.message}`))}finally{m.current||l(!1)}},[t]);r.useEffect(()=>(m.current=!1,x(),()=>{m.current=!0}),[x]),r.useEffect(()=>{if(!u)return;const j=setInterval(async()=>{try{const E=await T.get("/doctor/health");i(R=>R&&((R.health.status!==E.status||R.health.issues.length!==E.issues.length)&&x(),R))}catch{}},jc);return()=>clearInterval(j)},[u,x]);const g=async v=>{var j;try{const E=await T.post("/doctor/check",{checkName:v});t.info(`${E.name}: ${E.message}`,4e3),await x()}catch(E){const R=E;t.error(`Check failed: ${((j=R.data)==null?void 0:j.message)??E.message}`)}},b=()=>{if(a)try{const v=new Blob([JSON.stringify(a,null,2)],{type:"application/json"}),j=URL.createObjectURL(v),E=document.createElement("a");E.href=j,E.download=`doctor-snapshot-${new Date().toISOString().replace(/[:.]/g,"-")}.json`,document.body.appendChild(E),E.click(),document.body.removeChild(E),URL.revokeObjectURL(j)}catch(v){t.error(`Export failed: ${v.message}`)}},z=()=>{s("settings")},k=a==null?void 0:a.counts,w=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(oe,{size:"lg"}),e.jsx("p",{children:"Running health checks…"})]});if(!a)return e.jsx("div",{className:"view view-doctor",children:e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsx(ps,{size:14})," Doctor unavailable"]}),e.jsx(ne,{children:"Could not reach /api/doctor."}),e.jsx("div",{className:"doctor-fallback-actions",children:e.jsxs($,{variant:"primary",onClick:x,children:[e.jsx(de,{size:12})," Retry"]})})]})});const S=a.health.status,A=S==="ok"?qe:S==="warn"?ze:ps,f=S==="ok"?"Healthy":S==="warn"?"Warning":"Failed";return e.jsxs("div",{className:"view view-doctor","data-overall":S,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(ca,{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-${S}`),children:[e.jsx(A,{size:14,"aria-hidden":!0}),e.jsx("span",{className:"doctor-overall-label",children:f}),e.jsxs(Qe,{kind:S,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(ns,{size:12,"aria-hidden":!0}),e.jsxs("span",{"aria-live":"polite","aria-atomic":"true",children:["v",a.bizarVersion," · ",a.platform,"/",a.arch," ·"," ","up ",Math.floor(a.uptime),"s",h?` · refreshed ${_e(new Date(h))}`:""]})]})]}),e.jsxs("div",{className:"doctor-grid",children:[e.jsx(xt,{category:"system",checks:a.checks.system,meta:`${a.platform}/${a.arch}`}),e.jsx(xt,{category:"services",checks:a.checks.services,meta:(N=a.services.opencode)!=null&&N.reachable?`opencode on ${a.services.opencode.port??"?"}`:"opencode not connected"}),e.jsx(xt,{category:"counts",checks:[],info:w,meta:k!=null&&k.activeProject?`active: ${k.activeProject}`:"no active project"}),e.jsxs(G,{className:"doctor-errors-card",children:[e.jsxs(te,{children:[e.jsx(ps,{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((v,j)=>e.jsxs("li",{className:"doctor-error-row",children:[e.jsx("span",{className:"doctor-error-ts mono",children:v.ts?_e(new Date(v.ts)):"??:??:??"}),e.jsx("span",{className:"doctor-error-line mono",children:v.line})]},`${v.tsMs??j}-${j}`))})]}),e.jsxs(G,{className:"doctor-actions-card",children:[e.jsxs(te,{children:[e.jsx(vt,{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($,{variant:"primary",onClick:x,disabled:o,"aria-label":"Refresh diagnostics",children:[o?e.jsx(oe,{size:"sm"}):e.jsx(de,{size:12}),o?"Running…":"Run Health Check Now"]}),e.jsxs($,{variant:"secondary",onClick:z,children:[e.jsx(ke,{size:12})," View Full Logs"]}),e.jsxs($,{variant:"secondary",onClick:b,children:[e.jsx(ls,{size:12})," Export Diagnostics as JSON"]}),e.jsx($,{variant:"ghost",onClick:()=>d(v=>!v),"aria-label":u?"Pause auto-refresh":"Resume auto-refresh",children:u?"Pause auto-refresh":"Resume auto-refresh"})]}),a.checks.services.some(v=>v.status!=="ok")||a.checks.config.some(v=>v.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(v=>v.status!=="ok").map(v=>e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>g(v.name),title:`Run check: ${v.name}`,children:[e.jsx(vt,{size:10})," ",v.name]},v.name))})]}):null]})]})]})}const yc=Fe.memo(vc);function bc(s){return s.total<=0?"fail":s.failed===0?"pass":s.passed/s.total>.8?"warn":"fail"}function La({run:s,onClick:t,selected:a,ariaLabel:i}){const n=bc(s),c=s.total>0?(s.passed/s.total*100).toFixed(1):"0.0",o=!!t;return e.jsxs(G,{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(te,{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:[_e(s.startedAt)," · ",s.suitePath]})]})}const pt=8;function Nc({onAdded:s,onCancel:t}){const a=re(),[i,n]=r.useState(""),[c,o]=r.useState(""),[l,h]=r.useState(""),[p,u]=r.useState("thor"),[d,m]=r.useState(!1),x=async g=>{if(g.preventDefault(),!i||!c||!l){a.error("name, suitePath, and cron are required");return}m(!0);try{const b=await T.post("/eval/schedules",{name:i,suitePath:c,cron:l,agent:p});s(b),a.success("Schedule created")}catch(b){a.error(`Failed to create schedule: ${b.message}`)}finally{m(!1)}};return e.jsxs("form",{className:"eval-schedule-form",onSubmit:x,children:[e.jsxs("div",{className:"form-row",children:[e.jsx("label",{htmlFor:"sched-name",children:"Name"}),e.jsx("input",{id:"sched-name",type:"text",value:i,onChange:g=>n(g.target.value),placeholder:"Daily fixture check",required:!0})]}),e.jsxs("div",{className:"form-row",children:[e.jsx("label",{htmlFor:"sched-suite",children:"Suite path"}),e.jsx("input",{id:"sched-suite",type:"text",value:c,onChange:g=>o(g.target.value),placeholder:"./fixtures",required:!0})]}),e.jsxs("div",{className:"form-row",children:[e.jsx("label",{htmlFor:"sched-cron",children:"Cron"}),e.jsx("input",{id:"sched-cron",type:"text",value:l,onChange:g=>h(g.target.value),placeholder:"0 8 * * *",required:!0})]}),e.jsxs("div",{className:"form-row",children:[e.jsx("label",{htmlFor:"sched-agent",children:"Agent"}),e.jsx("input",{id:"sched-agent",type:"text",value:p,onChange:g=>u(g.target.value),placeholder:"thor"})]}),e.jsxs("div",{className:"form-actions",children:[e.jsx($,{type:"submit",variant:"primary",size:"sm",disabled:d,children:d?"Creating…":"Create schedule"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:t,children:"Cancel"})]})]})}function kc({setActiveTab:s}){const t=re(),[a,i]=r.useState([]),[n,c]=r.useState(!0),[o,l]=r.useState("runs"),[h,p]=r.useState([]),[u,d]=r.useState(!1),[m,x]=r.useState(!1),g=r.useRef(!1),b=r.useCallback(async()=>{c(!0);try{const f=await T.get(`/eval/runs?limit=${pt}`);g.current||i(f.runs||[])}catch(f){g.current||t.error(`Failed to load eval runs: ${f.message}`)}finally{g.current||c(!1)}},[t]),z=r.useCallback(async()=>{d(!0);try{const f=await T.get("/eval/schedules");g.current||p(f.schedules||[])}catch(f){g.current||t.error(`Failed to load eval schedules: ${f.message}`)}finally{g.current||d(!1)}},[t]);r.useEffect(()=>(g.current=!1,b(),o==="schedules"&&z(),()=>{g.current=!0}),[b,z,o]);const k=async f=>{try{await T.del(`/eval/schedules/${f}`),p(N=>N.filter(v=>v.id!==f)),t.success("Schedule deleted")}catch(N){t.error(`Failed to delete schedule: ${N.message}`)}},w=a.slice(0,pt),S=a.reduce((f,N)=>(f.total+=N.total,f.passed+=N.passed,f.failed+=N.failed,N.failed===0&&(f.fullPass+=1),f),{total:0,passed:0,failed:0,fullPass:0}),A=S.total>0?(S.passed/S.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(Je,{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($,{variant:"secondary",size:"sm",onClick:b,disabled:n,children:[n?e.jsx(oe,{size:"sm"}):e.jsx(de,{size:12}),n?"Refreshing…":"Refresh"]}),e.jsxs($,{variant:"primary",size:"sm",onClick:()=>s("evalReport"),title:"Open the full eval report",children:[e.jsx(ys,{size:12})," Open Eval Report"]})]})]}),e.jsxs("div",{className:"eval-summary-grid",children:[e.jsxs(G,{className:"eval-summary-card",children:[e.jsx(te,{children:"Recent runs"}),e.jsx("div",{className:"eval-summary-value",children:a.length}),e.jsxs(ne,{className:"muted",children:["Latest ",pt," runs across all suites."]})]}),e.jsxs(G,{className:"eval-summary-card",children:[e.jsx(te,{children:"Fixtures run"}),e.jsx("div",{className:"eval-summary-value",children:S.total}),e.jsx(ne,{className:"muted",children:e.jsxs("span",{className:V("eval-rate",S.failed===0?"is-pass":"is-fail"),children:[A,"% pass rate"]})})]}),e.jsxs(G,{className:"eval-summary-card",children:[e.jsx(te,{children:"Clean runs"}),e.jsx("div",{className:"eval-summary-value",children:S.fullPass}),e.jsx(ne,{className:"muted",children:"Runs where every fixture passed."})]}),e.jsxs(G,{className:"eval-summary-card eval-summary-cta",children:[e.jsx(te,{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($,{variant:"primary",size:"sm",onClick:()=>s("evalReport"),className:"eval-summary-cta-btn",children:["Open report ",e.jsx(Vn,{size:12})]})]})]}),e.jsxs("div",{className:"eval-recent-section",children:[e.jsxs("div",{className:"eval-sub-tabs",children:[e.jsxs("button",{type:"button",className:V("eval-sub-tab",o==="runs"?"is-active":""),onClick:()=>l("runs"),children:[e.jsx(Je,{size:12,"aria-hidden":!0})," Runs"]}),e.jsxs("button",{type:"button",className:V("eval-sub-tab",o==="schedules"?"is-active":""),onClick:()=>{l("schedules"),h.length===0&&z()},children:[e.jsx(ns,{size:12,"aria-hidden":!0})," Schedules"]})]}),o==="runs"?e.jsxs(e.Fragment,{children:[e.jsx("h2",{className:"eval-section-title",children:"Recent runs"}),n&&w.length===0?e.jsxs("div",{className:"eval-runs-loading",children:[e.jsx(oe,{size:"sm"}),e.jsx("span",{className:"muted",children:"Loading runs…"})]}):w.length===0?e.jsx(pe,{icon:e.jsx(Je,{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:w.map(f=>e.jsx(La,{run:f},f.id))})]}):e.jsxs(e.Fragment,{children:[e.jsx("h2",{className:"eval-section-title",children:"Schedules"}),u?e.jsxs("div",{className:"eval-runs-loading",children:[e.jsx(oe,{size:"sm"}),e.jsx("span",{className:"muted",children:"Loading schedules…"})]}):h.length===0?e.jsx(pe,{icon:e.jsx(ns,{size:28}),title:"No eval schedules",message:"Schedules let you run eval suites automatically on a cron. Add one below."}):e.jsx("div",{className:"eval-schedules-list",children:h.map(f=>e.jsx(G,{className:"eval-schedule-card",children:e.jsxs("div",{className:"eval-schedule-row",children:[e.jsxs("div",{className:"eval-schedule-info",children:[e.jsx(te,{children:f.name}),e.jsxs(ne,{className:"muted",children:[f.cron," · ",f.suitePath," · agent:",f.agent||"thor"]})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>k(f.id),title:"Delete schedule",children:e.jsx(we,{size:12,"aria-hidden":!0})})]})},f.id))}),e.jsxs("div",{className:"eval-schedule-add",children:[e.jsx(Nc,{onAdded:f=>{p(N=>[...N,f]),x(!1)},onCancel:()=>x(!1)}),!m&&e.jsxs($,{variant:"secondary",size:"sm",onClick:()=>x(!0),children:[e.jsx(be,{size:12,"aria-hidden":!0})," Add schedule"]})]})]})]})]})}const wc=Fe.memo(kc);function Da(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 h=a.get(l),p=i.get(l),u=h?h.ok:null,d=p?p.ok:null;let m;h&&p?u===d?m="same":u===!1&&d===!0?m="improved":m="regressed":p&&!h?m="added":m="removed",c.push({fixtureId:l,before:u,after:d,change:m})}const o={regressed:0,improved:1,added:2,removed:3,same:4};return c.sort((l,h)=>{const p=o[l.change]-o[h.change];return p!==0?p:l.fixtureId.localeCompare(h.fixtureId)}),c}function Sc({runA:s,runB:t,title:a="Regression Analysis"}){const i=Da(s,t),n=i.filter(h=>h.change==="improved").length,c=i.filter(h=>h.change==="regressed").length,o=i.filter(h=>h.change==="same").length,l=i.filter(h=>h.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(h=>e.jsxs("li",{"data-fixture-id":h.fixtureId,className:V("eval-diff-row",`is-${h.change}`),children:[e.jsx("span",{className:"eval-diff-fixture mono",children:h.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",h.before?"is-pass":"is-fail"),children:h.before===null?"—":h.before?"pass":"fail"}),e.jsx("span",{className:"eval-diff-arrow-small","aria-hidden":!0,children:"→"}),e.jsx("span",{className:V("eval-diff-state",h.after?"is-pass":"is-fail"),children:h.after===null?"—":h.after?"pass":"fail"})]})]},h.fixtureId))})]})}function Cc({runId:s,variant:t="secondary",size:a="sm"}){const i=()=>{const n=T.getToken();window.open(`/api/eval/runs/${encodeURIComponent(s)}/export.csv?_t=${encodeURIComponent(n)}`,"_blank")};return e.jsxs($,{variant:t,size:a,onClick:i,title:"Export results as CSV",children:[e.jsx(ls,{size:14,"aria-hidden":!0}),"Export CSV"]})}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,h)=>l.ok!==h.ok?l.ok?1:-1:l.fixtureId.localeCompare(h.fixtureId));return e.jsxs("div",{className:"eval-run-detail","data-testid":"eval-run-detail",children:[e.jsxs(G,{className:"eval-run-detail-header",children:[e.jsxs("div",{className:"eval-run-detail-header-row",children:[e.jsxs(te,{children:[e.jsx(Je,{size:14,"aria-hidden":!0})," ",s.id]}),e.jsxs("div",{className:"eval-run-detail-actions",children:[e.jsx(Cc,{runId:s.id}),e.jsxs($,{variant:"ghost",size:"sm",onClick:i,title:"Close detail",children:[e.jsx(Ne,{size:12})," Close"]})]})]}),e.jsxs(ne,{children:[_e(s.startedAt),s.finishedAt?` → ${_e(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(G,{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 h=Da(l,s),p=h.filter(d=>d.change==="improved").length,u=h.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(Na,{size:14,"aria-hidden":!0})," Comparing ",l.id," → ",s.id]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:t,children:[e.jsx(Ne,{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:["+",p," improved"]}),e.jsxs("span",{className:"eval-diff-stat regressed",children:["−",u," regressed"]})]}),e.jsx(Sc,{runA:l,runB:s})]})})()}):e.jsx(G,{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(G,{className:"eval-fixtures-card",children:[e.jsxs(te,{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(h=>!h.ok).map(h=>h.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 Tc({setActiveTab:s}){const t=re(),[a,i]=r.useState([]),[n,c]=r.useState(!0),[o,l]=r.useState(null),[h,p]=r.useState(null),[u,d]=r.useState(null),[m,x]=r.useState(!1),[g,b]=r.useState(null),z=r.useRef(!1),k=r.useCallback(async()=>{c(!0);try{const v=await T.get("/eval/runs");z.current||i(v.runs||[])}catch(v){z.current||t.error(`Failed to load eval runs: ${v.message}`)}finally{z.current||c(!1)}},[t]),w=r.useCallback(async v=>{x(!0);try{const j=await T.get(`/eval/runs/${encodeURIComponent(v)}`);z.current||d(j)}catch(j){z.current||(t.error(`Failed to load run ${v}: ${j.message}`),d(null))}finally{z.current||x(!1)}},[t]),S=r.useCallback(async v=>{try{const j=await T.get(`/eval/runs/${encodeURIComponent(v)}`);z.current||b(j)}catch(j){z.current||(t.error(`Failed to load run ${v}: ${j.message}`),b(null))}},[t]);r.useEffect(()=>(z.current=!1,k(),()=>{z.current=!0}),[k]);const A=async v=>{v!==o&&(l(v),p(null),b(null),await w(v))},f=async v=>{v!==o&&(p(v),await S(v))},N=[];return g&&N.push(g),u&&N.push(u),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(Je,{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($,{variant:"secondary",size:"sm",onClick:k,disabled:n,children:[n?e.jsx(oe,{size:"sm"}):e.jsx(de,{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(oe,{size:"sm"}),e.jsx("span",{className:"muted",children:"Loading runs…"})]}):a.length===0?e.jsx(pe,{icon:e.jsx(Je,{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(v=>e.jsxs("div",{className:"eval-run-card-wrap",children:[e.jsx(La,{run:v,selected:v.id===o,onClick:()=>A(v.id)}),o&&v.id!==o?e.jsxs("button",{type:"button",className:"eval-baseline-btn",onClick:()=>f(v.id),title:"Use this run as a baseline for diffing",children:[e.jsx(Na,{size:10,"aria-hidden":!0}),"Use as baseline"]}):null]},v.id))}),e.jsx("div",{className:"eval-detail",children:m&&!u?e.jsxs("div",{className:"eval-detail-loading",children:[e.jsx(oe,{size:"sm"}),e.jsx("span",{className:"muted",children:"Loading run details…"})]}):u?e.jsx(zc,{run:u,compareRun:h,runsForDiff:N,onClearCompare:()=>{p(null),b(null)},onClearSelection:()=>{l(null),d(null),p(null),b(null)}}):e.jsx(G,{className:"eval-detail-empty",children:e.jsx(pe,{icon:e.jsx(Je,{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 Rc=Fe.memo(Tc),gt={overview:Gi,chat:dr,agents:pr,artifacts:_r,memory:Eo,tasks:Zr,activity:cl,background:rc,config:Xt,settings:Xt,marketplace:El,mods:Ll,schedules:Ql,skills:io,history:Do,minimax:Vo,plugins:Ol,doctor:yc,eval:wc,evalReport:Rc},$c="v4.5.0";function Ac(s,t,a,i){if(gt[s]){const o=gt[s];return e.jsx(o,{...t})}const n=a.find(o=>o.id===s);if(n)return e.jsx(Bl,{viewId:n.id,reloadKey:i,activeTab:t.activeTab,setActiveTab:t.setActiveTab});const c=gt.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&&(T.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($,{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(ei,{children:e.jsx(li,{children:e.jsx(Ec,{})})})}function Ec(){var se,ie,me;const s=re(),t=Re(),{isModalOpen:a}=t,i=r.useRef(!1),[n,c]=r.useState("overview"),[o,l]=r.useState(null),[h,p]=r.useState(null),[u,d]=r.useState("connecting"),[m,x]=r.useState(null),[g,b]=r.useState(!1),[z,k]=r.useState(null),[w,S]=r.useState(!1),[A,f]=r.useState(!1),[N,v]=r.useState([]),[j,E]=r.useState(!1),[R,y]=r.useState([]),[M,P]=r.useState(0),C=r.useRef(null),[D,Y]=r.useState(null);r.useEffect(()=>{let _=!1;return(async()=>{try{const L=await T.get("/mods/views");if(_)return;y(L.views||[])}catch{_||y([])}})(),()=>{_=!0}},[M,o==null?void 0:o.mods]),r.useEffect(()=>{if(!D)return;const _=D.on(L=>{((L==null?void 0:L.type)==="mod:change"||(L==null?void 0:L.type)==="mod:enabled"||(L==null?void 0:L.type)==="mod:installed")&&P(J=>J+1)});return()=>_()},[D]),r.useEffect(()=>{h!=null&&h.theme&&(Rs(h.theme),xs(h.theme))},[h==null?void 0:h.theme]),r.useEffect(()=>{i.current=a},[a]),r.useEffect(()=>{var J;if(((J=h==null?void 0:h.theme)==null?void 0:J.mode)!=="system")return;const _=window.matchMedia("(prefers-color-scheme: light)"),L=()=>Rs(h.theme.mode);return _.addEventListener("change",L),()=>_.removeEventListener("change",L)},[(se=h==null?void 0:h.theme)==null?void 0:se.mode]);const O=r.useCallback(async()=>{let _=!1;const L=()=>Promise.all([T.get("/snapshot").catch(()=>null),T.get("/settings").catch(()=>null),T.get("/agents/stuck").catch(()=>null)]),J=(U,le,q)=>{U&&l(U),le!=null&&le.data&&p(le.data),q!=null&&q.stuck&&v(q.stuck)};try{const U=await T.probeAuthStatus(),[le,q,ce]=await L();if(J(le,q,ce),le||q){x(null);return}if(!U.loopback){x("Dashboard server unreachable.");return}await new Promise(He=>setTimeout(He,1e3));const[$e,Ie,Oe]=await L();J($e,Ie,Oe),!$e&&!Ie&&x("Dashboard server unreachable.")}catch(U){const le=(U==null?void 0:U.message)??"unknown error";if(U instanceof Ga&&U.status===401){x(le),S(!0),s.error(`Auth required: ${le}`);return}x(le),s.error(`Failed to load: ${le}`)}},[s]);r.useEffect(()=>{let _=!1;const L=setTimeout(()=>{_||O()},0);return()=>{_=!0,clearTimeout(L)}},[O]),r.useEffect(()=>{let _=!1;return T.get("/settings").then(L=>{var U,le;if(_)return;const J=(le=(U=L==null?void 0:L.data)==null?void 0:U.ui)==null?void 0:le.defaultTab;J&&c(J)}).catch(()=>{}),()=>{_=!0}},[]),r.useEffect(()=>{let _=!1;const L=async()=>{try{const U=await T.get("/agents/stuck");_||v(le=>{const q=U.stuck||[];return le.length===0&&q.length>0&&s.warning(`${q.length} agent${q.length===1?"":"s"} stuck`,5e3),q})}catch{}},J=setInterval(L,3e4);return L(),()=>{_=!0,clearInterval(J)}},[]),r.useEffect(()=>{const _=new Hs;C.current=_,Y(_);const L=_.onStatus(U=>d(U)),J=_.on(U=>{var le;if(U.type==="snapshot"&&"data"in U&&U.data)l(q=>({...q??{},...U.data}));else if(U.type==="change"){const q=U,ce=((le=q.path)==null?void 0:le.split("/").pop())||q.path||"";s.info(`File changed: ${ce}`,2500)}else if(U.type==="tasks:change"){const q=U;l(ce=>{if(!ce)return ce;const $e=(ce.tasks||[]).map(Oe=>Oe.id===q.task.id?q.task:Oe),Ie=$e.some(Oe=>Oe.id===q.task.id);return{...ce,tasks:Ie?$e:[q.task,...$e]}})}else if(U.type==="tasks:delete"){const q=U;l(ce=>ce&&{...ce,tasks:(ce.tasks||[]).filter($e=>$e.id!==q.id)})}else if(U.type==="settings:change"){const q=U;q.settings&&p(q.settings)}else if(U.type==="project:change")T.get("/snapshot").then(q=>l(ce=>({...ce??{},...q}))).catch(()=>{});else if(U.type==="agents:change"||U.type==="schedules:change")T.get("/snapshot").then(q=>l(ce=>({...ce??{},...q}))).catch(()=>{});else if(U.type==="agent:status"||U.type==="agent:restarted"){const q=U;l(ce=>{if(!ce)return ce;const $e=(ce.agents||[]).map(Ie=>Ie.name===q.agent.name?q.agent:Ie);return{...ce,agents:$e}})}else if(U.type==="artifact:change")T.get("/artifacts").then(q=>{l(ce=>ce&&{...ce,artifacts:q.artifacts||[]})}).catch(()=>{});else if(U.type==="agent:stuck")v(U.agents||[]);else if(U.type==="dialog:show"){const q=U;q.dialog&&t.open({title:q.dialog.title,width:520,children:e.jsx(Ei,{dialog:q.dialog,onClose:()=>t.close()})})}});return()=>{L(),J(),_.close(),Y(null)}},[s]);const Q=r.useCallback(_=>D?D.on(_):()=>{},[D]),ae=r.useRef(0);r.useEffect(()=>{const _=()=>{ae.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 _={};yt.forEach((J,U)=>{_[String(U+1)]=J.id});const L=J=>{var He,Ds,Ns,Ps;if((J.metaKey||J.ctrlKey)&&J.key.toLowerCase()==="k"){J.preventDefault(),f(!0);return}if(J.key==="/"&&!J.metaKey&&!J.ctrlKey){const ks=(Ds=(He=J.target)==null?void 0:He.tagName)==null?void 0:Ds.toLowerCase();if(ks!=="input"&&ks!=="textarea"&&!((Ns=J.target)!=null&&Ns.isContentEditable)){J.preventDefault(),f(!0);return}}const U=document.activeElement;if(!U||U===document.body||U===document.documentElement)return;const q=J.target,ce=(Ps=q==null?void 0:q.tagName)==null?void 0:Ps.toLowerCase(),$e=ce==="input"||ce==="textarea"||ce==="select"||ce==="button"||ce==="option"||ce==="label"||!!(q!=null&&q.isContentEditable);let Ie=!1;if(q&&typeof q.closest=="function"&&(Ie=!!q.closest('form, [role="dialog"], [contenteditable], [data-no-key]')),J.repeat||i.current||$e||Ie||J.metaKey||J.ctrlKey||J.altKey||J.shiftKey||Date.now()<ae.current)return;const Oe=_[J.key];Oe&&(J.preventDefault(),F(Oe))};return document.addEventListener("keydown",L),()=>document.removeEventListener("keydown",L)},[]);const ee=r.useMemo(()=>async()=>{try{const _=await T.get("/snapshot");l(L=>({...L??{},..._}))}catch(_){s.error(`Refresh failed: ${_.message}`)}},[s]),F=r.useCallback(_=>{c(_),b(_==="settings")},[]),H=r.useMemo(()=>{const _=R.map(L=>({id:L.id,label:L.label,icon:L.kind==="iframe"?vs:Es,isMod:!0,modId:L.modId}));return[...yt,..._]},[R]),K=r.useMemo(()=>o&&h?Ac(n,{snapshot:o,settings:h,activeTab:n,setActiveTab:F,refreshSnapshot:ee,settingsMode:g,settingsActiveSection:z,setSettingsActiveSection:k},R,M):null,[n,o,h,R,M,ee,g,z,k,F]),B=async()=>{try{const _=await T.get("/projects");l(L=>{var J;return L&&{...L,projects:_.projects||[],activeProject:((J=_.projects)==null?void 0:J.find(U=>U.id===_.active))||null}})}catch(_){s.error(`Projects refresh failed: ${_.message}`)}},Z=async _=>{try{await T.post(`/projects/${encodeURIComponent(_)}/activate`),l(L=>L&&{...L,activeProject:L.projects.find(J=>J.id===_)||null})}catch(L){s.error(`Activate failed: ${L.message}`)}},he=_=>{const L=_.type;if(L==="agent")F("agents");else if(L==="task")F("tasks");else if(L==="mod")F("mods");else if(L==="schedule")F("schedules");else if(L==="project"){const J=_.item.id;Z(J)}else if(L==="command")s.info(`/${_.item.name} — run from the TUI`,2500);else if(L==="setting"){const J=_.item.id||_.item.path||"";F("settings");const U=le=>{if(le<=0)return;const q=J?document.querySelector(`[data-setting-id="${CSS.escape(J)}"]`):null;q?(q.scrollIntoView({behavior:"smooth",block:"center"}),q.classList.remove("setting-flash"),q.offsetWidth,q.classList.add("setting-flash"),window.setTimeout(()=>q.classList.remove("setting-flash"),1500)):window.setTimeout(()=>U(le-1),80)};window.setTimeout(()=>U(15),60)}},Se=((ie=h==null?void 0:h.ui)==null?void 0:ie.layout)||"topnav",W=((me=h==null?void 0:h.ui)==null?void 0:me.showHeader)!==!1;return e.jsxs("div",{className:"app","data-layout":Se,"data-active-tab":n,children:[e.jsx("a",{className:"skip-to-main",href:"#main-content",children:"Skip to main content"}),W&&e.jsx(fi,{activeTab:n,onTabChange:F,wsStatus:u,version:$c,activeProject:(o==null?void 0:o.activeProject)||null,projects:(o==null?void 0:o.projects)||[],onProjectChange:Z,onProjectsRefresh:B,onOpenSearch:()=>f(!0),settings:h,notificationsSlot:e.jsx(Ci,{wsSubscribe:Q}),showTabs:Se==="topnav",extraTabs:H}),N.length>0&&!j&&e.jsxs("div",{className:"stuck-banner",role:"alert",children:[e.jsx(ze,{size:16}),e.jsxs("span",{children:[e.jsx("strong",{children:N.length})," agent",N.length===1?"":"s"," stuck:"," ",e.jsx("span",{className:"mono",children:N.map(_=>_.name).join(", ")})]}),e.jsx($,{variant:"secondary",size:"sm",onClick:()=>{F("agents"),E(!0)},children:"Review"}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Dismiss",onClick:()=>E(!0),children:e.jsx(Ne,{size:14})})]}),e.jsxs("div",{className:"layout-body",children:[Se!=="topnav"&&e.jsx(Ni,{tabs:H,activeTab:n,onTabChange:F,settingsMode:g,settingsActiveSection:z,onSettingsSectionChange:k,onExitSettings:()=>F("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}),w&&e.jsx(Mc,{onSaved:()=>{S(!1),O()}}),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||!h)&&e.jsxs("div",{className:"loading",children:[e.jsx(oe,{size:"lg"}),e.jsx("p",{children:"Loading Bizar…"})]}),K&&e.jsx(r.Suspense,{fallback:e.jsxs("div",{className:"loading",children:[e.jsx(oe,{size:"lg"}),e.jsx("p",{children:"Loading…"})]}),children:e.jsx(Lc,{children:K})})]})]}),e.jsx(ki,{open:A,onClose:()=>f(!1),onSelect:he})]})}class Lc extends r.Component{constructor(){super(...arguments);ws(this,"state",{err:null});ws(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(ze,{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($,{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(Ka,{}):e.jsx(Ic,{})}const Pa=document.getElementById("root");if(!Pa)throw new Error("Root element #root not found");Ya(Pa).render(e.jsx(r.StrictMode,{children:e.jsx(Dc,{})}));
|