@polderlabs/bizar 5.1.0 → 5.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/bizar-dash/dist/assets/{MobileChat-BVojK0n5.js → MobileChat-OidrxXR9.js} +1 -1
  2. package/bizar-dash/dist/assets/{MobileChat-BVojK0n5.js.map → MobileChat-OidrxXR9.js.map} +1 -1
  3. package/bizar-dash/dist/assets/{MobileSettings-C85ApWKZ.js → MobileSettings-B91gVFii.js} +1 -1
  4. package/bizar-dash/dist/assets/{MobileSettings-C85ApWKZ.js.map → MobileSettings-B91gVFii.js.map} +1 -1
  5. package/bizar-dash/dist/assets/{icons-Clz0NR6Y.js → icons-Bd8piSb2.js} +159 -134
  6. package/bizar-dash/dist/assets/icons-Bd8piSb2.js.map +1 -0
  7. package/bizar-dash/dist/assets/{main-DTkNlLrw.css → main-3G6mOhiK.css} +1 -1
  8. package/bizar-dash/dist/assets/main-6YUZY968.js +19 -0
  9. package/bizar-dash/dist/assets/main-6YUZY968.js.map +1 -0
  10. package/bizar-dash/dist/assets/{mobile-IaZ47uKC.js → mobile-CSsp30lr.js} +2 -2
  11. package/bizar-dash/dist/assets/{mobile-IaZ47uKC.js.map → mobile-CSsp30lr.js.map} +1 -1
  12. package/bizar-dash/dist/assets/{mobile-D2pc-iNh.js → mobile-DtwK7DOV.js} +1 -1
  13. package/bizar-dash/dist/assets/{mobile-D2pc-iNh.js.map → mobile-DtwK7DOV.js.map} +1 -1
  14. package/bizar-dash/dist/assets/{useSlashCommands-DjEwHl4n.js → useSlashCommands-DEkxEvOO.js} +2 -2
  15. package/bizar-dash/dist/assets/{useSlashCommands-DjEwHl4n.js.map → useSlashCommands-DEkxEvOO.js.map} +1 -1
  16. package/bizar-dash/dist/index.html +5 -5
  17. package/bizar-dash/dist/mobile.html +3 -3
  18. package/bizar-dash/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -1
  19. package/bizar-dash/src/server/api.mjs +4 -0
  20. package/bizar-dash/src/server/eval-store.mjs +55 -0
  21. package/bizar-dash/src/server/eval.mjs +63 -0
  22. package/bizar-dash/src/server/plugins/permission-audit.mjs +109 -0
  23. package/bizar-dash/src/server/plugins/sandbox.mjs +76 -2
  24. package/bizar-dash/src/server/plugins/store.mjs +4 -0
  25. package/bizar-dash/src/server/routes/eval.mjs +42 -2
  26. package/bizar-dash/src/server/routes/plugins.mjs +55 -7
  27. package/bizar-dash/src/server/routes/tailscale.mjs +46 -0
  28. package/bizar-dash/src/server/routes/voice.mjs +42 -6
  29. package/bizar-dash/src/server/schedules-runner.mjs +61 -0
  30. package/bizar-dash/src/server/server.mjs +13 -0
  31. package/bizar-dash/src/server/voice-store.mjs +27 -0
  32. package/bizar-dash/src/server/workers/transcription-worker.mjs +213 -0
  33. package/bizar-dash/src/web/App.tsx +9 -0
  34. package/bizar-dash/src/web/components/EvalDiff.tsx +157 -0
  35. package/bizar-dash/src/web/components/EvalExportButton.tsx +27 -0
  36. package/bizar-dash/src/web/components/EvalRunCard.tsx +78 -0
  37. package/bizar-dash/src/web/components/InstallConfirmDialog.tsx +62 -0
  38. package/bizar-dash/src/web/components/MarketplacePluginCard.tsx +51 -0
  39. package/bizar-dash/src/web/components/PluginCard.tsx +64 -0
  40. package/bizar-dash/src/web/components/PluginPermissions.tsx +36 -0
  41. package/bizar-dash/src/web/components/ScheduleTemplateCard.tsx +1 -0
  42. package/bizar-dash/src/web/components/TailscaleSettings.tsx +161 -0
  43. package/bizar-dash/src/web/components/Toggle.tsx +31 -0
  44. package/bizar-dash/src/web/components/Topbar.tsx +9 -0
  45. package/bizar-dash/src/web/components/VoiceNotesPanel.tsx +28 -0
  46. package/bizar-dash/src/web/styles/main.css +684 -0
  47. package/bizar-dash/src/web/views/Doctor.tsx +3 -3
  48. package/bizar-dash/src/web/views/Eval.tsx +372 -0
  49. package/bizar-dash/src/web/views/EvalReport.tsx +353 -0
  50. package/bizar-dash/src/web/views/Marketplace.tsx +135 -0
  51. package/bizar-dash/src/web/views/Plugins.tsx +134 -0
  52. package/bizar-dash/src/web/views/Schedules.tsx +1 -1
  53. package/bizar-dash/src/web/views/Settings.tsx +2 -0
  54. package/bizar-dash/tests/a11y/components.test.tsx +149 -0
  55. package/bizar-dash/tests/a11y/forms.test.tsx +191 -0
  56. package/bizar-dash/tests/a11y/navigation.test.tsx +112 -0
  57. package/bizar-dash/tests/cli-tailscale.test.mjs +113 -0
  58. package/bizar-dash/tests/components/marketplace-plugin-card.test.tsx +144 -0
  59. package/bizar-dash/tests/components/plugin-permissions.test.tsx +95 -0
  60. package/bizar-dash/tests/eval-csv.test.mjs +67 -0
  61. package/bizar-dash/tests/eval-scheduled.test.mjs +84 -0
  62. package/bizar-dash/tests/eval-web-ui.test.tsx +220 -0
  63. package/bizar-dash/tests/plugins-permissions.test.mjs +525 -0
  64. package/bizar-dash/tests/voice-transcribe-worker.test.mjs +343 -0
  65. package/cli/bin.mjs +14 -0
  66. package/cli/commands/dash.mjs +19 -1
  67. package/cli/commands/service.mjs +7 -0
  68. package/cli/commands/tailscale.mjs +251 -0
  69. package/package.json +1 -1
  70. package/bizar-dash/dist/assets/icons-Clz0NR6Y.js.map +0 -1
  71. package/bizar-dash/dist/assets/main-8feQWXiF.js +0 -19
  72. package/bizar-dash/dist/assets/main-8feQWXiF.js.map +0 -1
@@ -1,19 +0,0 @@
1
- var Ua=Object.defineProperty;var _a=(s,t,a)=>t in s?Ua(s,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):s[t]=a;var ks=(s,t,a)=>_a(s,typeof t!="symbol"?t+"":t,a);import{a as z,c as Y,f as Ce,b as Ze,S as me,t as aa,e as Wa,p as Va,W as Ct,_ as na,d as hs,g as zs,A as Ha,M as qa}from"./mobile-IaZ47uKC.js";import{r,j as e,a as ia,R as We,b as Ka}from"./react-vendor-Dn4wqh4Z.js";import{X as ke,A as zt,R as ce,F as Ga,H as Ya,a as Xa,C as Zs,b as Fe,c as Qa,d as Oe,e as Ke,L as ra,M as et,B as Xe,f as Ks,S as Rs,g as $e,h as Ja,i as Ve,j as Pe,P as Gs,k as $s,l as As,m as Tt,n as la,o as Rt,p as pe,q as Za,r as ze,s as oa,t as Ot,T as ps,u as en,v as Ws,G as sn,w as ca,x as tn,y as ns,z as be,D as _e,I as st,E as js,J as Te,K as is,N as Ys,O as rs,Q as Qe,U as Xs,V as an,W as we,Y as $t,Z as tt,_ as xs,$ as nn,a0 as at,a1 as gs,a2 as rn,a3 as fs,a4 as qe,a5 as da,a6 as ma,a7 as Ms,a8 as ln,a9 as vs,aa as on,ab as cn,ac as dn,ad as as,ae as mn,af as un,ag as hn,ah as xn,ai as pn,aj as gn,ak as Bt,al as ua,am as At,an as jn,ao as fn,ap as ha,aq as vn,ar as yn,as as bn,at as kn,au as Nn,av as wn,aw as Sn,ax as Ts,ay as Cn,az as zn,aA as yt,aB as xa,aC as Ds,aD as ls,aE as pa,aF as Is,aG as ga,aH as Tn,aI as Rn,aJ as Qs,aK as $n,aL as ja,aM as Ls,aN as An,aO as Mn,aP as fa,aQ as Es,aR as bt,aS as Mt,aT as va,aU as xe,aV as In,aW as Ln,aX as ya,aY as En,aZ as Dn,a_ as Pn,a$ as ba,b0 as it,b1 as ka,b2 as It,b3 as Fn,b4 as On,b5 as Na,b6 as Bn,b7 as Un,b8 as _n}from"./icons-Clz0NR6Y.js";import{u as re,V as Lt,C as Wn,a as Vn,b as Hn,c as qn,d as Kn,T as Gn}from"./useSlashCommands-DjEwHl4n.js";import{M as wa,r as Sa}from"./markdown-C6mXtQxD.js";import"./vendor-CeHGtduv.js";const Ca=r.createContext(null),Yn=["button:not([disabled])","[href]","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(", ");function Ae(){const s=r.useContext(Ca);return s||{open:()=>"",close:()=>{},isModalOpen:!1}}function Xn({children:s}){const[t,a]=r.useState([]),i=r.useCallback(c=>{a(o=>{if(!c)return o.slice(0,-1);const l=o.findIndex(h=>h.id===c);return l===-1||l!==o.length-1?o:o.slice(0,-1)})},[]),n=r.useCallback(c=>{const o=`m${Math.random().toString(36).slice(2,9)}`;return a(l=>[...l,{...c,id:o}]),o},[]);return r.useEffect(()=>{if(t.length===0)return;const c=o=>{o.key==="Escape"&&(o.stopPropagation(),i())};return document.addEventListener("keydown",c),()=>document.removeEventListener("keydown",c)},[t.length,i]),e.jsxs(Ca.Provider,{value:{open:n,close:i,isModalOpen:t.length>0},children:[s,typeof document<"u"&&ia.createPortal(e.jsx("div",{className:"modal-stack","aria-hidden":t.length===0,children:t.map((c,o)=>e.jsx(Qn,{modal:c,onClose:()=>{var l;(l=c.onClose)==null||l.call(c),i(c.id)},depth:o},c.id))}),document.body)]})}function Qn({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(Yn)).filter(h=>!h.hasAttribute("disabled")&&h.tabIndex!==-1):[]};return r.useEffect(()=>{var x;n.current=document.activeElement instanceof HTMLElement?document.activeElement:null,(x=o()[0]??i.current)==null||x.focus();const h=u=>{var f,y,S;if(u.key!=="Tab")return;const d=o();if(d.length===0){u.preventDefault(),(f=i.current)==null||f.focus();return}const m=d[0],p=d[d.length-1],g=document.activeElement instanceof HTMLElement?document.activeElement:null;if(u.shiftKey){(!g||g===m||!((y=i.current)!=null&&y.contains(g)))&&(u.preventDefault(),p.focus());return}(!g||g===p||!((S=i.current)!=null&&S.contains(g)))&&(u.preventDefault(),m.focus())};return document.addEventListener("keydown",h),()=>{document.removeEventListener("keydown",h);const u=n.current;u&&u.isConnected&&u.focus()}},[]),e.jsx("div",{className:"modal-backdrop",onClick:l=>{l.stopPropagation(),l.target===l.currentTarget&&t()},style:a>0?{background:"rgba(0,0,0,0.4)"}:void 0,children:e.jsxs("div",{ref:i,className:"modal",role:"dialog","aria-modal":"true","aria-labelledby":s.title?c:void 0,tabIndex:-1,onClick:l=>l.stopPropagation(),style:s.width?{maxWidth:s.width}:void 0,children:[s.title&&e.jsxs("header",{className:"modal-header",children:[e.jsx("h2",{id:c,className:"modal-title",children:s.title}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Close",onClick:t,children:e.jsx(ke,{size:16})})]}),e.jsx("div",{className:"modal-body",children:s.children}),s.footer&&e.jsx("footer",{className:"modal-footer",children:s.footer})]})})}const Jn=200,Zn=5*60*1e3,ts=new Map;function ei(s){const t=ts.get(s);return t?Date.now()-t.ts>Zn?(ts.delete(s),null):t.data:null}function rt(s,t){ts.size>=Jn&&[...ts.entries()].sort((i,n)=>i[1].ts-n[1].ts).slice(0,50).map(([i])=>i).forEach(i=>ts.delete(i)),ts.set(s,{data:t,ts:Date.now()})}function si(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 ti(s){return[...s].sort((t,a)=>t.isDir!==a.isDir?t.isDir?-1:1:t.name.localeCompare(a.name,void 0,{sensitivity:"base"}))}function ai(s){const t=s.trim();return t?t!==s?{ok:!1,reason:"Name cannot have leading or trailing whitespace."}:t==="."?{ok:!1,reason:"Name cannot be '.'."}:t===".."?{ok:!1,reason:"Name cannot be '..'."}:t.startsWith("-")?{ok:!1,reason:"Name cannot start with '-'."}:t.length>255?{ok:!1,reason:"Name cannot be longer than 255 characters."}:/[/\0:*?"<>|]/.test(t)?{ok:!1,reason:'Name cannot contain / \\ : * ? " < > |'}:{ok:!0}:{ok:!1,reason:"Name cannot be empty."}}function za({value:s,onChange:t,initialPath:a,projectsDirectory:i,rootLabel:n="Home",height:c=360}){const[o,l]=r.useState(a??i??""),[h,x]=r.useState(new Set),[u,d]=r.useState(-1),[m,p]=r.useState(null),[g,f]=r.useState({}),[y,S]=r.useState(!1),[k,w]=r.useState(null),[E,v]=r.useState(!1),[C,R]=r.useState(""),[j,P]=r.useState(null),[T,b]=r.useState(!1),A=r.useRef(null),O=r.useCallback(async D=>{try{const se=ei(D);if(se)return se;const W=await z.get("/fs?path="+encodeURIComponent(D));return rt(D,W),W}catch{return null}},[]),N=r.useCallback(async D=>{var se;S(!0),w(null);try{const W=await z.get("/fs?path="+encodeURIComponent(D));rt(D,W),p(W),d(-1)}catch(W){const oe=((se=W.data)==null?void 0:se.message)??W.message??"Failed to load directory";w(oe)}finally{S(!1)}},[]);r.useEffect(()=>{o?N(o):z.get("/fs").then(D=>{rt("",D),p(D),l(D.path),D.path!==s&&t(D.path)}).catch(()=>{w("Could not determine home directory."),S(!1)})},[o]),r.useEffect(()=>{s&&s!==o&&l(s)},[s]);const F=m?ti(m.entries):[],K=F.filter(D=>D.isDir),L=F,G=D=>{D.isDir&&(l(D.path),t(D.path))},ne=()=>{m!=null&&m.parent&&(l(m.parent),t(m.parent))},te=D=>{D!==o&&(l(D),t(D))},B=async()=>{const D=await O("");D&&(l(D.path),t(D.path))},V=async()=>{if(!i)return;const D=await O(i);D&&(l(D.path),t(D.path))},X=()=>{v(!0),R(""),P(null),setTimeout(()=>{var D;return(D=A.current)==null?void 0:D.focus()},0)},U=()=>{v(!1),R(""),P(null)},J=async()=>{var se;const D=ai(C);if(!D.ok){P(D.reason);return}b(!0),P(null);try{const W=await z.post("/fs/mkdir",{parent:o,name:C.trim()});ts.delete(o),await N(o),t(W.path),v(!1),R("")}catch(W){const oe=W;oe.status===409?P(`A folder named "${C.trim()}" already exists.`):P(((se=oe.data)==null?void 0:se.message)??W.message??"Failed to create folder.")}finally{b(!1)}},he=D=>{D.key==="Enter"?(D.preventDefault(),J()):D.key==="Escape"&&(D.preventDefault(),U())},ye=D=>{x(se=>{const W=new Set(se);return W.has(D)?W.delete(D):W.add(D),W}),g[D]||O(D).then(se=>{se&&f(W=>({...W,[D]:se.entries.filter(oe=>oe.isDir)}))})},I=D=>{if(!m)return;const se=L.filter(q=>q.isDir),W=L.filter(q=>!q.isDir),oe=[...se,...W];if(D.key==="ArrowDown")D.preventDefault(),d(q=>Math.min(q+1,oe.length-1));else if(D.key==="ArrowUp")D.preventDefault(),d(q=>Math.max(q-1,0));else if(D.key==="Enter"||D.key===" "){D.preventDefault();const q=oe[u];q&&(D.key==="Enter"&&q.isDir?G(q):q.isDir&&t(q.path))}else D.key==="Backspace"&&(D.preventDefault(),ne())},H=si((m==null?void 0:m.path)??o??"/"),Q=m==null?void 0:m.parent,le=Q!=null,_=o.split("/").filter(Boolean).at(-1)??"/";return e.jsxs("div",{className:"file-browser",onKeyDown:I,tabIndex:-1,children:[e.jsx("div",{className:"file-browser-breadcrumb",role:"navigation","aria-label":"Path breadcrumb",children:H.map((D,se)=>e.jsxs("span",{className:"file-browser-breadcrumb-item",children:[se>0&&e.jsx("span",{className:"file-browser-breadcrumb-sep","aria-hidden":!0,children:"/"}),e.jsx("button",{type:"button",className:"file-browser-breadcrumb-btn",onClick:()=>te(D.path),title:D.path,children:se===0?D.path==="/"?"/":n:D.label})]},D.path))}),e.jsxs("div",{className:"file-browser-toolbar",children:[e.jsxs("div",{className:"file-browser-toolbar-left",children:[e.jsx("button",{type:"button",className:"file-browser-tool-btn",onClick:ne,disabled:!le,title:"Go up (Backspace)","aria-label":"Go up one level",children:e.jsx(zt,{size:13})}),e.jsx("button",{type:"button",className:"file-browser-tool-btn",onClick:()=>N(o),disabled:y,title:"Refresh","aria-label":"Refresh",children:e.jsx(ce,{size:13,className:y?"spin":""})}),e.jsx("button",{type:"button",className:"file-browser-tool-btn",onClick:X,title:"New folder","aria-label":"Create new folder",children:e.jsx(Ga,{size:13})}),e.jsxs("div",{className:"file-browser-chips",children:[e.jsxs("button",{type:"button",className:"file-browser-chip",onClick:B,children:[e.jsx(Ya,{size:11})," ",n]}),i&&e.jsxs("button",{type:"button",className:"file-browser-chip",onClick:V,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:C,onChange:D=>{R(D.target.value),P(null)},onKeyDown:he,"aria-label":"New folder name","aria-invalid":j?"true":void 0,"aria-describedby":j?"mkdir-error":void 0,disabled:T,maxLength:255}),j?e.jsx("span",{id:"mkdir-error",className:"file-browser-mkdir-error",role:"alert",children:j}):e.jsx("span",{className:"file-browser-mkdir-hint",children:"Enter to create, Esc to cancel"})]}):e.jsx("span",{className:"file-browser-count-hint",children:y?"…":`${F.length} in ${_}`})]}),k&&e.jsxs("div",{className:"file-browser-error",children:[e.jsx(Zs,{size:13}),e.jsx("span",{children:k}),e.jsx("button",{type:"button",className:"file-browser-retry",onClick:()=>N(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:y&&!m?e.jsx(ni,{}):e.jsx(Ta,{path:o,entries:K,expanded:h,childrenMap:g,onToggle:ye,onNavigate:G,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"})]}),y&&!m?e.jsx(ii,{}):e.jsxs(e.Fragment,{children:[(m==null?void 0:m.truncated)&&e.jsxs("div",{className:"file-browser-truncated-banner",role:"status",children:["Showing first 500 of ",m.totalEntries," entries. Navigate into a subfolder to see more."]}),L.length===0?e.jsx("div",{className:"file-browser-empty",children:"This folder is empty"}):e.jsx("div",{className:"file-browser-flat-list",children:L.map((D,se)=>{const W=D.isDir,oe=se===u,q=D.path===s;return e.jsxs("div",{role:"option","aria-selected":q,className:["file-browser-row",W?"file-browser-row--dir":"file-browser-row--file",oe&&"file-browser-row--selected",q&&W&&"file-browser-row--active",!W&&"file-browser-row--disabled"].filter(Boolean).join(" "),onClick:()=>{W&&(d(se),t(D.path))},onDoubleClick:()=>{W&&G(D)},title:D.path,children:[e.jsx("span",{className:"file-browser-row-icon",children:W?e.jsx(Fe,{size:13}):e.jsx(Qa,{size:13})}),e.jsx("span",{className:"file-browser-row-name",children:D.name}),e.jsx("span",{className:"file-browser-row-type",children:W?"Folder":""})]},D.path)})})]})]})]}),e.jsxs("div",{className:"file-browser-footer-hint",children:["Select a folder, then click Add. Use ",e.jsx("kbd",{children:"↑"})," ",e.jsx("kbd",{children:"↓"})," to navigate, ",e.jsx("kbd",{children:"Enter"})," to confirm."]})]})}function Ta({path:s,entries:t,expanded:a,childrenMap:i,onToggle:n,onNavigate:c,level:o}){return e.jsx("ul",{className:"file-browser-tree-list",role:"group",children:t.map(l=>{const h=a.has(l.path),x=i[l.path]??[];return e.jsxs("li",{className:"file-browser-tree-node",children:[e.jsxs("div",{className:["file-browser-tree-row",h&&"file-browser-tree-row--expanded"].filter(Boolean).join(" "),style:{paddingLeft:`${o*16+8}px`},children:[e.jsx("button",{type:"button",className:"file-browser-tree-toggle",onClick:u=>{u.stopPropagation(),n(l.path)},"aria-label":h?"Collapse":"Expand",children:(x.length>0,h?e.jsx(Oe,{size:11}):e.jsx(Ke,{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})]})]}),h&&x.length>0&&e.jsx(Ta,{path:l.path,entries:x,expanded:a,childrenMap:i,onToggle:n,onNavigate:c,level:o+1})]},l.path)})})}function ni(){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 ii(){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 $=r.forwardRef(function({variant:t="secondary",size:a="md",iconOnly:i=!1,loading:n=!1,disabled:c,className:o,children:l,...h},x){return e.jsxs("button",{ref:x,type:h.type??"button",disabled:c||n,className:Y("btn",`btn-${t}`,`btn-size-${a}`,i&&"btn-icon",n&&"btn-loading",o),...h,children:[n?e.jsx("span",{className:"btn-spinner","aria-hidden":!0}):null,l]})}),kt=[{id:"overview",label:"Overview",icon:ra},{id:"chat",label:"Chat",icon:et},{id:"agents",label:"Agents",icon:Xe},{id:"artifacts",label:"Glyphs",icon:Ks},{id:"tasks",label:"Tasks",icon:Rs},{id:"activity",label:"Activity",icon:$e},{id:"background",label:"Active",icon:Ja},{id:"skills",label:"Skills",icon:Ve},{id:"memory",label:"Memory",icon:Pe},{id:"mods",label:"Mods",icon:Gs},{id:"schedules",label:"Schedules",icon:$s},{id:"history",label:"History",icon:As},{id:"minimax",label:"Usage",icon:Tt},{id:"doctor",label:"Doctor",icon:la},{id:"settings",label:"Settings",icon:Rt}];function ri({activeTab:s,onTabChange:t,wsStatus:a,version:i,activeProject:n,projects:c,onProjectChange:o,onProjectsRefresh:l,onOpenSearch:h,settings:x,rightSlot:u,notificationsSlot:d,showTabs:m=!0,extraTabs:p}){return e.jsxs("header",{className:"topbar",children:[e.jsxs("div",{className:"topbar-row",children:[e.jsxs("div",{className:"brand",children:[e.jsx("span",{className:"brand-logo","aria-hidden":"true",children:"ᛒ"}),e.jsx("span",{className:"brand-title",children:"Bizar"}),e.jsx("span",{className:"brand-version",children:i})]}),e.jsx(li,{activeProject:n,projects:c,onChange:o,onRefresh:l,settings:x??null}),e.jsxs("button",{type:"button",className:"topbar-search",onClick:h,title:"Search (Ctrl/Cmd+K)","aria-label":"Open search",children:[e.jsx(pe,{size:14}),e.jsx("span",{className:"muted",children:"Search…"}),e.jsx("kbd",{children:"⌘K"})]}),e.jsx("div",{className:"topbar-spacer"}),e.jsxs("div",{className:"topbar-right",children:[d,u,e.jsxs("div",{className:Y("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:[kt.map(g=>{const f=g.icon,y=g.id===s;return e.jsxs("button",{type:"button",role:"tab","aria-selected":y,className:Y("tab",y&&"tab-active"),onClick:()=>t(g.id),title:g.label,children:[e.jsx(f,{size:14,className:"tab-icon"}),e.jsx("span",{className:"tab-label",children:g.label}),g.id==="settings"&&y&&e.jsx("span",{className:"settings-mode-indicator",title:"Settings mode active",children:e.jsx(Za,{size:12})})]},g.id)}),p&&p.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"tab-separator","aria-hidden":"true"}),p.map(g=>{const f=g.icon,y=g.id===s;return e.jsxs("button",{type:"button",role:"tab","aria-selected":y,className:Y("tab","tab-mod",y&&"tab-active"),onClick:()=>t(g.id),title:`${g.label} (mod)`,children:[e.jsx(f,{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 li({activeProject:s,projects:t,onChange:a,onRefresh:i,settings:n}){const[c,o]=r.useState(!1),l=Ae();r.useEffect(()=>{if(!c)return;const x=()=>o(!1);return document.addEventListener("click",x),()=>document.removeEventListener("click",x)},[c]);const h=()=>{l.open({title:"Add project",children:e.jsx(oi,{settings:n,onAdd:async(x,u)=>{try{await z.post("/projects",{path:x,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:x=>x.stopPropagation(),children:[e.jsxs("button",{type:"button",className:"project-selector-btn",onClick:()=>o(x=>!x),title:"Switch active project","aria-haspopup":"menu","aria-expanded":c,children:[e.jsx(Fe,{size:14}),e.jsx("span",{className:"project-selector-name",children:(s==null?void 0:s.name)||"(no project)"}),e.jsx(Oe,{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(ce,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn",onClick:h,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(x=>e.jsx("li",{children:e.jsxs("button",{type:"button",className:Y("project-selector-item",(s==null?void 0:s.id)===x.id&&"active"),onClick:()=>{a(x.id),o(!1)},children:[e.jsx("span",{className:"project-selector-item-name",children:x.name}),e.jsx("span",{className:"project-selector-item-status",children:x.status})]})},x.id))]})]})]})}function oi({settings:s,onAdd:t}){var d,m;const[a,i]=r.useState(((d=s==null?void 0:s.dashboard)==null?void 0:d.projectsDirectory)??""),[n,c]=r.useState(""),[o,l]=r.useState(!1),[h,x]=r.useState(null),u=async()=>{var p;if(a){l(!0),x(null);try{await z.get("/fs?path="+encodeURIComponent(a)),t(a,n||null)}catch(g){const f=g;f.status===404?x("That folder no longer exists. Pick another."):x(((p=f.data)==null?void 0:p.message)??g.message??"Validation failed.")}finally{l(!1)}}};return e.jsxs("div",{children:[e.jsx("label",{className:"field-label",children:"Folder"}),e.jsx(za,{value:a,onChange:p=>{i(p),x(null)},projectsDirectory:(m=s==null?void 0:s.dashboard)==null?void 0:m.projectsDirectory,height:320}),h&&e.jsx("p",{className:"field-help",style:{color:"var(--error)",marginTop:4},children:h}),e.jsxs("div",{style:{marginTop:"var(--space-3)"},children:[e.jsx("label",{className:"field-label",htmlFor:"topbar-add-project-name",children:"Name (optional)"}),e.jsx("input",{id:"topbar-add-project-name",className:"input",type:"text",placeholder:"My App",value:n,onChange:p=>c(p.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 ci=[{label:"General",sections:[{id:"theme",label:"Theme",icon:oa},{id:"layout",label:"Layout",icon:Ot},{id:"general",label:"General",icon:Ot}]},{label:"Core",sections:[{id:"env-vars",label:"Env Vars",icon:ps},{id:"providers",label:"Providers",icon:en},{id:"memory",label:"Memory",icon:Pe},{id:"system-llm",label:"System LLM",icon:Ws}]},{label:"Experience",sections:[{id:"updates",label:"Updates",icon:ce},{id:"skills",label:"Skills",icon:Ve},{id:"headroom",label:"Headroom",icon:sn}]},{label:"Data",sections:[{id:"backup",label:"Backup",icon:ca}]}];function di({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(zt,{size:14}),e.jsx("span",{children:"Back"})]}),e.jsx("div",{className:"settings-nav-divider","aria-hidden":"true"}),ci.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:Y("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(Ke,{size:12,className:"settings-nav-item-chevron","aria-hidden":!0})]},n.id)})]},i.label))]})}function mi({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(di,{activeSection:n??null,onSectionChange:c??(()=>{}),onExitSettings:o??(()=>{})})});const l=s.filter(x=>!x.isMod),h=s.filter(x=>x.isMod);return e.jsx("aside",{className:"sidebar","aria-label":"Primary navigation",children:e.jsxs("nav",{className:"sidebar-nav",role:"tablist",children:[l.map(x=>{const u=x.icon,d=x.id===t;return e.jsxs("button",{type:"button",role:"tab","aria-selected":d,className:Y("sidebar-tab",d&&"sidebar-tab-active"),onClick:()=>a(x.id),title:x.label,children:[e.jsx(u,{size:18,"aria-hidden":!0}),e.jsx("span",{className:"sidebar-tab-label",children:x.label})]},x.id)}),h.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"sidebar-section-divider","aria-hidden":"true"}),e.jsx("div",{className:"sidebar-section-label",children:"Mods"}),h.map(x=>{const u=x.icon,d=x.id===t;return e.jsxs("button",{type:"button",role:"tab","aria-selected":d,className:Y("sidebar-tab","sidebar-tab-mod",d&&"sidebar-tab-active"),onClick:()=>a(x.id),title:`${x.label} (mod)`,children:[e.jsx(u,{size:18,"aria-hidden":!0}),e.jsx("span",{className:"sidebar-tab-label",children:x.label})]},x.id)})]})]})})}const lt=[{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"}],Ut={all:null,projects:"project",agents:"agent",tasks:"task",mods:"mod",schedules:"schedule",commands:"command",settings:"setting"};function ui({open:s,onClose:t,onSelect:a}){const i=re(),[n,c]=r.useState(""),[o,l]=r.useState("all"),[h,x]=r.useState([]),[u,d]=r.useState(!1),[m,p]=r.useState(0),g=r.useRef(null),f=r.useRef(null);if(r.useEffect(()=>{let w;return s&&(f.current=document.activeElement instanceof HTMLElement?document.activeElement:null,c(""),x([]),p(0),w=window.setTimeout(()=>{var E;return(E=g.current)==null?void 0:E.focus()},30)),()=>{if(w&&window.clearTimeout(w),!s)return;const E=f.current;E&&E.isConnected&&E.focus()}},[s]),r.useEffect(()=>{if(!s)return;if(!n.trim()){x([]),p(0);return}let w=!1;d(!0);const E=setTimeout(()=>{z.get(`/search?q=${encodeURIComponent(n)}&scope=${o}`).then(v=>{w||(x(v.results||[]),p(0))}).catch(v=>{w||i.error(`Search failed: ${v.message}`)}).finally(()=>!w&&d(!1))},150);return()=>{w=!0,clearTimeout(E)}},[n,o,s,i]),!s)return null;const y={};for(const w of h){const E=w.type.toLowerCase();y[E]=y[E]||[],y[E].push(w)}const S=[];for(const w of lt.map(E=>E.id)){const E=Ut[w];E&&y[E]&&S.push(...y[E])}const k=w=>{if(w.key==="Escape")t();else if(w.key==="ArrowDown"){if(w.preventDefault(),S.length===0)return;p(E=>Math.min(E+1,S.length-1))}else if(w.key==="ArrowUp"){if(w.preventDefault(),S.length===0)return;p(E=>Math.max(E-1,0))}else w.key==="Enter"&&S[m]&&(w.preventDefault(),a(S[m]),t())};return e.jsx("div",{className:"search-modal-backdrop",onClick:t,children:e.jsxs("div",{className:"search-modal",role:"dialog","aria-modal":"true","aria-labelledby":"search-modal-title",onClick:w=>w.stopPropagation(),children:[e.jsxs("div",{className:"search-modal-head",role:"search",children:[e.jsx(pe,{size:14,"aria-hidden":!0}),e.jsx("span",{id:"search-modal-title",className:"sr-only",children:"Search"}),e.jsx("input",{ref:g,className:"search-modal-input",placeholder:"Search tasks, agents, settings, projects…",value:n,onChange:w=>c(w.target.value),onKeyDown:k,"aria-label":"Search"}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Close",onClick:t,children:e.jsx(ke,{size:14})})]}),e.jsx("div",{className:"search-modal-scopes",role:"tablist","aria-label":"Search scope",children:lt.map(w=>e.jsx("button",{type:"button",role:"tab","aria-selected":o===w.id,className:Y("search-scope",o===w.id&&"search-scope-active"),onClick:()=>l(w.id),children:w.label},w.id))}),e.jsxs("div",{className:"search-modal-body",children:[u&&e.jsx("div",{className:"muted",children:"Searching…"}),!u&&n&&S.length===0&&e.jsx("div",{className:"muted",children:"No results."}),!u&&!n&&e.jsx("div",{className:"muted",children:"Type to search…"}),lt.map(w=>{const E=Ut[w.id];if(!E)return null;const v=y[E];return!v||v.length===0?null:e.jsxs("div",{className:"search-group",children:[e.jsx("div",{className:"search-group-head",children:w.label}),v.map(C=>{const R=S.indexOf(C);return e.jsxs("button",{type:"button",className:Y("search-result",R===m&&"search-result-active"),onMouseEnter:()=>p(R),onClick:()=>{a(C),t()},children:[e.jsx("span",{className:"search-result-type",children:C.type}),e.jsx("span",{className:"search-result-label",children:hi(C)})]},`${C.type}-${R}`)})]},w.id)})]}),e.jsx("div",{className:"search-modal-foot",children:e.jsx("span",{className:"muted",children:"↑↓ navigate · ↵ open · esc close"})})]})})}function hi(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 xi={info:st,success:_e,warning:be,error:Zs};function pi({onCountChange:s,wsSubscribe:t}){const a=re(),[i,n]=r.useState(!1),[c,o]=r.useState([]),[l,h]=r.useState(null),[x,u]=r.useState(!1),d=r.useRef(null),m=r.useRef(0),p=async()=>{var k;try{u(!0);const w=await z.get("/notifications?limit=200");o(w.notifications||[]),h(w.stats||null),m.current=((k=w.stats)==null?void 0:k.unread)||0,s==null||s(m.current)}catch(w){console.warn("[notifications] reload failed:",w.message)}finally{u(!1)}};r.useEffect(()=>{p()},[]),r.useEffect(()=>t?t(w=>{if(w.type==="notification:new"){const E=w.notification;o(v=>[E,...v.filter(C=>C.id!==E.id)]),E.read||(m.current+=1,h(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 w.type==="notifications:change"&&p()}):void 0,[t]),r.useEffect(()=>{if(!i)return;const k=E=>{d.current&&(d.current.contains(E.target)||n(!1))},w=E=>{E.key==="Escape"&&n(!1)};return document.addEventListener("mousedown",k),document.addEventListener("keydown",w),()=>{document.removeEventListener("mousedown",k),document.removeEventListener("keydown",w)}},[i]);const g=async()=>{try{await z.post("/notifications/read-all",{}),o(k=>k.map(w=>({...w,read:!0}))),h(k=>k&&{...k,unread:0}),m.current=0,s==null||s(0),a.success("All notifications marked as read.",1500)}catch(k){a.error(`Failed: ${k.message}`)}},f=async k=>{try{await z.post(`/notifications/${encodeURIComponent(k)}/read`,{}),o(w=>w.map(E=>E.id===k?{...E,read:!0}:E)),h(w=>w&&{...w,unread:Math.max(0,(w.unread||1)-1)}),m.current=Math.max(0,m.current-1),s==null||s(m.current)}catch(w){a.error(`Failed: ${w.message}`)}},y=async k=>{try{await z.del(`/notifications/${encodeURIComponent(k)}`),o(w=>{const E=w.find(v=>v.id===k);return E&&!E.read&&(m.current=Math.max(0,m.current-1),h(v=>v&&{...v,unread:Math.max(0,v.unread-1)}),s==null||s(m.current)),w.filter(v=>v.id!==k)})}catch(w){a.error(`Failed: ${w.message}`)}},S=(l==null?void 0:l.unread)||0;return e.jsxs("div",{className:"notifications-root",ref:d,children:[e.jsxs("button",{type:"button",className:Y("topbar-icon-btn notifications-bell",i&&"is-open"),onClick:()=>n(k=>!k),title:"Notifications","aria-label":"Notifications","aria-haspopup":"true","aria-expanded":i,children:[e.jsx(tn,{size:16}),S>0&&e.jsx("span",{className:"notifications-badge",children:S>99?"99+":S})]}),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"}),S>0&&e.jsxs("span",{className:"muted text-sm",children:[" · ",S," unread"]})]}),e.jsxs("div",{className:"notifications-panel-head-actions",children:[e.jsxs($,{size:"sm",variant:"ghost",onClick:g,disabled:S===0,children:[e.jsx(ns,{size:12})," Mark all read"]}),e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>n(!1),"aria-label":"Close",title:"Close",children:e.jsx(ke,{size:14})})]})]}),e.jsx("div",{className:"notifications-list",children:x&&c.length===0?e.jsx("div",{className:"notifications-empty muted",children:"Loading…"}):c.length===0?e.jsx("div",{className:"notifications-empty muted",children:"No notifications yet."}):c.map(k=>{const w=xi[k.severity]||st;return e.jsxs("div",{className:Y("notification-item",!k.read&&"is-unread",`severity-${k.severity}`),children:[e.jsx(w,{size:14,className:`notification-icon severity-${k.severity}`}),e.jsxs("div",{className:"notification-body",children:[k.title&&e.jsx("div",{className:"notification-title",children:k.title}),e.jsx("div",{className:"notification-msg",children:k.message}),e.jsxs("div",{className:"notification-meta muted",children:[e.jsx("span",{className:"mono",children:k.source}),e.jsx("span",{children:"·"}),e.jsx("span",{children:Ce(k.ts)})]})]}),e.jsxs("div",{className:"notification-actions",children:[!k.read&&e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>f(k.id),title:"Mark as read","aria-label":"Mark as read",children:e.jsx(ns,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger",onClick:()=>y(k.id),title:"Remove","aria-label":"Remove",children:e.jsx(ke,{size:12})})]})]},k.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 gi({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 ji=["blank","feature-design","bug-investigation","decision-record","horizontal","vertical"];function fi({data:s,onClose:t}){const a=(s==null?void 0:s.templates)??ji,i=(s==null?void 0:s.defaultTemplate)??"blank",[n,c]=r.useState(""),[o,l]=r.useState(i),[h,x]=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}x(!0),d(null);try{await z.post("/artifacts",{slug:n,template:o}),t()}catch(p){d(p.message),x(!1)}};return e.jsxs("div",{children:[e.jsxs("p",{style:{marginBottom:16,color:"var(--color-muted)",fontSize:13},children:["Create a new visual plan. Plans are stored in ",e.jsx("code",{children:"artifacts/"})," in your worktree."]}),e.jsxs("div",{style:{marginBottom:12},children:[e.jsx("label",{className:"field-label",htmlFor:"plan-slug",children:"Plan slug"}),e.jsx("input",{id:"plan-slug",className:"input",type:"text",placeholder:"e.g. my-feature",value:n,onChange:p=>{c(p.target.value),d(null)},autoFocus:!0})]}),e.jsxs("div",{style:{marginBottom:16},children:[e.jsx("label",{className:"field-label",htmlFor:"plan-template",children:"Template"}),e.jsx("select",{id:"plan-template",className:"select",value:o,onChange:p=>l(p.target.value),children:a.map(p=>e.jsx("option",{value:p,children:p},p))})]}),u&&e.jsx("p",{style:{marginBottom:12,color:"var(--color-danger)",fontSize:13},children:u}),e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx($,{variant:"ghost",onClick:t,disabled:h,children:"Cancel"}),e.jsx($,{variant:"primary",onClick:m,disabled:h||!n.trim(),children:h?"Creating…":"Create"})]})]})}function vi({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 yi({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 bi({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 z.post("/chat/audit",{});c(l)}catch(l){c({ok:!1,findings:[],error:l.message})}finally{i(!1)}};return e.jsx("div",{children:n===null?e.jsxs(e.Fragment,{children:[e.jsx("p",{style:{marginBottom:16,lineHeight:1.6},children:"Run a security audit of your Bizar agent configuration. The audit checks for common misconfigurations, exposed secrets, and insecure defaults."}),e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx($,{variant:"ghost",onClick:t,children:"Cancel"}),e.jsx($,{variant:"primary",onClick:o,disabled:a,children:a?"Running…":"Run Audit"})]})]}):e.jsxs(e.Fragment,{children:[n.ok?e.jsxs("div",{children:[e.jsx("p",{style:{marginBottom:12,fontWeight:600,color:"var(--color-success)"},children:"Audit passed — no issues found."}),n.findings.length>0&&e.jsx("ul",{style:{marginBottom:16,paddingLeft:20},children:n.findings.map((l,h)=>e.jsx("li",{style:{marginBottom:4,fontSize:13},children:l},h))})]}):e.jsxs("p",{style:{marginBottom:16,color:"var(--color-danger)"},children:["Audit failed: ",n.error??"unknown error"]}),e.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:e.jsx($,{variant:"ghost",onClick:t,children:"Close"})})]})})}function ki({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 Ni({dialog:s,onClose:t}){switch(s.component){case"visual-artifact":return e.jsx(gi,{data:s.data,onClose:t});case"artifact-create":return e.jsx(fi,{data:s.data,onClose:t});case"artifact-list":return e.jsx(vi,{data:s.data,onClose:t});case"help":return e.jsx(yi,{data:s.data,onClose:t});case"audit":return e.jsx(bi,{data:s.data,onClose:t});default:return e.jsx(ki,{dialog:s,onClose:t})}}function ee({variant:s="elevated",interactive:t=!1,className:a,children:i,...n}){return e.jsx("div",{className:Y("card",`card-${s}`,t&&"card-interactive",a),...n,children:i})}function ae({children:s,className:t}){return e.jsx("h3",{className:Y("card-title",t),children:s})}function ie({children:s,className:t}){return e.jsx("div",{className:Y("card-meta",t),children:s})}function wi({setActiveTab:s,refreshKey:t=0}){var x;const[a,i]=r.useState(null),[n,c]=r.useState(!0),o=async()=>{c(!0);try{const[u,d,m]=await Promise.all([z.get("/memory/status").catch(()=>null),z.get("/memory/health").catch(()=>null),z.get("/memory/lightrag/stats").catch(()=>null)]);i({initialized:!!(u!=null&&u.initialized),mode:u==null?void 0:u.mode,projectId:u==null?void 0:u.projectId,vaultRoot:u==null?void 0:u.vaultRoot,branch:u==null?void 0:u.branch,gitClean:u==null?void 0:u.gitClean,noteCount:(u==null?void 0:u.noteCount)||0,healthScore:d==null?void 0:d.score,healthStatus:d==null?void 0:d.status,lightrag:m?{running:m.running,indexedApprox:m.indexedApprox}:void 0})}catch{i({initialized:!1})}finally{c(!1)}};r.useEffect(()=>{o()},[t]);const l=()=>s("memory"),h=(a==null?void 0:a.healthStatus)==="healthy"?"var(--success)":(a==null?void 0:a.healthStatus)==="degraded"?"var(--warning)":(a==null?void 0:a.healthStatus)==="unhealthy"?"var(--error)":"var(--text-dim)";return e.jsxs(ee,{className:"memory-overview-card",children:[e.jsxs(ae,{children:[e.jsx(Pe,{size:14})," Memory",e.jsxs($,{variant:"ghost",size:"sm",style:{marginLeft:"auto"},onClick:l,children:["Open Memory ",e.jsx(js,{size:12})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:o,"aria-label":"Refresh",title:"Refresh",children:e.jsx(ce,{size:12})})]}),e.jsx(ie,{children:"LightRAG + Obsidian vault + git sync — opens the dedicated Memory tab."}),a!=null&&a.initialized?e.jsxs("div",{className:"memory-status-card-grid",children:[e.jsxs("div",{className:"memory-status-card-cell",children:[e.jsxs("div",{className:"memory-status-card-label",children:[e.jsx($e,{size:11})," Health"]}),e.jsx("div",{className:"memory-status-card-value",style:{color:h},children:a.healthScore!==void 0?`${a.healthScore}/100`:"—"}),e.jsx("div",{className:"memory-status-card-sub muted",children:a.healthStatus||"—"})]}),e.jsxs("div",{className:"memory-status-card-cell",children:[e.jsxs("div",{className:"memory-status-card-label",children:[e.jsx(Pe,{size:11})," LightRAG"]}),e.jsx("div",{className:"memory-status-card-value",children:(x=a.lightrag)!=null&&x.running?"running":"stopped"}),e.jsx("div",{className:"memory-status-card-sub muted",children:a.lightrag?`${a.lightrag.indexedApprox} chunks`:"—"})]}),e.jsxs("div",{className:"memory-status-card-cell",children:[e.jsxs("div",{className:"memory-status-card-label",children:[e.jsx(Te,{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}`:Ze(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 Ne({icon:s,title:t,message:a,action:i,className:n}){return e.jsxs("div",{className:Y("empty-state",n),children:[e.jsx("div",{className:"empty-icon",children:s??e.jsx(Ys,{size:32})}),e.jsx("div",{className:"empty-title",children:t}),a&&e.jsx("div",{className:"empty-message",children:a}),i&&e.jsx("div",{className:"empty-action",children:i})]})}function Si({snapshot:s,settings:t,setActiveTab:a,refreshSnapshot:i}){var G,ne,te;const n=re(),c=Ae(),o=r.useRef(null),[l,h]=r.useState(s.overview??null),[x,u]=r.useState(!s.overview),[d,m]=r.useState(s.projects||[]),[p,g]=r.useState(((G=s.activeProject)==null?void 0:G.id)||null),[f,y]=r.useState(s.mods||[]),[S,k]=r.useState(!1),[w,E]=r.useState(((ne=s.overview)==null?void 0:ne.recentActivity)??[]),[v,C]=r.useState(!1),[R,j]=r.useState(new Set);r.useEffect(()=>{let B=!1;return(async()=>{try{const V=await z.get("/activity/hidden");B||j(new Set(V.hidden||[]))}catch{}})(),()=>{B=!0}},[]);const P=(B,V)=>{const X=`${B.kind||""}|${B.ts||""}|${B.slug||B.title||""}|${V}`;let U=0;for(let J=0;J<X.length;J++)U=(U<<5)-U+X.charCodeAt(J)|0;return Math.abs(U).toString(16).padStart(8,"0").slice(0,16)},T=async B=>{const V=new Set(R);V.add(B),j(V);try{await z.post("/activity/hide",{keys:[B]})}catch(X){const U=new Set(R);j(U),n.error(`Hide failed: ${X.message}`)}},b=async()=>{if(!confirm("Hide every recent activity item from the overview? The full log stays in Settings → Activity Log."))return;const B=w.map((X,U)=>P(X,U)),V=new Set(R);B.forEach(X=>V.add(X)),j(V);try{await z.post("/activity/hide",{keys:B}),n.success(`Hidden ${B.length} item(s). Restore them in Settings → Activity Log.`)}catch(X){n.error(`Clear failed: ${X.message}`)}},A=async()=>{j(new Set);try{await z.del("/activity/hide"),n.success("All hidden activity restored to the overview.")}catch(B){n.error(`Restore failed: ${B.message}`)}};r.useEffect(()=>{var B;s.overview&&(h(s.overview),E(s.overview.recentActivity??[]),u(!1)),m(s.projects||[]),g(((B=s.activeProject)==null?void 0:B.id)||null),y(s.mods||[])},[s.overview,s.projects,s.activeProject,s.mods]),r.useEffect(()=>{let B;try{const V=z.getToken(),X=V?`/api/activity/stream?token=${encodeURIComponent(V)}`:"/api/activity/stream";B=new EventSource(X),B.addEventListener("snapshot",U=>{try{const J=JSON.parse(U.data);E(Array.isArray(J.events)?J.events.slice(0,50):[])}catch{}}),B.addEventListener("activity",U=>{try{const J=JSON.parse(U.data);E(he=>[J,...he].slice(0,50))}catch{}})}catch{}return()=>{try{B==null||B.close()}catch{}}},[]);const O=async()=>{n.info("Refreshing…",1500),await i();try{const B=await z.get("/projects");m(B.projects||[]),g(B.active||null)}catch{}},N=()=>{c.open({title:"Add project",children:e.jsx(Ci,{settings:t,onAdd:async(B,V)=>{try{const X=await z.post("/projects",{path:B,name:V});m(U=>[...U.filter(J=>J.id!==X.id),X]),n.success("Project added."),c.close()}catch(X){n.error(`Add failed: ${X.message}`)}}}),footer:e.jsx("div",{className:"modal-footer-actions",children:e.jsx($,{variant:"ghost",onClick:()=>c.close(),children:"Cancel"})})})},F=async()=>{var B;try{const V=await z.post("/projects/auto-detect");m(V.projects||[]),g(V.active||null);const X=(B=V.projects)==null?void 0:B.find(U=>U.id===V.active);n.success(X?`Active: ${X.name}`:"Projects refreshed."),await i()}catch(V){n.error(`Auto-detect failed: ${V.message}`)}},K=async B=>{try{await z.post(`/projects/${encodeURIComponent(B)}/activate`),g(B),n.success("Project activated."),await i()}catch(V){n.error(`Activate failed: ${V.message}`)}},L=async B=>{if(confirm(`Remove project "${B}" from the registry?`))try{await z.del(`/projects/${encodeURIComponent(B)}`),m(V=>V.filter(X=>X.id!==B)),p===B&&g(null),n.success("Project removed.")}catch(V){n.error(`Remove failed: ${V.message}`)}};return x||!l?e.jsxs("div",{className:"view-loading",children:[e.jsx(me,{size:"lg"}),e.jsx("p",{children:"Loading overview…"})]}):e.jsxs("div",{className:"view view-overview",children:[e.jsxs("div",{className:"overview-hero-noframe",children:[e.jsx("h1",{children:"What do you want to do?"}),e.jsx("p",{className:"overview-hero-subtitle",children:"Describe what you want — Odin will split it into tasks, create a plan, delegate to background agents, and track progress in real time."}),e.jsxs("form",{className:"overview-hero-form-noframe",onSubmit:async B=>{var X,U;B.preventDefault();const V=(((X=o.current)==null?void 0:X.value)||"").trim();if(V){k(!0);try{const J=await z.post("/tasks/submit",{title:V});n.success(`Odin split it into ${((U=J.subtasks)==null?void 0:U.length)||1} task(s)`),o.current&&(o.current.value=""),await i()}catch(J){n.error(`Failed: ${J.message}`)}finally{k(!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:S,"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:S,children:[S?e.jsx(me,{size:"sm"}):e.jsx(rs,{size:16}),"Submit to Odin"]}),e.jsxs("span",{className:"muted",style:{fontSize:12},children:[e.jsx(Ve,{size:12,style:{display:"inline",verticalAlign:-2,color:"var(--accent)"}})," ","Odin + 12 specialist agents available"]})]})]}),e.jsx("div",{className:"overview-quick-actions-row",children:["Implement feature","Fix bug","Refactor","Investigate","Add tests","Document","Optimize","Deploy"].map(B=>e.jsx("button",{type:"button",className:"overview-quick-chip",onClick:()=>{o.current&&(o.current.value=B,o.current.focus())},children:B},B))})]}),e.jsxs("div",{className:"overview-feed",children:[e.jsxs("div",{className:"overview-feed-head",children:[e.jsx("h2",{children:"Recent activity"}),e.jsxs("div",{className:"overview-feed-head-actions",children:[R.size>0&&e.jsxs($,{variant:"ghost",size:"sm",onClick:A,title:"Restore hidden items to this overview",children:[e.jsx(Qe,{size:12})," Show ",R.size," hidden"]}),w.length>8&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>C(B=>!B),children:v?"Show less":"Show all"}),w.length>0&&e.jsxs($,{variant:"ghost",size:"sm",onClick:b,title:"Hide every item from the overview (full log kept)",children:[e.jsx(Xs,{size:12})," Hide all"]})]})]}),R.size>0&&e.jsxs("div",{className:"activity-hidden-banner",role:"status",children:[e.jsxs("span",{children:[e.jsx(Xs,{size:12,style:{verticalAlign:-2,marginRight:6}}),R.size," item",R.size===1?"":"s"," hidden from the overview."]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:A,children:[e.jsx(Qe,{size:12})," Show them again"]})]}),w.length===0?e.jsx("div",{className:"muted",style:{padding:"24px 0",fontSize:13},children:"No activity yet. Use the chat above or invoke a Bizar command to start a feed."}):e.jsxs("div",{className:Y("activity-feed-list-wrap",!v&&"activity-feed-list-wrap-collapsed"),"aria-live":"polite","aria-relevant":"additions",children:[e.jsx(Lt,{items:w.slice(0,30).filter((B,V)=>!R.has(P(B,V))),itemHeight:60,height:Math.min(w.filter((B,V)=>!R.has(P(B,V))).length*60,480),className:"activity-feed-list",renderItem:(B,V)=>{const X=w.slice(0,30).findIndex(U=>U===B);return e.jsx(Ei,{item:B,activityKey:P(B,X),onNavigate:a,onHide:T})}}),!v&&w.length>8&&e.jsx("div",{className:"activity-feed-fade","aria-hidden":"true"})]})]}),e.jsxs(ee,{className:"project-picker",children:[e.jsxs(ae,{children:[e.jsx(Fe,{size:14})," Projects",e.jsxs($,{variant:"ghost",size:"sm",style:{marginLeft:"auto"},onClick:N,children:[e.jsx(ze,{size:12})," Add"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:F,title:"Use the server's working directory",children:[e.jsx(ze,{size:12})," Auto-detect"]}),((te=t==null?void 0:t.dashboard)==null?void 0:te.projectsDirectory)&&e.jsxs($,{variant:"ghost",size:"sm",title:`Scan ${t.dashboard.projectsDirectory} for projects`,onClick:async()=>{try{const B=await z.post("/projects/scan");B.error?n.error(B.error):n.success(`Added ${B.added.length}, skipped ${B.skipped}.`),await i();const V=await z.get("/projects");m(V.projects||[]),g(V.active||null)}catch(B){n.error(`Scan failed: ${B.message}`)}},children:[e.jsx(an,{size:12})," Scan"]}),e.jsx($,{variant:"ghost",size:"sm",onClick:O,title:"Refresh",children:e.jsx(ce,{size:12})})]}),e.jsxs(ie,{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(Ne,{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:F,children:[e.jsx(ze,{size:14})," Use current directory"]}),e.jsx($,{variant:"secondary",onClick:N,children:"Add by path…"})]})}):e.jsx("div",{className:"project-grid",children:d.map(B=>e.jsx(zi,{project:B,active:p===B.id,onOpen:()=>K(B.id),onRemove:()=>L(B.id)},B.id))})]}),e.jsx(wi,{setActiveTab:a}),e.jsxs("div",{className:"overview-cols",children:[e.jsxs(ee,{children:[e.jsx(ae,{children:"Mods"}),e.jsxs(ie,{children:["Extensions installed under ",e.jsx("code",{children:"~/.config/bizar/mods/"})]}),f.length===0?e.jsx("div",{className:"muted",children:"No mods installed."}):e.jsx("ul",{className:"mod-mini-list",children:f.map(B=>e.jsxs("li",{className:"mod-mini",children:[e.jsx("span",{className:"mod-mini-name",children:B.name}),e.jsxs("span",{className:"mod-mini-meta",children:["v",B.version," · ",B.type]}),e.jsx("span",{className:`mod-mini-pill ${B.enabled?"mod-mini-pill-on":"mod-mini-pill-off"}`,children:B.enabled?"on":"off"})]},B.id))})]}),e.jsxs(ee,{children:[e.jsx(ae,{children:"Environment"}),e.jsx(ie,{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:Ze(l.generatedAt)})]})]})]})]})}function Ci({settings:s,onAdd:t}){var d,m;const[a,i]=r.useState(((d=s==null?void 0:s.dashboard)==null?void 0:d.projectsDirectory)??""),[n,c]=r.useState(""),[o,l]=r.useState(!1),[h,x]=r.useState(null),u=async()=>{var p;if(a){l(!0),x(null);try{await z.get("/fs?path="+encodeURIComponent(a)),t(a,n||null)}catch(g){const f=g;f.status===404?x("That folder no longer exists. Pick another."):x(((p=f.data)==null?void 0:p.message)??g.message??"Validation failed.")}finally{l(!1)}}};return e.jsxs("div",{children:[e.jsx("label",{className:"field-label",children:"Folder"}),e.jsx(za,{value:a,onChange:p=>{i(p),x(null)},projectsDirectory:(m=s==null?void 0:s.dashboard)==null?void 0:m.projectsDirectory,height:320}),h&&e.jsx("p",{className:"field-help",style:{color:"var(--error)",marginTop:4},children:h}),e.jsxs("div",{style:{marginTop:"var(--space-3)"},children:[e.jsx("label",{className:"field-label",htmlFor:"add-project-name",children:"Name (optional)"}),e.jsx("input",{id:"add-project-name",className:"input",type:"text",placeholder:"My App",value:n,onChange:p=>c(p.target.value)}),e.jsx("p",{className:"field-help",style:{marginTop:4},children:"Display name for this project. Defaults to the folder name."})]}),e.jsx("div",{style:{marginTop:"var(--space-3)",display:"flex",justifyContent:"flex-end"},children:e.jsxs($,{variant:"primary",onClick:u,disabled:!a||o,children:[o?e.jsx("span",{className:"btn-spinner"}):null,o?"Checking…":"Add"]})})]})}function zi({project:s,active:t,onOpen:a,onRemove:i}){const n={active:"status-on",inactive:"status-neutral",error:"status-error"}[s.status]||"status-neutral";return e.jsxs("div",{className:`project-card ${t?"project-card-active":""}`,children:[e.jsxs("div",{className:"project-card-head",children:[e.jsx("span",{className:`project-card-status ${n}`,children:s.status}),e.jsx("div",{className:"project-card-name",children:s.name}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Remove project",title:"Remove",onClick:c=>{c.stopPropagation(),i()},children:e.jsx(we,{size:12})})]}),e.jsx("div",{className:"project-card-path mono ellipsis",title:s.path,children:s.path}),e.jsx("div",{className:"project-card-meta",children:s.lastAccessed&&e.jsxs("span",{className:"muted",children:["Last opened ",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($t,{size:12})," Active"]}):e.jsx(e.Fragment,{children:"Open"})})})]})}function Ti(s){return s&&s.charAt(0).toUpperCase()+s.slice(1)}function Ri(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]||Ti(a.replace(/-/g," ")),l=c[i]||i.replace(/-/g," ");return`${o} ${l}`.trim()}function Os(s,t){for(const a of t){const i=s[a];if(typeof i=="string"&&i.trim())return i.trim()}return""}function $i(s){const t=Os(s,["message","text","prompt","title","name"]);if(t)return t;const a=[],i=Os(s,["slug"]),n=Os(s,["agent","author"]),c=Os(s,["status"]);return i&&a.push(`Plan ${i}`),n&&a.push(n),c&&a.push(c),a.length?a.join(" · "):"No additional details."}function Ai(s){return Ce(s)}function Mi(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 Ii(s){const t=s.toLowerCase();return t==="task"?Rs:t==="agent"?Xe:t==="plan"?Ks:t.includes("bg")||t.includes("background")||t.includes("job")?tt:t==="mod"?Gs:t==="skill"?Ve:t.includes("error")||t.includes("failure")?xs:t.includes("warn")?be:$e}function Li(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 Ei({item:s,activityKey:t,onNavigate:a,onHide:i}){const n=Mi(s),c=Ii(s.kind||""),o=Ri(s.kind||"activity"),l=$i(s),h=Li(s.kind||""),x=n==="error"?"var(--error)":n==="warning"?"var(--warning)":n==="success"?"var(--success)":"var(--accent)";return e.jsxs("div",{className:Y("activity-feed-row",`activity-feed-row-${n}`),children:[e.jsxs("button",{type:"button",className:"activity-feed-row-main",onClick:()=>{h&&a(h)},title:h?`Open ${h}`:o,children:[e.jsx("div",{className:"activity-feed-icon",style:{color:x},children:e.jsx(c,{size:14})}),e.jsxs("div",{className:"activity-feed-body",children:[e.jsxs("div",{className:"activity-feed-title-row",children:[e.jsx("div",{className:"activity-feed-title",children:o}),e.jsx("div",{className:"activity-feed-time text-xs muted tabular-nums",children:Ai(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(ke,{size:12})})]})}const Di=We.memo(Si);function Pi({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 Fi({session:s,mode:t,anchor:a,renameDraft:i,setRenameDraft:n,onEdit:c,onDeleteRequest:o,onConfirmDelete:l,onConfirmRename:h,onClose:x}){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=S=>{const k=S.target;!u.current||!k||u.current.contains(k)||x()},f=S=>{S.key==="Escape"&&x()},y=window.setTimeout(()=>{document.addEventListener("mousedown",g),document.addEventListener("keydown",f)},0);return()=>{window.clearTimeout(y),document.removeEventListener("mousedown",g),document.removeEventListener("keydown",f)}},[x]),r.useEffect(()=>{if(t!=="rename")return;const g=window.setTimeout(()=>{var y;const f=(y=u.current)==null?void 0:y.querySelector("input.session-row-menu-input");f==null||f.focus(),f==null||f.select()},0);return()=>window.clearTimeout(g)},[t]);const p=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(we,{size:13,"aria-hidden":!0}),e.jsx("span",{children:"Delete"}),e.jsx("kbd",{children:"⌫"})]})]}),t==="rename"&&e.jsxs("div",{className:"session-row-menu-inline",children:[e.jsx("div",{className:"session-row-menu-inline-label chat-mono",children:"Rename session"}),e.jsx("input",{type:"text",className:"session-row-menu-input",value:i,onChange:g=>n(g.target.value),onKeyDown:g=>{g.key==="Enter"?(g.preventDefault(),h()):g.key==="Escape"&&(g.preventDefault(),x())},onClick:g=>g.stopPropagation(),"aria-label":"New session name"}),e.jsxs("div",{className:"session-row-menu-inline-actions",children:[e.jsx("button",{type:"button",className:"btn btn-ghost",onClick:g=>{g.stopPropagation(),x()},children:"Cancel"}),e.jsx("button",{type:"button",className:"btn btn-primary",onClick:g=>{g.stopPropagation(),h()},children:"Save"})]})]}),t==="confirm-delete"&&e.jsxs("div",{className:"session-row-menu-inline",children:[e.jsx("div",{className:"session-row-menu-inline-label chat-mono",children:"Delete this session?"}),e.jsxs("div",{className:"session-row-menu-inline-message",children:['"',s.title,'" and its sub-agents will be removed.']}),e.jsxs("div",{className:"session-row-menu-inline-actions",children:[e.jsx("button",{type:"button",className:"btn btn-ghost",onClick:g=>{g.stopPropagation(),x()},children:"Cancel"}),e.jsx("button",{type:"button",className:"btn btn-danger",onClick:g=>{g.stopPropagation(),l()},children:"Delete"})]})]})]});return ia.createPortal(p,document.body)}function Nt({node:s,depth:t=0,collapsible:a=!1,isLast:i=!0,open:n,onToggle:c}){var p;const[o,l]=r.useState(a),h=n!==void 0,x=h?n:o,u=g=>{h||l(g),c==null||c(g)},d=(((p=s.children)==null?void 0:p.length)??0)>0,m=e.jsxs(e.Fragment,{children:[a&&e.jsx("span",{className:`agent-node-chevron ${x?"open":""}`,"aria-hidden":!0,children:"›"}),e.jsx("span",{className:`agent-node-dot status-${s.status}`,"aria-hidden":!0}),e.jsx("span",{className:"agent-node-name",children:s.name}),s.role&&e.jsx("span",{className:"agent-node-role chat-mono",children:s.role}),e.jsx("span",{className:`agent-node-pill status-${s.status}`,children:s.status})]});return e.jsxs("div",{className:["agent-node",`depth-${t}`,`status-${s.status}`,x?"open":"closed",i?"last":""].filter(Boolean).join(" "),children:[a?e.jsx("button",{type:"button",className:`agent-node-head status-${s.status} collapsible`,onClick:g=>{g.stopPropagation(),u(!x)},"aria-expanded":x,children:m}):e.jsx("div",{className:`agent-node-head status-${s.status}`,children:m}),x&&e.jsxs(e.Fragment,{children:[s.summary&&e.jsx("div",{className:"agent-node-summary",children:s.summary}),d&&e.jsx("div",{className:"agent-node-children",children:s.children.map((g,f)=>e.jsx(Nt,{node:g,depth:t+1,collapsible:!1,isLast:f===s.children.length-1},g.id))})]})]})}function Oi(s){return s.tree!==void 0}function Bi(s){const t=s.open??!0;if(Oi(s))return e.jsx("div",{className:`agent-tree variant-${s.variant??"full"}`,children:e.jsx(Nt,{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(Nt,{node:i,depth:0,collapsible:!1,open:t,isLast:n===a.length-1})},i.id))})})}function Ui({children:s,variant:t="rail",open:a=!0}){return a?e.jsx(Bi,{variant:t,open:a,children:s}):null}const _i=["Today","Yesterday","This week","Earlier"];function _t(s,t){return s.getFullYear()===t.getFullYear()&&s.getMonth()===t.getMonth()&&s.getDate()===t.getDate()}function Wi(s,t){const a=s.getTime()-t.getTime();return Math.floor(a/(1e3*60*60*24))}function Vi(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());_t(o,t)?n.Today.push(c):_t(o,a)?n.Yesterday.push(c):Wi(t,o)<7?n["This week"].push(c):n.Earlier.push(c)}return n}function Hi(s){return new Date(Number(s)||Date.now()).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1})}function qi({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 Ki({sessions:s,opencodeSessions:t=[],activeSessionId:a,activeOpencodeSessionId:i,activeProject:n,creating:c,onCreateSession:o,onSelectSession:l,onSelectOpencodeSession:h,onRenameSession:x,onDeleteSession:u,groupBy:d}){var L;const m=r.useMemo(()=>[...s,...t],[s,t]),p=r.useMemo(()=>[...m].sort((G,ne)=>Number(ne.mtime??0)-Number(G.mtime??0)),[m]),g=r.useMemo(()=>d?d(p):Vi(p),[d,p]),[f,y]=r.useState({}),S=G=>f[G]===!0,[k,w]=r.useState(null),[E,v]=r.useState("main"),[C,R]=r.useState(""),[j,P]=r.useState(null),T=r.useRef({}),b=(G,ne="main")=>{const te=T.current[G];if(!te)return;const B=ne==="main"?te:te.querySelector(".chat-rail-item-menu-trigger")??te;if(P({id:G,rect:B.getBoundingClientRect()}),w(G),v(ne),ne==="rename"){const V=[...s,...t].find(X=>X.id===G);R((V==null?void 0:V.title)??(V==null?void 0:V.id)??"")}},A=()=>{w(null),v("main"),R(""),P(null)},O=G=>{if(G.source==="opencode"){h(G);return}l(G.id)},N=()=>{if(!j)return;const G=j.id,ne=C.trim();if(!ne){A();return}x==null||x(G,ne),A()},F=()=>{j&&(u==null||u(j.id),A())},K=d?Object.entries(g):_i.filter(G=>{var ne;return(ne=g[G])==null?void 0:ne.length}).map(G=>[G,g[G]]);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"})]})}),p.length===0?e.jsx("div",{className:"chat-sessions-empty",children:e.jsx(Pi,{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:K.map(([G,ne])=>e.jsxs("div",{className:"chat-rail-group",children:[e.jsx("div",{className:"chat-rail-group-label",children:G}),ne.map(te=>{var he,ye;const B=te.source==="opencode",V=B?i===te.id:a===te.id,X=te.tree,U=!!((he=X==null?void 0:X.root)!=null&&he.children&&X.root.children.length>0),J=S(te.id);return e.jsxs(r.Fragment,{children:[e.jsxs("div",{ref:I=>{T.current[te.id]=I},role:"button",tabIndex:0,className:`chat-rail-item state-${te.state??"idle"}${V?" active":""}`,onClick:()=>O(te),onKeyDown:I=>{(I.key==="Enter"||I.key===" ")&&(I.preventDefault(),O(te))},"aria-current":V?"true":void 0,children:[e.jsx(qi,{state:te.state??"idle",agent:te.agent}),e.jsxs("div",{className:"chat-rail-item-title",children:[te.pinned&&e.jsx("span",{className:"chat-rail-pin","aria-hidden":!0,children:"★"}),B&&e.jsx(js,{size:11,style:{color:"var(--text-muted)",flexShrink:0},"aria-hidden":!0}),e.jsx("span",{className:"chat-ellipsis",children:te.title||te.id})]}),e.jsxs("div",{className:"chat-rail-item-meta",children:[e.jsx("span",{className:"chat-rail-item-meta-time",children:te.time??Hi(te.mtime)}),(te.unread??0)>0&&e.jsx("span",{className:"chat-rail-badge",children:te.unread})]}),e.jsx("button",{type:"button",className:`chat-rail-item-menu-trigger${k===te.id?" open":""}`,"aria-label":`Session options for ${te.title||te.id}`,"aria-haspopup":"menu","aria-expanded":k===te.id,onClick:I=>{I.stopPropagation(),k===te.id?A():b(te.id,"main")},children:e.jsxs("svg",{viewBox:"0 0 14 14","aria-hidden":!0,children:[e.jsx("circle",{cx:"3",cy:"7",r:"1.2",fill:"currentColor"}),e.jsx("circle",{cx:"7",cy:"7",r:"1.2",fill:"currentColor"}),e.jsx("circle",{cx:"11",cy:"7",r:"1.2",fill:"currentColor"})]})}),V&&U&&e.jsx("button",{type:"button",className:`chat-rail-tree-chevron${J?" open":""}`,"aria-label":J?"Collapse sub-agents":"Expand sub-agents","aria-expanded":J,onClick:I=>{I.stopPropagation(),y(H=>({...H,[te.id]:!H[te.id]}))},children:e.jsx("svg",{viewBox:"0 0 10 10","aria-hidden":!0,children:e.jsx("polyline",{points:"3,1.5 7,5 3,8.5"})})})]}),V&&U&&J&&((ye=X==null?void 0:X.root)==null?void 0:ye.children)&&e.jsx(Ui,{children:X.root.children,variant:"rail",open:!0})]},B?`oc-${te.id}`:te.id)})]},G))}),k&&j&&e.jsx(Fi,{session:{id:j.id,title:((L=[...s,...t].find(G=>G.id===j.id))==null?void 0:L.title)??j.id},mode:E,anchor:j,renameDraft:C,setRenameDraft:R,onEdit:()=>b(k,"rename"),onDeleteRequest:()=>b(k,"confirm-delete"),onConfirmDelete:F,onConfirmRename:N,onClose:A})]})}function Gi(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(Wn,{...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 ot(s){return s.toLocaleString()}function Yi(s){return!s||!s.includes("/")?"":s.split("/")[0]}function Xi(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 Qi({sessionId:s,messages:t,pinned:a,agent:i,model:n,agents:c,mcps:o,allCommands:l,activeSource:h="bizar",onRename:x,onDelete:u,onExport:d,busy:m,error:p,onRetry:g}){const[f,y]=r.useState(null);r.useEffect(()=>{let b=!1;return(async()=>{try{const A=await fetch("/api/usage?range=24h",{headers:{Accept:"application/json"}});if(!A.ok)return;const O=await A.json();b||y(O)}catch{}})(),()=>{b=!0}},[s]);const S=(t==null?void 0:t.length)??0,k=(a==null?void 0:a.size)??0,w=t.reduce((b,A)=>b+(A.content||A.message||"").length,0),E=Math.round(w/4),v=Xi(n),C=E/1e6*v,R=(f==null?void 0:f.totalTokens)??E,j=(f==null?void 0:f.costUsd)??C,P=128e3,T=Yi(n);return e.jsxs("aside",{className:"chat-info",children:[p&&e.jsxs("div",{className:"chat-info-section chat-info-error",role:"alert","aria-live":"polite",children:[e.jsxs("h4",{children:[e.jsx(be,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Couldn't load session"]}),e.jsx("p",{className:"chat-info-value chat-ellipsis",title:p.message,children:p.message}),e.jsxs("div",{className:"chat-info-mono",children:["code · ",p.code]}),p.suggestion?e.jsx("p",{className:"chat-info-suggestion",children:p.suggestion}):null,p.canRetry!==!1&&g?e.jsxs("button",{type:"button",className:"btn btn-ghost btn-sm chat-info-retry",onClick:g,title:"Retry loading the session",children:[e.jsx(at,{size:12,"aria-hidden":!0})," Retry"]}):null]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("div",{className:"chat-info-section-head",children:[e.jsxs("h4",{children:[e.jsx(et,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Session"]}),e.jsx("span",{className:`chat-source-badge chat-source-${h??"none"}`,style:{marginLeft:"auto"},children:h==="opencode"?"opencode":"bizar chat"})]}),e.jsx("div",{className:"chat-info-mono chat-ellipsis",title:s,children:s||"Live"}),e.jsxs("div",{className:"chat-info-mono",children:[ot(S)," message",S===1?"":"s",k>0&&` · ${k} pinned`]})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("h4",{children:[e.jsx(Xe,{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(gs,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Model"]}),e.jsx("div",{className:"chat-mono chat-ellipsis",title:n,children:n||"—"}),T&&e.jsxs("div",{className:"chat-info-mono",children:["provider · ",T]})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsx("h4",{children:"Tokens"}),e.jsxs("div",{className:"chat-mono",children:[ot(R)," / ",ot(P)]}),e.jsx("div",{className:"chat-info-bar","aria-hidden":!0,children:e.jsx("div",{className:"chat-info-bar-fill",style:{width:`${Math.min(100,R/Math.max(1,P)*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:["$",j.toFixed(4)]}),!f&&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(Xe,{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(b=>e.jsx("span",{className:"chat-info-agent",children:b.name},b.name))}):e.jsx("div",{className:"chat-info-mono",children:"None attached"})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("h4",{children:[e.jsx(gs,{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(b=>e.jsx("span",{className:"chat-info-agent",children:b.id},b.id))}):e.jsx("div",{className:"chat-info-mono",children:"No MCPs configured"})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("h4",{children:[e.jsx(ps,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Slash commands"]}),e.jsxs("div",{className:"chat-info-mono",children:[(l==null?void 0:l.length)??0," available"]})]}),(x||u||d)&&e.jsxs("div",{className:"chat-info-section",children:[e.jsx("h4",{children:"Actions"}),e.jsxs("div",{className:"chat-info-actions",children:[x&&e.jsxs("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:x,disabled:m==null?void 0:m.rename,title:"Rename session",children:[e.jsx(fs,{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(qe,{size:12,"aria-hidden":!0})," Export"]}),u&&e.jsxs("button",{type:"button",className:"btn btn-ghost btn-sm btn-danger",onClick:u,disabled:m==null?void 0:m.delete,title:"Delete session",children:[e.jsx(we,{size:12,"aria-hidden":!0})," Delete"]})]})]})]})}function Ji({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(da,{size:14,"aria-hidden":!0}),e.jsx("span",{children:"Jump to latest"}),t>0&&e.jsxs("span",{className:"jump-badge",children:[t," new"]})]})})}function Zi({snapshot:s,settings:t,setActiveTab:a,initialTaskId:i,onClearTaskId:n}){const c=re(),o=Ae(),l=Vn(s,t,i??"");r.useEffect(()=>{l.setToast({error:L=>c.error(L),success:L=>c.success(L),info:L=>c.info(L),warning:L=>c.warning(L)})},[l,c]);const[h,x]=r.useState(""),[u,d]=r.useState(t.defaultAgent||"odin"),[m,p]=r.useState(t.defaultModel||""),[g,f]=r.useState([]),y=r.useRef(null),{allCommands:S,suggestions:k,setQuery:w}=Hn(s);r.useEffect(()=>{w(h)},[h,w]);const E=()=>{var L;return(L=y.current)==null?void 0:L.click()},v=L=>{const G=L.target.files;if(!G)return;const ne=[];for(let te=0;te<G.length;te++)ne.push(G[te].name);f(te=>{const B=ne.filter(V=>!te.includes(V));return[...te,...B]}),y.current&&(y.current.value="")},C=async()=>{const L=h.trim();if(!L)return;x(""),w(""),(await l.onSend(L,u,m,g)).ok&&l.jumpToLatest()},R=async()=>{l.busy.create||await l.onCreateSession()},j=L=>{o.open({title:"Delete message?",children:e.jsx("p",{style:{margin:0},children:"This action cannot be undone."}),footer:e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx($,{variant:"secondary",size:"sm",onClick:()=>o.close(),children:"Cancel"}),e.jsx($,{variant:"danger",size:"sm",onClick:()=>{o.close(),l.deleteMessage(L)},children:"Delete"})]})})},P=(L,G)=>{let ne="";o.open({title:"Rename session",children:e.jsx("input",{id:"rename-session-input",autoFocus:!0,defaultValue:G,"aria-label":"Session title",onChange:te=>{ne=te.target.value},onKeyDown:te=>{te.key==="Enter"&&(te.preventDefault(),o.close(),l.renameSession(L,ne).then(B=>{B&&c.success("Renamed.")}))},style:{width:"100%",padding:"8px 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-sm)",color:"var(--text)",font:"13px/1.4 var(--font-sans)",marginTop:6}}),footer:e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx($,{variant:"secondary",size:"sm",onClick:()=>o.close(),children:"Cancel"}),e.jsx($,{variant:"primary",size:"sm",onClick:()=>{o.close(),l.renameSession(L,ne)},children:"Save"})]})})},T=(L,G)=>{o.open({title:"Delete session?",children:e.jsxs("p",{style:{margin:0},children:["Delete ",e.jsx("strong",{children:G}),"? 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(L)},children:"Delete"})]})})},b=()=>{const L=l.activeSource==="opencode"?l.activeOpencodeSessionId:l.sessionId;if(!L)return;const ne=(l.activeSource==="opencode"?l.opencodeMessages:l.bizarMessages).map(X=>{const U=X.ts??"",J=(X.role||"unknown").toUpperCase(),he=X.content||X.message||"";return`[${U}] ${J}: ${he}`}).join(`
2
-
3
- `),te=new Blob([ne],{type:"text/plain;charset=utf-8"}),B=URL.createObjectURL(te),V=document.createElement("a");V.href=B,V.download=`${L}.txt`,document.body.appendChild(V),V.click(),document.body.removeChild(V),URL.revokeObjectURL(B)},A=r.useMemo(()=>l.sessions.map(L=>l.getSessionDisplay(L)),[l.sessions,l.getSessionDisplay]),O=r.useMemo(()=>l.opencodeSessions.map(L=>l.getSessionDisplay(L)),[l.opencodeSessions,l.getSessionDisplay]),N=r.useMemo(()=>{const L=l.activeSource==="opencode"?l.activeOpencodeSessionId??"":l.sessionId;return L?A.find(G=>G.id===L)??O.find(G=>G.id===L)??null:null},[l.activeSource,l.activeOpencodeSessionId,l.sessionId,A,O]),F=(()=>{var ne;const L=`${u||"Odin"} · ${((ne=s.activeProject)==null?void 0:ne.name)??"no project"}`,G=(N==null?void 0:N.state)??"idle";return G==="streaming"?`Replying · ${L}`:G==="awaiting"?`Your turn · ${L}`:`${L} · idle`})(),K=l.activeSource==="opencode"?"opencode":"bizar chat";return e.jsxs("div",{className:"chat-shell",children:[e.jsx(qn,{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(Ki,{sessions:A,opencodeSessions:O,activeSessionId:l.sessionId,activeOpencodeSessionId:l.activeOpencodeSessionId,activeProject:s.activeProject,creating:l.busy.create,onCreateSession:R,onSelectSession:l.selectBizarSession,onSelectOpencodeSession:L=>l.loadOpencodeSession(L.id),onRenameSession:P,onDeleteSession:L=>{const G=l.sessions.find(ne=>ne.id===L)??l.opencodeSessions.find(ne=>ne.id===L);T(L,(G==null?void 0:G.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:(N==null?void 0:N.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:K})]}),e.jsxs("div",{className:`chat-thread-sub chat-muted state-${(N==null?void 0:N.state)??"idle"}`,children:[e.jsx("span",{className:"chat-thread-dot"}),F]}),l.opencodeError&&e.jsxs("div",{className:"chat-thread-error",role:"alert",children:[e.jsx("p",{className:"chat-error-message",children:l.opencodeError}),l.opencodeSuggestion&&e.jsx("p",{className:"chat-error-suggestion",children:l.opencodeSuggestion}),l.activeOpencodeSessionId&&e.jsx("button",{className:"btn btn-sm",type:"button",onClick:()=>l.loadOpencodeSession(l.activeOpencodeSessionId),children:"Retry"})]})]}),e.jsxs("div",{className:"chat-thread-actions",children:[N&&e.jsxs("button",{className:"btn btn-ghost",title:"Rename session",type:"button",disabled:l.busy.rename,onClick:()=>P(N.id,N.title??""),children:[e.jsx(fs,{size:12,"aria-hidden":!0})," ",e.jsx("span",{className:"mono",children:"rename"})]}),N&&e.jsxs("button",{className:"btn btn-ghost btn-danger",title:"Delete session",type:"button",disabled:l.busy.delete,onClick:()=>T(N.id,N.title??N.id),children:[e.jsx(we,{size:12,"aria-hidden":!0})," ",e.jsx("span",{className:"mono",children:"delete"})]}),e.jsx("button",{className:"btn btn-ghost",title:"Export transcript",type:"button",onClick:b,children:e.jsx("span",{className:"mono",children:"export"})})]})]}),e.jsx("div",{className:"chat-thread-scroll",ref:l.listRef,onScroll:l.handleScroll,role:"log","aria-live":"polite","aria-relevant":"additions","aria-label":"Chat message thread",children:e.jsx(Kn,{messages:l.activeSource==="opencode"?l.opencodeMessages:l.bizarMessages,loading:l.loading,activeProject:s.activeProject,sessionId:l.activeSource==="opencode"?l.activeOpencodeSessionId??l.sessionId:l.sessionId,pinned:l.pinned,activeSource:l.activeSource,onPickSuggestion:L=>x(L),onCopy:L=>l.copyMessage(L),onDelete:j,onTogglePin:l.togglePin,onRegenerate:l.onRegenerate})}),!l.stickToBottom&&e.jsx(Ji,{streaming:(N==null?void 0:N.state)==="streaming",newMessageCount:l.newMessageCount,onClick:l.jumpToLatest}),e.jsx(Gi,{agent:u,setAgent:d,model:m,setModel:p,text:h,setText:x,sending:l.sending,activeSource:l.activeSource,onSend:C,attachments:g,setAttachments:f,suggestions:k,onPickSuggestion:L=>x(`${L.split(" ")[0]} `),agents:s.agents||[],onAttach:E}),e.jsx("input",{ref:y,type:"file",multiple:!0,style:{display:"none"},onChange:v,"aria-label":"Attach files to message",tabIndex:-1})]}),e.jsx(Qi,{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:S,activeSource:l.activeSource,onRename:()=>{N&&P(N.id,N.title??"")},onDelete:()=>{N&&T(N.id,N.title??N.id)},onExport:b,busy:l.busy})]})]})}function er(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=er(s);return e.jsxs("span",{className:Y("badge",`badge-${n}`,a),title:`status: ${s}`,children:[i&&e.jsx("span",{className:"badge-dot"}),t]})}const Wt=["bash","read","edit","write","webfetch","websearch","task","glob","grep"],Vt=["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"],Vs=[{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 sr(s){var t;return((t=Vs.find(a=>a.id===s))==null?void 0:t.color)||"var(--text-dim)"}function tr({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 ar({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 nr({snapshot:s,refreshSnapshot:t}){const a=re(),i=Ae(),[n,c]=r.useState(s.agents||[]),[o,l]=r.useState(!s.agents),[h,x]=r.useState(""),[u,d]=r.useState("");r.useEffect(()=>{c(s.agents||[]),l(!s.agents)},[s.agents]);const m=async()=>{try{const v=await z.get("/agents");c(v.agents||[])}catch(v){a.error(`Agents load failed: ${v.message}`)}finally{l(!1)}},p=r.useMemo(()=>{let v=[...n];if(h&&(v=v.filter(C=>h==="__none__"?!C.category:(C.category||"")===h)),u){const C=u.toLowerCase();v=v.filter(R=>R.name.toLowerCase().includes(C)||(R.description||"").toLowerCase().includes(C)||(R.tags||[]).some(j=>j.toLowerCase().includes(C)))}return v.sort((C,R)=>C.name.localeCompare(R.name))},[n,h,u]),g=r.useMemo(()=>{const v=new Set;for(const C of n)for(const R of C.tags||[])v.add(R);return Array.from(v).sort()},[n]),f=()=>{let v=null,C=null,R=null,j=null,P=null,T=null,b=null,A=null,O=null;i.open({title:"New agent",width:640,children:e.jsxs("div",{className:"agent-form",children:[e.jsx("label",{className:"field-label",htmlFor:"agent-new-name",children:"Name (a-z, 0-9, dashes)"}),e.jsx("input",{id:"agent-new-name",ref:N=>v=N,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:N=>{C=N},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:N=>R=N,className:"select",defaultValue:"",children:[e.jsx("option",{value:"",children:"(provider default)"}),Vt.map(N=>e.jsx("option",{value:N,children:N},N))]})]}),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:N=>j=N,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:N=>P=N,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:N=>O=N,className:"select",defaultValue:"",children:[e.jsx("option",{value:"",children:"(none)"}),Vs.map(N=>e.jsx("option",{value:N.id,children:N.label},N.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:N=>A=N,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:N=>b=N,className:"agent-tools",children:Wt.map(N=>e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{type:"checkbox",value:N,"aria-label":N}),e.jsx("span",{children:N})]},N))})]}),e.jsx("label",{className:"field-label",htmlFor:"agent-new-prompt",children:"System prompt"}),e.jsx("textarea",{id:"agent-new-prompt",ref:N=>T=N,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 N=((v==null?void 0:v.value)||"").trim();if(!/^[a-z0-9][a-z0-9-]{0,63}$/i.test(N)){a.warning("Invalid name (a-z, 0-9, dashes).");return}const F=[];b&&b.querySelectorAll('input[type="checkbox"]:checked').forEach(L=>{F.push(L.value)});const K=((A==null?void 0:A.value)||"").split(",").map(L=>L.trim()).filter(Boolean);try{const L=await z.post("/agents",{name:N,description:((C==null?void 0:C.value)||"").trim(),model:(R==null?void 0:R.value)||"",mode:(j==null?void 0:j.value)||"subagent",color:(P==null?void 0:P.value)||"",tools:F,tags:K,category:(O==null?void 0:O.value)||"",prompt:(T==null?void 0:T.value)||""});c(G=>[...G,L]),a.success("Agent created."),i.close(),await t()}catch(L){a.error(`Create failed: ${L.message}`)}},children:[e.jsx(Ms,{size:12})," Create"]})]})})},y=async v=>{let C=null,R=null,j=null,P=null,T=null,b=null,A=null,O=null;try{const N=await z.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:N.path})]}),e.jsx("label",{className:"field-label",htmlFor:"agent-edit-desc",children:"Description"}),e.jsx("input",{id:"agent-edit-desc",ref:F=>{C=F},className:"input",type:"text",defaultValue:N.description}),e.jsxs("div",{className:"task-form-row",children:[e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"agent-edit-model",children:"Model"}),e.jsxs("select",{id:"agent-edit-model",ref:F=>R=F,className:"select",defaultValue:N.model,children:[e.jsx("option",{value:"",children:"(provider default)"}),Vt.map(F=>e.jsx("option",{value:F,children:F},F))]})]}),e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"agent-edit-mode",children:"Mode"}),e.jsxs("select",{id:"agent-edit-mode",ref:F=>j=F,className:"select",defaultValue:N.mode||"subagent",children:[e.jsx("option",{value:"primary",children:"primary"}),e.jsx("option",{value:"subagent",children:"subagent"}),e.jsx("option",{value:"all",children:"all"})]})]}),e.jsxs("div",{className:"task-form-field",style:{flex:"0 0 80px"},children:[e.jsx("label",{className:"field-label",htmlFor:"agent-edit-color",children:"Color"}),e.jsx("input",{id:"agent-edit-color",ref:F=>P=F,className:"input",type:"color",defaultValue:N.color||"#8b5cf6"})]})]}),e.jsxs("div",{className:"task-form-row",children:[e.jsxs("div",{className:"task-form-field",style:{flex:1},children:[e.jsx("label",{className:"field-label",htmlFor:"agent-edit-category",children:"Category"}),e.jsxs("select",{id:"agent-edit-category",ref:F=>O=F,className:"select",defaultValue:N.category||"",children:[e.jsx("option",{value:"",children:"(none)"}),Vs.map(F=>e.jsx("option",{value:F.id,children:F.label},F.id))]})]}),e.jsxs("div",{className:"task-form-field",style:{flex:2},children:[e.jsx("label",{className:"field-label",htmlFor:"agent-edit-tags",children:"Tags (comma-separated)"}),e.jsx("input",{id:"agent-edit-tags",ref:F=>A=F,className:"input",type:"text",defaultValue:(N.tags||[]).join(", ")})]})]}),e.jsxs("fieldset",{children:[e.jsx("legend",{className:"field-label",style:{padding:0},children:"Tools"}),e.jsx("div",{ref:F=>b=F,className:"agent-tools",children:Wt.map(F=>{var K;return e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{type:"checkbox",value:F,"aria-label":F,defaultChecked:(K=N.tools)==null?void 0:K.includes(F)}),e.jsx("span",{children:F})]},F)})})]}),e.jsx("label",{className:"field-label",htmlFor:"agent-edit-prompt",children:"System prompt"}),e.jsx("textarea",{id:"agent-edit-prompt",ref:F=>T=F,className:"textarea",rows:8,defaultValue:N.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 F=[];b&&b.querySelectorAll('input[type="checkbox"]:checked').forEach(L=>{F.push(L.value)});const K=((A==null?void 0:A.value)||"").split(",").map(L=>L.trim()).filter(Boolean);try{const L=await z.put(`/agents/${encodeURIComponent(v.name)}`,{description:((C==null?void 0:C.value)||"").trim(),model:(R==null?void 0:R.value)||"",mode:(j==null?void 0:j.value)||"subagent",color:(P==null?void 0:P.value)||"",tools:F,tags:K,category:(O==null?void 0:O.value)||"",prompt:(T==null?void 0:T.value)||""});c(G=>G.map(ne=>ne.name===v.name?L:ne)),a.success("Agent saved."),i.close(),await t()}catch(L){a.error(`Save failed: ${L.message}`)}},children:[e.jsx(Ms,{size:12})," Save"]})]})})}catch(N){a.error(`Load failed: ${N.message}`)}},S=async v=>{if(confirm(`Delete agent "${v.name}"? This removes ${v.path}.`))try{await z.del(`/agents/${encodeURIComponent(v.name)}`),c(C=>C.filter(R=>R.name!==v.name)),a.success("Agent deleted.")}catch(C){a.error(`Delete failed: ${C.message}`)}},k=async v=>{let C=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:R=>C=R,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 R=((C==null?void 0:C.value)||"").trim();if(!R){a.warning("Prompt is required.");return}try{await z.post(`/agents/${encodeURIComponent(v.name)}/invoke`,{prompt:R}),a.success(`Invoked ${v.name}.`),i.close()}catch(j){a.error(`Invoke failed: ${j.message}`)}},children:[e.jsx(vs,{size:14})," Invoke"]})]})})},w=async v=>{try{const C=await z.post(`/agents/${encodeURIComponent(v.name)}/restart`);c(R=>R.map(j=>j.name===v.name?C:j)),a.success(`${v.name} restarted.`)}catch(C){a.error(`Restart failed: ${C.message}`)}},E=async(v,C)=>{try{const R=await z.post(`/agents/${encodeURIComponent(v.name)}/status`,{status:C});c(j=>j.map(P=>P.name===v.name?R:P))}catch(R){a.error(`Status update failed: ${R.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(Xe,{size:18})," Agents (",p.length,")"]}),e.jsxs("p",{className:"view-subtitle",children:["The Norse pantheon — click ",e.jsx("kbd",{children:"Edit"})," to modify or ",e.jsx("kbd",{children:"Invoke"})," to dispatch."]})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs("div",{className:"search-input",children:[e.jsx("label",{htmlFor:"agents-search",className:"sr-only",children:"Search agents"}),e.jsx("input",{id:"agents-search",className:"input",type:"text",placeholder:"Search…",value: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:h,onChange:v=>x(v.target.value),children:[e.jsx("option",{value:"",children:"All categories"}),Vs.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(ce,{size:14})," Refresh"]}),e.jsxs($,{variant:"primary",size:"sm",onClick:f,children:[e.jsx(ze,{size:14})," New agent"]})]})]}),g.length>0&&e.jsxs("div",{className:"agent-tags-row",children:[e.jsx(ma,{size:12}),g.map(v=>e.jsx("span",{className:"tag",children:v},v))]}),o?e.jsx("div",{className:"view-loading",children:e.jsx(me,{size:"lg"})}):p.length===0?e.jsx(Ne,{icon:e.jsx(Xe,{size:32}),title:"No agents found",message:"Run bizar in the terminal to install Bizar."}):e.jsx("div",{className:"agent-grid",children:p.map(v=>e.jsx(ir,{agent:v,onInvoke:()=>k(v),onEdit:()=>y(v),onDelete:()=>S(v),onRestart:()=>w(v),onSetStatus:C=>E(v,C)},v.name))})]})}function ir({agent:s,onInvoke:t,onEdit:a,onDelete:i,onRestart:n,onSetStatus:c}){const[o,l]=r.useState(!1),h=sr(s.category),x=(s.status==="working"||!!s.currentTaskId)&&!s.isStuck;return e.jsxs(ee,{variant:"elevated",interactive:!0,className:Y("agent-card",x&&"is-working",s.isStuck&&"is-stuck"),children:[e.jsxs("div",{className:"agent-card-head",children:[e.jsxs("div",{className:"agent-card-name",children:[e.jsx(tr,{status:s.status,isStuck:s.isStuck}),s.name]}),e.jsxs("div",{className:"agent-card-badges",children:[s.category&&e.jsx("span",{className:"agent-card-category",style:{background:`color-mix(in srgb, ${h} 18%, transparent)`,color:h},children:s.category}),e.jsx(ar,{agent:s})]})]}),e.jsx("p",{className:"agent-card-desc",children:aa(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))}),(x||s.lastTask)&&e.jsxs("div",{className:"agent-card-activity",children:[s.currentTaskId&&e.jsxs("div",{className:"agent-card-row",children:[e.jsx($e,{size:12}),e.jsx("span",{className:"muted",children:"Working on"}),e.jsx("code",{className:"mono",children:s.currentTaskId})]}),s.lastTask&&!s.currentTaskId&&e.jsxs("div",{className:"agent-card-row",children:[e.jsx(_e,{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(be,{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(vs,{size:12})," Invoke"]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:a,children:[e.jsx(fs,{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(at,{size:12})," Restart"]}),e.jsx($,{variant:"ghost",size:"sm",onClick:i,children:e.jsx(we,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":o?"Collapse":"Expand",onClick:()=>l(u=>!u),style:{marginLeft:"auto"},children:o?e.jsx(Oe,{size:12}):e.jsx(Ke,{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 rr({id:s,children:t}){return e.jsx("div",{id:s,"data-block-id":s,className:Y("glyph-richtext"),style:Ra,children:e.jsx(wa,{remarkPlugins:[Sa],children:t})})}const lr={info:{bg:"var(--info-soft, rgba(96, 165, 250, 0.12))",border:"var(--info)",fg:"var(--info)",icon:st,label:"Note"},warn:{bg:"var(--warning-soft, rgba(251, 191, 36, 0.15))",border:"var(--warning)",fg:"var(--warning)",icon:be,label:"Warning"},success:{bg:"var(--success-soft, rgba(52, 211, 153, 0.15))",border:"var(--success)",fg:"var(--success)",icon:_e,label:"Success"},danger:{bg:"var(--error-soft, rgba(248, 113, 113, 0.12))",border:"var(--error)",fg:"var(--error)",icon:as,label:"Danger"}};function or({id:s,tone:t="info",children:a}){const i=lr[t],n=i.icon;return e.jsxs("div",{id:s,"data-block-id":s,className:Y("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:{...Ra,fontSize:14},children:e.jsx(wa,{remarkPlugins:[Sa],children:a})})]})]})}function cr({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(ns,{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 dr({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 mr({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 ur({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 hr({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:Ht,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:Ht}),c.kind==="multi"&&e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4},children:(c.options??[]).map(o=>{const l=a[c.id]??[],h=l.includes(o);return e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,fontSize:13,color:"var(--text)",cursor:"pointer"},children:[e.jsx("input",{type:"checkbox",checked:h,onChange:()=>{const x=h?l.filter(u=>u!==o):[...l,o];n(c.id,x)}}),e.jsx("span",{children:o})]},o)})})]},c.id))]})}const Ht={padding:"6px 10px",fontSize:13,borderRadius:6,border:"1px solid var(--border-strong)",background:"var(--bg)",color:"var(--text)",fontFamily:"inherit"},xr={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 pr({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=xr[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 gr({id:s,filename:t,language:a,mode:i="unified",before:n,after:c}){const o=n.split(`
4
- `),l=c.split(`
5
- `),h=e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"6px 12px",background:"var(--bg)",borderBottom:"1px solid var(--border)",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:[e.jsx(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})]}),x={margin:0,padding:0,fontFamily:"var(--font-mono)",fontSize:12.5,lineHeight:1.55,color:"var(--text)",background:"var(--bg-elev)"},u=(d,m,p)=>{const g={del:"var(--error-soft)",add:"var(--success-soft)",ctx:"transparent"},f={del:"var(--error)",add:"var(--success)",ctx:"var(--text-dim)"};return e.jsxs("div",{style:{display:"flex",padding:"0 12px",background:g[p]},children:[e.jsx("span",{style:{width:18,color:f[p],userSelect:"none",flexShrink:0},children:d}),e.jsx("span",{style:{whiteSpace:"pre",flex:1,overflowX:"auto"},children:m||" "})]})};return e.jsxs("div",{id:s,"data-block-id":s,className:"glyph-diff",style:{margin:"12px 0",border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:"var(--bg-elev)"},children:[h,i==="unified"?e.jsxs("pre",{style:x,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:{...x,borderRight:"1px solid var(--border)"},children:o.map((d,m)=>e.jsx("div",{children:u("-",d,"del")},m))}),e.jsx("pre",{style:x,children:l.map((d,m)=>e.jsx("div",{children:u("+",d,"add")},m))})]})]})}const jr={up:{fg:"var(--success)",Icon:Oe,label:"trending up"},down:{fg:"var(--error)",Icon:Oe,label:"trending down"},flat:{fg:"var(--text-dim)",Icon:dn,label:"flat"}};function fr({id:s,label:t,value:a,trend:i,hint:n}){const c=i?jr[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===Oe&&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 vr={task:{stroke:"var(--info)",fill:"var(--bg-elev)",fg:"var(--text)"},decision:{stroke:"var(--warning)",fill:"var(--bg-elev)",fg:"var(--text)"},note:{stroke:"var(--border-strong)",fill:"var(--bg)",fg:"var(--text-dim)"}},Me=160,De=56,cs=60,ds=80;function yr({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(br,{id:s})});const i=new Map(t.map(u=>[u.id,u])),n=kr(t),c=Math.max(...n.map(u=>u.col))+1,o=Math.max(...n.map(u=>u.row))+1,l=c*(Me+cs)+cs,h=o*(De+ds)+ds;function x(u){if(!i.get(u))return null;const m=n.find(p=>p.id===u);return m?{x:cs+m.col*(Me+cs)+Me/2,y:ds+m.row*(De+ds)+De/2}:null}return e.jsx("div",{id:s,"data-block-id":s,className:"glyph-workflow",style:{margin:"12px 0",padding:12,border:"1px solid var(--border)",borderRadius:10,background:"var(--bg-elev)",overflow:"auto"},children:e.jsxs("svg",{role:"img","aria-label":"Workflow diagram",width:l,height:h,style:{display:"block",maxWidth:"100%"},children:[e.jsx("defs",{children:e.jsx("marker",{id:`arrow-${s}`,viewBox:"0 0 10 10",refX:"9",refY:"5",markerWidth:"6",markerHeight:"6",orient:"auto-start-reverse",children:e.jsx("path",{d:"M 0 0 L 10 5 L 0 10 z",fill:"var(--text-dim)"})})}),a.map((u,d)=>{const m=x(u.from),p=x(u.to);if(!m||!p)return null;const g=p.x-m.x,f=p.y-m.y,y=g>=0?m.x+Me/2:m.x-Me/2,S=g>=0?p.x-Me/2:p.x+Me/2,k=f>=0?m.y+De/2:m.y-De/2,w=f>=0?p.y-De/2:p.y+De/2,E=(y+S)/2,v=(k+w)/2;return e.jsxs("g",{children:[e.jsx("line",{x1:y,y1:k,x2:S,y2:w,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(y=>y.id===u.id);if(!d)return null;const m=cs+d.col*(Me+cs),p=ds+d.row*(De+ds),g=vr[u.type];if(u.type==="decision"){const y=m+Me/2,S=p+De/2,k=[[y,p],[m+Me,S],[y,p+De],[m,S]].map(w=>w.join(",")).join(" ");return e.jsxs("g",{children:[e.jsx("polygon",{points:k,fill:g.fill,stroke:g.stroke,strokeWidth:2}),e.jsx("foreignObject",{x:m+8,y:S-14,width:Me-16,height:28,children:e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,fontSize:12,color:g.fg,textAlign:"center",lineHeight:1.2,fontStyle:"italic",height:"100%"},children:[e.jsx(on,{size:11}),u.label]})})]},u.id)}const f=u.type==="note";return e.jsxs("g",{children:[e.jsx("rect",{x:m,y:p,width:Me,height:De,rx:8,fill:g.fill,stroke:g.stroke,strokeWidth:f?1:2,strokeDasharray:f?"4 3":void 0}),e.jsx("foreignObject",{x:m+6,y:p+6,width:Me-12,height:De-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:f?"italic":"normal",height:"100%"},children:[f&&e.jsx(cn,{size:11}),u.label]})})]},u.id)})]})})}function br({id:s}){return e.jsx("div",{id:s,style:{padding:20,textAlign:"center",color:"var(--text-dim)",fontSize:13},children:"No workflow steps."})}function kr(s){return s.length===0?[]:s.map((t,a)=>({id:t.id,col:a,row:0}))}const Ra={fontSize:14,lineHeight:1.6,color:"var(--text)"};function Nr({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 wr extends We.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 Sr(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 Cr={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 zr(s){const t=[];let a={heading:null,blocks:[]};for(const i of s){const n=Cr[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 Tr({slug:s,onClose:t,onCommentAdded:a}){var U,J,he,ye;const i=re(),[n,c]=r.useState(null),[o,l]=r.useState([]),[h,x]=r.useState(!0),[u,d]=r.useState(null),[m,p]=r.useState(null),[g,f]=r.useState(!1),[y,S]=r.useState(!1),[k,w]=r.useState(null),[E,v]=r.useState(null),[C,R]=r.useState(""),[j,P]=r.useState(null),[T,b]=r.useState([]),A=We.useCallback((I,H,Q)=>{b(le=>le.some(_=>_.blockId===I)?le:[...le,{blockId:I,blockType:H,message:Q.message||String(Q)}])},[]),O=r.useRef(null),N=r.useMemo(()=>n?zr(n.blocks):[],[n]);r.useEffect(()=>{let I=!1;const H=5e3;return(async()=>{x(!0),d(null);try{const Q=new Promise((se,W)=>setTimeout(()=>W(new Error("Request timed out after 5s")),H)),[le,_]=await Promise.race([Promise.all([z.get(`/artifacts/${encodeURIComponent(s)}/render`),z.get(`/artifacts/${encodeURIComponent(s)}`)]),Q]);if(I)return;c(le);const D=(_==null?void 0:_.comments)??[];l(Array.isArray(D)?D:[])}catch(Q){if(!I){const le=Q.message;d(le),p(le)}}finally{I||x(!1)}})(),()=>{I=!0}},[s]);function F(I){if(!O.current)return;I.preventDefault();const H=O.current.getBoundingClientRect();w({x:I.clientX,y:I.clientY,worldX:I.clientX-H.left,worldY:I.clientY-H.top})}async function K(){if(!(!E||!C.trim()))try{const I=await z.post(`/artifacts/${encodeURIComponent(s)}/comments`,{x:E.worldX,y:E.worldY,text:C.trim(),author:"drb0rk"});l(H=>[...H,{id:I.id??`cmt_${Date.now()}`,x:E.worldX,y:E.worldY,text:C.trim(),author:"drb0rk",created:new Date().toISOString()}]),v(null),R(""),w(null),a==null||a(),i.success("Comment added")}catch(I){i.error(`Failed to add comment: ${I.message}`)}}async function L(){if(!g){f(!0);try{const I=await z.post(`/artifacts/${encodeURIComponent(s)}/submit`,{answers:[],submitter:"drb0rk"});I!=null&&I.ok?(i.success("Sent to agent — feedback.md written, status=review"),a==null||a()):i.error("Submit failed: server did not return ok=true")}catch(I){i.error(`Submit failed: ${I.message}`)}finally{f(!1)}}}function G(){S(I=>!I)}const ne=I=>{const H=I.id,Q=I.data??{},le=Sr(I);return le.ok?e.jsx(wr,{blockId:H,blockType:I.type,onError:A,children:te(I,H,Q)},H):e.jsxs("div",{id:H,className:"glyph-block-error",role:"alert",style:{border:"1px solid var(--error, #f85149)",background:"rgba(248, 81, 73, 0.06)",borderRadius:8,padding:"12px 14px",margin:"12px 0",color:"var(--text)",fontFamily:"var(--font-mono, ui-monospace, monospace)",fontSize:12,lineHeight:1.55},children:[e.jsxs("strong",{style:{color:"var(--error, #f85149)",fontFamily:"var(--font-sans, system-ui, sans-serif)",display:"block",marginBottom:4},children:[I.type," block invalid"]}),e.jsxs("div",{style:{color:"var(--text-muted)",marginBottom:6},children:["block id: ",e.jsx("code",{children:H})]}),e.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:le.error})]},H)},te=(I,H,Q)=>{switch(I.type){case"RichText":return e.jsx(rr,{id:H,children:I.childrenMarkdown??""},H);case"Callout":return e.jsx(or,{id:H,tone:Q.tone??"info",children:I.childrenMarkdown??""},H);case"Checklist":return e.jsx(cr,{id:H,items:Q.items??[]},H);case"Table":return e.jsx(dr,{id:H,columns:Q.columns??[],rows:Q.rows??[]},H);case"CodeTabs":return e.jsx(mr,{id:H,tabs:Q.tabs??[]},H);case"Decision":return e.jsx(ur,{id:H,title:Q.title,question:Q.question,options:Q.options??[]},H);case"OpenQuestions":return e.jsx(hr,{id:H,questions:Q.questions??[]},H);case"FileTree":return e.jsx(pr,{id:H,title:Q.title,entries:Q.entries??[]},H);case"Diff":return e.jsx(gr,{id:H,filename:Q.filename,language:Q.language,mode:Q.mode??"unified",before:Q.before??"",after:Q.after??""},H);case"Stat":return e.jsx(fr,{id:H,label:Q.label??"",value:Q.value,trend:Q.trend,hint:Q.hint},H);case"Workflow":return e.jsx(yr,{id:H,steps:Q.steps??[],connections:Q.connections},H);case"Mockup":return e.jsx(Nr,{id:H,title:Q.title,x:Q.x,y:Q.y,w:Q.w,h:Q.h,html:Q.html??""},H);case"Diagram":return e.jsx("div",{id:H,className:"glyph-block-placeholder",children:e.jsxs("em",{children:["[Diagram] ",H]})},H)}};if(h)return e.jsx("div",{className:"glyph-renderer glyph-renderer--loading",children:m?e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:"Failed to load glyph."}),e.jsx("pre",{children:m})]}):e.jsxs(e.Fragment,{children:[e.jsx(Rr,{})," 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 B=((U=n.frontmatter)==null?void 0:U.title)??s,V=((J=n.frontmatter)==null?void 0:J.status)??"draft",X=o.length;return e.jsxs("div",{className:`glyph-canvas ${y?"glyph-canvas--fullscreen":""}`,ref:O,onContextMenu:F,children:[e.jsxs("div",{className:"glyph-toolbar-floating",children:[e.jsxs("button",{className:"glyph-btn glyph-btn--primary glyph-btn--send",onClick:L,disabled:g,title:"Send comments + question answers to the agent — writes feedback.md, status=review",children:[e.jsx(rs,{size:14}),e.jsx("span",{children:"Send to agent"}),e.jsx("span",{className:"glyph-btn-badge",children:X})]}),e.jsx("span",{className:"glyph-toolbar-divider"}),e.jsx("button",{className:"glyph-icon-btn",title:"Share",onClick:()=>{typeof window<"u"&&navigator.clipboard&&(navigator.clipboard.writeText(window.location.href).catch(()=>{}),i.success("Link copied"))},children:e.jsx(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:y?"Exit fullscreen":"Fullscreen",onClick:G,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(et,{size:15}),e.jsx("span",{className:"glyph-icon-btn-count",children:X})]}),t&&e.jsx("button",{className:"glyph-icon-btn glyph-icon-btn--close",title:"Close",onClick:t,"aria-label":"Close",children:e.jsx(ke,{size:15})})]}),e.jsxs("div",{className:"glyph-canvas-content",children:[e.jsxs("header",{className:"glyph-canvas-title",children:[e.jsx("h1",{className:"glyph-title",children:B}),e.jsxs("div",{className:"glyph-meta",children:[e.jsx("span",{className:`glyph-status glyph-status--${V}`,children:V}),e.jsx("span",{className:"glyph-slug",children:s})]})]}),(T.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:T.length>0?`${T.length} block${T.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:[T.map((I,H)=>e.jsxs("li",{children:[e.jsx("strong",{children:I.blockType})," (",e.jsx("code",{children:I.blockId}),"): ",I.message]},`be-${H}`)),(ye=n.errors)==null?void 0:ye.map((I,H)=>e.jsxs("li",{children:[I.line?`line ${I.line}: `:"",I.message]},`ce-${H}`))]})]}),e.jsx("div",{className:"glyph-sections",children:N.map((I,H)=>e.jsxs("section",{className:`glyph-section ${I.heading?"glyph-section--headed":"glyph-section--plain"}`,children:[I.heading&&e.jsx("h2",{className:"glyph-section-heading",children:I.heading}),e.jsx("div",{className:"glyph-section-blocks",children:I.blocks.map(ne)})]},`sec-${H}-${I.heading??"ungrouped"}`))})]}),o.map(I=>e.jsxs("button",{className:`glyph-pin ${j===I.id?"glyph-pin--active":""}`,style:{left:I.x,top:I.y},onClick:H=>{H.stopPropagation(),P(j===I.id?null:I.id)},title:I.text,children:[e.jsx(Bt,{size:14}),j===I.id&&e.jsxs("div",{className:"glyph-pin-thread",children:[e.jsx("div",{className:"glyph-pin-text",children:I.text}),e.jsxs("div",{className:"glyph-pin-meta",children:[I.author??"anonymous"," · ",I.created?new Date(I.created).toLocaleString():""]})]})]},I.id)),k&&e.jsx("div",{className:"glyph-ctx-menu",style:{left:k.x,top:k.y},onClick:I=>I.stopPropagation(),children:e.jsxs("button",{className:"glyph-ctx-item",onClick:()=>{v({worldX:k.worldX,worldY:k.worldY}),w(null)},children:[e.jsx(Bt,{size:14})," Add comment here"]})}),E&&e.jsx("div",{className:"glyph-modal-overlay",onClick:()=>v(null),children:e.jsxs("div",{className:"glyph-modal",onClick:I=>I.stopPropagation(),children:[e.jsxs("h3",{children:["Add comment at (",Math.round(E.worldX),", ",Math.round(E.worldY),")"]}),e.jsx("textarea",{autoFocus:!0,value:C,onChange:I=>R(I.target.value),placeholder:"What should the agent know about this area?",rows:4,className:"glyph-modal-textarea"}),e.jsxs("div",{className:"glyph-modal-actions",children:[e.jsx("button",{className:"glyph-btn glyph-btn--ghost",onClick:()=>v(null),children:"Cancel"}),e.jsx("button",{className:"glyph-btn glyph-btn--primary",onClick:K,disabled:!C.trim(),children:"Add comment"})]})]})})]})}function Rr(){return e.jsx("span",{className:"glyph-spinner","aria-label":"loading",children:"…"})}function $r(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 Ar({snapshot:s,refreshSnapshot:t}){const a=re(),[i,n]=r.useState(s.artifacts||[]),[c,o]=r.useState(!s.artifacts),[l,h]=r.useState(null),[x,u]=r.useState(""),[d,m]=r.useState(!1);r.useEffect(()=>{s.artifacts&&(n(s.artifacts),o(!1))},[s.artifacts]);const p=async()=>{try{const S=await z.get("/artifacts");n(S.artifacts||[]),o(!1)}catch(S){a.error(`Artifacts load failed: ${S.message}`),o(!1)}},g=r.useMemo(()=>{let S=i;if(x){const k=x.toLowerCase();S=S.filter(w=>(w.slug||"").toLowerCase().includes(k)||(w.title||"").toLowerCase().includes(k))}return d||(S=S.filter(k=>k.status!=="archived")),S},[i,x,d]),f=async(S,k)=>{try{const w=await z.post("/artifacts",{slug:S,title:k});a.success(`Artifact "${w.slug}" created.`),h(w.slug),await p()}catch(w){a.error(`Create failed: ${w.message}`)}},y=async S=>{if(confirm(`Delete artifact "${S}"? This removes the directory permanently.`))try{await z.del(`/artifacts/${encodeURIComponent(S)}`),a.success("Artifact deleted."),l===S&&h(null),await p()}catch(k){a.error(`Delete failed: ${k.message}`)}};return l?e.jsxs("div",{className:"artifact-glyph-overlay",children:[e.jsx("div",{className:"artifact-glyph-toolbar",children:e.jsxs($,{variant:"ghost",onClick:()=>{h(null),p()},children:[e.jsx(zt,{size:14})," Back to artifacts"]})}),e.jsx(Tr,{slug:l,onClose:()=>{h(null),p()},onCommentAdded:()=>p()})]}):e.jsxs("div",{className:"view view-artifacts",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(Ks,{size:18})," Glyphs (",i.length,")"]}),e.jsx("p",{className:"view-subtitle",children:"Visual artifacts with elements, connections, and threaded comments."})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs("div",{className:"search-input",children:[e.jsx(pe,{size:14,"aria-hidden":!0}),e.jsx("label",{htmlFor:"artifacts-search",className:"sr-only",children:"Search artifacts"}),e.jsx("input",{id:"artifacts-search",className:"input",type:"text",placeholder:"Search…",value:x,onChange:S=>u(S.target.value),"aria-label":"Search artifacts"})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>m(S=>!S),title:d?"Hide archived":"Show archived",children:[d?e.jsx(ua,{size:14}):e.jsx(ca,{size:14}),d?"Hide archived":"Show archived"]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:p,children:[e.jsx(ce,{size:14})," Refresh"]})]})]}),e.jsx(Mr,{onCreate:f}),c?e.jsx("div",{className:"view-loading",children:e.jsx(me,{size:"lg"})}):g.length===0?e.jsx(Ne,{icon:e.jsx(Ks,{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(S=>e.jsx(Ir,{artifact:S,onOpen:()=>h(S.slug),onDelete:()=>y(S.slug)},S.slug))})]})}function Mr({onCreate:s}){const[t,a]=r.useState(""),[i,n]=r.useState("");return e.jsxs(ee,{className:"new-artifact",children:[e.jsxs(ae,{children:[e.jsx(ze,{size:14})," New artifact"]}),e.jsx(ie,{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 Ir({artifact:s,onOpen:t,onDelete:a}){const i=$r(s.status||"draft");return e.jsxs(ee,{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(Ke,{size:12})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:n=>{n.stopPropagation(),a()},children:[e.jsx(we,{size:12})," Delete"]})]})]})}function Lr({children:s,className:t,onRemove:a}){return e.jsxs("span",{className:Y("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 Er({task:s,agents:t,onPromote:a,onDelete:i,onEdit:n,onRefresh:c}){var u;const o=re(),l=async()=>{try{await z.post(`/tasks/${encodeURIComponent(s.id)}/promote`),o.success("Promoted to queued.",1500),a(s.id)}catch(d){o.error(`Promote failed: ${d.message}`)}},h=async()=>{if(confirm("Delete this task?"))try{await z.del(`/tasks/${encodeURIComponent(s.id)}`),o.success("Deleted.",1500),i(s.id)}catch(d){o.error(`Delete failed: ${d.message}`)}},x={high:"var(--warning)",normal:"var(--info)",low:"var(--muted)"};return e.jsxs("div",{className:"backlog-item","data-task-id":s.id,children:[e.jsxs("div",{className:"backlog-item-head",children:[e.jsx("span",{className:"priority-dot",style:{background:x[s.priority]||"var(--info)"}}),e.jsx("span",{className:"backlog-item-title",children:s.title}),s.assignee&&e.jsxs("span",{className:"backlog-item-badge",children:["@",s.assignee]}),((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(At,{size:13})}),e.jsx("button",{type:"button",className:"icon-btn",title:"Edit",onClick:()=>n(s),children:e.jsx(Ve,{size:13})}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger",title:"Delete",onClick:h,children:e.jsx(we,{size:13})})]})]})]})}function Dr({agents:s,onRefresh:t}){const a=re(),[i,n]=r.useState([]),[c,o]=r.useState(!1),l=async()=>{try{o(!0);const m=await z.get("/tasks/backlog");n(Array.isArray(m.tasks)?m.tasks:[])}catch(m){a.error(`Backlog load failed: ${m.message}`)}finally{o(!1)}};r.useEffect(()=>{l()},[]);const h=async m=>{n(p=>p.filter(g=>g.id!==m)),await t()},x=async m=>{n(p=>p.filter(g=>g.id!==m)),await t()},u=m=>{},d=async()=>{var m;if(i.length!==0)try{const g=((m=(await z.post("/tasks/promote-batch",{ids:i.map(f=>f.id)})).affected)==null?void 0:m.filter(f=>f.ok).length)??0;a.success(`Promoted ${g} task(s).`,2e3),n([]),await t()}catch(p){a.error(`Promote all failed: ${p.message}`)}};return e.jsxs("div",{className:"backlog-panel",children:[e.jsxs("div",{className:"backlog-panel-header",children:[e.jsxs("span",{className:"backlog-panel-title",children:[e.jsx(Ys,{size:15}),"Backlog (",i.length,")"]}),e.jsxs("div",{className:"backlog-panel-header-actions",children:[i.length>0&&e.jsxs($,{variant:"ghost",size:"sm",onClick:d,title:"Promote all to queued",children:[e.jsx(At,{size:12})," Promote all"]}),e.jsx($,{variant:"ghost",size:"sm",onClick:l,title:"Refresh backlog","aria-label":"Refresh backlog",children:e.jsx(ce,{size:12,className:c?"animate-spin":""})})]})]}),c?e.jsx("div",{className:"backlog-empty",children:"Loading…"}):i.length===0?e.jsxs("div",{className:"backlog-empty",children:[e.jsx(Ys,{size:28}),e.jsx("span",{children:"Backlog is empty."})]}):e.jsx("div",{className:"backlog-list",children:i.map(m=>e.jsx(Er,{task:m,agents:s,onPromote:h,onDelete:x,onEdit:u,onRefresh:t},m.id))})]})}const Hs=[{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"}],Et=["low","normal","high"];function Pr({snapshot:s,refreshSnapshot:t,setActiveTab:a}){const i=re(),n=Ae(),[c,o]=r.useState(s.tasks||[]),[l,h]=r.useState(!s.tasks),[x,u]=r.useState(""),[d,m]=r.useState(""),[p,g]=r.useState(!1),[f,y]=r.useState(0),[S,k]=r.useState(""),w=async()=>{try{const b=await z.get("/tasks");o(Array.isArray(b)?b:[])}catch(b){i.error(`Tasks load failed: ${b.message}`)}finally{h(!1)}};r.useEffect(()=>{s.tasks&&(o(s.tasks),h(!1))},[s.tasks]),r.useEffect(()=>{const b=setInterval(()=>y(A=>A+1),3e4);return()=>clearInterval(b)},[]);const E=r.useMemo(()=>{let b=c.filter(A=>A.status!=="backlog");if(d&&(b=b.filter(A=>(A.priority||"normal")===d)),x.trim()){const A=x.toLowerCase();b=b.filter(O=>(O.title||"").toLowerCase().includes(A)||(O.description||"").toLowerCase().includes(A))}return b},[c,x,d]),v=r.useMemo(()=>{const b={high:0,normal:1,low:2};return[...E].sort((A,O)=>{const N=b[A.priority]??1,F=b[O.priority]??1;return N!==F?N-F:new Date(O.createdAt).getTime()-new Date(A.createdAt).getTime()})},[E]),C=c.filter(b=>b.status==="backlog").length,R=async(b,A)=>{const O=c.find(F=>F.id===b);if(!O)return;const N=O.status;o(F=>F.map(K=>K.id===b?{...K,status:A}:K)),k(`Task ${O.title} moved to ${A}.`);try{await z.patch(`/tasks/${encodeURIComponent(b)}/status`,{status:A}),i.success(`Moved to ${A}.`,1200)}catch(F){o(K=>K.map(L=>L.id===b?{...L,status:N}:L)),k(`Failed to move task ${O.title}: ${F.message}`),i.error(`Move failed: ${F.message}`)}},j=async b=>{if(confirm("Delete this task?"))try{await z.del(`/tasks/${encodeURIComponent(b)}`),o(A=>A.filter(O=>O.id!==b)),i.success("Task deleted.",1200)}catch(A){i.error(`Delete failed: ${A.message}`)}},P=async b=>{try{const A=await z.post(`/tasks/${encodeURIComponent(b)}/start`);A&&A.task&&o(O=>O.map(N=>N.id===b?A.task:N)),i.success("Retry dispatched.",1200)}catch(A){i.error(`Retry failed: ${A.message}`)}},T=async b=>{const A=c.find(O=>O.id===b);if(A)try{const O=await z.post("/tasks/submit",{title:A.title,description:A.description,priority:A.priority,tags:A.tags}),N=(O.subtasks||[]).length;i.success(N>1?`Odin split it into ${N} subtasks.`:"Sent to Odin.",1500),O.subtasks&&O.subtasks.length>0&&o(F=>[O.main,...O.subtasks,...F.filter(K=>K.id!==A.id)]),await t()}catch(O){i.error(`Submit failed: ${O.message}`)}};return e.jsxs("div",{className:"view view-tasks",children:[e.jsx("div",{className:"sr-only",role:"status","aria-live":"polite",children:S}),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(pe,{size:12,"aria-hidden":!0}),e.jsx("input",{className:"input",type:"text",placeholder:"Search…",value:x,onChange:b=>u(b.target.value),"aria-label":"Search tasks"}),x&&e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Clear search",onClick:()=>u(""),children:e.jsx(ke,{size:12})})]})}),e.jsx("div",{className:"tasks-toolbar-divider"}),e.jsxs("div",{className:"tasks-toolbar-group",children:[e.jsx("label",{className:"tasks-toolbar-label",htmlFor:"tasks-priority-filter",children:"Priority"}),e.jsxs("select",{id:"tasks-priority-filter",className:"select select-sm",value:d,onChange:b=>m(b.target.value),title:"Filter by priority",children:[e.jsx("option",{value:"",children:"All"}),Et.map(b=>e.jsx("option",{value:b,children:b},b))]})]}),e.jsx("div",{className:"tasks-toolbar-spacer"}),e.jsxs("div",{className:"tasks-toolbar-group",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:w,title:"Refresh","aria-label":"Refresh tasks",children:e.jsx(ce,{size:14})}),C>0&&e.jsxs($,{variant:p?"accent":"ghost",size:"sm",onClick:()=>g(b=>!b),title:p?"Hide backlog":"Show backlog",children:[e.jsx(Ys,{size:14}),"Backlog",e.jsx("span",{className:"badge",children:C})]}),e.jsxs($,{variant:"primary",size:"sm",onClick:()=>Br(n,i,o,w,t),children:[e.jsx(ze,{size:14})," New task"]})]})]}),p&&C>0&&e.jsx(Dr,{agents:s.agents||[],onRefresh:t}),l?e.jsx("div",{className:"view-loading",children:e.jsx(me,{size:"lg"})}):e.jsx("div",{className:"kanban",children:Hs.map(b=>e.jsx(Fr,{column:b,tasks:v.filter(A=>A.status===b.id),onMove:R,onDelete:j,onRetry:P,onEdit:A=>Ur(n,i,A,o,w,t),onSubmitToOdin:T,tick:f},b.id))})]})}function Fr({column:s,tasks:t,onMove:a,onDelete:i,onRetry:n,onEdit:c,onSubmitToOdin:o,tick:l}){const[h,x]=r.useState(!1);return e.jsxs("div",{className:Y("kanban-column",h&&"kanban-column-drop"),"data-column":s.id,onDragOver:u=>{u.preventDefault(),x(!0)},onDragLeave:()=>x(!1),onDrop:u=>{u.preventDefault(),x(!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(ae,{children:[e.jsx("span",{className:Y("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(Or,{task:u,onMove:d=>{const p=Hs.findIndex(g=>g.id===u.status)+d;p>=0&&p<Hs.length&&a(u.id,Hs[p].id)},onEdit:()=>c(u),onDelete:()=>i(u.id),onRetry:()=>n(u.id),onSubmitToOdin:()=>o(u.id),tick:l},u.id))})]})}function Or({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:Y("task-card",`priority-${s.priority}`),"data-task-id":s.id,draggable:!0,onDragStart:h=>{h.dataTransfer.setData("text/task-id",s.id),h.dataTransfer.effectAllowed="move"},"data-tick":o,children:[e.jsxs("div",{className:"task-card-head",children:[e.jsx("span",{className:"priority-dot",style:{background:Va[s.priority]||"var(--info)"}}),e.jsx("div",{className:"task-card-title",children:s.title})]}),s.description&&e.jsx("div",{className:"task-card-desc",children:s.description.slice(0,160)}),e.jsxs("div",{className:"task-card-badges",children:[l&&e.jsxs("span",{className:"task-card-badge",title:`Auto-assigned to @${l}`,children:[e.jsx(Xe,{size:10})," @",l]}),s.timeSpent?e.jsxs("span",{className:"task-card-badge",children:[e.jsx($s,{size:10})," ",Math.round((s.timeSpent||0)/60),"m"]}):null,s.tags&&s.tags.length>0&&s.tags.slice(0,3).map(h=>e.jsx(Lr,{children:h},h))]}),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:h=>h.stopPropagation(),children:[e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Move left",title:"Move left",onClick:()=>t(-1),children:e.jsx(jn,{size:14})}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Edit",title:"Edit",onClick:a,children:e.jsx(fn,{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(at,{size:14})}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger","aria-label":"Delete",title:"Delete",onClick:i,children:e.jsx(we,{size:14})}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Move right",title:"Move right",onClick:()=>t(1),children:e.jsx(Ke,{size:14})})]})]})]})}function Br(s,t,a,i,n){let c=null,o=null,l=null,h=null;const x=async d=>{d&&typeof d.preventDefault=="function"&&d.preventDefault();const m=((c==null?void 0:c.value)||"").trim(),p=((o==null?void 0:o.value)||"").trim();if(!m){t.warning("Title is required."),c==null||c.focus();return}const g=(h==null?void 0:h.value)||"normal",f=((l==null?void 0:l.value)||"").split(",").map(y=>y.trim()).filter(Boolean);try{const y=await z.post("/tasks",{title:m,description:p,priority:g,tags:f});s.close(),typeof window<"u"&&window.dispatchEvent(new MouseEvent("mousedown")),a(S=>[y,...S]),t.success("Task created.",1200),await n()}catch(y){t.error(`Create failed: ${y.message}`)}},u=d=>{d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),x(d))};s.open({title:"New task",width:520,children:e.jsxs("div",{className:"task-form",children:[e.jsx("label",{className:"field-label",htmlFor:"task-title",children:"Title *"}),e.jsx("input",{ref:d=>{c=d},id:"task-title",className:"input",type:"text",maxLength:200,placeholder:"What needs to be done?",autoFocus:!0,onKeyDown: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 Wa(o.value);d!==o.value&&(o.value=d)},children:"✨"})]}),e.jsxs("div",{className:"task-form-row",children:[e.jsxs("label",{htmlFor:"task-priority",className:"task-form-field",children:["Priority hint",e.jsx("select",{ref:d=>{h=d},id:"task-priority",className:"select",defaultValue:"normal",children:Et.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=>x(d),children:[e.jsx(ze,{size:14})," Create task"]})]})})}function Ur(s,t,a,i,n,c){let o=null,l=null,h=null,x=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 p=(x==null?void 0:x.value)||"normal",g=((h==null?void 0:h.value)||"").split(",").map(f=>f.trim()).filter(Boolean);try{const f=await z.put(`/tasks/${encodeURIComponent(a.id)}`,{title:d,description:m,priority:p,tags:g});s.close(),typeof window<"u"&&window.dispatchEvent(new MouseEvent("mousedown")),i(y=>y.map(S=>S.id===a.id?f:S)),t.success("Task updated.",1200),await c()}catch(f){t.error(`Save failed: ${f.message}`)}};s.open({title:"Edit task",width:520,children:e.jsxs("div",{className:"task-form",children:[e.jsx("label",{className:"field-label",htmlFor:"edit-task-title",children:"Title *"}),e.jsx("input",{ref:d=>{o=d},id:"edit-task-title",className:"input",type:"text",maxLength:200,defaultValue:a.title,autoFocus:!0}),e.jsx("label",{className:"field-label",htmlFor:"edit-task-desc",children:"Description"}),e.jsx("textarea",{ref:d=>{l=d},id:"edit-task-desc",className:"textarea",rows:4,defaultValue:a.description||""}),e.jsxs("div",{className:"task-form-row",children:[e.jsxs("label",{htmlFor:"edit-task-priority",className:"task-form-field",children:["Priority hint",e.jsx("select",{ref:d=>{x=d},id:"edit-task-priority",className:"select",defaultValue:a.priority||"normal",children:Et.map(d=>e.jsx("option",{value:d,children:d},d))})]}),e.jsxs("label",{htmlFor:"edit-task-tags",className:"task-form-field",style:{flex:2},children:["Tags",e.jsx("input",{ref:d=>{h=d},id:"edit-task-tags",className:"input",type:"text",defaultValue:(a.tags||[]).join(", "),placeholder:"comma-separated"})]})]}),e.jsxs(ee,{children:[e.jsxs(ae,{children:[e.jsx(ma,{size:12})," Status"]}),e.jsxs(ie,{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(ua,{size:14})," Save"]})]})})}const _r=We.memo(Pr);function Wr(s){return z.urlWithToken(`/artifacts/${encodeURIComponent(s)}/content`)}function Vr(s,t){const a=Wr(t);window.open(a,"_blank","noopener,noreferrer")}const qt={"1m":60*1e3,"5m":5*60*1e3,"30m":30*60*1e3,"1h":60*60*1e3},Ie=56,He=32,ms=22,Hr=4,qr=.9,ct={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 dt(s){return s&&ct[s]||ct.idle}function Bs(s,t=24){return s?s.length<=t?s:s.slice(0,t-1)+"…":""}function Js(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 mt(s){const t=s._timerStart;return typeof t=="number"&&t>0?t:Js(s.createdAt)||Date.now()}function Kr(s,t){return(s.status==="done"||s.status==="archived"||s.status==="failed"||s.status==="killed")&&(Js(s.completedAt)||Js(s.updatedAt))||t}function Gr(s){return typeof s.startedAt=="number"&&s.startedAt>0?s.startedAt:Date.now()}function Yr(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 Xr(s){return s<=6e4?1e4:s<=3e5?3e4:s<=18e5?3e5:6e5}function Qr(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 Jr({snapshot:s,refreshSnapshot:t}){const a=re(),i=r.useRef(null),[n,c]=r.useState("live"),[o,l]=r.useState("5m"),[h,x]=r.useState(()=>typeof window>"u"?!0:window.innerWidth>900),[u,d]=r.useState([]),[m,p]=r.useState([]),[g,f]=r.useState(!0),[y,S]=r.useState(0),[k,w]=r.useState(Date.now()),[E,v]=r.useState(()=>Date.now()-qt["5m"]*.1),[C,R]=r.useState({width:800,height:400}),[j,P]=r.useState(null),[T,b]=r.useState(""),[A,O]=r.useState([]),[N,F]=r.useState(""),[K,L]=r.useState("normal"),[G,ne]=r.useState(""),[te,B]=r.useState(""),[V,X]=r.useState(!1),[U,J]=r.useState(!1),[he,ye]=r.useState([]),I=Ae(),H=s.agents||[],Q=s.tasks||[],le=qt[o],_=E,D=E+le,se=r.useCallback(async()=>{try{const[M,Z]=await Promise.all([z.get("/background").catch(()=>({instances:[]})),z.get("/activity?limit=200").catch(()=>({events:[]}))]);d(M.instances||[]),p(Z.events||[])}catch(M){console.warn("activity reload failed:",M)}finally{f(!1)}},[]);r.useEffect(()=>{se();const M=setInterval(se,3e3);return()=>clearInterval(M)},[se]),r.useEffect(()=>{S(M=>M+1)},[Q.length,H.length]),r.useEffect(()=>{if(n==="pause")return;w(Date.now());const M=setInterval(()=>w(Date.now()),1e3);return()=>clearInterval(M)},[n,y]),r.useEffect(()=>{if(n==="pause")return;(k-E)/le>qr&&v(k-le*.1)},[k,E,le,n]),r.useEffect(()=>{v(Date.now()-le*.1)},[o]),r.useEffect(()=>{n==="live"&&v(Date.now()-le*.1)},[n]),r.useLayoutEffect(()=>{const M=i.current;if(!M)return;const Z=new ResizeObserver(ge=>{for(const je of ge){const{width:ue,height:fe}=je.contentRect;R({width:Math.max(200,Math.floor(ue)),height:Math.max(120,Math.floor(fe))})}});return Z.observe(M),()=>Z.disconnect()},[]);const W=r.useMemo(()=>{const M=[];let Z=0;for(const ue of u){const fe=Gr(ue),Ee=Yr(ue,k);Ee<_||fe>D||M.push({kind:"bg",id:`bg:${ue.instanceId}`,index:Z++,label:`BG ${Bs(ue.promptPreview,20)||ue.instanceId.slice(0,10)}`,sub:ue.status||"pending",start:fe,end:Ee,data:ue})}const ge=[...Q].sort((ue,fe)=>mt(ue)-mt(fe)),je=[];for(const ue of ge){const fe=mt(ue),Ee=Kr(ue,k);if(Ee<_||fe>D)continue;let os=-1;for(let es=0;es<je.length;es++)if(je[es]<=fe){je[es]=Ee,os=es;break}os===-1&&(je.push(Ee),os=je.length-1),M.push({kind:"task",id:`task:${ue.id}`,index:Z+os,label:Bs(ue.title,32),sub:ue.status,start:fe,end:Ee,data:ue})}return M},[u,Q,k,_,D]),oe=r.useMemo(()=>{const M=new Map;for(const Z of W)M.set(Z.id,Z);return M},[W]),q=r.useCallback(M=>le<=0?0:(M-_)/le*C.width,[_,le,C.width]),de=r.useMemo(()=>{const M=Xr(le),Z=[],ge=Math.floor(_/M)*M;for(let je=ge;je<=D+M;je+=M){if(je<_-M)continue;if(je>D)break;const ue=q(je);ue<-40||ue>C.width+40||Z.push({t:je,x:ue,label:Qr(je,le)})}return Z},[_,D,le,C.width,q]),Re=r.useMemo(()=>{const M=[];for(const Z of W){if(Z.kind==="events")continue;const ge=Math.max(Z.start,_),je=Math.min(Z.end,D);if(je<_||ge>D)continue;const ue=q(ge),fe=q(je),Ee=Math.max(Hr,fe-ue),os=He+ms+Z.index*Ie+8,es=Ie-16;let Ue="doing";if(Z.kind==="bg"){const Se=Z.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=Z.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 Ba=(j==null?void 0:j.id)===Z.id;M.push({id:Z.id,laneIndex:Z.index,x:ue,y:os,w:Ee,h:es,label:Z.label,statusClass:Ue,selected:Ba,data:Z.data,kind:Z.kind,start:Z.start,end:Z.end})}return M},[W,q,j,_,D]),Le=r.useMemo(()=>{const M=[];for(const Z of m){const ge=Js(Z.ts);if(ge<_-5e3||ge>D+5e3)continue;const je=q(ge);let ue=He+12;if(Z.taskId){const fe=oe.get(`task:${Z.taskId}`);fe&&(ue=He+ms+fe.index*Ie+Ie/2)}else if(Z.nodeId){const fe=String(Z.nodeId),Ee=oe.get(fe.startsWith("task:")||fe.startsWith("bg:")?fe:`task:${fe}`);Ee&&(ue=He+ms+Ee.index*Ie+Ie/2)}M.push({id:`${Z.ts}-${Z.kind}-${Z.author??""}-${Z.taskId??""}`,x:je,y:ue,kind:Z.kind||"event",ts:ge,text:String(Z.text||Z.kind||""),author:Z.author})}return M},[m,_,D,q,oe]),Be=r.useMemo(()=>W.map(M=>({id:M.id,y:He+ms+M.index*Ie,h:Ie})),[W]),Ge=r.useMemo(()=>{const M=q(k);return Math.max(0,Math.min(C.width,M))},[q,k,C.width]),Ps=r.useCallback(M=>{const ge={id:M.id,kind:M.kind,label:M.label,status:M.statusClass,data:M.data};P(ge)},[]);r.useEffect(()=>{if(!j){O([]),B(""),ye([]);return}b(""),F(""),ne(""),ye([]),(async()=>{try{const M=await z.get(`/activity?nodeId=${encodeURIComponent(j.id)}&limit=50`);O(M.events||[])}catch{O([])}if(j.kind==="bg"){const M=j.data;try{const Z=await z.get(`/background/${encodeURIComponent(M.instanceId)}/output?lines=80`);B(Z.output||"")}catch{B("")}if(M.taskId)try{const Z=await z.get(`/tasks/${encodeURIComponent(M.taskId)}/artifacts`);ye((Z.artifacts||[]).map(ge=>ge.id))}catch{ye([])}}})()},[j]);const ys=async()=>{if(!(!j||!T.trim())){J(!0);try{await z.post("/comments",{nodeId:j.id,text:T,author:"user"}),b("");const M=await z.get(`/activity?nodeId=${encodeURIComponent(j.id)}&limit=50`);O(M.events||[]),a.success("Comment added.")}catch(M){a.error(`Comment failed: ${M.message}`)}finally{J(!1)}}},Fs=async()=>{if(!(!j||!N.trim())){X(!0);try{await z.post(`/nodes/${encodeURIComponent(j.id)}/tasks`,{title:N,description:`Created from timeline selection ${j.id}.`,priority:K}),F(""),a.success("Task created."),await t()}catch(M){a.error(`Task create failed: ${M.message}`)}finally{X(!1)}}},bs=async()=>{if(!j||j.kind!=="bg"||!G.trim())return;const M=j.data;try{const Z=await z.post(`/background/${encodeURIComponent(M.instanceId)}/message`,{message:G});Z.ok?(a.success("Message sent."),ne("")):a.warning(Z.error||"Send failed")}catch(Z){a.error(`Send failed: ${Z.message}`)}},Pa=async()=>{if(!j||j.kind!=="bg"||!confirm("Kill this bg instance session?"))return;const M=j.data;try{const Z=await z.del(`/background/${encodeURIComponent(M.instanceId)}`);Z.ok?a.success("Session killed."):a.warning(Z.error||"Kill failed"),await se()}catch(Z){a.error(`Kill failed: ${Z.message}`)}},Fa=async()=>{if(!j||j.kind!=="bg")return;const M=j.data;try{const Z=await z.get(`/background/${encodeURIComponent(M.instanceId)}/output?lines=80`);B(Z.output||"")}catch{}};r.useEffect(()=>{const M=Z=>{Z.key==="Escape"&&P(null)};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[]);const Oa=()=>{S(M=>M+1),se()},nt=He+ms+W.length*Ie;return e.jsxs("div",{className:"view view-activity",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx($e,{size:18})," Activity"]}),e.jsx("p",{className:"view-subtitle",children:"Live timeline of agents, tasks, and background sessions. Active tasks pulse; the red line marks “now”."})]}),e.jsx("div",{className:"view-actions",children:e.jsxs("div",{className:"tl-mode-toggle",children:[e.jsxs($,{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(ha,{size:14}):e.jsx(vs,{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:Y("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:Oa,title:"Refresh",children:[e.jsx(ce,{size:14})," Refresh"]})]})})]}),g&&e.jsx("div",{className:"view-loading",children:e.jsx(me,{size:"lg"})}),!g&&H.length===0&&Q.length===0&&u.length===0&&m.length===0?e.jsx(Ne,{icon:e.jsx($e,{size:32}),title:"No activity yet",message:"Once agents, tasks, or background instances exist, they'll show up here on the timeline."}):e.jsx("div",{className:Y("tl-view",j&&"tl-view-detail-open"),children:e.jsxs("div",{className:Y("tl-body",!h&&"tl-body-stream-collapsed"),children:[e.jsxs("aside",{className:Y("tl-stream",!h&&"tl-stream-collapsed"),children:[e.jsxs("div",{className:"tl-stream-head",children:[e.jsxs("h3",{children:[e.jsx(As,{size:13})," Live events"]}),e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>x(!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(Lt,{items:[...m].reverse(),itemHeight:40,height:400,className:"tl-stream-virtual",renderItem:M=>{const Z=M.author?Xe:M.kind==="task"?Rs:M.kind==="bg"?Ws:$e;return e.jsxs("div",{className:"tl-stream-event",children:[e.jsx("span",{className:"tl-stream-event-time",children:new Date(M.ts).toLocaleTimeString("en-GB",{hour12:!1})}),e.jsx("span",{className:"tl-stream-event-icon",style:{color:dt(M.kind)},children:e.jsx(Z,{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:[!h&&e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>x(!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(D).toLocaleTimeString("en-GB",{hour12:!1})]})]}),e.jsxs("div",{className:"tl-canvas-legend",children:[e.jsxs("span",{className:"tl-legend-item",children:[e.jsx("span",{className:"tl-legend-dot",style:{background:"var(--success)"}})," active"]}),e.jsxs("span",{className:"tl-legend-item",children:[e.jsx("span",{className:"tl-legend-dot tl-legend-dot-dashed",style:{borderColor:"var(--info)"}})," queued"]}),e.jsxs("span",{className:"tl-legend-item",children:[e.jsx("span",{className:"tl-legend-dot",style:{background:"var(--warning)"}})," blocked"]}),e.jsxs("span",{className:"tl-legend-item",children:[e.jsx("span",{className:"tl-legend-dot",style:{background:"var(--error)"}})," error"]}),e.jsx("span",{className:"tl-legend-sep"}),e.jsxs("span",{className:"tl-legend-item",children:[e.jsx(bn,{size:11})," agent"]}),e.jsxs("span",{className:"tl-legend-item",children:[e.jsx(kn,{size:11})," task"]}),e.jsxs("span",{className:"tl-legend-item",children:[e.jsx(Ws,{size:11})," bg"]})]})]}),e.jsx("div",{className:"tl-canvas-scroll",children:e.jsxs("svg",{className:"tl-canvas",width:C.width,height:Math.max(C.height,nt),role:"application","aria-label":"Activity timeline",children:[e.jsx("defs",{children:e.jsx("pattern",{id:"tl-canvas-grid",width:C.width,height:Ie,patternUnits:"userSpaceOnUse",children:e.jsx("path",{d:`M 0 0 L 0 ${Ie}`,fill:"none",stroke:"var(--border)",strokeWidth:.5,opacity:.35})})}),e.jsx("rect",{width:"100%",height:"100%",fill:"url(#tl-canvas-grid)"}),Be.map(M=>e.jsx("rect",{className:"tl-lane-bg",x:0,y:M.y,width:C.width,height:M.h,fill:M.id.charCodeAt(M.id.length-1)%2===0?"var(--bg-elev-2)":"var(--bg-elev)",opacity:.4},`bg-${M.id}`)),e.jsx("g",{className:"tl-time-axis",children:de.map(M=>e.jsxs("g",{children:[e.jsx("line",{x1:M.x,y1:0,x2:M.x,y2:nt,stroke:"var(--border)",strokeWidth:.5,strokeDasharray:"2,4",opacity:.5}),e.jsx("text",{x:M.x+4,y:He-8,fontSize:10,fontFamily:"var(--font-mono)",fill:"var(--text-dim)",children:M.label})]},`tick-${M.t}`))}),W.map(M=>{const Z=He+ms+M.index*Ie+Ie/2;return e.jsxs("g",{className:"tl-lane-label-group",children:[e.jsx("text",{x:6,y:Z-2,className:"tl-lane-label",textAnchor:"start",children:Bs(M.label,28)}),e.jsx("text",{x:6,y:Z+10,className:"tl-lane-label-sub",textAnchor:"start",children:M.sub})]},`label-${M.id}`)}),Re.map(M=>{const Z=dt(M.statusClass),ge=M.id===(j==null?void 0:j.id);return e.jsxs("g",{className:Y("tl-task-bar",`tl-task-bar-${M.statusClass}`,ge&&"tl-task-bar-selected"),onClick:()=>Ps(M),children:[e.jsx("rect",{x:M.x,y:M.y,width:M.w,height:M.h,rx:6,fill:Z,fillOpacity:M.statusClass==="done"?.35:M.statusClass==="queued"?.18:.85,stroke:Z,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:Bs(M.label,Math.max(4,Math.floor(M.w/7)))})]},`bar-${M.id}`)}),Le.map(M=>{const Z=dt(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:Z,strokeWidth:1.2,opacity:.7}),e.jsx("circle",{cx:M.x,cy:M.y,r:4,fill:Z,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:nt,stroke:"var(--error)",strokeWidth:1.5,opacity:.9}),e.jsxs("g",{className:"tl-now-marker",children:[e.jsx("circle",{cx:Ge,cy:He-4,r:4,fill:"var(--error)"}),e.jsx("text",{x:Ge+6,y:He-4,fontSize:10,fontWeight:700,fill:"var(--error)",fontFamily:"var(--font-mono)",children:"now"})]})]})})]}),j&&e.jsx("aside",{className:"tl-detail tl-detail-enter",children:e.jsxs(ee,{children:[e.jsxs(ae,{children:[j.kind==="agent"&&e.jsx(Xe,{size:14}),j.kind==="task"&&e.jsx(Rs,{size:14}),j.kind==="bg"&&e.jsx(Ws,{size:14}),j.label,e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>P(null),title:"Close","aria-label":"Close activity detail",style:{marginLeft:"auto"},children:e.jsx(ke,{size:14})})]}),e.jsxs("div",{className:"tl-detail-meta",children:[e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"type"})," ",j.kind]}),e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"status"})," ",e.jsx("code",{children:j.status})]}),j.kind==="agent"&&(()=>{const M=j.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]})]})})(),j.kind==="task"&&(()=>{const M=j.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()]})]})})(),j.kind==="bg"&&(()=>{const M=j.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"})]})]})})()]}),j.kind==="task"&&j.data.description&&e.jsx("div",{className:"tl-detail-desc",children:j.data.description}),j.kind==="bg"&&j.data.promptPreview&&e.jsx("div",{className:"tl-detail-desc",children:j.data.promptPreview}),j.kind==="bg"&&e.jsxs("div",{className:"tl-detail-bg",children:[e.jsx("pre",{className:"tl-bg-output",children:te||"(no output — start the session via tmux attach)"}),e.jsxs("div",{className:"tl-bg-output-actions",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:Fa,children:[e.jsx(ce,{size:12})," Refresh output"]}),he.length>0&&e.jsxs($,{variant:"secondary",size:"sm",onClick:()=>Vr(I,he[0]),children:[e.jsx(Te,{size:12})," Open artifact"]}),e.jsxs($,{variant:"danger",size:"sm",onClick:Pa,children:[e.jsx(we,{size:12})," Kill session"]})]}),e.jsxs("div",{className:"tl-form-row",children:[e.jsx("label",{htmlFor:"bg-message-input",className:"sr-only",children:"Send a message to this bg session"}),e.jsx("input",{id:"bg-message-input",className:"input",placeholder:"Send a message to this bg session…",value:G,onChange:M=>ne(M.target.value),onKeyDown:M=>{M.key==="Enter"&&bs()},"aria-label":"Send a message to this bg session"}),e.jsxs($,{variant:"primary",size:"sm",disabled:!G.trim(),onClick:bs,children:[e.jsx(rs,{size:12})," Send"]})]})]}),j.kind!=="bg"&&e.jsxs("div",{className:"tl-detail-create",children:[e.jsx("label",{className:"field-label",htmlFor:"followup-task-title",children:"Create follow-up task"}),e.jsx("input",{id:"followup-task-title",className:"input",placeholder:"Task title",value:N,onChange:M=>F(M.target.value)}),e.jsxs("div",{className:"tl-form-row",children:[e.jsx("label",{htmlFor:"followup-task-priority",className:"sr-only",children:"Task priority"}),e.jsxs("select",{id:"followup-task-priority",className:"select",value:K,onChange:M=>L(M.target.value),"aria-label":"Task priority",children:[e.jsx("option",{value:"low",children:"Low"}),e.jsx("option",{value:"normal",children:"Normal"}),e.jsx("option",{value:"high",children:"High"})]}),e.jsxs($,{variant:"primary",size:"sm",disabled:!N.trim()||V,onClick:Fs,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(et,{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,Z)=>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-${Z}`))]}),e.jsxs("div",{className:"comment-input-row",children:[e.jsx("label",{htmlFor:"comment-input",className:"sr-only",children:"Add a comment"}),e.jsx("input",{id:"comment-input",className:"input",placeholder:"Add a comment…",value:T,onChange:M=>b(M.target.value),onKeyDown:M=>{M.key==="Enter"&&!M.shiftKey&&ys()},"aria-label":"Add a comment"}),e.jsxs($,{variant:"secondary",size:"sm",disabled:!T.trim()||U,onClick:ys,children:[e.jsx(rs,{size:12})," Post"]})]})]})]})},j.id)]})})]})}function Zr(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 ut(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 Zr(s,t.substring(0,i))<=2?40:t.includes(s)?30:0}function el(s,t){const a=s.toLowerCase().trim();return a?t.map(i=>{const n=ut(a,i.label.toLowerCase()),c=i.value?ut(a,String(i.value).toLowerCase()):0,o=i.description?ut(a,i.description.toLowerCase()):0,l=Math.max(n,c,o);if(l===0)return null;const h=n>=c&&n>=o?"label":c>=n&&c>=o?"value":"description",x=h==="label"?i.label:h==="value"?String(i.value):i.description;return{...i,score:l,matchedField:h,matchedTerm:x}}).filter(i=>i!==null).sort((i,n)=>n.score-i.score):[]}const Dt="bizar_settings_recent";function $a(){try{const s=localStorage.getItem(Dt);return s?JSON.parse(s):[]}catch{return[]}}function sl(s){if(s)try{const t=$a().filter(a=>a!==s);t.unshift(s),localStorage.setItem(Dt,JSON.stringify(t.slice(0,5)))}catch{}}function tl(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 al(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 nl({sections:s,onJump:t}){const[a,i]=r.useState(""),[n,c]=r.useState([]),[o,l]=r.useState(0),[h,x]=r.useState(null),[u,d]=r.useState(!1),m=r.useRef(null),p=r.useRef(null),g=r.useRef(null),f=r.useRef([]);r.useEffect(()=>{f.current=al(s)},[s]);const y=r.useCallback((T,b=!1)=>{if(p.current&&clearTimeout(p.current),!T.trim()){c([]),l(0);return}const A=()=>{const O=el(T,f.current);c(O),l(0)};b?A():p.current=setTimeout(A,150)},[]);r.useEffect(()=>{y(a)},[a,y]),r.useEffect(()=>()=>{p.current&&clearTimeout(p.current),g.current&&clearTimeout(g.current)},[]);const S=(T,b)=>{const A=document.querySelector(`[data-section="${T}"] [data-setting-id="${b}"]`);A&&(A.scrollIntoView({behavior:"smooth",block:"center"}),A.classList.add("setting-flash"),setTimeout(()=>A.classList.remove("setting-flash"),2e3));const O=document.querySelector(`[data-section="${T}"]`);O&&O.scrollIntoView({behavior:"smooth",block:A?"nearest":"start"})},k=T=>{x(T),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>x(null),1500);const b=document.querySelector(`[data-section="${T}"]`);b&&b.scrollIntoView({behavior:"smooth",block:"start"})},w=T=>{var b;sl(a),T.key===T.section?(k(T.section),t(T.section)):(k(T.section),t(T.section,T.key),S(T.section,T.key)),i(""),(b=m.current)==null||b.blur()},E=T=>{var b;T.key==="Escape"?(i(""),(b=m.current)==null||b.blur()):T.key==="ArrowDown"?(T.preventDefault(),l(A=>Math.min(A+1,n.length-1))):T.key==="ArrowUp"?(T.preventDefault(),l(A=>Math.max(A-1,0))):T.key==="Enter"&&(T.preventDefault(),n.length===0&&a.trim()&&y(a,!0),n[o]&&w(n[o]))},v=T=>{w(T)},C=$a(),R=T=>{var b;i(T),(b=m.current)==null||b.focus()},j=()=>{try{localStorage.removeItem(Dt)}catch{}d(T=>T)},P=u&&!a.trim()&&C.length>0;return e.jsxs("div",{className:"settings-search",children:[e.jsxs("div",{className:"settings-search-input-wrap",children:[e.jsx(pe,{size:13,className:"settings-search-icon"}),e.jsx("input",{ref:m,className:"settings-search-input",placeholder:"Search settings…",value:a,onChange:T=>i(T.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(ke,{size:12})})]}),P&&e.jsxs("div",{className:"settings-search-recent",children:[e.jsxs("div",{className:"settings-search-recent-header",children:[e.jsx("span",{className:"settings-search-recent-label",children:"Recent"}),e.jsx("button",{type:"button",className:"settings-search-recent-clear",onClick:j,tabIndex:-1,children:"Clear"})]}),C.map(T=>e.jsxs("button",{type:"button",className:"settings-search-recent-item",onMouseDown:b=>{b.preventDefault(),R(T)},children:[e.jsx(pe,{size:11}),e.jsx("span",{children:T})]},T))]}),a&&n.length>0&&e.jsx("div",{className:"settings-search-results",children:n.map((T,b)=>e.jsxs("button",{type:"button",className:Y("settings-search-result",b===o&&"settings-search-result-active"),onClick:()=>v(T),onMouseEnter:()=>l(b),children:[e.jsx("span",{className:Y("settings-search-result-type",T.key===T.section&&"settings-search-result-type-section"),children:T.key===T.section?"section":"field"}),e.jsx("span",{className:"settings-search-result-label",children:tl(T.label,a)}),T.key!==T.section&&e.jsx("span",{className:"settings-search-result-key mono muted",children:T.key})]},`${T.section}::${T.key}`))}),a&&n.length===0&&e.jsx("div",{className:"settings-search-empty muted",children:"No matching settings."})]})}const il=[{id:"dark",label:"Dark",Icon:Nn},{id:"light",label:"Light",Icon:wn},{id:"system",label:"System",Icon:Sn}],rl=[{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"}],ll=["Inter","system-ui","Segoe UI","Roboto","JetBrains Mono","SF Mono","Cascadia Code"];function ol({settings:s,patchTheme:t,patchUi:a}){return e.jsxs(ee,{id:"settings-theme","data-section":"theme",children:[e.jsxs(ae,{children:[e.jsx(oa,{size:14})," Theme"]}),e.jsx(ie,{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:rl.map(i=>e.jsxs("button",{type:"button",className:Y("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:il.map(({id:i,label:n,Icon:c})=>{const o=s.theme.mode===i;return e.jsxs("button",{type:"button",className:Y("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:Y("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:ll.map(i=>e.jsx("option",{value:i,children:i},i))})]}),e.jsxs("div",{className:"field","data-setting-id":"theme.fontSize",children:[e.jsxs("label",{className:"field-label",children:["Font size: ",s.theme.fontSize,"px"]}),e.jsx("input",{type:"range",min:12,max:20,value:s.theme.fontSize,onChange:i=>t({fontSize:Number(i.target.value)})})]}),e.jsxs("label",{className:"checkbox-row","data-setting-id":"theme.compactMode",children:[e.jsx("input",{type:"checkbox",checked:s.theme.compactMode,onChange:i=>t({compactMode:i.target.checked})}),e.jsx("span",{children:"Compact mode (denser UI)"})]}),e.jsxs("label",{className:"checkbox-row","data-setting-id":"theme.animations",children:[e.jsx("input",{type:"checkbox",checked:s.theme.animations,onChange:i=>t({animations:i.target.checked})}),e.jsx("span",{children:"Enable animations"})]})]})}const ht=[{id:"bizar",name:"Bizar CLI"},{id:"bizar-dash",name:"Dashboard"},{id:"bizar-plugin",name:"Opencode Plugin"}];function cl(){const s=re(),[t,a]=r.useState({current:{},latest:null,checking:!1,updating:!1,hasUpdates:!1,requiresRestart:!1,perPackage:{}});r.useEffect(()=>{const l=new Ct;return l.on(h=>{(h.type==="update:progress"||h.type==="update:log"||h.type==="update:complete")&&a(x=>{if(h.type==="update:complete")return{...x,updating:!1,requiresRestart:!!h.requiresRestart};if(h.type==="update:log"){const d=h,m=x.perPackage[d.pkg]||{logs:[]};return{...x,perPackage:{...x.perPackage,[d.pkg]:{...m,logs:[...(m.logs||[]).slice(-50),d.line]}}}}const u=h;return{...x,perPackage:{...x.perPackage,[u.pkg]:{...x.perPackage[u.pkg],status:u.status,error:u.error,newVersion:u.newVersion}}}})}),()=>l.close()},[]),r.useEffect(()=>{z.get("/updates/status").then(l=>a(h=>({...h,current:l.current}))).catch(l=>a(h=>({...h,error:l.message})))},[]);const i=async()=>{a(l=>({...l,checking:!0,error:void 0}));try{const l=await z.get("/updates/check");a(h=>({...h,checking:!1,current:l.current,latest:l.latest,hasUpdates:l.hasUpdates}))}catch(l){a(h=>({...h,checking:!1,error:l.message}))}},n=async()=>{if(confirm("Update Bizar packages? The dashboard will restart automatically.")){a(l=>({...l,updating:!0,requiresRestart:!1,perPackage:{},error:void 0}));try{await z.post("/updates/apply",{packages:["bizar","bizar-dash","bizar-plugin"]})}catch(l){a(h=>({...h,updating:!1,error:l.message}))}}},c=async()=>{if(confirm("Restart the dashboard? You will be disconnected briefly."))try{await z.post("/restart"),s.info("Restarting…",3e3),setTimeout(()=>window.location.reload(),3e3)}catch{s.error("Restart failed")}},o=t.checking||t.updating;return e.jsxs(ee,{id:"settings-updates","data-section":"updates",children:[e.jsxs(ae,{children:[e.jsx(qe,{size:14})," Updates"]}),e.jsx(ie,{children:"Check installed Bizar packages and apply dashboard updates."}),e.jsxs("div",{className:"updates-current",children:[e.jsx("h4",{children:"Installed versions"}),e.jsx("ul",{children:ht.map(l=>e.jsxs("li",{children:[e.jsx("span",{children:l.name}),e.jsx("code",{className:"mono",children:t.current[l.id]||"—"})]},l.id))})]}),t.latest&&e.jsxs("div",{className:"updates-latest",children:[e.jsx("h4",{children:"Latest available"}),e.jsx("ul",{children:ht.map(l=>{var d;const h=t.current[l.id],x=(d=t.latest)==null?void 0:d[l.id],u=h&&x&&h!==x;return e.jsxs("li",{className:u?"updates-outdated":"updates-current-version",children:[e.jsx("span",{children:l.name}),e.jsxs("code",{className:"mono",children:[x||"—",u&&e.jsx("span",{className:"updates-badge",children:"update available"})]})]},l.id)})})]}),t.updating&&e.jsx("div",{className:"updates-progress-rows",children:ht.map(l=>{const h=t.perPackage[l.id]||{status:"idle",logs:[]};return e.jsxs("div",{className:"updates-pkg-row",children:[e.jsxs("div",{className:"updates-pkg-row-header",children:[e.jsx("span",{className:"updates-pkg-name",children:l.name}),e.jsxs("div",{className:"updates-pkg-status",children:[h.status==="starting"&&e.jsx("span",{className:"btn-spinner"}),h.status==="installing"&&e.jsx("span",{className:"btn-spinner"}),h.status==="done"&&e.jsx(Ts,{size:14,className:"icon-success"}),h.status==="error"&&e.jsx(Zs,{size:14,className:"icon-error"}),e.jsx("span",{children:h.status}),h.newVersion&&e.jsxs("code",{className:"mono",style:{fontSize:11},children:["→ ",h.newVersion]})]})]}),h.logs.length>0&&e.jsxs("details",{className:"updates-pkg-logs",children:[e.jsxs("summary",{children:["npm output (",h.logs.length," lines)"]}),e.jsx("pre",{children:h.logs.join(`
6
- `)})]}),h.status==="error"&&h.error&&e.jsxs("div",{className:"updates-pkg-error",children:[e.jsx(be,{size:12})," ",h.error]})]},l.id)})}),e.jsxs("div",{className:"updates-actions",children:[e.jsxs($,{onClick:i,disabled:o,children:[t.checking?e.jsx("span",{className:"btn-spinner"}):e.jsx(ce,{size:14}),"Check for updates"]}),e.jsxs($,{variant:"primary",onClick:n,disabled:!t.hasUpdates||t.updating,children:[t.updating?e.jsx("span",{className:"btn-spinner"}):e.jsx(qe,{size:14}),t.updating?"Updating…":t.hasUpdates?"Update now":"Up to date"]}),t.requiresRestart&&e.jsxs($,{variant:"danger",onClick:c,children:[e.jsx(ce,{size:14})," Restart Dashboard"]})]}),t.error&&e.jsxs("div",{className:"updates-error",children:[e.jsx(be,{size:14}),e.jsx("span",{children:t.error})]})]})}function dl(s,t,{delay:a=800,onSaved:i,onError:n}={}){const[c,o]=r.useState(s),[l,h]=r.useState("idle"),x=r.useRef(null),u=r.useRef(null),d=r.useRef(s),m=r.useRef(!1),p=r.useCallback(async S=>{h("saving");try{await t(S),d.current=S,u.current=null,h("saved"),i==null||i(),setTimeout(()=>h("idle"),2e3)}catch(k){h("error"),n==null||n(k)}},[t,i,n]),g=r.useCallback(S=>{o(S),u.current=S,m.current=!0,x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{x.current=null,m.current=!1;const k=u.current;u.current=null,k!==null&&p(k)},a)},[a,p]),f=r.useCallback(()=>{x.current&&(clearTimeout(x.current),x.current=null,m.current=!1)},[]),y=r.useCallback(async()=>{if(x.current){clearTimeout(x.current),x.current=null,m.current=!1;const S=u.current;u.current=null,S!==null&&await p(S)}},[p]);return r.useEffect(()=>()=>{if(x.current){clearTimeout(x.current),x.current=null;const S=u.current;u.current=null,S!==null&&(h("saving"),t(S).then(()=>{d.current=S,h("saved"),i==null||i()}).catch(k=>{h("error"),n==null||n(k)}).finally(()=>{setTimeout(()=>h("idle"),2e3)}))}},[t,i,n]),{value:c,setValue:g,status:l,save:p,flush:y,clearDebounce:f,hasPendingDebounceRef:m,pendingValueRef:u}}function wt({initialValue:s,saveFn:t,delay:a=800,render:i,className:n}){const{value:c,setValue:o,status:l,save:h,clearDebounce:x,hasPendingDebounceRef:u,pendingValueRef:d}=dl(s,t,{delay:a}),m=We.useCallback(()=>{u.current&&(x(),d.current!==null&&h(d.current))},[x,u,h,d]);return e.jsxs("div",{className:`autosave-field ${n||""} ${l}`,children:[i({value:c,onChange:o,onBlur:m}),e.jsxs("span",{className:"autosave-status",role:"status","aria-live":"polite",children:[l==="saving"&&e.jsx(Cn,{className:"spinning",size:12}),l==="saved"&&e.jsx(ns,{size:12}),l==="error"&&e.jsx(Zs,{size:12})]})]})}const ml=[{id:"topnav",label:"Top nav"},{id:"sidebar",label:"Sidebar"},{id:"both",label:"Both"}];function ul({settings:s,patchUi:t,patchTop:a,autoSave:i}){return e.jsxs(e.Fragment,{children:[e.jsxs(ee,{id:"settings-layout","data-section":"layout",children:[e.jsxs(ae,{children:[e.jsx(zn,{size:14})," UI layout"]}),e.jsx(ie,{children:"Choose how the dashboard's navigation is presented."}),e.jsx("div",{className:"layout-row","data-setting-id":"ui.layout",children:ml.map(n=>e.jsx("button",{type:"button",className:Y("layout-card",s.ui.layout===n.id&&"layout-card-active"),onClick:()=>t({layout:n.id}),children:e.jsx("span",{className:"layout-card-label",children:n.label})},n.id))}),e.jsxs("label",{className:"checkbox-row","data-setting-id":"ui.showHeader",children:[e.jsx("input",{type:"checkbox",checked:s.ui.showHeader,onChange:n=>t({showHeader:n.target.checked})}),e.jsx("span",{children:"Show header"})]}),e.jsxs("label",{className:"checkbox-row","data-setting-id":"ui.showStatusBar",children:[e.jsx("input",{type:"checkbox",checked:s.ui.showStatusBar,onChange:n=>t({showStatusBar:n.target.checked})}),e.jsx("span",{children:"Show status bar"})]}),e.jsxs("div",{className:"field","data-setting-id":"ui.defaultTab",children:[e.jsx("label",{className:"field-label",children:"Default tab"}),e.jsxs("select",{className:"select",value:s.ui.defaultTab,onChange:n=>t({defaultTab:n.target.value}),children:[e.jsx("option",{value:"overview",children:"Overview"}),e.jsx("option",{value:"chat",children:"Chat"}),e.jsx("option",{value:"agents",children:"Agents"}),e.jsx("option",{value:"artifacts",children:"Plans"}),e.jsx("option",{value:"projects",children:"Projects"}),e.jsx("option",{value:"tasks",children:"Tasks"}),e.jsx("option",{value:"config",children:"Config"}),e.jsx("option",{value:"settings",children:"Settings"}),e.jsx("option",{value:"mods",children:"Mods"}),e.jsx("option",{value:"schedules",children:"Schedules"})]})]})]}),e.jsxs(ee,{id:"settings-general","data-section":"general",children:[e.jsx(ae,{children:"General"}),e.jsx(ie,{children:"Default agent + model override."}),e.jsxs("div",{className:"field","data-setting-id":"defaultAgent",children:[e.jsx("label",{className:"field-label",htmlFor:"set-default-agent",children:"Default agent"}),e.jsx(wt,{initialValue:s.defaultAgent||"",saveFn:async n=>{a("defaultAgent",n),i==null||i("defaultAgent",n)},render:({value:n,onChange:c,onBlur:o})=>e.jsx("input",{id:"set-default-agent",className:"input",type:"text",placeholder:"e.g. odin",value:n,onChange:l=>c(l.target.value),onBlur:o})})]}),e.jsxs("div",{className:"field","data-setting-id":"defaultModel",children:[e.jsx("label",{className:"field-label",htmlFor:"set-default-model",children:"Model override"}),e.jsx(wt,{initialValue:s.defaultModel||"",saveFn:async n=>{a("defaultModel",n),i==null||i("defaultModel",n)},render:({value:n,onChange:c,onBlur:o})=>e.jsx("input",{id:"set-default-model",className:"input",type:"text",placeholder:"(leave empty for provider default)",value:n,onChange:l=>c(l.target.value),onBlur:o})})]})]})]})}function hl({tailscale:s,tailscaleDraft:t,setTailscaleDraft:a,onTailscaleToggle:i}){return e.jsxs(e.Fragment,{children:[e.jsxs(ee,{id:"settings-service","data-section":"service",children:[e.jsxs(ae,{children:[e.jsx(gs,{size:14})," Service"]}),e.jsx(ie,{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(ee,{id:"settings-tailscale","data-section":"tailscale",children:[e.jsxs(ae,{children:[e.jsx(yt,{size:14})," Tailscale serve"]}),e.jsx(ie,{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 xl({settings:s,patchNotifications:t}){return e.jsxs(ee,{id:"settings-notifications","data-section":"notifications",children:[e.jsx(ae,{children:"Notifications"}),e.jsx(ie,{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 pl({authStatus:s,setAuthStatus:t}){const a=re(),[i,n]=r.useState(z.getToken()),[c,o]=r.useState("");r.useEffect(()=>{let u=!1;return(async()=>{try{const d=await z.probeAuthStatus();u||t(d)}catch{u||t({required:!0,loopback:!1,peer:""})}})(),()=>{u=!0}},[]);const l=async()=>{try{const u=await z.get("/auth/reveal");o(u.token),n(u.token),z.setToken(u.token);try{await navigator.clipboard.writeText(u.token),a.success("Token copied to clipboard.")}catch{a.success("Token revealed — copy from the field below.")}}catch(u){a.error(`Reveal failed: ${u.message}`)}},h=async()=>{if(confirm("Regenerate the auth token? Anything still using the old token will start getting 401 errors immediately."))try{const u=await z.post("/auth/regenerate");o(u.token),n(u.token),z.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}`)}},x=()=>{z.setToken(i.trim()),a.success("Token saved. The dashboard will use it on the next request.")};return e.jsxs(ee,{id:"settings-auth","data-section":"auth",children:[e.jsxs(ae,{children:[e.jsx(xa,{size:14})," Authentication"]}),e.jsx(ie,{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:x,children:[e.jsx(Ds,{size:14})," Save token"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:l,children:[e.jsx(ls,{size:14})," Reveal & copy server token"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:h,children:[e.jsx(pa,{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 gl({settings:s,patchAgents:t,patchDashboard:a,autoSave:i}){var x,u,d,m;const n=re(),[c,o]=r.useState({});r.useEffect(()=>{z.get("/settings/plugin-options").then(o).catch(()=>{})},[]);const l=async()=>{try{await z.put("/settings/plugin-options",c),n.success("Saved — restart opencode for changes to take effect.")}catch(p){n.error(`Save failed: ${p.message}`)}},h=async()=>{try{const g=await(await fetch("/api/background/cleanup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({maxAgeDays:7})})).json();n.success(`Cleaned up ${g.deleted} old instances.`)}catch(p){n.error(`Cleanup failed: ${p.message}`)}};return e.jsxs(e.Fragment,{children:[e.jsxs(ee,{id:"settings-agents","data-section":"agents",children:[e.jsxs(ae,{children:[e.jsx(gs,{size:14})," Agent Behavior"]}),e.jsx(ie,{children:"Limits and timeouts for background agent dispatch."}),e.jsxs("div",{className:"form-row",children:[e.jsxs("label",{htmlFor:"agents-maxParallel",children:["Max parallel agents",e.jsx("span",{className:"meta-badge",children:"default: 6"})]}),e.jsx("input",{id:"agents-maxParallel",type:"number",min:1,max:20,value:((x=s.agents)==null?void 0:x.maxParallel)??6,onChange:p=>t({maxParallel:Math.max(1,Math.min(20,parseInt(p.target.value,10)||6))})})]}),e.jsxs("div",{className:"form-row",children:[e.jsxs("label",{htmlFor:"agents-stuckThresholdMs",children:["Stuck threshold (ms)",e.jsx("span",{className:"meta-badge",children:"default: 600000 (10 min)"})]}),e.jsx("input",{id:"agents-stuckThresholdMs",type:"number",min:6e4,max:36e5,step:6e4,value:((u=s.agents)==null?void 0:u.stuckThresholdMs)??6e5,onChange:p=>t({stuckThresholdMs:Math.max(6e4,Math.min(36e5,parseInt(p.target.value,10)||6e5))})})]}),e.jsxs("label",{className:"checkbox-row","data-setting-id":"agents.autoRestart",children:[e.jsx("input",{type:"checkbox",checked:!!((d=s.agents)!=null&&d.autoRestart),onChange:p=>t({autoRestart:p.target.checked})}),e.jsx("span",{children:"Auto-restart stuck agents"})]})]}),e.jsxs(ee,{id:"settings-dashboard","data-section":"dashboard",children:[e.jsxs(ae,{children:[e.jsx(Is,{size:14})," Dashboard"]}),e.jsxs(ie,{children:["Controls how ",e.jsx("code",{children:"bizar"})," starts up."]}),e.jsxs("label",{className:"checkbox-row","data-setting-id":"dashboard.autoLaunchWeb",children:[e.jsx("input",{type:"checkbox",checked:s.dashboard.autoLaunchWeb!==!1,onChange:p=>a({autoLaunchWeb:p.target.checked})}),e.jsx("span",{children:"Auto-launch web UI alongside TUI"})]}),e.jsxs("div",{className:"field","data-setting-id":"dashboard.projectsDirectory",style:{marginTop:"var(--space-4)"},children:[e.jsx("label",{className:"field-label",htmlFor:"set-projects-directory",children:"Projects directory"}),e.jsx("input",{id:"set-projects-directory",className:"input",type:"text",placeholder:"/home/user/projects",value:s.dashboard.projectsDirectory??"",onChange:p=>a({projectsDirectory:p.target.value})}),e.jsx("p",{className:"field-help",children:"New projects created via the dashboard will land here, and existing project directories inside this folder are auto-recognized on startup."}),s.dashboard.projectsDirectory&&e.jsxs(e.Fragment,{children:[!/^\/|^[A-Za-z]:/.test(s.dashboard.projectsDirectory)&&e.jsx("p",{style:{color:"var(--warning)",fontSize:11,marginTop:4},children:"Path should be absolute (start with / on Linux/Mac, or a drive letter on Windows)."}),s.dashboard.projectsDirectory.includes("..")&&e.jsx("p",{style:{color:"var(--error)",fontSize:11,marginTop:4},children:"Path traversal not allowed — this will be rejected server-side."})]})]}),e.jsxs("div",{className:"field","data-setting-id":"dashboard.allowedRoots",style:{marginTop:"var(--space-4)"},children:[e.jsxs("label",{className:"field-label",htmlFor:"set-allowed-roots",children:["Additional allowed roots ",e.jsx("span",{className:"muted",children:"(advanced)"})]}),e.jsx(wt,{initialValue:(s.dashboard.allowedRoots??[]).join(`
7
- `),delay:1500,saveFn:async p=>{const g=p.split(`
8
- `).map(f=>f.trim()).filter(Boolean);a({allowedRoots:g}),i==null||i("dashboard",{allowedRoots:g})},render:({value:p,onChange:g,onBlur:f})=>e.jsx("textarea",{id:"set-allowed-roots",className:"textarea",rows:4,placeholder:`/workspace
9
- /srv/projects`,value:p,onChange:y=>g(y.target.value),onBlur:f})},(m=s.dashboard.allowedRoots)==null?void 0:m.join(`
10
- `)),e.jsx("p",{className:"field-help",children:"Optional. Add filesystem roots beyond your home directory that the file browser and project scanner can access. Each path must be inside your home directory. One per line."}),(()=>{const p=(s.dashboard.allowedRoots??[]).join(`
11
- `).split(`
12
- `),g=[];return p.forEach((f,y)=>{f.trim()&&(/^\/|^[A-Za-z]:/.test(f)||g.push({key:`noabs-${y}`,msg:e.jsxs("p",{style:{color:"var(--warning)",fontSize:11,marginTop:2},children:["Line ",y+1,': "',f,'" — should be absolute (start with / or a drive letter).']})}),f.includes("..")&&g.push({key:`dots-${y}`,msg:e.jsxs("p",{style:{color:"var(--error)",fontSize:11,marginTop:2},children:["Line ",y+1,': "',f,`" — contains '..' (server will reject this).`]})}))}),g.map(f=>f.msg)})()]})]}),e.jsxs(ee,{id:"settings-background","data-section":"background",children:[e.jsxs(ae,{children:[e.jsx(gs,{size:14})," Background Agents"]}),e.jsx(ie,{children:"Tune plugin options. Changes take effect on next plugin restart."}),e.jsxs("div",{className:"form-row",children:[e.jsxs("label",{htmlFor:"bg-maxConcurrent",children:["Max concurrent instances",e.jsx("span",{className:"meta-badge",children:"default: 8"})]}),e.jsx("input",{id:"bg-maxConcurrent",type:"number",min:1,max:32,value:c.maxConcurrentInstances??8,onChange:p=>o(g=>({...g,maxConcurrentInstances:Math.max(1,Math.min(32,parseInt(p.target.value,10)||8))}))}),e.jsxs("small",{className:"muted",children:["Plugin option: ",e.jsx("code",{children:"maxConcurrentInstances"})]})]}),e.jsxs("div",{className:"form-row",children:[e.jsxs("label",{htmlFor:"bg-toolCallCap",children:["Tool-call cap",e.jsx("span",{className:"meta-badge",children:"default: 500"})]}),e.jsx("input",{id:"bg-toolCallCap",type:"number",min:1,max:5e3,value:c.backgroundToolCallCap??500,onChange:p=>o(g=>({...g,backgroundToolCallCap:Math.max(1,Math.min(5e3,parseInt(p.target.value,10)||500))}))}),e.jsxs("small",{className:"muted",children:["Plugin option: ",e.jsx("code",{children:"backgroundToolCallCap"})]})]}),e.jsxs("div",{className:"form-row",children:[e.jsxs("label",{htmlFor:"bg-stallTimeout",children:["Stall timeout (ms)",e.jsx("span",{className:"meta-badge",children:"default: 180000"})]}),e.jsx("input",{id:"bg-stallTimeout",type:"number",min:1e4,max:6e5,step:1e3,value:c.backgroundStallTimeoutMs??18e4,onChange:p=>o(g=>({...g,backgroundStallTimeoutMs:Math.max(1e4,Math.min(6e5,parseInt(p.target.value,10)||18e4))}))}),e.jsxs("small",{className:"muted",children:["Plugin option: ",e.jsx("code",{children:"backgroundStallTimeoutMs"})]})]}),e.jsxs("div",{className:"form-row",children:[e.jsxs("label",{htmlFor:"bg-thinkingLoopTimeout",children:["Thinking-loop timeout (ms)",e.jsx("span",{className:"meta-badge",children:"default: 300000"})]}),e.jsx("input",{id:"bg-thinkingLoopTimeout",type:"number",min:3e4,max:9e5,step:1e3,value:c.backgroundThinkingLoopTimeoutMs??3e5,onChange:p=>o(g=>({...g,backgroundThinkingLoopTimeoutMs:Math.max(3e4,Math.min(9e5,parseInt(p.target.value,10)||3e5))}))}),e.jsxs("small",{className:"muted",children:["Plugin option: ",e.jsx("code",{children:"backgroundThinkingLoopTimeoutMs"})]})]}),e.jsxs("div",{className:"form-row",children:[e.jsxs("label",{htmlFor:"bg-maxInterventions",children:["Max interventions",e.jsx("span",{className:"meta-badge",children:"default: 1"})]}),e.jsx("input",{id:"bg-maxInterventions",type:"number",min:1,max:3,value:c.backgroundMaxInterventions??1,onChange:p=>o(g=>({...g,backgroundMaxInterventions:Math.max(1,Math.min(3,parseInt(p.target.value,10)||1))}))}),e.jsxs("small",{className:"muted",children:["Plugin option: ",e.jsx("code",{children:"backgroundMaxInterventions"})]})]}),e.jsxs("div",{className:"form-row",children:[e.jsxs($,{variant:"secondary",size:"sm",onClick:l,children:[e.jsx(Ms,{size:14})," Save plugin options"]}),e.jsx($,{variant:"secondary",size:"sm",onClick:h,children:"Cleanup old instances (>7 days)"})]}),e.jsx("div",{className:"form-row",children:e.jsxs("small",{children:["Plugin options are read at startup. Save changes and run ",e.jsx("code",{children:"bizar update"})," to apply."]})})]})]})}function jl({settings:s,patchTop:t}){var a,i,n;return e.jsxs(ee,{id:"settings-system-llm","data-section":"system-llm",children:[e.jsxs(ae,{children:[e.jsx(Ve,{size:14})," System LLM API"]}),e.jsx(ie,{children:"Configures the LLM used for automatic title generation, prompt enhancement, summarization, and other system-level calls."}),e.jsxs("label",{className:"checkbox-row","data-setting-id":"systemLlm.enabled",children:[e.jsx("input",{type:"checkbox",checked:!!((a=s.systemLlm)!=null&&a.enabled),onChange:c=>{const o=s.systemLlm||{enabled:!0,provider:"opencode",model:"opencode/deepseek-v4-flash-free"};t("systemLlm",{...o,enabled:c.target.checked})}}),e.jsx("span",{children:"Enable system LLM calls"})]}),e.jsxs("div",{className:"field","data-setting-id":"systemLlm.provider",style:{marginTop:"var(--space-3)"},children:[e.jsx("label",{className:"field-label",htmlFor:"set-system-llm-provider",children:"Provider"}),e.jsxs("select",{id:"set-system-llm-provider",className:"select",value:((i=s.systemLlm)==null?void 0:i.provider)||"opencode",onChange:c=>{const o=s.systemLlm||{enabled:!0,provider:"opencode",model:"opencode/deepseek-v4-flash-free"};t("systemLlm",{...o,provider:c.target.value})},children:[e.jsx("option",{value:"opencode",children:"Opencode"}),e.jsx("option",{value:"openrouter",children:"OpenRouter"}),e.jsx("option",{value:"minimax",children:"MiniMax"})]})]}),e.jsxs("div",{className:"field","data-setting-id":"systemLlm.model",children:[e.jsx("label",{className:"field-label",htmlFor:"set-system-llm-model",children:"Model"}),e.jsx("input",{id:"set-system-llm-model",className:"input mono",type:"text",placeholder:"opencode/deepseek-v4-flash-free",value:((n=s.systemLlm)==null?void 0:n.model)||"opencode/deepseek-v4-flash-free",onChange:c=>{const o=s.systemLlm||{enabled:!0,provider:"opencode",model:"opencode/deepseek-v4-flash-free"};t("systemLlm",{...o,model:c.target.value})}}),e.jsxs("p",{className:"field-help",children:["The API key is read from ",e.jsx("code",{children:"auth.json"})," for the selected provider. Leave the default model for best results."]})]}),e.jsxs("div",{style:{marginTop:"var(--space-4)"},children:[e.jsx("h4",{style:{margin:"0 0 var(--space-2)"},children:"Features using this API"}),e.jsxs("ul",{className:"settings-feature-list",style:{margin:0,paddingLeft:"var(--space-4)",lineHeight:1.8},children:[e.jsx("li",{children:"Auto-title generation for new chat sessions"}),e.jsx("li",{children:"Auto-title generation for new tasks"}),e.jsx("li",{children:'"Enhance prompt" button in the task input'}),e.jsx("li",{children:'"Enhance prompt" button in the chat composer'}),e.jsx("li",{className:"muted",style:{fontSize:12},children:"Future: summarization, name generation, and more"})]})]})]})}const fl=[{value:"anthropic",label:"Anthropic"},{value:"anyllm",label:"AnyLLM"},{value:"litellm-anthropic",label:"LiteLLM (Anthropic)"},{value:"litellm-openai",label:"LiteLLM (OpenAI)"}];function vl({settings:s,onPatch:t}){const a=re(),[i,n]=r.useState(null),[c,o]=r.useState(null),[l,h]=r.useState(!1),[x,u]=r.useState(!1),[d,m]=r.useState(!1),[p,g]=r.useState(!1),[f,y]=r.useState(!1),[S,k]=r.useState(!1),w=r.useCallback(async()=>{h(!0);try{const[L,G]=await Promise.all([z.get("/headroom/status"),z.get("/headroom/stats?hours=24").catch(()=>({error:"no stats"}))]);n(L),G.error||o(G)}catch(L){a.error(`Failed to load Headroom status: ${L.message}`)}finally{h(!1)}},[a]);r.useEffect(()=>{w()},[w]);const E=async()=>{u(!0);try{const L=await z.post("/headroom/install",{force:!0});L.installed?(a.success(`Headroom installed via ${L.method}.`),await w()):a.error('Headroom install failed. Try: pip install "headroom-ai[all]"')}catch(L){a.error(`Install failed: ${L.message}`)}finally{u(!1)}},v=async()=>{m(!0);try{(await z.post("/headroom/wrap",{port:s.port})).ok?(a.success("opencode wrapped with Headroom."),await w()):a.error("Wrap failed.")}catch(L){a.error(`Wrap failed: ${L.message}`)}finally{m(!1)}},C=async()=>{g(!0);try{(await z.post("/headroom/unwrap")).ok?(a.success("opencode unwrapped from Headroom."),await w()):a.error("Unwrap failed.")}catch(L){a.error(`Unwrap failed: ${L.message}`)}finally{g(!1)}},R=async()=>{y(!0);try{(await z.post("/headroom/proxy/start",{port:s.port,host:s.host})).ok?(a.success(`Headroom proxy started on ${s.host}:${s.port}.`),await w()):a.error("Proxy start failed.")}catch(L){a.error(`Proxy start failed: ${L.message}`)}finally{y(!1)}},j=async()=>{k(!0);try{(await z.post("/headroom/proxy/stop")).ok?(a.success("Headroom proxy stopped."),await w()):a.error("Proxy stop failed.")}catch(L){a.error(`Proxy stop failed: ${L.message}`)}finally{k(!1)}},P=async()=>{try{const{spawn:L}=await na(async()=>{const{spawn:G}=await import("./__vite-browser-external-BIHI7g3E.js");return{spawn:G}},[]);L("headroom",["dashboard"],{detached:!0,stdio:"ignore"})}catch{a.error("Could not open Headroom dashboard. Run `headroom dashboard` manually.")}},{installed:T,version:b,proxyRunning:A,proxyPort:O,wrapped:N}=i||{},F=(c==null?void 0:c.compressionRatio)??0,K=(c==null?void 0:c.tokensSaved)??0;return e.jsx("div",{id:"settings-headroom","data-section":"headroom",children:e.jsxs(ee,{children:[e.jsxs(ae,{children:[e.jsx($e,{size:14,style:{color:A?"var(--success)":"var(--text-dim)"}}),"Headroom",T&&b&&e.jsxs("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:6},children:["v",b," ",A?"✓":"✗"]}),!T&&e.jsx("span",{style:{fontSize:11,color:"var(--error)",marginLeft:6},children:"not installed"})]}),e.jsx(ie,{children:"Context compression for token efficiency. Compresses tool outputs, logs, and conversation history by 60–95% before they reach the model."}),e.jsxs("div",{style:{display:"flex",gap:16,flexWrap:"wrap",marginTop:12,marginBottom:12},children:[e.jsxs("div",{className:"headroom-status-item",children:[T?e.jsx(Ts,{size:12,style:{color:"var(--success)"}}):e.jsx(as,{size:12,style:{color:"var(--error)"}}),e.jsx("span",{children:T?"Installed":"Not installed"})]}),e.jsxs("div",{className:"headroom-status-item",children:[A?e.jsx(Ts,{size:12,style:{color:"var(--success)"}}):e.jsx(as,{size:12,style:{color:"var(--text-dim)"}}),e.jsxs("span",{children:["Proxy ",A?`${O} ✓`:"stopped"]})]}),e.jsxs("div",{className:"headroom-status-item",children:[N?e.jsx(Ts,{size:12,style:{color:"var(--success)"}}):e.jsx(as,{size:12,style:{color:"var(--text-dim)"}}),e.jsxs("span",{children:["opencode ",N?"wrapped":"not wrapped"]})]})]}),(K>0||F>0)&&e.jsxs("div",{style:{display:"flex",gap:24,marginBottom:12},children:[e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:20,fontWeight:700,color:"var(--success)"},children:F>0?`${Math.round(F*100)}%`:"—"}),e.jsx("div",{className:"muted",style:{fontSize:11},children:"Compression ratio"})]}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:20,fontWeight:700,color:"var(--accent)"},children:K>0?K.toLocaleString():"—"}),e.jsx("div",{className:"muted",style:{fontSize:11},children:"Tokens saved (24h)"})]})]}),e.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap",marginBottom:8},children:[T?e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"secondary",size:"sm",onClick:v,disabled:d||N,title:N?"opencode is already wrapped":"Wrap opencode to route through Headroom proxy",children:[d?e.jsx("span",{className:"btn-spinner"}):e.jsx(tt,{size:13}),d?"Wrapping…":N?"Wrapped ✓":"Wrap opencode"]}),N&&e.jsxs($,{variant:"ghost",size:"sm",onClick:C,disabled:p,children:[p?e.jsx("span",{className:"btn-spinner"}):e.jsx(ce,{size:13}),p?"Unwrapping…":"Unwrap"]})]}):e.jsxs($,{variant:"primary",size:"sm",onClick:E,disabled:x,children:[x?e.jsx("span",{className:"btn-spinner"}):e.jsx(qe,{size:13}),x?"Installing…":"Install Headroom"]}),T&&e.jsxs(e.Fragment,{children:[A?e.jsxs($,{variant:"secondary",size:"sm",onClick:j,disabled:S,children:[S?e.jsx("span",{className:"btn-spinner"}):e.jsx(ga,{size:13}),S?"Stopping…":"Stop proxy"]}):e.jsxs($,{variant:"secondary",size:"sm",onClick:R,disabled:f,children:[f?e.jsx("span",{className:"btn-spinner"}):e.jsx(vs,{size:13}),f?"Starting…":"Start proxy"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:P,children:[e.jsx(js,{size:13}),"Dashboard"]})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:w,disabled:l,children:e.jsx(ce,{size:13,className:l?"spin":""})})]}),e.jsxs("div",{style:{marginTop:16},children:[e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{type:"checkbox",checked:s.enabled,onChange:L=>t({enabled:L.target.checked})}),e.jsx("span",{children:"Enable Headroom"})]}),e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{type:"checkbox",checked:s.autoInstall,onChange:L=>t({autoInstall:L.target.checked})}),e.jsx("span",{children:"Auto-install if missing on dashboard startup"})]}),e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{type:"checkbox",checked:s.autoStart,onChange:L=>t({autoStart:L.target.checked})}),e.jsx("span",{children:"Auto-start proxy on dashboard startup"})]}),e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{type:"checkbox",checked:s.autoWrap,onChange:L=>t({autoWrap:L.target.checked})}),e.jsx("span",{children:"Auto-wrap opencode on dashboard startup"})]}),e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{type:"checkbox",checked:s.routeAllProviders,onChange:L=>t({routeAllProviders:L.target.checked})}),e.jsx("span",{children:"Route all providers through Headroom proxy"})]}),e.jsxs("div",{className:"task-form-row",style:{marginTop:12},children:[e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",children:"Proxy port"}),e.jsx("input",{type:"number",className:"input",value:s.port,min:1,max:65535,onChange:L=>t({port:Math.max(1,Math.min(65535,parseInt(L.target.value,10)||8787))})})]}),e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",children:"Proxy host"}),e.jsx("input",{type:"text",className:"input",value:s.host,onChange:L=>t({host:L.target.value})})]})]}),e.jsxs("div",{className:"task-form-row",children:[e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",children:"Backend"}),e.jsx("select",{className:"select",value:s.backend,onChange:L=>t({backend:L.target.value}),children:fl.map(L=>e.jsx("option",{value:L.value,children:L.label},L.value))})]}),e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",children:"Monthly budget (USD)"}),e.jsx("input",{type:"number",className:"input",value:s.budget,min:0,step:1,onChange:L=>t({budget:Math.max(0,parseFloat(L.target.value)||0)})}),e.jsx("span",{className:"field-help",children:"0 = unlimited"})]})]}),e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{type:"checkbox",checked:s.outputShaper,onChange:L=>t({outputShaper:L.target.checked})}),e.jsx("span",{children:"Enable output shaper"})]}),e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{type:"checkbox",checked:s.telemetry,onChange:L=>t({telemetry:L.target.checked})}),e.jsx("span",{children:"Enable telemetry"})]})]})]})})}const Kt={enabled:!0,autoInstall:!0,port:8787,host:"127.0.0.1",outputShaper:!1,telemetry:!1,budget:0,backend:"anthropic",autoStart:!0,autoWrap:!0,routeAllProviders:!0};function yl({settings:s,setSettings:t,setDirty:a}){return e.jsx(vl,{settings:s.headroom||Kt,onPatch:i=>{t(n=>({...n,headroom:{...n.headroom||Kt,...i}})),a(!0)}})}function bl(){const s=re(),[t,a]=r.useState([]),[i,n]=r.useState(new Set),[c,o]=r.useState(!0),[l,h]=r.useState(""),[x,u]=r.useState(!0),d=r.useCallback(async()=>{o(!0);try{const[y,S]=await Promise.all([z.get("/activity"),z.get("/activity/hidden")]);a(Array.isArray(y.items)?y.items:[]),n(new Set(S.hidden||[]))}catch(y){s.error(`Load failed: ${y.message}`)}finally{o(!1)}},[s]);r.useEffect(()=>{d()},[d]);const m=(y,S)=>{const k=`${y.kind||""}|${y.ts||""}|${y.slug||""}|${S}`;let w=0;for(let E=0;E<k.length;E++)w=(w<<5)-w+k.charCodeAt(E)|0;return Math.abs(w).toString(16).padStart(8,"0").slice(0,16)},p=async()=>{try{await z.del("/activity/hide"),n(new Set),s.success("All hidden activity restored.")}catch(y){s.error(`Restore failed: ${y.message}`)}},g=async y=>{try{await z.del(`/activity/hide/${encodeURIComponent(y)}`);const S=new Set(i);S.delete(y),n(S)}catch(S){s.error(`Restore failed: ${S.message}`)}},f=t.filter((y,S)=>{const k=m(y,S);if(!x&&i.has(k))return!1;if(!l)return!0;const w=l.toLowerCase();return[y.kind,y.slug,y.message].some(E=>typeof E=="string"&&E.toLowerCase().includes(w))});return e.jsxs(ee,{id:"settings-activity-log","data-section":"activity-log",children:[e.jsxs(ae,{children:[e.jsx($e,{size:14})," Activity log",e.jsxs("span",{className:"muted",style:{fontWeight:400,marginLeft:8,fontSize:12},children:[t.length," total · ",i.size," hidden"]}),e.jsx($,{variant:"ghost",size:"sm",style:{marginLeft:"auto"},onClick:d,title:"Reload",children:e.jsx(ce,{size:12})})]}),e.jsxs(ie,{children:["Full history from ",e.jsx("code",{children:"~/.bizar/activity.log"}),". Hiding an item in the Overview only hides it there — the entry stays here."]}),e.jsxs("div",{className:"activity-log-toolbar",children:[e.jsxs("div",{className:"activity-log-search",children:[e.jsx(pe,{size:12}),e.jsx("input",{type:"text",className:"input",placeholder:"Filter by kind, slug, or message…",value:l,onChange:y=>h(y.target.value)})]}),e.jsxs("label",{className:"activity-log-toggle",children:[e.jsx("input",{type:"checkbox",checked:x,onChange:y=>u(y.target.checked)}),"Show hidden"]}),e.jsxs($,{variant:"ghost",size:"sm",disabled:i.size===0,onClick:p,title:"Restore all hidden items to the Overview",children:[e.jsx(Qe,{size:12})," Restore all"]})]}),c?e.jsx("div",{className:"muted",style:{padding:"12px 0",fontSize:12},children:"Loading…"}):f.length===0?e.jsx("div",{className:"muted",style:{padding:"12px 0",fontSize:12},children:t.length===0?"No activity yet.":"No items match the current filter."}):e.jsxs("div",{className:"activity-log-table-wrap",children:[e.jsxs("table",{className:"activity-log-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Kind"}),e.jsx("th",{children:"Detail"}),e.jsx("th",{children:"Time"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:f.slice(0,200).map((y,S)=>{const k=m(y,S),w=i.has(k);return e.jsxs("tr",{className:Y(w&&"activity-log-row-hidden"),children:[e.jsx("td",{className:"activity-log-kind",children:y.kind||"activity"}),e.jsx("td",{className:"activity-log-detail",children:y.message||y.slug||"—"}),e.jsx("td",{className:"activity-log-time mono",children:y.ts?new Date(y.ts).toLocaleString():"—"}),e.jsx("td",{children:w?e.jsx($,{variant:"ghost",size:"sm",onClick:()=>g(k),title:"Restore to Overview",children:e.jsx(Qe,{size:12})}):e.jsx("span",{className:"activity-log-state-tag",children:"shown"})})]},`${y.ts}-${S}`)})})]}),f.length>200&&e.jsxs("div",{className:"muted",style:{fontSize:11,padding:"8px 0"},children:["Showing first 200 of ",f.length,"."]})]})]})}function kl({about:s}){return e.jsxs(ee,{id:"settings-about","data-section":"about",children:[e.jsxs(ae,{children:[e.jsx(st,{size:14})," About"]}),e.jsx(ie,{children:"Build metadata."}),e.jsxs("dl",{className:"about-table",children:[e.jsx("dt",{children:"Version"}),e.jsx("dd",{className:"mono",children:(s==null?void 0:s.version)||"—"}),e.jsx("dt",{children:"Homepage"}),e.jsx("dd",{children:e.jsx("a",{href:(s==null?void 0:s.homepage)||"https://github.com/DrB0rk/BizarHarness",target:"_blank",rel:"noopener noreferrer",children:(s==null?void 0:s.homepage)||"https://github.com/DrB0rk/BizarHarness"})}),e.jsx("dt",{children:"License"}),e.jsx("dd",{children:(s==null?void 0:s.license)||"MIT"})]})]})}function Nl({about:s}){return e.jsxs(e.Fragment,{children:[e.jsx(bl,{}),e.jsx(kl,{about:s})]})}function wl({workspaceId:s,onInviteCreated:t}){const a=Ae(),[i,n]=r.useState(""),[c,o]=r.useState("editor"),[l,h]=r.useState([]),[x,u]=r.useState(!1),[d,m]=r.useState(!1),[p,g]=r.useState(null),[f,y]=r.useState(null);r.useEffect(()=>{S()},[s]);async function S(){u(!0);try{const C=await z.get(`/workspaces/${s}/invites`);h(C.invites||[])}catch{}finally{u(!1)}}async function k(C){if(C.preventDefault(),!!i.trim()){m(!0),y(null);try{const R=await z.post(`/workspaces/${s}/invites`,{email:i.trim(),role:c});n(""),await S(),t==null||t(),a.open({title:"Invite Link Created",children:e.jsxs("div",{className:"invite-link-dialog",children:[e.jsxs("p",{children:["Share this link with ",e.jsx("strong",{children:i})," to invite them as ",e.jsx("strong",{children:c}),":"]}),e.jsxs("div",{className:"invite-url-box",children:[e.jsx(Rn,{size:14}),e.jsx("input",{type:"text",readOnly:!0,value:R.url,onClick:j=>j.target.select()}),e.jsx("button",{type:"button",className:"invite-copy-btn",onClick:()=>{navigator.clipboard.writeText(R.url).catch(()=>{}),g(R.token),setTimeout(()=>g(null),2e3)},children:p===R.token?e.jsx(ns,{size:14}):e.jsx(ls,{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(R){y(R.message||"Failed to create invite")}finally{m(!1)}}}async function w(C){if(confirm("Revoke this invite?"))try{await z.del(`/workspaces/${s}/invites/${C}`),await S()}catch(R){y(R.message||"Failed to revoke invite")}}function E(C,R){navigator.clipboard.writeText(C).catch(()=>{}),g(R),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:k,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:C=>n(C.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:C=>o(C.target.value),children:[e.jsx("option",{value:"viewer",children:"Viewer"}),e.jsx("option",{value:"editor",children:"Editor"}),e.jsx("option",{value:"admin",children:"Admin"})]})]}),e.jsxs($,{type:"submit",variant:"primary",size:"sm",loading:d,disabled:!i.trim(),children:[e.jsx(Tn,{size:13}),"Invite"]})]}),f&&e.jsx("p",{className:"invite-error",children:f})]}),e.jsxs("div",{className:"invite-list",children:[e.jsx("h4",{className:"invite-list-title",children:"Pending Invites"}),x&&e.jsx("p",{className:"invite-loading",children:"Loading..."}),!x&&l.length===0&&e.jsx("p",{className:"invite-empty",children:"No pending invites"}),l.map(C=>e.jsxs("div",{className:"invite-item",children:[e.jsxs("div",{className:"invite-item-info",children:[e.jsx("span",{className:"invite-item-email",children:C.email}),e.jsx("span",{className:Y("invite-item-role",v[C.role]),children:C.role})]}),e.jsxs("div",{className:"invite-item-actions",children:[e.jsx("button",{type:"button",className:"invite-action-btn",title:"Copy invite link",onClick:()=>{const R=`${window.location.origin}/accept-invite?token=${C.token}`;E(R,C.token)},children:p===C.token?e.jsx(ns,{size:13}):e.jsx(ls,{size:13})}),e.jsx("button",{type:"button",className:"invite-action-btn invite-action-revoke",title:"Revoke invite",onClick:()=>w(C.token),children:e.jsx(we,{size:13})})]})]},C.token))]})]})}const Sl={admin:$n,editor:xa,viewer:Qe},Cl={admin:"role-admin",editor:"role-editor",viewer:"role-viewer"};function zl(){const[s,t]=r.useState([]),[a,i]=r.useState(!0),[n,c]=r.useState(!1),[o,l]=r.useState(""),[h,x]=r.useState(null),[u,d]=r.useState(null),m=Ae();r.useEffect(()=>{p()},[]);async function p(){i(!0);try{const S=await z.get("/workspaces");t(S.workspaces||[])}catch{x("Failed to load workspaces")}finally{i(!1)}}async function g(S){if(S.preventDefault(),!!o.trim()){c(!0);try{await z.post("/workspaces",{name:o.trim()}),l(""),await p()}catch(k){x(k.message||"Failed to create workspace")}finally{c(!1)}}}async function f(S,k){if(confirm(`Delete workspace "${k}"?`)&&confirm("This cannot be undone."))try{await z.del(`/workspaces/${S}`),await p()}catch(w){x(w.message||"Failed to delete workspace")}}function y(S){navigator.clipboard.writeText(`${window.location.origin}/accept-invite?workspace=${S}`).catch(()=>{}),d(S),setTimeout(()=>d(null),2e3)}return a?e.jsx("div",{className:"settings-section-loading",children:"Loading workspaces..."}):e.jsxs("div",{className:"settings-section settings-section-workspaces",children:[e.jsx("h3",{className:"settings-section-title",children:"Workspaces"}),e.jsx("p",{className:"settings-section-desc",children:"Workspaces let you share access with team members. Each workspace has its own members, settings, and data."}),h&&e.jsxs("div",{className:"settings-section-error",children:[e.jsx("span",{children:h}),e.jsx("button",{onClick:()=>x(null),children:"×"})]}),e.jsxs("form",{className:"workspace-create-form",onSubmit:g,children:[e.jsx("input",{type:"text",placeholder:"New workspace name",value:o,onChange:S=>l(S.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:S,role:k})=>{const w=Sl[k]||Qe;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(Qs,{size:16})}),e.jsxs("div",{className:"workspace-item-details",children:[e.jsx("span",{className:"workspace-item-name",children:S.name}),e.jsxs("span",{className:Y("workspace-item-role",Cl[k]),children:[e.jsx(w,{size:11}),k]})]})]}),e.jsxs("div",{className:"workspace-item-actions",children:[e.jsx($,{variant:"ghost",size:"sm",iconOnly:!0,title:"Copy invite link",onClick:()=>y(S.id),children:u===S.id?e.jsx(ns,{size:13}):e.jsx(ls,{size:13})}),k==="admin"&&e.jsx($,{variant:"ghost",size:"sm",iconOnly:!0,title:"Manage members",onClick:()=>{m.open({title:`Manage "${S.name}"`,children:e.jsx(wl,{workspaceId:S.id,onInviteCreated:()=>p()}),width:520})},children:e.jsx(Qs,{size:13})}),k==="admin"&&s.length>1&&e.jsx($,{variant:"ghost",size:"sm",iconOnly:!0,title:"Delete workspace",onClick:()=>f(S.id,S.name),children:e.jsx(we,{size:13})})]})]},S.id)})]})]})}function Tl({onError:s}){const t=re(),[a,i]=r.useState([]),[n,c]=r.useState(!1),[o,l]=r.useState(!1),[h,x]=r.useState(new Set),[u,d]=r.useState(null),[m,p]=r.useState(""),[g,f]=r.useState(!1),[y,S]=r.useState(""),[k,w]=r.useState(""),[E,v]=r.useState(!1),[C,R]=r.useState(""),[j,P]=r.useState(!1),[T,b]=r.useState(""),[A,O]=r.useState(new Set),N=r.useCallback(async()=>{c(!0);try{const I=await z.get("/env-vars");i(I)}catch(I){t.error(`Load failed: ${I.message}`),s==null||s(I.message)}finally{c(!1)}},[t,s]);r.useEffect(()=>{N()},[N]);const F=I=>{x(H=>{const Q=new Set(H);return Q.has(I)?Q.delete(I):Q.add(I),Q})},K=async()=>{const I=y.trim().toUpperCase(),H=k.trim();if(!I||!/^BIZAR_[A-Z0-9_]+$/.test(I)){t.warning("Name must match BIZAR_<NAME> (e.g. BIZAR_MINIMAX_KEY)");return}if(!H){t.warning("Value is required.");return}if(a.some(Q=>Q.name===I)){t.warning(`${I} already exists.`);return}l(!0);try{await z.post("/env-vars",{name:I,value:H}),t.success(`${I} created.`),f(!1),S(""),w(""),await N()}catch(Q){t.error(`Create failed: ${Q.message}`)}finally{l(!1)}},L=I=>{d(I.name),p(I.value===I.value.replace(/\*/g,"")?I.value:""),x(H=>{const Q=new Set(H);return Q.add(I.name),Q})},G=async I=>{if(!m.trim()){t.warning("Value cannot be empty.");return}l(!0);try{await z.put(`/env-vars/${encodeURIComponent(I)}`,{value:m.trim()}),t.success(`${I} updated.`),d(null),await N()}catch(H){t.error(`Update failed: ${H.message}`)}finally{l(!1)}},ne=async I=>{if(confirm(`Delete ${I}? This cannot be undone.`))try{await z.del(`/env-vars/${encodeURIComponent(I)}`),t.success(`${I} deleted.`),await N()}catch(H){t.error(`Delete failed: ${H.message}`)}},te=async()=>{if(!C.trim()){t.warning("Nothing to import.");return}P(!0);try{const I=await z.post("/env-vars/bulk-import",{envContent:C});t.success(`Imported ${I.imported}, skipped ${I.skipped}.`),I.errors.length>0&&t.warning(`${I.errors.length} lines had errors: ${I.errors.slice(0,3).join("; ")}${I.errors.length>3?"…":""}`),R(""),v(!1),await N()}catch(I){t.error(`Bulk import failed: ${I.message}`)}finally{P(!1)}},B=async()=>{try{const I=await z.get("/env-vars/export"),H=new Blob([I],{type:"text/plain"}),Q=URL.createObjectURL(H),le=document.createElement("a");le.href=Q,le.download=".env",le.click(),URL.revokeObjectURL(Q),t.success("Exported .env file.")}catch(I){t.error(`Export failed: ${I.message}`)}},V=r.useMemo(()=>{if(!T.trim())return a;const I=T.toLowerCase();return a.filter(H=>H.name.toLowerCase().includes(I))},[a,T]),X=r.useMemo(()=>{const I={};for(const H of V){const Q=H.name.split("_")[0]+"_";(I[Q]??(I[Q]=[])).push(H)}return I},[V]),U=I=>{O(H=>{const Q=new Set(H);return Q.has(I)?Q.delete(I):Q.add(I),Q})},J=r.useMemo(()=>{const I=["BIZAR_","PROVIDER_","MODEL_","API_"];return Object.keys(X).sort((Q,le)=>{const _=I.indexOf(Q),D=I.indexOf(le);return _===-1&&D===-1?Q.localeCompare(le):_===-1?1:D===-1?-1:_-D})},[X]);if(n)return e.jsx("div",{className:"muted",style:{padding:"16px 0",fontSize:13},children:"Loading env vars…"});const ye=J.length>1;return e.jsxs("div",{className:"env-var-manager",children:[e.jsxs("div",{className:"env-var-toolbar",children:[e.jsxs($,{variant:"primary",size:"sm",onClick:()=>f(!0),children:[e.jsx(ze,{size:12})," New variable"]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:()=>v(I=>!I),className:E?"active":"",children:[e.jsx(ja,{size:12})," Bulk import"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:B,title:"Export as .env",children:[e.jsx(qe,{size:12})," Export"]}),e.jsxs("div",{className:"env-var-search-wrap",children:[e.jsx(pe,{size:12,className:"env-var-search-icon"}),e.jsx("input",{className:"env-var-search input",placeholder:"Filter…",value:T,onChange:I=>b(I.target.value)})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:N,title:"Reload",children:e.jsx(ce,{size:12})})]}),E&&e.jsxs("div",{className:"env-var-bulk-panel",children:[e.jsxs("div",{className:"env-var-bulk-header",children:[e.jsxs("span",{children:["Paste ",e.jsx("code",{children:"KEY=value"})," lines (one per line):"]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>v(!1),children:e.jsx(ke,{size:12})})]}),e.jsx("textarea",{className:"input mono env-var-bulk-textarea",placeholder:`BIZAR_API_KEY=your-key-here
13
- PROVIDER_OPENAI_KEY=sk-...
14
- MODEL_KEY=gem-...`,value:C,onChange:I=>R(I.target.value),rows:6}),e.jsxs("div",{className:"env-var-bulk-footer",children:[e.jsx($,{variant:"primary",size:"sm",onClick:te,disabled:j||!C.trim(),children:j?"Importing…":"Import"}),e.jsx("span",{className:"muted",style:{fontSize:11},children:"Existing keys are skipped unless re-created individually. Invalid lines are reported."})]})]}),a.length===0&&!g&&e.jsxs("div",{className:"env-var-empty",children:[e.jsx(Ds,{size:20}),e.jsx("span",{children:"No BIZAR_* env vars yet."}),e.jsx("span",{style:{fontSize:11},children:"Create one to store API keys securely."})]}),g&&e.jsxs("div",{className:"env-var-add-form",children:[e.jsxs("div",{className:"env-var-add-row",children:[e.jsx("input",{className:"input mono",style:{width:240},placeholder:"BIZAR_NAME",value:y,onChange:I=>S(I.target.value.toUpperCase()),onKeyDown:I=>{I.key==="Enter"&&K(),I.key==="Escape"&&f(!1)},autoFocus:!0}),e.jsx("input",{className:"input mono",type:"password",placeholder:"value (API key, token, etc.)",value:k,onChange:I=>w(I.target.value),onKeyDown:I=>{I.key==="Enter"&&K(),I.key==="Escape"&&f(!1)}}),e.jsxs($,{variant:"primary",size:"sm",onClick:K,disabled:o,children:[e.jsx(Ts,{size:12})," Create"]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>{f(!1),S(""),w("")},children:e.jsx(ke,{size:12})})]}),e.jsxs("p",{style:{fontSize:11,color:"var(--text-dim)",margin:0},children:["Names must match ",e.jsxs("code",{children:["BIZAR_",e.jsx("var",{children:"NAME"})]})," (uppercase letters, digits, underscores)."]})]}),V.length>0&&(ye?e.jsx("div",{className:"env-var-groups",children:J.map(I=>{const H=X[I],Q=A.has(I);return e.jsxs("div",{className:"env-var-group",children:[e.jsxs("button",{type:"button",className:"env-var-group-header",onClick:()=>U(I),children:[Q?e.jsx(Ke,{size:12}):e.jsx(Oe,{size:12}),e.jsx("span",{className:"env-var-group-prefix mono",children:I}),e.jsxs("span",{className:"env-var-group-count muted",children:["(",H.length,")"]})]}),!Q&&e.jsx("div",{className:"env-var-list",children:H.map(le=>e.jsx(Gt,{v:le,editing:u,editValue:m,isRevealed:h.has(le.name),onToggleReveal:F,onStartEdit:L,onEditValueChange:p,onHandleUpdate:G,onCancelEdit:()=>d(null),onDelete:ne,saving:o},le.name))})]},I)})}):e.jsx("div",{className:"env-var-list",children:V.map(I=>e.jsx(Gt,{v:I,editing:u,editValue:m,isRevealed:h.has(I.name),onToggleReveal:F,onStartEdit:L,onEditValueChange:p,onHandleUpdate:G,onCancelEdit:()=>d(null),onDelete:ne,saving:o},I.name))})),V.length===0&&a.length>0&&e.jsxs("div",{className:"env-var-empty",children:[e.jsx(pe,{size:16}),e.jsxs("span",{children:['No env vars match "',T,'"']})]})]})}function Gt({v:s,editing:t,editValue:a,isRevealed:i,onToggleReveal:n,onStartEdit:c,onEditValueChange:o,onHandleUpdate:l,onCancelEdit:h,onDelete:x,saving:u}){const d=t===s.name;return e.jsxs("div",{className:Y("env-var-row",d&&"env-var-row-editing"),children:[e.jsx("span",{className:"env-var-name mono",children:s.name}),d?e.jsx("input",{className:"input mono",type:"password",style:{flex:1,minWidth:200},value:a,onChange:m=>o(m.target.value),onKeyDown:m=>{m.key==="Enter"&&l(s.name),m.key==="Escape"&&h()},autoFocus:!0}):e.jsx("span",{className:Y("env-var-value mono",!i&&"env-var-value-masked"),children:s.value}),e.jsx("span",{className:"env-var-source muted",children:s.source}),e.jsxs("div",{className:"env-var-actions",children:[!d&&e.jsx("button",{type:"button",className:"icon-btn",title:i?"Hide":"Reveal",onClick:()=>n(s.name),children:i?e.jsx(Xs,{size:12}):e.jsx(Qe,{size:12})}),d?e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"primary",size:"sm",onClick:()=>l(s.name),disabled:u,children:"Save"}),e.jsx($,{variant:"ghost",size:"sm",onClick:h,children:"Cancel"})]}):e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"icon-btn",title:"Edit",onClick:()=>c(s),children:e.jsx(fs,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger",title:"Delete",onClick:()=>x(s.name),children:e.jsx(we,{size:12})})]})]})]})}function Rl(){return e.jsxs(ee,{id:"settings-env-vars","data-section":"env-vars",children:[e.jsxs(ae,{children:[e.jsx(Ds,{size:14})," Environment Variables"]}),e.jsxs(ie,{children:["Manage BIZAR_* env vars (API keys, secrets). Values are stored in ",e.jsx("code",{children:"~/.config/bizar/env.json"})," (mode 0600)."]}),e.jsx(Tl,{})]})}const $l=[{id:"theme",label:"Theme"},{id:"updates",label:"Updates"},{id:"layout",label:"Layout"},{id:"general",label:"General"},{id:"env-vars",label:"Env Vars"},{id:"network",label:"Network"},{id:"notifications",label:"Notifications"},{id:"auth",label:"Auth"},{id:"agents",label:"Agents"},{id:"dashboard",label:"Dashboard"},{id:"background",label:"Background"},{id:"system-llm",label:"System LLM"},{id:"headroom",label:"Headroom"},{id:"activity-log",label:"Activity"},{id:"about",label:"About"},{id:"workspaces",label:"Workspaces"}],Al=[{id:"theme",label:"Theme",fields:[{key:"theme.presets",label:"Accent presets",section:"theme"},{key:"theme.accent",label:"Accent color",section:"theme"},{key:"theme.success",label:"Success color",section:"theme"},{key:"theme.warning",label:"Warning color",section:"theme"},{key:"theme.error",label:"Error color",section:"theme"},{key:"theme.info",label:"Info color",section:"theme"},{key:"theme.fontFamily",label:"Font family",section:"theme"},{key:"theme.fontSize",label:"Font size",section:"theme"},{key:"theme.compactMode",label:"Compact mode",section:"theme"},{key:"theme.animations",label:"Animations",section:"theme"}]},{id:"updates",label:"Updates",fields:[{key:"updates.channel",label:"Update channel",section:"updates"}]},{id:"layout",label:"Layout",fields:[{key:"ui.layout",label:"UI layout",section:"layout"},{key:"ui.showHeader",label:"Show header",section:"layout"},{key:"ui.showStatusBar",label:"Show status bar",section:"layout"},{key:"ui.defaultTab",label:"Default tab",section:"layout"}]},{id:"general",label:"General",fields:[{key:"defaultAgent",label:"Default agent",section:"general"},{key:"defaultModel",label:"Model override",section:"general"}]},{id:"env-vars",label:"Environment Variables",fields:[{key:"env-vars.count",label:"Env var count",section:"env-vars"}]},{id:"network",label:"Network",fields:[{key:"tailscale.enabled",label:"Tailscale Serve",section:"network"},{key:"tailscale.port",label:"Tailscale port",section:"network"},{key:"tailscale.https",label:"Tailscale HTTPS",section:"network"},{key:"tailscale.hostname",label:"Tailscale hostname",section:"network"}]},{id:"notifications",label:"Notifications",fields:[{key:"notifications.onAgentComplete",label:"Notify on agent complete",section:"notifications"},{key:"notifications.onPlanApproval",label:"Notify on plan approval",section:"notifications"}]},{id:"auth",label:"Auth",fields:[{key:"auth.enabled",label:"Auth enabled",section:"auth"},{key:"auth.loopback",label:"Loopback mode",section:"auth"},{key:"auth.token",label:"Auth token",section:"auth"}]},{id:"agents",label:"Agents",fields:[{key:"agents.maxParallel",label:"Max parallel agents",section:"agents"},{key:"agents.stuckThresholdMs",label:"Stuck threshold",section:"agents"},{key:"agents.autoRestart",label:"Auto restart",section:"agents"},{key:"workflow.artifactsEnabled",label:"Artifacts enabled",section:"agents"},{key:"workflow.agentsDecideAutonomously",label:"Autonomous decisions",section:"agents"}]},{id:"dashboard",label:"Dashboard",fields:[{key:"dashboard.autoLaunchWeb",label:"Auto-launch web",section:"dashboard"},{key:"dashboard.projectsDirectory",label:"Projects directory",section:"dashboard"},{key:"dashboard.allowedRoots",label:"Allowed roots",section:"dashboard"}]},{id:"background",label:"Background",fields:[{key:"service.enabled",label:"Background service",section:"background"},{key:"service.autostart",label:"Auto-start service",section:"background"}]},{id:"system-llm",label:"System LLM",fields:[{key:"systemLlm.enabled",label:"System LLM enabled",section:"system-llm"}]},{id:"headroom",label:"Headroom",fields:[{key:"headroom.enabled",label:"Headroom enabled",section:"headroom"},{key:"headroom.port",label:"Headroom port",section:"headroom"},{key:"headroom.budget",label:"Headroom budget",section:"headroom"},{key:"headroom.backend",label:"Headroom backend",section:"headroom"}]},{id:"activity-log",label:"Activity",fields:[{key:"activity.log",label:"Activity log",section:"activity-log"}]},{id:"about",label:"About",fields:[{key:"about.version",label:"Version",section:"about"},{key:"about.homepage",label:"Homepage",section:"about"},{key:"about.license",label:"License",section:"about"}]}];function Ml({settings:s,refreshSnapshot:t,settingsMode:a,settingsActiveSection:i,setSettingsActiveSection:n,setActiveTab:c}){const o=re(),[l,h]=r.useState(s),[x,u]=r.useState(!1),[d,m]=r.useState(!1),[p,g]=r.useState(null),[f,y]=r.useState({port:4321,https:!0,hostname:""}),[S,k]=r.useState(null),w=()=>{c("overview")};r.useEffect(()=>{h(s),u(!1),s.theme&&hs(s.theme)},[s]),r.useEffect(()=>{p&&y({port:p.settings.port,https:p.settings.https!==!1,hostname:p.settings.hostname||""})},[p]),r.useEffect(()=>{z.get("/tailscale/status").then(g).catch(()=>{})},[]);const E=r.useRef(null),v=r.useCallback(async(U,J)=>{h(he=>({...he,[U]:J})),E.current&&clearTimeout(E.current),E.current=setTimeout(async()=>{try{await z.put("/settings",{...l,[U]:J})}catch(he){console.error("autoSave failed",he)}},300)},[l]);r.useEffect(()=>()=>{E.current&&clearTimeout(E.current)},[]);const C=U=>{h(J=>{const he={...J,theme:{...J.theme,...U}};return hs(he.theme),he}),u(!0)},R=U=>{h(J=>({...J,ui:{...J.ui,...U}})),u(!0)},j=(U,J)=>{h(he=>({...he,[U]:J})),u(!0)},P=U=>{h(J=>({...J,notifications:{...J.notifications,...U}})),u(!0)},T=U=>{h(J=>({...J,agents:{...J.agents,...U}})),u(!0)},b=U=>{h(J=>({...J,dashboard:{...J.dashboard,...U}})),u(!0)},[A,O]=r.useState(()=>{if(typeof window>"u")return null;const U=window.location.hash.replace(/^#settings-/,"");return $l.some(J=>J.id===U)?U:null}),N=a?i??null:A,F=U=>{if(a)n==null||n(U);else{O(U);try{if(history.replaceState(null,"",U?`#settings-${U}`:window.location.pathname),U){const J=document.getElementById(`settings-${U}`);J&&J.scrollIntoView({behavior:"smooth",block:"start"})}else window.scrollTo({top:0,behavior:"smooth"})}catch{}}if(U){const J=document.getElementById(`settings-${U}`);J&&J.scrollIntoView({behavior:"smooth",block:"start"})}else window.scrollTo({top:0,behavior:"smooth"})},K=async()=>{try{p!=null&&p.settings.enabled?(await z.post("/tailscale/disable"),o.success("Tailscale serve disabled.")):(await z.post("/tailscale/enable",{port:f.port||4321,https:f.https,hostname:f.hostname||""}),o.success("Tailscale serve enabled.")),g(await z.get("/tailscale/status"))}catch(U){o.error(`Tailscale failed: ${U.message}`)}},L=async()=>{m(!0);try{const U=await z.put("/settings",l);h(U.data),u(!1),zs(U.data.theme),hs(U.data.theme),o.success("Settings saved."),await t()}catch(U){o.error(`Save failed: ${U.message}`)}finally{m(!1)}},G=async()=>{try{const U=await z.get("/settings");h(U.data),u(!1),zs(U.data.theme),hs(U.data.theme),o.info("Settings reloaded.",1500)}catch(U){o.error(`Reload failed: ${U.message}`)}},ne=async()=>{if(confirm("Reset all settings to defaults?"))try{const U=await z.post("/settings/reset");h(U.data),u(!1),zs(U.data.theme),hs(U.data.theme),o.success("Settings reset."),await t()}catch(U){o.error(`Reset failed: ${U.message}`)}},te={settings:l,patchTheme:C,patchUi:R,patchTop:j,patchNotifications:P,patchAgents:T,patchDashboard:b},B=l.about||{version:"3.0.4",homepage:"https://github.com/DrB0rk/BizarHarness",license:"MIT"},V=N===null,X=U=>N===U;return e.jsxs("div",{className:"view view-settings",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(Rt,{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:ne,children:[e.jsx(pa,{size:14})," Reset"]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:G,children:[e.jsx(ce,{size:14})," Reload"]}),e.jsxs($,{variant:"primary",size:"sm",disabled:!x||d,onClick:L,children:[d?e.jsx("span",{className:"btn-spinner"}):e.jsx(Ms,{size:14}),d?"Saving…":"Save"]})]})]}),a&&e.jsxs("div",{className:"settings-mode-banner",children:[e.jsx("span",{children:"You're in settings mode. All sections are visible in the sidebar."}),e.jsx($,{variant:"secondary",size:"sm",onClick:w,children:"← Back to main view"})]}),e.jsx(nl,{sections:Al,onJump:F}),e.jsxs("div",{className:Y("settings-grid",N&&"settings-grid-filtered"),"data-active-section":N||void 0,children:[(V||X("theme"))&&e.jsx(ol,{...te}),(V||X("updates"))&&e.jsx(cl,{}),(V||X("layout")||X("general"))&&e.jsx(ul,{...te,autoSave:v}),(V||X("env-vars"))&&e.jsx(Rl,{}),(V||X("network")||X("service")||X("tailscale"))&&e.jsx(hl,{tailscale:p,tailscaleDraft:f,setTailscaleDraft:y,onTailscaleToggle:K}),(V||X("notifications"))&&e.jsx(xl,{...te}),(V||X("auth"))&&e.jsx(pl,{settings:l,authStatus:S,setAuthStatus:k}),(V||X("agents")||X("dashboard")||X("background"))&&e.jsx(gl,{...te,autoSave:v}),(V||X("system-llm"))&&e.jsx(jl,{...te}),(V||X("headroom"))&&e.jsx(yl,{settings:l,setSettings:h,setDirty:u}),(V||X("activity-log")||X("about"))&&e.jsx(Nl,{about:B}),(V||X("workspaces"))&&e.jsx(zl,{})]})]})}const Yt=We.memo(Ml);function Il({snapshot:s,refreshSnapshot:t}){const a=re(),i=Ae(),[n,c]=r.useState(Array.isArray(s.mods)?s.mods:[]),[o,l]=r.useState(!0),[h,x]=r.useState(null),[u,d]=r.useState([]),[m,p]=r.useState(null),[g,f]=r.useState(!1),[y,S]=r.useState(null),[k,w]=r.useState(!1),[E,v]=r.useState({}),C=async()=>{var N,F,K;w(!0);try{const L=await z.get("/mods/registry");S({source:((N=L.registry)==null?void 0:N.source)||"",version:(F=L.registry)==null?void 0:F.version,updatedAt:(K=L.registry)==null?void 0:K.updatedAt,mods:L.mods||[]})}catch(L){S({source:"",mods:[],error:L.message})}finally{w(!1)}},R=async N=>{v(F=>({...F,[N]:!0}));try{const F=await z.post("/mods",{id:N});c(K=>[...K.filter(L=>L.id!==F.id),F]),a.success(`Mod "${F.id}" installed from registry.`),await t()}catch(F){a.error(`Install failed: ${F.message}`)}finally{v(F=>({...F,[N]:!1}))}},j=async(N,F=!1)=>{v(K=>({...K,[N]:!0}));try{const K=await z.post(`/mods/${encodeURIComponent(N)}/upgrade`,{backup:F});c(G=>[...G.filter(ne=>ne.id!==K.mod.id),K.mod]);const L=K.backupPath?` (backup at ${K.backupPath})`:"";a.success(`Mod "${N}" upgraded v${K.from} → v${K.to}${L}.`),await t()}catch(K){a.error(`Upgrade failed: ${K.message}`)}finally{v(K=>({...K,[N]:!1}))}},P=async()=>{try{const N=await z.get("/mods");c(N.mods||[]);try{const F=await z.get("/mods/views");d(F.views||[])}catch{d([])}}catch(N){a.error(`Mods load failed: ${N.message}`)}finally{l(!1)}};r.useEffect(()=>{P()},[]),r.useEffect(()=>{Array.isArray(s.mods)&&s.mods!==n&&c(s.mods)},[s.mods]);const T=()=>{let N=null;i.open({title:"Install mod",children:e.jsxs("div",{children:[e.jsxs("p",{className:"muted",children:["Provide the absolute path to a mod folder (one that contains a ",e.jsx("code",{children:"mod.json"}),"). The folder will be copied to"," ",e.jsx("code",{children:"~/.config/bizar/mods/<id>/"}),"."]}),e.jsx("label",{className:"field-label",htmlFor:"install-mod-path",children:"Path"}),e.jsx("input",{id:"install-mod-path",ref:F=>N=F,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 F=((N==null?void 0:N.value)||"").trim();if(!F){a.warning("Path is required.");return}try{const K=await z.post("/mods",{path:F});c(L=>[...L,K]),a.success(`Mod "${K.id}" installed.`),i.close(),await t()}catch(K){a.error(`Install failed: ${K.message}`)}},children:"Install"})]})})},b=async N=>{if(confirm(`Uninstall mod "${N}"? This removes the folder from ~/.config/bizar/mods/.`))try{await z.del(`/mods/${encodeURIComponent(N)}`),c(F=>F.filter(K=>K.id!==N)),h===N&&x(null),a.success("Mod uninstalled.")}catch(F){a.error(`Uninstall failed: ${F.message}`)}},A=async N=>{try{const F=await z.put(`/mods/${encodeURIComponent(N.id)}`,{enabled:!N.enabled});c(K=>K.map(L=>L.id===N.id?F:L)),a.success(`Mod ${F.enabled?"enabled":"disabled"}.`)}catch(F){a.error(`Toggle failed: ${F.message}`)}},O=n.find(N=>N.id===h)||null;return o?e.jsx("div",{className:"view-loading",children:e.jsx(me,{size:"lg"})}):e.jsxs("div",{className:"view view-mods",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(Gs,{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:P,children:[e.jsx(ce,{size:14})," Refresh"]}),e.jsxs($,{variant:"primary",size:"sm",onClick:T,children:[e.jsx(ze,{size:14})," Install mod"]})]})]}),n.length===0?e.jsx(Ne,{icon:e.jsx(Gs,{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(N=>e.jsxs("div",{className:Y("mod-list-item",h===N.id&&"mod-list-item-active"),onClick:()=>x(N.id),children:[e.jsxs("div",{className:"mod-list-item-head",children:[e.jsxs("div",{children:[e.jsx("div",{className:"mod-list-item-name",children:N.name}),e.jsxs("div",{className:"mod-list-item-meta",children:["v",N.version," · ",N.type," · ",N.author]})]}),e.jsxs("div",{className:"mod-list-item-actions",onClick:F=>F.stopPropagation(),children:[e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Toggle enabled",title:N.enabled?"Disable":"Enable",onClick:()=>A(N),children:e.jsx($t,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger","aria-label":"Uninstall",title:"Uninstall",onClick:()=>b(N.id),children:e.jsx(we,{size:12})})]})]}),e.jsx("div",{className:"mod-list-item-desc ellipsis-2",title:N.description,children:N.description}),e.jsx("div",{className:"mod-list-item-status",children:e.jsx("span",{className:`mod-mini-pill ${N.enabled?"mod-mini-pill-on":"mod-mini-pill-off"}`,children:N.enabled?"enabled":"disabled"})})]},N.id))}),O&&e.jsx(Ll,{mod:O})]}),e.jsxs(ee,{className:"mods-registry-card",children:[e.jsxs("button",{type:"button",className:"mods-registry-head","aria-expanded":g,"aria-controls":"mods-registry-body",onClick:()=>{!y&&!k&&C(),f(N=>!N)},children:[e.jsx(Is,{size:14,"aria-hidden":!0}),e.jsx("span",{className:"mods-registry-title",children:"Mod registry"}),e.jsx("span",{className:"muted",style:{fontSize:11},children:y!=null&&y.mods?`${y.mods.length} available`:"click to browse"}),e.jsx("span",{className:"mods-registry-spacer"}),g?e.jsx(Oe,{size:14,"aria-hidden":!0}):e.jsx(Ke,{size:14,"aria-hidden":!0})]}),g&&e.jsx("div",{id:"mods-registry-body",className:"mods-registry-body",children:k?e.jsx("div",{className:"muted",style:{padding:12,fontSize:12},children:"Loading registry…"}):y!=null&&y.error?e.jsxs("div",{className:"mods-registry-error",children:[e.jsx(Ls,{size:12})," Could not load registry: ",y.error]}):!y||y.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:[y.source&&e.jsxs("div",{className:"muted",style:{fontSize:11,marginBottom:8},children:["Source: ",e.jsx("code",{children:y.source})]}),e.jsx("div",{className:"mods-registry-grid",children:y.mods.map(N=>{const F=n.some(L=>L.id===N.id),K=!!E[N.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:N.name}),N.latest&&e.jsxs("span",{className:Y("mod-registry-version",N.upgradeAvailable&&"mod-registry-version-upgrade"),children:["v",N.latest,N.upgradeAvailable?" ↑":""]})]}),N.description&&e.jsx("div",{className:"mod-registry-card-desc",children:N.description}),e.jsxs("div",{className:"mod-registry-card-meta",children:[N.author&&e.jsxs("span",{className:"muted",children:["by ",N.author]}),N.homepage&&e.jsx("a",{href:N.homepage,target:"_blank",rel:"noopener noreferrer",className:"mod-registry-link",children:"homepage"})]}),(N.permissions||[]).length>0&&e.jsxs("div",{className:"mod-registry-perms",children:[e.jsx(Ls,{size:10}),(N.permissions||[]).slice(0,4).map(L=>e.jsx("span",{className:"mod-registry-perm",children:L},L)),(N.permissions||[]).length>4&&e.jsxs("span",{className:"mod-registry-perm-more",children:["+",N.permissions.length-4]})]}),e.jsxs("div",{className:"mod-registry-card-actions",children:[!F&&e.jsx($,{variant:"primary",size:"sm",disabled:K,onClick:()=>R(N.id),title:"Install from registry",children:K?e.jsx(me,{size:"sm"}):e.jsxs(e.Fragment,{children:[e.jsx(qe,{size:12})," Install"]})}),F&&N.upgradeAvailable&&e.jsx($,{variant:"primary",size:"sm",disabled:K,onClick:()=>j(N.id),title:`Upgrade from v${N.installedVersion||"?"} to v${N.upgradeAvailable}`,children:K?e.jsx(me,{size:"sm"}):e.jsxs(e.Fragment,{children:[e.jsx(qe,{size:12})," Upgrade to v",N.upgradeAvailable]})}),F&&!N.upgradeAvailable&&e.jsxs($,{variant:"ghost",size:"sm",disabled:!0,title:`Installed v${N.installedVersion||"?"}`,children:["Installed v",N.installedVersion||"?"]})]})]},N.id)})})]})})]}),u.length>0&&e.jsxs(ee,{className:"mod-views-hint",children:[e.jsxs(ae,{children:[e.jsx(Is,{size:14})," Mod views"]}),e.jsxs(ie,{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:()=>p(null),children:e.jsx(ke,{size:14})})]}),e.jsx("iframe",{src:m,className:"mod-iframe",title:"Mod view",sandbox:"allow-scripts allow-same-origin allow-forms allow-popups"})]})]})}function Ll({mod:s}){const t=re(),[a,i]=r.useState(null),[n,c]=r.useState(!1),[o,l]=r.useState(!1),[h,x]=r.useState(null),u=async()=>{c(!0);try{const m=await z.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 z.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(ee,{className:"mod-details",children:[e.jsxs(ae,{children:[e.jsx(Te,{size:14})," Mod details — ",s.name]}),e.jsx(ie,{children:e.jsx("code",{children:s.path})}),e.jsxs("dl",{className:"env-table",children:[e.jsx("dt",{children:"ID"}),e.jsx("dd",{className:"mono",children:s.id}),e.jsx("dt",{children:"Version"}),e.jsx("dd",{className:"mono",children:s.version}),e.jsx("dt",{children:"Type"}),e.jsx("dd",{className:"mono",children:s.type}),e.jsx("dt",{children:"Author"}),e.jsx("dd",{className:"mono",children:s.author||"—"}),e.jsx("dt",{children:"Bizar"}),e.jsx("dd",{className:"mono",children:s.bizar||"*"}),e.jsx("dt",{children:"Enabled"}),e.jsx("dd",{children:s.enabled?"yes":"no"}),e.jsx("dt",{children:"Permissions"}),e.jsxs("dd",{children:[(s.permissions||[]).map(m=>e.jsx("span",{className:"tag",children:m},m)),(s.permissions||[]).length===0&&e.jsx("span",{className:"muted",children:"(none)"})]})]}),e.jsxs("div",{className:"mod-files",children:[e.jsx("div",{className:"muted",children:"Files"}),e.jsx("ul",{children:(s.files||[]).map(m=>e.jsxs("li",{children:[e.jsx("span",{className:"mod-file-cat",children:m.category}),e.jsx("span",{className:"mono",children:m.path})]},m.path))})]}),e.jsxs("div",{className:"mod-instructions",children:[e.jsxs("button",{type:"button",className:"mod-instructions-head","aria-expanded":o,"aria-controls":`mod-instructions-body-${s.id}`,onClick:()=>{!a&&!n&&u(),l(m=>!m)},children:[e.jsx(An,{size:14,"aria-hidden":!0}),e.jsx("span",{children:"Installed instructions"}),e.jsx("span",{className:"muted",style:{fontSize:11},children:a?`${a.total} files`:"click to view"}),e.jsx("span",{className:"mod-instructions-spacer"}),o?e.jsx(Oe,{size:14,"aria-hidden":!0}):e.jsx(Ke,{size:14,"aria-hidden":!0})]}),o&&a&&e.jsxs("div",{id:`mod-instructions-body-${s.id}`,className:"mod-instructions-body",children:[a.agents.length>0&&e.jsxs("div",{className:"mod-instructions-section",children:[e.jsxs("div",{className:"mod-instructions-section-title",children:[e.jsx(Mn,{size:11})," Agents (",a.agents.length,")"]}),a.agents.map(m=>e.jsxs("div",{className:"mod-instructions-file",children:[e.jsxs("div",{className:"mod-instructions-file-head",onClick:()=>x(p=>p===m.filename?null:m.filename),children:[e.jsx("span",{className:"mono",children:m.filename}),e.jsxs("span",{className:"muted",style:{fontSize:10},children:["installed at ",m.fullPath]})]}),h===m.filename&&e.jsx("pre",{className:"mod-instructions-content",children:m.content||e.jsx("em",{className:"muted",children:"(file missing on disk)"})})]},m.filename))]}),a.commands.length>0&&e.jsxs("div",{className:"mod-instructions-section",children:[e.jsxs("div",{className:"mod-instructions-section-title",children:[e.jsx(ps,{size:11})," Commands (",a.commands.length,")"]}),a.commands.map(m=>e.jsxs("div",{className:"mod-instructions-file",children:[e.jsxs("div",{className:"mod-instructions-file-head",onClick:()=>x(p=>p===m.filename?null:m.filename),children:[e.jsx("span",{className:"mono",children:m.filename}),e.jsxs("span",{className:"muted",style:{fontSize:10},children:["installed at ",m.fullPath]})]}),h===m.filename&&e.jsx("pre",{className:"mod-instructions-content",children:m.content||e.jsx("em",{className:"muted",children:"(file missing on disk)"})})]},m.filename))]}),a.skills.length>0&&e.jsxs("div",{className:"mod-instructions-section",children:[e.jsxs("div",{className:"mod-instructions-section-title",children:[e.jsx(fa,{size:11})," Skills (",a.skills.length,")"]}),a.skills.map(m=>e.jsxs("div",{className:"mod-instructions-file",children:[e.jsxs("div",{className:"mod-instructions-file-head",onClick:()=>x(p=>p===m.name?null:m.name),children:[e.jsx("span",{className:"mono",children:m.name}),e.jsxs("span",{className:"muted",style:{fontSize:10},children:["installed at ",m.fullPath]})]}),h===m.name&&e.jsx("pre",{className:"mod-instructions-content",children:m.content||e.jsx("em",{className:"muted",children:"(file missing on disk)"})})]},m.name))]}),a.total===0&&e.jsxs("div",{className:"muted",style:{padding:8,fontSize:12},children:["This mod did not install any instruction files. Mods install instructions by shipping a top-level ",e.jsx("code",{children:"INSTRUCTIONS.md"}),", an ",e.jsx("code",{children:"agents/"})," directory, a ",e.jsx("code",{children:"commands/"})," directory, or a ",e.jsx("code",{children:"skills/"})," directory."]}),e.jsx("div",{className:"mod-instructions-actions",children:e.jsxs($,{variant:"ghost",size:"sm",onClick:d,children:[e.jsx(ce,{size:11})," Reinstall from mod folder"]})})]})]})]})}function El({viewId:s,reloadKey:t,setActiveTab:a}){const i=re(),[n,c]=r.useState(null),[o,l]=r.useState(!0),[h,x]=r.useState(0);if(r.useEffect(()=>{let u=!1;return(async()=>{try{const d=await z.get("/mods/views");if(u)return;const m=(d.views||[]).find(p=>p.id===s);c(m||null)}catch(d){i.error(`Failed to load mod view: ${d.message}`)}finally{u||l(!1)}})(),()=>{u=!0}},[s,i]),o)return e.jsx(Ne,{title:"Loading mod view…"});if(!n)return e.jsx(Ne,{title:"Mod view not found",message:`No view with id "${s}" is currently installed.`,action:e.jsx($,{onClick:()=>a("mods"),variant:"primary",size:"sm",children:"Open Mods"})});if(n.kind==="iframe"){const u=`/api/mods/${n.modId}/web/index.html?t=${h+(t||0)}`;return e.jsxs("div",{className:"mod-view-iframe-pane",children:[e.jsxs("div",{className:"mod-view-iframe-header",children:[e.jsxs("span",{className:"mod-view-iframe-label",children:[e.jsx(Is,{size:14}),n.label,e.jsxs("span",{className:"muted",style:{fontSize:11,fontWeight:400},children:["by ",n.modId]})]}),e.jsxs("div",{className:"mod-view-iframe-actions",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>x(d=>d+1),title:"Reload this view",children:[e.jsx(ce,{size:11})," Reload"]}),e.jsx("a",{href:u,target:"_blank",rel:"noopener noreferrer",className:"icon-btn",title:"Open in new tab",children:e.jsx(js,{size:12})})]})]}),e.jsx("iframe",{src:u,className:"mod-view-iframe",title:n.label},h+(t||0))]})}if(n.component){const u=n.component,d=n.modId,m=r.lazy(()=>na(()=>import(`/api/mods/${encodeURIComponent(d)}/views/${encodeURIComponent(u)}`),[]).then(p=>({default:p.default??(()=>null)})));return e.jsxs("div",{className:"mod-view-tab-pane",children:[e.jsx("div",{className:"mod-view-iframe-header",children:e.jsxs("span",{className:"mod-view-iframe-label",children:[e.jsx(Es,{size:14}),n.label,e.jsxs("span",{className:"muted",style:{fontSize:11,fontWeight:400},children:["by ",n.modId]})]})}),e.jsx("div",{className:"mod-view-tab-body",children:e.jsx(Dl,{modId:n.modId,component:n.component,children:e.jsx(r.Suspense,{fallback:e.jsxs("div",{style:{padding:24},children:[e.jsx(me,{size:"md"})," ",e.jsx("span",{className:"muted",children:"Loading mod view…"})]}),children:e.jsx(m,{})})})})]})}return e.jsxs(ee,{children:[e.jsxs(ae,{children:[e.jsx(Es,{size:14})," ",n.label]}),e.jsxs(ie,{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(be,{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(ee,{className:"schedule-template-card",children:[e.jsxs("div",{className:"schedule-template-header",children:[e.jsx(ae,{children:s.name}),s.tags&&s.tags.length>0&&e.jsx("div",{className:"schedule-template-tags",children:s.tags.map(a=>e.jsx("span",{className:"tag",children:a},a))})]}),e.jsx(ie,{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),children:"Use this template"})]})}const Ol=["interval","cron","once"],Bl=["command","agent","webhook"],St=[{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),Pt=Array.from({length:24},(s,t)=>({value:t,label:t===0?"12 AM":t<12?`${t} AM`:t===12?"12 PM":`${t-12} PM`})),Ft=[{value:"*",label:"Every day"},{value:"0",label:"Sunday"},{value:"1",label:"Monday"},{value:"2",label:"Tuesday"},{value:"3",label:"Wednesday"},{value:"4",label:"Thursday"},{value:"5",label:"Friday"},{value:"6",label:"Saturday"}],Aa=[{value:"s",label:"seconds"},{value:"m",label:"minutes"},{value:"h",label:"hours"},{value:"d",label:"days"}];function Ma(s){if(typeof s!="string")return null;const t=s.trim().split(/\s+/);if(t.length!==5)return null;const[a,i,,,n]=t,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"?Ma(s.schedule):null,a=s.type==="interval"?_l(s.schedule):null,i=s.timezone||"UTC",n=St.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"?Vl(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 Vl(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 Hl(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=Ft.find(u=>u.value===s.cronDow))==null?void 0:a.label)||"",l=((i=Pt.find(u=>u.value===s.cronHour))==null?void 0:i.label)||`${s.cronHour}`,h=String(s.cronMinute).padStart(2,"0"),x=o==="Every day"?`Every day at ${l.replace(" ","")} (min ${h})`:`Every ${o} at ${l.replace(" ","")} (min ${h})`;return{schedule:c,humanLabel:s.humanLabel||x}}if(s.type==="interval"){const c=((n=Aa.find(l=>l.value===s.intervalUnit))==null?void 0:n.label)||s.intervalUnit;return{schedule:`${s.intervalN}${s.intervalUnit}`,humanLabel:s.humanLabel||`Every ${s.intervalN} ${c}`}}return s.onceAt?{schedule:new Date(s.onceAt).toISOString(),humanLabel:s.humanLabel||new Date(s.onceAt).toLocaleString()}:{schedule:"",humanLabel:s.humanLabel||""}}function ql({snapshot:s,refreshSnapshot:t}){var E;const a=re(),i=Ae(),[n,c]=r.useState(s.schedules||[]),[o,l]=r.useState(!s.schedules),[h,x]=r.useState("schedules"),[u,d]=r.useState([]),[m,p]=r.useState(!1),g=async()=>{try{const v=await z.get("/projects/active/schedules");c(v.schedules||[])}catch(v){a.error(`Schedules load failed: ${v.message}`)}finally{l(!1)}},f=async()=>{p(!0);try{const v=await z.get("/schedules/templates");d(v.templates||[])}catch(v){a.error(`Templates load failed: ${v.message}`)}finally{p(!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(()=>{h==="templates"&&u.length===0&&f()},[h]);const y=v=>{i.open({title:v?`Edit schedule: ${v.name}`:"New schedule",width:640,children:e.jsx(Kl,{initial:v,onClose:i.close,onSubmitted:async C=>{c(R=>{const j=R.findIndex(T=>T.id===C.id);if(j===-1)return[...R,C];const P=R.slice();return P[j]=C,P}),a.success(v?"Schedule updated.":"Schedule created."),i.close(),await t()},onError:C=>a.error(C)})})},S=async v=>{var C;try{const R=await z.post(`/schedules/${encodeURIComponent(v.id)}/run`);a.success(R.ok?"Schedule ran.":`Run failed: ${((C=R.runResult)==null?void 0:C.error)||"unknown"}`),await g()}catch(R){a.error(`Run failed: ${R.message}`)}},k=async v=>{if(confirm(`Delete schedule "${v.name}"?`))try{await z.del(`/schedules/${encodeURIComponent(v.id)}`),c(C=>C.filter(R=>R.id!==v.id)),a.success("Schedule deleted.")}catch(C){a.error(`Delete failed: ${C.message}`)}},w=async v=>{try{const C=await z.post("/schedules/from-template",{templateId:v.id});c(R=>[...R,C]),x("schedules"),a.success(`Schedule "${C.name}" created from template.`),await t()}catch(C){a.error(`Failed to create schedule: ${C.message}`)}};return o?e.jsx("div",{className:"view-loading",children:e.jsx(me,{size:"lg"})}):e.jsxs("div",{className:"view view-schedules",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("div",{className:"view-title-row",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx($s,{size:18})," Schedules"]}),e.jsxs("div",{className:"view-section-tabs",children:[e.jsxs("button",{type:"button",className:`tab-btn ${h==="schedules"?"tab-btn-active":""}`,onClick:()=>x("schedules"),children:["Schedules (",n.length,")"]}),e.jsxs("button",{type:"button",className:`tab-btn ${h==="templates"?"tab-btn-active":""}`,onClick:()=>x("templates"),children:[e.jsx(Es,{size:14})," Templates"]})]})]}),e.jsx("p",{className:"view-subtitle",children:h==="schedules"?e.jsxs(e.Fragment,{children:["Recurring tasks for ",e.jsx("strong",{children:((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:[h==="schedules"&&e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"secondary",size:"sm",onClick:g,children:[e.jsx(ce,{size:14})," Refresh"]}),e.jsxs($,{variant:"primary",size:"sm",onClick:()=>y(),children:[e.jsx(ze,{size:14})," New schedule"]})]}),h==="templates"&&e.jsxs($,{variant:"secondary",size:"sm",onClick:f,disabled:m,children:[e.jsx(ce,{size:14})," Refresh"]})]})]}),h==="templates"?m?e.jsx("div",{className:"view-loading",children:e.jsx(me,{size:"lg"})}):u.length===0?e.jsx(Ne,{icon:e.jsx(Es,{size:32}),title:"No templates",message:"No schedule templates found. Templates are loaded from templates/schedules/."}):e.jsx("div",{className:"schedule-template-grid",children:u.map(v=>e.jsx(Fl,{template:v,onUse:w},v.id))}):n.length===0?e.jsx(Ne,{icon:e.jsx($s,{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 C;return e.jsxs(ee,{className:"schedule-card",children:[e.jsxs("div",{className:"schedule-card-head",children:[e.jsxs("div",{children:[e.jsx(ae,{children:v.name}),e.jsxs(ie,{children:[e.jsx("code",{children:v.type})," ·"," ",e.jsx("span",{title:v.schedule,children:Gl(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:()=>y(v),children:[e.jsx(fs,{size:12})," Edit"]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:()=>S(v),children:[e.jsx(bt,{size:12})," Run now"]}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger","aria-label":"Delete",title:"Delete",onClick:()=>k(v),children:e.jsx(we,{size:12})})]})]}),e.jsxs("div",{className:"schedule-card-action",children:[e.jsx("span",{className:"muted",children:"action:"})," ",e.jsxs("code",{children:[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]})]}),((C=v.budgetCheck)==null?void 0:C.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 ${Xt(v.lastResult)}`,children:v.lastResult}),v.lastError&&e.jsxs("span",{className:"muted schedule-card-error",title:v.lastError,children:[" ","— ",Qt(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(As,{size:12})," ",v.history.length," run",v.history.length===1?"":"s"]}),e.jsx("ul",{children:v.history.slice(-10).reverse().map((R,j)=>e.jsxs("li",{children:[e.jsx("span",{className:"tabular-nums muted",children:Ce(R.ts)})," ",e.jsx("span",{className:`tag ${Xt(R.result)}`,children:R.result}),R.error&&e.jsxs("span",{className:"muted",children:[" — ",Qt(R.error,80)]})]},j))})]})]},v.id)})})]})}function Kl({initial:s,onClose:t,onSubmitted:a,onError:i}){const[n,c]=r.useState(()=>Wl(s)),[o,l]=r.useState(!1),h=r.useMemo(()=>St.some(d=>d.value===n.timezone)?n.timezone:"Other…",[n.timezone]),x=(d,m)=>{c(p=>({...p,[d]:m}))},u=async d=>{d.preventDefault();const m=n.name.trim();if(!m){i("Name is required.");return}const p=Hl(n);if(!p.schedule){i("Schedule value is required.");return}if(!n.actionTarget.trim()){i("Action target is required.");return}const g=n.timezone==="Other…"?n.customTimezone.trim():n.timezone,f={type:n.actionType,target:n.actionTarget.trim()};n.actionType==="agent"&&n.actionPrompt.trim()&&(f.prompt=n.actionPrompt.trim());const y={name:m,type:n.type,schedule:p.schedule,timezone:g||"UTC",action:f,budgetCheck:{maxConcurrent:n.maxConcurrent,skipIfBudgetLow:n.skipIfBudgetLow},enabled:n.enabled};l(!0);try{const S=s?await z.put(`/schedules/${encodeURIComponent(s.id)}`,y):await z.post("/schedules",y);await a(S)}catch(S){i(`${s?"Update":"Create"} failed: ${S.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=>x("name",d.target.value),autoFocus:!0}),e.jsx("div",{className:"task-form-row",children:e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-type",children:"Type"}),e.jsx("select",{id:"schedule-type",className:"select",value:n.type,onChange:d=>x("type",d.target.value),children: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=>x("cronDow",d.target.value),children:Ft.map(d=>e.jsx("option",{value:d.value,children:d.label},d.value))})]}),e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-hour",children:"Hour"}),e.jsx("select",{id:"schedule-hour",className:"select",value:String(n.cronHour),onChange:d=>x("cronHour",parseInt(d.target.value,10)),children:Pt.map(d=>e.jsx("option",{value:String(d.value),children:d.label},d.value))})]}),e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-minute",children:"Minute"}),e.jsx("select",{id:"schedule-minute",className:"select",value:String(n.cronMinute),onChange:d=>x("cronMinute",parseInt(d.target.value,10)),children: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=>x("rawCron",d.target.value),placeholder:"0 13 * * 0"})]}),e.jsxs("button",{type:"button",className:"link-btn",onClick:()=>x("showAdvanced",!n.showAdvanced),"aria-expanded":n.showAdvanced,children:[e.jsx(Oe,{size:12,style:{transform:n.showAdvanced?"rotate(180deg)":"none",transition:"transform 0.15s"}}),n.showAdvanced?"Hide advanced":"Advanced (raw cron)"]})]}),n.type==="interval"&&e.jsxs("div",{className:"task-form-row",children:[e.jsxs("div",{className:"task-form-field",style:{flex:1},children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-interval-n",children:"Every"}),e.jsx("input",{id:"schedule-interval-n",className:"input",type:"number",min:1,value:n.intervalN,onChange:d=>x("intervalN",parseInt(d.target.value,10)||1)})]}),e.jsxs("div",{className:"task-form-field",style:{flex:1},children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-interval-unit",children:"Unit"}),e.jsx("select",{id:"schedule-interval-unit",className:"select",value:n.intervalUnit,onChange:d=>x("intervalUnit",d.target.value),children:Aa.map(d=>e.jsx("option",{value:d.value,children:d.label},d.value))})]})]}),n.type==="once"&&e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-once-at",children:"Run at"}),e.jsx("input",{id:"schedule-once-at",className:"input",type:"datetime-local",value:n.onceAt,onChange:d=>x("onceAt",d.target.value)})]}),e.jsxs("div",{className:"task-form-row",children:[e.jsxs("div",{className:"task-form-field",style:{flex:1},children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-timezone",children:"Timezone"}),e.jsxs("select",{id:"schedule-timezone",className:"select",value:h,onChange:d=>x("timezone",d.target.value),children:[St.map(d=>e.jsx("option",{value:d.value,children:d.label},d.value)),e.jsx("option",{value:"Other…",children:"Other…"})]})]}),n.timezone==="Other…"&&e.jsxs("div",{className:"task-form-field",style:{flex:1},children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-custom-tz",children:"IANA name"}),e.jsx("input",{id:"schedule-custom-tz",className:"input",type:"text",placeholder:"Europe/Paris",value:n.customTimezone,onChange:d=>x("customTimezone",d.target.value)})]})]}),e.jsxs("div",{className:"task-form-row",children:[e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-action-type",children:"Action"}),e.jsx("select",{id:"schedule-action-type",className:"select",value:n.actionType,onChange:d=>x("actionType",d.target.value),children: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=>x("actionTarget",d.target.value)})]})]}),n.actionType==="agent"&&e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-action-prompt",children:"Prompt (what to send the agent)"}),e.jsx("textarea",{id:"schedule-action-prompt",className:"input",rows:3,placeholder:"Review open PRs for stale code review comments and nudge reviewers.",value:n.actionPrompt,onChange:d=>x("actionPrompt",d.target.value)})]}),e.jsxs("fieldset",{className:"schedule-budget-card",children:[e.jsx("legend",{children:"Budget pre-flight"}),e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{id:"schedule-skip-budget",type:"checkbox",checked:n.skipIfBudgetLow,onChange:d=>x("skipIfBudgetLow",d.target.checked)}),e.jsx("span",{children:"Skip this run when too many background tasks are already running."})]}),e.jsxs("div",{className:"task-form-field",children:[e.jsx("label",{className:"field-label",htmlFor:"schedule-max-concurrent",children:"Max concurrent bg tasks"}),e.jsx("input",{id:"schedule-max-concurrent",className:"input",type:"number",min:1,max:64,value:n.maxConcurrent,onChange:d=>x("maxConcurrent",parseInt(d.target.value,10)||6),disabled:!n.skipIfBudgetLow})]})]}),e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{id:"schedule-enabled",type:"checkbox",checked:n.enabled,onChange:d=>x("enabled",d.target.checked)}),e.jsx("span",{children:"Enabled"})]}),e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx($,{variant:"ghost",type:"button",onClick:t,disabled:o,children:"Cancel"}),e.jsx($,{variant:"primary",type:"submit",disabled:o,children:s?"Save":"Create"})]})]})}function Gl(s){var c,o;if(s.type!=="cron")return s.schedule;const t=Ma(s.schedule);if(!t)return s.schedule;const a=((c=Ft.find(l=>l.value===t.dow))==null?void 0:c.label)||"",i=((o=Pt.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 Xt(s){return s==="success"?"tag-success":s==="skipped"?"tag-warning":"tag-error"}function Qt(s,t){return s.length<=t?s:s.slice(0,t-1)+"…"}const Xl=[{id:"all",label:"All",icon:Ve},{id:"shipped",label:"Shipped",icon:Mt},{id:"user",label:"User",icon:Qs},{id:"project",label:"Project",icon:Fe}],qs={shipped:"Shipped",user:"User",project:"Project"},Ql={shipped:Mt,user:Qs,project:Fe};function Jl({snapshot:s,refreshSnapshot:t}){const a=re(),i=Ae(),[n,c]=r.useState([]),[o,l]=r.useState({shipped:0,user:0,project:0,all:0}),[h,x]=r.useState(!0),[u,d]=r.useState("all"),[m,p]=r.useState(""),[g,f]=r.useState(null),[y,S]=r.useState(!1),k=async()=>{var C,R,j;x(!0);try{const P=await z.get("/skills");c(P.skills||[]),l({shipped:((C=P.counts)==null?void 0:C.shipped)??0,user:((R=P.counts)==null?void 0:R.user)??0,project:((j=P.counts)==null?void 0:j.project)??0,all:(P.skills||[]).length})}catch(P){a.error(`Skills load failed: ${P.message}`)}finally{x(!1)}};r.useEffect(()=>{k()},[]),r.useEffect(()=>{if(!m.trim()){f(null);return}S(!0);const C=setTimeout(async()=>{try{const R=await z.get(`/skills/search?q=${encodeURIComponent(m.trim())}`);f(R.results||[])}catch(R){a.error(`Search failed: ${R.message}`)}finally{S(!1)}},280);return()=>clearTimeout(C)},[m]);const w=r.useMemo(()=>g!==null?g:u==="all"?n:n.filter(C=>C.source===u),[n,u,g]),E=async()=>{try{await z.post("/skills/refresh",{}),a.success("Skills refreshed."),await k()}catch(C){a.error(`Refresh failed: ${C.message}`)}},v=async C=>{try{const R=await z.get(`/skills/${encodeURIComponent(C.source)}/${encodeURIComponent(C.name)}`);i.open({title:R.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":R.source,children:qs[R.source]||R.source}),e.jsx("code",{className:"mono text-sm muted",children:R.path})]}),R.description&&e.jsx("p",{className:"skill-detail-desc",children:R.description}),R.body&&e.jsx("div",{className:"skill-detail-body",children:e.jsx("pre",{className:"skill-body-pre",children:R.body})})]}),footer:e.jsx($,{variant:"ghost",onClick:()=>i.close(),children:"Close"})})}catch{i.open({title:C.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":C.source,children:qs[C.source]||C.source}),e.jsx("code",{className:"mono text-sm muted",children:C.path})]}),C.description&&e.jsx("p",{className:"skill-detail-desc",children:C.description})]}),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(Ve,{size:18})," Skills"]}),e.jsx("p",{className:"view-subtitle",children:"Browse all available skills — shipped, user, and project-local."})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs("div",{className:"search-input",children:[e.jsx(pe,{size:14,"aria-hidden":!0}),e.jsx("label",{htmlFor:"skills-search",className:"sr-only",children:"Search skills"}),e.jsx("input",{id:"skills-search",className:"input",type:"text",placeholder:"Search skills…",value:m,onChange:C=>p(C.target.value),"aria-label":"Search skills"}),m&&e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Clear search",onClick:()=>p(""),children:e.jsx(as,{size:12})})]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:E,children:[e.jsx(ce,{size:14})," Refresh"]})]})]}),!m.trim()&&e.jsx("div",{className:"skills-tabs",children:Xl.map(C=>{const R=C.icon,j=C.id==="all"?o.all:o[C.id]??0;return e.jsxs("button",{type:"button",className:Y("skills-tab",u===C.id&&"skills-tab-active"),onClick:()=>d(C.id),children:[e.jsx(R,{size:14}),e.jsx("span",{children:C.label}),e.jsx("span",{className:"skills-tab-count",children:j})]},C.id)})}),m.trim()&&e.jsxs("section",{className:"skills-section",children:[e.jsxs("h3",{className:"skills-section-title",children:[e.jsx(pe,{size:14})," Search results",y&&e.jsx(me,{size:"sm"})]}),y?e.jsx("div",{className:"skills-grid",children:[0,1,2].map(C=>e.jsx("div",{className:"skill-card skill-card-skeleton"},C))}):g&&g.length===0?e.jsx(Ne,{icon:e.jsx(pe,{size:28}),title:"No matches",message:`No skills match "${m}".`}):e.jsx("div",{className:"skills-grid",children:(g||[]).map((C,R)=>e.jsx(Jt,{skill:C,onShow:()=>v(C),searchQ:m},`search-${R}`))})]}),!m.trim()&&e.jsx("section",{className:"skills-section",children:h?e.jsx("div",{className:"view-loading",children:e.jsx(me,{size:"lg"})}):w.length===0?e.jsx(Ne,{icon:e.jsx(fa,{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 ${qs[u]} tab.`}):e.jsx("div",{className:"skills-grid",children:w.map((C,R)=>e.jsx(Jt,{skill:C,onShow:()=>v(C)},`${C.source}-${C.name}-${R}`))})}),!m.trim()&&e.jsx("footer",{className:"view-footer",children:e.jsxs("span",{className:"text-sm muted",children:["Skills are discovered from"," ",e.jsx("code",{children:"~/.opencode/skills/"}),","," ",e.jsx("code",{children:"~/.agents/skills/"}),","," ",e.jsx("code",{children:"bizar-dash/skills/"}),", and project-local directories."]})})]})}function Jt({skill:s,onShow:t,searchQ:a=""}){const i=Ql[s.source]||Mt,n=s.description?s.description.length>200?s.description.slice(0,200)+"…":s.description:"No description.";return e.jsxs(ee,{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:qs[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(js,{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=We.memo(Jl);function so({refreshKey:s,onRefresh:t,setActiveSubPanel:a}){const i=re(),[n,c]=r.useState(null),[o,l]=r.useState(!0),h=async g=>{l(!0);try{const[f,y,S,k]=await Promise.all([z.get("/memory/health",g).catch(()=>null),z.get("/memory/status",g).catch(()=>null),z.get("/memory/lightrag/stats",g).catch(()=>null),z.get("/memory/storage",g).catch(()=>null)]);c({health:f||{score:0,status:"unconfigured",checks:[],message:"memory not initialised"},vault:{exists:!!(y!=null&&y.initialized),vaultRoot:(y==null?void 0:y.vaultRoot)||"",mode:(y==null?void 0:y.mode)||"local-only",noteCount:(y==null?void 0:y.noteCount)||0,totalSize:(k==null?void 0:k.total)||0,folderCount:0,folders:[],lastModified:null,gitClean:(y==null?void 0:y.gitClean)??null,gitBranch:(y==null?void 0:y.branch)||null},lightrag:S||{running:!1,pid:null,host:"127.0.0.1",port:9621,indexedApprox:0,queryCountLast24h:0,lastReindexAt:null},storage:k||{total:0,breakdown:[]}})}catch(f){i.error(`Memory overview failed: ${f.message}`)}finally{l(!1)}};if(r.useEffect(()=>{const g=new AbortController;return h(g.signal),()=>g.abort()},[s]),o&&!n)return e.jsxs("div",{className:"view-loading",children:[e.jsx(me,{size:"lg"}),e.jsx("p",{children:"Loading memory overview…"})]});if(!n)return e.jsx("div",{className:"muted",children:"No memory data available."});const{health:x,vault:u,lightrag:d,storage:m}=n,p=x.score>=80?"var(--success)":x.score>=50?"var(--warning)":"var(--error)";return e.jsxs("div",{className:"memory-overview",children:[e.jsxs(ee,{variant:"elevated",className:"memory-health-hero",children:[e.jsxs("div",{className:"memory-health-score",style:{borderColor:p},children:[e.jsx("span",{className:"memory-health-score-value",style:{color:p},children:x.score}),e.jsx("span",{className:"memory-health-score-label",children:"/ 100"})]}),e.jsxs("div",{className:"memory-health-meta",children:[e.jsxs("h3",{className:"memory-health-title",children:[e.jsx($e,{size:16}),"Memory health ·"," ",e.jsx("span",{style:{color:p},children:x.status})]}),e.jsx("p",{className:"memory-health-message",children:x.message}),e.jsxs($,{variant:"ghost",size:"sm",onClick:t,children:[e.jsx(ce,{size:12})," Refresh"]})]})]}),e.jsxs("div",{className:"memory-source-pills",children:[e.jsxs("button",{type:"button",className:"memory-source-pill",onClick:()=>a("lightrag"),children:[e.jsx(Pe,{size:14}),e.jsx("span",{children:"LightRAG"}),e.jsx("span",{className:Y("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(Te,{size:14}),e.jsx("span",{children:"Obsidian Vault"}),e.jsxs("span",{className:Y("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:Y("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(pe,{size:14}),e.jsx("span",{children:"Semantic Search"}),e.jsx("span",{className:"memory-source-pill-status na",children:"cross-source"})]})]}),e.jsxs("div",{className:"memory-stat-grid",children:[e.jsx(us,{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(us,{icon:e.jsx(Te,{size:16}),label:"Obsidian",value:`${u.noteCount} notes`,sub:u.folderCount>0?`${u.folderCount} folders`:"no folders yet",onClick:()=>a("obsidian")}),e.jsx(us,{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(us,{icon:e.jsx(va,{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(us,{icon:e.jsx(Ve,{size:16}),label:"Last reindex",value:d.lastReindexAt?Ze(d.lastReindexAt):"never",sub:"lightrag ingest",onClick:()=>a("lightrag")}),e.jsx(us,{icon:e.jsx(Ls,{size:16}),label:"Health",value:`${x.score}/100`,sub:x.status,onClick:()=>a("config")})]}),x.checks.length>0&&e.jsxs(ee,{children:[e.jsx(ae,{children:"Health checks"}),e.jsx(ie,{children:"Composite score across all memory subsystems"}),e.jsx("ul",{className:"memory-check-list",children:x.checks.map(g=>e.jsxs("li",{className:"memory-check-row",children:[e.jsx("span",{className:"memory-check-icon",children:g.pass?e.jsx(_e,{size:14,style:{color:"var(--success)"}}):g.name.includes("secrets")||g.name.includes("schema")?e.jsx(be,{size:14,style:{color:"var(--warning)"}}):e.jsx(as,{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 us({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:Y("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([]),[h,x]=r.useState(!0),[u,d]=r.useState(null),[m,p]=r.useState(""),[g,f]=r.useState(null),y=async()=>{x(!0);try{const[j,P,T]=await Promise.all([z.get("/memory/lightrag/stats").catch(()=>null),z.get("/memory/config").then(b=>(b==null?void 0:b.lightrag)||null).catch(()=>null),z.get("/memory/lightrag/log").catch(()=>({lines:[]}))]);i(j),c(P),l((T==null?void 0:T.lines)||[])}catch(j){t.error(`LightRAG status failed: ${j.message}`)}finally{x(!1)}};r.useEffect(()=>{y()},[s]);const S=async(j,P,T)=>{d(j);try{await P(),t.success(T),await y()}catch(b){t.error(`${j} failed: ${b.message}`)}finally{d(null)}},k=()=>S("start",()=>z.post("/memory/lightrag/start",{}),"LightRAG starting…"),w=()=>S("stop",()=>z.post("/memory/lightrag/stop",{}),"LightRAG stopping…"),E=async()=>{d("restart");try{await z.post("/memory/lightrag/stop",{}).catch(()=>{}),await new Promise(j=>setTimeout(j,600)),await z.post("/memory/lightrag/start",{}),t.success("LightRAG restarted."),await y()}catch(j){t.error(`Restart failed: ${j.message}`)}finally{d(null)}},v=()=>S("reindex",()=>z.post("/memory/lightrag/reindex",{}),"Reindex complete."),C=()=>S("rebuild",()=>z.post("/memory/lightrag/rebuild-graph",{}),"Graph rebuilt."),R=async()=>{var j,P,T;if(m.trim()){d("query");try{const b=await z.get(`/memory/query?q=${encodeURIComponent(m)}&topK=8`),A=(j=b==null?void 0:b.semantic)!=null&&j.response?typeof b.semantic.response=="string"?b.semantic.response:JSON.stringify(b.semantic.response):((P=b==null?void 0:b.semantic)==null?void 0:P.error)||"No response";f({ok:!!((T=b==null?void 0:b.semantic)!=null&&T.ok),text:A})}catch(b){f({ok:!1,text:b.message})}finally{d(null)}}};return h&&!a?e.jsxs("div",{className:"view-loading",children:[e.jsx(me,{size:"lg"}),e.jsx("p",{children:"Loading LightRAG status…"})]}):a?e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(ee,{variant:"elevated",children:[e.jsxs(ae,{children:[e.jsx(Pe,{size:14}),"LightRAG",e.jsx("span",{className:Y("memory-source-pill-status",a.running?"on":"off"),children:a.running?"running":"stopped"})]}),e.jsx(ie,{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:k,disabled:!!u||a.running,children:[u==="start"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(vs,{size:12}),"Start"]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:w,disabled:!!u||!a.running,children:[u==="stop"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(In,{size:12}),"Stop"]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:E,disabled:!!u,children:[u==="restart"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx($t,{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(ce,{size:12}),"Reindex all"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:C,disabled:!!u,title:"Wipe working dir + reindex from scratch",children:[u==="rebuild"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(at,{size:12}),"Rebuild graph"]})]})]}),e.jsxs("div",{className:"memory-stat-grid",children:[e.jsx(Ns,{icon:e.jsx(va,{size:14}),label:"Indexed chunks (approx)",value:String(a.indexedApprox)}),e.jsx(Ns,{icon:e.jsx(no,{n:a.noteCount}),label:"Notes in vault",value:String(a.noteCount)}),e.jsx(Ns,{icon:e.jsx(tt,{size:14}),label:"Queries last 24h",value:String(a.queryCountLast24h)}),e.jsx(Ns,{icon:e.jsx(Ve,{size:14}),label:"Avg response",value:a.avgResponseMs!==null?`${a.avgResponseMs} ms`:"—"}),e.jsx(Ns,{icon:a.lastReindexOk?e.jsx(_e,{size:14}):a.lastReindexOk===!1?e.jsx(as,{size:14}):e.jsx(ce,{size:14}),label:"Last reindex",value:a.lastReindexAt?Ze(a.lastReindexAt):"never",sub:a.lastReindexInserted!==null?`${a.lastReindexInserted} inserted${a.lastReindexFailed?`, ${a.lastReindexFailed} failed`:""}`:void 0})]}),e.jsxs(ee,{children:[e.jsxs(ae,{children:[e.jsx(pe,{size:14})," Quick search"]}),e.jsx(ie,{children:"Send a natural-language query to the LightRAG index."}),e.jsxs("div",{className:"memory-search-row",children:[e.jsx("label",{htmlFor:"lightrag-query",className:"sr-only",children:"Search LightRAG"}),e.jsx("input",{id:"lightrag-query",type:"text",className:"input",placeholder:"e.g. how does the memory service write notes?",value:m,onChange:j=>p(j.target.value),onKeyDown:j=>{j.key==="Enter"&&R()},disabled:u==="query","aria-label":"Search LightRAG"}),e.jsxs($,{variant:"primary",onClick:R,disabled:u==="query"||!m.trim(),children:[u==="query"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(pe,{size:12}),"Query"]})]}),g&&e.jsx("div",{className:Y("memory-query-result",g.ok?"ok":"err"),children:e.jsx("pre",{className:"mono text-sm",children:g.text})})]}),n&&e.jsxs(ee,{children:[e.jsx(ae,{children:"Configuration"}),e.jsxs(ie,{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(ee,{children:[e.jsxs(ae,{children:[e.jsx(ce,{size:14})," Server log (tail)"]}),e.jsxs(ie,{children:["Last ",o.length," lines from ",e.jsx("code",{children:"lightrag.log"})]}),e.jsx("pre",{className:"memory-log-tail mono text-xs",children:o.join(`
15
- `)})]})]}):e.jsx("div",{className:"muted",children:"No LightRAG data available."})}function Ns({icon:s,label:t,value:a,sub:i}){return e.jsxs("div",{className:"memory-stat-card",children:[e.jsx("div",{className:"memory-stat-icon",children:s}),e.jsxs("div",{className:"memory-stat-body",children:[e.jsx("div",{className:"memory-stat-label",children:t}),e.jsx("div",{className:"memory-stat-value",children:a}),i&&e.jsx("div",{className:"memory-stat-sub muted",children:i})]})]})}function no({n:s}){return e.jsxs("span",{style:{position:"relative",display:"inline-block"},children:[e.jsx(pe,{size:14}),e.jsx("span",{className:"memory-mini-badge",children:s})]})}function io({refreshKey:s}){const t=re(),a=Ae(),[i,n]=r.useState([]),[c,o]=r.useState(null),[l,h]=r.useState(!0),[x,u]=r.useState(""),[d,m]=r.useState(null),[p,g]=r.useState(!1),[f,y]=r.useState(null),[S,k]=r.useState([]),w=async()=>{var T;h(!0);try{const[b,A]=await Promise.all([z.get("/memory/notes").catch(()=>({notes:[]})),z.get("/memory/obsidian/tree").catch(()=>({tree:null}))]);n(b.notes||[]),o(A.tree),f&&!((T=b.notes)!=null&&T.find(O=>O.relPath===f))&&(y(null),k([]))}catch(b){t.error(`Vault load failed: ${b.message}`)}finally{h(!1)}};r.useEffect(()=>{w()},[s]),r.useEffect(()=>{if(!x.trim()){m(null);return}g(!0);const T=setTimeout(async()=>{try{const b=await z.get(`/memory/search?q=${encodeURIComponent(x)}&limit=50`),A=new Set((b.results||[]).map(O=>O.relPath));m(i.filter(O=>A.has(O.relPath)))}catch(b){t.error(`Search failed: ${b.message}`)}finally{g(!1)}},240);return()=>clearTimeout(T)},[x,i,t]);const E=async T=>{y(T);try{const b=await z.get(`/memory/obsidian/backlinks?note=${encodeURIComponent(T)}`);k(b.backlinks||[])}catch{k([])}},v=()=>{a.open({title:"New note",width:720,children:e.jsx(Zt,{mode:"create",onSave:async(T,b,A)=>{try{await z.post("/memory/notes",{path:T,frontmatter:b,body:A}),t.success(`Created ${T}.`),a.close(),await w(),E(T)}catch(O){t.error(`Create failed: ${O.message}`)}},onCancel:()=>a.close()})})},C=async T=>{try{const b=await z.get(`/memory/notes/${T.split("/").map(encodeURIComponent).join("/")}`);a.open({title:`Edit ${T}`,width:720,children:e.jsx(Zt,{mode:"edit",initial:{relPath:b.relPath,frontmatter:b.frontmatter,body:b.body},onSave:async(A,O,N)=>{try{await z.put(`/memory/notes/${A.split("/").map(encodeURIComponent).join("/")}`,{frontmatter:O,body:N}),t.success(`Saved ${A}.`),a.close(),await w(),E(A)}catch(F){t.error(`Save failed: ${F.message}`)}},onCancel:()=>a.close()})})}catch(b){t.error(`Load failed: ${b.message}`)}},R=async T=>{if(confirm(`Delete ${T}? This cannot be undone.`))try{await z.del(`/memory/notes/${T.split("/").map(encodeURIComponent).join("/")}`),t.success(`Deleted ${T}.`),f===T&&y(null),await w()}catch(b){t.error(`Delete failed: ${b.message}`)}},j=r.useMemo(()=>[...i].sort((T,b)=>b.mtime-T.mtime),[i]),P=d??j;return l&&!i.length?e.jsxs("div",{className:"view-loading",children:[e.jsx(me,{size:"lg"}),e.jsx("p",{children:"Loading vault…"})]}):e.jsxs("div",{className:"memory-panel-content memory-obsidian-grid",children:[e.jsxs(ee,{variant:"outlined",className:"memory-tree-card",children:[e.jsxs(ae,{children:[e.jsx(Fe,{size:14})," Folders"]}),e.jsx(ie,{children:c?`${Ea(c)} folder(s)`:"no vault"}),e.jsx("div",{className:"memory-tree-body",children:c?e.jsx(La,{node:c,depth:0,onSelect:E,selected:f}):null})]}),e.jsxs("div",{className:"memory-obsidian-list-col",children:[e.jsxs("div",{className:"memory-list-toolbar",children:[e.jsxs("div",{className:"search-input",children:[e.jsx(pe,{size:14,"aria-hidden":!0}),e.jsx("label",{htmlFor:"obsidian-search",className:"sr-only",children:"Search notes"}),e.jsx("input",{id:"obsidian-search",type:"text",className:"input",placeholder:"Search notes…",value:x,onChange:T=>u(T.target.value),"aria-label":"Search notes"}),x&&e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>u(""),"aria-label":"Clear search",children:e.jsx(ke,{size:12})})]}),e.jsxs($,{variant:"primary",size:"sm",onClick:v,children:[e.jsx(Ln,{size:12})," New note"]}),e.jsx($,{variant:"ghost",size:"sm",onClick:w,title:"Refresh",children:e.jsx(ce,{size:12})})]}),p&&e.jsx("div",{className:"muted text-sm",children:"Searching…"}),P.length===0?e.jsx(Ne,{icon:e.jsx(Te,{size:28}),title:"No notes",message:i.length===0?'No notes in this vault yet. Click "New note" to create one.':`No notes match "${x}".`}):e.jsx("ul",{className:"memory-note-list",children:P.map(T=>e.jsxs("li",{className:Y("memory-note-card",f===T.relPath&&"memory-note-card-active"),children:[e.jsxs("button",{type:"button",className:"memory-note-card-main",onClick:()=>E(T.relPath),children:[e.jsxs("div",{className:"memory-note-card-title",children:[e.jsx(Te,{size:12}),e.jsx("span",{children:Ia(T)})]}),e.jsxs("div",{className:"memory-note-card-meta",children:[e.jsx("code",{className:"muted",children:T.relPath}),e.jsxs("span",{className:"muted",children:["· ",Ce(T.mtime)]}),!T.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:()=>C(T.relPath),"aria-label":`Edit ${T.relPath}`,title:"Edit",children:e.jsx(fs,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>R(T.relPath),"aria-label":`Delete ${T.relPath}`,title:"Delete",children:e.jsx(we,{size:12})})]})]},T.relPath))})]}),e.jsx("div",{className:"memory-obsidian-detail-col",children:f?e.jsx(ro,{relPath:f,onClose:()=>y(null)}):e.jsx(Ne,{icon:e.jsx(Te,{size:28}),title:"Pick a note",message:"Select a note from the list to view its content, frontmatter, and backlinks."})})]})}function Ia(s){var a;const t=(a=s.frontmatter)==null?void 0:a.title;return typeof t=="string"&&t.trim()?t:s.relPath.replace(/\.md$/i,"")}function La({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:Y("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(Te,{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(Oe,{size:11}):e.jsx(Ke,{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(La,{node:o,depth:t+1,onSelect:a,selected:i},`${o.path}-${l}`))})]})}function Ea(s){return s.type==="note"?0:1+(s.children||[]).reduce((t,a)=>t+Ea(a),0)}function 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[p,g]=await Promise.all([z.get(`/memory/notes/${s.split("/").map(encodeURIComponent).join("/")}`),z.get(`/memory/obsidian/backlinks?note=${encodeURIComponent(s)}`)]);if(m)return;i(p),c(g.backlinks||[])}catch{m||i(null)}finally{m||l(!1)}})(),()=>{m=!0}},[s]),o)return e.jsx("div",{className:"view-loading",children:e.jsx(me,{size:"sm"})});if(!a)return e.jsx("div",{className:"muted",children:"Note not found."});const h=Array.isArray((u=a.frontmatter)==null?void 0:u.tags)?a.frontmatter.tags:[],x=Array.isArray((d=a.frontmatter)==null?void 0:d.links)?a.frontmatter.links:[];return e.jsxs("div",{className:"memory-note-detail",children:[e.jsxs("div",{className:"memory-note-detail-head",children:[e.jsx("h3",{children:Ia(a)}),e.jsx("button",{type:"button",className:"icon-btn",onClick:t,"aria-label":"Close",children:e.jsx(ke,{size:12})})]}),e.jsxs("div",{className:"memory-note-detail-meta",children:[e.jsx("code",{children:s}),e.jsxs("span",{className:"muted",children:["· modified ",Ze(a.mtime)]})]}),h.length>0&&e.jsx("div",{className:"memory-tag-row",children:h.map((m,p)=>e.jsx("span",{className:"memory-tag",children:String(m)},p))}),e.jsx("pre",{className:"memory-note-body mono text-sm",children:a.body}),n.length>0&&e.jsxs("div",{className:"memory-backlinks",children:[e.jsx("h4",{children:"Backlinks"}),e.jsx("ul",{children:n.map(m=>e.jsxs("li",{children:[e.jsx("code",{children:m.fromRelPath}),e.jsx("p",{className:"muted text-sm",children:m.snippet})]},m.fromRelPath))})]}),x.length>0&&e.jsxs("div",{className:"memory-backlinks",children:[e.jsx("h4",{children:"Forward links"}),e.jsx("ul",{children:x.map((m,p)=>e.jsx("li",{children:e.jsx("code",{children:String(m)})},p))})]})]})}function Zt({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: ""
16
- tags: []
17
- `),[h,x]=r.useState((t==null?void 0:t.body)||""),[u,d]=r.useState(!1),m=re(),p=async()=>{if(!n.endsWith(".md")){m.error("Path must end in .md");return}let g;try{g=oo(o)||{}}catch(f){m.error(`Frontmatter parse failed: ${f.message}`);return}d(!0);try{await a(n,g,h)}finally{d(!1)}};return e.jsxs("div",{className:"memory-editor-modal",children:[e.jsx("label",{className:"field-label",htmlFor:"obsidian-note-path",children:"Path"}),e.jsx("input",{id:"obsidian-note-path",type:"text",className:"input mono",value:n,onChange:g=>c(g.target.value),disabled:s==="edit",placeholder:"notes/example.md"}),e.jsx("label",{className:"field-label",htmlFor:"obsidian-note-frontmatter",style:{marginTop:12},children:"Frontmatter (YAML)"}),e.jsx("textarea",{id:"obsidian-note-frontmatter",className:"memory-editor-textarea mono text-sm",rows:6,value:o,onChange:g=>l(g.target.value),"aria-label":"Frontmatter YAML"}),e.jsx("label",{className:"field-label",htmlFor:"obsidian-note-body",style:{marginTop:12},children:"Body (Markdown)"}),e.jsx("textarea",{id:"obsidian-note-body",className:"memory-editor-textarea mono text-sm",rows:14,value:h,onChange:g=>x(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:p,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(` - ${xt(n)}`)}else if(typeof i=="object"){t.push(`${a}:`);for(const[n,c]of Object.entries(i))t.push(` ${n}: ${xt(c)}`)}else t.push(`${a}: ${xt(i)}`);return t.join(`
18
- `)}function xt(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 h={},x=[];let u=!1,d=!1;for(;i+1<a.length;){const m=a[i+1];if(!m.startsWith(" "))break;if(m.startsWith(" - "))u=!0,x.push(pt(m.slice(4))),i++;else{d=!0;const p=m.match(/^ ([A-Za-z_][\w-]*):\s*(.*)$/);p&&(h[p[1]]=pt(p[2])),i++}}t[o]=u&&!d?x:d?h:{}}else t[o]=pt(l);i++}return t}function pt(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 w,E,v,C;const t=re(),[a,i]=r.useState(null),[n,c]=r.useState(null),[o,l]=r.useState(!0),[h,x]=r.useState(null),[u,d]=r.useState(null),m=async()=>{var R;l(!0);try{const[j,P,T]=await Promise.all([z.get("/memory/git/status").catch(()=>null),z.get("/memory/git/diff").catch(()=>null),z.get("/memory/config/global").catch(()=>null)]);i(j),c(P),d(((R=T==null?void 0:T.config)==null?void 0:R.git)||null)}catch(j){t.error(`Git status failed: ${j.message}`)}finally{l(!1)}};r.useEffect(()=>{m()},[s]);const p=async(R,j,P)=>{x(R);try{await j(),t.success(P),await m()}catch(T){t.error(`${R} failed: ${T.message}`)}finally{x(null)}},g=()=>p("pull",()=>z.post("/memory/git/pull",{}),"Pull complete."),f=()=>p("push",()=>z.post("/memory/git/push",{}),"Push complete."),y=()=>{const R=prompt("Commit message:",`[memory-sync] ${new Date().toISOString().slice(0,10)} vault sync`);R&&p("commit",()=>z.post("/memory/git/commit",{message:R}),"Committed.")},S=()=>p("fetch",()=>z.post("/memory/git/sync",{push:!1}),"Fetch complete.");if(o&&!a)return e.jsxs("div",{className:"view-loading",children:[e.jsx(me,{size:"lg"}),e.jsx("p",{children:"Loading git status…"})]});if(!a)return e.jsx("div",{className:"muted",children:"No git data available."});const k=a.mode==="local-only";return e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(ee,{variant:"elevated",children:[e.jsxs(ae,{children:[e.jsx(is,{size:14})," Git sync",k?e.jsx("span",{className:"memory-source-pill-status na",children:"local-only"}):e.jsx("span",{className:Y("memory-source-pill-status",a.clean?"on":"warn"),children:a.clean?"clean":"dirty"})]}),e.jsx(ie,{children:k?"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]})}),!k&&e.jsxs("div",{className:"memory-git-status-row",children:[e.jsx(ws,{ok:a.clean??!1,label:"Working tree"}),e.jsx(ws,{ok:(a.ahead??0)===0,label:`Ahead: ${a.ahead??0}`}),e.jsx(ws,{ok:(a.behind??0)===0,label:`Behind: ${a.behind??0}`}),e.jsx(ws,{ok:(((w=a.modified)==null?void 0:w.length)??0)===0,label:`Modified: ${((E=a.modified)==null?void 0:E.length)??0}`}),e.jsx(ws,{ok:(((v=a.untracked)==null?void 0:v.length)??0)===0,label:`Untracked: ${((C=a.untracked)==null?void 0:C.length)??0}`})]}),e.jsxs("div",{className:"memory-action-row",children:[e.jsxs($,{variant:"secondary",size:"sm",onClick:g,disabled:!!h||k,children:[h==="pull"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(da,{size:12}),"Pull"]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:f,disabled:!!h||k,children:[h==="push"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(At,{size:12}),"Push"]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:y,disabled:!!h||k,children:[h==="commit"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(ya,{size:12}),"Commit"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:S,disabled:!!h||k,children:[h==="fetch"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(En,{size:12}),"Fetch + sync"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:m,disabled:!!h,children:[e.jsx(ce,{size:12})," Refresh"]})]})]}),u&&e.jsxs(ee,{children:[e.jsxs(ae,{children:[e.jsx(Dn,{size:14})," Repository"]}),e.jsxs(ie,{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(ee,{children:[e.jsxs(ae,{children:[e.jsx(Pn,{size:14})," Working-tree diff"]}),e.jsx(ie,{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(R=>e.jsx("li",{children:e.jsx("code",{children:R})},R))}),n&&n.lines.length>1&&e.jsx("pre",{className:"memory-log-tail mono text-xs",children:n.lines.slice(0,400).join(`
19
- `)})]})]})}function ws({ok:s,label:t}){return e.jsxs("span",{className:Y("memory-git-status-pill",s?"ok":"warn"),children:[s?e.jsx(_e,{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),[h,x]=r.useState(!1),[u,d]=r.useState(""),m=async g=>{if(g.trim()){x(!0),d(g);try{const f=[...n.lightrag?["lightrag"]:[],...n.obsidian?["obsidian"]:[]],y=await z.post("/memory/semantic-search",{query:g,limit:20,sources:f});l(y.results||[])}catch(f){t.error(`Search failed: ${f.message}`),l([])}finally{x(!1)}}};r.useEffect(()=>{u&&m(u)},[n]),r.useEffect(()=>{u&&m(u)},[s]);const p=r.useMemo(()=>{const g=(o||[]).filter(y=>y.source==="obsidian"),f=(o||[]).filter(y=>y.source==="lightrag");return{obs:g,lr:f}},[o]);return e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(ee,{variant:"elevated",children:[e.jsxs(ae,{children:[e.jsx(pe,{size:14})," Semantic search"]}),e.jsx(ie,{children:"Query both LightRAG (graph-based) and the Obsidian vault in one shot."}),e.jsxs("div",{className:"memory-search-row",children:[e.jsx("label",{htmlFor:"semantic-search-input",className:"sr-only",children:"Semantic search"}),e.jsx("input",{id:"semantic-search-input",type:"text",className:"input",placeholder:"e.g. how are notes indexed?",value:a,onChange:g=>i(g.target.value),onKeyDown:g=>{g.key==="Enter"&&m(a)},disabled:h,"aria-label":"Semantic search query"}),e.jsxs($,{variant:"primary",onClick:()=>m(a),disabled:h||!a.trim(),children:[h?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(pe,{size:12}),"Search"]})]}),e.jsxs("div",{className:"memory-source-toggle-row",children:[e.jsx(ea,{active:n.obsidian,onToggle:()=>c(g=>({...g,obsidian:!g.obsidian})),label:"Obsidian",icon:e.jsx(Te,{size:11})}),e.jsx(ea,{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(ke,{size:12})})]})]}),h&&e.jsx("div",{className:"view-loading",children:e.jsx(me,{size:"md"})}),!h&&o&&o.length===0&&e.jsx(Ne,{icon:e.jsx(pe,{size:28}),title:"No matches",message:`Nothing in scope matched "${u}".`}),p.obs.length>0&&e.jsxs(ee,{children:[e.jsxs(ae,{children:[e.jsx(Te,{size:14})," Obsidian (",p.obs.length,")"]}),e.jsx("ul",{className:"memory-search-result-list",children:p.obs.map((g,f)=>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-${f}`))})]}),p.lr.length>0&&e.jsxs(ee,{children:[e.jsxs(ae,{children:[e.jsx(Pe,{size:14})," LightRAG (",p.lr.length,")"]}),e.jsx("div",{className:"memory-search-result-list",children:p.lr.map((g,f)=>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-${f}`))})]})]})}function ea({active:s,onToggle:t,label:a,icon:i}){return e.jsxs("button",{type:"button",className:Y("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),[h,x]=r.useState(""),[u]=r.useState(""),[d,m]=r.useState(null),[p,g]=r.useState(null),[f,y]=r.useState(null),[S,k]=r.useState(!1),w=async()=>{var j,P;c(!0);try{const T=await z.get("/memory/config/global");i(T.config),x(((P=(j=T.config)==null?void 0:j.git)==null?void 0:P.remoteUrl)||""),await E()}catch(T){t.error(`Config load failed: ${T.message}`)}finally{c(!1)}},E=async()=>{try{const j=await z.get("/memory/git/status");j.ok&&m({clean:j.clean,branch:j.branch,modified:j.modified,untracked:j.untracked})}catch{}};r.useEffect(()=>{w()},[s]);const v=async()=>{if(a){l(!0);try{await z.put("/memory/config/global",{git:{remoteUrl:h}}),t.success("Config saved.")}catch(j){t.error(`Save failed: ${j.message}`)}finally{l(!1)}}},C=async j=>{g(j);try{if(j==="pull"){const P=await z.post("/memory/git/pull",{});P.ok?t.success("Pull successful."):t.error(`Pull failed: ${P.output||"unknown error"}`)}else if(j==="push")(await z.post("/memory/git/push",{})).ok?t.success("Push successful."):t.error("Push failed.");else if(j==="commit"){const P=await z.post("/memory/git/commit",{});P.ok?t.success(`Committed: ${P.message}`):t.error("Commit failed.")}await E()}catch(P){t.error(`${j} failed: ${P.message}`)}finally{g(null)}},R=async()=>{k(!0);try{const j=await z.post("/memory/test-git",{});y(j.checks)}catch(j){t.error(`Test failed: ${j.message}`)}finally{k(!1)}};return n&&!a?e.jsxs("div",{className:"view-loading",children:[e.jsx(me,{size:"md"}),e.jsx("p",{children:"Loading config…"})]}):a?e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(ee,{children:[e.jsxs(ae,{children:[e.jsx(is,{size:14})," Git sync"]}),e.jsx(ie,{children:"Configure the git remote and sync your memory vault."}),e.jsxs("div",{className:"memory-config-form",children:[e.jsx(gt,{label:"Vault path",inline:!0,children:e.jsx("span",{className:"memory-vault-path mono muted",children:u||"(loading…)"})}),e.jsx(gt,{label:"Remote URL",children:e.jsx("input",{type:"text",className:"input mono",value:h,onChange:j=>x(j.target.value),placeholder:"git@github.com:org/repo.git"})}),d&&e.jsxs(gt,{label:"Status",inline:!0,children:[e.jsx("span",{className:Y("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:()=>C("pull"),disabled:p!==null,children:[p==="pull"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(qe,{size:12}),"Pull"]}),e.jsxs($,{variant:"secondary",onClick:()=>C("commit"),disabled:p!==null,children:[p==="commit"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(ya,{size:12}),"Commit"]}),e.jsxs($,{variant:"secondary",onClick:()=>C("push"),disabled:p!==null,children:[p==="push"?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(ja,{size:12}),"Push"]})]})]}),e.jsxs(ee,{children:[e.jsxs(ae,{children:[e.jsx(yt,{size:14})," Connection tests"]}),e.jsx(ie,{children:"Verify the configured git remote is reachable."}),e.jsxs("div",{className:"memory-action-row",children:[e.jsxs($,{variant:"secondary",onClick:R,disabled:S,children:[S?e.jsx(xe,{size:12,className:"memory-spin"}):e.jsx(yt,{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(Ms,{size:12}),"Save config"]})]}),f&&f.length>0&&e.jsx("ul",{className:"memory-check-list",style:{marginTop:12},children:f.map((j,P)=>e.jsxs("li",{className:"memory-check-row",children:[e.jsx("span",{className:"memory-check-icon",children:e.jsx("span",{className:Y("memory-pill",j.pass?"memory-pill-ok":"memory-pill-warn"),children:j.pass?"OK":"FAIL"})}),e.jsx("span",{className:"memory-check-name",children:j.name}),e.jsx("span",{className:"memory-check-detail muted",children:j.detail})]},P))})]})]}):e.jsx("div",{className:"muted",children:"No config available."})}function gt({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 Ye=800,sa=60,jt={default:"#8b5cf6",note:"#8b5cf6",entity:"#34d399",concept:"#fbbf24",root:"#f87171"};function ho(s,t){return jt[s]||jt[t]||jt.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,h)=>{const x=h/s.length*Math.PI*2,u=Ye*.28;return{...l,x:Ye/2+u*Math.cos(x)+(Math.random()-.5)*40,y:Ye/2+u*Math.sin(x)+(Math.random()-.5)*40,vx:0,vy:0}}),n=new Map;for(const l of i)n.set(l.id,l);for(let l=0;l<sa;l++){const h=1-l/sa;for(let d=0;d<i.length;d++)for(let m=d+1;m<i.length;m++){const p=i[d],g=i[m],f=g.x-p.x,y=g.y-p.y,S=Math.sqrt(f*f+y*y)||1,k=400*h/(S*S),w=f/S*k,E=y/S*k;p.vx-=w,p.vy-=E,g.vx+=w,g.vy+=E}for(const d of t){const m=n.get(d.source),p=n.get(d.target);if(!m||!p)continue;const g=p.x-m.x,f=p.y-m.y,y=Math.sqrt(g*g+f*f)||1,k=(y-80)*.08*h,w=g/y*k,E=f/y*k;m.vx+=w,m.vy+=E,p.vx-=w,p.vy-=E}const x=Ye/2,u=Ye/2;for(const d of i)d.vx+=(x-d.x)*.01*h,d.vy+=(u-d.y)*.01*h;for(const d of i)d.vx*=.85,d.vy*=.85,d.x+=d.vx,d.y+=d.vy,d.x=Math.max(20,Math.min(Ye-20,d.x)),d.y=Math.max(20,Math.min(Ye-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}),h=r.useRef(null),[x,u]=r.useState(null),[d,m]=r.useState(null),p=r.useMemo(()=>po(s.nodes,s.edges),[s.nodes,s.edges]),g=r.useMemo(()=>{const j=new Map;for(const P of p)j.set(P.id,P);return j},[p]),f=r.useCallback(j=>{j.target.closest(".memory-graph-node")||(o.current=!0,l.current={x:j.clientX,y:j.clientY,tx:n.x,ty:n.y})},[n]),y=r.useCallback(j=>{if(!o.current)return;const P=j.clientX-l.current.x,T=j.clientY-l.current.y;c(b=>({...b,x:l.current.tx+P,y:l.current.ty+T}))},[]),S=r.useCallback(()=>{o.current=!1},[]),k=r.useCallback(j=>{j.preventDefault();const P=j.deltaY<0?1.1:.9,T=i.current;if(!T)return;const b=T.getBoundingClientRect(),A=j.clientX-b.left,O=j.clientY-b.top;c(N=>{const F=Math.max(.2,Math.min(4,N.scale*P)),K=F/N.scale;return{x:A-(A-N.x)*K,y:O-(O-N.y)*K,scale:F}})},[]),w=r.useCallback(j=>{const P=Array.from(j.touches);if(P.length===2){const[T,b]=P;h.current=Math.hypot(b.clientX-T.clientX,b.clientY-T.clientY)}else P.length===1&&(o.current=!0,l.current={x:P[0].clientX,y:P[0].clientY,tx:n.x,ty:n.y})},[n]),E=r.useCallback(j=>{const P=Array.from(j.touches);if(P.length===2&&h.current!==null){const[T,b]=P,A=Math.hypot(b.clientX-T.clientX,b.clientY-T.clientY),O=A/h.current;h.current=A,c(N=>({...N,scale:Math.max(.2,Math.min(4,N.scale*O))}))}else if(P.length===1&&o.current){const T=P[0].clientX-l.current.x,b=P[0].clientY-l.current.y;c(A=>({...A,x:l.current.tx+T,y:l.current.ty+b}))}},[]),v=r.useCallback(()=>{o.current=!1,h.current=null},[]),C=r.useCallback(j=>{u(j.id===x?null:j.id),t==null||t(j)},[x,t]),R=Math.max(.5,1/Math.log2(n.scale+1));return e.jsx("svg",{ref:i,className:Y("memory-graph-canvas",a),viewBox:`0 0 ${Ye} ${Ye}`,style:{width:"100%",height:"100%",minHeight:400,cursor:o.current?"grabbing":"grab"},onMouseDown:f,onMouseMove:y,onMouseUp:S,onMouseLeave:S,onWheel:k,onTouchStart:w,onTouchMove:E,onTouchEnd:v,children:e.jsxs("g",{transform:`translate(${n.x},${n.y}) scale(${n.scale})`,children:[s.edges.map((j,P)=>{const T=g.get(j.source),b=g.get(j.target);if(!T||!b)return null;const A=d===j.source||d===j.target||x===j.source||x===j.target;return e.jsx("line",{x1:T.x,y1:T.y,x2:b.x,y2:b.y,stroke:A?"#8b5cf6":"#2d3648",strokeWidth:A?R*2:R,strokeOpacity:A?.9:.5},`e-${P}`)}),p.map(j=>{const P=xo(j),T=ho(j.group,j.type),b=x===j.id,A=d===j.id;return e.jsxs("g",{className:"memory-graph-node",transform:`translate(${j.x},${j.y})`,onClick:()=>C(j),onMouseEnter:()=>m(j.id),onMouseLeave:()=>m(null),style:{cursor:"pointer"},children:[e.jsx("circle",{r:P+6,fill:"transparent"}),(b||A)&&e.jsx("circle",{r:P+4,fill:T,fillOpacity:.2}),e.jsx("circle",{r:P,fill:T,fillOpacity:b?1:.75,stroke:b?"#fff":T,strokeWidth:b?2:1}),n.scale>.5&&e.jsx("text",{y:P+12,textAnchor:"middle",fontSize:Math.max(8,Math.min(11,10/Math.sqrt(n.scale))),fill:"var(--text-dim, #b4bcd0)",style:{pointerEvents:"none",userSelect:"none"},children:j.label.length>20?j.label.slice(0,18)+"…":j.label})]},j.id)})]})})}const jo=[{color:"#8b5cf6",label:"Note / Default"},{color:"#34d399",label:"Entity (LightRAG)"},{color:"#fbbf24",label:"Concept (LightRAG)"},{color:"#f87171",label:"Root / Ungrouped"}];function fo({className:s}){return e.jsx("div",{className:Y("memory-graph-legend",s),children:jo.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),[h,x]=r.useState(""),[u,d]=r.useState(2),[m,p]=r.useState(""),[g,f]=r.useState(null),[y,S]=r.useState(null),k=r.useCallback(async()=>{var v,C;c(!0),l(null);try{const R=new URLSearchParams({limit:"200"});m&&R.set("root",m),R.set("depth",String(u));const j=await z.get(`/memory/graph?${R}`);i({nodes:j.nodes||[],edges:j.edges||[]}),f({totalNodes:j.totalNodes??((v=j.nodes)==null?void 0:v.length)??0,totalEdges:j.totalEdges??((C=j.edges)==null?void 0:C.length)??0})}catch(R){l(R.message),t.error(`Graph load failed: ${R.message}`)}finally{c(!1)}},[m,u,t]);r.useEffect(()=>{k()},[k,s]);const w=r.useCallback(v=>{S(C=>(C==null?void 0:C.id)===v.id?null:v)},[]),E=h.trim()?{nodes:a.nodes.filter(v=>v.label.toLowerCase().includes(h.toLowerCase())),edges:a.edges.filter(v=>a.nodes.some(C=>C.id===v.source&&C.label.toLowerCase().includes(h.toLowerCase()))||a.nodes.some(C=>C.id===v.target&&C.label.toLowerCase().includes(h.toLowerCase())))}:a;return e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(ee,{children:[e.jsxs(ae,{children:[e.jsx(ba,{size:14})," Memory Graph"]}),e.jsx(ie,{children:"Interactive knowledge graph — LightRAG entities + Obsidian wikilinks. Drag to pan, scroll to zoom."}),e.jsxs("div",{className:"memory-graph-controls",children:[e.jsxs("div",{className:"memory-graph-search-row",children:[e.jsx("label",{htmlFor:"graph-filter",className:"sr-only",children:"Filter nodes"}),e.jsx("input",{id:"graph-filter",type:"text",className:"input",placeholder:"Filter nodes…",value:h,onChange:v=>x(v.target.value),style:{maxWidth:240}}),e.jsx("input",{type:"text",className:"input",placeholder:"Root note id (optional)",value:m,onChange:v=>p(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:k,title:"Refresh graph",disabled:n,children:e.jsx(ce,{size:14,className:n?"memory-spin":""})})]}),e.jsx(fo,{})]})]}),e.jsx(ee,{children:n&&!a.nodes.length?e.jsxs("div",{className:"view-loading",children:[e.jsx(me,{size:"lg"}),e.jsx("p",{children:"Loading graph…"})]}):o&&!a.nodes.length?e.jsxs("div",{className:"muted text-sm",children:["Failed to load graph: ",o]}):a.nodes.length===0?e.jsx("div",{className:"muted text-sm",children:"No graph data available. Index some notes first with LightRAG or add wikilinks to your vault."}):e.jsxs("div",{style:{position:"relative"},children:[e.jsx(go,{data:E,onNodeClick:w,className:"memory-graph-canvas-svg"}),h&&e.jsxs("div",{className:"text-xs muted",style:{marginTop:4},children:["Showing ",E.nodes.length," of ",a.nodes.length," nodes"]})]})}),y&&e.jsxs(ee,{children:[e.jsx(ae,{children:y.label}),e.jsx(ie,{children:e.jsx("code",{children:y.id})}),e.jsxs("dl",{className:"memory-config-row",children:[e.jsx("dt",{children:"Type"}),e.jsx("dd",{children:e.jsx("code",{children:y.type})}),e.jsx("dt",{children:"Group"}),e.jsx("dd",{children:e.jsx("code",{children:y.group})}),e.jsx("dt",{children:"Size"}),e.jsx("dd",{children:y.size})]})]}),g&&e.jsx(ee,{children:e.jsxs("div",{className:"memory-graph-stats",children:[e.jsxs("span",{children:[g.totalNodes," node",g.totalNodes!==1?"s":""]}),e.jsx("span",{className:"muted",children:"·"}),e.jsxs("span",{children:[g.totalEdges," edge",g.totalEdges!==1?"s":""]}),h&&e.jsxs("span",{className:"muted",children:["· ",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),h=r.useCallback(async()=>{l(!0);try{const d=await navigator.mediaDevices.getDisplayMedia({video:{mediaSource:"screen"}}),m=document.createElement("video");m.srcObject=d,await m.play();const p=document.createElement("canvas");p.width=m.videoWidth,p.height=m.videoHeight;const g=p.getContext("2d");if(!g){t.error("Failed to get canvas context");return}g.drawImage(m,0,0),d.getTracks().forEach(f=>f.stop()),m.remove(),p.toBlob(async f=>{if(!f){t.error("Failed to capture screenshot");return}const y=URL.createObjectURL(f);i(y),await x(f)},"image/png")}catch(d){d.name!=="NotAllowedError"&&t.error(`Capture failed: ${d.message}`)}finally{l(!1)}},[t]),x=r.useCallback(async d=>{c(!0);try{const m=new FileReader,p=await new Promise((f,y)=>{m.onload=()=>{const S=m.result,k=S.includes(",")?S.split(",")[1]:S;f(k)},m.onerror=()=>y(new Error("FileReader failed")),m.readAsDataURL(d)}),g=await z.post("/ocr/process",{image:p,lang:"eng"});g.ok&&(t.success("Text extracted from screenshot"),s==null||s(g.text,g.notePath))}catch(m){t.error(`OCR failed: ${m.message}`)}finally{c(!1)}},[t,s]),u=r.useCallback(()=>{i(null)},[]);return e.jsxs(ee,{variant:"outlined",className:"screenshot-capture-card",children:[e.jsxs(ae,{children:[e.jsx(it,{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(it,{size:32,className:"muted"}),e.jsx("p",{className:"muted text-sm",children:"Capture your screen to extract text via OCR."}),e.jsxs($,{variant:"primary",size:"sm",onClick:h,disabled:o,children:[o?e.jsx(xe,{size:12,className:"spinner"}):e.jsx(it,{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(ee,{variant:"outlined",className:"screenshot-ocr-result-card",children:[e.jsxs(ae,{children:[e.jsx(Te,{size:14})," Extracted Text"]}),a&&e.jsxs(ie,{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 ko({refreshKey:s}){return e.jsx("div",{className:"memory-panel-content",children:e.jsx(ee,{variant:"outlined",className:"memory-panel-card",children:e.jsx("div",{className:"memory-panel-body",children:e.jsx(bo,{})})})})}function No({refreshKey:s}){const t=re(),[a,i]=r.useState(""),[n,c]=r.useState(""),[o,l]=r.useState(""),[h,x]=r.useState(!1),u=async()=>{if(!o.trim()){t.error("Content is required");return}x(!0);try{const d=await z.post("/clipboard/save",{url:a.trim()||void 0,title:n.trim()||void 0,content:o,savedAt:new Date().toISOString()});d.ok&&(t.success(`Saved to ${d.notePath}`),i(""),c(""),l(""))}catch(d){t.error(`Save failed: ${d.message}`)}finally{x(!1)}};return e.jsx("div",{className:"memory-panel-content",children:e.jsx(ee,{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(ka,{size:16}),e.jsx("span",{children:"Paste Content"})]}),e.jsx("label",{className:"field-label",htmlFor:"clip-url",children:"URL (optional)"}),e.jsx("input",{id:"clip-url",type:"text",className:"input",placeholder:"https://example.com",value:a,onChange:d=>i(d.target.value)}),e.jsx("label",{className:"field-label",htmlFor:"clip-title",style:{marginTop:10},children:"Title (optional)"}),e.jsx("input",{id:"clip-title",type:"text",className:"input",placeholder:"Page title",value:n,onChange:d=>c(d.target.value)}),e.jsx("label",{className:"field-label",htmlFor:"clip-content",style:{marginTop:10},children:"Content *"}),e.jsx("textarea",{id:"clip-content",className:"input vault-clipboard-textarea mono text-sm",rows:12,placeholder:"Paste or type content to save to your vault…",value:o,onChange:d=>l(d.target.value)}),e.jsx("div",{className:"vault-clipboard-actions",style:{marginTop:12},children:e.jsxs($,{variant:"primary",size:"sm",onClick:u,disabled:h||!o.trim(),children:[h&&e.jsx(xe,{size:12,className:"spinner"}),"Save to Vault"]})})]})})})})}function wo({vaultPath:s,onSaved:t}){const[a,i]=r.useState(!1),[n,c]=r.useState(!1),o=r.useRef(null),l=r.useRef([]),h=async()=>{try{const d=await navigator.mediaDevices.getUserMedia({audio:!0}),m=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm",p=new MediaRecorder(d,{mimeType:m});p.ondataavailable=g=>{g.data&&g.data.size>0&&l.current.push(g.data)},p.onstop=async()=>{const g=new Blob(l.current,{type:"audio/webm"});l.current=[],d.getTracks().forEach(f=>f.stop()),await u(g)},p.start(1e3),o.current=p,i(!0)}catch(d){console.error("[VoiceRecorder] failed to start recording:",d)}},x=()=>{const d=o.current;d&&(d.stop(),i(!1),c(!0))},u=async d=>{try{const m=new FormData;m.append("audio",d,"voice-note.webm"),m.append("vaultPath",s||"");const p=await fetch("/api/voice/upload",{method:"POST",body:m});if(!p.ok){console.error("[VoiceRecorder] upload failed:",p.status,await p.text()),c(!1);return}const{notePath:g,transcription:f}=await p.json();t==null||t(g,f)}catch(m){console.error("[VoiceRecorder] upload error:",m)}finally{c(!1)}};return e.jsxs("div",{className:"voice-recorder",children:[!a&&!n&&e.jsxs($,{variant:"accent",size:"sm",onClick:h,"aria-label":"Start recording",children:[e.jsx(It,{size:14})," Record"]}),a&&e.jsxs($,{variant:"danger",size:"sm",onClick:x,"aria-label":"Stop recording",children:[e.jsx(ga,{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(ha,{size:13}):e.jsx(vs,{size:13})}),e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>t(s.id),"aria-label":"Delete note",title:"Delete note",children:e.jsx(we,{size:13})})]})]}),s.transcript&&e.jsx("p",{className:"voice-note-transcript",children:s.transcript}),!s.transcript&&e.jsx("p",{className:"voice-note-no-transcript muted text-sm",children:"No transcription available"})]})}function Co({vaultPath:s,refreshKey:t=0}){const[a,i]=r.useState([]),[n,c]=r.useState(""),[o,l]=r.useState(!0),h=async()=>{l(!0);try{const d=s?`?vaultPath=${encodeURIComponent(s)}`:"",p=await(await fetch(`/api/voice/list${d}`)).json();i(p.notes||[])}catch(d){console.error("[VoiceNotesPanel] failed to load notes:",d)}finally{l(!1)}};r.useEffect(()=>{h()},[s,t]);const x=async d=>{try{const m=await fetch(`/api/voice/${d}`,{method:"DELETE"});(m.ok||m.status===204)&&i(p=>p.filter(g=>g.id!==d))}catch(m){console.error("[VoiceNotesPanel] delete failed:",m)}},u=a.filter(d=>{var m;return!n||(((m=d.transcript)==null?void 0:m.toLowerCase().includes(n.toLowerCase()))??!1)});return e.jsxs(ee,{children:[e.jsxs(ae,{children:[e.jsx(It,{size:14})," Voice Notes"]}),e.jsx(ie,{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:h})}),o?e.jsx("p",{className:"muted text-sm",children:"Loading notes…"}):u.length===0?e.jsx("p",{className:"muted text-sm",children:n?"No notes match your search.":"No voice notes yet. Hit Record to add one."}):e.jsx("div",{className:"voice-note-list",children:u.map(d=>e.jsx(So,{note:d,onDelete:x},d.id))})]})}const zo=[{id:"overview",label:"Overview",icon:ra},{id:"lightrag",label:"LightRAG",icon:Pe},{id:"obsidian",label:"Obsidian Vault",icon:Te},{id:"git",label:"Git Sync",icon:is},{id:"semantic",label:"Semantic Search",icon:pe},{id:"config",label:"Config",icon:Rt},{id:"graph",label:"Memory Graph",icon:ba},{id:"webclip",label:"Web Clip",icon:ka},{id:"screenshot",label:"Screenshot OCR",icon:Fn},{id:"voice",label:"Voice Notes",icon:It}];function To(s){const t=re(),[a,i]=r.useState("overview"),[n,c]=r.useState(0),o=r.useCallback(()=>{c(x=>x+1)},[]),l=r.useCallback(async()=>{o(),t.info("Refreshing memory…",1200)},[o,t]),h=()=>{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(No,{refreshKey:n});case"screenshot":return e.jsx(ko,{refreshKey:n});case"voice":return e.jsx(Co,{refreshKey:n});default:return e.jsxs(ee,{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(ce,{size:14})})})]}),e.jsxs("div",{className:"memory-tab-body",children:[e.jsx("nav",{className:"memory-source-rail","aria-label":"Memory sources",children:zo.map(x=>{const u=x.icon,d=a===x.id;return e.jsxs("button",{type:"button",role:"tab","aria-selected":d,className:Y("memory-source-button",d&&"memory-source-button-active"),onClick:()=>i(x.id),children:[e.jsx(u,{size:16,"aria-hidden":!0}),e.jsx("span",{children:x.label})]},x.id)})}),e.jsx("div",{className:"memory-main",children:h()},a)]})]})}const Ro=We.memo(To),Ss=[{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(ee,{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(Te,{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(Oe,{size:14}):e.jsx(Ke,{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 y,S;const t=re(),[a,i]=r.useState(null),[n,c]=r.useState(!0),[o,l]=r.useState("1d"),[h,x]=r.useState(new Set),[u,d]=r.useState(0),m=async k=>{try{const w=k?`?since=${encodeURIComponent(k)}&limit=1000`:"?limit=1000",E=await z.get(`/history${w}`);i(E),x(new Set(E.projects.filter(v=>E.events.some(C=>C.projectId===v.id)).map(v=>v.id)))}catch(w){t.error(`History load failed: ${w.message}`)}finally{c(!1)}};r.useEffect(()=>{c(!0);const k=Ss.find(w=>w.id===o)||Ss[1];if(k.ms>0){const w=new Date(Date.now()-k.ms).toISOString();m(w)}else m()},[o]),r.useEffect(()=>{const k=setInterval(()=>d(w=>w+1),3e4);return()=>clearInterval(k)},[]);const p=new Map;for(const k of(a==null?void 0:a.events)||[]){const w=k.projectId||"global";p.has(w)||p.set(w,[]),p.get(w).push(k)}const g=k=>{x(w=>{const E=new Set(w);return E.has(k)?E.delete(k):E.add(k),E})},f=()=>{if(!a)return;const k=new Blob([JSON.stringify(a,null,2)],{type:"application/json"}),w=URL.createObjectURL(k),E=document.createElement("a");E.href=w,E.download=`bizar-history-${new Date().toISOString().replace(/[:.]/g,"-")}.json`,E.click(),URL.revokeObjectURL(w),t.success("History exported.")};return e.jsxs("div",{className:"view view-history","data-tick":u,children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(As,{size:18})," History"]}),e.jsxs("p",{className:"view-subtitle",children:["Cross-project history of events, tasks, and plans.",((y=a==null?void 0:a.stats)==null?void 0:y.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(On,{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:k=>l(k.target.value),title:"Time range","aria-label":"Time range",children:Ss.map(k=>e.jsx("option",{value:k.id,children:k.label},k.id))})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>{c(!0);const k=Ss.find(w=>w.id===o)||Ss[1];k.ms>0?m(new Date(Date.now()-k.ms).toISOString()):m()},children:[e.jsx(ce,{size:14})," Refresh"]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:f,children:[e.jsx(qe,{size:14})," Export"]})]})]}),n&&e.jsxs("div",{className:"view-loading",children:[e.jsx(me,{size:"lg"}),e.jsx("p",{children:"Loading history…"})]}),!n&&a&&e.jsxs("div",{className:"history-list",children:[a.projects.length===0&&e.jsxs(ee,{children:[e.jsxs(ae,{children:[e.jsx(Fe,{size:14})," No projects"]}),e.jsx(ie,{children:"Register a project in Overview to start tracking history."})]}),a.projects.length>0&&e.jsx(Lt,{items:a.projects,itemHeight:70,height:Math.min(a.projects.length*70,500),className:"history-virtual-list",renderItem:k=>$o(k,p.get(k.id)||[],h,g)}),p.has("global")&&e.jsxs(ee,{className:"history-project",children:[e.jsx("div",{className:"history-project-head",children:e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4,minWidth:0,flex:1},children:[e.jsxs("div",{className:"history-project-name",children:[e.jsx(As,{size:16})," Global events"]}),e.jsx("div",{className:"history-project-meta",children:"Activity not tied to a specific project"})]})}),e.jsx("div",{className:"history-timeline-mini",children:(p.get("global")||[]).slice(-100).reverse().map((k,w)=>e.jsxs("div",{className:"history-timeline-row",children:[e.jsx("span",{className:"history-timeline-ts",children:new Date(k.ts).toLocaleTimeString()}),e.jsx("span",{className:"history-timeline-kind",children:k.kind||"event"}),e.jsxs("span",{className:"history-timeline-msg",title:String(k.text||k.title||""),children:[k.author?`@${k.author} `:"",String(k.text??k.title??k.name??"")]})]},w))})]}),((S=a.stats)==null?void 0:S.counts)&&Object.keys(a.stats.counts).length>0&&e.jsxs(ee,{children:[e.jsx(ae,{children:"Event counts by kind"}),e.jsxs(ie,{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((k,w)=>w[1]-k[1]).slice(0,30).map(([k,w])=>e.jsxs("span",{className:Y("tag","tag-neutral"),style:{fontFamily:"var(--font-mono)"},children:[k,": ",w]},k))})]})]})]})}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:h,tokens:x}=s,u=l.length;if(u===0)return e.jsx("div",{className:Y("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,p=Math.max(...h,1),g=Math.max(...x,1),f=Math.max(4,Math.min(24,Math.floor(d/u)-4)),y=(d-f*u)/(u+1);function S(A){return ve.left+y+A*(f+y)}function k(A){return A/p*m*.75}function w(A){return ve.top+m-A/g*m*.75}const E=x.map((A,O)=>`${S(O)+f/2},${w(A)}`).join(" "),v=[0,.25,.5,.75,1].map(A=>({y:ve.top+m-A*m*.75,label:A===0?"0":`${Math.round(p*A).toLocaleString()}`})),C=[0,.25,.5,.75,1].map(A=>({y:ve.top+m-A*m*.75,label:A===0?"0":`${Math.round(g*A/1e3)}k`})),R=Math.max(1,Math.floor(u/7)),j=l.map((A,O)=>({i:O,l:A,x:S(O)+f/2})).filter((A,O)=>O%R===0),P=r.useCallback(A=>{if(!n.current)return;const O=n.current.getBoundingClientRect(),N=(A.clientX-O.left)*(600/O.width),F=(A.clientY-O.top)*(t/O.height),K=N-ve.left,L=Math.round((K-y/2)/(f+y)),G=Math.max(0,Math.min(u-1,L));o({index:G,x:A.clientX-O.left,y:A.clientY-O.top}),a==null||a(G,N,F)},[u,f,y,a,t]),T=r.useCallback(()=>{o(null),a==null||a(null,0,0)},[a]),b=c;return e.jsxs("div",{ref:n,className:Y("usage-chart",i),style:{position:"relative"},children:[e.jsxs("svg",{viewBox:`0 0 600 ${t}`,width:"100%",height:t,style:{display:"block",overflow:"visible"},onMouseMove:P,onMouseLeave:T,children:[v.map((A,O)=>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-${O}`)),v.map((A,O)=>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-${O}`)),C.map((A,O)=>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-${O}`)),h.map((A,O)=>{const N=k(A),F=S(O),K=ve.top+m-N;return e.jsx("rect",{x:F,y:K,width:f,height:N,rx:2,fill:((b==null?void 0:b.index)===O,"var(--accent)"),opacity:(b==null?void 0:b.index)===O?1:.75,style:{transition:"opacity 120ms ease"}},`bar-${O}`)}),e.jsx("polyline",{points:E,fill:"none",stroke:"var(--warning, #d29922)",strokeWidth:2,strokeLinejoin:"round",strokeLinecap:"round",opacity:.9}),x.map((A,O)=>e.jsx("circle",{cx:S(O)+f/2,cy:w(A),r:(b==null?void 0:b.index)===O?5:3,fill:"var(--warning, #d29922)",opacity:(b==null?void 0:b.index)===O?1:.7,style:{transition:"r 120ms ease"}},`dot-${O}`)),j.map(({i:A,l:O,x:N})=>e.jsx("text",{x:N,y:ve.top+m+18,textAnchor:"middle",fontSize:10,fill:"var(--text-muted)",fontFamily:"var(--font-mono, ui-monospace, monospace)",children:O},`xl-${A}`)),e.jsx("line",{x1:ve.left,y1:ve.top+m,x2:600-ve.right,y2:ve.top+m,stroke:"var(--border)",strokeWidth:1})]}),b!==null&&e.jsxs("div",{className:"usage-chart-tooltip",style:{left:Math.min(b.x+12,460),top:b.y-60},children:[e.jsx("div",{className:"usage-tooltip-date",children:l[b.index]}),e.jsxs("div",{className:"usage-tooltip-row",children:[e.jsx("span",{className:"usage-tooltip-dot",style:{background:"var(--accent)"}}),e.jsx("span",{children:"Requests:"}),e.jsx("strong",{children:h[b.index].toLocaleString()})]}),e.jsxs("div",{className:"usage-tooltip-row",children:[e.jsx("span",{className:"usage-tooltip-dot",style:{background:"var(--warning, #d29922)"}}),e.jsx("span",{children:"Tokens:"}),e.jsx("strong",{children:x[b.index].toLocaleString()})]})]})]})}function ss({label:s,col:t,sortKey:a,sortDir:i,onSort:n}){const c=a===t;return e.jsxs("th",{className:Y("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(ss,{label:"Model",col:"modelId",sortKey:t,sortDir:a,onSort:i}),e.jsx(ss,{label:"Requests",col:"requests",sortKey:t,sortDir:a,onSort:i}),e.jsx(ss,{label:"Prompt Tok",col:"promptTokens",sortKey:t,sortDir:a,onSort:i}),e.jsx(ss,{label:"Compl Tok",col:"completionTokens",sortKey:t,sortDir:a,onSort:i}),e.jsx(ss,{label:"Total Tok",col:"totalTokens",sortKey:t,sortDir:a,onSort:i}),e.jsx(ss,{label:"Avg Latency",col:"avgLatencyMs",sortKey:t,sortDir:a,onSort:i}),e.jsx(ss,{label:"Errors",col:"errors",sortKey:t,sortDir:a,onSort:i})]})}),e.jsx("tbody",{children:s.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:7,className:"usage-table-empty",children:"No data for this range"})}):s.map(n=>e.jsxs("tr",{children:[e.jsx("td",{className:"usage-table-model",children:e.jsx("code",{children:n.modelId})}),e.jsx("td",{className:"mono",children:n.requests.toLocaleString()}),e.jsx("td",{className:"mono",children:n.promptTokens.toLocaleString()}),e.jsx("td",{className:"mono",children:n.completionTokens.toLocaleString()}),e.jsx("td",{className:"mono",children:n.totalTokens.toLocaleString()}),e.jsxs("td",{className:"mono",children:[n.avgLatencyMs,"ms"]}),e.jsx("td",{className:Y("mono",n.errors>0&&"is-err"),children:n.errors>0?n.errors:"—"})]},`${n.providerId}::${n.modelId}`))})]})})}function Lo({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:Y("minimax-sub-tab",a==="quota"&&"is-active"),onClick:()=>i("quota"),children:[e.jsx(Tt,{size:13})," Token Plan"]}),e.jsxs("button",{className:Y("minimax-sub-tab",a==="analytics"&&"is-active"),onClick:()=>i("analytics"),children:[e.jsx(Na,{size:13})," Usage Analytics"]})]}),a==="quota"?e.jsx(Eo,{activeTab:s,setActiveTab:t}):e.jsx(Do,{toast:n})]})}function Eo({activeTab:s,setActiveTab:t}){var X;const a=re(),[i,n]=r.useState(null),[c,o]=r.useState(null),[l,h]=r.useState(null),[x,u]=r.useState(!0),[d,m]=r.useState(!1),[p,g]=r.useState(null),[f,y]=r.useState(null),[S,k]=r.useState(!1),[w,E]=r.useState(0),[v,C]=r.useState(!1),[R,j]=r.useState(null),[P,T]=r.useState(""),[b,A]=r.useState(!1),[O,N]=r.useState(!1),F=r.useCallback(async()=>{u(!0),g(null);try{const[U,J,he]=await Promise.all([z.get("/minimax/status"),z.get("/minimax/remains"),z.get("/minimax/onboarding")]);n(U),o(J),h(he),U.configured&&E(4)}catch(U){g(U.message||"Failed to load MiniMax data")}finally{u(!1)}},[]);r.useEffect(()=>{F()},[F]);const K=r.useCallback(async()=>{try{await z.post("/minimax/onboarding",{dismissedAt:Date.now()}),h(U=>U&&{...U,dismissedAt:Date.now()})}catch{}},[]),L=r.useCallback(async()=>{if(!P.trim()){a.error("Paste a Subscription Key first.");return}C(!0),j(null);try{const U=await z.post("/minimax/test",{prompt:"Reply with a single word: pong",model:"MiniMax-M3",maxTokens:16});if(j(U),U.ok){E(3),a.success("Key works. Saving…");try{await z.post("/minimax/onboarding/save-key",{key:P.trim(),groupId:"default"}),ne(),a.success("Subscription Key saved.")}catch(J){a.error(`Save failed: ${J.message}`)}F()}else a.error(`Verification failed: ${U.message??U.error??"unknown"}`)}catch(U){a.error(`Test request failed: ${U.message}`)}finally{C(!1)}},[P,a,F]),G=r.useCallback(async()=>{if(!P.trim()){a.error("Paste a Subscription Key first.");return}N(!0);try{const U=await z.post("/minimax/onboarding/save-key",{key:P.trim(),groupId:"default"});if(!U.ok){a.error(`Save failed: ${U.message??U.error??"unknown"}`);return}T(""),ne(),a.success("Subscription Key saved. Loading quota…"),F()}catch(U){a.error(`Save failed: ${U.message}`)}finally{N(!1)}},[P,a,F]),ne=r.useCallback(async()=>{try{await z.del("/minimax/cache")}catch{}},[]),te=r.useCallback(async()=>{m(!0),g(null);try{await z.post("/minimax/remains/refresh"),await F(),a.success("Refreshed")}catch(U){a.error(`Refresh failed: ${U.message}`)}finally{m(!1)}},[F,a]),B=r.useCallback(async()=>{var U;k(!0),y(null);try{const J=await z.post("/minimax/test",{prompt:"Reply with a single word: pong",model:"MiniMax-M3",maxTokens:16});y(J),J.ok?a.success(`Test ok — used ${((U=J.usage)==null?void 0:U.total_tokens)??"?"} tokens`):a.error(`Test failed: ${J.message??J.error??"unknown"}`)}catch(J){a.error(`Test request failed: ${J.message}`)}finally{k(!1)}},[a]);return x&&!i?e.jsxs("div",{className:"view-container",children:[e.jsx(me,{})," Loading MiniMax data…"]}):i?!i.configured&&(l==null?void 0:l.dismissedAt)==null&&w<4?e.jsx(Oo,{step:w,setStep:E,keyDraft:P,setKeyDraft:T,showKey:b,setShowKey:A,verifying:v,verifyResult:R,onVerify:L,onSkip:async()=>{await K(),a.success("Skipped.")},onManualKeySave:G,savingKey:O,status:i}):e.jsxs(e.Fragment,{children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-titles",children:[e.jsxs("h1",{className:"view-title",children:[e.jsx(Tt,{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(Ds,{size:14})," ",i.configured?`Key ${i.apiKeyHint}`:"Add key"]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:te,disabled:d,children:[d?e.jsx(xe,{size:14,className:"spin"}):e.jsx(ce,{size:14})," Refresh"]})]})]}),c&&!c.ok&&e.jsxs("div",{className:"banner banner-err",children:[e.jsx(be,{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(Us,{label:"Models tracked",value:String(c.models.length),hint:"Distinct model quotas returned by the API"}),e.jsx(Us,{label:"Last fetched",value:c.fetchedAt?Fo(c.fetchedAt):"—",hint:"Refreshed on demand + every 60s"}),e.jsx(Us,{label:"Group",value:c.groupId??"—",hint:"Usually 'default' for an individual team"}),e.jsx(Us,{label:"API key",value:c.apiKeyHint??"—",hint:"Masked; the real key never leaves auth.json"})]}),e.jsx("div",{className:"minimax-models-grid",children:c.models.map(U=>e.jsx(Po,{model:U},U.model_name))})]}),i.configured&&e.jsxs(ee,{id:"minimax-test",children:[e.jsxs(ae,{children:[e.jsx(rs,{size:14})," Test the API key"]}),e.jsxs(ie,{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:B,disabled:S,variant:"primary",size:"sm",children:[S?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"'})]}),f&&e.jsxs("div",{className:Y("minimax-test-result",f.ok?"ok":"err"),children:[f.ok?e.jsx(_e,{size:14}):e.jsx(be,{size:14}),e.jsx("div",{className:"minimax-test-body",children:f.ok?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"minimax-test-line",children:[e.jsx("strong",{children:"model:"})," ",e.jsx("code",{children:f.model})," ·"," ",e.jsx("strong",{children:"finish:"})," ",f.finishReason??"—"]}),f.content&&e.jsx("div",{className:"minimax-test-content",children:e.jsx("code",{children:f.content})}),f.usage&&e.jsxs("div",{className:"minimax-test-usage",children:[e.jsx("strong",{children:"usage:"})," total ",e.jsx("code",{children:f.usage.total_tokens??"?"})," · prompt"," ",e.jsx("code",{children:f.usage.prompt_tokens??"?"})," · completion"," ",e.jsx("code",{children:f.usage.completion_tokens??"?"}),((X=f.usage.prompt_tokens_details)==null?void 0:X.cached_tokens)!=null&&e.jsxs(e.Fragment,{children:[" · cached ",e.jsx("code",{children:f.usage.prompt_tokens_details.cached_tokens})]})]})]}):e.jsx("pre",{children:f.message??f.error??"unknown error"})})]})]})]}):e.jsx("div",{className:"view-container",children:e.jsxs("div",{className:"error-card",children:[e.jsx(be,{size:20}),e.jsxs("div",{children:[e.jsx("strong",{children:"Couldn't load MiniMax status"}),e.jsx("pre",{children:p??"unknown error"})]})]})})}function Do({toast:s}){const[t,a]=r.useState("24h"),[i,n]=r.useState(""),[c,o]=r.useState(""),[l,h]=r.useState(!0),[x,u]=r.useState(null),[d,m]=r.useState([]),[p,g]=r.useState("requests"),[f,y]=r.useState("desc"),[S,k]=r.useState(!1),w=r.useCallback(async(b,A,O)=>{h(!0);try{const N=new URLSearchParams({range:b});b==="custom"&&A&&O&&(N.set("from",String(A)),N.set("to",String(O)));const[F,K]=await Promise.all([z.get(`/usage?${N.toString()}`),z.get("/usage/recent?limit=20")]);u(F),m(K.records)}catch(N){s.error(`Failed to load usage data: ${N.message}`)}finally{h(!1)}},[s]);r.useEffect(()=>{if(t==="custom"){const b=i?new Date(i).getTime():Date.now()-6048e5,A=c?new Date(c).getTime():Date.now();w("custom",b,A)}else w(t)},[t,w]);const E=r.useCallback(b=>{p===b?y(A=>A==="asc"?"desc":"asc"):(g(b),y("desc"))},[p]),v=r.useMemo(()=>x!=null&&x.perModel?[...x.perModel].sort((b,A)=>{const O=b[p]??0,N=A[p]??0,F=typeof O=="number"&&typeof N=="number"?O-N:String(O).localeCompare(String(N));return f==="asc"?F:-F}):[],[x==null?void 0:x.perModel,p,f]),C=r.useMemo(()=>x!=null&&x.daily?{labels:x.daily.map(b=>b.date.slice(5)),requests:x.daily.map(b=>b.requests),tokens:x.daily.map(b=>b.totalTokens)}:{labels:[],requests:[],tokens:[]},[x==null?void 0:x.daily]),R=r.useCallback(async()=>{k(!0),await w(t==="custom"?"custom":t,t==="custom"&&i?new Date(i).getTime():void 0,t==="custom"&&c?new Date(c).getTime():void 0),k(!1)},[w,t,i,c]);if(l&&!x)return e.jsxs("div",{className:"view-container",children:[e.jsx(me,{})," Loading usage data…"]});const j=x==null?void 0:x.totals,P=(x==null?void 0:x.errors)??[],T=(x==null?void 0:x.perKey)??[];return e.jsxs(e.Fragment,{children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-titles",children:[e.jsxs("h1",{className:"view-title",children:[e.jsx(Na,{size:20,style:{verticalAlign:"text-bottom",marginRight:6}}),"Usage Analytics"]}),e.jsxs("p",{className:"view-subtitle",children:["Aggregated from ",e.jsx("code",{children:"~/.local/share/bizar/usage.jsonl"})," — every chatCompletion and fetchRemains call."]})]}),e.jsx("div",{className:"view-header-actions",children:e.jsxs($,{variant:"secondary",size:"sm",onClick:R,disabled:S,children:[S?e.jsx(xe,{size:14,className:"spin"}):e.jsx(ce,{size:14})," Refresh"]})})]}),e.jsxs("div",{className:"usage-time-range",children:[["24h","7d","30d","custom"].map(b=>e.jsx("button",{className:Y("usage-range-chip",t===b&&"is-active"),onClick:()=>a(b),children:b==="custom"?"Custom":b.toUpperCase()},b)),t==="custom"&&e.jsxs("div",{className:"usage-custom-dates",children:[e.jsx("label",{htmlFor:"usage-from-date",className:"sr-only",children:"From date"}),e.jsx("input",{id:"usage-from-date",type:"date",className:"usage-date-input",value:i,onChange:b=>n(b.target.value),"aria-label":"From date"}),e.jsx("span",{style:{color:"var(--text-muted)",fontSize:12},"aria-hidden":!0,children:"to"}),e.jsx("label",{htmlFor:"usage-to-date",className:"sr-only",children:"To date"}),e.jsx("input",{id:"usage-to-date",type:"date",className:"usage-date-input",value:c,onChange:b=>o(b.target.value),"aria-label":"To date"})]})]}),e.jsxs("div",{className:"usage-kpi-row",children:[e.jsx(Cs,{label:"Total Requests",value:(j==null?void 0:j.requests.toLocaleString())??"—",sub:j?`${j.errors} errors`:void 0,tone:j&&j.errors>j.requests*.1?"warn":void 0}),e.jsx(Cs,{label:"Total Tokens",value:j?j.totalTokens>=1e3?`${Math.round(j.totalTokens/1e3)}k`:String(j.totalTokens):"—",sub:j?`${j.promptTokens.toLocaleString()} prompt · ${j.completionTokens.toLocaleString()} completion`:void 0}),e.jsx(Cs,{label:"Errors",value:String((j==null?void 0:j.errors)??"—"),sub:P.length>0?`${P[0].code}: ${P[0].count}`:void 0,tone:j&&j.errors>0?"err":void 0}),e.jsx(Cs,{label:"Avg Latency",value:(j==null?void 0:j.avgLatencyMs)!=null?`${j.avgLatencyMs}ms`:"—",sub:(j==null?void 0:j.p95LatencyMs)!=null?`p95 ${j.p95LatencyMs}ms`:void 0}),e.jsx(Cs,{label:"Est. Cost",value:(j==null?void 0:j.costEstimate)!=null&&j.costEstimate>0?`$${j.costEstimate.toFixed(4)}`:"—",sub:"approximate USD",tone:void 0})]}),e.jsxs(ee,{className:"usage-chart-card",children:[e.jsx("div",{className:"usage-chart-wrap",children:e.jsx(Mo,{series:C,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(ee,{children:[e.jsx(ae,{children:"Per-model breakdown"}),e.jsx(Io,{rows:v,sortKey:p,sortDir:f,onSort:E})]}),T.length>0&&e.jsxs(ee,{children:[e.jsx(ae,{children:"API Keys"}),e.jsx("div",{className:"usage-key-row",children:T.map(b=>e.jsxs("span",{className:Y("usage-key-badge",b.isBackup?"is-backup":"is-active"),children:[e.jsx("span",{className:"usage-key-dot"}),b.keyEnvVar,b.isBackup?" (backup)":" (active)"," · ",b.requests," req"]},b.keyEnvVar))})]}),d.length>0&&e.jsxs(ee,{children:[e.jsx(ae,{children:"Recent activity"}),e.jsx("div",{className:"usage-recent-list",children:d.map((b,A)=>e.jsxs("div",{className:Y("usage-recent-item",b.error&&"is-err"),children:[e.jsx("span",{className:"usage-recent-time",children:new Date(b.ts).toLocaleTimeString()}),e.jsx("span",{className:"usage-recent-model",children:e.jsx("code",{children:b.modelId})}),e.jsxs("span",{className:"usage-recent-tokens",children:[b.totalTokens.toLocaleString()," tok"]}),e.jsxs("span",{className:"usage-recent-latency",children:[b.latencyMs,"ms"]}),e.jsx("span",{className:"usage-recent-endpoint",children:b.endpoint})]},`${b.requestId}-${A}`))})]})]})}function Cs({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:Y("usage-kpi-value",i&&`is-${i}`),children:t}),a&&e.jsx("div",{className:"usage-kpi-sub",children:a})]})}function Us({label:s,value:t,hint:a}){return e.jsxs("div",{className:"stat",children:[e.jsx("div",{className:"stat-label",children:s}),e.jsx("div",{className:"stat-value",children:t}),a&&e.jsx("div",{className:"stat-hint",children:a})]})}function Po({model:s}){const t=_s(s.current_interval_remaining_percent??0,0,100),a=_s(s.current_weekly_remaining_percent??0,0,100),i=_s(100-t,0,100),n=_s(100-a,0,100);return e.jsxs(ee,{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:Y("minimax-model-status",t<25||a<25?"is-warn":"is-ok"),children:[s.current_interval_status===1?"active":"idle"," ·"," ",s.current_weekly_status===1?"week active":"week idle"]})]}),e.jsxs("div",{className:"minimax-quota-rows",children:[e.jsx(ta,{icon:e.jsx($e,{size:12}),label:"5-hour rolling",remainingPct:t,consumedPct:i,used:s.current_interval_usage_count??0,total:s.current_interval_total_count??0,resetIn:s.intervalResetInHuman,resetISO:s.endTimeISO}),e.jsx(ta,{icon:e.jsx(Bn,{size:12}),label:"Weekly",remainingPct:a,consumedPct:n,used:s.current_weekly_usage_count??0,total:s.current_weekly_total_count??0,resetIn:s.weeklyResetInHuman,resetISO:s.weeklyEndTimeISO})]})]})}function ta({icon:s,label:t,remainingPct:a,consumedPct:i,used:n,total:c,resetIn:o,resetISO:l}){const h=a>=75?"good":a>=25?"warn":"low";return e.jsxs("div",{className:`minimax-quota-row is-${h}`,children:[e.jsxs("div",{className:"minimax-quota-head",children:[e.jsxs("span",{className:"minimax-quota-label",children:[s," ",t]}),e.jsxs("span",{className:"minimax-quota-remaining",children:[a,"% remaining"]}),e.jsxs("span",{className:"minimax-quota-consumed",children:["· ",i,"% used"]})]}),e.jsx("div",{className:"minimax-bar",children:e.jsx("div",{className:"minimax-bar-fill",style:{width:`${i}%`},"aria-label":`${i}% consumed`})}),e.jsxs("div",{className:"minimax-quota-meta",children:[e.jsxs("span",{children:[e.jsx("strong",{children:n})," / ",c||"—"," requests"]}),e.jsx("span",{title:l,children:o?`resets in ${o}`:"—"})]})]})}function _s(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:h,onSkip:x,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(Ve,{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:x,children:[e.jsx(ke,{size:14})," Skip for now"]})})]}),e.jsx("div",{className:"minimax-wizard-stepper",children:["Welcome","Get a key","Paste & test","Done"].map((p,g)=>e.jsxs("div",{className:Y("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(_e,{size:14}):g+1}),e.jsx("div",{className:"minimax-wizard-step-label",children:p})]},p))}),e.jsxs(ee,{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(js,{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(Ds,{size:12,className:"minimax-key-icon","aria-hidden":!0}),e.jsx("label",{htmlFor:"minimax-key-input",className:"sr-only",children:"Subscription Key"}),e.jsx("input",{id:"minimax-key-input",type:n?"text":"password",value:a,onChange:p=>i(p.target.value),placeholder:"sk-cp-...",spellCheck:!1,autoComplete:"off",className:"minimax-key-input",autoFocus:!0,"aria-label":"Subscription Key"}),e.jsx("button",{type:"button",onClick:()=>c(p=>!p),className:"minimax-key-toggle","aria-label":n?"Hide key":"Show key",children:n?e.jsx(Xs,{size:13}):e.jsx(Qe,{size:13})})]})}),l&&!l.ok&&e.jsxs("div",{className:"minimax-wizard-error",children:[e.jsx(be,{size:14}),e.jsxs("span",{children:[e.jsx("strong",{children:"Verification failed:"})," ",l.message??l.error]})]}),e.jsxs("div",{className:"minimax-wizard-actions",children:[e.jsx($,{variant:"secondary",size:"md",onClick:()=>t(1),children:"← Back"}),e.jsxs($,{variant:"primary",size:"md",onClick:h,disabled:o||!a.trim(),children:[o?e.jsx(xe,{size:14,className:"spin"}):e.jsx(Ls,{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:p=>{p.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(_e,{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(Ls,{size:11}),e.jsxs("span",{children:["Key written to ",e.jsx("code",{children:"~/.local/share/opencode/auth.json"})," with mode 0600."]})]})]})]})}const Bo=We.memo(Lo),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 Vo({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 Ho(s,t,a,i,n){s.open({title:"Kill instance?",width:400,children:e.jsx(Vo,{instanceId:a,instanceName:i,onConfirm:async()=>{try{const o=await(await fetch(`/api/background/${encodeURIComponent(a)}`,{method:"DELETE"})).json();o.ok?(t.success(`Instance ${a} killed.`),n==null||n()):t.error(`Kill failed: ${o.error||"unknown error"}`)}catch(c){t.error(`Kill failed: ${c.message}`)}},onClose:()=>s.close()})})}function qo({instance:s}){const t=re(),[a,i]=r.useState(!1),n=s.tmuxSession,c=n?`tmux attach -t ${n}`:null,o=async()=>{if(c)try{await navigator.clipboard.writeText(c),t.success("Attach command copied")}catch{t.error("Could not copy to clipboard")}},l=async()=>{if(!(!s.instanceId||!n)){i(!0);try{const h=await z.post(`/background/${encodeURIComponent(s.instanceId)}/open-terminal`,{emulator:"system"});if(h.ok)t.success("Opening terminal…");else if(t.error(h.error||"Failed to open terminal"),c)try{await navigator.clipboard.writeText(c),t.success("Command copied to clipboard")}catch{}}catch(h){if(t.error(`Failed: ${h.message}`),c)try{await navigator.clipboard.writeText(c),t.success("Command copied to clipboard")}catch{}}finally{i(!1)}}};return n?e.jsxs(ee,{variant:"outlined",className:"bg-tmux-card",children:[e.jsxs("div",{className:"bg-tmux-card-header",children:[e.jsx(ps,{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(ls,{size:14})," Copy"]}),e.jsxs($,{variant:"primary",size:"sm",onClick:l,loading:a,title:"Open in system terminal",children:[e.jsx(ps,{size:14})," Open terminal"]})]})]}):e.jsxs(ee,{variant:"outlined",className:"bg-tmux-card bg-tmux-card-warn",children:[e.jsxs("div",{className:"bg-tmux-card-header",children:[e.jsx(be,{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 Ko=5e3,Go=2e3,Yo=120;function Xo(s){return s.status==="pending"||s.status==="running"}function Qo(s){if(!Number.isFinite(s)||s<0)return"—";const t=Math.floor(s/1e3),a=Math.floor(t/3600),i=Math.floor(t%3600/60),n=t%60;return a>0?`${a}h ${i}m ${n}s`:i>0?`${i}m ${n}s`:`${n}s`}function Jo(s){const t=re(),a=Ae(),[i,n]=r.useState([]),[c,o]=r.useState(!0),[l,h]=r.useState(null),[,x]=r.useState(0),u=r.useCallback(async()=>{try{const f=await z.get("/background");n(Array.isArray(f==null?void 0:f.instances)?f.instances:[]),h(null)}catch(f){h((f==null?void 0:f.message)||"Failed to load background agents.")}finally{o(!1)}},[]);r.useEffect(()=>{u();const f=setInterval(u,Ko);return()=>clearInterval(f)},[u]),r.useEffect(()=>{const f=setInterval(()=>x(y=>(y+1)%1e6),1e3);return()=>clearInterval(f)},[]),r.useEffect(()=>{const f=new Ct,y=f.on(S=>{const k=S.type;(k==="background:change"||k==="background:cleanup")&&u()});return()=>{y(),f.close()}},[u]);const d=i.filter(Xo),m=f=>{ec(a,f)},p=async f=>{try{const y=await z.get(`/background/${encodeURIComponent(f.instanceId)}/tmux`);tc(a,y)}catch(y){t.error(`Tmux info failed: ${y.message}`)}},g=f=>{Ho(a,t,f.instanceId,f.agent||f.prompt,()=>{n(y=>y.filter(S=>S.instanceId!==f.instanceId))})};return c?e.jsx("div",{className:"bg-active-view",children:e.jsxs("div",{className:"bg-active-loading",children:[e.jsx(me,{size:"md"}),e.jsx("span",{children:"Loading background agents…"})]})}):l?e.jsx("div",{className:"bg-active-view",children:e.jsx(Ne,{icon:e.jsx($e,{size:32}),title:"Couldn't load background agents",message:l,action:e.jsxs($,{variant:"primary",onClick:u,children:[e.jsx(ce,{size:14})," Retry"]})})}):e.jsxs("div",{className:"bg-active-view",children:[e.jsxs("div",{className:"bg-active-header",children:[e.jsxs("div",{className:"bg-active-header-text",children:[e.jsx("h2",{className:"bg-active-title",children:"Active Background Agents"}),e.jsxs("p",{className:"bg-active-subtitle muted",children:[d.length," active · ",i.length," total in store"]})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:u,title:"Refresh now",children:[e.jsx(ce,{size:14})," Refresh"]})]}),d.length===0?e.jsx(Ne,{icon:e.jsx($e,{size:32}),title:"No active background agents",message:"Spawn one from the Agents tab or via the bizar_spawn_background tool."}):e.jsx("div",{className:"bg-active-list",children:d.map(f=>e.jsx(Zo,{inst:f,onViewOutput:()=>m(f),onOpenTmux:()=>p(f),onKill:()=>g(f)},f.instanceId))})]})}function Zo({inst:s,onViewOutput:t,onOpenTmux:a,onKill:i}){const n=typeof s.startedAt=="number"?s.startedAt:0,c=n?Ze(n):"—",o=n?Date.now()-n:0,l=aa(s.prompt,Yo);return e.jsxs(ee,{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:"})," ",Qo(o)]}),e.jsxs("span",{children:[e.jsx("strong",{children:"Tool calls:"})," ",s.toolCallCount??0]}),s.tmuxSession&&e.jsxs("span",{className:Y(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(Qe,{size:14})," View output"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:a,children:[e.jsx(ps,{size:14})," Open in tmux"]}),e.jsxs($,{variant:"danger",size:"sm",onClick:i,children:[e.jsx(we,{size:14})," Kill"]})]}),e.jsx(qo,{instance:s})]})}function 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),[h,x]=r.useState(!0),u=r.useRef(null),d=r.useRef(!0),m=r.useCallback(async()=>{try{const f=await z.get(`/background/${encodeURIComponent(s)}/output?lines=200`);i((f==null?void 0:f.output)??""),x((f==null?void 0:f.available)!==!1),l(null)}catch(f){l((f==null?void 0:f.message)||"Failed to load output.")}finally{c(!1)}},[s]);r.useEffect(()=>{m();const f=setInterval(m,Go);return()=>clearInterval(f)},[m]),r.useEffect(()=>{var f;d.current&&((f=u.current)==null||f.scrollIntoView({behavior:"auto",block:"end"}))},[a]);const p=f=>{const y=f.currentTarget,S=y.scrollHeight-y.scrollTop-y.clientHeight<24;d.current=S},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:h?`${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(ce,{size:14})," Refresh"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:g,disabled:!a,children:[e.jsx(ls,{size:14})," Copy"]})]})]}),n&&!a?e.jsxs("div",{className:"bg-output-loading",children:[e.jsx(xe,{size:16,className:"spin"})," Loading…"]}):o?e.jsx("div",{className:"bg-output-error",children:o}):a?e.jsxs("div",{className:"bg-output-scroll",onScroll:p,children:[e.jsx("pre",{className:"bg-output-pre mono",children:e.jsx("code",{children:a})}),e.jsx("div",{ref: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(ls,{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:gs,emptyTitle:"No system checks",emptyMessage:"System checks did not return any rows."},services:{title:"Services",icon:tt,emptyTitle:"No service probes",emptyMessage:"Service probes did not return any rows."},counts:{title:"Counts",icon:$e,emptyTitle:"No counts",emptyMessage:"No counts reported by the dashboard stores."},errors:{title:"Recent errors",icon:xs,emptyTitle:"No recent errors",emptyMessage:"No error lines in the service log within the last hour."},actions:{title:"Actions",icon:Un,emptyTitle:"No actions",emptyMessage:"No actions available."}};function ic(s){return s==="ok"?_e:s==="warn"?_n:xs}function rc(s){return s==="ok"?"ok":s==="warn"?"warn":"fail"}function ft({category:s,title:t,icon:a,checks:i,info:n,meta:c,children:o,className:l}){const h=nc[s],x=a??h.icon,u=t??h.title,d=i.length>0||n&&n.length>0||o;return e.jsxs(ee,{className:Y("doctor-panel",`doctor-panel-${s}`,l),children:[e.jsxs(ae,{children:[e.jsx(x,{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 p=ic(m.status);return e.jsxs("li",{className:Y("doctor-check-row",`doctor-check-${m.status}`),children:[e.jsx("span",{className:"doctor-check-icon","aria-hidden":!0,children:e.jsx(p,{size:14,className:Y("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(We.Fragment,{children:[e.jsx("dt",{children:m.label}),e.jsx("dd",{className:"tabular-nums",children:m.value})]},m.label))}):null]}):e.jsx(Ne,{icon:e.jsx(x,{size:28,"aria-hidden":!0}),title:h.emptyTitle,message:h.emptyMessage})]})}const lc=3e4;function oc({setActiveTab:s}){var C;const t=re(),[a,i]=r.useState(null),[n,c]=r.useState(!0),[o,l]=r.useState(!1),[h,x]=r.useState(null),[u,d]=r.useState(!0),m=r.useRef(!1),p=r.useCallback(async()=>{l(!0);try{const R=await z.get("/doctor");m.current||(i(R),x(Date.now()),c(!1))}catch(R){m.current||(c(!1),t.error(`Doctor refresh failed: ${R.message}`))}finally{m.current||l(!1)}},[t]);r.useEffect(()=>(m.current=!1,p(),()=>{m.current=!0}),[p]),r.useEffect(()=>{if(!u)return;const j=setInterval(async()=>{try{const P=await z.get("/doctor/health");i(T=>T&&((T.health.status!==P.status||T.health.issues.length!==P.issues.length)&&p(),T))}catch{}},lc);return()=>clearInterval(j)},[u,p]);const g=async R=>{var j;try{const P=await z.post("/doctor/check",{checkName:R});t.info(`${P.name}: ${P.message}`,4e3),await p()}catch(P){const T=P;t.error(`Check failed: ${((j=T.data)==null?void 0:j.message)??P.message}`)}},f=()=>{if(a)try{const R=new Blob([JSON.stringify(a,null,2)],{type:"application/json"}),j=URL.createObjectURL(R),P=document.createElement("a");P.href=j,P.download=`doctor-snapshot-${new Date().toISOString().replace(/[:.]/g,"-")}.json`,document.body.appendChild(P),P.click(),document.body.removeChild(P),URL.revokeObjectURL(j)}catch(R){t.error(`Export failed: ${R.message}`)}},y=()=>{s("settings")},S=a==null?void 0:a.counts,k=r.useMemo(()=>S?[{label:"Tasks",value:S.tasks},{label:"Schedules",value:S.schedules},{label:"Mods",value:S.mods},{label:"Providers",value:S.providers},{label:"MCPs",value:S.mcps},{label:"Agents",value:S.agents},{label:"Projects",value:S.projects},{label:"Workspaces",value:S.workspaces},{label:"Voice notes",value:S.voiceNotes},{label:"Eval runs",value:S.evalRuns},{label:"Backups",value:S.backups}]:[],[S]);if(n)return e.jsxs("div",{className:"view view-doctor view-loading",children:[e.jsx(me,{size:"lg"}),e.jsx("p",{children:"Running health checks…"})]});if(!a)return e.jsx("div",{className:"view view-doctor",children:e.jsxs(ee,{children:[e.jsxs(ae,{children:[e.jsx(xs,{size:14})," Doctor unavailable"]}),e.jsx(ie,{children:"Could not reach /api/doctor."}),e.jsx("div",{className:"doctor-fallback-actions",children:e.jsxs($,{variant:"primary",onClick:p,children:[e.jsx(ce,{size:12})," Retry"]})})]})});const w=a.health.status,E=w==="ok"?_e:w==="warn"?be:xs,v=w==="ok"?"Healthy":w==="warn"?"Warning":"Failed";return e.jsxs("div",{className:"view view-doctor","data-overall":w,children:[e.jsxs("div",{className:"doctor-header",children:[e.jsxs("div",{className:"doctor-header-row",children:[e.jsxs("div",{className:"doctor-header-title",children:[e.jsx(la,{size:20,"aria-hidden":!0}),e.jsx("h1",{children:"Doctor"})]}),e.jsx("div",{className:"doctor-header-status",children:e.jsxs("span",{className:Y("doctor-overall-pill",`doctor-overall-${w}`),children:[e.jsx(E,{size:14,"aria-hidden":!0}),e.jsx("span",{className:"doctor-overall-label",children:v}),e.jsxs(Je,{kind:w,dot:!0,children:[a.health.issues.length," issue",a.health.issues.length===1?"":"s"]})]})})]}),e.jsxs("div",{className:"doctor-header-meta muted",children:[e.jsx($s,{size:12,"aria-hidden":!0}),e.jsxs("span",{children:["v",a.bizarVersion," · ",a.platform,"/",a.arch," ·"," ","up ",Math.floor(a.uptime),"s",h?` · refreshed ${Ze(new Date(h))}`:""]})]})]}),e.jsxs("div",{className:"doctor-grid",children:[e.jsx(ft,{category:"system",checks:a.checks.system,meta:`${a.platform}/${a.arch}`}),e.jsx(ft,{category:"services",checks:a.checks.services,meta:(C=a.services.opencode)!=null&&C.reachable?`opencode on ${a.services.opencode.port??"?"}`:"opencode not connected"}),e.jsx(ft,{category:"counts",checks:[],info:k,meta:S!=null&&S.activeProject?`active: ${S.activeProject}`:"no active project"}),e.jsxs(ee,{className:"doctor-errors-card",children:[e.jsxs(ae,{children:[e.jsx(xs,{size:14,"aria-hidden":!0}),e.jsx("span",{children:"Recent errors (last hour)"}),e.jsxs("span",{className:"card-meta-inline muted",children:[a.recentErrors.length," line",a.recentErrors.length===1?"":"s"]})]}),a.recentErrors.length===0?e.jsx("div",{className:"muted doctor-errors-empty",children:"No errors in the last hour. Nice."}):e.jsx("ul",{className:"doctor-errors-list",role:"list",children:a.recentErrors.map((R,j)=>e.jsxs("li",{className:"doctor-error-row",children:[e.jsx("span",{className:"doctor-error-ts mono",children:R.ts?Ze(new Date(R.ts)):"??:??:??"}),e.jsx("span",{className:"doctor-error-line mono",children:R.line})]},`${R.tsMs??j}-${j}`))})]}),e.jsxs(ee,{className:"doctor-actions-card",children:[e.jsxs(ae,{children:[e.jsx(bt,{size:14,"aria-hidden":!0})," Actions"]}),e.jsx(ie,{children:"Run a check, view logs, or export the snapshot."}),e.jsxs("div",{className:"doctor-actions-row",children:[e.jsxs($,{variant:"primary",onClick:p,disabled:o,children:[o?e.jsx(me,{size:"sm"}):e.jsx(ce,{size:12}),o?"Running…":"Run Health Check Now"]}),e.jsxs($,{variant:"secondary",onClick:y,children:[e.jsx(Te,{size:12})," View Full Logs"]}),e.jsxs($,{variant:"secondary",onClick:f,children:[e.jsx(qe,{size:12})," Export Diagnostics as JSON"]}),e.jsx($,{variant:"ghost",onClick:()=>d(R=>!R),title:"Toggle auto-refresh",children:u?"Pause auto-refresh":"Resume auto-refresh"})]}),a.checks.services.some(R=>R.status!=="ok")||a.checks.config.some(R=>R.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(R=>R.status!=="ok").map(R=>e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>g(R.name),title:`Run check: ${R.name}`,children:[e.jsx(bt,{size:10})," ",R.name]},R.name))})]}):null]})]})]})}const cc=We.memo(oc),vt={overview:Di,chat:Zi,agents:nr,artifacts:Ar,memory:Ro,tasks:_r,activity:Jr,background:Jo,config:Yt,settings:Yt,mods:Il,schedules:ql,skills:eo,history:Ao,minimax:Bo,doctor:cc},dc="v4.5.0";function mc(s,t,a,i){if(vt[s]){const o=vt[s];return e.jsx(o,{...t})}const n=a.find(o=>o.id===s);if(n)return e.jsx(El,{viewId:n.id,reloadKey:i,activeTab:t.activeTab,setActiveTab:t.setActiveTab});const c=vt.overview;return e.jsx(c,{...t})}function uc({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&&(z.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 hc(){return e.jsx(Gn,{children:e.jsx(Xn,{children:e.jsx(xc,{})})})}function xc(){var H,Q,le;const s=re(),t=Ae(),{isModalOpen:a}=t,i=r.useRef(!1),[n,c]=r.useState("overview"),[o,l]=r.useState(null),[h,x]=r.useState(null),[u,d]=r.useState("connecting"),[m,p]=r.useState(null),[g,f]=r.useState(!1),[y,S]=r.useState(null),[k,w]=r.useState(!1),[E,v]=r.useState(!1),[C,R]=r.useState([]),[j,P]=r.useState(!1),[T,b]=r.useState([]),[A,O]=r.useState(0),N=r.useRef(null),[F,K]=r.useState(null);r.useEffect(()=>{let _=!1;return(async()=>{try{const D=await z.get("/mods/views");if(_)return;b(D.views||[])}catch{_||b([])}})(),()=>{_=!0}},[A,o==null?void 0:o.mods]),r.useEffect(()=>{if(!F)return;const _=F.on(D=>{((D==null?void 0:D.type)==="mod:change"||(D==null?void 0:D.type)==="mod:enabled"||(D==null?void 0:D.type)==="mod:installed")&&O(se=>se+1)});return()=>_()},[F]),r.useEffect(()=>{h!=null&&h.theme&&(zs(h.theme),hs(h.theme))},[h==null?void 0:h.theme]),r.useEffect(()=>{i.current=a},[a]),r.useEffect(()=>{var se;if(((se=h==null?void 0:h.theme)==null?void 0:se.mode)!=="system")return;const _=window.matchMedia("(prefers-color-scheme: light)"),D=()=>zs(h.theme.mode);return _.addEventListener("change",D),()=>_.removeEventListener("change",D)},[(H=h==null?void 0:h.theme)==null?void 0:H.mode]);const L=r.useCallback(async()=>{let _=!1;const D=()=>Promise.all([z.get("/snapshot").catch(()=>null),z.get("/settings").catch(()=>null),z.get("/agents/stuck").catch(()=>null)]),se=(W,oe,q)=>{W&&l(W),oe!=null&&oe.data&&x(oe.data),q!=null&&q.stuck&&R(q.stuck)};try{const W=await z.probeAuthStatus(),[oe,q,de]=await D();if(se(oe,q,de),oe||q){p(null);return}if(!W.loopback){p("Dashboard server unreachable.");return}await new Promise(Ge=>setTimeout(Ge,1e3));const[Re,Le,Be]=await D();se(Re,Le,Be),!Re&&!Le&&p("Dashboard server unreachable.")}catch(W){const oe=(W==null?void 0:W.message)??"unknown error";if(W instanceof Ha&&W.status===401){p(oe),w(!0),s.error(`Auth required: ${oe}`);return}p(oe),s.error(`Failed to load: ${oe}`)}},[s]);r.useEffect(()=>{let _=!1;const D=setTimeout(()=>{_||L()},0);return()=>{_=!0,clearTimeout(D)}},[L]),r.useEffect(()=>{let _=!1;return z.get("/settings").then(D=>{var W,oe;if(_)return;const se=(oe=(W=D==null?void 0:D.data)==null?void 0:W.ui)==null?void 0:oe.defaultTab;se&&c(se)}).catch(()=>{}),()=>{_=!0}},[]),r.useEffect(()=>{let _=!1;const D=async()=>{try{const W=await z.get("/agents/stuck");_||R(oe=>{const q=W.stuck||[];return oe.length===0&&q.length>0&&s.warning(`${q.length} agent${q.length===1?"":"s"} stuck`,5e3),q})}catch{}},se=setInterval(D,3e4);return D(),()=>{_=!0,clearInterval(se)}},[]),r.useEffect(()=>{const _=new Ct;N.current=_,K(_);const D=_.onStatus(W=>d(W)),se=_.on(W=>{var oe;if(W.type==="snapshot"&&"data"in W&&W.data)l(q=>({...q??{},...W.data}));else if(W.type==="change"){const q=W,de=((oe=q.path)==null?void 0:oe.split("/").pop())||q.path||"";s.info(`File changed: ${de}`,2500)}else if(W.type==="tasks:change"){const q=W;l(de=>{if(!de)return de;const Re=(de.tasks||[]).map(Be=>Be.id===q.task.id?q.task:Be),Le=Re.some(Be=>Be.id===q.task.id);return{...de,tasks:Le?Re:[q.task,...Re]}})}else if(W.type==="tasks:delete"){const q=W;l(de=>de&&{...de,tasks:(de.tasks||[]).filter(Re=>Re.id!==q.id)})}else if(W.type==="settings:change"){const q=W;q.settings&&x(q.settings)}else if(W.type==="project:change")z.get("/snapshot").then(q=>l(de=>({...de??{},...q}))).catch(()=>{});else if(W.type==="agents:change"||W.type==="schedules:change")z.get("/snapshot").then(q=>l(de=>({...de??{},...q}))).catch(()=>{});else if(W.type==="agent:status"||W.type==="agent:restarted"){const q=W;l(de=>{if(!de)return de;const Re=(de.agents||[]).map(Le=>Le.name===q.agent.name?q.agent:Le);return{...de,agents:Re}})}else if(W.type==="artifact:change")z.get("/artifacts").then(q=>{l(de=>de&&{...de,artifacts:q.artifacts||[]})}).catch(()=>{});else if(W.type==="agent:stuck")R(W.agents||[]);else if(W.type==="dialog:show"){const q=W;q.dialog&&t.open({title:q.dialog.title,width:520,children:e.jsx(Ni,{dialog:q.dialog,onClose:()=>t.close()})})}});return()=>{D(),se(),_.close(),K(null)}},[s]);const G=r.useCallback(_=>F?F.on(_):()=>{},[F]),ne=r.useRef(0);r.useEffect(()=>{const _=()=>{ne.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 _={};kt.forEach((se,W)=>{_[String(W+1)]=se.id});const D=se=>{var Ge,Ps,ys,Fs;if((se.metaKey||se.ctrlKey)&&se.key.toLowerCase()==="k"){se.preventDefault(),v(!0);return}if(se.key==="/"&&!se.metaKey&&!se.ctrlKey){const bs=(Ps=(Ge=se.target)==null?void 0:Ge.tagName)==null?void 0:Ps.toLowerCase();if(bs!=="input"&&bs!=="textarea"&&!((ys=se.target)!=null&&ys.isContentEditable)){se.preventDefault(),v(!0);return}}const W=document.activeElement;if(!W||W===document.body||W===document.documentElement)return;const q=se.target,de=(Fs=q==null?void 0:q.tagName)==null?void 0:Fs.toLowerCase(),Re=de==="input"||de==="textarea"||de==="select"||de==="button"||de==="option"||de==="label"||!!(q!=null&&q.isContentEditable);let Le=!1;if(q&&typeof q.closest=="function"&&(Le=!!q.closest('form, [role="dialog"], [contenteditable], [data-no-key]')),se.repeat||i.current||Re||Le||se.metaKey||se.ctrlKey||se.altKey||se.shiftKey||Date.now()<ne.current)return;const Be=_[se.key];Be&&(se.preventDefault(),B(Be))};return document.addEventListener("keydown",D),()=>document.removeEventListener("keydown",D)},[]);const te=r.useMemo(()=>async()=>{try{const _=await z.get("/snapshot");l(D=>({...D??{},..._}))}catch(_){s.error(`Refresh failed: ${_.message}`)}},[s]),B=r.useCallback(_=>{c(_),f(_==="settings")},[]),V=r.useMemo(()=>{const _=T.map(D=>({id:D.id,label:D.label,icon:D.kind==="iframe"?Is:Es,isMod:!0,modId:D.modId}));return[...kt,..._]},[T]),X=r.useMemo(()=>o&&h?mc(n,{snapshot:o,settings:h,activeTab:n,setActiveTab:B,refreshSnapshot:te,settingsMode:g,settingsActiveSection:y,setSettingsActiveSection:S},T,A):null,[n,o,h,T,A,te,g,y,S,B]),U=async()=>{try{const _=await z.get("/projects");l(D=>{var se;return D&&{...D,projects:_.projects||[],activeProject:((se=_.projects)==null?void 0:se.find(W=>W.id===_.active))||null}})}catch(_){s.error(`Projects refresh failed: ${_.message}`)}},J=async _=>{try{await z.post(`/projects/${encodeURIComponent(_)}/activate`),l(D=>D&&{...D,activeProject:D.projects.find(se=>se.id===_)||null})}catch(D){s.error(`Activate failed: ${D.message}`)}},he=_=>{const D=_.type;if(D==="agent")B("agents");else if(D==="task")B("tasks");else if(D==="mod")B("mods");else if(D==="schedule")B("schedules");else if(D==="project"){const se=_.item.id;J(se)}else if(D==="command")s.info(`/${_.item.name} — run from the TUI`,2500);else if(D==="setting"){const se=_.item.id||_.item.path||"";B("settings");const W=oe=>{if(oe<=0)return;const q=se?document.querySelector(`[data-setting-id="${CSS.escape(se)}"]`):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(()=>W(oe-1),80)};window.setTimeout(()=>W(15),60)}},ye=((Q=h==null?void 0:h.ui)==null?void 0:Q.layout)||"topnav",I=((le=h==null?void 0:h.ui)==null?void 0:le.showHeader)!==!1;return e.jsxs("div",{className:"app","data-layout":ye,"data-active-tab":n,children:[e.jsx("a",{className:"skip-to-main",href:"#main-content",children:"Skip to main content"}),I&&e.jsx(ri,{activeTab:n,onTabChange:B,wsStatus:u,version:dc,activeProject:(o==null?void 0:o.activeProject)||null,projects:(o==null?void 0:o.projects)||[],onProjectChange:J,onProjectsRefresh:U,onOpenSearch:()=>v(!0),settings:h,notificationsSlot:e.jsx(pi,{wsSubscribe:G}),showTabs:ye==="topnav",extraTabs:V}),C.length>0&&!j&&e.jsxs("div",{className:"stuck-banner",role:"alert",children:[e.jsx(be,{size:16}),e.jsxs("span",{children:[e.jsx("strong",{children:C.length})," agent",C.length===1?"":"s"," stuck:"," ",e.jsx("span",{className:"mono",children:C.map(_=>_.name).join(", ")})]}),e.jsx($,{variant:"secondary",size:"sm",onClick:()=>{B("agents"),P(!0)},children:"Review"}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Dismiss",onClick:()=>P(!0),children:e.jsx(ke,{size:14})})]}),e.jsxs("div",{className:"layout-body",children:[ye!=="topnav"&&e.jsx(mi,{tabs:V,activeTab:n,onTabChange:B,settingsMode:g,settingsActiveSection:y,onSettingsSectionChange:S,onExitSettings:()=>B("overview")}),e.jsxs("main",{className:"content",id:"main-content",tabIndex:-1,children:[m&&e.jsxs("div",{className:"boot-error",children:[e.jsx("h2",{children:"Dashboard unavailable"}),e.jsx("p",{children:m}),k&&e.jsx(uc,{onSaved:()=>{w(!1),L()}}),e.jsxs("p",{className:"boot-error-hint",children:["Make sure the Bizar dashboard server is running. Try"," ",e.jsx("code",{children:"bizar-dash start"})," in your terminal."]})]}),!m&&(!o||!h)&&e.jsxs("div",{className:"loading",children:[e.jsx(me,{size:"lg"}),e.jsx("p",{children:"Loading Bizar…"})]}),X&&e.jsx(r.Suspense,{fallback:e.jsxs("div",{className:"loading",children:[e.jsx(me,{size:"lg"}),e.jsx("p",{children:"Loading…"})]}),children:e.jsx(pc,{children:X})})]})]}),e.jsx(ui,{open:E,onClose:()=>v(!1),onSelect:he})]})}class pc 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(be,{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 gc(){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(qa,{}):e.jsx(hc,{})}const Da=document.getElementById("root");if(!Da)throw new Error("Root element #root not found");Ka(Da).render(e.jsx(r.StrictMode,{children:e.jsx(gc,{})}));