@polderlabs/bizar 5.4.0 → 5.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/bizar-dash/dist/assets/{EnvVarsSection-DqvB8ZcJ.js → EnvVarsSection-L413CQEI.js} +3 -3
  2. package/bizar-dash/dist/assets/{EnvVarsSection-DqvB8ZcJ.js.map → EnvVarsSection-L413CQEI.js.map} +1 -1
  3. package/bizar-dash/dist/assets/{MobileChat-DRXP2ERQ.js → MobileChat-0kGQb1S6.js} +1 -1
  4. package/bizar-dash/dist/assets/{MobileChat-DRXP2ERQ.js.map → MobileChat-0kGQb1S6.js.map} +1 -1
  5. package/bizar-dash/dist/assets/MobileSettings-Cq1oFIdO.js +1 -0
  6. package/bizar-dash/dist/assets/{MobileSettings-CVW9VhEo.js.map → MobileSettings-Cq1oFIdO.js.map} +1 -1
  7. package/bizar-dash/dist/assets/{Toast-CcZVVN4i.js → Toast-C6f1zFJ2.js} +1 -1
  8. package/bizar-dash/dist/assets/{Toast-CcZVVN4i.js.map → Toast-C6f1zFJ2.js.map} +1 -1
  9. package/bizar-dash/dist/assets/{icons-OMEGx5KA.js → icons-BsWXWkEF.js} +121 -126
  10. package/bizar-dash/dist/assets/icons-BsWXWkEF.js.map +1 -0
  11. package/bizar-dash/dist/assets/main-BklYy02e.css +1 -0
  12. package/bizar-dash/dist/assets/main-CBTgYSeG.js +18 -0
  13. package/bizar-dash/dist/assets/main-CBTgYSeG.js.map +1 -0
  14. package/bizar-dash/dist/assets/mobile-CsaN4CxH.js +1 -0
  15. package/bizar-dash/dist/assets/{mobile-XN2P7YfM.js.map → mobile-CsaN4CxH.js.map} +1 -1
  16. package/bizar-dash/dist/assets/{mobile-layout-D6V-7WnA.css → mobile-layout-CJnZNLy3.css} +1 -1
  17. package/bizar-dash/dist/assets/mobile-layout-iFBdjEE4.js +2 -0
  18. package/bizar-dash/dist/assets/mobile-layout-iFBdjEE4.js.map +1 -0
  19. package/bizar-dash/dist/assets/{useSlashCommands-iyoW95UB.js → useSlashCommands-DGJcC9iQ.js} +2 -2
  20. package/bizar-dash/dist/assets/{useSlashCommands-iyoW95UB.js.map → useSlashCommands-DGJcC9iQ.js.map} +1 -1
  21. package/bizar-dash/dist/index.html +8 -8
  22. package/bizar-dash/dist/mobile.html +4 -4
  23. package/bizar-dash/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -1
  24. package/bizar-dash/src/server/backup-store.mjs +6 -1
  25. package/bizar-dash/src/server/bg-spawner.mjs +574 -0
  26. package/bizar-dash/src/server/memory-lightrag.mjs +242 -0
  27. package/bizar-dash/src/server/memory-store.mjs +43 -3
  28. package/bizar-dash/src/server/routes/background.mjs +143 -0
  29. package/bizar-dash/src/server/routes/lightrag.mjs +10 -0
  30. package/bizar-dash/src/server/routes/memory.mjs +8 -0
  31. package/bizar-dash/src/server/server.mjs +22 -0
  32. package/bizar-dash/src/web/App.tsx +3 -0
  33. package/bizar-dash/src/web/MobileApp.tsx +1 -10
  34. package/bizar-dash/src/web/components/InstallConfirmDialog.tsx +1 -1
  35. package/bizar-dash/src/web/components/SettingsNav.tsx +1 -10
  36. package/bizar-dash/src/web/lib/types.ts +39 -1
  37. package/bizar-dash/src/web/styles/main.css +43 -0
  38. package/bizar-dash/src/web/styles/mobile-layout.css +7 -5
  39. package/bizar-dash/src/web/styles/settings.css +46 -0
  40. package/bizar-dash/src/web/views/BackgroundAgents.tsx +399 -30
  41. package/bizar-dash/src/web/views/Settings.tsx +12 -12
  42. package/bizar-dash/src/web/views/SpawnAgentModal.tsx +221 -0
  43. package/bizar-dash/tests/BackgroundAgents.test.tsx +160 -0
  44. package/bizar-dash/tests/background-pause-resume.test.mjs +46 -0
  45. package/bizar-dash/tests/background-spawn-from-ui.test.mjs +36 -0
  46. package/bizar-dash/tests/background-steer.test.mjs +42 -0
  47. package/bizar-dash/tests/lightrag-startup-hook.test.mjs +206 -0
  48. package/bizar-dash/tests/memory-auto-reindex.test.mjs +196 -0
  49. package/bizar-dash/tests/memory-cli.test.mjs +1 -1
  50. package/bizar-dash/tests/memory-default-vault.test.mjs +90 -3
  51. package/bizar-dash/tests/memory-lightrag-extended.test.mjs +131 -0
  52. package/bizar-dash/tests/mobile-layout.test.tsx +36 -0
  53. package/bizar-dash/tests/settings-layout.test.tsx +3 -3
  54. package/bizar-dash/tests/settings-nav.test.tsx +7 -5
  55. package/cli/bin.mjs +16 -0
  56. package/cli/commands/deploy/docker.mjs +2 -1
  57. package/cli/commands/lightrag.mjs +171 -0
  58. package/cli/commands/service.mjs +7 -0
  59. package/cli/commands/util.mjs +8 -1
  60. package/cli/init.mjs +1 -1
  61. package/cli/post-install-smoke.mjs +230 -0
  62. package/cli/provision.mjs +177 -0
  63. package/cli/provision.test.mjs +180 -0
  64. package/cli/service-controller.mjs +378 -28
  65. package/cli/service-controller.test.mjs +100 -0
  66. package/cli/service-env.mjs +139 -0
  67. package/cli/service.mjs +23 -0
  68. package/config/agents/_shared/AGENT_BASELINE.md +6 -6
  69. package/install.sh +87 -6
  70. package/package.json +1 -1
  71. package/plugins/bizar/index.ts +147 -0
  72. package/plugins/bizar/src/background-state.ts +84 -5
  73. package/plugins/bizar/src/background.ts +388 -10
  74. package/plugins/bizar/src/hooks/memory-inject.ts +247 -0
  75. package/plugins/bizar/src/hooks/memory-write-on-end.ts +188 -0
  76. package/plugins/bizar/src/opencode-runner.ts +87 -1
  77. package/plugins/bizar/src/tools/bg-pause.ts +77 -0
  78. package/plugins/bizar/src/tools/bg-report-progress.ts +101 -0
  79. package/plugins/bizar/src/tools/bg-resume.ts +72 -0
  80. package/plugins/bizar/src/tools/bg-send-message.ts +105 -0
  81. package/plugins/bizar/src/tools/bg-spawn.ts +13 -6
  82. package/plugins/bizar/src/tools/bg-status.ts +10 -0
  83. package/plugins/bizar/src/tools/memory-list.ts +135 -0
  84. package/plugins/bizar/src/tools/memory-read.ts +142 -0
  85. package/plugins/bizar/src/tools/memory-search.ts +228 -0
  86. package/plugins/bizar/src/tools/memory-write.ts +183 -0
  87. package/plugins/bizar/tests/memory-write-on-end.test.ts +92 -0
  88. package/plugins/bizar/tests/tools/bg-pause.test.ts +64 -0
  89. package/plugins/bizar/tests/tools/bg-report-progress.test.ts +82 -0
  90. package/plugins/bizar/tests/tools/bg-resume.test.ts +43 -0
  91. package/plugins/bizar/tests/tools/bg-send-message.test.ts +46 -0
  92. package/bizar-dash/dist/assets/MobileSettings-CVW9VhEo.js +0 -1
  93. package/bizar-dash/dist/assets/icons-OMEGx5KA.js.map +0 -1
  94. package/bizar-dash/dist/assets/main-CMAGZouj.js +0 -16
  95. package/bizar-dash/dist/assets/main-CMAGZouj.js.map +0 -1
  96. package/bizar-dash/dist/assets/main-O2tZVdHm.css +0 -1
  97. package/bizar-dash/dist/assets/mobile-XN2P7YfM.js +0 -1
  98. package/bizar-dash/dist/assets/mobile-layout-DqTxvXZp.js +0 -2
  99. package/bizar-dash/dist/assets/mobile-layout-DqTxvXZp.js.map +0 -1
@@ -1,16 +0,0 @@
1
- var Ba=Object.defineProperty;var Ua=(s,t,a)=>t in s?Ba(s,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):s[t]=a;var ks=(s,t,a)=>Ua(s,typeof t!="symbol"?t+"":t,a);import{a as T,c as V,f as Ce,b as _e,S as oe,t as Zt,e as _a,p as Wa,d as xs,g as Ts,_ as qa,W as ea,A as Va,M as Ha}from"./mobile-layout-DqTxvXZp.js";import{r,j as e,a as sa,R as Oe,b as Ga}from"./react-vendor-Dn4wqh4Z.js";import{X as Ne,A as bt,R as de,F as Ka,H as Ya,a as Xa,C as ta,b as Fe,c as Ja,d as We,e as Xe,L as aa,M as Xs,B as Ye,f as Hs,S as Rs,g as De,h as Qa,i as He,j as Pe,P as ts,k as na,l as as,m as $s,n as Nt,o as Qe,p as ia,q as kt,r as ye,s as Za,t as ze,u as ra,v as Pt,T as ns,w as en,x as _s,G as sn,y as la,z as tn,D as gs,E as Te,I as qe,J as wt,K as ys,N as be,O as is,Q as Gs,U as rs,V as fs,W as pt,Y as an,Z as ke,_ as St,$ as Ct,a0 as ps,a1 as nn,a2 as Js,a3 as js,a4 as rn,a5 as Es,a6 as ls,a7 as oa,a8 as ca,a9 as As,aa as ln,ab as Ls,ac as on,ad as cn,ae as dn,af as Qs,ag as mn,ah as un,ai as hn,aj as xn,ak as pn,al as gn,am as Ft,an as da,ao as zt,ap as fn,aq as jn,ar as ma,as as vn,at as yn,au as bn,av as Nn,aw as kn,ax as wn,ay as Sn,az as gt,aA as Tt,aB as Rt,aC as os,aD as ua,aE as vs,aF as Cn,aG as zn,aH as Ks,aI as Tn,aJ as Ms,aK as Rn,aL as $n,aM as ha,aN as xa,aO as Is,aP as ft,aQ as $t,aR as pa,aS as xe,aT as An,aU as Mn,aV as ga,aW as In,aX as En,aY as Ln,aZ as fa,a_ as et,a$ as ja,b0 as At,b1 as Dn,b2 as Pn,b3 as Fn,b4 as va,b5 as On,b6 as Bn,b7 as Un,b8 as _n,b9 as ya}from"./icons-OMEGx5KA.js";import{B as $,C as G,a as te,b as ne,A as Wn,U as qn,G as Vn,E as Hn,T as Gn,S as Kn,H as Yn,c as Xn}from"./EnvVarsSection-DqvB8ZcJ.js";import{u as re,T as Jn}from"./Toast-CcZVVN4i.js";import{V as Mt,C as Qn,u as Zn,a as ei,b as si,c as ti}from"./useSlashCommands-iyoW95UB.js";import{M as ba,r as Na}from"./markdown-C6mXtQxD.js";import"./vendor-CeHGtduv.js";const ka=r.createContext(null),ai=["button:not([disabled])","[href]","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(", ");function $e(){const s=r.useContext(ka);return s||{open:()=>"",close:()=>{},isModalOpen:!1}}function ni({children:s}){const[t,a]=r.useState([]),i=r.useCallback(c=>{a(o=>{if(!c)return o.slice(0,-1);const l=o.findIndex(x=>x.id===c);return l===-1||l!==o.length-1?o:o.slice(0,-1)})},[]),n=r.useCallback(c=>{const o=`m${Math.random().toString(36).slice(2,9)}`;return a(l=>[...l,{...c,id:o}]),o},[]);return r.useEffect(()=>{if(t.length===0)return;const c=o=>{o.key==="Escape"&&(o.stopPropagation(),i())};return document.addEventListener("keydown",c),()=>document.removeEventListener("keydown",c)},[t.length,i]),e.jsxs(ka.Provider,{value:{open:n,close:i,isModalOpen:t.length>0},children:[s,typeof document<"u"&&sa.createPortal(e.jsx("div",{className:"modal-stack","aria-hidden":t.length===0,children:t.map((c,o)=>e.jsx(ii,{modal:c,onClose:()=>{var l;(l=c.onClose)==null||l.call(c),i(c.id)},depth:o},c.id))}),document.body)]})}function ii({modal:s,onClose:t,depth:a}){const i=r.useRef(null),n=r.useRef(null),c=r.useId(),o=()=>{const l=i.current;return l?Array.from(l.querySelectorAll(ai)).filter(x=>!x.hasAttribute("disabled")&&x.tabIndex!==-1):[]};return r.useEffect(()=>{var p;n.current=document.activeElement instanceof HTMLElement?document.activeElement:null,(p=o()[0]??i.current)==null||p.focus();const x=u=>{var j,k,z;if(u.key!=="Tab")return;const d=o();if(d.length===0){u.preventDefault(),(j=i.current)==null||j.focus();return}const m=d[0],h=d[d.length-1],g=document.activeElement instanceof HTMLElement?document.activeElement:null;if(u.shiftKey){(!g||g===m||!((k=i.current)!=null&&k.contains(g)))&&(u.preventDefault(),h.focus());return}(!g||g===h||!((z=i.current)!=null&&z.contains(g)))&&(u.preventDefault(),m.focus())};return document.addEventListener("keydown",x),()=>{document.removeEventListener("keydown",x);const u=n.current;u&&u.isConnected&&u.focus()}},[]),e.jsx("div",{className:"modal-backdrop",onClick:l=>{l.stopPropagation(),l.target===l.currentTarget&&t()},style:a>0?{background:"rgba(0,0,0,0.4)"}:void 0,children:e.jsxs("div",{ref:i,className:"modal",role:"dialog","aria-modal":"true","aria-labelledby":s.title?c:void 0,tabIndex:-1,onClick:l=>l.stopPropagation(),style:s.width?{maxWidth:s.width}:void 0,children:[s.title&&e.jsxs("header",{className:"modal-header",children:[e.jsx("h2",{id:c,className:"modal-title",children:s.title}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Close",onClick:t,children:e.jsx(Ne,{size:16})})]}),e.jsx("div",{className:"modal-body",children:s.children}),s.footer&&e.jsx("footer",{className:"modal-footer",children:s.footer})]})})}const ri=200,li=5*60*1e3,ss=new Map;function oi(s){const t=ss.get(s);return t?Date.now()-t.ts>li?(ss.delete(s),null):t.data:null}function st(s,t){ss.size>=ri&&[...ss.entries()].sort((i,n)=>i[1].ts-n[1].ts).slice(0,50).map(([i])=>i).forEach(i=>ss.delete(i)),ss.set(s,{data:t,ts:Date.now()})}function ci(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 di(s){return[...s].sort((t,a)=>t.isDir!==a.isDir?t.isDir?-1:1:t.name.localeCompare(a.name,void 0,{sensitivity:"base"}))}function mi(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 wa({value:s,onChange:t,initialPath:a,projectsDirectory:i,rootLabel:n="Home",height:c=360}){const[o,l]=r.useState(a??i??""),[x,p]=r.useState(new Set),[u,d]=r.useState(-1),[m,h]=r.useState(null),[g,j]=r.useState({}),[k,z]=r.useState(!1),[N,S]=r.useState(null),[E,v]=r.useState(!1),[b,w]=r.useState(""),[f,L]=r.useState(null),[R,y]=r.useState(!1),A=r.useRef(null),P=r.useCallback(async I=>{try{const Q=oi(I);if(Q)return Q;const U=await T.get("/fs?path="+encodeURIComponent(I));return st(I,U),U}catch{return null}},[]),C=r.useCallback(async I=>{var Q;z(!0),S(null);try{const U=await T.get("/fs?path="+encodeURIComponent(I));st(I,U),h(U),d(-1)}catch(U){const le=((Q=U.data)==null?void 0:Q.message)??U.message??"Failed to load directory";S(le)}finally{z(!1)}},[]);r.useEffect(()=>{o?C(o):T.get("/fs").then(I=>{st("",I),h(I),l(I.path),I.path!==s&&t(I.path)}).catch(()=>{S("Could not determine home directory."),z(!1)})},[o]),r.useEffect(()=>{s&&s!==o&&l(s)},[s]);const D=m?di(m.entries):[],Y=D.filter(I=>I.isDir),O=D,J=I=>{I.isDir&&(l(I.path),t(I.path))},ae=()=>{m!=null&&m.parent&&(l(m.parent),t(m.parent))},ee=I=>{I!==o&&(l(I),t(I))},F=async()=>{const I=await P("");I&&(l(I.path),t(I.path))},H=async()=>{if(!i)return;const I=await P(i);I&&(l(I.path),t(I.path))},K=()=>{v(!0),w(""),L(null),setTimeout(()=>{var I;return(I=A.current)==null?void 0:I.focus()},0)},B=()=>{v(!1),w(""),L(null)},Z=async()=>{var Q;const I=mi(b);if(!I.ok){L(I.reason);return}y(!0),L(null);try{const U=await T.post("/fs/mkdir",{parent:o,name:b.trim()});ss.delete(o),await C(o),t(U.path),v(!1),w("")}catch(U){const le=U;le.status===409?L(`A folder named "${b.trim()}" already exists.`):L(((Q=le.data)==null?void 0:Q.message)??U.message??"Failed to create folder.")}finally{y(!1)}},he=I=>{I.key==="Enter"?(I.preventDefault(),Z()):I.key==="Escape"&&(I.preventDefault(),B())},we=I=>{p(Q=>{const U=new Set(Q);return U.has(I)?U.delete(I):U.add(I),U}),g[I]||P(I).then(Q=>{Q&&j(U=>({...U,[I]:Q.entries.filter(le=>le.isDir)}))})},W=I=>{if(!m)return;const Q=O.filter(q=>q.isDir),U=O.filter(q=>!q.isDir),le=[...Q,...U];if(I.key==="ArrowDown")I.preventDefault(),d(q=>Math.min(q+1,le.length-1));else if(I.key==="ArrowUp")I.preventDefault(),d(q=>Math.max(q-1,0));else if(I.key==="Enter"||I.key===" "){I.preventDefault();const q=le[u];q&&(I.key==="Enter"&&q.isDir?J(q):q.isDir&&t(q.path))}else I.key==="Backspace"&&(I.preventDefault(),ae())},se=ci((m==null?void 0:m.path)??o??"/"),ie=m==null?void 0:m.parent,me=ie!=null,_=o.split("/").filter(Boolean).at(-1)??"/";return e.jsxs("div",{className:"file-browser",onKeyDown:W,tabIndex:-1,children:[e.jsx("div",{className:"file-browser-breadcrumb",role:"navigation","aria-label":"Path breadcrumb",children:se.map((I,Q)=>e.jsxs("span",{className:"file-browser-breadcrumb-item",children:[Q>0&&e.jsx("span",{className:"file-browser-breadcrumb-sep","aria-hidden":!0,children:"/"}),e.jsx("button",{type:"button",className:"file-browser-breadcrumb-btn",onClick:()=>ee(I.path),title:I.path,children:Q===0?I.path==="/"?"/":n:I.label})]},I.path))}),e.jsxs("div",{className:"file-browser-toolbar",children:[e.jsxs("div",{className:"file-browser-toolbar-left",children:[e.jsx("button",{type:"button",className:"file-browser-tool-btn",onClick:ae,disabled:!me,title:"Go up (Backspace)","aria-label":"Go up one level",children:e.jsx(bt,{size:13})}),e.jsx("button",{type:"button",className:"file-browser-tool-btn",onClick:()=>C(o),disabled:k,title:"Refresh","aria-label":"Refresh",children:e.jsx(de,{size:13,className:k?"spin":""})}),e.jsx("button",{type:"button",className:"file-browser-tool-btn",onClick:K,title:"New folder","aria-label":"Create new folder",children:e.jsx(Ka,{size:13})}),e.jsxs("div",{className:"file-browser-chips",children:[e.jsxs("button",{type:"button",className:"file-browser-chip",onClick:F,children:[e.jsx(Ya,{size:11})," ",n]}),i&&e.jsxs("button",{type:"button",className:"file-browser-chip",onClick:H,title:i,children:[e.jsx(Xa,{size:11})," ",i.split("/").filter(Boolean).at(-1)??"Projects"]})]})]}),E?e.jsxs("div",{className:"file-browser-mkdir",children:[e.jsx("input",{ref:A,type:"text",className:"file-browser-mkdir-input",placeholder:"Folder name",value:b,onChange:I=>{w(I.target.value),L(null)},onKeyDown:he,"aria-label":"New folder name","aria-invalid":f?"true":void 0,"aria-describedby":f?"mkdir-error":void 0,disabled:R,maxLength:255}),f?e.jsx("span",{id:"mkdir-error",className:"file-browser-mkdir-error",role:"alert",children:f}):e.jsx("span",{className:"file-browser-mkdir-hint",children:"Enter to create, Esc to cancel"})]}):e.jsx("span",{className:"file-browser-count-hint",children:k?"…":`${D.length} in ${_}`})]}),N&&e.jsxs("div",{className:"file-browser-error",children:[e.jsx(ta,{size:13}),e.jsx("span",{children:N}),e.jsx("button",{type:"button",className:"file-browser-retry",onClick:()=>C(o),children:"Retry"})]}),e.jsxs("div",{className:"file-browser-body",style:{height:c},children:[e.jsx("div",{className:"file-browser-pane file-browser-tree","aria-label":"Folder tree",children:k&&!m?e.jsx(ui,{}):e.jsx(Sa,{path:o,entries:Y,expanded:x,childrenMap:g,onToggle:we,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"})]}),k&&!m?e.jsx(hi,{}):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((I,Q)=>{const U=I.isDir,le=Q===u,q=I.path===s;return e.jsxs("div",{role:"option","aria-selected":q,className:["file-browser-row",U?"file-browser-row--dir":"file-browser-row--file",le&&"file-browser-row--selected",q&&U&&"file-browser-row--active",!U&&"file-browser-row--disabled"].filter(Boolean).join(" "),onClick:()=>{U&&(d(Q),t(I.path))},onDoubleClick:()=>{U&&J(I)},title:I.path,children:[e.jsx("span",{className:"file-browser-row-icon",children:U?e.jsx(Fe,{size:13}):e.jsx(Ja,{size:13})}),e.jsx("span",{className:"file-browser-row-name",children:I.name}),e.jsx("span",{className:"file-browser-row-type",children:U?"Folder":""})]},I.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 Sa({path:s,entries:t,expanded:a,childrenMap:i,onToggle:n,onNavigate:c,level:o}){return e.jsx("ul",{className:"file-browser-tree-list",role:"group",children:t.map(l=>{const x=a.has(l.path),p=i[l.path]??[];return e.jsxs("li",{className:"file-browser-tree-node",children:[e.jsxs("div",{className:["file-browser-tree-row",x&&"file-browser-tree-row--expanded"].filter(Boolean).join(" "),style:{paddingLeft:`${o*16+8}px`},children:[e.jsx("button",{type:"button",className:"file-browser-tree-toggle",onClick:u=>{u.stopPropagation(),n(l.path)},"aria-label":x?"Collapse":"Expand",children:(p.length>0,x?e.jsx(We,{size:11}):e.jsx(Xe,{size:11}))}),e.jsxs("button",{type:"button",className:"file-browser-tree-name",onClick:()=>c(l),title:l.path,children:[e.jsx(Fe,{size:12}),e.jsx("span",{children:l.name})]})]}),x&&p.length>0&&e.jsx(Sa,{path:l.path,entries:p,expanded:a,childrenMap:i,onToggle:n,onNavigate:c,level:o+1})]},l.path)})})}function ui(){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 hi(){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 jt=[{id:"overview",label:"Overview",icon:aa},{id:"chat",label:"Chat",icon:Xs},{id:"agents",label:"Agents",icon:Ye},{id:"artifacts",label:"Glyphs",icon:Hs},{id:"tasks",label:"Tasks",icon:Rs},{id:"activity",label:"Activity",icon:De},{id:"background",label:"Active",icon:Qa},{id:"skills",label:"Skills",icon:He},{id:"memory",label:"Memory",icon:Pe},{id:"mods",label:"Mods",icon:ts},{id:"marketplace",label:"Marketplace",icon:na},{id:"schedules",label:"Schedules",icon:as},{id:"plugins",label:"Plugins",icon:ts},{id:"history",label:"History",icon:$s},{id:"minimax",label:"Usage",icon:Nt},{id:"eval",label:"Eval",icon:Qe},{id:"doctor",label:"Doctor",icon:ia},{id:"settings",label:"Settings",icon:kt}];function xi({activeTab:s,onTabChange:t,wsStatus:a,version:i,activeProject:n,projects:c,onProjectChange:o,onProjectsRefresh:l,onOpenSearch:x,settings:p,rightSlot:u,notificationsSlot:d,showTabs:m=!0,extraTabs:h}){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(pi,{activeProject:n,projects:c,onChange:o,onRefresh:l,settings:p??null}),e.jsxs("button",{type:"button",className:"topbar-search",onClick:x,title:"Search (Ctrl/Cmd+K)","aria-label":"Open search",children:[e.jsx(ye,{size:14}),e.jsx("span",{className:"muted",children:"Search…"}),e.jsx("kbd",{children:"⌘K"})]}),e.jsx("div",{className:"topbar-spacer"}),e.jsxs("div",{className:"topbar-right",children:[d,u,e.jsxs("div",{className:V("ws-status",`ws-${a}`),title:`WebSocket: ${a}`,children:[e.jsx("span",{className:"ws-dot"}),e.jsx("span",{className:"ws-label",children:a})]})]})]}),m&&e.jsxs("nav",{className:"tabs-row",role:"tablist","aria-label":"Primary tabs",children:[jt.map(g=>{const j=g.icon,k=g.id===s;return e.jsxs("button",{type:"button",role:"tab","aria-selected":k,className:V("tab",k&&"tab-active"),onClick:()=>t(g.id),title:g.label,children:[e.jsx(j,{size:14,className:"tab-icon"}),e.jsx("span",{className:"tab-label",children:g.label}),g.id==="settings"&&k&&e.jsx("span",{className:"settings-mode-indicator",title:"Settings mode active",children:e.jsx(Za,{size:12})})]},g.id)}),h&&h.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"tab-separator","aria-hidden":"true"}),h.map(g=>{const j=g.icon,k=g.id===s;return e.jsxs("button",{type:"button",role:"tab","aria-selected":k,className:V("tab","tab-mod",k&&"tab-active"),onClick:()=>t(g.id),title:`${g.label} (mod)`,children:[e.jsx(j,{size:14,className:"tab-icon"}),e.jsx("span",{className:"tab-label",children:g.label}),e.jsx("span",{className:"tab-badge",children:"mod"})]},g.id)})]})]})]})}function pi({activeProject:s,projects:t,onChange:a,onRefresh:i,settings:n}){const[c,o]=r.useState(!1),l=$e();r.useEffect(()=>{if(!c)return;const p=()=>o(!1);return document.addEventListener("click",p),()=>document.removeEventListener("click",p)},[c]);const x=()=>{l.open({title:"Add project",children:e.jsx(gi,{settings:n,onAdd:async(p,u)=>{try{await T.post("/projects",{path:p,name:u}),i(),o(!1),l.close()}catch(d){alert(`Add failed: ${d.message}`)}}}),footer:e.jsx("div",{className:"modal-footer-actions",children:e.jsx($,{variant:"ghost",onClick:()=>l.close(),children:"Cancel"})})})};return e.jsxs("div",{className:"project-selector",onClick:p=>p.stopPropagation(),children:[e.jsxs("button",{type:"button",className:"project-selector-btn",onClick:()=>o(p=>!p),title:"Switch active project","aria-haspopup":"menu","aria-expanded":c,children:[e.jsx(Fe,{size:14}),e.jsx("span",{className:"project-selector-name",children:(s==null?void 0:s.name)||"(no project)"}),e.jsx(We,{size:12})]}),c&&e.jsxs("div",{className:"project-selector-menu",children:[e.jsxs("div",{className:"project-selector-menu-head",children:[e.jsxs("span",{className:"muted",children:[t.length," project",t.length===1?"":"s"]}),e.jsxs("div",{className:"project-selector-menu-actions",children:[e.jsx("button",{type:"button",className:"icon-btn",onClick:i,title:"Refresh","aria-label":"Refresh projects",children:e.jsx(de,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn",onClick:x,title:"Add project","aria-label":"Add project",children:e.jsx(ze,{size:12})})]})]}),e.jsxs("ul",{className:"project-selector-list",children:[t.length===0&&e.jsx("li",{className:"muted project-selector-empty",children:"No projects. Add one to start."}),t.map(p=>e.jsx("li",{children:e.jsxs("button",{type:"button",className:V("project-selector-item",(s==null?void 0:s.id)===p.id&&"active"),onClick:()=>{a(p.id),o(!1)},children:[e.jsx("span",{className:"project-selector-item-name",children:p.name}),e.jsx("span",{className:"project-selector-item-status",children:p.status})]})},p.id))]})]})]})}function gi({settings:s,onAdd:t}){var d,m;const[a,i]=r.useState(((d=s==null?void 0:s.dashboard)==null?void 0:d.projectsDirectory)??""),[n,c]=r.useState(""),[o,l]=r.useState(!1),[x,p]=r.useState(null),u=async()=>{var h;if(a){l(!0),p(null);try{await T.get("/fs?path="+encodeURIComponent(a)),t(a,n||null)}catch(g){const j=g;j.status===404?p("That folder no longer exists. Pick another."):p(((h=j.data)==null?void 0:h.message)??g.message??"Validation failed.")}finally{l(!1)}}};return e.jsxs("div",{children:[e.jsx("label",{className:"field-label",children:"Folder"}),e.jsx(wa,{value:a,onChange:h=>{i(h),p(null)},projectsDirectory:(m=s==null?void 0:s.dashboard)==null?void 0:m.projectsDirectory,height:320}),x&&e.jsx("p",{className:"field-help",style:{color:"var(--error)",marginTop:4},children:x}),e.jsxs("div",{style:{marginTop:"var(--space-3)"},children:[e.jsx("label",{className:"field-label",htmlFor:"topbar-add-project-name",children:"Name (optional)"}),e.jsx("input",{id:"topbar-add-project-name",className:"input",type:"text",placeholder:"My App",value:n,onChange:h=>c(h.target.value)})]}),e.jsx("div",{style:{marginTop:"var(--space-3)",display:"flex",justifyContent:"flex-end"},children:e.jsxs($,{variant:"primary",onClick:u,disabled:!a||o,children:[o?e.jsx("span",{className:"btn-spinner"}):null,o?"Checking…":"Add"]})})]})}const fi=[{label:"General",sections:[{id:"theme",label:"Theme",icon:ra},{id:"layout",label:"Layout",icon:Pt},{id:"general",label:"General",icon:Pt}]},{label:"Core",sections:[{id:"env-vars",label:"Env Vars",icon:ns},{id:"providers",label:"Providers",icon:en},{id:"memory",label:"Memory",icon:Pe},{id:"system-llm",label:"System LLM",icon:_s}]},{label:"Experience",sections:[{id:"updates",label:"Updates",icon:de},{id:"skills",label:"Skills",icon:He},{id:"headroom",label:"Headroom",icon:sn}]},{label:"Data",sections:[{id:"backup",label:"Backup",icon:la}]}];function ji({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(bt,{size:14}),e.jsx("span",{children:"Back"})]}),e.jsx("div",{className:"settings-nav-divider","aria-hidden":"true"}),fi.map(i=>e.jsxs("div",{className:"settings-nav-group",children:[e.jsx("div",{className:"settings-nav-group-label",children:i.label}),i.sections.map(n=>{const c=n.icon,o=s===n.id;return e.jsxs("button",{type:"button",className:V("settings-nav-item",o&&"settings-nav-item-active"),onClick:()=>t(o?null:n.id),"aria-current":o?"page":void 0,children:[c&&e.jsx(c,{size:14,className:"settings-nav-item-icon","aria-hidden":!0}),e.jsx("span",{className:"settings-nav-item-label",children:n.label}),o&&e.jsx(Xe,{size:12,className:"settings-nav-item-chevron","aria-hidden":!0})]},n.id)})]},i.label))]})}function vi({tabs:s,activeTab:t,onTabChange:a,settingsMode:i,settingsActiveSection:n,onSettingsSectionChange:c,onExitSettings:o}){if(i)return e.jsx("aside",{className:"sidebar sidebar-settings-mode","aria-label":"Settings navigation",children:e.jsx(ji,{activeSection:n??null,onSectionChange:c??(()=>{}),onExitSettings:o??(()=>{})})});const l=s.filter(p=>!p.isMod),x=s.filter(p=>p.isMod);return e.jsx("aside",{className:"sidebar","aria-label":"Primary navigation",children:e.jsxs("nav",{className:"sidebar-nav",role:"tablist",children:[l.map(p=>{const u=p.icon,d=p.id===t;return e.jsxs("button",{type:"button",role:"tab","aria-selected":d,className:V("sidebar-tab",d&&"sidebar-tab-active"),onClick:()=>a(p.id),title:p.label,children:[e.jsx(u,{size:18,"aria-hidden":!0}),e.jsx("span",{className:"sidebar-tab-label",children:p.label})]},p.id)}),x.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"}),x.map(p=>{const u=p.icon,d=p.id===t;return e.jsxs("button",{type:"button",role:"tab","aria-selected":d,className:V("sidebar-tab","sidebar-tab-mod",d&&"sidebar-tab-active"),onClick:()=>a(p.id),title:`${p.label} (mod)`,children:[e.jsx(u,{size:18,"aria-hidden":!0}),e.jsx("span",{className:"sidebar-tab-label",children:p.label})]},p.id)})]})]})})}const tt=[{id:"all",label:"All"},{id:"projects",label:"Projects"},{id:"agents",label:"Agents"},{id:"tasks",label:"Tasks"},{id:"mods",label:"Mods"},{id:"schedules",label:"Schedules"},{id:"commands",label:"Commands"},{id:"settings",label:"Settings"}],Ot={all:null,projects:"project",agents:"agent",tasks:"task",mods:"mod",schedules:"schedule",commands:"command",settings:"setting"};function yi({open:s,onClose:t,onSelect:a}){const i=re(),[n,c]=r.useState(""),[o,l]=r.useState("all"),[x,p]=r.useState([]),[u,d]=r.useState(!1),[m,h]=r.useState(0),g=r.useRef(null),j=r.useRef(null);if(r.useEffect(()=>{let S;return s&&(j.current=document.activeElement instanceof HTMLElement?document.activeElement:null,c(""),p([]),h(0),S=window.setTimeout(()=>{var E;return(E=g.current)==null?void 0:E.focus()},30)),()=>{if(S&&window.clearTimeout(S),!s)return;const E=j.current;E&&E.isConnected&&E.focus()}},[s]),r.useEffect(()=>{if(!s)return;if(!n.trim()){p([]),h(0);return}let S=!1;d(!0);const E=setTimeout(()=>{T.get(`/search?q=${encodeURIComponent(n)}&scope=${o}`).then(v=>{S||(p(v.results||[]),h(0))}).catch(v=>{S||i.error(`Search failed: ${v.message}`)}).finally(()=>!S&&d(!1))},150);return()=>{S=!0,clearTimeout(E)}},[n,o,s,i]),!s)return null;const k={};for(const S of x){const E=S.type.toLowerCase();k[E]=k[E]||[],k[E].push(S)}const z=[];for(const S of tt.map(E=>E.id)){const E=Ot[S];E&&k[E]&&z.push(...k[E])}const N=S=>{if(S.key==="Escape")t();else if(S.key==="ArrowDown"){if(S.preventDefault(),z.length===0)return;h(E=>Math.min(E+1,z.length-1))}else if(S.key==="ArrowUp"){if(S.preventDefault(),z.length===0)return;h(E=>Math.max(E-1,0))}else S.key==="Enter"&&z[m]&&(S.preventDefault(),a(z[m]),t())};return e.jsx("div",{className:"search-modal-backdrop",onClick:t,children:e.jsxs("div",{className:"search-modal",role:"dialog","aria-modal":"true","aria-labelledby":"search-modal-title",onClick:S=>S.stopPropagation(),children:[e.jsxs("div",{className:"search-modal-head",role:"search",children:[e.jsx(ye,{size:14,"aria-hidden":!0}),e.jsx("span",{id:"search-modal-title",className:"sr-only",children:"Search"}),e.jsx("input",{ref:g,className:"search-modal-input",placeholder:"Search tasks, agents, settings, projects…",value:n,onChange:S=>c(S.target.value),onKeyDown:N,"aria-label":"Search"}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Close",onClick:t,children:e.jsx(Ne,{size:14})})]}),e.jsx("div",{className:"search-modal-scopes",role:"tablist","aria-label":"Search scope",children:tt.map(S=>e.jsx("button",{type:"button",role:"tab","aria-selected":o===S.id,className:V("search-scope",o===S.id&&"search-scope-active"),onClick:()=>l(S.id),children:S.label},S.id))}),e.jsxs("div",{className:"search-modal-body",children:[u&&e.jsx("div",{className:"muted",children:"Searching…"}),!u&&n&&z.length===0&&e.jsx("div",{className:"muted",children:"No results."}),!u&&!n&&e.jsx("div",{className:"muted",children:"Type to search…"}),tt.map(S=>{const E=Ot[S.id];if(!E)return null;const v=k[E];return!v||v.length===0?null:e.jsxs("div",{className:"search-group",children:[e.jsx("div",{className:"search-group-head",children:S.label}),v.map(b=>{const w=z.indexOf(b);return e.jsxs("button",{type:"button",className:V("search-result",w===m&&"search-result-active"),onMouseEnter:()=>h(w),onClick:()=>{a(b),t()},children:[e.jsx("span",{className:"search-result-type",children:b.type}),e.jsx("span",{className:"search-result-label",children:bi(b)})]},`${b.type}-${w}`)})]},S.id)})]}),e.jsx("div",{className:"search-modal-foot",children:e.jsx("span",{className:"muted",children:"↑↓ navigate · ↵ open · esc close"})})]})})}function bi(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 Ni={info:wt,success:qe,warning:Te,error:ta};function ki({onCountChange:s,wsSubscribe:t}){const a=re(),[i,n]=r.useState(!1),[c,o]=r.useState([]),[l,x]=r.useState(null),[p,u]=r.useState(!1),d=r.useRef(null),m=r.useRef(0),h=async()=>{var N;try{u(!0);const S=await T.get("/notifications?limit=200");o(S.notifications||[]),x(S.stats||null),m.current=((N=S.stats)==null?void 0:N.unread)||0,s==null||s(m.current)}catch(S){console.warn("[notifications] reload failed:",S.message)}finally{u(!1)}};r.useEffect(()=>{h()},[]),r.useEffect(()=>t?t(S=>{if(S.type==="notification:new"){const E=S.notification;o(v=>[E,...v.filter(b=>b.id!==E.id)]),E.read||(m.current+=1,x(v=>v?{...v,unread:(v.unread||0)+1}:{total:1,unread:1,lastTs:E.ts,counts:{[E.severity||"info"]:1}}),s==null||s(m.current))}else S.type==="notifications:change"&&h()}):void 0,[t]),r.useEffect(()=>{if(!i)return;const N=E=>{d.current&&(d.current.contains(E.target)||n(!1))},S=E=>{E.key==="Escape"&&n(!1)};return document.addEventListener("mousedown",N),document.addEventListener("keydown",S),()=>{document.removeEventListener("mousedown",N),document.removeEventListener("keydown",S)}},[i]);const g=async()=>{try{await T.post("/notifications/read-all",{}),o(N=>N.map(S=>({...S,read:!0}))),x(N=>N&&{...N,unread:0}),m.current=0,s==null||s(0),a.success("All notifications marked as read.",1500)}catch(N){a.error(`Failed: ${N.message}`)}},j=async N=>{try{await T.post(`/notifications/${encodeURIComponent(N)}/read`,{}),o(S=>S.map(E=>E.id===N?{...E,read:!0}:E)),x(S=>S&&{...S,unread:Math.max(0,(S.unread||1)-1)}),m.current=Math.max(0,m.current-1),s==null||s(m.current)}catch(S){a.error(`Failed: ${S.message}`)}},k=async N=>{try{await T.del(`/notifications/${encodeURIComponent(N)}`),o(S=>{const E=S.find(v=>v.id===N);return E&&!E.read&&(m.current=Math.max(0,m.current-1),x(v=>v&&{...v,unread:Math.max(0,v.unread-1)}),s==null||s(m.current)),S.filter(v=>v.id!==N)})}catch(S){a.error(`Failed: ${S.message}`)}},z=(l==null?void 0:l.unread)||0;return e.jsxs("div",{className:"notifications-root",ref:d,children:[e.jsxs("button",{type:"button",className:V("topbar-icon-btn notifications-bell",i&&"is-open"),onClick:()=>n(N=>!N),title:"Notifications","aria-label":"Notifications","aria-haspopup":"true","aria-expanded":i,children:[e.jsx(tn,{size:16}),z>0&&e.jsx("span",{className:"notifications-badge",children:z>99?"99+":z})]}),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"}),z>0&&e.jsxs("span",{className:"muted text-sm",children:[" · ",z," unread"]})]}),e.jsxs("div",{className:"notifications-panel-head-actions",children:[e.jsxs($,{size:"sm",variant:"ghost",onClick:g,disabled:z===0,children:[e.jsx(gs,{size:12})," Mark all read"]}),e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>n(!1),"aria-label":"Close",title:"Close",children:e.jsx(Ne,{size:14})})]})]}),e.jsx("div",{className:"notifications-list",children:p&&c.length===0?e.jsx("div",{className:"notifications-empty muted",children:"Loading…"}):c.length===0?e.jsx("div",{className:"notifications-empty muted",children:"No notifications yet."}):c.map(N=>{const S=Ni[N.severity]||wt;return e.jsxs("div",{className:V("notification-item",!N.read&&"is-unread",`severity-${N.severity}`),children:[e.jsx(S,{size:14,className:`notification-icon severity-${N.severity}`}),e.jsxs("div",{className:"notification-body",children:[N.title&&e.jsx("div",{className:"notification-title",children:N.title}),e.jsx("div",{className:"notification-msg",children:N.message}),e.jsxs("div",{className:"notification-meta muted",children:[e.jsx("span",{className:"mono",children:N.source}),e.jsx("span",{children:"·"}),e.jsx("span",{children:Ce(N.ts)})]})]}),e.jsxs("div",{className:"notification-actions",children:[!N.read&&e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>j(N.id),title:"Mark as read","aria-label":"Mark as read",children:e.jsx(gs,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger",onClick:()=>k(N.id),title:"Remove","aria-label":"Remove",children:e.jsx(Ne,{size:12})})]})]},N.id)})}),e.jsx("footer",{className:"notifications-panel-foot",children:e.jsx("span",{className:"muted text-sm",children:l?`${l.total} total · last ${Ce(l.lastTs||new Date().toISOString())}`:""})})]})]})}function wi({data:s,onClose:t}){const a=s==null?void 0:s.enabled;s==null||s.previousEnabled;const i=s==null?void 0:s.mode,n=s==null?void 0:s.defaultTemplate,c=s==null?void 0:s.lastUsedSlug,o=i==="toggle";return e.jsxs("div",{children:[o?e.jsxs("p",{style:{marginBottom:16,lineHeight:1.6},children:["Visual plan mode has been ",e.jsx("strong",{children:a?"enabled":"disabled"}),".",a?" The agent will create a plan and wait for your feedback on complex tasks.":" The agent will work without a visual plan canvas."]}):e.jsxs("div",{style:{marginBottom:16},children:[e.jsxs("p",{style:{marginBottom:8,fontWeight:600},children:["Visual Plan: ",e.jsx("span",{style:{color:a?"var(--color-success)":"var(--color-muted)"},children:a?"ON":"OFF"})]}),e.jsx("p",{style:{lineHeight:1.6,color:"var(--color-muted)",fontSize:13},children:"When enabled, the agent creates a visual plan and waits for your feedback before proceeding with complex tasks."}),n&&e.jsxs("p",{style:{marginTop:8,fontSize:13,color:"var(--color-muted)"},children:["Default template: ",e.jsx("code",{children:n})]}),c&&e.jsxs("p",{style:{fontSize:13,color:"var(--color-muted)"},children:["Last used plan: ",e.jsx("code",{children:c})]}),e.jsxs("p",{style:{marginTop:12,fontSize:13,color:"var(--color-muted)"},children:["Use ",e.jsx("code",{children:"/visual-plan on"})," or ",e.jsx("code",{children:"/visual-plan off"})," to toggle."]})]}),e.jsx("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:e.jsx($,{variant:"ghost",onClick:t,children:"Close"})})]})}const Si=["blank","feature-design","bug-investigation","decision-record","horizontal","vertical"];function Ci({data:s,onClose:t}){const a=(s==null?void 0:s.templates)??Si,i=(s==null?void 0:s.defaultTemplate)??"blank",[n,c]=r.useState(""),[o,l]=r.useState(i),[x,p]=r.useState(!1),[u,d]=r.useState(null),m=async()=>{if(!n.trim()){d("Slug is required.");return}if(!/^[a-z0-9][a-z0-9-]{0,63}$/.test(n)){d("Invalid slug. Use lowercase letters, numbers, and hyphens. Must start with an alphanumeric character.");return}p(!0),d(null);try{await T.post("/artifacts",{slug:n,template:o}),t()}catch(h){d(h.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:h=>{c(h.target.value),d(null)},autoFocus:!0})]}),e.jsxs("div",{style:{marginBottom:16},children:[e.jsx("label",{className:"field-label",htmlFor:"plan-template",children:"Template"}),e.jsx("select",{id:"plan-template",className:"select",value:o,onChange:h=>l(h.target.value),children:a.map(h=>e.jsx("option",{value:h,children:h},h))})]}),u&&e.jsx("p",{style:{marginBottom:12,color:"var(--color-danger)",fontSize:13},children:u}),e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx($,{variant:"ghost",onClick:t,disabled:x,children:"Cancel"}),e.jsx($,{variant:"primary",onClick:m,disabled:x||!n.trim(),children:x?"Creating…":"Create"})]})]})}function zi({data:s,onClose:t}){const a=(s==null?void 0:s.plans)??[],i=(s==null?void 0:s.count)??a.length,n=c=>{window.open(`/artifacts/${c}/`,"_blank")};return e.jsxs("div",{children:[a.length===0?e.jsxs("p",{style:{marginBottom:16,color:"var(--color-muted)"},children:["No plans found in this worktree. Use ",e.jsx("code",{children:"/artifact new <slug>"})," to create one."]}):e.jsxs("div",{style:{marginBottom:16},children:[e.jsxs("p",{style:{marginBottom:12,fontSize:13,color:"var(--color-muted)"},children:[i," plan",i!==1?"s":""," in this worktree:"]}),e.jsx("ul",{style:{listStyle:"none",padding:0,margin:0},children:a.map(c=>e.jsxs("li",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"6px 0",borderBottom:"1px solid var(--color-border)"},children:[e.jsx("code",{style:{fontSize:13},children:c}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>n(c),children:"Open"})]},c))})]}),e.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:e.jsx($,{variant:"ghost",onClick:t,children:"Close"})})]})}function Ti({data:s,onClose:t}){const a=(s==null?void 0:s.commands)??[],i=(s==null?void 0:s.templates)??[],n=(s==null?void 0:s.statuses)??[];return e.jsxs("div",{children:[a.length>0?e.jsx("table",{style:{width:"100%",borderCollapse:"collapse",marginBottom:16,fontSize:13},children:e.jsx("tbody",{children:a.map(c=>e.jsxs("tr",{style:{borderBottom:"1px solid var(--color-border)"},children:[e.jsx("td",{style:{padding:"5px 8px 5px 0",whiteSpace:"nowrap"},children:e.jsx("code",{style:{fontSize:12},children:c.cmd})}),e.jsx("td",{style:{padding:"5px 0",color:"var(--color-muted)"},children:c.desc})]},c.cmd))})}):e.jsx("p",{style:{marginBottom:16,color:"var(--color-muted)"},children:"No commands available."}),i.length>0&&e.jsxs("div",{style:{marginBottom:12},children:[e.jsx("p",{style:{fontSize:12,color:"var(--color-muted)",marginBottom:4},children:"Available templates:"}),e.jsx("p",{style:{fontSize:13},children:i.join(", ")})]}),n.length>0&&e.jsxs("div",{style:{marginBottom:12},children:[e.jsx("p",{style:{fontSize:12,color:"var(--color-muted)",marginBottom:4},children:"Available statuses:"}),e.jsx("p",{style:{fontSize:13},children:n.join(", ")})]}),e.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:e.jsx($,{variant:"ghost",onClick:t,children:"Close"})})]})}function Ri({data:s,onClose:t}){const[a,i]=r.useState(!1),[n,c]=r.useState(null),o=async()=>{i(!0),c(null);try{const l=await T.post("/chat/audit",{});c(l)}catch(l){c({ok:!1,findings:[],error:l.message})}finally{i(!1)}};return e.jsx("div",{children:n===null?e.jsxs(e.Fragment,{children:[e.jsx("p",{style:{marginBottom:16,lineHeight:1.6},children:"Run a security audit of your Bizar agent configuration. The audit checks for common misconfigurations, exposed secrets, and insecure defaults."}),e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx($,{variant:"ghost",onClick:t,children:"Cancel"}),e.jsx($,{variant:"primary",onClick:o,disabled:a,children:a?"Running…":"Run Audit"})]})]}):e.jsxs(e.Fragment,{children:[n.ok?e.jsxs("div",{children:[e.jsx("p",{style:{marginBottom:12,fontWeight:600,color:"var(--color-success)"},children:"Audit passed — no issues found."}),n.findings.length>0&&e.jsx("ul",{style:{marginBottom:16,paddingLeft:20},children:n.findings.map((l,x)=>e.jsx("li",{style:{marginBottom:4,fontSize:13},children:l},x))})]}):e.jsxs("p",{style:{marginBottom:16,color:"var(--color-danger)"},children:["Audit failed: ",n.error??"unknown error"]}),e.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:e.jsx($,{variant:"ghost",onClick:t,children:"Close"})})]})})}function $i({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 Ai({dialog:s,onClose:t}){switch(s.component){case"visual-artifact":return e.jsx(wi,{data:s.data,onClose:t});case"artifact-create":return e.jsx(Ci,{data:s.data,onClose:t});case"artifact-list":return e.jsx(zi,{data:s.data,onClose:t});case"help":return e.jsx(Ti,{data:s.data,onClose:t});case"audit":return e.jsx(Ri,{data:s.data,onClose:t});default:return e.jsx($i,{dialog:s,onClose:t})}}function Mi({setActiveTab:s,refreshKey:t=0}){var p;const[a,i]=r.useState(null),[n,c]=r.useState(!0),o=async()=>{c(!0);try{const[u,d,m]=await Promise.all([T.get("/memory/status").catch(()=>null),T.get("/memory/health").catch(()=>null),T.get("/memory/lightrag/stats").catch(()=>null)]);i({initialized:!!(u!=null&&u.initialized),mode:u==null?void 0:u.mode,projectId:u==null?void 0:u.projectId,vaultRoot:u==null?void 0:u.vaultRoot,branch:u==null?void 0:u.branch,gitClean:u==null?void 0:u.gitClean,noteCount:(u==null?void 0:u.noteCount)||0,healthScore:d==null?void 0:d.score,healthStatus:d==null?void 0:d.status,lightrag:m?{running:m.running,indexedApprox:m.indexedApprox}:void 0})}catch{i({initialized:!1})}finally{c(!1)}};r.useEffect(()=>{o()},[t]);const l=()=>s("memory"),x=(a==null?void 0:a.healthStatus)==="healthy"?"var(--success)":(a==null?void 0:a.healthStatus)==="degraded"?"var(--warning)":(a==null?void 0:a.healthStatus)==="unhealthy"?"var(--error)":"var(--text-dim)";return e.jsxs(G,{className:"memory-overview-card",children:[e.jsxs(te,{children:[e.jsx(Pe,{size:14})," Memory",e.jsxs($,{variant:"ghost",size:"sm",style:{marginLeft:"auto"},onClick:l,children:["Open Memory ",e.jsx(ys,{size:12})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:o,"aria-label":"Refresh",title:"Refresh",children:e.jsx(de,{size:12})})]}),e.jsx(ne,{children:"LightRAG + Obsidian vault + git sync — opens the dedicated Memory tab."}),a!=null&&a.initialized?e.jsxs("div",{className:"memory-status-card-grid",children:[e.jsxs("div",{className:"memory-status-card-cell",children:[e.jsxs("div",{className:"memory-status-card-label",children:[e.jsx(De,{size:11})," Health"]}),e.jsx("div",{className:"memory-status-card-value",style:{color:x},children:a.healthScore!==void 0?`${a.healthScore}/100`:"—"}),e.jsx("div",{className:"memory-status-card-sub muted",children:a.healthStatus||"—"})]}),e.jsxs("div",{className:"memory-status-card-cell",children:[e.jsxs("div",{className:"memory-status-card-label",children:[e.jsx(Pe,{size:11})," LightRAG"]}),e.jsx("div",{className:"memory-status-card-value",children:(p=a.lightrag)!=null&&p.running?"running":"stopped"}),e.jsx("div",{className:"memory-status-card-sub muted",children:a.lightrag?`${a.lightrag.indexedApprox} chunks`:"—"})]}),e.jsxs("div",{className:"memory-status-card-cell",children:[e.jsxs("div",{className:"memory-status-card-label",children:[e.jsx(be,{size:11})," Vault"]}),e.jsxs("div",{className:"memory-status-card-value",children:[a.noteCount," notes"]}),e.jsx("div",{className:"memory-status-card-sub muted ellipsis",title:a.vaultRoot||"",children:a.vaultRoot?a.vaultRoot.split("/").slice(-2).join("/"):"—"})]}),e.jsxs("div",{className:"memory-status-card-cell",children:[e.jsxs("div",{className:"memory-status-card-label",children:[e.jsx(is,{size:11})," Git"]}),e.jsx("div",{className:"memory-status-card-value",children:a.gitClean===null?a.mode==="local-only"?"local-only":"—":a.gitClean?"clean":"dirty"}),e.jsx("div",{className:"memory-status-card-sub muted",children:a.branch?`branch ${a.branch}`:_e(a.branch||"")||"—"})]})]}):e.jsxs("div",{className:"muted",children:["Memory not initialised. Click ",e.jsx("strong",{children:"Open Memory"})," to set it up."]}),n&&!a&&e.jsx("div",{className:"muted text-sm",children:"Loading…"})]})}function pe({icon:s,title:t,message:a,action:i,className:n}){return e.jsxs("div",{className:V("empty-state",n),children:[e.jsx("div",{className:"empty-icon",children:s??e.jsx(Gs,{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 Ii({snapshot:s,settings:t,setActiveTab:a,refreshSnapshot:i}){var J,ae,ee;const n=re(),c=$e(),o=r.useRef(null),[l,x]=r.useState(s.overview??null),[p,u]=r.useState(!s.overview),[d,m]=r.useState(s.projects||[]),[h,g]=r.useState(((J=s.activeProject)==null?void 0:J.id)||null),[j,k]=r.useState(s.mods||[]),[z,N]=r.useState(!1),[S,E]=r.useState(((ae=s.overview)==null?void 0:ae.recentActivity)??[]),[v,b]=r.useState(!1),[w,f]=r.useState(new Set);r.useEffect(()=>{let F=!1;return(async()=>{try{const H=await T.get("/activity/hidden");F||f(new Set(H.hidden||[]))}catch{}})(),()=>{F=!0}},[]);const L=(F,H)=>{const K=`${F.kind||""}|${F.ts||""}|${F.slug||F.title||""}|${H}`;let B=0;for(let Z=0;Z<K.length;Z++)B=(B<<5)-B+K.charCodeAt(Z)|0;return Math.abs(B).toString(16).padStart(8,"0").slice(0,16)},R=async F=>{const H=new Set(w);H.add(F),f(H);try{await T.post("/activity/hide",{keys:[F]})}catch(K){const B=new Set(w);f(B),n.error(`Hide failed: ${K.message}`)}},y=async()=>{if(!confirm("Hide every recent activity item from the overview? The full log stays in Settings → Activity Log."))return;const F=S.map((K,B)=>L(K,B)),H=new Set(w);F.forEach(K=>H.add(K)),f(H);try{await T.post("/activity/hide",{keys:F}),n.success(`Hidden ${F.length} item(s). Restore them in Settings → Activity Log.`)}catch(K){n.error(`Clear failed: ${K.message}`)}},A=async()=>{f(new Set);try{await T.del("/activity/hide"),n.success("All hidden activity restored to the overview.")}catch(F){n.error(`Restore failed: ${F.message}`)}};r.useEffect(()=>{var F;s.overview&&(x(s.overview),E(s.overview.recentActivity??[]),u(!1)),m(s.projects||[]),g(((F=s.activeProject)==null?void 0:F.id)||null),k(s.mods||[])},[s.overview,s.projects,s.activeProject,s.mods]),r.useEffect(()=>{let F;try{const H=T.getToken(),K=H?`/api/activity/stream?token=${encodeURIComponent(H)}`:"/api/activity/stream";F=new EventSource(K),F.addEventListener("snapshot",B=>{try{const Z=JSON.parse(B.data);E(Array.isArray(Z.events)?Z.events.slice(0,50):[])}catch{}}),F.addEventListener("activity",B=>{try{const Z=JSON.parse(B.data);E(he=>[Z,...he].slice(0,50))}catch{}})}catch{}return()=>{try{F==null||F.close()}catch{}}},[]);const P=async()=>{n.info("Refreshing…",1500),await i();try{const F=await T.get("/projects");m(F.projects||[]),g(F.active||null)}catch{}},C=()=>{c.open({title:"Add project",children:e.jsx(Ei,{settings:t,onAdd:async(F,H)=>{try{const K=await T.post("/projects",{path:F,name:H});m(B=>[...B.filter(Z=>Z.id!==K.id),K]),n.success("Project added."),c.close()}catch(K){n.error(`Add failed: ${K.message}`)}}}),footer:e.jsx("div",{className:"modal-footer-actions",children:e.jsx($,{variant:"ghost",onClick:()=>c.close(),children:"Cancel"})})})},D=async()=>{var F;try{const H=await T.post("/projects/auto-detect");m(H.projects||[]),g(H.active||null);const K=(F=H.projects)==null?void 0:F.find(B=>B.id===H.active);n.success(K?`Active: ${K.name}`:"Projects refreshed."),await i()}catch(H){n.error(`Auto-detect failed: ${H.message}`)}},Y=async F=>{try{await T.post(`/projects/${encodeURIComponent(F)}/activate`),g(F),n.success("Project activated."),await i()}catch(H){n.error(`Activate failed: ${H.message}`)}},O=async F=>{if(confirm(`Remove project "${F}" from the registry?`))try{await T.del(`/projects/${encodeURIComponent(F)}`),m(H=>H.filter(K=>K.id!==F)),h===F&&g(null),n.success("Project removed.")}catch(H){n.error(`Remove failed: ${H.message}`)}};return p||!l?e.jsxs("div",{className:"view-loading",children:[e.jsx(oe,{size:"lg"}),e.jsx("p",{children:"Loading overview…"})]}):e.jsxs("div",{className:"view view-overview",children:[e.jsxs("div",{className:"overview-hero-noframe",children:[e.jsx("h1",{children:"What do you want to do?"}),e.jsx("p",{className:"overview-hero-subtitle",children:"Describe what you want — Odin will split it into tasks, create a plan, delegate to background agents, and track progress in real time."}),e.jsxs("form",{className:"overview-hero-form-noframe",onSubmit:async F=>{var K,B;F.preventDefault();const H=(((K=o.current)==null?void 0:K.value)||"").trim();if(H){N(!0);try{const Z=await T.post("/tasks/submit",{title:H});n.success(`Odin split it into ${((B=Z.subtasks)==null?void 0:B.length)||1} task(s)`),o.current&&(o.current.value=""),await i()}catch(Z){n.error(`Failed: ${Z.message}`)}finally{N(!1)}}},children:[e.jsx("label",{htmlFor:"overview-hero-input",className:"sr-only",children:"Describe what you want Odin to do"}),e.jsx("textarea",{id:"overview-hero-input",ref:o,className:"overview-input-hero",placeholder:"e.g. Implement user authentication with email + password, including registration, login, password reset, and integration tests. Use Bcrypt, JWT tokens, and the existing API style.",disabled:z,"aria-label":"Describe what you want Odin to do"}),e.jsxs("div",{style:{display:"flex",gap:"var(--space-2)",alignItems:"center",flexWrap:"wrap"},children:[e.jsxs($,{type:"submit",variant:"primary",size:"lg",disabled:z,children:[z?e.jsx(oe,{size:"sm"}):e.jsx(rs,{size:16}),"Submit to Odin"]}),e.jsxs("span",{className:"muted",style:{fontSize:12},children:[e.jsx(He,{size:12,style:{display:"inline",verticalAlign:-2,color:"var(--accent)"}})," ","Odin + 12 specialist agents available"]})]})]}),e.jsx("div",{className:"overview-quick-actions-row",children:["Implement feature","Fix bug","Refactor","Investigate","Add tests","Document","Optimize","Deploy"].map(F=>e.jsx("button",{type:"button",className:"overview-quick-chip",onClick:()=>{o.current&&(o.current.value=F,o.current.focus())},children:F},F))})]}),e.jsxs("div",{className:"overview-feed",children:[e.jsxs("div",{className:"overview-feed-head",children:[e.jsx("h2",{children:"Recent activity"}),e.jsxs("div",{className:"overview-feed-head-actions",children:[w.size>0&&e.jsxs($,{variant:"ghost",size:"sm",onClick:A,title:"Restore hidden items to this overview",children:[e.jsx(fs,{size:12})," Show ",w.size," hidden"]}),S.length>8&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>b(F=>!F),children:v?"Show less":"Show all"}),S.length>0&&e.jsxs($,{variant:"ghost",size:"sm",onClick:y,title:"Hide every item from the overview (full log kept)",children:[e.jsx(pt,{size:12})," Hide all"]})]})]}),w.size>0&&e.jsxs("div",{className:"activity-hidden-banner",role:"status",children:[e.jsxs("span",{children:[e.jsx(pt,{size:12,style:{verticalAlign:-2,marginRight:6}}),w.size," item",w.size===1?"":"s"," hidden from the overview."]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:A,children:[e.jsx(fs,{size:12})," Show them again"]})]}),S.length===0?e.jsx("div",{className:"muted",style:{padding:"24px 0",fontSize:13},children:"No activity yet. Use the chat above or invoke a Bizar command to start a feed."}):e.jsxs("div",{className:V("activity-feed-list-wrap",!v&&"activity-feed-list-wrap-collapsed"),"aria-live":"polite","aria-relevant":"additions",children:[e.jsx(Mt,{items:S.slice(0,30).filter((F,H)=>!w.has(L(F,H))),itemHeight:60,height:Math.min(S.filter((F,H)=>!w.has(L(F,H))).length*60,480),className:"activity-feed-list",renderItem:(F,H)=>{const K=S.slice(0,30).findIndex(B=>B===F);return e.jsx(Wi,{item:F,activityKey:L(F,K),onNavigate:a,onHide:R})}}),!v&&S.length>8&&e.jsx("div",{className:"activity-feed-fade","aria-hidden":"true"})]})]}),e.jsxs(G,{className:"project-picker",children:[e.jsxs(te,{children:[e.jsx(Fe,{size:14})," Projects",e.jsxs($,{variant:"ghost",size:"sm",style:{marginLeft:"auto"},onClick:C,children:[e.jsx(ze,{size:12})," Add"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:D,title:"Use the server's working directory",children:[e.jsx(ze,{size:12})," Auto-detect"]}),((ee=t==null?void 0:t.dashboard)==null?void 0:ee.projectsDirectory)&&e.jsxs($,{variant:"ghost",size:"sm",title:`Scan ${t.dashboard.projectsDirectory} for projects`,onClick:async()=>{try{const F=await T.post("/projects/scan");F.error?n.error(F.error):n.success(`Added ${F.added.length}, skipped ${F.skipped}.`),await i();const H=await T.get("/projects");m(H.projects||[]),g(H.active||null)}catch(F){n.error(`Scan failed: ${F.message}`)}},children:[e.jsx(an,{size:12})," Scan"]}),e.jsx($,{variant:"ghost",size:"sm",onClick:P,title:"Refresh",children:e.jsx(de,{size:12})})]}),e.jsxs(ne,{children:[d.length," project",d.length===1?"":"s"," ·"," ",l.counts.agents," agents ·"," ",l.counts.sessions," session",l.counts.sessions===1?"":"s"]}),d.length===0?e.jsx(pe,{icon:e.jsx(Fe,{size:32}),title:"No projects yet",message:"Add a project to start tracking its tasks, plans, and schedules.",action:e.jsxs("div",{className:"empty-state-actions",children:[e.jsxs($,{variant:"primary",onClick:D,children:[e.jsx(ze,{size:14})," Use current directory"]}),e.jsx($,{variant:"secondary",onClick:C,children:"Add by path…"})]})}):e.jsx("div",{className:"project-grid",children:d.map(F=>e.jsx(Li,{project:F,active:h===F.id,onOpen:()=>Y(F.id),onRemove:()=>O(F.id)},F.id))})]}),e.jsx(Mi,{setActiveTab:a}),e.jsxs("div",{className:"overview-cols",children:[e.jsxs(G,{children:[e.jsx(te,{children:"Mods"}),e.jsxs(ne,{children:["Extensions installed under ",e.jsx("code",{children:"~/.config/bizar/mods/"})]}),j.length===0?e.jsx("div",{className:"muted",children:"No mods installed."}):e.jsx("ul",{className:"mod-mini-list",children:j.map(F=>e.jsxs("li",{className:"mod-mini",children:[e.jsx("span",{className:"mod-mini-name",children:F.name}),e.jsxs("span",{className:"mod-mini-meta",children:["v",F.version," · ",F.type]}),e.jsx("span",{className:`mod-mini-pill ${F.enabled?"mod-mini-pill-on":"mod-mini-pill-off"}`,children:F.enabled?"on":"off"})]},F.id))})]}),e.jsxs(G,{children:[e.jsx(te,{children:"Environment"}),e.jsx(ne,{children:"Runtime + paths"}),e.jsxs("dl",{className:"env-table",children:[e.jsx("dt",{children:"Node"}),e.jsx("dd",{className:"mono",children:l.versions.node}),e.jsx("dt",{children:"Platform"}),e.jsx("dd",{className:"mono",children:l.versions.platform}),e.jsx("dt",{children:"Project root"}),e.jsx("dd",{className:"mono ellipsis",title:l.versions.projectRoot,children:l.versions.projectRoot}),e.jsx("dt",{children:"Bizar root"}),e.jsx("dd",{className:"mono ellipsis",title:l.versions.bizarRoot,children:l.versions.bizarRoot}),e.jsx("dt",{children:"Generated"}),e.jsx("dd",{className:"mono tabular-nums",children:_e(l.generatedAt)})]})]})]})]})}function Ei({settings:s,onAdd:t}){var d,m;const[a,i]=r.useState(((d=s==null?void 0:s.dashboard)==null?void 0:d.projectsDirectory)??""),[n,c]=r.useState(""),[o,l]=r.useState(!1),[x,p]=r.useState(null),u=async()=>{var h;if(a){l(!0),p(null);try{await T.get("/fs?path="+encodeURIComponent(a)),t(a,n||null)}catch(g){const j=g;j.status===404?p("That folder no longer exists. Pick another."):p(((h=j.data)==null?void 0:h.message)??g.message??"Validation failed.")}finally{l(!1)}}};return e.jsxs("div",{children:[e.jsx("label",{className:"field-label",children:"Folder"}),e.jsx(wa,{value:a,onChange:h=>{i(h),p(null)},projectsDirectory:(m=s==null?void 0:s.dashboard)==null?void 0:m.projectsDirectory,height:320}),x&&e.jsx("p",{className:"field-help",style:{color:"var(--error)",marginTop:4},children:x}),e.jsxs("div",{style:{marginTop:"var(--space-3)"},children:[e.jsx("label",{className:"field-label",htmlFor:"add-project-name",children:"Name (optional)"}),e.jsx("input",{id:"add-project-name",className:"input",type:"text",placeholder:"My App",value:n,onChange:h=>c(h.target.value)}),e.jsx("p",{className:"field-help",style:{marginTop:4},children:"Display name for this project. Defaults to the folder name."})]}),e.jsx("div",{style:{marginTop:"var(--space-3)",display:"flex",justifyContent:"flex-end"},children:e.jsxs($,{variant:"primary",onClick:u,disabled:!a||o,children:[o?e.jsx("span",{className:"btn-spinner"}):null,o?"Checking…":"Add"]})})]})}function Li({project:s,active:t,onOpen:a,onRemove:i}){const n={active:"status-on",inactive:"status-neutral",error:"status-error"}[s.status]||"status-neutral";return e.jsxs("div",{className:`project-card ${t?"project-card-active":""}`,children:[e.jsxs("div",{className:"project-card-head",children:[e.jsx("span",{className:`project-card-status ${n}`,children:s.status}),e.jsx("div",{className:"project-card-name",children:s.name}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Remove project",title:"Remove",onClick:c=>{c.stopPropagation(),i()},children:e.jsx(ke,{size:12})})]}),e.jsx("div",{className:"project-card-path mono ellipsis",title:s.path,children:s.path}),e.jsx("div",{className:"project-card-meta",children:s.lastAccessed&&e.jsxs("span",{className:"muted",children:["Last opened ",Ce(s.lastAccessed)]})}),e.jsx("div",{className:"project-card-actions",children:e.jsx($,{variant:t?"ghost":"primary",size:"sm",onClick:a,children:t?e.jsxs(e.Fragment,{children:[e.jsx(St,{size:12})," Active"]}):e.jsx(e.Fragment,{children:"Open"})})})]})}function Di(s){return s&&s.charAt(0).toUpperCase()+s.slice(1)}function Pi(s){const t=s.trim().toLowerCase().replace(/[:_]/g,"."),[a,i="updated"]=t.split("."),n={settings:"Settings",task:"Task",tasks:"Task",agent:"Agent",agents:"Agent",plan:"Plan",plans:"Plan",bg:"Background job",background:"Background job",session:"Session",mod:"Mod",mods:"Mod",provider:"Provider",providers:"Provider"},c={create:"created",created:"created",add:"added",added:"added",update:"updated",updated:"updated",delegate:"delegated",delegated:"delegated",invoke:"invoked",invoked:"invoked",restart:"restarted",restarted:"restarted",delete:"deleted",deleted:"deleted",remove:"removed",removed:"removed",archive:"archived",archived:"archived",restore:"restored",restored:"restored",complete:"completed",completed:"completed",fail:"failed",failed:"failed",error:"errored",stuck:"marked stuck"},o=n[a]||Di(a.replace(/-/g," ")),l=c[i]||i.replace(/-/g," ");return`${o} ${l}`.trim()}function Fs(s,t){for(const a of t){const i=s[a];if(typeof i=="string"&&i.trim())return i.trim()}return""}function Fi(s){const t=Fs(s,["message","text","prompt","title","name"]);if(t)return t;const a=[],i=Fs(s,["slug"]),n=Fs(s,["agent","author"]),c=Fs(s,["status"]);return i&&a.push(`Plan ${i}`),n&&a.push(n),c&&a.push(c),a.length?a.join(" · "):"No additional details."}function Oi(s){return Ce(s)}function Bi(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 Ui(s){const t=s.toLowerCase();return t==="task"?Rs:t==="agent"?Ye:t==="plan"?Hs:t.includes("bg")||t.includes("background")||t.includes("job")?Ct:t==="mod"?ts:t==="skill"?He:t.includes("error")||t.includes("failure")?ps:t.includes("warn")?Te:De}function _i(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 Wi({item:s,activityKey:t,onNavigate:a,onHide:i}){const n=Bi(s),c=Ui(s.kind||""),o=Pi(s.kind||"activity"),l=Fi(s),x=_i(s.kind||""),p=n==="error"?"var(--error)":n==="warning"?"var(--warning)":n==="success"?"var(--success)":"var(--accent)";return e.jsxs("div",{className:V("activity-feed-row",`activity-feed-row-${n}`),children:[e.jsxs("button",{type:"button",className:"activity-feed-row-main",onClick:()=>{x&&a(x)},title:x?`Open ${x}`:o,children:[e.jsx("div",{className:"activity-feed-icon",style:{color:p},children:e.jsx(c,{size:14})}),e.jsxs("div",{className:"activity-feed-body",children:[e.jsxs("div",{className:"activity-feed-title-row",children:[e.jsx("div",{className:"activity-feed-title",children:o}),e.jsx("div",{className:"activity-feed-time text-xs muted tabular-nums",children:Oi(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 qi=Oe.memo(Ii);function Vi({icon:s,title:t,message:a,action:i}){return e.jsxs("div",{className:"chat-empty-state",children:[s&&e.jsx("div",{className:"chat-empty-state-icon",children:s}),e.jsx("h2",{className:"chat-empty-state-title",children:t}),e.jsx("p",{className:"chat-empty-state-message",children:a}),i&&e.jsx("div",{className:"chat-empty-state-action",children:i})]})}function Hi({session:s,mode:t,anchor:a,renameDraft:i,setRenameDraft:n,onEdit:c,onDeleteRequest:o,onConfirmDelete:l,onConfirmRename:x,onClose:p}){const u=r.useRef(null),d=Math.round(a.rect.bottom+2),m=Math.max(8,Math.round(window.innerWidth-a.rect.right));r.useEffect(()=>{const g=z=>{const N=z.target;!u.current||!N||u.current.contains(N)||p()},j=z=>{z.key==="Escape"&&p()},k=window.setTimeout(()=>{document.addEventListener("mousedown",g),document.addEventListener("keydown",j)},0);return()=>{window.clearTimeout(k),document.removeEventListener("mousedown",g),document.removeEventListener("keydown",j)}},[p]),r.useEffect(()=>{if(t!=="rename")return;const g=window.setTimeout(()=>{var k;const j=(k=u.current)==null?void 0:k.querySelector("input.session-row-menu-input");j==null||j.focus(),j==null||j.select()},0);return()=>window.clearTimeout(g)},[t]);const h=e.jsxs("div",{ref:u,className:"session-row-menu",role:"menu","aria-label":`Options for ${s.title}`,style:{position:"fixed",top:d,right:m},onClick:g=>g.stopPropagation(),children:[t==="main"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",className:"session-row-menu-item",role:"menuitem",onClick:g=>{g.stopPropagation(),c()},children:[e.jsx(nn,{size:13,"aria-hidden":!0}),e.jsx("span",{children:"Rename"}),e.jsx("kbd",{children:"R"})]}),e.jsxs("button",{type:"button",className:"session-row-menu-item session-row-menu-item-danger",role:"menuitem",onClick:g=>{g.stopPropagation(),o()},children:[e.jsx(ke,{size:13,"aria-hidden":!0}),e.jsx("span",{children:"Delete"}),e.jsx("kbd",{children:"⌫"})]})]}),t==="rename"&&e.jsxs("div",{className:"session-row-menu-inline",children:[e.jsx("div",{className:"session-row-menu-inline-label chat-mono",children:"Rename session"}),e.jsx("input",{type:"text",className:"session-row-menu-input",value:i,onChange:g=>n(g.target.value),onKeyDown:g=>{g.key==="Enter"?(g.preventDefault(),x()):g.key==="Escape"&&(g.preventDefault(),p())},onClick:g=>g.stopPropagation(),"aria-label":"New session name"}),e.jsxs("div",{className:"session-row-menu-inline-actions",children:[e.jsx("button",{type:"button",className:"btn btn-ghost",onClick:g=>{g.stopPropagation(),p()},children:"Cancel"}),e.jsx("button",{type:"button",className:"btn btn-primary",onClick:g=>{g.stopPropagation(),x()},children:"Save"})]})]}),t==="confirm-delete"&&e.jsxs("div",{className:"session-row-menu-inline",children:[e.jsx("div",{className:"session-row-menu-inline-label chat-mono",children:"Delete this session?"}),e.jsxs("div",{className:"session-row-menu-inline-message",children:['"',s.title,'" and its sub-agents will be removed.']}),e.jsxs("div",{className:"session-row-menu-inline-actions",children:[e.jsx("button",{type:"button",className:"btn btn-ghost",onClick:g=>{g.stopPropagation(),p()},children:"Cancel"}),e.jsx("button",{type:"button",className:"btn btn-danger",onClick:g=>{g.stopPropagation(),l()},children:"Delete"})]})]})]});return sa.createPortal(h,document.body)}function vt({node:s,depth:t=0,collapsible:a=!1,isLast:i=!0,open:n,onToggle:c}){var h;const[o,l]=r.useState(a),x=n!==void 0,p=x?n:o,u=g=>{x||l(g),c==null||c(g)},d=(((h=s.children)==null?void 0:h.length)??0)>0,m=e.jsxs(e.Fragment,{children:[a&&e.jsx("span",{className:`agent-node-chevron ${p?"open":""}`,"aria-hidden":!0,children:"›"}),e.jsx("span",{className:`agent-node-dot status-${s.status}`,"aria-hidden":!0}),e.jsx("span",{className:"agent-node-name",children:s.name}),s.role&&e.jsx("span",{className:"agent-node-role chat-mono",children:s.role}),e.jsx("span",{className:`agent-node-pill status-${s.status}`,children:s.status})]});return e.jsxs("div",{className:["agent-node",`depth-${t}`,`status-${s.status}`,p?"open":"closed",i?"last":""].filter(Boolean).join(" "),children:[a?e.jsx("button",{type:"button",className:`agent-node-head status-${s.status} collapsible`,onClick:g=>{g.stopPropagation(),u(!p)},"aria-expanded":p,children:m}):e.jsx("div",{className:`agent-node-head status-${s.status}`,children:m}),p&&e.jsxs(e.Fragment,{children:[s.summary&&e.jsx("div",{className:"agent-node-summary",children:s.summary}),d&&e.jsx("div",{className:"agent-node-children",children:s.children.map((g,j)=>e.jsx(vt,{node:g,depth:t+1,collapsible:!1,isLast:j===s.children.length-1},g.id))})]})]})}function Gi(s){return s.tree!==void 0}function Ki(s){const t=s.open??!0;if(Gi(s))return e.jsx("div",{className:`agent-tree variant-${s.variant??"full"}`,children:e.jsx(vt,{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(vt,{node:i,depth:0,collapsible:!1,open:t,isLast:n===a.length-1})},i.id))})})}function Yi({children:s,variant:t="rail",open:a=!0}){return a?e.jsx(Ki,{variant:t,open:a,children:s}):null}const Xi=["Today","Yesterday","This week","Earlier"];function Bt(s,t){return s.getFullYear()===t.getFullYear()&&s.getMonth()===t.getMonth()&&s.getDate()===t.getDate()}function Ji(s,t){const a=s.getTime()-t.getTime();return Math.floor(a/(1e3*60*60*24))}function Qi(s){const t=new Date,a=new Date(t);a.setDate(a.getDate()-1);const i=new Date(t);i.setDate(i.getDate()-7);const n={Today:[],Yesterday:[],"This week":[],Earlier:[]};for(const c of s){const o=new Date(Number(c.mtime)||Date.now());Bt(o,t)?n.Today.push(c):Bt(o,a)?n.Yesterday.push(c):Ji(t,o)<7?n["This week"].push(c):n.Earlier.push(c)}return n}function Zi(s){return new Date(Number(s)||Date.now()).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1})}function er({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 sr({sessions:s,opencodeSessions:t=[],activeSessionId:a,activeOpencodeSessionId:i,activeProject:n,creating:c,onCreateSession:o,onSelectSession:l,onSelectOpencodeSession:x,onRenameSession:p,onDeleteSession:u,groupBy:d}){var O;const m=r.useMemo(()=>[...s,...t],[s,t]),h=r.useMemo(()=>[...m].sort((J,ae)=>Number(ae.mtime??0)-Number(J.mtime??0)),[m]),g=r.useMemo(()=>d?d(h):Qi(h),[d,h]),[j,k]=r.useState({}),z=J=>j[J]===!0,[N,S]=r.useState(null),[E,v]=r.useState("main"),[b,w]=r.useState(""),[f,L]=r.useState(null),R=r.useRef({}),y=(J,ae="main")=>{const ee=R.current[J];if(!ee)return;const F=ae==="main"?ee:ee.querySelector(".chat-rail-item-menu-trigger")??ee;if(L({id:J,rect:F.getBoundingClientRect()}),S(J),v(ae),ae==="rename"){const H=[...s,...t].find(K=>K.id===J);w((H==null?void 0:H.title)??(H==null?void 0:H.id)??"")}},A=()=>{S(null),v("main"),w(""),L(null)},P=J=>{if(J.source==="opencode"){x(J);return}l(J.id)},C=()=>{if(!f)return;const J=f.id,ae=b.trim();if(!ae){A();return}p==null||p(J,ae),A()},D=()=>{f&&(u==null||u(f.id),A())},Y=d?Object.entries(g):Xi.filter(J=>{var ae;return(ae=g[J])==null?void 0:ae.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:o,disabled:c||!n,title:n?"Create new session":"Pick a project first","aria-label":"Create new session",children:[e.jsx(ze,{size:14,"aria-hidden":!0}),e.jsx("span",{children:c?"Creating…":"New session"})]})}),h.length===0?e.jsx("div",{className:"chat-sessions-empty",children:e.jsx(Vi,{icon:e.jsx(ze,{size:20,"aria-hidden":!0}),title:n?"No sessions yet":"No project",message:n?"Create your first session to start chatting.":"Pick a project in Overview to scope chat sessions."})}):e.jsx("div",{className:"chat-rail-list",children:Y.map(([J,ae])=>e.jsxs("div",{className:"chat-rail-group",children:[e.jsx("div",{className:"chat-rail-group-label",children:J}),ae.map(ee=>{var he,we;const F=ee.source==="opencode",H=F?i===ee.id:a===ee.id,K=ee.tree,B=!!((he=K==null?void 0:K.root)!=null&&he.children&&K.root.children.length>0),Z=z(ee.id);return e.jsxs(r.Fragment,{children:[e.jsxs("div",{ref:W=>{R.current[ee.id]=W},role:"button",tabIndex:0,className:`chat-rail-item state-${ee.state??"idle"}${H?" active":""}`,onClick:()=>P(ee),onKeyDown:W=>{(W.key==="Enter"||W.key===" ")&&(W.preventDefault(),P(ee))},"aria-current":H?"true":void 0,children:[e.jsx(er,{state:ee.state??"idle",agent:ee.agent}),e.jsxs("div",{className:"chat-rail-item-title",children:[ee.pinned&&e.jsx("span",{className:"chat-rail-pin","aria-hidden":!0,children:"★"}),F&&e.jsx(ys,{size:11,style:{color:"var(--text-muted)",flexShrink:0},"aria-hidden":!0}),e.jsx("span",{className:"chat-ellipsis",children:ee.title||ee.id})]}),e.jsxs("div",{className:"chat-rail-item-meta",children:[e.jsx("span",{className:"chat-rail-item-meta-time",children:ee.time??Zi(ee.mtime)}),(ee.unread??0)>0&&e.jsx("span",{className:"chat-rail-badge",children:ee.unread})]}),e.jsx("button",{type:"button",className:`chat-rail-item-menu-trigger${N===ee.id?" open":""}`,"aria-label":`Session options for ${ee.title||ee.id}`,"aria-haspopup":"menu","aria-expanded":N===ee.id,onClick:W=>{W.stopPropagation(),N===ee.id?A():y(ee.id,"main")},children:e.jsxs("svg",{viewBox:"0 0 14 14","aria-hidden":!0,children:[e.jsx("circle",{cx:"3",cy:"7",r:"1.2",fill:"currentColor"}),e.jsx("circle",{cx:"7",cy:"7",r:"1.2",fill:"currentColor"}),e.jsx("circle",{cx:"11",cy:"7",r:"1.2",fill:"currentColor"})]})}),H&&B&&e.jsx("button",{type:"button",className:`chat-rail-tree-chevron${Z?" open":""}`,"aria-label":Z?"Collapse sub-agents":"Expand sub-agents","aria-expanded":Z,onClick:W=>{W.stopPropagation(),k(se=>({...se,[ee.id]:!se[ee.id]}))},children:e.jsx("svg",{viewBox:"0 0 10 10","aria-hidden":!0,children:e.jsx("polyline",{points:"3,1.5 7,5 3,8.5"})})})]}),H&&B&&Z&&((we=K==null?void 0:K.root)==null?void 0:we.children)&&e.jsx(Yi,{children:K.root.children,variant:"rail",open:!0})]},F?`oc-${ee.id}`:ee.id)})]},J))}),N&&f&&e.jsx(Hi,{session:{id:f.id,title:((O=[...s,...t].find(J=>J.id===f.id))==null?void 0:O.title)??f.id},mode:E,anchor:f,renameDraft:b,setRenameDraft:w,onEdit:()=>y(N,"rename"),onDeleteRequest:()=>y(N,"confirm-delete"),onConfirmDelete:D,onConfirmRename:C,onClose:A})]})}function tr(s){const{text:t,sending:a,onSend:i,activeSource:n}=s,[c,o]=r.useState(!1),l=()=>{!t.trim()||a||(o(!0),i(),window.setTimeout(()=>o(!1),320))};return e.jsxs("div",{className:`chat-composer-wrap chat-composer-source-${n??"none"}`,children:[e.jsx("div",{className:`chat-composer-pill${c?" takeoff":""}`,children:e.jsx(Qn,{...s,onSend:l})}),e.jsxs("div",{className:"chat-composer-hint chat-muted",children:[e.jsxs("span",{children:[e.jsx("kbd",{children:"⏎"})," send"]}),e.jsxs("span",{children:[e.jsx("kbd",{children:"⇧⏎"})," newline"]}),e.jsxs("span",{children:[e.jsx("kbd",{children:"/"})," commands"]}),n==="opencode"&&e.jsx("span",{className:"chat-composer-source-hint",children:"→ opencode"}),n==="bizar"&&e.jsx("span",{className:"chat-composer-source-hint",children:"→ bizar chat"}),a&&e.jsx("span",{className:"chat-composer-source-hint",children:"sending…"})]})]})}function at(s){return s.toLocaleString()}function ar(s){return!s||!s.includes("/")?"":s.split("/")[0]}function nr(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 ir({sessionId:s,messages:t,pinned:a,agent:i,model:n,agents:c,mcps:o,allCommands:l,activeSource:x="bizar",onRename:p,onDelete:u,onExport:d,busy:m,error:h,onRetry:g}){const[j,k]=r.useState(null);r.useEffect(()=>{let y=!1;return(async()=>{try{const A=await fetch("/api/usage?range=24h",{headers:{Accept:"application/json"}});if(!A.ok)return;const P=await A.json();y||k(P)}catch{}})(),()=>{y=!0}},[s]);const z=(t==null?void 0:t.length)??0,N=(a==null?void 0:a.size)??0,S=t.reduce((y,A)=>y+(A.content||A.message||"").length,0),E=Math.round(S/4),v=nr(n),b=E/1e6*v,w=(j==null?void 0:j.totalTokens)??E,f=(j==null?void 0:j.costUsd)??b,L=128e3,R=ar(n);return e.jsxs("aside",{className:"chat-info",children:[h&&e.jsxs("div",{className:"chat-info-section chat-info-error",role:"alert","aria-live":"polite",children:[e.jsxs("h4",{children:[e.jsx(Te,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Couldn't load session"]}),e.jsx("p",{className:"chat-info-value chat-ellipsis",title:h.message,children:h.message}),e.jsxs("div",{className:"chat-info-mono",children:["code · ",h.code]}),h.suggestion?e.jsx("p",{className:"chat-info-suggestion",children:h.suggestion}):null,h.canRetry!==!1&&g?e.jsxs("button",{type:"button",className:"btn btn-ghost btn-sm chat-info-retry",onClick:g,title:"Retry loading the session",children:[e.jsx(Js,{size:12,"aria-hidden":!0})," Retry"]}):null]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("div",{className:"chat-info-section-head",children:[e.jsxs("h4",{children:[e.jsx(Xs,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Session"]}),e.jsx("span",{className:`chat-source-badge chat-source-${x??"none"}`,style:{marginLeft:"auto"},children:x==="opencode"?"opencode":"bizar chat"})]}),e.jsx("div",{className:"chat-info-mono chat-ellipsis",title:s,children:s||"Live"}),e.jsxs("div",{className:"chat-info-mono",children:[at(z)," message",z===1?"":"s",N>0&&` · ${N} pinned`]})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("h4",{children:[e.jsx(Ye,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Agent"]}),e.jsx("div",{className:"chat-info-value",children:i||"—"})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("h4",{children:[e.jsx(js,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Model"]}),e.jsx("div",{className:"chat-mono chat-ellipsis",title:n,children:n||"—"}),R&&e.jsxs("div",{className:"chat-info-mono",children:["provider · ",R]})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsx("h4",{children:"Tokens"}),e.jsxs("div",{className:"chat-mono",children:[at(w)," / ",at(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,w/Math.max(1,L)*100)}%`}})})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("h4",{children:[e.jsx(rn,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Cost"]}),e.jsxs("div",{className:"chat-mono",children:["$",f.toFixed(4)]}),!j&&e.jsx("div",{className:"chat-info-mono",children:"approx · live from MiniMax"})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("h4",{children:[e.jsx(Ye,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Attached agents"]}),c!=null&&c.length?e.jsx("div",{className:"chat-info-agents",children:c.map(y=>e.jsx("span",{className:"chat-info-agent",children:y.name},y.name))}):e.jsx("div",{className:"chat-info-mono",children:"None attached"})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("h4",{children:[e.jsx(js,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","MCPs"]}),o!=null&&o.length?e.jsx("div",{className:"chat-info-agents",children:o.map(y=>e.jsx("span",{className:"chat-info-agent",children:y.id},y.id))}):e.jsx("div",{className:"chat-info-mono",children:"No MCPs configured"})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("h4",{children:[e.jsx(ns,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Slash commands"]}),e.jsxs("div",{className:"chat-info-mono",children:[(l==null?void 0:l.length)??0," available"]})]}),(p||u||d)&&e.jsxs("div",{className:"chat-info-section",children:[e.jsx("h4",{children:"Actions"}),e.jsxs("div",{className:"chat-info-actions",children:[p&&e.jsxs("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:p,disabled:m==null?void 0:m.rename,title:"Rename session",children:[e.jsx(Es,{size:12,"aria-hidden":!0})," Rename"]}),d&&e.jsxs("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:d,title:"Export transcript",children:[e.jsx(ls,{size:12,"aria-hidden":!0})," Export"]}),u&&e.jsxs("button",{type:"button",className:"btn btn-ghost btn-sm btn-danger",onClick:u,disabled:m==null?void 0:m.delete,title:"Delete session",children:[e.jsx(ke,{size:12,"aria-hidden":!0})," Delete"]})]})]})]})}function rr({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(oa,{size:14,"aria-hidden":!0}),e.jsx("span",{children:"Jump to latest"}),t>0&&e.jsxs("span",{className:"jump-badge",children:[t," new"]})]})})}function lr({snapshot:s,settings:t,setActiveTab:a,initialTaskId:i,onClearTaskId:n}){const c=re(),o=$e(),l=Zn(s,t,i??"");r.useEffect(()=>{l.setToast({error:O=>c.error(O),success:O=>c.success(O),info:O=>c.info(O),warning:O=>c.warning(O)})},[l,c]);const[x,p]=r.useState(""),[u,d]=r.useState(t.defaultAgent||"odin"),[m,h]=r.useState(t.defaultModel||""),[g,j]=r.useState([]),k=r.useRef(null),{allCommands:z,suggestions:N,setQuery:S}=ei(s);r.useEffect(()=>{S(x)},[x,S]);const E=()=>{var O;return(O=k.current)==null?void 0:O.click()},v=O=>{const J=O.target.files;if(!J)return;const ae=[];for(let ee=0;ee<J.length;ee++)ae.push(J[ee].name);j(ee=>{const F=ae.filter(H=>!ee.includes(H));return[...ee,...F]}),k.current&&(k.current.value="")},b=async()=>{const O=x.trim();if(!O)return;p(""),S(""),(await l.onSend(O,u,m,g)).ok&&l.jumpToLatest()},w=async()=>{l.busy.create||await l.onCreateSession()},f=O=>{o.open({title:"Delete message?",children:e.jsx("p",{style:{margin:0},children:"This action cannot be undone."}),footer:e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx($,{variant:"secondary",size:"sm",onClick:()=>o.close(),children:"Cancel"}),e.jsx($,{variant:"danger",size:"sm",onClick:()=>{o.close(),l.deleteMessage(O)},children:"Delete"})]})})},L=(O,J)=>{let ae="";o.open({title:"Rename session",children:e.jsx("input",{id:"rename-session-input",autoFocus:!0,defaultValue:J,"aria-label":"Session title",onChange:ee=>{ae=ee.target.value},onKeyDown:ee=>{ee.key==="Enter"&&(ee.preventDefault(),o.close(),l.renameSession(O,ae).then(F=>{F&&c.success("Renamed.")}))},style:{width:"100%",padding:"8px 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-sm)",color:"var(--text)",font:"13px/1.4 var(--font-sans)",marginTop:6}}),footer:e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx($,{variant:"secondary",size:"sm",onClick:()=>o.close(),children:"Cancel"}),e.jsx($,{variant:"primary",size:"sm",onClick:()=>{o.close(),l.renameSession(O,ae)},children:"Save"})]})})},R=(O,J)=>{o.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($,{variant:"secondary",size:"sm",onClick:()=>o.close(),children:"Cancel"}),e.jsx($,{variant:"danger",size:"sm",onClick:async()=>{o.close(),await l.deleteSession(O)},children:"Delete"})]})})},y=()=>{const O=l.activeSource==="opencode"?l.activeOpencodeSessionId:l.sessionId;if(!O)return;const ae=(l.activeSource==="opencode"?l.opencodeMessages:l.bizarMessages).map(K=>{const B=K.ts??"",Z=(K.role||"unknown").toUpperCase(),he=K.content||K.message||"";return`[${B}] ${Z}: ${he}`}).join(`
2
-
3
- `),ee=new Blob([ae],{type:"text/plain;charset=utf-8"}),F=URL.createObjectURL(ee),H=document.createElement("a");H.href=F,H.download=`${O}.txt`,document.body.appendChild(H),H.click(),document.body.removeChild(H),URL.revokeObjectURL(F)},A=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?A.find(J=>J.id===O)??P.find(J=>J.id===O)??null:null},[l.activeSource,l.activeOpencodeSessionId,l.sessionId,A,P]),D=(()=>{var ae;const O=`${u||"Odin"} · ${((ae=s.activeProject)==null?void 0:ae.name)??"no project"}`,J=(C==null?void 0:C.state)??"idle";return J==="streaming"?`Replying · ${O}`:J==="awaiting"?`Your turn · ${O}`:`${O} · idle`})(),Y=l.activeSource==="opencode"?"opencode":"bizar chat";return e.jsxs("div",{className:"chat-shell",children:[e.jsx(si,{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(sr,{sessions:A,opencodeSessions:P,activeSessionId:l.sessionId,activeOpencodeSessionId:l.activeOpencodeSessionId,activeProject:s.activeProject,creating:l.busy.create,onCreateSession:w,onSelectSession:l.selectBizarSession,onSelectOpencodeSession:O=>l.loadOpencodeSession(O.id),onRenameSession:L,onDeleteSession:O=>{const J=l.sessions.find(ae=>ae.id===O)??l.opencodeSessions.find(ae=>ae.id===O);R(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:Y})]}),e.jsxs("div",{className:`chat-thread-sub chat-muted state-${(C==null?void 0:C.state)??"idle"}`,children:[e.jsx("span",{className:"chat-thread-dot"}),D]}),l.opencodeError&&e.jsxs("div",{className:"chat-thread-error",role:"alert",children:[e.jsx("p",{className:"chat-error-message",children:l.opencodeError}),l.opencodeSuggestion&&e.jsx("p",{className:"chat-error-suggestion",children:l.opencodeSuggestion}),l.activeOpencodeSessionId&&e.jsx("button",{className:"btn btn-sm",type:"button",onClick:()=>l.loadOpencodeSession(l.activeOpencodeSessionId),children:"Retry"})]})]}),e.jsxs("div",{className:"chat-thread-actions",children:[C&&e.jsxs("button",{className:"btn btn-ghost",title:"Rename session",type:"button",disabled:l.busy.rename,onClick:()=>L(C.id,C.title??""),children:[e.jsx(Es,{size:12,"aria-hidden":!0})," ",e.jsx("span",{className:"mono",children:"rename"})]}),C&&e.jsxs("button",{className:"btn btn-ghost btn-danger",title:"Delete session",type:"button",disabled:l.busy.delete,onClick:()=>R(C.id,C.title??C.id),children:[e.jsx(ke,{size:12,"aria-hidden":!0})," ",e.jsx("span",{className:"mono",children:"delete"})]}),e.jsx("button",{className:"btn btn-ghost",title:"Export transcript",type:"button",onClick: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(ti,{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:f,onTogglePin:l.togglePin,onRegenerate:l.onRegenerate})}),!l.stickToBottom&&e.jsx(rr,{streaming:(C==null?void 0:C.state)==="streaming",newMessageCount:l.newMessageCount,onClick:l.jumpToLatest}),e.jsx(tr,{agent:u,setAgent:d,model:m,setModel:h,text:x,setText:p,sending:l.sending,activeSource:l.activeSource,onSend:b,attachments:g,setAttachments:j,suggestions:N,onPickSuggestion:O=>p(`${O.split(" ")[0]} `),agents:s.agents||[],onAttach:E}),e.jsx("input",{ref:k,type:"file",multiple:!0,style:{display:"none"},onChange:v,"aria-label":"Attach files to message",tabIndex:-1})]}),e.jsx(ir,{sessionId:l.activeSource==="opencode"?l.activeOpencodeSessionId??l.sessionId:l.sessionId,messages:l.activeSource==="opencode"?l.opencodeMessages:l.bizarMessages,pinned:l.pinned,agent:u,model:m,agents:s.agents||[],mcps:s.mcps||[],allCommands:z,activeSource:l.activeSource,onRename:()=>{C&&L(C.id,C.title??"")},onDelete:()=>{C&&R(C.id,C.title??C.id)},onExport:y,busy:l.busy})]})]})}function or(s){return s==="ok"?"success":s==="warn"?"warning":s==="fail"?"error":s}function Je({kind:s="neutral",children:t,className:a,dot:i=!1}){const n=or(s);return e.jsxs("span",{className:V("badge",`badge-${n}`,a),title:`status: ${s}`,children:[i&&e.jsx("span",{className:"badge-dot"}),t]})}const Ut=["bash","read","edit","write","webfetch","websearch","task","glob","grep"],_t=["anthropic/claude-3-5-sonnet","anthropic/claude-3-5-haiku","openai/gpt-4o","openai/gpt-4o-mini","openrouter/minimax/minimax-m3","openrouter/minimax/minimax-m2.7"],Ws=[{id:"reasoning",label:"Reasoning",color:"var(--accent)"},{id:"code",label:"Code",color:"var(--info)"},{id:"design",label:"Design",color:"var(--success)"},{id:"planning",label:"Planning",color:"var(--warning)"},{id:"gitops",label:"GitOps",color:"var(--error)"},{id:"analysis",label:"Analysis",color:"var(--text-dim)"}];function cr(s){var t;return((t=Ws.find(a=>a.id===s))==null?void 0:t.color)||"var(--text-dim)"}function dr({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 mr({agent:s}){if(s.isStuck)return e.jsx(Je,{kind:"error",dot:!0,children:"stuck"});const t=s.status||"idle";return t==="working"?e.jsx(Je,{kind:"info",dot:!0,children:"working"}):t==="error"?e.jsx(Je,{kind:"error",dot:!0,children:"error"}):e.jsx(Je,{kind:"neutral",dot:!0,children:"idle"})}function ur({snapshot:s,refreshSnapshot:t}){const a=re(),i=$e(),[n,c]=r.useState(s.agents||[]),[o,l]=r.useState(!s.agents),[x,p]=r.useState(""),[u,d]=r.useState("");r.useEffect(()=>{c(s.agents||[]),l(!s.agents)},[s.agents]);const m=async()=>{try{const v=await T.get("/agents");c(v.agents||[])}catch(v){a.error(`Agents load failed: ${v.message}`)}finally{l(!1)}},h=r.useMemo(()=>{let v=[...n];if(x&&(v=v.filter(b=>x==="__none__"?!b.category:(b.category||"")===x)),u){const b=u.toLowerCase();v=v.filter(w=>w.name.toLowerCase().includes(b)||(w.description||"").toLowerCase().includes(b)||(w.tags||[]).some(f=>f.toLowerCase().includes(b)))}return v.sort((b,w)=>b.name.localeCompare(w.name))},[n,x,u]),g=r.useMemo(()=>{const v=new Set;for(const b of n)for(const w of b.tags||[])v.add(w);return Array.from(v).sort()},[n]),j=()=>{let v=null,b=null,w=null,f=null,L=null,R=null,y=null,A=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=>v=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=>{b=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=>w=C,className:"select",defaultValue:"",children:[e.jsx("option",{value:"",children:"(provider default)"}),_t.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=>f=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)"}),Ws.map(C=>e.jsx("option",{value:C.id,children:C.label},C.id))]})]}),e.jsxs("div",{className:"task-form-field",style:{flex:2},children:[e.jsx("label",{className:"field-label",htmlFor:"agent-new-tags",children:"Tags (comma-separated)"}),e.jsx("input",{id:"agent-new-tags",ref:C=>A=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:Ut.map(C=>e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{type:"checkbox",value:C,"aria-label":C}),e.jsx("span",{children:C})]},C))})]}),e.jsx("label",{className:"field-label",htmlFor:"agent-new-prompt",children:"System prompt"}),e.jsx("textarea",{id:"agent-new-prompt",ref:C=>R=C,className:"textarea",rows:6,placeholder:"You are a..."})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx($,{variant:"ghost",onClick:()=>i.close(),children:"Cancel"}),e.jsxs($,{variant:"primary",onClick:async()=>{const C=((v==null?void 0:v.value)||"").trim();if(!/^[a-z0-9][a-z0-9-]{0,63}$/i.test(C)){a.warning("Invalid name (a-z, 0-9, dashes).");return}const D=[];y&&y.querySelectorAll('input[type="checkbox"]:checked').forEach(O=>{D.push(O.value)});const Y=((A==null?void 0:A.value)||"").split(",").map(O=>O.trim()).filter(Boolean);try{const O=await T.post("/agents",{name:C,description:((b==null?void 0:b.value)||"").trim(),model:(w==null?void 0:w.value)||"",mode:(f==null?void 0:f.value)||"subagent",color:(L==null?void 0:L.value)||"",tools:D,tags:Y,category:(P==null?void 0:P.value)||"",prompt:(R==null?void 0:R.value)||""});c(J=>[...J,O]),a.success("Agent created."),i.close(),await t()}catch(O){a.error(`Create failed: ${O.message}`)}},children:[e.jsx(As,{size:12})," Create"]})]})})},k=async v=>{let b=null,w=null,f=null,L=null,R=null,y=null,A=null,P=null;try{const C=await T.get(`/agents/${encodeURIComponent(v.name)}`);i.open({title:`Edit ${v.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=>{b=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=>w=D,className:"select",defaultValue:C.model,children:[e.jsx("option",{value:"",children:"(provider default)"}),_t.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=>f=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)"}),Ws.map(D=>e.jsx("option",{value:D.id,children:D.label},D.id))]})]}),e.jsxs("div",{className:"task-form-field",style:{flex:2},children:[e.jsx("label",{className:"field-label",htmlFor:"agent-edit-tags",children:"Tags (comma-separated)"}),e.jsx("input",{id:"agent-edit-tags",ref:D=>A=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:Ut.map(D=>{var Y;return e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{type:"checkbox",value:D,"aria-label":D,defaultChecked:(Y=C.tools)==null?void 0:Y.includes(D)}),e.jsx("span",{children:D})]},D)})})]}),e.jsx("label",{className:"field-label",htmlFor:"agent-edit-prompt",children:"System prompt"}),e.jsx("textarea",{id:"agent-edit-prompt",ref:D=>R=D,className:"textarea",rows:8,defaultValue:C.prompt||""})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx($,{variant:"ghost",onClick:()=>i.close(),children:"Cancel"}),e.jsxs($,{variant:"primary",onClick:async()=>{const D=[];y&&y.querySelectorAll('input[type="checkbox"]:checked').forEach(O=>{D.push(O.value)});const Y=((A==null?void 0:A.value)||"").split(",").map(O=>O.trim()).filter(Boolean);try{const O=await T.put(`/agents/${encodeURIComponent(v.name)}`,{description:((b==null?void 0:b.value)||"").trim(),model:(w==null?void 0:w.value)||"",mode:(f==null?void 0:f.value)||"subagent",color:(L==null?void 0:L.value)||"",tools:D,tags:Y,category:(P==null?void 0:P.value)||"",prompt:(R==null?void 0:R.value)||""});c(J=>J.map(ae=>ae.name===v.name?O:ae)),a.success("Agent saved."),i.close(),await t()}catch(O){a.error(`Save failed: ${O.message}`)}},children:[e.jsx(As,{size:12})," Save"]})]})})}catch(C){a.error(`Load failed: ${C.message}`)}},z=async v=>{if(confirm(`Delete agent "${v.name}"? This removes ${v.path}.`))try{await T.del(`/agents/${encodeURIComponent(v.name)}`),c(b=>b.filter(w=>w.name!==v.name)),a.success("Agent deleted.")}catch(b){a.error(`Delete failed: ${b.message}`)}},N=async v=>{let b=null;i.open({title:`Invoke ${v.name}`,children:e.jsxs("div",{className:"invoke-form",children:[e.jsxs("p",{className:"muted invoke-form-meta mono",children:[v.model||"—"," · ",v.path]}),e.jsx("p",{className:"invoke-form-desc",children:v.description}),e.jsx("label",{className:"field-label",htmlFor:"invoke-prompt",children:"Prompt"}),e.jsx("textarea",{ref:w=>b=w,id:"invoke-prompt",className:"textarea",rows:5,placeholder:"What should this agent do?",autoFocus:!0})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx($,{variant:"ghost",onClick:()=>i.close(),children:"Cancel"}),e.jsxs($,{variant:"primary",onClick:async()=>{const w=((b==null?void 0:b.value)||"").trim();if(!w){a.warning("Prompt is required.");return}try{await T.post(`/agents/${encodeURIComponent(v.name)}/invoke`,{prompt:w}),a.success(`Invoked ${v.name}.`),i.close()}catch(f){a.error(`Invoke failed: ${f.message}`)}},children:[e.jsx(Ls,{size:14})," Invoke"]})]})})},S=async v=>{try{const b=await T.post(`/agents/${encodeURIComponent(v.name)}/restart`);c(w=>w.map(f=>f.name===v.name?b:f)),a.success(`${v.name} restarted.`)}catch(b){a.error(`Restart failed: ${b.message}`)}},E=async(v,b)=>{try{const w=await T.post(`/agents/${encodeURIComponent(v.name)}/status`,{status:b});c(f=>f.map(L=>L.name===v.name?w:L))}catch(w){a.error(`Status update failed: ${w.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(Ye,{size:18})," Agents (",h.length,")"]}),e.jsxs("p",{className:"view-subtitle",children:["The Norse pantheon — click ",e.jsx("kbd",{children:"Edit"})," to modify or ",e.jsx("kbd",{children:"Invoke"})," to dispatch."]})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs("div",{className:"search-input",children:[e.jsx("label",{htmlFor:"agents-search",className:"sr-only",children:"Search agents"}),e.jsx("input",{id:"agents-search",className:"input",type:"text",placeholder:"Search…",value:u,onChange:v=>d(v.target.value),"aria-label":"Search agents"})]}),e.jsx("label",{htmlFor:"agents-category-filter",className:"sr-only",children:"Filter by category"}),e.jsxs("select",{id:"agents-category-filter",className:"select select-sm",value:x,onChange:v=>p(v.target.value),children:[e.jsx("option",{value:"",children:"All categories"}),Ws.map(v=>e.jsx("option",{value:v.id,children:v.label},v.id)),e.jsx("option",{value:"__none__",children:"(no category)"})]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:m,children:[e.jsx(de,{size:14})," Refresh"]}),e.jsxs($,{variant:"primary",size:"sm",onClick:j,children:[e.jsx(ze,{size:14})," New agent"]})]})]}),g.length>0&&e.jsxs("div",{className:"agent-tags-row",children:[e.jsx(ca,{size:12}),g.map(v=>e.jsx("span",{className:"tag",children:v},v))]}),o?e.jsx("div",{className:"view-loading",children:e.jsx(oe,{size:"lg"})}):h.length===0?e.jsx(pe,{icon:e.jsx(Ye,{size:32}),title:"No agents found",message:"Run bizar in the terminal to install Bizar."}):e.jsx("div",{className:"agent-grid",children:h.map(v=>e.jsx(hr,{agent:v,onInvoke:()=>N(v),onEdit:()=>k(v),onDelete:()=>z(v),onRestart:()=>S(v),onSetStatus:b=>E(v,b)},v.name))})]})}function hr({agent:s,onInvoke:t,onEdit:a,onDelete:i,onRestart:n,onSetStatus:c}){const[o,l]=r.useState(!1),x=cr(s.category),p=(s.status==="working"||!!s.currentTaskId)&&!s.isStuck;return e.jsxs(G,{variant:"elevated",interactive:!0,className:V("agent-card",p&&"is-working",s.isStuck&&"is-stuck"),children:[e.jsxs("div",{className:"agent-card-head",children:[e.jsxs("div",{className:"agent-card-name",children:[e.jsx(dr,{status:s.status,isStuck:s.isStuck}),s.name]}),e.jsxs("div",{className:"agent-card-badges",children:[s.category&&e.jsx("span",{className:"agent-card-category",style:{background:`color-mix(in srgb, ${x} 18%, transparent)`,color:x},children:s.category}),e.jsx(mr,{agent:s})]})]}),e.jsx("p",{className:"agent-card-desc",children:Zt(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:Ce(s.mtime)})]}),s.tags&&s.tags.length>0&&e.jsx("div",{className:"agent-card-tags",children:s.tags.map(u=>e.jsx("span",{className:"agent-card-tag",children:u},u))}),(p||s.lastTask)&&e.jsxs("div",{className:"agent-card-activity",children:[s.currentTaskId&&e.jsxs("div",{className:"agent-card-row",children:[e.jsx(De,{size:12}),e.jsx("span",{className:"muted",children:"Working on"}),e.jsx("code",{className:"mono",children:s.currentTaskId})]}),s.lastTask&&!s.currentTaskId&&e.jsxs("div",{className:"agent-card-row",children:[e.jsx(qe,{size:12}),e.jsx("span",{className:"muted",children:"Last"}),e.jsx("code",{className:"mono",children:s.lastTask.id}),e.jsx("span",{className:"muted tabular-nums",children:Ce(s.lastTask.finishedAt)})]}),s.tasksTotal!=null&&s.tasksTotal>0&&e.jsxs("div",{className:"agent-card-row",children:[e.jsx(ln,{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(Te,{size:12}),e.jsxs("span",{className:"muted",children:["Last error: ",s.lastError.message]})]}),e.jsxs("div",{className:"agent-card-actions",children:[e.jsxs($,{variant:"primary",size:"sm",onClick:t,children:[e.jsx(Ls,{size:12})," Invoke"]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:a,children:[e.jsx(Es,{size:12})," Edit"]}),(s.isStuck||s.status==="working"||s.status==="error")&&e.jsxs($,{variant:"ghost",size:"sm",onClick:n,title:"Reset agent status",children:[e.jsx(Js,{size:12})," Restart"]}),e.jsx($,{variant:"ghost",size:"sm",onClick:i,children:e.jsx(ke,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":o?"Collapse":"Expand",onClick:()=>l(u=>!u),style:{marginLeft:"auto"},children:o?e.jsx(We,{size:12}):e.jsx(Xe,{size:12})})]}),o&&e.jsxs("div",{className:"agent-card-expanded",children:[e.jsxs("div",{className:"agent-card-status-actions",children:[e.jsx("span",{className:"muted text-sm",children:"Set status:"}),e.jsx($,{variant:s.status==="idle"?"primary":"ghost",size:"sm",onClick:()=>c("idle"),children:"Idle"}),e.jsx($,{variant:s.status==="working"?"primary":"ghost",size:"sm",onClick:()=>c("working"),children:"Working"}),e.jsx($,{variant:s.status==="error"?"primary":"ghost",size:"sm",onClick:()=>c("error"),children:"Error"})]}),e.jsxs("div",{className:"agent-card-meta",children:[e.jsx(Fe,{size:11}),e.jsx("code",{className:"mono agent-card-path",children:s.path})]})]})]})}function xr({id:s,children:t}){return e.jsx("div",{id:s,"data-block-id":s,className:V("glyph-richtext"),style:Ca,children:e.jsx(ba,{remarkPlugins:[Na],children:t})})}const pr={info:{bg:"var(--info-soft, rgba(96, 165, 250, 0.12))",border:"var(--info)",fg:"var(--info)",icon:wt,label:"Note"},warn:{bg:"var(--warning-soft, rgba(251, 191, 36, 0.15))",border:"var(--warning)",fg:"var(--warning)",icon:Te,label:"Warning"},success:{bg:"var(--success-soft, rgba(52, 211, 153, 0.15))",border:"var(--success)",fg:"var(--success)",icon:qe,label:"Success"},danger:{bg:"var(--error-soft, rgba(248, 113, 113, 0.12))",border:"var(--error)",fg:"var(--error)",icon:Qs,label:"Danger"}};function gr({id:s,tone:t="info",children:a}){const i=pr[t],n=i.icon;return e.jsxs("div",{id:s,"data-block-id":s,className:V("glyph-callout",`glyph-callout-${t}`),style:{display:"flex",gap:12,padding:"12px 16px",margin:"12px 0",borderLeft:`3px solid ${i.border}`,background:i.bg,borderRadius:8,color:"var(--text)"},role:t==="danger"||t==="warn"?"alert":void 0,children:[e.jsx("div",{style:{flexShrink:0,color:i.fg,paddingTop:2},children:e.jsx(n,{size:18})}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontWeight:600,fontSize:13,color:i.fg,marginBottom:4},children:i.label}),e.jsx("div",{className:"glyph-richtext",style:{...Ca,fontSize:14},children:e.jsx(ba,{remarkPlugins:[Na],children:a})})]})]})}function fr({id:s,items:t}){return e.jsx("ul",{id:s,"data-block-id":s,className:"glyph-checklist",style:{listStyle:"none",padding:0,margin:"12px 0",display:"flex",flexDirection:"column",gap:6},children:t.map(a=>e.jsxs("li",{style:{display:"flex",alignItems:"flex-start",gap:10,padding:"6px 10px",borderRadius:6,background:"var(--bg-elev)",border:"1px solid var(--border)",fontSize:14},children:[e.jsx("span",{"aria-hidden":!0,style:{flexShrink:0,marginTop:1,width:16,height:16,borderRadius:4,border:`1.5px solid ${a.checked?"var(--success)":"var(--border-strong)"}`,background:a.checked?"var(--success)":"transparent",color:"var(--bg)",display:"inline-flex",alignItems:"center",justifyContent:"center"},children:a.checked?e.jsx(gs,{size:12,strokeWidth:3}):null}),e.jsx("span",{style:{color:a.checked?"var(--text-dim)":"var(--text)",textDecoration:a.checked?"line-through":"none",wordBreak:"break-word"},children:a.label})]},a.id))})}function jr({id:s,columns:t,rows:a}){return e.jsx("div",{id:s,"data-block-id":s,className:"glyph-table-wrap",style:{margin:"12px 0",border:"1px solid var(--border)",borderRadius:8,overflow:"auto",background:"var(--bg-elev)"},children:e.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:13},children:[e.jsx("thead",{children:e.jsx("tr",{children:t.map((i,n)=>e.jsx("th",{style:{textAlign:"left",padding:"8px 12px",borderBottom:"1px solid var(--border-strong)",background:"var(--bg)",color:"var(--text-dim)",fontWeight:600,fontSize:12,textTransform:"uppercase",letterSpacing:.3,whiteSpace:"nowrap"},children:i},n))})}),e.jsx("tbody",{children:a.map((i,n)=>e.jsx("tr",{style:{borderTop:n===0?"none":"1px solid var(--border)"},children:i.map((c,o)=>e.jsx("td",{style:{padding:"8px 12px",color:"var(--text)",verticalAlign:"top",wordBreak:"break-word"},children:c},o))},n))})]})})}function vr({id:s,tabs:t}){var c;const[a,i]=r.useState(((c=t[0])==null?void 0:c.id)??""),n=r.useMemo(()=>t.find(o=>o.id===a)??t[0],[t,a]);return e.jsxs("div",{id:s,"data-block-id":s,className:"glyph-codetabs",style:{margin:"12px 0",border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:"var(--bg-elev)"},children:[e.jsx("div",{role:"tablist",style:{display:"flex",gap:2,padding:4,background:"var(--bg)",borderBottom:"1px solid var(--border)",overflowX:"auto"},children:t.map(o=>{const l=o.id===(n==null?void 0:n.id);return e.jsxs("button",{type:"button",role:"tab","aria-selected":l,onClick:()=>i(o.id),style:{padding:"6px 12px",fontSize:12,fontFamily:"var(--font-mono)",borderRadius:6,border:"none",cursor:"pointer",background:l?"var(--bg-elev)":"transparent",color:l?"var(--text-strong)":"var(--text-dim)",boxShadow:l?"0 0 0 1px var(--border)":"none",whiteSpace:"nowrap"},children:[e.jsx("span",{children:o.label}),o.language&&e.jsx("span",{style:{marginLeft:6,color:"var(--text-dim)",fontSize:11},children:o.language})]},o.id)})}),n&&e.jsxs(e.Fragment,{children:[e.jsx("pre",{style:{margin:0,padding:14,overflowX:"auto",fontFamily:"var(--font-mono)",fontSize:12.5,lineHeight:1.55,color:"var(--text)",background:"var(--bg-elev)"},children:e.jsx("code",{children:n.code})}),n.caption&&e.jsx("div",{style:{padding:"8px 14px",borderTop:"1px solid var(--border)",fontSize:12,color:"var(--text-dim)",background:"var(--bg)"},children:n.caption})]})]})}function yr({id:s,title:t,question:a,options:i}){return e.jsxs("div",{id:s,"data-block-id":s,className:"glyph-decision",style:{margin:"16px 0",padding:16,border:"1px solid var(--border)",borderRadius:10,background:"var(--bg-elev)"},children:[t&&e.jsx("h3",{style:{margin:0,marginBottom:4,fontSize:15,fontWeight:600,color:"var(--text-strong)"},children:t}),a&&e.jsx("p",{style:{margin:0,marginBottom:12,fontSize:13,color:"var(--text-dim)"},children:a}),e.jsx("div",{style:{display:"grid",gap:10,gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))"},children:i.map(n=>{const c=!!n.recommended;return e.jsxs("div",{style:{position:"relative",padding:12,borderRadius:8,border:c?"2px solid var(--success)":"1px solid var(--border)",background:c?"var(--success-soft)":"var(--bg)"},children:[c&&e.jsx("span",{style:{position:"absolute",top:-10,right:10,padding:"2px 8px",fontSize:11,fontWeight:600,color:"var(--bg)",background:"var(--success)",borderRadius:999},children:"Recommended"}),e.jsx("div",{style:{fontWeight:600,fontSize:14,color:"var(--text-strong)",marginBottom:4},children:n.label}),e.jsx("div",{style:{fontSize:13,color:"var(--text)"},children:n.detail})]},n.id)})})]})}function br({id:s,questions:t}){const[a,i]=r.useState({});function n(c,o){i(l=>({...l,[c]:o}))}return e.jsxs("div",{id:s,"data-block-id":s,className:"glyph-openquestions",style:{margin:"16px 0",padding:16,border:"1px solid var(--border)",borderRadius:10,background:"var(--bg-elev)",display:"flex",flexDirection:"column",gap:14},children:[e.jsx("div",{style:{fontSize:13,fontWeight:600,color:"var(--text-strong)"},children:"Open questions"}),t.map(c=>e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[e.jsx("label",{htmlFor:`oq-${c.id}`,style:{fontSize:13,color:"var(--text)",fontWeight:500},children:c.label}),c.kind==="choice"&&e.jsxs("select",{id:`oq-${c.id}`,value:a[c.id]??"",onChange:o=>n(c.id,o.target.value),style:Wt,children:[e.jsx("option",{value:"",children:"— select —"}),(c.options??[]).map(o=>e.jsx("option",{value:o,children:o},o))]}),c.kind==="text"&&e.jsx("input",{id:`oq-${c.id}`,type:"text",value:a[c.id]??"",onChange:o=>n(c.id,o.target.value),style:Wt}),c.kind==="multi"&&e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4},children:(c.options??[]).map(o=>{const l=a[c.id]??[],x=l.includes(o);return e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,color:"var(--text)",cursor:"pointer"},children:[e.jsx("input",{type:"checkbox",checked:x,onChange:()=>{const p=x?l.filter(u=>u!==o):[...l,o];n(c.id,p)}}),e.jsx("span",{children:o})]},o)})})]},c.id))]})}const Wt={padding:"6px 10px",fontSize:13,borderRadius:6,border:"1px solid var(--border-strong)",background:"var(--bg)",color:"var(--text)",fontFamily:"inherit"},Nr={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 kr({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=Nr[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 wr({id:s,filename:t,language:a,mode:i="unified",before:n,after:c}){const o=n.split(`
4
- `),l=c.split(`
5
- `),x=e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 12px",background:"var(--bg)",borderBottom:"1px solid var(--border)",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:[e.jsx(mn,{size:14}),e.jsx("span",{style:{color:"var(--text)"},children:t??"diff"}),a&&e.jsxs("span",{children:["· ",a]}),e.jsx("span",{style:{marginLeft:"auto",textTransform:"uppercase",letterSpacing:.3},children:i})]}),p={margin:0,padding:0,fontFamily:"var(--font-mono)",fontSize:12.5,lineHeight:1.55,color:"var(--text)",background:"var(--bg-elev)"},u=(d,m,h)=>{const g={del:"var(--error-soft)",add:"var(--success-soft)",ctx:"transparent"},j={del:"var(--error)",add:"var(--success)",ctx:"var(--text-dim)"};return e.jsxs("div",{style:{display:"flex",padding:"0 12px",background:g[h]},children:[e.jsx("span",{style:{width:18,color:j[h],userSelect:"none",flexShrink:0},children:d}),e.jsx("span",{style:{whiteSpace:"pre",flex:1,overflowX:"auto"},children:m||" "})]})};return e.jsxs("div",{id:s,"data-block-id":s,className:"glyph-diff",style:{margin:"12px 0",border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:"var(--bg-elev)"},children:[x,i==="unified"?e.jsxs("pre",{style:p,children:[o.map((d,m)=>e.jsx("div",{children:u("-",d,"del")},`b${m}`)),l.map((d,m)=>e.jsx("div",{children:u("+",d,"add")},`a${m}`))]}):e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr"},children:[e.jsx("pre",{style:{...p,borderRight:"1px solid var(--border)"},children:o.map((d,m)=>e.jsx("div",{children:u("-",d,"del")},m))}),e.jsx("pre",{style:p,children:l.map((d,m)=>e.jsx("div",{children:u("+",d,"add")},m))})]})]})}const Sr={up:{fg:"var(--success)",Icon:We,label:"trending up"},down:{fg:"var(--error)",Icon:We,label:"trending down"},flat:{fg:"var(--text-dim)",Icon:dn,label:"flat"}};function Cr({id:s,label:t,value:a,trend:i,hint:n}){const c=i?Sr[i]:null;return e.jsxs("div",{id:s,"data-block-id":s,className:"glyph-stat",style:{padding:14,border:"1px solid var(--border)",borderRadius:10,background:"var(--bg-elev)",display:"flex",flexDirection:"column",gap:4,minWidth:140},children:[e.jsx("div",{style:{fontSize:12,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:t}),e.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:8},children:[e.jsx("span",{style:{fontSize:24,fontWeight:700,color:"var(--text-strong)"},children:a}),c&&e.jsx("span",{"aria-label":c.label,style:{display:"inline-flex",alignItems:"center",color:c.fg,transform:c.Icon===We&&i==="up"?"rotate(180deg)":void 0},children:e.jsx(c.Icon,{size:14})})]}),n&&e.jsx("div",{style:{fontSize:12,color:"var(--text-dim)"},children:n})]})}const zr={task:{stroke:"var(--info)",fill:"var(--bg-elev)",fg:"var(--text)"},decision:{stroke:"var(--warning)",fill:"var(--bg-elev)",fg:"var(--text)"},note:{stroke:"var(--border-strong)",fill:"var(--bg)",fg:"var(--text-dim)"}},Ae=160,Le=56,ds=60,ms=80;function Tr({id:s,steps:t,connections:a=[]}){if(t.length===0)return e.jsx("div",{id:s,"data-block-id":s,className:"glyph-workflow",children:e.jsx(Rr,{id:s})});const i=new Map(t.map(u=>[u.id,u])),n=$r(t),c=Math.max(...n.map(u=>u.col))+1,o=Math.max(...n.map(u=>u.row))+1,l=c*(Ae+ds)+ds,x=o*(Le+ms)+ms;function p(u){if(!i.get(u))return null;const m=n.find(h=>h.id===u);return m?{x:ds+m.col*(Ae+ds)+Ae/2,y:ms+m.row*(Le+ms)+Le/2}:null}return e.jsx("div",{id:s,"data-block-id":s,className:"glyph-workflow",style:{margin:"12px 0",padding:12,border:"1px solid var(--border)",borderRadius:10,background:"var(--bg-elev)",overflow:"auto"},children:e.jsxs("svg",{role:"img","aria-label":"Workflow diagram",width:l,height:x,style:{display:"block",maxWidth:"100%"},children:[e.jsx("defs",{children:e.jsx("marker",{id:`arrow-${s}`,viewBox:"0 0 10 10",refX:"9",refY:"5",markerWidth:"6",markerHeight:"6",orient:"auto-start-reverse",children:e.jsx("path",{d:"M 0 0 L 10 5 L 0 10 z",fill:"var(--text-dim)"})})}),a.map((u,d)=>{const m=p(u.from),h=p(u.to);if(!m||!h)return null;const g=h.x-m.x,j=h.y-m.y,k=g>=0?m.x+Ae/2:m.x-Ae/2,z=g>=0?h.x-Ae/2:h.x+Ae/2,N=j>=0?m.y+Le/2:m.y-Le/2,S=j>=0?h.y-Le/2:h.y+Le/2,E=(k+z)/2,v=(N+S)/2;return e.jsxs("g",{children:[e.jsx("line",{x1:k,y1:N,x2:z,y2:S,stroke:"var(--text-dim)",strokeWidth:1.5,markerEnd:`url(#arrow-${s})`}),u.label&&e.jsx("text",{x:E,y:v-4,fontSize:10,fill:"var(--text-dim)",textAnchor:"middle",fontFamily:"var(--font-mono)",children:u.label})]},d)}),t.map(u=>{const d=n.find(k=>k.id===u.id);if(!d)return null;const m=ds+d.col*(Ae+ds),h=ms+d.row*(Le+ms),g=zr[u.type];if(u.type==="decision"){const k=m+Ae/2,z=h+Le/2,N=[[k,h],[m+Ae,z],[k,h+Le],[m,z]].map(S=>S.join(",")).join(" ");return e.jsxs("g",{children:[e.jsx("polygon",{points:N,fill:g.fill,stroke:g.stroke,strokeWidth:2}),e.jsx("foreignObject",{x:m+8,y:z-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(on,{size:11}),u.label]})})]},u.id)}const j=u.type==="note";return e.jsxs("g",{children:[e.jsx("rect",{x:m,y:h,width:Ae,height:Le,rx:8,fill:g.fill,stroke:g.stroke,strokeWidth:j?1:2,strokeDasharray:j?"4 3":void 0}),e.jsx("foreignObject",{x:m+6,y:h+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:j?"italic":"normal",height:"100%"},children:[j&&e.jsx(cn,{size:11}),u.label]})})]},u.id)})]})})}function Rr({id:s}){return e.jsx("div",{id:s,style:{padding:20,textAlign:"center",color:"var(--text-dim)",fontSize:13},children:"No workflow steps."})}function $r(s){return s.length===0?[]:s.map((t,a)=>({id:t.id,col:a,row:0}))}const Ca={fontSize:14,lineHeight:1.6,color:"var(--text)"};function Ar({id:s,title:t,x:a,y:i,w:n,h:c,html:o}){return e.jsxs("figure",{id:s,"data-block-id":s,className:"glyph-mockup",style:{width:n,minHeight:c},children:[t&&e.jsx("figcaption",{className:"glyph-mockup-title",children:t}),e.jsxs("div",{className:"glyph-mockup-frame",children:[e.jsxs("div",{className:"glyph-mockup-chrome",children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]}),e.jsx("div",{className:"glyph-mockup-body",dangerouslySetInnerHTML:{__html:o}})]})]})}class Mr extends Oe.Component{constructor(){super(...arguments);ks(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 Ir(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 Er={overview:"Overview",implementation:"Implementation plan","implementation-plan":"Implementation plan",questions:"Open questions","open-questions":"Open questions","open-questions-for-you":"Open questions",comments:"Comments",handoff:"Handoff"};function Lr(s){const t=[];let a={heading:null,blocks:[]};for(const i of s){const n=Er[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 Dr({slug:s,onClose:t,onCommentAdded:a}){var B,Z,he,we;const i=re(),[n,c]=r.useState(null),[o,l]=r.useState([]),[x,p]=r.useState(!0),[u,d]=r.useState(null),[m,h]=r.useState(null),[g,j]=r.useState(!1),[k,z]=r.useState(!1),[N,S]=r.useState(null),[E,v]=r.useState(null),[b,w]=r.useState(""),[f,L]=r.useState(null),[R,y]=r.useState([]),A=Oe.useCallback((W,se,ie)=>{y(me=>me.some(_=>_.blockId===W)?me:[...me,{blockId:W,blockType:se,message:ie.message||String(ie)}])},[]),P=r.useRef(null),C=r.useMemo(()=>n?Lr(n.blocks):[],[n]);r.useEffect(()=>{let W=!1;const se=5e3;return(async()=>{p(!0),d(null);try{const ie=new Promise((Q,U)=>setTimeout(()=>U(new Error("Request timed out after 5s")),se)),[me,_]=await Promise.race([Promise.all([T.get(`/artifacts/${encodeURIComponent(s)}/render`),T.get(`/artifacts/${encodeURIComponent(s)}`)]),ie]);if(W)return;c(me);const I=(_==null?void 0:_.comments)??[];l(Array.isArray(I)?I:[])}catch(ie){if(!W){const me=ie.message;d(me),h(me)}}finally{W||p(!1)}})(),()=>{W=!0}},[s]);function D(W){if(!P.current)return;W.preventDefault();const se=P.current.getBoundingClientRect();S({x:W.clientX,y:W.clientY,worldX:W.clientX-se.left,worldY:W.clientY-se.top})}async function Y(){if(!(!E||!b.trim()))try{const W=await T.post(`/artifacts/${encodeURIComponent(s)}/comments`,{x:E.worldX,y:E.worldY,text:b.trim(),author:"drb0rk"});l(se=>[...se,{id:W.id??`cmt_${Date.now()}`,x:E.worldX,y:E.worldY,text:b.trim(),author:"drb0rk",created:new Date().toISOString()}]),v(null),w(""),S(null),a==null||a(),i.success("Comment added")}catch(W){i.error(`Failed to add comment: ${W.message}`)}}async function O(){if(!g){j(!0);try{const W=await T.post(`/artifacts/${encodeURIComponent(s)}/submit`,{answers:[],submitter:"drb0rk"});W!=null&&W.ok?(i.success("Sent to agent — feedback.md written, status=review"),a==null||a()):i.error("Submit failed: server did not return ok=true")}catch(W){i.error(`Submit failed: ${W.message}`)}finally{j(!1)}}}function J(){z(W=>!W)}const ae=W=>{const se=W.id,ie=W.data??{},me=Ir(W);return me.ok?e.jsx(Mr,{blockId:se,blockType:W.type,onError:A,children:ee(W,se,ie)},se):e.jsxs("div",{id:se,className:"glyph-block-error",role:"alert",style:{border:"1px solid var(--error, #f85149)",background:"rgba(248, 81, 73, 0.06)",borderRadius:8,padding:"12px 14px",margin:"12px 0",color:"var(--text)",fontFamily:"var(--font-mono, ui-monospace, monospace)",fontSize:12,lineHeight:1.55},children:[e.jsxs("strong",{style:{color:"var(--error, #f85149)",fontFamily:"var(--font-sans, system-ui, sans-serif)",display:"block",marginBottom:4},children:[W.type," block invalid"]}),e.jsxs("div",{style:{color:"var(--text-muted)",marginBottom:6},children:["block id: ",e.jsx("code",{children:se})]}),e.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:me.error})]},se)},ee=(W,se,ie)=>{switch(W.type){case"RichText":return e.jsx(xr,{id:se,children:W.childrenMarkdown??""},se);case"Callout":return e.jsx(gr,{id:se,tone:ie.tone??"info",children:W.childrenMarkdown??""},se);case"Checklist":return e.jsx(fr,{id:se,items:ie.items??[]},se);case"Table":return e.jsx(jr,{id:se,columns:ie.columns??[],rows:ie.rows??[]},se);case"CodeTabs":return e.jsx(vr,{id:se,tabs:ie.tabs??[]},se);case"Decision":return e.jsx(yr,{id:se,title:ie.title,question:ie.question,options:ie.options??[]},se);case"OpenQuestions":return e.jsx(br,{id:se,questions:ie.questions??[]},se);case"FileTree":return e.jsx(kr,{id:se,title:ie.title,entries:ie.entries??[]},se);case"Diff":return e.jsx(wr,{id:se,filename:ie.filename,language:ie.language,mode:ie.mode??"unified",before:ie.before??"",after:ie.after??""},se);case"Stat":return e.jsx(Cr,{id:se,label:ie.label??"",value:ie.value,trend:ie.trend,hint:ie.hint},se);case"Workflow":return e.jsx(Tr,{id:se,steps:ie.steps??[],connections:ie.connections},se);case"Mockup":return e.jsx(Ar,{id:se,title:ie.title,x:ie.x,y:ie.y,w:ie.w,h:ie.h,html:ie.html??""},se);case"Diagram":return e.jsx("div",{id:se,className:"glyph-block-placeholder",children:e.jsxs("em",{children:["[Diagram] ",se]})},se)}};if(x)return e.jsx("div",{className:"glyph-renderer glyph-renderer--loading",children:m?e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:"Failed to load glyph."}),e.jsx("pre",{children:m})]}):e.jsxs(e.Fragment,{children:[e.jsx(Pr,{})," Loading glyph…"]})});if(u||!n)return e.jsxs("div",{className:"glyph-renderer glyph-renderer--error",children:[e.jsx("strong",{children:"Failed to load glyph."}),e.jsx("pre",{children:u??"unknown error"})]});const F=((B=n.frontmatter)==null?void 0:B.title)??s,H=((Z=n.frontmatter)==null?void 0:Z.status)??"draft",K=o.length;return e.jsxs("div",{className:`glyph-canvas ${k?"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(rs,{size:14}),e.jsx("span",{children:"Send to agent"}),e.jsx("span",{className:"glyph-btn-badge",children:K})]}),e.jsx("span",{className:"glyph-toolbar-divider"}),e.jsx("button",{className:"glyph-icon-btn",title:"Share",onClick:()=>{typeof window<"u"&&navigator.clipboard&&(navigator.clipboard.writeText(window.location.href).catch(()=>{}),i.success("Link copied"))},children:e.jsx(un,{size:15})}),e.jsx("button",{className:"glyph-icon-btn",title:"Undo",disabled:!0,children:e.jsx(hn,{size:15})}),e.jsx("button",{className:"glyph-icon-btn",title:"Redo",disabled:!0,children:e.jsx(xn,{size:15})}),e.jsx("button",{className:"glyph-icon-btn",title:k?"Exit fullscreen":"Fullscreen",onClick:J,children:e.jsx(pn,{size:15})}),e.jsx("button",{className:"glyph-icon-btn",title:"More",children:e.jsx(gn,{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(Xs,{size:15}),e.jsx("span",{className:"glyph-icon-btn-count",children:K})]}),t&&e.jsx("button",{className:"glyph-icon-btn glyph-icon-btn--close",title:"Close",onClick:t,"aria-label":"Close",children:e.jsx(Ne,{size:15})})]}),e.jsxs("div",{className:"glyph-canvas-content",children:[e.jsxs("header",{className:"glyph-canvas-title",children:[e.jsx("h1",{className:"glyph-title",children:F}),e.jsxs("div",{className:"glyph-meta",children:[e.jsx("span",{className:`glyph-status glyph-status--${H}`,children:H}),e.jsx("span",{className:"glyph-slug",children:s})]})]}),(R.length>0||((he=n.errors)==null?void 0:he.length)>0)&&e.jsxs("div",{className:"glyph-render-errors",role:"alert",style:{border:"1px solid var(--error, #f85149)",background:"rgba(248, 81, 73, 0.08)",borderRadius:8,padding:"12px 16px",margin:"0 0 16px 0",color:"var(--text)"},children:[e.jsx("strong",{style:{color:"var(--error, #f85149)",display:"block",marginBottom:8},children:R.length>0?`${R.length} block${R.length===1?"":"s"} failed to render`:"Compiler warnings"}),e.jsxs("ul",{style:{margin:0,paddingLeft:20,fontFamily:"var(--font-mono, ui-monospace, monospace)",fontSize:12,lineHeight:1.6},children:[R.map((W,se)=>e.jsxs("li",{children:[e.jsx("strong",{children:W.blockType})," (",e.jsx("code",{children:W.blockId}),"): ",W.message]},`be-${se}`)),(we=n.errors)==null?void 0:we.map((W,se)=>e.jsxs("li",{children:[W.line?`line ${W.line}: `:"",W.message]},`ce-${se}`))]})]}),e.jsx("div",{className:"glyph-sections",children:C.map((W,se)=>e.jsxs("section",{className:`glyph-section ${W.heading?"glyph-section--headed":"glyph-section--plain"}`,children:[W.heading&&e.jsx("h2",{className:"glyph-section-heading",children:W.heading}),e.jsx("div",{className:"glyph-section-blocks",children:W.blocks.map(ae)})]},`sec-${se}-${W.heading??"ungrouped"}`))})]}),o.map(W=>e.jsxs("button",{className:`glyph-pin ${f===W.id?"glyph-pin--active":""}`,style:{left:W.x,top:W.y},onClick:se=>{se.stopPropagation(),L(f===W.id?null:W.id)},title:W.text,children:[e.jsx(Ft,{size:14}),f===W.id&&e.jsxs("div",{className:"glyph-pin-thread",children:[e.jsx("div",{className:"glyph-pin-text",children:W.text}),e.jsxs("div",{className:"glyph-pin-meta",children:[W.author??"anonymous"," · ",W.created?new Date(W.created).toLocaleString():""]})]})]},W.id)),N&&e.jsx("div",{className:"glyph-ctx-menu",style:{left:N.x,top:N.y},onClick:W=>W.stopPropagation(),children:e.jsxs("button",{className:"glyph-ctx-item",onClick:()=>{v({worldX:N.worldX,worldY:N.worldY}),S(null)},children:[e.jsx(Ft,{size:14})," Add comment here"]})}),E&&e.jsx("div",{className:"glyph-modal-overlay",onClick:()=>v(null),children:e.jsxs("div",{className:"glyph-modal",onClick:W=>W.stopPropagation(),children:[e.jsxs("h3",{children:["Add comment at (",Math.round(E.worldX),", ",Math.round(E.worldY),")"]}),e.jsx("textarea",{autoFocus:!0,value:b,onChange:W=>w(W.target.value),placeholder:"What should the agent know about this area?",rows:4,className:"glyph-modal-textarea"}),e.jsxs("div",{className:"glyph-modal-actions",children:[e.jsx("button",{className:"glyph-btn glyph-btn--ghost",onClick:()=>v(null),children:"Cancel"}),e.jsx("button",{className:"glyph-btn glyph-btn--primary",onClick:Y,disabled:!b.trim(),children:"Add comment"})]})]})})]})}function Pr(){return e.jsx("span",{className:"glyph-spinner","aria-label":"loading",children:"…"})}function Fr(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 Or({snapshot:s,refreshSnapshot:t}){const a=re(),[i,n]=r.useState(s.artifacts||[]),[c,o]=r.useState(!s.artifacts),[l,x]=r.useState(null),[p,u]=r.useState(""),[d,m]=r.useState(!1);r.useEffect(()=>{s.artifacts&&(n(s.artifacts),o(!1))},[s.artifacts]);const h=async()=>{try{const z=await T.get("/artifacts");n(z.artifacts||[]),o(!1)}catch(z){a.error(`Artifacts load failed: ${z.message}`),o(!1)}},g=r.useMemo(()=>{let z=i;if(p){const N=p.toLowerCase();z=z.filter(S=>(S.slug||"").toLowerCase().includes(N)||(S.title||"").toLowerCase().includes(N))}return d||(z=z.filter(N=>N.status!=="archived")),z},[i,p,d]),j=async(z,N)=>{try{const S=await T.post("/artifacts",{slug:z,title:N});a.success(`Artifact "${S.slug}" created.`),x(S.slug),await h()}catch(S){a.error(`Create failed: ${S.message}`)}},k=async z=>{if(confirm(`Delete artifact "${z}"? This removes the directory permanently.`))try{await T.del(`/artifacts/${encodeURIComponent(z)}`),a.success("Artifact deleted."),l===z&&x(null),await h()}catch(N){a.error(`Delete failed: ${N.message}`)}};return l?e.jsxs("div",{className:"artifact-glyph-overlay",children:[e.jsx("div",{className:"artifact-glyph-toolbar",children:e.jsxs($,{variant:"ghost",onClick:()=>{x(null),h()},children:[e.jsx(bt,{size:14})," Back to artifacts"]})}),e.jsx(Dr,{slug:l,onClose:()=>{x(null),h()},onCommentAdded:()=>h()})]}):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(Hs,{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:z=>u(z.target.value),"aria-label":"Search artifacts"})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>m(z=>!z),title:d?"Hide archived":"Show archived",children:[d?e.jsx(da,{size:14}):e.jsx(la,{size:14}),d?"Hide archived":"Show archived"]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:h,children:[e.jsx(de,{size:14})," Refresh"]})]})]}),e.jsx(Br,{onCreate:j}),c?e.jsx("div",{className:"view-loading",children:e.jsx(oe,{size:"lg"})}):g.length===0?e.jsx(pe,{icon:e.jsx(Hs,{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(z=>e.jsx(Ur,{artifact:z,onOpen:()=>x(z.slug),onDelete:()=>k(z.slug)},z.slug))})]})}function Br({onCreate:s}){const[t,a]=r.useState(""),[i,n]=r.useState("");return e.jsxs(G,{className:"new-artifact",children:[e.jsxs(te,{children:[e.jsx(ze,{size:14})," New artifact"]}),e.jsx(ne,{children:"Slug must be lowercase, may contain hyphens, 1–64 chars."}),e.jsxs("form",{className:"new-artifact-form",onSubmit:c=>{c.preventDefault(),t.trim()&&(s(t.trim(),i.trim()||void 0),a(""),n(""))},children:[e.jsx("label",{htmlFor:"new-artifact-slug",className:"sr-only",children:"Artifact slug"}),e.jsx("input",{id:"new-artifact-slug",className:"input",type:"text",placeholder:"slug (e.g. dashboard-v3.1)",pattern:"[a-z0-9][a-z0-9-]{0,63}",required:!0,value:t,onChange:c=>a(c.target.value),"aria-label":"Artifact slug"}),e.jsx("label",{htmlFor:"new-artifact-title",className:"sr-only",children:"Artifact title"}),e.jsx("input",{id:"new-artifact-title",className:"input",type:"text",placeholder:"Title (optional)",value:i,onChange:c=>n(c.target.value)}),e.jsx($,{variant:"primary",type:"submit",children:"Create"})]})]})}function Ur({artifact:s,onOpen:t,onDelete:a}){const i=Fr(s.status||"draft");return e.jsxs(G,{variant:"elevated",interactive:!0,className:"artifact-card",onClick:t,children:[e.jsxs("div",{className:"artifact-card-head",children:[e.jsx("div",{className:"artifact-card-title",children:s.title||s.slug}),e.jsx(Je,{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 ",Ce(s.mtime)]})]}),e.jsxs("div",{className:"artifact-card-actions",children:[e.jsxs($,{variant:"primary",size:"sm",onClick:n=>{n.stopPropagation(),t()},children:["Open",e.jsx(Xe,{size:12})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:n=>{n.stopPropagation(),a()},children:[e.jsx(ke,{size:12})," Delete"]})]})]})}function _r({children:s,className:t,onRemove:a}){return e.jsxs("span",{className:V("tag",t),children:[s,a&&e.jsx("button",{type:"button",className:"tag-remove","aria-label":`Remove ${typeof s=="string"?s:"tag"}`,onClick:a,children:"×"})]})}function Wr({task:s,agents:t,onPromote:a,onDelete:i,onEdit:n,onRefresh:c}){var u;const o=re(),l=async()=>{try{await T.post(`/tasks/${encodeURIComponent(s.id)}/promote`),o.success("Promoted to queued.",1500),a(s.id)}catch(d){o.error(`Promote failed: ${d.message}`)}},x=async()=>{if(confirm("Delete this task?"))try{await T.del(`/tasks/${encodeURIComponent(s.id)}`),o.success("Deleted.",1500),i(s.id)}catch(d){o.error(`Delete failed: ${d.message}`)}},p={high:"var(--warning)",normal:"var(--info)",low:"var(--muted)"};return e.jsxs("div",{className:"backlog-item","data-task-id":s.id,children:[e.jsxs("div",{className:"backlog-item-head",children:[e.jsx("span",{className:"priority-dot",style:{background:p[s.priority]||"var(--info)"}}),e.jsx("span",{className:"backlog-item-title",children:s.title}),s.assignee&&e.jsxs("span",{className:"backlog-item-badge",children:["@",s.assignee]}),((u=s.tags)==null?void 0:u.length)>0&&e.jsx("span",{className:"backlog-item-badge",children:s.tags.join(", ")})]}),s.description&&e.jsx("div",{className:"backlog-item-desc",children:s.description.slice(0,120)}),e.jsxs("div",{className:"backlog-item-footer",children:[e.jsx("span",{className:"muted text-sm tabular-nums",children:Ce(s.createdAt)}),e.jsxs("div",{className:"backlog-item-actions",children:[e.jsx("button",{type:"button",className:"icon-btn",title:"Promote to queued",onClick:l,children:e.jsx(zt,{size:13})}),e.jsx("button",{type:"button",className:"icon-btn",title:"Edit",onClick:()=>n(s),children:e.jsx(He,{size:13})}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger",title:"Delete",onClick:x,children:e.jsx(ke,{size:13})})]})]})]})}function qr({agents:s,onRefresh:t}){const a=re(),[i,n]=r.useState([]),[c,o]=r.useState(!1),l=async()=>{try{o(!0);const m=await T.get("/tasks/backlog");n(Array.isArray(m.tasks)?m.tasks:[])}catch(m){a.error(`Backlog load failed: ${m.message}`)}finally{o(!1)}};r.useEffect(()=>{l()},[]);const x=async m=>{n(h=>h.filter(g=>g.id!==m)),await t()},p=async m=>{n(h=>h.filter(g=>g.id!==m)),await t()},u=m=>{},d=async()=>{var m;if(i.length!==0)try{const g=((m=(await T.post("/tasks/promote-batch",{ids:i.map(j=>j.id)})).affected)==null?void 0:m.filter(j=>j.ok).length)??0;a.success(`Promoted ${g} task(s).`,2e3),n([]),await t()}catch(h){a.error(`Promote all failed: ${h.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(Gs,{size:15}),"Backlog (",i.length,")"]}),e.jsxs("div",{className:"backlog-panel-header-actions",children:[i.length>0&&e.jsxs($,{variant:"ghost",size:"sm",onClick:d,title:"Promote all to queued",children:[e.jsx(zt,{size:12})," Promote all"]}),e.jsx($,{variant:"ghost",size:"sm",onClick:l,title:"Refresh backlog","aria-label":"Refresh backlog",children:e.jsx(de,{size:12,className:c?"animate-spin":""})})]})]}),c?e.jsx("div",{className:"backlog-empty",children:"Loading…"}):i.length===0?e.jsxs("div",{className:"backlog-empty",children:[e.jsx(Gs,{size:28}),e.jsx("span",{children:"Backlog is empty."})]}):e.jsx("div",{className:"backlog-list",children:i.map(m=>e.jsx(Wr,{task:m,agents:s,onPromote:x,onDelete:p,onEdit:u,onRefresh:t},m.id))})]})}const qs=[{id:"queued",label:"Todo",kind:"info"},{id:"doing",label:"In progress",kind:"accent"},{id:"done",label:"Done",kind:"success"},{id:"blocked",label:"Failed",kind:"error"}],It=["low","normal","high"];function Vr({snapshot:s,refreshSnapshot:t,setActiveTab:a}){const i=re(),n=$e(),[c,o]=r.useState(s.tasks||[]),[l,x]=r.useState(!s.tasks),[p,u]=r.useState(""),[d,m]=r.useState(""),[h,g]=r.useState(!1),[j,k]=r.useState(0),[z,N]=r.useState(""),S=async()=>{try{const y=await T.get("/tasks");o(Array.isArray(y)?y:[])}catch(y){i.error(`Tasks load failed: ${y.message}`)}finally{x(!1)}};r.useEffect(()=>{s.tasks&&(o(s.tasks),x(!1))},[s.tasks]),r.useEffect(()=>{const y=setInterval(()=>k(A=>A+1),3e4);return()=>clearInterval(y)},[]);const E=r.useMemo(()=>{let y=c.filter(A=>A.status!=="backlog");if(d&&(y=y.filter(A=>(A.priority||"normal")===d)),p.trim()){const A=p.toLowerCase();y=y.filter(P=>(P.title||"").toLowerCase().includes(A)||(P.description||"").toLowerCase().includes(A))}return y},[c,p,d]),v=r.useMemo(()=>{const y={high:0,normal:1,low:2};return[...E].sort((A,P)=>{const C=y[A.priority]??1,D=y[P.priority]??1;return C!==D?C-D:new Date(P.createdAt).getTime()-new Date(A.createdAt).getTime()})},[E]),b=c.filter(y=>y.status==="backlog").length,w=async(y,A)=>{const P=c.find(D=>D.id===y);if(!P)return;const C=P.status;o(D=>D.map(Y=>Y.id===y?{...Y,status:A}:Y)),N(`Task ${P.title} moved to ${A}.`);try{await T.patch(`/tasks/${encodeURIComponent(y)}/status`,{status:A}),i.success(`Moved to ${A}.`,1200)}catch(D){o(Y=>Y.map(O=>O.id===y?{...O,status:C}:O)),N(`Failed to move task ${P.title}: ${D.message}`),i.error(`Move failed: ${D.message}`)}},f=async y=>{if(confirm("Delete this task?"))try{await T.del(`/tasks/${encodeURIComponent(y)}`),o(A=>A.filter(P=>P.id!==y)),i.success("Task deleted.",1200)}catch(A){i.error(`Delete failed: ${A.message}`)}},L=async y=>{try{const A=await T.post(`/tasks/${encodeURIComponent(y)}/start`);A&&A.task&&o(P=>P.map(C=>C.id===y?A.task:C)),i.success("Retry dispatched.",1200)}catch(A){i.error(`Retry failed: ${A.message}`)}},R=async y=>{const A=c.find(P=>P.id===y);if(A)try{const P=await T.post("/tasks/submit",{title:A.title,description:A.description,priority:A.priority,tags:A.tags}),C=(P.subtasks||[]).length;i.success(C>1?`Odin split it into ${C} subtasks.`:"Sent to Odin.",1500),P.subtasks&&P.subtasks.length>0&&o(D=>[P.main,...P.subtasks,...D.filter(Y=>Y.id!==A.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:z}),e.jsx("header",{className:"view-header",children:e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(Rs,{size:18})," Tasks (",v.length,")"]}),e.jsx("p",{className:"view-subtitle",children:"Add a task — title and description is all you need. Odin picks the agent and priority."})]})}),e.jsxs("div",{className:"tasks-toolbar",children:[e.jsx("div",{className:"tasks-toolbar-group",children:e.jsxs("div",{className:"search-input",style:{width:200},children:[e.jsx(ye,{size:12,"aria-hidden":!0}),e.jsx("input",{className:"input",type:"text",placeholder:"Search…",value:p,onChange:y=>u(y.target.value),"aria-label":"Search tasks"}),p&&e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Clear search",onClick:()=>u(""),children:e.jsx(Ne,{size:12})})]})}),e.jsx("div",{className:"tasks-toolbar-divider"}),e.jsxs("div",{className:"tasks-toolbar-group",children:[e.jsx("label",{className:"tasks-toolbar-label",htmlFor:"tasks-priority-filter",children:"Priority"}),e.jsxs("select",{id:"tasks-priority-filter",className:"select select-sm",value:d,onChange:y=>m(y.target.value),title:"Filter by priority",children:[e.jsx("option",{value:"",children:"All"}),It.map(y=>e.jsx("option",{value:y,children:y},y))]})]}),e.jsx("div",{className:"tasks-toolbar-spacer"}),e.jsxs("div",{className:"tasks-toolbar-group",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:S,title:"Refresh","aria-label":"Refresh tasks",children:e.jsx(de,{size:14})}),b>0&&e.jsxs($,{variant:h?"accent":"ghost",size:"sm",onClick:()=>g(y=>!y),title:h?"Hide backlog":"Show backlog",children:[e.jsx(Gs,{size:14}),"Backlog",e.jsx("span",{className:"badge",children:b})]}),e.jsxs($,{variant:"primary",size:"sm",onClick:()=>Kr(n,i,o,S,t),children:[e.jsx(ze,{size:14})," New task"]})]})]}),h&&b>0&&e.jsx(qr,{agents:s.agents||[],onRefresh:t}),l?e.jsx("div",{className:"view-loading",children:e.jsx(oe,{size:"lg"})}):e.jsx("div",{className:"kanban",children:qs.map(y=>e.jsx(Hr,{column:y,tasks:v.filter(A=>A.status===y.id),onMove:w,onDelete:f,onRetry:L,onEdit:A=>Yr(n,i,A,o,S,t),onSubmitToOdin:R,tick:j},y.id))})]})}function Hr({column:s,tasks:t,onMove:a,onDelete:i,onRetry:n,onEdit:c,onSubmitToOdin:o,tick:l}){const[x,p]=r.useState(!1);return e.jsxs("div",{className:V("kanban-column",x&&"kanban-column-drop"),"data-column":s.id,onDragOver:u=>{u.preventDefault(),p(!0)},onDragLeave:()=>p(!1),onDrop:u=>{u.preventDefault(),p(!1);const d=u.dataTransfer.getData("text/task-id");d&&a(d,s.id)},children:[e.jsxs("div",{className:"kanban-col-header",children:[e.jsxs(te,{children:[e.jsx("span",{className:V("status-dot",`status-${s.kind}`)}),s.label]}),e.jsx("span",{className:"kanban-col-count tabular-nums",children:t.length})]}),e.jsx("div",{className:"kanban-col-body",children:t.length===0?e.jsx("div",{className:"kanban-empty",children:"No tasks"}):t.map(u=>e.jsx(Gr,{task:u,onMove:d=>{const h=qs.findIndex(g=>g.id===u.status)+d;h>=0&&h<qs.length&&a(u.id,qs[h].id)},onEdit:()=>c(u),onDelete:()=>i(u.id),onRetry:()=>n(u.id),onSubmitToOdin:()=>o(u.id),tick:l},u.id))})]})}function Gr({task:s,onMove:t,onEdit:a,onDelete:i,onRetry:n,onSubmitToOdin:c,tick:o}){const l=s.workedBy||s.assignee||null;return e.jsxs("div",{className:V("task-card",`priority-${s.priority}`),"data-task-id":s.id,draggable:!0,onDragStart:x=>{x.dataTransfer.setData("text/task-id",s.id),x.dataTransfer.effectAllowed="move"},"data-tick":o,children:[e.jsxs("div",{className:"task-card-head",children:[e.jsx("span",{className:"priority-dot",style:{background:Wa[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(Ye,{size:10})," @",l]}),s.timeSpent?e.jsxs("span",{className:"task-card-badge",children:[e.jsx(as,{size:10})," ",Math.round((s.timeSpent||0)/60),"m"]}):null,s.tags&&s.tags.length>0&&s.tags.slice(0,3).map(x=>e.jsx(_r,{children:x},x))]}),e.jsxs("div",{className:"task-card-footer",children:[e.jsx("span",{className:"task-card-time tabular-nums muted",children:Ce(s.createdAt)}),e.jsxs("div",{className:"task-card-actions",onClick:x=>x.stopPropagation(),children:[e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Move left",title:"Move left",onClick:()=>t(-1),children:e.jsx(fn,{size:14})}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Edit",title:"Edit",onClick:a,children:e.jsx(jn,{size:14})}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Submit to Odin",title:"Re-delegate to Odin",onClick:c,children:e.jsx(rs,{size:14})}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Retry",title:"Retry",onClick:n,children:e.jsx(Js,{size:14})}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger","aria-label":"Delete",title:"Delete",onClick:i,children:e.jsx(ke,{size:14})}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Move right",title:"Move right",onClick:()=>t(1),children:e.jsx(Xe,{size:14})})]})]})]})}function Kr(s,t,a,i,n){let c=null,o=null,l=null,x=null;const p=async d=>{d&&typeof d.preventDefault=="function"&&d.preventDefault();const m=((c==null?void 0:c.value)||"").trim(),h=((o==null?void 0:o.value)||"").trim();if(!m){t.warning("Title is required."),c==null||c.focus();return}const g=(x==null?void 0:x.value)||"normal",j=((l==null?void 0:l.value)||"").split(",").map(k=>k.trim()).filter(Boolean);try{const k=await T.post("/tasks",{title:m,description:h,priority:g,tags:j});s.close(),typeof window<"u"&&window.dispatchEvent(new MouseEvent("mousedown")),a(z=>[k,...z]),t.success("Task created.",1200),await n()}catch(k){t.error(`Create failed: ${k.message}`)}},u=d=>{d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),p(d))};s.open({title:"New task",width:520,children:e.jsxs("div",{className:"task-form",children:[e.jsx("label",{className:"field-label",htmlFor:"task-title",children:"Title *"}),e.jsx("input",{ref:d=>{c=d},id:"task-title",className:"input",type:"text",maxLength:200,placeholder:"What needs to be done?",autoFocus:!0,onKeyDown:u}),e.jsx("label",{className:"field-label",htmlFor:"task-desc",children:"Description"}),e.jsxs("div",{style:{display:"flex",gap:6,alignItems:"flex-start"},children:[e.jsx("textarea",{ref:d=>{o=d},id:"task-desc",className:"textarea",rows:4,placeholder:"Add any context Odin might need (markdown ok)…",style:{flex:1}}),e.jsx("button",{type:"button",className:"btn btn-ghost btn-icon",title:"Enhance with AI",onClick:async()=>{var m;if(!((m=o==null?void 0:o.value)!=null&&m.trim()))return;const d=await _a(o.value);d!==o.value&&(o.value=d)},children:"✨"})]}),e.jsxs("div",{className:"task-form-row",children:[e.jsxs("label",{htmlFor:"task-priority",className:"task-form-field",children:["Priority hint",e.jsx("select",{ref:d=>{x=d},id:"task-priority",className:"select",defaultValue:"normal",children:It.map(d=>e.jsx("option",{value:d,children:d},d))})]}),e.jsxs("label",{htmlFor:"task-tags",className:"task-form-field",style:{flex:2},children:["Tags ",e.jsx("span",{className:"field-hint",children:"(comma-separated)"}),e.jsx("input",{ref:d=>{l=d},id:"task-tags",className:"input",type:"text",placeholder:"bug, frontend, urgent"})]})]}),e.jsx("p",{className:"muted text-sm",style:{marginTop:8},children:"The agent and final priority are decided by Odin after you submit."})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx($,{variant:"ghost",onClick:()=>s.close(),children:"Cancel"}),e.jsxs($,{variant:"primary",type:"button",onClick:d=>p(d),children:[e.jsx(ze,{size:14})," Create task"]})]})})}function Yr(s,t,a,i,n,c){let o=null,l=null,x=null,p=null;const u=async()=>{const d=((o==null?void 0:o.value)||"").trim(),m=((l==null?void 0:l.value)||"").trim();if(!d){t.warning("Title is required."),o==null||o.focus();return}const h=(p==null?void 0:p.value)||"normal",g=((x==null?void 0:x.value)||"").split(",").map(j=>j.trim()).filter(Boolean);try{const j=await T.put(`/tasks/${encodeURIComponent(a.id)}`,{title:d,description:m,priority:h,tags:g});s.close(),typeof window<"u"&&window.dispatchEvent(new MouseEvent("mousedown")),i(k=>k.map(z=>z.id===a.id?j:z)),t.success("Task updated.",1200),await c()}catch(j){t.error(`Save failed: ${j.message}`)}};s.open({title:"Edit task",width:520,children:e.jsxs("div",{className:"task-form",children:[e.jsx("label",{className:"field-label",htmlFor:"edit-task-title",children:"Title *"}),e.jsx("input",{ref:d=>{o=d},id:"edit-task-title",className:"input",type:"text",maxLength:200,defaultValue:a.title,autoFocus:!0}),e.jsx("label",{className:"field-label",htmlFor:"edit-task-desc",children:"Description"}),e.jsx("textarea",{ref:d=>{l=d},id:"edit-task-desc",className:"textarea",rows:4,defaultValue:a.description||""}),e.jsxs("div",{className:"task-form-row",children:[e.jsxs("label",{htmlFor:"edit-task-priority",className:"task-form-field",children:["Priority hint",e.jsx("select",{ref:d=>{p=d},id:"edit-task-priority",className:"select",defaultValue:a.priority||"normal",children:It.map(d=>e.jsx("option",{value:d,children:d},d))})]}),e.jsxs("label",{htmlFor:"edit-task-tags",className:"task-form-field",style:{flex:2},children:["Tags",e.jsx("input",{ref:d=>{x=d},id:"edit-task-tags",className:"input",type:"text",defaultValue:(a.tags||[]).join(", "),placeholder:"comma-separated"})]})]}),e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsx(ca,{size:12})," Status"]}),e.jsxs(ne,{children:["Current: ",e.jsx("strong",{children:a.status}),a.workedBy&&e.jsxs(e.Fragment,{children:[" · Worked by @",a.workedBy]}),a.assignee&&!a.workedBy&&e.jsxs(e.Fragment,{children:[" · Assigned @",a.assignee]})]})]})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx($,{variant:"ghost",onClick:()=>s.close(),children:"Cancel"}),e.jsxs($,{variant:"primary",onClick:u,children:[e.jsx(da,{size:14})," Save"]})]})})}const Xr=Oe.memo(Vr);function Jr(s){return T.urlWithToken(`/artifacts/${encodeURIComponent(s)}/content`)}function Qr(s,t){const a=Jr(t);window.open(a,"_blank","noopener,noreferrer")}const qt={"1m":60*1e3,"5m":5*60*1e3,"30m":30*60*1e3,"1h":60*60*1e3},Me=56,Ve=32,us=22,Zr=4,el=.9,nt={working:"var(--success)",running:"var(--success)",doing:"var(--info)",queued:"var(--info)",done:"var(--success)",success:"var(--success)",blocked:"var(--warning)",error:"var(--error)",failed:"var(--error)",stuck:"var(--warning)",killed:"var(--error)",idle:"var(--text-dim)",pending:"var(--info)",timed_out:"var(--warning)"};function it(s){return s&&nt[s]||nt.idle}function Os(s,t=24){return s?s.length<=t?s:s.slice(0,t-1)+"…":""}function Ys(s){if(s==null)return 0;if(typeof s=="number")return s;const t=new Date(s).getTime();return Number.isNaN(t)?0:t}function rt(s){const t=s._timerStart;return typeof t=="number"&&t>0?t:Ys(s.createdAt)||Date.now()}function sl(s,t){return(s.status==="done"||s.status==="archived"||s.status==="failed"||s.status==="killed")&&(Ys(s.completedAt)||Ys(s.updatedAt))||t}function tl(s){return typeof s.startedAt=="number"&&s.startedAt>0?s.startedAt:Date.now()}function al(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 nl(s){return s<=6e4?1e4:s<=3e5?3e4:s<=18e5?3e5:6e5}function il(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 rl({snapshot:s,refreshSnapshot:t}){const a=re(),i=r.useRef(null),[n,c]=r.useState("live"),[o,l]=r.useState("5m"),[x,p]=r.useState(()=>typeof window>"u"?!0:window.innerWidth>900),[u,d]=r.useState([]),[m,h]=r.useState([]),[g,j]=r.useState(!0),[k,z]=r.useState(0),[N,S]=r.useState(Date.now()),[E,v]=r.useState(()=>Date.now()-qt["5m"]*.1),[b,w]=r.useState({width:800,height:400}),[f,L]=r.useState(null),[R,y]=r.useState(""),[A,P]=r.useState([]),[C,D]=r.useState(""),[Y,O]=r.useState("normal"),[J,ae]=r.useState(""),[ee,F]=r.useState(""),[H,K]=r.useState(!1),[B,Z]=r.useState(!1),[he,we]=r.useState([]),W=$e(),se=s.agents||[],ie=s.tasks||[],me=qt[o],_=E,I=E+me,Q=r.useCallback(async()=>{try{const[M,X]=await Promise.all([T.get("/background").catch(()=>({instances:[]})),T.get("/activity?limit=200").catch(()=>({events:[]}))]);d(M.instances||[]),h(X.events||[])}catch(M){console.warn("activity reload failed:",M)}finally{j(!1)}},[]);r.useEffect(()=>{Q();const M=setInterval(Q,3e3);return()=>clearInterval(M)},[Q]),r.useEffect(()=>{z(M=>M+1)},[ie.length,se.length]),r.useEffect(()=>{if(n==="pause")return;S(Date.now());const M=setInterval(()=>S(Date.now()),1e3);return()=>clearInterval(M)},[n,k]),r.useEffect(()=>{if(n==="pause")return;(N-E)/me>el&&v(N-me*.1)},[N,E,me,n]),r.useEffect(()=>{v(Date.now()-me*.1)},[o]),r.useEffect(()=>{n==="live"&&v(Date.now()-me*.1)},[n]),r.useLayoutEffect(()=>{const M=i.current;if(!M)return;const X=new ResizeObserver(ge=>{for(const fe of ge){const{width:ue,height:je}=fe.contentRect;w({width:Math.max(200,Math.floor(ue)),height:Math.max(120,Math.floor(je))})}});return X.observe(M),()=>X.disconnect()},[]);const U=r.useMemo(()=>{const M=[];let X=0;for(const ue of u){const je=tl(ue),Ee=al(ue,N);Ee<_||je>I||M.push({kind:"bg",id:`bg:${ue.instanceId}`,index:X++,label:`BG ${Os(ue.promptPreview,20)||ue.instanceId.slice(0,10)}`,sub:ue.status||"pending",start:je,end:Ee,data:ue})}const ge=[...ie].sort((ue,je)=>rt(ue)-rt(je)),fe=[];for(const ue of ge){const je=rt(ue),Ee=sl(ue,N);if(Ee<_||je>I)continue;let cs=-1;for(let Ze=0;Ze<fe.length;Ze++)if(fe[Ze]<=je){fe[Ze]=Ee,cs=Ze;break}cs===-1&&(fe.push(Ee),cs=fe.length-1),M.push({kind:"task",id:`task:${ue.id}`,index:X+cs,label:Os(ue.title,32),sub:ue.status,start:je,end:Ee,data:ue})}return M},[u,ie,N,_,I]),le=r.useMemo(()=>{const M=new Map;for(const X of U)M.set(X.id,X);return M},[U]),q=r.useCallback(M=>me<=0?0:(M-_)/me*b.width,[_,me,b.width]),ce=r.useMemo(()=>{const M=nl(me),X=[],ge=Math.floor(_/M)*M;for(let fe=ge;fe<=I+M;fe+=M){if(fe<_-M)continue;if(fe>I)break;const ue=q(fe);ue<-40||ue>b.width+40||X.push({t:fe,x:ue,label:il(fe,me)})}return X},[_,I,me,b.width,q]),Re=r.useMemo(()=>{const M=[];for(const X of U){if(X.kind==="events")continue;const ge=Math.max(X.start,_),fe=Math.min(X.end,I);if(fe<_||ge>I)continue;const ue=q(ge),je=q(fe),Ee=Math.max(Zr,je-ue),cs=Ve+us+X.index*Me+8,Ze=Me-16;let Ue="doing";if(X.kind==="bg"){const Se=X.data.status||"pending";Se==="done"||Se==="success"?Ue="done":Se==="failed"||Se==="killed"||Se==="error"?Ue="failed":Se==="queued"||Se==="pending"?Ue="queued":Se==="blocked"||Se==="stuck"?Ue="blocked":Ue="doing"}else{const Se=X.data.status;Se==="done"||Se==="archived"?Ue="done":Se==="failed"||Se==="killed"?Ue="failed":Se==="queued"?Ue="queued":Se==="blocked"?Ue="blocked":Ue="doing"}const Oa=(f==null?void 0:f.id)===X.id;M.push({id:X.id,laneIndex:X.index,x:ue,y:cs,w:Ee,h:Ze,label:X.label,statusClass:Ue,selected:Oa,data:X.data,kind:X.kind,start:X.start,end:X.end})}return M},[U,q,f,_,I]),Ie=r.useMemo(()=>{const M=[];for(const X of m){const ge=Ys(X.ts);if(ge<_-5e3||ge>I+5e3)continue;const fe=q(ge);let ue=Ve+12;if(X.taskId){const je=le.get(`task:${X.taskId}`);je&&(ue=Ve+us+je.index*Me+Me/2)}else if(X.nodeId){const je=String(X.nodeId),Ee=le.get(je.startsWith("task:")||je.startsWith("bg:")?je:`task:${je}`);Ee&&(ue=Ve+us+Ee.index*Me+Me/2)}M.push({id:`${X.ts}-${X.kind}-${X.author??""}-${X.taskId??""}`,x:fe,y:ue,kind:X.kind||"event",ts:ge,text:String(X.text||X.kind||""),author:X.author})}return M},[m,_,I,q,le]),Be=r.useMemo(()=>U.map(M=>({id:M.id,y:Ve+us+M.index*Me,h:Me})),[U]),Ge=r.useMemo(()=>{const M=q(N);return Math.max(0,Math.min(b.width,M))},[q,N,b.width]),Ds=r.useCallback(M=>{const ge={id:M.id,kind:M.kind,label:M.label,status:M.statusClass,data:M.data};L(ge)},[]);r.useEffect(()=>{if(!f){P([]),F(""),we([]);return}y(""),D(""),ae(""),we([]),(async()=>{try{const M=await T.get(`/activity?nodeId=${encodeURIComponent(f.id)}&limit=50`);P(M.events||[])}catch{P([])}if(f.kind==="bg"){const M=f.data;try{const X=await T.get(`/background/${encodeURIComponent(M.instanceId)}/output?lines=80`);F(X.output||"")}catch{F("")}if(M.taskId)try{const X=await T.get(`/tasks/${encodeURIComponent(M.taskId)}/artifacts`);we((X.artifacts||[]).map(ge=>ge.id))}catch{we([])}}})()},[f]);const bs=async()=>{if(!(!f||!R.trim())){Z(!0);try{await T.post("/comments",{nodeId:f.id,text:R,author:"user"}),y("");const M=await T.get(`/activity?nodeId=${encodeURIComponent(f.id)}&limit=50`);P(M.events||[]),a.success("Comment added.")}catch(M){a.error(`Comment failed: ${M.message}`)}finally{Z(!1)}}},Ps=async()=>{if(!(!f||!C.trim())){K(!0);try{await T.post(`/nodes/${encodeURIComponent(f.id)}/tasks`,{title:C,description:`Created from timeline selection ${f.id}.`,priority:Y}),D(""),a.success("Task created."),await t()}catch(M){a.error(`Task create failed: ${M.message}`)}finally{K(!1)}}},Ns=async()=>{if(!f||f.kind!=="bg"||!J.trim())return;const M=f.data;try{const X=await T.post(`/background/${encodeURIComponent(M.instanceId)}/message`,{message:J});X.ok?(a.success("Message sent."),ae("")):a.warning(X.error||"Send failed")}catch(X){a.error(`Send failed: ${X.message}`)}},Da=async()=>{if(!f||f.kind!=="bg"||!confirm("Kill this bg instance session?"))return;const M=f.data;try{const X=await T.del(`/background/${encodeURIComponent(M.instanceId)}`);X.ok?a.success("Session killed."):a.warning(X.error||"Kill failed"),await Q()}catch(X){a.error(`Kill failed: ${X.message}`)}},Pa=async()=>{if(!f||f.kind!=="bg")return;const M=f.data;try{const X=await T.get(`/background/${encodeURIComponent(M.instanceId)}/output?lines=80`);F(X.output||"")}catch{}};r.useEffect(()=>{const M=X=>{X.key==="Escape"&&L(null)};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[]);const Fa=()=>{z(M=>M+1),Q()},Zs=Ve+us+U.length*Me;return e.jsxs("div",{className:"view view-activity",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(De,{size:18})," Activity"]}),e.jsx("p",{className:"view-subtitle",children:"Live timeline of agents, tasks, and background sessions. Active tasks pulse; the red line marks “now”."})]}),e.jsx("div",{className:"view-actions",children:e.jsxs("div",{className:"tl-mode-toggle",children:[e.jsxs($,{variant:n==="live"?"primary":"secondary",size:"sm",onClick:()=>c(n==="live"?"pause":"live"),title:n==="live"?"Pause timeline":"Resume timeline",children:[n==="live"?e.jsx(ma,{size:14}):e.jsx(Ls,{size:14}),n==="live"?"Live":"Paused"]}),e.jsx("div",{className:"tl-zoom-group",children:["1m","5m","30m","1h"].map(M=>e.jsx("button",{type:"button",className:V("tl-zoom-btn",o===M&&"tl-zoom-btn-active"),onClick:()=>l(M),title:`Zoom to ${M}`,children:M},M))}),e.jsxs($,{variant:"secondary",size:"sm",onClick:Fa,title:"Refresh",children:[e.jsx(de,{size:14})," Refresh"]})]})})]}),g&&e.jsx("div",{className:"view-loading",children:e.jsx(oe,{size:"lg"})}),!g&&se.length===0&&ie.length===0&&u.length===0&&m.length===0?e.jsx(pe,{icon:e.jsx(De,{size:32}),title:"No activity yet",message:"Once agents, tasks, or background instances exist, they'll show up here on the timeline."}):e.jsx("div",{className:V("tl-view",f&&"tl-view-detail-open"),children:e.jsxs("div",{className:V("tl-body",!x&&"tl-body-stream-collapsed"),children:[e.jsxs("aside",{className:V("tl-stream",!x&&"tl-stream-collapsed"),children:[e.jsxs("div",{className:"tl-stream-head",children:[e.jsxs("h3",{children:[e.jsx($s,{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(vn,{size:14})})]}),e.jsx("div",{className:"tl-stream-list",children:m.length===0?e.jsx("div",{className:"tl-stream-empty",children:e.jsx("p",{children:"No events yet."})}):e.jsx(Mt,{items:[...m].reverse(),itemHeight:40,height:400,className:"tl-stream-virtual",renderItem:M=>{const X=M.author?Ye:M.kind==="task"?Rs:M.kind==="bg"?_s:De;return e.jsxs("div",{className:"tl-stream-event",children:[e.jsx("span",{className:"tl-stream-event-time",children:new Date(M.ts).toLocaleTimeString("en-GB",{hour12:!1})}),e.jsx("span",{className:"tl-stream-event-icon",style:{color:it(M.kind)},children:e.jsx(X,{size:12})}),e.jsx("span",{className:"tl-stream-event-text",children:M.author||M.text||M.kind})]})}})})]}),e.jsxs("div",{className:"tl-canvas-wrap",ref:i,children:[e.jsxs("div",{className:"tl-canvas-toolbar",children:[e.jsxs("div",{className:"tl-canvas-toolbar-left",children:[!x&&e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>p(!0),title:"Show event stream",children:[e.jsx(yn,{size:14})," Events"]}),e.jsx("span",{className:"tl-canvas-mode",children:n==="live"?"● Live":"⏸ Paused"}),e.jsxs("span",{className:"tl-canvas-range",children:[new Date(_).toLocaleTimeString("en-GB",{hour12:!1})," →"," ",new Date(I).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(bn,{size:11})," agent"]}),e.jsxs("span",{className:"tl-legend-item",children:[e.jsx(Nn,{size:11})," task"]}),e.jsxs("span",{className:"tl-legend-item",children:[e.jsx(_s,{size:11})," bg"]})]})]}),e.jsx("div",{className:"tl-canvas-scroll",children:e.jsxs("svg",{className:"tl-canvas",width:b.width,height:Math.max(b.height,Zs),role:"application","aria-label":"Activity timeline",children:[e.jsx("defs",{children:e.jsx("pattern",{id:"tl-canvas-grid",width:b.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(M=>e.jsx("rect",{className:"tl-lane-bg",x:0,y:M.y,width:b.width,height:M.h,fill:M.id.charCodeAt(M.id.length-1)%2===0?"var(--bg-elev-2)":"var(--bg-elev)",opacity:.4},`bg-${M.id}`)),e.jsx("g",{className:"tl-time-axis",children:ce.map(M=>e.jsxs("g",{children:[e.jsx("line",{x1:M.x,y1:0,x2:M.x,y2:Zs,stroke:"var(--border)",strokeWidth:.5,strokeDasharray:"2,4",opacity:.5}),e.jsx("text",{x:M.x+4,y:Ve-8,fontSize:10,fontFamily:"var(--font-mono)",fill:"var(--text-dim)",children:M.label})]},`tick-${M.t}`))}),U.map(M=>{const X=Ve+us+M.index*Me+Me/2;return e.jsxs("g",{className:"tl-lane-label-group",children:[e.jsx("text",{x:6,y:X-2,className:"tl-lane-label",textAnchor:"start",children:Os(M.label,28)}),e.jsx("text",{x:6,y:X+10,className:"tl-lane-label-sub",textAnchor:"start",children:M.sub})]},`label-${M.id}`)}),Re.map(M=>{const X=it(M.statusClass),ge=M.id===(f==null?void 0:f.id);return e.jsxs("g",{className:V("tl-task-bar",`tl-task-bar-${M.statusClass}`,ge&&"tl-task-bar-selected"),onClick:()=>Ds(M),children:[e.jsx("rect",{x:M.x,y:M.y,width:M.w,height:M.h,rx:6,fill:X,fillOpacity:M.statusClass==="done"?.35:M.statusClass==="queued"?.18:.85,stroke:X,strokeWidth:ge?2.5:1.5,strokeOpacity:M.statusClass==="done"?.5:1,strokeDasharray:M.statusClass==="queued"?"4 4":void 0,style:{cursor:"pointer"}}),M.w>36&&e.jsx("text",{x:M.x+8,y:M.y+M.h/2+4,fontSize:11,fontFamily:"var(--font-sans)",fontWeight:500,fill:"var(--text-strong)",style:{pointerEvents:"none"},opacity:M.statusClass==="done"?.7:1,children:Os(M.label,Math.max(4,Math.floor(M.w/7)))})]},`bar-${M.id}`)}),Ie.map(M=>{const X=it(M.kind);return e.jsxs("g",{className:"tl-event-marker-group",children:[e.jsx("line",{x1:M.x,y1:M.y-6,x2:M.x,y2:M.y+6,stroke:X,strokeWidth:1.2,opacity:.7}),e.jsx("circle",{cx:M.x,cy:M.y,r:4,fill:X,opacity:.9,children:e.jsx("title",{children:`${M.kind}${M.author?` · ${M.author}`:""} · ${new Date(M.ts).toLocaleTimeString("en-GB",{hour12:!1})}`})})]},`ev-${M.id}`)}),e.jsx("line",{className:"tl-now-line",x1:Ge,y1:0,x2:Ge,y2:Zs,stroke:"var(--error)",strokeWidth:1.5,opacity:.9}),e.jsxs("g",{className:"tl-now-marker",children:[e.jsx("circle",{cx:Ge,cy:Ve-4,r:4,fill:"var(--error)"}),e.jsx("text",{x:Ge+6,y:Ve-4,fontSize:10,fontWeight:700,fill:"var(--error)",fontFamily:"var(--font-mono)",children:"now"})]})]})})]}),f&&e.jsx("aside",{className:"tl-detail tl-detail-enter",children:e.jsxs(G,{children:[e.jsxs(te,{children:[f.kind==="agent"&&e.jsx(Ye,{size:14}),f.kind==="task"&&e.jsx(Rs,{size:14}),f.kind==="bg"&&e.jsx(_s,{size:14}),f.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"})," ",f.kind]}),e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"status"})," ",e.jsx("code",{children:f.status})]}),f.kind==="agent"&&(()=>{const M=f.data;return e.jsxs(e.Fragment,{children:[M.role&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"role"})," ",M.role]}),M.model&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"model"})," ",M.model]})]})})(),f.kind==="task"&&(()=>{const M=f.data;return e.jsxs(e.Fragment,{children:[M.assignee&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"assignee"})," @",M.assignee]}),M.priority&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"priority"})," ",M.priority]}),M.createdAt&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"created"})," ",new Date(M.createdAt).toLocaleString()]})]})})(),f.kind==="bg"&&(()=>{const M=f.data;return e.jsxs(e.Fragment,{children:[M.startedAt&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"started"})," ",new Date(M.startedAt).toLocaleString()]}),M.tmuxSession&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"tmux"})," ",e.jsx("code",{children:M.tmuxSession})," ",M.tmuxActive?e.jsx("span",{className:"tag tag-success",children:"active"}):e.jsx("span",{className:"tag",children:"inactive"})]})]})})()]}),f.kind==="task"&&f.data.description&&e.jsx("div",{className:"tl-detail-desc",children:f.data.description}),f.kind==="bg"&&f.data.promptPreview&&e.jsx("div",{className:"tl-detail-desc",children:f.data.promptPreview}),f.kind==="bg"&&e.jsxs("div",{className:"tl-detail-bg",children:[e.jsx("pre",{className:"tl-bg-output",children:ee||"(no output — start the session via tmux attach)"}),e.jsxs("div",{className:"tl-bg-output-actions",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:Pa,children:[e.jsx(de,{size:12})," Refresh output"]}),he.length>0&&e.jsxs($,{variant:"secondary",size:"sm",onClick:()=>Qr(W,he[0]),children:[e.jsx(be,{size:12})," Open artifact"]}),e.jsxs($,{variant:"danger",size:"sm",onClick:Da,children:[e.jsx(ke,{size:12})," Kill session"]})]}),e.jsxs("div",{className:"tl-form-row",children:[e.jsx("label",{htmlFor:"bg-message-input",className:"sr-only",children:"Send a message to this bg session"}),e.jsx("input",{id:"bg-message-input",className:"input",placeholder:"Send a message to this bg session…",value:J,onChange:M=>ae(M.target.value),onKeyDown:M=>{M.key==="Enter"&&Ns()},"aria-label":"Send a message to this bg session"}),e.jsxs($,{variant:"primary",size:"sm",disabled:!J.trim(),onClick:Ns,children:[e.jsx(rs,{size:12})," Send"]})]})]}),f.kind!=="bg"&&e.jsxs("div",{className:"tl-detail-create",children:[e.jsx("label",{className:"field-label",htmlFor:"followup-task-title",children:"Create follow-up task"}),e.jsx("input",{id:"followup-task-title",className:"input",placeholder:"Task title",value:C,onChange:M=>D(M.target.value)}),e.jsxs("div",{className:"tl-form-row",children:[e.jsx("label",{htmlFor:"followup-task-priority",className:"sr-only",children:"Task priority"}),e.jsxs("select",{id:"followup-task-priority",className:"select",value:Y,onChange:M=>O(M.target.value),"aria-label":"Task priority",children:[e.jsx("option",{value:"low",children:"Low"}),e.jsx("option",{value:"normal",children:"Normal"}),e.jsx("option",{value:"high",children:"High"})]}),e.jsxs($,{variant:"primary",size:"sm",disabled:!C.trim()||H,onClick:Ps,children:[e.jsx(ze,{size:12})," Add task"]})]})]}),e.jsxs("div",{className:"tl-detail-comments",children:[e.jsxs("div",{className:"field-label",children:[e.jsx(Xs,{size:12})," Comments & activity"]}),e.jsxs("ul",{className:"comment-list",children:[A.length===0&&e.jsx("li",{className:"muted",children:"No comments yet."}),A.map((M,X)=>e.jsxs("li",{className:"comment-item",children:[e.jsxs("div",{className:"comment-head",children:[e.jsx("strong",{children:M.author||"system"}),e.jsxs("span",{className:"muted",children:[M.kind," · ",new Date(M.ts).toLocaleString()]})]}),M.text&&e.jsx("div",{className:"comment-text",children:M.text}),M.taskId&&e.jsxs("div",{className:"muted",children:["→ task ",e.jsx("code",{children:String(M.taskId)})]})]},`c-${X}`))]}),e.jsxs("div",{className:"comment-input-row",children:[e.jsx("label",{htmlFor:"comment-input",className:"sr-only",children:"Add a comment"}),e.jsx("input",{id:"comment-input",className:"input",placeholder:"Add a comment…",value:R,onChange:M=>y(M.target.value),onKeyDown:M=>{M.key==="Enter"&&!M.shiftKey&&bs()},"aria-label":"Add a comment"}),e.jsxs($,{variant:"secondary",size:"sm",disabled:!R.trim()||B,onClick:bs,children:[e.jsx(rs,{size:12})," Post"]})]})]})]})},f.id)]})})]})}function ll(s,t){const a=s.length,i=t.length,n=Array.from({length:i+1},()=>Array(a+1).fill(0));for(let c=0;c<=a;c++)n[0][c]=c;for(let c=0;c<=i;c++)n[c][0]=c;for(let c=1;c<=i;c++)for(let o=1;o<=a;o++){const l=s[o-1]===t[c-1]?0:1;n[c][o]=Math.min(n[c][o-1]+1,n[c-1][o]+1,n[c-1][o-1]+l)}return n[i][a]}function lt(s,t){if(t===s)return 100;if(t.startsWith(s))return 90;const a=t.split(/\s+/);for(const c of a)if(c.startsWith(s))return 80;const i=Math.min(s.length,t.length);return ll(s,t.substring(0,i))<=2?40:t.includes(s)?30:0}function ol(s,t){const a=s.toLowerCase().trim();return a?t.map(i=>{const n=lt(a,i.label.toLowerCase()),c=i.value?lt(a,String(i.value).toLowerCase()):0,o=i.description?lt(a,i.description.toLowerCase()):0,l=Math.max(n,c,o);if(l===0)return null;const x=n>=c&&n>=o?"label":c>=n&&c>=o?"value":"description",p=x==="label"?i.label:x==="value"?String(i.value):i.description;return{...i,score:l,matchedField:x,matchedTerm:p}}).filter(i=>i!==null).sort((i,n)=>n.score-i.score):[]}const Et="bizar_settings_recent";function za(){try{const s=localStorage.getItem(Et);return s?JSON.parse(s):[]}catch{return[]}}function cl(s){if(s)try{const t=za().filter(a=>a!==s);t.unshift(s),localStorage.setItem(Et,JSON.stringify(t.slice(0,5)))}catch{}}function dl(s,t){if(!t)return s;const a=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`(${a})`,"gi");return s.split(i).map((c,o)=>i.test(c)?e.jsx("mark",{children:c},o):e.jsx("span",{children:c},o))}function ml(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 ul({sections:s,onJump:t}){const[a,i]=r.useState(""),[n,c]=r.useState([]),[o,l]=r.useState(0),[x,p]=r.useState(null),[u,d]=r.useState(!1),m=r.useRef(null),h=r.useRef(null),g=r.useRef(null),j=r.useRef([]);r.useEffect(()=>{j.current=ml(s)},[s]);const k=r.useCallback((R,y=!1)=>{if(h.current&&clearTimeout(h.current),!R.trim()){c([]),l(0);return}const A=()=>{const P=ol(R,j.current);c(P),l(0)};y?A():h.current=setTimeout(A,150)},[]);r.useEffect(()=>{k(a)},[a,k]),r.useEffect(()=>()=>{h.current&&clearTimeout(h.current),g.current&&clearTimeout(g.current)},[]);const z=(R,y)=>{const A=document.querySelector(`[data-section="${R}"] [data-setting-id="${y}"]`);A&&(A.scrollIntoView({behavior:"smooth",block:"center"}),A.classList.add("setting-flash"),setTimeout(()=>A.classList.remove("setting-flash"),2e3));const P=document.querySelector(`[data-section="${R}"]`);P&&P.scrollIntoView({behavior:"smooth",block:A?"nearest":"start"})},N=R=>{p(R),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>p(null),1500);const y=document.querySelector(`[data-section="${R}"]`);y&&y.scrollIntoView({behavior:"smooth",block:"start"})},S=R=>{var y;cl(a),R.key===R.section?(N(R.section),t(R.section)):(N(R.section),t(R.section,R.key),z(R.section,R.key)),i(""),(y=m.current)==null||y.blur()},E=R=>{var y;R.key==="Escape"?(i(""),(y=m.current)==null||y.blur()):R.key==="ArrowDown"?(R.preventDefault(),l(A=>Math.min(A+1,n.length-1))):R.key==="ArrowUp"?(R.preventDefault(),l(A=>Math.max(A-1,0))):R.key==="Enter"&&(R.preventDefault(),n.length===0&&a.trim()&&k(a,!0),n[o]&&S(n[o]))},v=R=>{S(R)},b=za(),w=R=>{var y;i(R),(y=m.current)==null||y.focus()},f=()=>{try{localStorage.removeItem(Et)}catch{}d(R=>R)},L=u&&!a.trim()&&b.length>0;return e.jsxs("div",{className:"settings-search",children:[e.jsxs("div",{className:"settings-search-input-wrap",children:[e.jsx(ye,{size:13,className:"settings-search-icon"}),e.jsx("input",{ref:m,className:"settings-search-input",placeholder:"Search settings…",value:a,onChange:R=>i(R.target.value),onKeyDown:E,onFocus:()=>d(!0),onBlur:()=>setTimeout(()=>d(!1),150),"aria-label":"Search settings"}),a&&e.jsx("button",{type:"button",className:"icon-btn settings-search-clear",onClick:()=>i(""),"aria-label":"Clear search",children:e.jsx(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:f,tabIndex:-1,children:"Clear"})]}),b.map(R=>e.jsxs("button",{type:"button",className:"settings-search-recent-item",onMouseDown:y=>{y.preventDefault(),w(R)},children:[e.jsx(ye,{size:11}),e.jsx("span",{children:R})]},R))]}),a&&n.length>0&&e.jsx("div",{className:"settings-search-results",children:n.map((R,y)=>e.jsxs("button",{type:"button",className:V("settings-search-result",y===o&&"settings-search-result-active"),onClick:()=>v(R),onMouseEnter:()=>l(y),children:[e.jsx("span",{className:V("settings-search-result-type",R.key===R.section&&"settings-search-result-type-section"),children:R.key===R.section?"section":"field"}),e.jsx("span",{className:"settings-search-result-label",children:dl(R.label,a)}),R.key!==R.section&&e.jsx("span",{className:"settings-search-result-key mono muted",children:R.key})]},`${R.section}::${R.key}`))}),a&&n.length===0&&e.jsx("div",{className:"settings-search-empty muted",children:"No matching settings."})]})}const hl=[{id:"dark",label:"Dark",Icon:kn},{id:"light",label:"Light",Icon:wn},{id:"system",label:"System",Icon:Sn}],xl=[{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"}],pl=["Inter","system-ui","Segoe UI","Roboto","JetBrains Mono","SF Mono","Cascadia Code"];function gl({settings:s,patchTheme:t,patchUi:a}){return e.jsxs(G,{id:"settings-theme","data-section":"theme",children:[e.jsxs(te,{children:[e.jsx(ra,{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:xl.map(i=>e.jsxs("button",{type:"button",className:V("theme-preset",s.theme.accent===i.accent&&"theme-preset-active"),onClick:()=>t({accent:i.accent}),title:i.name,children:[e.jsx("span",{className:"theme-preset-swatch",style:{background:i.accent}}),e.jsx("span",{className:"theme-preset-name",children:i.name})]},i.name))})]}),e.jsxs("div",{className:"field","data-setting-id":"theme.mode",children:[e.jsx("label",{className:"field-label",children:"Mode"}),e.jsx("div",{className:"theme-row",children:hl.map(({id:i,label:n,Icon:c})=>{const o=s.theme.mode===i;return e.jsxs("button",{type:"button",className:V("theme-card",o&&"theme-card-active"),onClick:()=>t({mode:i}),children:[e.jsx(c,{size:16}),e.jsx("span",{className:"theme-card-label",children:n}),e.jsx("span",{className:V("theme-card-swatch",`theme-card-swatch-${i}`)})]},i)})})]}),e.jsx("div",{className:"theme-colors",children:["accent","success","warning","error","info"].map(i=>e.jsxs("div",{className:"field","data-setting-id":`theme.${i}`,children:[e.jsx("label",{className:"field-label",children:i.charAt(0).toUpperCase()+i.slice(1)}),e.jsxs("div",{className:"color-row",children:[e.jsx("input",{type:"color",className:"input color-input",value:s.theme[i],onChange:n=>t({[i]:n.target.value}),"aria-label":`${i} color`}),e.jsx("input",{type:"text",className:"input",value:s.theme[i],onChange:n=>t({[i]:n.target.value}),"aria-label":`${i} color hex`})]})]},i))}),e.jsxs("div",{className:"field","data-setting-id":"theme.fontFamily",children:[e.jsx("label",{className:"field-label",children:"Font family"}),e.jsx("select",{className:"select",value:s.theme.fontFamily,onChange:i=>t({fontFamily:i.target.value}),children:pl.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 fl({tailscale:s,tailscaleDraft:t,setTailscaleDraft:a,onTailscaleToggle:i}){return e.jsxs(e.Fragment,{children:[e.jsxs(G,{id:"settings-service","data-section":"service",children:[e.jsxs(te,{children:[e.jsx(js,{size:14})," Service"]}),e.jsx(ne,{children:"Background daemon that runs schedules."}),e.jsx("div",{"data-setting-id":"service.enabled",children:s?e.jsxs("div",{className:"service-card",children:[e.jsxs("p",{children:["Status: ",e.jsx("strong",{children:s.settings.enabled?"enabled":"disabled"})," ","· Tailscale installed: ",e.jsx("strong",{children:s.installed?"yes":"no"})," ","· authenticated: ",e.jsx("strong",{children:s.authenticated?"yes":"no"})]}),e.jsxs("p",{className:"muted",children:["Use ",e.jsx("code",{children:"bizar service start"})," / ",e.jsx("code",{children:"bizar service stop"})," in your terminal to control the daemon."]})]}):e.jsx("p",{className:"muted",children:"Loading service status…"})})]}),e.jsxs(G,{id:"settings-tailscale","data-section":"tailscale",children:[e.jsxs(te,{children:[e.jsx(gt,{size:14})," Tailscale serve"]}),e.jsx(ne,{children:"Expose the dashboard over your Tailscale network."}),s?e.jsxs(e.Fragment,{children:[e.jsxs("p",{children:["Installed: ",e.jsx("strong",{children:s.installed?"yes":"no"})," ",s.version&&e.jsxs("span",{className:"muted",children:["(",s.version,")"]})]}),e.jsxs("p",{children:["Authenticated: ",e.jsx("strong",{children:s.authenticated?"yes":"no"})]}),e.jsxs("p",{children:["Serve enabled: ",e.jsx("strong",{children:s.settings.enabled?"yes":"no"})]}),e.jsxs("div",{className:"task-form-row",children:[e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",children:"Port"}),e.jsx("input",{type:"number",className:"input",value:t.port,onChange:n=>a(c=>({...c,port:Number(n.target.value)||4321}))})]}),e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"tailscale-https",children:"Use HTTPS"}),e.jsx("input",{id:"tailscale-https",type:"checkbox",checked:t.https,onChange:n=>a(c=>({...c,https:n.target.checked}))})]})]}),e.jsx($,{variant:"primary",onClick:i,children:s.settings.enabled?"Disable serve":"Enable serve"})]}):e.jsx("p",{className:"muted",children:"Loading Tailscale status…"})]})]})}function jl({settings:s,patchNotifications:t}){return e.jsxs(G,{id:"settings-notifications","data-section":"notifications",children:[e.jsx(te,{children:"Notifications"}),e.jsx(ne,{children:"Toast triggers inside the dashboard."}),e.jsxs("label",{className:"checkbox-row","data-setting-id":"notifications.onAgentComplete",children:[e.jsx("input",{type:"checkbox",checked:!!s.notifications.onAgentComplete,onChange:a=>t({onAgentComplete:a.target.checked})}),e.jsx("span",{children:"Notify when an agent invocation completes"})]}),e.jsxs("label",{className:"checkbox-row","data-setting-id":"notifications.onPlanApproval",children:[e.jsx("input",{type:"checkbox",checked:!!s.notifications.onPlanApproval,onChange:a=>t({onPlanApproval:a.target.checked})}),e.jsx("span",{children:"Notify when a plan needs approval"})]})]})}function vl({authStatus:s,setAuthStatus:t}){const a=re(),[i,n]=r.useState(T.getToken()),[c,o]=r.useState("");r.useEffect(()=>{let u=!1;return(async()=>{try{const d=await T.probeAuthStatus();u||t(d)}catch{u||t({required:!0,loopback:!1,peer:""})}})(),()=>{u=!0}},[]);const l=async()=>{try{const u=await T.get("/auth/reveal");o(u.token),n(u.token),T.setToken(u.token);try{await navigator.clipboard.writeText(u.token),a.success("Token copied to clipboard.")}catch{a.success("Token revealed — copy from the field below.")}}catch(u){a.error(`Reveal failed: ${u.message}`)}},x=async()=>{if(confirm("Regenerate the auth token? Anything still using the old token will start getting 401 errors immediately."))try{const u=await T.post("/auth/regenerate");o(u.token),n(u.token),T.setToken(u.token);try{await navigator.clipboard.writeText(u.token),a.success("New token generated and copied to clipboard.")}catch{a.success("New token generated — copy from the field below. Old token is now invalid.")}}catch(u){a.error(`Regenerate failed: ${u.message}`)}},p=()=>{T.setToken(i.trim()),a.success("Token saved. The dashboard will use it on the next request.")};return e.jsxs(G,{id:"settings-auth","data-section":"auth",children:[e.jsxs(te,{children:[e.jsx(Tt,{size:14})," Authentication"]}),e.jsx(ne,{children:"Localhost and Tailscale browser access are auto-trusted via loopback. A bearer token is still available for non-loopback clients and forced-auth mode."}),e.jsxs("div",{className:"field","data-setting-id":"auth.status",children:[e.jsx("label",{className:"field-label",children:"Server status"}),e.jsxs("p",{style:{margin:"4px 0"},children:["Auth required:"," ",e.jsx("strong",{children:s?s.required?"yes":"no":"probing…"})]}),e.jsxs("p",{style:{margin:"4px 0"},children:["Connection:"," ",e.jsx("strong",{children:s?s.loopback?"loopback (auto-trusted)":"remote":"probing…"})]}),e.jsxs("p",{style:{margin:"4px 0"},children:["Peer address:"," ",s!=null&&s.peer?e.jsx("code",{children:s.peer}):e.jsx("span",{className:"muted",children:"probing…"})]}),e.jsxs("p",{className:"muted",style:{fontSize:12,margin:"4px 0"},children:["Localhost and Tailscale browser access are auto-trusted because the dashboard sees a loopback peer. Paste a token only for non-loopback API clients/scripts, or if you force auth for every connection with"," ",e.jsx("code",{children:"BIZAR_DASHBOARD_REQUIRE_AUTH=1"}),"."]}),e.jsxs("p",{className:"muted",style:{fontSize:12,margin:"4px 0"},children:["Dashboard tokens are generated on first boot and saved to"," ",e.jsx("code",{children:"~/.config/bizar/dashboard-secret"})," (mode 0600)."]}),e.jsx("p",{className:"muted",style:{fontSize:12,margin:"4px 0"},children:"For Tailscale Serve or any reverse-proxy access, paste this token once via the boot screen — it is saved per-origin and works for all subsequent visits."})]}),e.jsxs("div",{className:"field","data-setting-id":"auth.token",children:[e.jsx("label",{className:"field-label",children:"Token (this browser)"}),e.jsx("input",{type:"password",className:"input mono",value:i,onChange:u=>n(u.target.value),placeholder:"Paste token from server stderr or another browser",spellCheck:!1,autoComplete:"off"}),e.jsxs("div",{className:"task-form-row",style:{marginTop:8},children:[e.jsxs($,{variant:"secondary",size:"sm",onClick:p,children:[e.jsx(Rt,{size:14})," Save token"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:l,children:[e.jsx(os,{size:14})," Reveal & copy server token"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:x,children:[e.jsx(ua,{size:14})," Regenerate"]})]}),c?e.jsxs("p",{className:"muted",style:{fontSize:12,marginTop:8},children:["Last revealed token (one-time): ",e.jsx("code",{className:"mono",children:c})]}):null,e.jsx("p",{className:"muted",style:{fontSize:12,marginTop:8},children:"Regenerating invalidates the current token immediately. Anything still using the old token will see 401 until it's updated."})]})]})}function yl({settings:s,patchAgents:t,patchDashboard:a,autoSave:i}){var p,u,d,m;const n=re(),[c,o]=r.useState({});r.useEffect(()=>{T.get("/settings/plugin-options").then(o).catch(()=>{})},[]);const l=async()=>{try{await T.put("/settings/plugin-options",c),n.success("Saved — restart opencode for changes to take effect.")}catch(h){n.error(`Save failed: ${h.message}`)}},x=async()=>{try{const g=await(await fetch("/api/background/cleanup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({maxAgeDays:7})})).json();n.success(`Cleaned up ${g.deleted} old instances.`)}catch(h){n.error(`Cleanup failed: ${h.message}`)}};return e.jsxs(e.Fragment,{children:[e.jsxs(G,{id:"settings-agents","data-section":"agents",children:[e.jsxs(te,{children:[e.jsx(js,{size:14})," Agent Behavior"]}),e.jsx(ne,{children:"Limits and timeouts for background agent dispatch."}),e.jsxs("div",{className:"form-row",children:[e.jsxs("label",{htmlFor:"agents-maxParallel",children:["Max parallel agents",e.jsx("span",{className:"meta-badge",children:"default: 6"})]}),e.jsx("input",{id:"agents-maxParallel",type:"number",min:1,max:20,value:((p=s.agents)==null?void 0:p.maxParallel)??6,onChange:h=>t({maxParallel:Math.max(1,Math.min(20,parseInt(h.target.value,10)||6))})})]}),e.jsxs("div",{className:"form-row",children:[e.jsxs("label",{htmlFor:"agents-stuckThresholdMs",children:["Stuck threshold (ms)",e.jsx("span",{className:"meta-badge",children:"default: 600000 (10 min)"})]}),e.jsx("input",{id:"agents-stuckThresholdMs",type:"number",min:6e4,max:36e5,step:6e4,value:((u=s.agents)==null?void 0:u.stuckThresholdMs)??6e5,onChange:h=>t({stuckThresholdMs:Math.max(6e4,Math.min(36e5,parseInt(h.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:h=>t({autoRestart:h.target.checked})}),e.jsx("span",{children:"Auto-restart stuck agents"})]})]}),e.jsxs(G,{id:"settings-dashboard","data-section":"dashboard",children:[e.jsxs(te,{children:[e.jsx(vs,{size:14})," Dashboard"]}),e.jsxs(ne,{children:["Controls how ",e.jsx("code",{children:"bizar"})," starts up."]}),e.jsxs("label",{className:"checkbox-row","data-setting-id":"dashboard.autoLaunchWeb",children:[e.jsx("input",{type:"checkbox",checked:s.dashboard.autoLaunchWeb!==!1,onChange:h=>a({autoLaunchWeb:h.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:h=>a({projectsDirectory:h.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(Wn,{initialValue:(s.dashboard.allowedRoots??[]).join(`
6
- `),delay:1500,saveFn:async h=>{const g=h.split(`
7
- `).map(j=>j.trim()).filter(Boolean);a({allowedRoots:g}),i==null||i("dashboard",{allowedRoots:g})},render:({value:h,onChange:g,onBlur:j})=>e.jsx("textarea",{id:"set-allowed-roots",className:"textarea",rows:4,placeholder:`/workspace
8
- /srv/projects`,value:h,onChange:k=>g(k.target.value),onBlur:j})},(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 h=(s.dashboard.allowedRoots??[]).join(`
10
- `).split(`
11
- `),g=[];return h.forEach((j,k)=>{j.trim()&&(/^\/|^[A-Za-z]:/.test(j)||g.push({key:`noabs-${k}`,msg:e.jsxs("p",{style:{color:"var(--warning)",fontSize:11,marginTop:2},children:["Line ",k+1,': "',j,'" — should be absolute (start with / or a drive letter).']})}),j.includes("..")&&g.push({key:`dots-${k}`,msg:e.jsxs("p",{style:{color:"var(--error)",fontSize:11,marginTop:2},children:["Line ",k+1,': "',j,`" — contains '..' (server will reject this).`]})}))}),g.map(j=>j.msg)})()]})]}),e.jsxs(G,{id:"settings-background","data-section":"background",children:[e.jsxs(te,{children:[e.jsx(js,{size:14})," Background Agents"]}),e.jsx(ne,{children:"Tune plugin options. Changes take effect on next plugin restart."}),e.jsxs("div",{className:"form-row",children:[e.jsxs("label",{htmlFor:"bg-maxConcurrent",children:["Max concurrent instances",e.jsx("span",{className:"meta-badge",children:"default: 8"})]}),e.jsx("input",{id:"bg-maxConcurrent",type:"number",min:1,max:32,value:c.maxConcurrentInstances??8,onChange:h=>o(g=>({...g,maxConcurrentInstances:Math.max(1,Math.min(32,parseInt(h.target.value,10)||8))}))}),e.jsxs("small",{className:"muted",children:["Plugin option: ",e.jsx("code",{children:"maxConcurrentInstances"})]})]}),e.jsxs("div",{className:"form-row",children:[e.jsxs("label",{htmlFor:"bg-toolCallCap",children:["Tool-call cap",e.jsx("span",{className:"meta-badge",children:"default: 500"})]}),e.jsx("input",{id:"bg-toolCallCap",type:"number",min:1,max:5e3,value:c.backgroundToolCallCap??500,onChange:h=>o(g=>({...g,backgroundToolCallCap:Math.max(1,Math.min(5e3,parseInt(h.target.value,10)||500))}))}),e.jsxs("small",{className:"muted",children:["Plugin option: ",e.jsx("code",{children:"backgroundToolCallCap"})]})]}),e.jsxs("div",{className:"form-row",children:[e.jsxs("label",{htmlFor:"bg-stallTimeout",children:["Stall timeout (ms)",e.jsx("span",{className:"meta-badge",children:"default: 180000"})]}),e.jsx("input",{id:"bg-stallTimeout",type:"number",min:1e4,max:6e5,step:1e3,value:c.backgroundStallTimeoutMs??18e4,onChange:h=>o(g=>({...g,backgroundStallTimeoutMs:Math.max(1e4,Math.min(6e5,parseInt(h.target.value,10)||18e4))}))}),e.jsxs("small",{className:"muted",children:["Plugin option: ",e.jsx("code",{children:"backgroundStallTimeoutMs"})]})]}),e.jsxs("div",{className:"form-row",children:[e.jsxs("label",{htmlFor:"bg-thinkingLoopTimeout",children:["Thinking-loop timeout (ms)",e.jsx("span",{className:"meta-badge",children:"default: 300000"})]}),e.jsx("input",{id:"bg-thinkingLoopTimeout",type:"number",min:3e4,max:9e5,step:1e3,value:c.backgroundThinkingLoopTimeoutMs??3e5,onChange:h=>o(g=>({...g,backgroundThinkingLoopTimeoutMs:Math.max(3e4,Math.min(9e5,parseInt(h.target.value,10)||3e5))}))}),e.jsxs("small",{className:"muted",children:["Plugin option: ",e.jsx("code",{children:"backgroundThinkingLoopTimeoutMs"})]})]}),e.jsxs("div",{className:"form-row",children:[e.jsxs("label",{htmlFor:"bg-maxInterventions",children:["Max interventions",e.jsx("span",{className:"meta-badge",children:"default: 1"})]}),e.jsx("input",{id:"bg-maxInterventions",type:"number",min:1,max:3,value:c.backgroundMaxInterventions??1,onChange:h=>o(g=>({...g,backgroundMaxInterventions:Math.max(1,Math.min(3,parseInt(h.target.value,10)||1))}))}),e.jsxs("small",{className:"muted",children:["Plugin option: ",e.jsx("code",{children:"backgroundMaxInterventions"})]})]}),e.jsxs("div",{className:"form-row",children:[e.jsxs($,{variant:"secondary",size:"sm",onClick:l,children:[e.jsx(As,{size:14})," Save plugin options"]}),e.jsx($,{variant:"secondary",size:"sm",onClick:x,children:"Cleanup old instances (>7 days)"})]}),e.jsx("div",{className:"form-row",children:e.jsxs("small",{children:["Plugin options are read at startup. Save changes and run ",e.jsx("code",{children:"bizar update"})," to apply."]})})]})]})}function bl({workspaceId:s,onInviteCreated:t}){const a=$e(),[i,n]=r.useState(""),[c,o]=r.useState("editor"),[l,x]=r.useState([]),[p,u]=r.useState(!1),[d,m]=r.useState(!1),[h,g]=r.useState(null),[j,k]=r.useState(null);r.useEffect(()=>{z()},[s]);async function z(){u(!0);try{const b=await T.get(`/workspaces/${s}/invites`);x(b.invites||[])}catch{}finally{u(!1)}}async function N(b){if(b.preventDefault(),!!i.trim()){m(!0),k(null);try{const w=await T.post(`/workspaces/${s}/invites`,{email:i.trim(),role:c});n(""),await z(),t==null||t(),a.open({title:"Invite Link Created",children:e.jsxs("div",{className:"invite-link-dialog",children:[e.jsxs("p",{children:["Share this link with ",e.jsx("strong",{children:i})," to invite them as ",e.jsx("strong",{children:c}),":"]}),e.jsxs("div",{className:"invite-url-box",children:[e.jsx(zn,{size:14}),e.jsx("input",{type:"text",readOnly:!0,value:w.url,onClick:f=>f.target.select()}),e.jsx("button",{type:"button",className:"invite-copy-btn",onClick:()=>{navigator.clipboard.writeText(w.url).catch(()=>{}),g(w.token),setTimeout(()=>g(null),2e3)},children:h===w.token?e.jsx(gs,{size:14}):e.jsx(os,{size:14})})]}),e.jsx("p",{className:"invite-url-note",children:"This link expires in 7 days."})]}),footer:e.jsx($,{variant:"primary",size:"sm",onClick:()=>a.close(),children:"Done"})})}catch(w){k(w.message||"Failed to create invite")}finally{m(!1)}}}async function S(b){if(confirm("Revoke this invite?"))try{await T.del(`/workspaces/${s}/invites/${b}`),await z()}catch(w){k(w.message||"Failed to revoke invite")}}function E(b,w){navigator.clipboard.writeText(b).catch(()=>{}),g(w),setTimeout(()=>g(null),2e3)}const v={admin:"role-admin",editor:"role-editor",viewer:"role-viewer"};return e.jsxs("div",{className:"invite-dialog",children:[e.jsxs("form",{className:"invite-form",onSubmit:N,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:b=>n(b.target.value),placeholder:"colleague@example.com",required:!0})]}),e.jsxs("div",{className:"invite-form-field invite-form-field-role",children:[e.jsx("label",{htmlFor:"invite-role",children:"Role"}),e.jsxs("select",{id:"invite-role",value:c,onChange:b=>o(b.target.value),children:[e.jsx("option",{value:"viewer",children:"Viewer"}),e.jsx("option",{value:"editor",children:"Editor"}),e.jsx("option",{value:"admin",children:"Admin"})]})]}),e.jsxs($,{type:"submit",variant:"primary",size:"sm",loading:d,disabled:!i.trim(),children:[e.jsx(Cn,{size:13}),"Invite"]})]}),j&&e.jsx("p",{className:"invite-error",children:j})]}),e.jsxs("div",{className:"invite-list",children:[e.jsx("h4",{className:"invite-list-title",children:"Pending Invites"}),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(b=>e.jsxs("div",{className:"invite-item",children:[e.jsxs("div",{className:"invite-item-info",children:[e.jsx("span",{className:"invite-item-email",children:b.email}),e.jsx("span",{className:V("invite-item-role",v[b.role]),children:b.role})]}),e.jsxs("div",{className:"invite-item-actions",children:[e.jsx("button",{type:"button",className:"invite-action-btn",title:"Copy invite link",onClick:()=>{const w=`${window.location.origin}/accept-invite?token=${b.token}`;E(w,b.token)},children:h===b.token?e.jsx(gs,{size:13}):e.jsx(os,{size:13})}),e.jsx("button",{type:"button",className:"invite-action-btn invite-action-revoke",title:"Revoke invite",onClick:()=>S(b.token),children:e.jsx(ke,{size:13})})]})]},b.token))]})]})}const Nl={admin:Tn,editor:Tt,viewer:fs},kl={admin:"role-admin",editor:"role-editor",viewer:"role-viewer"};function wl(){const[s,t]=r.useState([]),[a,i]=r.useState(!0),[n,c]=r.useState(!1),[o,l]=r.useState(""),[x,p]=r.useState(null),[u,d]=r.useState(null),m=$e();r.useEffect(()=>{h()},[]);async function h(){i(!0);try{const z=await T.get("/workspaces");t(z.workspaces||[])}catch{p("Failed to load workspaces")}finally{i(!1)}}async function g(z){if(z.preventDefault(),!!o.trim()){c(!0);try{await T.post("/workspaces",{name:o.trim()}),l(""),await h()}catch(N){p(N.message||"Failed to create workspace")}finally{c(!1)}}}async function j(z,N){if(confirm(`Delete workspace "${N}"?`)&&confirm("This cannot be undone."))try{await T.del(`/workspaces/${z}`),await h()}catch(S){p(S.message||"Failed to delete workspace")}}function k(z){navigator.clipboard.writeText(`${window.location.origin}/accept-invite?workspace=${z}`).catch(()=>{}),d(z),setTimeout(()=>d(null),2e3)}return a?e.jsx("div",{className:"settings-section-loading",children:"Loading workspaces..."}):e.jsxs("div",{className:"settings-section settings-section-workspaces",children:[e.jsx("h3",{className:"settings-section-title",children:"Workspaces"}),e.jsx("p",{className:"settings-section-desc",children:"Workspaces let you share access with team members. Each workspace has its own members, settings, and data."}),x&&e.jsxs("div",{className:"settings-section-error",children:[e.jsx("span",{children:x}),e.jsx("button",{onClick:()=>p(null),children:"×"})]}),e.jsxs("form",{className:"workspace-create-form",onSubmit:g,children:[e.jsx("input",{type:"text",placeholder:"New workspace name",value:o,onChange:z=>l(z.target.value),maxLength:64}),e.jsxs($,{type:"submit",variant:"primary",size:"sm",loading:n,disabled:!o.trim(),children:[e.jsx(ze,{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:z,role:N})=>{const S=Nl[N]||fs;return e.jsxs("div",{className:"workspace-item",children:[e.jsxs("div",{className:"workspace-item-info",children:[e.jsx("div",{className:"workspace-item-icon",children:e.jsx(Ks,{size:16})}),e.jsxs("div",{className:"workspace-item-details",children:[e.jsx("span",{className:"workspace-item-name",children:z.name}),e.jsxs("span",{className:V("workspace-item-role",kl[N]),children:[e.jsx(S,{size:11}),N]})]})]}),e.jsxs("div",{className:"workspace-item-actions",children:[e.jsx($,{variant:"ghost",size:"sm",iconOnly:!0,title:"Copy invite link",onClick:()=>k(z.id),children:u===z.id?e.jsx(gs,{size:13}):e.jsx(os,{size:13})}),N==="admin"&&e.jsx($,{variant:"ghost",size:"sm",iconOnly:!0,title:"Manage members",onClick:()=>{m.open({title:`Manage "${z.name}"`,children:e.jsx(bl,{workspaceId:z.id,onInviteCreated:()=>h()}),width:520})},children:e.jsx(Ks,{size:13})}),N==="admin"&&s.length>1&&e.jsx($,{variant:"ghost",size:"sm",iconOnly:!0,title:"Delete workspace",onClick:()=>j(z.id,z.name),children:e.jsx(ke,{size:13})})]})]},z.id)})]})]})}const Sl=[{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"}],Cl=[{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 zl({settings:s,refreshSnapshot:t,settingsMode:a,settingsActiveSection:i,setSettingsActiveSection:n,setActiveTab:c}){const o=re(),[l,x]=r.useState(s),[p,u]=r.useState(!1),[d,m]=r.useState(!1),[h,g]=r.useState(null),[j,k]=r.useState({port:4321,https:!0,hostname:""}),[z,N]=r.useState(null),S=()=>{c("overview")};r.useEffect(()=>{x(s),u(!1),s.theme&&xs(s.theme)},[s]),r.useEffect(()=>{h&&k({port:h.settings.port,https:h.settings.https!==!1,hostname:h.settings.hostname||""})},[h]),r.useEffect(()=>{T.get("/tailscale/status").then(g).catch(()=>{})},[]);const E=r.useRef(null),v=r.useCallback(async(B,Z)=>{x(he=>({...he,[B]:Z})),E.current&&clearTimeout(E.current),E.current=setTimeout(async()=>{try{await T.put("/settings",{...l,[B]:Z})}catch(he){console.error("autoSave failed",he)}},300)},[l]);r.useEffect(()=>()=>{E.current&&clearTimeout(E.current)},[]);const b=B=>{x(Z=>{const he={...Z,theme:{...Z.theme,...B}};return xs(he.theme),he}),u(!0)},w=B=>{x(Z=>({...Z,ui:{...Z.ui,...B}})),u(!0)},f=(B,Z)=>{x(he=>({...he,[B]:Z})),u(!0)},L=B=>{x(Z=>({...Z,notifications:{...Z.notifications,...B}})),u(!0)},R=B=>{x(Z=>({...Z,agents:{...Z.agents,...B}})),u(!0)},y=B=>{x(Z=>({...Z,dashboard:{...Z.dashboard,...B}})),u(!0)},[A,P]=r.useState(()=>{if(typeof window>"u")return null;const B=window.location.hash.replace(/^#settings-/,"");return Sl.some(Z=>Z.id===B)?B:null}),C=a?i??null:A,D=B=>{if(a)n==null||n(B);else{P(B);try{if(history.replaceState(null,"",B?`#settings-${B}`:window.location.pathname),B){const Z=document.getElementById(`settings-${B}`);Z&&Z.scrollIntoView({behavior:"smooth",block:"start"})}else window.scrollTo({top:0,behavior:"smooth"})}catch{}}if(B){const Z=document.getElementById(`settings-${B}`);Z&&Z.scrollIntoView({behavior:"smooth",block:"start"})}else window.scrollTo({top:0,behavior:"smooth"})},Y=async()=>{try{h!=null&&h.settings.enabled?(await T.post("/tailscale/disable"),o.success("Tailscale serve disabled.")):(await T.post("/tailscale/enable",{port:j.port||4321,https:j.https,hostname:j.hostname||""}),o.success("Tailscale serve enabled.")),g(await T.get("/tailscale/status"))}catch(B){o.error(`Tailscale failed: ${B.message}`)}},O=async()=>{m(!0);try{const B=await T.put("/settings",l);x(B.data),u(!1),Ts(B.data.theme),xs(B.data.theme),o.success("Settings saved."),await t()}catch(B){o.error(`Save failed: ${B.message}`)}finally{m(!1)}},J=async()=>{try{const B=await T.get("/settings");x(B.data),u(!1),Ts(B.data.theme),xs(B.data.theme),o.info("Settings reloaded.",1500)}catch(B){o.error(`Reload failed: ${B.message}`)}},ae=async()=>{if(confirm("Reset all settings to defaults?"))try{const B=await T.post("/settings/reset");x(B.data),u(!1),Ts(B.data.theme),xs(B.data.theme),o.success("Settings reset."),await t()}catch(B){o.error(`Reset failed: ${B.message}`)}},ee={settings:l,patchTheme:b,patchUi:w,patchTop:f,patchNotifications:L,patchAgents:R,patchDashboard:y},F=l.about||{version:"3.0.4",homepage:"https://github.com/DrB0rk/BizarHarness",license:"MIT"},H=C===null,K=B=>C===B;return e.jsxs("div",{className:"view view-settings",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(kt,{size:18})," Settings"]}),e.jsxs("p",{className:"view-subtitle",children:["Personal preferences. Changes are saved to ",e.jsx("code",{children:"~/.config/bizar/settings.json"}),"."]})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:ae,children:[e.jsx(ua,{size:14})," Reset"]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:J,children:[e.jsx(de,{size:14})," Reload"]}),e.jsxs($,{variant:"primary",size:"sm",disabled:!p||d,onClick:O,children:[d?e.jsx("span",{className:"btn-spinner"}):e.jsx(As,{size:14}),d?"Saving…":"Save"]})]})]}),a&&e.jsxs("div",{className:"settings-mode-banner",children:[e.jsx("span",{children:"You're in settings mode. All sections are visible in the sidebar."}),e.jsx($,{variant:"secondary",size:"sm",onClick:S,children:"← Back to main view"})]}),e.jsx(ul,{sections:Cl,onJump:D}),e.jsxs("div",{className:V("settings-grid",C&&"settings-grid-filtered"),"data-active-section":C||void 0,children:[(H||K("theme"))&&e.jsx(gl,{...ee}),(H||K("updates"))&&e.jsx(qn,{}),(H||K("layout")||K("general"))&&e.jsx(Vn,{...ee,autoSave:v}),(H||K("env-vars"))&&e.jsx(Hn,{}),(H||K("network")||K("service")||K("tailscale"))&&e.jsx(fl,{tailscale:h,tailscaleDraft:j,setTailscaleDraft:k,onTailscaleToggle:Y}),(H||K("network")||K("tailscale"))&&e.jsx(Gn,{initialStatus:h}),(H||K("notifications"))&&e.jsx(jl,{...ee}),(H||K("auth"))&&e.jsx(vl,{settings:l,authStatus:z,setAuthStatus:N}),(H||K("agents")||K("dashboard")||K("background"))&&e.jsx(yl,{...ee,autoSave:v}),(H||K("system-llm"))&&e.jsx(Kn,{...ee}),(H||K("headroom"))&&e.jsx(Yn,{settings:l,setSettings:x,setDirty:u}),(H||K("activity-log")||K("about"))&&e.jsx(Xn,{about:F}),(H||K("workspaces"))&&e.jsx(wl,{})]})]})}const Vt=Oe.memo(zl);function Tl({snapshot:s,refreshSnapshot:t}){const a=re(),i=$e(),[n,c]=r.useState(Array.isArray(s.mods)?s.mods:[]),[o,l]=r.useState(!0),[x,p]=r.useState(null),[u,d]=r.useState([]),[m,h]=r.useState(null),[g,j]=r.useState(!1),[k,z]=r.useState(null),[N,S]=r.useState(!1),[E,v]=r.useState({}),b=async()=>{var C,D,Y;S(!0);try{const O=await T.get("/mods/registry");z({source:((C=O.registry)==null?void 0:C.source)||"",version:(D=O.registry)==null?void 0:D.version,updatedAt:(Y=O.registry)==null?void 0:Y.updatedAt,mods:O.mods||[]})}catch(O){z({source:"",mods:[],error:O.message})}finally{S(!1)}},w=async C=>{v(D=>({...D,[C]:!0}));try{const D=await T.post("/mods",{id:C});c(Y=>[...Y.filter(O=>O.id!==D.id),D]),a.success(`Mod "${D.id}" installed from registry.`),await t()}catch(D){a.error(`Install failed: ${D.message}`)}finally{v(D=>({...D,[C]:!1}))}},f=async(C,D=!1)=>{v(Y=>({...Y,[C]:!0}));try{const Y=await T.post(`/mods/${encodeURIComponent(C)}/upgrade`,{backup:D});c(J=>[...J.filter(ae=>ae.id!==Y.mod.id),Y.mod]);const O=Y.backupPath?` (backup at ${Y.backupPath})`:"";a.success(`Mod "${C}" upgraded v${Y.from} → v${Y.to}${O}.`),await t()}catch(Y){a.error(`Upgrade failed: ${Y.message}`)}finally{v(Y=>({...Y,[C]:!1}))}},L=async()=>{try{const C=await T.get("/mods");c(C.mods||[]);try{const D=await T.get("/mods/views");d(D.views||[])}catch{d([])}}catch(C){a.error(`Mods load failed: ${C.message}`)}finally{l(!1)}};r.useEffect(()=>{L()},[]),r.useEffect(()=>{Array.isArray(s.mods)&&s.mods!==n&&c(s.mods)},[s.mods]);const R=()=>{let C=null;i.open({title:"Install mod",children:e.jsxs("div",{children:[e.jsxs("p",{className:"muted",children:["Provide the absolute path to a mod folder (one that contains a ",e.jsx("code",{children:"mod.json"}),"). The folder will be copied to"," ",e.jsx("code",{children:"~/.config/bizar/mods/<id>/"}),"."]}),e.jsx("label",{className:"field-label",htmlFor:"install-mod-path",children:"Path"}),e.jsx("input",{id:"install-mod-path",ref:D=>C=D,className:"input",type:"text",placeholder:"/path/to/my-mod",autoFocus:!0})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx($,{variant:"ghost",onClick:()=>i.close(),children:"Cancel"}),e.jsx($,{variant:"primary",onClick:async()=>{const D=((C==null?void 0:C.value)||"").trim();if(!D){a.warning("Path is required.");return}try{const Y=await T.post("/mods",{path:D});c(O=>[...O,Y]),a.success(`Mod "${Y.id}" installed.`),i.close(),await t()}catch(Y){a.error(`Install failed: ${Y.message}`)}},children:"Install"})]})})},y=async C=>{if(confirm(`Uninstall mod "${C}"? This removes the folder from ~/.config/bizar/mods/.`))try{await T.del(`/mods/${encodeURIComponent(C)}`),c(D=>D.filter(Y=>Y.id!==C)),x===C&&p(null),a.success("Mod uninstalled.")}catch(D){a.error(`Uninstall failed: ${D.message}`)}},A=async C=>{try{const D=await T.put(`/mods/${encodeURIComponent(C.id)}`,{enabled:!C.enabled});c(Y=>Y.map(O=>O.id===C.id?D:O)),a.success(`Mod ${D.enabled?"enabled":"disabled"}.`)}catch(D){a.error(`Toggle failed: ${D.message}`)}},P=n.find(C=>C.id===x)||null;return o?e.jsx("div",{className:"view-loading",children:e.jsx(oe,{size:"lg"})}):e.jsxs("div",{className:"view view-mods",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(ts,{size:18})," Mods (",n.length,")"]}),e.jsxs("p",{className:"view-subtitle",children:["Extensions installed in ",e.jsx("code",{children:"~/.config/bizar/mods/"}),". Mods can add agents, commands, routes, and views."]})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs($,{variant:"secondary",size:"sm",onClick:L,children:[e.jsx(de,{size:14})," Refresh"]}),e.jsxs($,{variant:"primary",size:"sm",onClick:R,children:[e.jsx(ze,{size:14})," Install mod"]})]})]}),n.length===0?e.jsx(pe,{icon:e.jsx(ts,{size:32}),title:"No mods installed",message:"Mods are folders with a mod.json. Install one to extend Bizar with custom agents, commands, and views."}):e.jsxs("div",{className:"mods-layout",children:[e.jsx("div",{className:"mods-list",children:n.map(C=>e.jsxs("div",{className:V("mod-list-item",x===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:()=>A(C),children:e.jsx(St,{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(ke,{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(Rl,{mod:P})]}),e.jsxs(G,{className:"mods-registry-card",children:[e.jsxs("button",{type:"button",className:"mods-registry-head","aria-expanded":g,"aria-controls":"mods-registry-body",onClick:()=>{!k&&!N&&b(),j(C=>!C)},children:[e.jsx(vs,{size:14,"aria-hidden":!0}),e.jsx("span",{className:"mods-registry-title",children:"Mod registry"}),e.jsx("span",{className:"muted",style:{fontSize:11},children:k!=null&&k.mods?`${k.mods.length} available`:"click to browse"}),e.jsx("span",{className:"mods-registry-spacer"}),g?e.jsx(We,{size:14,"aria-hidden":!0}):e.jsx(Xe,{size:14,"aria-hidden":!0})]}),g&&e.jsx("div",{id:"mods-registry-body",className:"mods-registry-body",children:N?e.jsx("div",{className:"muted",style:{padding:12,fontSize:12},children:"Loading registry…"}):k!=null&&k.error?e.jsxs("div",{className:"mods-registry-error",children:[e.jsx(Ms,{size:12})," Could not load registry: ",k.error]}):!k||k.mods.length===0?e.jsx("div",{className:"muted",style:{padding:12,fontSize:12},children:"No mods listed in the registry yet."}):e.jsxs(e.Fragment,{children:[k.source&&e.jsxs("div",{className:"muted",style:{fontSize:11,marginBottom:8},children:["Source: ",e.jsx("code",{children:k.source})]}),e.jsx("div",{className:"mods-registry-grid",children:k.mods.map(C=>{const D=n.some(O=>O.id===C.id),Y=!!E[C.id];return e.jsxs("div",{className:"mod-registry-card",children:[e.jsxs("div",{className:"mod-registry-card-head",children:[e.jsx("div",{className:"mod-registry-card-name",children:C.name}),C.latest&&e.jsxs("span",{className:V("mod-registry-version",C.upgradeAvailable&&"mod-registry-version-upgrade"),children:["v",C.latest,C.upgradeAvailable?" ↑":""]})]}),C.description&&e.jsx("div",{className:"mod-registry-card-desc",children:C.description}),e.jsxs("div",{className:"mod-registry-card-meta",children:[C.author&&e.jsxs("span",{className:"muted",children:["by ",C.author]}),C.homepage&&e.jsx("a",{href:C.homepage,target:"_blank",rel:"noopener noreferrer",className:"mod-registry-link",children:"homepage"})]}),(C.permissions||[]).length>0&&e.jsxs("div",{className:"mod-registry-perms",children:[e.jsx(Ms,{size:10}),(C.permissions||[]).slice(0,4).map(O=>e.jsx("span",{className:"mod-registry-perm",children:O},O)),(C.permissions||[]).length>4&&e.jsxs("span",{className:"mod-registry-perm-more",children:["+",C.permissions.length-4]})]}),e.jsxs("div",{className:"mod-registry-card-actions",children:[!D&&e.jsx($,{variant:"primary",size:"sm",disabled:Y,onClick:()=>w(C.id),title:"Install from registry",children:Y?e.jsx(oe,{size:"sm"}):e.jsxs(e.Fragment,{children:[e.jsx(ls,{size:12})," Install"]})}),D&&C.upgradeAvailable&&e.jsx($,{variant:"primary",size:"sm",disabled:Y,onClick:()=>f(C.id),title:`Upgrade from v${C.installedVersion||"?"} to v${C.upgradeAvailable}`,children:Y?e.jsx(oe,{size:"sm"}):e.jsxs(e.Fragment,{children:[e.jsx(ls,{size:12})," Upgrade to v",C.upgradeAvailable]})}),D&&!C.upgradeAvailable&&e.jsxs($,{variant:"ghost",size:"sm",disabled:!0,title:`Installed v${C.installedVersion||"?"}`,children:["Installed v",C.installedVersion||"?"]})]})]},C.id)})})]})})]}),u.length>0&&e.jsxs(G,{className:"mod-views-hint",children:[e.jsxs(te,{children:[e.jsx(vs,{size:14})," Mod views"]}),e.jsxs(ne,{children:[u.length," mod-supplied view",u.length===1?"":"s"," are now available in the sidebar navigation. Look for the ",e.jsx("strong",{children:"Mods"})," section at the bottom of the sidebar."]})]}),m&&e.jsxs("div",{className:"mod-iframe-panel",children:[e.jsxs("div",{className:"mod-iframe-header",children:[e.jsxs("span",{children:["Mod view — ",e.jsx("a",{href:m,target:"_blank",rel:"noreferrer",children:m})]}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Close iframe",onClick:()=>h(null),children:e.jsx(Ne,{size:14})})]}),e.jsx("iframe",{src:m,className:"mod-iframe",title:"Mod view",sandbox:"allow-scripts allow-same-origin allow-forms allow-popups"})]})]})}function Rl({mod:s}){const t=re(),[a,i]=r.useState(null),[n,c]=r.useState(!1),[o,l]=r.useState(!1),[x,p]=r.useState(null),u=async()=>{c(!0);try{const m=await T.get(`/mods/${s.id}/instructions`);i(m),l(!0)}catch(m){t.error(`Failed to load instructions: ${m.message}`)}finally{c(!1)}},d=async()=>{try{const m=await T.post(`/mods/${s.id}/instructions/reinstall`,{});t.success(`Reinstalled: ${m.counts.agents} agents, ${m.counts.commands} commands, ${m.counts.skills} skills, ${m.counts.instructions} instructions.`),await u()}catch(m){t.error(`Reinstall failed: ${m.message}`)}};return e.jsxs(G,{className:"mod-details",children:[e.jsxs(te,{children:[e.jsx(be,{size:14})," Mod details — ",s.name]}),e.jsx(ne,{children:e.jsx("code",{children:s.path})}),e.jsxs("dl",{className:"env-table",children:[e.jsx("dt",{children:"ID"}),e.jsx("dd",{className:"mono",children:s.id}),e.jsx("dt",{children:"Version"}),e.jsx("dd",{className:"mono",children:s.version}),e.jsx("dt",{children:"Type"}),e.jsx("dd",{className:"mono",children:s.type}),e.jsx("dt",{children:"Author"}),e.jsx("dd",{className:"mono",children:s.author||"—"}),e.jsx("dt",{children:"Bizar"}),e.jsx("dd",{className:"mono",children:s.bizar||"*"}),e.jsx("dt",{children:"Enabled"}),e.jsx("dd",{children:s.enabled?"yes":"no"}),e.jsx("dt",{children:"Permissions"}),e.jsxs("dd",{children:[(s.permissions||[]).map(m=>e.jsx("span",{className:"tag",children:m},m)),(s.permissions||[]).length===0&&e.jsx("span",{className:"muted",children:"(none)"})]})]}),e.jsxs("div",{className:"mod-files",children:[e.jsx("div",{className:"muted",children:"Files"}),e.jsx("ul",{children:(s.files||[]).map(m=>e.jsxs("li",{children:[e.jsx("span",{className:"mod-file-cat",children:m.category}),e.jsx("span",{className:"mono",children:m.path})]},m.path))})]}),e.jsxs("div",{className:"mod-instructions",children:[e.jsxs("button",{type:"button",className:"mod-instructions-head","aria-expanded":o,"aria-controls":`mod-instructions-body-${s.id}`,onClick:()=>{!a&&!n&&u(),l(m=>!m)},children:[e.jsx(Rn,{size:14,"aria-hidden":!0}),e.jsx("span",{children:"Installed instructions"}),e.jsx("span",{className:"muted",style:{fontSize:11},children:a?`${a.total} files`:"click to view"}),e.jsx("span",{className:"mod-instructions-spacer"}),o?e.jsx(We,{size:14,"aria-hidden":!0}):e.jsx(Xe,{size:14,"aria-hidden":!0})]}),o&&a&&e.jsxs("div",{id:`mod-instructions-body-${s.id}`,className:"mod-instructions-body",children:[a.agents.length>0&&e.jsxs("div",{className:"mod-instructions-section",children:[e.jsxs("div",{className:"mod-instructions-section-title",children:[e.jsx($n,{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(h=>h===m.filename?null:m.filename),children:[e.jsx("span",{className:"mono",children:m.filename}),e.jsxs("span",{className:"muted",style:{fontSize:10},children:["installed at ",m.fullPath]})]}),x===m.filename&&e.jsx("pre",{className:"mod-instructions-content",children:m.content||e.jsx("em",{className:"muted",children:"(file missing on disk)"})})]},m.filename))]}),a.commands.length>0&&e.jsxs("div",{className:"mod-instructions-section",children:[e.jsxs("div",{className:"mod-instructions-section-title",children:[e.jsx(ns,{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(h=>h===m.filename?null:m.filename),children:[e.jsx("span",{className:"mono",children:m.filename}),e.jsxs("span",{className:"muted",style:{fontSize:10},children:["installed at ",m.fullPath]})]}),x===m.filename&&e.jsx("pre",{className:"mod-instructions-content",children:m.content||e.jsx("em",{className:"muted",children:"(file missing on disk)"})})]},m.filename))]}),a.skills.length>0&&e.jsxs("div",{className:"mod-instructions-section",children:[e.jsxs("div",{className:"mod-instructions-section-title",children:[e.jsx(ha,{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(h=>h===m.name?null:m.name),children:[e.jsx("span",{className:"mono",children:m.name}),e.jsxs("span",{className:"muted",style:{fontSize:10},children:["installed at ",m.fullPath]})]}),x===m.name&&e.jsx("pre",{className:"mod-instructions-content",children:m.content||e.jsx("em",{className:"muted",children:"(file missing on disk)"})})]},m.name))]}),a.total===0&&e.jsxs("div",{className:"muted",style:{padding:8,fontSize:12},children:["This mod did not install any instruction files. Mods install instructions by shipping a top-level ",e.jsx("code",{children:"INSTRUCTIONS.md"}),", an ",e.jsx("code",{children:"agents/"})," directory, a ",e.jsx("code",{children:"commands/"})," directory, or a ",e.jsx("code",{children:"skills/"})," directory."]}),e.jsx("div",{className:"mod-instructions-actions",children:e.jsxs($,{variant:"ghost",size:"sm",onClick:d,children:[e.jsx(de,{size:11})," Reinstall from mod folder"]})})]})]})]})}const $l=r.forwardRef(function({className:t,checked:a,onChange:i,onClick:n,...c},o){return e.jsxs("label",{className:V("toggle",t),children:[e.jsx("input",{ref:o,type:"checkbox",role:"switch","aria-checked":a,checked:a,onChange:l=>i==null?void 0:i(l.target.checked),onClick:l=>{n==null||n(l)},...c}),e.jsx("span",{className:"toggle-slider","aria-hidden":!0})]})}),Al={net:{label:"Network access",icon:vs,color:"blue",description:"Can make HTTP requests to external services"},fs:{label:"Filesystem",icon:be,color:"yellow",description:"Can read and write files"},config:{label:"Config access",icon:xa,color:"gray",description:"Can read and write Bizar config"},log:{label:"Logging",icon:be,color:"gray",description:"Can write to the structured log"},exec:{label:"Shell execution",icon:ns,color:"red",description:"Can run shell commands"}};function Ml({permissions:s}){return e.jsx("div",{className:"plugin-permissions","aria-label":"Required permissions",children:s.map(t=>{const a=Al[t]??{label:t,icon:Tt,color:"gray",description:""},i=a.icon;return e.jsxs("div",{className:`permission-chip is-${a.color}`,title:a.description,children:[e.jsx(i,{size:12,"aria-hidden":!0}),e.jsx("span",{children:a.label})]},t)})})}function Il({plugin:s,onToggle:t,onUninstall:a,onConfigure:i}){return e.jsxs(G,{children:[e.jsxs("div",{className:"plugin-card-head",children:[e.jsxs("div",{children:[e.jsx(te,{children:s.name}),e.jsxs(ne,{children:["v",s.version," · ",s.id]})]}),e.jsx($l,{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(Ml,{permissions:s.permissions??[]}),e.jsxs("div",{className:"plugin-card-actions",children:[e.jsx($,{size:"sm",onClick:()=>i(s.id),"aria-label":`Configure ${s.name}`,children:"Configure"}),e.jsx($,{size:"sm",variant:"danger",onClick:()=>a(s.id),"aria-label":`Uninstall ${s.name}`,children:"Uninstall"})]}),e.jsxs("div",{className:"plugin-card-stats",children:[s.invocations??0," invocations",s.lastInvokedAt?` · last used ${s.lastInvokedAt}`:" · never used"]})]})}function El({setActiveTab:s}){const t=re(),[a,i]=r.useState([]),[n,c]=r.useState(!0),[o,l]=r.useState(""),x=async()=>{try{const h=await T.get("/plugins/installed");i(h.plugins)}catch(h){t.error(`Failed to load plugins: ${h.message}`)}finally{c(!1)}};r.useEffect(()=>{x()},[]);const p=async h=>{try{await T.post(`/plugins/${h}/toggle`).catch(()=>{}),await x(),t.success("Plugin toggled.")}catch(g){t.error(`Toggle failed: ${g.message}`)}},u=async h=>{if(confirm("Uninstall this plugin?"))try{await T.del(`/plugins/${h}`),await x(),t.success("Plugin uninstalled.")}catch(g){t.error(`Uninstall failed: ${g.message}`)}},d=h=>{};if(n)return e.jsx("div",{className:"view-loading",children:e.jsx(oe,{size:"lg"})});const m=a.filter(h=>h.name.toLowerCase().includes(o.toLowerCase()));return e.jsxs("div",{className:"view view-plugins",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(ts,{size:18,"aria-hidden":!0}),"Plugins (",a.length,")"]}),e.jsx("p",{className:"view-subtitle",children:"Manage plugins installed via the marketplace."})]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:()=>s("marketplace"),children:[e.jsx(na,{size:14,"aria-hidden":!0}),"Browse Marketplace"]})]}),a.length===0?e.jsx(pe,{icon:e.jsx(ts,{size:32}),title:"No plugins installed",message:"Browse the marketplace to discover and install plugins."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"plugins-toolbar",children:e.jsx("input",{className:"input",type:"search",placeholder:"Filter plugins…",value:o,onChange:h=>l(h.target.value),"aria-label":"Filter plugins",style:{maxWidth:320}})}),e.jsx("div",{className:"plugin-grid",children:m.map(h=>e.jsx(Il,{plugin:h,onToggle:p,onUninstall:u,onConfigure:d},h.id))})]})]})}function Ll({viewId:s,reloadKey:t,setActiveTab:a}){const i=re(),[n,c]=r.useState(null),[o,l]=r.useState(!0),[x,p]=r.useState(0);if(r.useEffect(()=>{let u=!1;return(async()=>{try{const d=await T.get("/mods/views");if(u)return;const m=(d.views||[]).find(h=>h.id===s);c(m||null)}catch(d){i.error(`Failed to load mod view: ${d.message}`)}finally{u||l(!1)}})(),()=>{u=!0}},[s,i]),o)return e.jsx(pe,{title:"Loading mod view…"});if(!n)return e.jsx(pe,{title:"Mod view not found",message:`No view with id "${s}" is currently installed.`,action:e.jsx($,{onClick:()=>a("mods"),variant:"primary",size:"sm",children:"Open Mods"})});if(n.kind==="iframe"){const u=`/api/mods/${n.modId}/web/index.html?t=${x+(t||0)}`;return e.jsxs("div",{className:"mod-view-iframe-pane",children:[e.jsxs("div",{className:"mod-view-iframe-header",children:[e.jsxs("span",{className:"mod-view-iframe-label",children:[e.jsx(vs,{size:14}),n.label,e.jsxs("span",{className:"muted",style:{fontSize:11,fontWeight:400},children:["by ",n.modId]})]}),e.jsxs("div",{className:"mod-view-iframe-actions",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>p(d=>d+1),title:"Reload this view",children:[e.jsx(de,{size:11})," Reload"]}),e.jsx("a",{href:u,target:"_blank",rel:"noopener noreferrer",className:"icon-btn",title:"Open in new tab",children:e.jsx(ys,{size:12})})]})]}),e.jsx("iframe",{src:u,className:"mod-view-iframe",title:n.label},x+(t||0))]})}if(n.component){const u=n.component,d=n.modId,m=r.lazy(()=>qa(()=>import(`/api/mods/${encodeURIComponent(d)}/views/${encodeURIComponent(u)}`),[]).then(h=>({default:h.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(Is,{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(Dl,{modId:n.modId,component:n.component,children:e.jsx(r.Suspense,{fallback:e.jsxs("div",{style:{padding:24},children:[e.jsx(oe,{size:"md"})," ",e.jsx("span",{className:"muted",children:"Loading mod view…"})]}),children:e.jsx(m,{})})})})]})}return e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsx(Is,{size:14})," ",n.label]}),e.jsxs(ne,{children:["by ",n.modId]}),n.description&&e.jsx("p",{className:"muted",style:{marginTop:8},children:n.description}),e.jsxs("p",{className:"muted",style:{fontSize:12,marginTop:12},children:["This mod declared a tab view but did not provide a component path in views/registry.json. Add a ",e.jsx("code",{children:"component"})," field (e.g. ",e.jsx("code",{children:'"MyView.js"'}),") and ship the file under ",e.jsx("code",{children:"views/"}),"."]}),e.jsx("div",{style:{marginTop:12},children:e.jsx($,{variant:"secondary",size:"sm",onClick:()=>a("mods"),children:"Open Mods page"})})]})}class Dl extends r.Component{constructor(){super(...arguments);ks(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(Te,{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 Pl(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 Fl({template:s,onUse:t}){return e.jsxs(G,{className:"schedule-template-card",children:[e.jsxs("div",{className:"schedule-template-header",children:[e.jsx(te,{children:s.name}),s.tags&&s.tags.length>0&&e.jsx("div",{className:"schedule-template-tags",children:s.tags.map(a=>e.jsx("span",{className:"tag",children:a},a))})]}),e.jsx(ne,{children:s.description}),e.jsxs("div",{className:"schedule-template-summary",children:[e.jsx("code",{children:Pl(s)})," · ",e.jsx("code",{children:s.action.type})]}),e.jsx($,{variant:"secondary",size:"sm",onClick:()=>t(s),"aria-label":`Use template: ${s.name}`,children:"Use this template"})]})}const Ol=["interval","cron","once"],Bl=["command","agent","webhook"],yt=[{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)"}],Ul=Array.from({length:12},(s,t)=>t*5),Lt=Array.from({length:24},(s,t)=>({value:t,label:t===0?"12 AM":t<12?`${t} AM`:t===12?"12 PM":`${t-12} PM`})),Dt=[{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"}],Ta=[{value:"s",label:"seconds"},{value:"m",label:"minutes"},{value:"h",label:"hours"},{value:"d",label:"days"}];function Ra(s){if(typeof s!="string")return null;const t=s.trim().split(/\s+/);if(t.length!==5)return null;const[a,i,,,n]=t,c=parseInt(a,10),o=parseInt(i,10);if(!Number.isFinite(c)||!Number.isFinite(o)||a!==String(c)||i!==String(o))return null;const l=n==="*"?"*":parseInt(n,10);return l===null||n!=="*"&&!Number.isFinite(l)?null:{minute:c,hour:o,dow:n==="*"?"*":String(l)}}function _l(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 Wl(s){var c,o;if(!s)return{name:"",type:"cron",cronMinute:0,cronHour:13,cronDow:"0",showAdvanced:!1,rawCron:"0 13 * * 0",intervalN:30,intervalUnit:"m",onceAt:"",timezone:"UTC",customTimezone:"",actionType:"agent",actionTarget:"",actionPrompt:"",skipIfBudgetLow:!1,maxConcurrent:6,enabled:!0,humanLabel:""};const t=s.type==="cron"?Ra(s.schedule):null,a=s.type==="interval"?_l(s.schedule):null,i=s.timezone||"UTC",n=yt.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:!!((c=s.budgetCheck)!=null&&c.skipIfBudgetLow),maxConcurrent:Number.isFinite((o=s.budgetCheck)==null?void 0:o.maxConcurrent)?s.budgetCheck.maxConcurrent:6,enabled:s.enabled!==!1,humanLabel:""}}function 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 Vl(s){var a,i,n;if(s.type==="cron"){if(s.showAdvanced)return{schedule:s.rawCron.trim(),humanLabel:s.humanLabel||s.rawCron.trim()};const c=`${s.cronMinute} ${s.cronHour} * * ${s.cronDow}`,o=((a=Dt.find(u=>u.value===s.cronDow))==null?void 0:a.label)||"",l=((i=Lt.find(u=>u.value===s.cronHour))==null?void 0:i.label)||`${s.cronHour}`,x=String(s.cronMinute).padStart(2,"0"),p=o==="Every day"?`Every day at ${l.replace(" ","")} (min ${x})`:`Every ${o} at ${l.replace(" ","")} (min ${x})`;return{schedule:c,humanLabel:s.humanLabel||p}}if(s.type==="interval"){const c=((n=Ta.find(l=>l.value===s.intervalUnit))==null?void 0:n.label)||s.intervalUnit;return{schedule:`${s.intervalN}${s.intervalUnit}`,humanLabel:s.humanLabel||`Every ${s.intervalN} ${c}`}}return s.onceAt?{schedule:new Date(s.onceAt).toISOString(),humanLabel:s.humanLabel||new Date(s.onceAt).toLocaleString()}:{schedule:"",humanLabel:s.humanLabel||""}}function Hl({snapshot:s,refreshSnapshot:t}){var E;const a=re(),i=$e(),[n,c]=r.useState(s.schedules||[]),[o,l]=r.useState(!s.schedules),[x,p]=r.useState("schedules"),[u,d]=r.useState([]),[m,h]=r.useState(!1),g=async()=>{try{const v=await T.get("/projects/active/schedules");c(v.schedules||[])}catch(v){a.error(`Schedules load failed: ${v.message}`)}finally{l(!1)}},j=async()=>{h(!0);try{const v=await T.get("/schedules/templates");d(v.templates||[])}catch(v){a.error(`Templates load failed: ${v.message}`)}finally{h(!1)}};r.useEffect(()=>{var v;if((v=s.schedules)!=null&&v.length||s.schedules){c(s.schedules||[]),l(!1);return}g()},[s.schedules]),r.useEffect(()=>{x==="templates"&&u.length===0&&j()},[x]);const k=v=>{i.open({title:v?`Edit schedule: ${v.name}`:"New schedule",width:640,children:e.jsx(Gl,{initial:v,onClose:i.close,onSubmitted:async b=>{c(w=>{const f=w.findIndex(R=>R.id===b.id);if(f===-1)return[...w,b];const L=w.slice();return L[f]=b,L}),a.success(v?"Schedule updated.":"Schedule created."),i.close(),await t()},onError:b=>a.error(b)})})},z=async v=>{var b;try{const w=await T.post(`/schedules/${encodeURIComponent(v.id)}/run`);a.success(w.ok?"Schedule ran.":`Run failed: ${((b=w.runResult)==null?void 0:b.error)||"unknown"}`),await g()}catch(w){a.error(`Run failed: ${w.message}`)}},N=async v=>{if(confirm(`Delete schedule "${v.name}"?`))try{await T.del(`/schedules/${encodeURIComponent(v.id)}`),c(b=>b.filter(w=>w.id!==v.id)),a.success("Schedule deleted.")}catch(b){a.error(`Delete failed: ${b.message}`)}},S=async v=>{try{const b=await T.post("/schedules/from-template",{templateId:v.id});c(w=>[...w,b]),p("schedules"),a.success(`Schedule "${b.name}" created from template.`),await t()}catch(b){a.error(`Failed to create schedule: ${b.message}`)}};return o?e.jsx("div",{className:"view-loading",children:e.jsx(oe,{size:"lg"})}):e.jsxs("div",{className:"view view-schedules",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("div",{className:"view-title-row",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(as,{size:18})," Schedules"]}),e.jsxs("div",{className:"view-section-tabs",children:[e.jsxs("button",{type:"button",className:`tab-btn ${x==="schedules"?"tab-btn-active":""}`,onClick:()=>p("schedules"),children:["Schedules (",n.length,")"]}),e.jsxs("button",{type:"button",className:`tab-btn ${x==="templates"?"tab-btn-active":""}`,onClick:()=>p("templates"),children:[e.jsx(Is,{size:14})," Templates"]})]})]}),e.jsx("p",{className:"view-subtitle",children:x==="schedules"?e.jsxs(e.Fragment,{children:["Recurring tasks for ",e.jsx("strong",{children:((E=s.activeProject)==null?void 0:E.name)||"(none)"}),". Service daemon runs them at the right time."]}):"Example schedules you can use as a starting point."})]}),e.jsxs("div",{className:"view-actions",children:[x==="schedules"&&e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"secondary",size:"sm",onClick:g,"aria-label":"Refresh schedules",children:[e.jsx(de,{size:14})," Refresh"]}),e.jsxs($,{variant:"primary",size:"sm",onClick:()=>k(),children:[e.jsx(ze,{size:14})," New schedule"]})]}),x==="templates"&&e.jsxs($,{variant:"secondary",size:"sm",onClick:j,disabled:m,children:[e.jsx(de,{size:14})," Refresh"]})]})]}),x==="templates"?m?e.jsx("div",{className:"view-loading",children:e.jsx(oe,{size:"lg"})}):u.length===0?e.jsx(pe,{icon:e.jsx(Is,{size:32}),title:"No templates",message:"No schedule templates found. Templates are loaded from templates/schedules/."}):e.jsx("div",{className:"schedule-template-grid",children:u.map(v=>e.jsx(Fl,{template:v,onUse:S},v.id))}):n.length===0?e.jsx(pe,{icon:e.jsx(as,{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(v=>{var b;return e.jsxs(G,{className:"schedule-card",children:[e.jsxs("div",{className:"schedule-card-head",children:[e.jsxs("div",{children:[e.jsx(te,{children:v.name}),e.jsxs(ne,{children:[e.jsx("code",{children:v.type})," ·"," ",e.jsx("span",{title:v.schedule,children:Kl(v)||v.schedule}),v.timezone&&v.timezone!=="UTC"?e.jsxs(e.Fragment,{children:[" · ",e.jsx("code",{children:v.timezone})]}):null," · ",e.jsx("span",{className:v.enabled?"status-on":"status-neutral",children:v.enabled?"enabled":"disabled"})]})]}),e.jsxs("div",{className:"schedule-card-actions",children:[e.jsxs($,{variant:"secondary",size:"sm",onClick:()=>k(v),children:[e.jsx(Es,{size:12})," Edit"]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:()=>z(v),children:[e.jsx(ft,{size:12})," Run now"]}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger","aria-label":"Delete",title:"Delete",onClick:()=>N(v),children:e.jsx(ke,{size:12})})]})]}),e.jsxs("div",{className:"schedule-card-action",children:[e.jsx("span",{className:"muted",children:"action:"})," ",e.jsxs("code",{children:[v.action.type," ",v.action.target]}),v.action.type==="agent"&&v.action.prompt&&e.jsxs("div",{className:"schedule-card-prompt",children:[e.jsx("span",{className:"muted",children:"prompt:"})," ",v.action.prompt]})]}),((b=v.budgetCheck)==null?void 0:b.skipIfBudgetLow)&&e.jsxs("div",{className:"schedule-card-budget",children:[e.jsx("span",{className:"muted",children:"budget gate:"})," ","skip if concurrent ≥ ",v.budgetCheck.maxConcurrent??6]}),e.jsxs("div",{className:"schedule-card-times",children:[e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"last"})," ",v.lastRun?Ce(v.lastRun):"—",v.lastResult&&e.jsx("span",{className:`tag ${Ht(v.lastResult)}`,children:v.lastResult}),v.lastError&&e.jsxs("span",{className:"muted schedule-card-error",title:v.lastError,children:[" ","— ",Gt(v.lastError,80)]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"next"})," ",v.nextRun?e.jsx("span",{title:new Date(v.nextRun).toISOString(),children:Yl(v.nextRun,v.timezone)}):"—",v.nextRun&&e.jsxs("span",{className:"muted",children:[" · ",Ce(v.nextRun)]})]})]}),v.history&&v.history.length>0&&e.jsxs("details",{className:"schedule-card-history",children:[e.jsxs("summary",{children:[e.jsx($s,{size:12})," ",v.history.length," run",v.history.length===1?"":"s"]}),e.jsx("ul",{children:v.history.slice(-10).reverse().map((w,f)=>e.jsxs("li",{children:[e.jsx("span",{className:"tabular-nums muted",children:Ce(w.ts)})," ",e.jsx("span",{className:`tag ${Ht(w.result)}`,children:w.result}),w.error&&e.jsxs("span",{className:"muted",children:[" — ",Gt(w.error,80)]})]},f))})]})]},v.id)})})]})}function Gl({initial:s,onClose:t,onSubmitted:a,onError:i}){const[n,c]=r.useState(()=>Wl(s)),[o,l]=r.useState(!1),x=r.useMemo(()=>yt.some(d=>d.value===n.timezone)?n.timezone:"Other…",[n.timezone]),p=(d,m)=>{c(h=>({...h,[d]:m}))},u=async d=>{d.preventDefault();const m=n.name.trim();if(!m){i("Name is required.");return}const h=Vl(n);if(!h.schedule){i("Schedule value is required.");return}if(!n.actionTarget.trim()){i("Action target is required.");return}const g=n.timezone==="Other…"?n.customTimezone.trim():n.timezone,j={type:n.actionType,target:n.actionTarget.trim()};n.actionType==="agent"&&n.actionPrompt.trim()&&(j.prompt=n.actionPrompt.trim());const k={name:m,type:n.type,schedule:h.schedule,timezone:g||"UTC",action:j,budgetCheck:{maxConcurrent:n.maxConcurrent,skipIfBudgetLow:n.skipIfBudgetLow},enabled:n.enabled};l(!0);try{const z=s?await T.put(`/schedules/${encodeURIComponent(s.id)}`,k):await T.post("/schedules",k);await a(z)}catch(z){i(`${s?"Update":"Create"} failed: ${z.message}`)}finally{l(!1)}};return e.jsxs("form",{className:"schedule-form",onSubmit:u,children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-name",children:"Name"}),e.jsx("input",{id:"schedule-name",className:"input",type:"text",placeholder:"Weekly code review",value:n.name,onChange:d=>p("name",d.target.value),autoFocus:!0}),e.jsx("div",{className:"task-form-row",children:e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-type",children:"Type"}),e.jsx("select",{id:"schedule-type",className:"select",value:n.type,onChange:d=>p("type",d.target.value),children:Ol.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:Dt.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:Lt.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:Ul.map(d=>e.jsx("option",{value:String(d),children:String(d).padStart(2,"0")},d))})]})]})}),n.showAdvanced&&e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-cron-expr",children:"Cron expression"}),e.jsx("input",{id:"schedule-cron-expr",className:"input",type:"text",value:n.rawCron,onChange:d=>p("rawCron",d.target.value),placeholder:"0 13 * * 0"})]}),e.jsxs("button",{type:"button",className:"link-btn",onClick:()=>p("showAdvanced",!n.showAdvanced),"aria-expanded":n.showAdvanced,children:[e.jsx(We,{size:12,style:{transform:n.showAdvanced?"rotate(180deg)":"none",transition:"transform 0.15s"}}),n.showAdvanced?"Hide advanced":"Advanced (raw cron)"]})]}),n.type==="interval"&&e.jsxs("div",{className:"task-form-row",children:[e.jsxs("div",{className:"task-form-field",style:{flex:1},children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-interval-n",children:"Every"}),e.jsx("input",{id:"schedule-interval-n",className:"input",type:"number",min:1,value:n.intervalN,onChange:d=>p("intervalN",parseInt(d.target.value,10)||1)})]}),e.jsxs("div",{className:"task-form-field",style:{flex:1},children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-interval-unit",children:"Unit"}),e.jsx("select",{id:"schedule-interval-unit",className:"select",value:n.intervalUnit,onChange:d=>p("intervalUnit",d.target.value),children:Ta.map(d=>e.jsx("option",{value:d.value,children:d.label},d.value))})]})]}),n.type==="once"&&e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-once-at",children:"Run at"}),e.jsx("input",{id:"schedule-once-at",className:"input",type:"datetime-local",value:n.onceAt,onChange:d=>p("onceAt",d.target.value)})]}),e.jsxs("div",{className:"task-form-row",children:[e.jsxs("div",{className:"task-form-field",style:{flex:1},children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-timezone",children:"Timezone"}),e.jsxs("select",{id:"schedule-timezone",className:"select",value:x,onChange:d=>p("timezone",d.target.value),children:[yt.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:Bl.map(d=>e.jsx("option",{value:d,children:d},d))})]}),e.jsxs("div",{className:"task-form-field",style:{flex:2},children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-action-target",children:"Target"}),e.jsx("input",{id:"schedule-action-target",className:"input",type:"text",placeholder:n.actionType==="webhook"?"https://...":n.actionType==="agent"?"agent name or task ref":"echo hi",value:n.actionTarget,onChange:d=>p("actionTarget",d.target.value)})]})]}),n.actionType==="agent"&&e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-action-prompt",children:"Prompt (what to send the agent)"}),e.jsx("textarea",{id:"schedule-action-prompt",className:"input",rows:3,placeholder:"Review open PRs for stale code review comments and nudge reviewers.",value:n.actionPrompt,onChange:d=>p("actionPrompt",d.target.value)})]}),e.jsxs("fieldset",{className:"schedule-budget-card",children:[e.jsx("legend",{children:"Budget pre-flight"}),e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{id:"schedule-skip-budget",type:"checkbox",checked:n.skipIfBudgetLow,onChange:d=>p("skipIfBudgetLow",d.target.checked)}),e.jsx("span",{children:"Skip this run when too many background tasks are already running."})]}),e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-max-concurrent",children:"Max concurrent bg tasks"}),e.jsx("input",{id:"schedule-max-concurrent",className:"input",type:"number",min:1,max:64,value:n.maxConcurrent,onChange:d=>p("maxConcurrent",parseInt(d.target.value,10)||6),disabled:!n.skipIfBudgetLow})]})]}),e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{id:"schedule-enabled",type:"checkbox",checked:n.enabled,onChange:d=>p("enabled",d.target.checked)}),e.jsx("span",{children:"Enabled"})]}),e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx($,{variant:"ghost",type:"button",onClick:t,disabled:o,children:"Cancel"}),e.jsx($,{variant:"primary",type:"submit",disabled:o,children:s?"Save":"Create"})]})]})}function Kl(s){var c,o;if(s.type!=="cron")return s.schedule;const t=Ra(s.schedule);if(!t)return s.schedule;const a=((c=Dt.find(l=>l.value===t.dow))==null?void 0:c.label)||"",i=((o=Lt.find(l=>l.value===t.hour))==null?void 0:o.label)||`${t.hour}`,n=String(t.minute).padStart(2,"0");return a==="Every day"?`Every day at ${i} :${n}`:`Every ${a} at ${i} :${n}`}function Yl(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 Ht(s){return s==="success"?"tag-success":s==="skipped"?"tag-warning":"tag-error"}function Gt(s,t){return s.length<=t?s:s.slice(0,t-1)+"…"}const Xl=[{id:"all",label:"All",icon:He},{id:"shipped",label:"Shipped",icon:$t},{id:"user",label:"User",icon:Ks},{id:"project",label:"Project",icon:Fe}],Vs={shipped:"Shipped",user:"User",project:"Project"},Jl={shipped:$t,user:Ks,project:Fe};function Ql({snapshot:s,refreshSnapshot:t}){const a=re(),i=$e(),[n,c]=r.useState([]),[o,l]=r.useState({shipped:0,user:0,project:0,all:0}),[x,p]=r.useState(!0),[u,d]=r.useState("all"),[m,h]=r.useState(""),[g,j]=r.useState(null),[k,z]=r.useState(!1),N=async()=>{var b,w,f;p(!0);try{const L=await T.get("/skills");c(L.skills||[]),l({shipped:((b=L.counts)==null?void 0:b.shipped)??0,user:((w=L.counts)==null?void 0:w.user)??0,project:((f=L.counts)==null?void 0:f.project)??0,all:(L.skills||[]).length})}catch(L){a.error(`Skills load failed: ${L.message}`)}finally{p(!1)}};r.useEffect(()=>{N()},[]),r.useEffect(()=>{if(!m.trim()){j(null);return}z(!0);const b=setTimeout(async()=>{try{const w=await T.get(`/skills/search?q=${encodeURIComponent(m.trim())}`);j(w.results||[])}catch(w){a.error(`Search failed: ${w.message}`)}finally{z(!1)}},280);return()=>clearTimeout(b)},[m]);const S=r.useMemo(()=>g!==null?g:u==="all"?n:n.filter(b=>b.source===u),[n,u,g]),E=async()=>{try{await T.post("/skills/refresh",{}),a.success("Skills refreshed."),await N()}catch(b){a.error(`Refresh failed: ${b.message}`)}},v=async b=>{try{const w=await T.get(`/skills/${encodeURIComponent(b.source)}/${encodeURIComponent(b.name)}`);i.open({title:w.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":w.source,children:Vs[w.source]||w.source}),e.jsx("code",{className:"mono text-sm muted",children:w.path})]}),w.description&&e.jsx("p",{className:"skill-detail-desc",children:w.description}),w.body&&e.jsx("div",{className:"skill-detail-body",children:e.jsx("pre",{className:"skill-body-pre",children:w.body})})]}),footer:e.jsx($,{variant:"ghost",onClick:()=>i.close(),children:"Close"})})}catch{i.open({title:b.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":b.source,children:Vs[b.source]||b.source}),e.jsx("code",{className:"mono text-sm muted",children:b.path})]}),b.description&&e.jsx("p",{className:"skill-detail-desc",children:b.description})]}),footer:e.jsx($,{variant:"ghost",onClick:()=>i.close(),children:"Close"})})}};return e.jsxs("div",{className:"view view-skills",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(He,{size:18})," Skills"]}),e.jsx("p",{className:"view-subtitle",children:"Browse all available skills — shipped, user, and project-local."})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs("div",{className:"search-input",children:[e.jsx(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:b=>h(b.target.value),"aria-label":"Search skills"}),m&&e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Clear search",onClick:()=>h(""),children:e.jsx(Qs,{size:12})})]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:E,children:[e.jsx(de,{size:14})," Refresh"]})]})]}),!m.trim()&&e.jsx("div",{className:"skills-tabs",children:Xl.map(b=>{const w=b.icon,f=b.id==="all"?o.all:o[b.id]??0;return e.jsxs("button",{type:"button",className:V("skills-tab",u===b.id&&"skills-tab-active"),onClick:()=>d(b.id),children:[e.jsx(w,{size:14}),e.jsx("span",{children:b.label}),e.jsx("span",{className:"skills-tab-count",children:f})]},b.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",k&&e.jsx(oe,{size:"sm"})]}),k?e.jsx("div",{className:"skills-grid",children:[0,1,2].map(b=>e.jsx("div",{className:"skill-card skill-card-skeleton"},b))}):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((b,w)=>e.jsx(Kt,{skill:b,onShow:()=>v(b),searchQ:m},`search-${w}`))})]}),!m.trim()&&e.jsx("section",{className:"skills-section",children:x?e.jsx("div",{className:"view-loading",children:e.jsx(oe,{size:"lg"})}):S.length===0?e.jsx(pe,{icon:e.jsx(ha,{size:28}),title:"No skills here",message:u==="all"?"No skills found. Install skills with the skills CLI or add SKILL.md files to a skills directory.":`No skills in the ${Vs[u]} tab.`}):e.jsx("div",{className:"skills-grid",children:S.map((b,w)=>e.jsx(Kt,{skill:b,onShow:()=>v(b)},`${b.source}-${b.name}-${w}`))})}),!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 Kt({skill:s,onShow:t,searchQ:a=""}){const i=Jl[s.source]||$t,n=s.description?s.description.length>200?s.description.slice(0,200)+"…":s.description:"No description.";return e.jsxs(G,{variant:"elevated",interactive:!0,className:"skill-card",children:[e.jsxs("div",{className:"skill-card-head",children:[e.jsx("div",{className:"skill-card-icon",style:{background:"color-mix(in srgb, var(--accent) 12%, transparent)"},children:e.jsx(i,{size:18})}),e.jsxs("div",{className:"skill-card-title-area",children:[e.jsx("div",{className:"skill-card-title",children:Zl(s.name,a)}),e.jsx("span",{className:"skill-source-badge","data-source":s.source,children:Vs[s.source]||s.source})]})]}),e.jsx("p",{className:"skill-card-desc",children:n}),e.jsx("div",{className:"skill-card-actions",children:e.jsxs($,{variant:"ghost",size:"sm",onClick:t,children:[e.jsx(ys,{size:12})," View"]})})]})}function Zl(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 eo=Oe.memo(Ql);function so({refreshKey:s,onRefresh:t,setActiveSubPanel:a}){const i=re(),[n,c]=r.useState(null),[o,l]=r.useState(!0),x=async g=>{l(!0);try{const[j,k,z,N]=await Promise.all([T.get("/memory/health",g).catch(()=>null),T.get("/memory/status",g).catch(()=>null),T.get("/memory/lightrag/stats",g).catch(()=>null),T.get("/memory/storage",g).catch(()=>null)]);c({health:j||{score:0,status:"unconfigured",checks:[],message:"memory not initialised"},vault:{exists:!!(k!=null&&k.initialized),vaultRoot:(k==null?void 0:k.vaultRoot)||"",mode:(k==null?void 0:k.mode)||"local-only",noteCount:(k==null?void 0:k.noteCount)||0,totalSize:(N==null?void 0:N.total)||0,folderCount:0,folders:[],lastModified:null,gitClean:(k==null?void 0:k.gitClean)??null,gitBranch:(k==null?void 0:k.branch)||null},lightrag:z||{running:!1,pid:null,host:"127.0.0.1",port:9621,indexedApprox:0,queryCountLast24h:0,lastReindexAt:null},storage:N||{total:0,breakdown:[]}})}catch(j){i.error(`Memory overview failed: ${j.message}`)}finally{l(!1)}};if(r.useEffect(()=>{const g=new AbortController;return x(g.signal),()=>g.abort()},[s]),o&&!n)return e.jsxs("div",{className:"view-loading",children:[e.jsx(oe,{size:"lg"}),e.jsx("p",{children:"Loading memory overview…"})]});if(!n)return e.jsx("div",{className:"muted",children:"No memory data available."});const{health:p,vault:u,lightrag:d,storage:m}=n,h=p.score>=80?"var(--success)":p.score>=50?"var(--warning)":"var(--error)";return e.jsxs("div",{className:"memory-overview",children:[e.jsxs(G,{variant:"elevated",className:"memory-health-hero",children:[e.jsxs("div",{className:"memory-health-score",style:{borderColor:h},children:[e.jsx("span",{className:"memory-health-score-value",style:{color:h},children:p.score}),e.jsx("span",{className:"memory-health-score-label",children:"/ 100"})]}),e.jsxs("div",{className:"memory-health-meta",children:[e.jsxs("h3",{className:"memory-health-title",children:[e.jsx(De,{size:16}),"Memory health ·"," ",e.jsx("span",{style:{color:h},children:p.status})]}),e.jsx("p",{className:"memory-health-message",children:p.message}),e.jsxs($,{variant:"ghost",size:"sm",onClick:t,children:[e.jsx(de,{size:12})," Refresh"]})]})]}),e.jsxs("div",{className:"memory-source-pills",children:[e.jsxs("button",{type:"button",className:"memory-source-pill",onClick:()=>a("lightrag"),children:[e.jsx(Pe,{size:14}),e.jsx("span",{children:"LightRAG"}),e.jsx("span",{className:V("memory-source-pill-status",d.running?"on":"off"),children:d.running?"running":"stopped"})]}),e.jsxs("button",{type:"button",className:"memory-source-pill",onClick:()=>a("obsidian"),children:[e.jsx(be,{size:14}),e.jsx("span",{children:"Obsidian Vault"}),e.jsxs("span",{className:V("memory-source-pill-status",u.exists?"on":"off"),children:[u.noteCount," notes"]})]}),e.jsxs("button",{type:"button",className:"memory-source-pill",onClick:()=>a("git"),children:[e.jsx(is,{size:14}),e.jsx("span",{children:"Git Sync"}),e.jsx("span",{className:V("memory-source-pill-status",u.gitClean===null?"na":u.gitClean?"on":"warn"),children:u.gitClean===null?"—":u.gitClean?"clean":"dirty"})]}),e.jsxs("button",{type:"button",className:"memory-source-pill",onClick:()=>a("semantic"),children:[e.jsx(ye,{size:14}),e.jsx("span",{children:"Semantic Search"}),e.jsx("span",{className:"memory-source-pill-status na",children:"cross-source"})]})]}),e.jsxs("div",{className:"memory-stat-grid",children:[e.jsx(hs,{icon:e.jsx(Pe,{size:16}),label:"LightRAG",value:d.running?`running · ${d.queryCountLast24h} q/24h`:"stopped",sub:d.running?`${d.indexedApprox} indexed chunks`:"start from the LightRAG panel",onClick:()=>a("lightrag")}),e.jsx(hs,{icon:e.jsx(be,{size:16}),label:"Obsidian",value:`${u.noteCount} notes`,sub:u.folderCount>0?`${u.folderCount} folders`:"no folders yet",onClick:()=>a("obsidian")}),e.jsx(hs,{icon:e.jsx(is,{size:16}),label:"Git",value:u.gitBranch?`branch ${u.gitBranch}`:"local-only",sub:u.gitClean===null?"not configured":u.gitClean?"clean working tree":"dirty — commit or pull",onClick:()=>a("git")}),e.jsx(hs,{icon:e.jsx(pa,{size:16}),label:"Storage",value:to(m.total),sub:m.breakdown.length>0?`${m.breakdown.length} dirs tracked`:"no memory data on disk"}),e.jsx(hs,{icon:e.jsx(He,{size:16}),label:"Last reindex",value:d.lastReindexAt?_e(d.lastReindexAt):"never",sub:"lightrag ingest",onClick:()=>a("lightrag")}),e.jsx(hs,{icon:e.jsx(Ms,{size:16}),label:"Health",value:`${p.score}/100`,sub:p.status,onClick:()=>a("config")})]}),p.checks.length>0&&e.jsxs(G,{children:[e.jsx(te,{children:"Health checks"}),e.jsx(ne,{children:"Composite score across all memory subsystems"}),e.jsx("ul",{className:"memory-check-list",children:p.checks.map(g=>e.jsxs("li",{className:"memory-check-row",children:[e.jsx("span",{className:"memory-check-icon",children:g.pass?e.jsx(qe,{size:14,style:{color:"var(--success)"}}):g.name.includes("secrets")||g.name.includes("schema")?e.jsx(Te,{size:14,style:{color:"var(--warning)"}}):e.jsx(Qs,{size:14,style:{color:"var(--error)"}})}),e.jsx("span",{className:"memory-check-name",children:g.name}),e.jsx("span",{className:"memory-check-detail muted",children:g.detail})]},g.name))})]})]})}function hs({icon:s,label:t,value:a,sub:i,onClick:n}){const c=n?"button":"div";return e.jsxs(c,{type:n?"button":void 0,onClick:n,className:V("memory-stat-card",n&&"memory-stat-card-clickable"),children:[e.jsx("div",{className:"memory-stat-icon",children:s}),e.jsxs("div",{className:"memory-stat-body",children:[e.jsx("div",{className:"memory-stat-label",children:t}),e.jsx("div",{className:"memory-stat-value",children:a}),e.jsx("div",{className:"memory-stat-sub muted",children:i})]})]})}function to(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 ao({refreshKey:s}){const t=re(),[a,i]=r.useState(null),[n,c]=r.useState(null),[o,l]=r.useState([]),[x,p]=r.useState(!0),[u,d]=r.useState(null),[m,h]=r.useState(""),[g,j]=r.useState(null),k=async()=>{p(!0);try{const[f,L,R]=await Promise.all([T.get("/memory/lightrag/stats").catch(()=>null),T.get("/memory/config").then(y=>(y==null?void 0:y.lightrag)||null).catch(()=>null),T.get("/memory/lightrag/log").catch(()=>({lines:[]}))]);i(f),c(L),l((R==null?void 0:R.lines)||[])}catch(f){t.error(`LightRAG status failed: ${f.message}`)}finally{p(!1)}};r.useEffect(()=>{k()},[s]);const z=async(f,L,R)=>{d(f);try{await L(),t.success(R),await k()}catch(y){t.error(`${f} failed: ${y.message}`)}finally{d(null)}},N=()=>z("start",()=>T.post("/memory/lightrag/start",{}),"LightRAG starting…"),S=()=>z("stop",()=>T.post("/memory/lightrag/stop",{}),"LightRAG stopping…"),E=async()=>{d("restart");try{await T.post("/memory/lightrag/stop",{}).catch(()=>{}),await new Promise(f=>setTimeout(f,600)),await T.post("/memory/lightrag/start",{}),t.success("LightRAG restarted."),await k()}catch(f){t.error(`Restart failed: ${f.message}`)}finally{d(null)}},v=()=>z("reindex",()=>T.post("/memory/lightrag/reindex",{}),"Reindex complete."),b=()=>z("rebuild",()=>T.post("/memory/lightrag/rebuild-graph",{}),"Graph rebuilt."),w=async()=>{var f,L,R;if(m.trim()){d("query");try{const y=await T.get(`/memory/query?q=${encodeURIComponent(m)}&topK=8`),A=(f=y==null?void 0:y.semantic)!=null&&f.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";j({ok:!!((R=y==null?void 0:y.semantic)!=null&&R.ok),text:A})}catch(y){j({ok:!1,text:y.message})}finally{d(null)}}};return x&&!a?e.jsxs("div",{className:"view-loading",children:[e.jsx(oe,{size:"lg"}),e.jsx("p",{children:"Loading LightRAG status…"})]}):a?e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(G,{variant:"elevated",children:[e.jsxs(te,{children:[e.jsx(Pe,{size:14}),"LightRAG",e.jsx("span",{className:V("memory-source-pill-status",a.running?"on":"off"),children:a.running?"running":"stopped"})]}),e.jsx(ne,{children:a.running?e.jsxs(e.Fragment,{children:["PID ",e.jsx("code",{children:a.pid})," · ",a.host,":",a.port]}):e.jsx(e.Fragment,{children:"Server is not running. Start it from the controls below."})}),e.jsxs("div",{className:"memory-action-row",children:[e.jsxs($,{variant:"primary",size:"sm",onClick:N,disabled:!!u||a.running,children:[u==="start"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(Ls,{size:12}),"Start"]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:S,disabled:!!u||!a.running,children:[u==="stop"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(An,{size:12}),"Stop"]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:E,disabled:!!u,children:[u==="restart"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(St,{size:12}),"Restart"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:v,disabled:!!u,children:[u==="reindex"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(de,{size:12}),"Reindex all"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:b,disabled:!!u,title:"Wipe working dir + reindex from scratch",children:[u==="rebuild"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(Js,{size:12}),"Rebuild graph"]})]})]}),e.jsxs("div",{className:"memory-stat-grid",children:[e.jsx(ws,{icon:e.jsx(pa,{size:14}),label:"Indexed chunks (approx)",value:String(a.indexedApprox)}),e.jsx(ws,{icon:e.jsx(no,{n:a.noteCount}),label:"Notes in vault",value:String(a.noteCount)}),e.jsx(ws,{icon:e.jsx(Ct,{size:14}),label:"Queries last 24h",value:String(a.queryCountLast24h)}),e.jsx(ws,{icon:e.jsx(He,{size:14}),label:"Avg response",value:a.avgResponseMs!==null?`${a.avgResponseMs} ms`:"—"}),e.jsx(ws,{icon:a.lastReindexOk?e.jsx(qe,{size:14}):a.lastReindexOk===!1?e.jsx(Qs,{size:14}):e.jsx(de,{size:14}),label:"Last reindex",value:a.lastReindexAt?_e(a.lastReindexAt):"never",sub:a.lastReindexInserted!==null?`${a.lastReindexInserted} inserted${a.lastReindexFailed?`, ${a.lastReindexFailed} failed`:""}`:void 0})]}),e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsx(ye,{size:14})," Quick search"]}),e.jsx(ne,{children:"Send a natural-language query to the LightRAG index."}),e.jsxs("div",{className:"memory-search-row",children:[e.jsx("label",{htmlFor:"lightrag-query",className:"sr-only",children:"Search LightRAG"}),e.jsx("input",{id:"lightrag-query",type:"text",className:"input",placeholder:"e.g. how does the memory service write notes?",value:m,onChange:f=>h(f.target.value),onKeyDown:f=>{f.key==="Enter"&&w()},disabled:u==="query","aria-label":"Search LightRAG"}),e.jsxs($,{variant:"primary",onClick:w,disabled:u==="query"||!m.trim(),children:[u==="query"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(ye,{size:12}),"Query"]})]}),g&&e.jsx("div",{className:V("memory-query-result",g.ok?"ok":"err"),children:e.jsx("pre",{className:"mono text-sm",children:g.text})})]}),n&&e.jsxs(G,{children:[e.jsx(te,{children:"Configuration"}),e.jsxs(ne,{children:["Effective values from ",e.jsx("code",{children:".bizar/memory.json"})," + env defaults."]}),e.jsxs("dl",{className:"memory-config-row",children:[e.jsx("dt",{children:"LLM binding"}),e.jsxs("dd",{children:[e.jsx("code",{children:n.llmBinding})," · ",e.jsx("code",{children:n.llmModel})]}),e.jsx("dt",{children:"Embedding"}),e.jsxs("dd",{children:[e.jsx("code",{children:n.embeddingBinding})," · ",e.jsx("code",{children:n.embeddingModel})]}),e.jsx("dt",{children:"Host"}),e.jsx("dd",{children:e.jsxs("code",{children:[n.host,":",n.port]})}),e.jsx("dt",{children:"Working dir"}),e.jsx("dd",{className:"mono ellipsis",title:n.workingDir,children:n.workingDir})]})]}),o.length>0&&e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsx(de,{size:14})," Server log (tail)"]}),e.jsxs(ne,{children:["Last ",o.length," lines from ",e.jsx("code",{children:"lightrag.log"})]}),e.jsx("pre",{className:"memory-log-tail mono text-xs",children:o.join(`
12
- `)})]})]}):e.jsx("div",{className:"muted",children:"No LightRAG data available."})}function ws({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 no({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 io({refreshKey:s}){const t=re(),a=$e(),[i,n]=r.useState([]),[c,o]=r.useState(null),[l,x]=r.useState(!0),[p,u]=r.useState(""),[d,m]=r.useState(null),[h,g]=r.useState(!1),[j,k]=r.useState(null),[z,N]=r.useState([]),S=async()=>{var R;x(!0);try{const[y,A]=await Promise.all([T.get("/memory/notes").catch(()=>({notes:[]})),T.get("/memory/obsidian/tree").catch(()=>({tree:null}))]);n(y.notes||[]),o(A.tree),j&&!((R=y.notes)!=null&&R.find(P=>P.relPath===j))&&(k(null),N([]))}catch(y){t.error(`Vault load failed: ${y.message}`)}finally{x(!1)}};r.useEffect(()=>{S()},[s]),r.useEffect(()=>{if(!p.trim()){m(null);return}g(!0);const R=setTimeout(async()=>{try{const y=await T.get(`/memory/search?q=${encodeURIComponent(p)}&limit=50`),A=new Set((y.results||[]).map(P=>P.relPath));m(i.filter(P=>A.has(P.relPath)))}catch(y){t.error(`Search failed: ${y.message}`)}finally{g(!1)}},240);return()=>clearTimeout(R)},[p,i,t]);const E=async R=>{k(R);try{const y=await T.get(`/memory/obsidian/backlinks?note=${encodeURIComponent(R)}`);N(y.backlinks||[])}catch{N([])}},v=()=>{a.open({title:"New note",width:720,children:e.jsx(Yt,{mode:"create",onSave:async(R,y,A)=>{try{await T.post("/memory/notes",{path:R,frontmatter:y,body:A}),t.success(`Created ${R}.`),a.close(),await S(),E(R)}catch(P){t.error(`Create failed: ${P.message}`)}},onCancel:()=>a.close()})})},b=async R=>{try{const y=await T.get(`/memory/notes/${R.split("/").map(encodeURIComponent).join("/")}`);a.open({title:`Edit ${R}`,width:720,children:e.jsx(Yt,{mode:"edit",initial:{relPath:y.relPath,frontmatter:y.frontmatter,body:y.body},onSave:async(A,P,C)=>{try{await T.put(`/memory/notes/${A.split("/").map(encodeURIComponent).join("/")}`,{frontmatter:P,body:C}),t.success(`Saved ${A}.`),a.close(),await S(),E(A)}catch(D){t.error(`Save failed: ${D.message}`)}},onCancel:()=>a.close()})})}catch(y){t.error(`Load failed: ${y.message}`)}},w=async R=>{if(confirm(`Delete ${R}? This cannot be undone.`))try{await T.del(`/memory/notes/${R.split("/").map(encodeURIComponent).join("/")}`),t.success(`Deleted ${R}.`),j===R&&k(null),await S()}catch(y){t.error(`Delete failed: ${y.message}`)}},f=r.useMemo(()=>[...i].sort((R,y)=>y.mtime-R.mtime),[i]),L=d??f;return l&&!i.length?e.jsxs("div",{className:"view-loading",children:[e.jsx(oe,{size:"lg"}),e.jsx("p",{children:"Loading vault…"})]}):e.jsxs("div",{className:"memory-panel-content memory-obsidian-grid",children:[e.jsxs(G,{variant:"outlined",className:"memory-tree-card",children:[e.jsxs(te,{children:[e.jsx(Fe,{size:14})," Folders"]}),e.jsx(ne,{children:c?`${Ma(c)} folder(s)`:"no vault"}),e.jsx("div",{className:"memory-tree-body",children:c?e.jsx(Aa,{node:c,depth:0,onSelect:E,selected:j}):null})]}),e.jsxs("div",{className:"memory-obsidian-list-col",children:[e.jsxs("div",{className:"memory-list-toolbar",children:[e.jsxs("div",{className:"search-input",children:[e.jsx(ye,{size:14,"aria-hidden":!0}),e.jsx("label",{htmlFor:"obsidian-search",className:"sr-only",children:"Search notes"}),e.jsx("input",{id:"obsidian-search",type:"text",className:"input",placeholder:"Search notes…",value:p,onChange:R=>u(R.target.value),"aria-label":"Search notes"}),p&&e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>u(""),"aria-label":"Clear search",children:e.jsx(Ne,{size:12})})]}),e.jsxs($,{variant:"primary",size:"sm",onClick:v,children:[e.jsx(Mn,{size:12})," New note"]}),e.jsx($,{variant:"ghost",size:"sm",onClick:S,title:"Refresh",children:e.jsx(de,{size:12})})]}),h&&e.jsx("div",{className:"muted text-sm",children:"Searching…"}),L.length===0?e.jsx(pe,{icon:e.jsx(be,{size:28}),title:"No notes",message:i.length===0?'No notes in this vault yet. Click "New note" to create one.':`No notes match "${p}".`}):e.jsx("ul",{className:"memory-note-list",children:L.map(R=>e.jsxs("li",{className:V("memory-note-card",j===R.relPath&&"memory-note-card-active"),children:[e.jsxs("button",{type:"button",className:"memory-note-card-main",onClick:()=>E(R.relPath),children:[e.jsxs("div",{className:"memory-note-card-title",children:[e.jsx(be,{size:12}),e.jsx("span",{children:$a(R)})]}),e.jsxs("div",{className:"memory-note-card-meta",children:[e.jsx("code",{className:"muted",children:R.relPath}),e.jsxs("span",{className:"muted",children:["· ",Ce(R.mtime)]}),!R.schemaValid&&e.jsx("span",{className:"memory-pill-warn",children:"schema"})]})]}),e.jsxs("div",{className:"memory-note-card-actions",children:[e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>b(R.relPath),"aria-label":`Edit ${R.relPath}`,title:"Edit",children:e.jsx(Es,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>w(R.relPath),"aria-label":`Delete ${R.relPath}`,title:"Delete",children:e.jsx(ke,{size:12})})]})]},R.relPath))})]}),e.jsx("div",{className:"memory-obsidian-detail-col",children:j?e.jsx(ro,{relPath:j,onClose:()=>k(null)}):e.jsx(pe,{icon:e.jsx(be,{size:28}),title:"Pick a note",message:"Select a note from the list to view its content, frontmatter, and backlinks."})})]})}function $a(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 Aa({node:s,depth:t,onSelect:a,selected:i}){const[n,c]=r.useState(t<2);return s.type==="note"?e.jsxs("button",{type:"button",className:V("memory-tree-node memory-tree-node-note",i===s.path&&"memory-tree-node-active"),style:{paddingLeft:6+t*12},onClick:()=>a(s.path),children:[e.jsx(be,{size:11}),e.jsx("span",{children:s.name})]}):e.jsxs("div",{className:"memory-tree-folder",children:[e.jsxs("button",{type:"button",className:"memory-tree-node memory-tree-node-folder",style:{paddingLeft:6+t*12},onClick:()=>c(o=>!o),children:[n?e.jsx(We,{size:11}):e.jsx(Xe,{size:11}),e.jsx(Fe,{size:11}),e.jsx("span",{children:s.name||"vault"}),s.children&&s.children.length>0&&e.jsx("span",{className:"muted text-xs",children:s.children.length})]}),n&&s.children&&e.jsx("div",{className:"memory-tree-children",children:s.children.map((o,l)=>e.jsx(Aa,{node:o,depth:t+1,onSelect:a,selected:i},`${o.path}-${l}`))})]})}function Ma(s){return s.type==="note"?0:1+(s.children||[]).reduce((t,a)=>t+Ma(a),0)}function ro({relPath:s,onClose:t}){var u,d;const[a,i]=r.useState(null),[n,c]=r.useState([]),[o,l]=r.useState(!0);if(r.useEffect(()=>{let m=!1;return l(!0),(async()=>{try{const[h,g]=await Promise.all([T.get(`/memory/notes/${s.split("/").map(encodeURIComponent).join("/")}`),T.get(`/memory/obsidian/backlinks?note=${encodeURIComponent(s)}`)]);if(m)return;i(h),c(g.backlinks||[])}catch{m||i(null)}finally{m||l(!1)}})(),()=>{m=!0}},[s]),o)return e.jsx("div",{className:"view-loading",children:e.jsx(oe,{size:"sm"})});if(!a)return e.jsx("div",{className:"muted",children:"Note not found."});const x=Array.isArray((u=a.frontmatter)==null?void 0:u.tags)?a.frontmatter.tags:[],p=Array.isArray((d=a.frontmatter)==null?void 0:d.links)?a.frontmatter.links:[];return e.jsxs("div",{className:"memory-note-detail",children:[e.jsxs("div",{className:"memory-note-detail-head",children:[e.jsx("h3",{children:$a(a)}),e.jsx("button",{type:"button",className:"icon-btn",onClick:t,"aria-label":"Close",children:e.jsx(Ne,{size:12})})]}),e.jsxs("div",{className:"memory-note-detail-meta",children:[e.jsx("code",{children:s}),e.jsxs("span",{className:"muted",children:["· modified ",_e(a.mtime)]})]}),x.length>0&&e.jsx("div",{className:"memory-tag-row",children:x.map((m,h)=>e.jsx("span",{className:"memory-tag",children:String(m)},h))}),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,h)=>e.jsx("li",{children:e.jsx("code",{children:String(m)})},h))})]})]})}function Yt({mode:s,initial:t,onSave:a,onCancel:i}){const[n,c]=r.useState((t==null?void 0:t.relPath)||"untitled.md"),[o,l]=r.useState(t!=null&&t.frontmatter?lo(t.frontmatter):`title: ""
13
- tags: []
14
- `),[x,p]=r.useState((t==null?void 0:t.body)||""),[u,d]=r.useState(!1),m=re(),h=async()=>{if(!n.endsWith(".md")){m.error("Path must end in .md");return}let g;try{g=oo(o)||{}}catch(j){m.error(`Frontmatter parse failed: ${j.message}`);return}d(!0);try{await a(n,g,x)}finally{d(!1)}};return e.jsxs("div",{className:"memory-editor-modal",children:[e.jsx("label",{className:"field-label",htmlFor:"obsidian-note-path",children:"Path"}),e.jsx("input",{id:"obsidian-note-path",type:"text",className:"input mono",value:n,onChange:g=>c(g.target.value),disabled:s==="edit",placeholder:"notes/example.md"}),e.jsx("label",{className:"field-label",htmlFor:"obsidian-note-frontmatter",style:{marginTop:12},children:"Frontmatter (YAML)"}),e.jsx("textarea",{id:"obsidian-note-frontmatter",className:"memory-editor-textarea mono text-sm",rows:6,value:o,onChange:g=>l(g.target.value),"aria-label":"Frontmatter YAML"}),e.jsx("label",{className:"field-label",htmlFor:"obsidian-note-body",style:{marginTop:12},children:"Body (Markdown)"}),e.jsx("textarea",{id:"obsidian-note-body",className:"memory-editor-textarea mono text-sm",rows:14,value:x,onChange:g=>p(g.target.value),"aria-label":"Body markdown"}),e.jsxs("div",{className:"modal-footer-actions",style:{marginTop:12},children:[e.jsx($,{variant:"ghost",onClick:i,disabled:u,children:"Cancel"}),e.jsxs($,{variant:"primary",onClick:h,disabled:u,children:[u&&e.jsx(xe,{size:12,className:"memory-spin"}),s==="create"?"Create":"Save"]})]})]})}function lo(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(` - ${ot(n)}`)}else if(typeof i=="object"){t.push(`${a}:`);for(const[n,c]of Object.entries(i))t.push(` ${n}: ${ot(c)}`)}else t.push(`${a}: ${ot(i)}`);return t.join(`
15
- `)}function ot(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 oo(s){const t={},a=s.split(/\r?\n/);let i=0;for(;i<a.length;){const n=a[i];if(!n.trim()||n.trim().startsWith("#")){i++;continue}const c=n.match(/^([A-Za-z_][\w-]*):\s*(.*)$/);if(!c){i++;continue}const[,o,l]=c;if(l===""){const x={},p=[];let u=!1,d=!1;for(;i+1<a.length;){const m=a[i+1];if(!m.startsWith(" "))break;if(m.startsWith(" - "))u=!0,p.push(ct(m.slice(4))),i++;else{d=!0;const h=m.match(/^ ([A-Za-z_][\w-]*):\s*(.*)$/);h&&(x[h[1]]=ct(h[2])),i++}}t[o]=u&&!d?p:d?x:{}}else t[o]=ct(l);i++}return t}function ct(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 co({refreshKey:s}){var S,E,v,b;const t=re(),[a,i]=r.useState(null),[n,c]=r.useState(null),[o,l]=r.useState(!0),[x,p]=r.useState(null),[u,d]=r.useState(null),m=async()=>{var w;l(!0);try{const[f,L,R]=await Promise.all([T.get("/memory/git/status").catch(()=>null),T.get("/memory/git/diff").catch(()=>null),T.get("/memory/config/global").catch(()=>null)]);i(f),c(L),d(((w=R==null?void 0:R.config)==null?void 0:w.git)||null)}catch(f){t.error(`Git status failed: ${f.message}`)}finally{l(!1)}};r.useEffect(()=>{m()},[s]);const h=async(w,f,L)=>{p(w);try{await f(),t.success(L),await m()}catch(R){t.error(`${w} failed: ${R.message}`)}finally{p(null)}},g=()=>h("pull",()=>T.post("/memory/git/pull",{}),"Pull complete."),j=()=>h("push",()=>T.post("/memory/git/push",{}),"Push complete."),k=()=>{const w=prompt("Commit message:",`[memory-sync] ${new Date().toISOString().slice(0,10)} vault sync`);w&&h("commit",()=>T.post("/memory/git/commit",{message:w}),"Committed.")},z=()=>h("fetch",()=>T.post("/memory/git/sync",{push:!1}),"Fetch complete.");if(o&&!a)return e.jsxs("div",{className:"view-loading",children:[e.jsx(oe,{size:"lg"}),e.jsx("p",{children:"Loading git status…"})]});if(!a)return e.jsx("div",{className:"muted",children:"No git data available."});const N=a.mode==="local-only";return e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(G,{variant:"elevated",children:[e.jsxs(te,{children:[e.jsx(is,{size:14})," Git sync",N?e.jsx("span",{className:"memory-source-pill-status na",children:"local-only"}):e.jsx("span",{className:V("memory-source-pill-status",a.clean?"on":"warn"),children:a.clean?"clean":"dirty"})]}),e.jsx(ne,{children:N?"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]})}),!N&&e.jsxs("div",{className:"memory-git-status-row",children:[e.jsx(Ss,{ok:a.clean??!1,label:"Working tree"}),e.jsx(Ss,{ok:(a.ahead??0)===0,label:`Ahead: ${a.ahead??0}`}),e.jsx(Ss,{ok:(a.behind??0)===0,label:`Behind: ${a.behind??0}`}),e.jsx(Ss,{ok:(((S=a.modified)==null?void 0:S.length)??0)===0,label:`Modified: ${((E=a.modified)==null?void 0:E.length)??0}`}),e.jsx(Ss,{ok:(((v=a.untracked)==null?void 0:v.length)??0)===0,label:`Untracked: ${((b=a.untracked)==null?void 0:b.length)??0}`})]}),e.jsxs("div",{className:"memory-action-row",children:[e.jsxs($,{variant:"secondary",size:"sm",onClick:g,disabled:!!x||N,children:[x==="pull"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(oa,{size:12}),"Pull"]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:j,disabled:!!x||N,children:[x==="push"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(zt,{size:12}),"Push"]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:k,disabled:!!x||N,children:[x==="commit"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(ga,{size:12}),"Commit"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:z,disabled:!!x||N,children:[x==="fetch"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(In,{size:12}),"Fetch + sync"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:m,disabled:!!x,children:[e.jsx(de,{size:12})," Refresh"]})]})]}),u&&e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsx(xa,{size:14})," Repository"]}),e.jsxs(ne,{children:["Snapshot of ",e.jsx("code",{children:"~/.config/bizar/memory-config.json"})," → git block."]}),e.jsxs("dl",{className:"memory-config-row",children:[e.jsx("dt",{children:"Path"}),e.jsx("dd",{className:"mono ellipsis",title:u.repoPath,children:u.repoPath||"—"}),e.jsx("dt",{children:"Remote"}),e.jsx("dd",{className:"mono ellipsis",title:u.remoteUrl,children:u.remoteUrl||"—"}),e.jsx("dt",{children:"Branch"}),e.jsx("dd",{children:e.jsx("code",{children:u.branch||"main"})}),e.jsx("dt",{children:"Auto-sync"}),e.jsx("dd",{children:u.autoSync?"enabled":"disabled"})]})]}),e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsx(En,{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(w=>e.jsx("li",{children:e.jsx("code",{children:w})},w))}),n&&n.lines.length>1&&e.jsx("pre",{className:"memory-log-tail mono text-xs",children:n.lines.slice(0,400).join(`
16
- `)})]})]})}function Ss({ok:s,label:t}){return e.jsxs("span",{className:V("memory-git-status-pill",s?"ok":"warn"),children:[s?e.jsx(qe,{size:11}):e.jsx(xe,{size:11,className:"memory-spin"}),t]})}function mo({refreshKey:s}){const t=re(),[a,i]=r.useState(""),[n,c]=r.useState({lightrag:!0,obsidian:!0}),[o,l]=r.useState(null),[x,p]=r.useState(!1),[u,d]=r.useState(""),m=async g=>{if(g.trim()){p(!0),d(g);try{const j=[...n.lightrag?["lightrag"]:[],...n.obsidian?["obsidian"]:[]],k=await T.post("/memory/semantic-search",{query:g,limit:20,sources:j});l(k.results||[])}catch(j){t.error(`Search failed: ${j.message}`),l([])}finally{p(!1)}}};r.useEffect(()=>{u&&m(u)},[n]),r.useEffect(()=>{u&&m(u)},[s]);const h=r.useMemo(()=>{const g=(o||[]).filter(k=>k.source==="obsidian"),j=(o||[]).filter(k=>k.source==="lightrag");return{obs:g,lr:j}},[o]);return e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(G,{variant:"elevated",children:[e.jsxs(te,{children:[e.jsx(ye,{size:14})," Semantic search"]}),e.jsx(ne,{children:"Query both LightRAG (graph-based) and the Obsidian vault in one shot."}),e.jsxs("div",{className:"memory-search-row",children:[e.jsx("label",{htmlFor:"semantic-search-input",className:"sr-only",children:"Semantic search"}),e.jsx("input",{id:"semantic-search-input",type:"text",className:"input",placeholder:"e.g. how are notes indexed?",value:a,onChange:g=>i(g.target.value),onKeyDown:g=>{g.key==="Enter"&&m(a)},disabled:x,"aria-label":"Semantic search query"}),e.jsxs($,{variant:"primary",onClick:()=>m(a),disabled:x||!a.trim(),children:[x?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(ye,{size:12}),"Search"]})]}),e.jsxs("div",{className:"memory-source-toggle-row",children:[e.jsx(Xt,{active:n.obsidian,onToggle:()=>c(g=>({...g,obsidian:!g.obsidian})),label:"Obsidian",icon:e.jsx(be,{size:11})}),e.jsx(Xt,{active:n.lightrag,onToggle:()=>c(g=>({...g,lightrag:!g.lightrag})),label:"LightRAG",icon:e.jsx(Pe,{size:11})}),a&&e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>{i(""),l(null),d("")},"aria-label":"Clear",children:e.jsx(Ne,{size:12})})]})]}),x&&e.jsx("div",{className:"view-loading",children:e.jsx(oe,{size:"md"})}),!x&&o&&o.length===0&&e.jsx(pe,{icon:e.jsx(ye,{size:28}),title:"No matches",message:`Nothing in scope matched "${u}".`}),h.obs.length>0&&e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsx(be,{size:14})," Obsidian (",h.obs.length,")"]}),e.jsx("ul",{className:"memory-search-result-list",children:h.obs.map((g,j)=>e.jsxs("li",{className:"memory-search-result",children:[e.jsxs("div",{className:"memory-search-result-head",children:[e.jsx("code",{children:g.relPath}),e.jsxs("span",{className:"muted text-xs",children:["score ",g.score.toFixed(1)]})]}),e.jsx("p",{className:"muted text-sm",children:g.snippet})]},`obs-${j}`))})]}),h.lr.length>0&&e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsx(Pe,{size:14})," LightRAG (",h.lr.length,")"]}),e.jsx("div",{className:"memory-search-result-list",children:h.lr.map((g,j)=>e.jsxs("div",{className:"memory-search-result",children:[e.jsxs("div",{className:"memory-search-result-head",children:[e.jsxs("span",{className:"memory-source-pill",children:[e.jsx(Pe,{size:11})," LightRAG"]}),g.error&&e.jsxs("span",{className:"muted text-xs",children:["error: ",g.error]})]}),e.jsx("p",{className:"text-sm",children:g.snippet})]},`lr-${j}`))})]})]})}function Xt({active:s,onToggle:t,label:a,icon:i}){return e.jsxs("button",{type:"button",className:V("memory-toggle-chip",s&&"memory-toggle-chip-active"),onClick:t,"aria-pressed":s,children:[i,e.jsx("span",{children:a})]})}function uo({refreshKey:s}){const t=re(),[a,i]=r.useState(null),[n,c]=r.useState(!0),[o,l]=r.useState(!1),[x,p]=r.useState(""),[u]=r.useState(""),[d,m]=r.useState(null),[h,g]=r.useState(null),[j,k]=r.useState(null),[z,N]=r.useState(!1),S=async()=>{var f,L;c(!0);try{const R=await T.get("/memory/config/global");i(R.config),p(((L=(f=R.config)==null?void 0:f.git)==null?void 0:L.remoteUrl)||""),await E()}catch(R){t.error(`Config load failed: ${R.message}`)}finally{c(!1)}},E=async()=>{try{const f=await T.get("/memory/git/status");f.ok&&m({clean:f.clean,branch:f.branch,modified:f.modified,untracked:f.untracked})}catch{}};r.useEffect(()=>{S()},[s]);const v=async()=>{if(a){l(!0);try{await T.put("/memory/config/global",{git:{remoteUrl:x}}),t.success("Config saved.")}catch(f){t.error(`Save failed: ${f.message}`)}finally{l(!1)}}},b=async f=>{g(f);try{if(f==="pull"){const L=await T.post("/memory/git/pull",{});L.ok?t.success("Pull successful."):t.error(`Pull failed: ${L.output||"unknown error"}`)}else if(f==="push")(await T.post("/memory/git/push",{})).ok?t.success("Push successful."):t.error("Push failed.");else if(f==="commit"){const L=await T.post("/memory/git/commit",{});L.ok?t.success(`Committed: ${L.message}`):t.error("Commit failed.")}await E()}catch(L){t.error(`${f} failed: ${L.message}`)}finally{g(null)}},w=async()=>{N(!0);try{const f=await T.post("/memory/test-git",{});k(f.checks)}catch(f){t.error(`Test failed: ${f.message}`)}finally{N(!1)}};return n&&!a?e.jsxs("div",{className:"view-loading",children:[e.jsx(oe,{size:"md"}),e.jsx("p",{children:"Loading config…"})]}):a?e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsx(is,{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(dt,{label:"Vault path",inline:!0,children:e.jsx("span",{className:"memory-vault-path mono muted",children:u||"(loading…)"})}),e.jsx(dt,{label:"Remote URL",children:e.jsx("input",{type:"text",className:"input mono",value:x,onChange:f=>p(f.target.value),placeholder:"git@github.com:org/repo.git"})}),d&&e.jsxs(dt,{label:"Status",inline:!0,children:[e.jsx("span",{className:V("memory-pill",d.clean?"memory-pill-ok":"memory-pill-warn"),children:d.clean?"clean":"dirty"}),d.branch&&e.jsxs("span",{className:"muted",style:{marginLeft:8},children:[e.jsx(is,{size:12,style:{display:"inline"}})," ",d.branch]}),!d.clean&&d.modified!==void 0&&e.jsxs("span",{className:"muted",style:{marginLeft:8},children:[d.modified," modified, ",d.untracked," untracked"]})]})]}),e.jsxs("div",{className:"memory-action-row",style:{marginTop:12},children:[e.jsxs($,{variant:"secondary",onClick:()=>b("pull"),disabled:h!==null,children:[h==="pull"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(ls,{size:12}),"Pull"]}),e.jsxs($,{variant:"secondary",onClick:()=>b("commit"),disabled:h!==null,children:[h==="commit"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(ga,{size:12}),"Commit"]}),e.jsxs($,{variant:"secondary",onClick:()=>b("push"),disabled:h!==null,children:[h==="push"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(Ln,{size:12}),"Push"]})]})]}),e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsx(gt,{size:14})," Connection tests"]}),e.jsx(ne,{children:"Verify the configured git remote is reachable."}),e.jsxs("div",{className:"memory-action-row",children:[e.jsxs($,{variant:"secondary",onClick:w,disabled:z,children:[z?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(gt,{size:12}),"Test git connection"]}),e.jsxs($,{variant:"primary",onClick:v,disabled:o,children:[o?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(As,{size:12}),"Save config"]})]}),j&&j.length>0&&e.jsx("ul",{className:"memory-check-list",style:{marginTop:12},children:j.map((f,L)=>e.jsxs("li",{className:"memory-check-row",children:[e.jsx("span",{className:"memory-check-icon",children:e.jsx("span",{className:V("memory-pill",f.pass?"memory-pill-ok":"memory-pill-warn"),children:f.pass?"OK":"FAIL"})}),e.jsx("span",{className:"memory-check-name",children:f.name}),e.jsx("span",{className:"memory-check-detail muted",children:f.detail})]},L))})]})]}):e.jsx("div",{className:"muted",children:"No config available."})}function dt({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 Ke=800,Jt=60,mt={default:"#8b5cf6",note:"#8b5cf6",entity:"#34d399",concept:"#fbbf24",root:"#f87171"};function ho(s,t){return mt[s]||mt[t]||mt.default}function xo(s){return 6+Math.min(s.size*2,10)}function po(s,t){var c,o;if(s.length===0)return[];const a=new Map;for(const l of s)a.set(l.id,new Set);for(const l of t)(c=a.get(l.source))==null||c.add(l.target),(o=a.get(l.target))==null||o.add(l.source);const i=s.map((l,x)=>{const p=x/s.length*Math.PI*2,u=Ke*.28;return{...l,x:Ke/2+u*Math.cos(p)+(Math.random()-.5)*40,y:Ke/2+u*Math.sin(p)+(Math.random()-.5)*40,vx:0,vy:0}}),n=new Map;for(const l of i)n.set(l.id,l);for(let l=0;l<Jt;l++){const x=1-l/Jt;for(let d=0;d<i.length;d++)for(let m=d+1;m<i.length;m++){const h=i[d],g=i[m],j=g.x-h.x,k=g.y-h.y,z=Math.sqrt(j*j+k*k)||1,N=400*x/(z*z),S=j/z*N,E=k/z*N;h.vx-=S,h.vy-=E,g.vx+=S,g.vy+=E}for(const d of t){const m=n.get(d.source),h=n.get(d.target);if(!m||!h)continue;const g=h.x-m.x,j=h.y-m.y,k=Math.sqrt(g*g+j*j)||1,N=(k-80)*.08*x,S=g/k*N,E=j/k*N;m.vx+=S,m.vy+=E,h.vx-=S,h.vy-=E}const p=Ke/2,u=Ke/2;for(const d of i)d.vx+=(p-d.x)*.01*x,d.vy+=(u-d.y)*.01*x;for(const d of i)d.vx*=.85,d.vy*=.85,d.x+=d.vx,d.y+=d.vy,d.x=Math.max(20,Math.min(Ke-20,d.x)),d.y=Math.max(20,Math.min(Ke-20,d.y))}return i}function go({data:s,onNodeClick:t,className:a}){const i=r.useRef(null),[n,c]=r.useState({x:0,y:0,scale:1}),o=r.useRef(!1),l=r.useRef({x:0,y:0,tx:0,ty:0}),x=r.useRef(null),[p,u]=r.useState(null),[d,m]=r.useState(null),h=r.useMemo(()=>po(s.nodes,s.edges),[s.nodes,s.edges]),g=r.useMemo(()=>{const f=new Map;for(const L of h)f.set(L.id,L);return f},[h]),j=r.useCallback(f=>{f.target.closest(".memory-graph-node")||(o.current=!0,l.current={x:f.clientX,y:f.clientY,tx:n.x,ty:n.y})},[n]),k=r.useCallback(f=>{if(!o.current)return;const L=f.clientX-l.current.x,R=f.clientY-l.current.y;c(y=>({...y,x:l.current.tx+L,y:l.current.ty+R}))},[]),z=r.useCallback(()=>{o.current=!1},[]),N=r.useCallback(f=>{f.preventDefault();const L=f.deltaY<0?1.1:.9,R=i.current;if(!R)return;const y=R.getBoundingClientRect(),A=f.clientX-y.left,P=f.clientY-y.top;c(C=>{const D=Math.max(.2,Math.min(4,C.scale*L)),Y=D/C.scale;return{x:A-(A-C.x)*Y,y:P-(P-C.y)*Y,scale:D}})},[]),S=r.useCallback(f=>{const L=Array.from(f.touches);if(L.length===2){const[R,y]=L;x.current=Math.hypot(y.clientX-R.clientX,y.clientY-R.clientY)}else L.length===1&&(o.current=!0,l.current={x:L[0].clientX,y:L[0].clientY,tx:n.x,ty:n.y})},[n]),E=r.useCallback(f=>{const L=Array.from(f.touches);if(L.length===2&&x.current!==null){const[R,y]=L,A=Math.hypot(y.clientX-R.clientX,y.clientY-R.clientY),P=A/x.current;x.current=A,c(C=>({...C,scale:Math.max(.2,Math.min(4,C.scale*P))}))}else if(L.length===1&&o.current){const R=L[0].clientX-l.current.x,y=L[0].clientY-l.current.y;c(A=>({...A,x:l.current.tx+R,y:l.current.ty+y}))}},[]),v=r.useCallback(()=>{o.current=!1,x.current=null},[]),b=r.useCallback(f=>{u(f.id===p?null:f.id),t==null||t(f)},[p,t]),w=Math.max(.5,1/Math.log2(n.scale+1));return e.jsx("svg",{ref:i,className:V("memory-graph-canvas",a),viewBox:`0 0 ${Ke} ${Ke}`,style:{width:"100%",height:"100%",minHeight:400,cursor:o.current?"grabbing":"grab"},onMouseDown:j,onMouseMove:k,onMouseUp:z,onMouseLeave:z,onWheel:N,onTouchStart:S,onTouchMove:E,onTouchEnd:v,children:e.jsxs("g",{transform:`translate(${n.x},${n.y}) scale(${n.scale})`,children:[s.edges.map((f,L)=>{const R=g.get(f.source),y=g.get(f.target);if(!R||!y)return null;const A=d===f.source||d===f.target||p===f.source||p===f.target;return e.jsx("line",{x1:R.x,y1:R.y,x2:y.x,y2:y.y,stroke:A?"#8b5cf6":"#2d3648",strokeWidth:A?w*2:w,strokeOpacity:A?.9:.5},`e-${L}`)}),h.map(f=>{const L=xo(f),R=ho(f.group,f.type),y=p===f.id,A=d===f.id;return e.jsxs("g",{className:"memory-graph-node",transform:`translate(${f.x},${f.y})`,onClick:()=>b(f),onMouseEnter:()=>m(f.id),onMouseLeave:()=>m(null),style:{cursor:"pointer"},children:[e.jsx("circle",{r:L+6,fill:"transparent"}),(y||A)&&e.jsx("circle",{r:L+4,fill:R,fillOpacity:.2}),e.jsx("circle",{r:L,fill:R,fillOpacity:y?1:.75,stroke:y?"#fff":R,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:f.label.length>20?f.label.slice(0,18)+"…":f.label})]},f.id)})]})})}const fo=[{color:"#8b5cf6",label:"Note / Default"},{color:"#34d399",label:"Entity (LightRAG)"},{color:"#fbbf24",label:"Concept (LightRAG)"},{color:"#f87171",label:"Root / Ungrouped"}];function jo({className:s}){return e.jsx("div",{className:V("memory-graph-legend",s),children:fo.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 vo({refreshKey:s}){const t=re(),[a,i]=r.useState({nodes:[],edges:[]}),[n,c]=r.useState(!0),[o,l]=r.useState(null),[x,p]=r.useState(""),[u,d]=r.useState(2),[m,h]=r.useState(""),[g,j]=r.useState(null),[k,z]=r.useState(null),N=r.useCallback(async()=>{var v,b;c(!0),l(null);try{const w=new URLSearchParams({limit:"200"});m&&w.set("root",m),w.set("depth",String(u));const f=await T.get(`/memory/graph?${w}`);i({nodes:f.nodes||[],edges:f.edges||[]}),j({totalNodes:f.totalNodes??((v=f.nodes)==null?void 0:v.length)??0,totalEdges:f.totalEdges??((b=f.edges)==null?void 0:b.length)??0})}catch(w){l(w.message),t.error(`Graph load failed: ${w.message}`)}finally{c(!1)}},[m,u,t]);r.useEffect(()=>{N()},[N,s]);const S=r.useCallback(v=>{z(b=>(b==null?void 0:b.id)===v.id?null:v)},[]),E=x.trim()?{nodes:a.nodes.filter(v=>v.label.toLowerCase().includes(x.toLowerCase())),edges:a.edges.filter(v=>a.nodes.some(b=>b.id===v.source&&b.label.toLowerCase().includes(x.toLowerCase()))||a.nodes.some(b=>b.id===v.target&&b.label.toLowerCase().includes(x.toLowerCase())))}:a;return e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsx(fa,{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:x,onChange:v=>p(v.target.value),style:{maxWidth:240}}),e.jsx("input",{type:"text",className:"input",placeholder:"Root note id (optional)",value:m,onChange:v=>h(v.target.value),style:{maxWidth:240},title:"Start from a specific note"}),e.jsx("label",{htmlFor:"graph-depth",className:"sr-only",children:"Depth"}),e.jsxs("span",{className:"muted text-sm",style:{whiteSpace:"nowrap"},children:["Depth",e.jsx("input",{id:"graph-depth",type:"range",min:1,max:3,value:u,onChange:v=>d(parseInt(v.target.value,10)),style:{marginLeft:8,verticalAlign:"middle"}}),u]}),e.jsx("button",{type:"button",className:"icon-btn",onClick:N,title:"Refresh graph",disabled:n,children:e.jsx(de,{size:14,className:n?"memory-spin":""})})]}),e.jsx(jo,{})]})]}),e.jsx(G,{children:n&&!a.nodes.length?e.jsxs("div",{className:"view-loading",children:[e.jsx(oe,{size:"lg"}),e.jsx("p",{children:"Loading graph…"})]}):o&&!a.nodes.length?e.jsxs("div",{className:"muted text-sm",children:["Failed to load graph: ",o]}):a.nodes.length===0?e.jsx("div",{className:"muted text-sm",children:"No graph data available. Index some notes first with LightRAG or add wikilinks to your vault."}):e.jsxs("div",{style:{position:"relative"},children:[e.jsx(go,{data:E,onNodeClick:S,className:"memory-graph-canvas-svg"}),x&&e.jsxs("div",{className:"text-xs muted",style:{marginTop:4},children:["Showing ",E.nodes.length," of ",a.nodes.length," nodes"]})]})}),k&&e.jsxs(G,{children:[e.jsx(te,{children:k.label}),e.jsx(ne,{children:e.jsx("code",{children:k.id})}),e.jsxs("dl",{className:"memory-config-row",children:[e.jsx("dt",{children:"Type"}),e.jsx("dd",{children:e.jsx("code",{children:k.type})}),e.jsx("dt",{children:"Group"}),e.jsx("dd",{children:e.jsx("code",{children:k.group})}),e.jsx("dt",{children:"Size"}),e.jsx("dd",{children:k.size})]})]}),g&&e.jsx(G,{children:e.jsxs("div",{className:"memory-graph-stats",children:[e.jsxs("span",{children:[g.totalNodes," node",g.totalNodes!==1?"s":""]}),e.jsx("span",{className:"muted",children:"·"}),e.jsxs("span",{children:[g.totalEdges," edge",g.totalEdges!==1?"s":""]}),x&&e.jsxs("span",{className:"muted",children:["· ",E.nodes.length," shown"]})]})})]})}function yo({onTextExtracted:s}){const t=re(),[a,i]=r.useState(null),[n,c]=r.useState(!1),[o,l]=r.useState(!1),x=r.useCallback(async()=>{l(!0);try{const d=await navigator.mediaDevices.getDisplayMedia({video:{mediaSource:"screen"}}),m=document.createElement("video");m.srcObject=d,await m.play();const h=document.createElement("canvas");h.width=m.videoWidth,h.height=m.videoHeight;const g=h.getContext("2d");if(!g){t.error("Failed to get canvas context");return}g.drawImage(m,0,0),d.getTracks().forEach(j=>j.stop()),m.remove(),h.toBlob(async j=>{if(!j){t.error("Failed to capture screenshot");return}const k=URL.createObjectURL(j);i(k),await p(j)},"image/png")}catch(d){d.name!=="NotAllowedError"&&t.error(`Capture failed: ${d.message}`)}finally{l(!1)}},[t]),p=r.useCallback(async d=>{c(!0);try{const m=new FileReader,h=await new Promise((j,k)=>{m.onload=()=>{const z=m.result,N=z.includes(",")?z.split(",")[1]:z;j(N)},m.onerror=()=>k(new Error("FileReader failed")),m.readAsDataURL(d)}),g=await T.post("/ocr/process",{image:h,lang:"eng"});g.ok&&(t.success("Text extracted from screenshot"),s==null||s(g.text,g.notePath))}catch(m){t.error(`OCR failed: ${m.message}`)}finally{c(!1)}},[t,s]),u=r.useCallback(()=>{i(null)},[]);return e.jsxs(G,{variant:"outlined",className:"screenshot-capture-card",children:[e.jsxs(te,{children:[e.jsx(et,{size:14})," Screenshot Capture"]}),e.jsx("div",{className:"screenshot-capture-body",children:a?e.jsxs("div",{className:"screenshot-capture-preview",children:[e.jsx("img",{src:a,alt:"Captured screenshot",className:"screenshot-capture-img"}),e.jsxs("div",{className:"screenshot-capture-actions",children:[n&&e.jsxs("span",{className:"text-sm muted",children:[e.jsx(xe,{size:12,className:"spinner"})," Extracting text…"]}),e.jsx($,{variant:"ghost",size:"sm",onClick:u,disabled:n,children:"Dismiss"})]})]}):e.jsxs("div",{className:"screenshot-capture-empty",children:[e.jsx(et,{size:32,className:"muted"}),e.jsx("p",{className:"muted text-sm",children:"Capture your screen to extract text via OCR."}),e.jsxs($,{variant:"primary",size:"sm",onClick:x,disabled:o,children:[o?e.jsx(xe,{size:12,className:"spinner"}):e.jsx(et,{size:12}),o?"Selecting…":"Capture Screen"]})]})})]})}function bo(){const[s,t]=r.useState(null),[a,i]=r.useState(null),n=(c,o)=>{t(c),i(o)};return e.jsxs("div",{className:"screenshot-ocr-panel",children:[e.jsx(yo,{onTextExtracted:n}),s!==null&&e.jsxs(G,{variant:"outlined",className:"screenshot-ocr-result-card",children:[e.jsxs(te,{children:[e.jsx(be,{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 No({refreshKey:s}){return e.jsx("div",{className:"memory-panel-content",children:e.jsx(G,{variant:"outlined",className:"memory-panel-card",children:e.jsx("div",{className:"memory-panel-body",children:e.jsx(bo,{})})})})}function ko({refreshKey:s}){const t=re(),[a,i]=r.useState(""),[n,c]=r.useState(""),[o,l]=r.useState(""),[x,p]=r.useState(!1),u=async()=>{if(!o.trim()){t.error("Content is required");return}p(!0);try{const d=await T.post("/clipboard/save",{url:a.trim()||void 0,title:n.trim()||void 0,content:o,savedAt:new Date().toISOString()});d.ok&&(t.success(`Saved to ${d.notePath}`),i(""),c(""),l(""))}catch(d){t.error(`Save failed: ${d.message}`)}finally{p(!1)}};return e.jsx("div",{className:"memory-panel-content",children:e.jsx(G,{variant:"outlined",className:"memory-panel-card",children:e.jsx("div",{className:"memory-panel-body",children:e.jsxs("div",{className:"vault-clipboard-panel",children:[e.jsxs("div",{className:"vault-clipboard-header",children:[e.jsx(ja,{size:16}),e.jsx("span",{children:"Paste Content"})]}),e.jsx("label",{className:"field-label",htmlFor:"clip-url",children:"URL (optional)"}),e.jsx("input",{id:"clip-url",type:"text",className:"input",placeholder:"https://example.com",value:a,onChange:d=>i(d.target.value)}),e.jsx("label",{className:"field-label",htmlFor:"clip-title",style:{marginTop:10},children:"Title (optional)"}),e.jsx("input",{id:"clip-title",type:"text",className:"input",placeholder:"Page title",value:n,onChange:d=>c(d.target.value)}),e.jsx("label",{className:"field-label",htmlFor:"clip-content",style:{marginTop:10},children:"Content *"}),e.jsx("textarea",{id:"clip-content",className:"input vault-clipboard-textarea mono text-sm",rows:12,placeholder:"Paste or type content to save to your vault…",value:o,onChange:d=>l(d.target.value)}),e.jsx("div",{className:"vault-clipboard-actions",style:{marginTop:12},children:e.jsxs($,{variant:"primary",size:"sm",onClick:u,disabled:x||!o.trim(),children:[x&&e.jsx(xe,{size:12,className:"spinner"}),"Save to Vault"]})})]})})})})}function wo({vaultPath:s,onSaved:t}){const[a,i]=r.useState(!1),[n,c]=r.useState(!1),o=r.useRef(null),l=r.useRef([]),x=async()=>{try{const d=await navigator.mediaDevices.getUserMedia({audio:!0}),m=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm",h=new MediaRecorder(d,{mimeType:m});h.ondataavailable=g=>{g.data&&g.data.size>0&&l.current.push(g.data)},h.onstop=async()=>{const g=new Blob(l.current,{type:"audio/webm"});l.current=[],d.getTracks().forEach(j=>j.stop()),await u(g)},h.start(1e3),o.current=h,i(!0)}catch(d){console.error("[VoiceRecorder] failed to start recording:",d)}},p=()=>{const d=o.current;d&&(d.stop(),i(!1),c(!0))},u=async d=>{try{const m=new FormData;m.append("audio",d,"voice-note.webm"),m.append("vaultPath",s||"");const h=await fetch("/api/voice/upload",{method:"POST",body:m});if(!h.ok){console.error("[VoiceRecorder] upload failed:",h.status,await h.text()),c(!1);return}const{notePath:g,transcription:j}=await h.json();t==null||t(g,j)}catch(m){console.error("[VoiceRecorder] upload error:",m)}finally{c(!1)}};return e.jsxs("div",{className:"voice-recorder",children:[!a&&!n&&e.jsxs($,{variant:"accent",size:"sm",onClick:x,"aria-label":"Start recording",children:[e.jsx(At,{size:14})," Record"]}),a&&e.jsxs($,{variant:"danger",size:"sm",onClick:p,"aria-label":"Stop recording",children:[e.jsx(Dn,{size:14})," Stop"]}),n&&e.jsxs($,{variant:"secondary",size:"sm",disabled:!0,children:[e.jsx(xe,{size:14,className:"spinning"})," Transcribing…"]})]})}function So({note:s,onDelete:t}){const[a,i]=r.useState(!1),[n]=r.useState(()=>{if(!s.audioPath)return null;const l=new Audio(`/api/voice/${s.id}/audio`);return l.onended=()=>i(!1),l}),c=()=>{n&&(a?(n.pause(),n.currentTime=0,i(!1)):(n.play(),i(!0)))},o=new Date(s.createdAtMs).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"});return e.jsxs("div",{className:"voice-note-card",children:[e.jsxs("div",{className:"voice-note-card-head",children:[e.jsxs("div",{className:"voice-note-card-meta",children:[e.jsx("span",{className:"voice-note-date",children:o}),s.durationSec&&e.jsxs("span",{className:"voice-note-duration",children:[Math.round(s.durationSec),"s"]})]}),e.jsxs("div",{className:"voice-note-card-actions",children:[n&&e.jsx("button",{type:"button",className:"icon-btn",onClick:c,"aria-label":a?"Pause":"Play",title:a?"Pause":"Play",children:a?e.jsx(ma,{size:13}):e.jsx(Ls,{size:13})}),e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>t(s.id),"aria-label":"Delete note",title:"Delete note",children:e.jsx(ke,{size:13})})]})]}),s.transcript&&e.jsx("p",{className:"voice-note-transcript",children:s.transcript}),!s.transcript&&e.jsx("p",{className:"voice-note-no-transcript muted text-sm",children:"No transcription available"})]})}function Co({vaultPath:s,refreshKey:t=0}){const[a,i]=r.useState([]),[n,c]=r.useState(""),[o,l]=r.useState(!0),x=async()=>{l(!0);try{const d=s?`?vaultPath=${encodeURIComponent(s)}`:"",h=await(await fetch(`/api/voice/list${d}`)).json();i(h.notes||[])}catch(d){console.error("[VoiceNotesPanel] failed to load notes:",d)}finally{l(!1)}};r.useEffect(()=>{x();const d=g=>{try{const j=JSON.parse(g.data);j.type==="voice:updated"&&j.noteId&&i(k=>k.map(z=>{var N;return z.id===j.noteId?{...z,transcript:((N=j.patch)==null?void 0:N.transcript)??z.transcript}:z}))}catch{}},m=`${location.protocol==="https:"?"wss":"ws"}://${location.host}/ws`;let h=null;try{h=new WebSocket(m),h.addEventListener("message",d)}catch{}return()=>{h==null||h.removeEventListener("message",d),h==null||h.close()}},[s,t]);const p=async d=>{try{const m=await fetch(`/api/voice/${d}`,{method:"DELETE"});(m.ok||m.status===204)&&i(h=>h.filter(g=>g.id!==d))}catch(m){console.error("[VoiceNotesPanel] delete failed:",m)}},u=a.filter(d=>{var m;return!n||(((m=d.transcript)==null?void 0:m.toLowerCase().includes(n.toLowerCase()))??!1)});return e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsx(At,{size:14})," Voice Notes"]}),e.jsx(ne,{children:"Record and transcribe audio notes into your vault"}),e.jsx("div",{className:"memory-search-row",children:e.jsx("input",{type:"text",className:"input search-input",value:n,onChange:d=>c(d.target.value),placeholder:"Search transcripts…","aria-label":"Search voice notes"})}),e.jsx("div",{className:"voice-recorder-row",children:e.jsx(wo,{vaultPath:s,onSaved:x})}),o?e.jsx("p",{className:"muted text-sm",children:"Loading notes…"}):u.length===0?e.jsx("p",{className:"muted text-sm",children:n?"No notes match your search.":"No voice notes yet. Hit Record to add one."}):e.jsx("div",{className:"voice-note-list",children:u.map(d=>e.jsx(So,{note:d,onDelete:p},d.id))})]})}const zo=[{id:"overview",label:"Overview",icon:aa},{id:"lightrag",label:"LightRAG",icon:Pe},{id:"obsidian",label:"Obsidian Vault",icon:be},{id:"git",label:"Git Sync",icon:is},{id:"semantic",label:"Semantic Search",icon:ye},{id:"config",label:"Config",icon:kt},{id:"graph",label:"Memory Graph",icon:fa},{id:"webclip",label:"Web Clip",icon:ja},{id:"screenshot",label:"Screenshot OCR",icon:Pn},{id:"voice",label:"Voice Notes",icon:At}];function To(s){const t=re(),[a,i]=r.useState("overview"),[n,c]=r.useState(0),o=r.useCallback(()=>{c(p=>p+1)},[]),l=r.useCallback(async()=>{o(),t.info("Refreshing memory…",1200)},[o,t]),x=()=>{switch(a){case"overview":return e.jsx(so,{refreshKey:n,onRefresh:o,setActiveSubPanel:i});case"lightrag":return e.jsx(ao,{refreshKey:n});case"obsidian":return e.jsx(io,{refreshKey:n});case"git":return e.jsx(co,{refreshKey:n});case"semantic":return e.jsx(mo,{refreshKey:n});case"config":return e.jsx(uo,{refreshKey:n});case"graph":return e.jsx(vo,{refreshKey:n});case"webclip":return e.jsx(ko,{refreshKey:n});case"screenshot":return e.jsx(No,{refreshKey:n});case"voice":return e.jsx(Co,{refreshKey:n});default:return e.jsxs(G,{children:["Unknown panel: ",a]})}};return e.jsxs("div",{className:"view view-memory memory-tab",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(Pe,{size:18})," Memory"]}),e.jsx("p",{className:"view-subtitle",children:"LightRAG, Obsidian vault, git sync, semantic search, web clips, and screenshot OCR — all in one place."})]}),e.jsx("div",{className:"view-actions",children:e.jsx("button",{type:"button",className:"icon-btn",onClick:l,"aria-label":"Refresh memory",title:"Refresh",children:e.jsx(de,{size:14})})})]}),e.jsxs("div",{className:"memory-tab-body",children:[e.jsx("nav",{className:"memory-source-rail","aria-label":"Memory sources",children:zo.map(p=>{const u=p.icon,d=a===p.id;return e.jsxs("button",{type:"button",role:"tab","aria-selected":d,className:V("memory-source-button",d&&"memory-source-button-active"),onClick:()=>i(p.id),children:[e.jsx(u,{size:16,"aria-hidden":!0}),e.jsx("span",{children:p.label})]},p.id)})}),e.jsx("div",{className:"memory-main",children:x()},a)]})]})}const Ro=Oe.memo(To),Cs=[{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 $o(s,t,a,i){const n=a.has(s.id);return e.jsxs(G,{className:"history-project",style:{marginBottom:4},children:[e.jsxs("div",{className:"history-project-head",children:[e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4,minWidth:0,flex:1},children:[e.jsxs("div",{className:"history-project-name",children:[e.jsx(Fe,{size:16})," ",s.name]}),e.jsx("div",{className:"history-project-meta",children:s.path})]}),e.jsxs("div",{className:"history-project-stats",children:[e.jsxs("span",{className:"history-project-stat",children:[e.jsx("span",{className:"history-project-stat-num",children:s.tasks.done}),e.jsxs("span",{className:"muted",children:["/ ",s.tasks.total," done"]})]}),s.tasks.doing>0&&e.jsxs("span",{className:"history-project-stat",children:[e.jsx("span",{className:"history-project-stat-num",children:s.tasks.doing}),e.jsx("span",{className:"muted",children:"doing"})]}),s.tasks.blocked>0&&e.jsxs("span",{className:"history-project-stat",children:[e.jsx("span",{className:"history-project-stat-num",children:s.tasks.blocked}),e.jsx("span",{className:"muted",children:"blocked"})]}),e.jsxs("span",{className:"history-project-stat",children:[e.jsx(be,{size:11})," ",e.jsx("span",{className:"history-project-stat-num",children:s.plans}),e.jsxs("span",{className:"muted",children:[" plan",s.plans===1?"":"s"]})]}),s.lastAccessed&&e.jsx("span",{className:"history-project-stat",children:e.jsxs("span",{className:"muted",children:["last opened ",Ce(s.lastAccessed)]})})]}),e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>i(s.id),"aria-label":n?"Collapse":"Expand",children:n?e.jsx(We,{size:14}):e.jsx(Xe,{size:14})})]}),n&&e.jsx("div",{className:"history-timeline-mini",children:t.length===0?e.jsx("div",{className:"muted",style:{padding:"12px 8px",fontSize:12},children:"No events in this time range."}):t.slice(-100).reverse().map((c,o)=>e.jsxs("div",{className:"history-timeline-row",children:[e.jsx("span",{className:"history-timeline-ts",children:new Date(c.ts).toLocaleTimeString()}),e.jsx("span",{className:"history-timeline-kind",children:c.kind||"event"}),e.jsxs("span",{className:"history-timeline-msg",title:String(c.text||c.title||""),children:[c.author?`@${c.author} `:"",String(c.text??c.title??c.name??"")]})]},o))})]},s.id)}function Ao({snapshot:s}){var k,z;const t=re(),[a,i]=r.useState(null),[n,c]=r.useState(!0),[o,l]=r.useState("1d"),[x,p]=r.useState(new Set),[u,d]=r.useState(0),m=async N=>{try{const S=N?`?since=${encodeURIComponent(N)}&limit=1000`:"?limit=1000",E=await T.get(`/history${S}`);i(E),p(new Set(E.projects.filter(v=>E.events.some(b=>b.projectId===v.id)).map(v=>v.id)))}catch(S){t.error(`History load failed: ${S.message}`)}finally{c(!1)}};r.useEffect(()=>{c(!0);const N=Cs.find(S=>S.id===o)||Cs[1];if(N.ms>0){const S=new Date(Date.now()-N.ms).toISOString();m(S)}else m()},[o]),r.useEffect(()=>{const N=setInterval(()=>d(S=>S+1),3e4);return()=>clearInterval(N)},[]);const h=new Map;for(const N of(a==null?void 0:a.events)||[]){const S=N.projectId||"global";h.has(S)||h.set(S,[]),h.get(S).push(N)}const g=N=>{p(S=>{const E=new Set(S);return E.has(N)?E.delete(N):E.add(N),E})},j=()=>{if(!a)return;const N=new Blob([JSON.stringify(a,null,2)],{type:"application/json"}),S=URL.createObjectURL(N),E=document.createElement("a");E.href=S,E.download=`bizar-history-${new Date().toISOString().replace(/[:.]/g,"-")}.json`,E.click(),URL.revokeObjectURL(S),t.success("History exported.")};return e.jsxs("div",{className:"view view-history","data-tick":u,children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx($s,{size:18})," History"]}),e.jsxs("p",{className:"view-subtitle",children:["Cross-project history of events, tasks, and plans.",((k=a==null?void 0:a.stats)==null?void 0:k.lastTs)&&e.jsxs(e.Fragment,{children:[" · last event ",Ce(a.stats.lastTs)]})]})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs("div",{className:"tasks-toolbar-group",children:[e.jsx(Fn,{size:14,style:{color:"var(--text-dim)"},"aria-hidden":!0}),e.jsx("label",{htmlFor:"history-range",className:"sr-only",children:"Time range"}),e.jsx("select",{id:"history-range",className:"select select-sm",value:o,onChange:N=>l(N.target.value),title:"Time range","aria-label":"Time range",children:Cs.map(N=>e.jsx("option",{value:N.id,children:N.label},N.id))})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>{c(!0);const N=Cs.find(S=>S.id===o)||Cs[1];N.ms>0?m(new Date(Date.now()-N.ms).toISOString()):m()},children:[e.jsx(de,{size:14})," Refresh"]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:j,children:[e.jsx(ls,{size:14})," Export"]})]})]}),n&&e.jsxs("div",{className:"view-loading",children:[e.jsx(oe,{size:"lg"}),e.jsx("p",{children:"Loading history…"})]}),!n&&a&&e.jsxs("div",{className:"history-list",children:[a.projects.length===0&&e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsx(Fe,{size:14})," No projects"]}),e.jsx(ne,{children:"Register a project in Overview to start tracking history."})]}),a.projects.length>0&&e.jsx(Mt,{items:a.projects,itemHeight:70,height:Math.min(a.projects.length*70,500),className:"history-virtual-list",renderItem:N=>$o(N,h.get(N.id)||[],x,g)}),h.has("global")&&e.jsxs(G,{className:"history-project",children:[e.jsx("div",{className:"history-project-head",children:e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4,minWidth:0,flex:1},children:[e.jsxs("div",{className:"history-project-name",children:[e.jsx($s,{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:(h.get("global")||[]).slice(-100).reverse().map((N,S)=>e.jsxs("div",{className:"history-timeline-row",children:[e.jsx("span",{className:"history-timeline-ts",children:new Date(N.ts).toLocaleTimeString()}),e.jsx("span",{className:"history-timeline-kind",children:N.kind||"event"}),e.jsxs("span",{className:"history-timeline-msg",title:String(N.text||N.title||""),children:[N.author?`@${N.author} `:"",String(N.text??N.title??N.name??"")]})]},S))})]}),((z=a.stats)==null?void 0:z.counts)&&Object.keys(a.stats.counts).length>0&&e.jsxs(G,{children:[e.jsx(te,{children:"Event counts by kind"}),e.jsxs(ne,{children:[a.stats.lines," total lines in log"]}),e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:8,marginTop:8},children:Object.entries(a.stats.counts).sort((N,S)=>S[1]-N[1]).slice(0,30).map(([N,S])=>e.jsxs("span",{className:V("tag","tag-neutral"),style:{fontFamily:"var(--font-mono)"},children:[N,": ",S]},N))})]})]})]})}const ve={top:16,right:20,bottom:40,left:52};function Mo({series:s,height:t=280,onHover:a,className:i}){const n=r.useRef(null),[c,o]=r.useState(null),{labels:l,requests:x,tokens:p}=s,u=l.length;if(u===0)return e.jsx("div",{className:V("usage-chart-empty",i),style:{height:t},children:e.jsx("span",{children:"No data for this range"})});const d=600-ve.left-ve.right,m=t-ve.top-ve.bottom,h=Math.max(...x,1),g=Math.max(...p,1),j=Math.max(4,Math.min(24,Math.floor(d/u)-4)),k=(d-j*u)/(u+1);function z(A){return ve.left+k+A*(j+k)}function N(A){return A/h*m*.75}function S(A){return ve.top+m-A/g*m*.75}const E=p.map((A,P)=>`${z(P)+j/2},${S(A)}`).join(" "),v=[0,.25,.5,.75,1].map(A=>({y:ve.top+m-A*m*.75,label:A===0?"0":`${Math.round(h*A).toLocaleString()}`})),b=[0,.25,.5,.75,1].map(A=>({y:ve.top+m-A*m*.75,label:A===0?"0":`${Math.round(g*A/1e3)}k`})),w=Math.max(1,Math.floor(u/7)),f=l.map((A,P)=>({i:P,l:A,x:z(P)+j/2})).filter((A,P)=>P%w===0),L=r.useCallback(A=>{if(!n.current)return;const P=n.current.getBoundingClientRect(),C=(A.clientX-P.left)*(600/P.width),D=(A.clientY-P.top)*(t/P.height),Y=C-ve.left,O=Math.round((Y-k/2)/(j+k)),J=Math.max(0,Math.min(u-1,O));o({index:J,x:A.clientX-P.left,y:A.clientY-P.top}),a==null||a(J,C,D)},[u,j,k,a,t]),R=r.useCallback(()=>{o(null),a==null||a(null,0,0)},[a]),y=c;return e.jsxs("div",{ref:n,className:V("usage-chart",i),style:{position:"relative"},children:[e.jsxs("svg",{viewBox:`0 0 600 ${t}`,width:"100%",height:t,style:{display:"block",overflow:"visible"},onMouseMove:L,onMouseLeave:R,children:[v.map((A,P)=>e.jsx("line",{x1:ve.left,y1:A.y,x2:600-ve.right,y2:A.y,stroke:"var(--border)",strokeWidth:1,strokeDasharray:"4,3",opacity:.5},`grid-${P}`)),v.map((A,P)=>e.jsx("text",{x:ve.left-6,y:A.y+4,textAnchor:"end",fontSize:10,fill:"var(--text-muted)",fontFamily:"var(--font-mono, ui-monospace, monospace)",children:A.label},`ly-${P}`)),b.map((A,P)=>e.jsx("text",{x:600-ve.right+6,y:A.y+4,textAnchor:"start",fontSize:10,fill:"var(--text-muted)",fontFamily:"var(--font-mono, ui-monospace, monospace)",children:A.label},`ry-${P}`)),x.map((A,P)=>{const C=N(A),D=z(P),Y=ve.top+m-C;return e.jsx("rect",{x:D,y:Y,width:j,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:E,fill:"none",stroke:"var(--warning, #d29922)",strokeWidth:2,strokeLinejoin:"round",strokeLinecap:"round",opacity:.9}),p.map((A,P)=>e.jsx("circle",{cx:z(P)+j/2,cy:S(A),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}`)),f.map(({i:A,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-${A}`)),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:x[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 es({label:s,col:t,sortKey:a,sortDir:i,onSort:n}){const c=a===t;return e.jsxs("th",{className:V("usage-sort-header",c&&"is-active"),onClick:()=>n(t),"aria-sort":c?i==="asc"?"ascending":"descending":"none",children:[e.jsx("span",{children:s}),e.jsx("span",{className:"usage-sort-icon",children:c?i==="asc"?" ↑":" ↓":" ↕"})]})}function Io({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(es,{label:"Model",col:"modelId",sortKey:t,sortDir:a,onSort:i}),e.jsx(es,{label:"Requests",col:"requests",sortKey:t,sortDir:a,onSort:i}),e.jsx(es,{label:"Prompt Tok",col:"promptTokens",sortKey:t,sortDir:a,onSort:i}),e.jsx(es,{label:"Compl Tok",col:"completionTokens",sortKey:t,sortDir:a,onSort:i}),e.jsx(es,{label:"Total Tok",col:"totalTokens",sortKey:t,sortDir:a,onSort:i}),e.jsx(es,{label:"Avg Latency",col:"avgLatencyMs",sortKey:t,sortDir:a,onSort:i}),e.jsx(es,{label:"Errors",col:"errors",sortKey:t,sortDir:a,onSort:i})]})}),e.jsx("tbody",{children:s.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:7,className:"usage-table-empty",children:"No data for this range"})}):s.map(n=>e.jsxs("tr",{children:[e.jsx("td",{className:"usage-table-model",children:e.jsx("code",{children:n.modelId})}),e.jsx("td",{className:"mono",children:n.requests.toLocaleString()}),e.jsx("td",{className:"mono",children:n.promptTokens.toLocaleString()}),e.jsx("td",{className:"mono",children:n.completionTokens.toLocaleString()}),e.jsx("td",{className:"mono",children:n.totalTokens.toLocaleString()}),e.jsxs("td",{className:"mono",children:[n.avgLatencyMs,"ms"]}),e.jsx("td",{className:V("mono",n.errors>0&&"is-err"),children:n.errors>0?n.errors:"—"})]},`${n.providerId}::${n.modelId}`))})]})})}function Eo({activeTab:s,setActiveTab:t}){const[a,i]=r.useState("quota"),n=re();return e.jsxs("div",{className:"view-container view-minimax-usage",children:[e.jsxs("div",{className:"minimax-sub-tabs",children:[e.jsxs("button",{className:V("minimax-sub-tab",a==="quota"&&"is-active"),onClick:()=>i("quota"),children:[e.jsx(Nt,{size:13})," Token Plan"]}),e.jsxs("button",{className:V("minimax-sub-tab",a==="analytics"&&"is-active"),onClick:()=>i("analytics"),children:[e.jsx(va,{size:13})," Usage Analytics"]})]}),a==="quota"?e.jsx(Lo,{activeTab:s,setActiveTab:t}):e.jsx(Do,{toast:n})]})}function Lo({activeTab:s,setActiveTab:t}){var K;const a=re(),[i,n]=r.useState(null),[c,o]=r.useState(null),[l,x]=r.useState(null),[p,u]=r.useState(!0),[d,m]=r.useState(!1),[h,g]=r.useState(null),[j,k]=r.useState(null),[z,N]=r.useState(!1),[S,E]=r.useState(0),[v,b]=r.useState(!1),[w,f]=r.useState(null),[L,R]=r.useState(""),[y,A]=r.useState(!1),[P,C]=r.useState(!1),D=r.useCallback(async()=>{u(!0),g(null);try{const[B,Z,he]=await Promise.all([T.get("/minimax/status"),T.get("/minimax/remains"),T.get("/minimax/onboarding")]);n(B),o(Z),x(he),B.configured&&E(4)}catch(B){g(B.message||"Failed to load MiniMax data")}finally{u(!1)}},[]);r.useEffect(()=>{D()},[D]);const Y=r.useCallback(async()=>{try{await T.post("/minimax/onboarding",{dismissedAt:Date.now()}),x(B=>B&&{...B,dismissedAt:Date.now()})}catch{}},[]),O=r.useCallback(async()=>{if(!L.trim()){a.error("Paste a Subscription Key first.");return}b(!0),f(null);try{const B=await T.post("/minimax/test",{prompt:"Reply with a single word: pong",model:"MiniMax-M3",maxTokens:16});if(f(B),B.ok){E(3),a.success("Key works. Saving…");try{await T.post("/minimax/onboarding/save-key",{key:L.trim(),groupId:"default"}),ae(),a.success("Subscription Key saved.")}catch(Z){a.error(`Save failed: ${Z.message}`)}D()}else a.error(`Verification failed: ${B.message??B.error??"unknown"}`)}catch(B){a.error(`Test request failed: ${B.message}`)}finally{b(!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 T.post("/minimax/onboarding/save-key",{key:L.trim(),groupId:"default"});if(!B.ok){a.error(`Save failed: ${B.message??B.error??"unknown"}`);return}R(""),ae(),a.success("Subscription Key saved. Loading quota…"),D()}catch(B){a.error(`Save failed: ${B.message}`)}finally{C(!1)}},[L,a,D]),ae=r.useCallback(async()=>{try{await T.del("/minimax/cache")}catch{}},[]),ee=r.useCallback(async()=>{m(!0),g(null);try{await T.post("/minimax/remains/refresh"),await D(),a.success("Refreshed")}catch(B){a.error(`Refresh failed: ${B.message}`)}finally{m(!1)}},[D,a]),F=r.useCallback(async()=>{var B;N(!0),k(null);try{const Z=await T.post("/minimax/test",{prompt:"Reply with a single word: pong",model:"MiniMax-M3",maxTokens:16});k(Z),Z.ok?a.success(`Test ok — used ${((B=Z.usage)==null?void 0:B.total_tokens)??"?"} tokens`):a.error(`Test failed: ${Z.message??Z.error??"unknown"}`)}catch(Z){a.error(`Test request failed: ${Z.message}`)}finally{N(!1)}},[a]);return p&&!i?e.jsxs("div",{className:"view-container",children:[e.jsx(oe,{})," Loading MiniMax data…"]}):i?!i.configured&&(l==null?void 0:l.dismissedAt)==null&&S<4?e.jsx(Oo,{step:S,setStep:E,keyDraft:L,setKeyDraft:R,showKey:y,setShowKey:A,verifying:v,verifyResult:w,onVerify:O,onSkip:async()=>{await Y(),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(Nt,{size:20,style:{verticalAlign:"text-bottom",marginRight:6}}),"MiniMax Token Plan"]}),e.jsxs("p",{className:"view-subtitle",children:["Remaining 5-hour + weekly quota per model. Fetches live from"," ",e.jsx("code",{children:"www.minimax.io/v1/token_plan/remains"}),"."]})]}),e.jsxs("div",{className:"view-header-actions",children:[e.jsxs($,{variant:"secondary",size:"sm",onClick:()=>t("settings"),title:"Configure your Subscription Key",children:[e.jsx(Rt,{size:14})," ",i.configured?`Key ${i.apiKeyHint}`:"Add key"]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:ee,disabled:d,children:[d?e.jsx(xe,{size:14,className:"spin"}):e.jsx(de,{size:14})," Refresh"]})]})]}),c&&!c.ok&&e.jsxs("div",{className:"banner banner-err",children:[e.jsx(Te,{size:16}),e.jsxs("span",{children:[e.jsx("strong",{children:"Couldn't load quota"}),": ",c.message??c.error??"unknown error"]})]}),(c==null?void 0:c.ok)&&c.models&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"minimax-stats-row",children:[e.jsx(Bs,{label:"Models tracked",value:String(c.models.length),hint:"Distinct model quotas returned by the API"}),e.jsx(Bs,{label:"Last fetched",value:c.fetchedAt?Fo(c.fetchedAt):"—",hint:"Refreshed on demand + every 60s"}),e.jsx(Bs,{label:"Group",value:c.groupId??"—",hint:"Usually 'default' for an individual team"}),e.jsx(Bs,{label:"API key",value:c.apiKeyHint??"—",hint:"Masked; the real key never leaves auth.json"})]}),e.jsx("div",{className:"minimax-models-grid",children:c.models.map(B=>e.jsx(Po,{model:B},B.model_name))})]}),i.configured&&e.jsxs(G,{id:"minimax-test",children:[e.jsxs(te,{children:[e.jsx(rs,{size:14})," Test the API key"]}),e.jsxs(ne,{children:["One-shot chat completion to ",e.jsxs("code",{children:[i.chatBaseUrl,"/chat/completions"]}),"."]}),e.jsxs("div",{className:"minimax-test-actions",children:[e.jsxs($,{onClick:F,disabled:z,variant:"primary",size:"sm",children:[z?e.jsx(xe,{size:14,className:"spin"}):e.jsx(rs,{size:14})," Send test prompt"]}),e.jsx("code",{className:"minimax-test-prompt",children:'"Reply with a single word: pong"'})]}),j&&e.jsxs("div",{className:V("minimax-test-result",j.ok?"ok":"err"),children:[j.ok?e.jsx(qe,{size:14}):e.jsx(Te,{size:14}),e.jsx("div",{className:"minimax-test-body",children:j.ok?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"minimax-test-line",children:[e.jsx("strong",{children:"model:"})," ",e.jsx("code",{children:j.model})," ·"," ",e.jsx("strong",{children:"finish:"})," ",j.finishReason??"—"]}),j.content&&e.jsx("div",{className:"minimax-test-content",children:e.jsx("code",{children:j.content})}),j.usage&&e.jsxs("div",{className:"minimax-test-usage",children:[e.jsx("strong",{children:"usage:"})," total ",e.jsx("code",{children:j.usage.total_tokens??"?"})," · prompt"," ",e.jsx("code",{children:j.usage.prompt_tokens??"?"})," · completion"," ",e.jsx("code",{children:j.usage.completion_tokens??"?"}),((K=j.usage.prompt_tokens_details)==null?void 0:K.cached_tokens)!=null&&e.jsxs(e.Fragment,{children:[" · cached ",e.jsx("code",{children:j.usage.prompt_tokens_details.cached_tokens})]})]})]}):e.jsx("pre",{children:j.message??j.error??"unknown error"})})]})]})]}):e.jsx("div",{className:"view-container",children:e.jsxs("div",{className:"error-card",children:[e.jsx(Te,{size:20}),e.jsxs("div",{children:[e.jsx("strong",{children:"Couldn't load MiniMax status"}),e.jsx("pre",{children:h??"unknown error"})]})]})})}function Do({toast:s}){const[t,a]=r.useState("24h"),[i,n]=r.useState(""),[c,o]=r.useState(""),[l,x]=r.useState(!0),[p,u]=r.useState(null),[d,m]=r.useState([]),[h,g]=r.useState("requests"),[j,k]=r.useState("desc"),[z,N]=r.useState(!1),S=r.useCallback(async(y,A,P)=>{x(!0);try{const C=new URLSearchParams({range:y});y==="custom"&&A&&P&&(C.set("from",String(A)),C.set("to",String(P)));const[D,Y]=await Promise.all([T.get(`/usage?${C.toString()}`),T.get("/usage/recent?limit=20")]);u(D),m(Y.records)}catch(C){s.error(`Failed to load usage data: ${C.message}`)}finally{x(!1)}},[s]);r.useEffect(()=>{if(t==="custom"){const y=i?new Date(i).getTime():Date.now()-6048e5,A=c?new Date(c).getTime():Date.now();S("custom",y,A)}else S(t)},[t,S]);const E=r.useCallback(y=>{h===y?k(A=>A==="asc"?"desc":"asc"):(g(y),k("desc"))},[h]),v=r.useMemo(()=>p!=null&&p.perModel?[...p.perModel].sort((y,A)=>{const P=y[h]??0,C=A[h]??0,D=typeof P=="number"&&typeof C=="number"?P-C:String(P).localeCompare(String(C));return j==="asc"?D:-D}):[],[p==null?void 0:p.perModel,h,j]),b=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]),w=r.useCallback(async()=>{N(!0),await S(t==="custom"?"custom":t,t==="custom"&&i?new Date(i).getTime():void 0,t==="custom"&&c?new Date(c).getTime():void 0),N(!1)},[S,t,i,c]);if(l&&!p)return e.jsxs("div",{className:"view-container",children:[e.jsx(oe,{})," Loading usage data…"]});const f=p==null?void 0:p.totals,L=(p==null?void 0:p.errors)??[],R=(p==null?void 0:p.perKey)??[];return e.jsxs(e.Fragment,{children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-titles",children:[e.jsxs("h1",{className:"view-title",children:[e.jsx(va,{size:20,style:{verticalAlign:"text-bottom",marginRight:6}}),"Usage Analytics"]}),e.jsxs("p",{className:"view-subtitle",children:["Aggregated from ",e.jsx("code",{children:"~/.local/share/bizar/usage.jsonl"})," — every chatCompletion and fetchRemains call."]})]}),e.jsx("div",{className:"view-header-actions",children:e.jsxs($,{variant:"secondary",size:"sm",onClick:w,disabled:z,children:[z?e.jsx(xe,{size:14,className:"spin"}):e.jsx(de,{size:14})," Refresh"]})})]}),e.jsxs("div",{className:"usage-time-range",children:[["24h","7d","30d","custom"].map(y=>e.jsx("button",{className:V("usage-range-chip",t===y&&"is-active"),onClick:()=>a(y),children:y==="custom"?"Custom":y.toUpperCase()},y)),t==="custom"&&e.jsxs("div",{className:"usage-custom-dates",children:[e.jsx("label",{htmlFor:"usage-from-date",className:"sr-only",children:"From date"}),e.jsx("input",{id:"usage-from-date",type:"date",className:"usage-date-input",value:i,onChange:y=>n(y.target.value),"aria-label":"From date"}),e.jsx("span",{style:{color:"var(--text-muted)",fontSize:12},"aria-hidden":!0,children:"to"}),e.jsx("label",{htmlFor:"usage-to-date",className:"sr-only",children:"To date"}),e.jsx("input",{id:"usage-to-date",type:"date",className:"usage-date-input",value:c,onChange:y=>o(y.target.value),"aria-label":"To date"})]})]}),e.jsxs("div",{className:"usage-kpi-row",children:[e.jsx(zs,{label:"Total Requests",value:(f==null?void 0:f.requests.toLocaleString())??"—",sub:f?`${f.errors} errors`:void 0,tone:f&&f.errors>f.requests*.1?"warn":void 0}),e.jsx(zs,{label:"Total Tokens",value:f?f.totalTokens>=1e3?`${Math.round(f.totalTokens/1e3)}k`:String(f.totalTokens):"—",sub:f?`${f.promptTokens.toLocaleString()} prompt · ${f.completionTokens.toLocaleString()} completion`:void 0}),e.jsx(zs,{label:"Errors",value:String((f==null?void 0:f.errors)??"—"),sub:L.length>0?`${L[0].code}: ${L[0].count}`:void 0,tone:f&&f.errors>0?"err":void 0}),e.jsx(zs,{label:"Avg Latency",value:(f==null?void 0:f.avgLatencyMs)!=null?`${f.avgLatencyMs}ms`:"—",sub:(f==null?void 0:f.p95LatencyMs)!=null?`p95 ${f.p95LatencyMs}ms`:void 0}),e.jsx(zs,{label:"Est. Cost",value:(f==null?void 0:f.costEstimate)!=null&&f.costEstimate>0?`$${f.costEstimate.toFixed(4)}`:"—",sub:"approximate USD",tone:void 0})]}),e.jsxs(G,{className:"usage-chart-card",children:[e.jsx("div",{className:"usage-chart-wrap",children:e.jsx(Mo,{series:b,height:280})}),e.jsxs("div",{className:"usage-legend",children:[e.jsxs("div",{className:"usage-legend-item",children:[e.jsx("div",{className:"usage-legend-bar",style:{background:"var(--accent)"}}),e.jsx("span",{children:"Requests (bar)"})]}),e.jsxs("div",{className:"usage-legend-item",children:[e.jsx("div",{className:"usage-legend-line",style:{background:"var(--warning, #d29922)"}}),e.jsx("span",{children:"Tokens (line)"})]})]})]}),e.jsxs(G,{children:[e.jsx(te,{children:"Per-model breakdown"}),e.jsx(Io,{rows:v,sortKey:h,sortDir:j,onSort:E})]}),R.length>0&&e.jsxs(G,{children:[e.jsx(te,{children:"API Keys"}),e.jsx("div",{className:"usage-key-row",children:R.map(y=>e.jsxs("span",{className:V("usage-key-badge",y.isBackup?"is-backup":"is-active"),children:[e.jsx("span",{className:"usage-key-dot"}),y.keyEnvVar,y.isBackup?" (backup)":" (active)"," · ",y.requests," req"]},y.keyEnvVar))})]}),d.length>0&&e.jsxs(G,{children:[e.jsx(te,{children:"Recent activity"}),e.jsx("div",{className:"usage-recent-list",children:d.map((y,A)=>e.jsxs("div",{className:V("usage-recent-item",y.error&&"is-err"),children:[e.jsx("span",{className:"usage-recent-time",children:new Date(y.ts).toLocaleTimeString()}),e.jsx("span",{className:"usage-recent-model",children:e.jsx("code",{children:y.modelId})}),e.jsxs("span",{className:"usage-recent-tokens",children:[y.totalTokens.toLocaleString()," tok"]}),e.jsxs("span",{className:"usage-recent-latency",children:[y.latencyMs,"ms"]}),e.jsx("span",{className:"usage-recent-endpoint",children:y.endpoint})]},`${y.requestId}-${A}`))})]})]})}function zs({label:s,value:t,sub:a,tone:i}){return e.jsxs("div",{className:"usage-kpi-card",children:[e.jsx("div",{className:"usage-kpi-label",children:s}),e.jsx("div",{className:V("usage-kpi-value",i&&`is-${i}`),children:t}),a&&e.jsx("div",{className:"usage-kpi-sub",children:a})]})}function Bs({label:s,value:t,hint:a}){return e.jsxs("div",{className:"stat",children:[e.jsx("div",{className:"stat-label",children:s}),e.jsx("div",{className:"stat-value",children:t}),a&&e.jsx("div",{className:"stat-hint",children:a})]})}function Po({model:s}){const t=Us(s.current_interval_remaining_percent??0,0,100),a=Us(s.current_weekly_remaining_percent??0,0,100),i=Us(100-t,0,100),n=Us(100-a,0,100);return e.jsxs(G,{id:`minimax-model-${s.model_name}`,className:"minimax-model-card",children:[e.jsxs("div",{className:"minimax-model-head",children:[e.jsx("div",{className:"minimax-model-name",children:s.model_name}),e.jsxs("div",{className:V("minimax-model-status",t<25||a<25?"is-warn":"is-ok"),children:[s.current_interval_status===1?"active":"idle"," ·"," ",s.current_weekly_status===1?"week active":"week idle"]})]}),e.jsxs("div",{className:"minimax-quota-rows",children:[e.jsx(Qt,{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(Qt,{icon:e.jsx(On,{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 Qt({icon:s,label:t,remainingPct:a,consumedPct:i,used:n,total:c,resetIn:o,resetISO:l}){const x=a>=75?"good":a>=25?"warn":"low";return e.jsxs("div",{className:`minimax-quota-row is-${x}`,children:[e.jsxs("div",{className:"minimax-quota-head",children:[e.jsxs("span",{className:"minimax-quota-label",children:[s," ",t]}),e.jsxs("span",{className:"minimax-quota-remaining",children:[a,"% remaining"]}),e.jsxs("span",{className:"minimax-quota-consumed",children:["· ",i,"% used"]})]}),e.jsx("div",{className:"minimax-bar",children:e.jsx("div",{className:"minimax-bar-fill",style:{width:`${i}%`},"aria-label":`${i}% consumed`})}),e.jsxs("div",{className:"minimax-quota-meta",children:[e.jsxs("span",{children:[e.jsx("strong",{children:n})," / ",c||"—"," requests"]}),e.jsx("span",{title:l,children:o?`resets in ${o}`:"—"})]})]})}function Us(s,t,a){return Math.max(t,Math.min(a,s))}function Fo(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 Oo({step:s,setStep:t,keyDraft:a,setKeyDraft:i,showKey:n,setShowKey:c,verifying:o,verifyResult:l,onVerify:x,onSkip:p,onManualKeySave:u,savingKey:d,status:m}){return e.jsxs("div",{className:"view-container view-minimax-onboarding",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-titles",children:[e.jsxs("h1",{className:"view-title",children:[e.jsx(He,{size:20,style:{verticalAlign:"text-bottom",marginRight:6}}),"Set up MiniMax Token Plan tracking"]}),e.jsx("p",{className:"view-subtitle",children:"We'll read your Subscription Key and show your remaining quota."})]}),e.jsx("div",{className:"view-header-actions",children:e.jsxs($,{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((h,g)=>e.jsxs("div",{className:V("minimax-wizard-step",g===s&&"is-current",g<s&&"is-done",g>s&&"is-todo"),children:[e.jsx("div",{className:"minimax-wizard-step-bullet",children:g<s?e.jsx(qe,{size:14}):g+1}),e.jsx("div",{className:"minimax-wizard-step-label",children:h})]},h))}),e.jsxs(G,{id:"minimax-wizard-card",children:[s===0&&e.jsxs("div",{className:"minimax-wizard-body",children:[e.jsx("h3",{className:"minimax-wizard-title",children:"Welcome"}),e.jsxs("p",{className:"minimax-wizard-prose",children:["BizarHarness shows you how much of your MiniMax Token Plan quota you have left — both the ",e.jsx("strong",{children:"5-hour rolling"})," and ",e.jsx("strong",{children:"weekly"})," windows."]}),e.jsxs("ul",{className:"minimax-wizard-list",children:[e.jsxs("li",{children:["Stored in ",e.jsx("code",{children:"~/.local/share/opencode/auth.json"}),"."]}),e.jsx("li",{children:"Read fresh on every dashboard load."}),e.jsx("li",{children:"Never logged in full."})]}),e.jsx("div",{className:"minimax-wizard-actions",children:e.jsxs($,{onClick:()=>t(1),variant:"primary",size:"md",children:["Get started ",e.jsx("span",{style:{marginLeft:6},children:"→"})]})})]}),s===1&&e.jsxs("div",{className:"minimax-wizard-body",children:[e.jsx("h3",{className:"minimax-wizard-title",children:"Get your Subscription Key"}),e.jsx("p",{className:"minimax-wizard-prose",children:"Go to the MiniMax console and copy your Subscription Key."}),e.jsxs("ol",{className:"minimax-wizard-list",children:[e.jsxs("li",{children:["Open ",e.jsxs("a",{href:"https://platform.minimax.io/user-center/payment/token-plan",target:"_blank",rel:"noreferrer",className:"minimax-wizard-link",children:[e.jsx(ys,{size:12})," platform.minimax.io"]})]}),e.jsxs("li",{children:["Click ",e.jsx("strong",{children:"Copy Subscription Key"}),"."]}),e.jsx("li",{children:"Come back here and paste it."})]}),e.jsxs("div",{className:"minimax-wizard-actions",children:[e.jsx($,{variant:"secondary",size:"md",onClick:()=>t(0),children:"← Back"}),e.jsxs($,{variant:"primary",size:"md",onClick:()=>t(2),children:["I have my key ",e.jsx("span",{style:{marginLeft:6},children:"→"})]})]})]}),s===2&&e.jsxs("div",{className:"minimax-wizard-body",children:[e.jsx("h3",{className:"minimax-wizard-title",children:"Paste & test"}),e.jsx("p",{className:"minimax-wizard-prose",children:"Paste your key below. We'll test it against the real API before saving."}),e.jsx("div",{className:"minimax-key-row",children:e.jsxs("div",{className:"minimax-key-input-wrap",children:[e.jsx(Rt,{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:h=>i(h.target.value),placeholder:"sk-cp-...",spellCheck:!1,autoComplete:"off",className:"minimax-key-input",autoFocus:!0,"aria-label":"Subscription Key"}),e.jsx("button",{type:"button",onClick:()=>c(h=>!h),className:"minimax-key-toggle","aria-label":n?"Hide key":"Show key",children:n?e.jsx(pt,{size:13}):e.jsx(fs,{size:13})})]})}),l&&!l.ok&&e.jsxs("div",{className:"minimax-wizard-error",children:[e.jsx(Te,{size:14}),e.jsxs("span",{children:[e.jsx("strong",{children:"Verification failed:"})," ",l.message??l.error]})]}),e.jsxs("div",{className:"minimax-wizard-actions",children:[e.jsx($,{variant:"secondary",size:"md",onClick:()=>t(1),children:"← Back"}),e.jsxs($,{variant:"primary",size:"md",onClick:x,disabled:o||!a.trim(),children:[o?e.jsx(xe,{size:14,className:"spin"}):e.jsx(Ms,{size:14}),o?"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:h=>{h.preventDefault(),u()},className:"minimax-wizard-link",children:"Save without testing"})]})]}),s===3&&e.jsxs("div",{className:"minimax-wizard-body",children:[e.jsxs("h3",{className:"minimax-wizard-title",children:[e.jsx(qe,{size:18,style:{verticalAlign:"text-bottom",marginRight:6}}),"All set"]}),e.jsx("p",{className:"minimax-wizard-prose",children:"The key works and is saved. Reloading so you can see your live quota."}),e.jsx("div",{className:"minimax-wizard-actions",children:e.jsx($,{variant:"primary",size:"md",onClick:()=>window.location.reload(),children:"View your quota →"})})]}),e.jsxs("div",{className:"minimax-wizard-footer",children:[e.jsx(Ms,{size:11}),e.jsxs("span",{children:["Key written to ",e.jsx("code",{children:"~/.local/share/opencode/auth.json"})," with mode 0600."]})]})]})]})}const Bo=Oe.memo(Eo),Uo={pending:"info",running:"accent",done:"success",failed:"error",killed:"neutral",timed_out:"warning"},_o={pending:"Pending",running:"Running",done:"Done",failed:"Failed",killed:"Killed",timed_out:"Timed out"};function Wo({status:s,dot:t}){const a=Uo[s]||"neutral",i=_o[s]||s;return e.jsx(Je,{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($,{variant:"ghost",onClick:i,children:"Cancel"}),e.jsx($,{variant:"danger",onClick:async()=>{await a(),i()},children:"Kill"})]})]})}function Vo(s,t,a,i,n){s.open({title:"Kill instance?",width:400,children:e.jsx(qo,{instanceId:a,instanceName:i,onConfirm:async()=>{try{const o=await(await fetch(`/api/background/${encodeURIComponent(a)}`,{method:"DELETE"})).json();o.ok?(t.success(`Instance ${a} killed.`),n==null||n()):t.error(`Kill failed: ${o.error||"unknown error"}`)}catch(c){t.error(`Kill failed: ${c.message}`)}},onClose:()=>s.close()})})}function Ho({instance:s}){const t=re(),[a,i]=r.useState(!1),n=s.tmuxSession,c=n?`tmux attach -t ${n}`:null,o=async()=>{if(c)try{await navigator.clipboard.writeText(c),t.success("Attach command copied")}catch{t.error("Could not copy to clipboard")}},l=async()=>{if(!(!s.instanceId||!n)){i(!0);try{const x=await T.post(`/background/${encodeURIComponent(s.instanceId)}/open-terminal`,{emulator:"system"});if(x.ok)t.success("Opening terminal…");else if(t.error(x.error||"Failed to open terminal"),c)try{await navigator.clipboard.writeText(c),t.success("Command copied to clipboard")}catch{}}catch(x){if(t.error(`Failed: ${x.message}`),c)try{await navigator.clipboard.writeText(c),t.success("Command copied to clipboard")}catch{}}finally{i(!1)}}};return n?e.jsxs(G,{variant:"outlined",className:"bg-tmux-card",children:[e.jsxs("div",{className:"bg-tmux-card-header",children:[e.jsx(ns,{size:14}),e.jsx("span",{children:"tmux session"}),s.tmuxActive!==!1?e.jsx("span",{className:"badge badge-success",children:"live"}):e.jsx("span",{className:"badge badge-warning",children:"inactive"})]}),e.jsx("code",{className:"mono bg-tmux-session-name",children:n}),e.jsx("p",{className:"muted bg-tmux-hint",children:"Attach to the agent's tmux session from a terminal on the host running the dashboard."}),e.jsxs("div",{className:"bg-tmux-card-actions",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:o,title:"Copy attach command",children:[e.jsx(os,{size:14})," Copy"]}),e.jsxs($,{variant:"primary",size:"sm",onClick:l,loading:a,title:"Open in system terminal",children:[e.jsx(ns,{size:14})," Open terminal"]})]})]}):e.jsxs(G,{variant:"outlined",className:"bg-tmux-card bg-tmux-card-warn",children:[e.jsxs("div",{className:"bg-tmux-card-header",children:[e.jsx(Te,{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 Go=5e3,Ko=2e3,Yo=120;function Xo(s){return s.status==="pending"||s.status==="running"}function Jo(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 Qo(s){const t=re(),a=$e(),[i,n]=r.useState([]),[c,o]=r.useState(!0),[l,x]=r.useState(null),[,p]=r.useState(0),u=r.useCallback(async()=>{try{const j=await T.get("/background");n(Array.isArray(j==null?void 0:j.instances)?j.instances:[]),x(null)}catch(j){x((j==null?void 0:j.message)||"Failed to load background agents.")}finally{o(!1)}},[]);r.useEffect(()=>{u();const j=setInterval(u,Go);return()=>clearInterval(j)},[u]),r.useEffect(()=>{const j=setInterval(()=>p(k=>(k+1)%1e6),1e3);return()=>clearInterval(j)},[]),r.useEffect(()=>{const j=new ea,k=j.on(z=>{const N=z.type;(N==="background:change"||N==="background:cleanup")&&u()});return()=>{k(),j.close()}},[u]);const d=i.filter(Xo),m=j=>{ec(a,j)},h=async j=>{try{const k=await T.get(`/background/${encodeURIComponent(j.instanceId)}/tmux`);tc(a,k)}catch(k){t.error(`Tmux info failed: ${k.message}`)}},g=j=>{Vo(a,t,j.instanceId,j.agent||j.prompt,()=>{n(k=>k.filter(z=>z.instanceId!==j.instanceId))})};return c?e.jsx("div",{className:"bg-active-view",children:e.jsxs("div",{className:"bg-active-loading",children:[e.jsx(oe,{size:"md"}),e.jsx("span",{children:"Loading background agents…"})]})}):l?e.jsx("div",{className:"bg-active-view",children:e.jsx(pe,{icon:e.jsx(De,{size:32}),title:"Couldn't load background agents",message:l,action:e.jsxs($,{variant:"primary",onClick:u,children:[e.jsx(de,{size:14})," Retry"]})})}):e.jsxs("div",{className:"bg-active-view",children:[e.jsxs("div",{className:"bg-active-header",children:[e.jsxs("div",{className:"bg-active-header-text",children:[e.jsx("h2",{className:"bg-active-title",children:"Active Background Agents"}),e.jsxs("p",{className:"bg-active-subtitle muted",children:[d.length," active · ",i.length," total in store"]})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:u,title:"Refresh now",children:[e.jsx(de,{size:14})," Refresh"]})]}),d.length===0?e.jsx(pe,{icon:e.jsx(De,{size:32}),title:"No active background agents",message:"Spawn one from the Agents tab or via the bizar_spawn_background tool."}):e.jsx("div",{className:"bg-active-list",children:d.map(j=>e.jsx(Zo,{inst:j,onViewOutput:()=>m(j),onOpenTmux:()=>h(j),onKill:()=>g(j)},j.instanceId))})]})}function Zo({inst:s,onViewOutput:t,onOpenTmux:a,onKill:i}){const n=typeof s.startedAt=="number"?s.startedAt:0,c=n?_e(n):"—",o=n?Date.now()-n:0,l=Zt(s.prompt,Yo);return e.jsxs(G,{className:"bg-active-card",variant:"elevated",children:[e.jsxs("div",{className:"bg-active-card-top",children:[e.jsxs("div",{className:"bg-active-card-id",children:[e.jsx("code",{className:"mono",children:s.instanceId}),e.jsx(Wo,{status:s.status||"pending",dot:!0})]}),e.jsxs("div",{className:"bg-active-card-agent",children:[e.jsx("span",{className:"bg-active-card-agent-label",children:"Agent"}),e.jsx("span",{className:"bg-active-card-agent-name",children:s.agent||"unknown"})]})]}),l&&e.jsx("div",{className:"bg-active-prompt",children:l}),s.currentStep&&e.jsxs("div",{className:"bg-active-step",children:[e.jsx("span",{className:"bg-active-step-label",children:"Step:"}),e.jsx("span",{className:"bg-active-step-value",children:s.currentStep})]}),typeof s.progress=="number"&&e.jsxs("div",{className:"progress-bar","aria-label":"Progress",children:[e.jsx("div",{className:"progress-fill",style:{width:`${Math.max(0,Math.min(100,s.progress))}%`}}),e.jsxs("span",{className:"progress-label",children:[Math.round(s.progress),"%"]})]}),e.jsxs("div",{className:"bg-active-meta",children:[e.jsxs("span",{title:c,children:[e.jsx("strong",{children:"Started:"})," ",c]}),e.jsxs("span",{children:[e.jsx("strong",{children:"Duration:"})," ",Jo(o)]}),e.jsxs("span",{children:[e.jsx("strong",{children:"Tool calls:"})," ",s.toolCallCount??0]}),s.tmuxSession&&e.jsxs("span",{className:V(s.tmuxActive&&"bg-active-meta-tmux-live"),children:[e.jsx("strong",{children:"tmux:"})," ",e.jsx("code",{className:"mono",children:s.tmuxSession}),s.tmuxActive?" · live":""]})]}),e.jsxs("div",{className:"bg-active-actions",children:[e.jsxs($,{variant:"secondary",size:"sm",onClick:t,children:[e.jsx(fs,{size:14})," View output"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:a,children:[e.jsx(ns,{size:14})," Open in tmux"]}),e.jsxs($,{variant:"danger",size:"sm",onClick:i,children:[e.jsx(ke,{size:14})," Kill"]})]}),e.jsx(Ho,{instance:s})]})}function ec(s,t){s.open({title:`Output — ${t.agent||t.instanceId}`,width:720,children:e.jsx(sc,{instanceId:t.instanceId})})}function sc({instanceId:s}){const t=re(),[a,i]=r.useState(""),[n,c]=r.useState(!0),[o,l]=r.useState(null),[x,p]=r.useState(!0),u=r.useRef(null),d=r.useRef(!0),m=r.useCallback(async()=>{try{const j=await T.get(`/background/${encodeURIComponent(s)}/output?lines=200`);i((j==null?void 0:j.output)??""),p((j==null?void 0:j.available)!==!1),l(null)}catch(j){l((j==null?void 0:j.message)||"Failed to load output.")}finally{c(!1)}},[s]);r.useEffect(()=>{m();const j=setInterval(m,Ko);return()=>clearInterval(j)},[m]),r.useEffect(()=>{var j;d.current&&((j=u.current)==null||j.scrollIntoView({behavior:"auto",block:"end"}))},[a]);const h=j=>{const k=j.currentTarget,z=k.scrollHeight-k.scrollTop-k.clientHeight<24;d.current=z},g=async()=>{try{await navigator.clipboard.writeText(a),t.success("Output copied.")}catch{}};return e.jsxs("div",{className:"bg-output-modal",children:[e.jsxs("div",{className:"bg-output-toolbar",children:[e.jsx("span",{className:"muted",children:x?`${a.length} chars · auto-refresh 2s`:"Output unavailable"}),e.jsxs("div",{className:"bg-output-toolbar-actions",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:m,title:"Refresh now",children:[e.jsx(de,{size:14})," Refresh"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:g,disabled:!a,children:[e.jsx(os,{size:14})," Copy"]})]})]}),n&&!a?e.jsxs("div",{className:"bg-output-loading",children:[e.jsx(xe,{size:16,className:"spin"})," Loading…"]}):o?e.jsx("div",{className:"bg-output-error",children:o}):a?e.jsxs("div",{className:"bg-output-scroll",onScroll:h,children:[e.jsx("pre",{className:"bg-output-pre mono",children:e.jsx("code",{children:a})}),e.jsx("div",{ref:u})]}):e.jsx("div",{className:"bg-output-empty muted",children:"No output captured yet."})]})}function tc(s,t){const a=t.attachCommand||t.session||"";s.open({title:"Attach to tmux",width:520,children:e.jsx(ac,{info:t,cmd:a})})}function ac({info:s,cmd:t}){const[a,i]=r.useState(!1),n=async()=>{try{await navigator.clipboard.writeText(t),i(!0),window.setTimeout(()=>i(!1),1500)}catch{}};return e.jsx("div",{className:"bg-tmux-modal",children:t?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"bg-tmux-meta",children:[s.exists?e.jsx("span",{className:"badge badge-success",children:"session live"}):e.jsxs("span",{className:"badge badge-warning",children:["session not running",s.reason?` — ${s.reason}`:""]}),s.session&&e.jsxs("span",{className:"bg-tmux-session muted",children:["· session ",e.jsx("code",{className:"mono",children:s.session})]})]}),e.jsx("label",{className:"field-label",children:"Attach command"}),e.jsxs("div",{className:"bg-tmux-command-row",children:[e.jsx("code",{className:"bg-tmux-command mono",children:t}),e.jsxs($,{variant:"secondary",size:"sm",onClick:n,children:[e.jsx(os,{size:14})," ",a?"Copied":"Copy"]})]}),e.jsx("p",{className:"muted bg-tmux-hint",children:"Paste this into a terminal on the host running the dashboard. The dashboard itself does not open terminals."})]}):e.jsx("p",{className:"muted",children:"No tmux session attached to this instance."})})}const nc={system:{title:"System health",icon:js,emptyTitle:"No system checks",emptyMessage:"System checks did not return any rows."},services:{title:"Services",icon:Ct,emptyTitle:"No service probes",emptyMessage:"Service probes did not return any rows."},counts:{title:"Counts",icon:De,emptyTitle:"No counts",emptyMessage:"No counts reported by the dashboard stores."},errors:{title:"Recent errors",icon:ps,emptyTitle:"No recent errors",emptyMessage:"No error lines in the service log within the last hour."},actions:{title:"Actions",icon:Bn,emptyTitle:"No actions",emptyMessage:"No actions available."}};function ic(s){return s==="ok"?qe:s==="warn"?Un:ps}function rc(s){return s==="ok"?"ok":s==="warn"?"warn":"fail"}function ut({category:s,title:t,icon:a,checks:i,info:n,meta:c,children:o,className:l}){const x=nc[s],p=a??x.icon,u=t??x.title,d=i.length>0||n&&n.length>0||o;return e.jsxs(G,{className:V("doctor-panel",`doctor-panel-${s}`,l),children:[e.jsxs(te,{children:[e.jsx(p,{size:14,"aria-hidden":!0}),e.jsx("span",{children:u}),c?e.jsx("span",{className:"card-meta-inline muted",children:c}):null]}),d?e.jsxs("div",{className:"doctor-panel-body",children:[o,i.length>0?e.jsx("ul",{className:"doctor-check-list",role:"list",children:i.map(m=>{const h=ic(m.status);return e.jsxs("li",{className:V("doctor-check-row",`doctor-check-${m.status}`),children:[e.jsx("span",{className:"doctor-check-icon","aria-hidden":!0,children:e.jsx(h,{size:14,className:V("doctor-check-icon-svg",m.status==="ok"&&"doctor-check-icon-ok",m.status==="warn"&&"doctor-check-icon-warn",m.status==="fail"&&"doctor-check-icon-fail")})}),e.jsx("span",{className:"doctor-check-name mono",children:m.name}),e.jsx("span",{className:"doctor-check-message",children:m.message}),e.jsx(Je,{kind:m.status,dot:!0,children:rc(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:x.emptyTitle,message:x.emptyMessage})]})}const lc=3e4;function oc({setActiveTab:s}){var b;const t=re(),[a,i]=r.useState(null),[n,c]=r.useState(!0),[o,l]=r.useState(!1),[x,p]=r.useState(null),[u,d]=r.useState(!0),m=r.useRef(!1),h=r.useCallback(async()=>{l(!0);try{const w=await T.get("/doctor");m.current||(i(w),p(Date.now()),c(!1))}catch(w){m.current||(c(!1),t.error(`Doctor refresh failed: ${w.message}`))}finally{m.current||l(!1)}},[t]);r.useEffect(()=>(m.current=!1,h(),()=>{m.current=!0}),[h]),r.useEffect(()=>{if(!u)return;const f=setInterval(async()=>{try{const L=await T.get("/doctor/health");i(R=>R&&((R.health.status!==L.status||R.health.issues.length!==L.issues.length)&&h(),R))}catch{}},lc);return()=>clearInterval(f)},[u,h]);const g=async w=>{var f;try{const L=await T.post("/doctor/check",{checkName:w});t.info(`${L.name}: ${L.message}`,4e3),await h()}catch(L){const R=L;t.error(`Check failed: ${((f=R.data)==null?void 0:f.message)??L.message}`)}},j=()=>{if(a)try{const w=new Blob([JSON.stringify(a,null,2)],{type:"application/json"}),f=URL.createObjectURL(w),L=document.createElement("a");L.href=f,L.download=`doctor-snapshot-${new Date().toISOString().replace(/[:.]/g,"-")}.json`,document.body.appendChild(L),L.click(),document.body.removeChild(L),URL.revokeObjectURL(f)}catch(w){t.error(`Export failed: ${w.message}`)}},k=()=>{s("settings")},z=a==null?void 0:a.counts,N=r.useMemo(()=>z?[{label:"Tasks",value:z.tasks},{label:"Schedules",value:z.schedules},{label:"Mods",value:z.mods},{label:"Providers",value:z.providers},{label:"MCPs",value:z.mcps},{label:"Agents",value:z.agents},{label:"Projects",value:z.projects},{label:"Workspaces",value:z.workspaces},{label:"Voice notes",value:z.voiceNotes},{label:"Eval runs",value:z.evalRuns},{label:"Backups",value:z.backups}]:[],[z]);if(n)return e.jsxs("div",{className:"view view-doctor view-loading",children:[e.jsx(oe,{size:"lg"}),e.jsx("p",{children:"Running health checks…"})]});if(!a)return e.jsx("div",{className:"view view-doctor",children:e.jsxs(G,{children:[e.jsxs(te,{children:[e.jsx(ps,{size:14})," Doctor unavailable"]}),e.jsx(ne,{children:"Could not reach /api/doctor."}),e.jsx("div",{className:"doctor-fallback-actions",children:e.jsxs($,{variant:"primary",onClick:h,children:[e.jsx(de,{size:12})," Retry"]})})]})});const S=a.health.status,E=S==="ok"?qe:S==="warn"?Te:ps,v=S==="ok"?"Healthy":S==="warn"?"Warning":"Failed";return e.jsxs("div",{className:"view view-doctor","data-overall":S,children:[e.jsxs("div",{className:"doctor-header",children:[e.jsxs("div",{className:"doctor-header-row",children:[e.jsxs("div",{className:"doctor-header-title",children:[e.jsx(ia,{size:20,"aria-hidden":!0}),e.jsx("h1",{children:"Doctor"})]}),e.jsx("div",{className:"doctor-header-status",children:e.jsxs("span",{className:V("doctor-overall-pill",`doctor-overall-${S}`),children:[e.jsx(E,{size:14,"aria-hidden":!0}),e.jsx("span",{className:"doctor-overall-label",children:v}),e.jsxs(Je,{kind:S,dot:!0,children:[a.health.issues.length," issue",a.health.issues.length===1?"":"s"]})]})})]}),e.jsxs("div",{className:"doctor-header-meta muted",children:[e.jsx(as,{size:12,"aria-hidden":!0}),e.jsxs("span",{"aria-live":"polite","aria-atomic":"true",children:["v",a.bizarVersion," · ",a.platform,"/",a.arch," ·"," ","up ",Math.floor(a.uptime),"s",x?` · refreshed ${_e(new Date(x))}`:""]})]})]}),e.jsxs("div",{className:"doctor-grid",children:[e.jsx(ut,{category:"system",checks:a.checks.system,meta:`${a.platform}/${a.arch}`}),e.jsx(ut,{category:"services",checks:a.checks.services,meta:(b=a.services.opencode)!=null&&b.reachable?`opencode on ${a.services.opencode.port??"?"}`:"opencode not connected"}),e.jsx(ut,{category:"counts",checks:[],info:N,meta:z!=null&&z.activeProject?`active: ${z.activeProject}`:"no active project"}),e.jsxs(G,{className:"doctor-errors-card",children:[e.jsxs(te,{children:[e.jsx(ps,{size:14,"aria-hidden":!0}),e.jsx("span",{children:"Recent errors (last hour)"}),e.jsxs("span",{className:"card-meta-inline muted",children:[a.recentErrors.length," line",a.recentErrors.length===1?"":"s"]})]}),a.recentErrors.length===0?e.jsx("div",{className:"muted doctor-errors-empty",children:"No errors in the last hour. Nice."}):e.jsx("ul",{className:"doctor-errors-list",role:"list",children:a.recentErrors.map((w,f)=>e.jsxs("li",{className:"doctor-error-row",children:[e.jsx("span",{className:"doctor-error-ts mono",children:w.ts?_e(new Date(w.ts)):"??:??:??"}),e.jsx("span",{className:"doctor-error-line mono",children:w.line})]},`${w.tsMs??f}-${f}`))})]}),e.jsxs(G,{className:"doctor-actions-card",children:[e.jsxs(te,{children:[e.jsx(ft,{size:14,"aria-hidden":!0})," Actions"]}),e.jsx(ne,{children:"Run a check, view logs, or export the snapshot."}),e.jsxs("div",{className:"doctor-actions-row",children:[e.jsxs($,{variant:"primary",onClick:h,disabled:o,"aria-label":"Refresh diagnostics",children:[o?e.jsx(oe,{size:"sm"}):e.jsx(de,{size:12}),o?"Running…":"Run Health Check Now"]}),e.jsxs($,{variant:"secondary",onClick:k,children:[e.jsx(be,{size:12})," View Full Logs"]}),e.jsxs($,{variant:"secondary",onClick:j,children:[e.jsx(ls,{size:12})," Export Diagnostics as JSON"]}),e.jsx($,{variant:"ghost",onClick:()=>d(w=>!w),"aria-label":u?"Pause auto-refresh":"Resume auto-refresh",children:u?"Pause auto-refresh":"Resume auto-refresh"})]}),a.checks.services.some(w=>w.status!=="ok")||a.checks.config.some(w=>w.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(w=>w.status!=="ok").map(w=>e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>g(w.name),title:`Run check: ${w.name}`,children:[e.jsx(ft,{size:10})," ",w.name]},w.name))})]}):null]})]})]})}const cc=Oe.memo(oc);function dc(s){return s.total<=0?"fail":s.failed===0?"pass":s.passed/s.total>.8?"warn":"fail"}function Ia({run:s,onClick:t,selected:a,ariaLabel:i}){const n=dc(s),c=s.total>0?(s.passed/s.total*100).toFixed(1):"0.0",o=!!t;return e.jsxs(G,{onClick:t,interactive:o,"aria-label":i??`Eval run ${s.id}`,"aria-pressed":o?a:void 0,className:V("eval-run-card",a&&"eval-run-card-selected",`eval-run-${n}`),children:[e.jsxs("div",{className:"eval-run-head",children:[e.jsx(te,{className:"eval-run-title",children:s.id}),e.jsxs("span",{className:V("eval-status",`is-${n}`),children:[s.passed,"/",s.total," (",c,"%)"]})]}),e.jsxs(ne,{className:"eval-run-meta",children:[_e(s.startedAt)," · ",s.suitePath]})]})}const ht=8;function mc({onAdded:s,onCancel:t}){const a=re(),[i,n]=r.useState(""),[c,o]=r.useState(""),[l,x]=r.useState(""),[p,u]=r.useState("thor"),[d,m]=r.useState(!1),h=async g=>{if(g.preventDefault(),!i||!c||!l){a.error("name, suitePath, and cron are required");return}m(!0);try{const j=await T.post("/eval/schedules",{name:i,suitePath:c,cron:l,agent:p});s(j),a.success("Schedule created")}catch(j){a.error(`Failed to create schedule: ${j.message}`)}finally{m(!1)}};return e.jsxs("form",{className:"eval-schedule-form",onSubmit:h,children:[e.jsxs("div",{className:"form-row",children:[e.jsx("label",{htmlFor:"sched-name",children:"Name"}),e.jsx("input",{id:"sched-name",type:"text",value:i,onChange:g=>n(g.target.value),placeholder:"Daily fixture check",required:!0})]}),e.jsxs("div",{className:"form-row",children:[e.jsx("label",{htmlFor:"sched-suite",children:"Suite path"}),e.jsx("input",{id:"sched-suite",type:"text",value:c,onChange:g=>o(g.target.value),placeholder:"./fixtures",required:!0})]}),e.jsxs("div",{className:"form-row",children:[e.jsx("label",{htmlFor:"sched-cron",children:"Cron"}),e.jsx("input",{id:"sched-cron",type:"text",value:l,onChange:g=>x(g.target.value),placeholder:"0 8 * * *",required:!0})]}),e.jsxs("div",{className:"form-row",children:[e.jsx("label",{htmlFor:"sched-agent",children:"Agent"}),e.jsx("input",{id:"sched-agent",type:"text",value:p,onChange:g=>u(g.target.value),placeholder:"thor"})]}),e.jsxs("div",{className:"form-actions",children:[e.jsx($,{type:"submit",variant:"primary",size:"sm",disabled:d,children:d?"Creating…":"Create schedule"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:t,children:"Cancel"})]})]})}function uc({setActiveTab:s}){const t=re(),[a,i]=r.useState([]),[n,c]=r.useState(!0),[o,l]=r.useState("runs"),[x,p]=r.useState([]),[u,d]=r.useState(!1),[m,h]=r.useState(!1),g=r.useRef(!1),j=r.useCallback(async()=>{c(!0);try{const v=await T.get(`/eval/runs?limit=${ht}`);g.current||i(v.runs||[])}catch(v){g.current||t.error(`Failed to load eval runs: ${v.message}`)}finally{g.current||c(!1)}},[t]),k=r.useCallback(async()=>{d(!0);try{const v=await T.get("/eval/schedules");g.current||p(v.schedules||[])}catch(v){g.current||t.error(`Failed to load eval schedules: ${v.message}`)}finally{g.current||d(!1)}},[t]);r.useEffect(()=>(g.current=!1,j(),o==="schedules"&&k(),()=>{g.current=!0}),[j,k,o]);const z=async v=>{try{await T.del(`/eval/schedules/${v}`),p(b=>b.filter(w=>w.id!==v)),t.success("Schedule deleted")}catch(b){t.error(`Failed to delete schedule: ${b.message}`)}},N=a.slice(0,ht),S=a.reduce((v,b)=>(v.total+=b.total,v.passed+=b.passed,v.failed+=b.failed,b.failed===0&&(v.fullPass+=1),v),{total:0,passed:0,failed:0,fullPass:0}),E=S.total>0?(S.passed/S.total*100).toFixed(1):"—";return e.jsxs("div",{className:"view view-eval","data-testid":"eval-overview",children:[e.jsxs("div",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h1",{className:"view-title",children:[e.jsx(Qe,{size:20,"aria-hidden":!0})," Eval"]}),e.jsx("p",{className:"view-subtitle muted",children:"Track golden-fixture runs, catch regressions, and compare run history."})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs($,{variant:"secondary",size:"sm",onClick:j,disabled:n,children:[n?e.jsx(oe,{size:"sm"}):e.jsx(de,{size:12}),n?"Refreshing…":"Refresh"]}),e.jsxs($,{variant:"primary",size:"sm",onClick:()=>s("evalReport"),title:"Open the full eval report",children:[e.jsx(ys,{size:12})," Open Eval Report"]})]})]}),e.jsxs("div",{className:"eval-summary-grid",children:[e.jsxs(G,{className:"eval-summary-card",children:[e.jsx(te,{children:"Recent runs"}),e.jsx("div",{className:"eval-summary-value",children:a.length}),e.jsxs(ne,{className:"muted",children:["Latest ",ht," runs across all suites."]})]}),e.jsxs(G,{className:"eval-summary-card",children:[e.jsx(te,{children:"Fixtures run"}),e.jsx("div",{className:"eval-summary-value",children:S.total}),e.jsx(ne,{className:"muted",children:e.jsxs("span",{className:V("eval-rate",S.failed===0?"is-pass":"is-fail"),children:[E,"% pass rate"]})})]}),e.jsxs(G,{className:"eval-summary-card",children:[e.jsx(te,{children:"Clean runs"}),e.jsx("div",{className:"eval-summary-value",children:S.fullPass}),e.jsx(ne,{className:"muted",children:"Runs where every fixture passed."})]}),e.jsxs(G,{className:"eval-summary-card eval-summary-cta",children:[e.jsx(te,{children:"Compare runs"}),e.jsx(ne,{children:"Open the detailed report to diff two runs side-by-side and spot regressions fixture by fixture."}),e.jsxs($,{variant:"primary",size:"sm",onClick:()=>s("evalReport"),className:"eval-summary-cta-btn",children:["Open report ",e.jsx(_n,{size:12})]})]})]}),e.jsxs("div",{className:"eval-recent-section",children:[e.jsxs("div",{className:"eval-sub-tabs",children:[e.jsxs("button",{type:"button",className:V("eval-sub-tab",o==="runs"?"is-active":""),onClick:()=>l("runs"),children:[e.jsx(Qe,{size:12,"aria-hidden":!0})," Runs"]}),e.jsxs("button",{type:"button",className:V("eval-sub-tab",o==="schedules"?"is-active":""),onClick:()=>{l("schedules"),x.length===0&&k()},children:[e.jsx(as,{size:12,"aria-hidden":!0})," Schedules"]})]}),o==="runs"?e.jsxs(e.Fragment,{children:[e.jsx("h2",{className:"eval-section-title",children:"Recent runs"}),n&&N.length===0?e.jsxs("div",{className:"eval-runs-loading",children:[e.jsx(oe,{size:"sm"}),e.jsx("span",{className:"muted",children:"Loading runs…"})]}):N.length===0?e.jsx(pe,{icon:e.jsx(Qe,{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:N.map(v=>e.jsx(Ia,{run:v},v.id))})]}):e.jsxs(e.Fragment,{children:[e.jsx("h2",{className:"eval-section-title",children:"Schedules"}),u?e.jsxs("div",{className:"eval-runs-loading",children:[e.jsx(oe,{size:"sm"}),e.jsx("span",{className:"muted",children:"Loading schedules…"})]}):x.length===0?e.jsx(pe,{icon:e.jsx(as,{size:28}),title:"No eval schedules",message:"Schedules let you run eval suites automatically on a cron. Add one below."}):e.jsx("div",{className:"eval-schedules-list",children:x.map(v=>e.jsx(G,{className:"eval-schedule-card",children:e.jsxs("div",{className:"eval-schedule-row",children:[e.jsxs("div",{className:"eval-schedule-info",children:[e.jsx(te,{children:v.name}),e.jsxs(ne,{className:"muted",children:[v.cron," · ",v.suitePath," · agent:",v.agent||"thor"]})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>z(v.id),title:"Delete schedule",children:e.jsx(ke,{size:12,"aria-hidden":!0})})]})},v.id))}),e.jsxs("div",{className:"eval-schedule-add",children:[e.jsx(mc,{onAdded:v=>{p(b=>[...b,v]),h(!1)},onCancel:()=>h(!1)}),!m&&e.jsxs($,{variant:"secondary",size:"sm",onClick:()=>h(!0),children:[e.jsx(ze,{size:12,"aria-hidden":!0})," Add schedule"]})]})]})]})]})}const hc=Oe.memo(uc);function Ea(s,t){const a=new Map(s.results.map(l=>[l.fixtureId,l])),i=new Map(t.results.map(l=>[l.fixtureId,l])),n=new Set([...a.keys(),...i.keys()]),c=[];for(const l of n){const x=a.get(l),p=i.get(l),u=x?x.ok:null,d=p?p.ok:null;let m;x&&p?u===d?m="same":u===!1&&d===!0?m="improved":m="regressed":p&&!x?m="added":m="removed",c.push({fixtureId:l,before:u,after:d,change:m})}const o={regressed:0,improved:1,added:2,removed:3,same:4};return c.sort((l,x)=>{const p=o[l.change]-o[x.change];return p!==0?p:l.fixtureId.localeCompare(x.fixtureId)}),c}function xc({runA:s,runB:t,title:a="Regression Analysis"}){const i=Ea(s,t),n=i.filter(x=>x.change==="improved").length,c=i.filter(x=>x.change==="regressed").length,o=i.filter(x=>x.change==="same").length,l=i.filter(x=>x.change!=="same");return e.jsxs("div",{className:"eval-diff","data-testid":"eval-diff",children:[e.jsx("h3",{className:"eval-diff-title",children:a}),e.jsxs("div",{className:"eval-diff-subtitle muted",children:["Comparing ",e.jsx("code",{className:"mono",children:s.id})," →"," ",e.jsx("code",{className:"mono",children:t.id})]}),e.jsxs("div",{className:"eval-diff-stats","aria-label":"Diff summary",children:[e.jsxs("span",{className:"eval-diff-stat improved",children:[e.jsx("span",{className:"eval-diff-stat-icon","aria-hidden":!0,children:"+"}),n," improved"]}),e.jsxs("span",{className:"eval-diff-stat regressed",children:[e.jsx("span",{className:"eval-diff-stat-icon","aria-hidden":!0,children:"−"}),c," regressed"]}),e.jsxs("span",{className:"eval-diff-stat unchanged muted",children:[o," unchanged"]})]}),l.length===0?e.jsx("p",{className:"eval-diff-empty muted",children:"No fixture-level changes between these runs."}):e.jsx("ul",{className:"eval-diff-list",role:"list",children:l.map(x=>e.jsxs("li",{"data-fixture-id":x.fixtureId,className:V("eval-diff-row",`is-${x.change}`),children:[e.jsx("span",{className:"eval-diff-fixture mono",children:x.fixtureId}),e.jsx("span",{className:"eval-diff-arrow","aria-hidden":!0,children:"→"}),e.jsxs("span",{className:"eval-diff-states",children:[e.jsx("span",{className:V("eval-diff-state",x.before?"is-pass":"is-fail"),children:x.before===null?"—":x.before?"pass":"fail"}),e.jsx("span",{className:"eval-diff-arrow-small","aria-hidden":!0,children:"→"}),e.jsx("span",{className:V("eval-diff-state",x.after?"is-pass":"is-fail"),children:x.after===null?"—":x.after?"pass":"fail"})]})]},x.fixtureId))})]})}function pc({runId:s,variant:t="secondary",size:a="sm"}){const i=()=>{const n=T.getToken();window.open(`/api/eval/runs/${encodeURIComponent(s)}/export.csv?_t=${encodeURIComponent(n)}`,"_blank")};return e.jsxs($,{variant:t,size:a,onClick:i,title:"Export results as CSV",children:[e.jsx(ls,{size:14,"aria-hidden":!0}),"Export CSV"]})}function gc({run:s,onClearCompare:t,compareRun:a,onClearSelection:i,runsForDiff:n}){const c=s.total>0?(s.passed/s.total*100).toFixed(1):"0.0",o=[...s.results].sort((l,x)=>l.ok!==x.ok?l.ok?1:-1:l.fixtureId.localeCompare(x.fixtureId));return e.jsxs("div",{className:"eval-run-detail","data-testid":"eval-run-detail",children:[e.jsxs(G,{className:"eval-run-detail-header",children:[e.jsxs("div",{className:"eval-run-detail-header-row",children:[e.jsxs(te,{children:[e.jsx(Qe,{size:14,"aria-hidden":!0})," ",s.id]}),e.jsxs("div",{className:"eval-run-detail-actions",children:[e.jsx(pc,{runId:s.id}),e.jsxs($,{variant:"ghost",size:"sm",onClick:i,title:"Close detail",children:[e.jsx(Ne,{size:12})," Close"]})]})]}),e.jsxs(ne,{children:[_e(s.startedAt),s.finishedAt?` → ${_e(s.finishedAt)}`:""," · ",s.suitePath]}),e.jsxs("div",{className:"eval-run-detail-summary",children:[e.jsxs("span",{className:V("eval-status",s.failed===0?"is-pass":"is-fail"),children:[s.passed,"/",s.total," (",c,"%)"]}),e.jsxs("span",{className:"muted",children:[s.failed," failed · ",s.passed," passed"]})]})]}),a?e.jsx(G,{className:"eval-diff-card",children:(()=>{const l=n.find(d=>d.id===a);if(!l)return e.jsxs("div",{className:"eval-diff-missing muted",children:["Baseline run ",e.jsx("code",{children:a})," not loaded. Pick another from the list."]});const x=Ea(l,s),p=x.filter(d=>d.change==="improved").length,u=x.filter(d=>d.change==="regressed").length;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"eval-diff-card-head",children:[e.jsxs("span",{className:"eval-diff-card-title",children:[e.jsx(ya,{size:14,"aria-hidden":!0})," Comparing ",l.id," → ",s.id]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:t,children:[e.jsx(Ne,{size:12})," Clear baseline"]})]}),e.jsxs("div",{className:"eval-diff-stats","aria-label":"Diff summary",children:[e.jsxs("span",{className:"eval-diff-stat improved",children:["+",p," improved"]}),e.jsxs("span",{className:"eval-diff-stat regressed",children:["−",u," regressed"]})]}),e.jsx(xc,{runA:l,runB:s})]})})()}):e.jsx(G,{className:"eval-baseline-hint",children:e.jsx(ne,{children:"Tip: click another run in the list to use it as a baseline for diffing."})}),e.jsxs(G,{className:"eval-fixtures-card",children:[e.jsxs(te,{children:["Fixtures (",s.results.length,")"]}),o.length===0?e.jsx(ne,{className:"muted",children:"No fixture results in this run."}):e.jsx("ul",{className:"eval-fixtures-list",role:"list",children:o.map(l=>e.jsxs("li",{className:V("eval-fixture-row",l.ok?"is-pass":"is-fail"),children:[e.jsx("span",{className:V("eval-fixture-pill",l.ok?"is-pass":"is-fail"),"aria-label":l.ok?"pass":"fail",children:l.ok?"✓":"✗"}),e.jsx("span",{className:"eval-fixture-id mono",children:l.fixtureId}),!l.ok&&l.checks?e.jsx("span",{className:"eval-fixture-fails muted",children:l.checks.filter(x=>!x.ok).map(x=>x.message).filter(Boolean).join(" · ")}):null,l.latencyMs!=null?e.jsxs("span",{className:"eval-fixture-latency muted",children:[Math.round(l.latencyMs),"ms"]}):null]},l.fixtureId))})]})]})}function fc({setActiveTab:s}){const t=re(),[a,i]=r.useState([]),[n,c]=r.useState(!0),[o,l]=r.useState(null),[x,p]=r.useState(null),[u,d]=r.useState(null),[m,h]=r.useState(!1),[g,j]=r.useState(null),k=r.useRef(!1),z=r.useCallback(async()=>{c(!0);try{const w=await T.get("/eval/runs");k.current||i(w.runs||[])}catch(w){k.current||t.error(`Failed to load eval runs: ${w.message}`)}finally{k.current||c(!1)}},[t]),N=r.useCallback(async w=>{h(!0);try{const f=await T.get(`/eval/runs/${encodeURIComponent(w)}`);k.current||d(f)}catch(f){k.current||(t.error(`Failed to load run ${w}: ${f.message}`),d(null))}finally{k.current||h(!1)}},[t]),S=r.useCallback(async w=>{try{const f=await T.get(`/eval/runs/${encodeURIComponent(w)}`);k.current||j(f)}catch(f){k.current||(t.error(`Failed to load run ${w}: ${f.message}`),j(null))}},[t]);r.useEffect(()=>(k.current=!1,z(),()=>{k.current=!0}),[z]);const E=async w=>{w!==o&&(l(w),p(null),j(null),await N(w))},v=async w=>{w!==o&&(p(w),await S(w))},b=[];return g&&b.push(g),u&&b.push(u),e.jsxs("div",{className:"view view-eval-report","data-testid":"eval-report",children:[e.jsxs("div",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h1",{className:"view-title",children:[e.jsx(Qe,{size:20,"aria-hidden":!0})," Eval Reports"]}),e.jsx("p",{className:"view-subtitle muted",children:"Browse eval runs, inspect per-fixture results, and diff two runs to spot regressions."})]}),e.jsx("div",{className:"view-actions",children:e.jsxs($,{variant:"secondary",size:"sm",onClick:z,disabled:n,children:[n?e.jsx(oe,{size:"sm"}):e.jsx(de,{size:12}),n?"Refreshing…":"Refresh"]})})]}),e.jsxs("div",{className:"eval-grid",children:[e.jsx("div",{className:"eval-runs-list",children:n&&a.length===0?e.jsxs("div",{className:"eval-runs-loading",children:[e.jsx(oe,{size:"sm"}),e.jsx("span",{className:"muted",children:"Loading runs…"})]}):a.length===0?e.jsx(pe,{icon:e.jsx(Qe,{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(w=>e.jsxs("div",{className:"eval-run-card-wrap",children:[e.jsx(Ia,{run:w,selected:w.id===o,onClick:()=>E(w.id)}),o&&w.id!==o?e.jsxs("button",{type:"button",className:"eval-baseline-btn",onClick:()=>v(w.id),title:"Use this run as a baseline for diffing",children:[e.jsx(ya,{size:10,"aria-hidden":!0}),"Use as baseline"]}):null]},w.id))}),e.jsx("div",{className:"eval-detail",children:m&&!u?e.jsxs("div",{className:"eval-detail-loading",children:[e.jsx(oe,{size:"sm"}),e.jsx("span",{className:"muted",children:"Loading run details…"})]}):u?e.jsx(gc,{run:u,compareRun:x,runsForDiff:b,onClearCompare:()=>{p(null),j(null)},onClearSelection:()=>{l(null),d(null),p(null),j(null)}}):e.jsx(G,{className:"eval-detail-empty",children:e.jsx(pe,{icon:e.jsx(Qe,{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 jc=Oe.memo(fc),xt={overview:qi,chat:lr,agents:ur,artifacts:Or,memory:Ro,tasks:Xr,activity:rl,background:Qo,config:Vt,settings:Vt,mods:Tl,schedules:Hl,skills:eo,history:Ao,minimax:Bo,plugins:El,doctor:cc,eval:hc,evalReport:jc},vc="v4.5.0";function yc(s,t,a,i){if(xt[s]){const o=xt[s];return e.jsx(o,{...t})}const n=a.find(o=>o.id===s);if(n)return e.jsx(Ll,{viewId:n.id,reloadKey:i,activeTab:t.activeTab,setActiveTab:t.setActiveTab});const c=xt.overview;return e.jsx(c,{...t})}function bc({onSaved:s}){const[t,a]=r.useState(""),i=r.useRef(null);r.useEffect(()=>{var o;(o=i.current)==null||o.focus()},[]);const n=()=>{const o=t.trim();o&&(T.setToken(o),s())},c=o=>{o.key==="Escape"&&(o.preventDefault(),s()),o.key==="Enter"&&(o.preventDefault(),n())};return e.jsxs("form",{className:"token-entry-form",onSubmit:o=>{o.preventDefault(),n()},children:[e.jsxs("div",{className:"token-entry-row",children:[e.jsx("input",{ref:i,type:"password",className:"input mono",value:t,onChange:o=>a(o.target.value),placeholder:"Paste auth token",spellCheck:!1,autoComplete:"off",onKeyDown:c}),e.jsx($,{type:"submit",variant:"primary",size:"sm",disabled:!t.trim(),children:"Save & retry"})]}),e.jsxs("p",{className:"token-entry-hint",children:["Where do I find this token? Check the file"," ",e.jsx("code",{children:"~/.config/bizar/dashboard-secret"})," on the machine running the dashboard, or look for it in the server output."]})]})}function Nc(){return e.jsx(Jn,{children:e.jsx(ni,{children:e.jsx(kc,{})})})}function kc(){var se,ie,me;const s=re(),t=$e(),{isModalOpen:a}=t,i=r.useRef(!1),[n,c]=r.useState("overview"),[o,l]=r.useState(null),[x,p]=r.useState(null),[u,d]=r.useState("connecting"),[m,h]=r.useState(null),[g,j]=r.useState(!1),[k,z]=r.useState(null),[N,S]=r.useState(!1),[E,v]=r.useState(!1),[b,w]=r.useState([]),[f,L]=r.useState(!1),[R,y]=r.useState([]),[A,P]=r.useState(0),C=r.useRef(null),[D,Y]=r.useState(null);r.useEffect(()=>{let _=!1;return(async()=>{try{const I=await T.get("/mods/views");if(_)return;y(I.views||[])}catch{_||y([])}})(),()=>{_=!0}},[A,o==null?void 0:o.mods]),r.useEffect(()=>{if(!D)return;const _=D.on(I=>{((I==null?void 0:I.type)==="mod:change"||(I==null?void 0:I.type)==="mod:enabled"||(I==null?void 0:I.type)==="mod:installed")&&P(Q=>Q+1)});return()=>_()},[D]),r.useEffect(()=>{x!=null&&x.theme&&(Ts(x.theme),xs(x.theme))},[x==null?void 0:x.theme]),r.useEffect(()=>{i.current=a},[a]),r.useEffect(()=>{var Q;if(((Q=x==null?void 0:x.theme)==null?void 0:Q.mode)!=="system")return;const _=window.matchMedia("(prefers-color-scheme: light)"),I=()=>Ts(x.theme.mode);return _.addEventListener("change",I),()=>_.removeEventListener("change",I)},[(se=x==null?void 0:x.theme)==null?void 0:se.mode]);const O=r.useCallback(async()=>{let _=!1;const I=()=>Promise.all([T.get("/snapshot").catch(()=>null),T.get("/settings").catch(()=>null),T.get("/agents/stuck").catch(()=>null)]),Q=(U,le,q)=>{U&&l(U),le!=null&&le.data&&p(le.data),q!=null&&q.stuck&&w(q.stuck)};try{const U=await T.probeAuthStatus(),[le,q,ce]=await I();if(Q(le,q,ce),le||q){h(null);return}if(!U.loopback){h("Dashboard server unreachable.");return}await new Promise(Ge=>setTimeout(Ge,1e3));const[Re,Ie,Be]=await I();Q(Re,Ie,Be),!Re&&!Ie&&h("Dashboard server unreachable.")}catch(U){const le=(U==null?void 0:U.message)??"unknown error";if(U instanceof Va&&U.status===401){h(le),S(!0),s.error(`Auth required: ${le}`);return}h(le),s.error(`Failed to load: ${le}`)}},[s]);r.useEffect(()=>{let _=!1;const I=setTimeout(()=>{_||O()},0);return()=>{_=!0,clearTimeout(I)}},[O]),r.useEffect(()=>{let _=!1;return T.get("/settings").then(I=>{var U,le;if(_)return;const Q=(le=(U=I==null?void 0:I.data)==null?void 0:U.ui)==null?void 0:le.defaultTab;Q&&c(Q)}).catch(()=>{}),()=>{_=!0}},[]),r.useEffect(()=>{let _=!1;const I=async()=>{try{const U=await T.get("/agents/stuck");_||w(le=>{const q=U.stuck||[];return le.length===0&&q.length>0&&s.warning(`${q.length} agent${q.length===1?"":"s"} stuck`,5e3),q})}catch{}},Q=setInterval(I,3e4);return I(),()=>{_=!0,clearInterval(Q)}},[]),r.useEffect(()=>{const _=new ea;C.current=_,Y(_);const I=_.onStatus(U=>d(U)),Q=_.on(U=>{var le;if(U.type==="snapshot"&&"data"in U&&U.data)l(q=>({...q??{},...U.data}));else if(U.type==="change"){const q=U,ce=((le=q.path)==null?void 0:le.split("/").pop())||q.path||"";s.info(`File changed: ${ce}`,2500)}else if(U.type==="tasks:change"){const q=U;l(ce=>{if(!ce)return ce;const Re=(ce.tasks||[]).map(Be=>Be.id===q.task.id?q.task:Be),Ie=Re.some(Be=>Be.id===q.task.id);return{...ce,tasks:Ie?Re:[q.task,...Re]}})}else if(U.type==="tasks:delete"){const q=U;l(ce=>ce&&{...ce,tasks:(ce.tasks||[]).filter(Re=>Re.id!==q.id)})}else if(U.type==="settings:change"){const q=U;q.settings&&p(q.settings)}else if(U.type==="project:change")T.get("/snapshot").then(q=>l(ce=>({...ce??{},...q}))).catch(()=>{});else if(U.type==="agents:change"||U.type==="schedules:change")T.get("/snapshot").then(q=>l(ce=>({...ce??{},...q}))).catch(()=>{});else if(U.type==="agent:status"||U.type==="agent:restarted"){const q=U;l(ce=>{if(!ce)return ce;const Re=(ce.agents||[]).map(Ie=>Ie.name===q.agent.name?q.agent:Ie);return{...ce,agents:Re}})}else if(U.type==="artifact:change")T.get("/artifacts").then(q=>{l(ce=>ce&&{...ce,artifacts:q.artifacts||[]})}).catch(()=>{});else if(U.type==="agent:stuck")w(U.agents||[]);else if(U.type==="dialog:show"){const q=U;q.dialog&&t.open({title:q.dialog.title,width:520,children:e.jsx(Ai,{dialog:q.dialog,onClose:()=>t.close()})})}});return()=>{I(),Q(),_.close(),Y(null)}},[s]);const J=r.useCallback(_=>D?D.on(_):()=>{},[D]),ae=r.useRef(0);r.useEffect(()=>{const _=()=>{ae.current=Date.now()+1500};return document.addEventListener("mousedown",_,!0),document.addEventListener("click",_,!0),document.addEventListener("focusin",_,!0),document.addEventListener("keydown",_,!0),()=>{document.removeEventListener("mousedown",_,!0),document.removeEventListener("click",_,!0),document.removeEventListener("focusin",_,!0),document.removeEventListener("keydown",_,!0)}},[]),r.useEffect(()=>{const _={};jt.forEach((Q,U)=>{_[String(U+1)]=Q.id});const I=Q=>{var Ge,Ds,bs,Ps;if((Q.metaKey||Q.ctrlKey)&&Q.key.toLowerCase()==="k"){Q.preventDefault(),v(!0);return}if(Q.key==="/"&&!Q.metaKey&&!Q.ctrlKey){const Ns=(Ds=(Ge=Q.target)==null?void 0:Ge.tagName)==null?void 0:Ds.toLowerCase();if(Ns!=="input"&&Ns!=="textarea"&&!((bs=Q.target)!=null&&bs.isContentEditable)){Q.preventDefault(),v(!0);return}}const U=document.activeElement;if(!U||U===document.body||U===document.documentElement)return;const q=Q.target,ce=(Ps=q==null?void 0:q.tagName)==null?void 0:Ps.toLowerCase(),Re=ce==="input"||ce==="textarea"||ce==="select"||ce==="button"||ce==="option"||ce==="label"||!!(q!=null&&q.isContentEditable);let Ie=!1;if(q&&typeof q.closest=="function"&&(Ie=!!q.closest('form, [role="dialog"], [contenteditable], [data-no-key]')),Q.repeat||i.current||Re||Ie||Q.metaKey||Q.ctrlKey||Q.altKey||Q.shiftKey||Date.now()<ae.current)return;const Be=_[Q.key];Be&&(Q.preventDefault(),F(Be))};return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[]);const ee=r.useMemo(()=>async()=>{try{const _=await T.get("/snapshot");l(I=>({...I??{},..._}))}catch(_){s.error(`Refresh failed: ${_.message}`)}},[s]),F=r.useCallback(_=>{c(_),j(_==="settings")},[]),H=r.useMemo(()=>{const _=R.map(I=>({id:I.id,label:I.label,icon:I.kind==="iframe"?vs:Is,isMod:!0,modId:I.modId}));return[...jt,..._]},[R]),K=r.useMemo(()=>o&&x?yc(n,{snapshot:o,settings:x,activeTab:n,setActiveTab:F,refreshSnapshot:ee,settingsMode:g,settingsActiveSection:k,setSettingsActiveSection:z},R,A):null,[n,o,x,R,A,ee,g,k,z,F]),B=async()=>{try{const _=await T.get("/projects");l(I=>{var Q;return I&&{...I,projects:_.projects||[],activeProject:((Q=_.projects)==null?void 0:Q.find(U=>U.id===_.active))||null}})}catch(_){s.error(`Projects refresh failed: ${_.message}`)}},Z=async _=>{try{await T.post(`/projects/${encodeURIComponent(_)}/activate`),l(I=>I&&{...I,activeProject:I.projects.find(Q=>Q.id===_)||null})}catch(I){s.error(`Activate failed: ${I.message}`)}},he=_=>{const I=_.type;if(I==="agent")F("agents");else if(I==="task")F("tasks");else if(I==="mod")F("mods");else if(I==="schedule")F("schedules");else if(I==="project"){const Q=_.item.id;Z(Q)}else if(I==="command")s.info(`/${_.item.name} — run from the TUI`,2500);else if(I==="setting"){const Q=_.item.id||_.item.path||"";F("settings");const U=le=>{if(le<=0)return;const q=Q?document.querySelector(`[data-setting-id="${CSS.escape(Q)}"]`):null;q?(q.scrollIntoView({behavior:"smooth",block:"center"}),q.classList.remove("setting-flash"),q.offsetWidth,q.classList.add("setting-flash"),window.setTimeout(()=>q.classList.remove("setting-flash"),1500)):window.setTimeout(()=>U(le-1),80)};window.setTimeout(()=>U(15),60)}},we=((ie=x==null?void 0:x.ui)==null?void 0:ie.layout)||"topnav",W=((me=x==null?void 0:x.ui)==null?void 0:me.showHeader)!==!1;return e.jsxs("div",{className:"app","data-layout":we,"data-active-tab":n,children:[e.jsx("a",{className:"skip-to-main",href:"#main-content",children:"Skip to main content"}),W&&e.jsx(xi,{activeTab:n,onTabChange:F,wsStatus:u,version:vc,activeProject:(o==null?void 0:o.activeProject)||null,projects:(o==null?void 0:o.projects)||[],onProjectChange:Z,onProjectsRefresh:B,onOpenSearch:()=>v(!0),settings:x,notificationsSlot:e.jsx(ki,{wsSubscribe:J}),showTabs:we==="topnav",extraTabs:H}),b.length>0&&!f&&e.jsxs("div",{className:"stuck-banner",role:"alert",children:[e.jsx(Te,{size:16}),e.jsxs("span",{children:[e.jsx("strong",{children:b.length})," agent",b.length===1?"":"s"," stuck:"," ",e.jsx("span",{className:"mono",children:b.map(_=>_.name).join(", ")})]}),e.jsx($,{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:[we!=="topnav"&&e.jsx(vi,{tabs:H,activeTab:n,onTabChange:F,settingsMode:g,settingsActiveSection:k,onSettingsSectionChange:z,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}),N&&e.jsx(bc,{onSaved:()=>{S(!1),O()}}),e.jsxs("p",{className:"boot-error-hint",children:["Make sure the Bizar dashboard server is running. Try"," ",e.jsx("code",{children:"bizar-dash start"})," in your terminal."]})]}),!m&&(!o||!x)&&e.jsxs("div",{className:"loading",children:[e.jsx(oe,{size:"lg"}),e.jsx("p",{children:"Loading Bizar…"})]}),K&&e.jsx(r.Suspense,{fallback:e.jsxs("div",{className:"loading",children:[e.jsx(oe,{size:"lg"}),e.jsx("p",{children:"Loading…"})]}),children:e.jsx(wc,{children:K})})]})]}),e.jsx(yi,{open:E,onClose:()=>v(!1),onSelect:he})]})}class wc extends r.Component{constructor(){super(...arguments);ks(this,"state",{err:null});ks(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(Te,{size:20}),e.jsxs("div",{className:"view-error-body",children:[e.jsx("strong",{children:"This view crashed."}),e.jsx("pre",{children:this.state.err.message}),e.jsx($,{variant:"secondary",size:"sm",onClick:this.reset,children:"Retry"})]})]}):this.props.children}}function Sc(){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(Ha,{}):e.jsx(Nc,{})}const La=document.getElementById("root");if(!La)throw new Error("Root element #root not found");Ga(La).render(e.jsx(r.StrictMode,{children:e.jsx(Sc,{})}));