@polderlabs/bizar 5.4.1 → 5.5.1
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-DhLHZ5ua.js → EnvVarsSection-BUQnyVQD.js} +3 -3
- package/bizar-dash/dist/assets/{EnvVarsSection-DhLHZ5ua.js.map → EnvVarsSection-BUQnyVQD.js.map} +1 -1
- package/bizar-dash/dist/assets/{MobileChat-9UpvDP6-.js → MobileChat-8FupFgTv.js} +1 -1
- package/bizar-dash/dist/assets/{MobileChat-9UpvDP6-.js.map → MobileChat-8FupFgTv.js.map} +1 -1
- package/bizar-dash/dist/assets/MobileSettings-BkXtglA6.js +1 -0
- package/bizar-dash/dist/assets/MobileSettings-BkXtglA6.js.map +1 -0
- package/bizar-dash/dist/assets/{Toast-BlcKl_dN.js → Toast-CUwkLRms.js} +1 -1
- package/bizar-dash/dist/assets/{Toast-BlcKl_dN.js.map → Toast-CUwkLRms.js.map} +1 -1
- package/bizar-dash/dist/assets/{icons-CMPxNV8t.js → icons-COpQr35l.js} +125 -110
- package/bizar-dash/dist/assets/icons-COpQr35l.js.map +1 -0
- package/bizar-dash/dist/assets/main-Bz_zWFCw.css +1 -0
- package/bizar-dash/dist/assets/main-gqVwliHz.js +18 -0
- package/bizar-dash/dist/assets/main-gqVwliHz.js.map +1 -0
- package/bizar-dash/dist/assets/mobile-B7dAkmYd.js +1 -0
- package/bizar-dash/dist/assets/{mobile-DDY1lquG.js.map → mobile-B7dAkmYd.js.map} +1 -1
- package/bizar-dash/dist/assets/mobile-layout-ClC6Qa42.js +2 -0
- package/bizar-dash/dist/assets/mobile-layout-ClC6Qa42.js.map +1 -0
- package/bizar-dash/dist/assets/{useSlashCommands-eFCiWHVt.js → useSlashCommands-B3MZ1JXa.js} +2 -2
- package/bizar-dash/dist/assets/{useSlashCommands-eFCiWHVt.js.map → useSlashCommands-B3MZ1JXa.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/backup-store.mjs +6 -1
- package/bizar-dash/src/server/bg-spawner.mjs +791 -0
- package/bizar-dash/src/server/headroom.mjs +3 -1
- package/bizar-dash/src/server/memory-lightrag.mjs +268 -2
- package/bizar-dash/src/server/memory-store.mjs +43 -3
- 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 +161 -0
- package/bizar-dash/src/server/routes/lightrag.mjs +10 -0
- package/bizar-dash/src/server/routes/memory.mjs +8 -0
- package/bizar-dash/src/server/routes/opencode-session-detail.mjs +1 -1
- package/bizar-dash/src/server/server.mjs +26 -1
- package/bizar-dash/src/web/App.tsx +46 -36
- package/bizar-dash/src/web/components/InstallConfirmDialog.tsx +1 -1
- package/bizar-dash/src/web/components/Sidebar.tsx +7 -27
- package/bizar-dash/src/web/components/Topbar.tsx +48 -11
- package/bizar-dash/src/web/lib/types.ts +39 -1
- package/bizar-dash/src/web/styles/main.css +93 -26
- package/bizar-dash/src/web/styles/memory.css +17 -0
- package/bizar-dash/src/web/styles/settings.css +9 -171
- package/bizar-dash/src/web/views/BackgroundAgents.tsx +399 -30
- package/bizar-dash/src/web/views/Marketplace.tsx +192 -31
- package/bizar-dash/src/web/views/Settings.tsx +205 -184
- package/bizar-dash/src/web/views/SpawnAgentModal.tsx +221 -0
- 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/BackgroundAgents.test.tsx +160 -0
- package/bizar-dash/tests/background-pause-resume.test.mjs +46 -0
- 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-spawn-from-ui.test.mjs +36 -0
- package/bizar-dash/tests/background-steer-sdk.test.mjs +71 -0
- package/bizar-dash/tests/background-steer.test.mjs +60 -0
- package/bizar-dash/tests/lightrag-startup-hook.test.mjs +206 -0
- package/bizar-dash/tests/memory-auto-reindex.test.mjs +196 -0
- package/bizar-dash/tests/memory-cli.test.mjs +1 -1
- package/bizar-dash/tests/memory-default-vault.test.mjs +90 -3
- package/bizar-dash/tests/memory-lightrag-extended.test.mjs +131 -0
- package/bizar-dash/tests/views/Marketplace.test.tsx +200 -0
- package/bizar-dash/tests/views/Memory.test.tsx +235 -0
- package/bizar-dash/tests/views/Settings.test.tsx +160 -0
- package/bizar-dash/tests/views/sidebar.test.tsx +116 -0
- package/bizar-dash/tests/views/topbar.test.tsx +102 -0
- package/cli/bin.mjs +16 -0
- package/cli/commands/deploy/docker.mjs +2 -1
- package/cli/commands/lightrag.mjs +171 -0
- package/cli/commands/marketplace.mjs +1 -1
- package/cli/commands/service.mjs +7 -0
- package/cli/commands/util.mjs +8 -1
- package/cli/init.mjs +1 -1
- package/cli/post-install-smoke.mjs +230 -0
- package/cli/provision.mjs +177 -0
- package/cli/provision.test.mjs +180 -0
- package/cli/service-controller.mjs +378 -28
- package/cli/service-controller.test.mjs +100 -0
- package/cli/service-env.mjs +139 -0
- package/cli/service.mjs +23 -0
- package/config/agents/_shared/AGENT_BASELINE.md +6 -6
- package/install.sh +87 -6
- package/package.json +1 -1
- package/plugins/bizar/index.ts +147 -0
- package/plugins/bizar/src/background-state.ts +95 -5
- package/plugins/bizar/src/background.ts +571 -15
- package/plugins/bizar/src/hooks/memory-inject.ts +247 -0
- package/plugins/bizar/src/hooks/memory-write-on-end.ts +188 -0
- package/plugins/bizar/src/opencode-runner.ts +100 -287
- package/plugins/bizar/src/tools/bg-pause.ts +77 -0
- package/plugins/bizar/src/tools/bg-report-progress.ts +101 -0
- package/plugins/bizar/src/tools/bg-resume.ts +72 -0
- package/plugins/bizar/src/tools/bg-send-message.ts +204 -0
- package/plugins/bizar/src/tools/bg-spawn.ts +237 -151
- package/plugins/bizar/src/tools/bg-status.ts +10 -0
- package/plugins/bizar/src/tools/memory-list.ts +135 -0
- package/plugins/bizar/src/tools/memory-read.ts +142 -0
- package/plugins/bizar/src/tools/memory-search.ts +228 -0
- package/plugins/bizar/src/tools/memory-write.ts +183 -0
- package/plugins/bizar/tests/memory-write-on-end.test.ts +92 -0
- package/plugins/bizar/tests/tools/bg-pause.test.ts +64 -0
- package/plugins/bizar/tests/tools/bg-report-progress.test.ts +82 -0
- package/plugins/bizar/tests/tools/bg-resume.test.ts +43 -0
- package/plugins/bizar/tests/tools/bg-send-message.test.ts +119 -0
- package/plugins/bizar/tests/tools/bg-spawn-http.test.ts +223 -0
- package/bizar-dash/dist/assets/MobileSettings-BFmN9ZWR.js +0 -1
- package/bizar-dash/dist/assets/MobileSettings-BFmN9ZWR.js.map +0 -1
- package/bizar-dash/dist/assets/icons-CMPxNV8t.js.map +0 -1
- package/bizar-dash/dist/assets/main-Dhrvp9Gt.js +0 -16
- package/bizar-dash/dist/assets/main-Dhrvp9Gt.js.map +0 -1
- package/bizar-dash/dist/assets/main-O2tZVdHm.css +0 -1
- package/bizar-dash/dist/assets/mobile-DDY1lquG.js +0 -1
- package/bizar-dash/dist/assets/mobile-layout-BjkoHh1W.js +0 -2
- package/bizar-dash/dist/assets/mobile-layout-BjkoHh1W.js.map +0 -1
- package/bizar-dash/src/web/components/SettingsNav.tsx +0 -101
- package/bizar-dash/tests/settings-layout.test.tsx +0 -129
- package/bizar-dash/tests/settings-mode-wiring.test.tsx +0 -151
- package/bizar-dash/tests/settings-nav.test.tsx +0 -126
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
var Ga=Object.defineProperty;var Ka=(s,t,a)=>t in s?Ga(s,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):s[t]=a;var bs=(s,t,a)=>Ka(s,typeof t!="symbol"?t+"":t,a);import{a as R,c as H,f as ze,b as Oe,S as le,t as na,e as Ya,p as Xa,d as us,g as Cs,_ as Qa,W as Hs,A as Ja,M as Za}from"./mobile-layout-ClC6Qa42.js";import{r,j as e,a as ia,R as De,b as en}from"./react-vendor-Dn4wqh4Z.js";import{X as Ne,A as ra,R as oe,F as sn,H as tn,a as an,C as la,b as $e,c as nn,d as Ue,e as Xe,L as oa,M as Qs,B as Be,f as Gs,S as Rs,g as Te,h as rn,i as We,j as Fe,P as ss,k as hs,l as Ge,m as Ts,n as vt,o as He,p as ca,q as ln,r as yt,s as bt,t as da,W as Nt,u as kt,v as ma,T as Ke,w as zs,G as ua,x as Se,y as ve,z as ps,D as ye,E as Ee,I as wt,J as vs,K as be,N as ts,O as Ks,Q as Ye,U as gs,V as ut,Y as on,Z as ke,_ as St,$ as Ct,a0 as xs,a1 as cn,a2 as Js,a3 as js,a4 as dn,a5 as Is,a6 as as,a7 as ha,a8 as xa,a9 as fs,aa as mn,ab as ys,ac as un,ad as hn,ae as xn,af as Ms,ag as pn,ah as gn,ai as jn,aj as fn,ak as vn,al as yn,am as Ut,an as pa,ao as bn,ap as zt,aq as Nn,ar as kn,as as Rt,at as wn,au as Sn,av as Cn,aw as zn,ax as Rn,ay as Tn,az as $n,aA as ht,aB as Tt,aC as $t,aD as ns,aE as ga,aF as is,aG as An,aH as In,aI as Ys,aJ as Mn,aK as ja,aL as $s,aM as Ln,aN as En,aO as fa,aP as As,aQ as xt,aR as At,aS as va,aT as me,aU as Dn,aV as Pn,aW as ya,aX as Fn,aY as On,aZ as Bt,a_ as Un,a$ as ba,b0 as et,b1 as Na,b2 as It,b3 as Bn,b4 as _n,b5 as qn,b6 as ka,b7 as Wn,b8 as Vn,b9 as Hn,ba as Gn,bb as Kn,bc as wa}from"./icons-COpQr35l.js";import{B as T,C as G,a as se,b as ae,A as Yn,c as Xn,H as Qn,S as Jn,T as Zn,E as ei,G as _t,U as si}from"./EnvVarsSection-BUQnyVQD.js";import{u as re,T as ti}from"./Toast-CUwkLRms.js";import{V as Mt,C as ai,u as ni,a as ii,b as ri,c as li}from"./useSlashCommands-B3MZ1JXa.js";import{M as Sa,r as Ca}from"./markdown-C6mXtQxD.js";import"./vendor-CeHGtduv.js";const za=r.createContext(null),oi=["button:not([disabled])","[href]","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(", ");function Re(){const s=r.useContext(za);return s||{open:()=>"",close:()=>{},isModalOpen:!1}}function ci({children:s}){const[t,a]=r.useState([]),i=r.useCallback(o=>{a(c=>{if(!o)return c.slice(0,-1);const l=c.findIndex(x=>x.id===o);return l===-1||l!==c.length-1?c:c.slice(0,-1)})},[]),n=r.useCallback(o=>{const c=`m${Math.random().toString(36).slice(2,9)}`;return a(l=>[...l,{...o,id:c}]),c},[]);return r.useEffect(()=>{if(t.length===0)return;const o=c=>{c.key==="Escape"&&(c.stopPropagation(),i())};return document.addEventListener("keydown",o),()=>document.removeEventListener("keydown",o)},[t.length,i]),e.jsxs(za.Provider,{value:{open:n,close:i,isModalOpen:t.length>0},children:[s,typeof document<"u"&&ia.createPortal(e.jsx("div",{className:"modal-stack","aria-hidden":t.length===0,children:t.map((o,c)=>e.jsx(di,{modal:o,onClose:()=>{var l;(l=o.onClose)==null||l.call(o),i(o.id)},depth:c},o.id))}),document.body)]})}function di({modal:s,onClose:t,depth:a}){const i=r.useRef(null),n=r.useRef(null),o=r.useId(),c=()=>{const l=i.current;return l?Array.from(l.querySelectorAll(oi)).filter(x=>!x.hasAttribute("disabled")&&x.tabIndex!==-1):[]};return r.useEffect(()=>{var p;n.current=document.activeElement instanceof HTMLElement?document.activeElement:null,(p=c()[0]??i.current)==null||p.focus();const x=h=>{var k,z,C;if(h.key!=="Tab")return;const d=c();if(d.length===0){h.preventDefault(),(k=i.current)==null||k.focus();return}const m=d[0],u=d[d.length-1],g=document.activeElement instanceof HTMLElement?document.activeElement:null;if(h.shiftKey){(!g||g===m||!((z=i.current)!=null&&z.contains(g)))&&(h.preventDefault(),u.focus());return}(!g||g===u||!((C=i.current)!=null&&C.contains(g)))&&(h.preventDefault(),m.focus())};return document.addEventListener("keydown",x),()=>{document.removeEventListener("keydown",x);const h=n.current;h&&h.isConnected&&h.focus()}},[]),e.jsx("div",{className:"modal-backdrop",onClick:l=>{l.stopPropagation(),l.target===l.currentTarget&&t()},style:a>0?{background:"rgba(0,0,0,0.4)"}:void 0,children:e.jsxs("div",{ref:i,className:"modal",role:"dialog","aria-modal":"true","aria-labelledby":s.title?o: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:o,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 mi=200,ui=5*60*1e3,es=new Map;function hi(s){const t=es.get(s);return t?Date.now()-t.ts>ui?(es.delete(s),null):t.data:null}function st(s,t){es.size>=mi&&[...es.entries()].sort((i,n)=>i[1].ts-n[1].ts).slice(0,50).map(([i])=>i).forEach(i=>es.delete(i)),es.set(s,{data:t,ts:Date.now()})}function xi(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 pi(s){return[...s].sort((t,a)=>t.isDir!==a.isDir?t.isDir?-1:1:t.name.localeCompare(a.name,void 0,{sensitivity:"base"}))}function gi(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 Ra({value:s,onChange:t,initialPath:a,projectsDirectory:i,rootLabel:n="Home",height:o=360}){const[c,l]=r.useState(a??i??""),[x,p]=r.useState(new Set),[h,d]=r.useState(-1),[m,u]=r.useState(null),[g,k]=r.useState({}),[z,C]=r.useState(!1),[y,w]=r.useState(null),[$,j]=r.useState(!1),[N,v]=r.useState(""),[f,D]=r.useState(null),[M,b]=r.useState(!1),A=r.useRef(null),O=r.useCallback(async E=>{try{const J=hi(E);if(J)return J;const ee=await R.get("/fs?path="+encodeURIComponent(E));return st(E,ee),ee}catch{return null}},[]),S=r.useCallback(async E=>{var J;C(!0),w(null);try{const ee=await R.get("/fs?path="+encodeURIComponent(E));st(E,ee),u(ee),d(-1)}catch(ee){const ue=((J=ee.data)==null?void 0:J.message)??ee.message??"Failed to load directory";w(ue)}finally{C(!1)}},[]);r.useEffect(()=>{c?S(c):R.get("/fs").then(E=>{st("",E),u(E),l(E.path),E.path!==s&&t(E.path)}).catch(()=>{w("Could not determine home directory."),C(!1)})},[c]),r.useEffect(()=>{s&&s!==c&&l(s)},[s]);const F=m?pi(m.entries):[],_=F.filter(E=>E.isDir),P=F,V=E=>{E.isDir&&(l(E.path),t(E.path))},W=()=>{m!=null&&m.parent&&(l(m.parent),t(m.parent))},K=E=>{E!==c&&(l(E),t(E))},B=async()=>{const E=await O("");E&&(l(E.path),t(E.path))},Q=async()=>{if(!i)return;const E=await O(i);E&&(l(E.path),t(E.path))},te=()=>{j(!0),v(""),D(null),setTimeout(()=>{var E;return(E=A.current)==null?void 0:E.focus()},0)},Z=()=>{j(!1),v(""),D(null)},ie=async()=>{var J;const E=gi(N);if(!E.ok){D(E.reason);return}b(!0),D(null);try{const ee=await R.post("/fs/mkdir",{parent:c,name:N.trim()});es.delete(c),await S(c),t(ee.path),j(!1),v("")}catch(ee){const ue=ee;ue.status===409?D(`A folder named "${N.trim()}" already exists.`):D(((J=ue.data)==null?void 0:J.message)??ee.message??"Failed to create folder.")}finally{b(!1)}},je=E=>{E.key==="Enter"?(E.preventDefault(),ie()):E.key==="Escape"&&(E.preventDefault(),Z())},Ce=E=>{p(J=>{const ee=new Set(J);return ee.has(E)?ee.delete(E):ee.add(E),ee}),g[E]||O(E).then(J=>{J&&k(ee=>({...ee,[E]:J.entries.filter(ue=>ue.isDir)}))})},L=E=>{if(!m)return;const J=P.filter(ce=>ce.isDir),ee=P.filter(ce=>!ce.isDir),ue=[...J,...ee];if(E.key==="ArrowDown")E.preventDefault(),d(ce=>Math.min(ce+1,ue.length-1));else if(E.key==="ArrowUp")E.preventDefault(),d(ce=>Math.max(ce-1,0));else if(E.key==="Enter"||E.key===" "){E.preventDefault();const ce=ue[h];ce&&(E.key==="Enter"&&ce.isDir?V(ce):ce.isDir&&t(ce.path))}else E.key==="Backspace"&&(E.preventDefault(),W())},U=xi((m==null?void 0:m.path)??c??"/"),q=m==null?void 0:m.parent,Y=q!=null,ne=c.split("/").filter(Boolean).at(-1)??"/";return e.jsxs("div",{className:"file-browser",onKeyDown:L,tabIndex:-1,children:[e.jsx("div",{className:"file-browser-breadcrumb",role:"navigation","aria-label":"Path breadcrumb",children:U.map((E,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:()=>K(E.path),title:E.path,children:J===0?E.path==="/"?"/":n:E.label})]},E.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:W,disabled:!Y,title:"Go up (Backspace)","aria-label":"Go up one level",children:e.jsx(ra,{size:13})}),e.jsx("button",{type:"button",className:"file-browser-tool-btn",onClick:()=>S(c),disabled:z,title:"Refresh","aria-label":"Refresh",children:e.jsx(oe,{size:13,className:z?"spin":""})}),e.jsx("button",{type:"button",className:"file-browser-tool-btn",onClick:te,title:"New folder","aria-label":"Create new folder",children:e.jsx(sn,{size:13})}),e.jsxs("div",{className:"file-browser-chips",children:[e.jsxs("button",{type:"button",className:"file-browser-chip",onClick:B,children:[e.jsx(tn,{size:11})," ",n]}),i&&e.jsxs("button",{type:"button",className:"file-browser-chip",onClick:Q,title:i,children:[e.jsx(an,{size:11})," ",i.split("/").filter(Boolean).at(-1)??"Projects"]})]})]}),$?e.jsxs("div",{className:"file-browser-mkdir",children:[e.jsx("input",{ref:A,type:"text",className:"file-browser-mkdir-input",placeholder:"Folder name",value:N,onChange:E=>{v(E.target.value),D(null)},onKeyDown:je,"aria-label":"New folder name","aria-invalid":f?"true":void 0,"aria-describedby":f?"mkdir-error":void 0,disabled:M,maxLength:255}),f?e.jsx("span",{id:"mkdir-error",className:"file-browser-mkdir-error",role:"alert",children:f}):e.jsx("span",{className:"file-browser-mkdir-hint",children:"Enter to create, Esc to cancel"})]}):e.jsx("span",{className:"file-browser-count-hint",children:z?"…":`${F.length} in ${ne}`})]}),y&&e.jsxs("div",{className:"file-browser-error",children:[e.jsx(la,{size:13}),e.jsx("span",{children:y}),e.jsx("button",{type:"button",className:"file-browser-retry",onClick:()=>S(c),children:"Retry"})]}),e.jsxs("div",{className:"file-browser-body",style:{height:o},children:[e.jsx("div",{className:"file-browser-pane file-browser-tree","aria-label":"Folder tree",children:z&&!m?e.jsx(ji,{}):e.jsx(Ta,{path:c,entries:_,expanded:x,childrenMap:g,onToggle:Ce,onNavigate:V,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(fi,{}):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."]}),P.length===0?e.jsx("div",{className:"file-browser-empty",children:"This folder is empty"}):e.jsx("div",{className:"file-browser-flat-list",children:P.map((E,J)=>{const ee=E.isDir,ue=J===h,ce=E.path===s;return e.jsxs("div",{role:"option","aria-selected":ce,className:["file-browser-row",ee?"file-browser-row--dir":"file-browser-row--file",ue&&"file-browser-row--selected",ce&&ee&&"file-browser-row--active",!ee&&"file-browser-row--disabled"].filter(Boolean).join(" "),onClick:()=>{ee&&(d(J),t(E.path))},onDoubleClick:()=>{ee&&V(E)},title:E.path,children:[e.jsx("span",{className:"file-browser-row-icon",children:ee?e.jsx($e,{size:13}):e.jsx(nn,{size:13})}),e.jsx("span",{className:"file-browser-row-name",children:E.name}),e.jsx("span",{className:"file-browser-row-type",children:ee?"Folder":""})]},E.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 Ta({path:s,entries:t,expanded:a,childrenMap:i,onToggle:n,onNavigate:o,level:c}){return e.jsx("ul",{className:"file-browser-tree-list",role:"group",children:t.map(l=>{const x=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",x&&"file-browser-tree-row--expanded"].filter(Boolean).join(" "),style:{paddingLeft:`${c*16+8}px`},children:[e.jsx("button",{type:"button",className:"file-browser-tree-toggle",onClick:h=>{h.stopPropagation(),n(l.path)},"aria-label":x?"Collapse":"Expand",children:(p.length>0,x?e.jsx(Ue,{size:11}):e.jsx(Xe,{size:11}))}),e.jsxs("button",{type:"button",className:"file-browser-tree-name",onClick:()=>o(l),title:l.path,children:[e.jsx($e,{size:12}),e.jsx("span",{children:l.name})]})]}),x&&p.length>0&&e.jsx(Ta,{path:l.path,entries:p,expanded:a,childrenMap:i,onToggle:n,onNavigate:o,level:c+1})]},l.path)})})}function ji(){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 fi(){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 pt=[{id:"overview",label:"Overview",icon:oa},{id:"chat",label:"Chat",icon:Qs},{id:"agents",label:"Agents",icon:Be},{id:"artifacts",label:"Glyphs",icon:Gs},{id:"tasks",label:"Tasks",icon:Rs},{id:"activity",label:"Activity",icon:Te},{id:"background",label:"Active",icon:rn},{id:"skills",label:"Skills",icon:We},{id:"memory",label:"Memory",icon:Fe},{id:"mods",label:"Mods",icon:ss},{id:"marketplace",label:"Marketplace",icon:hs},{id:"schedules",label:"Schedules",icon:Ge},{id:"plugins",label:"Plugins",icon:ss},{id:"history",label:"History",icon:Ts},{id:"minimax",label:"Usage",icon:vt},{id:"eval",label:"Eval",icon:He},{id:"doctor",label:"Doctor",icon:ca},{id:"__settings_divider__",label:"",icon:ln},{id:"settings-theme",label:"Theme",icon:yt},{id:"settings-general",label:"General",icon:bt},{id:"settings-layout",label:"Layout",icon:da},{id:"settings-network",label:"Network",icon:Nt},{id:"settings-notifications",label:"Notifications",icon:kt},{id:"settings-auth",label:"Auth",icon:ma},{id:"settings-env-vars",label:"Env Vars",icon:Ke},{id:"settings-agents",label:"Agents",icon:Be},{id:"settings-system-llm",label:"System LLM",icon:zs},{id:"settings-headroom",label:"Headroom",icon:ua},{id:"settings-updates",label:"Updates",icon:oe},{id:"settings-activity-log",label:"Activity Log",icon:Te},{id:"settings-workspaces",label:"Workspaces",icon:$e}];function vi({activeTab:s,onTabChange:t,wsStatus:a,version:i,activeProject:n,projects:o,onProjectChange:c,onProjectsRefresh:l,onOpenSearch:x,settings:p,rightSlot:h,notificationsSlot:d,showTabs:m=!0,extraTabs:u}){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(yi,{activeProject:n,projects:o,onChange:c,onRefresh:l,settings:p??null}),e.jsxs("button",{type:"button",className:"topbar-search",onClick:x,title:"Search (Ctrl/Cmd+K)","aria-label":"Open search",children:[e.jsx(Se,{size:14}),e.jsx("span",{className:"muted",children:"Search…"}),e.jsx("kbd",{children:"⌘K"})]}),e.jsx("div",{className:"topbar-spacer"}),e.jsxs("div",{className:"topbar-right",children:[d,h,e.jsxs("div",{className:H("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:[pt.map(g=>{if(g.id==="__settings_divider__")return e.jsx("span",{className:"tab-separator tab-separator-settings","aria-hidden":"true",children:e.jsx("span",{className:"tab-separator-label",children:"Settings"})},g.id);const k=g.icon,z=g.id===s;return e.jsxs("button",{type:"button",role:"tab","aria-selected":z,className:H("tab",z&&"tab-active"),onClick:()=>t(g.id),title:g.label,children:[e.jsx(k,{size:14,className:"tab-icon"}),e.jsx("span",{className:"tab-label",children:g.label})]},g.id)}),u&&u.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"tab-separator","aria-hidden":"true"}),u.map(g=>{const k=g.icon,z=g.id===s;return e.jsxs("button",{type:"button",role:"tab","aria-selected":z,className:H("tab","tab-mod",z&&"tab-active"),onClick:()=>t(g.id),title:`${g.label} (mod)`,children:[e.jsx(k,{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 yi({activeProject:s,projects:t,onChange:a,onRefresh:i,settings:n}){const[o,c]=r.useState(!1),l=Re();r.useEffect(()=>{if(!o)return;const p=()=>c(!1);return document.addEventListener("click",p),()=>document.removeEventListener("click",p)},[o]);const x=()=>{l.open({title:"Add project",children:e.jsx(bi,{settings:n,onAdd:async(p,h)=>{try{await R.post("/projects",{path:p,name:h}),i(),c(!1),l.close()}catch(d){alert(`Add failed: ${d.message}`)}}}),footer:e.jsx("div",{className:"modal-footer-actions",children:e.jsx(T,{variant:"ghost",onClick:()=>l.close(),children:"Cancel"})})})};return e.jsxs("div",{className:"project-selector",onClick:p=>p.stopPropagation(),children:[e.jsxs("button",{type:"button",className:"project-selector-btn",onClick:()=>c(p=>!p),title:"Switch active project","aria-haspopup":"menu","aria-expanded":o,children:[e.jsx($e,{size:14}),e.jsx("span",{className:"project-selector-name",children:(s==null?void 0:s.name)||"(no project)"}),e.jsx(Ue,{size:12})]}),o&&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(oe,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn",onClick:x,title:"Add project","aria-label":"Add project",children:e.jsx(ve,{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:H("project-selector-item",(s==null?void 0:s.id)===p.id&&"active"),onClick:()=>{a(p.id),c(!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 bi({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,o]=r.useState(""),[c,l]=r.useState(!1),[x,p]=r.useState(null),h=async()=>{var u;if(a){l(!0),p(null);try{await R.get("/fs?path="+encodeURIComponent(a)),t(a,n||null)}catch(g){const k=g;k.status===404?p("That folder no longer exists. Pick another."):p(((u=k.data)==null?void 0:u.message)??g.message??"Validation failed.")}finally{l(!1)}}};return e.jsxs("div",{children:[e.jsx("label",{className:"field-label",children:"Folder"}),e.jsx(Ra,{value:a,onChange:u=>{i(u),p(null)},projectsDirectory:(m=s==null?void 0:s.dashboard)==null?void 0:m.projectsDirectory,height:320}),x&&e.jsx("p",{className:"field-help",style:{color:"var(--error)",marginTop:4},children:x}),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:u=>o(u.target.value)})]}),e.jsx("div",{style:{marginTop:"var(--space-3)",display:"flex",justifyContent:"flex-end"},children:e.jsxs(T,{variant:"primary",onClick:h,disabled:!a||c,children:[c?e.jsx("span",{className:"btn-spinner"}):null,c?"Checking…":"Add"]})})]})}function Ni({tabs:s,activeTab:t,onTabChange:a}){const i=s.filter(o=>!o.isMod),n=s.filter(o=>o.isMod);return e.jsx("aside",{className:"sidebar","aria-label":"Primary navigation",children:e.jsxs("nav",{className:"sidebar-nav",role:"tablist",children:[i.map(o=>{const c=o.icon,l=o.id===t;return e.jsxs("button",{type:"button",role:"tab","aria-selected":l,className:H("sidebar-tab",l&&"sidebar-tab-active"),onClick:()=>a(o.id),title:o.label,children:[e.jsx(c,{size:18,"aria-hidden":!0}),e.jsx("span",{className:"sidebar-tab-label",children:o.label})]},o.id)}),n.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"}),n.map(o=>{const c=o.icon,l=o.id===t;return e.jsxs("button",{type:"button",role:"tab","aria-selected":l,className:H("sidebar-tab","sidebar-tab-mod",l&&"sidebar-tab-active"),onClick:()=>a(o.id),title:`${o.label} (mod)`,children:[e.jsx(c,{size:18,"aria-hidden":!0}),e.jsx("span",{className:"sidebar-tab-label",children:o.label})]},o.id)})]})]})})}const tt=[{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,o]=r.useState(""),[c,l]=r.useState("all"),[x,p]=r.useState([]),[h,d]=r.useState(!1),[m,u]=r.useState(0),g=r.useRef(null),k=r.useRef(null);if(r.useEffect(()=>{let w;return s&&(k.current=document.activeElement instanceof HTMLElement?document.activeElement:null,o(""),p([]),u(0),w=window.setTimeout(()=>{var $;return($=g.current)==null?void 0:$.focus()},30)),()=>{if(w&&window.clearTimeout(w),!s)return;const $=k.current;$&&$.isConnected&&$.focus()}},[s]),r.useEffect(()=>{if(!s)return;if(!n.trim()){p([]),u(0);return}let w=!1;d(!0);const $=setTimeout(()=>{R.get(`/search?q=${encodeURIComponent(n)}&scope=${c}`).then(j=>{w||(p(j.results||[]),u(0))}).catch(j=>{w||i.error(`Search failed: ${j.message}`)}).finally(()=>!w&&d(!1))},150);return()=>{w=!0,clearTimeout($)}},[n,c,s,i]),!s)return null;const z={};for(const w of x){const $=w.type.toLowerCase();z[$]=z[$]||[],z[$].push(w)}const C=[];for(const w of tt.map($=>$.id)){const $=qt[w];$&&z[$]&&C.push(...z[$])}const y=w=>{if(w.key==="Escape")t();else if(w.key==="ArrowDown"){if(w.preventDefault(),C.length===0)return;u($=>Math.min($+1,C.length-1))}else if(w.key==="ArrowUp"){if(w.preventDefault(),C.length===0)return;u($=>Math.max($-1,0))}else w.key==="Enter"&&C[m]&&(w.preventDefault(),a(C[m]),t())};return e.jsx("div",{className:"search-modal-backdrop",onClick:t,children:e.jsxs("div",{className:"search-modal",role:"dialog","aria-modal":"true","aria-labelledby":"search-modal-title",onClick:w=>w.stopPropagation(),children:[e.jsxs("div",{className:"search-modal-head",role:"search",children:[e.jsx(Se,{size:14,"aria-hidden":!0}),e.jsx("span",{id:"search-modal-title",className:"sr-only",children:"Search"}),e.jsx("input",{ref:g,className:"search-modal-input",placeholder:"Search tasks, agents, settings, projects…",value:n,onChange:w=>o(w.target.value),onKeyDown:y,"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:tt.map(w=>e.jsx("button",{type:"button",role:"tab","aria-selected":c===w.id,className:H("search-scope",c===w.id&&"search-scope-active"),onClick:()=>l(w.id),children:w.label},w.id))}),e.jsxs("div",{className:"search-modal-body",children:[h&&e.jsx("div",{className:"muted",children:"Searching…"}),!h&&n&&C.length===0&&e.jsx("div",{className:"muted",children:"No results."}),!h&&!n&&e.jsx("div",{className:"muted",children:"Type to search…"}),tt.map(w=>{const $=qt[w.id];if(!$)return null;const j=z[$];return!j||j.length===0?null:e.jsxs("div",{className:"search-group",children:[e.jsx("div",{className:"search-group-head",children:w.label}),j.map(N=>{const v=C.indexOf(N);return e.jsxs("button",{type:"button",className:H("search-result",v===m&&"search-result-active"),onMouseEnter:()=>u(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}`)})]},w.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:wt,success:Ee,warning:ye,error:la};function Ci({onCountChange:s,wsSubscribe:t}){const a=re(),[i,n]=r.useState(!1),[o,c]=r.useState([]),[l,x]=r.useState(null),[p,h]=r.useState(!1),d=r.useRef(null),m=r.useRef(0),u=async()=>{var y;try{h(!0);const w=await R.get("/notifications?limit=200");c(w.notifications||[]),x(w.stats||null),m.current=((y=w.stats)==null?void 0:y.unread)||0,s==null||s(m.current)}catch(w){console.warn("[notifications] reload failed:",w.message)}finally{h(!1)}};r.useEffect(()=>{u()},[]),r.useEffect(()=>t?t(w=>{if(w.type==="notification:new"){const $=w.notification;c(j=>[$,...j.filter(N=>N.id!==$.id)]),$.read||(m.current+=1,x(j=>j?{...j,unread:(j.unread||0)+1}:{total:1,unread:1,lastTs:$.ts,counts:{[$.severity||"info"]:1}}),s==null||s(m.current))}else w.type==="notifications:change"&&u()}):void 0,[t]),r.useEffect(()=>{if(!i)return;const y=$=>{d.current&&(d.current.contains($.target)||n(!1))},w=$=>{$.key==="Escape"&&n(!1)};return document.addEventListener("mousedown",y),document.addEventListener("keydown",w),()=>{document.removeEventListener("mousedown",y),document.removeEventListener("keydown",w)}},[i]);const g=async()=>{try{await R.post("/notifications/read-all",{}),c(y=>y.map(w=>({...w,read:!0}))),x(y=>y&&{...y,unread:0}),m.current=0,s==null||s(0),a.success("All notifications marked as read.",1500)}catch(y){a.error(`Failed: ${y.message}`)}},k=async y=>{try{await R.post(`/notifications/${encodeURIComponent(y)}/read`,{}),c(w=>w.map($=>$.id===y?{...$,read:!0}:$)),x(w=>w&&{...w,unread:Math.max(0,(w.unread||1)-1)}),m.current=Math.max(0,m.current-1),s==null||s(m.current)}catch(w){a.error(`Failed: ${w.message}`)}},z=async y=>{try{await R.del(`/notifications/${encodeURIComponent(y)}`),c(w=>{const $=w.find(j=>j.id===y);return $&&!$.read&&(m.current=Math.max(0,m.current-1),x(j=>j&&{...j,unread:Math.max(0,j.unread-1)}),s==null||s(m.current)),w.filter(j=>j.id!==y)})}catch(w){a.error(`Failed: ${w.message}`)}},C=(l==null?void 0:l.unread)||0;return e.jsxs("div",{className:"notifications-root",ref:d,children:[e.jsxs("button",{type:"button",className:H("topbar-icon-btn notifications-bell",i&&"is-open"),onClick:()=>n(y=>!y),title:"Notifications","aria-label":"Notifications","aria-haspopup":"true","aria-expanded":i,children:[e.jsx(kt,{size:16}),C>0&&e.jsx("span",{className:"notifications-badge",children:C>99?"99+":C})]}),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"}),C>0&&e.jsxs("span",{className:"muted text-sm",children:[" · ",C," unread"]})]}),e.jsxs("div",{className:"notifications-panel-head-actions",children:[e.jsxs(T,{size:"sm",variant:"ghost",onClick:g,disabled:C===0,children:[e.jsx(ps,{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&&o.length===0?e.jsx("div",{className:"notifications-empty muted",children:"Loading…"}):o.length===0?e.jsx("div",{className:"notifications-empty muted",children:"No notifications yet."}):o.map(y=>{const w=Si[y.severity]||wt;return e.jsxs("div",{className:H("notification-item",!y.read&&"is-unread",`severity-${y.severity}`),children:[e.jsx(w,{size:14,className:`notification-icon severity-${y.severity}`}),e.jsxs("div",{className:"notification-body",children:[y.title&&e.jsx("div",{className:"notification-title",children:y.title}),e.jsx("div",{className:"notification-msg",children:y.message}),e.jsxs("div",{className:"notification-meta muted",children:[e.jsx("span",{className:"mono",children:y.source}),e.jsx("span",{children:"·"}),e.jsx("span",{children:ze(y.ts)})]})]}),e.jsxs("div",{className:"notification-actions",children:[!y.read&&e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>k(y.id),title:"Mark as read","aria-label":"Mark as read",children:e.jsx(ps,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger",onClick:()=>z(y.id),title:"Remove","aria-label":"Remove",children:e.jsx(Ne,{size:12})})]})]},y.id)})}),e.jsx("footer",{className:"notifications-panel-foot",children:e.jsx("span",{className:"muted text-sm",children:l?`${l.total} total · last ${ze(l.lastTs||new Date().toISOString())}`:""})})]})]})}function 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,o=s==null?void 0:s.lastUsedSlug,c=i==="toggle";return e.jsxs("div",{children:[c?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})]}),o&&e.jsxs("p",{style:{fontSize:13,color:"var(--color-muted)"},children:["Last used plan: ",e.jsx("code",{children:o})]}),e.jsxs("p",{style:{marginTop:12,fontSize:13,color:"var(--color-muted)"},children:["Use ",e.jsx("code",{children:"/visual-plan on"})," or ",e.jsx("code",{children:"/visual-plan off"})," to toggle."]})]}),e.jsx("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:e.jsx(T,{variant:"ghost",onClick:t,children:"Close"})})]})}const Ri=["blank","feature-design","bug-investigation","decision-record","horizontal","vertical"];function Ti({data:s,onClose:t}){const a=(s==null?void 0:s.templates)??Ri,i=(s==null?void 0:s.defaultTemplate)??"blank",[n,o]=r.useState(""),[c,l]=r.useState(i),[x,p]=r.useState(!1),[h,d]=r.useState(null),m=async()=>{if(!n.trim()){d("Slug is required.");return}if(!/^[a-z0-9][a-z0-9-]{0,63}$/.test(n)){d("Invalid slug. Use lowercase letters, numbers, and hyphens. Must start with an alphanumeric character.");return}p(!0),d(null);try{await R.post("/artifacts",{slug:n,template:c}),t()}catch(u){d(u.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:u=>{o(u.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:c,onChange:u=>l(u.target.value),children:a.map(u=>e.jsx("option",{value:u,children:u},u))})]}),h&&e.jsx("p",{style:{marginBottom:12,color:"var(--color-danger)",fontSize:13},children:h}),e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx(T,{variant:"ghost",onClick:t,disabled:x,children:"Cancel"}),e.jsx(T,{variant:"primary",onClick:m,disabled:x||!n.trim(),children:x?"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=o=>{window.open(`/artifacts/${o}/`,"_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(o=>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:o}),e.jsx(T,{variant:"ghost",size:"sm",onClick:()=>n(o),children:"Open"})]},o))})]}),e.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:e.jsx(T,{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(o=>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:o.cmd})}),e.jsx("td",{style:{padding:"5px 0",color:"var(--color-muted)"},children:o.desc})]},o.cmd))})}):e.jsx("p",{style:{marginBottom:16,color:"var(--color-muted)"},children:"No commands available."}),i.length>0&&e.jsxs("div",{style:{marginBottom:12},children:[e.jsx("p",{style:{fontSize:12,color:"var(--color-muted)",marginBottom:4},children:"Available templates:"}),e.jsx("p",{style:{fontSize:13},children:i.join(", ")})]}),n.length>0&&e.jsxs("div",{style:{marginBottom:12},children:[e.jsx("p",{style:{fontSize:12,color:"var(--color-muted)",marginBottom:4},children:"Available statuses:"}),e.jsx("p",{style:{fontSize:13},children:n.join(", ")})]}),e.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:e.jsx(T,{variant:"ghost",onClick:t,children:"Close"})})]})}function Ii({data:s,onClose:t}){const[a,i]=r.useState(!1),[n,o]=r.useState(null),c=async()=>{i(!0),o(null);try{const l=await R.post("/chat/audit",{});o(l)}catch(l){o({ok:!1,findings:[],error:l.message})}finally{i(!1)}};return e.jsx("div",{children:n===null?e.jsxs(e.Fragment,{children:[e.jsx("p",{style:{marginBottom:16,lineHeight:1.6},children:"Run a security audit of your Bizar agent configuration. The audit checks for common misconfigurations, exposed secrets, and insecure defaults."}),e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx(T,{variant:"ghost",onClick:t,children:"Cancel"}),e.jsx(T,{variant:"primary",onClick:c,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,x)=>e.jsx("li",{style:{marginBottom:4,fontSize:13},children:l},x))})]}):e.jsxs("p",{style:{marginBottom:16,color:"var(--color-danger)"},children:["Audit failed: ",n.error??"unknown error"]}),e.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:e.jsx(T,{variant:"ghost",onClick:t,children:"Close"})})]})})}function Mi({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 Li({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(Ti,{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(Ii,{data:s.data,onClose:t});default:return e.jsx(Mi,{dialog:s,onClose:t})}}function Ei({setActiveTab:s,refreshKey:t=0}){var p;const[a,i]=r.useState(null),[n,o]=r.useState(!0),c=async()=>{o(!0);try{const[h,d,m]=await Promise.all([R.get("/memory/status").catch(()=>null),R.get("/memory/health").catch(()=>null),R.get("/memory/lightrag/stats").catch(()=>null)]);i({initialized:!!(h!=null&&h.initialized),mode:h==null?void 0:h.mode,projectId:h==null?void 0:h.projectId,vaultRoot:h==null?void 0:h.vaultRoot,branch:h==null?void 0:h.branch,gitClean:h==null?void 0:h.gitClean,noteCount:(h==null?void 0:h.noteCount)||0,healthScore:d==null?void 0:d.score,healthStatus:d==null?void 0:d.status,lightrag:m?{running:m.running,indexedApprox:m.indexedApprox}:void 0})}catch{i({initialized:!1})}finally{o(!1)}};r.useEffect(()=>{c()},[t]);const l=()=>s("memory"),x=(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(se,{children:[e.jsx(Fe,{size:14})," Memory",e.jsxs(T,{variant:"ghost",size:"sm",style:{marginLeft:"auto"},onClick:l,children:["Open Memory ",e.jsx(vs,{size:12})]}),e.jsx(T,{variant:"ghost",size:"sm",onClick:c,"aria-label":"Refresh",title:"Refresh",children:e.jsx(oe,{size:12})})]}),e.jsx(ae,{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(Te,{size:11})," Health"]}),e.jsx("div",{className:"memory-status-card-value",style:{color:x},children:a.healthScore!==void 0?`${a.healthScore}/100`:"—"}),e.jsx("div",{className:"memory-status-card-sub muted",children:a.healthStatus||"—"})]}),e.jsxs("div",{className:"memory-status-card-cell",children:[e.jsxs("div",{className:"memory-status-card-label",children:[e.jsx(Fe,{size:11})," LightRAG"]}),e.jsx("div",{className:"memory-status-card-value",children:(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(be,{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(ts,{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}`:Oe(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 he({icon:s,title:t,message:a,action:i,className:n}){return e.jsxs("div",{className:H("empty-state",n),children:[e.jsx("div",{className:"empty-icon",children:s??e.jsx(Ks,{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 V,W,K;const n=re(),o=Re(),c=r.useRef(null),[l,x]=r.useState(s.overview??null),[p,h]=r.useState(!s.overview),[d,m]=r.useState(s.projects||[]),[u,g]=r.useState(((V=s.activeProject)==null?void 0:V.id)||null),[k,z]=r.useState(s.mods||[]),[C,y]=r.useState(!1),[w,$]=r.useState(((W=s.overview)==null?void 0:W.recentActivity)??[]),[j,N]=r.useState(!1),[v,f]=r.useState(new Set);r.useEffect(()=>{let B=!1;return(async()=>{try{const Q=await R.get("/activity/hidden");B||f(new Set(Q.hidden||[]))}catch{}})(),()=>{B=!0}},[]);const D=(B,Q)=>{const te=`${B.kind||""}|${B.ts||""}|${B.slug||B.title||""}|${Q}`;let Z=0;for(let ie=0;ie<te.length;ie++)Z=(Z<<5)-Z+te.charCodeAt(ie)|0;return Math.abs(Z).toString(16).padStart(8,"0").slice(0,16)},M=async B=>{const Q=new Set(v);Q.add(B),f(Q);try{await R.post("/activity/hide",{keys:[B]})}catch(te){const Z=new Set(v);f(Z),n.error(`Hide failed: ${te.message}`)}},b=async()=>{if(!confirm("Hide every recent activity item from the overview? The full log stays in Settings → Activity Log."))return;const B=w.map((te,Z)=>D(te,Z)),Q=new Set(v);B.forEach(te=>Q.add(te)),f(Q);try{await R.post("/activity/hide",{keys:B}),n.success(`Hidden ${B.length} item(s). Restore them in Settings → Activity Log.`)}catch(te){n.error(`Clear failed: ${te.message}`)}},A=async()=>{f(new Set);try{await R.del("/activity/hide"),n.success("All hidden activity restored to the overview.")}catch(B){n.error(`Restore failed: ${B.message}`)}};r.useEffect(()=>{var B;s.overview&&(x(s.overview),$(s.overview.recentActivity??[]),h(!1)),m(s.projects||[]),g(((B=s.activeProject)==null?void 0:B.id)||null),z(s.mods||[])},[s.overview,s.projects,s.activeProject,s.mods]),r.useEffect(()=>{let B;try{const Q=R.getToken(),te=Q?`/api/activity/stream?token=${encodeURIComponent(Q)}`:"/api/activity/stream";B=new EventSource(te),B.addEventListener("snapshot",Z=>{try{const ie=JSON.parse(Z.data);$(Array.isArray(ie.events)?ie.events.slice(0,50):[])}catch{}}),B.addEventListener("activity",Z=>{try{const ie=JSON.parse(Z.data);$(je=>[ie,...je].slice(0,50))}catch{}})}catch{}return()=>{try{B==null||B.close()}catch{}}},[]);const O=async()=>{n.info("Refreshing…",1500),await i();try{const B=await R.get("/projects");m(B.projects||[]),g(B.active||null)}catch{}},S=()=>{o.open({title:"Add project",children:e.jsx(Pi,{settings:t,onAdd:async(B,Q)=>{try{const te=await R.post("/projects",{path:B,name:Q});m(Z=>[...Z.filter(ie=>ie.id!==te.id),te]),n.success("Project added."),o.close()}catch(te){n.error(`Add failed: ${te.message}`)}}}),footer:e.jsx("div",{className:"modal-footer-actions",children:e.jsx(T,{variant:"ghost",onClick:()=>o.close(),children:"Cancel"})})})},F=async()=>{var B;try{const Q=await R.post("/projects/auto-detect");m(Q.projects||[]),g(Q.active||null);const te=(B=Q.projects)==null?void 0:B.find(Z=>Z.id===Q.active);n.success(te?`Active: ${te.name}`:"Projects refreshed."),await i()}catch(Q){n.error(`Auto-detect failed: ${Q.message}`)}},_=async B=>{try{await R.post(`/projects/${encodeURIComponent(B)}/activate`),g(B),n.success("Project activated."),await i()}catch(Q){n.error(`Activate failed: ${Q.message}`)}},P=async B=>{if(confirm(`Remove project "${B}" from the registry?`))try{await R.del(`/projects/${encodeURIComponent(B)}`),m(Q=>Q.filter(te=>te.id!==B)),u===B&&g(null),n.success("Project removed.")}catch(Q){n.error(`Remove failed: ${Q.message}`)}};return p||!l?e.jsxs("div",{className:"view-loading",children:[e.jsx(le,{size:"lg"}),e.jsx("p",{children:"Loading overview…"})]}):e.jsxs("div",{className:"view view-overview",children:[e.jsxs("div",{className:"overview-hero-noframe",children:[e.jsx("h1",{children:"What do you want to do?"}),e.jsx("p",{className:"overview-hero-subtitle",children:"Describe what you want — Odin will split it into tasks, create a plan, delegate to background agents, and track progress in real time."}),e.jsxs("form",{className:"overview-hero-form-noframe",onSubmit:async B=>{var te,Z;B.preventDefault();const Q=(((te=c.current)==null?void 0:te.value)||"").trim();if(Q){y(!0);try{const ie=await R.post("/tasks/submit",{title:Q});n.success(`Odin split it into ${((Z=ie.subtasks)==null?void 0:Z.length)||1} task(s)`),c.current&&(c.current.value=""),await i()}catch(ie){n.error(`Failed: ${ie.message}`)}finally{y(!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:c,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:C,"aria-label":"Describe what you want Odin to do"}),e.jsxs("div",{style:{display:"flex",gap:"var(--space-2)",alignItems:"center",flexWrap:"wrap"},children:[e.jsxs(T,{type:"submit",variant:"primary",size:"lg",disabled:C,children:[C?e.jsx(le,{size:"sm"}):e.jsx(Ye,{size:16}),"Submit to Odin"]}),e.jsxs("span",{className:"muted",style:{fontSize:12},children:[e.jsx(We,{size:12,style:{display:"inline",verticalAlign:-2,color:"var(--accent)"}})," ","Odin + 12 specialist agents available"]})]})]}),e.jsx("div",{className:"overview-quick-actions-row",children:["Implement feature","Fix bug","Refactor","Investigate","Add tests","Document","Optimize","Deploy"].map(B=>e.jsx("button",{type:"button",className:"overview-quick-chip",onClick:()=>{c.current&&(c.current.value=B,c.current.focus())},children:B},B))})]}),e.jsxs("div",{className:"overview-feed",children:[e.jsxs("div",{className:"overview-feed-head",children:[e.jsx("h2",{children:"Recent activity"}),e.jsxs("div",{className:"overview-feed-head-actions",children:[v.size>0&&e.jsxs(T,{variant:"ghost",size:"sm",onClick:A,title:"Restore hidden items to this overview",children:[e.jsx(gs,{size:12})," Show ",v.size," hidden"]}),w.length>8&&e.jsx(T,{variant:"ghost",size:"sm",onClick:()=>N(B=>!B),children:j?"Show less":"Show all"}),w.length>0&&e.jsxs(T,{variant:"ghost",size:"sm",onClick:b,title:"Hide every item from the overview (full log kept)",children:[e.jsx(ut,{size:12})," Hide all"]})]})]}),v.size>0&&e.jsxs("div",{className:"activity-hidden-banner",role:"status",children:[e.jsxs("span",{children:[e.jsx(ut,{size:12,style:{verticalAlign:-2,marginRight:6}}),v.size," item",v.size===1?"":"s"," hidden from the overview."]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:A,children:[e.jsx(gs,{size:12})," Show them again"]})]}),w.length===0?e.jsx("div",{className:"muted",style:{padding:"24px 0",fontSize:13},children:"No activity yet. Use the chat above or invoke a Bizar command to start a feed."}):e.jsxs("div",{className:H("activity-feed-list-wrap",!j&&"activity-feed-list-wrap-collapsed"),"aria-live":"polite","aria-relevant":"additions",children:[e.jsx(Mt,{items:w.slice(0,30).filter((B,Q)=>!v.has(D(B,Q))),itemHeight:60,height:Math.min(w.filter((B,Q)=>!v.has(D(B,Q))).length*60,480),className:"activity-feed-list",renderItem:(B,Q)=>{const te=w.slice(0,30).findIndex(Z=>Z===B);return e.jsx(Hi,{item:B,activityKey:D(B,te),onNavigate:a,onHide:M})}}),!j&&w.length>8&&e.jsx("div",{className:"activity-feed-fade","aria-hidden":"true"})]})]}),e.jsxs(G,{className:"project-picker",children:[e.jsxs(se,{children:[e.jsx($e,{size:14})," Projects",e.jsxs(T,{variant:"ghost",size:"sm",style:{marginLeft:"auto"},onClick:S,children:[e.jsx(ve,{size:12})," Add"]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:F,title:"Use the server's working directory",children:[e.jsx(ve,{size:12})," Auto-detect"]}),((K=t==null?void 0:t.dashboard)==null?void 0:K.projectsDirectory)&&e.jsxs(T,{variant:"ghost",size:"sm",title:`Scan ${t.dashboard.projectsDirectory} for projects`,onClick:async()=>{try{const B=await R.post("/projects/scan");B.error?n.error(B.error):n.success(`Added ${B.added.length}, skipped ${B.skipped}.`),await i();const Q=await R.get("/projects");m(Q.projects||[]),g(Q.active||null)}catch(B){n.error(`Scan failed: ${B.message}`)}},children:[e.jsx(on,{size:12})," Scan"]}),e.jsx(T,{variant:"ghost",size:"sm",onClick:O,title:"Refresh",children:e.jsx(oe,{size:12})})]}),e.jsxs(ae,{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(he,{icon:e.jsx($e,{size:32}),title:"No projects yet",message:"Add a project to start tracking its tasks, plans, and schedules.",action:e.jsxs("div",{className:"empty-state-actions",children:[e.jsxs(T,{variant:"primary",onClick:F,children:[e.jsx(ve,{size:14})," Use current directory"]}),e.jsx(T,{variant:"secondary",onClick:S,children:"Add by path…"})]})}):e.jsx("div",{className:"project-grid",children:d.map(B=>e.jsx(Fi,{project:B,active:u===B.id,onOpen:()=>_(B.id),onRemove:()=>P(B.id)},B.id))})]}),e.jsx(Ei,{setActiveTab:a}),e.jsxs("div",{className:"overview-cols",children:[e.jsxs(G,{children:[e.jsx(se,{children:"Mods"}),e.jsxs(ae,{children:["Extensions installed under ",e.jsx("code",{children:"~/.config/bizar/mods/"})]}),k.length===0?e.jsx("div",{className:"muted",children:"No mods installed."}):e.jsx("ul",{className:"mod-mini-list",children:k.map(B=>e.jsxs("li",{className:"mod-mini",children:[e.jsx("span",{className:"mod-mini-name",children:B.name}),e.jsxs("span",{className:"mod-mini-meta",children:["v",B.version," · ",B.type]}),e.jsx("span",{className:`mod-mini-pill ${B.enabled?"mod-mini-pill-on":"mod-mini-pill-off"}`,children:B.enabled?"on":"off"})]},B.id))})]}),e.jsxs(G,{children:[e.jsx(se,{children:"Environment"}),e.jsx(ae,{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:Oe(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,o]=r.useState(""),[c,l]=r.useState(!1),[x,p]=r.useState(null),h=async()=>{var u;if(a){l(!0),p(null);try{await R.get("/fs?path="+encodeURIComponent(a)),t(a,n||null)}catch(g){const k=g;k.status===404?p("That folder no longer exists. Pick another."):p(((u=k.data)==null?void 0:u.message)??g.message??"Validation failed.")}finally{l(!1)}}};return e.jsxs("div",{children:[e.jsx("label",{className:"field-label",children:"Folder"}),e.jsx(Ra,{value:a,onChange:u=>{i(u),p(null)},projectsDirectory:(m=s==null?void 0:s.dashboard)==null?void 0:m.projectsDirectory,height:320}),x&&e.jsx("p",{className:"field-help",style:{color:"var(--error)",marginTop:4},children:x}),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:u=>o(u.target.value)}),e.jsx("p",{className:"field-help",style:{marginTop:4},children:"Display name for this project. Defaults to the folder name."})]}),e.jsx("div",{style:{marginTop:"var(--space-3)",display:"flex",justifyContent:"flex-end"},children:e.jsxs(T,{variant:"primary",onClick:h,disabled:!a||c,children:[c?e.jsx("span",{className:"btn-spinner"}):null,c?"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:o=>{o.stopPropagation(),i()},children:e.jsx(ke,{size:12})})]}),e.jsx("div",{className:"project-card-path mono ellipsis",title:s.path,children:s.path}),e.jsx("div",{className:"project-card-meta",children:s.lastAccessed&&e.jsxs("span",{className:"muted",children:["Last opened ",ze(s.lastAccessed)]})}),e.jsx("div",{className:"project-card-actions",children:e.jsx(T,{variant:t?"ghost":"primary",size:"sm",onClick:a,children:t?e.jsxs(e.Fragment,{children:[e.jsx(St,{size:12})," Active"]}):e.jsx(e.Fragment,{children:"Open"})})})]})}function Oi(s){return s&&s.charAt(0).toUpperCase()+s.slice(1)}function Ui(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"},o={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"},c=n[a]||Oi(a.replace(/-/g," ")),l=o[i]||i.replace(/-/g," ");return`${c} ${l}`.trim()}function Ps(s,t){for(const a of t){const i=s[a];if(typeof i=="string"&&i.trim())return i.trim()}return""}function Bi(s){const t=Ps(s,["message","text","prompt","title","name"]);if(t)return t;const a=[],i=Ps(s,["slug"]),n=Ps(s,["agent","author"]),o=Ps(s,["status"]);return i&&a.push(`Plan ${i}`),n&&a.push(n),o&&a.push(o),a.length?a.join(" · "):"No additional details."}function _i(s){return ze(s)}function qi(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 Wi(s){const t=s.toLowerCase();return t==="task"?Rs:t==="agent"?Be:t==="plan"?Gs:t.includes("bg")||t.includes("background")||t.includes("job")?Ct:t==="mod"?ss:t==="skill"?We:t.includes("error")||t.includes("failure")?xs:t.includes("warn")?ye:Te}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=qi(s),o=Wi(s.kind||""),c=Ui(s.kind||"activity"),l=Bi(s),x=Vi(s.kind||""),p=n==="error"?"var(--error)":n==="warning"?"var(--warning)":n==="success"?"var(--success)":"var(--accent)";return e.jsxs("div",{className:H("activity-feed-row",`activity-feed-row-${n}`),children:[e.jsxs("button",{type:"button",className:"activity-feed-row-main",onClick:()=>{x&&a(x)},title:x?`Open ${x}`:c,children:[e.jsx("div",{className:"activity-feed-icon",style:{color:p},children:e.jsx(o,{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:c}),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=De.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:o,onDeleteRequest:c,onConfirmDelete:l,onConfirmRename:x,onClose:p}){const h=r.useRef(null),d=Math.round(a.rect.bottom+2),m=Math.max(8,Math.round(window.innerWidth-a.rect.right));r.useEffect(()=>{const g=C=>{const y=C.target;!h.current||!y||h.current.contains(y)||p()},k=C=>{C.key==="Escape"&&p()},z=window.setTimeout(()=>{document.addEventListener("mousedown",g),document.addEventListener("keydown",k)},0);return()=>{window.clearTimeout(z),document.removeEventListener("mousedown",g),document.removeEventListener("keydown",k)}},[p]),r.useEffect(()=>{if(t!=="rename")return;const g=window.setTimeout(()=>{var z;const k=(z=h.current)==null?void 0:z.querySelector("input.session-row-menu-input");k==null||k.focus(),k==null||k.select()},0);return()=>window.clearTimeout(g)},[t]);const u=e.jsxs("div",{ref:h,className:"session-row-menu",role:"menu","aria-label":`Options for ${s.title}`,style:{position:"fixed",top:d,right:m},onClick:g=>g.stopPropagation(),children:[t==="main"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",className:"session-row-menu-item",role:"menuitem",onClick:g=>{g.stopPropagation(),o()},children:[e.jsx(cn,{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(),c()},children:[e.jsx(ke,{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(),x()):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(),x()},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 ia.createPortal(u,document.body)}function gt({node:s,depth:t=0,collapsible:a=!1,isLast:i=!0,open:n,onToggle:o}){var u;const[c,l]=r.useState(a),x=n!==void 0,p=x?n:c,h=g=>{x||l(g),o==null||o(g)},d=(((u=s.children)==null?void 0:u.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(),h(!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,k)=>e.jsx(gt,{node:g,depth:t+1,collapsible:!1,isLast:k===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(gt,{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(gt,{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 Wt(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 o of s){const c=new Date(Number(o.mtime)||Date.now());Wt(c,t)?n.Today.push(o):Wt(c,a)?n.Yesterday.push(o):er(t,c)<7?n["This week"].push(o):n.Earlier.push(o)}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:o,onCreateSession:c,onSelectSession:l,onSelectOpencodeSession:x,onRenameSession:p,onDeleteSession:h,groupBy:d}){var P;const m=r.useMemo(()=>[...s,...t],[s,t]),u=r.useMemo(()=>[...m].sort((V,W)=>Number(W.mtime??0)-Number(V.mtime??0)),[m]),g=r.useMemo(()=>d?d(u):sr(u),[d,u]),[k,z]=r.useState({}),C=V=>k[V]===!0,[y,w]=r.useState(null),[$,j]=r.useState("main"),[N,v]=r.useState(""),[f,D]=r.useState(null),M=r.useRef({}),b=(V,W="main")=>{const K=M.current[V];if(!K)return;const B=W==="main"?K:K.querySelector(".chat-rail-item-menu-trigger")??K;if(D({id:V,rect:B.getBoundingClientRect()}),w(V),j(W),W==="rename"){const Q=[...s,...t].find(te=>te.id===V);v((Q==null?void 0:Q.title)??(Q==null?void 0:Q.id)??"")}},A=()=>{w(null),j("main"),v(""),D(null)},O=V=>{if(V.source==="opencode"){x(V);return}l(V.id)},S=()=>{if(!f)return;const V=f.id,W=N.trim();if(!W){A();return}p==null||p(V,W),A()},F=()=>{f&&(h==null||h(f.id),A())},_=d?Object.entries(g):Zi.filter(V=>{var W;return(W=g[V])==null?void 0:W.length}).map(V=>[V,g[V]]);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:c,disabled:o||!n,title:n?"Create new session":"Pick a project first","aria-label":"Create new session",children:[e.jsx(ve,{size:14,"aria-hidden":!0}),e.jsx("span",{children:o?"Creating…":"New session"})]})}),u.length===0?e.jsx("div",{className:"chat-sessions-empty",children:e.jsx(Ki,{icon:e.jsx(ve,{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:_.map(([V,W])=>e.jsxs("div",{className:"chat-rail-group",children:[e.jsx("div",{className:"chat-rail-group-label",children:V}),W.map(K=>{var je,Ce;const B=K.source==="opencode",Q=B?i===K.id:a===K.id,te=K.tree,Z=!!((je=te==null?void 0:te.root)!=null&&je.children&&te.root.children.length>0),ie=C(K.id);return e.jsxs(r.Fragment,{children:[e.jsxs("div",{ref:L=>{M.current[K.id]=L},role:"button",tabIndex:0,className:`chat-rail-item state-${K.state??"idle"}${Q?" active":""}`,onClick:()=>O(K),onKeyDown:L=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),O(K))},"aria-current":Q?"true":void 0,children:[e.jsx(ar,{state:K.state??"idle",agent:K.agent}),e.jsxs("div",{className:"chat-rail-item-title",children:[K.pinned&&e.jsx("span",{className:"chat-rail-pin","aria-hidden":!0,children:"★"}),B&&e.jsx(vs,{size:11,style:{color:"var(--text-muted)",flexShrink:0},"aria-hidden":!0}),e.jsx("span",{className:"chat-ellipsis",children:K.title||K.id})]}),e.jsxs("div",{className:"chat-rail-item-meta",children:[e.jsx("span",{className:"chat-rail-item-meta-time",children:K.time??tr(K.mtime)}),(K.unread??0)>0&&e.jsx("span",{className:"chat-rail-badge",children:K.unread})]}),e.jsx("button",{type:"button",className:`chat-rail-item-menu-trigger${y===K.id?" open":""}`,"aria-label":`Session options for ${K.title||K.id}`,"aria-haspopup":"menu","aria-expanded":y===K.id,onClick:L=>{L.stopPropagation(),y===K.id?A():b(K.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"})]})}),Q&&Z&&e.jsx("button",{type:"button",className:`chat-rail-tree-chevron${ie?" open":""}`,"aria-label":ie?"Collapse sub-agents":"Expand sub-agents","aria-expanded":ie,onClick:L=>{L.stopPropagation(),z(U=>({...U,[K.id]:!U[K.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"})})})]}),Q&&Z&&ie&&((Ce=te==null?void 0:te.root)==null?void 0:Ce.children)&&e.jsx(Ji,{children:te.root.children,variant:"rail",open:!0})]},B?`oc-${K.id}`:K.id)})]},V))}),y&&f&&e.jsx(Yi,{session:{id:f.id,title:((P=[...s,...t].find(V=>V.id===f.id))==null?void 0:P.title)??f.id},mode:$,anchor:f,renameDraft:N,setRenameDraft:v,onEdit:()=>b(y,"rename"),onDeleteRequest:()=>b(y,"confirm-delete"),onConfirmDelete:F,onConfirmRename:S,onClose:A})]})}function ir(s){const{text:t,sending:a,onSend:i,activeSource:n}=s,[o,c]=r.useState(!1),l=()=>{!t.trim()||a||(c(!0),i(),window.setTimeout(()=>c(!1),320))};return e.jsxs("div",{className:`chat-composer-wrap chat-composer-source-${n??"none"}`,children:[e.jsx("div",{className:`chat-composer-pill${o?" takeoff":""}`,children:e.jsx(ai,{...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 at(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:o,mcps:c,allCommands:l,activeSource:x="bizar",onRename:p,onDelete:h,onExport:d,busy:m,error:u,onRetry:g}){const[k,z]=r.useState(null);r.useEffect(()=>{let b=!1;return(async()=>{try{const A=await fetch("/api/usage?range=24h",{headers:{Accept:"application/json"}});if(!A.ok)return;const O=await A.json();b||z(O)}catch{}})(),()=>{b=!0}},[s]);const C=(t==null?void 0:t.length)??0,y=(a==null?void 0:a.size)??0,w=t.reduce((b,A)=>b+(A.content||A.message||"").length,0),$=Math.round(w/4),j=lr(n),N=$/1e6*j,v=(k==null?void 0:k.totalTokens)??$,f=(k==null?void 0:k.costUsd)??N,D=128e3,M=rr(n);return e.jsxs("aside",{className:"chat-info",children:[u&&e.jsxs("div",{className:"chat-info-section chat-info-error",role:"alert","aria-live":"polite",children:[e.jsxs("h4",{children:[e.jsx(ye,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Couldn't load session"]}),e.jsx("p",{className:"chat-info-value chat-ellipsis",title:u.message,children:u.message}),e.jsxs("div",{className:"chat-info-mono",children:["code · ",u.code]}),u.suggestion?e.jsx("p",{className:"chat-info-suggestion",children:u.suggestion}):null,u.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(Js,{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(Qs,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Session"]}),e.jsx("span",{className:`chat-source-badge chat-source-${x??"none"}`,style:{marginLeft:"auto"},children:x==="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:[at(C)," message",C===1?"":"s",y>0&&` · ${y} pinned`]})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("h4",{children:[e.jsx(Be,{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||"—"}),M&&e.jsxs("div",{className:"chat-info-mono",children:["provider · ",M]})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsx("h4",{children:"Tokens"}),e.jsxs("div",{className:"chat-mono",children:[at(v)," / ",at(D)]}),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,D)*100)}%`}})})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("h4",{children:[e.jsx(dn,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Cost"]}),e.jsxs("div",{className:"chat-mono",children:["$",f.toFixed(4)]}),!k&&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(Be,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Attached agents"]}),o!=null&&o.length?e.jsx("div",{className:"chat-info-agents",children:o.map(b=>e.jsx("span",{className:"chat-info-agent",children:b.name},b.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"]}),c!=null&&c.length?e.jsx("div",{className:"chat-info-agents",children:c.map(b=>e.jsx("span",{className:"chat-info-agent",children:b.id},b.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(Ke,{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||h||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(Is,{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(as,{size:12,"aria-hidden":!0})," Export"]}),h&&e.jsxs("button",{type:"button",className:"btn btn-ghost btn-sm btn-danger",onClick:h,disabled:m==null?void 0:m.delete,title:"Delete session",children:[e.jsx(ke,{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(ha,{size:14,"aria-hidden":!0}),e.jsx("span",{children:"Jump to latest"}),t>0&&e.jsxs("span",{className:"jump-badge",children:[t," new"]})]})})}function dr({snapshot:s,settings:t,setActiveTab:a,initialTaskId:i,onClearTaskId:n}){const o=re(),c=Re(),l=ni(s,t,i??"");r.useEffect(()=>{l.setToast({error:P=>o.error(P),success:P=>o.success(P),info:P=>o.info(P),warning:P=>o.warning(P)})},[l,o]);const[x,p]=r.useState(""),[h,d]=r.useState(t.defaultAgent||"odin"),[m,u]=r.useState(t.defaultModel||""),[g,k]=r.useState([]),z=r.useRef(null),{allCommands:C,suggestions:y,setQuery:w}=ii(s);r.useEffect(()=>{w(x)},[x,w]);const $=()=>{var P;return(P=z.current)==null?void 0:P.click()},j=P=>{const V=P.target.files;if(!V)return;const W=[];for(let K=0;K<V.length;K++)W.push(V[K].name);k(K=>{const B=W.filter(Q=>!K.includes(Q));return[...K,...B]}),z.current&&(z.current.value="")},N=async()=>{const P=x.trim();if(!P)return;p(""),w(""),(await l.onSend(P,h,m,g)).ok&&l.jumpToLatest()},v=async()=>{l.busy.create||await l.onCreateSession()},f=P=>{c.open({title:"Delete message?",children:e.jsx("p",{style:{margin:0},children:"This action cannot be undone."}),footer:e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx(T,{variant:"secondary",size:"sm",onClick:()=>c.close(),children:"Cancel"}),e.jsx(T,{variant:"danger",size:"sm",onClick:()=>{c.close(),l.deleteMessage(P)},children:"Delete"})]})})},D=(P,V)=>{let W="";c.open({title:"Rename session",children:e.jsx("input",{id:"rename-session-input",autoFocus:!0,defaultValue:V,"aria-label":"Session title",onChange:K=>{W=K.target.value},onKeyDown:K=>{K.key==="Enter"&&(K.preventDefault(),c.close(),l.renameSession(P,W).then(B=>{B&&o.success("Renamed.")}))},style:{width:"100%",padding:"8px 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-sm)",color:"var(--text)",font:"13px/1.4 var(--font-sans)",marginTop:6}}),footer:e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx(T,{variant:"secondary",size:"sm",onClick:()=>c.close(),children:"Cancel"}),e.jsx(T,{variant:"primary",size:"sm",onClick:()=>{c.close(),l.renameSession(P,W)},children:"Save"})]})})},M=(P,V)=>{c.open({title:"Delete session?",children:e.jsxs("p",{style:{margin:0},children:["Delete ",e.jsx("strong",{children:V}),"? Messages on the opencode serve will be removed. This cannot be undone."]}),footer:e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx(T,{variant:"secondary",size:"sm",onClick:()=>c.close(),children:"Cancel"}),e.jsx(T,{variant:"danger",size:"sm",onClick:async()=>{c.close(),await l.deleteSession(P)},children:"Delete"})]})})},b=()=>{const P=l.activeSource==="opencode"?l.activeOpencodeSessionId:l.sessionId;if(!P)return;const W=(l.activeSource==="opencode"?l.opencodeMessages:l.bizarMessages).map(te=>{const Z=te.ts??"",ie=(te.role||"unknown").toUpperCase(),je=te.content||te.message||"";return`[${Z}] ${ie}: ${je}`}).join(`
|
|
2
|
+
|
|
3
|
+
`),K=new Blob([W],{type:"text/plain;charset=utf-8"}),B=URL.createObjectURL(K),Q=document.createElement("a");Q.href=B,Q.download=`${P}.txt`,document.body.appendChild(Q),Q.click(),document.body.removeChild(Q),URL.revokeObjectURL(B)},A=r.useMemo(()=>l.sessions.map(P=>l.getSessionDisplay(P)),[l.sessions,l.getSessionDisplay]),O=r.useMemo(()=>l.opencodeSessions.map(P=>l.getSessionDisplay(P)),[l.opencodeSessions,l.getSessionDisplay]),S=r.useMemo(()=>{const P=l.activeSource==="opencode"?l.activeOpencodeSessionId??"":l.sessionId;return P?A.find(V=>V.id===P)??O.find(V=>V.id===P)??null:null},[l.activeSource,l.activeOpencodeSessionId,l.sessionId,A,O]),F=(()=>{var W;const P=`${h||"Odin"} · ${((W=s.activeProject)==null?void 0:W.name)??"no project"}`,V=(S==null?void 0:S.state)??"idle";return V==="streaming"?`Replying · ${P}`:V==="awaiting"?`Your turn · ${P}`:`${P} · idle`})(),_=l.activeSource==="opencode"?"opencode":"bizar chat";return e.jsxs("div",{className:"chat-shell",children:[e.jsx(ri,{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:A,opencodeSessions:O,activeSessionId:l.sessionId,activeOpencodeSessionId:l.activeOpencodeSessionId,activeProject:s.activeProject,creating:l.busy.create,onCreateSession:v,onSelectSession:l.selectBizarSession,onSelectOpencodeSession:P=>l.loadOpencodeSession(P.id),onRenameSession:D,onDeleteSession:P=>{const V=l.sessions.find(W=>W.id===P)??l.opencodeSessions.find(W=>W.id===P);M(P,(V==null?void 0:V.title)??"")}}),e.jsxs("section",{className:"chat-thread-section",children:[e.jsxs("div",{className:"chat-thread-head",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"chat-thread-title-row",children:[e.jsx("div",{className:"chat-thread-title",children:(S==null?void 0:S.title)??l.sessionId??"New chat"}),e.jsx("span",{className:`chat-source-badge chat-source-${l.activeSource??"none"}`,title:l.activeSource==="opencode"?"Messages go to the opencode serve child":"Messages go to the local chat store",children:_})]}),e.jsxs("div",{className:`chat-thread-sub chat-muted state-${(S==null?void 0:S.state)??"idle"}`,children:[e.jsx("span",{className:"chat-thread-dot"}),F]}),l.opencodeError&&e.jsxs("div",{className:"chat-thread-error",role:"alert",children:[e.jsx("p",{className:"chat-error-message",children:l.opencodeError}),l.opencodeSuggestion&&e.jsx("p",{className:"chat-error-suggestion",children:l.opencodeSuggestion}),l.activeOpencodeSessionId&&e.jsx("button",{className:"btn btn-sm",type:"button",onClick:()=>l.loadOpencodeSession(l.activeOpencodeSessionId),children:"Retry"})]})]}),e.jsxs("div",{className:"chat-thread-actions",children:[S&&e.jsxs("button",{className:"btn btn-ghost",title:"Rename session",type:"button",disabled:l.busy.rename,onClick:()=>D(S.id,S.title??""),children:[e.jsx(Is,{size:12,"aria-hidden":!0})," ",e.jsx("span",{className:"mono",children:"rename"})]}),S&&e.jsxs("button",{className:"btn btn-ghost btn-danger",title:"Delete session",type:"button",disabled:l.busy.delete,onClick:()=>M(S.id,S.title??S.id),children:[e.jsx(ke,{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:b,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(li,{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:P=>p(P),onCopy:P=>l.copyMessage(P),onDelete:f,onTogglePin:l.togglePin,onRegenerate:l.onRegenerate})}),!l.stickToBottom&&e.jsx(cr,{streaming:(S==null?void 0:S.state)==="streaming",newMessageCount:l.newMessageCount,onClick:l.jumpToLatest}),e.jsx(ir,{agent:h,setAgent:d,model:m,setModel:u,text:x,setText:p,sending:l.sending,activeSource:l.activeSource,onSend:N,attachments:g,setAttachments:k,suggestions:y,onPickSuggestion:P=>p(`${P.split(" ")[0]} `),agents:s.agents||[],onAttach:$}),e.jsx("input",{ref:z,type:"file",multiple:!0,style:{display:"none"},onChange:j,"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:h,model:m,agents:s.agents||[],mcps:s.mcps||[],allCommands:C,activeSource:l.activeSource,onRename:()=>{S&&D(S.id,S.title??"")},onDelete:()=>{S&&M(S.id,S.title??S.id)},onExport:b,busy:l.busy})]})]})}function mr(s){return s==="ok"?"success":s==="warn"?"warning":s==="fail"?"error":s}function Ve({kind:s="neutral",children:t,className:a,dot:i=!1}){const n=mr(s);return e.jsxs("span",{className:H("badge",`badge-${n}`,a),title:`status: ${s}`,children:[i&&e.jsx("span",{className:"badge-dot"}),t]})}const Vt=["bash","read","edit","write","webfetch","websearch","task","glob","grep"],Ht=["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"],_s=[{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=_s.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(Ve,{kind:"error",dot:!0,children:"stuck"});const t=s.status||"idle";return t==="working"?e.jsx(Ve,{kind:"info",dot:!0,children:"working"}):t==="error"?e.jsx(Ve,{kind:"error",dot:!0,children:"error"}):e.jsx(Ve,{kind:"neutral",dot:!0,children:"idle"})}function pr({snapshot:s,refreshSnapshot:t}){const a=re(),i=Re(),[n,o]=r.useState(s.agents||[]),[c,l]=r.useState(!s.agents),[x,p]=r.useState(""),[h,d]=r.useState("");r.useEffect(()=>{o(s.agents||[]),l(!s.agents)},[s.agents]);const m=async()=>{try{const j=await R.get("/agents");o(j.agents||[])}catch(j){a.error(`Agents load failed: ${j.message}`)}finally{l(!1)}},u=r.useMemo(()=>{let j=[...n];if(x&&(j=j.filter(N=>x==="__none__"?!N.category:(N.category||"")===x)),h){const N=h.toLowerCase();j=j.filter(v=>v.name.toLowerCase().includes(N)||(v.description||"").toLowerCase().includes(N)||(v.tags||[]).some(f=>f.toLowerCase().includes(N)))}return j.sort((N,v)=>N.name.localeCompare(v.name))},[n,x,h]),g=r.useMemo(()=>{const j=new Set;for(const N of n)for(const v of N.tags||[])j.add(v);return Array.from(j).sort()},[n]),k=()=>{let j=null,N=null,v=null,f=null,D=null,M=null,b=null,A=null,O=null;i.open({title:"New agent",width:640,children:e.jsxs("div",{className:"agent-form",children:[e.jsx("label",{className:"field-label",htmlFor:"agent-new-name",children:"Name (a-z, 0-9, dashes)"}),e.jsx("input",{id:"agent-new-name",ref:S=>j=S,className:"input",type:"text",placeholder:"my-agent",autoFocus:!0}),e.jsx("label",{className:"field-label",htmlFor:"agent-new-desc",children:"Description"}),e.jsx("input",{id:"agent-new-desc",ref:S=>{N=S},className:"input",type:"text",placeholder:"What does this agent do?"}),e.jsxs("div",{className:"task-form-row",children:[e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"agent-new-model",children:"Model"}),e.jsxs("select",{id:"agent-new-model",ref:S=>v=S,className:"select",defaultValue:"",children:[e.jsx("option",{value:"",children:"(provider default)"}),Ht.map(S=>e.jsx("option",{value:S,children:S},S))]})]}),e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"agent-new-mode",children:"Mode"}),e.jsxs("select",{id:"agent-new-mode",ref:S=>f=S,className:"select",defaultValue:"subagent",children:[e.jsx("option",{value:"primary",children:"primary"}),e.jsx("option",{value:"subagent",children:"subagent"}),e.jsx("option",{value:"all",children:"all"})]})]}),e.jsxs("div",{className:"task-form-field",style:{flex:"0 0 80px"},children:[e.jsx("label",{className:"field-label",htmlFor:"agent-new-color",children:"Color"}),e.jsx("input",{id:"agent-new-color",ref:S=>D=S,className:"input",type:"color",defaultValue:"#8b5cf6"})]})]}),e.jsxs("div",{className:"task-form-row",children:[e.jsxs("div",{className:"task-form-field",style:{flex:1},children:[e.jsx("label",{className:"field-label",htmlFor:"agent-new-category",children:"Category"}),e.jsxs("select",{id:"agent-new-category",ref:S=>O=S,className:"select",defaultValue:"",children:[e.jsx("option",{value:"",children:"(none)"}),_s.map(S=>e.jsx("option",{value:S.id,children:S.label},S.id))]})]}),e.jsxs("div",{className:"task-form-field",style:{flex:2},children:[e.jsx("label",{className:"field-label",htmlFor:"agent-new-tags",children:"Tags (comma-separated)"}),e.jsx("input",{id:"agent-new-tags",ref:S=>A=S,className:"input",type:"text",placeholder:"reasoning, code, planning"})]})]}),e.jsxs("fieldset",{children:[e.jsx("legend",{className:"field-label",style:{padding:0},children:"Tools"}),e.jsx("div",{ref:S=>b=S,className:"agent-tools",children:Vt.map(S=>e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{type:"checkbox",value:S,"aria-label":S}),e.jsx("span",{children:S})]},S))})]}),e.jsx("label",{className:"field-label",htmlFor:"agent-new-prompt",children:"System prompt"}),e.jsx("textarea",{id:"agent-new-prompt",ref:S=>M=S,className:"textarea",rows:6,placeholder:"You are a..."})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx(T,{variant:"ghost",onClick:()=>i.close(),children:"Cancel"}),e.jsxs(T,{variant:"primary",onClick:async()=>{const S=((j==null?void 0:j.value)||"").trim();if(!/^[a-z0-9][a-z0-9-]{0,63}$/i.test(S)){a.warning("Invalid name (a-z, 0-9, dashes).");return}const F=[];b&&b.querySelectorAll('input[type="checkbox"]:checked').forEach(P=>{F.push(P.value)});const _=((A==null?void 0:A.value)||"").split(",").map(P=>P.trim()).filter(Boolean);try{const P=await R.post("/agents",{name:S,description:((N==null?void 0:N.value)||"").trim(),model:(v==null?void 0:v.value)||"",mode:(f==null?void 0:f.value)||"subagent",color:(D==null?void 0:D.value)||"",tools:F,tags:_,category:(O==null?void 0:O.value)||"",prompt:(M==null?void 0:M.value)||""});o(V=>[...V,P]),a.success("Agent created."),i.close(),await t()}catch(P){a.error(`Create failed: ${P.message}`)}},children:[e.jsx(fs,{size:12})," Create"]})]})})},z=async j=>{let N=null,v=null,f=null,D=null,M=null,b=null,A=null,O=null;try{const S=await R.get(`/agents/${encodeURIComponent(j.name)}`);i.open({title:`Edit ${j.name}`,width:640,children:e.jsxs("div",{className:"agent-form",children:[e.jsxs("div",{className:"muted",children:["File: ",e.jsx("code",{children:S.path})]}),e.jsx("label",{className:"field-label",htmlFor:"agent-edit-desc",children:"Description"}),e.jsx("input",{id:"agent-edit-desc",ref:F=>{N=F},className:"input",type:"text",defaultValue:S.description}),e.jsxs("div",{className:"task-form-row",children:[e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"agent-edit-model",children:"Model"}),e.jsxs("select",{id:"agent-edit-model",ref:F=>v=F,className:"select",defaultValue:S.model,children:[e.jsx("option",{value:"",children:"(provider default)"}),Ht.map(F=>e.jsx("option",{value:F,children:F},F))]})]}),e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"agent-edit-mode",children:"Mode"}),e.jsxs("select",{id:"agent-edit-mode",ref:F=>f=F,className:"select",defaultValue:S.mode||"subagent",children:[e.jsx("option",{value:"primary",children:"primary"}),e.jsx("option",{value:"subagent",children:"subagent"}),e.jsx("option",{value:"all",children:"all"})]})]}),e.jsxs("div",{className:"task-form-field",style:{flex:"0 0 80px"},children:[e.jsx("label",{className:"field-label",htmlFor:"agent-edit-color",children:"Color"}),e.jsx("input",{id:"agent-edit-color",ref:F=>D=F,className:"input",type:"color",defaultValue:S.color||"#8b5cf6"})]})]}),e.jsxs("div",{className:"task-form-row",children:[e.jsxs("div",{className:"task-form-field",style:{flex:1},children:[e.jsx("label",{className:"field-label",htmlFor:"agent-edit-category",children:"Category"}),e.jsxs("select",{id:"agent-edit-category",ref:F=>O=F,className:"select",defaultValue:S.category||"",children:[e.jsx("option",{value:"",children:"(none)"}),_s.map(F=>e.jsx("option",{value:F.id,children:F.label},F.id))]})]}),e.jsxs("div",{className:"task-form-field",style:{flex:2},children:[e.jsx("label",{className:"field-label",htmlFor:"agent-edit-tags",children:"Tags (comma-separated)"}),e.jsx("input",{id:"agent-edit-tags",ref:F=>A=F,className:"input",type:"text",defaultValue:(S.tags||[]).join(", ")})]})]}),e.jsxs("fieldset",{children:[e.jsx("legend",{className:"field-label",style:{padding:0},children:"Tools"}),e.jsx("div",{ref:F=>b=F,className:"agent-tools",children:Vt.map(F=>{var _;return e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{type:"checkbox",value:F,"aria-label":F,defaultChecked:(_=S.tools)==null?void 0:_.includes(F)}),e.jsx("span",{children:F})]},F)})})]}),e.jsx("label",{className:"field-label",htmlFor:"agent-edit-prompt",children:"System prompt"}),e.jsx("textarea",{id:"agent-edit-prompt",ref:F=>M=F,className:"textarea",rows:8,defaultValue:S.prompt||""})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx(T,{variant:"ghost",onClick:()=>i.close(),children:"Cancel"}),e.jsxs(T,{variant:"primary",onClick:async()=>{const F=[];b&&b.querySelectorAll('input[type="checkbox"]:checked').forEach(P=>{F.push(P.value)});const _=((A==null?void 0:A.value)||"").split(",").map(P=>P.trim()).filter(Boolean);try{const P=await R.put(`/agents/${encodeURIComponent(j.name)}`,{description:((N==null?void 0:N.value)||"").trim(),model:(v==null?void 0:v.value)||"",mode:(f==null?void 0:f.value)||"subagent",color:(D==null?void 0:D.value)||"",tools:F,tags:_,category:(O==null?void 0:O.value)||"",prompt:(M==null?void 0:M.value)||""});o(V=>V.map(W=>W.name===j.name?P:W)),a.success("Agent saved."),i.close(),await t()}catch(P){a.error(`Save failed: ${P.message}`)}},children:[e.jsx(fs,{size:12})," Save"]})]})})}catch(S){a.error(`Load failed: ${S.message}`)}},C=async j=>{if(confirm(`Delete agent "${j.name}"? This removes ${j.path}.`))try{await R.del(`/agents/${encodeURIComponent(j.name)}`),o(N=>N.filter(v=>v.name!==j.name)),a.success("Agent deleted.")}catch(N){a.error(`Delete failed: ${N.message}`)}},y=async j=>{let N=null;i.open({title:`Invoke ${j.name}`,children:e.jsxs("div",{className:"invoke-form",children:[e.jsxs("p",{className:"muted invoke-form-meta mono",children:[j.model||"—"," · ",j.path]}),e.jsx("p",{className:"invoke-form-desc",children:j.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(T,{variant:"ghost",onClick:()=>i.close(),children:"Cancel"}),e.jsxs(T,{variant:"primary",onClick:async()=>{const v=((N==null?void 0:N.value)||"").trim();if(!v){a.warning("Prompt is required.");return}try{await R.post(`/agents/${encodeURIComponent(j.name)}/invoke`,{prompt:v}),a.success(`Invoked ${j.name}.`),i.close()}catch(f){a.error(`Invoke failed: ${f.message}`)}},children:[e.jsx(ys,{size:14})," Invoke"]})]})})},w=async j=>{try{const N=await R.post(`/agents/${encodeURIComponent(j.name)}/restart`);o(v=>v.map(f=>f.name===j.name?N:f)),a.success(`${j.name} restarted.`)}catch(N){a.error(`Restart failed: ${N.message}`)}},$=async(j,N)=>{try{const v=await R.post(`/agents/${encodeURIComponent(j.name)}/status`,{status:N});o(f=>f.map(D=>D.name===j.name?v:D))}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(Be,{size:18})," Agents (",u.length,")"]}),e.jsxs("p",{className:"view-subtitle",children:["The Norse pantheon — click ",e.jsx("kbd",{children:"Edit"})," to modify or ",e.jsx("kbd",{children:"Invoke"})," to dispatch."]})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs("div",{className:"search-input",children:[e.jsx("label",{htmlFor:"agents-search",className:"sr-only",children:"Search agents"}),e.jsx("input",{id:"agents-search",className:"input",type:"text",placeholder:"Search…",value:h,onChange:j=>d(j.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:x,onChange:j=>p(j.target.value),children:[e.jsx("option",{value:"",children:"All categories"}),_s.map(j=>e.jsx("option",{value:j.id,children:j.label},j.id)),e.jsx("option",{value:"__none__",children:"(no category)"})]}),e.jsxs(T,{variant:"secondary",size:"sm",onClick:m,children:[e.jsx(oe,{size:14})," Refresh"]}),e.jsxs(T,{variant:"primary",size:"sm",onClick:k,children:[e.jsx(ve,{size:14})," New agent"]})]})]}),g.length>0&&e.jsxs("div",{className:"agent-tags-row",children:[e.jsx(xa,{size:12}),g.map(j=>e.jsx("span",{className:"tag",children:j},j))]}),c?e.jsx("div",{className:"view-loading",children:e.jsx(le,{size:"lg"})}):u.length===0?e.jsx(he,{icon:e.jsx(Be,{size:32}),title:"No agents found",message:"Run bizar in the terminal to install Bizar."}):e.jsx("div",{className:"agent-grid",children:u.map(j=>e.jsx(gr,{agent:j,onInvoke:()=>y(j),onEdit:()=>z(j),onDelete:()=>C(j),onRestart:()=>w(j),onSetStatus:N=>$(j,N)},j.name))})]})}function gr({agent:s,onInvoke:t,onEdit:a,onDelete:i,onRestart:n,onSetStatus:o}){const[c,l]=r.useState(!1),x=ur(s.category),p=(s.status==="working"||!!s.currentTaskId)&&!s.isStuck;return e.jsxs(G,{variant:"elevated",interactive:!0,className:H("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, ${x} 18%, transparent)`,color:x},children:s.category}),e.jsx(xr,{agent:s})]})]}),e.jsx("p",{className:"agent-card-desc",children:na(s.description,200)}),e.jsxs("div",{className:"agent-card-meta",children:[e.jsx("span",{className:"mono",title:s.model||"",children:s.model||"—"}),e.jsx("span",{className:"tabular-nums muted",children:ze(s.mtime)})]}),s.tags&&s.tags.length>0&&e.jsx("div",{className:"agent-card-tags",children:s.tags.map(h=>e.jsx("span",{className:"agent-card-tag",children:h},h))}),(p||s.lastTask)&&e.jsxs("div",{className:"agent-card-activity",children:[s.currentTaskId&&e.jsxs("div",{className:"agent-card-row",children:[e.jsx(Te,{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(Ee,{size:12}),e.jsx("span",{className:"muted",children:"Last"}),e.jsx("code",{className:"mono",children:s.lastTask.id}),e.jsx("span",{className:"muted tabular-nums",children:ze(s.lastTask.finishedAt)})]}),s.tasksTotal!=null&&s.tasksTotal>0&&e.jsxs("div",{className:"agent-card-row",children:[e.jsx(mn,{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(ye,{size:12}),e.jsxs("span",{className:"muted",children:["Last error: ",s.lastError.message]})]}),e.jsxs("div",{className:"agent-card-actions",children:[e.jsxs(T,{variant:"primary",size:"sm",onClick:t,children:[e.jsx(ys,{size:12})," Invoke"]}),e.jsxs(T,{variant:"secondary",size:"sm",onClick:a,children:[e.jsx(Is,{size:12})," Edit"]}),(s.isStuck||s.status==="working"||s.status==="error")&&e.jsxs(T,{variant:"ghost",size:"sm",onClick:n,title:"Reset agent status",children:[e.jsx(Js,{size:12})," Restart"]}),e.jsx(T,{variant:"ghost",size:"sm",onClick:i,children:e.jsx(ke,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":c?"Collapse":"Expand",onClick:()=>l(h=>!h),style:{marginLeft:"auto"},children:c?e.jsx(Ue,{size:12}):e.jsx(Xe,{size:12})})]}),c&&e.jsxs("div",{className:"agent-card-expanded",children:[e.jsxs("div",{className:"agent-card-status-actions",children:[e.jsx("span",{className:"muted text-sm",children:"Set status:"}),e.jsx(T,{variant:s.status==="idle"?"primary":"ghost",size:"sm",onClick:()=>o("idle"),children:"Idle"}),e.jsx(T,{variant:s.status==="working"?"primary":"ghost",size:"sm",onClick:()=>o("working"),children:"Working"}),e.jsx(T,{variant:s.status==="error"?"primary":"ghost",size:"sm",onClick:()=>o("error"),children:"Error"})]}),e.jsxs("div",{className:"agent-card-meta",children:[e.jsx($e,{size:11}),e.jsx("code",{className:"mono agent-card-path",children:s.path})]})]})]})}function jr({id:s,children:t}){return e.jsx("div",{id:s,"data-block-id":s,className:H("glyph-richtext"),style:$a,children:e.jsx(Sa,{remarkPlugins:[Ca],children:t})})}const fr={info:{bg:"var(--info-soft, rgba(96, 165, 250, 0.12))",border:"var(--info)",fg:"var(--info)",icon:wt,label:"Note"},warn:{bg:"var(--warning-soft, rgba(251, 191, 36, 0.15))",border:"var(--warning)",fg:"var(--warning)",icon:ye,label:"Warning"},success:{bg:"var(--success-soft, rgba(52, 211, 153, 0.15))",border:"var(--success)",fg:"var(--success)",icon:Ee,label:"Success"},danger:{bg:"var(--error-soft, rgba(248, 113, 113, 0.12))",border:"var(--error)",fg:"var(--error)",icon:Ms,label:"Danger"}};function vr({id:s,tone:t="info",children:a}){const i=fr[t],n=i.icon;return e.jsxs("div",{id:s,"data-block-id":s,className:H("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:{...$a,fontSize:14},children:e.jsx(Sa,{remarkPlugins:[Ca],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(ps,{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((o,c)=>e.jsx("td",{style:{padding:"8px 12px",color:"var(--text)",verticalAlign:"top",wordBreak:"break-word"},children:o},c))},n))})]})})}function Nr({id:s,tabs:t}){var o;const[a,i]=r.useState(((o=t[0])==null?void 0:o.id)??""),n=r.useMemo(()=>t.find(c=>c.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(c=>{const l=c.id===(n==null?void 0:n.id);return e.jsxs("button",{type:"button",role:"tab","aria-selected":l,onClick:()=>i(c.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:c.label}),c.language&&e.jsx("span",{style:{marginLeft:6,color:"var(--text-dim)",fontSize:11},children:c.language})]},c.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 o=!!n.recommended;return e.jsxs("div",{style:{position:"relative",padding:12,borderRadius:8,border:o?"2px solid var(--success)":"1px solid var(--border)",background:o?"var(--success-soft)":"var(--bg)"},children:[o&&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(o,c){i(l=>({...l,[o]:c}))}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(o=>e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[e.jsx("label",{htmlFor:`oq-${o.id}`,style:{fontSize:13,color:"var(--text)",fontWeight:500},children:o.label}),o.kind==="choice"&&e.jsxs("select",{id:`oq-${o.id}`,value:a[o.id]??"",onChange:c=>n(o.id,c.target.value),style:Gt,children:[e.jsx("option",{value:"",children:"— select —"}),(o.options??[]).map(c=>e.jsx("option",{value:c,children:c},c))]}),o.kind==="text"&&e.jsx("input",{id:`oq-${o.id}`,type:"text",value:a[o.id]??"",onChange:c=>n(o.id,c.target.value),style:Gt}),o.kind==="multi"&&e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4},children:(o.options??[]).map(c=>{const l=a[o.id]??[],x=l.includes(c);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:x,onChange:()=>{const p=x?l.filter(h=>h!==c):[...l,c];n(o.id,p)}}),e.jsx("span",{children:c})]},c)})})]},o.id))]})}const Gt={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:o}){const c=n.split(`
|
|
4
|
+
`),l=o.split(`
|
|
5
|
+
`),x=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(pn,{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)"},h=(d,m,u)=>{const g={del:"var(--error-soft)",add:"var(--success-soft)",ctx:"transparent"},k={del:"var(--error)",add:"var(--success)",ctx:"var(--text-dim)"};return e.jsxs("div",{style:{display:"flex",padding:"0 12px",background:g[u]},children:[e.jsx("span",{style:{width:18,color:k[u],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:[x,i==="unified"?e.jsxs("pre",{style:p,children:[c.map((d,m)=>e.jsx("div",{children:h("-",d,"del")},`b${m}`)),l.map((d,m)=>e.jsx("div",{children:h("+",d,"add")},`a${m}`))]}):e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr"},children:[e.jsx("pre",{style:{...p,borderRight:"1px solid var(--border)"},children:c.map((d,m)=>e.jsx("div",{children:h("-",d,"del")},m))}),e.jsx("pre",{style:p,children:l.map((d,m)=>e.jsx("div",{children:h("+",d,"add")},m))})]})]})}const Rr={up:{fg:"var(--success)",Icon:Ue,label:"trending up"},down:{fg:"var(--error)",Icon:Ue,label:"trending down"},flat:{fg:"var(--text-dim)",Icon:xn,label:"flat"}};function Tr({id:s,label:t,value:a,trend:i,hint:n}){const o=i?Rr[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}),o&&e.jsx("span",{"aria-label":o.label,style:{display:"inline-flex",alignItems:"center",color:o.fg,transform:o.Icon===Ue&&i==="up"?"rotate(180deg)":void 0},children:e.jsx(o.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,os=60,cs=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(Ir,{id:s})});const i=new Map(t.map(h=>[h.id,h])),n=Mr(t),o=Math.max(...n.map(h=>h.col))+1,c=Math.max(...n.map(h=>h.row))+1,l=o*(Ae+os)+os,x=c*(Le+cs)+cs;function p(h){if(!i.get(h))return null;const m=n.find(u=>u.id===h);return m?{x:os+m.col*(Ae+os)+Ae/2,y:cs+m.row*(Le+cs)+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:x,style:{display:"block",maxWidth:"100%"},children:[e.jsx("defs",{children:e.jsx("marker",{id:`arrow-${s}`,viewBox:"0 0 10 10",refX:"9",refY:"5",markerWidth:"6",markerHeight:"6",orient:"auto-start-reverse",children:e.jsx("path",{d:"M 0 0 L 10 5 L 0 10 z",fill:"var(--text-dim)"})})}),a.map((h,d)=>{const m=p(h.from),u=p(h.to);if(!m||!u)return null;const g=u.x-m.x,k=u.y-m.y,z=g>=0?m.x+Ae/2:m.x-Ae/2,C=g>=0?u.x-Ae/2:u.x+Ae/2,y=k>=0?m.y+Le/2:m.y-Le/2,w=k>=0?u.y-Le/2:u.y+Le/2,$=(z+C)/2,j=(y+w)/2;return e.jsxs("g",{children:[e.jsx("line",{x1:z,y1:y,x2:C,y2:w,stroke:"var(--text-dim)",strokeWidth:1.5,markerEnd:`url(#arrow-${s})`}),h.label&&e.jsx("text",{x:$,y:j-4,fontSize:10,fill:"var(--text-dim)",textAnchor:"middle",fontFamily:"var(--font-mono)",children:h.label})]},d)}),t.map(h=>{const d=n.find(z=>z.id===h.id);if(!d)return null;const m=os+d.col*(Ae+os),u=cs+d.row*(Le+cs),g=$r[h.type];if(h.type==="decision"){const z=m+Ae/2,C=u+Le/2,y=[[z,u],[m+Ae,C],[z,u+Le],[m,C]].map(w=>w.join(",")).join(" ");return e.jsxs("g",{children:[e.jsx("polygon",{points:y,fill:g.fill,stroke:g.stroke,strokeWidth:2}),e.jsx("foreignObject",{x:m+8,y:C-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(un,{size:11}),h.label]})})]},h.id)}const k=h.type==="note";return e.jsxs("g",{children:[e.jsx("rect",{x:m,y:u,width:Ae,height:Le,rx:8,fill:g.fill,stroke:g.stroke,strokeWidth:k?1:2,strokeDasharray:k?"4 3":void 0}),e.jsx("foreignObject",{x:m+6,y:u+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:k?"italic":"normal",height:"100%"},children:[k&&e.jsx(hn,{size:11}),h.label]})})]},h.id)})]})})}function Ir({id:s}){return e.jsx("div",{id:s,style:{padding:20,textAlign:"center",color:"var(--text-dim)",fontSize:13},children:"No workflow steps."})}function Mr(s){return s.length===0?[]:s.map((t,a)=>({id:t.id,col:a,row:0}))}const $a={fontSize:14,lineHeight:1.6,color:"var(--text)"};function Lr({id:s,title:t,x:a,y:i,w:n,h:o,html:c}){return e.jsxs("figure",{id:s,"data-block-id":s,className:"glyph-mockup",style:{width:n,minHeight:o},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:c}})]})]})}class Er extends De.Component{constructor(){super(...arguments);bs(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 Z,ie,je,Ce;const i=re(),[n,o]=r.useState(null),[c,l]=r.useState([]),[x,p]=r.useState(!0),[h,d]=r.useState(null),[m,u]=r.useState(null),[g,k]=r.useState(!1),[z,C]=r.useState(!1),[y,w]=r.useState(null),[$,j]=r.useState(null),[N,v]=r.useState(""),[f,D]=r.useState(null),[M,b]=r.useState([]),A=De.useCallback((L,U,q)=>{b(Y=>Y.some(ne=>ne.blockId===L)?Y:[...Y,{blockId:L,blockType:U,message:q.message||String(q)}])},[]),O=r.useRef(null),S=r.useMemo(()=>n?Fr(n.blocks):[],[n]);r.useEffect(()=>{let L=!1;const U=5e3;return(async()=>{p(!0),d(null);try{const q=new Promise((J,ee)=>setTimeout(()=>ee(new Error("Request timed out after 5s")),U)),[Y,ne]=await Promise.race([Promise.all([R.get(`/artifacts/${encodeURIComponent(s)}/render`),R.get(`/artifacts/${encodeURIComponent(s)}`)]),q]);if(L)return;o(Y);const E=(ne==null?void 0:ne.comments)??[];l(Array.isArray(E)?E:[])}catch(q){if(!L){const Y=q.message;d(Y),u(Y)}}finally{L||p(!1)}})(),()=>{L=!0}},[s]);function F(L){if(!O.current)return;L.preventDefault();const U=O.current.getBoundingClientRect();w({x:L.clientX,y:L.clientY,worldX:L.clientX-U.left,worldY:L.clientY-U.top})}async function _(){if(!(!$||!N.trim()))try{const L=await R.post(`/artifacts/${encodeURIComponent(s)}/comments`,{x:$.worldX,y:$.worldY,text:N.trim(),author:"drb0rk"});l(U=>[...U,{id:L.id??`cmt_${Date.now()}`,x:$.worldX,y:$.worldY,text:N.trim(),author:"drb0rk",created:new Date().toISOString()}]),j(null),v(""),w(null),a==null||a(),i.success("Comment added")}catch(L){i.error(`Failed to add comment: ${L.message}`)}}async function P(){if(!g){k(!0);try{const L=await R.post(`/artifacts/${encodeURIComponent(s)}/submit`,{answers:[],submitter:"drb0rk"});L!=null&&L.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(L){i.error(`Submit failed: ${L.message}`)}finally{k(!1)}}}function V(){C(L=>!L)}const W=L=>{const U=L.id,q=L.data??{},Y=Dr(L);return Y.ok?e.jsx(Er,{blockId:U,blockType:L.type,onError:A,children:K(L,U,q)},U):e.jsxs("div",{id:U,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:[L.type," block invalid"]}),e.jsxs("div",{style:{color:"var(--text-muted)",marginBottom:6},children:["block id: ",e.jsx("code",{children:U})]}),e.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:Y.error})]},U)},K=(L,U,q)=>{switch(L.type){case"RichText":return e.jsx(jr,{id:U,children:L.childrenMarkdown??""},U);case"Callout":return e.jsx(vr,{id:U,tone:q.tone??"info",children:L.childrenMarkdown??""},U);case"Checklist":return e.jsx(yr,{id:U,items:q.items??[]},U);case"Table":return e.jsx(br,{id:U,columns:q.columns??[],rows:q.rows??[]},U);case"CodeTabs":return e.jsx(Nr,{id:U,tabs:q.tabs??[]},U);case"Decision":return e.jsx(kr,{id:U,title:q.title,question:q.question,options:q.options??[]},U);case"OpenQuestions":return e.jsx(wr,{id:U,questions:q.questions??[]},U);case"FileTree":return e.jsx(Cr,{id:U,title:q.title,entries:q.entries??[]},U);case"Diff":return e.jsx(zr,{id:U,filename:q.filename,language:q.language,mode:q.mode??"unified",before:q.before??"",after:q.after??""},U);case"Stat":return e.jsx(Tr,{id:U,label:q.label??"",value:q.value,trend:q.trend,hint:q.hint},U);case"Workflow":return e.jsx(Ar,{id:U,steps:q.steps??[],connections:q.connections},U);case"Mockup":return e.jsx(Lr,{id:U,title:q.title,x:q.x,y:q.y,w:q.w,h:q.h,html:q.html??""},U);case"Diagram":return e.jsx("div",{id:U,className:"glyph-block-placeholder",children:e.jsxs("em",{children:["[Diagram] ",U]})},U)}};if(x)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(Ur,{})," Loading glyph…"]})});if(h||!n)return e.jsxs("div",{className:"glyph-renderer glyph-renderer--error",children:[e.jsx("strong",{children:"Failed to load glyph."}),e.jsx("pre",{children:h??"unknown error"})]});const B=((Z=n.frontmatter)==null?void 0:Z.title)??s,Q=((ie=n.frontmatter)==null?void 0:ie.status)??"draft",te=c.length;return e.jsxs("div",{className:`glyph-canvas ${z?"glyph-canvas--fullscreen":""}`,ref:O,onContextMenu:F,children:[e.jsxs("div",{className:"glyph-toolbar-floating",children:[e.jsxs("button",{className:"glyph-btn glyph-btn--primary glyph-btn--send",onClick:P,disabled:g,title:"Send comments + question answers to the agent — writes feedback.md, status=review",children:[e.jsx(Ye,{size:14}),e.jsx("span",{children:"Send to agent"}),e.jsx("span",{className:"glyph-btn-badge",children:te})]}),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(gn,{size:15})}),e.jsx("button",{className:"glyph-icon-btn",title:"Undo",disabled:!0,children:e.jsx(jn,{size:15})}),e.jsx("button",{className:"glyph-icon-btn",title:"Redo",disabled:!0,children:e.jsx(fn,{size:15})}),e.jsx("button",{className:"glyph-icon-btn",title:z?"Exit fullscreen":"Fullscreen",onClick:V,children:e.jsx(vn,{size:15})}),e.jsx("button",{className:"glyph-icon-btn",title:"More",children:e.jsx(yn,{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(Qs,{size:15}),e.jsx("span",{className:"glyph-icon-btn-count",children:te})]}),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:B}),e.jsxs("div",{className:"glyph-meta",children:[e.jsx("span",{className:`glyph-status glyph-status--${Q}`,children:Q}),e.jsx("span",{className:"glyph-slug",children:s})]})]}),(M.length>0||((je=n.errors)==null?void 0:je.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:M.length>0?`${M.length} block${M.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:[M.map((L,U)=>e.jsxs("li",{children:[e.jsx("strong",{children:L.blockType})," (",e.jsx("code",{children:L.blockId}),"): ",L.message]},`be-${U}`)),(Ce=n.errors)==null?void 0:Ce.map((L,U)=>e.jsxs("li",{children:[L.line?`line ${L.line}: `:"",L.message]},`ce-${U}`))]})]}),e.jsx("div",{className:"glyph-sections",children:S.map((L,U)=>e.jsxs("section",{className:`glyph-section ${L.heading?"glyph-section--headed":"glyph-section--plain"}`,children:[L.heading&&e.jsx("h2",{className:"glyph-section-heading",children:L.heading}),e.jsx("div",{className:"glyph-section-blocks",children:L.blocks.map(W)})]},`sec-${U}-${L.heading??"ungrouped"}`))})]}),c.map(L=>e.jsxs("button",{className:`glyph-pin ${f===L.id?"glyph-pin--active":""}`,style:{left:L.x,top:L.y},onClick:U=>{U.stopPropagation(),D(f===L.id?null:L.id)},title:L.text,children:[e.jsx(Ut,{size:14}),f===L.id&&e.jsxs("div",{className:"glyph-pin-thread",children:[e.jsx("div",{className:"glyph-pin-text",children:L.text}),e.jsxs("div",{className:"glyph-pin-meta",children:[L.author??"anonymous"," · ",L.created?new Date(L.created).toLocaleString():""]})]})]},L.id)),y&&e.jsx("div",{className:"glyph-ctx-menu",style:{left:y.x,top:y.y},onClick:L=>L.stopPropagation(),children:e.jsxs("button",{className:"glyph-ctx-item",onClick:()=>{j({worldX:y.worldX,worldY:y.worldY}),w(null)},children:[e.jsx(Ut,{size:14})," Add comment here"]})}),$&&e.jsx("div",{className:"glyph-modal-overlay",onClick:()=>j(null),children:e.jsxs("div",{className:"glyph-modal",onClick:L=>L.stopPropagation(),children:[e.jsxs("h3",{children:["Add comment at (",Math.round($.worldX),", ",Math.round($.worldY),")"]}),e.jsx("textarea",{autoFocus:!0,value:N,onChange:L=>v(L.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:()=>j(null),children:"Cancel"}),e.jsx("button",{className:"glyph-btn glyph-btn--primary",onClick:_,disabled:!N.trim(),children:"Add comment"})]})]})})]})}function Ur(){return e.jsx("span",{className:"glyph-spinner","aria-label":"loading",children:"…"})}function Br(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||[]),[o,c]=r.useState(!s.artifacts),[l,x]=r.useState(null),[p,h]=r.useState(""),[d,m]=r.useState(!1);r.useEffect(()=>{s.artifacts&&(n(s.artifacts),c(!1))},[s.artifacts]);const u=async()=>{try{const C=await R.get("/artifacts");n(C.artifacts||[]),c(!1)}catch(C){a.error(`Artifacts load failed: ${C.message}`),c(!1)}},g=r.useMemo(()=>{let C=i;if(p){const y=p.toLowerCase();C=C.filter(w=>(w.slug||"").toLowerCase().includes(y)||(w.title||"").toLowerCase().includes(y))}return d||(C=C.filter(y=>y.status!=="archived")),C},[i,p,d]),k=async(C,y)=>{try{const w=await R.post("/artifacts",{slug:C,title:y});a.success(`Artifact "${w.slug}" created.`),x(w.slug),await u()}catch(w){a.error(`Create failed: ${w.message}`)}},z=async C=>{if(confirm(`Delete artifact "${C}"? This removes the directory permanently.`))try{await R.del(`/artifacts/${encodeURIComponent(C)}`),a.success("Artifact deleted."),l===C&&x(null),await u()}catch(y){a.error(`Delete failed: ${y.message}`)}};return l?e.jsxs("div",{className:"artifact-glyph-overlay",children:[e.jsx("div",{className:"artifact-glyph-toolbar",children:e.jsxs(T,{variant:"ghost",onClick:()=>{x(null),u()},children:[e.jsx(ra,{size:14})," Back to artifacts"]})}),e.jsx(Or,{slug:l,onClose:()=>{x(null),u()},onCommentAdded:()=>u()})]}):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(Se,{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:C=>h(C.target.value),"aria-label":"Search artifacts"})]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:()=>m(C=>!C),title:d?"Hide archived":"Show archived",children:[d?e.jsx(pa,{size:14}):e.jsx(bn,{size:14}),d?"Hide archived":"Show archived"]}),e.jsxs(T,{variant:"secondary",size:"sm",onClick:u,children:[e.jsx(oe,{size:14})," Refresh"]})]})]}),e.jsx(qr,{onCreate:k}),o?e.jsx("div",{className:"view-loading",children:e.jsx(le,{size:"lg"})}):g.length===0?e.jsx(he,{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(C=>e.jsx(Wr,{artifact:C,onOpen:()=>x(C.slug),onDelete:()=>z(C.slug)},C.slug))})]})}function qr({onCreate:s}){const[t,a]=r.useState(""),[i,n]=r.useState("");return e.jsxs(G,{className:"new-artifact",children:[e.jsxs(se,{children:[e.jsx(ve,{size:14})," New artifact"]}),e.jsx(ae,{children:"Slug must be lowercase, may contain hyphens, 1–64 chars."}),e.jsxs("form",{className:"new-artifact-form",onSubmit:o=>{o.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:o=>a(o.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:o=>n(o.target.value)}),e.jsx(T,{variant:"primary",type:"submit",children:"Create"})]})]})}function Wr({artifact:s,onOpen:t,onDelete:a}){const i=Br(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(Ve,{kind:i,children:s.status||"draft"})]}),e.jsxs("div",{className:"artifact-card-slug mono",children:[s.slug," · ",s.source]}),e.jsxs("div",{className:"artifact-card-meta",children:[s.elementCount!=null&&e.jsxs("span",{children:[s.elementCount," elements"]}),s.commentCount!=null&&e.jsxs("span",{children:[" · ",s.commentCount," comments"]}),e.jsxs("span",{children:[" · edited ",ze(s.mtime)]})]}),e.jsxs("div",{className:"artifact-card-actions",children:[e.jsxs(T,{variant:"primary",size:"sm",onClick:n=>{n.stopPropagation(),t()},children:["Open",e.jsx(Xe,{size:12})]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:n=>{n.stopPropagation(),a()},children:[e.jsx(ke,{size:12})," Delete"]})]})]})}function Vr({children:s,className:t,onRemove:a}){return e.jsxs("span",{className:H("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:o}){var h;const c=re(),l=async()=>{try{await R.post(`/tasks/${encodeURIComponent(s.id)}/promote`),c.success("Promoted to queued.",1500),a(s.id)}catch(d){c.error(`Promote failed: ${d.message}`)}},x=async()=>{if(confirm("Delete this task?"))try{await R.del(`/tasks/${encodeURIComponent(s.id)}`),c.success("Deleted.",1500),i(s.id)}catch(d){c.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]}),((h=s.tags)==null?void 0:h.length)>0&&e.jsx("span",{className:"backlog-item-badge",children:s.tags.join(", ")})]}),s.description&&e.jsx("div",{className:"backlog-item-desc",children:s.description.slice(0,120)}),e.jsxs("div",{className:"backlog-item-footer",children:[e.jsx("span",{className:"muted text-sm tabular-nums",children:ze(s.createdAt)}),e.jsxs("div",{className:"backlog-item-actions",children:[e.jsx("button",{type:"button",className:"icon-btn",title:"Promote to queued",onClick:l,children:e.jsx(zt,{size:13})}),e.jsx("button",{type:"button",className:"icon-btn",title:"Edit",onClick:()=>n(s),children:e.jsx(We,{size:13})}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger",title:"Delete",onClick:x,children:e.jsx(ke,{size:13})})]})]})]})}function Gr({agents:s,onRefresh:t}){const a=re(),[i,n]=r.useState([]),[o,c]=r.useState(!1),l=async()=>{try{c(!0);const m=await R.get("/tasks/backlog");n(Array.isArray(m.tasks)?m.tasks:[])}catch(m){a.error(`Backlog load failed: ${m.message}`)}finally{c(!1)}};r.useEffect(()=>{l()},[]);const x=async m=>{n(u=>u.filter(g=>g.id!==m)),await t()},p=async m=>{n(u=>u.filter(g=>g.id!==m)),await t()},h=m=>{},d=async()=>{var m;if(i.length!==0)try{const g=((m=(await R.post("/tasks/promote-batch",{ids:i.map(k=>k.id)})).affected)==null?void 0:m.filter(k=>k.ok).length)??0;a.success(`Promoted ${g} task(s).`,2e3),n([]),await t()}catch(u){a.error(`Promote all failed: ${u.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(Ks,{size:15}),"Backlog (",i.length,")"]}),e.jsxs("div",{className:"backlog-panel-header-actions",children:[i.length>0&&e.jsxs(T,{variant:"ghost",size:"sm",onClick:d,title:"Promote all to queued",children:[e.jsx(zt,{size:12})," Promote all"]}),e.jsx(T,{variant:"ghost",size:"sm",onClick:l,title:"Refresh backlog","aria-label":"Refresh backlog",children:e.jsx(oe,{size:12,className:o?"animate-spin":""})})]})]}),o?e.jsx("div",{className:"backlog-empty",children:"Loading…"}):i.length===0?e.jsxs("div",{className:"backlog-empty",children:[e.jsx(Ks,{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:x,onDelete:p,onEdit:h,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"}],Lt=["low","normal","high"];function Kr({snapshot:s,refreshSnapshot:t,setActiveTab:a}){const i=re(),n=Re(),[o,c]=r.useState(s.tasks||[]),[l,x]=r.useState(!s.tasks),[p,h]=r.useState(""),[d,m]=r.useState(""),[u,g]=r.useState(!1),[k,z]=r.useState(0),[C,y]=r.useState(""),w=async()=>{try{const b=await R.get("/tasks");c(Array.isArray(b)?b:[])}catch(b){i.error(`Tasks load failed: ${b.message}`)}finally{x(!1)}};r.useEffect(()=>{s.tasks&&(c(s.tasks),x(!1))},[s.tasks]),r.useEffect(()=>{const b=setInterval(()=>z(A=>A+1),3e4);return()=>clearInterval(b)},[]);const $=r.useMemo(()=>{let b=o.filter(A=>A.status!=="backlog");if(d&&(b=b.filter(A=>(A.priority||"normal")===d)),p.trim()){const A=p.toLowerCase();b=b.filter(O=>(O.title||"").toLowerCase().includes(A)||(O.description||"").toLowerCase().includes(A))}return b},[o,p,d]),j=r.useMemo(()=>{const b={high:0,normal:1,low:2};return[...$].sort((A,O)=>{const S=b[A.priority]??1,F=b[O.priority]??1;return S!==F?S-F:new Date(O.createdAt).getTime()-new Date(A.createdAt).getTime()})},[$]),N=o.filter(b=>b.status==="backlog").length,v=async(b,A)=>{const O=o.find(F=>F.id===b);if(!O)return;const S=O.status;c(F=>F.map(_=>_.id===b?{..._,status:A}:_)),y(`Task ${O.title} moved to ${A}.`);try{await R.patch(`/tasks/${encodeURIComponent(b)}/status`,{status:A}),i.success(`Moved to ${A}.`,1200)}catch(F){c(_=>_.map(P=>P.id===b?{...P,status:S}:P)),y(`Failed to move task ${O.title}: ${F.message}`),i.error(`Move failed: ${F.message}`)}},f=async b=>{if(confirm("Delete this task?"))try{await R.del(`/tasks/${encodeURIComponent(b)}`),c(A=>A.filter(O=>O.id!==b)),i.success("Task deleted.",1200)}catch(A){i.error(`Delete failed: ${A.message}`)}},D=async b=>{try{const A=await R.post(`/tasks/${encodeURIComponent(b)}/start`);A&&A.task&&c(O=>O.map(S=>S.id===b?A.task:S)),i.success("Retry dispatched.",1200)}catch(A){i.error(`Retry failed: ${A.message}`)}},M=async b=>{const A=o.find(O=>O.id===b);if(A)try{const O=await R.post("/tasks/submit",{title:A.title,description:A.description,priority:A.priority,tags:A.tags}),S=(O.subtasks||[]).length;i.success(S>1?`Odin split it into ${S} subtasks.`:"Sent to Odin.",1500),O.subtasks&&O.subtasks.length>0&&c(F=>[O.main,...O.subtasks,...F.filter(_=>_.id!==A.id)]),await t()}catch(O){i.error(`Submit failed: ${O.message}`)}};return e.jsxs("div",{className:"view view-tasks",children:[e.jsx("div",{className:"sr-only",role:"status","aria-live":"polite",children:C}),e.jsx("header",{className:"view-header",children:e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(Rs,{size:18})," Tasks (",j.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(Se,{size:12,"aria-hidden":!0}),e.jsx("input",{className:"input",type:"text",placeholder:"Search…",value:p,onChange:b=>h(b.target.value),"aria-label":"Search tasks"}),p&&e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Clear search",onClick:()=>h(""),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:b=>m(b.target.value),title:"Filter by priority",children:[e.jsx("option",{value:"",children:"All"}),Lt.map(b=>e.jsx("option",{value:b,children:b},b))]})]}),e.jsx("div",{className:"tasks-toolbar-spacer"}),e.jsxs("div",{className:"tasks-toolbar-group",children:[e.jsx(T,{variant:"ghost",size:"sm",onClick:w,title:"Refresh","aria-label":"Refresh tasks",children:e.jsx(oe,{size:14})}),N>0&&e.jsxs(T,{variant:u?"accent":"ghost",size:"sm",onClick:()=>g(b=>!b),title:u?"Hide backlog":"Show backlog",children:[e.jsx(Ks,{size:14}),"Backlog",e.jsx("span",{className:"badge",children:N})]}),e.jsxs(T,{variant:"primary",size:"sm",onClick:()=>Qr(n,i,c,w,t),children:[e.jsx(ve,{size:14})," New task"]})]})]}),u&&N>0&&e.jsx(Gr,{agents:s.agents||[],onRefresh:t}),l?e.jsx("div",{className:"view-loading",children:e.jsx(le,{size:"lg"})}):e.jsx("div",{className:"kanban",children:qs.map(b=>e.jsx(Yr,{column:b,tasks:j.filter(A=>A.status===b.id),onMove:v,onDelete:f,onRetry:D,onEdit:A=>Jr(n,i,A,c,w,t),onSubmitToOdin:M,tick:k},b.id))})]})}function Yr({column:s,tasks:t,onMove:a,onDelete:i,onRetry:n,onEdit:o,onSubmitToOdin:c,tick:l}){const[x,p]=r.useState(!1);return e.jsxs("div",{className:H("kanban-column",x&&"kanban-column-drop"),"data-column":s.id,onDragOver:h=>{h.preventDefault(),p(!0)},onDragLeave:()=>p(!1),onDrop:h=>{h.preventDefault(),p(!1);const d=h.dataTransfer.getData("text/task-id");d&&a(d,s.id)},children:[e.jsxs("div",{className:"kanban-col-header",children:[e.jsxs(se,{children:[e.jsx("span",{className:H("status-dot",`status-${s.kind}`)}),s.label]}),e.jsx("span",{className:"kanban-col-count tabular-nums",children:t.length})]}),e.jsx("div",{className:"kanban-col-body",children:t.length===0?e.jsx("div",{className:"kanban-empty",children:"No tasks"}):t.map(h=>e.jsx(Xr,{task:h,onMove:d=>{const u=qs.findIndex(g=>g.id===h.status)+d;u>=0&&u<qs.length&&a(h.id,qs[u].id)},onEdit:()=>o(h),onDelete:()=>i(h.id),onRetry:()=>n(h.id),onSubmitToOdin:()=>c(h.id),tick:l},h.id))})]})}function Xr({task:s,onMove:t,onEdit:a,onDelete:i,onRetry:n,onSubmitToOdin:o,tick:c}){const l=s.workedBy||s.assignee||null;return e.jsxs("div",{className:H("task-card",`priority-${s.priority}`),"data-task-id":s.id,draggable:!0,onDragStart:x=>{x.dataTransfer.setData("text/task-id",s.id),x.dataTransfer.effectAllowed="move"},"data-tick":c,children:[e.jsxs("div",{className:"task-card-head",children:[e.jsx("span",{className:"priority-dot",style:{background:Xa[s.priority]||"var(--info)"}}),e.jsx("div",{className:"task-card-title",children:s.title})]}),s.description&&e.jsx("div",{className:"task-card-desc",children:s.description.slice(0,160)}),e.jsxs("div",{className:"task-card-badges",children:[l&&e.jsxs("span",{className:"task-card-badge",title:`Auto-assigned to @${l}`,children:[e.jsx(Be,{size:10})," @",l]}),s.timeSpent?e.jsxs("span",{className:"task-card-badge",children:[e.jsx(Ge,{size:10})," ",Math.round((s.timeSpent||0)/60),"m"]}):null,s.tags&&s.tags.length>0&&s.tags.slice(0,3).map(x=>e.jsx(Vr,{children:x},x))]}),e.jsxs("div",{className:"task-card-footer",children:[e.jsx("span",{className:"task-card-time tabular-nums muted",children:ze(s.createdAt)}),e.jsxs("div",{className:"task-card-actions",onClick:x=>x.stopPropagation(),children:[e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Move left",title:"Move left",onClick:()=>t(-1),children:e.jsx(Nn,{size:14})}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Edit",title:"Edit",onClick:a,children:e.jsx(kn,{size:14})}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Submit to Odin",title:"Re-delegate to Odin",onClick:o,children:e.jsx(Ye,{size:14})}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Retry",title:"Retry",onClick:n,children:e.jsx(Js,{size:14})}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger","aria-label":"Delete",title:"Delete",onClick:i,children:e.jsx(ke,{size:14})}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Move right",title:"Move right",onClick:()=>t(1),children:e.jsx(Xe,{size:14})})]})]})]})}function Qr(s,t,a,i,n){let o=null,c=null,l=null,x=null;const p=async d=>{d&&typeof d.preventDefault=="function"&&d.preventDefault();const m=((o==null?void 0:o.value)||"").trim(),u=((c==null?void 0:c.value)||"").trim();if(!m){t.warning("Title is required."),o==null||o.focus();return}const g=(x==null?void 0:x.value)||"normal",k=((l==null?void 0:l.value)||"").split(",").map(z=>z.trim()).filter(Boolean);try{const z=await R.post("/tasks",{title:m,description:u,priority:g,tags:k});s.close(),typeof window<"u"&&window.dispatchEvent(new MouseEvent("mousedown")),a(C=>[z,...C]),t.success("Task created.",1200),await n()}catch(z){t.error(`Create failed: ${z.message}`)}},h=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=>{o=d},id:"task-title",className:"input",type:"text",maxLength:200,placeholder:"What needs to be done?",autoFocus:!0,onKeyDown:h}),e.jsx("label",{className:"field-label",htmlFor:"task-desc",children:"Description"}),e.jsxs("div",{style:{display:"flex",gap:6,alignItems:"flex-start"},children:[e.jsx("textarea",{ref:d=>{c=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=c==null?void 0:c.value)!=null&&m.trim()))return;const d=await Ya(c.value);d!==c.value&&(c.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=>{x=d},id:"task-priority",className:"select",defaultValue:"normal",children:Lt.map(d=>e.jsx("option",{value:d,children:d},d))})]}),e.jsxs("label",{htmlFor:"task-tags",className:"task-form-field",style:{flex:2},children:["Tags ",e.jsx("span",{className:"field-hint",children:"(comma-separated)"}),e.jsx("input",{ref:d=>{l=d},id:"task-tags",className:"input",type:"text",placeholder:"bug, frontend, urgent"})]})]}),e.jsx("p",{className:"muted text-sm",style:{marginTop:8},children:"The agent and final priority are decided by Odin after you submit."})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx(T,{variant:"ghost",onClick:()=>s.close(),children:"Cancel"}),e.jsxs(T,{variant:"primary",type:"button",onClick:d=>p(d),children:[e.jsx(ve,{size:14})," Create task"]})]})})}function Jr(s,t,a,i,n,o){let c=null,l=null,x=null,p=null;const h=async()=>{const d=((c==null?void 0:c.value)||"").trim(),m=((l==null?void 0:l.value)||"").trim();if(!d){t.warning("Title is required."),c==null||c.focus();return}const u=(p==null?void 0:p.value)||"normal",g=((x==null?void 0:x.value)||"").split(",").map(k=>k.trim()).filter(Boolean);try{const k=await R.put(`/tasks/${encodeURIComponent(a.id)}`,{title:d,description:m,priority:u,tags:g});s.close(),typeof window<"u"&&window.dispatchEvent(new MouseEvent("mousedown")),i(z=>z.map(C=>C.id===a.id?k:C)),t.success("Task updated.",1200),await o()}catch(k){t.error(`Save failed: ${k.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=>{c=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:Lt.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=>{x=d},id:"edit-task-tags",className:"input",type:"text",defaultValue:(a.tags||[]).join(", "),placeholder:"comma-separated"})]})]}),e.jsxs(G,{children:[e.jsxs(se,{children:[e.jsx(xa,{size:12})," Status"]}),e.jsxs(ae,{children:["Current: ",e.jsx("strong",{children:a.status}),a.workedBy&&e.jsxs(e.Fragment,{children:[" · Worked by @",a.workedBy]}),a.assignee&&!a.workedBy&&e.jsxs(e.Fragment,{children:[" · Assigned @",a.assignee]})]})]})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx(T,{variant:"ghost",onClick:()=>s.close(),children:"Cancel"}),e.jsxs(T,{variant:"primary",onClick:h,children:[e.jsx(pa,{size:14})," Save"]})]})})}const Zr=De.memo(Kr);function el(s){return R.urlWithToken(`/artifacts/${encodeURIComponent(s)}/content`)}function sl(s,t){const a=el(t);window.open(a,"_blank","noopener,noreferrer")}const Kt={"1m":60*1e3,"5m":5*60*1e3,"30m":30*60*1e3,"1h":60*60*1e3},Ie=56,_e=32,ds=22,tl=4,al=.9,nt={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 it(s){return s&&nt[s]||nt.idle}function Fs(s,t=24){return s?s.length<=t?s:s.slice(0,t-1)+"…":""}function Xs(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 rt(s){const t=s._timerStart;return typeof t=="number"&&t>0?t:Xs(s.createdAt)||Date.now()}function nl(s,t){return(s.status==="done"||s.status==="archived"||s.status==="failed"||s.status==="killed")&&(Xs(s.completedAt)||Xs(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,o]=r.useState("live"),[c,l]=r.useState("5m"),[x,p]=r.useState(()=>typeof window>"u"?!0:window.innerWidth>900),[h,d]=r.useState([]),[m,u]=r.useState([]),[g,k]=r.useState(!0),[z,C]=r.useState(0),[y,w]=r.useState(Date.now()),[$,j]=r.useState(()=>Date.now()-Kt["5m"]*.1),[N,v]=r.useState({width:800,height:400}),[f,D]=r.useState(null),[M,b]=r.useState(""),[A,O]=r.useState([]),[S,F]=r.useState(""),[_,P]=r.useState("normal"),[V,W]=r.useState(""),[K,B]=r.useState(""),[Q,te]=r.useState(!1),[Z,ie]=r.useState(!1),[je,Ce]=r.useState([]),L=Re(),U=s.agents||[],q=s.tasks||[],Y=Kt[c],ne=$,E=$+Y,J=r.useCallback(async()=>{try{const[I,X]=await Promise.all([R.get("/background").catch(()=>({instances:[]})),R.get("/activity?limit=200").catch(()=>({events:[]}))]);d(I.instances||[]),u(X.events||[])}catch(I){console.warn("activity reload failed:",I)}finally{k(!1)}},[]);r.useEffect(()=>{J();const I=setInterval(J,3e3);return()=>clearInterval(I)},[J]),r.useEffect(()=>{C(I=>I+1)},[q.length,U.length]),r.useEffect(()=>{if(n==="pause")return;w(Date.now());const I=setInterval(()=>w(Date.now()),1e3);return()=>clearInterval(I)},[n,z]),r.useEffect(()=>{if(n==="pause")return;(y-$)/Y>al&&j(y-Y*.1)},[y,$,Y,n]),r.useEffect(()=>{j(Date.now()-Y*.1)},[c]),r.useEffect(()=>{n==="live"&&j(Date.now()-Y*.1)},[n]),r.useLayoutEffect(()=>{const I=i.current;if(!I)return;const X=new ResizeObserver(xe=>{for(const pe of xe){const{width:de,height:ge}=pe.contentRect;v({width:Math.max(200,Math.floor(de)),height:Math.max(120,Math.floor(ge))})}});return X.observe(I),()=>X.disconnect()},[]);const ee=r.useMemo(()=>{const I=[];let X=0;for(const de of h){const ge=il(de),Me=rl(de,y);Me<ne||ge>E||I.push({kind:"bg",id:`bg:${de.instanceId}`,index:X++,label:`BG ${Fs(de.promptPreview,20)||de.instanceId.slice(0,10)}`,sub:de.status||"pending",start:ge,end:Me,data:de})}const xe=[...q].sort((de,ge)=>rt(de)-rt(ge)),pe=[];for(const de of xe){const ge=rt(de),Me=nl(de,y);if(Me<ne||ge>E)continue;let ls=-1;for(let Je=0;Je<pe.length;Je++)if(pe[Je]<=ge){pe[Je]=Me,ls=Je;break}ls===-1&&(pe.push(Me),ls=pe.length-1),I.push({kind:"task",id:`task:${de.id}`,index:X+ls,label:Fs(de.title,32),sub:de.status,start:ge,end:Me,data:de})}return I},[h,q,y,ne,E]),ue=r.useMemo(()=>{const I=new Map;for(const X of ee)I.set(X.id,X);return I},[ee]),ce=r.useCallback(I=>Y<=0?0:(I-ne)/Y*N.width,[ne,Y,N.width]),rs=r.useMemo(()=>{const I=ll(Y),X=[],xe=Math.floor(ne/I)*I;for(let pe=xe;pe<=E+I;pe+=I){if(pe<ne-I)continue;if(pe>E)break;const de=ce(pe);de<-40||de>N.width+40||X.push({t:pe,x:de,label:ol(pe,Y)})}return X},[ne,E,Y,N.width,ce]),Ls=r.useMemo(()=>{const I=[];for(const X of ee){if(X.kind==="events")continue;const xe=Math.max(X.start,ne),pe=Math.min(X.end,E);if(pe<ne||xe>E)continue;const de=ce(xe),ge=ce(pe),Me=Math.max(tl,ge-de),ls=_e+ds+X.index*Ie+8,Je=Ie-16;let Pe="doing";if(X.kind==="bg"){const we=X.data.status||"pending";we==="done"||we==="success"?Pe="done":we==="failed"||we==="killed"||we==="error"?Pe="failed":we==="queued"||we==="pending"?Pe="queued":we==="blocked"||we==="stuck"?Pe="blocked":Pe="doing"}else{const we=X.data.status;we==="done"||we==="archived"?Pe="done":we==="failed"||we==="killed"?Pe="failed":we==="queued"?Pe="queued":we==="blocked"?Pe="blocked":Pe="doing"}const Ha=(f==null?void 0:f.id)===X.id;I.push({id:X.id,laneIndex:X.index,x:de,y:ls,w:Me,h:Je,label:X.label,statusClass:Pe,selected:Ha,data:X.data,kind:X.kind,start:X.start,end:X.end})}return I},[ee,ce,f,ne,E]),Es=r.useMemo(()=>{const I=[];for(const X of m){const xe=Xs(X.ts);if(xe<ne-5e3||xe>E+5e3)continue;const pe=ce(xe);let de=_e+12;if(X.taskId){const ge=ue.get(`task:${X.taskId}`);ge&&(de=_e+ds+ge.index*Ie+Ie/2)}else if(X.nodeId){const ge=String(X.nodeId),Me=ue.get(ge.startsWith("task:")||ge.startsWith("bg:")?ge:`task:${ge}`);Me&&(de=_e+ds+Me.index*Ie+Ie/2)}I.push({id:`${X.ts}-${X.kind}-${X.author??""}-${X.taskId??""}`,x:pe,y:de,kind:X.kind||"event",ts:xe,text:String(X.text||X.kind||""),author:X.author})}return I},[m,ne,E,ce,ue]),Ds=r.useMemo(()=>ee.map(I=>({id:I.id,y:_e+ds+I.index*Ie,h:Ie})),[ee]),Qe=r.useMemo(()=>{const I=ce(y);return Math.max(0,Math.min(N.width,I))},[ce,y,N.width]),Ba=r.useCallback(I=>{const xe={id:I.id,kind:I.kind,label:I.label,status:I.statusClass,data:I.data};D(xe)},[]);r.useEffect(()=>{if(!f){O([]),B(""),Ce([]);return}b(""),F(""),W(""),Ce([]),(async()=>{try{const I=await R.get(`/activity?nodeId=${encodeURIComponent(f.id)}&limit=50`);O(I.events||[])}catch{O([])}if(f.kind==="bg"){const I=f.data;try{const X=await R.get(`/background/${encodeURIComponent(I.instanceId)}/output?lines=80`);B(X.output||"")}catch{B("")}if(I.taskId)try{const X=await R.get(`/tasks/${encodeURIComponent(I.taskId)}/artifacts`);Ce((X.artifacts||[]).map(xe=>xe.id))}catch{Ce([])}}})()},[f]);const Ft=async()=>{if(!(!f||!M.trim())){ie(!0);try{await R.post("/comments",{nodeId:f.id,text:M,author:"user"}),b("");const I=await R.get(`/activity?nodeId=${encodeURIComponent(f.id)}&limit=50`);O(I.events||[]),a.success("Comment added.")}catch(I){a.error(`Comment failed: ${I.message}`)}finally{ie(!1)}}},_a=async()=>{if(!(!f||!S.trim())){te(!0);try{await R.post(`/nodes/${encodeURIComponent(f.id)}/tasks`,{title:S,description:`Created from timeline selection ${f.id}.`,priority:_}),F(""),a.success("Task created."),await t()}catch(I){a.error(`Task create failed: ${I.message}`)}finally{te(!1)}}},Ot=async()=>{if(!f||f.kind!=="bg"||!V.trim())return;const I=f.data;try{const X=await R.post(`/background/${encodeURIComponent(I.instanceId)}/message`,{message:V});X.ok?(a.success("Message sent."),W("")):a.warning(X.error||"Send failed")}catch(X){a.error(`Send failed: ${X.message}`)}},qa=async()=>{if(!f||f.kind!=="bg"||!confirm("Kill this bg instance session?"))return;const I=f.data;try{const X=await R.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}`)}},Wa=async()=>{if(!f||f.kind!=="bg")return;const I=f.data;try{const X=await R.get(`/background/${encodeURIComponent(I.instanceId)}/output?lines=80`);B(X.output||"")}catch{}};r.useEffect(()=>{const I=X=>{X.key==="Escape"&&D(null)};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[]);const Va=()=>{C(I=>I+1),J()},Zs=_e+ds+ee.length*Ie;return e.jsxs("div",{className:"view view-activity",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(Te,{size:18})," Activity"]}),e.jsx("p",{className:"view-subtitle",children:"Live timeline of agents, tasks, and background sessions. Active tasks pulse; the red line marks “now”."})]}),e.jsx("div",{className:"view-actions",children:e.jsxs("div",{className:"tl-mode-toggle",children:[e.jsxs(T,{variant:n==="live"?"primary":"secondary",size:"sm",onClick:()=>o(n==="live"?"pause":"live"),title:n==="live"?"Pause timeline":"Resume timeline",children:[n==="live"?e.jsx(Rt,{size:14}):e.jsx(ys,{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:H("tl-zoom-btn",c===I&&"tl-zoom-btn-active"),onClick:()=>l(I),title:`Zoom to ${I}`,children:I},I))}),e.jsxs(T,{variant:"secondary",size:"sm",onClick:Va,title:"Refresh",children:[e.jsx(oe,{size:14})," Refresh"]})]})})]}),g&&e.jsx("div",{className:"view-loading",children:e.jsx(le,{size:"lg"})}),!g&&U.length===0&&q.length===0&&h.length===0&&m.length===0?e.jsx(he,{icon:e.jsx(Te,{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:H("tl-view",f&&"tl-view-detail-open"),children:e.jsxs("div",{className:H("tl-body",!x&&"tl-body-stream-collapsed"),children:[e.jsxs("aside",{className:H("tl-stream",!x&&"tl-stream-collapsed"),children:[e.jsxs("div",{className:"tl-stream-head",children:[e.jsxs("h3",{children:[e.jsx(Ts,{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(wn,{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(Mt,{items:[...m].reverse(),itemHeight:40,height:400,className:"tl-stream-virtual",renderItem:I=>{const X=I.author?Be:I.kind==="task"?Rs:I.kind==="bg"?zs:Te;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:it(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:[!x&&e.jsxs(T,{variant:"ghost",size:"sm",onClick:()=>p(!0),title:"Show event stream",children:[e.jsx(Sn,{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(ne).toLocaleTimeString("en-GB",{hour12:!1})," →"," ",new Date(E).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(Cn,{size:11})," agent"]}),e.jsxs("span",{className:"tl-legend-item",children:[e.jsx(zn,{size:11})," task"]}),e.jsxs("span",{className:"tl-legend-item",children:[e.jsx(zs,{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,Zs),role:"application","aria-label":"Activity timeline",children:[e.jsx("defs",{children:e.jsx("pattern",{id:"tl-canvas-grid",width:N.width,height:Ie,patternUnits:"userSpaceOnUse",children:e.jsx("path",{d:`M 0 0 L 0 ${Ie}`,fill:"none",stroke:"var(--border)",strokeWidth:.5,opacity:.35})})}),e.jsx("rect",{width:"100%",height:"100%",fill:"url(#tl-canvas-grid)"}),Ds.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:rs.map(I=>e.jsxs("g",{children:[e.jsx("line",{x1:I.x,y1:0,x2:I.x,y2:Zs,stroke:"var(--border)",strokeWidth:.5,strokeDasharray:"2,4",opacity:.5}),e.jsx("text",{x:I.x+4,y:_e-8,fontSize:10,fontFamily:"var(--font-mono)",fill:"var(--text-dim)",children:I.label})]},`tick-${I.t}`))}),ee.map(I=>{const X=_e+ds+I.index*Ie+Ie/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:Fs(I.label,28)}),e.jsx("text",{x:6,y:X+10,className:"tl-lane-label-sub",textAnchor:"start",children:I.sub})]},`label-${I.id}`)}),Ls.map(I=>{const X=it(I.statusClass),xe=I.id===(f==null?void 0:f.id);return e.jsxs("g",{className:H("tl-task-bar",`tl-task-bar-${I.statusClass}`,xe&&"tl-task-bar-selected"),onClick:()=>Ba(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:xe?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:Fs(I.label,Math.max(4,Math.floor(I.w/7)))})]},`bar-${I.id}`)}),Es.map(I=>{const X=it(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:Qe,y1:0,x2:Qe,y2:Zs,stroke:"var(--error)",strokeWidth:1.5,opacity:.9}),e.jsxs("g",{className:"tl-now-marker",children:[e.jsx("circle",{cx:Qe,cy:_e-4,r:4,fill:"var(--error)"}),e.jsx("text",{x:Qe+6,y:_e-4,fontSize:10,fontWeight:700,fill:"var(--error)",fontFamily:"var(--font-mono)",children:"now"})]})]})})]}),f&&e.jsx("aside",{className:"tl-detail tl-detail-enter",children:e.jsxs(G,{children:[e.jsxs(se,{children:[f.kind==="agent"&&e.jsx(Be,{size:14}),f.kind==="task"&&e.jsx(Rs,{size:14}),f.kind==="bg"&&e.jsx(zs,{size:14}),f.label,e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>D(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"})," ",f.kind]}),e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"status"})," ",e.jsx("code",{children:f.status})]}),f.kind==="agent"&&(()=>{const I=f.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]})]})})(),f.kind==="task"&&(()=>{const I=f.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()]})]})})(),f.kind==="bg"&&(()=>{const I=f.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"})]})]})})()]}),f.kind==="task"&&f.data.description&&e.jsx("div",{className:"tl-detail-desc",children:f.data.description}),f.kind==="bg"&&f.data.promptPreview&&e.jsx("div",{className:"tl-detail-desc",children:f.data.promptPreview}),f.kind==="bg"&&e.jsxs("div",{className:"tl-detail-bg",children:[e.jsx("pre",{className:"tl-bg-output",children:K||"(no output — start the session via tmux attach)"}),e.jsxs("div",{className:"tl-bg-output-actions",children:[e.jsxs(T,{variant:"ghost",size:"sm",onClick:Wa,children:[e.jsx(oe,{size:12})," Refresh output"]}),je.length>0&&e.jsxs(T,{variant:"secondary",size:"sm",onClick:()=>sl(L,je[0]),children:[e.jsx(be,{size:12})," Open artifact"]}),e.jsxs(T,{variant:"danger",size:"sm",onClick:qa,children:[e.jsx(ke,{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:V,onChange:I=>W(I.target.value),onKeyDown:I=>{I.key==="Enter"&&Ot()},"aria-label":"Send a message to this bg session"}),e.jsxs(T,{variant:"primary",size:"sm",disabled:!V.trim(),onClick:Ot,children:[e.jsx(Ye,{size:12})," Send"]})]})]}),f.kind!=="bg"&&e.jsxs("div",{className:"tl-detail-create",children:[e.jsx("label",{className:"field-label",htmlFor:"followup-task-title",children:"Create follow-up task"}),e.jsx("input",{id:"followup-task-title",className:"input",placeholder:"Task title",value:S,onChange:I=>F(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:_,onChange:I=>P(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(T,{variant:"primary",size:"sm",disabled:!S.trim()||Q,onClick:_a,children:[e.jsx(ve,{size:12})," Add task"]})]})]}),e.jsxs("div",{className:"tl-detail-comments",children:[e.jsxs("div",{className:"field-label",children:[e.jsx(Qs,{size:12})," Comments & activity"]}),e.jsxs("ul",{className:"comment-list",children:[A.length===0&&e.jsx("li",{className:"muted",children:"No comments yet."}),A.map((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:M,onChange:I=>b(I.target.value),onKeyDown:I=>{I.key==="Enter"&&!I.shiftKey&&Ft()},"aria-label":"Add a comment"}),e.jsxs(T,{variant:"secondary",size:"sm",disabled:!M.trim()||Z,onClick:Ft,children:[e.jsx(Ye,{size:12})," Post"]})]})]})]})},f.id)]})})]})}const dl=[{id:"dark",label:"Dark",Icon:Rn},{id:"light",label:"Light",Icon:Tn},{id:"system",label:"System",Icon:$n}],ml=[{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"}],ul=["Inter","system-ui","Segoe UI","Roboto","JetBrains Mono","SF Mono","Cascadia Code"];function hl({settings:s,patchTheme:t,patchUi:a}){return e.jsxs(G,{id:"settings-theme","data-section":"theme",children:[e.jsxs(se,{children:[e.jsx(yt,{size:14})," Theme"]}),e.jsx(ae,{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:ml.map(i=>e.jsxs("button",{type:"button",className:H("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:dl.map(({id:i,label:n,Icon:o})=>{const c=s.theme.mode===i;return e.jsxs("button",{type:"button",className:H("theme-card",c&&"theme-card-active"),onClick:()=>t({mode:i}),children:[e.jsx(o,{size:16}),e.jsx("span",{className:"theme-card-label",children:n}),e.jsx("span",{className:H("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:ul.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 xl({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(se,{children:[e.jsx(js,{size:14})," Service"]}),e.jsx(ae,{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(se,{children:[e.jsx(ht,{size:14})," Tailscale serve"]}),e.jsx(ae,{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(o=>({...o,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(o=>({...o,https:n.target.checked}))})]})]}),e.jsx(T,{variant:"primary",onClick:i,children:s.settings.enabled?"Disable serve":"Enable serve"})]}):e.jsx("p",{className:"muted",children:"Loading Tailscale status…"})]})]})}function pl({settings:s,patchNotifications:t}){return e.jsxs(G,{id:"settings-notifications","data-section":"notifications",children:[e.jsx(se,{children:"Notifications"}),e.jsx(ae,{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 gl({authStatus:s,setAuthStatus:t}){const a=re(),[i,n]=r.useState(R.getToken()),[o,c]=r.useState("");r.useEffect(()=>{let h=!1;return(async()=>{try{const d=await R.probeAuthStatus();h||t(d)}catch{h||t({required:!0,loopback:!1,peer:""})}})(),()=>{h=!0}},[]);const l=async()=>{try{const h=await R.get("/auth/reveal");c(h.token),n(h.token),R.setToken(h.token);try{await navigator.clipboard.writeText(h.token),a.success("Token copied to clipboard.")}catch{a.success("Token revealed — copy from the field below.")}}catch(h){a.error(`Reveal failed: ${h.message}`)}},x=async()=>{if(confirm("Regenerate the auth token? Anything still using the old token will start getting 401 errors immediately."))try{const h=await R.post("/auth/regenerate");c(h.token),n(h.token),R.setToken(h.token);try{await navigator.clipboard.writeText(h.token),a.success("New token generated and copied to clipboard.")}catch{a.success("New token generated — copy from the field below. Old token is now invalid.")}}catch(h){a.error(`Regenerate failed: ${h.message}`)}},p=()=>{R.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(se,{children:[e.jsx(Tt,{size:14})," Authentication"]}),e.jsx(ae,{children:"Localhost and Tailscale browser access are auto-trusted via loopback. A bearer token is still available for non-loopback clients and forced-auth mode."}),e.jsxs("div",{className:"field","data-setting-id":"auth.status",children:[e.jsx("label",{className:"field-label",children:"Server status"}),e.jsxs("p",{style:{margin:"4px 0"},children:["Auth required:"," ",e.jsx("strong",{children:s?s.required?"yes":"no":"probing…"})]}),e.jsxs("p",{style:{margin:"4px 0"},children:["Connection:"," ",e.jsx("strong",{children:s?s.loopback?"loopback (auto-trusted)":"remote":"probing…"})]}),e.jsxs("p",{style:{margin:"4px 0"},children:["Peer address:"," ",s!=null&&s.peer?e.jsx("code",{children:s.peer}):e.jsx("span",{className:"muted",children:"probing…"})]}),e.jsxs("p",{className:"muted",style:{fontSize:12,margin:"4px 0"},children:["Localhost and Tailscale browser access are auto-trusted because the dashboard sees a loopback peer. Paste a token only for non-loopback API clients/scripts, or if you force auth for every connection with"," ",e.jsx("code",{children:"BIZAR_DASHBOARD_REQUIRE_AUTH=1"}),"."]}),e.jsxs("p",{className:"muted",style:{fontSize:12,margin:"4px 0"},children:["Dashboard tokens are generated on first boot and saved to"," ",e.jsx("code",{children:"~/.config/bizar/dashboard-secret"})," (mode 0600)."]}),e.jsx("p",{className:"muted",style:{fontSize:12,margin:"4px 0"},children:"For Tailscale Serve or any reverse-proxy access, paste this token once via the boot screen — it is saved per-origin and works for all subsequent visits."})]}),e.jsxs("div",{className:"field","data-setting-id":"auth.token",children:[e.jsx("label",{className:"field-label",children:"Token (this browser)"}),e.jsx("input",{type:"password",className:"input mono",value:i,onChange:h=>n(h.target.value),placeholder:"Paste token from server stderr or another browser",spellCheck:!1,autoComplete:"off"}),e.jsxs("div",{className:"task-form-row",style:{marginTop:8},children:[e.jsxs(T,{variant:"secondary",size:"sm",onClick:p,children:[e.jsx($t,{size:14})," Save token"]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:l,children:[e.jsx(ns,{size:14})," Reveal & copy server token"]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:x,children:[e.jsx(ga,{size:14})," Regenerate"]})]}),o?e.jsxs("p",{className:"muted",style:{fontSize:12,marginTop:8},children:["Last revealed token (one-time): ",e.jsx("code",{className:"mono",children:o})]}):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 jl({settings:s,patchAgents:t,patchDashboard:a,autoSave:i}){var p,h,d,m;const n=re(),[o,c]=r.useState({});r.useEffect(()=>{R.get("/settings/plugin-options").then(c).catch(()=>{})},[]);const l=async()=>{try{await R.put("/settings/plugin-options",o),n.success("Saved — restart opencode for changes to take effect.")}catch(u){n.error(`Save failed: ${u.message}`)}},x=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(u){n.error(`Cleanup failed: ${u.message}`)}};return e.jsxs(e.Fragment,{children:[e.jsxs(G,{id:"settings-agents","data-section":"agents",children:[e.jsxs(se,{children:[e.jsx(js,{size:14})," Agent Behavior"]}),e.jsx(ae,{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:u=>t({maxParallel:Math.max(1,Math.min(20,parseInt(u.target.value,10)||6))})})]}),e.jsxs("div",{className:"form-row",children:[e.jsxs("label",{htmlFor:"agents-stuckThresholdMs",children:["Stuck threshold (ms)",e.jsx("span",{className:"meta-badge",children:"default: 600000 (10 min)"})]}),e.jsx("input",{id:"agents-stuckThresholdMs",type:"number",min:6e4,max:36e5,step:6e4,value:((h=s.agents)==null?void 0:h.stuckThresholdMs)??6e5,onChange:u=>t({stuckThresholdMs:Math.max(6e4,Math.min(36e5,parseInt(u.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:u=>t({autoRestart:u.target.checked})}),e.jsx("span",{children:"Auto-restart stuck agents"})]})]}),e.jsxs(G,{id:"settings-dashboard","data-section":"dashboard",children:[e.jsxs(se,{children:[e.jsx(is,{size:14})," Dashboard"]}),e.jsxs(ae,{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:u=>a({autoLaunchWeb:u.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:u=>a({projectsDirectory:u.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(Yn,{initialValue:(s.dashboard.allowedRoots??[]).join(`
|
|
6
|
+
`),delay:1500,saveFn:async u=>{const g=u.split(`
|
|
7
|
+
`).map(k=>k.trim()).filter(Boolean);a({allowedRoots:g}),i==null||i("dashboard",{allowedRoots:g})},render:({value:u,onChange:g,onBlur:k})=>e.jsx("textarea",{id:"set-allowed-roots",className:"textarea",rows:4,placeholder:`/workspace
|
|
8
|
+
/srv/projects`,value:u,onChange:z=>g(z.target.value),onBlur:k})},(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 u=(s.dashboard.allowedRoots??[]).join(`
|
|
10
|
+
`).split(`
|
|
11
|
+
`),g=[];return u.forEach((k,z)=>{k.trim()&&(/^\/|^[A-Za-z]:/.test(k)||g.push({key:`noabs-${z}`,msg:e.jsxs("p",{style:{color:"var(--warning)",fontSize:11,marginTop:2},children:["Line ",z+1,': "',k,'" — should be absolute (start with / or a drive letter).']})}),k.includes("..")&&g.push({key:`dots-${z}`,msg:e.jsxs("p",{style:{color:"var(--error)",fontSize:11,marginTop:2},children:["Line ",z+1,': "',k,`" — contains '..' (server will reject this).`]})}))}),g.map(k=>k.msg)})()]})]}),e.jsxs(G,{id:"settings-background","data-section":"background",children:[e.jsxs(se,{children:[e.jsx(js,{size:14})," Background Agents"]}),e.jsx(ae,{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:o.maxConcurrentInstances??8,onChange:u=>c(g=>({...g,maxConcurrentInstances:Math.max(1,Math.min(32,parseInt(u.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:o.backgroundToolCallCap??500,onChange:u=>c(g=>({...g,backgroundToolCallCap:Math.max(1,Math.min(5e3,parseInt(u.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:o.backgroundStallTimeoutMs??18e4,onChange:u=>c(g=>({...g,backgroundStallTimeoutMs:Math.max(1e4,Math.min(6e5,parseInt(u.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:o.backgroundThinkingLoopTimeoutMs??3e5,onChange:u=>c(g=>({...g,backgroundThinkingLoopTimeoutMs:Math.max(3e4,Math.min(9e5,parseInt(u.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:o.backgroundMaxInterventions??1,onChange:u=>c(g=>({...g,backgroundMaxInterventions:Math.max(1,Math.min(3,parseInt(u.target.value,10)||1))}))}),e.jsxs("small",{className:"muted",children:["Plugin option: ",e.jsx("code",{children:"backgroundMaxInterventions"})]})]}),e.jsxs("div",{className:"form-row",children:[e.jsxs(T,{variant:"secondary",size:"sm",onClick:l,children:[e.jsx(fs,{size:14})," Save plugin options"]}),e.jsx(T,{variant:"secondary",size:"sm",onClick:x,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 fl({workspaceId:s,onInviteCreated:t}){const a=Re(),[i,n]=r.useState(""),[o,c]=r.useState("editor"),[l,x]=r.useState([]),[p,h]=r.useState(!1),[d,m]=r.useState(!1),[u,g]=r.useState(null),[k,z]=r.useState(null);r.useEffect(()=>{C()},[s]);async function C(){h(!0);try{const N=await R.get(`/workspaces/${s}/invites`);x(N.invites||[])}catch{}finally{h(!1)}}async function y(N){if(N.preventDefault(),!!i.trim()){m(!0),z(null);try{const v=await R.post(`/workspaces/${s}/invites`,{email:i.trim(),role:o});n(""),await C(),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:o}),":"]}),e.jsxs("div",{className:"invite-url-box",children:[e.jsx(In,{size:14}),e.jsx("input",{type:"text",readOnly:!0,value:v.url,onClick:f=>f.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:u===v.token?e.jsx(ps,{size:14}):e.jsx(ns,{size:14})})]}),e.jsx("p",{className:"invite-url-note",children:"This link expires in 7 days."})]}),footer:e.jsx(T,{variant:"primary",size:"sm",onClick:()=>a.close(),children:"Done"})})}catch(v){z(v.message||"Failed to create invite")}finally{m(!1)}}}async function w(N){if(confirm("Revoke this invite?"))try{await R.del(`/workspaces/${s}/invites/${N}`),await C()}catch(v){z(v.message||"Failed to revoke invite")}}function $(N,v){navigator.clipboard.writeText(N).catch(()=>{}),g(v),setTimeout(()=>g(null),2e3)}const j={admin:"role-admin",editor:"role-editor",viewer:"role-viewer"};return e.jsxs("div",{className:"invite-dialog",children:[e.jsxs("form",{className:"invite-form",onSubmit:y,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:o,onChange:N=>c(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(T,{type:"submit",variant:"primary",size:"sm",loading:d,disabled:!i.trim(),children:[e.jsx(An,{size:13}),"Invite"]})]}),k&&e.jsx("p",{className:"invite-error",children:k})]}),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:H("invite-item-role",j[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}`;$(v,N.token)},children:u===N.token?e.jsx(ps,{size:13}):e.jsx(ns,{size:13})}),e.jsx("button",{type:"button",className:"invite-action-btn invite-action-revoke",title:"Revoke invite",onClick:()=>w(N.token),children:e.jsx(ke,{size:13})})]})]},N.token))]})]})}const vl={admin:Mn,editor:Tt,viewer:gs},yl={admin:"role-admin",editor:"role-editor",viewer:"role-viewer"};function bl(){const[s,t]=r.useState([]),[a,i]=r.useState(!0),[n,o]=r.useState(!1),[c,l]=r.useState(""),[x,p]=r.useState(null),[h,d]=r.useState(null),m=Re();r.useEffect(()=>{u()},[]);async function u(){i(!0);try{const C=await R.get("/workspaces");t(C.workspaces||[])}catch{p("Failed to load workspaces")}finally{i(!1)}}async function g(C){if(C.preventDefault(),!!c.trim()){o(!0);try{await R.post("/workspaces",{name:c.trim()}),l(""),await u()}catch(y){p(y.message||"Failed to create workspace")}finally{o(!1)}}}async function k(C,y){if(confirm(`Delete workspace "${y}"?`)&&confirm("This cannot be undone."))try{await R.del(`/workspaces/${C}`),await u()}catch(w){p(w.message||"Failed to delete workspace")}}function z(C){navigator.clipboard.writeText(`${window.location.origin}/accept-invite?workspace=${C}`).catch(()=>{}),d(C),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."}),x&&e.jsxs("div",{className:"settings-section-error",children:[e.jsx("span",{children:x}),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:c,onChange:C=>l(C.target.value),maxLength:64}),e.jsxs(T,{type:"submit",variant:"primary",size:"sm",loading:n,disabled:!c.trim(),children:[e.jsx(ve,{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:C,role:y})=>{const w=vl[y]||gs;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(Ys,{size:16})}),e.jsxs("div",{className:"workspace-item-details",children:[e.jsx("span",{className:"workspace-item-name",children:C.name}),e.jsxs("span",{className:H("workspace-item-role",yl[y]),children:[e.jsx(w,{size:11}),y]})]})]}),e.jsxs("div",{className:"workspace-item-actions",children:[e.jsx(T,{variant:"ghost",size:"sm",iconOnly:!0,title:"Copy invite link",onClick:()=>z(C.id),children:h===C.id?e.jsx(ps,{size:13}):e.jsx(ns,{size:13})}),y==="admin"&&e.jsx(T,{variant:"ghost",size:"sm",iconOnly:!0,title:"Manage members",onClick:()=>{m.open({title:`Manage "${C.name}"`,children:e.jsx(fl,{workspaceId:C.id,onInviteCreated:()=>u()}),width:520})},children:e.jsx(Ys,{size:13})}),y==="admin"&&s.length>1&&e.jsx(T,{variant:"ghost",size:"sm",iconOnly:!0,title:"Delete workspace",onClick:()=>k(C.id,C.name),children:e.jsx(ke,{size:13})})]})]},C.id)})]})]})}const Yt={theme:{id:"theme",label:"Theme",icon:yt,description:"Accent colors, fonts, density, and animation preferences.",render:({sp:s})=>e.jsx(hl,{...s})},updates:{id:"updates",label:"Updates",icon:oe,description:"Choose the update channel and check for new Bizar versions.",render:()=>e.jsx(si,{})},layout:{id:"layout",label:"Layout",icon:da,description:"UI layout mode, default tab, and status bar visibility.",render:({sp:s,autoSave:t})=>e.jsx(_t,{...s,autoSave:t})},general:{id:"general",label:"General",icon:bt,description:"Default agent and model overrides.",render:({sp:s,autoSave:t})=>e.jsx(_t,{...s,autoSave:t})},"env-vars":{id:"env-vars",label:"Env Vars",icon:Ke,description:"Inspect and edit environment variables exposed to agents.",render:()=>e.jsx(ei,{})},network:{id:"network",label:"Network",icon:Nt,description:"Tailscale Serve, proxy settings, and dashboard network options.",render:({sp:s,tailscale:t,tailscaleDraft:a,setTailscaleDraft:i,onTailscaleToggle:n})=>e.jsxs(e.Fragment,{children:[e.jsx(xl,{tailscale:t,tailscaleDraft:a,setTailscaleDraft:i,onTailscaleToggle:n}),e.jsx(Zn,{initialStatus:t})]})},notifications:{id:"notifications",label:"Notifications",icon:kt,description:"When the dashboard should ping you.",render:({sp:s})=>e.jsx(pl,{...s})},auth:{id:"auth",label:"Auth",icon:ma,description:"Authentication and token-bearer settings.",render:({sp:s,authStatus:t,setAuthStatus:a})=>e.jsx(gl,{settings:s.settings,authStatus:t,setAuthStatus:a})},agents:{id:"agents",label:"Agents",icon:Be,description:"Agent runner config: parallelism, stuck thresholds, autonomy.",render:({sp:s,autoSave:t})=>e.jsx(jl,{...s,autoSave:t})},"system-llm":{id:"system-llm",label:"System LLM",icon:zs,description:"LLM used by the dashboard for auto-titling and enhancements.",render:({sp:s})=>e.jsx(Jn,{...s})},headroom:{id:"headroom",label:"Headroom",icon:ua,description:"Context compression proxy settings.",render:({sp:s,setSettings:t,setDirty:a})=>e.jsx(Qn,{settings:s.settings,setSettings:t,setDirty:a})},"activity-log":{id:"activity-log",label:"Activity Log",icon:Te,description:"Per-agent activity retention and the About card.",render:({about:s})=>e.jsx(Xn,{about:s})},workspaces:{id:"workspaces",label:"Workspaces",icon:$e,description:"Manage workspace roots and shared directories.",render:()=>e.jsx(bl,{})}};function Nl({settings:s,refreshSnapshot:t,section:a="theme"}){const i=re(),[n,o]=r.useState(s),[c,l]=r.useState(!1),[x,p]=r.useState(!1),[h,d]=r.useState(null),[m,u]=r.useState({port:4321,https:!0,hostname:""}),[g,k]=r.useState(null),z=Yt[a]??Yt.theme;r.useEffect(()=>{o(s),l(!1),s.theme&&us(s.theme)},[s]),r.useEffect(()=>{h&&u({port:h.settings.port,https:h.settings.https!==!1,hostname:h.settings.hostname||""})},[h]),r.useEffect(()=>{R.get("/tailscale/status").then(d).catch(()=>{})},[]);const C=r.useRef(null),y=r.useCallback(async(_,P)=>{o(V=>({...V,[_]:P})),C.current&&clearTimeout(C.current),C.current=setTimeout(async()=>{try{await R.put("/settings",{...n,[_]:P})}catch(V){console.error("autoSave failed",V)}},300)},[n]);r.useEffect(()=>()=>{C.current&&clearTimeout(C.current)},[]);const w=_=>{o(P=>{const V={...P,theme:{...P.theme,..._}};return us(V.theme),V}),l(!0)},$=_=>{o(P=>({...P,ui:{...P.ui,..._}})),l(!0)},j=(_,P)=>{o(V=>({...V,[_]:P})),l(!0)},N=_=>{o(P=>({...P,notifications:{...P.notifications,..._}})),l(!0)},v=_=>{o(P=>({...P,agents:{...P.agents,..._}})),l(!0)},f=_=>{o(P=>({...P,dashboard:{...P.dashboard,..._}})),l(!0)},D=async()=>{try{h!=null&&h.settings.enabled?(await R.post("/tailscale/disable"),i.success("Tailscale serve disabled.")):(await R.post("/tailscale/enable",{port:m.port||4321,https:m.https,hostname:m.hostname||""}),i.success("Tailscale serve enabled.")),d(await R.get("/tailscale/status"))}catch(_){i.error(`Tailscale failed: ${_.message}`)}},M=async()=>{p(!0);try{const _=await R.put("/settings",n);o(_.data),l(!1),Cs(_.data.theme),us(_.data.theme),i.success("Settings saved."),await t()}catch(_){i.error(`Save failed: ${_.message}`)}finally{p(!1)}},b=async()=>{try{const _=await R.get("/settings");o(_.data),l(!1),Cs(_.data.theme),us(_.data.theme),i.info("Settings reloaded.",1500)}catch(_){i.error(`Reload failed: ${_.message}`)}},A=async()=>{if(confirm("Reset all settings to defaults?"))try{const _=await R.post("/settings/reset");o(_.data),l(!1),Cs(_.data.theme),us(_.data.theme),i.success("Settings reset."),await t()}catch(_){i.error(`Reset failed: ${_.message}`)}},O={settings:n,patchTheme:w,patchUi:$,patchTop:j,patchNotifications:N,patchAgents:v,patchDashboard:f},S=n.about||{version:"3.0.4",homepage:"https://github.com/DrB0rk/BizarHarness",license:"MIT"},F=z.icon;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(F,{size:18,"aria-hidden":!0})," ",z.label]}),e.jsx("p",{className:"view-subtitle",children:z.description})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs(T,{variant:"ghost",size:"sm",onClick:A,"aria-label":"Reset all settings",children:[e.jsx(ga,{size:14})," Reset"]}),e.jsxs(T,{variant:"secondary",size:"sm",onClick:b,"aria-label":"Reload settings from disk",children:[e.jsx(oe,{size:14})," Reload"]}),e.jsxs(T,{variant:"primary",size:"sm",disabled:!c||x,onClick:M,children:[x?e.jsx("span",{className:"btn-spinner"}):e.jsx(fs,{size:14,"aria-hidden":!0}),x?"Saving…":"Save"]})]})]}),e.jsx("div",{className:"settings-body","data-section":z.id,children:e.jsx("div",{id:`settings-${z.id}`,children:z.render({sp:O,autoSave:y,tailscale:h,tailscaleDraft:m,setTailscaleDraft:u,onTailscaleToggle:D,authStatus:g,setAuthStatus:k,setSettings:o,setDirty:l,about:S})})})]})}const Aa=De.memo(Nl),kl={net:{label:"Network access",icon:is,color:"blue",description:"Can make HTTP requests to external services"},fs:{label:"Filesystem",icon:be,color:"yellow",description:"Can read and write files"},config:{label:"Config access",icon:ja,color:"gray",description:"Can read and write Bizar config"},log:{label:"Logging",icon:be,color:"gray",description:"Can write to the structured log"},exec:{label:"Shell execution",icon:Ke,color:"red",description:"Can run shell commands"}};function Et({permissions:s}){return e.jsx("div",{className:"plugin-permissions","aria-label":"Required permissions",children:s.map(t=>{const a=kl[t]??{label:t,icon:Tt,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 wl({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(se,{children:s.name}),e.jsxs(ae,{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(Et,{permissions:s.permissions??[]}),e.jsxs("div",{className:"marketplace-plugin-actions",children:[e.jsx(T,{onClick:a,children:"Details"}),e.jsx(T,{variant:"primary",onClick:t,children:"Install"})]})]})}function Sl({plugin:s,onConfirm:t,onCancel:a,installing:i}){const n=Re(),o=r.useRef(null);return r.useEffect(()=>{s&&o.current!==s.id&&(o.current=s.id,n.open({title:`Install ${s.name}?`,width:560,onClose:()=>{o.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(ye,{size:16}),e.jsx("p",{children:"This plugin will run code on your machine. It requests these permissions:"})]}),e.jsx(Et,{permissions:s.permissions??[]}),e.jsxs("div",{className:"install-confirm-actions",children:[e.jsx(T,{onClick:a,disabled:i,children:"Cancel"}),e.jsx(T,{variant:"primary",onClick:t,disabled:i,children:i?"Installing...":"Install"})]})]})}))},[s,i]),null}function Cl(){var D;const s=re(),[t,a]=r.useState(null),[i,n]=r.useState(""),[o,c]=r.useState(null),[l,x]=r.useState(null),[p,h]=r.useState(null),[d,m]=r.useState(!0),[u,g]=r.useState(!1),[k,z]=r.useState(null),C=r.useCallback(async(M={})=>{M.refresh?g(!0):m(!0),z(null);try{const b=await R.get("/plugins/registry");a(b)}catch(b){const A=b,O=A==null?void 0:A.data,S=O==null?void 0:O.registryUrl,F=(A==null?void 0:A.message)||"unknown error";z({message:F,url:S}),s.error(`Failed to load marketplace: ${F}`)}finally{m(!1),g(!1)}},[s]);r.useEffect(()=>{C()},[C]);const y=async M=>{x(M);try{await R.post("/plugins/install",{pluginId:M.id}),s.success(`${M.name} installed`),x(null),h(null)}catch(b){s.error(`Install failed: ${b.message}`),x(null)}},w=(t==null?void 0:t.plugins)??[],$=w.filter(M=>(!i||M.name.toLowerCase().includes(i.toLowerCase()))&&(!o||M.category===o)),j=[...new Set(w.map(M=>M.category))],N=(D=t==null?void 0:t.registry)==null?void 0:D.source,v=!!(t!=null&&t.cached),f=(t==null?void 0:t.cacheTimestamp)??null;return d?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(hs,{size:18,"aria-hidden":!0}),"Plugin Marketplace"]}),e.jsx("p",{className:"view-subtitle",children:"Fetching registry from the community server…"})]})}),e.jsxs("div",{className:"view-loading","data-testid":"marketplace-loading",children:[e.jsx(le,{size:"lg"}),e.jsxs("p",{children:["Fetching registry from ",e.jsx("code",{children:N??"https://github.com/DrB0rk/bizar-mods"}),"…"]})]})]}):k?e.jsxs("div",{className:"view view-marketplace",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(hs,{size:18,"aria-hidden":!0}),"Plugin Marketplace"]}),e.jsx("p",{className:"view-subtitle",children:"Couldn't reach the community registry."})]}),e.jsx("div",{className:"view-actions",children:e.jsxs(T,{variant:"secondary",size:"sm",onClick:()=>C({refresh:!0}),disabled:u,children:[u?e.jsx(le,{size:"sm"}):e.jsx(oe,{size:14}),"Retry"]})})]}),e.jsx(he,{icon:e.jsx(ye,{size:32}),title:"Registry unreachable",message:e.jsxs(e.Fragment,{children:[e.jsx("p",{children:"All registry URLs failed to respond."}),k.url&&e.jsxs("p",{className:"mono muted",style:{marginTop:8,fontSize:12},children:["Last tried: ",k.url]}),e.jsx("p",{className:"muted",style:{marginTop:8,fontSize:12},children:k.message})]}),action:e.jsxs(T,{variant:"primary",size:"sm",onClick:()=>C({refresh:!0}),disabled:u,children:[u?e.jsx(le,{size:"sm"}):e.jsx(oe,{size:14})," Try again"]})})]}):e.jsxs("div",{className:"view view-marketplace",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(hs,{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:"view-actions",children:e.jsxs(T,{variant:"secondary",size:"sm",onClick:()=>C({refresh:!0}),disabled:u,"data-testid":"marketplace-refresh",children:[u?e.jsx(le,{size:"sm"}):e.jsx(oe,{size:14}),"Refresh"]})})]}),e.jsxs("div",{className:"marketplace-source-banner muted","data-testid":"marketplace-source",children:[e.jsx(is,{size:12,"aria-hidden":!0}),e.jsxs("span",{children:["Source:"," ",N?e.jsx("code",{className:"mono",children:N}):e.jsx("span",{children:"community registry"})]}),v&&e.jsxs("span",{className:"marketplace-cache-notice","data-testid":"marketplace-cache-notice",children:[e.jsx(Ge,{size:12,"aria-hidden":!0})," Showing cached results",f&&` from ${new Date(f).toLocaleString()}`]}),e.jsxs("span",{className:"marketplace-count-pill","data-testid":"marketplace-count",children:[w.length," plugin",w.length===1?"":"s"]})]}),e.jsx("div",{className:"marketplace-search-row",children:e.jsx("input",{className:"input",type:"search",placeholder:"Search plugins...",value:i,onChange:M=>n(M.target.value),style:{maxWidth:320},"aria-label":"Search marketplace plugins"})}),j.length>0&&e.jsxs("div",{className:"category-chips",children:[e.jsx("button",{type:"button",onClick:()=>c(null),className:o?"":"active","data-testid":"marketplace-category-all",children:"All"}),j.map(M=>e.jsx("button",{type:"button",onClick:()=>c(M),className:o===M?"active":"","data-testid":`marketplace-category-${M.toLowerCase().replace(/\s+/g,"-")}`,children:M},M))]}),$.length===0?e.jsx(he,{icon:w.length===0?e.jsx(Nt,{size:32}):e.jsx(hs,{size:32}),title:w.length===0?"No plugins published yet":"No plugins match your filter",message:w.length===0?e.jsxs(e.Fragment,{children:[e.jsx("p",{children:"The community registry is empty right now."}),N&&e.jsxs("p",{className:"mono muted",style:{marginTop:8,fontSize:12},children:["Check back at ",e.jsx("code",{children:N})," later, or publish your own."]})]}):i?`No plugins match "${i}".`:o?`No plugins in "${o}".`:"Try a different search or category filter.",action:w.length===0?e.jsxs(T,{variant:"secondary",size:"sm",onClick:()=>C({refresh:!0}),disabled:u,children:[u?e.jsx(le,{size:"sm"}):e.jsx(oe,{size:14})," Refresh"]}):null}):e.jsx("div",{className:"marketplace-grid","data-testid":"marketplace-grid",children:$.map(M=>e.jsx(wl,{plugin:M,onInstall:()=>h(M),onView:()=>h(M)},M.id))}),p&&e.jsx(Sl,{plugin:p,onConfirm:()=>y(p),onCancel:()=>h(null),installing:(l==null?void 0:l.id)===p.id||!1})]})}function zl({snapshot:s,refreshSnapshot:t}){const a=re(),i=Re(),[n,o]=r.useState(Array.isArray(s.mods)?s.mods:[]),[c,l]=r.useState(!0),[x,p]=r.useState(null),[h,d]=r.useState([]),[m,u]=r.useState(null),[g,k]=r.useState(!1),[z,C]=r.useState(null),[y,w]=r.useState(!1),[$,j]=r.useState({}),N=async()=>{var S,F,_;w(!0);try{const P=await R.get("/mods/registry");C({source:((S=P.registry)==null?void 0:S.source)||"",version:(F=P.registry)==null?void 0:F.version,updatedAt:(_=P.registry)==null?void 0:_.updatedAt,mods:P.mods||[]})}catch(P){C({source:"",mods:[],error:P.message})}finally{w(!1)}},v=async S=>{j(F=>({...F,[S]:!0}));try{const F=await R.post("/mods",{id:S});o(_=>[..._.filter(P=>P.id!==F.id),F]),a.success(`Mod "${F.id}" installed from registry.`),await t()}catch(F){a.error(`Install failed: ${F.message}`)}finally{j(F=>({...F,[S]:!1}))}},f=async(S,F=!1)=>{j(_=>({..._,[S]:!0}));try{const _=await R.post(`/mods/${encodeURIComponent(S)}/upgrade`,{backup:F});o(V=>[...V.filter(W=>W.id!==_.mod.id),_.mod]);const P=_.backupPath?` (backup at ${_.backupPath})`:"";a.success(`Mod "${S}" upgraded v${_.from} → v${_.to}${P}.`),await t()}catch(_){a.error(`Upgrade failed: ${_.message}`)}finally{j(_=>({..._,[S]:!1}))}},D=async()=>{try{const S=await R.get("/mods");o(S.mods||[]);try{const F=await R.get("/mods/views");d(F.views||[])}catch{d([])}}catch(S){a.error(`Mods load failed: ${S.message}`)}finally{l(!1)}};r.useEffect(()=>{D()},[]),r.useEffect(()=>{Array.isArray(s.mods)&&s.mods!==n&&o(s.mods)},[s.mods]);const M=()=>{let S=null;i.open({title:"Install mod",children:e.jsxs("div",{children:[e.jsxs("p",{className:"muted",children:["Provide the absolute path to a mod folder (one that contains a ",e.jsx("code",{children:"mod.json"}),"). The folder will be copied to"," ",e.jsx("code",{children:"~/.config/bizar/mods/<id>/"}),"."]}),e.jsx("label",{className:"field-label",htmlFor:"install-mod-path",children:"Path"}),e.jsx("input",{id:"install-mod-path",ref:F=>S=F,className:"input",type:"text",placeholder:"/path/to/my-mod",autoFocus:!0})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx(T,{variant:"ghost",onClick:()=>i.close(),children:"Cancel"}),e.jsx(T,{variant:"primary",onClick:async()=>{const F=((S==null?void 0:S.value)||"").trim();if(!F){a.warning("Path is required.");return}try{const _=await R.post("/mods",{path:F});o(P=>[...P,_]),a.success(`Mod "${_.id}" installed.`),i.close(),await t()}catch(_){a.error(`Install failed: ${_.message}`)}},children:"Install"})]})})},b=async S=>{if(confirm(`Uninstall mod "${S}"? This removes the folder from ~/.config/bizar/mods/.`))try{await R.del(`/mods/${encodeURIComponent(S)}`),o(F=>F.filter(_=>_.id!==S)),x===S&&p(null),a.success("Mod uninstalled.")}catch(F){a.error(`Uninstall failed: ${F.message}`)}},A=async S=>{try{const F=await R.put(`/mods/${encodeURIComponent(S.id)}`,{enabled:!S.enabled});o(_=>_.map(P=>P.id===S.id?F:P)),a.success(`Mod ${F.enabled?"enabled":"disabled"}.`)}catch(F){a.error(`Toggle failed: ${F.message}`)}},O=n.find(S=>S.id===x)||null;return c?e.jsx("div",{className:"view-loading",children:e.jsx(le,{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(ss,{size:18})," Mods (",n.length,")"]}),e.jsxs("p",{className:"view-subtitle",children:["Extensions installed in ",e.jsx("code",{children:"~/.config/bizar/mods/"}),". Mods can add agents, commands, routes, and views."]})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs(T,{variant:"secondary",size:"sm",onClick:D,children:[e.jsx(oe,{size:14})," Refresh"]}),e.jsxs(T,{variant:"primary",size:"sm",onClick:M,children:[e.jsx(ve,{size:14})," Install mod"]})]})]}),n.length===0?e.jsx(he,{icon:e.jsx(ss,{size:32}),title:"No mods installed",message:"Mods are folders with a mod.json. Install one to extend Bizar with custom agents, commands, and views."}):e.jsxs("div",{className:"mods-layout",children:[e.jsx("div",{className:"mods-list",children:n.map(S=>e.jsxs("div",{className:H("mod-list-item",x===S.id&&"mod-list-item-active"),onClick:()=>p(S.id),children:[e.jsxs("div",{className:"mod-list-item-head",children:[e.jsxs("div",{children:[e.jsx("div",{className:"mod-list-item-name",children:S.name}),e.jsxs("div",{className:"mod-list-item-meta",children:["v",S.version," · ",S.type," · ",S.author]})]}),e.jsxs("div",{className:"mod-list-item-actions",onClick:F=>F.stopPropagation(),children:[e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Toggle enabled",title:S.enabled?"Disable":"Enable",onClick:()=>A(S),children:e.jsx(St,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger","aria-label":"Uninstall",title:"Uninstall",onClick:()=>b(S.id),children:e.jsx(ke,{size:12})})]})]}),e.jsx("div",{className:"mod-list-item-desc ellipsis-2",title:S.description,children:S.description}),e.jsx("div",{className:"mod-list-item-status",children:e.jsx("span",{className:`mod-mini-pill ${S.enabled?"mod-mini-pill-on":"mod-mini-pill-off"}`,children:S.enabled?"enabled":"disabled"})})]},S.id))}),O&&e.jsx(Rl,{mod:O})]}),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&&!y&&N(),k(S=>!S)},children:[e.jsx(is,{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(Ue,{size:14,"aria-hidden":!0}):e.jsx(Xe,{size:14,"aria-hidden":!0})]}),g&&e.jsx("div",{id:"mods-registry-body",className:"mods-registry-body",children:y?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($s,{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(S=>{const F=n.some(P=>P.id===S.id),_=!!$[S.id];return e.jsxs("div",{className:"mod-registry-card",children:[e.jsxs("div",{className:"mod-registry-card-head",children:[e.jsx("div",{className:"mod-registry-card-name",children:S.name}),S.latest&&e.jsxs("span",{className:H("mod-registry-version",S.upgradeAvailable&&"mod-registry-version-upgrade"),children:["v",S.latest,S.upgradeAvailable?" ↑":""]})]}),S.description&&e.jsx("div",{className:"mod-registry-card-desc",children:S.description}),e.jsxs("div",{className:"mod-registry-card-meta",children:[S.author&&e.jsxs("span",{className:"muted",children:["by ",S.author]}),S.homepage&&e.jsx("a",{href:S.homepage,target:"_blank",rel:"noopener noreferrer",className:"mod-registry-link",children:"homepage"})]}),(S.permissions||[]).length>0&&e.jsxs("div",{className:"mod-registry-perms",children:[e.jsx($s,{size:10}),(S.permissions||[]).slice(0,4).map(P=>e.jsx("span",{className:"mod-registry-perm",children:P},P)),(S.permissions||[]).length>4&&e.jsxs("span",{className:"mod-registry-perm-more",children:["+",S.permissions.length-4]})]}),e.jsxs("div",{className:"mod-registry-card-actions",children:[!F&&e.jsx(T,{variant:"primary",size:"sm",disabled:_,onClick:()=>v(S.id),title:"Install from registry",children:_?e.jsx(le,{size:"sm"}):e.jsxs(e.Fragment,{children:[e.jsx(as,{size:12})," Install"]})}),F&&S.upgradeAvailable&&e.jsx(T,{variant:"primary",size:"sm",disabled:_,onClick:()=>f(S.id),title:`Upgrade from v${S.installedVersion||"?"} to v${S.upgradeAvailable}`,children:_?e.jsx(le,{size:"sm"}):e.jsxs(e.Fragment,{children:[e.jsx(as,{size:12})," Upgrade to v",S.upgradeAvailable]})}),F&&!S.upgradeAvailable&&e.jsxs(T,{variant:"ghost",size:"sm",disabled:!0,title:`Installed v${S.installedVersion||"?"}`,children:["Installed v",S.installedVersion||"?"]})]})]},S.id)})})]})})]}),h.length>0&&e.jsxs(G,{className:"mod-views-hint",children:[e.jsxs(se,{children:[e.jsx(is,{size:14})," Mod views"]}),e.jsxs(ae,{children:[h.length," mod-supplied view",h.length===1?"":"s"," are now available in the sidebar navigation. Look for the ",e.jsx("strong",{children:"Mods"})," section at the bottom of the sidebar."]})]}),m&&e.jsxs("div",{className:"mod-iframe-panel",children:[e.jsxs("div",{className:"mod-iframe-header",children:[e.jsxs("span",{children:["Mod view — ",e.jsx("a",{href:m,target:"_blank",rel:"noreferrer",children:m})]}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Close iframe",onClick:()=>u(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 Rl({mod:s}){const t=re(),[a,i]=r.useState(null),[n,o]=r.useState(!1),[c,l]=r.useState(!1),[x,p]=r.useState(null),h=async()=>{o(!0);try{const m=await R.get(`/mods/${s.id}/instructions`);i(m),l(!0)}catch(m){t.error(`Failed to load instructions: ${m.message}`)}finally{o(!1)}},d=async()=>{try{const m=await R.post(`/mods/${s.id}/instructions/reinstall`,{});t.success(`Reinstalled: ${m.counts.agents} agents, ${m.counts.commands} commands, ${m.counts.skills} skills, ${m.counts.instructions} instructions.`),await h()}catch(m){t.error(`Reinstall failed: ${m.message}`)}};return e.jsxs(G,{className:"mod-details",children:[e.jsxs(se,{children:[e.jsx(be,{size:14})," Mod details — ",s.name]}),e.jsx(ae,{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":c,"aria-controls":`mod-instructions-body-${s.id}`,onClick:()=>{!a&&!n&&h(),l(m=>!m)},children:[e.jsx(Ln,{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"}),c?e.jsx(Ue,{size:14,"aria-hidden":!0}):e.jsx(Xe,{size:14,"aria-hidden":!0})]}),c&&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(En,{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(u=>u===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]})]}),x===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(Ke,{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(u=>u===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]})]}),x===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(fa,{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(u=>u===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]})]}),x===m.name&&e.jsx("pre",{className:"mod-instructions-content",children:m.content||e.jsx("em",{className:"muted",children:"(file missing on disk)"})})]},m.name))]}),a.total===0&&e.jsxs("div",{className:"muted",style:{padding:8,fontSize:12},children:["This mod did not install any instruction files. Mods install instructions by shipping a top-level ",e.jsx("code",{children:"INSTRUCTIONS.md"}),", an ",e.jsx("code",{children:"agents/"})," directory, a ",e.jsx("code",{children:"commands/"})," directory, or a ",e.jsx("code",{children:"skills/"})," directory."]}),e.jsx("div",{className:"mod-instructions-actions",children:e.jsxs(T,{variant:"ghost",size:"sm",onClick:d,children:[e.jsx(oe,{size:11})," Reinstall from mod folder"]})})]})]})]})}const Tl=r.forwardRef(function({className:t,checked:a,onChange:i,onClick:n,...o},c){return e.jsxs("label",{className:H("toggle",t),children:[e.jsx("input",{ref:c,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)},...o}),e.jsx("span",{className:"toggle-slider","aria-hidden":!0})]})});function $l({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(se,{children:s.name}),e.jsxs(ae,{children:["v",s.version," · ",s.id]})]}),e.jsx(Tl,{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(Et,{permissions:s.permissions??[]}),e.jsxs("div",{className:"plugin-card-actions",children:[e.jsx(T,{size:"sm",onClick:()=>i(s.id),"aria-label":`Configure ${s.name}`,children:"Configure"}),e.jsx(T,{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 Al({setActiveTab:s}){const t=re(),[a,i]=r.useState([]),[n,o]=r.useState(!0),[c,l]=r.useState(""),x=async()=>{try{const u=await R.get("/plugins/installed");i(u.plugins)}catch(u){t.error(`Failed to load plugins: ${u.message}`)}finally{o(!1)}};r.useEffect(()=>{x()},[]);const p=async u=>{try{await R.post(`/plugins/${u}/toggle`).catch(()=>{}),await x(),t.success("Plugin toggled.")}catch(g){t.error(`Toggle failed: ${g.message}`)}},h=async u=>{if(confirm("Uninstall this plugin?"))try{await R.del(`/plugins/${u}`),await x(),t.success("Plugin uninstalled.")}catch(g){t.error(`Uninstall failed: ${g.message}`)}},d=u=>{};if(n)return e.jsx("div",{className:"view-loading",children:e.jsx(le,{size:"lg"})});const m=a.filter(u=>u.name.toLowerCase().includes(c.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(ss,{size:18,"aria-hidden":!0}),"Plugins (",a.length,")"]}),e.jsx("p",{className:"view-subtitle",children:"Manage plugins installed via the marketplace."})]}),e.jsxs(T,{variant:"secondary",size:"sm",onClick:()=>s("marketplace"),children:[e.jsx(hs,{size:14,"aria-hidden":!0}),"Browse Marketplace"]})]}),a.length===0?e.jsx(he,{icon:e.jsx(ss,{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:c,onChange:u=>l(u.target.value),"aria-label":"Filter plugins",style:{maxWidth:320}})}),e.jsx("div",{className:"plugin-grid",children:m.map(u=>e.jsx($l,{plugin:u,onToggle:p,onUninstall:h,onConfigure:d},u.id))})]})]})}function Il({viewId:s,reloadKey:t,setActiveTab:a}){const i=re(),[n,o]=r.useState(null),[c,l]=r.useState(!0),[x,p]=r.useState(0);if(r.useEffect(()=>{let h=!1;return(async()=>{try{const d=await R.get("/mods/views");if(h)return;const m=(d.views||[]).find(u=>u.id===s);o(m||null)}catch(d){i.error(`Failed to load mod view: ${d.message}`)}finally{h||l(!1)}})(),()=>{h=!0}},[s,i]),c)return e.jsx(he,{title:"Loading mod view…"});if(!n)return e.jsx(he,{title:"Mod view not found",message:`No view with id "${s}" is currently installed.`,action:e.jsx(T,{onClick:()=>a("mods"),variant:"primary",size:"sm",children:"Open Mods"})});if(n.kind==="iframe"){const h=`/api/mods/${n.modId}/web/index.html?t=${x+(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(is,{size:14}),n.label,e.jsxs("span",{className:"muted",style:{fontSize:11,fontWeight:400},children:["by ",n.modId]})]}),e.jsxs("div",{className:"mod-view-iframe-actions",children:[e.jsxs(T,{variant:"ghost",size:"sm",onClick:()=>p(d=>d+1),title:"Reload this view",children:[e.jsx(oe,{size:11})," Reload"]}),e.jsx("a",{href:h,target:"_blank",rel:"noopener noreferrer",className:"icon-btn",title:"Open in new tab",children:e.jsx(vs,{size:12})})]})]}),e.jsx("iframe",{src:h,className:"mod-view-iframe",title:n.label},x+(t||0))]})}if(n.component){const h=n.component,d=n.modId,m=r.lazy(()=>Qa(()=>import(`/api/mods/${encodeURIComponent(d)}/views/${encodeURIComponent(h)}`),[]).then(u=>({default:u.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(As,{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(Ml,{modId:n.modId,component:n.component,children:e.jsx(r.Suspense,{fallback:e.jsxs("div",{style:{padding:24},children:[e.jsx(le,{size:"md"})," ",e.jsx("span",{className:"muted",children:"Loading mod view…"})]}),children:e.jsx(m,{})})})})]})}return e.jsxs(G,{children:[e.jsxs(se,{children:[e.jsx(As,{size:14})," ",n.label]}),e.jsxs(ae,{children:["by ",n.modId]}),n.description&&e.jsx("p",{className:"muted",style:{marginTop:8},children:n.description}),e.jsxs("p",{className:"muted",style:{fontSize:12,marginTop:12},children:["This mod declared a tab view but did not provide a component path in views/registry.json. Add a ",e.jsx("code",{children:"component"})," field (e.g. ",e.jsx("code",{children:'"MyView.js"'}),") and ship the file under ",e.jsx("code",{children:"views/"}),"."]}),e.jsx("div",{style:{marginTop:12},children:e.jsx(T,{variant:"secondary",size:"sm",onClick:()=>a("mods"),children:"Open Mods page"})})]})}class Ml extends r.Component{constructor(){super(...arguments);bs(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(ye,{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 Ll(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 El({template:s,onUse:t}){return e.jsxs(G,{className:"schedule-template-card",children:[e.jsxs("div",{className:"schedule-template-header",children:[e.jsx(se,{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(ae,{children:s.description}),e.jsxs("div",{className:"schedule-template-summary",children:[e.jsx("code",{children:Ll(s)})," · ",e.jsx("code",{children:s.action.type})]}),e.jsx(T,{variant:"secondary",size:"sm",onClick:()=>t(s),"aria-label":`Use template: ${s.name}`,children:"Use this template"})]})}const Dl=["interval","cron","once"],Pl=["command","agent","webhook"],jt=[{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)"}],Fl=Array.from({length:12},(s,t)=>t*5),Dt=Array.from({length:24},(s,t)=>({value:t,label:t===0?"12 AM":t<12?`${t} AM`:t===12?"12 PM":`${t-12} PM`})),Pt=[{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"}],Ia=[{value:"s",label:"seconds"},{value:"m",label:"minutes"},{value:"h",label:"hours"},{value:"d",label:"days"}];function Ma(s){if(typeof s!="string")return null;const t=s.trim().split(/\s+/);if(t.length!==5)return null;const[a,i,,,n]=t,o=parseInt(a,10),c=parseInt(i,10);if(!Number.isFinite(o)||!Number.isFinite(c)||a!==String(o)||i!==String(c))return null;const l=n==="*"?"*":parseInt(n,10);return l===null||n!=="*"&&!Number.isFinite(l)?null:{minute:o,hour:c,dow:n==="*"?"*":String(l)}}function Ol(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 Ul(s){var o,c;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"?Ma(s.schedule):null,a=s.type==="interval"?Ol(s.schedule):null,i=s.timezone||"UTC",n=jt.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"?Bl(s.schedule):"",timezone:n?i:"Other…",customTimezone:n?"":i,actionType:s.action.type,actionTarget:s.action.target||"",actionPrompt:s.action.prompt||"",skipIfBudgetLow:!!((o=s.budgetCheck)!=null&&o.skipIfBudgetLow),maxConcurrent:Number.isFinite((c=s.budgetCheck)==null?void 0:c.maxConcurrent)?s.budgetCheck.maxConcurrent:6,enabled:s.enabled!==!1,humanLabel:""}}function Bl(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 _l(s){var a,i,n;if(s.type==="cron"){if(s.showAdvanced)return{schedule:s.rawCron.trim(),humanLabel:s.humanLabel||s.rawCron.trim()};const o=`${s.cronMinute} ${s.cronHour} * * ${s.cronDow}`,c=((a=Pt.find(h=>h.value===s.cronDow))==null?void 0:a.label)||"",l=((i=Dt.find(h=>h.value===s.cronHour))==null?void 0:i.label)||`${s.cronHour}`,x=String(s.cronMinute).padStart(2,"0"),p=c==="Every day"?`Every day at ${l.replace(" ","")} (min ${x})`:`Every ${c} at ${l.replace(" ","")} (min ${x})`;return{schedule:o,humanLabel:s.humanLabel||p}}if(s.type==="interval"){const o=((n=Ia.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} ${o}`}}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 $;const a=re(),i=Re(),[n,o]=r.useState(s.schedules||[]),[c,l]=r.useState(!s.schedules),[x,p]=r.useState("schedules"),[h,d]=r.useState([]),[m,u]=r.useState(!1),g=async()=>{try{const j=await R.get("/projects/active/schedules");o(j.schedules||[])}catch(j){a.error(`Schedules load failed: ${j.message}`)}finally{l(!1)}},k=async()=>{u(!0);try{const j=await R.get("/schedules/templates");d(j.templates||[])}catch(j){a.error(`Templates load failed: ${j.message}`)}finally{u(!1)}};r.useEffect(()=>{var j;if((j=s.schedules)!=null&&j.length||s.schedules){o(s.schedules||[]),l(!1);return}g()},[s.schedules]),r.useEffect(()=>{x==="templates"&&h.length===0&&k()},[x]);const z=j=>{i.open({title:j?`Edit schedule: ${j.name}`:"New schedule",width:640,children:e.jsx(Wl,{initial:j,onClose:i.close,onSubmitted:async N=>{o(v=>{const f=v.findIndex(M=>M.id===N.id);if(f===-1)return[...v,N];const D=v.slice();return D[f]=N,D}),a.success(j?"Schedule updated.":"Schedule created."),i.close(),await t()},onError:N=>a.error(N)})})},C=async j=>{var N;try{const v=await R.post(`/schedules/${encodeURIComponent(j.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}`)}},y=async j=>{if(confirm(`Delete schedule "${j.name}"?`))try{await R.del(`/schedules/${encodeURIComponent(j.id)}`),o(N=>N.filter(v=>v.id!==j.id)),a.success("Schedule deleted.")}catch(N){a.error(`Delete failed: ${N.message}`)}},w=async j=>{try{const N=await R.post("/schedules/from-template",{templateId:j.id});o(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 c?e.jsx("div",{className:"view-loading",children:e.jsx(le,{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(Ge,{size:18})," Schedules"]}),e.jsxs("div",{className:"view-section-tabs",children:[e.jsxs("button",{type:"button",className:`tab-btn ${x==="schedules"?"tab-btn-active":""}`,onClick:()=>p("schedules"),children:["Schedules (",n.length,")"]}),e.jsxs("button",{type:"button",className:`tab-btn ${x==="templates"?"tab-btn-active":""}`,onClick:()=>p("templates"),children:[e.jsx(As,{size:14})," Templates"]})]})]}),e.jsx("p",{className:"view-subtitle",children:x==="schedules"?e.jsxs(e.Fragment,{children:["Recurring tasks for ",e.jsx("strong",{children:(($=s.activeProject)==null?void 0:$.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:[x==="schedules"&&e.jsxs(e.Fragment,{children:[e.jsxs(T,{variant:"secondary",size:"sm",onClick:g,"aria-label":"Refresh schedules",children:[e.jsx(oe,{size:14})," Refresh"]}),e.jsxs(T,{variant:"primary",size:"sm",onClick:()=>z(),children:[e.jsx(ve,{size:14})," New schedule"]})]}),x==="templates"&&e.jsxs(T,{variant:"secondary",size:"sm",onClick:k,disabled:m,children:[e.jsx(oe,{size:14})," Refresh"]})]})]}),x==="templates"?m?e.jsx("div",{className:"view-loading",children:e.jsx(le,{size:"lg"})}):h.length===0?e.jsx(he,{icon:e.jsx(As,{size:32}),title:"No templates",message:"No schedule templates found. Templates are loaded from templates/schedules/."}):e.jsx("div",{className:"schedule-template-grid",children:h.map(j=>e.jsx(El,{template:j,onUse:w},j.id))}):n.length===0?e.jsx(he,{icon:e.jsx(Ge,{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(j=>{var N;return e.jsxs(G,{className:"schedule-card",children:[e.jsxs("div",{className:"schedule-card-head",children:[e.jsxs("div",{children:[e.jsx(se,{children:j.name}),e.jsxs(ae,{children:[e.jsx("code",{children:j.type})," ·"," ",e.jsx("span",{title:j.schedule,children:Vl(j)||j.schedule}),j.timezone&&j.timezone!=="UTC"?e.jsxs(e.Fragment,{children:[" · ",e.jsx("code",{children:j.timezone})]}):null," · ",e.jsx("span",{className:j.enabled?"status-on":"status-neutral",children:j.enabled?"enabled":"disabled"})]})]}),e.jsxs("div",{className:"schedule-card-actions",children:[e.jsxs(T,{variant:"secondary",size:"sm",onClick:()=>z(j),children:[e.jsx(Is,{size:12})," Edit"]}),e.jsxs(T,{variant:"secondary",size:"sm",onClick:()=>C(j),children:[e.jsx(xt,{size:12})," Run now"]}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger","aria-label":"Delete",title:"Delete",onClick:()=>y(j),children:e.jsx(ke,{size:12})})]})]}),e.jsxs("div",{className:"schedule-card-action",children:[e.jsx("span",{className:"muted",children:"action:"})," ",e.jsxs("code",{children:[j.action.type," ",j.action.target]}),j.action.type==="agent"&&j.action.prompt&&e.jsxs("div",{className:"schedule-card-prompt",children:[e.jsx("span",{className:"muted",children:"prompt:"})," ",j.action.prompt]})]}),((N=j.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 ≥ ",j.budgetCheck.maxConcurrent??6]}),e.jsxs("div",{className:"schedule-card-times",children:[e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"last"})," ",j.lastRun?ze(j.lastRun):"—",j.lastResult&&e.jsx("span",{className:`tag ${Xt(j.lastResult)}`,children:j.lastResult}),j.lastError&&e.jsxs("span",{className:"muted schedule-card-error",title:j.lastError,children:[" ","— ",Qt(j.lastError,80)]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"next"})," ",j.nextRun?e.jsx("span",{title:new Date(j.nextRun).toISOString(),children:Hl(j.nextRun,j.timezone)}):"—",j.nextRun&&e.jsxs("span",{className:"muted",children:[" · ",ze(j.nextRun)]})]})]}),j.history&&j.history.length>0&&e.jsxs("details",{className:"schedule-card-history",children:[e.jsxs("summary",{children:[e.jsx(Ts,{size:12})," ",j.history.length," run",j.history.length===1?"":"s"]}),e.jsx("ul",{children:j.history.slice(-10).reverse().map((v,f)=>e.jsxs("li",{children:[e.jsx("span",{className:"tabular-nums muted",children:ze(v.ts)})," ",e.jsx("span",{className:`tag ${Xt(v.result)}`,children:v.result}),v.error&&e.jsxs("span",{className:"muted",children:[" — ",Qt(v.error,80)]})]},f))})]})]},j.id)})})]})}function Wl({initial:s,onClose:t,onSubmitted:a,onError:i}){const[n,o]=r.useState(()=>Ul(s)),[c,l]=r.useState(!1),x=r.useMemo(()=>jt.some(d=>d.value===n.timezone)?n.timezone:"Other…",[n.timezone]),p=(d,m)=>{o(u=>({...u,[d]:m}))},h=async d=>{d.preventDefault();const m=n.name.trim();if(!m){i("Name is required.");return}const u=_l(n);if(!u.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,k={type:n.actionType,target:n.actionTarget.trim()};n.actionType==="agent"&&n.actionPrompt.trim()&&(k.prompt=n.actionPrompt.trim());const z={name:m,type:n.type,schedule:u.schedule,timezone:g||"UTC",action:k,budgetCheck:{maxConcurrent:n.maxConcurrent,skipIfBudgetLow:n.skipIfBudgetLow},enabled:n.enabled};l(!0);try{const C=s?await R.put(`/schedules/${encodeURIComponent(s.id)}`,z):await R.post("/schedules",z);await a(C)}catch(C){i(`${s?"Update":"Create"} failed: ${C.message}`)}finally{l(!1)}};return e.jsxs("form",{className:"schedule-form",onSubmit:h,children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-name",children:"Name"}),e.jsx("input",{id:"schedule-name",className:"input",type:"text",placeholder:"Weekly code review",value:n.name,onChange:d=>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:Dl.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:Pt.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:Dt.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:Fl.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(Ue,{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:Ia.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:x,onChange:d=>p("timezone",d.target.value),children:[jt.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:Pl.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(T,{variant:"ghost",type:"button",onClick:t,disabled:c,children:"Cancel"}),e.jsx(T,{variant:"primary",type:"submit",disabled:c,children:s?"Save":"Create"})]})]})}function Vl(s){var o,c;if(s.type!=="cron")return s.schedule;const t=Ma(s.schedule);if(!t)return s.schedule;const a=((o=Pt.find(l=>l.value===t.dow))==null?void 0:o.label)||"",i=((c=Dt.find(l=>l.value===t.hour))==null?void 0:c.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 Hl(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 Xt(s){return s==="success"?"tag-success":s==="skipped"?"tag-warning":"tag-error"}function Qt(s,t){return s.length<=t?s:s.slice(0,t-1)+"…"}const Gl=[{id:"all",label:"All",icon:We},{id:"shipped",label:"Shipped",icon:At},{id:"user",label:"User",icon:Ys},{id:"project",label:"Project",icon:$e}],Ws={shipped:"Shipped",user:"User",project:"Project"},Kl={shipped:At,user:Ys,project:$e};function Yl({snapshot:s,refreshSnapshot:t}){const a=re(),i=Re(),[n,o]=r.useState([]),[c,l]=r.useState({shipped:0,user:0,project:0,all:0}),[x,p]=r.useState(!0),[h,d]=r.useState("all"),[m,u]=r.useState(""),[g,k]=r.useState(null),[z,C]=r.useState(!1),y=async()=>{var N,v,f;p(!0);try{const D=await R.get("/skills");o(D.skills||[]),l({shipped:((N=D.counts)==null?void 0:N.shipped)??0,user:((v=D.counts)==null?void 0:v.user)??0,project:((f=D.counts)==null?void 0:f.project)??0,all:(D.skills||[]).length})}catch(D){a.error(`Skills load failed: ${D.message}`)}finally{p(!1)}};r.useEffect(()=>{y()},[]),r.useEffect(()=>{if(!m.trim()){k(null);return}C(!0);const N=setTimeout(async()=>{try{const v=await R.get(`/skills/search?q=${encodeURIComponent(m.trim())}`);k(v.results||[])}catch(v){a.error(`Search failed: ${v.message}`)}finally{C(!1)}},280);return()=>clearTimeout(N)},[m]);const w=r.useMemo(()=>g!==null?g:h==="all"?n:n.filter(N=>N.source===h),[n,h,g]),$=async()=>{try{await R.post("/skills/refresh",{}),a.success("Skills refreshed."),await y()}catch(N){a.error(`Refresh failed: ${N.message}`)}},j=async N=>{try{const v=await R.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:Ws[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(T,{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:Ws[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(T,{variant:"ghost",onClick:()=>i.close(),children:"Close"})})}};return e.jsxs("div",{className:"view view-skills",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(We,{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(Se,{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=>u(N.target.value),"aria-label":"Search skills"}),m&&e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Clear search",onClick:()=>u(""),children:e.jsx(Ms,{size:12})})]}),e.jsxs(T,{variant:"secondary",size:"sm",onClick:$,children:[e.jsx(oe,{size:14})," Refresh"]})]})]}),!m.trim()&&e.jsx("div",{className:"skills-tabs",children:Gl.map(N=>{const v=N.icon,f=N.id==="all"?c.all:c[N.id]??0;return e.jsxs("button",{type:"button",className:H("skills-tab",h===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:f})]},N.id)})}),m.trim()&&e.jsxs("section",{className:"skills-section",children:[e.jsxs("h3",{className:"skills-section-title",children:[e.jsx(Se,{size:14})," Search results",z&&e.jsx(le,{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(he,{icon:e.jsx(Se,{size:28}),title:"No matches",message:`No skills match "${m}".`}):e.jsx("div",{className:"skills-grid",children:(g||[]).map((N,v)=>e.jsx(Jt,{skill:N,onShow:()=>j(N),searchQ:m},`search-${v}`))})]}),!m.trim()&&e.jsx("section",{className:"skills-section",children:x?e.jsx("div",{className:"view-loading",children:e.jsx(le,{size:"lg"})}):w.length===0?e.jsx(he,{icon:e.jsx(fa,{size:28}),title:"No skills here",message:h==="all"?"No skills found. Install skills with the skills CLI or add SKILL.md files to a skills directory.":`No skills in the ${Ws[h]} tab.`}):e.jsx("div",{className:"skills-grid",children:w.map((N,v)=>e.jsx(Jt,{skill:N,onShow:()=>j(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 Jt({skill:s,onShow:t,searchQ:a=""}){const i=Kl[s.source]||At,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:Xl(s.name,a)}),e.jsx("span",{className:"skill-source-badge","data-source":s.source,children:Ws[s.source]||s.source})]})]}),e.jsx("p",{className:"skill-card-desc",children:n}),e.jsx("div",{className:"skill-card-actions",children:e.jsxs(T,{variant:"ghost",size:"sm",onClick:t,children:[e.jsx(vs,{size:12})," View"]})})]})}function Xl(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 Ql=De.memo(Yl);function Jl({refreshKey:s,onRefresh:t,setActiveSubPanel:a}){const i=re(),[n,o]=r.useState(null),[c,l]=r.useState(""),[x,p]=r.useState(!0),h=async z=>{p(!0);try{const[C,y,w,$]=await Promise.all([R.get("/memory/health",z).catch(()=>null),R.get("/memory/status",z).catch(()=>null),R.get("/memory/lightrag/stats",z).catch(()=>null),R.get("/memory/storage",z).catch(()=>null)]);l((y==null?void 0:y.vaultRoot)||""),o({health:C||{score:0,status:"unconfigured",checks:[],message:"memory not initialised"},vault:{exists:!!(y!=null&&y.initialized),vaultRoot:(y==null?void 0:y.vaultRoot)||"",mode:(y==null?void 0:y.mode)||"local-only",noteCount:(y==null?void 0:y.noteCount)||0,totalSize:($==null?void 0:$.total)||0,folderCount:0,folders:[],lastModified:null,gitClean:(y==null?void 0:y.gitClean)??null,gitBranch:(y==null?void 0:y.branch)||null},lightrag:w||{running:!1,pid:null,host:"127.0.0.1",port:9621,indexedApprox:0,queryCountLast24h:0,lastReindexAt:null},storage:$||{total:0,breakdown:[]}})}catch(C){i.error(`Memory overview failed: ${C.message}`)}finally{p(!1)}};if(r.useEffect(()=>{const z=new AbortController;return h(z.signal),()=>z.abort()},[s]),x&&!n)return e.jsxs("div",{className:"view-loading",children:[e.jsx(le,{size:"lg"}),e.jsx("p",{children:"Loading memory overview…"})]});if(!n)return e.jsx("div",{className:"muted",children:"No memory data available."});const{health:d,vault:m,lightrag:u,storage:g}=n,k=d.score>=80?"var(--success)":d.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:k},children:[e.jsx("span",{className:"memory-health-score-value",style:{color:k},children:d.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(Te,{size:16}),"Memory health ·"," ",e.jsx("span",{style:{color:k},children:d.status})]}),e.jsx("p",{className:"memory-health-message",children:d.message}),e.jsxs("p",{className:"memory-health-vault mono muted","data-testid":"memory-overview-vault-path",children:[e.jsx("span",{className:"memory-health-vault-label",children:"Vault:"})," ",c||e.jsx("em",{children:"not initialised"})]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:t,children:[e.jsx(oe,{size:12})," Refresh"]})]})]}),e.jsxs("div",{className:"memory-source-pills",children:[e.jsxs("button",{type:"button",className:"memory-source-pill",onClick:()=>a("lightrag"),children:[e.jsx(Fe,{size:14}),e.jsx("span",{children:"LightRAG"}),e.jsx("span",{className:H("memory-source-pill-status",u.running?"on":"off"),children:u.running?"running":"stopped"})]}),e.jsxs("button",{type:"button",className:"memory-source-pill",onClick:()=>a("obsidian"),children:[e.jsx(be,{size:14}),e.jsx("span",{children:"Obsidian Vault"}),e.jsxs("span",{className:H("memory-source-pill-status",m.exists?"on":"off"),children:[m.noteCount," notes"]})]}),e.jsxs("button",{type:"button",className:"memory-source-pill",onClick:()=>a("git"),children:[e.jsx(ts,{size:14}),e.jsx("span",{children:"Git Sync"}),e.jsx("span",{className:H("memory-source-pill-status",m.gitClean===null?"na":m.gitClean?"on":"warn"),children:m.gitClean===null?"—":m.gitClean?"clean":"dirty"})]}),e.jsxs("button",{type:"button",className:"memory-source-pill",onClick:()=>a("semantic"),children:[e.jsx(Se,{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(ms,{icon:e.jsx(Fe,{size:16}),label:"LightRAG",value:u.running?`running · ${u.queryCountLast24h} q/24h`:"stopped",sub:u.running?`${u.indexedApprox} indexed chunks`:"start from the LightRAG panel",onClick:()=>a("lightrag")}),e.jsx(ms,{icon:e.jsx(be,{size:16}),label:"Obsidian",value:`${m.noteCount} notes`,sub:m.folderCount>0?`${m.folderCount} folders`:"no folders yet",onClick:()=>a("obsidian")}),e.jsx(ms,{icon:e.jsx(ts,{size:16}),label:"Git",value:m.gitBranch?`branch ${m.gitBranch}`:"local-only",sub:m.gitClean===null?"not configured":m.gitClean?"clean working tree":"dirty — commit or pull",onClick:()=>a("git")}),e.jsx(ms,{icon:e.jsx(va,{size:16}),label:"Storage",value:Zl(g.total),sub:g.breakdown.length>0?`${g.breakdown.length} dirs tracked`:"no memory data on disk"}),e.jsx(ms,{icon:e.jsx(We,{size:16}),label:"Last reindex",value:u.lastReindexAt?Oe(u.lastReindexAt):"never",sub:"lightrag ingest",onClick:()=>a("lightrag")}),e.jsx(ms,{icon:e.jsx($s,{size:16}),label:"Health",value:`${d.score}/100`,sub:d.status,onClick:()=>a("config")})]}),d.checks.length>0&&e.jsxs(G,{children:[e.jsx(se,{children:"Health checks"}),e.jsx(ae,{children:"Composite score across all memory subsystems"}),e.jsx("ul",{className:"memory-check-list",children:d.checks.map(z=>e.jsxs("li",{className:"memory-check-row",children:[e.jsx("span",{className:"memory-check-icon",children:z.pass?e.jsx(Ee,{size:14,style:{color:"var(--success)"}}):z.name.includes("secrets")||z.name.includes("schema")?e.jsx(ye,{size:14,style:{color:"var(--warning)"}}):e.jsx(Ms,{size:14,style:{color:"var(--error)"}})}),e.jsx("span",{className:"memory-check-name",children:z.name}),e.jsx("span",{className:"memory-check-detail muted",children:z.detail})]},z.name))})]})]})}function ms({icon:s,label:t,value:a,sub:i,onClick:n}){const o=n?"button":"div";return e.jsxs(o,{type:n?"button":void 0,onClick:n,className:H("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 Zl(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 eo({refreshKey:s}){const t=re(),[a,i]=r.useState(null),[n,o]=r.useState(null),[c,l]=r.useState([]),[x,p]=r.useState(!0),[h,d]=r.useState(null),[m,u]=r.useState(""),[g,k]=r.useState(null),z=async()=>{p(!0);try{const[f,D,M]=await Promise.all([R.get("/memory/lightrag/stats").catch(()=>null),R.get("/memory/config").then(b=>(b==null?void 0:b.lightrag)||null).catch(()=>null),R.get("/memory/lightrag/log").catch(()=>({lines:[]}))]);i(f),o(D),l((M==null?void 0:M.lines)||[])}catch(f){t.error(`LightRAG status failed: ${f.message}`)}finally{p(!1)}};r.useEffect(()=>{z()},[s]);const C=async(f,D,M)=>{d(f);try{await D(),t.success(M),await z()}catch(b){t.error(`${f} failed: ${b.message}`)}finally{d(null)}},y=()=>C("start",()=>R.post("/memory/lightrag/start",{}),"LightRAG starting…"),w=()=>C("stop",()=>R.post("/memory/lightrag/stop",{}),"LightRAG stopping…"),$=async()=>{d("restart");try{await R.post("/memory/lightrag/stop",{}).catch(()=>{}),await new Promise(f=>setTimeout(f,600)),await R.post("/memory/lightrag/start",{}),t.success("LightRAG restarted."),await z()}catch(f){t.error(`Restart failed: ${f.message}`)}finally{d(null)}},j=()=>C("reindex",()=>R.post("/memory/lightrag/reindex",{}),"Reindex complete."),N=()=>C("rebuild",()=>R.post("/memory/lightrag/rebuild-graph",{}),"Graph rebuilt."),v=async()=>{var f,D,M;if(m.trim()){d("query");try{const b=await R.get(`/memory/query?q=${encodeURIComponent(m)}&topK=8`),A=(f=b==null?void 0:b.semantic)!=null&&f.response?typeof b.semantic.response=="string"?b.semantic.response:JSON.stringify(b.semantic.response):((D=b==null?void 0:b.semantic)==null?void 0:D.error)||"No response";k({ok:!!((M=b==null?void 0:b.semantic)!=null&&M.ok),text:A})}catch(b){k({ok:!1,text:b.message})}finally{d(null)}}};return x&&!a?e.jsxs("div",{className:"view-loading",children:[e.jsx(le,{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(se,{children:[e.jsx(Fe,{size:14}),"LightRAG",e.jsx("span",{className:H("memory-source-pill-status",a.running?"on":"off"),children:a.running?"running":"stopped"})]}),e.jsx(ae,{children:a.running?e.jsxs(e.Fragment,{children:["PID ",e.jsx("code",{children:a.pid})," · ",a.host,":",a.port]}):e.jsx(e.Fragment,{children:"Server is not running. Start it from the controls below."})}),e.jsxs("div",{className:"memory-action-row",children:[e.jsxs(T,{variant:"primary",size:"sm",onClick:y,disabled:!!h||a.running,children:[h==="start"?e.jsx(me,{size:12,className:"memory-spin"}):e.jsx(ys,{size:12}),"Start"]}),e.jsxs(T,{variant:"secondary",size:"sm",onClick:w,disabled:!!h||!a.running,children:[h==="stop"?e.jsx(me,{size:12,className:"memory-spin"}):e.jsx(Dn,{size:12}),"Stop"]}),e.jsxs(T,{variant:"secondary",size:"sm",onClick:$,disabled:!!h,children:[h==="restart"?e.jsx(me,{size:12,className:"memory-spin"}):e.jsx(St,{size:12}),"Restart"]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:j,disabled:!!h,children:[h==="reindex"?e.jsx(me,{size:12,className:"memory-spin"}):e.jsx(oe,{size:12}),"Reindex all"]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:N,disabled:!!h,title:"Wipe working dir + reindex from scratch",children:[h==="rebuild"?e.jsx(me,{size:12,className:"memory-spin"}):e.jsx(Js,{size:12}),"Rebuild graph"]})]})]}),e.jsxs("div",{className:"memory-stat-grid",children:[e.jsx(Ns,{icon:e.jsx(va,{size:14}),label:"Indexed chunks (approx)",value:String(a.indexedApprox)}),e.jsx(Ns,{icon:e.jsx(so,{n:a.noteCount}),label:"Notes in vault",value:String(a.noteCount)}),e.jsx(Ns,{icon:e.jsx(Ct,{size:14}),label:"Queries last 24h",value:String(a.queryCountLast24h)}),e.jsx(Ns,{icon:e.jsx(We,{size:14}),label:"Avg response",value:a.avgResponseMs!==null?`${a.avgResponseMs} ms`:"—"}),e.jsx(Ns,{icon:a.lastReindexOk?e.jsx(Ee,{size:14}):a.lastReindexOk===!1?e.jsx(Ms,{size:14}):e.jsx(oe,{size:14}),label:"Last reindex",value:a.lastReindexAt?Oe(a.lastReindexAt):"never",sub:a.lastReindexInserted!==null?`${a.lastReindexInserted} inserted${a.lastReindexFailed?`, ${a.lastReindexFailed} failed`:""}`:void 0})]}),e.jsxs(G,{children:[e.jsxs(se,{children:[e.jsx(Se,{size:14})," Quick search"]}),e.jsx(ae,{children:"Send a natural-language query to the LightRAG index."}),e.jsxs("div",{className:"memory-search-row",children:[e.jsx("label",{htmlFor:"lightrag-query",className:"sr-only",children:"Search LightRAG"}),e.jsx("input",{id:"lightrag-query",type:"text",className:"input",placeholder:"e.g. how does the memory service write notes?",value:m,onChange:f=>u(f.target.value),onKeyDown:f=>{f.key==="Enter"&&v()},disabled:h==="query","aria-label":"Search LightRAG"}),e.jsxs(T,{variant:"primary",onClick:v,disabled:h==="query"||!m.trim(),children:[h==="query"?e.jsx(me,{size:12,className:"memory-spin"}):e.jsx(Se,{size:12}),"Query"]})]}),g&&e.jsx("div",{className:H("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(se,{children:"Configuration"}),e.jsxs(ae,{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})]})]}),c.length>0&&e.jsxs(G,{children:[e.jsxs(se,{children:[e.jsx(oe,{size:14})," Server log (tail)"]}),e.jsxs(ae,{children:["Last ",c.length," lines from ",e.jsx("code",{children:"lightrag.log"})]}),e.jsx("pre",{className:"memory-log-tail mono text-xs",children:c.join(`
|
|
12
|
+
`)})]})]}):e.jsx("div",{className:"muted",children:"No LightRAG data available."})}function Ns({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 so({n:s}){return e.jsxs("span",{style:{position:"relative",display:"inline-block"},children:[e.jsx(Se,{size:14}),e.jsx("span",{className:"memory-mini-badge",children:s})]})}function to({refreshKey:s}){const t=re(),a=Re(),[i,n]=r.useState([]),[o,c]=r.useState(null),[l,x]=r.useState(!0),[p,h]=r.useState(""),[d,m]=r.useState(null),[u,g]=r.useState(!1),[k,z]=r.useState(null),[C,y]=r.useState([]),w=async()=>{var M;x(!0);try{const[b,A]=await Promise.all([R.get("/memory/notes").catch(()=>({notes:[]})),R.get("/memory/obsidian/tree").catch(()=>({tree:null}))]);n(b.notes||[]),c(A.tree),k&&!((M=b.notes)!=null&&M.find(O=>O.relPath===k))&&(z(null),y([]))}catch(b){t.error(`Vault load failed: ${b.message}`)}finally{x(!1)}};r.useEffect(()=>{w()},[s]),r.useEffect(()=>{if(!p.trim()){m(null);return}g(!0);const M=setTimeout(async()=>{try{const b=await R.get(`/memory/search?q=${encodeURIComponent(p)}&limit=50`),A=new Set((b.results||[]).map(O=>O.relPath));m(i.filter(O=>A.has(O.relPath)))}catch(b){t.error(`Search failed: ${b.message}`)}finally{g(!1)}},240);return()=>clearTimeout(M)},[p,i,t]);const $=async M=>{z(M);try{const b=await R.get(`/memory/obsidian/backlinks?note=${encodeURIComponent(M)}`);y(b.backlinks||[])}catch{y([])}},j=()=>{a.open({title:"New note",width:720,children:e.jsx(Zt,{mode:"create",onSave:async(M,b,A)=>{try{await R.post("/memory/notes",{path:M,frontmatter:b,body:A}),t.success(`Created ${M}.`),a.close(),await w(),$(M)}catch(O){t.error(`Create failed: ${O.message}`)}},onCancel:()=>a.close()})})},N=async M=>{try{const b=await R.get(`/memory/notes/${M.split("/").map(encodeURIComponent).join("/")}`);a.open({title:`Edit ${M}`,width:720,children:e.jsx(Zt,{mode:"edit",initial:{relPath:b.relPath,frontmatter:b.frontmatter,body:b.body},onSave:async(A,O,S)=>{try{await R.put(`/memory/notes/${A.split("/").map(encodeURIComponent).join("/")}`,{frontmatter:O,body:S}),t.success(`Saved ${A}.`),a.close(),await w(),$(A)}catch(F){t.error(`Save failed: ${F.message}`)}},onCancel:()=>a.close()})})}catch(b){t.error(`Load failed: ${b.message}`)}},v=async M=>{if(confirm(`Delete ${M}? This cannot be undone.`))try{await R.del(`/memory/notes/${M.split("/").map(encodeURIComponent).join("/")}`),t.success(`Deleted ${M}.`),k===M&&z(null),await w()}catch(b){t.error(`Delete failed: ${b.message}`)}},f=r.useMemo(()=>[...i].sort((M,b)=>b.mtime-M.mtime),[i]),D=d??f;return l&&!i.length?e.jsxs("div",{className:"view-loading",children:[e.jsx(le,{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(se,{children:[e.jsx($e,{size:14})," Folders"]}),e.jsx(ae,{children:o?`${Da(o)} folder(s)`:"no vault"}),e.jsx("div",{className:"memory-tree-body",children:o?e.jsx(Ea,{node:o,depth:0,onSelect:$,selected:k}):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(Se,{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:M=>h(M.target.value),"aria-label":"Search notes"}),p&&e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>h(""),"aria-label":"Clear search",children:e.jsx(Ne,{size:12})})]}),e.jsxs(T,{variant:"primary",size:"sm",onClick:j,children:[e.jsx(Pn,{size:12})," New note"]}),e.jsx(T,{variant:"ghost",size:"sm",onClick:w,title:"Refresh",children:e.jsx(oe,{size:12})})]}),u&&e.jsx("div",{className:"muted text-sm",children:"Searching…"}),D.length===0?e.jsx(he,{icon:e.jsx(be,{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:D.map(M=>e.jsxs("li",{className:H("memory-note-card",k===M.relPath&&"memory-note-card-active"),children:[e.jsxs("button",{type:"button",className:"memory-note-card-main",onClick:()=>$(M.relPath),children:[e.jsxs("div",{className:"memory-note-card-title",children:[e.jsx(be,{size:12}),e.jsx("span",{children:La(M)})]}),e.jsxs("div",{className:"memory-note-card-meta",children:[e.jsx("code",{className:"muted",children:M.relPath}),e.jsxs("span",{className:"muted",children:["· ",ze(M.mtime)]}),!M.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(M.relPath),"aria-label":`Edit ${M.relPath}`,title:"Edit",children:e.jsx(Is,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>v(M.relPath),"aria-label":`Delete ${M.relPath}`,title:"Delete",children:e.jsx(ke,{size:12})})]})]},M.relPath))})]}),e.jsx("div",{className:"memory-obsidian-detail-col",children:k?e.jsx(ao,{relPath:k,onClose:()=>z(null)}):e.jsx(he,{icon:e.jsx(be,{size:28}),title:"Pick a note",message:"Select a note from the list to view its content, frontmatter, and backlinks."})})]})}function La(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 Ea({node:s,depth:t,onSelect:a,selected:i}){const[n,o]=r.useState(t<2);return s.type==="note"?e.jsxs("button",{type:"button",className:H("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(be,{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:()=>o(c=>!c),children:[n?e.jsx(Ue,{size:11}):e.jsx(Xe,{size:11}),e.jsx($e,{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((c,l)=>e.jsx(Ea,{node:c,depth:t+1,onSelect:a,selected:i},`${c.path}-${l}`))})]})}function Da(s){return s.type==="note"?0:1+(s.children||[]).reduce((t,a)=>t+Da(a),0)}function ao({relPath:s,onClose:t}){var h,d;const[a,i]=r.useState(null),[n,o]=r.useState([]),[c,l]=r.useState(!0);if(r.useEffect(()=>{let m=!1;return l(!0),(async()=>{try{const[u,g]=await Promise.all([R.get(`/memory/notes/${s.split("/").map(encodeURIComponent).join("/")}`),R.get(`/memory/obsidian/backlinks?note=${encodeURIComponent(s)}`)]);if(m)return;i(u),o(g.backlinks||[])}catch{m||i(null)}finally{m||l(!1)}})(),()=>{m=!0}},[s]),c)return e.jsx("div",{className:"view-loading",children:e.jsx(le,{size:"sm"})});if(!a)return e.jsx("div",{className:"muted",children:"Note not found."});const x=Array.isArray((h=a.frontmatter)==null?void 0:h.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:La(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 ",Oe(a.mtime)]})]}),x.length>0&&e.jsx("div",{className:"memory-tag-row",children:x.map((m,u)=>e.jsx("span",{className:"memory-tag",children:String(m)},u))}),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,u)=>e.jsx("li",{children:e.jsx("code",{children:String(m)})},u))})]})]})}function Zt({mode:s,initial:t,onSave:a,onCancel:i}){const[n,o]=r.useState((t==null?void 0:t.relPath)||"untitled.md"),[c,l]=r.useState(t!=null&&t.frontmatter?no(t.frontmatter):`title: ""
|
|
13
|
+
tags: []
|
|
14
|
+
`),[x,p]=r.useState((t==null?void 0:t.body)||""),[h,d]=r.useState(!1),m=re(),u=async()=>{if(!n.endsWith(".md")){m.error("Path must end in .md");return}let g;try{g=io(c)||{}}catch(k){m.error(`Frontmatter parse failed: ${k.message}`);return}d(!0);try{await a(n,g,x)}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=>o(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:c,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:x,onChange:g=>p(g.target.value),"aria-label":"Body markdown"}),e.jsxs("div",{className:"modal-footer-actions",style:{marginTop:12},children:[e.jsx(T,{variant:"ghost",onClick:i,disabled:h,children:"Cancel"}),e.jsxs(T,{variant:"primary",onClick:u,disabled:h,children:[h&&e.jsx(me,{size:12,className:"memory-spin"}),s==="create"?"Create":"Save"]})]})]})}function no(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(` - ${lt(n)}`)}else if(typeof i=="object"){t.push(`${a}:`);for(const[n,o]of Object.entries(i))t.push(` ${n}: ${lt(o)}`)}else t.push(`${a}: ${lt(i)}`);return t.join(`
|
|
15
|
+
`)}function lt(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 io(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 o=n.match(/^([A-Za-z_][\w-]*):\s*(.*)$/);if(!o){i++;continue}const[,c,l]=o;if(l===""){const x={},p=[];let h=!1,d=!1;for(;i+1<a.length;){const m=a[i+1];if(!m.startsWith(" "))break;if(m.startsWith(" - "))h=!0,p.push(ot(m.slice(4))),i++;else{d=!0;const u=m.match(/^ ([A-Za-z_][\w-]*):\s*(.*)$/);u&&(x[u[1]]=ot(u[2])),i++}}t[c]=h&&!d?p:d?x:{}}else t[c]=ot(l);i++}return t}function ot(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 ro({refreshKey:s}){var w,$,j,N;const t=re(),[a,i]=r.useState(null),[n,o]=r.useState(null),[c,l]=r.useState(!0),[x,p]=r.useState(null),[h,d]=r.useState(null),m=async()=>{var v;l(!0);try{const[f,D,M]=await Promise.all([R.get("/memory/git/status").catch(()=>null),R.get("/memory/git/diff").catch(()=>null),R.get("/memory/config/global").catch(()=>null)]);i(f),o(D),d(((v=M==null?void 0:M.config)==null?void 0:v.git)||null)}catch(f){t.error(`Git status failed: ${f.message}`)}finally{l(!1)}};r.useEffect(()=>{m()},[s]);const u=async(v,f,D)=>{p(v);try{await f(),t.success(D),await m()}catch(M){t.error(`${v} failed: ${M.message}`)}finally{p(null)}},g=()=>u("pull",()=>R.post("/memory/git/pull",{}),"Pull complete."),k=()=>u("push",()=>R.post("/memory/git/push",{}),"Push complete."),z=()=>{const v=prompt("Commit message:",`[memory-sync] ${new Date().toISOString().slice(0,10)} vault sync`);v&&u("commit",()=>R.post("/memory/git/commit",{message:v}),"Committed.")},C=()=>u("fetch",()=>R.post("/memory/git/sync",{push:!1}),"Fetch complete.");if(c&&!a)return e.jsxs("div",{className:"view-loading",children:[e.jsx(le,{size:"lg"}),e.jsx("p",{children:"Loading git status…"})]});if(!a)return e.jsx("div",{className:"muted",children:"No git data available."});const y=a.mode==="local-only";return e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(G,{variant:"elevated",children:[e.jsxs(se,{children:[e.jsx(ts,{size:14})," Git sync",y?e.jsx("span",{className:"memory-source-pill-status na",children:"local-only"}):e.jsx("span",{className:H("memory-source-pill-status",a.clean?"on":"warn"),children:a.clean?"clean":"dirty"})]}),e.jsx(ae,{children:y?"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]})}),!y&&e.jsxs("div",{className:"memory-git-status-row",children:[e.jsx(ks,{ok:a.clean??!1,label:"Working tree"}),e.jsx(ks,{ok:(a.ahead??0)===0,label:`Ahead: ${a.ahead??0}`}),e.jsx(ks,{ok:(a.behind??0)===0,label:`Behind: ${a.behind??0}`}),e.jsx(ks,{ok:(((w=a.modified)==null?void 0:w.length)??0)===0,label:`Modified: ${(($=a.modified)==null?void 0:$.length)??0}`}),e.jsx(ks,{ok:(((j=a.untracked)==null?void 0:j.length)??0)===0,label:`Untracked: ${((N=a.untracked)==null?void 0:N.length)??0}`})]}),e.jsxs("div",{className:"memory-action-row",children:[e.jsxs(T,{variant:"secondary",size:"sm",onClick:g,disabled:!!x||y,children:[x==="pull"?e.jsx(me,{size:12,className:"memory-spin"}):e.jsx(ha,{size:12}),"Pull"]}),e.jsxs(T,{variant:"secondary",size:"sm",onClick:k,disabled:!!x||y,children:[x==="push"?e.jsx(me,{size:12,className:"memory-spin"}):e.jsx(zt,{size:12}),"Push"]}),e.jsxs(T,{variant:"secondary",size:"sm",onClick:z,disabled:!!x||y,children:[x==="commit"?e.jsx(me,{size:12,className:"memory-spin"}):e.jsx(ya,{size:12}),"Commit"]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:C,disabled:!!x||y,children:[x==="fetch"?e.jsx(me,{size:12,className:"memory-spin"}):e.jsx(Fn,{size:12}),"Fetch + sync"]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:m,disabled:!!x,children:[e.jsx(oe,{size:12})," Refresh"]})]})]}),h&&e.jsxs(G,{children:[e.jsxs(se,{children:[e.jsx(ja,{size:14})," Repository"]}),e.jsxs(ae,{children:["Snapshot of ",e.jsx("code",{children:"~/.config/bizar/memory-config.json"})," → git block."]}),e.jsxs("dl",{className:"memory-config-row",children:[e.jsx("dt",{children:"Path"}),e.jsx("dd",{className:"mono ellipsis",title:h.repoPath,children:h.repoPath||"—"}),e.jsx("dt",{children:"Remote"}),e.jsx("dd",{className:"mono ellipsis",title:h.remoteUrl,children:h.remoteUrl||"—"}),e.jsx("dt",{children:"Branch"}),e.jsx("dd",{children:e.jsx("code",{children:h.branch||"main"})}),e.jsx("dt",{children:"Auto-sync"}),e.jsx("dd",{children:h.autoSync?"enabled":"disabled"})]})]}),e.jsxs(G,{children:[e.jsxs(se,{children:[e.jsx(On,{size:14})," Working-tree diff"]}),e.jsx(ae,{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 ks({ok:s,label:t}){return e.jsxs("span",{className:H("memory-git-status-pill",s?"ok":"warn"),children:[s?e.jsx(Ee,{size:11}):e.jsx(me,{size:11,className:"memory-spin"}),t]})}function lo({refreshKey:s}){const t=re(),[a,i]=r.useState(""),[n,o]=r.useState({lightrag:!0,obsidian:!0}),[c,l]=r.useState(null),[x,p]=r.useState(!1),[h,d]=r.useState(""),m=async g=>{if(g.trim()){p(!0),d(g);try{const k=[...n.lightrag?["lightrag"]:[],...n.obsidian?["obsidian"]:[]],z=await R.post("/memory/semantic-search",{query:g,limit:20,sources:k});l(z.results||[])}catch(k){t.error(`Search failed: ${k.message}`),l([])}finally{p(!1)}}};r.useEffect(()=>{h&&m(h)},[n]),r.useEffect(()=>{h&&m(h)},[s]);const u=r.useMemo(()=>{const g=(c||[]).filter(z=>z.source==="obsidian"),k=(c||[]).filter(z=>z.source==="lightrag");return{obs:g,lr:k}},[c]);return e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(G,{variant:"elevated",children:[e.jsxs(se,{children:[e.jsx(Se,{size:14})," Semantic search"]}),e.jsx(ae,{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:x,"aria-label":"Semantic search query"}),e.jsxs(T,{variant:"primary",onClick:()=>m(a),disabled:x||!a.trim(),children:[x?e.jsx(me,{size:12,className:"memory-spin"}):e.jsx(Se,{size:12}),"Search"]})]}),e.jsxs("div",{className:"memory-source-toggle-row",children:[e.jsx(ea,{active:n.obsidian,onToggle:()=>o(g=>({...g,obsidian:!g.obsidian})),label:"Obsidian",icon:e.jsx(be,{size:11})}),e.jsx(ea,{active:n.lightrag,onToggle:()=>o(g=>({...g,lightrag:!g.lightrag})),label:"LightRAG",icon:e.jsx(Fe,{size:11})}),a&&e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>{i(""),l(null),d("")},"aria-label":"Clear",children:e.jsx(Ne,{size:12})})]})]}),x&&e.jsx("div",{className:"view-loading",children:e.jsx(le,{size:"md"})}),!x&&c&&c.length===0&&e.jsx(he,{icon:e.jsx(Se,{size:28}),title:"No matches",message:`Nothing in scope matched "${h}".`}),u.obs.length>0&&e.jsxs(G,{children:[e.jsxs(se,{children:[e.jsx(be,{size:14})," Obsidian (",u.obs.length,")"]}),e.jsx("ul",{className:"memory-search-result-list",children:u.obs.map((g,k)=>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-${k}`))})]}),u.lr.length>0&&e.jsxs(G,{children:[e.jsxs(se,{children:[e.jsx(Fe,{size:14})," LightRAG (",u.lr.length,")"]}),e.jsx("div",{className:"memory-search-result-list",children:u.lr.map((g,k)=>e.jsxs("div",{className:"memory-search-result",children:[e.jsxs("div",{className:"memory-search-result-head",children:[e.jsxs("span",{className:"memory-source-pill",children:[e.jsx(Fe,{size:11})," LightRAG"]}),g.error&&e.jsxs("span",{className:"muted text-xs",children:["error: ",g.error]})]}),e.jsx("p",{className:"text-sm",children:g.snippet})]},`lr-${k}`))})]})]})}function ea({active:s,onToggle:t,label:a,icon:i}){return e.jsxs("button",{type:"button",className:H("memory-toggle-chip",s&&"memory-toggle-chip-active"),onClick:t,"aria-pressed":s,children:[i,e.jsx("span",{children:a})]})}function oo({refreshKey:s}){const t=re(),[a,i]=r.useState(null),[n,o]=r.useState(!0),[c,l]=r.useState(!1),[x,p]=r.useState(""),[h,d]=r.useState(null),[m,u]=r.useState(""),[g,k]=r.useState(!1),[z,C]=r.useState(!1),[y,w]=r.useState(null),[$,j]=r.useState(null),[N,v]=r.useState(null),[f,D]=r.useState(!1),M=async()=>{var W,K;o(!0);try{const[B,Q]=await Promise.all([R.get("/memory/config/global").catch(()=>null),R.get("/memory/status").catch(()=>null)]);B?(i(B.config),p(((K=(W=B.config)==null?void 0:W.git)==null?void 0:K.remoteUrl)||"")):i({}),Q&&(d(Q),u(te=>te||Q.vaultRoot||"")),await b()}catch(B){t.error(`Config load failed: ${B.message}`)}finally{o(!1)}},b=async()=>{try{const W=await R.get("/memory/git/status");W.ok&&w({clean:W.clean,branch:W.branch,modified:W.modified,untracked:W.untracked})}catch{}};r.useEffect(()=>{M()},[s]);const A=async()=>{const W=m.trim();if(!W){t.error("Vault path cannot be empty.");return}C(!0);try{const K=await R.get("/memory/status").catch(()=>null);(K==null?void 0:K.initialized)?t.info("Vault path already initialised — run `bizar memory init --path <new>` from the CLI to move it."):(await R.post("/memory/init",{vaultRoot:W}),t.success(`Vault initialised at ${W}.`)),u(W),await M()}catch(K){t.error(`Vault path save failed: ${K.message}`)}finally{C(!1)}},O=async()=>{k(!0);try{await R.post("/memory/init",{}),t.success("Vault initialised."),await M()}catch(W){t.error(`Init failed: ${W.message}`)}finally{k(!1)}},S=async()=>{if(a){l(!0);try{await R.put("/memory/config/global",{git:{remoteUrl:x}}),t.success("Config saved.")}catch(W){t.error(`Save failed: ${W.message}`)}finally{l(!1)}}},F=async W=>{j(W);try{if(W==="pull"){const K=await R.post("/memory/git/pull",{});K.ok?t.success("Pull successful."):t.error(`Pull failed: ${K.output||"unknown error"}`)}else if(W==="push")(await R.post("/memory/git/push",{})).ok?t.success("Push successful."):t.error("Push failed.");else if(W==="commit"){const K=await R.post("/memory/git/commit",{});K.ok?t.success(`Committed: ${K.message}`):t.error("Commit failed.")}await b()}catch(K){t.error(`${W} failed: ${K.message}`)}finally{j(null)}},_=async()=>{D(!0);try{const W=await R.post("/memory/test-git",{});v(W.checks)}catch(W){t.error(`Test failed: ${W.message}`)}finally{D(!1)}};if(n&&!a)return e.jsxs("div",{className:"view-loading",children:[e.jsx(le,{size:"md"}),e.jsx("p",{children:"Loading config…"})]});if(!a)return e.jsx("div",{className:"muted",children:"No config available."});const P=!!(h!=null&&h.initialized),V=(h==null?void 0:h.vaultRoot)??"";return e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(G,{children:[e.jsxs(se,{children:[e.jsx(Bt,{size:14})," Vault location"]}),e.jsxs(ae,{children:["The on-disk folder where notes and memory metadata live. Default:"," ",e.jsx("code",{children:"~/.bizar_memory"}),"."]}),e.jsxs("div",{className:"memory-config-form",children:[e.jsxs(Os,{label:"Current path",inline:!0,children:[e.jsx("span",{className:"memory-vault-path mono","data-testid":"memory-current-vault-path",children:V||e.jsx("span",{className:"muted",children:"not initialised"})}),P?e.jsxs("span",{className:"memory-pill memory-pill-ok",style:{marginLeft:8},title:"Vault folder exists on disk",children:[e.jsx(Ee,{size:10})," initialised"]}):e.jsxs("span",{className:"memory-pill memory-pill-warn",style:{marginLeft:8},title:"Vault folder does not exist yet",children:[e.jsx(Ms,{size:10})," not initialised"]})]}),e.jsxs(Os,{label:"Set path",children:[e.jsx("input",{type:"text",className:"input mono",value:m,onChange:W=>u(W.target.value),placeholder:"~/.bizar_memory","aria-label":"Vault path","data-testid":"memory-vault-path-input"}),e.jsx("span",{className:"field-hint",children:P?"Save to update the working path (or use `bizar memory init --path <new>` from the CLI to migrate).":"Save and initialise will create this folder if it does not exist."})]})]}),e.jsxs("div",{className:"memory-action-row",style:{marginTop:12},children:[e.jsxs(T,{variant:"primary",onClick:A,disabled:z||g||!m.trim(),"data-testid":"memory-save-vault-path",children:[z?e.jsx(me,{size:12,className:"memory-spin"}):e.jsx(fs,{size:12}),P?"Save path":"Save and initialise"]}),!P&&e.jsxs(T,{variant:"secondary",onClick:O,disabled:g||z,"data-testid":"memory-init-vault",children:[g?e.jsx(me,{size:12,className:"memory-spin"}):e.jsx(Bt,{size:12}),"Initialise default"]})]})]}),e.jsxs(G,{children:[e.jsxs(se,{children:[e.jsx(ts,{size:14})," Git sync"]}),e.jsx(ae,{children:"Configure the git remote and sync your memory vault."}),e.jsxs("div",{className:"memory-config-form",children:[e.jsx(Os,{label:"Remote URL",children:e.jsx("input",{type:"text",className:"input mono",value:x,onChange:W=>p(W.target.value),placeholder:"git@github.com:org/repo.git"})}),y&&e.jsxs(Os,{label:"Status",inline:!0,children:[e.jsx("span",{className:H("memory-pill",y.clean?"memory-pill-ok":"memory-pill-warn"),children:y.clean?"clean":"dirty"}),y.branch&&e.jsxs("span",{className:"muted",style:{marginLeft:8},children:[e.jsx(ts,{size:12,style:{display:"inline"}})," ",y.branch]}),!y.clean&&y.modified!==void 0&&e.jsxs("span",{className:"muted",style:{marginLeft:8},children:[y.modified," modified, ",y.untracked," untracked"]})]})]}),e.jsxs("div",{className:"memory-action-row",style:{marginTop:12},children:[e.jsxs(T,{variant:"secondary",onClick:()=>F("pull"),disabled:$!==null,children:[$==="pull"?e.jsx(me,{size:12,className:"memory-spin"}):e.jsx(as,{size:12}),"Pull"]}),e.jsxs(T,{variant:"secondary",onClick:()=>F("commit"),disabled:$!==null,children:[$==="commit"?e.jsx(me,{size:12,className:"memory-spin"}):e.jsx(ya,{size:12}),"Commit"]}),e.jsxs(T,{variant:"secondary",onClick:()=>F("push"),disabled:$!==null,children:[$==="push"?e.jsx(me,{size:12,className:"memory-spin"}):e.jsx(Un,{size:12}),"Push"]})]})]}),e.jsxs(G,{children:[e.jsxs(se,{children:[e.jsx(ht,{size:14})," Connection tests"]}),e.jsx(ae,{children:"Verify the configured git remote is reachable."}),e.jsxs("div",{className:"memory-action-row",children:[e.jsxs(T,{variant:"secondary",onClick:_,disabled:f,children:[f?e.jsx(me,{size:12,className:"memory-spin"}):e.jsx(ht,{size:12}),"Test git connection"]}),e.jsxs(T,{variant:"primary",onClick:S,disabled:c,children:[c?e.jsx(me,{size:12,className:"memory-spin"}):e.jsx(fs,{size:12}),"Save config"]})]}),N&&N.length>0&&e.jsx("ul",{className:"memory-check-list",style:{marginTop:12},children:N.map((W,K)=>e.jsxs("li",{className:"memory-check-row",children:[e.jsx("span",{className:"memory-check-icon",children:e.jsx("span",{className:H("memory-pill",W.pass?"memory-pill-ok":"memory-pill-warn"),children:W.pass?"OK":"FAIL"})}),e.jsx("span",{className:"memory-check-name",children:W.name}),e.jsx("span",{className:"memory-check-detail muted",children:W.detail})]},K))})]})]})}function Os({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 qe=800,sa=60,ct={default:"#8b5cf6",note:"#8b5cf6",entity:"#34d399",concept:"#fbbf24",root:"#f87171"};function co(s,t){return ct[s]||ct[t]||ct.default}function mo(s){return 6+Math.min(s.size*2,10)}function uo(s,t){var o,c;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)(o=a.get(l.source))==null||o.add(l.target),(c=a.get(l.target))==null||c.add(l.source);const i=s.map((l,x)=>{const p=x/s.length*Math.PI*2,h=qe*.28;return{...l,x:qe/2+h*Math.cos(p)+(Math.random()-.5)*40,y:qe/2+h*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<sa;l++){const x=1-l/sa;for(let d=0;d<i.length;d++)for(let m=d+1;m<i.length;m++){const u=i[d],g=i[m],k=g.x-u.x,z=g.y-u.y,C=Math.sqrt(k*k+z*z)||1,y=400*x/(C*C),w=k/C*y,$=z/C*y;u.vx-=w,u.vy-=$,g.vx+=w,g.vy+=$}for(const d of t){const m=n.get(d.source),u=n.get(d.target);if(!m||!u)continue;const g=u.x-m.x,k=u.y-m.y,z=Math.sqrt(g*g+k*k)||1,y=(z-80)*.08*x,w=g/z*y,$=k/z*y;m.vx+=w,m.vy+=$,u.vx-=w,u.vy-=$}const p=qe/2,h=qe/2;for(const d of i)d.vx+=(p-d.x)*.01*x,d.vy+=(h-d.y)*.01*x;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(qe-20,d.x)),d.y=Math.max(20,Math.min(qe-20,d.y))}return i}function ho({data:s,onNodeClick:t,className:a}){const i=r.useRef(null),[n,o]=r.useState({x:0,y:0,scale:1}),c=r.useRef(!1),l=r.useRef({x:0,y:0,tx:0,ty:0}),x=r.useRef(null),[p,h]=r.useState(null),[d,m]=r.useState(null),u=r.useMemo(()=>uo(s.nodes,s.edges),[s.nodes,s.edges]),g=r.useMemo(()=>{const f=new Map;for(const D of u)f.set(D.id,D);return f},[u]),k=r.useCallback(f=>{f.target.closest(".memory-graph-node")||(c.current=!0,l.current={x:f.clientX,y:f.clientY,tx:n.x,ty:n.y})},[n]),z=r.useCallback(f=>{if(!c.current)return;const D=f.clientX-l.current.x,M=f.clientY-l.current.y;o(b=>({...b,x:l.current.tx+D,y:l.current.ty+M}))},[]),C=r.useCallback(()=>{c.current=!1},[]),y=r.useCallback(f=>{f.preventDefault();const D=f.deltaY<0?1.1:.9,M=i.current;if(!M)return;const b=M.getBoundingClientRect(),A=f.clientX-b.left,O=f.clientY-b.top;o(S=>{const F=Math.max(.2,Math.min(4,S.scale*D)),_=F/S.scale;return{x:A-(A-S.x)*_,y:O-(O-S.y)*_,scale:F}})},[]),w=r.useCallback(f=>{const D=Array.from(f.touches);if(D.length===2){const[M,b]=D;x.current=Math.hypot(b.clientX-M.clientX,b.clientY-M.clientY)}else D.length===1&&(c.current=!0,l.current={x:D[0].clientX,y:D[0].clientY,tx:n.x,ty:n.y})},[n]),$=r.useCallback(f=>{const D=Array.from(f.touches);if(D.length===2&&x.current!==null){const[M,b]=D,A=Math.hypot(b.clientX-M.clientX,b.clientY-M.clientY),O=A/x.current;x.current=A,o(S=>({...S,scale:Math.max(.2,Math.min(4,S.scale*O))}))}else if(D.length===1&&c.current){const M=D[0].clientX-l.current.x,b=D[0].clientY-l.current.y;o(A=>({...A,x:l.current.tx+M,y:l.current.ty+b}))}},[]),j=r.useCallback(()=>{c.current=!1,x.current=null},[]),N=r.useCallback(f=>{h(f.id===p?null:f.id),t==null||t(f)},[p,t]),v=Math.max(.5,1/Math.log2(n.scale+1));return e.jsx("svg",{ref:i,className:H("memory-graph-canvas",a),viewBox:`0 0 ${qe} ${qe}`,style:{width:"100%",height:"100%",minHeight:400,cursor:c.current?"grabbing":"grab"},onMouseDown:k,onMouseMove:z,onMouseUp:C,onMouseLeave:C,onWheel:y,onTouchStart:w,onTouchMove:$,onTouchEnd:j,children:e.jsxs("g",{transform:`translate(${n.x},${n.y}) scale(${n.scale})`,children:[s.edges.map((f,D)=>{const M=g.get(f.source),b=g.get(f.target);if(!M||!b)return null;const A=d===f.source||d===f.target||p===f.source||p===f.target;return e.jsx("line",{x1:M.x,y1:M.y,x2:b.x,y2:b.y,stroke:A?"#8b5cf6":"#2d3648",strokeWidth:A?v*2:v,strokeOpacity:A?.9:.5},`e-${D}`)}),u.map(f=>{const D=mo(f),M=co(f.group,f.type),b=p===f.id,A=d===f.id;return e.jsxs("g",{className:"memory-graph-node",transform:`translate(${f.x},${f.y})`,onClick:()=>N(f),onMouseEnter:()=>m(f.id),onMouseLeave:()=>m(null),style:{cursor:"pointer"},children:[e.jsx("circle",{r:D+6,fill:"transparent"}),(b||A)&&e.jsx("circle",{r:D+4,fill:M,fillOpacity:.2}),e.jsx("circle",{r:D,fill:M,fillOpacity:b?1:.75,stroke:b?"#fff":M,strokeWidth:b?2:1}),n.scale>.5&&e.jsx("text",{y:D+12,textAnchor:"middle",fontSize:Math.max(8,Math.min(11,10/Math.sqrt(n.scale))),fill:"var(--text-dim, #b4bcd0)",style:{pointerEvents:"none",userSelect:"none"},children:f.label.length>20?f.label.slice(0,18)+"…":f.label})]},f.id)})]})})}const xo=[{color:"#8b5cf6",label:"Note / Default"},{color:"#34d399",label:"Entity (LightRAG)"},{color:"#fbbf24",label:"Concept (LightRAG)"},{color:"#f87171",label:"Root / Ungrouped"}];function po({className:s}){return e.jsx("div",{className:H("memory-graph-legend",s),children:xo.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 go({refreshKey:s}){const t=re(),[a,i]=r.useState({nodes:[],edges:[]}),[n,o]=r.useState(!0),[c,l]=r.useState(null),[x,p]=r.useState(""),[h,d]=r.useState(2),[m,u]=r.useState(""),[g,k]=r.useState(null),[z,C]=r.useState(null),y=r.useCallback(async()=>{var j,N;o(!0),l(null);try{const v=new URLSearchParams({limit:"200"});m&&v.set("root",m),v.set("depth",String(h));const f=await R.get(`/memory/graph?${v}`);i({nodes:f.nodes||[],edges:f.edges||[]}),k({totalNodes:f.totalNodes??((j=f.nodes)==null?void 0:j.length)??0,totalEdges:f.totalEdges??((N=f.edges)==null?void 0:N.length)??0})}catch(v){l(v.message),t.error(`Graph load failed: ${v.message}`)}finally{o(!1)}},[m,h,t]);r.useEffect(()=>{y()},[y,s]);const w=r.useCallback(j=>{C(N=>(N==null?void 0:N.id)===j.id?null:j)},[]),$=x.trim()?{nodes:a.nodes.filter(j=>j.label.toLowerCase().includes(x.toLowerCase())),edges:a.edges.filter(j=>a.nodes.some(N=>N.id===j.source&&N.label.toLowerCase().includes(x.toLowerCase()))||a.nodes.some(N=>N.id===j.target&&N.label.toLowerCase().includes(x.toLowerCase())))}:a;return e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(G,{children:[e.jsxs(se,{children:[e.jsx(ba,{size:14})," Memory Graph"]}),e.jsx(ae,{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:x,onChange:j=>p(j.target.value),style:{maxWidth:240}}),e.jsx("input",{type:"text",className:"input",placeholder:"Root note id (optional)",value:m,onChange:j=>u(j.target.value),style:{maxWidth:240},title:"Start from a specific note"}),e.jsx("label",{htmlFor:"graph-depth",className:"sr-only",children:"Depth"}),e.jsxs("span",{className:"muted text-sm",style:{whiteSpace:"nowrap"},children:["Depth",e.jsx("input",{id:"graph-depth",type:"range",min:1,max:3,value:h,onChange:j=>d(parseInt(j.target.value,10)),style:{marginLeft:8,verticalAlign:"middle"}}),h]}),e.jsx("button",{type:"button",className:"icon-btn",onClick:y,title:"Refresh graph",disabled:n,children:e.jsx(oe,{size:14,className:n?"memory-spin":""})})]}),e.jsx(po,{})]})]}),e.jsx(G,{children:n&&!a.nodes.length?e.jsxs("div",{className:"view-loading",children:[e.jsx(le,{size:"lg"}),e.jsx("p",{children:"Loading graph…"})]}):c&&!a.nodes.length?e.jsxs("div",{className:"muted text-sm",children:["Failed to load graph: ",c]}):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(ho,{data:$,onNodeClick:w,className:"memory-graph-canvas-svg"}),x&&e.jsxs("div",{className:"text-xs muted",style:{marginTop:4},children:["Showing ",$.nodes.length," of ",a.nodes.length," nodes"]})]})}),z&&e.jsxs(G,{children:[e.jsx(se,{children:z.label}),e.jsx(ae,{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":""]}),x&&e.jsxs("span",{className:"muted",children:["· ",$.nodes.length," shown"]})]})})]})}function jo({onTextExtracted:s}){const t=re(),[a,i]=r.useState(null),[n,o]=r.useState(!1),[c,l]=r.useState(!1),x=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 u=document.createElement("canvas");u.width=m.videoWidth,u.height=m.videoHeight;const g=u.getContext("2d");if(!g){t.error("Failed to get canvas context");return}g.drawImage(m,0,0),d.getTracks().forEach(k=>k.stop()),m.remove(),u.toBlob(async k=>{if(!k){t.error("Failed to capture screenshot");return}const z=URL.createObjectURL(k);i(z),await p(k)},"image/png")}catch(d){d.name!=="NotAllowedError"&&t.error(`Capture failed: ${d.message}`)}finally{l(!1)}},[t]),p=r.useCallback(async d=>{o(!0);try{const m=new FileReader,u=await new Promise((k,z)=>{m.onload=()=>{const C=m.result,y=C.includes(",")?C.split(",")[1]:C;k(y)},m.onerror=()=>z(new Error("FileReader failed")),m.readAsDataURL(d)}),g=await R.post("/ocr/process",{image:u,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{o(!1)}},[t,s]),h=r.useCallback(()=>{i(null)},[]);return e.jsxs(G,{variant:"outlined",className:"screenshot-capture-card",children:[e.jsxs(se,{children:[e.jsx(et,{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(me,{size:12,className:"spinner"})," Extracting text…"]}),e.jsx(T,{variant:"ghost",size:"sm",onClick:h,disabled:n,children:"Dismiss"})]})]}):e.jsxs("div",{className:"screenshot-capture-empty",children:[e.jsx(et,{size:32,className:"muted"}),e.jsx("p",{className:"muted text-sm",children:"Capture your screen to extract text via OCR."}),e.jsxs(T,{variant:"primary",size:"sm",onClick:x,disabled:c,children:[c?e.jsx(me,{size:12,className:"spinner"}):e.jsx(et,{size:12}),c?"Selecting…":"Capture Screen"]})]})})]})}function fo(){const[s,t]=r.useState(null),[a,i]=r.useState(null),n=(o,c)=>{t(o),i(c)};return e.jsxs("div",{className:"screenshot-ocr-panel",children:[e.jsx(jo,{onTextExtracted:n}),s!==null&&e.jsxs(G,{variant:"outlined",className:"screenshot-ocr-result-card",children:[e.jsxs(se,{children:[e.jsx(be,{size:14})," Extracted Text"]}),a&&e.jsxs(ae,{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 vo({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(fo,{})})})})}function yo({refreshKey:s}){const t=re(),[a,i]=r.useState(""),[n,o]=r.useState(""),[c,l]=r.useState(""),[x,p]=r.useState(!1),h=async()=>{if(!c.trim()){t.error("Content is required");return}p(!0);try{const d=await R.post("/clipboard/save",{url:a.trim()||void 0,title:n.trim()||void 0,content:c,savedAt:new Date().toISOString()});d.ok&&(t.success(`Saved to ${d.notePath}`),i(""),o(""),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(Na,{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=>o(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:c,onChange:d=>l(d.target.value)}),e.jsx("div",{className:"vault-clipboard-actions",style:{marginTop:12},children:e.jsxs(T,{variant:"primary",size:"sm",onClick:h,disabled:x||!c.trim(),children:[x&&e.jsx(me,{size:12,className:"spinner"}),"Save to Vault"]})})]})})})})}function bo({vaultPath:s,onSaved:t}){const[a,i]=r.useState(!1),[n,o]=r.useState(!1),c=r.useRef(null),l=r.useRef([]),x=async()=>{try{const d=await navigator.mediaDevices.getUserMedia({audio:!0}),m=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm",u=new MediaRecorder(d,{mimeType:m});u.ondataavailable=g=>{g.data&&g.data.size>0&&l.current.push(g.data)},u.onstop=async()=>{const g=new Blob(l.current,{type:"audio/webm"});l.current=[],d.getTracks().forEach(k=>k.stop()),await h(g)},u.start(1e3),c.current=u,i(!0)}catch(d){console.error("[VoiceRecorder] failed to start recording:",d)}},p=()=>{const d=c.current;d&&(d.stop(),i(!1),o(!0))},h=async d=>{try{const m=new FormData;m.append("audio",d,"voice-note.webm"),m.append("vaultPath",s||"");const u=await fetch("/api/voice/upload",{method:"POST",body:m});if(!u.ok){console.error("[VoiceRecorder] upload failed:",u.status,await u.text()),o(!1);return}const{notePath:g,transcription:k}=await u.json();t==null||t(g,k)}catch(m){console.error("[VoiceRecorder] upload error:",m)}finally{o(!1)}};return e.jsxs("div",{className:"voice-recorder",children:[!a&&!n&&e.jsxs(T,{variant:"accent",size:"sm",onClick:x,"aria-label":"Start recording",children:[e.jsx(It,{size:14})," Record"]}),a&&e.jsxs(T,{variant:"danger",size:"sm",onClick:p,"aria-label":"Stop recording",children:[e.jsx(Bn,{size:14})," Stop"]}),n&&e.jsxs(T,{variant:"secondary",size:"sm",disabled:!0,children:[e.jsx(me,{size:14,className:"spinning"})," Transcribing…"]})]})}function No({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}),o=()=>{n&&(a?(n.pause(),n.currentTime=0,i(!1)):(n.play(),i(!0)))},c=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:c}),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:o,"aria-label":a?"Pause":"Play",title:a?"Pause":"Play",children:a?e.jsx(Rt,{size:13}):e.jsx(ys,{size:13})}),e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>t(s.id),"aria-label":"Delete note",title:"Delete note",children:e.jsx(ke,{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 ko({vaultPath:s,refreshKey:t=0}){const[a,i]=r.useState([]),[n,o]=r.useState(""),[c,l]=r.useState(!0),x=async()=>{l(!0);try{const d=s?`?vaultPath=${encodeURIComponent(s)}`:"",u=await(await fetch(`/api/voice/list${d}`)).json();i(u.notes||[])}catch(d){console.error("[VoiceNotesPanel] failed to load notes:",d)}finally{l(!1)}};r.useEffect(()=>{x();const d=g=>{try{const k=JSON.parse(g.data);k.type==="voice:updated"&&k.noteId&&i(z=>z.map(C=>{var y;return C.id===k.noteId?{...C,transcript:((y=k.patch)==null?void 0:y.transcript)??C.transcript}:C}))}catch{}},m=`${location.protocol==="https:"?"wss":"ws"}://${location.host}/ws`;let u=null;try{u=new WebSocket(m),u.addEventListener("message",d)}catch{}return()=>{u==null||u.removeEventListener("message",d),u==null||u.close()}},[s,t]);const p=async d=>{try{const m=await fetch(`/api/voice/${d}`,{method:"DELETE"});(m.ok||m.status===204)&&i(u=>u.filter(g=>g.id!==d))}catch(m){console.error("[VoiceNotesPanel] delete failed:",m)}},h=a.filter(d=>{var m;return!n||(((m=d.transcript)==null?void 0:m.toLowerCase().includes(n.toLowerCase()))??!1)});return e.jsxs(G,{children:[e.jsxs(se,{children:[e.jsx(It,{size:14})," Voice Notes"]}),e.jsx(ae,{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=>o(d.target.value),placeholder:"Search transcripts…","aria-label":"Search voice notes"})}),e.jsx("div",{className:"voice-recorder-row",children:e.jsx(bo,{vaultPath:s,onSaved:x})}),c?e.jsx("p",{className:"muted text-sm",children:"Loading notes…"}):h.length===0?e.jsx("p",{className:"muted text-sm",children:n?"No notes match your search.":"No voice notes yet. Hit Record to add one."}):e.jsx("div",{className:"voice-note-list",children:h.map(d=>e.jsx(No,{note:d,onDelete:p},d.id))})]})}const wo=[{id:"overview",label:"Overview",icon:oa},{id:"lightrag",label:"LightRAG",icon:Fe},{id:"obsidian",label:"Obsidian Vault",icon:be},{id:"git",label:"Git Sync",icon:ts},{id:"semantic",label:"Semantic Search",icon:Se},{id:"config",label:"Config",icon:bt},{id:"graph",label:"Memory Graph",icon:ba},{id:"webclip",label:"Web Clip",icon:Na},{id:"screenshot",label:"Screenshot OCR",icon:_n},{id:"voice",label:"Voice Notes",icon:It}];function So(s){const t=re(),[a,i]=r.useState("overview"),[n,o]=r.useState(0),c=r.useCallback(()=>{o(p=>p+1)},[]),l=r.useCallback(async()=>{c(),t.info("Refreshing memory…",1200)},[c,t]),x=()=>{switch(a){case"overview":return e.jsx(Jl,{refreshKey:n,onRefresh:c,setActiveSubPanel:i});case"lightrag":return e.jsx(eo,{refreshKey:n});case"obsidian":return e.jsx(to,{refreshKey:n});case"git":return e.jsx(ro,{refreshKey:n});case"semantic":return e.jsx(lo,{refreshKey:n});case"config":return e.jsx(oo,{refreshKey:n});case"graph":return e.jsx(go,{refreshKey:n});case"webclip":return e.jsx(yo,{refreshKey:n});case"screenshot":return e.jsx(vo,{refreshKey:n});case"voice":return e.jsx(ko,{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(Fe,{size:18})," Memory"]}),e.jsx("p",{className:"view-subtitle",children:"LightRAG, Obsidian vault, git sync, semantic search, web clips, and screenshot OCR — all in one place."})]}),e.jsx("div",{className:"view-actions",children:e.jsx("button",{type:"button",className:"icon-btn",onClick:l,"aria-label":"Refresh memory",title:"Refresh",children:e.jsx(oe,{size:14})})})]}),e.jsxs("div",{className:"memory-tab-body",children:[e.jsx("nav",{className:"memory-source-rail","aria-label":"Memory sources",children:wo.map(p=>{const h=p.icon,d=a===p.id;return e.jsxs("button",{type:"button",role:"tab","aria-selected":d,className:H("memory-source-button",d&&"memory-source-button-active"),onClick:()=>i(p.id),children:[e.jsx(h,{size:16,"aria-hidden":!0}),e.jsx("span",{children:p.label})]},p.id)})}),e.jsx("div",{className:"memory-main",children:x()},a)]})]})}const Co=De.memo(So),ws=[{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 zo(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($e,{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(be,{size:11})," ",e.jsx("span",{className:"history-project-stat-num",children:s.plans}),e.jsxs("span",{className:"muted",children:[" plan",s.plans===1?"":"s"]})]}),s.lastAccessed&&e.jsx("span",{className:"history-project-stat",children:e.jsxs("span",{className:"muted",children:["last opened ",ze(s.lastAccessed)]})})]}),e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>i(s.id),"aria-label":n?"Collapse":"Expand",children:n?e.jsx(Ue,{size:14}):e.jsx(Xe,{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((o,c)=>e.jsxs("div",{className:"history-timeline-row",children:[e.jsx("span",{className:"history-timeline-ts",children:new Date(o.ts).toLocaleTimeString()}),e.jsx("span",{className:"history-timeline-kind",children:o.kind||"event"}),e.jsxs("span",{className:"history-timeline-msg",title:String(o.text||o.title||""),children:[o.author?`@${o.author} `:"",String(o.text??o.title??o.name??"")]})]},c))})]},s.id)}function Ro({snapshot:s}){var z,C;const t=re(),[a,i]=r.useState(null),[n,o]=r.useState(!0),[c,l]=r.useState("1d"),[x,p]=r.useState(new Set),[h,d]=r.useState(0),m=async y=>{try{const w=y?`?since=${encodeURIComponent(y)}&limit=1000`:"?limit=1000",$=await R.get(`/history${w}`);i($),p(new Set($.projects.filter(j=>$.events.some(N=>N.projectId===j.id)).map(j=>j.id)))}catch(w){t.error(`History load failed: ${w.message}`)}finally{o(!1)}};r.useEffect(()=>{o(!0);const y=ws.find(w=>w.id===c)||ws[1];if(y.ms>0){const w=new Date(Date.now()-y.ms).toISOString();m(w)}else m()},[c]),r.useEffect(()=>{const y=setInterval(()=>d(w=>w+1),3e4);return()=>clearInterval(y)},[]);const u=new Map;for(const y of(a==null?void 0:a.events)||[]){const w=y.projectId||"global";u.has(w)||u.set(w,[]),u.get(w).push(y)}const g=y=>{p(w=>{const $=new Set(w);return $.has(y)?$.delete(y):$.add(y),$})},k=()=>{if(!a)return;const y=new Blob([JSON.stringify(a,null,2)],{type:"application/json"}),w=URL.createObjectURL(y),$=document.createElement("a");$.href=w,$.download=`bizar-history-${new Date().toISOString().replace(/[:.]/g,"-")}.json`,$.click(),URL.revokeObjectURL(w),t.success("History exported.")};return e.jsxs("div",{className:"view view-history","data-tick":h,children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(Ts,{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 ",ze(a.stats.lastTs)]})]})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs("div",{className:"tasks-toolbar-group",children:[e.jsx(qn,{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:c,onChange:y=>l(y.target.value),title:"Time range","aria-label":"Time range",children:ws.map(y=>e.jsx("option",{value:y.id,children:y.label},y.id))})]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:()=>{o(!0);const y=ws.find(w=>w.id===c)||ws[1];y.ms>0?m(new Date(Date.now()-y.ms).toISOString()):m()},children:[e.jsx(oe,{size:14})," Refresh"]}),e.jsxs(T,{variant:"secondary",size:"sm",onClick:k,children:[e.jsx(as,{size:14})," Export"]})]})]}),n&&e.jsxs("div",{className:"view-loading",children:[e.jsx(le,{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(se,{children:[e.jsx($e,{size:14})," No projects"]}),e.jsx(ae,{children:"Register a project in Overview to start tracking history."})]}),a.projects.length>0&&e.jsx(Mt,{items:a.projects,itemHeight:70,height:Math.min(a.projects.length*70,500),className:"history-virtual-list",renderItem:y=>zo(y,u.get(y.id)||[],x,g)}),u.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(Ts,{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:(u.get("global")||[]).slice(-100).reverse().map((y,w)=>e.jsxs("div",{className:"history-timeline-row",children:[e.jsx("span",{className:"history-timeline-ts",children:new Date(y.ts).toLocaleTimeString()}),e.jsx("span",{className:"history-timeline-kind",children:y.kind||"event"}),e.jsxs("span",{className:"history-timeline-msg",title:String(y.text||y.title||""),children:[y.author?`@${y.author} `:"",String(y.text??y.title??y.name??"")]})]},w))})]}),((C=a.stats)==null?void 0:C.counts)&&Object.keys(a.stats.counts).length>0&&e.jsxs(G,{children:[e.jsx(se,{children:"Event counts by kind"}),e.jsxs(ae,{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((y,w)=>w[1]-y[1]).slice(0,30).map(([y,w])=>e.jsxs("span",{className:H("tag","tag-neutral"),style:{fontFamily:"var(--font-mono)"},children:[y,": ",w]},y))})]})]})]})}const fe={top:16,right:20,bottom:40,left:52};function To({series:s,height:t=280,onHover:a,className:i}){const n=r.useRef(null),[o,c]=r.useState(null),{labels:l,requests:x,tokens:p}=s,h=l.length;if(h===0)return e.jsx("div",{className:H("usage-chart-empty",i),style:{height:t},children:e.jsx("span",{children:"No data for this range"})});const d=600-fe.left-fe.right,m=t-fe.top-fe.bottom,u=Math.max(...x,1),g=Math.max(...p,1),k=Math.max(4,Math.min(24,Math.floor(d/h)-4)),z=(d-k*h)/(h+1);function C(A){return fe.left+z+A*(k+z)}function y(A){return A/u*m*.75}function w(A){return fe.top+m-A/g*m*.75}const $=p.map((A,O)=>`${C(O)+k/2},${w(A)}`).join(" "),j=[0,.25,.5,.75,1].map(A=>({y:fe.top+m-A*m*.75,label:A===0?"0":`${Math.round(u*A).toLocaleString()}`})),N=[0,.25,.5,.75,1].map(A=>({y:fe.top+m-A*m*.75,label:A===0?"0":`${Math.round(g*A/1e3)}k`})),v=Math.max(1,Math.floor(h/7)),f=l.map((A,O)=>({i:O,l:A,x:C(O)+k/2})).filter((A,O)=>O%v===0),D=r.useCallback(A=>{if(!n.current)return;const O=n.current.getBoundingClientRect(),S=(A.clientX-O.left)*(600/O.width),F=(A.clientY-O.top)*(t/O.height),_=S-fe.left,P=Math.round((_-z/2)/(k+z)),V=Math.max(0,Math.min(h-1,P));c({index:V,x:A.clientX-O.left,y:A.clientY-O.top}),a==null||a(V,S,F)},[h,k,z,a,t]),M=r.useCallback(()=>{c(null),a==null||a(null,0,0)},[a]),b=o;return e.jsxs("div",{ref:n,className:H("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:D,onMouseLeave:M,children:[j.map((A,O)=>e.jsx("line",{x1:fe.left,y1:A.y,x2:600-fe.right,y2:A.y,stroke:"var(--border)",strokeWidth:1,strokeDasharray:"4,3",opacity:.5},`grid-${O}`)),j.map((A,O)=>e.jsx("text",{x:fe.left-6,y:A.y+4,textAnchor:"end",fontSize:10,fill:"var(--text-muted)",fontFamily:"var(--font-mono, ui-monospace, monospace)",children:A.label},`ly-${O}`)),N.map((A,O)=>e.jsx("text",{x:600-fe.right+6,y:A.y+4,textAnchor:"start",fontSize:10,fill:"var(--text-muted)",fontFamily:"var(--font-mono, ui-monospace, monospace)",children:A.label},`ry-${O}`)),x.map((A,O)=>{const S=y(A),F=C(O),_=fe.top+m-S;return e.jsx("rect",{x:F,y:_,width:k,height:S,rx:2,fill:((b==null?void 0:b.index)===O,"var(--accent)"),opacity:(b==null?void 0:b.index)===O?1:.75,style:{transition:"opacity 120ms ease"}},`bar-${O}`)}),e.jsx("polyline",{points:$,fill:"none",stroke:"var(--warning, #d29922)",strokeWidth:2,strokeLinejoin:"round",strokeLinecap:"round",opacity:.9}),p.map((A,O)=>e.jsx("circle",{cx:C(O)+k/2,cy:w(A),r:(b==null?void 0:b.index)===O?5:3,fill:"var(--warning, #d29922)",opacity:(b==null?void 0:b.index)===O?1:.7,style:{transition:"r 120ms ease"}},`dot-${O}`)),f.map(({i:A,l:O,x:S})=>e.jsx("text",{x:S,y:fe.top+m+18,textAnchor:"middle",fontSize:10,fill:"var(--text-muted)",fontFamily:"var(--font-mono, ui-monospace, monospace)",children:O},`xl-${A}`)),e.jsx("line",{x1:fe.left,y1:fe.top+m,x2:600-fe.right,y2:fe.top+m,stroke:"var(--border)",strokeWidth:1})]}),b!==null&&e.jsxs("div",{className:"usage-chart-tooltip",style:{left:Math.min(b.x+12,460),top:b.y-60},children:[e.jsx("div",{className:"usage-tooltip-date",children:l[b.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:x[b.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[b.index].toLocaleString()})]})]})]})}function Ze({label:s,col:t,sortKey:a,sortDir:i,onSort:n}){const o=a===t;return e.jsxs("th",{className:H("usage-sort-header",o&&"is-active"),onClick:()=>n(t),"aria-sort":o?i==="asc"?"ascending":"descending":"none",children:[e.jsx("span",{children:s}),e.jsx("span",{className:"usage-sort-icon",children:o?i==="asc"?" ↑":" ↓":" ↕"})]})}function $o({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(Ze,{label:"Model",col:"modelId",sortKey:t,sortDir:a,onSort:i}),e.jsx(Ze,{label:"Requests",col:"requests",sortKey:t,sortDir:a,onSort:i}),e.jsx(Ze,{label:"Prompt Tok",col:"promptTokens",sortKey:t,sortDir:a,onSort:i}),e.jsx(Ze,{label:"Compl Tok",col:"completionTokens",sortKey:t,sortDir:a,onSort:i}),e.jsx(Ze,{label:"Total Tok",col:"totalTokens",sortKey:t,sortDir:a,onSort:i}),e.jsx(Ze,{label:"Avg Latency",col:"avgLatencyMs",sortKey:t,sortDir:a,onSort:i}),e.jsx(Ze,{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:H("mono",n.errors>0&&"is-err"),children:n.errors>0?n.errors:"—"})]},`${n.providerId}::${n.modelId}`))})]})})}function Ao({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:H("minimax-sub-tab",a==="quota"&&"is-active"),onClick:()=>i("quota"),children:[e.jsx(vt,{size:13})," Token Plan"]}),e.jsxs("button",{className:H("minimax-sub-tab",a==="analytics"&&"is-active"),onClick:()=>i("analytics"),children:[e.jsx(ka,{size:13})," Usage Analytics"]})]}),a==="quota"?e.jsx(Io,{activeTab:s,setActiveTab:t}):e.jsx(Mo,{toast:n})]})}function Io({activeTab:s,setActiveTab:t}){var te;const a=re(),[i,n]=r.useState(null),[o,c]=r.useState(null),[l,x]=r.useState(null),[p,h]=r.useState(!0),[d,m]=r.useState(!1),[u,g]=r.useState(null),[k,z]=r.useState(null),[C,y]=r.useState(!1),[w,$]=r.useState(0),[j,N]=r.useState(!1),[v,f]=r.useState(null),[D,M]=r.useState(""),[b,A]=r.useState(!1),[O,S]=r.useState(!1),F=r.useCallback(async()=>{h(!0),g(null);try{const[Z,ie,je]=await Promise.all([R.get("/minimax/status"),R.get("/minimax/remains"),R.get("/minimax/onboarding")]);n(Z),c(ie),x(je),Z.configured&&$(4)}catch(Z){g(Z.message||"Failed to load MiniMax data")}finally{h(!1)}},[]);r.useEffect(()=>{F()},[F]);const _=r.useCallback(async()=>{try{await R.post("/minimax/onboarding",{dismissedAt:Date.now()}),x(Z=>Z&&{...Z,dismissedAt:Date.now()})}catch{}},[]),P=r.useCallback(async()=>{if(!D.trim()){a.error("Paste a Subscription Key first.");return}N(!0),f(null);try{const Z=await R.post("/minimax/test",{prompt:"Reply with a single word: pong",model:"MiniMax-M3",maxTokens:16});if(f(Z),Z.ok){$(3),a.success("Key works. Saving…");try{await R.post("/minimax/onboarding/save-key",{key:D.trim(),groupId:"default"}),W(),a.success("Subscription Key saved.")}catch(ie){a.error(`Save failed: ${ie.message}`)}F()}else a.error(`Verification failed: ${Z.message??Z.error??"unknown"}`)}catch(Z){a.error(`Test request failed: ${Z.message}`)}finally{N(!1)}},[D,a,F]),V=r.useCallback(async()=>{if(!D.trim()){a.error("Paste a Subscription Key first.");return}S(!0);try{const Z=await R.post("/minimax/onboarding/save-key",{key:D.trim(),groupId:"default"});if(!Z.ok){a.error(`Save failed: ${Z.message??Z.error??"unknown"}`);return}M(""),W(),a.success("Subscription Key saved. Loading quota…"),F()}catch(Z){a.error(`Save failed: ${Z.message}`)}finally{S(!1)}},[D,a,F]),W=r.useCallback(async()=>{try{await R.del("/minimax/cache")}catch{}},[]),K=r.useCallback(async()=>{m(!0),g(null);try{await R.post("/minimax/remains/refresh"),await F(),a.success("Refreshed")}catch(Z){a.error(`Refresh failed: ${Z.message}`)}finally{m(!1)}},[F,a]),B=r.useCallback(async()=>{var Z;y(!0),z(null);try{const ie=await R.post("/minimax/test",{prompt:"Reply with a single word: pong",model:"MiniMax-M3",maxTokens:16});z(ie),ie.ok?a.success(`Test ok — used ${((Z=ie.usage)==null?void 0:Z.total_tokens)??"?"} tokens`):a.error(`Test failed: ${ie.message??ie.error??"unknown"}`)}catch(ie){a.error(`Test request failed: ${ie.message}`)}finally{y(!1)}},[a]);return p&&!i?e.jsxs("div",{className:"view-container",children:[e.jsx(le,{})," Loading MiniMax data…"]}):i?!i.configured&&(l==null?void 0:l.dismissedAt)==null&&w<4?e.jsx(Do,{step:w,setStep:$,keyDraft:D,setKeyDraft:M,showKey:b,setShowKey:A,verifying:j,verifyResult:v,onVerify:P,onSkip:async()=>{await _(),a.success("Skipped.")},onManualKeySave:V,savingKey:O,status:i}):e.jsxs(e.Fragment,{children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-titles",children:[e.jsxs("h1",{className:"view-title",children:[e.jsx(vt,{size:20,style:{verticalAlign:"text-bottom",marginRight:6}}),"MiniMax Token Plan"]}),e.jsxs("p",{className:"view-subtitle",children:["Remaining 5-hour + weekly quota per model. Fetches live from"," ",e.jsx("code",{children:"www.minimax.io/v1/token_plan/remains"}),"."]})]}),e.jsxs("div",{className:"view-header-actions",children:[e.jsxs(T,{variant:"secondary",size:"sm",onClick:()=>t("settings"),title:"Configure your Subscription Key",children:[e.jsx($t,{size:14})," ",i.configured?`Key ${i.apiKeyHint}`:"Add key"]}),e.jsxs(T,{variant:"secondary",size:"sm",onClick:K,disabled:d,children:[d?e.jsx(me,{size:14,className:"spin"}):e.jsx(oe,{size:14})," Refresh"]})]})]}),o&&!o.ok&&e.jsxs("div",{className:"banner banner-err",children:[e.jsx(ye,{size:16}),e.jsxs("span",{children:[e.jsx("strong",{children:"Couldn't load quota"}),": ",o.message??o.error??"unknown error"]})]}),(o==null?void 0:o.ok)&&o.models&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"minimax-stats-row",children:[e.jsx(Us,{label:"Models tracked",value:String(o.models.length),hint:"Distinct model quotas returned by the API"}),e.jsx(Us,{label:"Last fetched",value:o.fetchedAt?Eo(o.fetchedAt):"—",hint:"Refreshed on demand + every 60s"}),e.jsx(Us,{label:"Group",value:o.groupId??"—",hint:"Usually 'default' for an individual team"}),e.jsx(Us,{label:"API key",value:o.apiKeyHint??"—",hint:"Masked; the real key never leaves auth.json"})]}),e.jsx("div",{className:"minimax-models-grid",children:o.models.map(Z=>e.jsx(Lo,{model:Z},Z.model_name))})]}),i.configured&&e.jsxs(G,{id:"minimax-test",children:[e.jsxs(se,{children:[e.jsx(Ye,{size:14})," Test the API key"]}),e.jsxs(ae,{children:["One-shot chat completion to ",e.jsxs("code",{children:[i.chatBaseUrl,"/chat/completions"]}),"."]}),e.jsxs("div",{className:"minimax-test-actions",children:[e.jsxs(T,{onClick:B,disabled:C,variant:"primary",size:"sm",children:[C?e.jsx(me,{size:14,className:"spin"}):e.jsx(Ye,{size:14})," Send test prompt"]}),e.jsx("code",{className:"minimax-test-prompt",children:'"Reply with a single word: pong"'})]}),k&&e.jsxs("div",{className:H("minimax-test-result",k.ok?"ok":"err"),children:[k.ok?e.jsx(Ee,{size:14}):e.jsx(ye,{size:14}),e.jsx("div",{className:"minimax-test-body",children:k.ok?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"minimax-test-line",children:[e.jsx("strong",{children:"model:"})," ",e.jsx("code",{children:k.model})," ·"," ",e.jsx("strong",{children:"finish:"})," ",k.finishReason??"—"]}),k.content&&e.jsx("div",{className:"minimax-test-content",children:e.jsx("code",{children:k.content})}),k.usage&&e.jsxs("div",{className:"minimax-test-usage",children:[e.jsx("strong",{children:"usage:"})," total ",e.jsx("code",{children:k.usage.total_tokens??"?"})," · prompt"," ",e.jsx("code",{children:k.usage.prompt_tokens??"?"})," · completion"," ",e.jsx("code",{children:k.usage.completion_tokens??"?"}),((te=k.usage.prompt_tokens_details)==null?void 0:te.cached_tokens)!=null&&e.jsxs(e.Fragment,{children:[" · cached ",e.jsx("code",{children:k.usage.prompt_tokens_details.cached_tokens})]})]})]}):e.jsx("pre",{children:k.message??k.error??"unknown error"})})]})]})]}):e.jsx("div",{className:"view-container",children:e.jsxs("div",{className:"error-card",children:[e.jsx(ye,{size:20}),e.jsxs("div",{children:[e.jsx("strong",{children:"Couldn't load MiniMax status"}),e.jsx("pre",{children:u??"unknown error"})]})]})})}function Mo({toast:s}){const[t,a]=r.useState("24h"),[i,n]=r.useState(""),[o,c]=r.useState(""),[l,x]=r.useState(!0),[p,h]=r.useState(null),[d,m]=r.useState([]),[u,g]=r.useState("requests"),[k,z]=r.useState("desc"),[C,y]=r.useState(!1),w=r.useCallback(async(b,A,O)=>{x(!0);try{const S=new URLSearchParams({range:b});b==="custom"&&A&&O&&(S.set("from",String(A)),S.set("to",String(O)));const[F,_]=await Promise.all([R.get(`/usage?${S.toString()}`),R.get("/usage/recent?limit=20")]);h(F),m(_.records)}catch(S){s.error(`Failed to load usage data: ${S.message}`)}finally{x(!1)}},[s]);r.useEffect(()=>{if(t==="custom"){const b=i?new Date(i).getTime():Date.now()-6048e5,A=o?new Date(o).getTime():Date.now();w("custom",b,A)}else w(t)},[t,w]);const $=r.useCallback(b=>{u===b?z(A=>A==="asc"?"desc":"asc"):(g(b),z("desc"))},[u]),j=r.useMemo(()=>p!=null&&p.perModel?[...p.perModel].sort((b,A)=>{const O=b[u]??0,S=A[u]??0,F=typeof O=="number"&&typeof S=="number"?O-S:String(O).localeCompare(String(S));return k==="asc"?F:-F}):[],[p==null?void 0:p.perModel,u,k]),N=r.useMemo(()=>p!=null&&p.daily?{labels:p.daily.map(b=>b.date.slice(5)),requests:p.daily.map(b=>b.requests),tokens:p.daily.map(b=>b.totalTokens)}:{labels:[],requests:[],tokens:[]},[p==null?void 0:p.daily]),v=r.useCallback(async()=>{y(!0),await w(t==="custom"?"custom":t,t==="custom"&&i?new Date(i).getTime():void 0,t==="custom"&&o?new Date(o).getTime():void 0),y(!1)},[w,t,i,o]);if(l&&!p)return e.jsxs("div",{className:"view-container",children:[e.jsx(le,{})," Loading usage data…"]});const f=p==null?void 0:p.totals,D=(p==null?void 0:p.errors)??[],M=(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(ka,{size:20,style:{verticalAlign:"text-bottom",marginRight:6}}),"Usage Analytics"]}),e.jsxs("p",{className:"view-subtitle",children:["Aggregated from ",e.jsx("code",{children:"~/.local/share/bizar/usage.jsonl"})," — every chatCompletion and fetchRemains call."]})]}),e.jsx("div",{className:"view-header-actions",children:e.jsxs(T,{variant:"secondary",size:"sm",onClick:v,disabled:C,children:[C?e.jsx(me,{size:14,className:"spin"}):e.jsx(oe,{size:14})," Refresh"]})})]}),e.jsxs("div",{className:"usage-time-range",children:[["24h","7d","30d","custom"].map(b=>e.jsx("button",{className:H("usage-range-chip",t===b&&"is-active"),onClick:()=>a(b),children:b==="custom"?"Custom":b.toUpperCase()},b)),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:b=>n(b.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:o,onChange:b=>c(b.target.value),"aria-label":"To date"})]})]}),e.jsxs("div",{className:"usage-kpi-row",children:[e.jsx(Ss,{label:"Total Requests",value:(f==null?void 0:f.requests.toLocaleString())??"—",sub:f?`${f.errors} errors`:void 0,tone:f&&f.errors>f.requests*.1?"warn":void 0}),e.jsx(Ss,{label:"Total Tokens",value:f?f.totalTokens>=1e3?`${Math.round(f.totalTokens/1e3)}k`:String(f.totalTokens):"—",sub:f?`${f.promptTokens.toLocaleString()} prompt · ${f.completionTokens.toLocaleString()} completion`:void 0}),e.jsx(Ss,{label:"Errors",value:String((f==null?void 0:f.errors)??"—"),sub:D.length>0?`${D[0].code}: ${D[0].count}`:void 0,tone:f&&f.errors>0?"err":void 0}),e.jsx(Ss,{label:"Avg Latency",value:(f==null?void 0:f.avgLatencyMs)!=null?`${f.avgLatencyMs}ms`:"—",sub:(f==null?void 0:f.p95LatencyMs)!=null?`p95 ${f.p95LatencyMs}ms`:void 0}),e.jsx(Ss,{label:"Est. Cost",value:(f==null?void 0:f.costEstimate)!=null&&f.costEstimate>0?`$${f.costEstimate.toFixed(4)}`:"—",sub:"approximate USD",tone:void 0})]}),e.jsxs(G,{className:"usage-chart-card",children:[e.jsx("div",{className:"usage-chart-wrap",children:e.jsx(To,{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(se,{children:"Per-model breakdown"}),e.jsx($o,{rows:j,sortKey:u,sortDir:k,onSort:$})]}),M.length>0&&e.jsxs(G,{children:[e.jsx(se,{children:"API Keys"}),e.jsx("div",{className:"usage-key-row",children:M.map(b=>e.jsxs("span",{className:H("usage-key-badge",b.isBackup?"is-backup":"is-active"),children:[e.jsx("span",{className:"usage-key-dot"}),b.keyEnvVar,b.isBackup?" (backup)":" (active)"," · ",b.requests," req"]},b.keyEnvVar))})]}),d.length>0&&e.jsxs(G,{children:[e.jsx(se,{children:"Recent activity"}),e.jsx("div",{className:"usage-recent-list",children:d.map((b,A)=>e.jsxs("div",{className:H("usage-recent-item",b.error&&"is-err"),children:[e.jsx("span",{className:"usage-recent-time",children:new Date(b.ts).toLocaleTimeString()}),e.jsx("span",{className:"usage-recent-model",children:e.jsx("code",{children:b.modelId})}),e.jsxs("span",{className:"usage-recent-tokens",children:[b.totalTokens.toLocaleString()," tok"]}),e.jsxs("span",{className:"usage-recent-latency",children:[b.latencyMs,"ms"]}),e.jsx("span",{className:"usage-recent-endpoint",children:b.endpoint})]},`${b.requestId}-${A}`))})]})]})}function Ss({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:H("usage-kpi-value",i&&`is-${i}`),children:t}),a&&e.jsx("div",{className:"usage-kpi-sub",children:a})]})}function Us({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 Lo({model:s}){const t=Bs(s.current_interval_remaining_percent??0,0,100),a=Bs(s.current_weekly_remaining_percent??0,0,100),i=Bs(100-t,0,100),n=Bs(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:H("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(ta,{icon:e.jsx(Te,{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(ta,{icon:e.jsx(Wn,{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 ta({icon:s,label:t,remainingPct:a,consumedPct:i,used:n,total:o,resetIn:c,resetISO:l}){const x=a>=75?"good":a>=25?"warn":"low";return e.jsxs("div",{className:`minimax-quota-row is-${x}`,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})," / ",o||"—"," requests"]}),e.jsx("span",{title:l,children:c?`resets in ${c}`:"—"})]})]})}function Bs(s,t,a){return Math.max(t,Math.min(a,s))}function Eo(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 Do({step:s,setStep:t,keyDraft:a,setKeyDraft:i,showKey:n,setShowKey:o,verifying:c,verifyResult:l,onVerify:x,onSkip:p,onManualKeySave:h,savingKey:d,status:m}){return e.jsxs("div",{className:"view-container view-minimax-onboarding",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-titles",children:[e.jsxs("h1",{className:"view-title",children:[e.jsx(We,{size:20,style:{verticalAlign:"text-bottom",marginRight:6}}),"Set up MiniMax Token Plan tracking"]}),e.jsx("p",{className:"view-subtitle",children:"We'll read your Subscription Key and show your remaining quota."})]}),e.jsx("div",{className:"view-header-actions",children:e.jsxs(T,{variant:"ghost",size:"sm",onClick: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((u,g)=>e.jsxs("div",{className:H("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(Ee,{size:14}):g+1}),e.jsx("div",{className:"minimax-wizard-step-label",children:u})]},u))}),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(T,{onClick:()=>t(1),variant:"primary",size:"md",children:["Get started ",e.jsx("span",{style:{marginLeft:6},children:"→"})]})})]}),s===1&&e.jsxs("div",{className:"minimax-wizard-body",children:[e.jsx("h3",{className:"minimax-wizard-title",children:"Get your Subscription Key"}),e.jsx("p",{className:"minimax-wizard-prose",children:"Go to the MiniMax console and copy your Subscription Key."}),e.jsxs("ol",{className:"minimax-wizard-list",children:[e.jsxs("li",{children:["Open ",e.jsxs("a",{href:"https://platform.minimax.io/user-center/payment/token-plan",target:"_blank",rel:"noreferrer",className:"minimax-wizard-link",children:[e.jsx(vs,{size:12})," platform.minimax.io"]})]}),e.jsxs("li",{children:["Click ",e.jsx("strong",{children:"Copy Subscription Key"}),"."]}),e.jsx("li",{children:"Come back here and paste it."})]}),e.jsxs("div",{className:"minimax-wizard-actions",children:[e.jsx(T,{variant:"secondary",size:"md",onClick:()=>t(0),children:"← Back"}),e.jsxs(T,{variant:"primary",size:"md",onClick:()=>t(2),children:["I have my key ",e.jsx("span",{style:{marginLeft:6},children:"→"})]})]})]}),s===2&&e.jsxs("div",{className:"minimax-wizard-body",children:[e.jsx("h3",{className:"minimax-wizard-title",children:"Paste & test"}),e.jsx("p",{className:"minimax-wizard-prose",children:"Paste your key below. We'll test it against the real API before saving."}),e.jsx("div",{className:"minimax-key-row",children:e.jsxs("div",{className:"minimax-key-input-wrap",children:[e.jsx($t,{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:u=>i(u.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:()=>o(u=>!u),className:"minimax-key-toggle","aria-label":n?"Hide key":"Show key",children:n?e.jsx(ut,{size:13}):e.jsx(gs,{size:13})})]})}),l&&!l.ok&&e.jsxs("div",{className:"minimax-wizard-error",children:[e.jsx(ye,{size:14}),e.jsxs("span",{children:[e.jsx("strong",{children:"Verification failed:"})," ",l.message??l.error]})]}),e.jsxs("div",{className:"minimax-wizard-actions",children:[e.jsx(T,{variant:"secondary",size:"md",onClick:()=>t(1),children:"← Back"}),e.jsxs(T,{variant:"primary",size:"md",onClick:x,disabled:c||!a.trim(),children:[c?e.jsx(me,{size:14,className:"spin"}):e.jsx($s,{size:14}),c?"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:u=>{u.preventDefault(),h()},className:"minimax-wizard-link",children:"Save without testing"})]})]}),s===3&&e.jsxs("div",{className:"minimax-wizard-body",children:[e.jsxs("h3",{className:"minimax-wizard-title",children:[e.jsx(Ee,{size:18,style:{verticalAlign:"text-bottom",marginRight:6}}),"All set"]}),e.jsx("p",{className:"minimax-wizard-prose",children:"The key works and is saved. Reloading so you can see your live quota."}),e.jsx("div",{className:"minimax-wizard-actions",children:e.jsx(T,{variant:"primary",size:"md",onClick:()=>window.location.reload(),children:"View your quota →"})})]}),e.jsxs("div",{className:"minimax-wizard-footer",children:[e.jsx($s,{size:11}),e.jsxs("span",{children:["Key written to ",e.jsx("code",{children:"~/.local/share/opencode/auth.json"})," with mode 0600."]})]})]})]})}const Po=De.memo(Ao),Fo={pending:"info",running:"accent",done:"success",failed:"error",killed:"neutral",timed_out:"warning"},Oo={pending:"Pending",running:"Running",done:"Done",failed:"Failed",killed:"Killed",timed_out:"Timed out"};function Uo({status:s,dot:t}){const a=Fo[s]||"neutral",i=Oo[s]||s;return e.jsx(Ve,{kind:a,dot:t,children:i})}function Bo({instanceId:s,instanceName:t,onConfirm:a,onClose:i}){return e.jsxs("div",{children:[e.jsxs("p",{style:{marginBottom:16,lineHeight:1.6},children:["Instance ",e.jsx("code",{children:s}),t?e.jsxs(e.Fragment,{children:[" (",t,")"]}):null," will be terminated. This cannot be undone."]}),e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx(T,{variant:"ghost",onClick:i,children:"Cancel"}),e.jsx(T,{variant:"danger",onClick:async()=>{await a(),i()},children:"Kill"})]})]})}function _o(s,t,a,i,n){s.open({title:"Kill instance?",width:400,children:e.jsx(Bo,{instanceId:a,instanceName:i,onConfirm:async()=>{try{const c=await(await fetch(`/api/background/${encodeURIComponent(a)}`,{method:"DELETE"})).json();c.ok?(t.success(`Instance ${a} killed.`),n==null||n()):t.error(`Kill failed: ${c.error||"unknown error"}`)}catch(o){t.error(`Kill failed: ${o.message}`)}},onClose:()=>s.close()})})}function qo({instance:s}){const t=re(),[a,i]=r.useState(!1),n=s.tmuxSession,o=n?`tmux attach -t ${n}`:null,c=async()=>{if(o)try{await navigator.clipboard.writeText(o),t.success("Attach command copied")}catch{t.error("Could not copy to clipboard")}},l=async()=>{if(!(!s.instanceId||!n)){i(!0);try{const x=await R.post(`/background/${encodeURIComponent(s.instanceId)}/open-terminal`,{emulator:"system"});if(x.ok)t.success("Opening terminal…");else if(t.error(x.error||"Failed to open terminal"),o)try{await navigator.clipboard.writeText(o),t.success("Command copied to clipboard")}catch{}}catch(x){if(t.error(`Failed: ${x.message}`),o)try{await navigator.clipboard.writeText(o),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(Ke,{size:14}),e.jsx("span",{children:"tmux session"}),s.tmuxActive!==!1?e.jsx("span",{className:"badge badge-success",children:"live"}):e.jsx("span",{className:"badge badge-warning",children:"inactive"})]}),e.jsx("code",{className:"mono bg-tmux-session-name",children:n}),e.jsx("p",{className:"muted bg-tmux-hint",children:"Attach to the agent's tmux session from a terminal on the host running the dashboard."}),e.jsxs("div",{className:"bg-tmux-card-actions",children:[e.jsxs(T,{variant:"ghost",size:"sm",onClick:c,title:"Copy attach command",children:[e.jsx(ns,{size:14})," Copy"]}),e.jsxs(T,{variant:"primary",size:"sm",onClick:l,loading:a,title:"Open in system terminal",children:[e.jsx(Ke,{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(ye,{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 Wo=[{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"}],Vo=[{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 Ho({open:s,onClose:t,onCreated:a,agents:i=Wo}){var N;const n=re(),[o,c]=r.useState(((N=i[0])==null?void 0:N.name)||"mimir"),[l,x]=r.useState(""),[p,h]=r.useState(""),[d,m]=r.useState(3e5),[u,g]=r.useState(!1),[k,z]=r.useState(""),[C,y]=r.useState(!1),[w,$]=r.useState(null);if(!s)return null;const j=async v=>{if(v.preventDefault(),$(null),!l.trim()){$("Prompt is required.");return}y(!0);try{const f=k.split(",").map(b=>b.trim()).filter(b=>b.length>0),D={agent:o,prompt:l,...p.trim()?{model:p.trim()}:{},timeoutMs:d,persistent:u,maxRestarts:3,...f.length>0?{tags:f}:{}},M=await R.post("/background",D);if(M!=null&&M.error)throw new Error(M.message||M.error);n.success(`Spawned ${o} (${M.instanceId.slice(0,14)}…)`),a==null||a(M.instanceId),x(""),h(""),g(!1),z(""),t()}catch(f){$((f==null?void 0:f.message)||"Failed to spawn.")}finally{y(!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(ve,{size:18})," Spawn background agent"]}),e.jsx(T,{variant:"ghost",size:"sm",onClick:t,title:"Close",children:e.jsx(Ne,{size:14})})]}),e.jsxs("form",{onSubmit:j,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:o,onChange:v=>c(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=>x(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=>h(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:Vo.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:u,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:k,onChange:v=>z(v.target.value),placeholder:"e.g. refactor, urgent"})]}),w&&e.jsx("div",{className:"spawn-modal-error",children:w}),e.jsxs("div",{className:"spawn-modal-actions",children:[e.jsx(T,{variant:"ghost",size:"sm",type:"button",onClick:t,children:"Cancel"}),e.jsx(T,{variant:"primary",size:"sm",type:"submit",disabled:C,children:C?"Spawning…":"Spawn agent"})]})]})]})})}const Go=5e3,aa=3e3,Ko=120,Yo=32e3;function Xo(s){return s.status==="pending"||s.status==="running"||s.status==="paused"}function ft(s){return s.status==="paused"}function Qo(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 Jo(s){const t=re(),a=Re(),[i,n]=r.useState([]),[o,c]=r.useState(!0),[l,x]=r.useState(null),[,p]=r.useState(0),[h,d]=r.useState(!1),m=r.useCallback(async()=>{try{const $=await R.get("/background");n(Array.isArray($==null?void 0:$.instances)?$.instances:[]),x(null)}catch($){x(($==null?void 0:$.message)||"Failed to load background agents.")}finally{c(!1)}},[]);r.useEffect(()=>{m();const $=setInterval(m,Go);return()=>clearInterval($)},[m]),r.useEffect(()=>{const $=setInterval(()=>p(j=>(j+1)%1e6),1e3);return()=>clearInterval($)},[]),r.useEffect(()=>{const $=new Hs,j=$.on(N=>{const v=N.type;(v==="background:change"||v==="background:cleanup"||v==="bg:progress"||v==="bg:tool-call")&&m()});return()=>{j(),$.close()}},[m]);const u=i.filter(Xo),g=$=>{ec(a,$)},k=async $=>{try{const j=await R.get(`/background/${encodeURIComponent($.instanceId)}/tmux`);ac(a,j)}catch(j){t.error(`Tmux info failed: ${j.message}`)}},z=$=>{_o(a,t,$.instanceId,$.agent||$.prompt,()=>{n(j=>j.filter(N=>N.instanceId!==$.instanceId))})},C=async $=>{try{const j=await R.post(`/background/${encodeURIComponent($.instanceId)}/pause`,{});j!=null&&j.ok?t.info(`Paused ${$.instanceId.slice(0,14)}…`):t.error((j==null?void 0:j.error)||"Pause failed.")}catch(j){t.error(`Pause failed: ${j.message}`)}},y=async $=>{try{const j=await R.post(`/background/${encodeURIComponent($.instanceId)}/resume`,{});j!=null&&j.ok?t.info(`Resumed ${$.instanceId.slice(0,14)}…`):t.error((j==null?void 0:j.error)||"Resume failed.")}catch(j){t.error(`Resume failed: ${j.message}`)}},w=$=>{nc(a,t,$,m)};return o?e.jsx("div",{className:"bg-active-view",children:e.jsxs("div",{className:"bg-active-loading",children:[e.jsx(le,{size:"md"}),e.jsx("span",{children:"Loading background agents…"})]})}):l?e.jsx("div",{className:"bg-active-view",children:e.jsx(he,{icon:e.jsx(Te,{size:32}),title:"Couldn't load background agents",message:l,action:e.jsxs(T,{variant:"primary",onClick:m,children:[e.jsx(oe,{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:[u.length," active · ",i.length," total in store"]})]}),e.jsxs("div",{className:"bg-active-header-actions",children:[e.jsxs(T,{variant:"primary",size:"sm",onClick:()=>d(!0),children:[e.jsx(ve,{size:14})," Spawn"]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:m,title:"Refresh now",children:[e.jsx(oe,{size:14})," Refresh"]})]})]}),e.jsx(Ho,{open:h,onClose:()=>d(!1),onCreated:()=>{m()}}),u.length===0?e.jsx(he,{icon:e.jsx(Te,{size:32}),title:"No active background agents",message:"Use the Spawn button above or call bizar_spawn_background from an agent.",action:e.jsxs(T,{variant:"primary",onClick:()=>d(!0),children:[e.jsx(ve,{size:14})," Spawn your first agent"]})}):e.jsx("div",{className:"bg-active-list",children:u.map($=>e.jsx(Zo,{inst:$,onViewOutput:()=>g($),onOpenTmux:()=>k($),onKill:()=>z($),onPause:ft($)?void 0:()=>C($),onResume:ft($)?()=>y($):void 0,onSteer:()=>w($)},$.instanceId))})]})}function Zo({inst:s,onViewOutput:t,onOpenTmux:a,onKill:i,onPause:n,onResume:o,onSteer:c}){const l=typeof s.startedAt=="number"?s.startedAt:0,x=l?Oe(l):"—",p=l?Date.now()-l:0,h=na(s.prompt,Ko),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(Uo,{status:s.status||"pending",dot:!0}),ft(s)&&e.jsxs("span",{className:"bg-active-card-paused-tag",children:[e.jsx(Vn,{size:12})," paused"]})]}),e.jsxs("div",{className:"bg-active-card-agent",children:[e.jsx("span",{className:"bg-active-card-agent-label",children:"Agent"}),e.jsx("span",{className:"bg-active-card-agent-name",children:s.agent||"unknown"})]})]}),h&&e.jsx("div",{className:"bg-active-prompt",children:h}),s.currentStep&&e.jsxs("div",{className:"bg-active-step",children:[e.jsx("span",{className:"bg-active-step-label",children:"Step:"}),e.jsx("span",{className:"bg-active-step-value",children:s.currentStep})]}),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:x,children:[e.jsx("strong",{children:"Started:"})," ",x]}),e.jsxs("span",{children:[e.jsx("strong",{children:"Duration:"})," ",Qo(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,u)=>e.jsxs("span",{className:"tag-pill",children:[m,u<s.tags.length-1?" ":""]},m))]}),s.tmuxSession&&e.jsxs("span",{className:H(s.tmuxActive&&"bg-active-meta-tmux-live"),children:[e.jsx("strong",{children:"tmux:"})," ",e.jsx("code",{className:"mono",children:s.tmuxSession}),s.tmuxActive?" · live":""]})]}),e.jsxs("div",{className:"bg-active-actions",children:[e.jsxs(T,{variant:"secondary",size:"sm",onClick:t,children:[e.jsx(gs,{size:14})," View output"]}),n&&e.jsxs(T,{variant:"secondary",size:"sm",onClick:n,title:"Pause subprocess (POSIX)",children:[e.jsx(Rt,{size:14})," Pause"]}),o&&e.jsxs(T,{variant:"secondary",size:"sm",onClick:o,title:"Resume subprocess (POSIX)",children:[e.jsx(ys,{size:14})," Resume"]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:c,title:"Steer with new instructions",children:[e.jsx(Ye,{size:14})," Steer"]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:a,children:[e.jsx(Ke,{size:14})," Open in tmux"]}),e.jsxs(T,{variant:"danger",size:"sm",onClick:i,children:[e.jsx(ke,{size:14})," Kill"]})]}),e.jsx(qo,{instance:s})]})}function ec(s,t){s.open({title:`Output — ${t.agent||t.instanceId}`,width:720,children:e.jsx(sc,{instanceId:t.instanceId})})}function sc({instanceId:s}){const t=re(),a=r.useRef([]),[i,n]=r.useState(""),[o,c]=r.useState(!0),[l,x]=r.useState(null),[p,h]=r.useState(!0),[d,m]=r.useState(!0),[u,g]=r.useState([]),[k,z]=r.useState(!0),C=r.useRef(null),y=r.useRef(!0),w=r.useCallback(()=>{n(a.current.join(`
|
|
17
|
+
`))},[]),$=r.useCallback(async()=>{try{const v=await R.get(`/background/${encodeURIComponent(s)}/output?lines=300`);if(h((v==null?void 0:v.available)!==!1),v!=null&&v.output&&a.current.length===0){const f=v.output.split(/\r?\n/);a.current=f.slice(-300),w()}x(null)}catch(v){x((v==null?void 0:v.message)||"Failed to load output.")}finally{c(!1)}},[s,w]);r.useEffect(()=>{$();const v=setInterval($,aa);return()=>clearInterval(v)},[$]),r.useEffect(()=>{const v=new Hs;let f=!1;const D=v.onStatus(b=>{f=b==="connected",m(f)}),M=v.on(b=>{var O;const A=b;if(A.type==="bg:output"&&A.instanceId===s&&typeof A.line=="string"){a.current.push(A.line);let S=0;for(let F=a.current.length-1;F>=0;F--)if(S+=(((O=a.current[F])==null?void 0:O.length)??0)+1,S>Yo){a.current=a.current.slice(F+1);break}n(a.current.join(`
|
|
18
|
+
`))}});return()=>{D(),M(),v.close()}},[s]),r.useEffect(()=>{let v=!1;const f=async()=>{try{const b=await R.get(`/background/${encodeURIComponent(s)}/tool-calls`);!v&&Array.isArray(b==null?void 0:b.toolCalls)&&g(b.toolCalls)}catch{}};f();const D=new Hs,M=D.on(b=>{const A=b;A.type==="bg:tool-call"&&A.instanceId===s&&f()});return()=>{v=!0,M(),D.close()}},[s]),r.useEffect(()=>{var v;y.current&&((v=C.current)==null||v.scrollIntoView({behavior:"auto",block:"end"}))},[i]);const j=v=>{const f=v.currentTarget,D=f.scrollHeight-f.scrollTop-f.clientHeight<24;y.current=D},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 ${aa/1e3}s (WS idle)`:"Output unavailable (no tmux session)"}),e.jsxs("div",{className:"bg-output-toolbar-actions",children:[e.jsx(T,{variant:"ghost",size:"sm",onClick:()=>z(v=>!v),title:"Toggle tool-call history",children:k?"Hide tools":"Show tools"}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:$,title:"Refresh now",children:[e.jsx(oe,{size:14})," Refresh"]}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:N,disabled:!i,children:[e.jsx(ns,{size:14})," Copy"]})]})]}),o&&!i?e.jsxs("div",{className:"bg-output-loading",children:[e.jsx(me,{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:j,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:C})]}),k&&e.jsx(tc,{calls:u})]})]})}function tc({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 ac(s,t){const a=t.attachCommand||t.session||"";s.open({title:"Attach to tmux",width:520,children:e.jsx(rc,{info:t,cmd:a})})}function nc(s,t,a,i){s.open({title:`Steer ${a.agent||a.instanceId}`,width:600,children:e.jsx(ic,{instanceId:a.instanceId,toast:t,onCreated:i,onClose:()=>s.close()})})}function ic({instanceId:s,toast:t,onCreated:a,onClose:i}){const[n,o]=r.useState(""),[c,l]=r.useState(!1),[x,p]=r.useState(null),h=async()=>{if(!n.trim()){p("Message is required.");return}l(!0);try{const d=await R.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=>o(d.target.value),placeholder:"What do you want the agent to do differently?"}),x&&e.jsx("div",{className:"bg-steer-error",children:x}),e.jsxs("div",{className:"bg-steer-actions",children:[e.jsx(T,{variant:"ghost",size:"sm",onClick:i,children:"Cancel"}),e.jsx(T,{variant:"primary",size:"sm",onClick:h,disabled:c||!n.trim(),children:c?"Steering…":"Steer"})]})]})}function rc({info:s,cmd:t}){const[a,i]=r.useState(!1),n=async()=>{try{await navigator.clipboard.writeText(t),i(!0),window.setTimeout(()=>i(!1),1500)}catch{}};return e.jsx("div",{className:"bg-tmux-modal",children:t?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"bg-tmux-meta",children:[s.exists?e.jsx("span",{className:"badge badge-success",children:"session live"}):e.jsxs("span",{className:"badge badge-warning",children:["session not running",s.reason?` — ${s.reason}`:""]}),s.session&&e.jsxs("span",{className:"bg-tmux-session muted",children:["· session ",e.jsx("code",{className:"mono",children:s.session})]})]}),e.jsx("label",{className:"field-label",children:"Attach command"}),e.jsxs("div",{className:"bg-tmux-command-row",children:[e.jsx("code",{className:"bg-tmux-command mono",children:t}),e.jsxs(T,{variant:"secondary",size:"sm",onClick:n,children:[e.jsx(ns,{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 lc={system:{title:"System health",icon:js,emptyTitle:"No system checks",emptyMessage:"System checks did not return any rows."},services:{title:"Services",icon:Ct,emptyTitle:"No service probes",emptyMessage:"Service probes did not return any rows."},counts:{title:"Counts",icon:Te,emptyTitle:"No counts",emptyMessage:"No counts reported by the dashboard stores."},errors:{title:"Recent errors",icon:xs,emptyTitle:"No recent errors",emptyMessage:"No error lines in the service log within the last hour."},actions:{title:"Actions",icon:Hn,emptyTitle:"No actions",emptyMessage:"No actions available."}};function oc(s){return s==="ok"?Ee:s==="warn"?Gn:xs}function cc(s){return s==="ok"?"ok":s==="warn"?"warn":"fail"}function dt({category:s,title:t,icon:a,checks:i,info:n,meta:o,children:c,className:l}){const x=lc[s],p=a??x.icon,h=t??x.title,d=i.length>0||n&&n.length>0||c;return e.jsxs(G,{className:H("doctor-panel",`doctor-panel-${s}`,l),children:[e.jsxs(se,{children:[e.jsx(p,{size:14,"aria-hidden":!0}),e.jsx("span",{children:h}),o?e.jsx("span",{className:"card-meta-inline muted",children:o}):null]}),d?e.jsxs("div",{className:"doctor-panel-body",children:[c,i.length>0?e.jsx("ul",{className:"doctor-check-list",role:"list",children:i.map(m=>{const u=oc(m.status);return e.jsxs("li",{className:H("doctor-check-row",`doctor-check-${m.status}`),children:[e.jsx("span",{className:"doctor-check-icon","aria-hidden":!0,children:e.jsx(u,{size:14,className:H("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(Ve,{kind:m.status,dot:!0,children:cc(m.status)})]},m.name)})}):null,n&&n.length>0?e.jsx("dl",{className:"doctor-info-list",children:n.map(m=>e.jsxs(De.Fragment,{children:[e.jsx("dt",{children:m.label}),e.jsx("dd",{className:"tabular-nums",children:m.value})]},m.label))}):null]}):e.jsx(he,{icon:e.jsx(p,{size:28,"aria-hidden":!0}),title:x.emptyTitle,message:x.emptyMessage})]})}const dc=3e4;function mc({setActiveTab:s}){var N;const t=re(),[a,i]=r.useState(null),[n,o]=r.useState(!0),[c,l]=r.useState(!1),[x,p]=r.useState(null),[h,d]=r.useState(!0),m=r.useRef(!1),u=r.useCallback(async()=>{l(!0);try{const v=await R.get("/doctor");m.current||(i(v),p(Date.now()),o(!1))}catch(v){m.current||(o(!1),t.error(`Doctor refresh failed: ${v.message}`))}finally{m.current||l(!1)}},[t]);r.useEffect(()=>(m.current=!1,u(),()=>{m.current=!0}),[u]),r.useEffect(()=>{if(!h)return;const f=setInterval(async()=>{try{const D=await R.get("/doctor/health");i(M=>M&&((M.health.status!==D.status||M.health.issues.length!==D.issues.length)&&u(),M))}catch{}},dc);return()=>clearInterval(f)},[h,u]);const g=async v=>{var f;try{const D=await R.post("/doctor/check",{checkName:v});t.info(`${D.name}: ${D.message}`,4e3),await u()}catch(D){const M=D;t.error(`Check failed: ${((f=M.data)==null?void 0:f.message)??D.message}`)}},k=()=>{if(a)try{const v=new Blob([JSON.stringify(a,null,2)],{type:"application/json"}),f=URL.createObjectURL(v),D=document.createElement("a");D.href=f,D.download=`doctor-snapshot-${new Date().toISOString().replace(/[:.]/g,"-")}.json`,document.body.appendChild(D),D.click(),document.body.removeChild(D),URL.revokeObjectURL(f)}catch(v){t.error(`Export failed: ${v.message}`)}},z=()=>{s("settings")},C=a==null?void 0:a.counts,y=r.useMemo(()=>C?[{label:"Tasks",value:C.tasks},{label:"Schedules",value:C.schedules},{label:"Mods",value:C.mods},{label:"Providers",value:C.providers},{label:"MCPs",value:C.mcps},{label:"Agents",value:C.agents},{label:"Projects",value:C.projects},{label:"Workspaces",value:C.workspaces},{label:"Voice notes",value:C.voiceNotes},{label:"Eval runs",value:C.evalRuns},{label:"Backups",value:C.backups}]:[],[C]);if(n)return e.jsxs("div",{className:"view view-doctor view-loading",children:[e.jsx(le,{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(se,{children:[e.jsx(xs,{size:14})," Doctor unavailable"]}),e.jsx(ae,{children:"Could not reach /api/doctor."}),e.jsx("div",{className:"doctor-fallback-actions",children:e.jsxs(T,{variant:"primary",onClick:u,children:[e.jsx(oe,{size:12})," Retry"]})})]})});const w=a.health.status,$=w==="ok"?Ee:w==="warn"?ye:xs,j=w==="ok"?"Healthy":w==="warn"?"Warning":"Failed";return e.jsxs("div",{className:"view view-doctor","data-overall":w,children:[e.jsxs("div",{className:"doctor-header",children:[e.jsxs("div",{className:"doctor-header-row",children:[e.jsxs("div",{className:"doctor-header-title",children:[e.jsx(ca,{size:20,"aria-hidden":!0}),e.jsx("h1",{children:"Doctor"})]}),e.jsx("div",{className:"doctor-header-status",children:e.jsxs("span",{className:H("doctor-overall-pill",`doctor-overall-${w}`),children:[e.jsx($,{size:14,"aria-hidden":!0}),e.jsx("span",{className:"doctor-overall-label",children:j}),e.jsxs(Ve,{kind:w,dot:!0,children:[a.health.issues.length," issue",a.health.issues.length===1?"":"s"]})]})})]}),e.jsxs("div",{className:"doctor-header-meta muted",children:[e.jsx(Ge,{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",x?` · refreshed ${Oe(new Date(x))}`:""]})]})]}),e.jsxs("div",{className:"doctor-grid",children:[e.jsx(dt,{category:"system",checks:a.checks.system,meta:`${a.platform}/${a.arch}`}),e.jsx(dt,{category:"services",checks:a.checks.services,meta:(N=a.services.opencode)!=null&&N.reachable?`opencode on ${a.services.opencode.port??"?"}`:"opencode not connected"}),e.jsx(dt,{category:"counts",checks:[],info:y,meta:C!=null&&C.activeProject?`active: ${C.activeProject}`:"no active project"}),e.jsxs(G,{className:"doctor-errors-card",children:[e.jsxs(se,{children:[e.jsx(xs,{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,f)=>e.jsxs("li",{className:"doctor-error-row",children:[e.jsx("span",{className:"doctor-error-ts mono",children:v.ts?Oe(new Date(v.ts)):"??:??:??"}),e.jsx("span",{className:"doctor-error-line mono",children:v.line})]},`${v.tsMs??f}-${f}`))})]}),e.jsxs(G,{className:"doctor-actions-card",children:[e.jsxs(se,{children:[e.jsx(xt,{size:14,"aria-hidden":!0})," Actions"]}),e.jsx(ae,{children:"Run a check, view logs, or export the snapshot."}),e.jsxs("div",{className:"doctor-actions-row",children:[e.jsxs(T,{variant:"primary",onClick:u,disabled:c,"aria-label":"Refresh diagnostics",children:[c?e.jsx(le,{size:"sm"}):e.jsx(oe,{size:12}),c?"Running…":"Run Health Check Now"]}),e.jsxs(T,{variant:"secondary",onClick:z,children:[e.jsx(be,{size:12})," View Full Logs"]}),e.jsxs(T,{variant:"secondary",onClick:k,children:[e.jsx(as,{size:12})," Export Diagnostics as JSON"]}),e.jsx(T,{variant:"ghost",onClick:()=>d(v=>!v),"aria-label":h?"Pause auto-refresh":"Resume auto-refresh",children:h?"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(T,{variant:"ghost",size:"sm",onClick:()=>g(v.name),title:`Run check: ${v.name}`,children:[e.jsx(xt,{size:10})," ",v.name]},v.name))})]}):null]})]})]})}const uc=De.memo(mc);function hc(s){return s.total<=0?"fail":s.failed===0?"pass":s.passed/s.total>.8?"warn":"fail"}function Pa({run:s,onClick:t,selected:a,ariaLabel:i}){const n=hc(s),o=s.total>0?(s.passed/s.total*100).toFixed(1):"0.0",c=!!t;return e.jsxs(G,{onClick:t,interactive:c,"aria-label":i??`Eval run ${s.id}`,"aria-pressed":c?a:void 0,className:H("eval-run-card",a&&"eval-run-card-selected",`eval-run-${n}`),children:[e.jsxs("div",{className:"eval-run-head",children:[e.jsx(se,{className:"eval-run-title",children:s.id}),e.jsxs("span",{className:H("eval-status",`is-${n}`),children:[s.passed,"/",s.total," (",o,"%)"]})]}),e.jsxs(ae,{className:"eval-run-meta",children:[Oe(s.startedAt)," · ",s.suitePath]})]})}const mt=8;function xc({onAdded:s,onCancel:t}){const a=re(),[i,n]=r.useState(""),[o,c]=r.useState(""),[l,x]=r.useState(""),[p,h]=r.useState("thor"),[d,m]=r.useState(!1),u=async g=>{if(g.preventDefault(),!i||!o||!l){a.error("name, suitePath, and cron are required");return}m(!0);try{const k=await R.post("/eval/schedules",{name:i,suitePath:o,cron:l,agent:p});s(k),a.success("Schedule created")}catch(k){a.error(`Failed to create schedule: ${k.message}`)}finally{m(!1)}};return e.jsxs("form",{className:"eval-schedule-form",onSubmit:u,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:o,onChange:g=>c(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=>x(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=>h(g.target.value),placeholder:"thor"})]}),e.jsxs("div",{className:"form-actions",children:[e.jsx(T,{type:"submit",variant:"primary",size:"sm",disabled:d,children:d?"Creating…":"Create schedule"}),e.jsx(T,{type:"button",variant:"ghost",size:"sm",onClick:t,children:"Cancel"})]})]})}function pc({setActiveTab:s}){const t=re(),[a,i]=r.useState([]),[n,o]=r.useState(!0),[c,l]=r.useState("runs"),[x,p]=r.useState([]),[h,d]=r.useState(!1),[m,u]=r.useState(!1),g=r.useRef(!1),k=r.useCallback(async()=>{o(!0);try{const j=await R.get(`/eval/runs?limit=${mt}`);g.current||i(j.runs||[])}catch(j){g.current||t.error(`Failed to load eval runs: ${j.message}`)}finally{g.current||o(!1)}},[t]),z=r.useCallback(async()=>{d(!0);try{const j=await R.get("/eval/schedules");g.current||p(j.schedules||[])}catch(j){g.current||t.error(`Failed to load eval schedules: ${j.message}`)}finally{g.current||d(!1)}},[t]);r.useEffect(()=>(g.current=!1,k(),c==="schedules"&&z(),()=>{g.current=!0}),[k,z,c]);const C=async j=>{try{await R.del(`/eval/schedules/${j}`),p(N=>N.filter(v=>v.id!==j)),t.success("Schedule deleted")}catch(N){t.error(`Failed to delete schedule: ${N.message}`)}},y=a.slice(0,mt),w=a.reduce((j,N)=>(j.total+=N.total,j.passed+=N.passed,j.failed+=N.failed,N.failed===0&&(j.fullPass+=1),j),{total:0,passed:0,failed:0,fullPass:0}),$=w.total>0?(w.passed/w.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(He,{size:20,"aria-hidden":!0})," Eval"]}),e.jsx("p",{className:"view-subtitle muted",children:"Track golden-fixture runs, catch regressions, and compare run history."})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs(T,{variant:"secondary",size:"sm",onClick:k,disabled:n,children:[n?e.jsx(le,{size:"sm"}):e.jsx(oe,{size:12}),n?"Refreshing…":"Refresh"]}),e.jsxs(T,{variant:"primary",size:"sm",onClick:()=>s("evalReport"),title:"Open the full eval report",children:[e.jsx(vs,{size:12})," Open Eval Report"]})]})]}),e.jsxs("div",{className:"eval-summary-grid",children:[e.jsxs(G,{className:"eval-summary-card",children:[e.jsx(se,{children:"Recent runs"}),e.jsx("div",{className:"eval-summary-value",children:a.length}),e.jsxs(ae,{className:"muted",children:["Latest ",mt," runs across all suites."]})]}),e.jsxs(G,{className:"eval-summary-card",children:[e.jsx(se,{children:"Fixtures run"}),e.jsx("div",{className:"eval-summary-value",children:w.total}),e.jsx(ae,{className:"muted",children:e.jsxs("span",{className:H("eval-rate",w.failed===0?"is-pass":"is-fail"),children:[$,"% pass rate"]})})]}),e.jsxs(G,{className:"eval-summary-card",children:[e.jsx(se,{children:"Clean runs"}),e.jsx("div",{className:"eval-summary-value",children:w.fullPass}),e.jsx(ae,{className:"muted",children:"Runs where every fixture passed."})]}),e.jsxs(G,{className:"eval-summary-card eval-summary-cta",children:[e.jsx(se,{children:"Compare runs"}),e.jsx(ae,{children:"Open the detailed report to diff two runs side-by-side and spot regressions fixture by fixture."}),e.jsxs(T,{variant:"primary",size:"sm",onClick:()=>s("evalReport"),className:"eval-summary-cta-btn",children:["Open report ",e.jsx(Kn,{size:12})]})]})]}),e.jsxs("div",{className:"eval-recent-section",children:[e.jsxs("div",{className:"eval-sub-tabs",children:[e.jsxs("button",{type:"button",className:H("eval-sub-tab",c==="runs"?"is-active":""),onClick:()=>l("runs"),children:[e.jsx(He,{size:12,"aria-hidden":!0})," Runs"]}),e.jsxs("button",{type:"button",className:H("eval-sub-tab",c==="schedules"?"is-active":""),onClick:()=>{l("schedules"),x.length===0&&z()},children:[e.jsx(Ge,{size:12,"aria-hidden":!0})," Schedules"]})]}),c==="runs"?e.jsxs(e.Fragment,{children:[e.jsx("h2",{className:"eval-section-title",children:"Recent runs"}),n&&y.length===0?e.jsxs("div",{className:"eval-runs-loading",children:[e.jsx(le,{size:"sm"}),e.jsx("span",{className:"muted",children:"Loading runs…"})]}):y.length===0?e.jsx(he,{icon:e.jsx(He,{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:y.map(j=>e.jsx(Pa,{run:j},j.id))})]}):e.jsxs(e.Fragment,{children:[e.jsx("h2",{className:"eval-section-title",children:"Schedules"}),h?e.jsxs("div",{className:"eval-runs-loading",children:[e.jsx(le,{size:"sm"}),e.jsx("span",{className:"muted",children:"Loading schedules…"})]}):x.length===0?e.jsx(he,{icon:e.jsx(Ge,{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:x.map(j=>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(se,{children:j.name}),e.jsxs(ae,{className:"muted",children:[j.cron," · ",j.suitePath," · agent:",j.agent||"thor"]})]}),e.jsx(T,{variant:"ghost",size:"sm",onClick:()=>C(j.id),title:"Delete schedule",children:e.jsx(ke,{size:12,"aria-hidden":!0})})]})},j.id))}),e.jsxs("div",{className:"eval-schedule-add",children:[e.jsx(xc,{onAdded:j=>{p(N=>[...N,j]),u(!1)},onCancel:()=>u(!1)}),!m&&e.jsxs(T,{variant:"secondary",size:"sm",onClick:()=>u(!0),children:[e.jsx(ve,{size:12,"aria-hidden":!0})," Add schedule"]})]})]})]})]})}const gc=De.memo(pc);function Fa(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()]),o=[];for(const l of n){const x=a.get(l),p=i.get(l),h=x?x.ok:null,d=p?p.ok:null;let m;x&&p?h===d?m="same":h===!1&&d===!0?m="improved":m="regressed":p&&!x?m="added":m="removed",o.push({fixtureId:l,before:h,after:d,change:m})}const c={regressed:0,improved:1,added:2,removed:3,same:4};return o.sort((l,x)=>{const p=c[l.change]-c[x.change];return p!==0?p:l.fixtureId.localeCompare(x.fixtureId)}),o}function jc({runA:s,runB:t,title:a="Regression Analysis"}){const i=Fa(s,t),n=i.filter(x=>x.change==="improved").length,o=i.filter(x=>x.change==="regressed").length,c=i.filter(x=>x.change==="same").length,l=i.filter(x=>x.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:"−"}),o," regressed"]}),e.jsxs("span",{className:"eval-diff-stat unchanged muted",children:[c," 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(x=>e.jsxs("li",{"data-fixture-id":x.fixtureId,className:H("eval-diff-row",`is-${x.change}`),children:[e.jsx("span",{className:"eval-diff-fixture mono",children:x.fixtureId}),e.jsx("span",{className:"eval-diff-arrow","aria-hidden":!0,children:"→"}),e.jsxs("span",{className:"eval-diff-states",children:[e.jsx("span",{className:H("eval-diff-state",x.before?"is-pass":"is-fail"),children:x.before===null?"—":x.before?"pass":"fail"}),e.jsx("span",{className:"eval-diff-arrow-small","aria-hidden":!0,children:"→"}),e.jsx("span",{className:H("eval-diff-state",x.after?"is-pass":"is-fail"),children:x.after===null?"—":x.after?"pass":"fail"})]})]},x.fixtureId))})]})}function fc({runId:s,variant:t="secondary",size:a="sm"}){const i=()=>{const n=R.getToken();window.open(`/api/eval/runs/${encodeURIComponent(s)}/export.csv?_t=${encodeURIComponent(n)}`,"_blank")};return e.jsxs(T,{variant:t,size:a,onClick:i,title:"Export results as CSV",children:[e.jsx(as,{size:14,"aria-hidden":!0}),"Export CSV"]})}function vc({run:s,onClearCompare:t,compareRun:a,onClearSelection:i,runsForDiff:n}){const o=s.total>0?(s.passed/s.total*100).toFixed(1):"0.0",c=[...s.results].sort((l,x)=>l.ok!==x.ok?l.ok?1:-1:l.fixtureId.localeCompare(x.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(se,{children:[e.jsx(He,{size:14,"aria-hidden":!0})," ",s.id]}),e.jsxs("div",{className:"eval-run-detail-actions",children:[e.jsx(fc,{runId:s.id}),e.jsxs(T,{variant:"ghost",size:"sm",onClick:i,title:"Close detail",children:[e.jsx(Ne,{size:12})," Close"]})]})]}),e.jsxs(ae,{children:[Oe(s.startedAt),s.finishedAt?` → ${Oe(s.finishedAt)}`:""," · ",s.suitePath]}),e.jsxs("div",{className:"eval-run-detail-summary",children:[e.jsxs("span",{className:H("eval-status",s.failed===0?"is-pass":"is-fail"),children:[s.passed,"/",s.total," (",o,"%)"]}),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 x=Fa(l,s),p=x.filter(d=>d.change==="improved").length,h=x.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(wa,{size:14,"aria-hidden":!0})," Comparing ",l.id," → ",s.id]}),e.jsxs(T,{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:["−",h," regressed"]})]}),e.jsx(jc,{runA:l,runB:s})]})})()}):e.jsx(G,{className:"eval-baseline-hint",children:e.jsx(ae,{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(se,{children:["Fixtures (",s.results.length,")"]}),c.length===0?e.jsx(ae,{className:"muted",children:"No fixture results in this run."}):e.jsx("ul",{className:"eval-fixtures-list",role:"list",children:c.map(l=>e.jsxs("li",{className:H("eval-fixture-row",l.ok?"is-pass":"is-fail"),children:[e.jsx("span",{className:H("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(x=>!x.ok).map(x=>x.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 yc({setActiveTab:s}){const t=re(),[a,i]=r.useState([]),[n,o]=r.useState(!0),[c,l]=r.useState(null),[x,p]=r.useState(null),[h,d]=r.useState(null),[m,u]=r.useState(!1),[g,k]=r.useState(null),z=r.useRef(!1),C=r.useCallback(async()=>{o(!0);try{const v=await R.get("/eval/runs");z.current||i(v.runs||[])}catch(v){z.current||t.error(`Failed to load eval runs: ${v.message}`)}finally{z.current||o(!1)}},[t]),y=r.useCallback(async v=>{u(!0);try{const f=await R.get(`/eval/runs/${encodeURIComponent(v)}`);z.current||d(f)}catch(f){z.current||(t.error(`Failed to load run ${v}: ${f.message}`),d(null))}finally{z.current||u(!1)}},[t]),w=r.useCallback(async v=>{try{const f=await R.get(`/eval/runs/${encodeURIComponent(v)}`);z.current||k(f)}catch(f){z.current||(t.error(`Failed to load run ${v}: ${f.message}`),k(null))}},[t]);r.useEffect(()=>(z.current=!1,C(),()=>{z.current=!0}),[C]);const $=async v=>{v!==c&&(l(v),p(null),k(null),await y(v))},j=async v=>{v!==c&&(p(v),await w(v))},N=[];return g&&N.push(g),h&&N.push(h),e.jsxs("div",{className:"view view-eval-report","data-testid":"eval-report",children:[e.jsxs("div",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h1",{className:"view-title",children:[e.jsx(He,{size:20,"aria-hidden":!0})," Eval Reports"]}),e.jsx("p",{className:"view-subtitle muted",children:"Browse eval runs, inspect per-fixture results, and diff two runs to spot regressions."})]}),e.jsx("div",{className:"view-actions",children:e.jsxs(T,{variant:"secondary",size:"sm",onClick:C,disabled:n,children:[n?e.jsx(le,{size:"sm"}):e.jsx(oe,{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(le,{size:"sm"}),e.jsx("span",{className:"muted",children:"Loading runs…"})]}):a.length===0?e.jsx(he,{icon:e.jsx(He,{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(Pa,{run:v,selected:v.id===c,onClick:()=>$(v.id)}),c&&v.id!==c?e.jsxs("button",{type:"button",className:"eval-baseline-btn",onClick:()=>j(v.id),title:"Use this run as a baseline for diffing",children:[e.jsx(wa,{size:10,"aria-hidden":!0}),"Use as baseline"]}):null]},v.id))}),e.jsx("div",{className:"eval-detail",children:m&&!h?e.jsxs("div",{className:"eval-detail-loading",children:[e.jsx(le,{size:"sm"}),e.jsx("span",{className:"muted",children:"Loading run details…"})]}):h?e.jsx(vc,{run:h,compareRun:x,runsForDiff:N,onClearCompare:()=>{p(null),k(null)},onClearSelection:()=>{l(null),d(null),p(null),k(null)}}):e.jsx(G,{className:"eval-detail-empty",children:e.jsx(he,{icon:e.jsx(He,{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 bc=De.memo(yc),Oa=["theme","updates","layout","general","env-vars","network","notifications","auth","agents","system-llm","headroom","activity-log","workspaces"],Vs={overview:Gi,chat:dr,agents:pr,artifacts:_r,memory:Co,tasks:Zr,activity:cl,background:Jo,config:Aa,marketplace:Cl,mods:zl,schedules:ql,skills:Ql,history:Ro,minimax:Po,plugins:Al,doctor:uc,eval:gc,evalReport:bc};for(const s of Oa)Vs[`settings-${s}`]=t=>e.jsx(Aa,{...t,section:s});const Nc="v4.5.0";function kc(s,t,a,i){if(Vs[s]){const c=Vs[s];return e.jsx(c,{...t})}const n=a.find(c=>c.id===s);if(n)return e.jsx(Il,{viewId:n.id,reloadKey:i,activeTab:t.activeTab,setActiveTab:t.setActiveTab});const o=Vs.overview;return e.jsx(o,{...t})}function wc({onSaved:s}){const[t,a]=r.useState(""),i=r.useRef(null);r.useEffect(()=>{var c;(c=i.current)==null||c.focus()},[]);const n=()=>{const c=t.trim();c&&(R.setToken(c),s())},o=c=>{c.key==="Escape"&&(c.preventDefault(),s()),c.key==="Enter"&&(c.preventDefault(),n())};return e.jsxs("form",{className:"token-entry-form",onSubmit:c=>{c.preventDefault(),n()},children:[e.jsxs("div",{className:"token-entry-row",children:[e.jsx("input",{ref:i,type:"password",className:"input mono",value:t,onChange:c=>a(c.target.value),placeholder:"Paste auth token",spellCheck:!1,autoComplete:"off",onKeyDown:o}),e.jsx(T,{type:"submit",variant:"primary",size:"sm",disabled:!t.trim(),children:"Save & retry"})]}),e.jsxs("p",{className:"token-entry-hint",children:["Where do I find this token? Check the file"," ",e.jsx("code",{children:"~/.config/bizar/dashboard-secret"})," on the machine running the dashboard, or look for it in the server output."]})]})}function Sc(){return e.jsx(ti,{children:e.jsx(ci,{children:e.jsx(Cc,{})})})}function Cc(){var ie,je,Ce;const s=re(),t=Re(),{isModalOpen:a}=t,i=r.useRef(!1),[n,o]=r.useState("overview"),[c,l]=r.useState(null),[x,p]=r.useState(null),[h,d]=r.useState("connecting"),[m,u]=r.useState(null),[g,k]=r.useState(!1),[z,C]=r.useState(!1),[y,w]=r.useState([]),[$,j]=r.useState(!1),[N,v]=r.useState([]),[f,D]=r.useState(0),M=r.useRef(null),[b,A]=r.useState(null);r.useEffect(()=>{let L=!1;return(async()=>{try{const U=await R.get("/mods/views");if(L)return;v(U.views||[])}catch{L||v([])}})(),()=>{L=!0}},[f,c==null?void 0:c.mods]),r.useEffect(()=>{if(!b)return;const L=b.on(U=>{((U==null?void 0:U.type)==="mod:change"||(U==null?void 0:U.type)==="mod:enabled"||(U==null?void 0:U.type)==="mod:installed")&&D(q=>q+1)});return()=>L()},[b]),r.useEffect(()=>{x!=null&&x.theme&&(Cs(x.theme),us(x.theme))},[x==null?void 0:x.theme]),r.useEffect(()=>{i.current=a},[a]),r.useEffect(()=>{var q;if(((q=x==null?void 0:x.theme)==null?void 0:q.mode)!=="system")return;const L=window.matchMedia("(prefers-color-scheme: light)"),U=()=>Cs(x.theme.mode);return L.addEventListener("change",U),()=>L.removeEventListener("change",U)},[(ie=x==null?void 0:x.theme)==null?void 0:ie.mode]);const O=r.useCallback(async()=>{let L=!1;const U=()=>Promise.all([R.get("/snapshot").catch(()=>null),R.get("/settings").catch(()=>null),R.get("/agents/stuck").catch(()=>null)]),q=(Y,ne,E)=>{Y&&l(Y),ne!=null&&ne.data&&p(ne.data),E!=null&&E.stuck&&w(E.stuck)};try{const Y=await R.probeAuthStatus(),[ne,E,J]=await U();if(q(ne,E,J),ne||E){u(null);return}if(!Y.loopback){u("Dashboard server unreachable.");return}await new Promise(rs=>setTimeout(rs,1e3));const[ee,ue,ce]=await U();q(ee,ue,ce),!ee&&!ue&&u("Dashboard server unreachable.")}catch(Y){const ne=(Y==null?void 0:Y.message)??"unknown error";if(Y instanceof Ja&&Y.status===401){u(ne),k(!0),s.error(`Auth required: ${ne}`);return}u(ne),s.error(`Failed to load: ${ne}`)}},[s]);r.useEffect(()=>{let L=!1;const U=setTimeout(()=>{L||O()},0);return()=>{L=!0,clearTimeout(U)}},[O]),r.useEffect(()=>{let L=!1;return R.get("/settings").then(U=>{var Y,ne;if(L)return;const q=(ne=(Y=U==null?void 0:U.data)==null?void 0:Y.ui)==null?void 0:ne.defaultTab;q&&o(q)}).catch(()=>{}),()=>{L=!0}},[]),r.useEffect(()=>{let L=!1;const U=async()=>{try{const Y=await R.get("/agents/stuck");L||w(ne=>{const E=Y.stuck||[];return ne.length===0&&E.length>0&&s.warning(`${E.length} agent${E.length===1?"":"s"} stuck`,5e3),E})}catch{}},q=setInterval(U,3e4);return U(),()=>{L=!0,clearInterval(q)}},[]),r.useEffect(()=>{const L=new Hs;M.current=L,A(L);const U=L.onStatus(Y=>d(Y)),q=L.on(Y=>{var ne;if(Y.type==="snapshot"&&"data"in Y&&Y.data)l(E=>({...E??{},...Y.data}));else if(Y.type==="change"){const E=Y,J=((ne=E.path)==null?void 0:ne.split("/").pop())||E.path||"";s.info(`File changed: ${J}`,2500)}else if(Y.type==="tasks:change"){const E=Y;l(J=>{if(!J)return J;const ee=(J.tasks||[]).map(ce=>ce.id===E.task.id?E.task:ce),ue=ee.some(ce=>ce.id===E.task.id);return{...J,tasks:ue?ee:[E.task,...ee]}})}else if(Y.type==="tasks:delete"){const E=Y;l(J=>J&&{...J,tasks:(J.tasks||[]).filter(ee=>ee.id!==E.id)})}else if(Y.type==="settings:change"){const E=Y;E.settings&&p(E.settings)}else if(Y.type==="project:change")R.get("/snapshot").then(E=>l(J=>({...J??{},...E}))).catch(()=>{});else if(Y.type==="agents:change"||Y.type==="schedules:change")R.get("/snapshot").then(E=>l(J=>({...J??{},...E}))).catch(()=>{});else if(Y.type==="agent:status"||Y.type==="agent:restarted"){const E=Y;l(J=>{if(!J)return J;const ee=(J.agents||[]).map(ue=>ue.name===E.agent.name?E.agent:ue);return{...J,agents:ee}})}else if(Y.type==="artifact:change")R.get("/artifacts").then(E=>{l(J=>J&&{...J,artifacts:E.artifacts||[]})}).catch(()=>{});else if(Y.type==="agent:stuck")w(Y.agents||[]);else if(Y.type==="dialog:show"){const E=Y;E.dialog&&t.open({title:E.dialog.title,width:520,children:e.jsx(Li,{dialog:E.dialog,onClose:()=>t.close()})})}});return()=>{U(),q(),L.close(),A(null)}},[s]);const S=r.useCallback(L=>b?b.on(L):()=>{},[b]),F=r.useRef(0);r.useEffect(()=>{const L=()=>{F.current=Date.now()+1500};return document.addEventListener("mousedown",L,!0),document.addEventListener("click",L,!0),document.addEventListener("focusin",L,!0),document.addEventListener("keydown",L,!0),()=>{document.removeEventListener("mousedown",L,!0),document.removeEventListener("click",L,!0),document.removeEventListener("focusin",L,!0),document.removeEventListener("keydown",L,!0)}},[]),r.useEffect(()=>{const L={};pt.forEach((q,Y)=>{L[String(Y+1)]=q.id});const U=q=>{var rs,Ls,Es,Ds;if((q.metaKey||q.ctrlKey)&&q.key.toLowerCase()==="k"){q.preventDefault(),C(!0);return}if(q.key==="/"&&!q.metaKey&&!q.ctrlKey){const Qe=(Ls=(rs=q.target)==null?void 0:rs.tagName)==null?void 0:Ls.toLowerCase();if(Qe!=="input"&&Qe!=="textarea"&&!((Es=q.target)!=null&&Es.isContentEditable)){q.preventDefault(),C(!0);return}}const Y=document.activeElement;if(!Y||Y===document.body||Y===document.documentElement)return;const E=q.target,J=(Ds=E==null?void 0:E.tagName)==null?void 0:Ds.toLowerCase(),ee=J==="input"||J==="textarea"||J==="select"||J==="button"||J==="option"||J==="label"||!!(E!=null&&E.isContentEditable);let ue=!1;if(E&&typeof E.closest=="function"&&(ue=!!E.closest('form, [role="dialog"], [contenteditable], [data-no-key]')),q.repeat||i.current||ee||ue||q.metaKey||q.ctrlKey||q.altKey||q.shiftKey||Date.now()<F.current)return;const ce=L[q.key];ce&&(q.preventDefault(),P(ce))};return document.addEventListener("keydown",U),()=>document.removeEventListener("keydown",U)},[]);const _=r.useMemo(()=>async()=>{try{const L=await R.get("/snapshot");l(U=>({...U??{},...L}))}catch(L){s.error(`Refresh failed: ${L.message}`)}},[s]),P=r.useCallback(L=>{o(L)},[]),V=r.useMemo(()=>{const L=N.map(U=>({id:U.id,label:U.label,icon:U.kind==="iframe"?is:As,isMod:!0,modId:U.modId}));return[...pt,...L]},[N]),W=r.useMemo(()=>c&&x?kc(n,{snapshot:c,settings:x,activeTab:n,setActiveTab:P,refreshSnapshot:_},N,f):null,[n,c,x,N,f,_,P]),K=async()=>{try{const L=await R.get("/projects");l(U=>{var q;return U&&{...U,projects:L.projects||[],activeProject:((q=L.projects)==null?void 0:q.find(Y=>Y.id===L.active))||null}})}catch(L){s.error(`Projects refresh failed: ${L.message}`)}},B=async L=>{try{await R.post(`/projects/${encodeURIComponent(L)}/activate`),l(U=>U&&{...U,activeProject:U.projects.find(q=>q.id===L)||null})}catch(U){s.error(`Activate failed: ${U.message}`)}},Q=L=>{const U=L.type;if(U==="agent")P("agents");else if(U==="task")P("tasks");else if(U==="mod")P("mods");else if(U==="schedule")P("schedules");else if(U==="project"){const q=L.item.id;B(q)}else if(U==="command")s.info(`/${L.item.name} — run from the TUI`,2500);else if(U==="setting"){const q=L.item.id||L.item.path||"",Y=q.split(".")[0]||"",ne=Oa.includes(Y)?`settings-${Y}`:"settings-general";P(ne);const E=J=>{if(J<=0)return;const ee=q?document.querySelector(`[data-setting-id="${CSS.escape(q)}"]`):null;ee?(ee.scrollIntoView({behavior:"smooth",block:"center"}),ee.classList.remove("setting-flash"),ee.offsetWidth,ee.classList.add("setting-flash"),window.setTimeout(()=>ee.classList.remove("setting-flash"),1500)):window.setTimeout(()=>E(J-1),80)};window.setTimeout(()=>E(15),60)}},te=((je=x==null?void 0:x.ui)==null?void 0:je.layout)||"topnav",Z=((Ce=x==null?void 0:x.ui)==null?void 0:Ce.showHeader)!==!1;return e.jsxs("div",{className:"app","data-layout":te,"data-active-tab":n,children:[e.jsx("a",{className:"skip-to-main",href:"#main-content",children:"Skip to main content"}),Z&&e.jsx(vi,{activeTab:n,onTabChange:P,wsStatus:h,version:Nc,activeProject:(c==null?void 0:c.activeProject)||null,projects:(c==null?void 0:c.projects)||[],onProjectChange:B,onProjectsRefresh:K,onOpenSearch:()=>C(!0),settings:x,notificationsSlot:e.jsx(Ci,{wsSubscribe:S}),showTabs:te==="topnav",extraTabs:V}),y.length>0&&!$&&e.jsxs("div",{className:"stuck-banner",role:"alert",children:[e.jsx(ye,{size:16}),e.jsxs("span",{children:[e.jsx("strong",{children:y.length})," agent",y.length===1?"":"s"," stuck:"," ",e.jsx("span",{className:"mono",children:y.map(L=>L.name).join(", ")})]}),e.jsx(T,{variant:"secondary",size:"sm",onClick:()=>{P("agents"),j(!0)},children:"Review"}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Dismiss",onClick:()=>j(!0),children:e.jsx(Ne,{size:14})})]}),e.jsxs("div",{className:"layout-body",children:[e.jsx(Ni,{tabs:V,activeTab:n,onTabChange:P}),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}),g&&e.jsx(wc,{onSaved:()=>{k(!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&&(!c||!x)&&e.jsxs("div",{className:"loading",children:[e.jsx(le,{size:"lg"}),e.jsx("p",{children:"Loading Bizar…"})]}),W&&e.jsx(r.Suspense,{fallback:e.jsxs("div",{className:"loading",children:[e.jsx(le,{size:"lg"}),e.jsx("p",{children:"Loading…"})]}),children:e.jsx(zc,{children:W})})]})]}),e.jsx(ki,{open:z,onClose:()=>C(!1),onSelect:Q})]})}class zc extends r.Component{constructor(){super(...arguments);bs(this,"state",{err:null});bs(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(ye,{size:20}),e.jsxs("div",{className:"view-error-body",children:[e.jsx("strong",{children:"This view crashed."}),e.jsx("pre",{children:this.state.err.message}),e.jsx(T,{variant:"secondary",size:"sm",onClick:this.reset,children:"Retry"})]})]}):this.props.children}}function Rc(){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(Za,{}):e.jsx(Sc,{})}const Ua=document.getElementById("root");if(!Ua)throw new Error("Root element #root not found");en(Ua).render(e.jsx(r.StrictMode,{children:e.jsx(Rc,{})}));
|