@polderlabs/bizar 5.5.0 → 5.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/bizar-dash/dist/assets/{EnvVarsSection-L413CQEI.js → EnvVarsSection-DoIzqrlb.js} +3 -3
  2. package/bizar-dash/dist/assets/{EnvVarsSection-L413CQEI.js.map → EnvVarsSection-DoIzqrlb.js.map} +1 -1
  3. package/bizar-dash/dist/assets/{MobileChat-0kGQb1S6.js → MobileChat-CoUCUsbr.js} +1 -1
  4. package/bizar-dash/dist/assets/{MobileChat-0kGQb1S6.js.map → MobileChat-CoUCUsbr.js.map} +1 -1
  5. package/bizar-dash/dist/assets/MobileSettings-BeO04g52.js +1 -0
  6. package/bizar-dash/dist/assets/MobileSettings-BeO04g52.js.map +1 -0
  7. package/bizar-dash/dist/assets/{Toast-C6f1zFJ2.js → Toast-D9nv5N6m.js} +1 -1
  8. package/bizar-dash/dist/assets/{Toast-C6f1zFJ2.js.map → Toast-D9nv5N6m.js.map} +1 -1
  9. package/bizar-dash/dist/assets/{icons-BsWXWkEF.js → icons-Btipv2pp.js} +100 -90
  10. package/bizar-dash/dist/assets/icons-Btipv2pp.js.map +1 -0
  11. package/bizar-dash/dist/assets/main-DHXPuddY.js +18 -0
  12. package/bizar-dash/dist/assets/main-DHXPuddY.js.map +1 -0
  13. package/bizar-dash/dist/assets/{main-BklYy02e.css → main-UG4jKK-F.css} +1 -1
  14. package/bizar-dash/dist/assets/mobile-H5KH9cTL.js +1 -0
  15. package/bizar-dash/dist/assets/{mobile-CsaN4CxH.js.map → mobile-H5KH9cTL.js.map} +1 -1
  16. package/bizar-dash/dist/assets/{mobile-layout-iFBdjEE4.js → mobile-layout-BqHxVb6_.js} +2 -2
  17. package/bizar-dash/dist/assets/{mobile-layout-iFBdjEE4.js.map → mobile-layout-BqHxVb6_.js.map} +1 -1
  18. package/bizar-dash/dist/assets/{useSlashCommands-DGJcC9iQ.js → useSlashCommands-C24-O1e7.js} +2 -2
  19. package/bizar-dash/dist/assets/{useSlashCommands-DGJcC9iQ.js.map → useSlashCommands-C24-O1e7.js.map} +1 -1
  20. package/bizar-dash/dist/index.html +7 -7
  21. package/bizar-dash/dist/mobile.html +3 -3
  22. package/bizar-dash/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -1
  23. package/bizar-dash/src/server/bg-spawner.mjs +522 -305
  24. package/bizar-dash/src/server/headroom.mjs +3 -1
  25. package/bizar-dash/src/server/memory-lightrag.mjs +26 -2
  26. package/bizar-dash/src/server/memory-store.mjs +74 -28
  27. package/bizar-dash/src/server/opencode-sdk.mjs +63 -3
  28. package/bizar-dash/src/server/plugins/registry.mjs +1 -1
  29. package/bizar-dash/src/server/routes/activity.mjs +85 -0
  30. package/bizar-dash/src/server/routes/background.mjs +31 -13
  31. package/bizar-dash/src/server/routes/memory.mjs +91 -38
  32. package/bizar-dash/src/server/routes/opencode-session-detail.mjs +1 -1
  33. package/bizar-dash/src/server/server.mjs +4 -1
  34. package/bizar-dash/src/web/components/Sidebar.tsx +0 -1
  35. package/bizar-dash/src/web/styles/main.css +52 -13
  36. package/bizar-dash/src/web/styles/memory.css +17 -0
  37. package/bizar-dash/src/web/styles/settings.css +6 -56
  38. package/bizar-dash/src/web/views/Marketplace.tsx +192 -31
  39. package/bizar-dash/src/web/views/memory/ConfigPanel.tsx +157 -7
  40. package/bizar-dash/src/web/views/memory/MemoryOverview.tsx +11 -0
  41. package/bizar-dash/src/web/views/settings/MemorySection.tsx +65 -11
  42. package/bizar-dash/tests/background-sdk-session.test.mjs +94 -0
  43. package/bizar-dash/tests/background-session-events.test.mjs +74 -0
  44. package/bizar-dash/tests/background-steer-sdk.test.mjs +71 -0
  45. package/bizar-dash/tests/background-steer.test.mjs +25 -7
  46. package/bizar-dash/tests/memory-namespace.test.mjs +2 -2
  47. package/bizar-dash/tests/memory-status-root.test.mjs +144 -0
  48. package/bizar-dash/tests/memory-store.test.mjs +5 -4
  49. package/bizar-dash/tests/memory-vault-config-endpoint.test.mjs +173 -0
  50. package/bizar-dash/tests/settings-mode-wiring.test.tsx +1 -1
  51. package/bizar-dash/tests/settings-nav.test.tsx +0 -1
  52. package/bizar-dash/tests/views/Marketplace.test.tsx +200 -0
  53. package/bizar-dash/tests/views/Memory.test.tsx +274 -0
  54. package/bizar-dash/tests/views/sidebar.test.tsx +116 -0
  55. package/bizar-dash/tests/views/topbar.test.tsx +87 -0
  56. package/cli/commands/marketplace.mjs +1 -1
  57. package/cli/memory.mjs +1 -1
  58. package/package.json +1 -1
  59. package/plugins/bizar/src/background-state.ts +11 -0
  60. package/plugins/bizar/src/background.ts +212 -34
  61. package/plugins/bizar/src/opencode-runner.ts +80 -353
  62. package/plugins/bizar/src/tools/bg-send-message.ts +160 -61
  63. package/plugins/bizar/src/tools/bg-spawn.ts +235 -156
  64. package/plugins/bizar/tests/tools/bg-send-message.test.ts +84 -11
  65. package/plugins/bizar/tests/tools/bg-spawn-http.test.ts +223 -0
  66. package/bizar-dash/dist/assets/MobileSettings-Cq1oFIdO.js +0 -1
  67. package/bizar-dash/dist/assets/MobileSettings-Cq1oFIdO.js.map +0 -1
  68. package/bizar-dash/dist/assets/icons-BsWXWkEF.js.map +0 -1
  69. package/bizar-dash/dist/assets/main-CBTgYSeG.js +0 -18
  70. package/bizar-dash/dist/assets/main-CBTgYSeG.js.map +0 -1
  71. package/bizar-dash/dist/assets/mobile-CsaN4CxH.js +0 -1
@@ -0,0 +1,18 @@
1
+ var Wa=Object.defineProperty;var qa=(s,t,a)=>t in s?Wa(s,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):s[t]=a;var Cs=(s,t,a)=>qa(s,typeof t!="symbol"?t+"":t,a);import{a as $,c as K,f as Re,b as We,S as le,t as ra,e as Va,p as Ha,d as ps,g as As,_ as Ga,W as Ys,A as Ka,M as Ya}from"./mobile-layout-BqHxVb6_.js";import{r,j as e,a as la,R as Oe,b as Xa}from"./react-vendor-Dn4wqh4Z.js";import{X as Ne,A as wt,R as ce,F as Qa,H as Ja,a as Za,C as oa,b as Pe,c as en,d as qe,e as Ye,L as ca,M as et,B as Ke,f as Xs,S as Ms,g as De,h as sn,i as Xe,j as _e,P as ns,k as gs,l as Ze,m as Is,n as St,o as Je,p as da,q as Ct,r as ye,s as tn,t as be,u as ma,v as _t,T as is,w as Vs,G as an,x as nn,y as fs,z as ke,D as Fe,I as zt,E as Ns,J as we,K as rs,N as Qs,O as es,Q as vs,U as jt,V as rn,W as Se,Y as Rt,Z as Tt,_ as js,$ as ln,a0 as st,a1 as ys,a2 as on,a3 as Ds,a4 as ls,a5 as ua,a6 as ha,a7 as bs,a8 as cn,a9 as ks,aa as dn,ab as mn,ac as un,ad as Ps,ae as hn,af as xn,ag as pn,ah as gn,ai as jn,aj as fn,ak as Wt,al as xa,am as vn,an as $t,ao as yn,ap as bn,aq as At,ar as Nn,as as kn,at as wn,au as Sn,av as Cn,aw as zn,ax as Rn,ay as ft,az as Mt,aA as It,aB as os,aC as pa,aD as cs,aE as Tn,aF as $n,aG as Js,aH as An,aI as ga,aJ as Mn,aK as Es,aL as In,aM as En,aN as ja,aO as Ls,aP as vt,aQ as Et,aR as fa,aS as he,aT as Ln,aU as Dn,aV as va,aW as Pn,aX as Fn,aY as qt,aZ as On,a_ as ya,a$ as at,b0 as ba,b1 as Lt,b2 as Bn,b3 as Un,b4 as _n,b5 as Na,b6 as Wn,b7 as qn,b8 as Vn,b9 as Hn,ba as Gn,bb as ka}from"./icons-Btipv2pp.js";import{B as A,C as Y,a as ae,b as ne,A as Kn,U as Yn,G as Xn,E as Qn,T as Jn,S as Zn,H as ei,c as si}from"./EnvVarsSection-DoIzqrlb.js";import{u as re,T as ti}from"./Toast-D9nv5N6m.js";import{V as Dt,C as ai,u as ni,a as ii,b as ri,c as li}from"./useSlashCommands-C24-O1e7.js";import{M as wa,r as Sa}from"./markdown-C6mXtQxD.js";import"./vendor-CeHGtduv.js";const Ca=r.createContext(null),oi=["button:not([disabled])","[href]","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(", ");function Te(){const s=r.useContext(Ca);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(h=>h.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(Ca.Provider,{value:{open:n,close:i,isModalOpen:t.length>0},children:[s,typeof document<"u"&&la.createPortal(e.jsx("div",{className:"modal-stack","aria-hidden":t.length===0,children:t.map((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(h=>!h.hasAttribute("disabled")&&h.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 h=x=>{var N,z,R;if(x.key!=="Tab")return;const d=c();if(d.length===0){x.preventDefault(),(N=i.current)==null||N.focus();return}const m=d[0],u=d[d.length-1],g=document.activeElement instanceof HTMLElement?document.activeElement:null;if(x.shiftKey){(!g||g===m||!((z=i.current)!=null&&z.contains(g)))&&(x.preventDefault(),u.focus());return}(!g||g===u||!((R=i.current)!=null&&R.contains(g)))&&(x.preventDefault(),m.focus())};return document.addEventListener("keydown",h),()=>{document.removeEventListener("keydown",h);const x=n.current;x&&x.isConnected&&x.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,as=new Map;function hi(s){const t=as.get(s);return t?Date.now()-t.ts>ui?(as.delete(s),null):t.data:null}function nt(s,t){as.size>=mi&&[...as.entries()].sort((i,n)=>i[1].ts-n[1].ts).slice(0,50).map(([i])=>i).forEach(i=>as.delete(i)),as.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 za({value:s,onChange:t,initialPath:a,projectsDirectory:i,rootLabel:n="Home",height:o=360}){const[c,l]=r.useState(a??i??""),[h,p]=r.useState(new Set),[x,d]=r.useState(-1),[m,u]=r.useState(null),[g,N]=r.useState({}),[z,R]=r.useState(!1),[b,w]=r.useState(null),[T,j]=r.useState(!1),[k,f]=r.useState(""),[v,L]=r.useState(null),[S,y]=r.useState(!1),M=r.useRef(null),P=r.useCallback(async E=>{try{const ee=hi(E);if(ee)return ee;const U=await $.get("/fs?path="+encodeURIComponent(E));return nt(E,U),U}catch{return null}},[]),C=r.useCallback(async E=>{var ee;R(!0),w(null);try{const U=await $.get("/fs?path="+encodeURIComponent(E));nt(E,U),u(U),d(-1)}catch(U){const oe=((ee=U.data)==null?void 0:ee.message)??U.message??"Failed to load directory";w(oe)}finally{R(!1)}},[]);r.useEffect(()=>{c?C(c):$.get("/fs").then(E=>{nt("",E),u(E),l(E.path),E.path!==s&&t(E.path)}).catch(()=>{w("Could not determine home directory."),R(!1)})},[c]),r.useEffect(()=>{s&&s!==c&&l(s)},[s]);const D=m?pi(m.entries):[],Q=D.filter(E=>E.isDir),O=D,J=E=>{E.isDir&&(l(E.path),t(E.path))},_=()=>{m!=null&&m.parent&&(l(m.parent),t(m.parent))},q=E=>{E!==c&&(l(E),t(E))},F=async()=>{const E=await P("");E&&(l(E.path),t(E.path))},V=async()=>{if(!i)return;const E=await P(i);E&&(l(E.path),t(E.path))},X=()=>{j(!0),f(""),L(null),setTimeout(()=>{var E;return(E=M.current)==null?void 0:E.focus()},0)},B=()=>{j(!1),f(""),L(null)},se=async()=>{var ee;const E=gi(k);if(!E.ok){L(E.reason);return}y(!0),L(null);try{const U=await $.post("/fs/mkdir",{parent:c,name:k.trim()});as.delete(c),await C(c),t(U.path),j(!1),f("")}catch(U){const oe=U;oe.status===409?L(`A folder named "${k.trim()}" already exists.`):L(((ee=oe.data)==null?void 0:ee.message)??U.message??"Failed to create folder.")}finally{y(!1)}},xe=E=>{E.key==="Enter"?(E.preventDefault(),se()):E.key==="Escape"&&(E.preventDefault(),B())},Ce=E=>{p(ee=>{const U=new Set(ee);return U.has(E)?U.delete(E):U.add(E),U}),g[E]||P(E).then(ee=>{ee&&N(U=>({...U,[E]:ee.entries.filter(oe=>oe.isDir)}))})},H=E=>{if(!m)return;const ee=O.filter(G=>G.isDir),U=O.filter(G=>!G.isDir),oe=[...ee,...U];if(E.key==="ArrowDown")E.preventDefault(),d(G=>Math.min(G+1,oe.length-1));else if(E.key==="ArrowUp")E.preventDefault(),d(G=>Math.max(G-1,0));else if(E.key==="Enter"||E.key===" "){E.preventDefault();const G=oe[x];G&&(E.key==="Enter"&&G.isDir?J(G):G.isDir&&t(G.path))}else E.key==="Backspace"&&(E.preventDefault(),_())},te=xi((m==null?void 0:m.path)??c??"/"),ie=m==null?void 0:m.parent,me=ie!=null,W=c.split("/").filter(Boolean).at(-1)??"/";return e.jsxs("div",{className:"file-browser",onKeyDown:H,tabIndex:-1,children:[e.jsx("div",{className:"file-browser-breadcrumb",role:"navigation","aria-label":"Path breadcrumb",children:te.map((E,ee)=>e.jsxs("span",{className:"file-browser-breadcrumb-item",children:[ee>0&&e.jsx("span",{className:"file-browser-breadcrumb-sep","aria-hidden":!0,children:"/"}),e.jsx("button",{type:"button",className:"file-browser-breadcrumb-btn",onClick:()=>q(E.path),title:E.path,children:ee===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:_,disabled:!me,title:"Go up (Backspace)","aria-label":"Go up one level",children:e.jsx(wt,{size:13})}),e.jsx("button",{type:"button",className:"file-browser-tool-btn",onClick:()=>C(c),disabled:z,title:"Refresh","aria-label":"Refresh",children:e.jsx(ce,{size:13,className:z?"spin":""})}),e.jsx("button",{type:"button",className:"file-browser-tool-btn",onClick:X,title:"New folder","aria-label":"Create new folder",children:e.jsx(Qa,{size:13})}),e.jsxs("div",{className:"file-browser-chips",children:[e.jsxs("button",{type:"button",className:"file-browser-chip",onClick:F,children:[e.jsx(Ja,{size:11})," ",n]}),i&&e.jsxs("button",{type:"button",className:"file-browser-chip",onClick:V,title:i,children:[e.jsx(Za,{size:11})," ",i.split("/").filter(Boolean).at(-1)??"Projects"]})]})]}),T?e.jsxs("div",{className:"file-browser-mkdir",children:[e.jsx("input",{ref:M,type:"text",className:"file-browser-mkdir-input",placeholder:"Folder name",value:k,onChange:E=>{f(E.target.value),L(null)},onKeyDown:xe,"aria-label":"New folder name","aria-invalid":v?"true":void 0,"aria-describedby":v?"mkdir-error":void 0,disabled:S,maxLength:255}),v?e.jsx("span",{id:"mkdir-error",className:"file-browser-mkdir-error",role:"alert",children:v}):e.jsx("span",{className:"file-browser-mkdir-hint",children:"Enter to create, Esc to cancel"})]}):e.jsx("span",{className:"file-browser-count-hint",children:z?"…":`${D.length} in ${W}`})]}),b&&e.jsxs("div",{className:"file-browser-error",children:[e.jsx(oa,{size:13}),e.jsx("span",{children:b}),e.jsx("button",{type:"button",className:"file-browser-retry",onClick:()=>C(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(Ra,{path:c,entries:Q,expanded:h,childrenMap:g,onToggle:Ce,onNavigate:J,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."]}),O.length===0?e.jsx("div",{className:"file-browser-empty",children:"This folder is empty"}):e.jsx("div",{className:"file-browser-flat-list",children:O.map((E,ee)=>{const U=E.isDir,oe=ee===x,G=E.path===s;return e.jsxs("div",{role:"option","aria-selected":G,className:["file-browser-row",U?"file-browser-row--dir":"file-browser-row--file",oe&&"file-browser-row--selected",G&&U&&"file-browser-row--active",!U&&"file-browser-row--disabled"].filter(Boolean).join(" "),onClick:()=>{U&&(d(ee),t(E.path))},onDoubleClick:()=>{U&&J(E)},title:E.path,children:[e.jsx("span",{className:"file-browser-row-icon",children:U?e.jsx(Pe,{size:13}):e.jsx(en,{size:13})}),e.jsx("span",{className:"file-browser-row-name",children:E.name}),e.jsx("span",{className:"file-browser-row-type",children:U?"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 Ra({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 h=a.has(l.path),p=i[l.path]??[];return e.jsxs("li",{className:"file-browser-tree-node",children:[e.jsxs("div",{className:["file-browser-tree-row",h&&"file-browser-tree-row--expanded"].filter(Boolean).join(" "),style:{paddingLeft:`${c*16+8}px`},children:[e.jsx("button",{type:"button",className:"file-browser-tree-toggle",onClick:x=>{x.stopPropagation(),n(l.path)},"aria-label":h?"Collapse":"Expand",children:(p.length>0,h?e.jsx(qe,{size:11}):e.jsx(Ye,{size:11}))}),e.jsxs("button",{type:"button",className:"file-browser-tree-name",onClick:()=>o(l),title:l.path,children:[e.jsx(Pe,{size:12}),e.jsx("span",{children:l.name})]})]}),h&&p.length>0&&e.jsx(Ra,{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 yt=[{id:"overview",label:"Overview",icon:ca},{id:"chat",label:"Chat",icon:et},{id:"agents",label:"Agents",icon:Ke},{id:"artifacts",label:"Glyphs",icon:Xs},{id:"tasks",label:"Tasks",icon:Ms},{id:"activity",label:"Activity",icon:De},{id:"background",label:"Active",icon:sn},{id:"skills",label:"Skills",icon:Xe},{id:"memory",label:"Memory",icon:_e},{id:"mods",label:"Mods",icon:ns},{id:"marketplace",label:"Marketplace",icon:gs},{id:"schedules",label:"Schedules",icon:Ze},{id:"plugins",label:"Plugins",icon:ns},{id:"history",label:"History",icon:Is},{id:"minimax",label:"Usage",icon:St},{id:"eval",label:"Eval",icon:Je},{id:"doctor",label:"Doctor",icon:da},{id:"settings",label:"Settings",icon:Ct}];function vi({activeTab:s,onTabChange:t,wsStatus:a,version:i,activeProject:n,projects:o,onProjectChange:c,onProjectsRefresh:l,onOpenSearch:h,settings:p,rightSlot:x,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:h,title:"Search (Ctrl/Cmd+K)","aria-label":"Open search",children:[e.jsx(ye,{size:14}),e.jsx("span",{className:"muted",children:"Search…"}),e.jsx("kbd",{children:"⌘K"})]}),e.jsx("div",{className:"topbar-spacer"}),e.jsxs("div",{className:"topbar-right",children:[d,x,e.jsxs("div",{className:K("ws-status",`ws-${a}`),title:`WebSocket: ${a}`,children:[e.jsx("span",{className:"ws-dot"}),e.jsx("span",{className:"ws-label",children:a})]})]})]}),m&&e.jsxs("nav",{className:"tabs-row",role:"tablist","aria-label":"Primary tabs",children:[yt.map(g=>{const N=g.icon,z=g.id===s;return e.jsxs("button",{type:"button",role:"tab","aria-selected":z,className:K("tab",z&&"tab-active"),onClick:()=>t(g.id),title:g.label,children:[e.jsx(N,{size:14,className:"tab-icon"}),e.jsx("span",{className:"tab-label",children:g.label}),g.id==="settings"&&z&&e.jsx("span",{className:"settings-mode-indicator",title:"Settings mode active",children:e.jsx(tn,{size:12})})]},g.id)}),u&&u.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"tab-separator","aria-hidden":"true"}),u.map(g=>{const N=g.icon,z=g.id===s;return e.jsxs("button",{type:"button",role:"tab","aria-selected":z,className:K("tab","tab-mod",z&&"tab-active"),onClick:()=>t(g.id),title:`${g.label} (mod)`,children:[e.jsx(N,{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=Te();r.useEffect(()=>{if(!o)return;const p=()=>c(!1);return document.addEventListener("click",p),()=>document.removeEventListener("click",p)},[o]);const h=()=>{l.open({title:"Add project",children:e.jsx(bi,{settings:n,onAdd:async(p,x)=>{try{await $.post("/projects",{path:p,name:x}),i(),c(!1),l.close()}catch(d){alert(`Add failed: ${d.message}`)}}}),footer:e.jsx("div",{className:"modal-footer-actions",children:e.jsx(A,{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(Pe,{size:14}),e.jsx("span",{className:"project-selector-name",children:(s==null?void 0:s.name)||"(no project)"}),e.jsx(qe,{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(ce,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn",onClick:h,title:"Add project","aria-label":"Add project",children:e.jsx(be,{size:12})})]})]}),e.jsxs("ul",{className:"project-selector-list",children:[t.length===0&&e.jsx("li",{className:"muted project-selector-empty",children:"No projects. Add one to start."}),t.map(p=>e.jsx("li",{children:e.jsxs("button",{type:"button",className:K("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),[h,p]=r.useState(null),x=async()=>{var u;if(a){l(!0),p(null);try{await $.get("/fs?path="+encodeURIComponent(a)),t(a,n||null)}catch(g){const N=g;N.status===404?p("That folder no longer exists. Pick another."):p(((u=N.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(za,{value:a,onChange:u=>{i(u),p(null)},projectsDirectory:(m=s==null?void 0:s.dashboard)==null?void 0:m.projectsDirectory,height:320}),h&&e.jsx("p",{className:"field-help",style:{color:"var(--error)",marginTop:4},children:h}),e.jsxs("div",{style:{marginTop:"var(--space-3)"},children:[e.jsx("label",{className:"field-label",htmlFor:"topbar-add-project-name",children:"Name (optional)"}),e.jsx("input",{id:"topbar-add-project-name",className:"input",type:"text",placeholder:"My App",value:n,onChange:u=>o(u.target.value)})]}),e.jsx("div",{style:{marginTop:"var(--space-3)",display:"flex",justifyContent:"flex-end"},children:e.jsxs(A,{variant:"primary",onClick:x,disabled:!a||c,children:[c?e.jsx("span",{className:"btn-spinner"}):null,c?"Checking…":"Add"]})})]})}const Ni=[{label:"General",sections:[{id:"theme",label:"Theme",icon:ma},{id:"layout",label:"Layout",icon:_t},{id:"general",label:"General",icon:_t}]},{label:"Core",sections:[{id:"env-vars",label:"Env Vars",icon:is},{id:"system-llm",label:"System LLM",icon:Vs}]},{label:"Experience",sections:[{id:"updates",label:"Updates",icon:ce},{id:"headroom",label:"Headroom",icon:an}]}];function ki({activeSection:s,onSectionChange:t,onExitSettings:a}){return e.jsxs("div",{className:"settings-nav-root","aria-label":"Settings sections",children:[e.jsxs("button",{type:"button",className:"settings-nav-back",onClick:a,"aria-label":"Exit settings",children:[e.jsx(wt,{size:14}),e.jsx("span",{children:"Back"})]}),e.jsx("div",{className:"settings-nav-divider","aria-hidden":"true"}),Ni.map(i=>e.jsxs("div",{className:"settings-nav-group",children:[e.jsx("div",{className:"settings-nav-group-label",children:i.label}),i.sections.map(n=>{const o=n.icon,c=s===n.id;return e.jsxs("button",{type:"button",className:K("settings-nav-item",c&&"settings-nav-item-active"),onClick:()=>t(c?null:n.id),"aria-current":c?"page":void 0,children:[o&&e.jsx(o,{size:14,className:"settings-nav-item-icon","aria-hidden":!0}),e.jsx("span",{className:"settings-nav-item-label",children:n.label}),c&&e.jsx(Ye,{size:12,className:"settings-nav-item-chevron","aria-hidden":!0})]},n.id)})]},i.label))]})}function wi({tabs:s,activeTab:t,onTabChange:a,settingsMode:i,settingsActiveSection:n,onSettingsSectionChange:o,onExitSettings:c}){if(i)return e.jsx("aside",{className:"sidebar sidebar-settings-mode","aria-label":"Settings navigation",children:e.jsx(ki,{activeSection:n??null,onSectionChange:o??(()=>{}),onExitSettings:c??(()=>{})})});const l=s.filter(p=>!p.isMod),h=s.filter(p=>p.isMod);return e.jsx("aside",{className:"sidebar","aria-label":"Primary navigation",children:e.jsxs("nav",{className:"sidebar-nav",role:"tablist",children:[l.map(p=>{const x=p.icon,d=p.id===t;return e.jsxs("button",{type:"button",role:"tab","aria-selected":d,className:K("sidebar-tab",d&&"sidebar-tab-active"),onClick:()=>a(p.id),title:p.label,children:[e.jsx(x,{size:18,"aria-hidden":!0}),e.jsx("span",{className:"sidebar-tab-label",children:p.label})]},p.id)}),h.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"sidebar-section-divider","aria-hidden":"true"}),e.jsx("div",{className:"sidebar-section-label",children:"Mods"}),h.map(p=>{const x=p.icon,d=p.id===t;return e.jsxs("button",{type:"button",role:"tab","aria-selected":d,className:K("sidebar-tab","sidebar-tab-mod",d&&"sidebar-tab-active"),onClick:()=>a(p.id),title:`${p.label} (mod)`,children:[e.jsx(x,{size:18,"aria-hidden":!0}),e.jsx("span",{className:"sidebar-tab-label",children:p.label})]},p.id)})]})]})})}const it=[{id:"all",label:"All"},{id:"projects",label:"Projects"},{id:"agents",label:"Agents"},{id:"tasks",label:"Tasks"},{id:"mods",label:"Mods"},{id:"schedules",label:"Schedules"},{id:"commands",label:"Commands"},{id:"settings",label:"Settings"}],Vt={all:null,projects:"project",agents:"agent",tasks:"task",mods:"mod",schedules:"schedule",commands:"command",settings:"setting"};function Si({open:s,onClose:t,onSelect:a}){const i=re(),[n,o]=r.useState(""),[c,l]=r.useState("all"),[h,p]=r.useState([]),[x,d]=r.useState(!1),[m,u]=r.useState(0),g=r.useRef(null),N=r.useRef(null);if(r.useEffect(()=>{let w;return s&&(N.current=document.activeElement instanceof HTMLElement?document.activeElement:null,o(""),p([]),u(0),w=window.setTimeout(()=>{var T;return(T=g.current)==null?void 0:T.focus()},30)),()=>{if(w&&window.clearTimeout(w),!s)return;const T=N.current;T&&T.isConnected&&T.focus()}},[s]),r.useEffect(()=>{if(!s)return;if(!n.trim()){p([]),u(0);return}let w=!1;d(!0);const T=setTimeout(()=>{$.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(T)}},[n,c,s,i]),!s)return null;const z={};for(const w of h){const T=w.type.toLowerCase();z[T]=z[T]||[],z[T].push(w)}const R=[];for(const w of it.map(T=>T.id)){const T=Vt[w];T&&z[T]&&R.push(...z[T])}const b=w=>{if(w.key==="Escape")t();else if(w.key==="ArrowDown"){if(w.preventDefault(),R.length===0)return;u(T=>Math.min(T+1,R.length-1))}else if(w.key==="ArrowUp"){if(w.preventDefault(),R.length===0)return;u(T=>Math.max(T-1,0))}else w.key==="Enter"&&R[m]&&(w.preventDefault(),a(R[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(ye,{size:14,"aria-hidden":!0}),e.jsx("span",{id:"search-modal-title",className:"sr-only",children:"Search"}),e.jsx("input",{ref:g,className:"search-modal-input",placeholder:"Search tasks, agents, settings, projects…",value:n,onChange:w=>o(w.target.value),onKeyDown:b,"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:it.map(w=>e.jsx("button",{type:"button",role:"tab","aria-selected":c===w.id,className:K("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:[x&&e.jsx("div",{className:"muted",children:"Searching…"}),!x&&n&&R.length===0&&e.jsx("div",{className:"muted",children:"No results."}),!x&&!n&&e.jsx("div",{className:"muted",children:"Type to search…"}),it.map(w=>{const T=Vt[w.id];if(!T)return null;const j=z[T];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(k=>{const f=R.indexOf(k);return e.jsxs("button",{type:"button",className:K("search-result",f===m&&"search-result-active"),onMouseEnter:()=>u(f),onClick:()=>{a(k),t()},children:[e.jsx("span",{className:"search-result-type",children:k.type}),e.jsx("span",{className:"search-result-label",children:Ci(k)})]},`${k.type}-${f}`)})]},w.id)})]}),e.jsx("div",{className:"search-modal-foot",children:e.jsx("span",{className:"muted",children:"↑↓ navigate · ↵ open · esc close"})})]})})}function Ci(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 zi={info:zt,success:Fe,warning:ke,error:oa};function Ri({onCountChange:s,wsSubscribe:t}){const a=re(),[i,n]=r.useState(!1),[o,c]=r.useState([]),[l,h]=r.useState(null),[p,x]=r.useState(!1),d=r.useRef(null),m=r.useRef(0),u=async()=>{var b;try{x(!0);const w=await $.get("/notifications?limit=200");c(w.notifications||[]),h(w.stats||null),m.current=((b=w.stats)==null?void 0:b.unread)||0,s==null||s(m.current)}catch(w){console.warn("[notifications] reload failed:",w.message)}finally{x(!1)}};r.useEffect(()=>{u()},[]),r.useEffect(()=>t?t(w=>{if(w.type==="notification:new"){const T=w.notification;c(j=>[T,...j.filter(k=>k.id!==T.id)]),T.read||(m.current+=1,h(j=>j?{...j,unread:(j.unread||0)+1}:{total:1,unread:1,lastTs:T.ts,counts:{[T.severity||"info"]:1}}),s==null||s(m.current))}else w.type==="notifications:change"&&u()}):void 0,[t]),r.useEffect(()=>{if(!i)return;const b=T=>{d.current&&(d.current.contains(T.target)||n(!1))},w=T=>{T.key==="Escape"&&n(!1)};return document.addEventListener("mousedown",b),document.addEventListener("keydown",w),()=>{document.removeEventListener("mousedown",b),document.removeEventListener("keydown",w)}},[i]);const g=async()=>{try{await $.post("/notifications/read-all",{}),c(b=>b.map(w=>({...w,read:!0}))),h(b=>b&&{...b,unread:0}),m.current=0,s==null||s(0),a.success("All notifications marked as read.",1500)}catch(b){a.error(`Failed: ${b.message}`)}},N=async b=>{try{await $.post(`/notifications/${encodeURIComponent(b)}/read`,{}),c(w=>w.map(T=>T.id===b?{...T,read:!0}:T)),h(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 b=>{try{await $.del(`/notifications/${encodeURIComponent(b)}`),c(w=>{const T=w.find(j=>j.id===b);return T&&!T.read&&(m.current=Math.max(0,m.current-1),h(j=>j&&{...j,unread:Math.max(0,j.unread-1)}),s==null||s(m.current)),w.filter(j=>j.id!==b)})}catch(w){a.error(`Failed: ${w.message}`)}},R=(l==null?void 0:l.unread)||0;return e.jsxs("div",{className:"notifications-root",ref:d,children:[e.jsxs("button",{type:"button",className:K("topbar-icon-btn notifications-bell",i&&"is-open"),onClick:()=>n(b=>!b),title:"Notifications","aria-label":"Notifications","aria-haspopup":"true","aria-expanded":i,children:[e.jsx(nn,{size:16}),R>0&&e.jsx("span",{className:"notifications-badge",children:R>99?"99+":R})]}),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"}),R>0&&e.jsxs("span",{className:"muted text-sm",children:[" · ",R," unread"]})]}),e.jsxs("div",{className:"notifications-panel-head-actions",children:[e.jsxs(A,{size:"sm",variant:"ghost",onClick:g,disabled:R===0,children:[e.jsx(fs,{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(b=>{const w=zi[b.severity]||zt;return e.jsxs("div",{className:K("notification-item",!b.read&&"is-unread",`severity-${b.severity}`),children:[e.jsx(w,{size:14,className:`notification-icon severity-${b.severity}`}),e.jsxs("div",{className:"notification-body",children:[b.title&&e.jsx("div",{className:"notification-title",children:b.title}),e.jsx("div",{className:"notification-msg",children:b.message}),e.jsxs("div",{className:"notification-meta muted",children:[e.jsx("span",{className:"mono",children:b.source}),e.jsx("span",{children:"·"}),e.jsx("span",{children:Re(b.ts)})]})]}),e.jsxs("div",{className:"notification-actions",children:[!b.read&&e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>N(b.id),title:"Mark as read","aria-label":"Mark as read",children:e.jsx(fs,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger",onClick:()=>z(b.id),title:"Remove","aria-label":"Remove",children:e.jsx(Ne,{size:12})})]})]},b.id)})}),e.jsx("footer",{className:"notifications-panel-foot",children:e.jsx("span",{className:"muted text-sm",children:l?`${l.total} total · last ${Re(l.lastTs||new Date().toISOString())}`:""})})]})]})}function Ti({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(A,{variant:"ghost",onClick:t,children:"Close"})})]})}const $i=["blank","feature-design","bug-investigation","decision-record","horizontal","vertical"];function Ai({data:s,onClose:t}){const a=(s==null?void 0:s.templates)??$i,i=(s==null?void 0:s.defaultTemplate)??"blank",[n,o]=r.useState(""),[c,l]=r.useState(i),[h,p]=r.useState(!1),[x,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 $.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))})]}),x&&e.jsx("p",{style:{marginBottom:12,color:"var(--color-danger)",fontSize:13},children:x}),e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx(A,{variant:"ghost",onClick:t,disabled:h,children:"Cancel"}),e.jsx(A,{variant:"primary",onClick:m,disabled:h||!n.trim(),children:h?"Creating…":"Create"})]})]})}function Mi({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(A,{variant:"ghost",size:"sm",onClick:()=>n(o),children:"Open"})]},o))})]}),e.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:e.jsx(A,{variant:"ghost",onClick:t,children:"Close"})})]})}function Ii({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(A,{variant:"ghost",onClick:t,children:"Close"})})]})}function Ei({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 $.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(A,{variant:"ghost",onClick:t,children:"Cancel"}),e.jsx(A,{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,h)=>e.jsx("li",{style:{marginBottom:4,fontSize:13},children:l},h))})]}):e.jsxs("p",{style:{marginBottom:16,color:"var(--color-danger)"},children:["Audit failed: ",n.error??"unknown error"]}),e.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:e.jsx(A,{variant:"ghost",onClick:t,children:"Close"})})]})})}function Li({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 Di({dialog:s,onClose:t}){switch(s.component){case"visual-artifact":return e.jsx(Ti,{data:s.data,onClose:t});case"artifact-create":return e.jsx(Ai,{data:s.data,onClose:t});case"artifact-list":return e.jsx(Mi,{data:s.data,onClose:t});case"help":return e.jsx(Ii,{data:s.data,onClose:t});case"audit":return e.jsx(Ei,{data:s.data,onClose:t});default:return e.jsx(Li,{dialog:s,onClose:t})}}function Pi({setActiveTab:s,refreshKey:t=0}){var p;const[a,i]=r.useState(null),[n,o]=r.useState(!0),c=async()=>{o(!0);try{const[x,d,m]=await Promise.all([$.get("/memory/status").catch(()=>null),$.get("/memory/health").catch(()=>null),$.get("/memory/lightrag/stats").catch(()=>null)]);i({initialized:!!(x!=null&&x.initialized),mode:x==null?void 0:x.mode,projectId:x==null?void 0:x.projectId,vaultRoot:x==null?void 0:x.vaultRoot,branch:x==null?void 0:x.branch,gitClean:x==null?void 0:x.gitClean,noteCount:(x==null?void 0:x.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"),h=(a==null?void 0:a.healthStatus)==="healthy"?"var(--success)":(a==null?void 0:a.healthStatus)==="degraded"?"var(--warning)":(a==null?void 0:a.healthStatus)==="unhealthy"?"var(--error)":"var(--text-dim)";return e.jsxs(Y,{className:"memory-overview-card",children:[e.jsxs(ae,{children:[e.jsx(_e,{size:14})," Memory",e.jsxs(A,{variant:"ghost",size:"sm",style:{marginLeft:"auto"},onClick:l,children:["Open Memory ",e.jsx(Ns,{size:12})]}),e.jsx(A,{variant:"ghost",size:"sm",onClick:c,"aria-label":"Refresh",title:"Refresh",children:e.jsx(ce,{size:12})})]}),e.jsx(ne,{children:"LightRAG + Obsidian vault + git sync — opens the dedicated Memory tab."}),a!=null&&a.initialized?e.jsxs("div",{className:"memory-status-card-grid",children:[e.jsxs("div",{className:"memory-status-card-cell",children:[e.jsxs("div",{className:"memory-status-card-label",children:[e.jsx(De,{size:11})," Health"]}),e.jsx("div",{className:"memory-status-card-value",style:{color:h},children:a.healthScore!==void 0?`${a.healthScore}/100`:"—"}),e.jsx("div",{className:"memory-status-card-sub muted",children:a.healthStatus||"—"})]}),e.jsxs("div",{className:"memory-status-card-cell",children:[e.jsxs("div",{className:"memory-status-card-label",children:[e.jsx(_e,{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(we,{size:11})," Vault"]}),e.jsxs("div",{className:"memory-status-card-value",children:[a.noteCount," notes"]}),e.jsx("div",{className:"memory-status-card-sub muted ellipsis",title:a.vaultRoot||"",children:a.vaultRoot?a.vaultRoot.split("/").slice(-2).join("/"):"—"})]}),e.jsxs("div",{className:"memory-status-card-cell",children:[e.jsxs("div",{className:"memory-status-card-label",children:[e.jsx(rs,{size:11})," Git"]}),e.jsx("div",{className:"memory-status-card-value",children:a.gitClean===null?a.mode==="local-only"?"local-only":"—":a.gitClean?"clean":"dirty"}),e.jsx("div",{className:"memory-status-card-sub muted",children:a.branch?`branch ${a.branch}`:We(a.branch||"")||"—"})]})]}):e.jsxs("div",{className:"muted",children:["Memory not initialised. Click ",e.jsx("strong",{children:"Open Memory"})," to set it up."]}),n&&!a&&e.jsx("div",{className:"muted text-sm",children:"Loading…"})]})}function pe({icon:s,title:t,message:a,action:i,className:n}){return e.jsxs("div",{className:K("empty-state",n),children:[e.jsx("div",{className:"empty-icon",children:s??e.jsx(Qs,{size:32})}),e.jsx("div",{className:"empty-title",children:t}),a&&e.jsx("div",{className:"empty-message",children:a}),i&&e.jsx("div",{className:"empty-action",children:i})]})}function Fi({snapshot:s,settings:t,setActiveTab:a,refreshSnapshot:i}){var J,_,q;const n=re(),o=Te(),c=r.useRef(null),[l,h]=r.useState(s.overview??null),[p,x]=r.useState(!s.overview),[d,m]=r.useState(s.projects||[]),[u,g]=r.useState(((J=s.activeProject)==null?void 0:J.id)||null),[N,z]=r.useState(s.mods||[]),[R,b]=r.useState(!1),[w,T]=r.useState(((_=s.overview)==null?void 0:_.recentActivity)??[]),[j,k]=r.useState(!1),[f,v]=r.useState(new Set);r.useEffect(()=>{let F=!1;return(async()=>{try{const V=await $.get("/activity/hidden");F||v(new Set(V.hidden||[]))}catch{}})(),()=>{F=!0}},[]);const L=(F,V)=>{const X=`${F.kind||""}|${F.ts||""}|${F.slug||F.title||""}|${V}`;let B=0;for(let se=0;se<X.length;se++)B=(B<<5)-B+X.charCodeAt(se)|0;return Math.abs(B).toString(16).padStart(8,"0").slice(0,16)},S=async F=>{const V=new Set(f);V.add(F),v(V);try{await $.post("/activity/hide",{keys:[F]})}catch(X){const B=new Set(f);v(B),n.error(`Hide failed: ${X.message}`)}},y=async()=>{if(!confirm("Hide every recent activity item from the overview? The full log stays in Settings → Activity Log."))return;const F=w.map((X,B)=>L(X,B)),V=new Set(f);F.forEach(X=>V.add(X)),v(V);try{await $.post("/activity/hide",{keys:F}),n.success(`Hidden ${F.length} item(s). Restore them in Settings → Activity Log.`)}catch(X){n.error(`Clear failed: ${X.message}`)}},M=async()=>{v(new Set);try{await $.del("/activity/hide"),n.success("All hidden activity restored to the overview.")}catch(F){n.error(`Restore failed: ${F.message}`)}};r.useEffect(()=>{var F;s.overview&&(h(s.overview),T(s.overview.recentActivity??[]),x(!1)),m(s.projects||[]),g(((F=s.activeProject)==null?void 0:F.id)||null),z(s.mods||[])},[s.overview,s.projects,s.activeProject,s.mods]),r.useEffect(()=>{let F;try{const V=$.getToken(),X=V?`/api/activity/stream?token=${encodeURIComponent(V)}`:"/api/activity/stream";F=new EventSource(X),F.addEventListener("snapshot",B=>{try{const se=JSON.parse(B.data);T(Array.isArray(se.events)?se.events.slice(0,50):[])}catch{}}),F.addEventListener("activity",B=>{try{const se=JSON.parse(B.data);T(xe=>[se,...xe].slice(0,50))}catch{}})}catch{}return()=>{try{F==null||F.close()}catch{}}},[]);const P=async()=>{n.info("Refreshing…",1500),await i();try{const F=await $.get("/projects");m(F.projects||[]),g(F.active||null)}catch{}},C=()=>{o.open({title:"Add project",children:e.jsx(Oi,{settings:t,onAdd:async(F,V)=>{try{const X=await $.post("/projects",{path:F,name:V});m(B=>[...B.filter(se=>se.id!==X.id),X]),n.success("Project added."),o.close()}catch(X){n.error(`Add failed: ${X.message}`)}}}),footer:e.jsx("div",{className:"modal-footer-actions",children:e.jsx(A,{variant:"ghost",onClick:()=>o.close(),children:"Cancel"})})})},D=async()=>{var F;try{const V=await $.post("/projects/auto-detect");m(V.projects||[]),g(V.active||null);const X=(F=V.projects)==null?void 0:F.find(B=>B.id===V.active);n.success(X?`Active: ${X.name}`:"Projects refreshed."),await i()}catch(V){n.error(`Auto-detect failed: ${V.message}`)}},Q=async F=>{try{await $.post(`/projects/${encodeURIComponent(F)}/activate`),g(F),n.success("Project activated."),await i()}catch(V){n.error(`Activate failed: ${V.message}`)}},O=async F=>{if(confirm(`Remove project "${F}" from the registry?`))try{await $.del(`/projects/${encodeURIComponent(F)}`),m(V=>V.filter(X=>X.id!==F)),u===F&&g(null),n.success("Project removed.")}catch(V){n.error(`Remove failed: ${V.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 F=>{var X,B;F.preventDefault();const V=(((X=c.current)==null?void 0:X.value)||"").trim();if(V){b(!0);try{const se=await $.post("/tasks/submit",{title:V});n.success(`Odin split it into ${((B=se.subtasks)==null?void 0:B.length)||1} task(s)`),c.current&&(c.current.value=""),await i()}catch(se){n.error(`Failed: ${se.message}`)}finally{b(!1)}}},children:[e.jsx("label",{htmlFor:"overview-hero-input",className:"sr-only",children:"Describe what you want Odin to do"}),e.jsx("textarea",{id:"overview-hero-input",ref: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:R,"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(A,{type:"submit",variant:"primary",size:"lg",disabled:R,children:[R?e.jsx(le,{size:"sm"}):e.jsx(es,{size:16}),"Submit to Odin"]}),e.jsxs("span",{className:"muted",style:{fontSize:12},children:[e.jsx(Xe,{size:12,style:{display:"inline",verticalAlign:-2,color:"var(--accent)"}})," ","Odin + 12 specialist agents available"]})]})]}),e.jsx("div",{className:"overview-quick-actions-row",children:["Implement feature","Fix bug","Refactor","Investigate","Add tests","Document","Optimize","Deploy"].map(F=>e.jsx("button",{type:"button",className:"overview-quick-chip",onClick:()=>{c.current&&(c.current.value=F,c.current.focus())},children:F},F))})]}),e.jsxs("div",{className:"overview-feed",children:[e.jsxs("div",{className:"overview-feed-head",children:[e.jsx("h2",{children:"Recent activity"}),e.jsxs("div",{className:"overview-feed-head-actions",children:[f.size>0&&e.jsxs(A,{variant:"ghost",size:"sm",onClick:M,title:"Restore hidden items to this overview",children:[e.jsx(vs,{size:12})," Show ",f.size," hidden"]}),w.length>8&&e.jsx(A,{variant:"ghost",size:"sm",onClick:()=>k(F=>!F),children:j?"Show less":"Show all"}),w.length>0&&e.jsxs(A,{variant:"ghost",size:"sm",onClick:y,title:"Hide every item from the overview (full log kept)",children:[e.jsx(jt,{size:12})," Hide all"]})]})]}),f.size>0&&e.jsxs("div",{className:"activity-hidden-banner",role:"status",children:[e.jsxs("span",{children:[e.jsx(jt,{size:12,style:{verticalAlign:-2,marginRight:6}}),f.size," item",f.size===1?"":"s"," hidden from the overview."]}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:M,children:[e.jsx(vs,{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:K("activity-feed-list-wrap",!j&&"activity-feed-list-wrap-collapsed"),"aria-live":"polite","aria-relevant":"additions",children:[e.jsx(Dt,{items:w.slice(0,30).filter((F,V)=>!f.has(L(F,V))),itemHeight:60,height:Math.min(w.filter((F,V)=>!f.has(L(F,V))).length*60,480),className:"activity-feed-list",renderItem:(F,V)=>{const X=w.slice(0,30).findIndex(B=>B===F);return e.jsx(Ki,{item:F,activityKey:L(F,X),onNavigate:a,onHide:S})}}),!j&&w.length>8&&e.jsx("div",{className:"activity-feed-fade","aria-hidden":"true"})]})]}),e.jsxs(Y,{className:"project-picker",children:[e.jsxs(ae,{children:[e.jsx(Pe,{size:14})," Projects",e.jsxs(A,{variant:"ghost",size:"sm",style:{marginLeft:"auto"},onClick:C,children:[e.jsx(be,{size:12})," Add"]}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:D,title:"Use the server's working directory",children:[e.jsx(be,{size:12})," Auto-detect"]}),((q=t==null?void 0:t.dashboard)==null?void 0:q.projectsDirectory)&&e.jsxs(A,{variant:"ghost",size:"sm",title:`Scan ${t.dashboard.projectsDirectory} for projects`,onClick:async()=>{try{const F=await $.post("/projects/scan");F.error?n.error(F.error):n.success(`Added ${F.added.length}, skipped ${F.skipped}.`),await i();const V=await $.get("/projects");m(V.projects||[]),g(V.active||null)}catch(F){n.error(`Scan failed: ${F.message}`)}},children:[e.jsx(rn,{size:12})," Scan"]}),e.jsx(A,{variant:"ghost",size:"sm",onClick:P,title:"Refresh",children:e.jsx(ce,{size:12})})]}),e.jsxs(ne,{children:[d.length," project",d.length===1?"":"s"," ·"," ",l.counts.agents," agents ·"," ",l.counts.sessions," session",l.counts.sessions===1?"":"s"]}),d.length===0?e.jsx(pe,{icon:e.jsx(Pe,{size:32}),title:"No projects yet",message:"Add a project to start tracking its tasks, plans, and schedules.",action:e.jsxs("div",{className:"empty-state-actions",children:[e.jsxs(A,{variant:"primary",onClick:D,children:[e.jsx(be,{size:14})," Use current directory"]}),e.jsx(A,{variant:"secondary",onClick:C,children:"Add by path…"})]})}):e.jsx("div",{className:"project-grid",children:d.map(F=>e.jsx(Bi,{project:F,active:u===F.id,onOpen:()=>Q(F.id),onRemove:()=>O(F.id)},F.id))})]}),e.jsx(Pi,{setActiveTab:a}),e.jsxs("div",{className:"overview-cols",children:[e.jsxs(Y,{children:[e.jsx(ae,{children:"Mods"}),e.jsxs(ne,{children:["Extensions installed under ",e.jsx("code",{children:"~/.config/bizar/mods/"})]}),N.length===0?e.jsx("div",{className:"muted",children:"No mods installed."}):e.jsx("ul",{className:"mod-mini-list",children:N.map(F=>e.jsxs("li",{className:"mod-mini",children:[e.jsx("span",{className:"mod-mini-name",children:F.name}),e.jsxs("span",{className:"mod-mini-meta",children:["v",F.version," · ",F.type]}),e.jsx("span",{className:`mod-mini-pill ${F.enabled?"mod-mini-pill-on":"mod-mini-pill-off"}`,children:F.enabled?"on":"off"})]},F.id))})]}),e.jsxs(Y,{children:[e.jsx(ae,{children:"Environment"}),e.jsx(ne,{children:"Runtime + paths"}),e.jsxs("dl",{className:"env-table",children:[e.jsx("dt",{children:"Node"}),e.jsx("dd",{className:"mono",children:l.versions.node}),e.jsx("dt",{children:"Platform"}),e.jsx("dd",{className:"mono",children:l.versions.platform}),e.jsx("dt",{children:"Project root"}),e.jsx("dd",{className:"mono ellipsis",title:l.versions.projectRoot,children:l.versions.projectRoot}),e.jsx("dt",{children:"Bizar root"}),e.jsx("dd",{className:"mono ellipsis",title:l.versions.bizarRoot,children:l.versions.bizarRoot}),e.jsx("dt",{children:"Generated"}),e.jsx("dd",{className:"mono tabular-nums",children:We(l.generatedAt)})]})]})]})]})}function Oi({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),[h,p]=r.useState(null),x=async()=>{var u;if(a){l(!0),p(null);try{await $.get("/fs?path="+encodeURIComponent(a)),t(a,n||null)}catch(g){const N=g;N.status===404?p("That folder no longer exists. Pick another."):p(((u=N.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(za,{value:a,onChange:u=>{i(u),p(null)},projectsDirectory:(m=s==null?void 0:s.dashboard)==null?void 0:m.projectsDirectory,height:320}),h&&e.jsx("p",{className:"field-help",style:{color:"var(--error)",marginTop:4},children:h}),e.jsxs("div",{style:{marginTop:"var(--space-3)"},children:[e.jsx("label",{className:"field-label",htmlFor:"add-project-name",children:"Name (optional)"}),e.jsx("input",{id:"add-project-name",className:"input",type:"text",placeholder:"My App",value:n,onChange: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(A,{variant:"primary",onClick:x,disabled:!a||c,children:[c?e.jsx("span",{className:"btn-spinner"}):null,c?"Checking…":"Add"]})})]})}function Bi({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(Se,{size:12})})]}),e.jsx("div",{className:"project-card-path mono ellipsis",title:s.path,children:s.path}),e.jsx("div",{className:"project-card-meta",children:s.lastAccessed&&e.jsxs("span",{className:"muted",children:["Last opened ",Re(s.lastAccessed)]})}),e.jsx("div",{className:"project-card-actions",children:e.jsx(A,{variant:t?"ghost":"primary",size:"sm",onClick:a,children:t?e.jsxs(e.Fragment,{children:[e.jsx(Rt,{size:12})," Active"]}):e.jsx(e.Fragment,{children:"Open"})})})]})}function Ui(s){return s&&s.charAt(0).toUpperCase()+s.slice(1)}function _i(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]||Ui(a.replace(/-/g," ")),l=o[i]||i.replace(/-/g," ");return`${c} ${l}`.trim()}function Bs(s,t){for(const a of t){const i=s[a];if(typeof i=="string"&&i.trim())return i.trim()}return""}function Wi(s){const t=Bs(s,["message","text","prompt","title","name"]);if(t)return t;const a=[],i=Bs(s,["slug"]),n=Bs(s,["agent","author"]),o=Bs(s,["status"]);return i&&a.push(`Plan ${i}`),n&&a.push(n),o&&a.push(o),a.length?a.join(" · "):"No additional details."}function qi(s){return Re(s)}function Vi(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 Hi(s){const t=s.toLowerCase();return t==="task"?Ms:t==="agent"?Ke:t==="plan"?Xs:t.includes("bg")||t.includes("background")||t.includes("job")?Tt:t==="mod"?ns:t==="skill"?Xe:t.includes("error")||t.includes("failure")?js:t.includes("warn")?ke:De}function Gi(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 Ki({item:s,activityKey:t,onNavigate:a,onHide:i}){const n=Vi(s),o=Hi(s.kind||""),c=_i(s.kind||"activity"),l=Wi(s),h=Gi(s.kind||""),p=n==="error"?"var(--error)":n==="warning"?"var(--warning)":n==="success"?"var(--success)":"var(--accent)";return e.jsxs("div",{className:K("activity-feed-row",`activity-feed-row-${n}`),children:[e.jsxs("button",{type:"button",className:"activity-feed-row-main",onClick:()=>{h&&a(h)},title:h?`Open ${h}`: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:qi(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 Yi=Oe.memo(Fi);function Xi({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 Qi({session:s,mode:t,anchor:a,renameDraft:i,setRenameDraft:n,onEdit:o,onDeleteRequest:c,onConfirmDelete:l,onConfirmRename:h,onClose:p}){const x=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=R=>{const b=R.target;!x.current||!b||x.current.contains(b)||p()},N=R=>{R.key==="Escape"&&p()},z=window.setTimeout(()=>{document.addEventListener("mousedown",g),document.addEventListener("keydown",N)},0);return()=>{window.clearTimeout(z),document.removeEventListener("mousedown",g),document.removeEventListener("keydown",N)}},[p]),r.useEffect(()=>{if(t!=="rename")return;const g=window.setTimeout(()=>{var z;const N=(z=x.current)==null?void 0:z.querySelector("input.session-row-menu-input");N==null||N.focus(),N==null||N.select()},0);return()=>window.clearTimeout(g)},[t]);const u=e.jsxs("div",{ref:x,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(ln,{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(Se,{size:13,"aria-hidden":!0}),e.jsx("span",{children:"Delete"}),e.jsx("kbd",{children:"⌫"})]})]}),t==="rename"&&e.jsxs("div",{className:"session-row-menu-inline",children:[e.jsx("div",{className:"session-row-menu-inline-label chat-mono",children:"Rename session"}),e.jsx("input",{type:"text",className:"session-row-menu-input",value:i,onChange:g=>n(g.target.value),onKeyDown:g=>{g.key==="Enter"?(g.preventDefault(),h()):g.key==="Escape"&&(g.preventDefault(),p())},onClick:g=>g.stopPropagation(),"aria-label":"New session name"}),e.jsxs("div",{className:"session-row-menu-inline-actions",children:[e.jsx("button",{type:"button",className:"btn btn-ghost",onClick:g=>{g.stopPropagation(),p()},children:"Cancel"}),e.jsx("button",{type:"button",className:"btn btn-primary",onClick:g=>{g.stopPropagation(),h()},children:"Save"})]})]}),t==="confirm-delete"&&e.jsxs("div",{className:"session-row-menu-inline",children:[e.jsx("div",{className:"session-row-menu-inline-label chat-mono",children:"Delete this session?"}),e.jsxs("div",{className:"session-row-menu-inline-message",children:['"',s.title,'" and its sub-agents will be removed.']}),e.jsxs("div",{className:"session-row-menu-inline-actions",children:[e.jsx("button",{type:"button",className:"btn btn-ghost",onClick:g=>{g.stopPropagation(),p()},children:"Cancel"}),e.jsx("button",{type:"button",className:"btn btn-danger",onClick:g=>{g.stopPropagation(),l()},children:"Delete"})]})]})]});return la.createPortal(u,document.body)}function bt({node:s,depth:t=0,collapsible:a=!1,isLast:i=!0,open:n,onToggle:o}){var u;const[c,l]=r.useState(a),h=n!==void 0,p=h?n:c,x=g=>{h||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(),x(!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,N)=>e.jsx(bt,{node:g,depth:t+1,collapsible:!1,isLast:N===s.children.length-1},g.id))})]})]})}function Ji(s){return s.tree!==void 0}function Zi(s){const t=s.open??!0;if(Ji(s))return e.jsx("div",{className:`agent-tree variant-${s.variant??"full"}`,children:e.jsx(bt,{node:s.tree.root,depth:0,open:t})});const a=s.children??[];return e.jsx("div",{className:`agent-tree variant-${s.variant} agent-tree-children-only`,children:e.jsx("div",{className:"agent-tree-children-body",children:a.map((i,n)=>e.jsx(r.Fragment,{children:e.jsx(bt,{node:i,depth:0,collapsible:!1,open:t,isLast:n===a.length-1})},i.id))})})}function er({children:s,variant:t="rail",open:a=!0}){return a?e.jsx(Zi,{variant:t,open:a,children:s}):null}const sr=["Today","Yesterday","This week","Earlier"];function Ht(s,t){return s.getFullYear()===t.getFullYear()&&s.getMonth()===t.getMonth()&&s.getDate()===t.getDate()}function tr(s,t){const a=s.getTime()-t.getTime();return Math.floor(a/(1e3*60*60*24))}function ar(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());Ht(c,t)?n.Today.push(o):Ht(c,a)?n.Yesterday.push(o):tr(t,c)<7?n["This week"].push(o):n.Earlier.push(o)}return n}function nr(s){return new Date(Number(s)||Date.now()).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1})}function ir({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 rr({sessions:s,opencodeSessions:t=[],activeSessionId:a,activeOpencodeSessionId:i,activeProject:n,creating:o,onCreateSession:c,onSelectSession:l,onSelectOpencodeSession:h,onRenameSession:p,onDeleteSession:x,groupBy:d}){var O;const m=r.useMemo(()=>[...s,...t],[s,t]),u=r.useMemo(()=>[...m].sort((J,_)=>Number(_.mtime??0)-Number(J.mtime??0)),[m]),g=r.useMemo(()=>d?d(u):ar(u),[d,u]),[N,z]=r.useState({}),R=J=>N[J]===!0,[b,w]=r.useState(null),[T,j]=r.useState("main"),[k,f]=r.useState(""),[v,L]=r.useState(null),S=r.useRef({}),y=(J,_="main")=>{const q=S.current[J];if(!q)return;const F=_==="main"?q:q.querySelector(".chat-rail-item-menu-trigger")??q;if(L({id:J,rect:F.getBoundingClientRect()}),w(J),j(_),_==="rename"){const V=[...s,...t].find(X=>X.id===J);f((V==null?void 0:V.title)??(V==null?void 0:V.id)??"")}},M=()=>{w(null),j("main"),f(""),L(null)},P=J=>{if(J.source==="opencode"){h(J);return}l(J.id)},C=()=>{if(!v)return;const J=v.id,_=k.trim();if(!_){M();return}p==null||p(J,_),M()},D=()=>{v&&(x==null||x(v.id),M())},Q=d?Object.entries(g):sr.filter(J=>{var _;return(_=g[J])==null?void 0:_.length}).map(J=>[J,g[J]]);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(be,{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(Xi,{icon:e.jsx(be,{size:20,"aria-hidden":!0}),title:n?"No sessions yet":"No project",message:n?"Create your first session to start chatting.":"Pick a project in Overview to scope chat sessions."})}):e.jsx("div",{className:"chat-rail-list",children:Q.map(([J,_])=>e.jsxs("div",{className:"chat-rail-group",children:[e.jsx("div",{className:"chat-rail-group-label",children:J}),_.map(q=>{var xe,Ce;const F=q.source==="opencode",V=F?i===q.id:a===q.id,X=q.tree,B=!!((xe=X==null?void 0:X.root)!=null&&xe.children&&X.root.children.length>0),se=R(q.id);return e.jsxs(r.Fragment,{children:[e.jsxs("div",{ref:H=>{S.current[q.id]=H},role:"button",tabIndex:0,className:`chat-rail-item state-${q.state??"idle"}${V?" active":""}`,onClick:()=>P(q),onKeyDown:H=>{(H.key==="Enter"||H.key===" ")&&(H.preventDefault(),P(q))},"aria-current":V?"true":void 0,children:[e.jsx(ir,{state:q.state??"idle",agent:q.agent}),e.jsxs("div",{className:"chat-rail-item-title",children:[q.pinned&&e.jsx("span",{className:"chat-rail-pin","aria-hidden":!0,children:"★"}),F&&e.jsx(Ns,{size:11,style:{color:"var(--text-muted)",flexShrink:0},"aria-hidden":!0}),e.jsx("span",{className:"chat-ellipsis",children:q.title||q.id})]}),e.jsxs("div",{className:"chat-rail-item-meta",children:[e.jsx("span",{className:"chat-rail-item-meta-time",children:q.time??nr(q.mtime)}),(q.unread??0)>0&&e.jsx("span",{className:"chat-rail-badge",children:q.unread})]}),e.jsx("button",{type:"button",className:`chat-rail-item-menu-trigger${b===q.id?" open":""}`,"aria-label":`Session options for ${q.title||q.id}`,"aria-haspopup":"menu","aria-expanded":b===q.id,onClick:H=>{H.stopPropagation(),b===q.id?M():y(q.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"})]})}),V&&B&&e.jsx("button",{type:"button",className:`chat-rail-tree-chevron${se?" open":""}`,"aria-label":se?"Collapse sub-agents":"Expand sub-agents","aria-expanded":se,onClick:H=>{H.stopPropagation(),z(te=>({...te,[q.id]:!te[q.id]}))},children:e.jsx("svg",{viewBox:"0 0 10 10","aria-hidden":!0,children:e.jsx("polyline",{points:"3,1.5 7,5 3,8.5"})})})]}),V&&B&&se&&((Ce=X==null?void 0:X.root)==null?void 0:Ce.children)&&e.jsx(er,{children:X.root.children,variant:"rail",open:!0})]},F?`oc-${q.id}`:q.id)})]},J))}),b&&v&&e.jsx(Qi,{session:{id:v.id,title:((O=[...s,...t].find(J=>J.id===v.id))==null?void 0:O.title)??v.id},mode:T,anchor:v,renameDraft:k,setRenameDraft:f,onEdit:()=>y(b,"rename"),onDeleteRequest:()=>y(b,"confirm-delete"),onConfirmDelete:D,onConfirmRename:C,onClose:M})]})}function lr(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 rt(s){return s.toLocaleString()}function or(s){return!s||!s.includes("/")?"":s.split("/")[0]}function cr(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 dr({sessionId:s,messages:t,pinned:a,agent:i,model:n,agents:o,mcps:c,allCommands:l,activeSource:h="bizar",onRename:p,onDelete:x,onExport:d,busy:m,error:u,onRetry:g}){const[N,z]=r.useState(null);r.useEffect(()=>{let y=!1;return(async()=>{try{const M=await fetch("/api/usage?range=24h",{headers:{Accept:"application/json"}});if(!M.ok)return;const P=await M.json();y||z(P)}catch{}})(),()=>{y=!0}},[s]);const R=(t==null?void 0:t.length)??0,b=(a==null?void 0:a.size)??0,w=t.reduce((y,M)=>y+(M.content||M.message||"").length,0),T=Math.round(w/4),j=cr(n),k=T/1e6*j,f=(N==null?void 0:N.totalTokens)??T,v=(N==null?void 0:N.costUsd)??k,L=128e3,S=or(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(ke,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Couldn't load session"]}),e.jsx("p",{className:"chat-info-value chat-ellipsis",title: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(st,{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(et,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Session"]}),e.jsx("span",{className:`chat-source-badge chat-source-${h??"none"}`,style:{marginLeft:"auto"},children:h==="opencode"?"opencode":"bizar chat"})]}),e.jsx("div",{className:"chat-info-mono chat-ellipsis",title:s,children:s||"Live"}),e.jsxs("div",{className:"chat-info-mono",children:[rt(R)," message",R===1?"":"s",b>0&&` · ${b} pinned`]})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("h4",{children:[e.jsx(Ke,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Agent"]}),e.jsx("div",{className:"chat-info-value",children:i||"—"})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("h4",{children:[e.jsx(ys,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Model"]}),e.jsx("div",{className:"chat-mono chat-ellipsis",title:n,children:n||"—"}),S&&e.jsxs("div",{className:"chat-info-mono",children:["provider · ",S]})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsx("h4",{children:"Tokens"}),e.jsxs("div",{className:"chat-mono",children:[rt(f)," / ",rt(L)]}),e.jsx("div",{className:"chat-info-bar","aria-hidden":!0,children:e.jsx("div",{className:"chat-info-bar-fill",style:{width:`${Math.min(100,f/Math.max(1,L)*100)}%`}})})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("h4",{children:[e.jsx(on,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Cost"]}),e.jsxs("div",{className:"chat-mono",children:["$",v.toFixed(4)]}),!N&&e.jsx("div",{className:"chat-info-mono",children:"approx · live from MiniMax"})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("h4",{children:[e.jsx(Ke,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Attached agents"]}),o!=null&&o.length?e.jsx("div",{className:"chat-info-agents",children:o.map(y=>e.jsx("span",{className:"chat-info-agent",children:y.name},y.name))}):e.jsx("div",{className:"chat-info-mono",children:"None attached"})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("h4",{children:[e.jsx(ys,{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(y=>e.jsx("span",{className:"chat-info-agent",children:y.id},y.id))}):e.jsx("div",{className:"chat-info-mono",children:"No MCPs configured"})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("h4",{children:[e.jsx(is,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Slash commands"]}),e.jsxs("div",{className:"chat-info-mono",children:[(l==null?void 0:l.length)??0," available"]})]}),(p||x||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(Ds,{size:12,"aria-hidden":!0})," Rename"]}),d&&e.jsxs("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:d,title:"Export transcript",children:[e.jsx(ls,{size:12,"aria-hidden":!0})," Export"]}),x&&e.jsxs("button",{type:"button",className:"btn btn-ghost btn-sm btn-danger",onClick:x,disabled:m==null?void 0:m.delete,title:"Delete session",children:[e.jsx(Se,{size:12,"aria-hidden":!0})," Delete"]})]})]})]})}function mr({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(ua,{size:14,"aria-hidden":!0}),e.jsx("span",{children:"Jump to latest"}),t>0&&e.jsxs("span",{className:"jump-badge",children:[t," new"]})]})})}function ur({snapshot:s,settings:t,setActiveTab:a,initialTaskId:i,onClearTaskId:n}){const o=re(),c=Te(),l=ni(s,t,i??"");r.useEffect(()=>{l.setToast({error:O=>o.error(O),success:O=>o.success(O),info:O=>o.info(O),warning:O=>o.warning(O)})},[l,o]);const[h,p]=r.useState(""),[x,d]=r.useState(t.defaultAgent||"odin"),[m,u]=r.useState(t.defaultModel||""),[g,N]=r.useState([]),z=r.useRef(null),{allCommands:R,suggestions:b,setQuery:w}=ii(s);r.useEffect(()=>{w(h)},[h,w]);const T=()=>{var O;return(O=z.current)==null?void 0:O.click()},j=O=>{const J=O.target.files;if(!J)return;const _=[];for(let q=0;q<J.length;q++)_.push(J[q].name);N(q=>{const F=_.filter(V=>!q.includes(V));return[...q,...F]}),z.current&&(z.current.value="")},k=async()=>{const O=h.trim();if(!O)return;p(""),w(""),(await l.onSend(O,x,m,g)).ok&&l.jumpToLatest()},f=async()=>{l.busy.create||await l.onCreateSession()},v=O=>{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(A,{variant:"secondary",size:"sm",onClick:()=>c.close(),children:"Cancel"}),e.jsx(A,{variant:"danger",size:"sm",onClick:()=>{c.close(),l.deleteMessage(O)},children:"Delete"})]})})},L=(O,J)=>{let _="";c.open({title:"Rename session",children:e.jsx("input",{id:"rename-session-input",autoFocus:!0,defaultValue:J,"aria-label":"Session title",onChange:q=>{_=q.target.value},onKeyDown:q=>{q.key==="Enter"&&(q.preventDefault(),c.close(),l.renameSession(O,_).then(F=>{F&&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(A,{variant:"secondary",size:"sm",onClick:()=>c.close(),children:"Cancel"}),e.jsx(A,{variant:"primary",size:"sm",onClick:()=>{c.close(),l.renameSession(O,_)},children:"Save"})]})})},S=(O,J)=>{c.open({title:"Delete session?",children:e.jsxs("p",{style:{margin:0},children:["Delete ",e.jsx("strong",{children:J}),"? 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(A,{variant:"secondary",size:"sm",onClick:()=>c.close(),children:"Cancel"}),e.jsx(A,{variant:"danger",size:"sm",onClick:async()=>{c.close(),await l.deleteSession(O)},children:"Delete"})]})})},y=()=>{const O=l.activeSource==="opencode"?l.activeOpencodeSessionId:l.sessionId;if(!O)return;const _=(l.activeSource==="opencode"?l.opencodeMessages:l.bizarMessages).map(X=>{const B=X.ts??"",se=(X.role||"unknown").toUpperCase(),xe=X.content||X.message||"";return`[${B}] ${se}: ${xe}`}).join(`
2
+
3
+ `),q=new Blob([_],{type:"text/plain;charset=utf-8"}),F=URL.createObjectURL(q),V=document.createElement("a");V.href=F,V.download=`${O}.txt`,document.body.appendChild(V),V.click(),document.body.removeChild(V),URL.revokeObjectURL(F)},M=r.useMemo(()=>l.sessions.map(O=>l.getSessionDisplay(O)),[l.sessions,l.getSessionDisplay]),P=r.useMemo(()=>l.opencodeSessions.map(O=>l.getSessionDisplay(O)),[l.opencodeSessions,l.getSessionDisplay]),C=r.useMemo(()=>{const O=l.activeSource==="opencode"?l.activeOpencodeSessionId??"":l.sessionId;return O?M.find(J=>J.id===O)??P.find(J=>J.id===O)??null:null},[l.activeSource,l.activeOpencodeSessionId,l.sessionId,M,P]),D=(()=>{var _;const O=`${x||"Odin"} · ${((_=s.activeProject)==null?void 0:_.name)??"no project"}`,J=(C==null?void 0:C.state)??"idle";return J==="streaming"?`Replying · ${O}`:J==="awaiting"?`Your turn · ${O}`:`${O} · idle`})(),Q=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(rr,{sessions:M,opencodeSessions:P,activeSessionId:l.sessionId,activeOpencodeSessionId:l.activeOpencodeSessionId,activeProject:s.activeProject,creating:l.busy.create,onCreateSession:f,onSelectSession:l.selectBizarSession,onSelectOpencodeSession:O=>l.loadOpencodeSession(O.id),onRenameSession:L,onDeleteSession:O=>{const J=l.sessions.find(_=>_.id===O)??l.opencodeSessions.find(_=>_.id===O);S(O,(J==null?void 0:J.title)??"")}}),e.jsxs("section",{className:"chat-thread-section",children:[e.jsxs("div",{className:"chat-thread-head",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"chat-thread-title-row",children:[e.jsx("div",{className:"chat-thread-title",children:(C==null?void 0:C.title)??l.sessionId??"New chat"}),e.jsx("span",{className:`chat-source-badge chat-source-${l.activeSource??"none"}`,title:l.activeSource==="opencode"?"Messages go to the opencode serve child":"Messages go to the local chat store",children:Q})]}),e.jsxs("div",{className:`chat-thread-sub chat-muted state-${(C==null?void 0:C.state)??"idle"}`,children:[e.jsx("span",{className:"chat-thread-dot"}),D]}),l.opencodeError&&e.jsxs("div",{className:"chat-thread-error",role:"alert",children:[e.jsx("p",{className:"chat-error-message",children:l.opencodeError}),l.opencodeSuggestion&&e.jsx("p",{className:"chat-error-suggestion",children:l.opencodeSuggestion}),l.activeOpencodeSessionId&&e.jsx("button",{className:"btn btn-sm",type:"button",onClick:()=>l.loadOpencodeSession(l.activeOpencodeSessionId),children:"Retry"})]})]}),e.jsxs("div",{className:"chat-thread-actions",children:[C&&e.jsxs("button",{className:"btn btn-ghost",title:"Rename session",type:"button",disabled:l.busy.rename,onClick:()=>L(C.id,C.title??""),children:[e.jsx(Ds,{size:12,"aria-hidden":!0})," ",e.jsx("span",{className:"mono",children:"rename"})]}),C&&e.jsxs("button",{className:"btn btn-ghost btn-danger",title:"Delete session",type:"button",disabled:l.busy.delete,onClick:()=>S(C.id,C.title??C.id),children:[e.jsx(Se,{size:12,"aria-hidden":!0})," ",e.jsx("span",{className:"mono",children:"delete"})]}),e.jsx("button",{className:"btn btn-ghost",title:"Export transcript",type:"button",onClick:y,children:e.jsx("span",{className:"mono",children:"export"})})]})]}),e.jsx("div",{className:"chat-thread-scroll",ref:l.listRef,onScroll:l.handleScroll,role:"log","aria-live":"polite","aria-relevant":"additions","aria-label":"Chat message thread",children:e.jsx(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:O=>p(O),onCopy:O=>l.copyMessage(O),onDelete:v,onTogglePin:l.togglePin,onRegenerate:l.onRegenerate})}),!l.stickToBottom&&e.jsx(mr,{streaming:(C==null?void 0:C.state)==="streaming",newMessageCount:l.newMessageCount,onClick:l.jumpToLatest}),e.jsx(lr,{agent:x,setAgent:d,model:m,setModel:u,text:h,setText:p,sending:l.sending,activeSource:l.activeSource,onSend:k,attachments:g,setAttachments:N,suggestions:b,onPickSuggestion:O=>p(`${O.split(" ")[0]} `),agents:s.agents||[],onAttach:T}),e.jsx("input",{ref:z,type:"file",multiple:!0,style:{display:"none"},onChange:j,"aria-label":"Attach files to message",tabIndex:-1})]}),e.jsx(dr,{sessionId:l.activeSource==="opencode"?l.activeOpencodeSessionId??l.sessionId:l.sessionId,messages:l.activeSource==="opencode"?l.opencodeMessages:l.bizarMessages,pinned:l.pinned,agent:x,model:m,agents:s.agents||[],mcps:s.mcps||[],allCommands:R,activeSource:l.activeSource,onRename:()=>{C&&L(C.id,C.title??"")},onDelete:()=>{C&&S(C.id,C.title??C.id)},onExport:y,busy:l.busy})]})]})}function hr(s){return s==="ok"?"success":s==="warn"?"warning":s==="fail"?"error":s}function Qe({kind:s="neutral",children:t,className:a,dot:i=!1}){const n=hr(s);return e.jsxs("span",{className:K("badge",`badge-${n}`,a),title:`status: ${s}`,children:[i&&e.jsx("span",{className:"badge-dot"}),t]})}const Gt=["bash","read","edit","write","webfetch","websearch","task","glob","grep"],Kt=["anthropic/claude-3-5-sonnet","anthropic/claude-3-5-haiku","openai/gpt-4o","openai/gpt-4o-mini","openrouter/minimax/minimax-m3","openrouter/minimax/minimax-m2.7"],Hs=[{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 xr(s){var t;return((t=Hs.find(a=>a.id===s))==null?void 0:t.color)||"var(--text-dim)"}function pr({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 gr({agent:s}){if(s.isStuck)return e.jsx(Qe,{kind:"error",dot:!0,children:"stuck"});const t=s.status||"idle";return t==="working"?e.jsx(Qe,{kind:"info",dot:!0,children:"working"}):t==="error"?e.jsx(Qe,{kind:"error",dot:!0,children:"error"}):e.jsx(Qe,{kind:"neutral",dot:!0,children:"idle"})}function jr({snapshot:s,refreshSnapshot:t}){const a=re(),i=Te(),[n,o]=r.useState(s.agents||[]),[c,l]=r.useState(!s.agents),[h,p]=r.useState(""),[x,d]=r.useState("");r.useEffect(()=>{o(s.agents||[]),l(!s.agents)},[s.agents]);const m=async()=>{try{const j=await $.get("/agents");o(j.agents||[])}catch(j){a.error(`Agents load failed: ${j.message}`)}finally{l(!1)}},u=r.useMemo(()=>{let j=[...n];if(h&&(j=j.filter(k=>h==="__none__"?!k.category:(k.category||"")===h)),x){const k=x.toLowerCase();j=j.filter(f=>f.name.toLowerCase().includes(k)||(f.description||"").toLowerCase().includes(k)||(f.tags||[]).some(v=>v.toLowerCase().includes(k)))}return j.sort((k,f)=>k.name.localeCompare(f.name))},[n,h,x]),g=r.useMemo(()=>{const j=new Set;for(const k of n)for(const f of k.tags||[])j.add(f);return Array.from(j).sort()},[n]),N=()=>{let j=null,k=null,f=null,v=null,L=null,S=null,y=null,M=null,P=null;i.open({title:"New agent",width:640,children:e.jsxs("div",{className:"agent-form",children:[e.jsx("label",{className:"field-label",htmlFor:"agent-new-name",children:"Name (a-z, 0-9, dashes)"}),e.jsx("input",{id:"agent-new-name",ref:C=>j=C,className:"input",type:"text",placeholder:"my-agent",autoFocus:!0}),e.jsx("label",{className:"field-label",htmlFor:"agent-new-desc",children:"Description"}),e.jsx("input",{id:"agent-new-desc",ref:C=>{k=C},className:"input",type:"text",placeholder:"What does this agent do?"}),e.jsxs("div",{className:"task-form-row",children:[e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"agent-new-model",children:"Model"}),e.jsxs("select",{id:"agent-new-model",ref:C=>f=C,className:"select",defaultValue:"",children:[e.jsx("option",{value:"",children:"(provider default)"}),Kt.map(C=>e.jsx("option",{value:C,children:C},C))]})]}),e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"agent-new-mode",children:"Mode"}),e.jsxs("select",{id:"agent-new-mode",ref:C=>v=C,className:"select",defaultValue:"subagent",children:[e.jsx("option",{value:"primary",children:"primary"}),e.jsx("option",{value:"subagent",children:"subagent"}),e.jsx("option",{value:"all",children:"all"})]})]}),e.jsxs("div",{className:"task-form-field",style:{flex:"0 0 80px"},children:[e.jsx("label",{className:"field-label",htmlFor:"agent-new-color",children:"Color"}),e.jsx("input",{id:"agent-new-color",ref:C=>L=C,className:"input",type:"color",defaultValue:"#8b5cf6"})]})]}),e.jsxs("div",{className:"task-form-row",children:[e.jsxs("div",{className:"task-form-field",style:{flex:1},children:[e.jsx("label",{className:"field-label",htmlFor:"agent-new-category",children:"Category"}),e.jsxs("select",{id:"agent-new-category",ref:C=>P=C,className:"select",defaultValue:"",children:[e.jsx("option",{value:"",children:"(none)"}),Hs.map(C=>e.jsx("option",{value:C.id,children:C.label},C.id))]})]}),e.jsxs("div",{className:"task-form-field",style:{flex:2},children:[e.jsx("label",{className:"field-label",htmlFor:"agent-new-tags",children:"Tags (comma-separated)"}),e.jsx("input",{id:"agent-new-tags",ref:C=>M=C,className:"input",type:"text",placeholder:"reasoning, code, planning"})]})]}),e.jsxs("fieldset",{children:[e.jsx("legend",{className:"field-label",style:{padding:0},children:"Tools"}),e.jsx("div",{ref:C=>y=C,className:"agent-tools",children:Gt.map(C=>e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{type:"checkbox",value:C,"aria-label":C}),e.jsx("span",{children:C})]},C))})]}),e.jsx("label",{className:"field-label",htmlFor:"agent-new-prompt",children:"System prompt"}),e.jsx("textarea",{id:"agent-new-prompt",ref:C=>S=C,className:"textarea",rows:6,placeholder:"You are a..."})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx(A,{variant:"ghost",onClick:()=>i.close(),children:"Cancel"}),e.jsxs(A,{variant:"primary",onClick:async()=>{const C=((j==null?void 0:j.value)||"").trim();if(!/^[a-z0-9][a-z0-9-]{0,63}$/i.test(C)){a.warning("Invalid name (a-z, 0-9, dashes).");return}const D=[];y&&y.querySelectorAll('input[type="checkbox"]:checked').forEach(O=>{D.push(O.value)});const Q=((M==null?void 0:M.value)||"").split(",").map(O=>O.trim()).filter(Boolean);try{const O=await $.post("/agents",{name:C,description:((k==null?void 0:k.value)||"").trim(),model:(f==null?void 0:f.value)||"",mode:(v==null?void 0:v.value)||"subagent",color:(L==null?void 0:L.value)||"",tools:D,tags:Q,category:(P==null?void 0:P.value)||"",prompt:(S==null?void 0:S.value)||""});o(J=>[...J,O]),a.success("Agent created."),i.close(),await t()}catch(O){a.error(`Create failed: ${O.message}`)}},children:[e.jsx(bs,{size:12})," Create"]})]})})},z=async j=>{let k=null,f=null,v=null,L=null,S=null,y=null,M=null,P=null;try{const C=await $.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:C.path})]}),e.jsx("label",{className:"field-label",htmlFor:"agent-edit-desc",children:"Description"}),e.jsx("input",{id:"agent-edit-desc",ref:D=>{k=D},className:"input",type:"text",defaultValue:C.description}),e.jsxs("div",{className:"task-form-row",children:[e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"agent-edit-model",children:"Model"}),e.jsxs("select",{id:"agent-edit-model",ref:D=>f=D,className:"select",defaultValue:C.model,children:[e.jsx("option",{value:"",children:"(provider default)"}),Kt.map(D=>e.jsx("option",{value:D,children:D},D))]})]}),e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"agent-edit-mode",children:"Mode"}),e.jsxs("select",{id:"agent-edit-mode",ref:D=>v=D,className:"select",defaultValue:C.mode||"subagent",children:[e.jsx("option",{value:"primary",children:"primary"}),e.jsx("option",{value:"subagent",children:"subagent"}),e.jsx("option",{value:"all",children:"all"})]})]}),e.jsxs("div",{className:"task-form-field",style:{flex:"0 0 80px"},children:[e.jsx("label",{className:"field-label",htmlFor:"agent-edit-color",children:"Color"}),e.jsx("input",{id:"agent-edit-color",ref:D=>L=D,className:"input",type:"color",defaultValue:C.color||"#8b5cf6"})]})]}),e.jsxs("div",{className:"task-form-row",children:[e.jsxs("div",{className:"task-form-field",style:{flex:1},children:[e.jsx("label",{className:"field-label",htmlFor:"agent-edit-category",children:"Category"}),e.jsxs("select",{id:"agent-edit-category",ref:D=>P=D,className:"select",defaultValue:C.category||"",children:[e.jsx("option",{value:"",children:"(none)"}),Hs.map(D=>e.jsx("option",{value:D.id,children:D.label},D.id))]})]}),e.jsxs("div",{className:"task-form-field",style:{flex:2},children:[e.jsx("label",{className:"field-label",htmlFor:"agent-edit-tags",children:"Tags (comma-separated)"}),e.jsx("input",{id:"agent-edit-tags",ref:D=>M=D,className:"input",type:"text",defaultValue:(C.tags||[]).join(", ")})]})]}),e.jsxs("fieldset",{children:[e.jsx("legend",{className:"field-label",style:{padding:0},children:"Tools"}),e.jsx("div",{ref:D=>y=D,className:"agent-tools",children:Gt.map(D=>{var Q;return e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{type:"checkbox",value:D,"aria-label":D,defaultChecked:(Q=C.tools)==null?void 0:Q.includes(D)}),e.jsx("span",{children:D})]},D)})})]}),e.jsx("label",{className:"field-label",htmlFor:"agent-edit-prompt",children:"System prompt"}),e.jsx("textarea",{id:"agent-edit-prompt",ref:D=>S=D,className:"textarea",rows:8,defaultValue:C.prompt||""})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx(A,{variant:"ghost",onClick:()=>i.close(),children:"Cancel"}),e.jsxs(A,{variant:"primary",onClick:async()=>{const D=[];y&&y.querySelectorAll('input[type="checkbox"]:checked').forEach(O=>{D.push(O.value)});const Q=((M==null?void 0:M.value)||"").split(",").map(O=>O.trim()).filter(Boolean);try{const O=await $.put(`/agents/${encodeURIComponent(j.name)}`,{description:((k==null?void 0:k.value)||"").trim(),model:(f==null?void 0:f.value)||"",mode:(v==null?void 0:v.value)||"subagent",color:(L==null?void 0:L.value)||"",tools:D,tags:Q,category:(P==null?void 0:P.value)||"",prompt:(S==null?void 0:S.value)||""});o(J=>J.map(_=>_.name===j.name?O:_)),a.success("Agent saved."),i.close(),await t()}catch(O){a.error(`Save failed: ${O.message}`)}},children:[e.jsx(bs,{size:12})," Save"]})]})})}catch(C){a.error(`Load failed: ${C.message}`)}},R=async j=>{if(confirm(`Delete agent "${j.name}"? This removes ${j.path}.`))try{await $.del(`/agents/${encodeURIComponent(j.name)}`),o(k=>k.filter(f=>f.name!==j.name)),a.success("Agent deleted.")}catch(k){a.error(`Delete failed: ${k.message}`)}},b=async j=>{let k=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:f=>k=f,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(A,{variant:"ghost",onClick:()=>i.close(),children:"Cancel"}),e.jsxs(A,{variant:"primary",onClick:async()=>{const f=((k==null?void 0:k.value)||"").trim();if(!f){a.warning("Prompt is required.");return}try{await $.post(`/agents/${encodeURIComponent(j.name)}/invoke`,{prompt:f}),a.success(`Invoked ${j.name}.`),i.close()}catch(v){a.error(`Invoke failed: ${v.message}`)}},children:[e.jsx(ks,{size:14})," Invoke"]})]})})},w=async j=>{try{const k=await $.post(`/agents/${encodeURIComponent(j.name)}/restart`);o(f=>f.map(v=>v.name===j.name?k:v)),a.success(`${j.name} restarted.`)}catch(k){a.error(`Restart failed: ${k.message}`)}},T=async(j,k)=>{try{const f=await $.post(`/agents/${encodeURIComponent(j.name)}/status`,{status:k});o(v=>v.map(L=>L.name===j.name?f:L))}catch(f){a.error(`Status update failed: ${f.message}`)}};return e.jsxs("div",{className:"view view-agents",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(Ke,{size:18})," Agents (",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:x,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:h,onChange:j=>p(j.target.value),children:[e.jsx("option",{value:"",children:"All categories"}),Hs.map(j=>e.jsx("option",{value:j.id,children:j.label},j.id)),e.jsx("option",{value:"__none__",children:"(no category)"})]}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:m,children:[e.jsx(ce,{size:14})," Refresh"]}),e.jsxs(A,{variant:"primary",size:"sm",onClick:N,children:[e.jsx(be,{size:14})," New agent"]})]})]}),g.length>0&&e.jsxs("div",{className:"agent-tags-row",children:[e.jsx(ha,{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(pe,{icon:e.jsx(Ke,{size:32}),title:"No agents found",message:"Run bizar in the terminal to install Bizar."}):e.jsx("div",{className:"agent-grid",children:u.map(j=>e.jsx(fr,{agent:j,onInvoke:()=>b(j),onEdit:()=>z(j),onDelete:()=>R(j),onRestart:()=>w(j),onSetStatus:k=>T(j,k)},j.name))})]})}function fr({agent:s,onInvoke:t,onEdit:a,onDelete:i,onRestart:n,onSetStatus:o}){const[c,l]=r.useState(!1),h=xr(s.category),p=(s.status==="working"||!!s.currentTaskId)&&!s.isStuck;return e.jsxs(Y,{variant:"elevated",interactive:!0,className:K("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(pr,{status:s.status,isStuck:s.isStuck}),s.name]}),e.jsxs("div",{className:"agent-card-badges",children:[s.category&&e.jsx("span",{className:"agent-card-category",style:{background:`color-mix(in srgb, ${h} 18%, transparent)`,color:h},children:s.category}),e.jsx(gr,{agent:s})]})]}),e.jsx("p",{className:"agent-card-desc",children:ra(s.description,200)}),e.jsxs("div",{className:"agent-card-meta",children:[e.jsx("span",{className:"mono",title:s.model||"",children:s.model||"—"}),e.jsx("span",{className:"tabular-nums muted",children:Re(s.mtime)})]}),s.tags&&s.tags.length>0&&e.jsx("div",{className:"agent-card-tags",children:s.tags.map(x=>e.jsx("span",{className:"agent-card-tag",children:x},x))}),(p||s.lastTask)&&e.jsxs("div",{className:"agent-card-activity",children:[s.currentTaskId&&e.jsxs("div",{className:"agent-card-row",children:[e.jsx(De,{size:12}),e.jsx("span",{className:"muted",children:"Working on"}),e.jsx("code",{className:"mono",children:s.currentTaskId})]}),s.lastTask&&!s.currentTaskId&&e.jsxs("div",{className:"agent-card-row",children:[e.jsx(Fe,{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:Re(s.lastTask.finishedAt)})]}),s.tasksTotal!=null&&s.tasksTotal>0&&e.jsxs("div",{className:"agent-card-row",children:[e.jsx(cn,{size:12}),e.jsx("span",{className:"muted",children:"Success rate"}),e.jsxs("span",{className:"tabular-nums",children:[Math.round((s.successRate||0)*100),"%"]}),e.jsxs("span",{className:"muted tabular-nums",children:["(",s.tasksSucceeded,"/",s.tasksTotal,")"]})]})]}),s.lastError&&e.jsxs("div",{className:"agent-card-error",children:[e.jsx(ke,{size:12}),e.jsxs("span",{className:"muted",children:["Last error: ",s.lastError.message]})]}),e.jsxs("div",{className:"agent-card-actions",children:[e.jsxs(A,{variant:"primary",size:"sm",onClick:t,children:[e.jsx(ks,{size:12})," Invoke"]}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:a,children:[e.jsx(Ds,{size:12})," Edit"]}),(s.isStuck||s.status==="working"||s.status==="error")&&e.jsxs(A,{variant:"ghost",size:"sm",onClick:n,title:"Reset agent status",children:[e.jsx(st,{size:12})," Restart"]}),e.jsx(A,{variant:"ghost",size:"sm",onClick:i,children:e.jsx(Se,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":c?"Collapse":"Expand",onClick:()=>l(x=>!x),style:{marginLeft:"auto"},children:c?e.jsx(qe,{size:12}):e.jsx(Ye,{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(A,{variant:s.status==="idle"?"primary":"ghost",size:"sm",onClick:()=>o("idle"),children:"Idle"}),e.jsx(A,{variant:s.status==="working"?"primary":"ghost",size:"sm",onClick:()=>o("working"),children:"Working"}),e.jsx(A,{variant:s.status==="error"?"primary":"ghost",size:"sm",onClick:()=>o("error"),children:"Error"})]}),e.jsxs("div",{className:"agent-card-meta",children:[e.jsx(Pe,{size:11}),e.jsx("code",{className:"mono agent-card-path",children:s.path})]})]})]})}function vr({id:s,children:t}){return e.jsx("div",{id:s,"data-block-id":s,className:K("glyph-richtext"),style:Ta,children:e.jsx(wa,{remarkPlugins:[Sa],children:t})})}const yr={info:{bg:"var(--info-soft, rgba(96, 165, 250, 0.12))",border:"var(--info)",fg:"var(--info)",icon:zt,label:"Note"},warn:{bg:"var(--warning-soft, rgba(251, 191, 36, 0.15))",border:"var(--warning)",fg:"var(--warning)",icon:ke,label:"Warning"},success:{bg:"var(--success-soft, rgba(52, 211, 153, 0.15))",border:"var(--success)",fg:"var(--success)",icon:Fe,label:"Success"},danger:{bg:"var(--error-soft, rgba(248, 113, 113, 0.12))",border:"var(--error)",fg:"var(--error)",icon:Ps,label:"Danger"}};function br({id:s,tone:t="info",children:a}){const i=yr[t],n=i.icon;return e.jsxs("div",{id:s,"data-block-id":s,className:K("glyph-callout",`glyph-callout-${t}`),style:{display:"flex",gap:12,padding:"12px 16px",margin:"12px 0",borderLeft:`3px solid ${i.border}`,background:i.bg,borderRadius:8,color:"var(--text)"},role:t==="danger"||t==="warn"?"alert":void 0,children:[e.jsx("div",{style:{flexShrink:0,color:i.fg,paddingTop:2},children:e.jsx(n,{size:18})}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontWeight:600,fontSize:13,color:i.fg,marginBottom:4},children:i.label}),e.jsx("div",{className:"glyph-richtext",style:{...Ta,fontSize:14},children:e.jsx(wa,{remarkPlugins:[Sa],children:a})})]})]})}function Nr({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(fs,{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 kr({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 wr({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 Sr({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 Cr({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:Yt,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:Yt}),o.kind==="multi"&&e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4},children:(o.options??[]).map(c=>{const l=a[o.id]??[],h=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:h,onChange:()=>{const p=h?l.filter(x=>x!==c):[...l,c];n(o.id,p)}}),e.jsx("span",{children:c})]},c)})})]},o.id))]})}const Yt={padding:"6px 10px",fontSize:13,borderRadius:6,border:"1px solid var(--border-strong)",background:"var(--bg)",color:"var(--text)",fontFamily:"inherit"},zr={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 Rr({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=zr[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 Tr({id:s,filename:t,language:a,mode:i="unified",before:n,after:o}){const c=n.split(`
4
+ `),l=o.split(`
5
+ `),h=e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 12px",background:"var(--bg)",borderBottom:"1px solid var(--border)",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:[e.jsx(hn,{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)"},x=(d,m,u)=>{const g={del:"var(--error-soft)",add:"var(--success-soft)",ctx:"transparent"},N={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:N[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:[h,i==="unified"?e.jsxs("pre",{style:p,children:[c.map((d,m)=>e.jsx("div",{children:x("-",d,"del")},`b${m}`)),l.map((d,m)=>e.jsx("div",{children:x("+",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:x("-",d,"del")},m))}),e.jsx("pre",{style:p,children:l.map((d,m)=>e.jsx("div",{children:x("+",d,"add")},m))})]})]})}const $r={up:{fg:"var(--success)",Icon:qe,label:"trending up"},down:{fg:"var(--error)",Icon:qe,label:"trending down"},flat:{fg:"var(--text-dim)",Icon:un,label:"flat"}};function Ar({id:s,label:t,value:a,trend:i,hint:n}){const o=i?$r[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===qe&&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 Mr={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,ms=60,us=80;function Ir({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(Er,{id:s})});const i=new Map(t.map(x=>[x.id,x])),n=Lr(t),o=Math.max(...n.map(x=>x.col))+1,c=Math.max(...n.map(x=>x.row))+1,l=o*(Ae+ms)+ms,h=c*(Le+us)+us;function p(x){if(!i.get(x))return null;const m=n.find(u=>u.id===x);return m?{x:ms+m.col*(Ae+ms)+Ae/2,y:us+m.row*(Le+us)+Le/2}:null}return e.jsx("div",{id:s,"data-block-id":s,className:"glyph-workflow",style:{margin:"12px 0",padding:12,border:"1px solid var(--border)",borderRadius:10,background:"var(--bg-elev)",overflow:"auto"},children:e.jsxs("svg",{role:"img","aria-label":"Workflow diagram",width:l,height:h,style:{display:"block",maxWidth:"100%"},children:[e.jsx("defs",{children:e.jsx("marker",{id:`arrow-${s}`,viewBox:"0 0 10 10",refX:"9",refY:"5",markerWidth:"6",markerHeight:"6",orient:"auto-start-reverse",children:e.jsx("path",{d:"M 0 0 L 10 5 L 0 10 z",fill:"var(--text-dim)"})})}),a.map((x,d)=>{const m=p(x.from),u=p(x.to);if(!m||!u)return null;const g=u.x-m.x,N=u.y-m.y,z=g>=0?m.x+Ae/2:m.x-Ae/2,R=g>=0?u.x-Ae/2:u.x+Ae/2,b=N>=0?m.y+Le/2:m.y-Le/2,w=N>=0?u.y-Le/2:u.y+Le/2,T=(z+R)/2,j=(b+w)/2;return e.jsxs("g",{children:[e.jsx("line",{x1:z,y1:b,x2:R,y2:w,stroke:"var(--text-dim)",strokeWidth:1.5,markerEnd:`url(#arrow-${s})`}),x.label&&e.jsx("text",{x:T,y:j-4,fontSize:10,fill:"var(--text-dim)",textAnchor:"middle",fontFamily:"var(--font-mono)",children:x.label})]},d)}),t.map(x=>{const d=n.find(z=>z.id===x.id);if(!d)return null;const m=ms+d.col*(Ae+ms),u=us+d.row*(Le+us),g=Mr[x.type];if(x.type==="decision"){const z=m+Ae/2,R=u+Le/2,b=[[z,u],[m+Ae,R],[z,u+Le],[m,R]].map(w=>w.join(",")).join(" ");return e.jsxs("g",{children:[e.jsx("polygon",{points:b,fill:g.fill,stroke:g.stroke,strokeWidth:2}),e.jsx("foreignObject",{x:m+8,y:R-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(dn,{size:11}),x.label]})})]},x.id)}const N=x.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:N?1:2,strokeDasharray:N?"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:N?"italic":"normal",height:"100%"},children:[N&&e.jsx(mn,{size:11}),x.label]})})]},x.id)})]})})}function Er({id:s}){return e.jsx("div",{id:s,style:{padding:20,textAlign:"center",color:"var(--text-dim)",fontSize:13},children:"No workflow steps."})}function Lr(s){return s.length===0?[]:s.map((t,a)=>({id:t.id,col:a,row:0}))}const Ta={fontSize:14,lineHeight:1.6,color:"var(--text)"};function Dr({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 Pr extends Oe.Component{constructor(){super(...arguments);Cs(this,"state",{err:null})}static getDerivedStateFromError(a){return{err:a}}componentDidCatch(a,i){try{this.props.onError(this.props.blockId,this.props.blockType,a,i)}catch{}}render(){return this.state.err?e.jsxs("div",{className:"glyph-block-error",role:"alert",style:{border:"1px solid var(--error, #f85149)",background:"rgba(248, 81, 73, 0.06)",borderRadius:8,padding:"12px 14px",margin:"12px 0",color:"var(--text)",fontFamily:"var(--font-mono, ui-monospace, monospace)",fontSize:12,lineHeight:1.55},children:[e.jsxs("strong",{style:{color:"var(--error, #f85149)",fontFamily:"var(--font-sans, system-ui, sans-serif)",display:"block",marginBottom:4},children:[this.props.blockType," block crashed"]}),e.jsxs("div",{style:{color:"var(--text-muted)",marginBottom:6},children:["block id: ",e.jsx("code",{children:this.props.blockId})]}),e.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word",color:"var(--text)"},children:this.state.err.message})]}):this.props.children}}function Fr(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 Or={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 Br(s){const t=[];let a={heading:null,blocks:[]};for(const i of s){const n=Or[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 Ur({slug:s,onClose:t,onCommentAdded:a}){var B,se,xe,Ce;const i=re(),[n,o]=r.useState(null),[c,l]=r.useState([]),[h,p]=r.useState(!0),[x,d]=r.useState(null),[m,u]=r.useState(null),[g,N]=r.useState(!1),[z,R]=r.useState(!1),[b,w]=r.useState(null),[T,j]=r.useState(null),[k,f]=r.useState(""),[v,L]=r.useState(null),[S,y]=r.useState([]),M=Oe.useCallback((H,te,ie)=>{y(me=>me.some(W=>W.blockId===H)?me:[...me,{blockId:H,blockType:te,message:ie.message||String(ie)}])},[]),P=r.useRef(null),C=r.useMemo(()=>n?Br(n.blocks):[],[n]);r.useEffect(()=>{let H=!1;const te=5e3;return(async()=>{p(!0),d(null);try{const ie=new Promise((ee,U)=>setTimeout(()=>U(new Error("Request timed out after 5s")),te)),[me,W]=await Promise.race([Promise.all([$.get(`/artifacts/${encodeURIComponent(s)}/render`),$.get(`/artifacts/${encodeURIComponent(s)}`)]),ie]);if(H)return;o(me);const E=(W==null?void 0:W.comments)??[];l(Array.isArray(E)?E:[])}catch(ie){if(!H){const me=ie.message;d(me),u(me)}}finally{H||p(!1)}})(),()=>{H=!0}},[s]);function D(H){if(!P.current)return;H.preventDefault();const te=P.current.getBoundingClientRect();w({x:H.clientX,y:H.clientY,worldX:H.clientX-te.left,worldY:H.clientY-te.top})}async function Q(){if(!(!T||!k.trim()))try{const H=await $.post(`/artifacts/${encodeURIComponent(s)}/comments`,{x:T.worldX,y:T.worldY,text:k.trim(),author:"drb0rk"});l(te=>[...te,{id:H.id??`cmt_${Date.now()}`,x:T.worldX,y:T.worldY,text:k.trim(),author:"drb0rk",created:new Date().toISOString()}]),j(null),f(""),w(null),a==null||a(),i.success("Comment added")}catch(H){i.error(`Failed to add comment: ${H.message}`)}}async function O(){if(!g){N(!0);try{const H=await $.post(`/artifacts/${encodeURIComponent(s)}/submit`,{answers:[],submitter:"drb0rk"});H!=null&&H.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(H){i.error(`Submit failed: ${H.message}`)}finally{N(!1)}}}function J(){R(H=>!H)}const _=H=>{const te=H.id,ie=H.data??{},me=Fr(H);return me.ok?e.jsx(Pr,{blockId:te,blockType:H.type,onError:M,children:q(H,te,ie)},te):e.jsxs("div",{id:te,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:[H.type," block invalid"]}),e.jsxs("div",{style:{color:"var(--text-muted)",marginBottom:6},children:["block id: ",e.jsx("code",{children:te})]}),e.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:me.error})]},te)},q=(H,te,ie)=>{switch(H.type){case"RichText":return e.jsx(vr,{id:te,children:H.childrenMarkdown??""},te);case"Callout":return e.jsx(br,{id:te,tone:ie.tone??"info",children:H.childrenMarkdown??""},te);case"Checklist":return e.jsx(Nr,{id:te,items:ie.items??[]},te);case"Table":return e.jsx(kr,{id:te,columns:ie.columns??[],rows:ie.rows??[]},te);case"CodeTabs":return e.jsx(wr,{id:te,tabs:ie.tabs??[]},te);case"Decision":return e.jsx(Sr,{id:te,title:ie.title,question:ie.question,options:ie.options??[]},te);case"OpenQuestions":return e.jsx(Cr,{id:te,questions:ie.questions??[]},te);case"FileTree":return e.jsx(Rr,{id:te,title:ie.title,entries:ie.entries??[]},te);case"Diff":return e.jsx(Tr,{id:te,filename:ie.filename,language:ie.language,mode:ie.mode??"unified",before:ie.before??"",after:ie.after??""},te);case"Stat":return e.jsx(Ar,{id:te,label:ie.label??"",value:ie.value,trend:ie.trend,hint:ie.hint},te);case"Workflow":return e.jsx(Ir,{id:te,steps:ie.steps??[],connections:ie.connections},te);case"Mockup":return e.jsx(Dr,{id:te,title:ie.title,x:ie.x,y:ie.y,w:ie.w,h:ie.h,html:ie.html??""},te);case"Diagram":return e.jsx("div",{id:te,className:"glyph-block-placeholder",children:e.jsxs("em",{children:["[Diagram] ",te]})},te)}};if(h)return e.jsx("div",{className:"glyph-renderer glyph-renderer--loading",children:m?e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:"Failed to load glyph."}),e.jsx("pre",{children:m})]}):e.jsxs(e.Fragment,{children:[e.jsx(_r,{})," Loading glyph…"]})});if(x||!n)return e.jsxs("div",{className:"glyph-renderer glyph-renderer--error",children:[e.jsx("strong",{children:"Failed to load glyph."}),e.jsx("pre",{children:x??"unknown error"})]});const F=((B=n.frontmatter)==null?void 0:B.title)??s,V=((se=n.frontmatter)==null?void 0:se.status)??"draft",X=c.length;return e.jsxs("div",{className:`glyph-canvas ${z?"glyph-canvas--fullscreen":""}`,ref:P,onContextMenu:D,children:[e.jsxs("div",{className:"glyph-toolbar-floating",children:[e.jsxs("button",{className:"glyph-btn glyph-btn--primary glyph-btn--send",onClick:O,disabled:g,title:"Send comments + question answers to the agent — writes feedback.md, status=review",children:[e.jsx(es,{size:14}),e.jsx("span",{children:"Send to agent"}),e.jsx("span",{className:"glyph-btn-badge",children:X})]}),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(xn,{size:15})}),e.jsx("button",{className:"glyph-icon-btn",title:"Undo",disabled:!0,children:e.jsx(pn,{size:15})}),e.jsx("button",{className:"glyph-icon-btn",title:"Redo",disabled:!0,children:e.jsx(gn,{size:15})}),e.jsx("button",{className:"glyph-icon-btn",title:z?"Exit fullscreen":"Fullscreen",onClick:J,children:e.jsx(jn,{size:15})}),e.jsx("button",{className:"glyph-icon-btn",title:"More",children:e.jsx(fn,{size:15})}),e.jsx("span",{className:"glyph-toolbar-divider"}),e.jsxs("button",{className:"glyph-icon-btn",title:"Comment count","aria-label":"Comment count",children:[e.jsx(et,{size:15}),e.jsx("span",{className:"glyph-icon-btn-count",children:X})]}),t&&e.jsx("button",{className:"glyph-icon-btn glyph-icon-btn--close",title:"Close",onClick:t,"aria-label":"Close",children:e.jsx(Ne,{size:15})})]}),e.jsxs("div",{className:"glyph-canvas-content",children:[e.jsxs("header",{className:"glyph-canvas-title",children:[e.jsx("h1",{className:"glyph-title",children:F}),e.jsxs("div",{className:"glyph-meta",children:[e.jsx("span",{className:`glyph-status glyph-status--${V}`,children:V}),e.jsx("span",{className:"glyph-slug",children:s})]})]}),(S.length>0||((xe=n.errors)==null?void 0:xe.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:S.length>0?`${S.length} block${S.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:[S.map((H,te)=>e.jsxs("li",{children:[e.jsx("strong",{children:H.blockType})," (",e.jsx("code",{children:H.blockId}),"): ",H.message]},`be-${te}`)),(Ce=n.errors)==null?void 0:Ce.map((H,te)=>e.jsxs("li",{children:[H.line?`line ${H.line}: `:"",H.message]},`ce-${te}`))]})]}),e.jsx("div",{className:"glyph-sections",children:C.map((H,te)=>e.jsxs("section",{className:`glyph-section ${H.heading?"glyph-section--headed":"glyph-section--plain"}`,children:[H.heading&&e.jsx("h2",{className:"glyph-section-heading",children:H.heading}),e.jsx("div",{className:"glyph-section-blocks",children:H.blocks.map(_)})]},`sec-${te}-${H.heading??"ungrouped"}`))})]}),c.map(H=>e.jsxs("button",{className:`glyph-pin ${v===H.id?"glyph-pin--active":""}`,style:{left:H.x,top:H.y},onClick:te=>{te.stopPropagation(),L(v===H.id?null:H.id)},title:H.text,children:[e.jsx(Wt,{size:14}),v===H.id&&e.jsxs("div",{className:"glyph-pin-thread",children:[e.jsx("div",{className:"glyph-pin-text",children:H.text}),e.jsxs("div",{className:"glyph-pin-meta",children:[H.author??"anonymous"," · ",H.created?new Date(H.created).toLocaleString():""]})]})]},H.id)),b&&e.jsx("div",{className:"glyph-ctx-menu",style:{left:b.x,top:b.y},onClick:H=>H.stopPropagation(),children:e.jsxs("button",{className:"glyph-ctx-item",onClick:()=>{j({worldX:b.worldX,worldY:b.worldY}),w(null)},children:[e.jsx(Wt,{size:14})," Add comment here"]})}),T&&e.jsx("div",{className:"glyph-modal-overlay",onClick:()=>j(null),children:e.jsxs("div",{className:"glyph-modal",onClick:H=>H.stopPropagation(),children:[e.jsxs("h3",{children:["Add comment at (",Math.round(T.worldX),", ",Math.round(T.worldY),")"]}),e.jsx("textarea",{autoFocus:!0,value:k,onChange:H=>f(H.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:Q,disabled:!k.trim(),children:"Add comment"})]})]})})]})}function _r(){return e.jsx("span",{className:"glyph-spinner","aria-label":"loading",children:"…"})}function Wr(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 qr({snapshot:s,refreshSnapshot:t}){const a=re(),[i,n]=r.useState(s.artifacts||[]),[o,c]=r.useState(!s.artifacts),[l,h]=r.useState(null),[p,x]=r.useState(""),[d,m]=r.useState(!1);r.useEffect(()=>{s.artifacts&&(n(s.artifacts),c(!1))},[s.artifacts]);const u=async()=>{try{const R=await $.get("/artifacts");n(R.artifacts||[]),c(!1)}catch(R){a.error(`Artifacts load failed: ${R.message}`),c(!1)}},g=r.useMemo(()=>{let R=i;if(p){const b=p.toLowerCase();R=R.filter(w=>(w.slug||"").toLowerCase().includes(b)||(w.title||"").toLowerCase().includes(b))}return d||(R=R.filter(b=>b.status!=="archived")),R},[i,p,d]),N=async(R,b)=>{try{const w=await $.post("/artifacts",{slug:R,title:b});a.success(`Artifact "${w.slug}" created.`),h(w.slug),await u()}catch(w){a.error(`Create failed: ${w.message}`)}},z=async R=>{if(confirm(`Delete artifact "${R}"? This removes the directory permanently.`))try{await $.del(`/artifacts/${encodeURIComponent(R)}`),a.success("Artifact deleted."),l===R&&h(null),await u()}catch(b){a.error(`Delete failed: ${b.message}`)}};return l?e.jsxs("div",{className:"artifact-glyph-overlay",children:[e.jsx("div",{className:"artifact-glyph-toolbar",children:e.jsxs(A,{variant:"ghost",onClick:()=>{h(null),u()},children:[e.jsx(wt,{size:14})," Back to artifacts"]})}),e.jsx(Ur,{slug:l,onClose:()=>{h(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(Xs,{size:18})," Glyphs (",i.length,")"]}),e.jsx("p",{className:"view-subtitle",children:"Visual artifacts with elements, connections, and threaded comments."})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs("div",{className:"search-input",children:[e.jsx(ye,{size:14,"aria-hidden":!0}),e.jsx("label",{htmlFor:"artifacts-search",className:"sr-only",children:"Search artifacts"}),e.jsx("input",{id:"artifacts-search",className:"input",type:"text",placeholder:"Search…",value:p,onChange:R=>x(R.target.value),"aria-label":"Search artifacts"})]}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:()=>m(R=>!R),title:d?"Hide archived":"Show archived",children:[d?e.jsx(xa,{size:14}):e.jsx(vn,{size:14}),d?"Hide archived":"Show archived"]}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:u,children:[e.jsx(ce,{size:14})," Refresh"]})]})]}),e.jsx(Vr,{onCreate:N}),o?e.jsx("div",{className:"view-loading",children:e.jsx(le,{size:"lg"})}):g.length===0?e.jsx(pe,{icon:e.jsx(Xs,{size:32}),title:d?"No artifacts":"No artifacts yet",message:d?"No artifacts match your filter (try Show archived off).":"Create one above to get started."}):e.jsx("div",{className:"artifacts-grid",children:g.map(R=>e.jsx(Hr,{artifact:R,onOpen:()=>h(R.slug),onDelete:()=>z(R.slug)},R.slug))})]})}function Vr({onCreate:s}){const[t,a]=r.useState(""),[i,n]=r.useState("");return e.jsxs(Y,{className:"new-artifact",children:[e.jsxs(ae,{children:[e.jsx(be,{size:14})," New artifact"]}),e.jsx(ne,{children:"Slug must be lowercase, may contain hyphens, 1–64 chars."}),e.jsxs("form",{className:"new-artifact-form",onSubmit: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(A,{variant:"primary",type:"submit",children:"Create"})]})]})}function Hr({artifact:s,onOpen:t,onDelete:a}){const i=Wr(s.status||"draft");return e.jsxs(Y,{variant:"elevated",interactive:!0,className:"artifact-card",onClick:t,children:[e.jsxs("div",{className:"artifact-card-head",children:[e.jsx("div",{className:"artifact-card-title",children:s.title||s.slug}),e.jsx(Qe,{kind:i,children:s.status||"draft"})]}),e.jsxs("div",{className:"artifact-card-slug mono",children:[s.slug," · ",s.source]}),e.jsxs("div",{className:"artifact-card-meta",children:[s.elementCount!=null&&e.jsxs("span",{children:[s.elementCount," elements"]}),s.commentCount!=null&&e.jsxs("span",{children:[" · ",s.commentCount," comments"]}),e.jsxs("span",{children:[" · edited ",Re(s.mtime)]})]}),e.jsxs("div",{className:"artifact-card-actions",children:[e.jsxs(A,{variant:"primary",size:"sm",onClick:n=>{n.stopPropagation(),t()},children:["Open",e.jsx(Ye,{size:12})]}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:n=>{n.stopPropagation(),a()},children:[e.jsx(Se,{size:12})," Delete"]})]})]})}function Gr({children:s,className:t,onRemove:a}){return e.jsxs("span",{className:K("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 Kr({task:s,agents:t,onPromote:a,onDelete:i,onEdit:n,onRefresh:o}){var x;const c=re(),l=async()=>{try{await $.post(`/tasks/${encodeURIComponent(s.id)}/promote`),c.success("Promoted to queued.",1500),a(s.id)}catch(d){c.error(`Promote failed: ${d.message}`)}},h=async()=>{if(confirm("Delete this task?"))try{await $.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]}),((x=s.tags)==null?void 0:x.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:Re(s.createdAt)}),e.jsxs("div",{className:"backlog-item-actions",children:[e.jsx("button",{type:"button",className:"icon-btn",title:"Promote to queued",onClick:l,children:e.jsx($t,{size:13})}),e.jsx("button",{type:"button",className:"icon-btn",title:"Edit",onClick:()=>n(s),children:e.jsx(Xe,{size:13})}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger",title:"Delete",onClick:h,children:e.jsx(Se,{size:13})})]})]})]})}function Yr({agents:s,onRefresh:t}){const a=re(),[i,n]=r.useState([]),[o,c]=r.useState(!1),l=async()=>{try{c(!0);const m=await $.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 h=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()},x=m=>{},d=async()=>{var m;if(i.length!==0)try{const g=((m=(await $.post("/tasks/promote-batch",{ids:i.map(N=>N.id)})).affected)==null?void 0:m.filter(N=>N.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(Qs,{size:15}),"Backlog (",i.length,")"]}),e.jsxs("div",{className:"backlog-panel-header-actions",children:[i.length>0&&e.jsxs(A,{variant:"ghost",size:"sm",onClick:d,title:"Promote all to queued",children:[e.jsx($t,{size:12})," Promote all"]}),e.jsx(A,{variant:"ghost",size:"sm",onClick:l,title:"Refresh backlog","aria-label":"Refresh backlog",children:e.jsx(ce,{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(Qs,{size:28}),e.jsx("span",{children:"Backlog is empty."})]}):e.jsx("div",{className:"backlog-list",children:i.map(m=>e.jsx(Kr,{task:m,agents:s,onPromote:h,onDelete:p,onEdit:x,onRefresh:t},m.id))})]})}const Gs=[{id:"queued",label:"Todo",kind:"info"},{id:"doing",label:"In progress",kind:"accent"},{id:"done",label:"Done",kind:"success"},{id:"blocked",label:"Failed",kind:"error"}],Pt=["low","normal","high"];function Xr({snapshot:s,refreshSnapshot:t,setActiveTab:a}){const i=re(),n=Te(),[o,c]=r.useState(s.tasks||[]),[l,h]=r.useState(!s.tasks),[p,x]=r.useState(""),[d,m]=r.useState(""),[u,g]=r.useState(!1),[N,z]=r.useState(0),[R,b]=r.useState(""),w=async()=>{try{const y=await $.get("/tasks");c(Array.isArray(y)?y:[])}catch(y){i.error(`Tasks load failed: ${y.message}`)}finally{h(!1)}};r.useEffect(()=>{s.tasks&&(c(s.tasks),h(!1))},[s.tasks]),r.useEffect(()=>{const y=setInterval(()=>z(M=>M+1),3e4);return()=>clearInterval(y)},[]);const T=r.useMemo(()=>{let y=o.filter(M=>M.status!=="backlog");if(d&&(y=y.filter(M=>(M.priority||"normal")===d)),p.trim()){const M=p.toLowerCase();y=y.filter(P=>(P.title||"").toLowerCase().includes(M)||(P.description||"").toLowerCase().includes(M))}return y},[o,p,d]),j=r.useMemo(()=>{const y={high:0,normal:1,low:2};return[...T].sort((M,P)=>{const C=y[M.priority]??1,D=y[P.priority]??1;return C!==D?C-D:new Date(P.createdAt).getTime()-new Date(M.createdAt).getTime()})},[T]),k=o.filter(y=>y.status==="backlog").length,f=async(y,M)=>{const P=o.find(D=>D.id===y);if(!P)return;const C=P.status;c(D=>D.map(Q=>Q.id===y?{...Q,status:M}:Q)),b(`Task ${P.title} moved to ${M}.`);try{await $.patch(`/tasks/${encodeURIComponent(y)}/status`,{status:M}),i.success(`Moved to ${M}.`,1200)}catch(D){c(Q=>Q.map(O=>O.id===y?{...O,status:C}:O)),b(`Failed to move task ${P.title}: ${D.message}`),i.error(`Move failed: ${D.message}`)}},v=async y=>{if(confirm("Delete this task?"))try{await $.del(`/tasks/${encodeURIComponent(y)}`),c(M=>M.filter(P=>P.id!==y)),i.success("Task deleted.",1200)}catch(M){i.error(`Delete failed: ${M.message}`)}},L=async y=>{try{const M=await $.post(`/tasks/${encodeURIComponent(y)}/start`);M&&M.task&&c(P=>P.map(C=>C.id===y?M.task:C)),i.success("Retry dispatched.",1200)}catch(M){i.error(`Retry failed: ${M.message}`)}},S=async y=>{const M=o.find(P=>P.id===y);if(M)try{const P=await $.post("/tasks/submit",{title:M.title,description:M.description,priority:M.priority,tags:M.tags}),C=(P.subtasks||[]).length;i.success(C>1?`Odin split it into ${C} subtasks.`:"Sent to Odin.",1500),P.subtasks&&P.subtasks.length>0&&c(D=>[P.main,...P.subtasks,...D.filter(Q=>Q.id!==M.id)]),await t()}catch(P){i.error(`Submit failed: ${P.message}`)}};return e.jsxs("div",{className:"view view-tasks",children:[e.jsx("div",{className:"sr-only",role:"status","aria-live":"polite",children:R}),e.jsx("header",{className:"view-header",children:e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(Ms,{size:18})," Tasks (",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(ye,{size:12,"aria-hidden":!0}),e.jsx("input",{className:"input",type:"text",placeholder:"Search…",value:p,onChange:y=>x(y.target.value),"aria-label":"Search tasks"}),p&&e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Clear search",onClick:()=>x(""),children:e.jsx(Ne,{size:12})})]})}),e.jsx("div",{className:"tasks-toolbar-divider"}),e.jsxs("div",{className:"tasks-toolbar-group",children:[e.jsx("label",{className:"tasks-toolbar-label",htmlFor:"tasks-priority-filter",children:"Priority"}),e.jsxs("select",{id:"tasks-priority-filter",className:"select select-sm",value:d,onChange:y=>m(y.target.value),title:"Filter by priority",children:[e.jsx("option",{value:"",children:"All"}),Pt.map(y=>e.jsx("option",{value:y,children:y},y))]})]}),e.jsx("div",{className:"tasks-toolbar-spacer"}),e.jsxs("div",{className:"tasks-toolbar-group",children:[e.jsx(A,{variant:"ghost",size:"sm",onClick:w,title:"Refresh","aria-label":"Refresh tasks",children:e.jsx(ce,{size:14})}),k>0&&e.jsxs(A,{variant:u?"accent":"ghost",size:"sm",onClick:()=>g(y=>!y),title:u?"Hide backlog":"Show backlog",children:[e.jsx(Qs,{size:14}),"Backlog",e.jsx("span",{className:"badge",children:k})]}),e.jsxs(A,{variant:"primary",size:"sm",onClick:()=>Zr(n,i,c,w,t),children:[e.jsx(be,{size:14})," New task"]})]})]}),u&&k>0&&e.jsx(Yr,{agents:s.agents||[],onRefresh:t}),l?e.jsx("div",{className:"view-loading",children:e.jsx(le,{size:"lg"})}):e.jsx("div",{className:"kanban",children:Gs.map(y=>e.jsx(Qr,{column:y,tasks:j.filter(M=>M.status===y.id),onMove:f,onDelete:v,onRetry:L,onEdit:M=>el(n,i,M,c,w,t),onSubmitToOdin:S,tick:N},y.id))})]})}function Qr({column:s,tasks:t,onMove:a,onDelete:i,onRetry:n,onEdit:o,onSubmitToOdin:c,tick:l}){const[h,p]=r.useState(!1);return e.jsxs("div",{className:K("kanban-column",h&&"kanban-column-drop"),"data-column":s.id,onDragOver:x=>{x.preventDefault(),p(!0)},onDragLeave:()=>p(!1),onDrop:x=>{x.preventDefault(),p(!1);const d=x.dataTransfer.getData("text/task-id");d&&a(d,s.id)},children:[e.jsxs("div",{className:"kanban-col-header",children:[e.jsxs(ae,{children:[e.jsx("span",{className:K("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(x=>e.jsx(Jr,{task:x,onMove:d=>{const u=Gs.findIndex(g=>g.id===x.status)+d;u>=0&&u<Gs.length&&a(x.id,Gs[u].id)},onEdit:()=>o(x),onDelete:()=>i(x.id),onRetry:()=>n(x.id),onSubmitToOdin:()=>c(x.id),tick:l},x.id))})]})}function Jr({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:K("task-card",`priority-${s.priority}`),"data-task-id":s.id,draggable:!0,onDragStart:h=>{h.dataTransfer.setData("text/task-id",s.id),h.dataTransfer.effectAllowed="move"},"data-tick":c,children:[e.jsxs("div",{className:"task-card-head",children:[e.jsx("span",{className:"priority-dot",style:{background:Ha[s.priority]||"var(--info)"}}),e.jsx("div",{className:"task-card-title",children:s.title})]}),s.description&&e.jsx("div",{className:"task-card-desc",children:s.description.slice(0,160)}),e.jsxs("div",{className:"task-card-badges",children:[l&&e.jsxs("span",{className:"task-card-badge",title:`Auto-assigned to @${l}`,children:[e.jsx(Ke,{size:10})," @",l]}),s.timeSpent?e.jsxs("span",{className:"task-card-badge",children:[e.jsx(Ze,{size:10})," ",Math.round((s.timeSpent||0)/60),"m"]}):null,s.tags&&s.tags.length>0&&s.tags.slice(0,3).map(h=>e.jsx(Gr,{children:h},h))]}),e.jsxs("div",{className:"task-card-footer",children:[e.jsx("span",{className:"task-card-time tabular-nums muted",children:Re(s.createdAt)}),e.jsxs("div",{className:"task-card-actions",onClick:h=>h.stopPropagation(),children:[e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Move left",title:"Move left",onClick:()=>t(-1),children:e.jsx(yn,{size:14})}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Edit",title:"Edit",onClick:a,children:e.jsx(bn,{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(es,{size:14})}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Retry",title:"Retry",onClick:n,children:e.jsx(st,{size:14})}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger","aria-label":"Delete",title:"Delete",onClick:i,children:e.jsx(Se,{size:14})}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Move right",title:"Move right",onClick:()=>t(1),children:e.jsx(Ye,{size:14})})]})]})]})}function Zr(s,t,a,i,n){let o=null,c=null,l=null,h=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=(h==null?void 0:h.value)||"normal",N=((l==null?void 0:l.value)||"").split(",").map(z=>z.trim()).filter(Boolean);try{const z=await $.post("/tasks",{title:m,description:u,priority:g,tags:N});s.close(),typeof window<"u"&&window.dispatchEvent(new MouseEvent("mousedown")),a(R=>[z,...R]),t.success("Task created.",1200),await n()}catch(z){t.error(`Create failed: ${z.message}`)}},x=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:x}),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 Va(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=>{h=d},id:"task-priority",className:"select",defaultValue:"normal",children:Pt.map(d=>e.jsx("option",{value:d,children:d},d))})]}),e.jsxs("label",{htmlFor:"task-tags",className:"task-form-field",style:{flex:2},children:["Tags ",e.jsx("span",{className:"field-hint",children:"(comma-separated)"}),e.jsx("input",{ref:d=>{l=d},id:"task-tags",className:"input",type:"text",placeholder:"bug, frontend, urgent"})]})]}),e.jsx("p",{className:"muted text-sm",style:{marginTop:8},children:"The agent and final priority are decided by Odin after you submit."})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx(A,{variant:"ghost",onClick:()=>s.close(),children:"Cancel"}),e.jsxs(A,{variant:"primary",type:"button",onClick:d=>p(d),children:[e.jsx(be,{size:14})," Create task"]})]})})}function el(s,t,a,i,n,o){let c=null,l=null,h=null,p=null;const x=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=((h==null?void 0:h.value)||"").split(",").map(N=>N.trim()).filter(Boolean);try{const N=await $.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(R=>R.id===a.id?N:R)),t.success("Task updated.",1200),await o()}catch(N){t.error(`Save failed: ${N.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:Pt.map(d=>e.jsx("option",{value:d,children:d},d))})]}),e.jsxs("label",{htmlFor:"edit-task-tags",className:"task-form-field",style:{flex:2},children:["Tags",e.jsx("input",{ref:d=>{h=d},id:"edit-task-tags",className:"input",type:"text",defaultValue:(a.tags||[]).join(", "),placeholder:"comma-separated"})]})]}),e.jsxs(Y,{children:[e.jsxs(ae,{children:[e.jsx(ha,{size:12})," Status"]}),e.jsxs(ne,{children:["Current: ",e.jsx("strong",{children:a.status}),a.workedBy&&e.jsxs(e.Fragment,{children:[" · Worked by @",a.workedBy]}),a.assignee&&!a.workedBy&&e.jsxs(e.Fragment,{children:[" · Assigned @",a.assignee]})]})]})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx(A,{variant:"ghost",onClick:()=>s.close(),children:"Cancel"}),e.jsxs(A,{variant:"primary",onClick:x,children:[e.jsx(xa,{size:14})," Save"]})]})})}const sl=Oe.memo(Xr);function tl(s){return $.urlWithToken(`/artifacts/${encodeURIComponent(s)}/content`)}function al(s,t){const a=tl(t);window.open(a,"_blank","noopener,noreferrer")}const Xt={"1m":60*1e3,"5m":5*60*1e3,"30m":30*60*1e3,"1h":60*60*1e3},Me=56,Ve=32,hs=22,nl=4,il=.9,lt={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 ot(s){return s&&lt[s]||lt.idle}function Us(s,t=24){return s?s.length<=t?s:s.slice(0,t-1)+"…":""}function Zs(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 ct(s){const t=s._timerStart;return typeof t=="number"&&t>0?t:Zs(s.createdAt)||Date.now()}function rl(s,t){return(s.status==="done"||s.status==="archived"||s.status==="failed"||s.status==="killed")&&(Zs(s.completedAt)||Zs(s.updatedAt))||t}function ll(s){return typeof s.startedAt=="number"&&s.startedAt>0?s.startedAt:Date.now()}function ol(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 cl(s){return s<=6e4?1e4:s<=3e5?3e4:s<=18e5?3e5:6e5}function dl(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 ml({snapshot:s,refreshSnapshot:t}){const a=re(),i=r.useRef(null),[n,o]=r.useState("live"),[c,l]=r.useState("5m"),[h,p]=r.useState(()=>typeof window>"u"?!0:window.innerWidth>900),[x,d]=r.useState([]),[m,u]=r.useState([]),[g,N]=r.useState(!0),[z,R]=r.useState(0),[b,w]=r.useState(Date.now()),[T,j]=r.useState(()=>Date.now()-Xt["5m"]*.1),[k,f]=r.useState({width:800,height:400}),[v,L]=r.useState(null),[S,y]=r.useState(""),[M,P]=r.useState([]),[C,D]=r.useState(""),[Q,O]=r.useState("normal"),[J,_]=r.useState(""),[q,F]=r.useState(""),[V,X]=r.useState(!1),[B,se]=r.useState(!1),[xe,Ce]=r.useState([]),H=Te(),te=s.agents||[],ie=s.tasks||[],me=Xt[c],W=T,E=T+me,ee=r.useCallback(async()=>{try{const[I,Z]=await Promise.all([$.get("/background").catch(()=>({instances:[]})),$.get("/activity?limit=200").catch(()=>({events:[]}))]);d(I.instances||[]),u(Z.events||[])}catch(I){console.warn("activity reload failed:",I)}finally{N(!1)}},[]);r.useEffect(()=>{ee();const I=setInterval(ee,3e3);return()=>clearInterval(I)},[ee]),r.useEffect(()=>{R(I=>I+1)},[ie.length,te.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;(b-T)/me>il&&j(b-me*.1)},[b,T,me,n]),r.useEffect(()=>{j(Date.now()-me*.1)},[c]),r.useEffect(()=>{n==="live"&&j(Date.now()-me*.1)},[n]),r.useLayoutEffect(()=>{const I=i.current;if(!I)return;const Z=new ResizeObserver(ge=>{for(const je of ge){const{width:ue,height:fe}=je.contentRect;f({width:Math.max(200,Math.floor(ue)),height:Math.max(120,Math.floor(fe))})}});return Z.observe(I),()=>Z.disconnect()},[]);const U=r.useMemo(()=>{const I=[];let Z=0;for(const ue of x){const fe=ll(ue),Ee=ol(ue,b);Ee<W||fe>E||I.push({kind:"bg",id:`bg:${ue.instanceId}`,index:Z++,label:`BG ${Us(ue.promptPreview,20)||ue.instanceId.slice(0,10)}`,sub:ue.status||"pending",start:fe,end:Ee,data:ue})}const ge=[...ie].sort((ue,fe)=>ct(ue)-ct(fe)),je=[];for(const ue of ge){const fe=ct(ue),Ee=rl(ue,b);if(Ee<W||fe>E)continue;let ds=-1;for(let ss=0;ss<je.length;ss++)if(je[ss]<=fe){je[ss]=Ee,ds=ss;break}ds===-1&&(je.push(Ee),ds=je.length-1),I.push({kind:"task",id:`task:${ue.id}`,index:Z+ds,label:Us(ue.title,32),sub:ue.status,start:fe,end:Ee,data:ue})}return I},[x,ie,b,W,E]),oe=r.useMemo(()=>{const I=new Map;for(const Z of U)I.set(Z.id,Z);return I},[U]),G=r.useCallback(I=>me<=0?0:(I-W)/me*k.width,[W,me,k.width]),de=r.useMemo(()=>{const I=cl(me),Z=[],ge=Math.floor(W/I)*I;for(let je=ge;je<=E+I;je+=I){if(je<W-I)continue;if(je>E)break;const ue=G(je);ue<-40||ue>k.width+40||Z.push({t:je,x:ue,label:dl(je,me)})}return Z},[W,E,me,k.width,G]),$e=r.useMemo(()=>{const I=[];for(const Z of U){if(Z.kind==="events")continue;const ge=Math.max(Z.start,W),je=Math.min(Z.end,E);if(je<W||ge>E)continue;const ue=G(ge),fe=G(je),Ee=Math.max(nl,fe-ue),ds=Ve+hs+Z.index*Me+8,ss=Me-16;let Ue="doing";if(Z.kind==="bg"){const ze=Z.data.status||"pending";ze==="done"||ze==="success"?Ue="done":ze==="failed"||ze==="killed"||ze==="error"?Ue="failed":ze==="queued"||ze==="pending"?Ue="queued":ze==="blocked"||ze==="stuck"?Ue="blocked":Ue="doing"}else{const ze=Z.data.status;ze==="done"||ze==="archived"?Ue="done":ze==="failed"||ze==="killed"?Ue="failed":ze==="queued"?Ue="queued":ze==="blocked"?Ue="blocked":Ue="doing"}const _a=(v==null?void 0:v.id)===Z.id;I.push({id:Z.id,laneIndex:Z.index,x:ue,y:ds,w:Ee,h:ss,label:Z.label,statusClass:Ue,selected:_a,data:Z.data,kind:Z.kind,start:Z.start,end:Z.end})}return I},[U,G,v,W,E]),Ie=r.useMemo(()=>{const I=[];for(const Z of m){const ge=Zs(Z.ts);if(ge<W-5e3||ge>E+5e3)continue;const je=G(ge);let ue=Ve+12;if(Z.taskId){const fe=oe.get(`task:${Z.taskId}`);fe&&(ue=Ve+hs+fe.index*Me+Me/2)}else if(Z.nodeId){const fe=String(Z.nodeId),Ee=oe.get(fe.startsWith("task:")||fe.startsWith("bg:")?fe:`task:${fe}`);Ee&&(ue=Ve+hs+Ee.index*Me+Me/2)}I.push({id:`${Z.ts}-${Z.kind}-${Z.author??""}-${Z.taskId??""}`,x:je,y:ue,kind:Z.kind||"event",ts:ge,text:String(Z.text||Z.kind||""),author:Z.author})}return I},[m,W,E,G,oe]),Be=r.useMemo(()=>U.map(I=>({id:I.id,y:Ve+hs+I.index*Me,h:Me})),[U]),He=r.useMemo(()=>{const I=G(b);return Math.max(0,Math.min(k.width,I))},[G,b,k.width]),Fs=r.useCallback(I=>{const ge={id:I.id,kind:I.kind,label:I.label,status:I.statusClass,data:I.data};L(ge)},[]);r.useEffect(()=>{if(!v){P([]),F(""),Ce([]);return}y(""),D(""),_(""),Ce([]),(async()=>{try{const I=await $.get(`/activity?nodeId=${encodeURIComponent(v.id)}&limit=50`);P(I.events||[])}catch{P([])}if(v.kind==="bg"){const I=v.data;try{const Z=await $.get(`/background/${encodeURIComponent(I.instanceId)}/output?lines=80`);F(Z.output||"")}catch{F("")}if(I.taskId)try{const Z=await $.get(`/tasks/${encodeURIComponent(I.taskId)}/artifacts`);Ce((Z.artifacts||[]).map(ge=>ge.id))}catch{Ce([])}}})()},[v]);const ws=async()=>{if(!(!v||!S.trim())){se(!0);try{await $.post("/comments",{nodeId:v.id,text:S,author:"user"}),y("");const I=await $.get(`/activity?nodeId=${encodeURIComponent(v.id)}&limit=50`);P(I.events||[]),a.success("Comment added.")}catch(I){a.error(`Comment failed: ${I.message}`)}finally{se(!1)}}},Os=async()=>{if(!(!v||!C.trim())){X(!0);try{await $.post(`/nodes/${encodeURIComponent(v.id)}/tasks`,{title:C,description:`Created from timeline selection ${v.id}.`,priority:Q}),D(""),a.success("Task created."),await t()}catch(I){a.error(`Task create failed: ${I.message}`)}finally{X(!1)}}},Ss=async()=>{if(!v||v.kind!=="bg"||!J.trim())return;const I=v.data;try{const Z=await $.post(`/background/${encodeURIComponent(I.instanceId)}/message`,{message:J});Z.ok?(a.success("Message sent."),_("")):a.warning(Z.error||"Send failed")}catch(Z){a.error(`Send failed: ${Z.message}`)}},Oa=async()=>{if(!v||v.kind!=="bg"||!confirm("Kill this bg instance session?"))return;const I=v.data;try{const Z=await $.del(`/background/${encodeURIComponent(I.instanceId)}`);Z.ok?a.success("Session killed."):a.warning(Z.error||"Kill failed"),await ee()}catch(Z){a.error(`Kill failed: ${Z.message}`)}},Ba=async()=>{if(!v||v.kind!=="bg")return;const I=v.data;try{const Z=await $.get(`/background/${encodeURIComponent(I.instanceId)}/output?lines=80`);F(Z.output||"")}catch{}};r.useEffect(()=>{const I=Z=>{Z.key==="Escape"&&L(null)};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[]);const Ua=()=>{R(I=>I+1),ee()},tt=Ve+hs+U.length*Me;return e.jsxs("div",{className:"view view-activity",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(De,{size:18})," Activity"]}),e.jsx("p",{className:"view-subtitle",children:"Live timeline of agents, tasks, and background sessions. Active tasks pulse; the red line marks “now”."})]}),e.jsx("div",{className:"view-actions",children:e.jsxs("div",{className:"tl-mode-toggle",children:[e.jsxs(A,{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(At,{size:14}):e.jsx(ks,{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:K("tl-zoom-btn",c===I&&"tl-zoom-btn-active"),onClick:()=>l(I),title:`Zoom to ${I}`,children:I},I))}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:Ua,title:"Refresh",children:[e.jsx(ce,{size:14})," Refresh"]})]})})]}),g&&e.jsx("div",{className:"view-loading",children:e.jsx(le,{size:"lg"})}),!g&&te.length===0&&ie.length===0&&x.length===0&&m.length===0?e.jsx(pe,{icon:e.jsx(De,{size:32}),title:"No activity yet",message:"Once agents, tasks, or background instances exist, they'll show up here on the timeline."}):e.jsx("div",{className:K("tl-view",v&&"tl-view-detail-open"),children:e.jsxs("div",{className:K("tl-body",!h&&"tl-body-stream-collapsed"),children:[e.jsxs("aside",{className:K("tl-stream",!h&&"tl-stream-collapsed"),children:[e.jsxs("div",{className:"tl-stream-head",children:[e.jsxs("h3",{children:[e.jsx(Is,{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(Nn,{size:14})})]}),e.jsx("div",{className:"tl-stream-list",children:m.length===0?e.jsx("div",{className:"tl-stream-empty",children:e.jsx("p",{children:"No events yet."})}):e.jsx(Dt,{items:[...m].reverse(),itemHeight:40,height:400,className:"tl-stream-virtual",renderItem:I=>{const Z=I.author?Ke:I.kind==="task"?Ms:I.kind==="bg"?Vs:De;return e.jsxs("div",{className:"tl-stream-event",children:[e.jsx("span",{className:"tl-stream-event-time",children:new Date(I.ts).toLocaleTimeString("en-GB",{hour12:!1})}),e.jsx("span",{className:"tl-stream-event-icon",style:{color:ot(I.kind)},children:e.jsx(Z,{size:12})}),e.jsx("span",{className:"tl-stream-event-text",children:I.author||I.text||I.kind})]})}})})]}),e.jsxs("div",{className:"tl-canvas-wrap",ref:i,children:[e.jsxs("div",{className:"tl-canvas-toolbar",children:[e.jsxs("div",{className:"tl-canvas-toolbar-left",children:[!h&&e.jsxs(A,{variant:"ghost",size:"sm",onClick:()=>p(!0),title:"Show event stream",children:[e.jsx(kn,{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(W).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(wn,{size:11})," agent"]}),e.jsxs("span",{className:"tl-legend-item",children:[e.jsx(Sn,{size:11})," task"]}),e.jsxs("span",{className:"tl-legend-item",children:[e.jsx(Vs,{size:11})," bg"]})]})]}),e.jsx("div",{className:"tl-canvas-scroll",children:e.jsxs("svg",{className:"tl-canvas",width:k.width,height:Math.max(k.height,tt),role:"application","aria-label":"Activity timeline",children:[e.jsx("defs",{children:e.jsx("pattern",{id:"tl-canvas-grid",width:k.width,height:Me,patternUnits:"userSpaceOnUse",children:e.jsx("path",{d:`M 0 0 L 0 ${Me}`,fill:"none",stroke:"var(--border)",strokeWidth:.5,opacity:.35})})}),e.jsx("rect",{width:"100%",height:"100%",fill:"url(#tl-canvas-grid)"}),Be.map(I=>e.jsx("rect",{className:"tl-lane-bg",x:0,y:I.y,width:k.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:de.map(I=>e.jsxs("g",{children:[e.jsx("line",{x1:I.x,y1:0,x2:I.x,y2:tt,stroke:"var(--border)",strokeWidth:.5,strokeDasharray:"2,4",opacity:.5}),e.jsx("text",{x:I.x+4,y:Ve-8,fontSize:10,fontFamily:"var(--font-mono)",fill:"var(--text-dim)",children:I.label})]},`tick-${I.t}`))}),U.map(I=>{const Z=Ve+hs+I.index*Me+Me/2;return e.jsxs("g",{className:"tl-lane-label-group",children:[e.jsx("text",{x:6,y:Z-2,className:"tl-lane-label",textAnchor:"start",children:Us(I.label,28)}),e.jsx("text",{x:6,y:Z+10,className:"tl-lane-label-sub",textAnchor:"start",children:I.sub})]},`label-${I.id}`)}),$e.map(I=>{const Z=ot(I.statusClass),ge=I.id===(v==null?void 0:v.id);return e.jsxs("g",{className:K("tl-task-bar",`tl-task-bar-${I.statusClass}`,ge&&"tl-task-bar-selected"),onClick:()=>Fs(I),children:[e.jsx("rect",{x:I.x,y:I.y,width:I.w,height:I.h,rx:6,fill:Z,fillOpacity:I.statusClass==="done"?.35:I.statusClass==="queued"?.18:.85,stroke:Z,strokeWidth:ge?2.5:1.5,strokeOpacity:I.statusClass==="done"?.5:1,strokeDasharray:I.statusClass==="queued"?"4 4":void 0,style:{cursor:"pointer"}}),I.w>36&&e.jsx("text",{x:I.x+8,y:I.y+I.h/2+4,fontSize:11,fontFamily:"var(--font-sans)",fontWeight:500,fill:"var(--text-strong)",style:{pointerEvents:"none"},opacity:I.statusClass==="done"?.7:1,children:Us(I.label,Math.max(4,Math.floor(I.w/7)))})]},`bar-${I.id}`)}),Ie.map(I=>{const Z=ot(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:Z,strokeWidth:1.2,opacity:.7}),e.jsx("circle",{cx:I.x,cy:I.y,r:4,fill:Z,opacity:.9,children:e.jsx("title",{children:`${I.kind}${I.author?` · ${I.author}`:""} · ${new Date(I.ts).toLocaleTimeString("en-GB",{hour12:!1})}`})})]},`ev-${I.id}`)}),e.jsx("line",{className:"tl-now-line",x1:He,y1:0,x2:He,y2:tt,stroke:"var(--error)",strokeWidth:1.5,opacity:.9}),e.jsxs("g",{className:"tl-now-marker",children:[e.jsx("circle",{cx:He,cy:Ve-4,r:4,fill:"var(--error)"}),e.jsx("text",{x:He+6,y:Ve-4,fontSize:10,fontWeight:700,fill:"var(--error)",fontFamily:"var(--font-mono)",children:"now"})]})]})})]}),v&&e.jsx("aside",{className:"tl-detail tl-detail-enter",children:e.jsxs(Y,{children:[e.jsxs(ae,{children:[v.kind==="agent"&&e.jsx(Ke,{size:14}),v.kind==="task"&&e.jsx(Ms,{size:14}),v.kind==="bg"&&e.jsx(Vs,{size:14}),v.label,e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>L(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"})," ",v.kind]}),e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"status"})," ",e.jsx("code",{children:v.status})]}),v.kind==="agent"&&(()=>{const I=v.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]})]})})(),v.kind==="task"&&(()=>{const I=v.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()]})]})})(),v.kind==="bg"&&(()=>{const I=v.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"})]})]})})()]}),v.kind==="task"&&v.data.description&&e.jsx("div",{className:"tl-detail-desc",children:v.data.description}),v.kind==="bg"&&v.data.promptPreview&&e.jsx("div",{className:"tl-detail-desc",children:v.data.promptPreview}),v.kind==="bg"&&e.jsxs("div",{className:"tl-detail-bg",children:[e.jsx("pre",{className:"tl-bg-output",children:q||"(no output — start the session via tmux attach)"}),e.jsxs("div",{className:"tl-bg-output-actions",children:[e.jsxs(A,{variant:"ghost",size:"sm",onClick:Ba,children:[e.jsx(ce,{size:12})," Refresh output"]}),xe.length>0&&e.jsxs(A,{variant:"secondary",size:"sm",onClick:()=>al(H,xe[0]),children:[e.jsx(we,{size:12})," Open artifact"]}),e.jsxs(A,{variant:"danger",size:"sm",onClick:Oa,children:[e.jsx(Se,{size:12})," Kill session"]})]}),e.jsxs("div",{className:"tl-form-row",children:[e.jsx("label",{htmlFor:"bg-message-input",className:"sr-only",children:"Send a message to this bg session"}),e.jsx("input",{id:"bg-message-input",className:"input",placeholder:"Send a message to this bg session…",value:J,onChange:I=>_(I.target.value),onKeyDown:I=>{I.key==="Enter"&&Ss()},"aria-label":"Send a message to this bg session"}),e.jsxs(A,{variant:"primary",size:"sm",disabled:!J.trim(),onClick:Ss,children:[e.jsx(es,{size:12})," Send"]})]})]}),v.kind!=="bg"&&e.jsxs("div",{className:"tl-detail-create",children:[e.jsx("label",{className:"field-label",htmlFor:"followup-task-title",children:"Create follow-up task"}),e.jsx("input",{id:"followup-task-title",className:"input",placeholder:"Task title",value:C,onChange:I=>D(I.target.value)}),e.jsxs("div",{className:"tl-form-row",children:[e.jsx("label",{htmlFor:"followup-task-priority",className:"sr-only",children:"Task priority"}),e.jsxs("select",{id:"followup-task-priority",className:"select",value:Q,onChange:I=>O(I.target.value),"aria-label":"Task priority",children:[e.jsx("option",{value:"low",children:"Low"}),e.jsx("option",{value:"normal",children:"Normal"}),e.jsx("option",{value:"high",children:"High"})]}),e.jsxs(A,{variant:"primary",size:"sm",disabled:!C.trim()||V,onClick:Os,children:[e.jsx(be,{size:12})," Add task"]})]})]}),e.jsxs("div",{className:"tl-detail-comments",children:[e.jsxs("div",{className:"field-label",children:[e.jsx(et,{size:12})," Comments & activity"]}),e.jsxs("ul",{className:"comment-list",children:[M.length===0&&e.jsx("li",{className:"muted",children:"No comments yet."}),M.map((I,Z)=>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-${Z}`))]}),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:S,onChange:I=>y(I.target.value),onKeyDown:I=>{I.key==="Enter"&&!I.shiftKey&&ws()},"aria-label":"Add a comment"}),e.jsxs(A,{variant:"secondary",size:"sm",disabled:!S.trim()||B,onClick:ws,children:[e.jsx(es,{size:12})," Post"]})]})]})]})},v.id)]})})]})}function ul(s,t){const a=s.length,i=t.length,n=Array.from({length:i+1},()=>Array(a+1).fill(0));for(let o=0;o<=a;o++)n[0][o]=o;for(let o=0;o<=i;o++)n[o][0]=o;for(let o=1;o<=i;o++)for(let c=1;c<=a;c++){const l=s[c-1]===t[o-1]?0:1;n[o][c]=Math.min(n[o][c-1]+1,n[o-1][c]+1,n[o-1][c-1]+l)}return n[i][a]}function dt(s,t){if(t===s)return 100;if(t.startsWith(s))return 90;const a=t.split(/\s+/);for(const o of a)if(o.startsWith(s))return 80;const i=Math.min(s.length,t.length);return ul(s,t.substring(0,i))<=2?40:t.includes(s)?30:0}function hl(s,t){const a=s.toLowerCase().trim();return a?t.map(i=>{const n=dt(a,i.label.toLowerCase()),o=i.value?dt(a,String(i.value).toLowerCase()):0,c=i.description?dt(a,i.description.toLowerCase()):0,l=Math.max(n,o,c);if(l===0)return null;const h=n>=o&&n>=c?"label":o>=n&&o>=c?"value":"description",p=h==="label"?i.label:h==="value"?String(i.value):i.description;return{...i,score:l,matchedField:h,matchedTerm:p}}).filter(i=>i!==null).sort((i,n)=>n.score-i.score):[]}const Ft="bizar_settings_recent";function $a(){try{const s=localStorage.getItem(Ft);return s?JSON.parse(s):[]}catch{return[]}}function xl(s){if(s)try{const t=$a().filter(a=>a!==s);t.unshift(s),localStorage.setItem(Ft,JSON.stringify(t.slice(0,5)))}catch{}}function pl(s,t){if(!t)return s;const a=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`(${a})`,"gi");return s.split(i).map((o,c)=>i.test(o)?e.jsx("mark",{children:o},c):e.jsx("span",{children:o},c))}function gl(s){const t=[];for(const a of s){t.push({key:a.id,label:a.label,section:a.id,description:`${a.fields.length} field${a.fields.length===1?"":"s"}`});for(const i of a.fields)t.push({key:i.key,label:i.label,section:a.id,value:i.value})}return t}function jl({sections:s,onJump:t}){const[a,i]=r.useState(""),[n,o]=r.useState([]),[c,l]=r.useState(0),[h,p]=r.useState(null),[x,d]=r.useState(!1),m=r.useRef(null),u=r.useRef(null),g=r.useRef(null),N=r.useRef([]);r.useEffect(()=>{N.current=gl(s)},[s]);const z=r.useCallback((S,y=!1)=>{if(u.current&&clearTimeout(u.current),!S.trim()){o([]),l(0);return}const M=()=>{const P=hl(S,N.current);o(P),l(0)};y?M():u.current=setTimeout(M,150)},[]);r.useEffect(()=>{z(a)},[a,z]),r.useEffect(()=>()=>{u.current&&clearTimeout(u.current),g.current&&clearTimeout(g.current)},[]);const R=(S,y)=>{const M=document.querySelector(`[data-section="${S}"] [data-setting-id="${y}"]`);M&&(M.scrollIntoView({behavior:"smooth",block:"center"}),M.classList.add("setting-flash"),setTimeout(()=>M.classList.remove("setting-flash"),2e3));const P=document.querySelector(`[data-section="${S}"]`);P&&P.scrollIntoView({behavior:"smooth",block:M?"nearest":"start"})},b=S=>{p(S),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>p(null),1500);const y=document.querySelector(`[data-section="${S}"]`);y&&y.scrollIntoView({behavior:"smooth",block:"start"})},w=S=>{var y;xl(a),S.key===S.section?(b(S.section),t(S.section)):(b(S.section),t(S.section,S.key),R(S.section,S.key)),i(""),(y=m.current)==null||y.blur()},T=S=>{var y;S.key==="Escape"?(i(""),(y=m.current)==null||y.blur()):S.key==="ArrowDown"?(S.preventDefault(),l(M=>Math.min(M+1,n.length-1))):S.key==="ArrowUp"?(S.preventDefault(),l(M=>Math.max(M-1,0))):S.key==="Enter"&&(S.preventDefault(),n.length===0&&a.trim()&&z(a,!0),n[c]&&w(n[c]))},j=S=>{w(S)},k=$a(),f=S=>{var y;i(S),(y=m.current)==null||y.focus()},v=()=>{try{localStorage.removeItem(Ft)}catch{}d(S=>S)},L=x&&!a.trim()&&k.length>0;return e.jsxs("div",{className:"settings-search",children:[e.jsxs("div",{className:"settings-search-input-wrap",children:[e.jsx(ye,{size:13,className:"settings-search-icon"}),e.jsx("input",{ref:m,className:"settings-search-input",placeholder:"Search settings…",value:a,onChange:S=>i(S.target.value),onKeyDown:T,onFocus:()=>d(!0),onBlur:()=>setTimeout(()=>d(!1),150),"aria-label":"Search settings"}),a&&e.jsx("button",{type:"button",className:"icon-btn settings-search-clear",onClick:()=>i(""),"aria-label":"Clear search",children:e.jsx(Ne,{size:12})})]}),L&&e.jsxs("div",{className:"settings-search-recent",children:[e.jsxs("div",{className:"settings-search-recent-header",children:[e.jsx("span",{className:"settings-search-recent-label",children:"Recent"}),e.jsx("button",{type:"button",className:"settings-search-recent-clear",onClick:v,tabIndex:-1,children:"Clear"})]}),k.map(S=>e.jsxs("button",{type:"button",className:"settings-search-recent-item",onMouseDown:y=>{y.preventDefault(),f(S)},children:[e.jsx(ye,{size:11}),e.jsx("span",{children:S})]},S))]}),a&&n.length>0&&e.jsx("div",{className:"settings-search-results",children:n.map((S,y)=>e.jsxs("button",{type:"button",className:K("settings-search-result",y===c&&"settings-search-result-active"),onClick:()=>j(S),onMouseEnter:()=>l(y),children:[e.jsx("span",{className:K("settings-search-result-type",S.key===S.section&&"settings-search-result-type-section"),children:S.key===S.section?"section":"field"}),e.jsx("span",{className:"settings-search-result-label",children:pl(S.label,a)}),S.key!==S.section&&e.jsx("span",{className:"settings-search-result-key mono muted",children:S.key})]},`${S.section}::${S.key}`))}),a&&n.length===0&&e.jsx("div",{className:"settings-search-empty muted",children:"No matching settings."})]})}const fl=[{id:"dark",label:"Dark",Icon:Cn},{id:"light",label:"Light",Icon:zn},{id:"system",label:"System",Icon:Rn}],vl=[{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"}],yl=["Inter","system-ui","Segoe UI","Roboto","JetBrains Mono","SF Mono","Cascadia Code"];function bl({settings:s,patchTheme:t,patchUi:a}){return e.jsxs(Y,{id:"settings-theme","data-section":"theme",children:[e.jsxs(ae,{children:[e.jsx(ma,{size:14})," Theme"]}),e.jsx(ne,{children:"Mode, accent, and colors. Live preview as you tweak."}),e.jsxs("div",{className:"field","data-setting-id":"theme.presets",children:[e.jsx("label",{className:"field-label",children:"Accent presets"}),e.jsx("div",{className:"theme-presets",children:vl.map(i=>e.jsxs("button",{type:"button",className:K("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:fl.map(({id:i,label:n,Icon:o})=>{const c=s.theme.mode===i;return e.jsxs("button",{type:"button",className:K("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:K("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:yl.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 Nl({tailscale:s,tailscaleDraft:t,setTailscaleDraft:a,onTailscaleToggle:i}){return e.jsxs(e.Fragment,{children:[e.jsxs(Y,{id:"settings-service","data-section":"service",children:[e.jsxs(ae,{children:[e.jsx(ys,{size:14})," Service"]}),e.jsx(ne,{children:"Background daemon that runs schedules."}),e.jsx("div",{"data-setting-id":"service.enabled",children:s?e.jsxs("div",{className:"service-card",children:[e.jsxs("p",{children:["Status: ",e.jsx("strong",{children:s.settings.enabled?"enabled":"disabled"})," ","· Tailscale installed: ",e.jsx("strong",{children:s.installed?"yes":"no"})," ","· authenticated: ",e.jsx("strong",{children:s.authenticated?"yes":"no"})]}),e.jsxs("p",{className:"muted",children:["Use ",e.jsx("code",{children:"bizar service start"})," / ",e.jsx("code",{children:"bizar service stop"})," in your terminal to control the daemon."]})]}):e.jsx("p",{className:"muted",children:"Loading service status…"})})]}),e.jsxs(Y,{id:"settings-tailscale","data-section":"tailscale",children:[e.jsxs(ae,{children:[e.jsx(ft,{size:14})," Tailscale serve"]}),e.jsx(ne,{children:"Expose the dashboard over your Tailscale network."}),s?e.jsxs(e.Fragment,{children:[e.jsxs("p",{children:["Installed: ",e.jsx("strong",{children:s.installed?"yes":"no"})," ",s.version&&e.jsxs("span",{className:"muted",children:["(",s.version,")"]})]}),e.jsxs("p",{children:["Authenticated: ",e.jsx("strong",{children:s.authenticated?"yes":"no"})]}),e.jsxs("p",{children:["Serve enabled: ",e.jsx("strong",{children:s.settings.enabled?"yes":"no"})]}),e.jsxs("div",{className:"task-form-row",children:[e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",children:"Port"}),e.jsx("input",{type:"number",className:"input",value:t.port,onChange:n=>a(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(A,{variant:"primary",onClick:i,children:s.settings.enabled?"Disable serve":"Enable serve"})]}):e.jsx("p",{className:"muted",children:"Loading Tailscale status…"})]})]})}function kl({settings:s,patchNotifications:t}){return e.jsxs(Y,{id:"settings-notifications","data-section":"notifications",children:[e.jsx(ae,{children:"Notifications"}),e.jsx(ne,{children:"Toast triggers inside the dashboard."}),e.jsxs("label",{className:"checkbox-row","data-setting-id":"notifications.onAgentComplete",children:[e.jsx("input",{type:"checkbox",checked:!!s.notifications.onAgentComplete,onChange:a=>t({onAgentComplete:a.target.checked})}),e.jsx("span",{children:"Notify when an agent invocation completes"})]}),e.jsxs("label",{className:"checkbox-row","data-setting-id":"notifications.onPlanApproval",children:[e.jsx("input",{type:"checkbox",checked:!!s.notifications.onPlanApproval,onChange:a=>t({onPlanApproval:a.target.checked})}),e.jsx("span",{children:"Notify when a plan needs approval"})]})]})}function wl({authStatus:s,setAuthStatus:t}){const a=re(),[i,n]=r.useState($.getToken()),[o,c]=r.useState("");r.useEffect(()=>{let x=!1;return(async()=>{try{const d=await $.probeAuthStatus();x||t(d)}catch{x||t({required:!0,loopback:!1,peer:""})}})(),()=>{x=!0}},[]);const l=async()=>{try{const x=await $.get("/auth/reveal");c(x.token),n(x.token),$.setToken(x.token);try{await navigator.clipboard.writeText(x.token),a.success("Token copied to clipboard.")}catch{a.success("Token revealed — copy from the field below.")}}catch(x){a.error(`Reveal failed: ${x.message}`)}},h=async()=>{if(confirm("Regenerate the auth token? Anything still using the old token will start getting 401 errors immediately."))try{const x=await $.post("/auth/regenerate");c(x.token),n(x.token),$.setToken(x.token);try{await navigator.clipboard.writeText(x.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(x){a.error(`Regenerate failed: ${x.message}`)}},p=()=>{$.setToken(i.trim()),a.success("Token saved. The dashboard will use it on the next request.")};return e.jsxs(Y,{id:"settings-auth","data-section":"auth",children:[e.jsxs(ae,{children:[e.jsx(Mt,{size:14})," Authentication"]}),e.jsx(ne,{children:"Localhost and Tailscale browser access are auto-trusted via loopback. A bearer token is still available for non-loopback clients and forced-auth mode."}),e.jsxs("div",{className:"field","data-setting-id":"auth.status",children:[e.jsx("label",{className:"field-label",children:"Server status"}),e.jsxs("p",{style:{margin:"4px 0"},children:["Auth required:"," ",e.jsx("strong",{children:s?s.required?"yes":"no":"probing…"})]}),e.jsxs("p",{style:{margin:"4px 0"},children:["Connection:"," ",e.jsx("strong",{children:s?s.loopback?"loopback (auto-trusted)":"remote":"probing…"})]}),e.jsxs("p",{style:{margin:"4px 0"},children:["Peer address:"," ",s!=null&&s.peer?e.jsx("code",{children:s.peer}):e.jsx("span",{className:"muted",children:"probing…"})]}),e.jsxs("p",{className:"muted",style:{fontSize:12,margin:"4px 0"},children:["Localhost and Tailscale browser access are auto-trusted because the dashboard sees a loopback peer. Paste a token only for non-loopback API clients/scripts, or if you force auth for every connection with"," ",e.jsx("code",{children:"BIZAR_DASHBOARD_REQUIRE_AUTH=1"}),"."]}),e.jsxs("p",{className:"muted",style:{fontSize:12,margin:"4px 0"},children:["Dashboard tokens are generated on first boot and saved to"," ",e.jsx("code",{children:"~/.config/bizar/dashboard-secret"})," (mode 0600)."]}),e.jsx("p",{className:"muted",style:{fontSize:12,margin:"4px 0"},children:"For Tailscale Serve or any reverse-proxy access, paste this token once via the boot screen — it is saved per-origin and works for all subsequent visits."})]}),e.jsxs("div",{className:"field","data-setting-id":"auth.token",children:[e.jsx("label",{className:"field-label",children:"Token (this browser)"}),e.jsx("input",{type:"password",className:"input mono",value:i,onChange:x=>n(x.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(A,{variant:"secondary",size:"sm",onClick:p,children:[e.jsx(It,{size:14})," Save token"]}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:l,children:[e.jsx(os,{size:14})," Reveal & copy server token"]}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:h,children:[e.jsx(pa,{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 Sl({settings:s,patchAgents:t,patchDashboard:a,autoSave:i}){var p,x,d,m;const n=re(),[o,c]=r.useState({});r.useEffect(()=>{$.get("/settings/plugin-options").then(c).catch(()=>{})},[]);const l=async()=>{try{await $.put("/settings/plugin-options",o),n.success("Saved — restart opencode for changes to take effect.")}catch(u){n.error(`Save failed: ${u.message}`)}},h=async()=>{try{const g=await(await fetch("/api/background/cleanup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({maxAgeDays:7})})).json();n.success(`Cleaned up ${g.deleted} old instances.`)}catch(u){n.error(`Cleanup failed: ${u.message}`)}};return e.jsxs(e.Fragment,{children:[e.jsxs(Y,{id:"settings-agents","data-section":"agents",children:[e.jsxs(ae,{children:[e.jsx(ys,{size:14})," Agent Behavior"]}),e.jsx(ne,{children:"Limits and timeouts for background agent dispatch."}),e.jsxs("div",{className:"form-row",children:[e.jsxs("label",{htmlFor:"agents-maxParallel",children:["Max parallel agents",e.jsx("span",{className:"meta-badge",children:"default: 6"})]}),e.jsx("input",{id:"agents-maxParallel",type:"number",min:1,max:20,value:((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:((x=s.agents)==null?void 0:x.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(Y,{id:"settings-dashboard","data-section":"dashboard",children:[e.jsxs(ae,{children:[e.jsx(cs,{size:14})," Dashboard"]}),e.jsxs(ne,{children:["Controls how ",e.jsx("code",{children:"bizar"})," starts up."]}),e.jsxs("label",{className:"checkbox-row","data-setting-id":"dashboard.autoLaunchWeb",children:[e.jsx("input",{type:"checkbox",checked:s.dashboard.autoLaunchWeb!==!1,onChange: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(Kn,{initialValue:(s.dashboard.allowedRoots??[]).join(`
6
+ `),delay:1500,saveFn:async u=>{const g=u.split(`
7
+ `).map(N=>N.trim()).filter(Boolean);a({allowedRoots:g}),i==null||i("dashboard",{allowedRoots:g})},render:({value:u,onChange:g,onBlur:N})=>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:N})},(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((N,z)=>{N.trim()&&(/^\/|^[A-Za-z]:/.test(N)||g.push({key:`noabs-${z}`,msg:e.jsxs("p",{style:{color:"var(--warning)",fontSize:11,marginTop:2},children:["Line ",z+1,': "',N,'" — should be absolute (start with / or a drive letter).']})}),N.includes("..")&&g.push({key:`dots-${z}`,msg:e.jsxs("p",{style:{color:"var(--error)",fontSize:11,marginTop:2},children:["Line ",z+1,': "',N,`" — contains '..' (server will reject this).`]})}))}),g.map(N=>N.msg)})()]})]}),e.jsxs(Y,{id:"settings-background","data-section":"background",children:[e.jsxs(ae,{children:[e.jsx(ys,{size:14})," Background Agents"]}),e.jsx(ne,{children:"Tune plugin options. Changes take effect on next plugin restart."}),e.jsxs("div",{className:"form-row",children:[e.jsxs("label",{htmlFor:"bg-maxConcurrent",children:["Max concurrent instances",e.jsx("span",{className:"meta-badge",children:"default: 8"})]}),e.jsx("input",{id:"bg-maxConcurrent",type:"number",min:1,max:32,value: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(A,{variant:"secondary",size:"sm",onClick:l,children:[e.jsx(bs,{size:14})," Save plugin options"]}),e.jsx(A,{variant:"secondary",size:"sm",onClick:h,children:"Cleanup old instances (>7 days)"})]}),e.jsx("div",{className:"form-row",children:e.jsxs("small",{children:["Plugin options are read at startup. Save changes and run ",e.jsx("code",{children:"bizar update"})," to apply."]})})]})]})}function Cl({workspaceId:s,onInviteCreated:t}){const a=Te(),[i,n]=r.useState(""),[o,c]=r.useState("editor"),[l,h]=r.useState([]),[p,x]=r.useState(!1),[d,m]=r.useState(!1),[u,g]=r.useState(null),[N,z]=r.useState(null);r.useEffect(()=>{R()},[s]);async function R(){x(!0);try{const k=await $.get(`/workspaces/${s}/invites`);h(k.invites||[])}catch{}finally{x(!1)}}async function b(k){if(k.preventDefault(),!!i.trim()){m(!0),z(null);try{const f=await $.post(`/workspaces/${s}/invites`,{email:i.trim(),role:o});n(""),await R(),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($n,{size:14}),e.jsx("input",{type:"text",readOnly:!0,value:f.url,onClick:v=>v.target.select()}),e.jsx("button",{type:"button",className:"invite-copy-btn",onClick:()=>{navigator.clipboard.writeText(f.url).catch(()=>{}),g(f.token),setTimeout(()=>g(null),2e3)},children:u===f.token?e.jsx(fs,{size:14}):e.jsx(os,{size:14})})]}),e.jsx("p",{className:"invite-url-note",children:"This link expires in 7 days."})]}),footer:e.jsx(A,{variant:"primary",size:"sm",onClick:()=>a.close(),children:"Done"})})}catch(f){z(f.message||"Failed to create invite")}finally{m(!1)}}}async function w(k){if(confirm("Revoke this invite?"))try{await $.del(`/workspaces/${s}/invites/${k}`),await R()}catch(f){z(f.message||"Failed to revoke invite")}}function T(k,f){navigator.clipboard.writeText(k).catch(()=>{}),g(f),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:b,children:[e.jsxs("div",{className:"invite-form-row",children:[e.jsxs("div",{className:"invite-form-field",children:[e.jsx("label",{htmlFor:"invite-email",children:"Email address"}),e.jsx("input",{id:"invite-email",type:"email",value:i,onChange:k=>n(k.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:k=>c(k.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(A,{type:"submit",variant:"primary",size:"sm",loading:d,disabled:!i.trim(),children:[e.jsx(Tn,{size:13}),"Invite"]})]}),N&&e.jsx("p",{className:"invite-error",children:N})]}),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(k=>e.jsxs("div",{className:"invite-item",children:[e.jsxs("div",{className:"invite-item-info",children:[e.jsx("span",{className:"invite-item-email",children:k.email}),e.jsx("span",{className:K("invite-item-role",j[k.role]),children:k.role})]}),e.jsxs("div",{className:"invite-item-actions",children:[e.jsx("button",{type:"button",className:"invite-action-btn",title:"Copy invite link",onClick:()=>{const f=`${window.location.origin}/accept-invite?token=${k.token}`;T(f,k.token)},children:u===k.token?e.jsx(fs,{size:13}):e.jsx(os,{size:13})}),e.jsx("button",{type:"button",className:"invite-action-btn invite-action-revoke",title:"Revoke invite",onClick:()=>w(k.token),children:e.jsx(Se,{size:13})})]})]},k.token))]})]})}const zl={admin:An,editor:Mt,viewer:vs},Rl={admin:"role-admin",editor:"role-editor",viewer:"role-viewer"};function Tl(){const[s,t]=r.useState([]),[a,i]=r.useState(!0),[n,o]=r.useState(!1),[c,l]=r.useState(""),[h,p]=r.useState(null),[x,d]=r.useState(null),m=Te();r.useEffect(()=>{u()},[]);async function u(){i(!0);try{const R=await $.get("/workspaces");t(R.workspaces||[])}catch{p("Failed to load workspaces")}finally{i(!1)}}async function g(R){if(R.preventDefault(),!!c.trim()){o(!0);try{await $.post("/workspaces",{name:c.trim()}),l(""),await u()}catch(b){p(b.message||"Failed to create workspace")}finally{o(!1)}}}async function N(R,b){if(confirm(`Delete workspace "${b}"?`)&&confirm("This cannot be undone."))try{await $.del(`/workspaces/${R}`),await u()}catch(w){p(w.message||"Failed to delete workspace")}}function z(R){navigator.clipboard.writeText(`${window.location.origin}/accept-invite?workspace=${R}`).catch(()=>{}),d(R),setTimeout(()=>d(null),2e3)}return a?e.jsx("div",{className:"settings-section-loading",children:"Loading workspaces..."}):e.jsxs("div",{className:"settings-section settings-section-workspaces",children:[e.jsx("h3",{className:"settings-section-title",children:"Workspaces"}),e.jsx("p",{className:"settings-section-desc",children:"Workspaces let you share access with team members. Each workspace has its own members, settings, and data."}),h&&e.jsxs("div",{className:"settings-section-error",children:[e.jsx("span",{children:h}),e.jsx("button",{onClick:()=>p(null),children:"×"})]}),e.jsxs("form",{className:"workspace-create-form",onSubmit:g,children:[e.jsx("input",{type:"text",placeholder:"New workspace name",value:c,onChange:R=>l(R.target.value),maxLength:64}),e.jsxs(A,{type:"submit",variant:"primary",size:"sm",loading:n,disabled:!c.trim(),children:[e.jsx(be,{size:13}),"Create"]})]}),e.jsxs("div",{className:"workspace-list",children:[s.length===0&&e.jsx("p",{className:"workspace-list-empty",children:"No workspaces yet. Create one above."}),s.map(({workspace:R,role:b})=>{const w=zl[b]||vs;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(Js,{size:16})}),e.jsxs("div",{className:"workspace-item-details",children:[e.jsx("span",{className:"workspace-item-name",children:R.name}),e.jsxs("span",{className:K("workspace-item-role",Rl[b]),children:[e.jsx(w,{size:11}),b]})]})]}),e.jsxs("div",{className:"workspace-item-actions",children:[e.jsx(A,{variant:"ghost",size:"sm",iconOnly:!0,title:"Copy invite link",onClick:()=>z(R.id),children:x===R.id?e.jsx(fs,{size:13}):e.jsx(os,{size:13})}),b==="admin"&&e.jsx(A,{variant:"ghost",size:"sm",iconOnly:!0,title:"Manage members",onClick:()=>{m.open({title:`Manage "${R.name}"`,children:e.jsx(Cl,{workspaceId:R.id,onInviteCreated:()=>u()}),width:520})},children:e.jsx(Js,{size:13})}),b==="admin"&&s.length>1&&e.jsx(A,{variant:"ghost",size:"sm",iconOnly:!0,title:"Delete workspace",onClick:()=>N(R.id,R.name),children:e.jsx(Se,{size:13})})]})]},R.id)})]})]})}const $l=[{id:"theme",label:"Theme"},{id:"updates",label:"Updates"},{id:"layout",label:"Layout"},{id:"general",label:"General"},{id:"env-vars",label:"Env Vars"},{id:"network",label:"Network"},{id:"notifications",label:"Notifications"},{id:"auth",label:"Auth"},{id:"agents",label:"Agents"},{id:"dashboard",label:"Dashboard"},{id:"background",label:"Background"},{id:"system-llm",label:"System LLM"},{id:"headroom",label:"Headroom"},{id:"activity-log",label:"Activity"},{id:"about",label:"About"},{id:"workspaces",label:"Workspaces"}],Al=[{id:"theme",label:"Theme",fields:[{key:"theme.presets",label:"Accent presets",section:"theme"},{key:"theme.accent",label:"Accent color",section:"theme"},{key:"theme.success",label:"Success color",section:"theme"},{key:"theme.warning",label:"Warning color",section:"theme"},{key:"theme.error",label:"Error color",section:"theme"},{key:"theme.info",label:"Info color",section:"theme"},{key:"theme.fontFamily",label:"Font family",section:"theme"},{key:"theme.fontSize",label:"Font size",section:"theme"},{key:"theme.compactMode",label:"Compact mode",section:"theme"},{key:"theme.animations",label:"Animations",section:"theme"}]},{id:"updates",label:"Updates",fields:[{key:"updates.channel",label:"Update channel",section:"updates"}]},{id:"layout",label:"Layout",fields:[{key:"ui.layout",label:"UI layout",section:"layout"},{key:"ui.showHeader",label:"Show header",section:"layout"},{key:"ui.showStatusBar",label:"Show status bar",section:"layout"},{key:"ui.defaultTab",label:"Default tab",section:"layout"}]},{id:"general",label:"General",fields:[{key:"defaultAgent",label:"Default agent",section:"general"},{key:"defaultModel",label:"Model override",section:"general"}]},{id:"env-vars",label:"Environment Variables",fields:[{key:"env-vars.count",label:"Env var count",section:"env-vars"}]},{id:"network",label:"Network",fields:[{key:"tailscale.enabled",label:"Tailscale Serve",section:"network"},{key:"tailscale.port",label:"Tailscale port",section:"network"},{key:"tailscale.https",label:"Tailscale HTTPS",section:"network"},{key:"tailscale.hostname",label:"Tailscale hostname",section:"network"}]},{id:"notifications",label:"Notifications",fields:[{key:"notifications.onAgentComplete",label:"Notify on agent complete",section:"notifications"},{key:"notifications.onPlanApproval",label:"Notify on plan approval",section:"notifications"}]},{id:"auth",label:"Auth",fields:[{key:"auth.enabled",label:"Auth enabled",section:"auth"},{key:"auth.loopback",label:"Loopback mode",section:"auth"},{key:"auth.token",label:"Auth token",section:"auth"}]},{id:"agents",label:"Agents",fields:[{key:"agents.maxParallel",label:"Max parallel agents",section:"agents"},{key:"agents.stuckThresholdMs",label:"Stuck threshold",section:"agents"},{key:"agents.autoRestart",label:"Auto restart",section:"agents"},{key:"workflow.artifactsEnabled",label:"Artifacts enabled",section:"agents"},{key:"workflow.agentsDecideAutonomously",label:"Autonomous decisions",section:"agents"}]},{id:"dashboard",label:"Dashboard",fields:[{key:"dashboard.autoLaunchWeb",label:"Auto-launch web",section:"dashboard"},{key:"dashboard.projectsDirectory",label:"Projects directory",section:"dashboard"},{key:"dashboard.allowedRoots",label:"Allowed roots",section:"dashboard"}]},{id:"background",label:"Background",fields:[{key:"service.enabled",label:"Background service",section:"background"},{key:"service.autostart",label:"Auto-start service",section:"background"}]},{id:"system-llm",label:"System LLM",fields:[{key:"systemLlm.enabled",label:"System LLM enabled",section:"system-llm"}]},{id:"headroom",label:"Headroom",fields:[{key:"headroom.enabled",label:"Headroom enabled",section:"headroom"},{key:"headroom.port",label:"Headroom port",section:"headroom"},{key:"headroom.budget",label:"Headroom budget",section:"headroom"},{key:"headroom.backend",label:"Headroom backend",section:"headroom"}]},{id:"activity-log",label:"Activity",fields:[{key:"activity.log",label:"Activity log",section:"activity-log"}]},{id:"about",label:"About",fields:[{key:"about.version",label:"Version",section:"about"},{key:"about.homepage",label:"Homepage",section:"about"},{key:"about.license",label:"License",section:"about"}]}];function Ml({settings:s,refreshSnapshot:t,settingsMode:a,settingsActiveSection:i,setSettingsActiveSection:n,setActiveTab:o}){const c=re(),[l,h]=r.useState(s),[p,x]=r.useState(!1),[d,m]=r.useState(!1),[u,g]=r.useState(null),[N,z]=r.useState({port:4321,https:!0,hostname:""}),[R,b]=r.useState(null),w=()=>{o("overview")};r.useEffect(()=>{h(s),x(!1),s.theme&&ps(s.theme)},[s]),r.useEffect(()=>{u&&z({port:u.settings.port,https:u.settings.https!==!1,hostname:u.settings.hostname||""})},[u]),r.useEffect(()=>{$.get("/tailscale/status").then(g).catch(()=>{})},[]);const T=r.useRef(null),j=r.useCallback(async(B,se)=>{h(xe=>({...xe,[B]:se})),T.current&&clearTimeout(T.current),T.current=setTimeout(async()=>{try{await $.put("/settings",{...l,[B]:se})}catch(xe){console.error("autoSave failed",xe)}},300)},[l]);r.useEffect(()=>()=>{T.current&&clearTimeout(T.current)},[]);const k=B=>{h(se=>{const xe={...se,theme:{...se.theme,...B}};return ps(xe.theme),xe}),x(!0)},f=B=>{h(se=>({...se,ui:{...se.ui,...B}})),x(!0)},v=(B,se)=>{h(xe=>({...xe,[B]:se})),x(!0)},L=B=>{h(se=>({...se,notifications:{...se.notifications,...B}})),x(!0)},S=B=>{h(se=>({...se,agents:{...se.agents,...B}})),x(!0)},y=B=>{h(se=>({...se,dashboard:{...se.dashboard,...B}})),x(!0)},[M,P]=r.useState(()=>{if(typeof window>"u")return null;const B=window.location.hash.replace(/^#settings-/,"");return $l.some(se=>se.id===B)?B:null}),C=a?i??null:M,D=B=>{if(a)n==null||n(B);else{P(B);try{if(history.replaceState(null,"",B?`#settings-${B}`:window.location.pathname),B){const se=document.getElementById(`settings-${B}`);se&&se.scrollIntoView({behavior:"smooth",block:"start"})}else window.scrollTo({top:0,behavior:"smooth"})}catch{}}if(B){const se=document.getElementById(`settings-${B}`);se&&se.scrollIntoView({behavior:"smooth",block:"start"})}else window.scrollTo({top:0,behavior:"smooth"})},Q=async()=>{try{u!=null&&u.settings.enabled?(await $.post("/tailscale/disable"),c.success("Tailscale serve disabled.")):(await $.post("/tailscale/enable",{port:N.port||4321,https:N.https,hostname:N.hostname||""}),c.success("Tailscale serve enabled.")),g(await $.get("/tailscale/status"))}catch(B){c.error(`Tailscale failed: ${B.message}`)}},O=async()=>{m(!0);try{const B=await $.put("/settings",l);h(B.data),x(!1),As(B.data.theme),ps(B.data.theme),c.success("Settings saved."),await t()}catch(B){c.error(`Save failed: ${B.message}`)}finally{m(!1)}},J=async()=>{try{const B=await $.get("/settings");h(B.data),x(!1),As(B.data.theme),ps(B.data.theme),c.info("Settings reloaded.",1500)}catch(B){c.error(`Reload failed: ${B.message}`)}},_=async()=>{if(confirm("Reset all settings to defaults?"))try{const B=await $.post("/settings/reset");h(B.data),x(!1),As(B.data.theme),ps(B.data.theme),c.success("Settings reset."),await t()}catch(B){c.error(`Reset failed: ${B.message}`)}},q={settings:l,patchTheme:k,patchUi:f,patchTop:v,patchNotifications:L,patchAgents:S,patchDashboard:y},F=l.about||{version:"3.0.4",homepage:"https://github.com/DrB0rk/BizarHarness",license:"MIT"},V=C===null,X=B=>C===B;return e.jsxs("div",{className:"view view-settings",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(Ct,{size:18})," Settings"]}),e.jsxs("p",{className:"view-subtitle",children:["Personal preferences. Changes are saved to ",e.jsx("code",{children:"~/.config/bizar/settings.json"}),"."]})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs(A,{variant:"ghost",size:"sm",onClick:_,children:[e.jsx(pa,{size:14})," Reset"]}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:J,children:[e.jsx(ce,{size:14})," Reload"]}),e.jsxs(A,{variant:"primary",size:"sm",disabled:!p||d,onClick:O,children:[d?e.jsx("span",{className:"btn-spinner"}):e.jsx(bs,{size:14}),d?"Saving…":"Save"]})]})]}),a&&e.jsxs("div",{className:"settings-mode-banner",children:[e.jsx("span",{children:"You're in settings mode. All sections are visible in the sidebar."}),e.jsx(A,{variant:"secondary",size:"sm",onClick:w,children:"← Back to main view"})]}),e.jsx(jl,{sections:Al,onJump:D}),e.jsxs("div",{className:K("settings-grid",C&&"settings-grid-filtered"),"data-active-section":C||void 0,children:[(V||X("theme"))&&e.jsx("div",{id:"settings-theme",children:e.jsx(bl,{...q})}),(V||X("updates"))&&e.jsx("div",{id:"settings-updates",children:e.jsx(Yn,{})}),(V||X("layout")||X("general"))&&e.jsx("div",{id:"settings-general",children:e.jsx(Xn,{...q,autoSave:j})}),(V||X("env-vars"))&&e.jsx("div",{id:"settings-env-vars",children:e.jsx(Qn,{})}),(V||X("network")||X("service")||X("tailscale"))&&e.jsx("div",{id:"settings-network",children:e.jsx(Nl,{tailscale:u,tailscaleDraft:N,setTailscaleDraft:z,onTailscaleToggle:Q})}),(V||X("network")||X("tailscale"))&&e.jsx(Jn,{initialStatus:u}),(V||X("notifications"))&&e.jsx("div",{id:"settings-notifications",children:e.jsx(kl,{...q})}),(V||X("auth"))&&e.jsx("div",{id:"settings-auth",children:e.jsx(wl,{settings:l,authStatus:R,setAuthStatus:b})}),(V||X("agents")||X("dashboard")||X("background"))&&e.jsx("div",{id:"settings-agents",children:e.jsx(Sl,{...q,autoSave:j})}),(V||X("system-llm"))&&e.jsx("div",{id:"settings-system-llm",children:e.jsx(Zn,{...q})}),(V||X("headroom"))&&e.jsx("div",{id:"settings-headroom",children:e.jsx(ei,{settings:l,setSettings:h,setDirty:x})}),(V||X("activity-log")||X("about"))&&e.jsx("div",{id:"settings-activity-log",children:e.jsx(si,{about:F})}),(V||X("workspaces"))&&e.jsx("div",{id:"settings-workspaces",children:e.jsx(Tl,{})})]})]})}const Qt=Oe.memo(Ml),Il={net:{label:"Network access",icon:cs,color:"blue",description:"Can make HTTP requests to external services"},fs:{label:"Filesystem",icon:we,color:"yellow",description:"Can read and write files"},config:{label:"Config access",icon:ga,color:"gray",description:"Can read and write Bizar config"},log:{label:"Logging",icon:we,color:"gray",description:"Can write to the structured log"},exec:{label:"Shell execution",icon:is,color:"red",description:"Can run shell commands"}};function Ot({permissions:s}){return e.jsx("div",{className:"plugin-permissions","aria-label":"Required permissions",children:s.map(t=>{const a=Il[t]??{label:t,icon:Mt,color:"gray",description:""},i=a.icon;return e.jsxs("div",{className:`permission-chip is-${a.color}`,title:a.description,children:[e.jsx(i,{size:12,"aria-hidden":!0}),e.jsx("span",{children:a.label})]},t)})})}function El({plugin:s,onInstall:t,onView:a}){return e.jsxs(Y,{className:"marketplace-plugin-card",children:[e.jsxs("div",{className:"marketplace-plugin-head",children:[e.jsxs("div",{children:[e.jsx(ae,{children:s.name}),e.jsxs(ne,{children:["v",s.version," · ",s.category]})]}),e.jsx("div",{className:"marketplace-plugin-author",children:s.author})]}),s.description&&e.jsx("p",{className:"marketplace-plugin-description",children:s.description}),s.tags&&s.tags.length>0&&e.jsx("div",{className:"marketplace-plugin-tags",children:s.tags.map(i=>e.jsx("span",{className:"tag",children:i},i))}),e.jsx(Ot,{permissions:s.permissions??[]}),e.jsxs("div",{className:"marketplace-plugin-actions",children:[e.jsx(A,{onClick:a,children:"Details"}),e.jsx(A,{variant:"primary",onClick:t,children:"Install"})]})]})}function Ll({plugin:s,onConfirm:t,onCancel:a,installing:i}){const n=Te(),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(ke,{size:16}),e.jsx("p",{children:"This plugin will run code on your machine. It requests these permissions:"})]}),e.jsx(Ot,{permissions:s.permissions??[]}),e.jsxs("div",{className:"install-confirm-actions",children:[e.jsx(A,{onClick:a,disabled:i,children:"Cancel"}),e.jsx(A,{variant:"primary",onClick:t,disabled:i,children:i?"Installing...":"Install"})]})]})}))},[s,i]),null}function Dl(){var L;const s=re(),[t,a]=r.useState(null),[i,n]=r.useState(""),[o,c]=r.useState(null),[l,h]=r.useState(null),[p,x]=r.useState(null),[d,m]=r.useState(!0),[u,g]=r.useState(!1),[N,z]=r.useState(null),R=r.useCallback(async(S={})=>{S.refresh?g(!0):m(!0),z(null);try{const y=await $.get("/plugins/registry");a(y)}catch(y){const M=y,P=M==null?void 0:M.data,C=P==null?void 0:P.registryUrl,D=(M==null?void 0:M.message)||"unknown error";z({message:D,url:C}),s.error(`Failed to load marketplace: ${D}`)}finally{m(!1),g(!1)}},[s]);r.useEffect(()=>{R()},[R]);const b=async S=>{h(S);try{await $.post("/plugins/install",{pluginId:S.id}),s.success(`${S.name} installed`),h(null),x(null)}catch(y){s.error(`Install failed: ${y.message}`),h(null)}},w=(t==null?void 0:t.plugins)??[],T=w.filter(S=>(!i||S.name.toLowerCase().includes(i.toLowerCase()))&&(!o||S.category===o)),j=[...new Set(w.map(S=>S.category))],k=(L=t==null?void 0:t.registry)==null?void 0:L.source,f=!!(t!=null&&t.cached),v=(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(gs,{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:k??"https://github.com/DrB0rk/bizar-mods"}),"…"]})]})]}):N?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(gs,{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(A,{variant:"secondary",size:"sm",onClick:()=>R({refresh:!0}),disabled:u,children:[u?e.jsx(le,{size:"sm"}):e.jsx(ce,{size:14}),"Retry"]})})]}),e.jsx(pe,{icon:e.jsx(ke,{size:32}),title:"Registry unreachable",message:e.jsxs(e.Fragment,{children:[e.jsx("p",{children:"All registry URLs failed to respond."}),N.url&&e.jsxs("p",{className:"mono muted",style:{marginTop:8,fontSize:12},children:["Last tried: ",N.url]}),e.jsx("p",{className:"muted",style:{marginTop:8,fontSize:12},children:N.message})]}),action:e.jsxs(A,{variant:"primary",size:"sm",onClick:()=>R({refresh:!0}),disabled:u,children:[u?e.jsx(le,{size:"sm"}):e.jsx(ce,{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(gs,{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(A,{variant:"secondary",size:"sm",onClick:()=>R({refresh:!0}),disabled:u,"data-testid":"marketplace-refresh",children:[u?e.jsx(le,{size:"sm"}):e.jsx(ce,{size:14}),"Refresh"]})})]}),e.jsxs("div",{className:"marketplace-source-banner muted","data-testid":"marketplace-source",children:[e.jsx(cs,{size:12,"aria-hidden":!0}),e.jsxs("span",{children:["Source:"," ",k?e.jsx("code",{className:"mono",children:k}):e.jsx("span",{children:"community registry"})]}),f&&e.jsxs("span",{className:"marketplace-cache-notice","data-testid":"marketplace-cache-notice",children:[e.jsx(Ze,{size:12,"aria-hidden":!0})," Showing cached results",v&&` from ${new Date(v).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:S=>n(S.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(S=>e.jsx("button",{type:"button",onClick:()=>c(S),className:o===S?"active":"","data-testid":`marketplace-category-${S.toLowerCase().replace(/\s+/g,"-")}`,children:S},S))]}),T.length===0?e.jsx(pe,{icon:w.length===0?e.jsx(Mn,{size:32}):e.jsx(gs,{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."}),k&&e.jsxs("p",{className:"mono muted",style:{marginTop:8,fontSize:12},children:["Check back at ",e.jsx("code",{children:k})," 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(A,{variant:"secondary",size:"sm",onClick:()=>R({refresh:!0}),disabled:u,children:[u?e.jsx(le,{size:"sm"}):e.jsx(ce,{size:14})," Refresh"]}):null}):e.jsx("div",{className:"marketplace-grid","data-testid":"marketplace-grid",children:T.map(S=>e.jsx(El,{plugin:S,onInstall:()=>x(S),onView:()=>x(S)},S.id))}),p&&e.jsx(Ll,{plugin:p,onConfirm:()=>b(p),onCancel:()=>x(null),installing:(l==null?void 0:l.id)===p.id||!1})]})}function Pl({snapshot:s,refreshSnapshot:t}){const a=re(),i=Te(),[n,o]=r.useState(Array.isArray(s.mods)?s.mods:[]),[c,l]=r.useState(!0),[h,p]=r.useState(null),[x,d]=r.useState([]),[m,u]=r.useState(null),[g,N]=r.useState(!1),[z,R]=r.useState(null),[b,w]=r.useState(!1),[T,j]=r.useState({}),k=async()=>{var C,D,Q;w(!0);try{const O=await $.get("/mods/registry");R({source:((C=O.registry)==null?void 0:C.source)||"",version:(D=O.registry)==null?void 0:D.version,updatedAt:(Q=O.registry)==null?void 0:Q.updatedAt,mods:O.mods||[]})}catch(O){R({source:"",mods:[],error:O.message})}finally{w(!1)}},f=async C=>{j(D=>({...D,[C]:!0}));try{const D=await $.post("/mods",{id:C});o(Q=>[...Q.filter(O=>O.id!==D.id),D]),a.success(`Mod "${D.id}" installed from registry.`),await t()}catch(D){a.error(`Install failed: ${D.message}`)}finally{j(D=>({...D,[C]:!1}))}},v=async(C,D=!1)=>{j(Q=>({...Q,[C]:!0}));try{const Q=await $.post(`/mods/${encodeURIComponent(C)}/upgrade`,{backup:D});o(J=>[...J.filter(_=>_.id!==Q.mod.id),Q.mod]);const O=Q.backupPath?` (backup at ${Q.backupPath})`:"";a.success(`Mod "${C}" upgraded v${Q.from} → v${Q.to}${O}.`),await t()}catch(Q){a.error(`Upgrade failed: ${Q.message}`)}finally{j(Q=>({...Q,[C]:!1}))}},L=async()=>{try{const C=await $.get("/mods");o(C.mods||[]);try{const D=await $.get("/mods/views");d(D.views||[])}catch{d([])}}catch(C){a.error(`Mods load failed: ${C.message}`)}finally{l(!1)}};r.useEffect(()=>{L()},[]),r.useEffect(()=>{Array.isArray(s.mods)&&s.mods!==n&&o(s.mods)},[s.mods]);const S=()=>{let C=null;i.open({title:"Install mod",children:e.jsxs("div",{children:[e.jsxs("p",{className:"muted",children:["Provide the absolute path to a mod folder (one that contains a ",e.jsx("code",{children:"mod.json"}),"). The folder will be copied to"," ",e.jsx("code",{children:"~/.config/bizar/mods/<id>/"}),"."]}),e.jsx("label",{className:"field-label",htmlFor:"install-mod-path",children:"Path"}),e.jsx("input",{id:"install-mod-path",ref:D=>C=D,className:"input",type:"text",placeholder:"/path/to/my-mod",autoFocus:!0})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx(A,{variant:"ghost",onClick:()=>i.close(),children:"Cancel"}),e.jsx(A,{variant:"primary",onClick:async()=>{const D=((C==null?void 0:C.value)||"").trim();if(!D){a.warning("Path is required.");return}try{const Q=await $.post("/mods",{path:D});o(O=>[...O,Q]),a.success(`Mod "${Q.id}" installed.`),i.close(),await t()}catch(Q){a.error(`Install failed: ${Q.message}`)}},children:"Install"})]})})},y=async C=>{if(confirm(`Uninstall mod "${C}"? This removes the folder from ~/.config/bizar/mods/.`))try{await $.del(`/mods/${encodeURIComponent(C)}`),o(D=>D.filter(Q=>Q.id!==C)),h===C&&p(null),a.success("Mod uninstalled.")}catch(D){a.error(`Uninstall failed: ${D.message}`)}},M=async C=>{try{const D=await $.put(`/mods/${encodeURIComponent(C.id)}`,{enabled:!C.enabled});o(Q=>Q.map(O=>O.id===C.id?D:O)),a.success(`Mod ${D.enabled?"enabled":"disabled"}.`)}catch(D){a.error(`Toggle failed: ${D.message}`)}},P=n.find(C=>C.id===h)||null;return 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(ns,{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(A,{variant:"secondary",size:"sm",onClick:L,children:[e.jsx(ce,{size:14})," Refresh"]}),e.jsxs(A,{variant:"primary",size:"sm",onClick:S,children:[e.jsx(be,{size:14})," Install mod"]})]})]}),n.length===0?e.jsx(pe,{icon:e.jsx(ns,{size:32}),title:"No mods installed",message:"Mods are folders with a mod.json. Install one to extend Bizar with custom agents, commands, and views."}):e.jsxs("div",{className:"mods-layout",children:[e.jsx("div",{className:"mods-list",children:n.map(C=>e.jsxs("div",{className:K("mod-list-item",h===C.id&&"mod-list-item-active"),onClick:()=>p(C.id),children:[e.jsxs("div",{className:"mod-list-item-head",children:[e.jsxs("div",{children:[e.jsx("div",{className:"mod-list-item-name",children:C.name}),e.jsxs("div",{className:"mod-list-item-meta",children:["v",C.version," · ",C.type," · ",C.author]})]}),e.jsxs("div",{className:"mod-list-item-actions",onClick:D=>D.stopPropagation(),children:[e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Toggle enabled",title:C.enabled?"Disable":"Enable",onClick:()=>M(C),children:e.jsx(Rt,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger","aria-label":"Uninstall",title:"Uninstall",onClick:()=>y(C.id),children:e.jsx(Se,{size:12})})]})]}),e.jsx("div",{className:"mod-list-item-desc ellipsis-2",title:C.description,children:C.description}),e.jsx("div",{className:"mod-list-item-status",children:e.jsx("span",{className:`mod-mini-pill ${C.enabled?"mod-mini-pill-on":"mod-mini-pill-off"}`,children:C.enabled?"enabled":"disabled"})})]},C.id))}),P&&e.jsx(Fl,{mod:P})]}),e.jsxs(Y,{className:"mods-registry-card",children:[e.jsxs("button",{type:"button",className:"mods-registry-head","aria-expanded":g,"aria-controls":"mods-registry-body",onClick:()=>{!z&&!b&&k(),N(C=>!C)},children:[e.jsx(cs,{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(qe,{size:14,"aria-hidden":!0}):e.jsx(Ye,{size:14,"aria-hidden":!0})]}),g&&e.jsx("div",{id:"mods-registry-body",className:"mods-registry-body",children:b?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(Es,{size:12})," Could not load registry: ",z.error]}):!z||z.mods.length===0?e.jsx("div",{className:"muted",style:{padding:12,fontSize:12},children:"No mods listed in the registry yet."}):e.jsxs(e.Fragment,{children:[z.source&&e.jsxs("div",{className:"muted",style:{fontSize:11,marginBottom:8},children:["Source: ",e.jsx("code",{children:z.source})]}),e.jsx("div",{className:"mods-registry-grid",children:z.mods.map(C=>{const D=n.some(O=>O.id===C.id),Q=!!T[C.id];return e.jsxs("div",{className:"mod-registry-card",children:[e.jsxs("div",{className:"mod-registry-card-head",children:[e.jsx("div",{className:"mod-registry-card-name",children:C.name}),C.latest&&e.jsxs("span",{className:K("mod-registry-version",C.upgradeAvailable&&"mod-registry-version-upgrade"),children:["v",C.latest,C.upgradeAvailable?" ↑":""]})]}),C.description&&e.jsx("div",{className:"mod-registry-card-desc",children:C.description}),e.jsxs("div",{className:"mod-registry-card-meta",children:[C.author&&e.jsxs("span",{className:"muted",children:["by ",C.author]}),C.homepage&&e.jsx("a",{href:C.homepage,target:"_blank",rel:"noopener noreferrer",className:"mod-registry-link",children:"homepage"})]}),(C.permissions||[]).length>0&&e.jsxs("div",{className:"mod-registry-perms",children:[e.jsx(Es,{size:10}),(C.permissions||[]).slice(0,4).map(O=>e.jsx("span",{className:"mod-registry-perm",children:O},O)),(C.permissions||[]).length>4&&e.jsxs("span",{className:"mod-registry-perm-more",children:["+",C.permissions.length-4]})]}),e.jsxs("div",{className:"mod-registry-card-actions",children:[!D&&e.jsx(A,{variant:"primary",size:"sm",disabled:Q,onClick:()=>f(C.id),title:"Install from registry",children:Q?e.jsx(le,{size:"sm"}):e.jsxs(e.Fragment,{children:[e.jsx(ls,{size:12})," Install"]})}),D&&C.upgradeAvailable&&e.jsx(A,{variant:"primary",size:"sm",disabled:Q,onClick:()=>v(C.id),title:`Upgrade from v${C.installedVersion||"?"} to v${C.upgradeAvailable}`,children:Q?e.jsx(le,{size:"sm"}):e.jsxs(e.Fragment,{children:[e.jsx(ls,{size:12})," Upgrade to v",C.upgradeAvailable]})}),D&&!C.upgradeAvailable&&e.jsxs(A,{variant:"ghost",size:"sm",disabled:!0,title:`Installed v${C.installedVersion||"?"}`,children:["Installed v",C.installedVersion||"?"]})]})]},C.id)})})]})})]}),x.length>0&&e.jsxs(Y,{className:"mod-views-hint",children:[e.jsxs(ae,{children:[e.jsx(cs,{size:14})," Mod views"]}),e.jsxs(ne,{children:[x.length," mod-supplied view",x.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 Fl({mod:s}){const t=re(),[a,i]=r.useState(null),[n,o]=r.useState(!1),[c,l]=r.useState(!1),[h,p]=r.useState(null),x=async()=>{o(!0);try{const m=await $.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 $.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 x()}catch(m){t.error(`Reinstall failed: ${m.message}`)}};return e.jsxs(Y,{className:"mod-details",children:[e.jsxs(ae,{children:[e.jsx(we,{size:14})," Mod details — ",s.name]}),e.jsx(ne,{children:e.jsx("code",{children:s.path})}),e.jsxs("dl",{className:"env-table",children:[e.jsx("dt",{children:"ID"}),e.jsx("dd",{className:"mono",children:s.id}),e.jsx("dt",{children:"Version"}),e.jsx("dd",{className:"mono",children:s.version}),e.jsx("dt",{children:"Type"}),e.jsx("dd",{className:"mono",children:s.type}),e.jsx("dt",{children:"Author"}),e.jsx("dd",{className:"mono",children:s.author||"—"}),e.jsx("dt",{children:"Bizar"}),e.jsx("dd",{className:"mono",children:s.bizar||"*"}),e.jsx("dt",{children:"Enabled"}),e.jsx("dd",{children:s.enabled?"yes":"no"}),e.jsx("dt",{children:"Permissions"}),e.jsxs("dd",{children:[(s.permissions||[]).map(m=>e.jsx("span",{className:"tag",children:m},m)),(s.permissions||[]).length===0&&e.jsx("span",{className:"muted",children:"(none)"})]})]}),e.jsxs("div",{className:"mod-files",children:[e.jsx("div",{className:"muted",children:"Files"}),e.jsx("ul",{children:(s.files||[]).map(m=>e.jsxs("li",{children:[e.jsx("span",{className:"mod-file-cat",children:m.category}),e.jsx("span",{className:"mono",children:m.path})]},m.path))})]}),e.jsxs("div",{className:"mod-instructions",children:[e.jsxs("button",{type:"button",className:"mod-instructions-head","aria-expanded":c,"aria-controls":`mod-instructions-body-${s.id}`,onClick:()=>{!a&&!n&&x(),l(m=>!m)},children:[e.jsx(In,{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(qe,{size:14,"aria-hidden":!0}):e.jsx(Ye,{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]})]}),h===m.filename&&e.jsx("pre",{className:"mod-instructions-content",children:m.content||e.jsx("em",{className:"muted",children:"(file missing on disk)"})})]},m.filename))]}),a.commands.length>0&&e.jsxs("div",{className:"mod-instructions-section",children:[e.jsxs("div",{className:"mod-instructions-section-title",children:[e.jsx(is,{size:11})," Commands (",a.commands.length,")"]}),a.commands.map(m=>e.jsxs("div",{className:"mod-instructions-file",children:[e.jsxs("div",{className:"mod-instructions-file-head",onClick:()=>p(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]})]}),h===m.filename&&e.jsx("pre",{className:"mod-instructions-content",children:m.content||e.jsx("em",{className:"muted",children:"(file missing on disk)"})})]},m.filename))]}),a.skills.length>0&&e.jsxs("div",{className:"mod-instructions-section",children:[e.jsxs("div",{className:"mod-instructions-section-title",children:[e.jsx(ja,{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]})]}),h===m.name&&e.jsx("pre",{className:"mod-instructions-content",children:m.content||e.jsx("em",{className:"muted",children:"(file missing on disk)"})})]},m.name))]}),a.total===0&&e.jsxs("div",{className:"muted",style:{padding:8,fontSize:12},children:["This mod did not install any instruction files. Mods install instructions by shipping a top-level ",e.jsx("code",{children:"INSTRUCTIONS.md"}),", an ",e.jsx("code",{children:"agents/"})," directory, a ",e.jsx("code",{children:"commands/"})," directory, or a ",e.jsx("code",{children:"skills/"})," directory."]}),e.jsx("div",{className:"mod-instructions-actions",children:e.jsxs(A,{variant:"ghost",size:"sm",onClick:d,children:[e.jsx(ce,{size:11})," Reinstall from mod folder"]})})]})]})]})}const Ol=r.forwardRef(function({className:t,checked:a,onChange:i,onClick:n,...o},c){return e.jsxs("label",{className:K("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 Bl({plugin:s,onToggle:t,onUninstall:a,onConfigure:i}){return e.jsxs(Y,{children:[e.jsxs("div",{className:"plugin-card-head",children:[e.jsxs("div",{children:[e.jsx(ae,{children:s.name}),e.jsxs(ne,{children:["v",s.version," · ",s.id]})]}),e.jsx(Ol,{checked:s.enabled??!0,onChange:()=>t(s.id),"aria-label":`Toggle ${s.name} enabled`})]}),s.description&&e.jsx("p",{className:"plugin-description",children:s.description}),e.jsx(Ot,{permissions:s.permissions??[]}),e.jsxs("div",{className:"plugin-card-actions",children:[e.jsx(A,{size:"sm",onClick:()=>i(s.id),"aria-label":`Configure ${s.name}`,children:"Configure"}),e.jsx(A,{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 Ul({setActiveTab:s}){const t=re(),[a,i]=r.useState([]),[n,o]=r.useState(!0),[c,l]=r.useState(""),h=async()=>{try{const u=await $.get("/plugins/installed");i(u.plugins)}catch(u){t.error(`Failed to load plugins: ${u.message}`)}finally{o(!1)}};r.useEffect(()=>{h()},[]);const p=async u=>{try{await $.post(`/plugins/${u}/toggle`).catch(()=>{}),await h(),t.success("Plugin toggled.")}catch(g){t.error(`Toggle failed: ${g.message}`)}},x=async u=>{if(confirm("Uninstall this plugin?"))try{await $.del(`/plugins/${u}`),await h(),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(ns,{size:18,"aria-hidden":!0}),"Plugins (",a.length,")"]}),e.jsx("p",{className:"view-subtitle",children:"Manage plugins installed via the marketplace."})]}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:()=>s("marketplace"),children:[e.jsx(gs,{size:14,"aria-hidden":!0}),"Browse Marketplace"]})]}),a.length===0?e.jsx(pe,{icon:e.jsx(ns,{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(Bl,{plugin:u,onToggle:p,onUninstall:x,onConfigure:d},u.id))})]})]})}function _l({viewId:s,reloadKey:t,setActiveTab:a}){const i=re(),[n,o]=r.useState(null),[c,l]=r.useState(!0),[h,p]=r.useState(0);if(r.useEffect(()=>{let x=!1;return(async()=>{try{const d=await $.get("/mods/views");if(x)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{x||l(!1)}})(),()=>{x=!0}},[s,i]),c)return e.jsx(pe,{title:"Loading mod view…"});if(!n)return e.jsx(pe,{title:"Mod view not found",message:`No view with id "${s}" is currently installed.`,action:e.jsx(A,{onClick:()=>a("mods"),variant:"primary",size:"sm",children:"Open Mods"})});if(n.kind==="iframe"){const x=`/api/mods/${n.modId}/web/index.html?t=${h+(t||0)}`;return e.jsxs("div",{className:"mod-view-iframe-pane",children:[e.jsxs("div",{className:"mod-view-iframe-header",children:[e.jsxs("span",{className:"mod-view-iframe-label",children:[e.jsx(cs,{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(A,{variant:"ghost",size:"sm",onClick:()=>p(d=>d+1),title:"Reload this view",children:[e.jsx(ce,{size:11})," Reload"]}),e.jsx("a",{href:x,target:"_blank",rel:"noopener noreferrer",className:"icon-btn",title:"Open in new tab",children:e.jsx(Ns,{size:12})})]})]}),e.jsx("iframe",{src:x,className:"mod-view-iframe",title:n.label},h+(t||0))]})}if(n.component){const x=n.component,d=n.modId,m=r.lazy(()=>Ga(()=>import(`/api/mods/${encodeURIComponent(d)}/views/${encodeURIComponent(x)}`),[]).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(Ls,{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(Wl,{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(Y,{children:[e.jsxs(ae,{children:[e.jsx(Ls,{size:14})," ",n.label]}),e.jsxs(ne,{children:["by ",n.modId]}),n.description&&e.jsx("p",{className:"muted",style:{marginTop:8},children:n.description}),e.jsxs("p",{className:"muted",style:{fontSize:12,marginTop:12},children:["This mod declared a tab view but did not provide a component path in views/registry.json. Add a ",e.jsx("code",{children:"component"})," field (e.g. ",e.jsx("code",{children:'"MyView.js"'}),") and ship the file under ",e.jsx("code",{children:"views/"}),"."]}),e.jsx("div",{style:{marginTop:12},children:e.jsx(A,{variant:"secondary",size:"sm",onClick:()=>a("mods"),children:"Open Mods page"})})]})}class Wl extends r.Component{constructor(){super(...arguments);Cs(this,"state",{error:null})}static getDerivedStateFromError(a){return{error:a}}componentDidCatch(){}render(){return this.state.error?e.jsxs("div",{className:"mod-view-error",children:[e.jsx(ke,{size:16}),e.jsx("strong",{children:"Failed to render mod view"}),e.jsxs("div",{className:"muted",style:{fontSize:12,marginTop:6},children:[this.props.modId," → ",this.props.component,": ",this.state.error.message]})]}):this.props.children}}function ql(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 Vl({template:s,onUse:t}){return e.jsxs(Y,{className:"schedule-template-card",children:[e.jsxs("div",{className:"schedule-template-header",children:[e.jsx(ae,{children:s.name}),s.tags&&s.tags.length>0&&e.jsx("div",{className:"schedule-template-tags",children:s.tags.map(a=>e.jsx("span",{className:"tag",children:a},a))})]}),e.jsx(ne,{children:s.description}),e.jsxs("div",{className:"schedule-template-summary",children:[e.jsx("code",{children:ql(s)})," · ",e.jsx("code",{children:s.action.type})]}),e.jsx(A,{variant:"secondary",size:"sm",onClick:()=>t(s),"aria-label":`Use template: ${s.name}`,children:"Use this template"})]})}const Hl=["interval","cron","once"],Gl=["command","agent","webhook"],Nt=[{value:"UTC",label:"UTC"},{value:"America/New_York",label:"America/New_York (ET)"},{value:"America/Los_Angeles",label:"America/Los_Angeles (PT)"},{value:"America/Chicago",label:"America/Chicago (CT)"},{value:"Europe/London",label:"Europe/London (UK)"},{value:"Europe/Berlin",label:"Europe/Berlin (CET)"},{value:"Asia/Tokyo",label:"Asia/Tokyo (JST)"}],Kl=Array.from({length:12},(s,t)=>t*5),Bt=Array.from({length:24},(s,t)=>({value:t,label:t===0?"12 AM":t<12?`${t} AM`:t===12?"12 PM":`${t-12} PM`})),Ut=[{value:"*",label:"Every day"},{value:"0",label:"Sunday"},{value:"1",label:"Monday"},{value:"2",label:"Tuesday"},{value:"3",label:"Wednesday"},{value:"4",label:"Thursday"},{value:"5",label:"Friday"},{value:"6",label:"Saturday"}],Aa=[{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 Yl(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 Xl(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"?Yl(s.schedule):null,i=s.timezone||"UTC",n=Nt.some(l=>l.value===i);return{name:s.name||"",type:s.type,cronMinute:(t==null?void 0:t.minute)??0,cronHour:(t==null?void 0:t.hour)??9,cronDow:(t==null?void 0:t.dow)??"*",showAdvanced:!t,rawCron:s.schedule,intervalN:(a==null?void 0:a.n)??30,intervalUnit:(a==null?void 0:a.unit)??"m",onceAt:s.type==="once"?Ql(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 Ql(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 Jl(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=Ut.find(x=>x.value===s.cronDow))==null?void 0:a.label)||"",l=((i=Bt.find(x=>x.value===s.cronHour))==null?void 0:i.label)||`${s.cronHour}`,h=String(s.cronMinute).padStart(2,"0"),p=c==="Every day"?`Every day at ${l.replace(" ","")} (min ${h})`:`Every ${c} at ${l.replace(" ","")} (min ${h})`;return{schedule:o,humanLabel:s.humanLabel||p}}if(s.type==="interval"){const o=((n=Aa.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 Zl({snapshot:s,refreshSnapshot:t}){var T;const a=re(),i=Te(),[n,o]=r.useState(s.schedules||[]),[c,l]=r.useState(!s.schedules),[h,p]=r.useState("schedules"),[x,d]=r.useState([]),[m,u]=r.useState(!1),g=async()=>{try{const j=await $.get("/projects/active/schedules");o(j.schedules||[])}catch(j){a.error(`Schedules load failed: ${j.message}`)}finally{l(!1)}},N=async()=>{u(!0);try{const j=await $.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(()=>{h==="templates"&&x.length===0&&N()},[h]);const z=j=>{i.open({title:j?`Edit schedule: ${j.name}`:"New schedule",width:640,children:e.jsx(eo,{initial:j,onClose:i.close,onSubmitted:async k=>{o(f=>{const v=f.findIndex(S=>S.id===k.id);if(v===-1)return[...f,k];const L=f.slice();return L[v]=k,L}),a.success(j?"Schedule updated.":"Schedule created."),i.close(),await t()},onError:k=>a.error(k)})})},R=async j=>{var k;try{const f=await $.post(`/schedules/${encodeURIComponent(j.id)}/run`);a.success(f.ok?"Schedule ran.":`Run failed: ${((k=f.runResult)==null?void 0:k.error)||"unknown"}`),await g()}catch(f){a.error(`Run failed: ${f.message}`)}},b=async j=>{if(confirm(`Delete schedule "${j.name}"?`))try{await $.del(`/schedules/${encodeURIComponent(j.id)}`),o(k=>k.filter(f=>f.id!==j.id)),a.success("Schedule deleted.")}catch(k){a.error(`Delete failed: ${k.message}`)}},w=async j=>{try{const k=await $.post("/schedules/from-template",{templateId:j.id});o(f=>[...f,k]),p("schedules"),a.success(`Schedule "${k.name}" created from template.`),await t()}catch(k){a.error(`Failed to create schedule: ${k.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(Ze,{size:18})," Schedules"]}),e.jsxs("div",{className:"view-section-tabs",children:[e.jsxs("button",{type:"button",className:`tab-btn ${h==="schedules"?"tab-btn-active":""}`,onClick:()=>p("schedules"),children:["Schedules (",n.length,")"]}),e.jsxs("button",{type:"button",className:`tab-btn ${h==="templates"?"tab-btn-active":""}`,onClick:()=>p("templates"),children:[e.jsx(Ls,{size:14})," Templates"]})]})]}),e.jsx("p",{className:"view-subtitle",children:h==="schedules"?e.jsxs(e.Fragment,{children:["Recurring tasks for ",e.jsx("strong",{children:((T=s.activeProject)==null?void 0:T.name)||"(none)"}),". Service daemon runs them at the right time."]}):"Example schedules you can use as a starting point."})]}),e.jsxs("div",{className:"view-actions",children:[h==="schedules"&&e.jsxs(e.Fragment,{children:[e.jsxs(A,{variant:"secondary",size:"sm",onClick:g,"aria-label":"Refresh schedules",children:[e.jsx(ce,{size:14})," Refresh"]}),e.jsxs(A,{variant:"primary",size:"sm",onClick:()=>z(),children:[e.jsx(be,{size:14})," New schedule"]})]}),h==="templates"&&e.jsxs(A,{variant:"secondary",size:"sm",onClick:N,disabled:m,children:[e.jsx(ce,{size:14})," Refresh"]})]})]}),h==="templates"?m?e.jsx("div",{className:"view-loading",children:e.jsx(le,{size:"lg"})}):x.length===0?e.jsx(pe,{icon:e.jsx(Ls,{size:32}),title:"No templates",message:"No schedule templates found. Templates are loaded from templates/schedules/."}):e.jsx("div",{className:"schedule-template-grid",children:x.map(j=>e.jsx(Vl,{template:j,onUse:w},j.id))}):n.length===0?e.jsx(pe,{icon:e.jsx(Ze,{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 k;return e.jsxs(Y,{className:"schedule-card",children:[e.jsxs("div",{className:"schedule-card-head",children:[e.jsxs("div",{children:[e.jsx(ae,{children:j.name}),e.jsxs(ne,{children:[e.jsx("code",{children:j.type})," ·"," ",e.jsx("span",{title:j.schedule,children:so(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(A,{variant:"secondary",size:"sm",onClick:()=>z(j),children:[e.jsx(Ds,{size:12})," Edit"]}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:()=>R(j),children:[e.jsx(vt,{size:12})," Run now"]}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger","aria-label":"Delete",title:"Delete",onClick:()=>b(j),children:e.jsx(Se,{size:12})})]})]}),e.jsxs("div",{className:"schedule-card-action",children:[e.jsx("span",{className:"muted",children:"action:"})," ",e.jsxs("code",{children:[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]})]}),((k=j.budgetCheck)==null?void 0:k.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?Re(j.lastRun):"—",j.lastResult&&e.jsx("span",{className:`tag ${Jt(j.lastResult)}`,children:j.lastResult}),j.lastError&&e.jsxs("span",{className:"muted schedule-card-error",title:j.lastError,children:[" ","— ",Zt(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:to(j.nextRun,j.timezone)}):"—",j.nextRun&&e.jsxs("span",{className:"muted",children:[" · ",Re(j.nextRun)]})]})]}),j.history&&j.history.length>0&&e.jsxs("details",{className:"schedule-card-history",children:[e.jsxs("summary",{children:[e.jsx(Is,{size:12})," ",j.history.length," run",j.history.length===1?"":"s"]}),e.jsx("ul",{children:j.history.slice(-10).reverse().map((f,v)=>e.jsxs("li",{children:[e.jsx("span",{className:"tabular-nums muted",children:Re(f.ts)})," ",e.jsx("span",{className:`tag ${Jt(f.result)}`,children:f.result}),f.error&&e.jsxs("span",{className:"muted",children:[" — ",Zt(f.error,80)]})]},v))})]})]},j.id)})})]})}function eo({initial:s,onClose:t,onSubmitted:a,onError:i}){const[n,o]=r.useState(()=>Xl(s)),[c,l]=r.useState(!1),h=r.useMemo(()=>Nt.some(d=>d.value===n.timezone)?n.timezone:"Other…",[n.timezone]),p=(d,m)=>{o(u=>({...u,[d]:m}))},x=async d=>{d.preventDefault();const m=n.name.trim();if(!m){i("Name is required.");return}const u=Jl(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,N={type:n.actionType,target:n.actionTarget.trim()};n.actionType==="agent"&&n.actionPrompt.trim()&&(N.prompt=n.actionPrompt.trim());const z={name:m,type:n.type,schedule:u.schedule,timezone:g||"UTC",action:N,budgetCheck:{maxConcurrent:n.maxConcurrent,skipIfBudgetLow:n.skipIfBudgetLow},enabled:n.enabled};l(!0);try{const R=s?await $.put(`/schedules/${encodeURIComponent(s.id)}`,z):await $.post("/schedules",z);await a(R)}catch(R){i(`${s?"Update":"Create"} failed: ${R.message}`)}finally{l(!1)}};return e.jsxs("form",{className:"schedule-form",onSubmit:x,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:Hl.map(d=>e.jsx("option",{value:d,children:d},d))})]})}),n.type==="cron"&&e.jsxs("div",{className:"schedule-cron-group",children:[!n.showAdvanced&&e.jsx(e.Fragment,{children:e.jsxs("div",{className:"task-form-row",children:[e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-dow",children:"Day of week"}),e.jsx("select",{id:"schedule-dow",className:"select",value:n.cronDow,onChange:d=>p("cronDow",d.target.value),children:Ut.map(d=>e.jsx("option",{value:d.value,children:d.label},d.value))})]}),e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-hour",children:"Hour"}),e.jsx("select",{id:"schedule-hour",className:"select",value:String(n.cronHour),onChange:d=>p("cronHour",parseInt(d.target.value,10)),children:Bt.map(d=>e.jsx("option",{value:String(d.value),children:d.label},d.value))})]}),e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-minute",children:"Minute"}),e.jsx("select",{id:"schedule-minute",className:"select",value:String(n.cronMinute),onChange:d=>p("cronMinute",parseInt(d.target.value,10)),children:Kl.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(qe,{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:Aa.map(d=>e.jsx("option",{value:d.value,children:d.label},d.value))})]})]}),n.type==="once"&&e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-once-at",children:"Run at"}),e.jsx("input",{id:"schedule-once-at",className:"input",type:"datetime-local",value:n.onceAt,onChange:d=>p("onceAt",d.target.value)})]}),e.jsxs("div",{className:"task-form-row",children:[e.jsxs("div",{className:"task-form-field",style:{flex:1},children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-timezone",children:"Timezone"}),e.jsxs("select",{id:"schedule-timezone",className:"select",value:h,onChange:d=>p("timezone",d.target.value),children:[Nt.map(d=>e.jsx("option",{value:d.value,children:d.label},d.value)),e.jsx("option",{value:"Other…",children:"Other…"})]})]}),n.timezone==="Other…"&&e.jsxs("div",{className:"task-form-field",style:{flex:1},children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-custom-tz",children:"IANA name"}),e.jsx("input",{id:"schedule-custom-tz",className:"input",type:"text",placeholder:"Europe/Paris",value:n.customTimezone,onChange:d=>p("customTimezone",d.target.value)})]})]}),e.jsxs("div",{className:"task-form-row",children:[e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-action-type",children:"Action"}),e.jsx("select",{id:"schedule-action-type",className:"select",value:n.actionType,onChange:d=>p("actionType",d.target.value),children:Gl.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(A,{variant:"ghost",type:"button",onClick:t,disabled:c,children:"Cancel"}),e.jsx(A,{variant:"primary",type:"submit",disabled:c,children:s?"Save":"Create"})]})]})}function so(s){var o,c;if(s.type!=="cron")return s.schedule;const t=Ma(s.schedule);if(!t)return s.schedule;const a=((o=Ut.find(l=>l.value===t.dow))==null?void 0:o.label)||"",i=((c=Bt.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 to(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 Jt(s){return s==="success"?"tag-success":s==="skipped"?"tag-warning":"tag-error"}function Zt(s,t){return s.length<=t?s:s.slice(0,t-1)+"…"}const ao=[{id:"all",label:"All",icon:Xe},{id:"shipped",label:"Shipped",icon:Et},{id:"user",label:"User",icon:Js},{id:"project",label:"Project",icon:Pe}],Ks={shipped:"Shipped",user:"User",project:"Project"},no={shipped:Et,user:Js,project:Pe};function io({snapshot:s,refreshSnapshot:t}){const a=re(),i=Te(),[n,o]=r.useState([]),[c,l]=r.useState({shipped:0,user:0,project:0,all:0}),[h,p]=r.useState(!0),[x,d]=r.useState("all"),[m,u]=r.useState(""),[g,N]=r.useState(null),[z,R]=r.useState(!1),b=async()=>{var k,f,v;p(!0);try{const L=await $.get("/skills");o(L.skills||[]),l({shipped:((k=L.counts)==null?void 0:k.shipped)??0,user:((f=L.counts)==null?void 0:f.user)??0,project:((v=L.counts)==null?void 0:v.project)??0,all:(L.skills||[]).length})}catch(L){a.error(`Skills load failed: ${L.message}`)}finally{p(!1)}};r.useEffect(()=>{b()},[]),r.useEffect(()=>{if(!m.trim()){N(null);return}R(!0);const k=setTimeout(async()=>{try{const f=await $.get(`/skills/search?q=${encodeURIComponent(m.trim())}`);N(f.results||[])}catch(f){a.error(`Search failed: ${f.message}`)}finally{R(!1)}},280);return()=>clearTimeout(k)},[m]);const w=r.useMemo(()=>g!==null?g:x==="all"?n:n.filter(k=>k.source===x),[n,x,g]),T=async()=>{try{await $.post("/skills/refresh",{}),a.success("Skills refreshed."),await b()}catch(k){a.error(`Refresh failed: ${k.message}`)}},j=async k=>{try{const f=await $.get(`/skills/${encodeURIComponent(k.source)}/${encodeURIComponent(k.name)}`);i.open({title:f.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":f.source,children:Ks[f.source]||f.source}),e.jsx("code",{className:"mono text-sm muted",children:f.path})]}),f.description&&e.jsx("p",{className:"skill-detail-desc",children:f.description}),f.body&&e.jsx("div",{className:"skill-detail-body",children:e.jsx("pre",{className:"skill-body-pre",children:f.body})})]}),footer:e.jsx(A,{variant:"ghost",onClick:()=>i.close(),children:"Close"})})}catch{i.open({title:k.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":k.source,children:Ks[k.source]||k.source}),e.jsx("code",{className:"mono text-sm muted",children:k.path})]}),k.description&&e.jsx("p",{className:"skill-detail-desc",children:k.description})]}),footer:e.jsx(A,{variant:"ghost",onClick:()=>i.close(),children:"Close"})})}};return e.jsxs("div",{className:"view view-skills",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(Xe,{size:18})," Skills"]}),e.jsx("p",{className:"view-subtitle",children:"Browse all available skills — shipped, user, and project-local."})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs("div",{className:"search-input",children:[e.jsx(ye,{size:14,"aria-hidden":!0}),e.jsx("label",{htmlFor:"skills-search",className:"sr-only",children:"Search skills"}),e.jsx("input",{id:"skills-search",className:"input",type:"text",placeholder:"Search skills…",value:m,onChange:k=>u(k.target.value),"aria-label":"Search skills"}),m&&e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Clear search",onClick:()=>u(""),children:e.jsx(Ps,{size:12})})]}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:T,children:[e.jsx(ce,{size:14})," Refresh"]})]})]}),!m.trim()&&e.jsx("div",{className:"skills-tabs",children:ao.map(k=>{const f=k.icon,v=k.id==="all"?c.all:c[k.id]??0;return e.jsxs("button",{type:"button",className:K("skills-tab",x===k.id&&"skills-tab-active"),onClick:()=>d(k.id),children:[e.jsx(f,{size:14}),e.jsx("span",{children:k.label}),e.jsx("span",{className:"skills-tab-count",children:v})]},k.id)})}),m.trim()&&e.jsxs("section",{className:"skills-section",children:[e.jsxs("h3",{className:"skills-section-title",children:[e.jsx(ye,{size:14})," Search results",z&&e.jsx(le,{size:"sm"})]}),z?e.jsx("div",{className:"skills-grid",children:[0,1,2].map(k=>e.jsx("div",{className:"skill-card skill-card-skeleton"},k))}):g&&g.length===0?e.jsx(pe,{icon:e.jsx(ye,{size:28}),title:"No matches",message:`No skills match "${m}".`}):e.jsx("div",{className:"skills-grid",children:(g||[]).map((k,f)=>e.jsx(ea,{skill:k,onShow:()=>j(k),searchQ:m},`search-${f}`))})]}),!m.trim()&&e.jsx("section",{className:"skills-section",children:h?e.jsx("div",{className:"view-loading",children:e.jsx(le,{size:"lg"})}):w.length===0?e.jsx(pe,{icon:e.jsx(ja,{size:28}),title:"No skills here",message:x==="all"?"No skills found. Install skills with the skills CLI or add SKILL.md files to a skills directory.":`No skills in the ${Ks[x]} tab.`}):e.jsx("div",{className:"skills-grid",children:w.map((k,f)=>e.jsx(ea,{skill:k,onShow:()=>j(k)},`${k.source}-${k.name}-${f}`))})}),!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 ea({skill:s,onShow:t,searchQ:a=""}){const i=no[s.source]||Et,n=s.description?s.description.length>200?s.description.slice(0,200)+"…":s.description:"No description.";return e.jsxs(Y,{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:ro(s.name,a)}),e.jsx("span",{className:"skill-source-badge","data-source":s.source,children:Ks[s.source]||s.source})]})]}),e.jsx("p",{className:"skill-card-desc",children:n}),e.jsx("div",{className:"skill-card-actions",children:e.jsxs(A,{variant:"ghost",size:"sm",onClick:t,children:[e.jsx(Ns,{size:12})," View"]})})]})}function ro(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 lo=Oe.memo(io);function oo({refreshKey:s,onRefresh:t,setActiveSubPanel:a}){const i=re(),[n,o]=r.useState(null),[c,l]=r.useState(""),[h,p]=r.useState(!0),x=async z=>{p(!0);try{const[R,b,w,T]=await Promise.all([$.get("/memory/health",z).catch(()=>null),$.get("/memory/status",z).catch(()=>null),$.get("/memory/lightrag/stats",z).catch(()=>null),$.get("/memory/storage",z).catch(()=>null)]);l((b==null?void 0:b.vaultRoot)||""),o({health:R||{score:0,status:"unconfigured",checks:[],message:"memory not initialised"},vault:{exists:!!(b!=null&&b.initialized),vaultRoot:(b==null?void 0:b.vaultRoot)||"",mode:(b==null?void 0:b.mode)||"local-only",noteCount:(b==null?void 0:b.noteCount)||0,totalSize:(T==null?void 0:T.total)||0,folderCount:0,folders:[],lastModified:null,gitClean:(b==null?void 0:b.gitClean)??null,gitBranch:(b==null?void 0:b.branch)||null},lightrag:w||{running:!1,pid:null,host:"127.0.0.1",port:9621,indexedApprox:0,queryCountLast24h:0,lastReindexAt:null},storage:T||{total:0,breakdown:[]}})}catch(R){i.error(`Memory overview failed: ${R.message}`)}finally{p(!1)}};if(r.useEffect(()=>{const z=new AbortController;return x(z.signal),()=>z.abort()},[s]),h&&!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,N=d.score>=80?"var(--success)":d.score>=50?"var(--warning)":"var(--error)";return e.jsxs("div",{className:"memory-overview",children:[e.jsxs(Y,{variant:"elevated",className:"memory-health-hero",children:[e.jsxs("div",{className:"memory-health-score",style:{borderColor:N},children:[e.jsx("span",{className:"memory-health-score-value",style:{color:N},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(De,{size:16}),"Memory health ·"," ",e.jsx("span",{style:{color:N},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(A,{variant:"ghost",size:"sm",onClick:t,children:[e.jsx(ce,{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(_e,{size:14}),e.jsx("span",{children:"LightRAG"}),e.jsx("span",{className:K("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(we,{size:14}),e.jsx("span",{children:"Obsidian Vault"}),e.jsxs("span",{className:K("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(rs,{size:14}),e.jsx("span",{children:"Git Sync"}),e.jsx("span",{className:K("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(ye,{size:14}),e.jsx("span",{children:"Semantic Search"}),e.jsx("span",{className:"memory-source-pill-status na",children:"cross-source"})]})]}),e.jsxs("div",{className:"memory-stat-grid",children:[e.jsx(xs,{icon:e.jsx(_e,{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(xs,{icon:e.jsx(we,{size:16}),label:"Obsidian",value:`${m.noteCount} notes`,sub:m.folderCount>0?`${m.folderCount} folders`:"no folders yet",onClick:()=>a("obsidian")}),e.jsx(xs,{icon:e.jsx(rs,{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(xs,{icon:e.jsx(fa,{size:16}),label:"Storage",value:co(g.total),sub:g.breakdown.length>0?`${g.breakdown.length} dirs tracked`:"no memory data on disk"}),e.jsx(xs,{icon:e.jsx(Xe,{size:16}),label:"Last reindex",value:u.lastReindexAt?We(u.lastReindexAt):"never",sub:"lightrag ingest",onClick:()=>a("lightrag")}),e.jsx(xs,{icon:e.jsx(Es,{size:16}),label:"Health",value:`${d.score}/100`,sub:d.status,onClick:()=>a("config")})]}),d.checks.length>0&&e.jsxs(Y,{children:[e.jsx(ae,{children:"Health checks"}),e.jsx(ne,{children:"Composite score across all memory subsystems"}),e.jsx("ul",{className:"memory-check-list",children:d.checks.map(z=>e.jsxs("li",{className:"memory-check-row",children:[e.jsx("span",{className:"memory-check-icon",children:z.pass?e.jsx(Fe,{size:14,style:{color:"var(--success)"}}):z.name.includes("secrets")||z.name.includes("schema")?e.jsx(ke,{size:14,style:{color:"var(--warning)"}}):e.jsx(Ps,{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 xs({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:K("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 co(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 mo({refreshKey:s}){const t=re(),[a,i]=r.useState(null),[n,o]=r.useState(null),[c,l]=r.useState([]),[h,p]=r.useState(!0),[x,d]=r.useState(null),[m,u]=r.useState(""),[g,N]=r.useState(null),z=async()=>{p(!0);try{const[v,L,S]=await Promise.all([$.get("/memory/lightrag/stats").catch(()=>null),$.get("/memory/config").then(y=>(y==null?void 0:y.lightrag)||null).catch(()=>null),$.get("/memory/lightrag/log").catch(()=>({lines:[]}))]);i(v),o(L),l((S==null?void 0:S.lines)||[])}catch(v){t.error(`LightRAG status failed: ${v.message}`)}finally{p(!1)}};r.useEffect(()=>{z()},[s]);const R=async(v,L,S)=>{d(v);try{await L(),t.success(S),await z()}catch(y){t.error(`${v} failed: ${y.message}`)}finally{d(null)}},b=()=>R("start",()=>$.post("/memory/lightrag/start",{}),"LightRAG starting…"),w=()=>R("stop",()=>$.post("/memory/lightrag/stop",{}),"LightRAG stopping…"),T=async()=>{d("restart");try{await $.post("/memory/lightrag/stop",{}).catch(()=>{}),await new Promise(v=>setTimeout(v,600)),await $.post("/memory/lightrag/start",{}),t.success("LightRAG restarted."),await z()}catch(v){t.error(`Restart failed: ${v.message}`)}finally{d(null)}},j=()=>R("reindex",()=>$.post("/memory/lightrag/reindex",{}),"Reindex complete."),k=()=>R("rebuild",()=>$.post("/memory/lightrag/rebuild-graph",{}),"Graph rebuilt."),f=async()=>{var v,L,S;if(m.trim()){d("query");try{const y=await $.get(`/memory/query?q=${encodeURIComponent(m)}&topK=8`),M=(v=y==null?void 0:y.semantic)!=null&&v.response?typeof y.semantic.response=="string"?y.semantic.response:JSON.stringify(y.semantic.response):((L=y==null?void 0:y.semantic)==null?void 0:L.error)||"No response";N({ok:!!((S=y==null?void 0:y.semantic)!=null&&S.ok),text:M})}catch(y){N({ok:!1,text:y.message})}finally{d(null)}}};return h&&!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(Y,{variant:"elevated",children:[e.jsxs(ae,{children:[e.jsx(_e,{size:14}),"LightRAG",e.jsx("span",{className:K("memory-source-pill-status",a.running?"on":"off"),children:a.running?"running":"stopped"})]}),e.jsx(ne,{children:a.running?e.jsxs(e.Fragment,{children:["PID ",e.jsx("code",{children:a.pid})," · ",a.host,":",a.port]}):e.jsx(e.Fragment,{children:"Server is not running. Start it from the controls below."})}),e.jsxs("div",{className:"memory-action-row",children:[e.jsxs(A,{variant:"primary",size:"sm",onClick:b,disabled:!!x||a.running,children:[x==="start"?e.jsx(he,{size:12,className:"memory-spin"}):e.jsx(ks,{size:12}),"Start"]}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:w,disabled:!!x||!a.running,children:[x==="stop"?e.jsx(he,{size:12,className:"memory-spin"}):e.jsx(Ln,{size:12}),"Stop"]}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:T,disabled:!!x,children:[x==="restart"?e.jsx(he,{size:12,className:"memory-spin"}):e.jsx(Rt,{size:12}),"Restart"]}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:j,disabled:!!x,children:[x==="reindex"?e.jsx(he,{size:12,className:"memory-spin"}):e.jsx(ce,{size:12}),"Reindex all"]}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:k,disabled:!!x,title:"Wipe working dir + reindex from scratch",children:[x==="rebuild"?e.jsx(he,{size:12,className:"memory-spin"}):e.jsx(st,{size:12}),"Rebuild graph"]})]})]}),e.jsxs("div",{className:"memory-stat-grid",children:[e.jsx(zs,{icon:e.jsx(fa,{size:14}),label:"Indexed chunks (approx)",value:String(a.indexedApprox)}),e.jsx(zs,{icon:e.jsx(uo,{n:a.noteCount}),label:"Notes in vault",value:String(a.noteCount)}),e.jsx(zs,{icon:e.jsx(Tt,{size:14}),label:"Queries last 24h",value:String(a.queryCountLast24h)}),e.jsx(zs,{icon:e.jsx(Xe,{size:14}),label:"Avg response",value:a.avgResponseMs!==null?`${a.avgResponseMs} ms`:"—"}),e.jsx(zs,{icon:a.lastReindexOk?e.jsx(Fe,{size:14}):a.lastReindexOk===!1?e.jsx(Ps,{size:14}):e.jsx(ce,{size:14}),label:"Last reindex",value:a.lastReindexAt?We(a.lastReindexAt):"never",sub:a.lastReindexInserted!==null?`${a.lastReindexInserted} inserted${a.lastReindexFailed?`, ${a.lastReindexFailed} failed`:""}`:void 0})]}),e.jsxs(Y,{children:[e.jsxs(ae,{children:[e.jsx(ye,{size:14})," Quick search"]}),e.jsx(ne,{children:"Send a natural-language query to the LightRAG index."}),e.jsxs("div",{className:"memory-search-row",children:[e.jsx("label",{htmlFor:"lightrag-query",className:"sr-only",children:"Search LightRAG"}),e.jsx("input",{id:"lightrag-query",type:"text",className:"input",placeholder:"e.g. how does the memory service write notes?",value:m,onChange:v=>u(v.target.value),onKeyDown:v=>{v.key==="Enter"&&f()},disabled:x==="query","aria-label":"Search LightRAG"}),e.jsxs(A,{variant:"primary",onClick:f,disabled:x==="query"||!m.trim(),children:[x==="query"?e.jsx(he,{size:12,className:"memory-spin"}):e.jsx(ye,{size:12}),"Query"]})]}),g&&e.jsx("div",{className:K("memory-query-result",g.ok?"ok":"err"),children:e.jsx("pre",{className:"mono text-sm",children:g.text})})]}),n&&e.jsxs(Y,{children:[e.jsx(ae,{children:"Configuration"}),e.jsxs(ne,{children:["Effective values from ",e.jsx("code",{children:".bizar/memory.json"})," + env defaults."]}),e.jsxs("dl",{className:"memory-config-row",children:[e.jsx("dt",{children:"LLM binding"}),e.jsxs("dd",{children:[e.jsx("code",{children:n.llmBinding})," · ",e.jsx("code",{children:n.llmModel})]}),e.jsx("dt",{children:"Embedding"}),e.jsxs("dd",{children:[e.jsx("code",{children:n.embeddingBinding})," · ",e.jsx("code",{children:n.embeddingModel})]}),e.jsx("dt",{children:"Host"}),e.jsx("dd",{children:e.jsxs("code",{children:[n.host,":",n.port]})}),e.jsx("dt",{children:"Working dir"}),e.jsx("dd",{className:"mono ellipsis",title:n.workingDir,children:n.workingDir})]})]}),c.length>0&&e.jsxs(Y,{children:[e.jsxs(ae,{children:[e.jsx(ce,{size:14})," Server log (tail)"]}),e.jsxs(ne,{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 zs({icon:s,label:t,value:a,sub:i}){return e.jsxs("div",{className:"memory-stat-card",children:[e.jsx("div",{className:"memory-stat-icon",children:s}),e.jsxs("div",{className:"memory-stat-body",children:[e.jsx("div",{className:"memory-stat-label",children:t}),e.jsx("div",{className:"memory-stat-value",children:a}),i&&e.jsx("div",{className:"memory-stat-sub muted",children:i})]})]})}function uo({n:s}){return e.jsxs("span",{style:{position:"relative",display:"inline-block"},children:[e.jsx(ye,{size:14}),e.jsx("span",{className:"memory-mini-badge",children:s})]})}function ho({refreshKey:s}){const t=re(),a=Te(),[i,n]=r.useState([]),[o,c]=r.useState(null),[l,h]=r.useState(!0),[p,x]=r.useState(""),[d,m]=r.useState(null),[u,g]=r.useState(!1),[N,z]=r.useState(null),[R,b]=r.useState([]),w=async()=>{var S;h(!0);try{const[y,M]=await Promise.all([$.get("/memory/notes").catch(()=>({notes:[]})),$.get("/memory/obsidian/tree").catch(()=>({tree:null}))]);n(y.notes||[]),c(M.tree),N&&!((S=y.notes)!=null&&S.find(P=>P.relPath===N))&&(z(null),b([]))}catch(y){t.error(`Vault load failed: ${y.message}`)}finally{h(!1)}};r.useEffect(()=>{w()},[s]),r.useEffect(()=>{if(!p.trim()){m(null);return}g(!0);const S=setTimeout(async()=>{try{const y=await $.get(`/memory/search?q=${encodeURIComponent(p)}&limit=50`),M=new Set((y.results||[]).map(P=>P.relPath));m(i.filter(P=>M.has(P.relPath)))}catch(y){t.error(`Search failed: ${y.message}`)}finally{g(!1)}},240);return()=>clearTimeout(S)},[p,i,t]);const T=async S=>{z(S);try{const y=await $.get(`/memory/obsidian/backlinks?note=${encodeURIComponent(S)}`);b(y.backlinks||[])}catch{b([])}},j=()=>{a.open({title:"New note",width:720,children:e.jsx(sa,{mode:"create",onSave:async(S,y,M)=>{try{await $.post("/memory/notes",{path:S,frontmatter:y,body:M}),t.success(`Created ${S}.`),a.close(),await w(),T(S)}catch(P){t.error(`Create failed: ${P.message}`)}},onCancel:()=>a.close()})})},k=async S=>{try{const y=await $.get(`/memory/notes/${S.split("/").map(encodeURIComponent).join("/")}`);a.open({title:`Edit ${S}`,width:720,children:e.jsx(sa,{mode:"edit",initial:{relPath:y.relPath,frontmatter:y.frontmatter,body:y.body},onSave:async(M,P,C)=>{try{await $.put(`/memory/notes/${M.split("/").map(encodeURIComponent).join("/")}`,{frontmatter:P,body:C}),t.success(`Saved ${M}.`),a.close(),await w(),T(M)}catch(D){t.error(`Save failed: ${D.message}`)}},onCancel:()=>a.close()})})}catch(y){t.error(`Load failed: ${y.message}`)}},f=async S=>{if(confirm(`Delete ${S}? This cannot be undone.`))try{await $.del(`/memory/notes/${S.split("/").map(encodeURIComponent).join("/")}`),t.success(`Deleted ${S}.`),N===S&&z(null),await w()}catch(y){t.error(`Delete failed: ${y.message}`)}},v=r.useMemo(()=>[...i].sort((S,y)=>y.mtime-S.mtime),[i]),L=d??v;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(Y,{variant:"outlined",className:"memory-tree-card",children:[e.jsxs(ae,{children:[e.jsx(Pe,{size:14})," Folders"]}),e.jsx(ne,{children:o?`${La(o)} folder(s)`:"no vault"}),e.jsx("div",{className:"memory-tree-body",children:o?e.jsx(Ea,{node:o,depth:0,onSelect:T,selected:N}):null})]}),e.jsxs("div",{className:"memory-obsidian-list-col",children:[e.jsxs("div",{className:"memory-list-toolbar",children:[e.jsxs("div",{className:"search-input",children:[e.jsx(ye,{size:14,"aria-hidden":!0}),e.jsx("label",{htmlFor:"obsidian-search",className:"sr-only",children:"Search notes"}),e.jsx("input",{id:"obsidian-search",type:"text",className:"input",placeholder:"Search notes…",value:p,onChange:S=>x(S.target.value),"aria-label":"Search notes"}),p&&e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>x(""),"aria-label":"Clear search",children:e.jsx(Ne,{size:12})})]}),e.jsxs(A,{variant:"primary",size:"sm",onClick:j,children:[e.jsx(Dn,{size:12})," New note"]}),e.jsx(A,{variant:"ghost",size:"sm",onClick:w,title:"Refresh",children:e.jsx(ce,{size:12})})]}),u&&e.jsx("div",{className:"muted text-sm",children:"Searching…"}),L.length===0?e.jsx(pe,{icon:e.jsx(we,{size:28}),title:"No notes",message:i.length===0?'No notes in this vault yet. Click "New note" to create one.':`No notes match "${p}".`}):e.jsx("ul",{className:"memory-note-list",children:L.map(S=>e.jsxs("li",{className:K("memory-note-card",N===S.relPath&&"memory-note-card-active"),children:[e.jsxs("button",{type:"button",className:"memory-note-card-main",onClick:()=>T(S.relPath),children:[e.jsxs("div",{className:"memory-note-card-title",children:[e.jsx(we,{size:12}),e.jsx("span",{children:Ia(S)})]}),e.jsxs("div",{className:"memory-note-card-meta",children:[e.jsx("code",{className:"muted",children:S.relPath}),e.jsxs("span",{className:"muted",children:["· ",Re(S.mtime)]}),!S.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:()=>k(S.relPath),"aria-label":`Edit ${S.relPath}`,title:"Edit",children:e.jsx(Ds,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>f(S.relPath),"aria-label":`Delete ${S.relPath}`,title:"Delete",children:e.jsx(Se,{size:12})})]})]},S.relPath))})]}),e.jsx("div",{className:"memory-obsidian-detail-col",children:N?e.jsx(xo,{relPath:N,onClose:()=>z(null)}):e.jsx(pe,{icon:e.jsx(we,{size:28}),title:"Pick a note",message:"Select a note from the list to view its content, frontmatter, and backlinks."})})]})}function Ia(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:K("memory-tree-node memory-tree-node-note",i===s.path&&"memory-tree-node-active"),style:{paddingLeft:6+t*12},onClick:()=>a(s.path),children:[e.jsx(we,{size:11}),e.jsx("span",{children:s.name})]}):e.jsxs("div",{className:"memory-tree-folder",children:[e.jsxs("button",{type:"button",className:"memory-tree-node memory-tree-node-folder",style:{paddingLeft:6+t*12},onClick:()=>o(c=>!c),children:[n?e.jsx(qe,{size:11}):e.jsx(Ye,{size:11}),e.jsx(Pe,{size:11}),e.jsx("span",{children:s.name||"vault"}),s.children&&s.children.length>0&&e.jsx("span",{className:"muted text-xs",children:s.children.length})]}),n&&s.children&&e.jsx("div",{className:"memory-tree-children",children:s.children.map((c,l)=>e.jsx(Ea,{node:c,depth:t+1,onSelect:a,selected:i},`${c.path}-${l}`))})]})}function La(s){return s.type==="note"?0:1+(s.children||[]).reduce((t,a)=>t+La(a),0)}function xo({relPath:s,onClose:t}){var x,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([$.get(`/memory/notes/${s.split("/").map(encodeURIComponent).join("/")}`),$.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 h=Array.isArray((x=a.frontmatter)==null?void 0:x.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:Ia(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 ",We(a.mtime)]})]}),h.length>0&&e.jsx("div",{className:"memory-tag-row",children:h.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 sa({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?po(t.frontmatter):`title: ""
13
+ tags: []
14
+ `),[h,p]=r.useState((t==null?void 0:t.body)||""),[x,d]=r.useState(!1),m=re(),u=async()=>{if(!n.endsWith(".md")){m.error("Path must end in .md");return}let g;try{g=go(c)||{}}catch(N){m.error(`Frontmatter parse failed: ${N.message}`);return}d(!0);try{await a(n,g,h)}finally{d(!1)}};return e.jsxs("div",{className:"memory-editor-modal",children:[e.jsx("label",{className:"field-label",htmlFor:"obsidian-note-path",children:"Path"}),e.jsx("input",{id:"obsidian-note-path",type:"text",className:"input mono",value:n,onChange:g=>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:h,onChange:g=>p(g.target.value),"aria-label":"Body markdown"}),e.jsxs("div",{className:"modal-footer-actions",style:{marginTop:12},children:[e.jsx(A,{variant:"ghost",onClick:i,disabled:x,children:"Cancel"}),e.jsxs(A,{variant:"primary",onClick:u,disabled:x,children:[x&&e.jsx(he,{size:12,className:"memory-spin"}),s==="create"?"Create":"Save"]})]})]})}function po(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(` - ${mt(n)}`)}else if(typeof i=="object"){t.push(`${a}:`);for(const[n,o]of Object.entries(i))t.push(` ${n}: ${mt(o)}`)}else t.push(`${a}: ${mt(i)}`);return t.join(`
15
+ `)}function mt(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 go(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 h={},p=[];let x=!1,d=!1;for(;i+1<a.length;){const m=a[i+1];if(!m.startsWith(" "))break;if(m.startsWith(" - "))x=!0,p.push(ut(m.slice(4))),i++;else{d=!0;const u=m.match(/^ ([A-Za-z_][\w-]*):\s*(.*)$/);u&&(h[u[1]]=ut(u[2])),i++}}t[c]=x&&!d?p:d?h:{}}else t[c]=ut(l);i++}return t}function ut(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 jo({refreshKey:s}){var w,T,j,k;const t=re(),[a,i]=r.useState(null),[n,o]=r.useState(null),[c,l]=r.useState(!0),[h,p]=r.useState(null),[x,d]=r.useState(null),m=async()=>{var f;l(!0);try{const[v,L,S]=await Promise.all([$.get("/memory/git/status").catch(()=>null),$.get("/memory/git/diff").catch(()=>null),$.get("/memory/config/global").catch(()=>null)]);i(v),o(L),d(((f=S==null?void 0:S.config)==null?void 0:f.git)||null)}catch(v){t.error(`Git status failed: ${v.message}`)}finally{l(!1)}};r.useEffect(()=>{m()},[s]);const u=async(f,v,L)=>{p(f);try{await v(),t.success(L),await m()}catch(S){t.error(`${f} failed: ${S.message}`)}finally{p(null)}},g=()=>u("pull",()=>$.post("/memory/git/pull",{}),"Pull complete."),N=()=>u("push",()=>$.post("/memory/git/push",{}),"Push complete."),z=()=>{const f=prompt("Commit message:",`[memory-sync] ${new Date().toISOString().slice(0,10)} vault sync`);f&&u("commit",()=>$.post("/memory/git/commit",{message:f}),"Committed.")},R=()=>u("fetch",()=>$.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 b=a.mode==="local-only";return e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(Y,{variant:"elevated",children:[e.jsxs(ae,{children:[e.jsx(rs,{size:14})," Git sync",b?e.jsx("span",{className:"memory-source-pill-status na",children:"local-only"}):e.jsx("span",{className:K("memory-source-pill-status",a.clean?"on":"warn"),children:a.clean?"clean":"dirty"})]}),e.jsx(ne,{children:b?"Memory is in local-only mode. Configure a shared repo in Settings → Memory to enable git sync.":e.jsxs(e.Fragment,{children:["Branch ",e.jsx("code",{children:a.branch||"—"}),a.ahead?e.jsxs(e.Fragment,{children:[" · ahead ",a.ahead]}):null,a.behind?e.jsxs(e.Fragment,{children:[" · behind ",a.behind]}):null]})}),!b&&e.jsxs("div",{className:"memory-git-status-row",children:[e.jsx(Rs,{ok:a.clean??!1,label:"Working tree"}),e.jsx(Rs,{ok:(a.ahead??0)===0,label:`Ahead: ${a.ahead??0}`}),e.jsx(Rs,{ok:(a.behind??0)===0,label:`Behind: ${a.behind??0}`}),e.jsx(Rs,{ok:(((w=a.modified)==null?void 0:w.length)??0)===0,label:`Modified: ${((T=a.modified)==null?void 0:T.length)??0}`}),e.jsx(Rs,{ok:(((j=a.untracked)==null?void 0:j.length)??0)===0,label:`Untracked: ${((k=a.untracked)==null?void 0:k.length)??0}`})]}),e.jsxs("div",{className:"memory-action-row",children:[e.jsxs(A,{variant:"secondary",size:"sm",onClick:g,disabled:!!h||b,children:[h==="pull"?e.jsx(he,{size:12,className:"memory-spin"}):e.jsx(ua,{size:12}),"Pull"]}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:N,disabled:!!h||b,children:[h==="push"?e.jsx(he,{size:12,className:"memory-spin"}):e.jsx($t,{size:12}),"Push"]}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:z,disabled:!!h||b,children:[h==="commit"?e.jsx(he,{size:12,className:"memory-spin"}):e.jsx(va,{size:12}),"Commit"]}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:R,disabled:!!h||b,children:[h==="fetch"?e.jsx(he,{size:12,className:"memory-spin"}):e.jsx(Pn,{size:12}),"Fetch + sync"]}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:m,disabled:!!h,children:[e.jsx(ce,{size:12})," Refresh"]})]})]}),x&&e.jsxs(Y,{children:[e.jsxs(ae,{children:[e.jsx(ga,{size:14})," Repository"]}),e.jsxs(ne,{children:["Snapshot of ",e.jsx("code",{children:"~/.config/bizar/memory-config.json"})," → git block."]}),e.jsxs("dl",{className:"memory-config-row",children:[e.jsx("dt",{children:"Path"}),e.jsx("dd",{className:"mono ellipsis",title:x.repoPath,children:x.repoPath||"—"}),e.jsx("dt",{children:"Remote"}),e.jsx("dd",{className:"mono ellipsis",title:x.remoteUrl,children:x.remoteUrl||"—"}),e.jsx("dt",{children:"Branch"}),e.jsx("dd",{children:e.jsx("code",{children:x.branch||"main"})}),e.jsx("dt",{children:"Auto-sync"}),e.jsx("dd",{children:x.autoSync?"enabled":"disabled"})]})]}),e.jsxs(Y,{children:[e.jsxs(ae,{children:[e.jsx(Fn,{size:14})," Working-tree diff"]}),e.jsx(ne,{children:n!=null&&n.hasDiff?`${n.files.length} file(s) changed`:"no working-tree changes"}),n&&n.files.length>0&&e.jsx("ul",{className:"memory-diff-files",children:n.files.map(f=>e.jsx("li",{children:e.jsx("code",{children:f})},f))}),n&&n.lines.length>1&&e.jsx("pre",{className:"memory-log-tail mono text-xs",children:n.lines.slice(0,400).join(`
16
+ `)})]})]})}function Rs({ok:s,label:t}){return e.jsxs("span",{className:K("memory-git-status-pill",s?"ok":"warn"),children:[s?e.jsx(Fe,{size:11}):e.jsx(he,{size:11,className:"memory-spin"}),t]})}function fo({refreshKey:s}){const t=re(),[a,i]=r.useState(""),[n,o]=r.useState({lightrag:!0,obsidian:!0}),[c,l]=r.useState(null),[h,p]=r.useState(!1),[x,d]=r.useState(""),m=async g=>{if(g.trim()){p(!0),d(g);try{const N=[...n.lightrag?["lightrag"]:[],...n.obsidian?["obsidian"]:[]],z=await $.post("/memory/semantic-search",{query:g,limit:20,sources:N});l(z.results||[])}catch(N){t.error(`Search failed: ${N.message}`),l([])}finally{p(!1)}}};r.useEffect(()=>{x&&m(x)},[n]),r.useEffect(()=>{x&&m(x)},[s]);const u=r.useMemo(()=>{const g=(c||[]).filter(z=>z.source==="obsidian"),N=(c||[]).filter(z=>z.source==="lightrag");return{obs:g,lr:N}},[c]);return e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(Y,{variant:"elevated",children:[e.jsxs(ae,{children:[e.jsx(ye,{size:14})," Semantic search"]}),e.jsx(ne,{children:"Query both LightRAG (graph-based) and the Obsidian vault in one shot."}),e.jsxs("div",{className:"memory-search-row",children:[e.jsx("label",{htmlFor:"semantic-search-input",className:"sr-only",children:"Semantic search"}),e.jsx("input",{id:"semantic-search-input",type:"text",className:"input",placeholder:"e.g. how are notes indexed?",value:a,onChange:g=>i(g.target.value),onKeyDown:g=>{g.key==="Enter"&&m(a)},disabled:h,"aria-label":"Semantic search query"}),e.jsxs(A,{variant:"primary",onClick:()=>m(a),disabled:h||!a.trim(),children:[h?e.jsx(he,{size:12,className:"memory-spin"}):e.jsx(ye,{size:12}),"Search"]})]}),e.jsxs("div",{className:"memory-source-toggle-row",children:[e.jsx(ta,{active:n.obsidian,onToggle:()=>o(g=>({...g,obsidian:!g.obsidian})),label:"Obsidian",icon:e.jsx(we,{size:11})}),e.jsx(ta,{active:n.lightrag,onToggle:()=>o(g=>({...g,lightrag:!g.lightrag})),label:"LightRAG",icon:e.jsx(_e,{size:11})}),a&&e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>{i(""),l(null),d("")},"aria-label":"Clear",children:e.jsx(Ne,{size:12})})]})]}),h&&e.jsx("div",{className:"view-loading",children:e.jsx(le,{size:"md"})}),!h&&c&&c.length===0&&e.jsx(pe,{icon:e.jsx(ye,{size:28}),title:"No matches",message:`Nothing in scope matched "${x}".`}),u.obs.length>0&&e.jsxs(Y,{children:[e.jsxs(ae,{children:[e.jsx(we,{size:14})," Obsidian (",u.obs.length,")"]}),e.jsx("ul",{className:"memory-search-result-list",children:u.obs.map((g,N)=>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-${N}`))})]}),u.lr.length>0&&e.jsxs(Y,{children:[e.jsxs(ae,{children:[e.jsx(_e,{size:14})," LightRAG (",u.lr.length,")"]}),e.jsx("div",{className:"memory-search-result-list",children:u.lr.map((g,N)=>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(_e,{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-${N}`))})]})]})}function ta({active:s,onToggle:t,label:a,icon:i}){return e.jsxs("button",{type:"button",className:K("memory-toggle-chip",s&&"memory-toggle-chip-active"),onClick:t,"aria-pressed":s,children:[i,e.jsx("span",{children:a})]})}function vo({refreshKey:s}){const t=re(),[a,i]=r.useState(null),[n,o]=r.useState(!0),[c,l]=r.useState(!1),[h,p]=r.useState(""),[x,d]=r.useState(null),[m,u]=r.useState(""),[g,N]=r.useState(!1),[z,R]=r.useState(!1),[b,w]=r.useState(null),[T,j]=r.useState(null),[k,f]=r.useState(null),[v,L]=r.useState(!1),S=async()=>{var _,q;o(!0);try{const[F,V]=await Promise.all([$.get("/memory/config/global").catch(()=>null),$.get("/memory/status").catch(()=>null)]);F?(i(F.config),p(((q=(_=F.config)==null?void 0:_.git)==null?void 0:q.remoteUrl)||"")):i({}),V&&(d(V),u(X=>X||V.vaultRoot||"")),await y()}catch(F){t.error(`Config load failed: ${F.message}`)}finally{o(!1)}},y=async()=>{try{const _=await $.get("/memory/git/status");_.ok&&w({clean:_.clean,branch:_.branch,modified:_.modified,untracked:_.untracked})}catch{}};r.useEffect(()=>{S()},[s]);const M=async()=>{const _=m.trim();if(!_){t.error("Vault path cannot be empty.");return}R(!0);try{const q=await $.get("/memory/status").catch(()=>null);(q==null?void 0:q.initialized)?(await $.post("/memory/config/vault",{vaultRoot:_}),t.success(`Vault path updated to ${_}.`)):(await $.post("/memory/init",{vaultRoot:_}),t.success(`Vault initialised at ${_}.`)),u(_),await S()}catch(q){t.error(`Vault path save failed: ${q.message}`)}finally{R(!1)}},P=async()=>{N(!0);try{await $.post("/memory/init",{}),t.success("Vault initialised."),await S()}catch(_){t.error(`Init failed: ${_.message}`)}finally{N(!1)}},C=async()=>{if(a){l(!0);try{await $.put("/memory/config/global",{git:{remoteUrl:h}}),t.success("Config saved.")}catch(_){t.error(`Save failed: ${_.message}`)}finally{l(!1)}}},D=async _=>{j(_);try{if(_==="pull"){const q=await $.post("/memory/git/pull",{});q.ok?t.success("Pull successful."):t.error(`Pull failed: ${q.output||"unknown error"}`)}else if(_==="push")(await $.post("/memory/git/push",{})).ok?t.success("Push successful."):t.error("Push failed.");else if(_==="commit"){const q=await $.post("/memory/git/commit",{});q.ok?t.success(`Committed: ${q.message}`):t.error("Commit failed.")}await y()}catch(q){t.error(`${_} failed: ${q.message}`)}finally{j(null)}},Q=async()=>{L(!0);try{const _=await $.post("/memory/test-git",{});f(_.checks)}catch(_){t.error(`Test failed: ${_.message}`)}finally{L(!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 O=!!(x!=null&&x.initialized),J=(x==null?void 0:x.vaultRoot)??"";return e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(Y,{children:[e.jsxs(ae,{children:[e.jsx(qt,{size:14})," Vault location"]}),e.jsxs(ne,{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(_s,{label:"Current path",inline:!0,children:[e.jsx("span",{className:"memory-vault-path mono","data-testid":"memory-current-vault-path",children:J||e.jsx("span",{className:"muted",children:"not initialised"})}),O?e.jsxs("span",{className:"memory-pill memory-pill-ok",style:{marginLeft:8},title:"Vault folder exists on disk",children:[e.jsx(Fe,{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(Ps,{size:10})," not initialised"]})]}),e.jsxs(_s,{label:"Set path",children:[e.jsx("input",{type:"text",className:"input mono",value:m,onChange:_=>u(_.target.value),placeholder:"~/.bizar_memory","aria-label":"Vault path","data-testid":"memory-vault-path-input"}),e.jsx("span",{className:"field-hint",children:O?"Save to update the working path.":"Save and initialise will create this folder if it does not exist."})]})]}),e.jsxs("div",{className:"memory-action-row",style:{marginTop:12},children:[e.jsxs(A,{variant:"primary",onClick:M,disabled:z||g||!m.trim(),"data-testid":"memory-save-vault-path",children:[z?e.jsx(he,{size:12,className:"memory-spin"}):e.jsx(bs,{size:12}),O?"Save path":"Save and initialise"]}),!O&&e.jsxs(A,{variant:"secondary",onClick:P,disabled:g||z,"data-testid":"memory-init-vault",children:[g?e.jsx(he,{size:12,className:"memory-spin"}):e.jsx(qt,{size:12}),"Initialise default"]})]})]}),e.jsxs(Y,{children:[e.jsxs(ae,{children:[e.jsx(rs,{size:14})," Git sync"]}),e.jsx(ne,{children:"Configure the git remote and sync your memory vault."}),e.jsxs("div",{className:"memory-config-form",children:[e.jsx(_s,{label:"Remote URL",children:e.jsx("input",{type:"text",className:"input mono",value:h,onChange:_=>p(_.target.value),placeholder:"git@github.com:org/repo.git"})}),b&&e.jsxs(_s,{label:"Status",inline:!0,children:[e.jsx("span",{className:K("memory-pill",b.clean?"memory-pill-ok":"memory-pill-warn"),children:b.clean?"clean":"dirty"}),b.branch&&e.jsxs("span",{className:"muted",style:{marginLeft:8},children:[e.jsx(rs,{size:12,style:{display:"inline"}})," ",b.branch]}),!b.clean&&b.modified!==void 0&&e.jsxs("span",{className:"muted",style:{marginLeft:8},children:[b.modified," modified, ",b.untracked," untracked"]})]})]}),e.jsxs("div",{className:"memory-action-row",style:{marginTop:12},children:[e.jsxs(A,{variant:"secondary",onClick:()=>D("pull"),disabled:T!==null,children:[T==="pull"?e.jsx(he,{size:12,className:"memory-spin"}):e.jsx(ls,{size:12}),"Pull"]}),e.jsxs(A,{variant:"secondary",onClick:()=>D("commit"),disabled:T!==null,children:[T==="commit"?e.jsx(he,{size:12,className:"memory-spin"}):e.jsx(va,{size:12}),"Commit"]}),e.jsxs(A,{variant:"secondary",onClick:()=>D("push"),disabled:T!==null,children:[T==="push"?e.jsx(he,{size:12,className:"memory-spin"}):e.jsx(On,{size:12}),"Push"]})]})]}),e.jsxs(Y,{children:[e.jsxs(ae,{children:[e.jsx(ft,{size:14})," Connection tests"]}),e.jsx(ne,{children:"Verify the configured git remote is reachable."}),e.jsxs("div",{className:"memory-action-row",children:[e.jsxs(A,{variant:"secondary",onClick:Q,disabled:v,children:[v?e.jsx(he,{size:12,className:"memory-spin"}):e.jsx(ft,{size:12}),"Test git connection"]}),e.jsxs(A,{variant:"primary",onClick:C,disabled:c,children:[c?e.jsx(he,{size:12,className:"memory-spin"}):e.jsx(bs,{size:12}),"Save config"]})]}),k&&k.length>0&&e.jsx("ul",{className:"memory-check-list",style:{marginTop:12},children:k.map((_,q)=>e.jsxs("li",{className:"memory-check-row",children:[e.jsx("span",{className:"memory-check-icon",children:e.jsx("span",{className:K("memory-pill",_.pass?"memory-pill-ok":"memory-pill-warn"),children:_.pass?"OK":"FAIL"})}),e.jsx("span",{className:"memory-check-name",children:_.name}),e.jsx("span",{className:"memory-check-detail muted",children:_.detail})]},q))})]})]})}function _s({label:s,children:t,inline:a}){return a?e.jsxs("div",{className:"memory-config-row-inline",children:[e.jsx("div",{className:"memory-config-row-label",id:`cfg-${s.replace(/\s+/g,"-").toLowerCase()}`,children:s}),e.jsx("div",{className:"memory-config-row-control",role:"group","aria-labelledby":`cfg-${s.replace(/\s+/g,"-").toLowerCase()}`,children:t})]}):e.jsxs("label",{className:"memory-config-row-stack",children:[e.jsx("span",{children:s}),t]})}const Ge=800,aa=60,ht={default:"#8b5cf6",note:"#8b5cf6",entity:"#34d399",concept:"#fbbf24",root:"#f87171"};function yo(s,t){return ht[s]||ht[t]||ht.default}function bo(s){return 6+Math.min(s.size*2,10)}function No(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,h)=>{const p=h/s.length*Math.PI*2,x=Ge*.28;return{...l,x:Ge/2+x*Math.cos(p)+(Math.random()-.5)*40,y:Ge/2+x*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<aa;l++){const h=1-l/aa;for(let d=0;d<i.length;d++)for(let m=d+1;m<i.length;m++){const u=i[d],g=i[m],N=g.x-u.x,z=g.y-u.y,R=Math.sqrt(N*N+z*z)||1,b=400*h/(R*R),w=N/R*b,T=z/R*b;u.vx-=w,u.vy-=T,g.vx+=w,g.vy+=T}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,N=u.y-m.y,z=Math.sqrt(g*g+N*N)||1,b=(z-80)*.08*h,w=g/z*b,T=N/z*b;m.vx+=w,m.vy+=T,u.vx-=w,u.vy-=T}const p=Ge/2,x=Ge/2;for(const d of i)d.vx+=(p-d.x)*.01*h,d.vy+=(x-d.y)*.01*h;for(const d of i)d.vx*=.85,d.vy*=.85,d.x+=d.vx,d.y+=d.vy,d.x=Math.max(20,Math.min(Ge-20,d.x)),d.y=Math.max(20,Math.min(Ge-20,d.y))}return i}function ko({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}),h=r.useRef(null),[p,x]=r.useState(null),[d,m]=r.useState(null),u=r.useMemo(()=>No(s.nodes,s.edges),[s.nodes,s.edges]),g=r.useMemo(()=>{const v=new Map;for(const L of u)v.set(L.id,L);return v},[u]),N=r.useCallback(v=>{v.target.closest(".memory-graph-node")||(c.current=!0,l.current={x:v.clientX,y:v.clientY,tx:n.x,ty:n.y})},[n]),z=r.useCallback(v=>{if(!c.current)return;const L=v.clientX-l.current.x,S=v.clientY-l.current.y;o(y=>({...y,x:l.current.tx+L,y:l.current.ty+S}))},[]),R=r.useCallback(()=>{c.current=!1},[]),b=r.useCallback(v=>{v.preventDefault();const L=v.deltaY<0?1.1:.9,S=i.current;if(!S)return;const y=S.getBoundingClientRect(),M=v.clientX-y.left,P=v.clientY-y.top;o(C=>{const D=Math.max(.2,Math.min(4,C.scale*L)),Q=D/C.scale;return{x:M-(M-C.x)*Q,y:P-(P-C.y)*Q,scale:D}})},[]),w=r.useCallback(v=>{const L=Array.from(v.touches);if(L.length===2){const[S,y]=L;h.current=Math.hypot(y.clientX-S.clientX,y.clientY-S.clientY)}else L.length===1&&(c.current=!0,l.current={x:L[0].clientX,y:L[0].clientY,tx:n.x,ty:n.y})},[n]),T=r.useCallback(v=>{const L=Array.from(v.touches);if(L.length===2&&h.current!==null){const[S,y]=L,M=Math.hypot(y.clientX-S.clientX,y.clientY-S.clientY),P=M/h.current;h.current=M,o(C=>({...C,scale:Math.max(.2,Math.min(4,C.scale*P))}))}else if(L.length===1&&c.current){const S=L[0].clientX-l.current.x,y=L[0].clientY-l.current.y;o(M=>({...M,x:l.current.tx+S,y:l.current.ty+y}))}},[]),j=r.useCallback(()=>{c.current=!1,h.current=null},[]),k=r.useCallback(v=>{x(v.id===p?null:v.id),t==null||t(v)},[p,t]),f=Math.max(.5,1/Math.log2(n.scale+1));return e.jsx("svg",{ref:i,className:K("memory-graph-canvas",a),viewBox:`0 0 ${Ge} ${Ge}`,style:{width:"100%",height:"100%",minHeight:400,cursor:c.current?"grabbing":"grab"},onMouseDown:N,onMouseMove:z,onMouseUp:R,onMouseLeave:R,onWheel:b,onTouchStart:w,onTouchMove:T,onTouchEnd:j,children:e.jsxs("g",{transform:`translate(${n.x},${n.y}) scale(${n.scale})`,children:[s.edges.map((v,L)=>{const S=g.get(v.source),y=g.get(v.target);if(!S||!y)return null;const M=d===v.source||d===v.target||p===v.source||p===v.target;return e.jsx("line",{x1:S.x,y1:S.y,x2:y.x,y2:y.y,stroke:M?"#8b5cf6":"#2d3648",strokeWidth:M?f*2:f,strokeOpacity:M?.9:.5},`e-${L}`)}),u.map(v=>{const L=bo(v),S=yo(v.group,v.type),y=p===v.id,M=d===v.id;return e.jsxs("g",{className:"memory-graph-node",transform:`translate(${v.x},${v.y})`,onClick:()=>k(v),onMouseEnter:()=>m(v.id),onMouseLeave:()=>m(null),style:{cursor:"pointer"},children:[e.jsx("circle",{r:L+6,fill:"transparent"}),(y||M)&&e.jsx("circle",{r:L+4,fill:S,fillOpacity:.2}),e.jsx("circle",{r:L,fill:S,fillOpacity:y?1:.75,stroke:y?"#fff":S,strokeWidth:y?2:1}),n.scale>.5&&e.jsx("text",{y:L+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:v.label.length>20?v.label.slice(0,18)+"…":v.label})]},v.id)})]})})}const wo=[{color:"#8b5cf6",label:"Note / Default"},{color:"#34d399",label:"Entity (LightRAG)"},{color:"#fbbf24",label:"Concept (LightRAG)"},{color:"#f87171",label:"Root / Ungrouped"}];function So({className:s}){return e.jsx("div",{className:K("memory-graph-legend",s),children:wo.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 Co({refreshKey:s}){const t=re(),[a,i]=r.useState({nodes:[],edges:[]}),[n,o]=r.useState(!0),[c,l]=r.useState(null),[h,p]=r.useState(""),[x,d]=r.useState(2),[m,u]=r.useState(""),[g,N]=r.useState(null),[z,R]=r.useState(null),b=r.useCallback(async()=>{var j,k;o(!0),l(null);try{const f=new URLSearchParams({limit:"200"});m&&f.set("root",m),f.set("depth",String(x));const v=await $.get(`/memory/graph?${f}`);i({nodes:v.nodes||[],edges:v.edges||[]}),N({totalNodes:v.totalNodes??((j=v.nodes)==null?void 0:j.length)??0,totalEdges:v.totalEdges??((k=v.edges)==null?void 0:k.length)??0})}catch(f){l(f.message),t.error(`Graph load failed: ${f.message}`)}finally{o(!1)}},[m,x,t]);r.useEffect(()=>{b()},[b,s]);const w=r.useCallback(j=>{R(k=>(k==null?void 0:k.id)===j.id?null:j)},[]),T=h.trim()?{nodes:a.nodes.filter(j=>j.label.toLowerCase().includes(h.toLowerCase())),edges:a.edges.filter(j=>a.nodes.some(k=>k.id===j.source&&k.label.toLowerCase().includes(h.toLowerCase()))||a.nodes.some(k=>k.id===j.target&&k.label.toLowerCase().includes(h.toLowerCase())))}:a;return e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(Y,{children:[e.jsxs(ae,{children:[e.jsx(ya,{size:14})," Memory Graph"]}),e.jsx(ne,{children:"Interactive knowledge graph — LightRAG entities + Obsidian wikilinks. Drag to pan, scroll to zoom."}),e.jsxs("div",{className:"memory-graph-controls",children:[e.jsxs("div",{className:"memory-graph-search-row",children:[e.jsx("label",{htmlFor:"graph-filter",className:"sr-only",children:"Filter nodes"}),e.jsx("input",{id:"graph-filter",type:"text",className:"input",placeholder:"Filter nodes…",value:h,onChange: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:x,onChange:j=>d(parseInt(j.target.value,10)),style:{marginLeft:8,verticalAlign:"middle"}}),x]}),e.jsx("button",{type:"button",className:"icon-btn",onClick:b,title:"Refresh graph",disabled:n,children:e.jsx(ce,{size:14,className:n?"memory-spin":""})})]}),e.jsx(So,{})]})]}),e.jsx(Y,{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(ko,{data:T,onNodeClick:w,className:"memory-graph-canvas-svg"}),h&&e.jsxs("div",{className:"text-xs muted",style:{marginTop:4},children:["Showing ",T.nodes.length," of ",a.nodes.length," nodes"]})]})}),z&&e.jsxs(Y,{children:[e.jsx(ae,{children:z.label}),e.jsx(ne,{children:e.jsx("code",{children:z.id})}),e.jsxs("dl",{className:"memory-config-row",children:[e.jsx("dt",{children:"Type"}),e.jsx("dd",{children:e.jsx("code",{children:z.type})}),e.jsx("dt",{children:"Group"}),e.jsx("dd",{children:e.jsx("code",{children:z.group})}),e.jsx("dt",{children:"Size"}),e.jsx("dd",{children:z.size})]})]}),g&&e.jsx(Y,{children:e.jsxs("div",{className:"memory-graph-stats",children:[e.jsxs("span",{children:[g.totalNodes," node",g.totalNodes!==1?"s":""]}),e.jsx("span",{className:"muted",children:"·"}),e.jsxs("span",{children:[g.totalEdges," edge",g.totalEdges!==1?"s":""]}),h&&e.jsxs("span",{className:"muted",children:["· ",T.nodes.length," shown"]})]})})]})}function zo({onTextExtracted:s}){const t=re(),[a,i]=r.useState(null),[n,o]=r.useState(!1),[c,l]=r.useState(!1),h=r.useCallback(async()=>{l(!0);try{const d=await navigator.mediaDevices.getDisplayMedia({video:{mediaSource:"screen"}}),m=document.createElement("video");m.srcObject=d,await m.play();const 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(N=>N.stop()),m.remove(),u.toBlob(async N=>{if(!N){t.error("Failed to capture screenshot");return}const z=URL.createObjectURL(N);i(z),await p(N)},"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((N,z)=>{m.onload=()=>{const R=m.result,b=R.includes(",")?R.split(",")[1]:R;N(b)},m.onerror=()=>z(new Error("FileReader failed")),m.readAsDataURL(d)}),g=await $.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]),x=r.useCallback(()=>{i(null)},[]);return e.jsxs(Y,{variant:"outlined",className:"screenshot-capture-card",children:[e.jsxs(ae,{children:[e.jsx(at,{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(he,{size:12,className:"spinner"})," Extracting text…"]}),e.jsx(A,{variant:"ghost",size:"sm",onClick:x,disabled:n,children:"Dismiss"})]})]}):e.jsxs("div",{className:"screenshot-capture-empty",children:[e.jsx(at,{size:32,className:"muted"}),e.jsx("p",{className:"muted text-sm",children:"Capture your screen to extract text via OCR."}),e.jsxs(A,{variant:"primary",size:"sm",onClick:h,disabled:c,children:[c?e.jsx(he,{size:12,className:"spinner"}):e.jsx(at,{size:12}),c?"Selecting…":"Capture Screen"]})]})})]})}function Ro(){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(zo,{onTextExtracted:n}),s!==null&&e.jsxs(Y,{variant:"outlined",className:"screenshot-ocr-result-card",children:[e.jsxs(ae,{children:[e.jsx(we,{size:14})," Extracted Text"]}),a&&e.jsxs(ne,{children:["Saved to: ",a]}),e.jsx("div",{className:"screenshot-ocr-text",children:s?e.jsx("pre",{className:"screenshot-ocr-pre mono text-sm",children:s}):e.jsx("p",{className:"muted text-sm",children:"No text was found in the captured image."})})]})]})}function To({refreshKey:s}){return e.jsx("div",{className:"memory-panel-content",children:e.jsx(Y,{variant:"outlined",className:"memory-panel-card",children:e.jsx("div",{className:"memory-panel-body",children:e.jsx(Ro,{})})})})}function $o({refreshKey:s}){const t=re(),[a,i]=r.useState(""),[n,o]=r.useState(""),[c,l]=r.useState(""),[h,p]=r.useState(!1),x=async()=>{if(!c.trim()){t.error("Content is required");return}p(!0);try{const d=await $.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(Y,{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(ba,{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(A,{variant:"primary",size:"sm",onClick:x,disabled:h||!c.trim(),children:[h&&e.jsx(he,{size:12,className:"spinner"}),"Save to Vault"]})})]})})})})}function Ao({vaultPath:s,onSaved:t}){const[a,i]=r.useState(!1),[n,o]=r.useState(!1),c=r.useRef(null),l=r.useRef([]),h=async()=>{try{const d=await navigator.mediaDevices.getUserMedia({audio:!0}),m=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm",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(N=>N.stop()),await x(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))},x=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:N}=await u.json();t==null||t(g,N)}catch(m){console.error("[VoiceRecorder] upload error:",m)}finally{o(!1)}};return e.jsxs("div",{className:"voice-recorder",children:[!a&&!n&&e.jsxs(A,{variant:"accent",size:"sm",onClick:h,"aria-label":"Start recording",children:[e.jsx(Lt,{size:14})," Record"]}),a&&e.jsxs(A,{variant:"danger",size:"sm",onClick:p,"aria-label":"Stop recording",children:[e.jsx(Bn,{size:14})," Stop"]}),n&&e.jsxs(A,{variant:"secondary",size:"sm",disabled:!0,children:[e.jsx(he,{size:14,className:"spinning"})," Transcribing…"]})]})}function Mo({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(At,{size:13}):e.jsx(ks,{size:13})}),e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>t(s.id),"aria-label":"Delete note",title:"Delete note",children:e.jsx(Se,{size:13})})]})]}),s.transcript&&e.jsx("p",{className:"voice-note-transcript",children:s.transcript}),!s.transcript&&e.jsx("p",{className:"voice-note-no-transcript muted text-sm",children:"No transcription available"})]})}function Io({vaultPath:s,refreshKey:t=0}){const[a,i]=r.useState([]),[n,o]=r.useState(""),[c,l]=r.useState(!0),h=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(()=>{h();const d=g=>{try{const N=JSON.parse(g.data);N.type==="voice:updated"&&N.noteId&&i(z=>z.map(R=>{var b;return R.id===N.noteId?{...R,transcript:((b=N.patch)==null?void 0:b.transcript)??R.transcript}:R}))}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)}},x=a.filter(d=>{var m;return!n||(((m=d.transcript)==null?void 0:m.toLowerCase().includes(n.toLowerCase()))??!1)});return e.jsxs(Y,{children:[e.jsxs(ae,{children:[e.jsx(Lt,{size:14})," Voice Notes"]}),e.jsx(ne,{children:"Record and transcribe audio notes into your vault"}),e.jsx("div",{className:"memory-search-row",children:e.jsx("input",{type:"text",className:"input search-input",value:n,onChange:d=>o(d.target.value),placeholder:"Search transcripts…","aria-label":"Search voice notes"})}),e.jsx("div",{className:"voice-recorder-row",children:e.jsx(Ao,{vaultPath:s,onSaved:h})}),c?e.jsx("p",{className:"muted text-sm",children:"Loading notes…"}):x.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:x.map(d=>e.jsx(Mo,{note:d,onDelete:p},d.id))})]})}const Eo=[{id:"overview",label:"Overview",icon:ca},{id:"lightrag",label:"LightRAG",icon:_e},{id:"obsidian",label:"Obsidian Vault",icon:we},{id:"git",label:"Git Sync",icon:rs},{id:"semantic",label:"Semantic Search",icon:ye},{id:"config",label:"Config",icon:Ct},{id:"graph",label:"Memory Graph",icon:ya},{id:"webclip",label:"Web Clip",icon:ba},{id:"screenshot",label:"Screenshot OCR",icon:Un},{id:"voice",label:"Voice Notes",icon:Lt}];function Lo(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]),h=()=>{switch(a){case"overview":return e.jsx(oo,{refreshKey:n,onRefresh:c,setActiveSubPanel:i});case"lightrag":return e.jsx(mo,{refreshKey:n});case"obsidian":return e.jsx(ho,{refreshKey:n});case"git":return e.jsx(jo,{refreshKey:n});case"semantic":return e.jsx(fo,{refreshKey:n});case"config":return e.jsx(vo,{refreshKey:n});case"graph":return e.jsx(Co,{refreshKey:n});case"webclip":return e.jsx($o,{refreshKey:n});case"screenshot":return e.jsx(To,{refreshKey:n});case"voice":return e.jsx(Io,{refreshKey:n});default:return e.jsxs(Y,{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(_e,{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(ce,{size:14})})})]}),e.jsxs("div",{className:"memory-tab-body",children:[e.jsx("nav",{className:"memory-source-rail","aria-label":"Memory sources",children:Eo.map(p=>{const x=p.icon,d=a===p.id;return e.jsxs("button",{type:"button",role:"tab","aria-selected":d,className:K("memory-source-button",d&&"memory-source-button-active"),onClick:()=>i(p.id),children:[e.jsx(x,{size:16,"aria-hidden":!0}),e.jsx("span",{children:p.label})]},p.id)})}),e.jsx("div",{className:"memory-main",children:h()},a)]})]})}const Do=Oe.memo(Lo),Ts=[{id:"1h",label:"Last hour",ms:60*60*1e3},{id:"1d",label:"Last day",ms:24*60*60*1e3},{id:"7d",label:"Last 7 days",ms:7*24*60*60*1e3},{id:"30d",label:"Last 30 days",ms:30*24*60*60*1e3},{id:"all",label:"All time",ms:0}];function Po(s,t,a,i){const n=a.has(s.id);return e.jsxs(Y,{className:"history-project",style:{marginBottom:4},children:[e.jsxs("div",{className:"history-project-head",children:[e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4,minWidth:0,flex:1},children:[e.jsxs("div",{className:"history-project-name",children:[e.jsx(Pe,{size:16})," ",s.name]}),e.jsx("div",{className:"history-project-meta",children:s.path})]}),e.jsxs("div",{className:"history-project-stats",children:[e.jsxs("span",{className:"history-project-stat",children:[e.jsx("span",{className:"history-project-stat-num",children:s.tasks.done}),e.jsxs("span",{className:"muted",children:["/ ",s.tasks.total," done"]})]}),s.tasks.doing>0&&e.jsxs("span",{className:"history-project-stat",children:[e.jsx("span",{className:"history-project-stat-num",children:s.tasks.doing}),e.jsx("span",{className:"muted",children:"doing"})]}),s.tasks.blocked>0&&e.jsxs("span",{className:"history-project-stat",children:[e.jsx("span",{className:"history-project-stat-num",children:s.tasks.blocked}),e.jsx("span",{className:"muted",children:"blocked"})]}),e.jsxs("span",{className:"history-project-stat",children:[e.jsx(we,{size:11})," ",e.jsx("span",{className:"history-project-stat-num",children:s.plans}),e.jsxs("span",{className:"muted",children:[" plan",s.plans===1?"":"s"]})]}),s.lastAccessed&&e.jsx("span",{className:"history-project-stat",children:e.jsxs("span",{className:"muted",children:["last opened ",Re(s.lastAccessed)]})})]}),e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>i(s.id),"aria-label":n?"Collapse":"Expand",children:n?e.jsx(qe,{size:14}):e.jsx(Ye,{size:14})})]}),n&&e.jsx("div",{className:"history-timeline-mini",children:t.length===0?e.jsx("div",{className:"muted",style:{padding:"12px 8px",fontSize:12},children:"No events in this time range."}):t.slice(-100).reverse().map((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 Fo({snapshot:s}){var z,R;const t=re(),[a,i]=r.useState(null),[n,o]=r.useState(!0),[c,l]=r.useState("1d"),[h,p]=r.useState(new Set),[x,d]=r.useState(0),m=async b=>{try{const w=b?`?since=${encodeURIComponent(b)}&limit=1000`:"?limit=1000",T=await $.get(`/history${w}`);i(T),p(new Set(T.projects.filter(j=>T.events.some(k=>k.projectId===j.id)).map(j=>j.id)))}catch(w){t.error(`History load failed: ${w.message}`)}finally{o(!1)}};r.useEffect(()=>{o(!0);const b=Ts.find(w=>w.id===c)||Ts[1];if(b.ms>0){const w=new Date(Date.now()-b.ms).toISOString();m(w)}else m()},[c]),r.useEffect(()=>{const b=setInterval(()=>d(w=>w+1),3e4);return()=>clearInterval(b)},[]);const u=new Map;for(const b of(a==null?void 0:a.events)||[]){const w=b.projectId||"global";u.has(w)||u.set(w,[]),u.get(w).push(b)}const g=b=>{p(w=>{const T=new Set(w);return T.has(b)?T.delete(b):T.add(b),T})},N=()=>{if(!a)return;const b=new Blob([JSON.stringify(a,null,2)],{type:"application/json"}),w=URL.createObjectURL(b),T=document.createElement("a");T.href=w,T.download=`bizar-history-${new Date().toISOString().replace(/[:.]/g,"-")}.json`,T.click(),URL.revokeObjectURL(w),t.success("History exported.")};return e.jsxs("div",{className:"view view-history","data-tick":x,children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(Is,{size:18})," 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 ",Re(a.stats.lastTs)]})]})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs("div",{className:"tasks-toolbar-group",children:[e.jsx(_n,{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:b=>l(b.target.value),title:"Time range","aria-label":"Time range",children:Ts.map(b=>e.jsx("option",{value:b.id,children:b.label},b.id))})]}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:()=>{o(!0);const b=Ts.find(w=>w.id===c)||Ts[1];b.ms>0?m(new Date(Date.now()-b.ms).toISOString()):m()},children:[e.jsx(ce,{size:14})," Refresh"]}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:N,children:[e.jsx(ls,{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(Y,{children:[e.jsxs(ae,{children:[e.jsx(Pe,{size:14})," No projects"]}),e.jsx(ne,{children:"Register a project in Overview to start tracking history."})]}),a.projects.length>0&&e.jsx(Dt,{items:a.projects,itemHeight:70,height:Math.min(a.projects.length*70,500),className:"history-virtual-list",renderItem:b=>Po(b,u.get(b.id)||[],h,g)}),u.has("global")&&e.jsxs(Y,{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(Is,{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((b,w)=>e.jsxs("div",{className:"history-timeline-row",children:[e.jsx("span",{className:"history-timeline-ts",children:new Date(b.ts).toLocaleTimeString()}),e.jsx("span",{className:"history-timeline-kind",children:b.kind||"event"}),e.jsxs("span",{className:"history-timeline-msg",title:String(b.text||b.title||""),children:[b.author?`@${b.author} `:"",String(b.text??b.title??b.name??"")]})]},w))})]}),((R=a.stats)==null?void 0:R.counts)&&Object.keys(a.stats.counts).length>0&&e.jsxs(Y,{children:[e.jsx(ae,{children:"Event counts by kind"}),e.jsxs(ne,{children:[a.stats.lines," total lines in log"]}),e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:8,marginTop:8},children:Object.entries(a.stats.counts).sort((b,w)=>w[1]-b[1]).slice(0,30).map(([b,w])=>e.jsxs("span",{className:K("tag","tag-neutral"),style:{fontFamily:"var(--font-mono)"},children:[b,": ",w]},b))})]})]})]})}const ve={top:16,right:20,bottom:40,left:52};function Oo({series:s,height:t=280,onHover:a,className:i}){const n=r.useRef(null),[o,c]=r.useState(null),{labels:l,requests:h,tokens:p}=s,x=l.length;if(x===0)return e.jsx("div",{className:K("usage-chart-empty",i),style:{height:t},children:e.jsx("span",{children:"No data for this range"})});const d=600-ve.left-ve.right,m=t-ve.top-ve.bottom,u=Math.max(...h,1),g=Math.max(...p,1),N=Math.max(4,Math.min(24,Math.floor(d/x)-4)),z=(d-N*x)/(x+1);function R(M){return ve.left+z+M*(N+z)}function b(M){return M/u*m*.75}function w(M){return ve.top+m-M/g*m*.75}const T=p.map((M,P)=>`${R(P)+N/2},${w(M)}`).join(" "),j=[0,.25,.5,.75,1].map(M=>({y:ve.top+m-M*m*.75,label:M===0?"0":`${Math.round(u*M).toLocaleString()}`})),k=[0,.25,.5,.75,1].map(M=>({y:ve.top+m-M*m*.75,label:M===0?"0":`${Math.round(g*M/1e3)}k`})),f=Math.max(1,Math.floor(x/7)),v=l.map((M,P)=>({i:P,l:M,x:R(P)+N/2})).filter((M,P)=>P%f===0),L=r.useCallback(M=>{if(!n.current)return;const P=n.current.getBoundingClientRect(),C=(M.clientX-P.left)*(600/P.width),D=(M.clientY-P.top)*(t/P.height),Q=C-ve.left,O=Math.round((Q-z/2)/(N+z)),J=Math.max(0,Math.min(x-1,O));c({index:J,x:M.clientX-P.left,y:M.clientY-P.top}),a==null||a(J,C,D)},[x,N,z,a,t]),S=r.useCallback(()=>{c(null),a==null||a(null,0,0)},[a]),y=o;return e.jsxs("div",{ref:n,className:K("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:L,onMouseLeave:S,children:[j.map((M,P)=>e.jsx("line",{x1:ve.left,y1:M.y,x2:600-ve.right,y2:M.y,stroke:"var(--border)",strokeWidth:1,strokeDasharray:"4,3",opacity:.5},`grid-${P}`)),j.map((M,P)=>e.jsx("text",{x:ve.left-6,y:M.y+4,textAnchor:"end",fontSize:10,fill:"var(--text-muted)",fontFamily:"var(--font-mono, ui-monospace, monospace)",children:M.label},`ly-${P}`)),k.map((M,P)=>e.jsx("text",{x:600-ve.right+6,y:M.y+4,textAnchor:"start",fontSize:10,fill:"var(--text-muted)",fontFamily:"var(--font-mono, ui-monospace, monospace)",children:M.label},`ry-${P}`)),h.map((M,P)=>{const C=b(M),D=R(P),Q=ve.top+m-C;return e.jsx("rect",{x:D,y:Q,width:N,height:C,rx:2,fill:((y==null?void 0:y.index)===P,"var(--accent)"),opacity:(y==null?void 0:y.index)===P?1:.75,style:{transition:"opacity 120ms ease"}},`bar-${P}`)}),e.jsx("polyline",{points:T,fill:"none",stroke:"var(--warning, #d29922)",strokeWidth:2,strokeLinejoin:"round",strokeLinecap:"round",opacity:.9}),p.map((M,P)=>e.jsx("circle",{cx:R(P)+N/2,cy:w(M),r:(y==null?void 0:y.index)===P?5:3,fill:"var(--warning, #d29922)",opacity:(y==null?void 0:y.index)===P?1:.7,style:{transition:"r 120ms ease"}},`dot-${P}`)),v.map(({i:M,l:P,x:C})=>e.jsx("text",{x:C,y:ve.top+m+18,textAnchor:"middle",fontSize:10,fill:"var(--text-muted)",fontFamily:"var(--font-mono, ui-monospace, monospace)",children:P},`xl-${M}`)),e.jsx("line",{x1:ve.left,y1:ve.top+m,x2:600-ve.right,y2:ve.top+m,stroke:"var(--border)",strokeWidth:1})]}),y!==null&&e.jsxs("div",{className:"usage-chart-tooltip",style:{left:Math.min(y.x+12,460),top:y.y-60},children:[e.jsx("div",{className:"usage-tooltip-date",children:l[y.index]}),e.jsxs("div",{className:"usage-tooltip-row",children:[e.jsx("span",{className:"usage-tooltip-dot",style:{background:"var(--accent)"}}),e.jsx("span",{children:"Requests:"}),e.jsx("strong",{children:h[y.index].toLocaleString()})]}),e.jsxs("div",{className:"usage-tooltip-row",children:[e.jsx("span",{className:"usage-tooltip-dot",style:{background:"var(--warning, #d29922)"}}),e.jsx("span",{children:"Tokens:"}),e.jsx("strong",{children:p[y.index].toLocaleString()})]})]})]})}function ts({label:s,col:t,sortKey:a,sortDir:i,onSort:n}){const o=a===t;return e.jsxs("th",{className:K("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 Bo({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(ts,{label:"Model",col:"modelId",sortKey:t,sortDir:a,onSort:i}),e.jsx(ts,{label:"Requests",col:"requests",sortKey:t,sortDir:a,onSort:i}),e.jsx(ts,{label:"Prompt Tok",col:"promptTokens",sortKey:t,sortDir:a,onSort:i}),e.jsx(ts,{label:"Compl Tok",col:"completionTokens",sortKey:t,sortDir:a,onSort:i}),e.jsx(ts,{label:"Total Tok",col:"totalTokens",sortKey:t,sortDir:a,onSort:i}),e.jsx(ts,{label:"Avg Latency",col:"avgLatencyMs",sortKey:t,sortDir:a,onSort:i}),e.jsx(ts,{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:K("mono",n.errors>0&&"is-err"),children:n.errors>0?n.errors:"—"})]},`${n.providerId}::${n.modelId}`))})]})})}function Uo({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:K("minimax-sub-tab",a==="quota"&&"is-active"),onClick:()=>i("quota"),children:[e.jsx(St,{size:13})," Token Plan"]}),e.jsxs("button",{className:K("minimax-sub-tab",a==="analytics"&&"is-active"),onClick:()=>i("analytics"),children:[e.jsx(Na,{size:13})," Usage Analytics"]})]}),a==="quota"?e.jsx(_o,{activeTab:s,setActiveTab:t}):e.jsx(Wo,{toast:n})]})}function _o({activeTab:s,setActiveTab:t}){var X;const a=re(),[i,n]=r.useState(null),[o,c]=r.useState(null),[l,h]=r.useState(null),[p,x]=r.useState(!0),[d,m]=r.useState(!1),[u,g]=r.useState(null),[N,z]=r.useState(null),[R,b]=r.useState(!1),[w,T]=r.useState(0),[j,k]=r.useState(!1),[f,v]=r.useState(null),[L,S]=r.useState(""),[y,M]=r.useState(!1),[P,C]=r.useState(!1),D=r.useCallback(async()=>{x(!0),g(null);try{const[B,se,xe]=await Promise.all([$.get("/minimax/status"),$.get("/minimax/remains"),$.get("/minimax/onboarding")]);n(B),c(se),h(xe),B.configured&&T(4)}catch(B){g(B.message||"Failed to load MiniMax data")}finally{x(!1)}},[]);r.useEffect(()=>{D()},[D]);const Q=r.useCallback(async()=>{try{await $.post("/minimax/onboarding",{dismissedAt:Date.now()}),h(B=>B&&{...B,dismissedAt:Date.now()})}catch{}},[]),O=r.useCallback(async()=>{if(!L.trim()){a.error("Paste a Subscription Key first.");return}k(!0),v(null);try{const B=await $.post("/minimax/test",{prompt:"Reply with a single word: pong",model:"MiniMax-M3",maxTokens:16});if(v(B),B.ok){T(3),a.success("Key works. Saving…");try{await $.post("/minimax/onboarding/save-key",{key:L.trim(),groupId:"default"}),_(),a.success("Subscription Key saved.")}catch(se){a.error(`Save failed: ${se.message}`)}D()}else a.error(`Verification failed: ${B.message??B.error??"unknown"}`)}catch(B){a.error(`Test request failed: ${B.message}`)}finally{k(!1)}},[L,a,D]),J=r.useCallback(async()=>{if(!L.trim()){a.error("Paste a Subscription Key first.");return}C(!0);try{const B=await $.post("/minimax/onboarding/save-key",{key:L.trim(),groupId:"default"});if(!B.ok){a.error(`Save failed: ${B.message??B.error??"unknown"}`);return}S(""),_(),a.success("Subscription Key saved. Loading quota…"),D()}catch(B){a.error(`Save failed: ${B.message}`)}finally{C(!1)}},[L,a,D]),_=r.useCallback(async()=>{try{await $.del("/minimax/cache")}catch{}},[]),q=r.useCallback(async()=>{m(!0),g(null);try{await $.post("/minimax/remains/refresh"),await D(),a.success("Refreshed")}catch(B){a.error(`Refresh failed: ${B.message}`)}finally{m(!1)}},[D,a]),F=r.useCallback(async()=>{var B;b(!0),z(null);try{const se=await $.post("/minimax/test",{prompt:"Reply with a single word: pong",model:"MiniMax-M3",maxTokens:16});z(se),se.ok?a.success(`Test ok — used ${((B=se.usage)==null?void 0:B.total_tokens)??"?"} tokens`):a.error(`Test failed: ${se.message??se.error??"unknown"}`)}catch(se){a.error(`Test request failed: ${se.message}`)}finally{b(!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(Ho,{step:w,setStep:T,keyDraft:L,setKeyDraft:S,showKey:y,setShowKey:M,verifying:j,verifyResult:f,onVerify:O,onSkip:async()=>{await Q(),a.success("Skipped.")},onManualKeySave:J,savingKey:P,status:i}):e.jsxs(e.Fragment,{children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-titles",children:[e.jsxs("h1",{className:"view-title",children:[e.jsx(St,{size:20,style:{verticalAlign:"text-bottom",marginRight:6}}),"MiniMax Token Plan"]}),e.jsxs("p",{className:"view-subtitle",children:["Remaining 5-hour + weekly quota per model. Fetches live from"," ",e.jsx("code",{children:"www.minimax.io/v1/token_plan/remains"}),"."]})]}),e.jsxs("div",{className:"view-header-actions",children:[e.jsxs(A,{variant:"secondary",size:"sm",onClick:()=>t("settings"),title:"Configure your Subscription Key",children:[e.jsx(It,{size:14})," ",i.configured?`Key ${i.apiKeyHint}`:"Add key"]}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:q,disabled:d,children:[d?e.jsx(he,{size:14,className:"spin"}):e.jsx(ce,{size:14})," Refresh"]})]})]}),o&&!o.ok&&e.jsxs("div",{className:"banner banner-err",children:[e.jsx(ke,{size:16}),e.jsxs("span",{children:[e.jsx("strong",{children:"Couldn't load quota"}),": ",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(Ws,{label:"Models tracked",value:String(o.models.length),hint:"Distinct model quotas returned by the API"}),e.jsx(Ws,{label:"Last fetched",value:o.fetchedAt?Vo(o.fetchedAt):"—",hint:"Refreshed on demand + every 60s"}),e.jsx(Ws,{label:"Group",value:o.groupId??"—",hint:"Usually 'default' for an individual team"}),e.jsx(Ws,{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(B=>e.jsx(qo,{model:B},B.model_name))})]}),i.configured&&e.jsxs(Y,{id:"minimax-test",children:[e.jsxs(ae,{children:[e.jsx(es,{size:14})," Test the API key"]}),e.jsxs(ne,{children:["One-shot chat completion to ",e.jsxs("code",{children:[i.chatBaseUrl,"/chat/completions"]}),"."]}),e.jsxs("div",{className:"minimax-test-actions",children:[e.jsxs(A,{onClick:F,disabled:R,variant:"primary",size:"sm",children:[R?e.jsx(he,{size:14,className:"spin"}):e.jsx(es,{size:14})," Send test prompt"]}),e.jsx("code",{className:"minimax-test-prompt",children:'"Reply with a single word: pong"'})]}),N&&e.jsxs("div",{className:K("minimax-test-result",N.ok?"ok":"err"),children:[N.ok?e.jsx(Fe,{size:14}):e.jsx(ke,{size:14}),e.jsx("div",{className:"minimax-test-body",children:N.ok?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"minimax-test-line",children:[e.jsx("strong",{children:"model:"})," ",e.jsx("code",{children:N.model})," ·"," ",e.jsx("strong",{children:"finish:"})," ",N.finishReason??"—"]}),N.content&&e.jsx("div",{className:"minimax-test-content",children:e.jsx("code",{children:N.content})}),N.usage&&e.jsxs("div",{className:"minimax-test-usage",children:[e.jsx("strong",{children:"usage:"})," total ",e.jsx("code",{children:N.usage.total_tokens??"?"})," · prompt"," ",e.jsx("code",{children:N.usage.prompt_tokens??"?"})," · completion"," ",e.jsx("code",{children:N.usage.completion_tokens??"?"}),((X=N.usage.prompt_tokens_details)==null?void 0:X.cached_tokens)!=null&&e.jsxs(e.Fragment,{children:[" · cached ",e.jsx("code",{children:N.usage.prompt_tokens_details.cached_tokens})]})]})]}):e.jsx("pre",{children:N.message??N.error??"unknown error"})})]})]})]}):e.jsx("div",{className:"view-container",children:e.jsxs("div",{className:"error-card",children:[e.jsx(ke,{size:20}),e.jsxs("div",{children:[e.jsx("strong",{children:"Couldn't load MiniMax status"}),e.jsx("pre",{children:u??"unknown error"})]})]})})}function Wo({toast:s}){const[t,a]=r.useState("24h"),[i,n]=r.useState(""),[o,c]=r.useState(""),[l,h]=r.useState(!0),[p,x]=r.useState(null),[d,m]=r.useState([]),[u,g]=r.useState("requests"),[N,z]=r.useState("desc"),[R,b]=r.useState(!1),w=r.useCallback(async(y,M,P)=>{h(!0);try{const C=new URLSearchParams({range:y});y==="custom"&&M&&P&&(C.set("from",String(M)),C.set("to",String(P)));const[D,Q]=await Promise.all([$.get(`/usage?${C.toString()}`),$.get("/usage/recent?limit=20")]);x(D),m(Q.records)}catch(C){s.error(`Failed to load usage data: ${C.message}`)}finally{h(!1)}},[s]);r.useEffect(()=>{if(t==="custom"){const y=i?new Date(i).getTime():Date.now()-6048e5,M=o?new Date(o).getTime():Date.now();w("custom",y,M)}else w(t)},[t,w]);const T=r.useCallback(y=>{u===y?z(M=>M==="asc"?"desc":"asc"):(g(y),z("desc"))},[u]),j=r.useMemo(()=>p!=null&&p.perModel?[...p.perModel].sort((y,M)=>{const P=y[u]??0,C=M[u]??0,D=typeof P=="number"&&typeof C=="number"?P-C:String(P).localeCompare(String(C));return N==="asc"?D:-D}):[],[p==null?void 0:p.perModel,u,N]),k=r.useMemo(()=>p!=null&&p.daily?{labels:p.daily.map(y=>y.date.slice(5)),requests:p.daily.map(y=>y.requests),tokens:p.daily.map(y=>y.totalTokens)}:{labels:[],requests:[],tokens:[]},[p==null?void 0:p.daily]),f=r.useCallback(async()=>{b(!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),b(!1)},[w,t,i,o]);if(l&&!p)return e.jsxs("div",{className:"view-container",children:[e.jsx(le,{})," Loading usage data…"]});const v=p==null?void 0:p.totals,L=(p==null?void 0:p.errors)??[],S=(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(Na,{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(A,{variant:"secondary",size:"sm",onClick:f,disabled:R,children:[R?e.jsx(he,{size:14,className:"spin"}):e.jsx(ce,{size:14})," Refresh"]})})]}),e.jsxs("div",{className:"usage-time-range",children:[["24h","7d","30d","custom"].map(y=>e.jsx("button",{className:K("usage-range-chip",t===y&&"is-active"),onClick:()=>a(y),children:y==="custom"?"Custom":y.toUpperCase()},y)),t==="custom"&&e.jsxs("div",{className:"usage-custom-dates",children:[e.jsx("label",{htmlFor:"usage-from-date",className:"sr-only",children:"From date"}),e.jsx("input",{id:"usage-from-date",type:"date",className:"usage-date-input",value:i,onChange:y=>n(y.target.value),"aria-label":"From date"}),e.jsx("span",{style:{color:"var(--text-muted)",fontSize:12},"aria-hidden":!0,children:"to"}),e.jsx("label",{htmlFor:"usage-to-date",className:"sr-only",children:"To date"}),e.jsx("input",{id:"usage-to-date",type:"date",className:"usage-date-input",value:o,onChange:y=>c(y.target.value),"aria-label":"To date"})]})]}),e.jsxs("div",{className:"usage-kpi-row",children:[e.jsx($s,{label:"Total Requests",value:(v==null?void 0:v.requests.toLocaleString())??"—",sub:v?`${v.errors} errors`:void 0,tone:v&&v.errors>v.requests*.1?"warn":void 0}),e.jsx($s,{label:"Total Tokens",value:v?v.totalTokens>=1e3?`${Math.round(v.totalTokens/1e3)}k`:String(v.totalTokens):"—",sub:v?`${v.promptTokens.toLocaleString()} prompt · ${v.completionTokens.toLocaleString()} completion`:void 0}),e.jsx($s,{label:"Errors",value:String((v==null?void 0:v.errors)??"—"),sub:L.length>0?`${L[0].code}: ${L[0].count}`:void 0,tone:v&&v.errors>0?"err":void 0}),e.jsx($s,{label:"Avg Latency",value:(v==null?void 0:v.avgLatencyMs)!=null?`${v.avgLatencyMs}ms`:"—",sub:(v==null?void 0:v.p95LatencyMs)!=null?`p95 ${v.p95LatencyMs}ms`:void 0}),e.jsx($s,{label:"Est. Cost",value:(v==null?void 0:v.costEstimate)!=null&&v.costEstimate>0?`$${v.costEstimate.toFixed(4)}`:"—",sub:"approximate USD",tone:void 0})]}),e.jsxs(Y,{className:"usage-chart-card",children:[e.jsx("div",{className:"usage-chart-wrap",children:e.jsx(Oo,{series:k,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(Y,{children:[e.jsx(ae,{children:"Per-model breakdown"}),e.jsx(Bo,{rows:j,sortKey:u,sortDir:N,onSort:T})]}),S.length>0&&e.jsxs(Y,{children:[e.jsx(ae,{children:"API Keys"}),e.jsx("div",{className:"usage-key-row",children:S.map(y=>e.jsxs("span",{className:K("usage-key-badge",y.isBackup?"is-backup":"is-active"),children:[e.jsx("span",{className:"usage-key-dot"}),y.keyEnvVar,y.isBackup?" (backup)":" (active)"," · ",y.requests," req"]},y.keyEnvVar))})]}),d.length>0&&e.jsxs(Y,{children:[e.jsx(ae,{children:"Recent activity"}),e.jsx("div",{className:"usage-recent-list",children:d.map((y,M)=>e.jsxs("div",{className:K("usage-recent-item",y.error&&"is-err"),children:[e.jsx("span",{className:"usage-recent-time",children:new Date(y.ts).toLocaleTimeString()}),e.jsx("span",{className:"usage-recent-model",children:e.jsx("code",{children:y.modelId})}),e.jsxs("span",{className:"usage-recent-tokens",children:[y.totalTokens.toLocaleString()," tok"]}),e.jsxs("span",{className:"usage-recent-latency",children:[y.latencyMs,"ms"]}),e.jsx("span",{className:"usage-recent-endpoint",children:y.endpoint})]},`${y.requestId}-${M}`))})]})]})}function $s({label:s,value:t,sub:a,tone:i}){return e.jsxs("div",{className:"usage-kpi-card",children:[e.jsx("div",{className:"usage-kpi-label",children:s}),e.jsx("div",{className:K("usage-kpi-value",i&&`is-${i}`),children:t}),a&&e.jsx("div",{className:"usage-kpi-sub",children:a})]})}function Ws({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 qo({model:s}){const t=qs(s.current_interval_remaining_percent??0,0,100),a=qs(s.current_weekly_remaining_percent??0,0,100),i=qs(100-t,0,100),n=qs(100-a,0,100);return e.jsxs(Y,{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:K("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(na,{icon:e.jsx(De,{size:12}),label:"5-hour rolling",remainingPct:t,consumedPct:i,used:s.current_interval_usage_count??0,total:s.current_interval_total_count??0,resetIn:s.intervalResetInHuman,resetISO:s.endTimeISO}),e.jsx(na,{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 na({icon:s,label:t,remainingPct:a,consumedPct:i,used:n,total:o,resetIn:c,resetISO:l}){const h=a>=75?"good":a>=25?"warn":"low";return e.jsxs("div",{className:`minimax-quota-row is-${h}`,children:[e.jsxs("div",{className:"minimax-quota-head",children:[e.jsxs("span",{className:"minimax-quota-label",children:[s," ",t]}),e.jsxs("span",{className:"minimax-quota-remaining",children:[a,"% remaining"]}),e.jsxs("span",{className:"minimax-quota-consumed",children:["· ",i,"% used"]})]}),e.jsx("div",{className:"minimax-bar",children:e.jsx("div",{className:"minimax-bar-fill",style:{width:`${i}%`},"aria-label":`${i}% consumed`})}),e.jsxs("div",{className:"minimax-quota-meta",children:[e.jsxs("span",{children:[e.jsx("strong",{children:n})," / ",o||"—"," requests"]}),e.jsx("span",{title:l,children:c?`resets in ${c}`:"—"})]})]})}function qs(s,t,a){return Math.max(t,Math.min(a,s))}function Vo(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 Ho({step:s,setStep:t,keyDraft:a,setKeyDraft:i,showKey:n,setShowKey:o,verifying:c,verifyResult:l,onVerify:h,onSkip:p,onManualKeySave:x,savingKey:d,status:m}){return e.jsxs("div",{className:"view-container view-minimax-onboarding",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-titles",children:[e.jsxs("h1",{className:"view-title",children:[e.jsx(Xe,{size:20,style:{verticalAlign:"text-bottom",marginRight:6}}),"Set up MiniMax Token Plan tracking"]}),e.jsx("p",{className:"view-subtitle",children:"We'll read your Subscription Key and show your remaining quota."})]}),e.jsx("div",{className:"view-header-actions",children:e.jsxs(A,{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:K("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(Fe,{size:14}):g+1}),e.jsx("div",{className:"minimax-wizard-step-label",children:u})]},u))}),e.jsxs(Y,{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(A,{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(Ns,{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(A,{variant:"secondary",size:"md",onClick:()=>t(0),children:"← Back"}),e.jsxs(A,{variant:"primary",size:"md",onClick:()=>t(2),children:["I have my key ",e.jsx("span",{style:{marginLeft:6},children:"→"})]})]})]}),s===2&&e.jsxs("div",{className:"minimax-wizard-body",children:[e.jsx("h3",{className:"minimax-wizard-title",children:"Paste & test"}),e.jsx("p",{className:"minimax-wizard-prose",children:"Paste your key below. We'll test it against the real API before saving."}),e.jsx("div",{className:"minimax-key-row",children:e.jsxs("div",{className:"minimax-key-input-wrap",children:[e.jsx(It,{size:12,className:"minimax-key-icon","aria-hidden":!0}),e.jsx("label",{htmlFor:"minimax-key-input",className:"sr-only",children:"Subscription Key"}),e.jsx("input",{id:"minimax-key-input",type:n?"text":"password",value:a,onChange: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(jt,{size:13}):e.jsx(vs,{size:13})})]})}),l&&!l.ok&&e.jsxs("div",{className:"minimax-wizard-error",children:[e.jsx(ke,{size:14}),e.jsxs("span",{children:[e.jsx("strong",{children:"Verification failed:"})," ",l.message??l.error]})]}),e.jsxs("div",{className:"minimax-wizard-actions",children:[e.jsx(A,{variant:"secondary",size:"md",onClick:()=>t(1),children:"← Back"}),e.jsxs(A,{variant:"primary",size:"md",onClick:h,disabled:c||!a.trim(),children:[c?e.jsx(he,{size:14,className:"spin"}):e.jsx(Es,{size:14}),c?"Testing…":"Test &amp; 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(),x()},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(Fe,{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(A,{variant:"primary",size:"md",onClick:()=>window.location.reload(),children:"View your quota →"})})]}),e.jsxs("div",{className:"minimax-wizard-footer",children:[e.jsx(Es,{size:11}),e.jsxs("span",{children:["Key written to ",e.jsx("code",{children:"~/.local/share/opencode/auth.json"})," with mode 0600."]})]})]})]})}const Go=Oe.memo(Uo),Ko={pending:"info",running:"accent",done:"success",failed:"error",killed:"neutral",timed_out:"warning"},Yo={pending:"Pending",running:"Running",done:"Done",failed:"Failed",killed:"Killed",timed_out:"Timed out"};function Xo({status:s,dot:t}){const a=Ko[s]||"neutral",i=Yo[s]||s;return e.jsx(Qe,{kind:a,dot:t,children:i})}function Qo({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(A,{variant:"ghost",onClick:i,children:"Cancel"}),e.jsx(A,{variant:"danger",onClick:async()=>{await a(),i()},children:"Kill"})]})]})}function Jo(s,t,a,i,n){s.open({title:"Kill instance?",width:400,children:e.jsx(Qo,{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 Zo({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 h=await $.post(`/background/${encodeURIComponent(s.instanceId)}/open-terminal`,{emulator:"system"});if(h.ok)t.success("Opening terminal…");else if(t.error(h.error||"Failed to open terminal"),o)try{await navigator.clipboard.writeText(o),t.success("Command copied to clipboard")}catch{}}catch(h){if(t.error(`Failed: ${h.message}`),o)try{await navigator.clipboard.writeText(o),t.success("Command copied to clipboard")}catch{}}finally{i(!1)}}};return n?e.jsxs(Y,{variant:"outlined",className:"bg-tmux-card",children:[e.jsxs("div",{className:"bg-tmux-card-header",children:[e.jsx(is,{size:14}),e.jsx("span",{children:"tmux session"}),s.tmuxActive!==!1?e.jsx("span",{className:"badge badge-success",children:"live"}):e.jsx("span",{className:"badge badge-warning",children:"inactive"})]}),e.jsx("code",{className:"mono bg-tmux-session-name",children:n}),e.jsx("p",{className:"muted bg-tmux-hint",children:"Attach to the agent's tmux session from a terminal on the host running the dashboard."}),e.jsxs("div",{className:"bg-tmux-card-actions",children:[e.jsxs(A,{variant:"ghost",size:"sm",onClick:c,title:"Copy attach command",children:[e.jsx(os,{size:14})," Copy"]}),e.jsxs(A,{variant:"primary",size:"sm",onClick:l,loading:a,title:"Open in system terminal",children:[e.jsx(is,{size:14})," Open terminal"]})]})]}):e.jsxs(Y,{variant:"outlined",className:"bg-tmux-card bg-tmux-card-warn",children:[e.jsxs("div",{className:"bg-tmux-card-header",children:[e.jsx(ke,{size:14}),e.jsx("span",{children:"No tmux session"})]}),e.jsx("p",{className:"bg-tmux-hint muted",children:"This instance does not have a tmux session attached. Sessions are created automatically when a background agent starts."})]})}const ec=[{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"}],sc=[{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 tc({open:s,onClose:t,onCreated:a,agents:i=ec}){var k;const n=re(),[o,c]=r.useState(((k=i[0])==null?void 0:k.name)||"mimir"),[l,h]=r.useState(""),[p,x]=r.useState(""),[d,m]=r.useState(3e5),[u,g]=r.useState(!1),[N,z]=r.useState(""),[R,b]=r.useState(!1),[w,T]=r.useState(null);if(!s)return null;const j=async f=>{if(f.preventDefault(),T(null),!l.trim()){T("Prompt is required.");return}b(!0);try{const v=N.split(",").map(y=>y.trim()).filter(y=>y.length>0),L={agent:o,prompt:l,...p.trim()?{model:p.trim()}:{},timeoutMs:d,persistent:u,maxRestarts:3,...v.length>0?{tags:v}:{}},S=await $.post("/background",L);if(S!=null&&S.error)throw new Error(S.message||S.error);n.success(`Spawned ${o} (${S.instanceId.slice(0,14)}…)`),a==null||a(S.instanceId),h(""),x(""),g(!1),z(""),t()}catch(v){T((v==null?void 0:v.message)||"Failed to spawn.")}finally{b(!1)}};return e.jsx("div",{className:"modal-backdrop",role:"dialog","aria-modal":"true",children:e.jsxs("div",{className:"modal-card spawn-modal",children:[e.jsxs("div",{className:"spawn-modal-header",children:[e.jsxs("h3",{children:[e.jsx(be,{size:18})," Spawn background agent"]}),e.jsx(A,{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:f=>c(f.target.value),required:!0,children:i.map(f=>e.jsxs("option",{value:f.name,children:[f.name,f.description?` — ${f.description}`:""]},f.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:f=>h(f.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:f=>x(f.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:sc.map(f=>e.jsx("button",{type:"button",className:"spawn-modal-timeout-pill"+(f.value===d?" spawn-modal-timeout-pill-active":""),onClick:()=>m(f.value),children:f.label},f.value))}),e.jsx("input",{type:"range",min:6e4,max:144e5,step:6e4,value:d,onChange:f=>m(Number(f.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:f=>g(f.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:N,onChange:f=>z(f.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(A,{variant:"ghost",size:"sm",type:"button",onClick:t,children:"Cancel"}),e.jsx(A,{variant:"primary",size:"sm",type:"submit",disabled:R,children:R?"Spawning…":"Spawn agent"})]})]})]})})}const ac=5e3,ia=3e3,nc=120,ic=32e3;function rc(s){return s.status==="pending"||s.status==="running"||s.status==="paused"}function kt(s){return s.status==="paused"}function lc(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 oc(s){const t=re(),a=Te(),[i,n]=r.useState([]),[o,c]=r.useState(!0),[l,h]=r.useState(null),[,p]=r.useState(0),[x,d]=r.useState(!1),m=r.useCallback(async()=>{try{const T=await $.get("/background");n(Array.isArray(T==null?void 0:T.instances)?T.instances:[]),h(null)}catch(T){h((T==null?void 0:T.message)||"Failed to load background agents.")}finally{c(!1)}},[]);r.useEffect(()=>{m();const T=setInterval(m,ac);return()=>clearInterval(T)},[m]),r.useEffect(()=>{const T=setInterval(()=>p(j=>(j+1)%1e6),1e3);return()=>clearInterval(T)},[]),r.useEffect(()=>{const T=new Ys,j=T.on(k=>{const f=k.type;(f==="background:change"||f==="background:cleanup"||f==="bg:progress"||f==="bg:tool-call")&&m()});return()=>{j(),T.close()}},[m]);const u=i.filter(rc),g=T=>{dc(a,T)},N=async T=>{try{const j=await $.get(`/background/${encodeURIComponent(T.instanceId)}/tmux`);hc(a,j)}catch(j){t.error(`Tmux info failed: ${j.message}`)}},z=T=>{Jo(a,t,T.instanceId,T.agent||T.prompt,()=>{n(j=>j.filter(k=>k.instanceId!==T.instanceId))})},R=async T=>{try{const j=await $.post(`/background/${encodeURIComponent(T.instanceId)}/pause`,{});j!=null&&j.ok?t.info(`Paused ${T.instanceId.slice(0,14)}…`):t.error((j==null?void 0:j.error)||"Pause failed.")}catch(j){t.error(`Pause failed: ${j.message}`)}},b=async T=>{try{const j=await $.post(`/background/${encodeURIComponent(T.instanceId)}/resume`,{});j!=null&&j.ok?t.info(`Resumed ${T.instanceId.slice(0,14)}…`):t.error((j==null?void 0:j.error)||"Resume failed.")}catch(j){t.error(`Resume failed: ${j.message}`)}},w=T=>{xc(a,t,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(pe,{icon:e.jsx(De,{size:32}),title:"Couldn't load background agents",message:l,action:e.jsxs(A,{variant:"primary",onClick:m,children:[e.jsx(ce,{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(A,{variant:"primary",size:"sm",onClick:()=>d(!0),children:[e.jsx(be,{size:14})," Spawn"]}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:m,title:"Refresh now",children:[e.jsx(ce,{size:14})," Refresh"]})]})]}),e.jsx(tc,{open:x,onClose:()=>d(!1),onCreated:()=>{m()}}),u.length===0?e.jsx(pe,{icon:e.jsx(De,{size:32}),title:"No active background agents",message:"Use the Spawn button above or call bizar_spawn_background from an agent.",action:e.jsxs(A,{variant:"primary",onClick:()=>d(!0),children:[e.jsx(be,{size:14})," Spawn your first agent"]})}):e.jsx("div",{className:"bg-active-list",children:u.map(T=>e.jsx(cc,{inst:T,onViewOutput:()=>g(T),onOpenTmux:()=>N(T),onKill:()=>z(T),onPause:kt(T)?void 0:()=>R(T),onResume:kt(T)?()=>b(T):void 0,onSteer:()=>w(T)},T.instanceId))})]})}function cc({inst:s,onViewOutput:t,onOpenTmux:a,onKill:i,onPause:n,onResume:o,onSteer:c}){const l=typeof s.startedAt=="number"?s.startedAt:0,h=l?We(l):"—",p=l?Date.now()-l:0,x=ra(s.prompt,nc),d=typeof s.progress=="number"?s.progress:null;return e.jsxs(Y,{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(Xo,{status:s.status||"pending",dot:!0}),kt(s)&&e.jsxs("span",{className:"bg-active-card-paused-tag",children:[e.jsx(qn,{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"})]})]}),x&&e.jsx("div",{className:"bg-active-prompt",children:x}),s.currentStep&&e.jsxs("div",{className:"bg-active-step",children:[e.jsx("span",{className:"bg-active-step-label",children:"Step:"}),e.jsx("span",{className:"bg-active-step-value",children:s.currentStep})]}),d!==null&&e.jsxs("div",{className:"progress-bar","aria-label":"Progress",children:[e.jsx("div",{className:"progress-fill",style:{width:`${d<0?100:Math.max(0,Math.min(100,d))}%`}}),e.jsxs("span",{className:"progress-label",children:[d<0?"…":`${Math.round(d)}%`,s.progressMessage?` · ${s.progressMessage}`:""]})]}),e.jsxs("div",{className:"bg-active-meta",children:[e.jsxs("span",{title:h,children:[e.jsx("strong",{children:"Started:"})," ",h]}),e.jsxs("span",{children:[e.jsx("strong",{children:"Duration:"})," ",lc(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:K(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(A,{variant:"secondary",size:"sm",onClick:t,children:[e.jsx(vs,{size:14})," View output"]}),n&&e.jsxs(A,{variant:"secondary",size:"sm",onClick:n,title:"Pause subprocess (POSIX)",children:[e.jsx(At,{size:14})," Pause"]}),o&&e.jsxs(A,{variant:"secondary",size:"sm",onClick:o,title:"Resume subprocess (POSIX)",children:[e.jsx(ks,{size:14})," Resume"]}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:c,title:"Steer with new instructions",children:[e.jsx(es,{size:14})," Steer"]}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:a,children:[e.jsx(is,{size:14})," Open in tmux"]}),e.jsxs(A,{variant:"danger",size:"sm",onClick:i,children:[e.jsx(Se,{size:14})," Kill"]})]}),e.jsx(Zo,{instance:s})]})}function dc(s,t){s.open({title:`Output — ${t.agent||t.instanceId}`,width:720,children:e.jsx(mc,{instanceId:t.instanceId})})}function mc({instanceId:s}){const t=re(),a=r.useRef([]),[i,n]=r.useState(""),[o,c]=r.useState(!0),[l,h]=r.useState(null),[p,x]=r.useState(!0),[d,m]=r.useState(!0),[u,g]=r.useState([]),[N,z]=r.useState(!0),R=r.useRef(null),b=r.useRef(!0),w=r.useCallback(()=>{n(a.current.join(`
17
+ `))},[]),T=r.useCallback(async()=>{try{const f=await $.get(`/background/${encodeURIComponent(s)}/output?lines=300`);if(x((f==null?void 0:f.available)!==!1),f!=null&&f.output&&a.current.length===0){const v=f.output.split(/\r?\n/);a.current=v.slice(-300),w()}h(null)}catch(f){h((f==null?void 0:f.message)||"Failed to load output.")}finally{c(!1)}},[s,w]);r.useEffect(()=>{T();const f=setInterval(T,ia);return()=>clearInterval(f)},[T]),r.useEffect(()=>{const f=new Ys;let v=!1;const L=f.onStatus(y=>{v=y==="connected",m(v)}),S=f.on(y=>{var P;const M=y;if(M.type==="bg:output"&&M.instanceId===s&&typeof M.line=="string"){a.current.push(M.line);let C=0;for(let D=a.current.length-1;D>=0;D--)if(C+=(((P=a.current[D])==null?void 0:P.length)??0)+1,C>ic){a.current=a.current.slice(D+1);break}n(a.current.join(`
18
+ `))}});return()=>{L(),S(),f.close()}},[s]),r.useEffect(()=>{let f=!1;const v=async()=>{try{const y=await $.get(`/background/${encodeURIComponent(s)}/tool-calls`);!f&&Array.isArray(y==null?void 0:y.toolCalls)&&g(y.toolCalls)}catch{}};v();const L=new Ys,S=L.on(y=>{const M=y;M.type==="bg:tool-call"&&M.instanceId===s&&v()});return()=>{f=!0,S(),L.close()}},[s]),r.useEffect(()=>{var f;b.current&&((f=R.current)==null||f.scrollIntoView({behavior:"auto",block:"end"}))},[i]);const j=f=>{const v=f.currentTarget,L=v.scrollHeight-v.scrollTop-v.clientHeight<24;b.current=L},k=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 ${ia/1e3}s (WS idle)`:"Output unavailable (no tmux session)"}),e.jsxs("div",{className:"bg-output-toolbar-actions",children:[e.jsx(A,{variant:"ghost",size:"sm",onClick:()=>z(f=>!f),title:"Toggle tool-call history",children:N?"Hide tools":"Show tools"}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:T,title:"Refresh now",children:[e.jsx(ce,{size:14})," Refresh"]}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:k,disabled:!i,children:[e.jsx(os,{size:14})," Copy"]})]})]}),o&&!i?e.jsxs("div",{className:"bg-output-loading",children:[e.jsx(he,{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:R})]}),N&&e.jsx(uc,{calls:u})]})]})}function uc({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 hc(s,t){const a=t.attachCommand||t.session||"";s.open({title:"Attach to tmux",width:520,children:e.jsx(gc,{info:t,cmd:a})})}function xc(s,t,a,i){s.open({title:`Steer ${a.agent||a.instanceId}`,width:600,children:e.jsx(pc,{instanceId:a.instanceId,toast:t,onCreated:i,onClose:()=>s.close()})})}function pc({instanceId:s,toast:t,onCreated:a,onClose:i}){const[n,o]=r.useState(""),[c,l]=r.useState(!1),[h,p]=r.useState(null),x=async()=>{if(!n.trim()){p("Message is required.");return}l(!0);try{const d=await $.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?"}),h&&e.jsx("div",{className:"bg-steer-error",children:h}),e.jsxs("div",{className:"bg-steer-actions",children:[e.jsx(A,{variant:"ghost",size:"sm",onClick:i,children:"Cancel"}),e.jsx(A,{variant:"primary",size:"sm",onClick:x,disabled:c||!n.trim(),children:c?"Steering…":"Steer"})]})]})}function gc({info:s,cmd:t}){const[a,i]=r.useState(!1),n=async()=>{try{await navigator.clipboard.writeText(t),i(!0),window.setTimeout(()=>i(!1),1500)}catch{}};return e.jsx("div",{className:"bg-tmux-modal",children:t?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"bg-tmux-meta",children:[s.exists?e.jsx("span",{className:"badge badge-success",children:"session live"}):e.jsxs("span",{className:"badge badge-warning",children:["session not running",s.reason?` — ${s.reason}`:""]}),s.session&&e.jsxs("span",{className:"bg-tmux-session muted",children:["· session ",e.jsx("code",{className:"mono",children:s.session})]})]}),e.jsx("label",{className:"field-label",children:"Attach command"}),e.jsxs("div",{className:"bg-tmux-command-row",children:[e.jsx("code",{className:"bg-tmux-command mono",children:t}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:n,children:[e.jsx(os,{size:14})," ",a?"Copied":"Copy"]})]}),e.jsx("p",{className:"muted bg-tmux-hint",children:"Paste this into a terminal on the host running the dashboard. The dashboard itself does not open terminals."})]}):e.jsx("p",{className:"muted",children:"No tmux session attached to this instance."})})}const jc={system:{title:"System health",icon:ys,emptyTitle:"No system checks",emptyMessage:"System checks did not return any rows."},services:{title:"Services",icon:Tt,emptyTitle:"No service probes",emptyMessage:"Service probes did not return any rows."},counts:{title:"Counts",icon:De,emptyTitle:"No counts",emptyMessage:"No counts reported by the dashboard stores."},errors:{title:"Recent errors",icon:js,emptyTitle:"No recent errors",emptyMessage:"No error lines in the service log within the last hour."},actions:{title:"Actions",icon:Vn,emptyTitle:"No actions",emptyMessage:"No actions available."}};function fc(s){return s==="ok"?Fe:s==="warn"?Hn:js}function vc(s){return s==="ok"?"ok":s==="warn"?"warn":"fail"}function xt({category:s,title:t,icon:a,checks:i,info:n,meta:o,children:c,className:l}){const h=jc[s],p=a??h.icon,x=t??h.title,d=i.length>0||n&&n.length>0||c;return e.jsxs(Y,{className:K("doctor-panel",`doctor-panel-${s}`,l),children:[e.jsxs(ae,{children:[e.jsx(p,{size:14,"aria-hidden":!0}),e.jsx("span",{children:x}),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=fc(m.status);return e.jsxs("li",{className:K("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:K("doctor-check-icon-svg",m.status==="ok"&&"doctor-check-icon-ok",m.status==="warn"&&"doctor-check-icon-warn",m.status==="fail"&&"doctor-check-icon-fail")})}),e.jsx("span",{className:"doctor-check-name mono",children:m.name}),e.jsx("span",{className:"doctor-check-message",children:m.message}),e.jsx(Qe,{kind:m.status,dot:!0,children:vc(m.status)})]},m.name)})}):null,n&&n.length>0?e.jsx("dl",{className:"doctor-info-list",children:n.map(m=>e.jsxs(Oe.Fragment,{children:[e.jsx("dt",{children:m.label}),e.jsx("dd",{className:"tabular-nums",children:m.value})]},m.label))}):null]}):e.jsx(pe,{icon:e.jsx(p,{size:28,"aria-hidden":!0}),title:h.emptyTitle,message:h.emptyMessage})]})}const yc=3e4;function bc({setActiveTab:s}){var k;const t=re(),[a,i]=r.useState(null),[n,o]=r.useState(!0),[c,l]=r.useState(!1),[h,p]=r.useState(null),[x,d]=r.useState(!0),m=r.useRef(!1),u=r.useCallback(async()=>{l(!0);try{const f=await $.get("/doctor");m.current||(i(f),p(Date.now()),o(!1))}catch(f){m.current||(o(!1),t.error(`Doctor refresh failed: ${f.message}`))}finally{m.current||l(!1)}},[t]);r.useEffect(()=>(m.current=!1,u(),()=>{m.current=!0}),[u]),r.useEffect(()=>{if(!x)return;const v=setInterval(async()=>{try{const L=await $.get("/doctor/health");i(S=>S&&((S.health.status!==L.status||S.health.issues.length!==L.issues.length)&&u(),S))}catch{}},yc);return()=>clearInterval(v)},[x,u]);const g=async f=>{var v;try{const L=await $.post("/doctor/check",{checkName:f});t.info(`${L.name}: ${L.message}`,4e3),await u()}catch(L){const S=L;t.error(`Check failed: ${((v=S.data)==null?void 0:v.message)??L.message}`)}},N=()=>{if(a)try{const f=new Blob([JSON.stringify(a,null,2)],{type:"application/json"}),v=URL.createObjectURL(f),L=document.createElement("a");L.href=v,L.download=`doctor-snapshot-${new Date().toISOString().replace(/[:.]/g,"-")}.json`,document.body.appendChild(L),L.click(),document.body.removeChild(L),URL.revokeObjectURL(v)}catch(f){t.error(`Export failed: ${f.message}`)}},z=()=>{s("settings")},R=a==null?void 0:a.counts,b=r.useMemo(()=>R?[{label:"Tasks",value:R.tasks},{label:"Schedules",value:R.schedules},{label:"Mods",value:R.mods},{label:"Providers",value:R.providers},{label:"MCPs",value:R.mcps},{label:"Agents",value:R.agents},{label:"Projects",value:R.projects},{label:"Workspaces",value:R.workspaces},{label:"Voice notes",value:R.voiceNotes},{label:"Eval runs",value:R.evalRuns},{label:"Backups",value:R.backups}]:[],[R]);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(Y,{children:[e.jsxs(ae,{children:[e.jsx(js,{size:14})," Doctor unavailable"]}),e.jsx(ne,{children:"Could not reach /api/doctor."}),e.jsx("div",{className:"doctor-fallback-actions",children:e.jsxs(A,{variant:"primary",onClick:u,children:[e.jsx(ce,{size:12})," Retry"]})})]})});const w=a.health.status,T=w==="ok"?Fe:w==="warn"?ke:js,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(da,{size:20,"aria-hidden":!0}),e.jsx("h1",{children:"Doctor"})]}),e.jsx("div",{className:"doctor-header-status",children:e.jsxs("span",{className:K("doctor-overall-pill",`doctor-overall-${w}`),children:[e.jsx(T,{size:14,"aria-hidden":!0}),e.jsx("span",{className:"doctor-overall-label",children:j}),e.jsxs(Qe,{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(Ze,{size:12,"aria-hidden":!0}),e.jsxs("span",{"aria-live":"polite","aria-atomic":"true",children:["v",a.bizarVersion," · ",a.platform,"/",a.arch," ·"," ","up ",Math.floor(a.uptime),"s",h?` · refreshed ${We(new Date(h))}`:""]})]})]}),e.jsxs("div",{className:"doctor-grid",children:[e.jsx(xt,{category:"system",checks:a.checks.system,meta:`${a.platform}/${a.arch}`}),e.jsx(xt,{category:"services",checks:a.checks.services,meta:(k=a.services.opencode)!=null&&k.reachable?`opencode on ${a.services.opencode.port??"?"}`:"opencode not connected"}),e.jsx(xt,{category:"counts",checks:[],info:b,meta:R!=null&&R.activeProject?`active: ${R.activeProject}`:"no active project"}),e.jsxs(Y,{className:"doctor-errors-card",children:[e.jsxs(ae,{children:[e.jsx(js,{size:14,"aria-hidden":!0}),e.jsx("span",{children:"Recent errors (last hour)"}),e.jsxs("span",{className:"card-meta-inline muted",children:[a.recentErrors.length," line",a.recentErrors.length===1?"":"s"]})]}),a.recentErrors.length===0?e.jsx("div",{className:"muted doctor-errors-empty",children:"No errors in the last hour. Nice."}):e.jsx("ul",{className:"doctor-errors-list",role:"list",children:a.recentErrors.map((f,v)=>e.jsxs("li",{className:"doctor-error-row",children:[e.jsx("span",{className:"doctor-error-ts mono",children:f.ts?We(new Date(f.ts)):"??:??:??"}),e.jsx("span",{className:"doctor-error-line mono",children:f.line})]},`${f.tsMs??v}-${v}`))})]}),e.jsxs(Y,{className:"doctor-actions-card",children:[e.jsxs(ae,{children:[e.jsx(vt,{size:14,"aria-hidden":!0})," Actions"]}),e.jsx(ne,{children:"Run a check, view logs, or export the snapshot."}),e.jsxs("div",{className:"doctor-actions-row",children:[e.jsxs(A,{variant:"primary",onClick:u,disabled:c,"aria-label":"Refresh diagnostics",children:[c?e.jsx(le,{size:"sm"}):e.jsx(ce,{size:12}),c?"Running…":"Run Health Check Now"]}),e.jsxs(A,{variant:"secondary",onClick:z,children:[e.jsx(we,{size:12})," View Full Logs"]}),e.jsxs(A,{variant:"secondary",onClick:N,children:[e.jsx(ls,{size:12})," Export Diagnostics as JSON"]}),e.jsx(A,{variant:"ghost",onClick:()=>d(f=>!f),"aria-label":x?"Pause auto-refresh":"Resume auto-refresh",children:x?"Pause auto-refresh":"Resume auto-refresh"})]}),a.checks.services.some(f=>f.status!=="ok")||a.checks.config.some(f=>f.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(f=>f.status!=="ok").map(f=>e.jsxs(A,{variant:"ghost",size:"sm",onClick:()=>g(f.name),title:`Run check: ${f.name}`,children:[e.jsx(vt,{size:10})," ",f.name]},f.name))})]}):null]})]})]})}const Nc=Oe.memo(bc);function kc(s){return s.total<=0?"fail":s.failed===0?"pass":s.passed/s.total>.8?"warn":"fail"}function Da({run:s,onClick:t,selected:a,ariaLabel:i}){const n=kc(s),o=s.total>0?(s.passed/s.total*100).toFixed(1):"0.0",c=!!t;return e.jsxs(Y,{onClick:t,interactive:c,"aria-label":i??`Eval run ${s.id}`,"aria-pressed":c?a:void 0,className:K("eval-run-card",a&&"eval-run-card-selected",`eval-run-${n}`),children:[e.jsxs("div",{className:"eval-run-head",children:[e.jsx(ae,{className:"eval-run-title",children:s.id}),e.jsxs("span",{className:K("eval-status",`is-${n}`),children:[s.passed,"/",s.total," (",o,"%)"]})]}),e.jsxs(ne,{className:"eval-run-meta",children:[We(s.startedAt)," · ",s.suitePath]})]})}const pt=8;function wc({onAdded:s,onCancel:t}){const a=re(),[i,n]=r.useState(""),[o,c]=r.useState(""),[l,h]=r.useState(""),[p,x]=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 N=await $.post("/eval/schedules",{name:i,suitePath:o,cron:l,agent:p});s(N),a.success("Schedule created")}catch(N){a.error(`Failed to create schedule: ${N.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=>h(g.target.value),placeholder:"0 8 * * *",required:!0})]}),e.jsxs("div",{className:"form-row",children:[e.jsx("label",{htmlFor:"sched-agent",children:"Agent"}),e.jsx("input",{id:"sched-agent",type:"text",value:p,onChange:g=>x(g.target.value),placeholder:"thor"})]}),e.jsxs("div",{className:"form-actions",children:[e.jsx(A,{type:"submit",variant:"primary",size:"sm",disabled:d,children:d?"Creating…":"Create schedule"}),e.jsx(A,{type:"button",variant:"ghost",size:"sm",onClick:t,children:"Cancel"})]})]})}function Sc({setActiveTab:s}){const t=re(),[a,i]=r.useState([]),[n,o]=r.useState(!0),[c,l]=r.useState("runs"),[h,p]=r.useState([]),[x,d]=r.useState(!1),[m,u]=r.useState(!1),g=r.useRef(!1),N=r.useCallback(async()=>{o(!0);try{const j=await $.get(`/eval/runs?limit=${pt}`);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 $.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,N(),c==="schedules"&&z(),()=>{g.current=!0}),[N,z,c]);const R=async j=>{try{await $.del(`/eval/schedules/${j}`),p(k=>k.filter(f=>f.id!==j)),t.success("Schedule deleted")}catch(k){t.error(`Failed to delete schedule: ${k.message}`)}},b=a.slice(0,pt),w=a.reduce((j,k)=>(j.total+=k.total,j.passed+=k.passed,j.failed+=k.failed,k.failed===0&&(j.fullPass+=1),j),{total:0,passed:0,failed:0,fullPass:0}),T=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(Je,{size:20,"aria-hidden":!0})," Eval"]}),e.jsx("p",{className:"view-subtitle muted",children:"Track golden-fixture runs, catch regressions, and compare run history."})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs(A,{variant:"secondary",size:"sm",onClick:N,disabled:n,children:[n?e.jsx(le,{size:"sm"}):e.jsx(ce,{size:12}),n?"Refreshing…":"Refresh"]}),e.jsxs(A,{variant:"primary",size:"sm",onClick:()=>s("evalReport"),title:"Open the full eval report",children:[e.jsx(Ns,{size:12})," Open Eval Report"]})]})]}),e.jsxs("div",{className:"eval-summary-grid",children:[e.jsxs(Y,{className:"eval-summary-card",children:[e.jsx(ae,{children:"Recent runs"}),e.jsx("div",{className:"eval-summary-value",children:a.length}),e.jsxs(ne,{className:"muted",children:["Latest ",pt," runs across all suites."]})]}),e.jsxs(Y,{className:"eval-summary-card",children:[e.jsx(ae,{children:"Fixtures run"}),e.jsx("div",{className:"eval-summary-value",children:w.total}),e.jsx(ne,{className:"muted",children:e.jsxs("span",{className:K("eval-rate",w.failed===0?"is-pass":"is-fail"),children:[T,"% pass rate"]})})]}),e.jsxs(Y,{className:"eval-summary-card",children:[e.jsx(ae,{children:"Clean runs"}),e.jsx("div",{className:"eval-summary-value",children:w.fullPass}),e.jsx(ne,{className:"muted",children:"Runs where every fixture passed."})]}),e.jsxs(Y,{className:"eval-summary-card eval-summary-cta",children:[e.jsx(ae,{children:"Compare runs"}),e.jsx(ne,{children:"Open the detailed report to diff two runs side-by-side and spot regressions fixture by fixture."}),e.jsxs(A,{variant:"primary",size:"sm",onClick:()=>s("evalReport"),className:"eval-summary-cta-btn",children:["Open report ",e.jsx(Gn,{size:12})]})]})]}),e.jsxs("div",{className:"eval-recent-section",children:[e.jsxs("div",{className:"eval-sub-tabs",children:[e.jsxs("button",{type:"button",className:K("eval-sub-tab",c==="runs"?"is-active":""),onClick:()=>l("runs"),children:[e.jsx(Je,{size:12,"aria-hidden":!0})," Runs"]}),e.jsxs("button",{type:"button",className:K("eval-sub-tab",c==="schedules"?"is-active":""),onClick:()=>{l("schedules"),h.length===0&&z()},children:[e.jsx(Ze,{size:12,"aria-hidden":!0})," Schedules"]})]}),c==="runs"?e.jsxs(e.Fragment,{children:[e.jsx("h2",{className:"eval-section-title",children:"Recent runs"}),n&&b.length===0?e.jsxs("div",{className:"eval-runs-loading",children:[e.jsx(le,{size:"sm"}),e.jsx("span",{className:"muted",children:"Loading runs…"})]}):b.length===0?e.jsx(pe,{icon:e.jsx(Je,{size:28}),title:"No eval runs yet",message:e.jsxs(e.Fragment,{children:["Run a suite via the CLI:"," ",e.jsx("code",{className:"mono",children:"bizar eval run ./path/to/fixtures"}),". Results will appear here."]})}):e.jsx("div",{className:"eval-runs-list",children:b.map(j=>e.jsx(Da,{run:j},j.id))})]}):e.jsxs(e.Fragment,{children:[e.jsx("h2",{className:"eval-section-title",children:"Schedules"}),x?e.jsxs("div",{className:"eval-runs-loading",children:[e.jsx(le,{size:"sm"}),e.jsx("span",{className:"muted",children:"Loading schedules…"})]}):h.length===0?e.jsx(pe,{icon:e.jsx(Ze,{size:28}),title:"No eval schedules",message:"Schedules let you run eval suites automatically on a cron. Add one below."}):e.jsx("div",{className:"eval-schedules-list",children:h.map(j=>e.jsx(Y,{className:"eval-schedule-card",children:e.jsxs("div",{className:"eval-schedule-row",children:[e.jsxs("div",{className:"eval-schedule-info",children:[e.jsx(ae,{children:j.name}),e.jsxs(ne,{className:"muted",children:[j.cron," · ",j.suitePath," · agent:",j.agent||"thor"]})]}),e.jsx(A,{variant:"ghost",size:"sm",onClick:()=>R(j.id),title:"Delete schedule",children:e.jsx(Se,{size:12,"aria-hidden":!0})})]})},j.id))}),e.jsxs("div",{className:"eval-schedule-add",children:[e.jsx(wc,{onAdded:j=>{p(k=>[...k,j]),u(!1)},onCancel:()=>u(!1)}),!m&&e.jsxs(A,{variant:"secondary",size:"sm",onClick:()=>u(!0),children:[e.jsx(be,{size:12,"aria-hidden":!0})," Add schedule"]})]})]})]})]})}const Cc=Oe.memo(Sc);function Pa(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 h=a.get(l),p=i.get(l),x=h?h.ok:null,d=p?p.ok:null;let m;h&&p?x===d?m="same":x===!1&&d===!0?m="improved":m="regressed":p&&!h?m="added":m="removed",o.push({fixtureId:l,before:x,after:d,change:m})}const c={regressed:0,improved:1,added:2,removed:3,same:4};return o.sort((l,h)=>{const p=c[l.change]-c[h.change];return p!==0?p:l.fixtureId.localeCompare(h.fixtureId)}),o}function zc({runA:s,runB:t,title:a="Regression Analysis"}){const i=Pa(s,t),n=i.filter(h=>h.change==="improved").length,o=i.filter(h=>h.change==="regressed").length,c=i.filter(h=>h.change==="same").length,l=i.filter(h=>h.change!=="same");return e.jsxs("div",{className:"eval-diff","data-testid":"eval-diff",children:[e.jsx("h3",{className:"eval-diff-title",children:a}),e.jsxs("div",{className:"eval-diff-subtitle muted",children:["Comparing ",e.jsx("code",{className:"mono",children:s.id})," →"," ",e.jsx("code",{className:"mono",children:t.id})]}),e.jsxs("div",{className:"eval-diff-stats","aria-label":"Diff summary",children:[e.jsxs("span",{className:"eval-diff-stat improved",children:[e.jsx("span",{className:"eval-diff-stat-icon","aria-hidden":!0,children:"+"}),n," improved"]}),e.jsxs("span",{className:"eval-diff-stat regressed",children:[e.jsx("span",{className:"eval-diff-stat-icon","aria-hidden":!0,children:"−"}),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(h=>e.jsxs("li",{"data-fixture-id":h.fixtureId,className:K("eval-diff-row",`is-${h.change}`),children:[e.jsx("span",{className:"eval-diff-fixture mono",children:h.fixtureId}),e.jsx("span",{className:"eval-diff-arrow","aria-hidden":!0,children:"→"}),e.jsxs("span",{className:"eval-diff-states",children:[e.jsx("span",{className:K("eval-diff-state",h.before?"is-pass":"is-fail"),children:h.before===null?"—":h.before?"pass":"fail"}),e.jsx("span",{className:"eval-diff-arrow-small","aria-hidden":!0,children:"→"}),e.jsx("span",{className:K("eval-diff-state",h.after?"is-pass":"is-fail"),children:h.after===null?"—":h.after?"pass":"fail"})]})]},h.fixtureId))})]})}function Rc({runId:s,variant:t="secondary",size:a="sm"}){const i=()=>{const n=$.getToken();window.open(`/api/eval/runs/${encodeURIComponent(s)}/export.csv?_t=${encodeURIComponent(n)}`,"_blank")};return e.jsxs(A,{variant:t,size:a,onClick:i,title:"Export results as CSV",children:[e.jsx(ls,{size:14,"aria-hidden":!0}),"Export CSV"]})}function Tc({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,h)=>l.ok!==h.ok?l.ok?1:-1:l.fixtureId.localeCompare(h.fixtureId));return e.jsxs("div",{className:"eval-run-detail","data-testid":"eval-run-detail",children:[e.jsxs(Y,{className:"eval-run-detail-header",children:[e.jsxs("div",{className:"eval-run-detail-header-row",children:[e.jsxs(ae,{children:[e.jsx(Je,{size:14,"aria-hidden":!0})," ",s.id]}),e.jsxs("div",{className:"eval-run-detail-actions",children:[e.jsx(Rc,{runId:s.id}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:i,title:"Close detail",children:[e.jsx(Ne,{size:12})," Close"]})]})]}),e.jsxs(ne,{children:[We(s.startedAt),s.finishedAt?` → ${We(s.finishedAt)}`:""," · ",s.suitePath]}),e.jsxs("div",{className:"eval-run-detail-summary",children:[e.jsxs("span",{className:K("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(Y,{className:"eval-diff-card",children:(()=>{const l=n.find(d=>d.id===a);if(!l)return e.jsxs("div",{className:"eval-diff-missing muted",children:["Baseline run ",e.jsx("code",{children:a})," not loaded. Pick another from the list."]});const h=Pa(l,s),p=h.filter(d=>d.change==="improved").length,x=h.filter(d=>d.change==="regressed").length;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"eval-diff-card-head",children:[e.jsxs("span",{className:"eval-diff-card-title",children:[e.jsx(ka,{size:14,"aria-hidden":!0})," Comparing ",l.id," → ",s.id]}),e.jsxs(A,{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:["−",x," regressed"]})]}),e.jsx(zc,{runA:l,runB:s})]})})()}):e.jsx(Y,{className:"eval-baseline-hint",children:e.jsx(ne,{children:"Tip: click another run in the list to use it as a baseline for diffing."})}),e.jsxs(Y,{className:"eval-fixtures-card",children:[e.jsxs(ae,{children:["Fixtures (",s.results.length,")"]}),c.length===0?e.jsx(ne,{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:K("eval-fixture-row",l.ok?"is-pass":"is-fail"),children:[e.jsx("span",{className:K("eval-fixture-pill",l.ok?"is-pass":"is-fail"),"aria-label":l.ok?"pass":"fail",children:l.ok?"✓":"✗"}),e.jsx("span",{className:"eval-fixture-id mono",children:l.fixtureId}),!l.ok&&l.checks?e.jsx("span",{className:"eval-fixture-fails muted",children:l.checks.filter(h=>!h.ok).map(h=>h.message).filter(Boolean).join(" · ")}):null,l.latencyMs!=null?e.jsxs("span",{className:"eval-fixture-latency muted",children:[Math.round(l.latencyMs),"ms"]}):null]},l.fixtureId))})]})]})}function $c({setActiveTab:s}){const t=re(),[a,i]=r.useState([]),[n,o]=r.useState(!0),[c,l]=r.useState(null),[h,p]=r.useState(null),[x,d]=r.useState(null),[m,u]=r.useState(!1),[g,N]=r.useState(null),z=r.useRef(!1),R=r.useCallback(async()=>{o(!0);try{const f=await $.get("/eval/runs");z.current||i(f.runs||[])}catch(f){z.current||t.error(`Failed to load eval runs: ${f.message}`)}finally{z.current||o(!1)}},[t]),b=r.useCallback(async f=>{u(!0);try{const v=await $.get(`/eval/runs/${encodeURIComponent(f)}`);z.current||d(v)}catch(v){z.current||(t.error(`Failed to load run ${f}: ${v.message}`),d(null))}finally{z.current||u(!1)}},[t]),w=r.useCallback(async f=>{try{const v=await $.get(`/eval/runs/${encodeURIComponent(f)}`);z.current||N(v)}catch(v){z.current||(t.error(`Failed to load run ${f}: ${v.message}`),N(null))}},[t]);r.useEffect(()=>(z.current=!1,R(),()=>{z.current=!0}),[R]);const T=async f=>{f!==c&&(l(f),p(null),N(null),await b(f))},j=async f=>{f!==c&&(p(f),await w(f))},k=[];return g&&k.push(g),x&&k.push(x),e.jsxs("div",{className:"view view-eval-report","data-testid":"eval-report",children:[e.jsxs("div",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h1",{className:"view-title",children:[e.jsx(Je,{size:20,"aria-hidden":!0})," Eval Reports"]}),e.jsx("p",{className:"view-subtitle muted",children:"Browse eval runs, inspect per-fixture results, and diff two runs to spot regressions."})]}),e.jsx("div",{className:"view-actions",children:e.jsxs(A,{variant:"secondary",size:"sm",onClick:R,disabled:n,children:[n?e.jsx(le,{size:"sm"}):e.jsx(ce,{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(pe,{icon:e.jsx(Je,{size:28}),title:"No eval runs yet",message:e.jsxs(e.Fragment,{children:["Run a suite via the CLI:"," ",e.jsx("code",{className:"mono",children:"bizar eval run ./path/to/fixtures"}),"."]})}):a.map(f=>e.jsxs("div",{className:"eval-run-card-wrap",children:[e.jsx(Da,{run:f,selected:f.id===c,onClick:()=>T(f.id)}),c&&f.id!==c?e.jsxs("button",{type:"button",className:"eval-baseline-btn",onClick:()=>j(f.id),title:"Use this run as a baseline for diffing",children:[e.jsx(ka,{size:10,"aria-hidden":!0}),"Use as baseline"]}):null]},f.id))}),e.jsx("div",{className:"eval-detail",children:m&&!x?e.jsxs("div",{className:"eval-detail-loading",children:[e.jsx(le,{size:"sm"}),e.jsx("span",{className:"muted",children:"Loading run details…"})]}):x?e.jsx(Tc,{run:x,compareRun:h,runsForDiff:k,onClearCompare:()=>{p(null),N(null)},onClearSelection:()=>{l(null),d(null),p(null),N(null)}}):e.jsx(Y,{className:"eval-detail-empty",children:e.jsx(pe,{icon:e.jsx(Je,{size:28}),title:"Select a run",message:"Pick an eval run from the list to view fixture-by-fixture results, latency, and per-check failure details."})})})]})]})}const Ac=Oe.memo($c),gt={overview:Yi,chat:ur,agents:jr,artifacts:qr,memory:Do,tasks:sl,activity:ml,background:oc,config:Qt,settings:Qt,marketplace:Dl,mods:Pl,schedules:Zl,skills:lo,history:Fo,minimax:Go,plugins:Ul,doctor:Nc,eval:Cc,evalReport:Ac},Mc="v4.5.0";function Ic(s,t,a,i){if(gt[s]){const c=gt[s];return e.jsx(c,{...t})}const n=a.find(c=>c.id===s);if(n)return e.jsx(_l,{viewId:n.id,reloadKey:i,activeTab:t.activeTab,setActiveTab:t.setActiveTab});const o=gt.overview;return e.jsx(o,{...t})}function Ec({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&&($.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(A,{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 Lc(){return e.jsx(ti,{children:e.jsx(ci,{children:e.jsx(Dc,{})})})}function Dc(){var te,ie,me;const s=re(),t=Te(),{isModalOpen:a}=t,i=r.useRef(!1),[n,o]=r.useState("overview"),[c,l]=r.useState(null),[h,p]=r.useState(null),[x,d]=r.useState("connecting"),[m,u]=r.useState(null),[g,N]=r.useState(!1),[z,R]=r.useState(null),[b,w]=r.useState(!1),[T,j]=r.useState(!1),[k,f]=r.useState([]),[v,L]=r.useState(!1),[S,y]=r.useState([]),[M,P]=r.useState(0),C=r.useRef(null),[D,Q]=r.useState(null);r.useEffect(()=>{let W=!1;return(async()=>{try{const E=await $.get("/mods/views");if(W)return;y(E.views||[])}catch{W||y([])}})(),()=>{W=!0}},[M,c==null?void 0:c.mods]),r.useEffect(()=>{if(!D)return;const W=D.on(E=>{((E==null?void 0:E.type)==="mod:change"||(E==null?void 0:E.type)==="mod:enabled"||(E==null?void 0:E.type)==="mod:installed")&&P(ee=>ee+1)});return()=>W()},[D]),r.useEffect(()=>{h!=null&&h.theme&&(As(h.theme),ps(h.theme))},[h==null?void 0:h.theme]),r.useEffect(()=>{i.current=a},[a]),r.useEffect(()=>{var ee;if(((ee=h==null?void 0:h.theme)==null?void 0:ee.mode)!=="system")return;const W=window.matchMedia("(prefers-color-scheme: light)"),E=()=>As(h.theme.mode);return W.addEventListener("change",E),()=>W.removeEventListener("change",E)},[(te=h==null?void 0:h.theme)==null?void 0:te.mode]);const O=r.useCallback(async()=>{let W=!1;const E=()=>Promise.all([$.get("/snapshot").catch(()=>null),$.get("/settings").catch(()=>null),$.get("/agents/stuck").catch(()=>null)]),ee=(U,oe,G)=>{U&&l(U),oe!=null&&oe.data&&p(oe.data),G!=null&&G.stuck&&f(G.stuck)};try{const U=await $.probeAuthStatus(),[oe,G,de]=await E();if(ee(oe,G,de),oe||G){u(null);return}if(!U.loopback){u("Dashboard server unreachable.");return}await new Promise(He=>setTimeout(He,1e3));const[$e,Ie,Be]=await E();ee($e,Ie,Be),!$e&&!Ie&&u("Dashboard server unreachable.")}catch(U){const oe=(U==null?void 0:U.message)??"unknown error";if(U instanceof Ka&&U.status===401){u(oe),w(!0),s.error(`Auth required: ${oe}`);return}u(oe),s.error(`Failed to load: ${oe}`)}},[s]);r.useEffect(()=>{let W=!1;const E=setTimeout(()=>{W||O()},0);return()=>{W=!0,clearTimeout(E)}},[O]),r.useEffect(()=>{let W=!1;return $.get("/settings").then(E=>{var U,oe;if(W)return;const ee=(oe=(U=E==null?void 0:E.data)==null?void 0:U.ui)==null?void 0:oe.defaultTab;ee&&o(ee)}).catch(()=>{}),()=>{W=!0}},[]),r.useEffect(()=>{let W=!1;const E=async()=>{try{const U=await $.get("/agents/stuck");W||f(oe=>{const G=U.stuck||[];return oe.length===0&&G.length>0&&s.warning(`${G.length} agent${G.length===1?"":"s"} stuck`,5e3),G})}catch{}},ee=setInterval(E,3e4);return E(),()=>{W=!0,clearInterval(ee)}},[]),r.useEffect(()=>{const W=new Ys;C.current=W,Q(W);const E=W.onStatus(U=>d(U)),ee=W.on(U=>{var oe;if(U.type==="snapshot"&&"data"in U&&U.data)l(G=>({...G??{},...U.data}));else if(U.type==="change"){const G=U,de=((oe=G.path)==null?void 0:oe.split("/").pop())||G.path||"";s.info(`File changed: ${de}`,2500)}else if(U.type==="tasks:change"){const G=U;l(de=>{if(!de)return de;const $e=(de.tasks||[]).map(Be=>Be.id===G.task.id?G.task:Be),Ie=$e.some(Be=>Be.id===G.task.id);return{...de,tasks:Ie?$e:[G.task,...$e]}})}else if(U.type==="tasks:delete"){const G=U;l(de=>de&&{...de,tasks:(de.tasks||[]).filter($e=>$e.id!==G.id)})}else if(U.type==="settings:change"){const G=U;G.settings&&p(G.settings)}else if(U.type==="project:change")$.get("/snapshot").then(G=>l(de=>({...de??{},...G}))).catch(()=>{});else if(U.type==="agents:change"||U.type==="schedules:change")$.get("/snapshot").then(G=>l(de=>({...de??{},...G}))).catch(()=>{});else if(U.type==="agent:status"||U.type==="agent:restarted"){const G=U;l(de=>{if(!de)return de;const $e=(de.agents||[]).map(Ie=>Ie.name===G.agent.name?G.agent:Ie);return{...de,agents:$e}})}else if(U.type==="artifact:change")$.get("/artifacts").then(G=>{l(de=>de&&{...de,artifacts:G.artifacts||[]})}).catch(()=>{});else if(U.type==="agent:stuck")f(U.agents||[]);else if(U.type==="dialog:show"){const G=U;G.dialog&&t.open({title:G.dialog.title,width:520,children:e.jsx(Di,{dialog:G.dialog,onClose:()=>t.close()})})}});return()=>{E(),ee(),W.close(),Q(null)}},[s]);const J=r.useCallback(W=>D?D.on(W):()=>{},[D]),_=r.useRef(0);r.useEffect(()=>{const W=()=>{_.current=Date.now()+1500};return document.addEventListener("mousedown",W,!0),document.addEventListener("click",W,!0),document.addEventListener("focusin",W,!0),document.addEventListener("keydown",W,!0),()=>{document.removeEventListener("mousedown",W,!0),document.removeEventListener("click",W,!0),document.removeEventListener("focusin",W,!0),document.removeEventListener("keydown",W,!0)}},[]),r.useEffect(()=>{const W={};yt.forEach((ee,U)=>{W[String(U+1)]=ee.id});const E=ee=>{var He,Fs,ws,Os;if((ee.metaKey||ee.ctrlKey)&&ee.key.toLowerCase()==="k"){ee.preventDefault(),j(!0);return}if(ee.key==="/"&&!ee.metaKey&&!ee.ctrlKey){const Ss=(Fs=(He=ee.target)==null?void 0:He.tagName)==null?void 0:Fs.toLowerCase();if(Ss!=="input"&&Ss!=="textarea"&&!((ws=ee.target)!=null&&ws.isContentEditable)){ee.preventDefault(),j(!0);return}}const U=document.activeElement;if(!U||U===document.body||U===document.documentElement)return;const G=ee.target,de=(Os=G==null?void 0:G.tagName)==null?void 0:Os.toLowerCase(),$e=de==="input"||de==="textarea"||de==="select"||de==="button"||de==="option"||de==="label"||!!(G!=null&&G.isContentEditable);let Ie=!1;if(G&&typeof G.closest=="function"&&(Ie=!!G.closest('form, [role="dialog"], [contenteditable], [data-no-key]')),ee.repeat||i.current||$e||Ie||ee.metaKey||ee.ctrlKey||ee.altKey||ee.shiftKey||Date.now()<_.current)return;const Be=W[ee.key];Be&&(ee.preventDefault(),F(Be))};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[]);const q=r.useMemo(()=>async()=>{try{const W=await $.get("/snapshot");l(E=>({...E??{},...W}))}catch(W){s.error(`Refresh failed: ${W.message}`)}},[s]),F=r.useCallback(W=>{o(W),N(W==="settings")},[]),V=r.useMemo(()=>{const W=S.map(E=>({id:E.id,label:E.label,icon:E.kind==="iframe"?cs:Ls,isMod:!0,modId:E.modId}));return[...yt,...W]},[S]),X=r.useMemo(()=>c&&h?Ic(n,{snapshot:c,settings:h,activeTab:n,setActiveTab:F,refreshSnapshot:q,settingsMode:g,settingsActiveSection:z,setSettingsActiveSection:R},S,M):null,[n,c,h,S,M,q,g,z,R,F]),B=async()=>{try{const W=await $.get("/projects");l(E=>{var ee;return E&&{...E,projects:W.projects||[],activeProject:((ee=W.projects)==null?void 0:ee.find(U=>U.id===W.active))||null}})}catch(W){s.error(`Projects refresh failed: ${W.message}`)}},se=async W=>{try{await $.post(`/projects/${encodeURIComponent(W)}/activate`),l(E=>E&&{...E,activeProject:E.projects.find(ee=>ee.id===W)||null})}catch(E){s.error(`Activate failed: ${E.message}`)}},xe=W=>{const E=W.type;if(E==="agent")F("agents");else if(E==="task")F("tasks");else if(E==="mod")F("mods");else if(E==="schedule")F("schedules");else if(E==="project"){const ee=W.item.id;se(ee)}else if(E==="command")s.info(`/${W.item.name} — run from the TUI`,2500);else if(E==="setting"){const ee=W.item.id||W.item.path||"";F("settings");const U=oe=>{if(oe<=0)return;const G=ee?document.querySelector(`[data-setting-id="${CSS.escape(ee)}"]`):null;G?(G.scrollIntoView({behavior:"smooth",block:"center"}),G.classList.remove("setting-flash"),G.offsetWidth,G.classList.add("setting-flash"),window.setTimeout(()=>G.classList.remove("setting-flash"),1500)):window.setTimeout(()=>U(oe-1),80)};window.setTimeout(()=>U(15),60)}},Ce=((ie=h==null?void 0:h.ui)==null?void 0:ie.layout)||"topnav",H=((me=h==null?void 0:h.ui)==null?void 0:me.showHeader)!==!1;return e.jsxs("div",{className:"app","data-layout":Ce,"data-active-tab":n,children:[e.jsx("a",{className:"skip-to-main",href:"#main-content",children:"Skip to main content"}),H&&e.jsx(vi,{activeTab:n,onTabChange:F,wsStatus:x,version:Mc,activeProject:(c==null?void 0:c.activeProject)||null,projects:(c==null?void 0:c.projects)||[],onProjectChange:se,onProjectsRefresh:B,onOpenSearch:()=>j(!0),settings:h,notificationsSlot:e.jsx(Ri,{wsSubscribe:J}),showTabs:Ce==="topnav",extraTabs:V}),k.length>0&&!v&&e.jsxs("div",{className:"stuck-banner",role:"alert",children:[e.jsx(ke,{size:16}),e.jsxs("span",{children:[e.jsx("strong",{children:k.length})," agent",k.length===1?"":"s"," stuck:"," ",e.jsx("span",{className:"mono",children:k.map(W=>W.name).join(", ")})]}),e.jsx(A,{variant:"secondary",size:"sm",onClick:()=>{F("agents"),L(!0)},children:"Review"}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Dismiss",onClick:()=>L(!0),children:e.jsx(Ne,{size:14})})]}),e.jsxs("div",{className:"layout-body",children:[Ce!=="topnav"&&e.jsx(wi,{tabs:V,activeTab:n,onTabChange:F,settingsMode:g,settingsActiveSection:z,onSettingsSectionChange:R,onExitSettings:()=>F("overview")}),e.jsxs("main",{className:"content",id:"main-content",tabIndex:-1,children:[m&&e.jsxs("div",{className:"boot-error",children:[e.jsx("h2",{children:"Dashboard unavailable"}),e.jsx("p",{children:m}),b&&e.jsx(Ec,{onSaved:()=>{w(!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||!h)&&e.jsxs("div",{className:"loading",children:[e.jsx(le,{size:"lg"}),e.jsx("p",{children:"Loading Bizar…"})]}),X&&e.jsx(r.Suspense,{fallback:e.jsxs("div",{className:"loading",children:[e.jsx(le,{size:"lg"}),e.jsx("p",{children:"Loading…"})]}),children:e.jsx(Pc,{children:X})})]})]}),e.jsx(Si,{open:T,onClose:()=>j(!1),onSelect:xe})]})}class Pc extends r.Component{constructor(){super(...arguments);Cs(this,"state",{err:null});Cs(this,"reset",()=>this.setState({err:null}))}static getDerivedStateFromError(a){return{err:a}}componentDidCatch(a,i){console.error("[ViewErrorBoundary] caught render error:",a,i==null?void 0:i.componentStack)}render(){return this.state.err?e.jsxs("div",{className:"view-error-fallback",role:"alert",children:[e.jsx(ke,{size:20}),e.jsxs("div",{className:"view-error-body",children:[e.jsx("strong",{children:"This view crashed."}),e.jsx("pre",{children:this.state.err.message}),e.jsx(A,{variant:"secondary",size:"sm",onClick:this.reset,children:"Retry"})]})]}):this.props.children}}function Fc(){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(Ya,{}):e.jsx(Lc,{})}const Fa=document.getElementById("root");if(!Fa)throw new Error("Root element #root not found");Xa(Fa).render(e.jsx(r.StrictMode,{children:e.jsx(Fc,{})}));