@polderlabs/bizar 5.0.0 → 5.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/bizar-dash/dist/assets/{icons-CFqu2M-c.js → icons-Bo0iH9EC.js} +166 -121
  2. package/bizar-dash/dist/assets/icons-Bo0iH9EC.js.map +1 -0
  3. package/bizar-dash/dist/assets/main-C1cpttnv.js +19 -0
  4. package/bizar-dash/dist/assets/main-C1cpttnv.js.map +1 -0
  5. package/bizar-dash/dist/assets/main-DTkNlLrw.css +1 -0
  6. package/bizar-dash/dist/assets/mobile-BtxQJftK.js +2 -0
  7. package/bizar-dash/dist/assets/mobile-BtxQJftK.js.map +1 -0
  8. package/bizar-dash/dist/assets/{mobile-DHXXbn1A.js → mobile-DD-FZrTC.js} +1 -1
  9. package/bizar-dash/dist/assets/{mobile-DHXXbn1A.js.map → mobile-DD-FZrTC.js.map} +1 -1
  10. package/bizar-dash/dist/index.html +4 -4
  11. package/bizar-dash/dist/mobile.html +3 -3
  12. package/bizar-dash/node_modules/.package-lock.json +6 -0
  13. package/bizar-dash/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -1
  14. package/bizar-dash/package-lock.json +6 -0
  15. package/bizar-dash/src/server/api.mjs +7 -0
  16. package/bizar-dash/src/server/diagnostics-store.mjs +452 -2
  17. package/bizar-dash/src/server/memory-store.mjs +46 -0
  18. package/bizar-dash/src/server/providers-store.mjs +11 -4
  19. package/bizar-dash/src/server/routes/_shared.mjs +2 -2
  20. package/bizar-dash/src/server/routes/doctor.mjs +71 -0
  21. package/bizar-dash/src/server/routes/env-vars.mjs +67 -1
  22. package/bizar-dash/src/server/routes/memory.mjs +3 -0
  23. package/bizar-dash/src/server/routes/opencode-session-detail.mjs +61 -42
  24. package/bizar-dash/src/server/routes/schedules.mjs +55 -0
  25. package/bizar-dash/src/server/serve-info.mjs +172 -0
  26. package/bizar-dash/src/web/App.tsx +48 -11
  27. package/bizar-dash/src/web/components/AutosaveField.tsx +50 -0
  28. package/bizar-dash/src/web/components/DoctorPanel.tsx +160 -0
  29. package/bizar-dash/src/web/components/EnvVarManager.tsx +245 -62
  30. package/bizar-dash/src/web/components/ScheduleTemplateCard.tsx +71 -0
  31. package/bizar-dash/src/web/components/SettingsNav.tsx +101 -0
  32. package/bizar-dash/src/web/components/Sidebar.tsx +25 -1
  33. package/bizar-dash/src/web/components/StatusBadge.tsx +33 -2
  34. package/bizar-dash/src/web/components/Topbar.tsx +11 -0
  35. package/bizar-dash/src/web/components/chat/ChatInfoPanel.tsx +64 -0
  36. package/bizar-dash/src/web/components/chat/Composer.tsx +1 -1
  37. package/bizar-dash/src/web/components/chat/useChat.ts +118 -1
  38. package/bizar-dash/src/web/hooks/useAutosave.ts +107 -0
  39. package/bizar-dash/src/web/lib/types.ts +134 -0
  40. package/bizar-dash/src/web/styles/chat.css +8 -5
  41. package/bizar-dash/src/web/styles/main.css +77 -2
  42. package/bizar-dash/src/web/styles/settings.css +265 -0
  43. package/bizar-dash/src/web/views/Chat.tsx +15 -1
  44. package/bizar-dash/src/web/views/Doctor.tsx +317 -0
  45. package/bizar-dash/src/web/views/MiniMaxUsage.tsx +1 -0
  46. package/bizar-dash/src/web/views/Schedules.tsx +94 -12
  47. package/bizar-dash/src/web/views/Settings.tsx +76 -46
  48. package/bizar-dash/src/web/views/memory/ConfigPanel.tsx +114 -133
  49. package/bizar-dash/src/web/views/settings/AgentSection.tsx +23 -12
  50. package/bizar-dash/src/web/views/settings/EnvVarsSection.tsx +5 -6
  51. package/bizar-dash/src/web/views/settings/GeneralSection.tsx +38 -15
  52. package/bizar-dash/src/web/views/settings/MemorySection.tsx +92 -8
  53. package/bizar-dash/tests/autosave.test.tsx +276 -0
  54. package/bizar-dash/tests/chat-composer.test.tsx +140 -0
  55. package/bizar-dash/tests/components/doctor-panel.test.tsx +105 -0
  56. package/bizar-dash/tests/diagnostics-store.test.mjs +206 -0
  57. package/bizar-dash/tests/env-vars-extended.test.mjs +190 -0
  58. package/bizar-dash/tests/layout-spacing.test.mjs +101 -0
  59. package/bizar-dash/tests/memory-default-vault.test.mjs +98 -0
  60. package/bizar-dash/tests/minimax-bar.test.tsx +113 -0
  61. package/bizar-dash/tests/minimax-models.test.mjs +123 -0
  62. package/bizar-dash/tests/opencode-sessions-detail.test.mjs +158 -0
  63. package/bizar-dash/tests/routes-doctor.test.mjs +159 -0
  64. package/bizar-dash/tests/schedules-templates.test.mjs +144 -0
  65. package/bizar-dash/tests/settings-layout.test.tsx +129 -0
  66. package/bizar-dash/tests/settings-mode-wiring.test.tsx +151 -0
  67. package/bizar-dash/tests/settings-nav.test.tsx +126 -0
  68. package/cli/commands/dash.mjs +5 -1
  69. package/cli/commands/minimax.mjs +5 -2
  70. package/cli/tests/minimax-cli.test.mjs +79 -0
  71. package/config/agents/frigg.md +1 -1
  72. package/config/agents/heimdall.md +1 -1
  73. package/config/agents/mimir.md +1 -1
  74. package/config/agents/quick.md +1 -1
  75. package/config/agents/semble-search.md +1 -1
  76. package/config/agents/vor.md +1 -1
  77. package/config/opencode.json +28 -21
  78. package/config/opencode.json.template +8 -1
  79. package/package.json +1 -1
  80. package/plugins/bizar/index.ts +77 -0
  81. package/plugins/bizar/src/compaction.d.mts +48 -0
  82. package/plugins/bizar/src/compaction.mjs +192 -0
  83. package/plugins/bizar/tests/compaction.test.ts +264 -0
  84. package/templates/schedules/daily-backup.json +12 -0
  85. package/templates/schedules/daily-cleanup.json +12 -0
  86. package/templates/schedules/hourly-health-check.json +12 -0
  87. package/templates/schedules/webhook-on-push.json +13 -0
  88. package/templates/schedules/weekly-digest.json +13 -0
  89. package/bizar-dash/dist/assets/icons-CFqu2M-c.js.map +0 -1
  90. package/bizar-dash/dist/assets/main-Dl8yY5_H.js +0 -16
  91. package/bizar-dash/dist/assets/main-Dl8yY5_H.js.map +0 -1
  92. package/bizar-dash/dist/assets/main-ZAfGKENE.css +0 -1
  93. package/bizar-dash/dist/assets/mobile-C2gysFOZ.js +0 -2
  94. package/bizar-dash/dist/assets/mobile-C2gysFOZ.js.map +0 -1
  95. package/bizar-dash/src/web/views/settings/BackupSection.tsx +0 -16
  96. package/bizar-dash/src/web/views/settings/ProvidersSection.tsx +0 -16
  97. package/bizar-dash/src/web/views/settings/SkillsSection.tsx +0 -16
@@ -1,16 +0,0 @@
1
- var Ra=Object.defineProperty;var $a=(s,t,a)=>t in s?Ra(s,t,{enumerable:!0,configurable:!0,writable:!0,value:a}):s[t]=a;var hs=(s,t,a)=>$a(s,typeof t!="symbol"?t+"":t,a);import{a as S,c as Y,u as Te,B as A,b as le,f as ke,d as cs,S as me,V as xt,E as Aa,C as Ma,e as La,g as Ia,h as Ea,i as Da,t as Yt,j as Pa,p as Fa,W as pt,_ as Xt,k as is,l as js,T as Oa,M as Ba,A as Ua,m as _a}from"./mobile-C2gysFOZ.js";import{r,j as e,R as qe,a as Wa,b as Ha}from"./react-vendor-DZRUXSPQ.js";import{A as Qt,R as oe,F as qa,H as Va,a as Ka,C as gt,b as Ee,c as Ga,d as Pe,e as Ve,L as Jt,M as qs,B as _e,f as Os,S as fs,g as Ae,h as Ya,i as Fe,j as Ie,P as Bs,k as Us,l as vs,m as jt,n as ft,o as ve,p as Ce,X as ze,q as Xa,r as ls,T as Ne,s as We,I as Vs,E as ds,t as we,G as os,u as _s,v as Qe,w as He,x as ot,y as Qa,z as be,D as vt,Z as yt,O as Ja,J as Za,K as ys,N as en,Q as bs,U as Ss,V as Je,W as Zt,Y as ea,_ as ks,$ as sn,a0 as ms,a1 as bt,a2 as tn,a3 as an,a4 as nn,a5 as Xe,a6 as rn,a7 as ln,a8 as on,a9 as cn,aa as dn,ab as mn,ac as Mt,ad as sa,ae as hn,af as kt,ag as un,ah as xn,ai as ta,aj as pn,ak as Gs,al as gn,am as jn,an as fn,ao as vn,ap as yn,aq as bn,ar as kn,as as Es,at as Nn,au as ct,av as aa,aw as Nt,ax as Ze,ay as na,az as Ns,aA as ia,aB as wn,aC as Sn,aD as Ws,aE as Cn,aF as ws,aG as zn,aH as Tn,aI as ra,aJ as dt,aK as Rn,aL as wt,aM as la,aN as ue,aO as $n,aP as An,aQ as Mn,aR as Ln,aS as In,aT as En,aU as oa,aV as Ys,aW as ca,aX as St,aY as Dn,aZ as Pn,a_ as da,a$ as Fn}from"./icons-CFqu2M-c.js";import{M as ma,r as ha}from"./markdown-DIquRulQ.js";const On=200,Bn=5*60*1e3,Ye=new Map;function Un(s){const t=Ye.get(s);return t?Date.now()-t.ts>Bn?(Ye.delete(s),null):t.data:null}function Xs(s,t){Ye.size>=On&&[...Ye.entries()].sort((i,n)=>i[1].ts-n[1].ts).slice(0,50).map(([i])=>i).forEach(i=>Ye.delete(i)),Ye.set(s,{data:t,ts:Date.now()})}function _n(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 Wn(s){return[...s].sort((t,a)=>t.isDir!==a.isDir?t.isDir?-1:1:t.name.localeCompare(a.name,void 0,{sensitivity:"base"}))}function Hn(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 ua({value:s,onChange:t,initialPath:a,projectsDirectory:i,rootLabel:n="Home",height:l=360}){const[d,o]=r.useState(a??i??""),[p,x]=r.useState(new Set),[u,c]=r.useState(-1),[m,h]=r.useState(null),[g,j]=r.useState({}),[b,C]=r.useState(!1),[k,N]=r.useState(null),[E,$]=r.useState(!1),[z,I]=r.useState(""),[f,F]=r.useState(null),[T,v]=r.useState(!1),w=r.useRef(null),P=r.useCallback(async O=>{try{const re=Un(O);if(re)return re;const se=await S.get("/fs?path="+encodeURIComponent(O));return Xs(O,se),se}catch{return null}},[]),y=r.useCallback(async O=>{var re;C(!0),N(null);try{const se=await S.get("/fs?path="+encodeURIComponent(O));Xs(O,se),h(se),c(-1)}catch(se){const he=((re=se.data)==null?void 0:re.message)??se.message??"Failed to load directory";N(he)}finally{C(!1)}},[]);r.useEffect(()=>{d?y(d):S.get("/fs").then(O=>{Xs("",O),h(O),o(O.path),O.path!==s&&t(O.path)}).catch(()=>{N("Could not determine home directory."),C(!1)})},[d]),r.useEffect(()=>{s&&s!==d&&o(s)},[s]);const L=m?Wn(m.entries):[],B=L.filter(O=>O.isDir),R=L,H=O=>{O.isDir&&(o(O.path),t(O.path))},ae=()=>{m!=null&&m.parent&&(o(m.parent),t(m.parent))},J=O=>{O!==d&&(o(O),t(O))},_=async()=>{const O=await P("");O&&(o(O.path),t(O.path))},X=async()=>{if(!i)return;const O=await P(i);O&&(o(O.path),t(O.path))},ee=()=>{$(!0),I(""),F(null),setTimeout(()=>{var O;return(O=w.current)==null?void 0:O.focus()},0)},Q=()=>{$(!1),I(""),F(null)},ie=async()=>{var re;const O=Hn(z);if(!O.ok){F(O.reason);return}v(!0),F(null);try{const se=await S.post("/fs/mkdir",{parent:d,name:z.trim()});Ye.delete(d),await y(d),t(se.path),$(!1),I("")}catch(se){const he=se;he.status===409?F(`A folder named "${z.trim()}" already exists.`):F(((re=he.data)==null?void 0:re.message)??se.message??"Failed to create folder.")}finally{v(!1)}},je=O=>{O.key==="Enter"?(O.preventDefault(),ie()):O.key==="Escape"&&(O.preventDefault(),Q())},V=O=>{x(re=>{const se=new Set(re);return se.has(O)?se.delete(O):se.add(O),se}),g[O]||P(O).then(re=>{re&&j(se=>({...se,[O]:re.entries.filter(he=>he.isDir)}))})},D=O=>{if(!m)return;const re=R.filter(ce=>ce.isDir),se=R.filter(ce=>!ce.isDir),he=[...re,...se];if(O.key==="ArrowDown")O.preventDefault(),c(ce=>Math.min(ce+1,he.length-1));else if(O.key==="ArrowUp")O.preventDefault(),c(ce=>Math.max(ce-1,0));else if(O.key==="Enter"||O.key===" "){O.preventDefault();const ce=he[u];ce&&(O.key==="Enter"&&ce.isDir?H(ce):ce.isDir&&t(ce.path))}else O.key==="Backspace"&&(O.preventDefault(),ae())},U=_n((m==null?void 0:m.path)??d??"/"),W=m==null?void 0:m.parent,ne=W!=null,q=d.split("/").filter(Boolean).at(-1)??"/";return e.jsxs("div",{className:"file-browser",onKeyDown:D,tabIndex:-1,children:[e.jsx("div",{className:"file-browser-breadcrumb",role:"navigation","aria-label":"Path breadcrumb",children:U.map((O,re)=>e.jsxs("span",{className:"file-browser-breadcrumb-item",children:[re>0&&e.jsx("span",{className:"file-browser-breadcrumb-sep","aria-hidden":!0,children:"/"}),e.jsx("button",{type:"button",className:"file-browser-breadcrumb-btn",onClick:()=>J(O.path),title:O.path,children:re===0?O.path==="/"?"/":n:O.label})]},O.path))}),e.jsxs("div",{className:"file-browser-toolbar",children:[e.jsxs("div",{className:"file-browser-toolbar-left",children:[e.jsx("button",{type:"button",className:"file-browser-tool-btn",onClick:ae,disabled:!ne,title:"Go up (Backspace)","aria-label":"Go up one level",children:e.jsx(Qt,{size:13})}),e.jsx("button",{type:"button",className:"file-browser-tool-btn",onClick:()=>y(d),disabled:b,title:"Refresh","aria-label":"Refresh",children:e.jsx(oe,{size:13,className:b?"spin":""})}),e.jsx("button",{type:"button",className:"file-browser-tool-btn",onClick:ee,title:"New folder","aria-label":"Create new folder",children:e.jsx(qa,{size:13})}),e.jsxs("div",{className:"file-browser-chips",children:[e.jsxs("button",{type:"button",className:"file-browser-chip",onClick:_,children:[e.jsx(Va,{size:11})," ",n]}),i&&e.jsxs("button",{type:"button",className:"file-browser-chip",onClick:X,title:i,children:[e.jsx(Ka,{size:11})," ",i.split("/").filter(Boolean).at(-1)??"Projects"]})]})]}),E?e.jsxs("div",{className:"file-browser-mkdir",children:[e.jsx("input",{ref:w,type:"text",className:"file-browser-mkdir-input",placeholder:"Folder name",value:z,onChange:O=>{I(O.target.value),F(null)},onKeyDown:je,"aria-label":"New folder name","aria-invalid":f?"true":void 0,"aria-describedby":f?"mkdir-error":void 0,disabled:T,maxLength:255}),f?e.jsx("span",{id:"mkdir-error",className:"file-browser-mkdir-error",role:"alert",children:f}):e.jsx("span",{className:"file-browser-mkdir-hint",children:"Enter to create, Esc to cancel"})]}):e.jsx("span",{className:"file-browser-count-hint",children:b?"…":`${L.length} in ${q}`})]}),k&&e.jsxs("div",{className:"file-browser-error",children:[e.jsx(gt,{size:13}),e.jsx("span",{children:k}),e.jsx("button",{type:"button",className:"file-browser-retry",onClick:()=>y(d),children:"Retry"})]}),e.jsxs("div",{className:"file-browser-body",style:{height:l},children:[e.jsx("div",{className:"file-browser-pane file-browser-tree","aria-label":"Folder tree",children:b&&!m?e.jsx(qn,{}):e.jsx(xa,{path:d,entries:B,expanded:p,childrenMap:g,onToggle:V,onNavigate:H,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"})]}),b&&!m?e.jsx(Vn,{}):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."]}),R.length===0?e.jsx("div",{className:"file-browser-empty",children:"This folder is empty"}):e.jsx("div",{className:"file-browser-flat-list",children:R.map((O,re)=>{const se=O.isDir,he=re===u,ce=O.path===s;return e.jsxs("div",{role:"option","aria-selected":ce,className:["file-browser-row",se?"file-browser-row--dir":"file-browser-row--file",he&&"file-browser-row--selected",ce&&se&&"file-browser-row--active",!se&&"file-browser-row--disabled"].filter(Boolean).join(" "),onClick:()=>{se&&(c(re),t(O.path))},onDoubleClick:()=>{se&&H(O)},title:O.path,children:[e.jsx("span",{className:"file-browser-row-icon",children:se?e.jsx(Ee,{size:13}):e.jsx(Ga,{size:13})}),e.jsx("span",{className:"file-browser-row-name",children:O.name}),e.jsx("span",{className:"file-browser-row-type",children:se?"Folder":""})]},O.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 xa({path:s,entries:t,expanded:a,childrenMap:i,onToggle:n,onNavigate:l,level:d}){return e.jsx("ul",{className:"file-browser-tree-list",role:"group",children:t.map(o=>{const p=a.has(o.path),x=i[o.path]??[];return e.jsxs("li",{className:"file-browser-tree-node",children:[e.jsxs("div",{className:["file-browser-tree-row",p&&"file-browser-tree-row--expanded"].filter(Boolean).join(" "),style:{paddingLeft:`${d*16+8}px`},children:[e.jsx("button",{type:"button",className:"file-browser-tree-toggle",onClick:u=>{u.stopPropagation(),n(o.path)},"aria-label":p?"Collapse":"Expand",children:(x.length>0,p?e.jsx(Pe,{size:11}):e.jsx(Ve,{size:11}))}),e.jsxs("button",{type:"button",className:"file-browser-tree-name",onClick:()=>l(o),title:o.path,children:[e.jsx(Ee,{size:12}),e.jsx("span",{children:o.name})]})]}),p&&x.length>0&&e.jsx(xa,{path:o.path,entries:x,expanded:a,childrenMap:i,onToggle:n,onNavigate:l,level:d+1})]},o.path)})})}function qn(){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 Vn(){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 mt=[{id:"overview",label:"Overview",icon:Jt},{id:"chat",label:"Chat",icon:qs},{id:"agents",label:"Agents",icon:_e},{id:"artifacts",label:"Glyphs",icon:Os},{id:"tasks",label:"Tasks",icon:fs},{id:"activity",label:"Activity",icon:Ae},{id:"background",label:"Active",icon:Ya},{id:"skills",label:"Skills",icon:Fe},{id:"memory",label:"Memory",icon:Ie},{id:"mods",label:"Mods",icon:Bs},{id:"schedules",label:"Schedules",icon:Us},{id:"history",label:"History",icon:vs},{id:"minimax",label:"Usage",icon:jt},{id:"settings",label:"Settings",icon:ft}];function Kn({activeTab:s,onTabChange:t,wsStatus:a,version:i,activeProject:n,projects:l,onProjectChange:d,onProjectsRefresh:o,onOpenSearch:p,settings:x,rightSlot:u,notificationsSlot:c,showTabs:m=!0,extraTabs:h}){return e.jsxs("header",{className:"topbar",children:[e.jsxs("div",{className:"topbar-row",children:[e.jsxs("div",{className:"brand",children:[e.jsx("span",{className:"brand-logo","aria-hidden":"true",children:"ᛒ"}),e.jsx("span",{className:"brand-title",children:"Bizar"}),e.jsx("span",{className:"brand-version",children:i})]}),e.jsx(Gn,{activeProject:n,projects:l,onChange:d,onRefresh:o,settings:x??null}),e.jsxs("button",{type:"button",className:"topbar-search",onClick:p,title:"Search (Ctrl/Cmd+K)","aria-label":"Open search",children:[e.jsx(ve,{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:[c,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:[mt.map(g=>{const j=g.icon,b=g.id===s;return e.jsxs("button",{type:"button",role:"tab","aria-selected":b,className:Y("tab",b&&"tab-active"),onClick:()=>t(g.id),title:g.label,children:[e.jsx(j,{size:14,className:"tab-icon"}),e.jsx("span",{className:"tab-label",children:g.label})]},g.id)}),h&&h.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"tab-separator","aria-hidden":"true"}),h.map(g=>{const j=g.icon,b=g.id===s;return e.jsxs("button",{type:"button",role:"tab","aria-selected":b,className:Y("tab","tab-mod",b&&"tab-active"),onClick:()=>t(g.id),title:`${g.label} (mod)`,children:[e.jsx(j,{size:14,className:"tab-icon"}),e.jsx("span",{className:"tab-label",children:g.label}),e.jsx("span",{className:"tab-badge",children:"mod"})]},g.id)})]})]})]})}function Gn({activeProject:s,projects:t,onChange:a,onRefresh:i,settings:n}){const[l,d]=r.useState(!1),o=Te();r.useEffect(()=>{if(!l)return;const x=()=>d(!1);return document.addEventListener("click",x),()=>document.removeEventListener("click",x)},[l]);const p=()=>{o.open({title:"Add project",children:e.jsx(Yn,{settings:n,onAdd:async(x,u)=>{try{await S.post("/projects",{path:x,name:u}),i(),d(!1),o.close()}catch(c){alert(`Add failed: ${c.message}`)}}}),footer:e.jsx("div",{className:"modal-footer-actions",children:e.jsx(A,{variant:"ghost",onClick:()=>o.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:()=>d(x=>!x),title:"Switch active project","aria-haspopup":"menu","aria-expanded":l,children:[e.jsx(Ee,{size:14}),e.jsx("span",{className:"project-selector-name",children:(s==null?void 0:s.name)||"(no project)"}),e.jsx(Pe,{size:12})]}),l&&e.jsxs("div",{className:"project-selector-menu",children:[e.jsxs("div",{className:"project-selector-menu-head",children:[e.jsxs("span",{className:"muted",children:[t.length," project",t.length===1?"":"s"]}),e.jsxs("div",{className:"project-selector-menu-actions",children:[e.jsx("button",{type:"button",className:"icon-btn",onClick:i,title:"Refresh","aria-label":"Refresh projects",children:e.jsx(oe,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn",onClick:p,title:"Add project","aria-label":"Add project",children:e.jsx(Ce,{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),d(!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 Yn({settings:s,onAdd:t}){var c,m;const[a,i]=r.useState(((c=s==null?void 0:s.dashboard)==null?void 0:c.projectsDirectory)??""),[n,l]=r.useState(""),[d,o]=r.useState(!1),[p,x]=r.useState(null),u=async()=>{var h;if(a){o(!0),x(null);try{await S.get("/fs?path="+encodeURIComponent(a)),t(a,n||null)}catch(g){const j=g;j.status===404?x("That folder no longer exists. Pick another."):x(((h=j.data)==null?void 0:h.message)??g.message??"Validation failed.")}finally{o(!1)}}};return e.jsxs("div",{children:[e.jsx("label",{className:"field-label",children:"Folder"}),e.jsx(ua,{value:a,onChange:h=>{i(h),x(null)},projectsDirectory:(m=s==null?void 0:s.dashboard)==null?void 0:m.projectsDirectory,height:320}),p&&e.jsx("p",{className:"field-help",style:{color:"var(--error)",marginTop:4},children:p}),e.jsxs("div",{style:{marginTop:"var(--space-3)"},children:[e.jsx("label",{className:"field-label",htmlFor:"topbar-add-project-name",children:"Name (optional)"}),e.jsx("input",{id:"topbar-add-project-name",className:"input",type:"text",placeholder:"My App",value:n,onChange:h=>l(h.target.value)})]}),e.jsx("div",{style:{marginTop:"var(--space-3)",display:"flex",justifyContent:"flex-end"},children:e.jsxs(A,{variant:"primary",onClick:u,disabled:!a||d,children:[d?e.jsx("span",{className:"btn-spinner"}):null,d?"Checking…":"Add"]})})]})}function Xn({tabs:s,activeTab:t,onTabChange:a}){const i=s.filter(l=>!l.isMod),n=s.filter(l=>l.isMod);return e.jsx("aside",{className:"sidebar","aria-label":"Primary navigation",children:e.jsxs("nav",{className:"sidebar-nav",role:"tablist",children:[i.map(l=>{const d=l.icon,o=l.id===t;return e.jsxs("button",{type:"button",role:"tab","aria-selected":o,className:Y("sidebar-tab",o&&"sidebar-tab-active"),onClick:()=>a(l.id),title:l.label,children:[e.jsx(d,{size:18,"aria-hidden":!0}),e.jsx("span",{className:"sidebar-tab-label",children:l.label})]},l.id)}),n.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"sidebar-section-divider","aria-hidden":"true"}),e.jsx("div",{className:"sidebar-section-label",children:"Mods"}),n.map(l=>{const d=l.icon,o=l.id===t;return e.jsxs("button",{type:"button",role:"tab","aria-selected":o,className:Y("sidebar-tab","sidebar-tab-mod",o&&"sidebar-tab-active"),onClick:()=>a(l.id),title:`${l.label} (mod)`,children:[e.jsx(d,{size:18,"aria-hidden":!0}),e.jsx("span",{className:"sidebar-tab-label",children:l.label})]},l.id)})]})]})})}const Qs=[{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"}],Lt={all:null,projects:"project",agents:"agent",tasks:"task",mods:"mod",schedules:"schedule",commands:"command",settings:"setting"};function Qn({open:s,onClose:t,onSelect:a}){const i=le(),[n,l]=r.useState(""),[d,o]=r.useState("all"),[p,x]=r.useState([]),[u,c]=r.useState(!1),[m,h]=r.useState(0),g=r.useRef(null),j=r.useRef(null);if(r.useEffect(()=>{let N;return s&&(j.current=document.activeElement instanceof HTMLElement?document.activeElement:null,l(""),x([]),h(0),N=window.setTimeout(()=>{var E;return(E=g.current)==null?void 0:E.focus()},30)),()=>{if(N&&window.clearTimeout(N),!s)return;const E=j.current;E&&E.isConnected&&E.focus()}},[s]),r.useEffect(()=>{if(!s)return;if(!n.trim()){x([]),h(0);return}let N=!1;c(!0);const E=setTimeout(()=>{S.get(`/search?q=${encodeURIComponent(n)}&scope=${d}`).then($=>{N||(x($.results||[]),h(0))}).catch($=>{N||i.error(`Search failed: ${$.message}`)}).finally(()=>!N&&c(!1))},150);return()=>{N=!0,clearTimeout(E)}},[n,d,s,i]),!s)return null;const b={};for(const N of p){const E=N.type.toLowerCase();b[E]=b[E]||[],b[E].push(N)}const C=[];for(const N of Qs.map(E=>E.id)){const E=Lt[N];E&&b[E]&&C.push(...b[E])}const k=N=>{if(N.key==="Escape")t();else if(N.key==="ArrowDown"){if(N.preventDefault(),C.length===0)return;h(E=>Math.min(E+1,C.length-1))}else if(N.key==="ArrowUp"){if(N.preventDefault(),C.length===0)return;h(E=>Math.max(E-1,0))}else N.key==="Enter"&&C[m]&&(N.preventDefault(),a(C[m]),t())};return e.jsx("div",{className:"search-modal-backdrop",onClick:t,children:e.jsxs("div",{className:"search-modal",role:"dialog","aria-modal":"true","aria-labelledby":"search-modal-title",onClick:N=>N.stopPropagation(),children:[e.jsxs("div",{className:"search-modal-head",role:"search",children:[e.jsx(ve,{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:N=>l(N.target.value),onKeyDown:k,"aria-label":"Search"}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Close",onClick:t,children:e.jsx(ze,{size:14})})]}),e.jsx("div",{className:"search-modal-scopes",role:"tablist","aria-label":"Search scope",children:Qs.map(N=>e.jsx("button",{type:"button",role:"tab","aria-selected":d===N.id,className:Y("search-scope",d===N.id&&"search-scope-active"),onClick:()=>o(N.id),children:N.label},N.id))}),e.jsxs("div",{className:"search-modal-body",children:[u&&e.jsx("div",{className:"muted",children:"Searching…"}),!u&&n&&C.length===0&&e.jsx("div",{className:"muted",children:"No results."}),!u&&!n&&e.jsx("div",{className:"muted",children:"Type to search…"}),Qs.map(N=>{const E=Lt[N.id];if(!E)return null;const $=b[E];return!$||$.length===0?null:e.jsxs("div",{className:"search-group",children:[e.jsx("div",{className:"search-group-head",children:N.label}),$.map(z=>{const I=C.indexOf(z);return e.jsxs("button",{type:"button",className:Y("search-result",I===m&&"search-result-active"),onMouseEnter:()=>h(I),onClick:()=>{a(z),t()},children:[e.jsx("span",{className:"search-result-type",children:z.type}),e.jsx("span",{className:"search-result-label",children:Jn(z)})]},`${z.type}-${I}`)})]},N.id)})]}),e.jsx("div",{className:"search-modal-foot",children:e.jsx("span",{className:"muted",children:"↑↓ navigate · ↵ open · esc close"})})]})})}function Jn(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 Zn={info:Vs,success:We,warning:Ne,error:gt};function ei({onCountChange:s,wsSubscribe:t}){const a=le(),[i,n]=r.useState(!1),[l,d]=r.useState([]),[o,p]=r.useState(null),[x,u]=r.useState(!1),c=r.useRef(null),m=r.useRef(0),h=async()=>{var k;try{u(!0);const N=await S.get("/notifications?limit=200");d(N.notifications||[]),p(N.stats||null),m.current=((k=N.stats)==null?void 0:k.unread)||0,s==null||s(m.current)}catch(N){console.warn("[notifications] reload failed:",N.message)}finally{u(!1)}};r.useEffect(()=>{h()},[]),r.useEffect(()=>t?t(N=>{if(N.type==="notification:new"){const E=N.notification;d($=>[E,...$.filter(z=>z.id!==E.id)]),E.read||(m.current+=1,p($=>$?{...$,unread:($.unread||0)+1}:{total:1,unread:1,lastTs:E.ts,counts:{[E.severity||"info"]:1}}),s==null||s(m.current))}else N.type==="notifications:change"&&h()}):void 0,[t]),r.useEffect(()=>{if(!i)return;const k=E=>{c.current&&(c.current.contains(E.target)||n(!1))},N=E=>{E.key==="Escape"&&n(!1)};return document.addEventListener("mousedown",k),document.addEventListener("keydown",N),()=>{document.removeEventListener("mousedown",k),document.removeEventListener("keydown",N)}},[i]);const g=async()=>{try{await S.post("/notifications/read-all",{}),d(k=>k.map(N=>({...N,read:!0}))),p(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}`)}},j=async k=>{try{await S.post(`/notifications/${encodeURIComponent(k)}/read`,{}),d(N=>N.map(E=>E.id===k?{...E,read:!0}:E)),p(N=>N&&{...N,unread:Math.max(0,(N.unread||1)-1)}),m.current=Math.max(0,m.current-1),s==null||s(m.current)}catch(N){a.error(`Failed: ${N.message}`)}},b=async k=>{try{await S.del(`/notifications/${encodeURIComponent(k)}`),d(N=>{const E=N.find($=>$.id===k);return E&&!E.read&&(m.current=Math.max(0,m.current-1),p($=>$&&{...$,unread:Math.max(0,$.unread-1)}),s==null||s(m.current)),N.filter($=>$.id!==k)})}catch(N){a.error(`Failed: ${N.message}`)}},C=(o==null?void 0:o.unread)||0;return e.jsxs("div",{className:"notifications-root",ref:c,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(Xa,{size:16}),C>0&&e.jsx("span",{className:"notifications-badge",children:C>99?"99+":C})]}),i&&e.jsxs("div",{className:"notifications-panel",role:"dialog","aria-label":"Notifications",children:[e.jsxs("header",{className:"notifications-panel-head",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Notifications"}),C>0&&e.jsxs("span",{className:"muted text-sm",children:[" · ",C," unread"]})]}),e.jsxs("div",{className:"notifications-panel-head-actions",children:[e.jsxs(A,{size:"sm",variant:"ghost",onClick:g,disabled:C===0,children:[e.jsx(ls,{size:12})," Mark all read"]}),e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>n(!1),"aria-label":"Close",title:"Close",children:e.jsx(ze,{size:14})})]})]}),e.jsx("div",{className:"notifications-list",children:x&&l.length===0?e.jsx("div",{className:"notifications-empty muted",children:"Loading…"}):l.length===0?e.jsx("div",{className:"notifications-empty muted",children:"No notifications yet."}):l.map(k=>{const N=Zn[k.severity]||Vs;return e.jsxs("div",{className:Y("notification-item",!k.read&&"is-unread",`severity-${k.severity}`),children:[e.jsx(N,{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:ke(k.ts)})]})]}),e.jsxs("div",{className:"notification-actions",children:[!k.read&&e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>j(k.id),title:"Mark as read","aria-label":"Mark as read",children:e.jsx(ls,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger",onClick:()=>b(k.id),title:"Remove","aria-label":"Remove",children:e.jsx(ze,{size:12})})]})]},k.id)})}),e.jsx("footer",{className:"notifications-panel-foot",children:e.jsx("span",{className:"muted text-sm",children:o?`${o.total} total · last ${ke(o.lastTs||new Date().toISOString())}`:""})})]})]})}function si({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,l=s==null?void 0:s.lastUsedSlug,d=i==="toggle";return e.jsxs("div",{children:[d?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})]}),l&&e.jsxs("p",{style:{fontSize:13,color:"var(--color-muted)"},children:["Last used plan: ",e.jsx("code",{children:l})]}),e.jsxs("p",{style:{marginTop:12,fontSize:13,color:"var(--color-muted)"},children:["Use ",e.jsx("code",{children:"/visual-plan on"})," or ",e.jsx("code",{children:"/visual-plan off"})," to toggle."]})]}),e.jsx("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:e.jsx(A,{variant:"ghost",onClick:t,children:"Close"})})]})}const ti=["blank","feature-design","bug-investigation","decision-record","horizontal","vertical"];function ai({data:s,onClose:t}){const a=(s==null?void 0:s.templates)??ti,i=(s==null?void 0:s.defaultTemplate)??"blank",[n,l]=r.useState(""),[d,o]=r.useState(i),[p,x]=r.useState(!1),[u,c]=r.useState(null),m=async()=>{if(!n.trim()){c("Slug is required.");return}if(!/^[a-z0-9][a-z0-9-]{0,63}$/.test(n)){c("Invalid slug. Use lowercase letters, numbers, and hyphens. Must start with an alphanumeric character.");return}x(!0),c(null);try{await S.post("/artifacts",{slug:n,template:d}),t()}catch(h){c(h.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:h=>{l(h.target.value),c(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:d,onChange:h=>o(h.target.value),children:a.map(h=>e.jsx("option",{value:h,children:h},h))})]}),u&&e.jsx("p",{style:{marginBottom:12,color:"var(--color-danger)",fontSize:13},children:u}),e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx(A,{variant:"ghost",onClick:t,disabled:p,children:"Cancel"}),e.jsx(A,{variant:"primary",onClick:m,disabled:p||!n.trim(),children:p?"Creating…":"Create"})]})]})}function ni({data:s,onClose:t}){const a=(s==null?void 0:s.plans)??[],i=(s==null?void 0:s.count)??a.length,n=l=>{window.open(`/artifacts/${l}/`,"_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(l=>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:l}),e.jsx(A,{variant:"ghost",size:"sm",onClick:()=>n(l),children:"Open"})]},l))})]}),e.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:e.jsx(A,{variant:"ghost",onClick:t,children:"Close"})})]})}function ii({data:s,onClose:t}){const a=(s==null?void 0:s.commands)??[],i=(s==null?void 0:s.templates)??[],n=(s==null?void 0:s.statuses)??[];return e.jsxs("div",{children:[a.length>0?e.jsx("table",{style:{width:"100%",borderCollapse:"collapse",marginBottom:16,fontSize:13},children:e.jsx("tbody",{children:a.map(l=>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:l.cmd})}),e.jsx("td",{style:{padding:"5px 0",color:"var(--color-muted)"},children:l.desc})]},l.cmd))})}):e.jsx("p",{style:{marginBottom:16,color:"var(--color-muted)"},children:"No commands available."}),i.length>0&&e.jsxs("div",{style:{marginBottom:12},children:[e.jsx("p",{style:{fontSize:12,color:"var(--color-muted)",marginBottom:4},children:"Available templates:"}),e.jsx("p",{style:{fontSize:13},children:i.join(", ")})]}),n.length>0&&e.jsxs("div",{style:{marginBottom:12},children:[e.jsx("p",{style:{fontSize:12,color:"var(--color-muted)",marginBottom:4},children:"Available statuses:"}),e.jsx("p",{style:{fontSize:13},children:n.join(", ")})]}),e.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:e.jsx(A,{variant:"ghost",onClick:t,children:"Close"})})]})}function ri({data:s,onClose:t}){const[a,i]=r.useState(!1),[n,l]=r.useState(null),d=async()=>{i(!0),l(null);try{const o=await S.post("/chat/audit",{});l(o)}catch(o){l({ok:!1,findings:[],error:o.message})}finally{i(!1)}};return e.jsx("div",{children:n===null?e.jsxs(e.Fragment,{children:[e.jsx("p",{style:{marginBottom:16,lineHeight:1.6},children:"Run a security audit of your Bizar agent configuration. The audit checks for common misconfigurations, exposed secrets, and insecure defaults."}),e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx(A,{variant:"ghost",onClick:t,children:"Cancel"}),e.jsx(A,{variant:"primary",onClick:d,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((o,p)=>e.jsx("li",{style:{marginBottom:4,fontSize:13},children:o},p))})]}):e.jsxs("p",{style:{marginBottom:16,color:"var(--color-danger)"},children:["Audit failed: ",n.error??"unknown error"]}),e.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:e.jsx(A,{variant:"ghost",onClick:t,children:"Close"})})]})})}function li({dialog:s,onClose:t}){if(!s.data)return e.jsxs("div",{children:[e.jsx("p",{style:{marginBottom:16,lineHeight:1.6},children:`Command: ${s.command}`}),e.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:e.jsx("button",{type:"button",className:"btn",onClick:t,children:"Close"})})]});const{message:a,detail:i,url:n}=s.data;return e.jsxs("div",{children:[e.jsx("p",{style:{marginBottom:16,lineHeight:1.6},children:a??`Command: ${s.command}`}),i&&e.jsx("p",{style:{marginBottom:16,color:"var(--color-muted)",fontSize:13},children:i}),n&&e.jsx("p",{style:{marginBottom:16},children:e.jsx("a",{href:n,target:"_blank",rel:"noopener noreferrer",children:n})}),e.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:e.jsx("button",{type:"button",className:"btn",onClick:t,children:"Close"})})]})}function oi({dialog:s,onClose:t}){switch(s.component){case"visual-artifact":return e.jsx(si,{data:s.data,onClose:t});case"artifact-create":return e.jsx(ai,{data:s.data,onClose:t});case"artifact-list":return e.jsx(ni,{data:s.data,onClose:t});case"help":return e.jsx(ii,{data:s.data,onClose:t});case"audit":return e.jsx(ri,{data:s.data,onClose:t});default:return e.jsx(li,{dialog:s,onClose:t})}}function K({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 Z({children:s,className:t}){return e.jsx("h3",{className:Y("card-title",t),children:s})}function te({children:s,className:t}){return e.jsx("div",{className:Y("card-meta",t),children:s})}function ci({setActiveTab:s,refreshKey:t=0}){var x;const[a,i]=r.useState(null),[n,l]=r.useState(!0),d=async()=>{l(!0);try{const[u,c,m]=await Promise.all([S.get("/memory/status").catch(()=>null),S.get("/memory/health").catch(()=>null),S.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:c==null?void 0:c.score,healthStatus:c==null?void 0:c.status,lightrag:m?{running:m.running,indexedApprox:m.indexedApprox}:void 0})}catch{i({initialized:!1})}finally{l(!1)}};r.useEffect(()=>{d()},[t]);const o=()=>s("memory"),p=(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(K,{className:"memory-overview-card",children:[e.jsxs(Z,{children:[e.jsx(Ie,{size:14})," Memory",e.jsxs(A,{variant:"ghost",size:"sm",style:{marginLeft:"auto"},onClick:o,children:["Open Memory ",e.jsx(ds,{size:12})]}),e.jsx(A,{variant:"ghost",size:"sm",onClick:d,"aria-label":"Refresh",title:"Refresh",children:e.jsx(oe,{size:12})})]}),e.jsx(te,{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(Ae,{size:11})," Health"]}),e.jsx("div",{className:"memory-status-card-value",style:{color:p},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(Ie,{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(we,{size:11})," Vault"]}),e.jsxs("div",{className:"memory-status-card-value",children:[a.noteCount," notes"]}),e.jsx("div",{className:"memory-status-card-sub muted ellipsis",title:a.vaultRoot||"",children:a.vaultRoot?a.vaultRoot.split("/").slice(-2).join("/"):"—"})]}),e.jsxs("div",{className:"memory-status-card-cell",children:[e.jsxs("div",{className:"memory-status-card-label",children:[e.jsx(os,{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}`:cs(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 Se({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(_s,{size:32})}),e.jsx("div",{className:"empty-title",children:t}),a&&e.jsx("div",{className:"empty-message",children:a}),i&&e.jsx("div",{className:"empty-action",children:i})]})}function di({snapshot:s,settings:t,setActiveTab:a,refreshSnapshot:i}){var H,ae,J;const n=le(),l=Te(),d=r.useRef(null),[o,p]=r.useState(s.overview??null),[x,u]=r.useState(!s.overview),[c,m]=r.useState(s.projects||[]),[h,g]=r.useState(((H=s.activeProject)==null?void 0:H.id)||null),[j,b]=r.useState(s.mods||[]),[C,k]=r.useState(!1),[N,E]=r.useState(((ae=s.overview)==null?void 0:ae.recentActivity)??[]),[$,z]=r.useState(!1),[I,f]=r.useState(new Set);r.useEffect(()=>{let _=!1;return(async()=>{try{const X=await S.get("/activity/hidden");_||f(new Set(X.hidden||[]))}catch{}})(),()=>{_=!0}},[]);const F=(_,X)=>{const ee=`${_.kind||""}|${_.ts||""}|${_.slug||_.title||""}|${X}`;let Q=0;for(let ie=0;ie<ee.length;ie++)Q=(Q<<5)-Q+ee.charCodeAt(ie)|0;return Math.abs(Q).toString(16).padStart(8,"0").slice(0,16)},T=async _=>{const X=new Set(I);X.add(_),f(X);try{await S.post("/activity/hide",{keys:[_]})}catch(ee){const Q=new Set(I);f(Q),n.error(`Hide failed: ${ee.message}`)}},v=async()=>{if(!confirm("Hide every recent activity item from the overview? The full log stays in Settings → Activity Log."))return;const _=N.map((ee,Q)=>F(ee,Q)),X=new Set(I);_.forEach(ee=>X.add(ee)),f(X);try{await S.post("/activity/hide",{keys:_}),n.success(`Hidden ${_.length} item(s). Restore them in Settings → Activity Log.`)}catch(ee){n.error(`Clear failed: ${ee.message}`)}},w=async()=>{f(new Set);try{await S.del("/activity/hide"),n.success("All hidden activity restored to the overview.")}catch(_){n.error(`Restore failed: ${_.message}`)}};r.useEffect(()=>{var _;s.overview&&(p(s.overview),E(s.overview.recentActivity??[]),u(!1)),m(s.projects||[]),g(((_=s.activeProject)==null?void 0:_.id)||null),b(s.mods||[])},[s.overview,s.projects,s.activeProject,s.mods]),r.useEffect(()=>{let _;try{const X=S.getToken(),ee=X?`/api/activity/stream?token=${encodeURIComponent(X)}`:"/api/activity/stream";_=new EventSource(ee),_.addEventListener("snapshot",Q=>{try{const ie=JSON.parse(Q.data);E(Array.isArray(ie.events)?ie.events.slice(0,50):[])}catch{}}),_.addEventListener("activity",Q=>{try{const ie=JSON.parse(Q.data);E(je=>[ie,...je].slice(0,50))}catch{}})}catch{}return()=>{try{_==null||_.close()}catch{}}},[]);const P=async()=>{n.info("Refreshing…",1500),await i();try{const _=await S.get("/projects");m(_.projects||[]),g(_.active||null)}catch{}},y=()=>{l.open({title:"Add project",children:e.jsx(mi,{settings:t,onAdd:async(_,X)=>{try{const ee=await S.post("/projects",{path:_,name:X});m(Q=>[...Q.filter(ie=>ie.id!==ee.id),ee]),n.success("Project added."),l.close()}catch(ee){n.error(`Add failed: ${ee.message}`)}}}),footer:e.jsx("div",{className:"modal-footer-actions",children:e.jsx(A,{variant:"ghost",onClick:()=>l.close(),children:"Cancel"})})})},L=async()=>{var _;try{const X=await S.post("/projects/auto-detect");m(X.projects||[]),g(X.active||null);const ee=(_=X.projects)==null?void 0:_.find(Q=>Q.id===X.active);n.success(ee?`Active: ${ee.name}`:"Projects refreshed."),await i()}catch(X){n.error(`Auto-detect failed: ${X.message}`)}},B=async _=>{try{await S.post(`/projects/${encodeURIComponent(_)}/activate`),g(_),n.success("Project activated."),await i()}catch(X){n.error(`Activate failed: ${X.message}`)}},R=async _=>{if(confirm(`Remove project "${_}" from the registry?`))try{await S.del(`/projects/${encodeURIComponent(_)}`),m(X=>X.filter(ee=>ee.id!==_)),h===_&&g(null),n.success("Project removed.")}catch(X){n.error(`Remove failed: ${X.message}`)}};return x||!o?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 _=>{var ee,Q;_.preventDefault();const X=(((ee=d.current)==null?void 0:ee.value)||"").trim();if(X){k(!0);try{const ie=await S.post("/tasks/submit",{title:X});n.success(`Odin split it into ${((Q=ie.subtasks)==null?void 0:Q.length)||1} task(s)`),d.current&&(d.current.value=""),await i()}catch(ie){n.error(`Failed: ${ie.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:d,className:"overview-input-hero",placeholder:"e.g. Implement user authentication with email + password, including registration, login, password reset, and integration tests. Use Bcrypt, JWT tokens, and the existing API style.",disabled:C,"aria-label":"Describe what you want Odin to do"}),e.jsxs("div",{style:{display:"flex",gap:"var(--space-2)",alignItems:"center",flexWrap:"wrap"},children:[e.jsxs(A,{type:"submit",variant:"primary",size:"lg",disabled:C,children:[C?e.jsx(me,{size:"sm"}):e.jsx(Qe,{size:16}),"Submit to Odin"]}),e.jsxs("span",{className:"muted",style:{fontSize:12},children:[e.jsx(Fe,{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(_=>e.jsx("button",{type:"button",className:"overview-quick-chip",onClick:()=>{d.current&&(d.current.value=_,d.current.focus())},children:_},_))})]}),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:[I.size>0&&e.jsxs(A,{variant:"ghost",size:"sm",onClick:w,title:"Restore hidden items to this overview",children:[e.jsx(He,{size:12})," Show ",I.size," hidden"]}),N.length>8&&e.jsx(A,{variant:"ghost",size:"sm",onClick:()=>z(_=>!_),children:$?"Show less":"Show all"}),N.length>0&&e.jsxs(A,{variant:"ghost",size:"sm",onClick:v,title:"Hide every item from the overview (full log kept)",children:[e.jsx(ot,{size:12})," Hide all"]})]})]}),I.size>0&&e.jsxs("div",{className:"activity-hidden-banner",role:"status",children:[e.jsxs("span",{children:[e.jsx(ot,{size:12,style:{verticalAlign:-2,marginRight:6}}),I.size," item",I.size===1?"":"s"," hidden from the overview."]}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:w,children:[e.jsx(He,{size:12})," Show them again"]})]}),N.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",!$&&"activity-feed-list-wrap-collapsed"),"aria-live":"polite","aria-relevant":"additions",children:[e.jsx(xt,{items:N.slice(0,30).filter((_,X)=>!I.has(F(_,X))),itemHeight:60,height:Math.min(N.filter((_,X)=>!I.has(F(_,X))).length*60,480),className:"activity-feed-list",renderItem:(_,X)=>{const ee=N.slice(0,30).findIndex(Q=>Q===_);return e.jsx(yi,{item:_,activityKey:F(_,ee),onNavigate:a,onHide:T})}}),!$&&N.length>8&&e.jsx("div",{className:"activity-feed-fade","aria-hidden":"true"})]})]}),e.jsxs(K,{className:"project-picker",children:[e.jsxs(Z,{children:[e.jsx(Ee,{size:14})," Projects",e.jsxs(A,{variant:"ghost",size:"sm",style:{marginLeft:"auto"},onClick:y,children:[e.jsx(Ce,{size:12})," Add"]}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:L,title:"Use the server's working directory",children:[e.jsx(Ce,{size:12})," Auto-detect"]}),((J=t==null?void 0:t.dashboard)==null?void 0:J.projectsDirectory)&&e.jsxs(A,{variant:"ghost",size:"sm",title:`Scan ${t.dashboard.projectsDirectory} for projects`,onClick:async()=>{try{const _=await S.post("/projects/scan");_.error?n.error(_.error):n.success(`Added ${_.added.length}, skipped ${_.skipped}.`),await i();const X=await S.get("/projects");m(X.projects||[]),g(X.active||null)}catch(_){n.error(`Scan failed: ${_.message}`)}},children:[e.jsx(Qa,{size:12})," Scan"]}),e.jsx(A,{variant:"ghost",size:"sm",onClick:P,title:"Refresh",children:e.jsx(oe,{size:12})})]}),e.jsxs(te,{children:[c.length," project",c.length===1?"":"s"," ·"," ",o.counts.agents," agents ·"," ",o.counts.sessions," session",o.counts.sessions===1?"":"s"]}),c.length===0?e.jsx(Se,{icon:e.jsx(Ee,{size:32}),title:"No projects yet",message:"Add a project to start tracking its tasks, plans, and schedules.",action:e.jsxs("div",{className:"empty-state-actions",children:[e.jsxs(A,{variant:"primary",onClick:L,children:[e.jsx(Ce,{size:14})," Use current directory"]}),e.jsx(A,{variant:"secondary",onClick:y,children:"Add by path…"})]})}):e.jsx("div",{className:"project-grid",children:c.map(_=>e.jsx(hi,{project:_,active:h===_.id,onOpen:()=>B(_.id),onRemove:()=>R(_.id)},_.id))})]}),e.jsx(ci,{setActiveTab:a}),e.jsxs("div",{className:"overview-cols",children:[e.jsxs(K,{children:[e.jsx(Z,{children:"Mods"}),e.jsxs(te,{children:["Extensions installed under ",e.jsx("code",{children:"~/.config/bizar/mods/"})]}),j.length===0?e.jsx("div",{className:"muted",children:"No mods installed."}):e.jsx("ul",{className:"mod-mini-list",children:j.map(_=>e.jsxs("li",{className:"mod-mini",children:[e.jsx("span",{className:"mod-mini-name",children:_.name}),e.jsxs("span",{className:"mod-mini-meta",children:["v",_.version," · ",_.type]}),e.jsx("span",{className:`mod-mini-pill ${_.enabled?"mod-mini-pill-on":"mod-mini-pill-off"}`,children:_.enabled?"on":"off"})]},_.id))})]}),e.jsxs(K,{children:[e.jsx(Z,{children:"Environment"}),e.jsx(te,{children:"Runtime + paths"}),e.jsxs("dl",{className:"env-table",children:[e.jsx("dt",{children:"Node"}),e.jsx("dd",{className:"mono",children:o.versions.node}),e.jsx("dt",{children:"Platform"}),e.jsx("dd",{className:"mono",children:o.versions.platform}),e.jsx("dt",{children:"Project root"}),e.jsx("dd",{className:"mono ellipsis",title:o.versions.projectRoot,children:o.versions.projectRoot}),e.jsx("dt",{children:"Bizar root"}),e.jsx("dd",{className:"mono ellipsis",title:o.versions.bizarRoot,children:o.versions.bizarRoot}),e.jsx("dt",{children:"Generated"}),e.jsx("dd",{className:"mono tabular-nums",children:cs(o.generatedAt)})]})]})]})]})}function mi({settings:s,onAdd:t}){var c,m;const[a,i]=r.useState(((c=s==null?void 0:s.dashboard)==null?void 0:c.projectsDirectory)??""),[n,l]=r.useState(""),[d,o]=r.useState(!1),[p,x]=r.useState(null),u=async()=>{var h;if(a){o(!0),x(null);try{await S.get("/fs?path="+encodeURIComponent(a)),t(a,n||null)}catch(g){const j=g;j.status===404?x("That folder no longer exists. Pick another."):x(((h=j.data)==null?void 0:h.message)??g.message??"Validation failed.")}finally{o(!1)}}};return e.jsxs("div",{children:[e.jsx("label",{className:"field-label",children:"Folder"}),e.jsx(ua,{value:a,onChange:h=>{i(h),x(null)},projectsDirectory:(m=s==null?void 0:s.dashboard)==null?void 0:m.projectsDirectory,height:320}),p&&e.jsx("p",{className:"field-help",style:{color:"var(--error)",marginTop:4},children:p}),e.jsxs("div",{style:{marginTop:"var(--space-3)"},children:[e.jsx("label",{className:"field-label",htmlFor:"add-project-name",children:"Name (optional)"}),e.jsx("input",{id:"add-project-name",className:"input",type:"text",placeholder:"My App",value:n,onChange:h=>l(h.target.value)}),e.jsx("p",{className:"field-help",style:{marginTop:4},children:"Display name for this project. Defaults to the folder name."})]}),e.jsx("div",{style:{marginTop:"var(--space-3)",display:"flex",justifyContent:"flex-end"},children:e.jsxs(A,{variant:"primary",onClick:u,disabled:!a||d,children:[d?e.jsx("span",{className:"btn-spinner"}):null,d?"Checking…":"Add"]})})]})}function hi({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:l=>{l.stopPropagation(),i()},children:e.jsx(be,{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 ",ke(s.lastAccessed)]})}),e.jsx("div",{className:"project-card-actions",children:e.jsx(A,{variant:t?"ghost":"primary",size:"sm",onClick:a,children:t?e.jsxs(e.Fragment,{children:[e.jsx(vt,{size:12})," Active"]}):e.jsx(e.Fragment,{children:"Open"})})})]})}function ui(s){return s&&s.charAt(0).toUpperCase()+s.slice(1)}function xi(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"},l={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"},d=n[a]||ui(a.replace(/-/g," ")),o=l[i]||i.replace(/-/g," ");return`${d} ${o}`.trim()}function As(s,t){for(const a of t){const i=s[a];if(typeof i=="string"&&i.trim())return i.trim()}return""}function pi(s){const t=As(s,["message","text","prompt","title","name"]);if(t)return t;const a=[],i=As(s,["slug"]),n=As(s,["agent","author"]),l=As(s,["status"]);return i&&a.push(`Plan ${i}`),n&&a.push(n),l&&a.push(l),a.length?a.join(" · "):"No additional details."}function gi(s){return ke(s)}function ji(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 fi(s){const t=s.toLowerCase();return t==="task"?fs:t==="agent"?_e:t==="plan"?Os:t.includes("bg")||t.includes("background")||t.includes("job")?yt:t==="mod"?Bs:t==="skill"?Fe:t.includes("error")||t.includes("failure")?Ja:t.includes("warn")?Ne:Ae}function vi(s){const t=s.toLowerCase();return t==="task"?"tasks":t==="agent"?"agents":t==="plan"?"artifacts":t.includes("bg")||t.includes("background")?"activity":t==="mod"?"mods":t==="skill"?"skills":null}function yi({item:s,activityKey:t,onNavigate:a,onHide:i}){const n=ji(s),l=fi(s.kind||""),d=xi(s.kind||"activity"),o=pi(s),p=vi(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:()=>{p&&a(p)},title:p?`Open ${p}`:d,children:[e.jsx("div",{className:"activity-feed-icon",style:{color:x},children:e.jsx(l,{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:d}),e.jsx("div",{className:"activity-feed-time text-xs muted tabular-nums",children:gi(s.ts)})]}),e.jsx("div",{className:"activity-feed-summary text-sm",children:o})]})]}),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(ze,{size:12})})]})}const bi=qe.memo(di);function ki({session:s,mode:t,anchor:a,renameDraft:i,setRenameDraft:n,onEdit:l,onDeleteRequest:d,onConfirmDelete:o,onConfirmRename:p,onClose:x}){const u=r.useRef(null),c=Math.round(a.rect.bottom+2),m=Math.max(8,Math.round(window.innerWidth-a.rect.right));r.useEffect(()=>{const g=C=>{const k=C.target;!u.current||!k||u.current.contains(k)||x()},j=C=>{C.key==="Escape"&&x()},b=window.setTimeout(()=>{document.addEventListener("mousedown",g),document.addEventListener("keydown",j)},0);return()=>{window.clearTimeout(b),document.removeEventListener("mousedown",g),document.removeEventListener("keydown",j)}},[x]),r.useEffect(()=>{if(t!=="rename")return;const g=window.setTimeout(()=>{var b;const j=(b=u.current)==null?void 0:b.querySelector("input.session-row-menu-input");j==null||j.focus(),j==null||j.select()},0);return()=>window.clearTimeout(g)},[t]);const h=e.jsxs("div",{ref:u,className:"session-row-menu",role:"menu","aria-label":`Options for ${s.title}`,style:{position:"fixed",top:c,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(),l()},children:[e.jsx(Za,{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(),d()},children:[e.jsx(be,{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(),p()):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(),p()},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(),o()},children:"Delete"})]})]})]});return Wa.createPortal(h,document.body)}function ht({node:s,depth:t=0,collapsible:a=!1,isLast:i=!0,open:n,onToggle:l}){var h;const[d,o]=r.useState(a),p=n!==void 0,x=p?n:d,u=g=>{p||o(g),l==null||l(g)},c=(((h=s.children)==null?void 0:h.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}),c&&e.jsx("div",{className:"agent-node-children",children:s.children.map((g,j)=>e.jsx(ht,{node:g,depth:t+1,collapsible:!1,isLast:j===s.children.length-1},g.id))})]})]})}function Ni(s){return s.tree!==void 0}function wi(s){const t=s.open??!0;if(Ni(s))return e.jsx("div",{className:`agent-tree variant-${s.variant??"full"}`,children:e.jsx(ht,{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(ht,{node:i,depth:0,collapsible:!1,open:t,isLast:n===a.length-1})},i.id))})})}function Si({children:s,variant:t="rail",open:a=!0}){return a?e.jsx(wi,{variant:t,open:a,children:s}):null}const Ci=["Today","Yesterday","This week","Earlier"];function It(s,t){return s.getFullYear()===t.getFullYear()&&s.getMonth()===t.getMonth()&&s.getDate()===t.getDate()}function zi(s,t){const a=s.getTime()-t.getTime();return Math.floor(a/(1e3*60*60*24))}function Ti(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 l of s){const d=new Date(Number(l.mtime)||Date.now());It(d,t)?n.Today.push(l):It(d,a)?n.Yesterday.push(l):zi(t,d)<7?n["This week"].push(l):n.Earlier.push(l)}return n}function Ri(s){return new Date(Number(s)||Date.now()).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1})}function $i({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 Ai({sessions:s,opencodeSessions:t=[],activeSessionId:a,activeOpencodeSessionId:i,activeProject:n,creating:l,onCreateSession:d,onSelectSession:o,onSelectOpencodeSession:p,onRenameSession:x,onDeleteSession:u,groupBy:c}){var R;const m=r.useMemo(()=>[...s,...t],[s,t]),h=r.useMemo(()=>[...m].sort((H,ae)=>Number(ae.mtime??0)-Number(H.mtime??0)),[m]),g=r.useMemo(()=>c?c(h):Ti(h),[c,h]),[j,b]=r.useState({}),C=H=>j[H]===!0,[k,N]=r.useState(null),[E,$]=r.useState("main"),[z,I]=r.useState(""),[f,F]=r.useState(null),T=r.useRef({}),v=(H,ae="main")=>{const J=T.current[H];if(!J)return;const _=ae==="main"?J:J.querySelector(".chat-rail-item-menu-trigger")??J;if(F({id:H,rect:_.getBoundingClientRect()}),N(H),$(ae),ae==="rename"){const X=[...s,...t].find(ee=>ee.id===H);I((X==null?void 0:X.title)??(X==null?void 0:X.id)??"")}},w=()=>{N(null),$("main"),I(""),F(null)},P=H=>{if(H.source==="opencode"){p(H);return}o(H.id)},y=()=>{if(!f)return;const H=f.id,ae=z.trim();if(!ae){w();return}x==null||x(H,ae),w()},L=()=>{f&&(u==null||u(f.id),w())},B=c?Object.entries(g):Ci.filter(H=>{var ae;return(ae=g[H])==null?void 0:ae.length}).map(H=>[H,g[H]]);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:d,disabled:l||!n,title:n?"Create new session":"Pick a project first","aria-label":"Create new session",children:[e.jsx(Ce,{size:14,"aria-hidden":!0}),e.jsx("span",{children:l?"Creating…":"New session"})]})}),h.length===0?e.jsx("div",{className:"chat-sessions-empty",children:e.jsx(Aa,{icon:e.jsx(Ce,{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:B.map(([H,ae])=>e.jsxs("div",{className:"chat-rail-group",children:[e.jsx("div",{className:"chat-rail-group-label",children:H}),ae.map(J=>{var je,V;const _=J.source==="opencode",X=_?i===J.id:a===J.id,ee=J.tree,Q=!!((je=ee==null?void 0:ee.root)!=null&&je.children&&ee.root.children.length>0),ie=C(J.id);return e.jsxs(r.Fragment,{children:[e.jsxs("div",{ref:D=>{T.current[J.id]=D},role:"button",tabIndex:0,className:`chat-rail-item state-${J.state??"idle"}${X?" active":""}`,onClick:()=>P(J),onKeyDown:D=>{(D.key==="Enter"||D.key===" ")&&(D.preventDefault(),P(J))},"aria-current":X?"true":void 0,children:[e.jsx($i,{state:J.state??"idle",agent:J.agent}),e.jsxs("div",{className:"chat-rail-item-title",children:[J.pinned&&e.jsx("span",{className:"chat-rail-pin","aria-hidden":!0,children:"★"}),_&&e.jsx(ds,{size:11,style:{color:"var(--text-muted)",flexShrink:0},"aria-hidden":!0}),e.jsx("span",{className:"chat-ellipsis",children:J.title||J.id})]}),e.jsxs("div",{className:"chat-rail-item-meta",children:[e.jsx("span",{className:"chat-rail-item-meta-time",children:J.time??Ri(J.mtime)}),(J.unread??0)>0&&e.jsx("span",{className:"chat-rail-badge",children:J.unread})]}),e.jsx("button",{type:"button",className:`chat-rail-item-menu-trigger${k===J.id?" open":""}`,"aria-label":`Session options for ${J.title||J.id}`,"aria-haspopup":"menu","aria-expanded":k===J.id,onClick:D=>{D.stopPropagation(),k===J.id?w():v(J.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"})]})}),X&&Q&&e.jsx("button",{type:"button",className:`chat-rail-tree-chevron${ie?" open":""}`,"aria-label":ie?"Collapse sub-agents":"Expand sub-agents","aria-expanded":ie,onClick:D=>{D.stopPropagation(),b(U=>({...U,[J.id]:!U[J.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"})})})]}),X&&Q&&ie&&((V=ee==null?void 0:ee.root)==null?void 0:V.children)&&e.jsx(Si,{children:ee.root.children,variant:"rail",open:!0})]},_?`oc-${J.id}`:J.id)})]},H))}),k&&f&&e.jsx(ki,{session:{id:f.id,title:((R=[...s,...t].find(H=>H.id===f.id))==null?void 0:R.title)??f.id},mode:E,anchor:f,renameDraft:z,setRenameDraft:I,onEdit:()=>v(k,"rename"),onDeleteRequest:()=>v(k,"confirm-delete"),onConfirmDelete:L,onConfirmRename:y,onClose:w})]})}function Mi(s){const{text:t,sending:a,onSend:i,activeSource:n}=s,[l,d]=r.useState(!1),o=()=>{!t.trim()||a||(d(!0),i(),window.setTimeout(()=>d(!1),320))};return e.jsxs("div",{className:`chat-composer-wrap chat-composer-source-${n??"none"}`,children:[e.jsx("div",{className:`chat-composer-pill${l?" takeoff":""}`,children:e.jsx(Ma,{...s,onSend:o})}),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 Js(s){return s.toLocaleString()}function Li(s){return!s||!s.includes("/")?"":s.split("/")[0]}function Ii(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 Ei({sessionId:s,messages:t,pinned:a,agent:i,model:n,agents:l,mcps:d,allCommands:o,activeSource:p="bizar",onRename:x,onDelete:u,onExport:c,busy:m}){const[h,g]=r.useState(null);r.useEffect(()=>{let F=!1;return(async()=>{try{const T=await fetch("/api/usage?range=24h",{headers:{Accept:"application/json"}});if(!T.ok)return;const v=await T.json();F||g(v)}catch{}})(),()=>{F=!0}},[s]);const j=(t==null?void 0:t.length)??0,b=(a==null?void 0:a.size)??0,C=t.reduce((F,T)=>F+(T.content||T.message||"").length,0),k=Math.round(C/4),N=Ii(n),E=k/1e6*N,$=(h==null?void 0:h.totalTokens)??k,z=(h==null?void 0:h.costUsd)??E,I=128e3,f=Li(n);return e.jsxs("aside",{className:"chat-info",children:[e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("div",{className:"chat-info-section-head",children:[e.jsxs("h4",{children:[e.jsx(qs,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Session"]}),e.jsx("span",{className:`chat-source-badge chat-source-${p??"none"}`,style:{marginLeft:"auto"},children:p==="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:[Js(j)," message",j===1?"":"s",b>0&&` · ${b} pinned`]})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("h4",{children:[e.jsx(_e,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Agent"]}),e.jsx("div",{className:"chat-info-value",children:i||"—"})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("h4",{children:[e.jsx(ys,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Model"]}),e.jsx("div",{className:"chat-mono chat-ellipsis",title:n,children:n||"—"}),f&&e.jsxs("div",{className:"chat-info-mono",children:["provider · ",f]})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsx("h4",{children:"Tokens"}),e.jsxs("div",{className:"chat-mono",children:[Js($)," / ",Js(I)]}),e.jsx("div",{className:"chat-info-bar","aria-hidden":!0,children:e.jsx("div",{className:"chat-info-bar-fill",style:{width:`${Math.min(100,$/Math.max(1,I)*100)}%`}})})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("h4",{children:[e.jsx(en,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Cost"]}),e.jsxs("div",{className:"chat-mono",children:["$",z.toFixed(4)]}),!h&&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(_e,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Attached agents"]}),l!=null&&l.length?e.jsx("div",{className:"chat-info-agents",children:l.map(F=>e.jsx("span",{className:"chat-info-agent",children:F.name},F.name))}):e.jsx("div",{className:"chat-info-mono",children:"None attached"})]}),e.jsxs("div",{className:"chat-info-section",children:[e.jsxs("h4",{children:[e.jsx(ys,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","MCPs"]}),d!=null&&d.length?e.jsx("div",{className:"chat-info-agents",children:d.map(F=>e.jsx("span",{className:"chat-info-agent",children:F.id},F.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(bs,{size:11,style:{marginRight:4,verticalAlign:-1},"aria-hidden":!0})," ","Slash commands"]}),e.jsxs("div",{className:"chat-info-mono",children:[(o==null?void 0:o.length)??0," available"]})]}),(x||u||c)&&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(Ss,{size:12,"aria-hidden":!0})," Rename"]}),c&&e.jsxs("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:c,title:"Export transcript",children:[e.jsx(Je,{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(be,{size:12,"aria-hidden":!0})," Delete"]})]})]})]})}function Di({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(Zt,{size:14,"aria-hidden":!0}),e.jsx("span",{children:"Jump to latest"}),t>0&&e.jsxs("span",{className:"jump-badge",children:[t," new"]})]})})}function Pi({snapshot:s,settings:t,setActiveTab:a,initialTaskId:i,onClearTaskId:n}){const l=le(),d=Te(),o=La(s,t,i??"");r.useEffect(()=>{o.setToast({error:R=>l.error(R),success:R=>l.success(R),info:R=>l.info(R),warning:R=>l.warning(R)})},[o,l]);const[p,x]=r.useState(""),[u,c]=r.useState(t.defaultAgent||"odin"),[m,h]=r.useState(t.defaultModel||""),[g,j]=r.useState([]),b=r.useRef(null),{allCommands:C,suggestions:k,setQuery:N}=Ia(s);r.useEffect(()=>{N(p)},[p,N]);const E=()=>{var R;return(R=b.current)==null?void 0:R.click()},$=R=>{const H=R.target.files;if(!H)return;const ae=[];for(let J=0;J<H.length;J++)ae.push(H[J].name);j(J=>{const _=ae.filter(X=>!J.includes(X));return[...J,..._]}),b.current&&(b.current.value="")},z=async()=>{const R=p.trim();if(!R)return;x(""),N(""),(await o.onSend(R,u,m,g)).ok&&o.jumpToLatest()},I=async()=>{o.busy.create||await o.onCreateSession()},f=R=>{d.open({title:"Delete message?",children:e.jsx("p",{style:{margin:0},children:"This action cannot be undone."}),footer:e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx(A,{variant:"secondary",size:"sm",onClick:()=>d.close(),children:"Cancel"}),e.jsx(A,{variant:"danger",size:"sm",onClick:()=>{d.close(),o.deleteMessage(R)},children:"Delete"})]})})},F=(R,H)=>{let ae="";d.open({title:"Rename session",children:e.jsx("input",{id:"rename-session-input",autoFocus:!0,defaultValue:H,"aria-label":"Session title",onChange:J=>{ae=J.target.value},onKeyDown:J=>{J.key==="Enter"&&(J.preventDefault(),d.close(),o.renameSession(R,ae).then(_=>{_&&l.success("Renamed.")}))},style:{width:"100%",padding:"8px 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-sm)",color:"var(--text)",font:"13px/1.4 var(--font-sans)",marginTop:6}}),footer:e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx(A,{variant:"secondary",size:"sm",onClick:()=>d.close(),children:"Cancel"}),e.jsx(A,{variant:"primary",size:"sm",onClick:()=>{d.close(),o.renameSession(R,ae)},children:"Save"})]})})},T=(R,H)=>{d.open({title:"Delete session?",children:e.jsxs("p",{style:{margin:0},children:["Delete ",e.jsx("strong",{children:H}),"? Messages on the opencode serve will be removed. This cannot be undone."]}),footer:e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx(A,{variant:"secondary",size:"sm",onClick:()=>d.close(),children:"Cancel"}),e.jsx(A,{variant:"danger",size:"sm",onClick:async()=>{d.close(),await o.deleteSession(R)},children:"Delete"})]})})},v=()=>{const R=o.activeSource==="opencode"?o.activeOpencodeSessionId:o.sessionId;if(!R)return;const ae=(o.activeSource==="opencode"?o.opencodeMessages:o.bizarMessages).map(ee=>{const Q=ee.ts??"",ie=(ee.role||"unknown").toUpperCase(),je=ee.content||ee.message||"";return`[${Q}] ${ie}: ${je}`}).join(`
2
-
3
- `),J=new Blob([ae],{type:"text/plain;charset=utf-8"}),_=URL.createObjectURL(J),X=document.createElement("a");X.href=_,X.download=`${R}.txt`,document.body.appendChild(X),X.click(),document.body.removeChild(X),URL.revokeObjectURL(_)},w=r.useMemo(()=>o.sessions.map(R=>o.getSessionDisplay(R)),[o.sessions,o.getSessionDisplay]),P=r.useMemo(()=>o.opencodeSessions.map(R=>o.getSessionDisplay(R)),[o.opencodeSessions,o.getSessionDisplay]),y=r.useMemo(()=>{const R=o.activeSource==="opencode"?o.activeOpencodeSessionId??"":o.sessionId;return R?w.find(H=>H.id===R)??P.find(H=>H.id===R)??null:null},[o.activeSource,o.activeOpencodeSessionId,o.sessionId,w,P]),L=(()=>{var ae;const R=`${u||"Odin"} · ${((ae=s.activeProject)==null?void 0:ae.name)??"no project"}`,H=(y==null?void 0:y.state)??"idle";return H==="streaming"?`Replying · ${R}`:H==="awaiting"?`Your turn · ${R}`:`${R} · idle`})(),B=o.activeSource==="opencode"?"opencode":"bizar chat";return e.jsxs("div",{className:"chat-shell",children:[e.jsx(Ea,{activeProject:s.activeProject,sessionCount:o.sessions.length,sessionsOpen:!0,infoOpen:!0,onToggleSessions:()=>{},onToggleInfo:()=>{},onOpenOverview:()=>a==null?void 0:a("overview")}),e.jsxs("div",{className:"chat-page",children:[e.jsx(Ai,{sessions:w,opencodeSessions:P,activeSessionId:o.sessionId,activeOpencodeSessionId:o.activeOpencodeSessionId,activeProject:s.activeProject,creating:o.busy.create,onCreateSession:I,onSelectSession:o.selectBizarSession,onSelectOpencodeSession:R=>o.loadOpencodeSession(R.id),onRenameSession:F,onDeleteSession:R=>{const H=o.sessions.find(ae=>ae.id===R)??o.opencodeSessions.find(ae=>ae.id===R);T(R,(H==null?void 0:H.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:(y==null?void 0:y.title)??o.sessionId??"New chat"}),e.jsx("span",{className:`chat-source-badge chat-source-${o.activeSource??"none"}`,title:o.activeSource==="opencode"?"Messages go to the opencode serve child":"Messages go to the local chat store",children:B})]}),e.jsxs("div",{className:`chat-thread-sub chat-muted state-${(y==null?void 0:y.state)??"idle"}`,children:[e.jsx("span",{className:"chat-thread-dot"}),L]}),o.opencodeError&&e.jsx("div",{className:"chat-thread-error",role:"alert",children:o.opencodeError})]}),e.jsxs("div",{className:"chat-thread-actions",children:[y&&e.jsxs("button",{className:"btn btn-ghost",title:"Rename session",type:"button",disabled:o.busy.rename,onClick:()=>F(y.id,y.title??""),children:[e.jsx(Ss,{size:12,"aria-hidden":!0})," ",e.jsx("span",{className:"mono",children:"rename"})]}),y&&e.jsxs("button",{className:"btn btn-ghost btn-danger",title:"Delete session",type:"button",disabled:o.busy.delete,onClick:()=>T(y.id,y.title??y.id),children:[e.jsx(be,{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:v,children:e.jsx("span",{className:"mono",children:"export"})})]})]}),e.jsx("div",{className:"chat-thread-scroll",ref:o.listRef,onScroll:o.handleScroll,role:"log","aria-live":"polite","aria-relevant":"additions","aria-label":"Chat message thread",children:e.jsx(Da,{messages:o.activeSource==="opencode"?o.opencodeMessages:o.bizarMessages,loading:o.loading,activeProject:s.activeProject,sessionId:o.activeSource==="opencode"?o.activeOpencodeSessionId??o.sessionId:o.sessionId,pinned:o.pinned,activeSource:o.activeSource,onPickSuggestion:R=>x(R),onCopy:R=>o.copyMessage(R),onDelete:f,onTogglePin:o.togglePin,onRegenerate:o.onRegenerate})}),!o.stickToBottom&&e.jsx(Di,{streaming:(y==null?void 0:y.state)==="streaming",newMessageCount:o.newMessageCount,onClick:o.jumpToLatest}),e.jsx(Mi,{agent:u,setAgent:c,model:m,setModel:h,text:p,setText:x,sending:o.sending,activeSource:o.activeSource,onSend:z,attachments:g,setAttachments:j,suggestions:k,onPickSuggestion:R=>x(`${R.split(" ")[0]} `),agents:s.agents||[],onAttach:E}),e.jsx("input",{ref:b,type:"file",multiple:!0,style:{display:"none"},onChange:$,"aria-label":"Attach files to message",tabIndex:-1})]}),e.jsx(Ei,{sessionId:o.activeSource==="opencode"?o.activeOpencodeSessionId??o.sessionId:o.sessionId,messages:o.activeSource==="opencode"?o.opencodeMessages:o.bizarMessages,pinned:o.pinned,agent:u,model:m,agents:s.agents||[],mcps:s.mcps||[],allCommands:C,activeSource:o.activeSource,onRename:()=>{y&&F(y.id,y.title??"")},onDelete:()=>{y&&T(y.id,y.title??y.id)},onExport:v,busy:o.busy})]})]})}function rs({kind:s="neutral",children:t,className:a,dot:i=!1}){return e.jsxs("span",{className:Y("badge",`badge-${s}`,a),children:[i&&e.jsx("span",{className:"badge-dot"}),t]})}const Et=["bash","read","edit","write","webfetch","websearch","task","glob","grep"],Dt=["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"],Ds=[{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 Fi(s){var t;return((t=Ds.find(a=>a.id===s))==null?void 0:t.color)||"var(--text-dim)"}function Oi({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 Bi({agent:s}){if(s.isStuck)return e.jsx(rs,{kind:"error",dot:!0,children:"stuck"});const t=s.status||"idle";return t==="working"?e.jsx(rs,{kind:"info",dot:!0,children:"working"}):t==="error"?e.jsx(rs,{kind:"error",dot:!0,children:"error"}):e.jsx(rs,{kind:"neutral",dot:!0,children:"idle"})}function Ui({snapshot:s,refreshSnapshot:t}){const a=le(),i=Te(),[n,l]=r.useState(s.agents||[]),[d,o]=r.useState(!s.agents),[p,x]=r.useState(""),[u,c]=r.useState("");r.useEffect(()=>{l(s.agents||[]),o(!s.agents)},[s.agents]);const m=async()=>{try{const $=await S.get("/agents");l($.agents||[])}catch($){a.error(`Agents load failed: ${$.message}`)}finally{o(!1)}},h=r.useMemo(()=>{let $=[...n];if(p&&($=$.filter(z=>p==="__none__"?!z.category:(z.category||"")===p)),u){const z=u.toLowerCase();$=$.filter(I=>I.name.toLowerCase().includes(z)||(I.description||"").toLowerCase().includes(z)||(I.tags||[]).some(f=>f.toLowerCase().includes(z)))}return $.sort((z,I)=>z.name.localeCompare(I.name))},[n,p,u]),g=r.useMemo(()=>{const $=new Set;for(const z of n)for(const I of z.tags||[])$.add(I);return Array.from($).sort()},[n]),j=()=>{let $=null,z=null,I=null,f=null,F=null,T=null,v=null,w=null,P=null;i.open({title:"New agent",width:640,children:e.jsxs("div",{className:"agent-form",children:[e.jsx("label",{className:"field-label",htmlFor:"agent-new-name",children:"Name (a-z, 0-9, dashes)"}),e.jsx("input",{id:"agent-new-name",ref:y=>$=y,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:y=>{z=y},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:y=>I=y,className:"select",defaultValue:"",children:[e.jsx("option",{value:"",children:"(provider default)"}),Dt.map(y=>e.jsx("option",{value:y,children:y},y))]})]}),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:y=>f=y,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:y=>F=y,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:y=>P=y,className:"select",defaultValue:"",children:[e.jsx("option",{value:"",children:"(none)"}),Ds.map(y=>e.jsx("option",{value:y.id,children:y.label},y.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:y=>w=y,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:y=>v=y,className:"agent-tools",children:Et.map(y=>e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{type:"checkbox",value:y,"aria-label":y}),e.jsx("span",{children:y})]},y))})]}),e.jsx("label",{className:"field-label",htmlFor:"agent-new-prompt",children:"System prompt"}),e.jsx("textarea",{id:"agent-new-prompt",ref:y=>T=y,className:"textarea",rows:6,placeholder:"You are a..."})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx(A,{variant:"ghost",onClick:()=>i.close(),children:"Cancel"}),e.jsxs(A,{variant:"primary",onClick:async()=>{const y=(($==null?void 0:$.value)||"").trim();if(!/^[a-z0-9][a-z0-9-]{0,63}$/i.test(y)){a.warning("Invalid name (a-z, 0-9, dashes).");return}const L=[];v&&v.querySelectorAll('input[type="checkbox"]:checked').forEach(R=>{L.push(R.value)});const B=((w==null?void 0:w.value)||"").split(",").map(R=>R.trim()).filter(Boolean);try{const R=await S.post("/agents",{name:y,description:((z==null?void 0:z.value)||"").trim(),model:(I==null?void 0:I.value)||"",mode:(f==null?void 0:f.value)||"subagent",color:(F==null?void 0:F.value)||"",tools:L,tags:B,category:(P==null?void 0:P.value)||"",prompt:(T==null?void 0:T.value)||""});l(H=>[...H,R]),a.success("Agent created."),i.close(),await t()}catch(R){a.error(`Create failed: ${R.message}`)}},children:[e.jsx(ks,{size:12})," Create"]})]})})},b=async $=>{let z=null,I=null,f=null,F=null,T=null,v=null,w=null,P=null;try{const y=await S.get(`/agents/${encodeURIComponent($.name)}`);i.open({title:`Edit ${$.name}`,width:640,children:e.jsxs("div",{className:"agent-form",children:[e.jsxs("div",{className:"muted",children:["File: ",e.jsx("code",{children:y.path})]}),e.jsx("label",{className:"field-label",htmlFor:"agent-edit-desc",children:"Description"}),e.jsx("input",{id:"agent-edit-desc",ref:L=>{z=L},className:"input",type:"text",defaultValue:y.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:L=>I=L,className:"select",defaultValue:y.model,children:[e.jsx("option",{value:"",children:"(provider default)"}),Dt.map(L=>e.jsx("option",{value:L,children:L},L))]})]}),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:L=>f=L,className:"select",defaultValue:y.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:L=>F=L,className:"input",type:"color",defaultValue:y.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:L=>P=L,className:"select",defaultValue:y.category||"",children:[e.jsx("option",{value:"",children:"(none)"}),Ds.map(L=>e.jsx("option",{value:L.id,children:L.label},L.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:L=>w=L,className:"input",type:"text",defaultValue:(y.tags||[]).join(", ")})]})]}),e.jsxs("fieldset",{children:[e.jsx("legend",{className:"field-label",style:{padding:0},children:"Tools"}),e.jsx("div",{ref:L=>v=L,className:"agent-tools",children:Et.map(L=>{var B;return e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{type:"checkbox",value:L,"aria-label":L,defaultChecked:(B=y.tools)==null?void 0:B.includes(L)}),e.jsx("span",{children:L})]},L)})})]}),e.jsx("label",{className:"field-label",htmlFor:"agent-edit-prompt",children:"System prompt"}),e.jsx("textarea",{id:"agent-edit-prompt",ref:L=>T=L,className:"textarea",rows:8,defaultValue:y.prompt||""})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx(A,{variant:"ghost",onClick:()=>i.close(),children:"Cancel"}),e.jsxs(A,{variant:"primary",onClick:async()=>{const L=[];v&&v.querySelectorAll('input[type="checkbox"]:checked').forEach(R=>{L.push(R.value)});const B=((w==null?void 0:w.value)||"").split(",").map(R=>R.trim()).filter(Boolean);try{const R=await S.put(`/agents/${encodeURIComponent($.name)}`,{description:((z==null?void 0:z.value)||"").trim(),model:(I==null?void 0:I.value)||"",mode:(f==null?void 0:f.value)||"subagent",color:(F==null?void 0:F.value)||"",tools:L,tags:B,category:(P==null?void 0:P.value)||"",prompt:(T==null?void 0:T.value)||""});l(H=>H.map(ae=>ae.name===$.name?R:ae)),a.success("Agent saved."),i.close(),await t()}catch(R){a.error(`Save failed: ${R.message}`)}},children:[e.jsx(ks,{size:12})," Save"]})]})})}catch(y){a.error(`Load failed: ${y.message}`)}},C=async $=>{if(confirm(`Delete agent "${$.name}"? This removes ${$.path}.`))try{await S.del(`/agents/${encodeURIComponent($.name)}`),l(z=>z.filter(I=>I.name!==$.name)),a.success("Agent deleted.")}catch(z){a.error(`Delete failed: ${z.message}`)}},k=async $=>{let z=null;i.open({title:`Invoke ${$.name}`,children:e.jsxs("div",{className:"invoke-form",children:[e.jsxs("p",{className:"muted invoke-form-meta mono",children:[$.model||"—"," · ",$.path]}),e.jsx("p",{className:"invoke-form-desc",children:$.description}),e.jsx("label",{className:"field-label",htmlFor:"invoke-prompt",children:"Prompt"}),e.jsx("textarea",{ref:I=>z=I,id:"invoke-prompt",className:"textarea",rows:5,placeholder:"What should this agent do?",autoFocus:!0})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx(A,{variant:"ghost",onClick:()=>i.close(),children:"Cancel"}),e.jsxs(A,{variant:"primary",onClick:async()=>{const I=((z==null?void 0:z.value)||"").trim();if(!I){a.warning("Prompt is required.");return}try{await S.post(`/agents/${encodeURIComponent($.name)}/invoke`,{prompt:I}),a.success(`Invoked ${$.name}.`),i.close()}catch(f){a.error(`Invoke failed: ${f.message}`)}},children:[e.jsx(ms,{size:14})," Invoke"]})]})})},N=async $=>{try{const z=await S.post(`/agents/${encodeURIComponent($.name)}/restart`);l(I=>I.map(f=>f.name===$.name?z:f)),a.success(`${$.name} restarted.`)}catch(z){a.error(`Restart failed: ${z.message}`)}},E=async($,z)=>{try{const I=await S.post(`/agents/${encodeURIComponent($.name)}/status`,{status:z});l(f=>f.map(F=>F.name===$.name?I:F))}catch(I){a.error(`Status update failed: ${I.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(_e,{size:18})," Agents (",h.length,")"]}),e.jsxs("p",{className:"view-subtitle",children:["The Norse pantheon — click ",e.jsx("kbd",{children:"Edit"})," to modify or ",e.jsx("kbd",{children:"Invoke"})," to dispatch."]})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs("div",{className:"search-input",children:[e.jsx("label",{htmlFor:"agents-search",className:"sr-only",children:"Search agents"}),e.jsx("input",{id:"agents-search",className:"input",type:"text",placeholder:"Search…",value:u,onChange:$=>c($.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:p,onChange:$=>x($.target.value),children:[e.jsx("option",{value:"",children:"All categories"}),Ds.map($=>e.jsx("option",{value:$.id,children:$.label},$.id)),e.jsx("option",{value:"__none__",children:"(no category)"})]}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:m,children:[e.jsx(oe,{size:14})," Refresh"]}),e.jsxs(A,{variant:"primary",size:"sm",onClick:j,children:[e.jsx(Ce,{size:14})," New agent"]})]})]}),g.length>0&&e.jsxs("div",{className:"agent-tags-row",children:[e.jsx(ea,{size:12}),g.map($=>e.jsx("span",{className:"tag",children:$},$))]}),d?e.jsx("div",{className:"view-loading",children:e.jsx(me,{size:"lg"})}):h.length===0?e.jsx(Se,{icon:e.jsx(_e,{size:32}),title:"No agents found",message:"Run bizar in the terminal to install Bizar."}):e.jsx("div",{className:"agent-grid",children:h.map($=>e.jsx(_i,{agent:$,onInvoke:()=>k($),onEdit:()=>b($),onDelete:()=>C($),onRestart:()=>N($),onSetStatus:z=>E($,z)},$.name))})]})}function _i({agent:s,onInvoke:t,onEdit:a,onDelete:i,onRestart:n,onSetStatus:l}){const[d,o]=r.useState(!1),p=Fi(s.category),x=(s.status==="working"||!!s.currentTaskId)&&!s.isStuck;return e.jsxs(K,{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(Oi,{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, ${p} 18%, transparent)`,color:p},children:s.category}),e.jsx(Bi,{agent:s})]})]}),e.jsx("p",{className:"agent-card-desc",children:Yt(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:ke(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(Ae,{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(We,{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:ke(s.lastTask.finishedAt)})]}),s.tasksTotal!=null&&s.tasksTotal>0&&e.jsxs("div",{className:"agent-card-row",children:[e.jsx(sn,{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(Ne,{size:12}),e.jsxs("span",{className:"muted",children:["Last error: ",s.lastError.message]})]}),e.jsxs("div",{className:"agent-card-actions",children:[e.jsxs(A,{variant:"primary",size:"sm",onClick:t,children:[e.jsx(ms,{size:12})," Invoke"]}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:a,children:[e.jsx(Ss,{size:12})," Edit"]}),(s.isStuck||s.status==="working"||s.status==="error")&&e.jsxs(A,{variant:"ghost",size:"sm",onClick:n,title:"Reset agent status",children:[e.jsx(bt,{size:12})," Restart"]}),e.jsx(A,{variant:"ghost",size:"sm",onClick:i,children:e.jsx(be,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":d?"Collapse":"Expand",onClick:()=>o(u=>!u),style:{marginLeft:"auto"},children:d?e.jsx(Pe,{size:12}):e.jsx(Ve,{size:12})})]}),d&&e.jsxs("div",{className:"agent-card-expanded",children:[e.jsxs("div",{className:"agent-card-status-actions",children:[e.jsx("span",{className:"muted text-sm",children:"Set status:"}),e.jsx(A,{variant:s.status==="idle"?"primary":"ghost",size:"sm",onClick:()=>l("idle"),children:"Idle"}),e.jsx(A,{variant:s.status==="working"?"primary":"ghost",size:"sm",onClick:()=>l("working"),children:"Working"}),e.jsx(A,{variant:s.status==="error"?"primary":"ghost",size:"sm",onClick:()=>l("error"),children:"Error"})]}),e.jsxs("div",{className:"agent-card-meta",children:[e.jsx(Ee,{size:11}),e.jsx("code",{className:"mono agent-card-path",children:s.path})]})]})]})}function Wi({id:s,children:t}){return e.jsx("div",{id:s,"data-block-id":s,className:Y("glyph-richtext"),style:pa,children:e.jsx(ma,{remarkPlugins:[ha],children:t})})}const Hi={info:{bg:"var(--info-soft, rgba(96, 165, 250, 0.12))",border:"var(--info)",fg:"var(--info)",icon:Vs,label:"Note"},warn:{bg:"var(--warning-soft, rgba(251, 191, 36, 0.15))",border:"var(--warning)",fg:"var(--warning)",icon:Ne,label:"Warning"},success:{bg:"var(--success-soft, rgba(52, 211, 153, 0.15))",border:"var(--success)",fg:"var(--success)",icon:We,label:"Success"},danger:{bg:"var(--error-soft, rgba(248, 113, 113, 0.12))",border:"var(--error)",fg:"var(--error)",icon:Xe,label:"Danger"}};function qi({id:s,tone:t="info",children:a}){const i=Hi[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:{...pa,fontSize:14},children:e.jsx(ma,{remarkPlugins:[ha],children:a})})]})]})}function Vi({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(ls,{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 Ki({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((l,d)=>e.jsx("td",{style:{padding:"8px 12px",color:"var(--text)",verticalAlign:"top",wordBreak:"break-word"},children:l},d))},n))})]})})}function Gi({id:s,tabs:t}){var l;const[a,i]=r.useState(((l=t[0])==null?void 0:l.id)??""),n=r.useMemo(()=>t.find(d=>d.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(d=>{const o=d.id===(n==null?void 0:n.id);return e.jsxs("button",{type:"button",role:"tab","aria-selected":o,onClick:()=>i(d.id),style:{padding:"6px 12px",fontSize:12,fontFamily:"var(--font-mono)",borderRadius:6,border:"none",cursor:"pointer",background:o?"var(--bg-elev)":"transparent",color:o?"var(--text-strong)":"var(--text-dim)",boxShadow:o?"0 0 0 1px var(--border)":"none",whiteSpace:"nowrap"},children:[e.jsx("span",{children:d.label}),d.language&&e.jsx("span",{style:{marginLeft:6,color:"var(--text-dim)",fontSize:11},children:d.language})]},d.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 Yi({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 l=!!n.recommended;return e.jsxs("div",{style:{position:"relative",padding:12,borderRadius:8,border:l?"2px solid var(--success)":"1px solid var(--border)",background:l?"var(--success-soft)":"var(--bg)"},children:[l&&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 Xi({id:s,questions:t}){const[a,i]=r.useState({});function n(l,d){i(o=>({...o,[l]:d}))}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(l=>e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[e.jsx("label",{htmlFor:`oq-${l.id}`,style:{fontSize:13,color:"var(--text)",fontWeight:500},children:l.label}),l.kind==="choice"&&e.jsxs("select",{id:`oq-${l.id}`,value:a[l.id]??"",onChange:d=>n(l.id,d.target.value),style:Pt,children:[e.jsx("option",{value:"",children:"— select —"}),(l.options??[]).map(d=>e.jsx("option",{value:d,children:d},d))]}),l.kind==="text"&&e.jsx("input",{id:`oq-${l.id}`,type:"text",value:a[l.id]??"",onChange:d=>n(l.id,d.target.value),style:Pt}),l.kind==="multi"&&e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4},children:(l.options??[]).map(d=>{const o=a[l.id]??[],p=o.includes(d);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:p,onChange:()=>{const x=p?o.filter(u=>u!==d):[...o,d];n(l.id,x)}}),e.jsx("span",{children:d})]},d)})})]},l.id))]})}const Pt={padding:"6px 10px",fontSize:13,borderRadius:6,border:"1px solid var(--border-strong)",background:"var(--bg)",color:"var(--text)",fontFamily:"inherit"},Qi={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 Ji({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=Qi[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 Zi({id:s,filename:t,language:a,mode:i="unified",before:n,after:l}){const d=n.split(`
4
- `),o=l.split(`
5
- `),p=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(rn,{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=(c,m,h)=>{const g={del:"var(--error-soft)",add:"var(--success-soft)",ctx:"transparent"},j={del:"var(--error)",add:"var(--success)",ctx:"var(--text-dim)"};return e.jsxs("div",{style:{display:"flex",padding:"0 12px",background:g[h]},children:[e.jsx("span",{style:{width:18,color:j[h],userSelect:"none",flexShrink:0},children:c}),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:[p,i==="unified"?e.jsxs("pre",{style:x,children:[d.map((c,m)=>e.jsx("div",{children:u("-",c,"del")},`b${m}`)),o.map((c,m)=>e.jsx("div",{children:u("+",c,"add")},`a${m}`))]}):e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr"},children:[e.jsx("pre",{style:{...x,borderRight:"1px solid var(--border)"},children:d.map((c,m)=>e.jsx("div",{children:u("-",c,"del")},m))}),e.jsx("pre",{style:x,children:o.map((c,m)=>e.jsx("div",{children:u("+",c,"add")},m))})]})]})}const er={up:{fg:"var(--success)",Icon:Pe,label:"trending up"},down:{fg:"var(--error)",Icon:Pe,label:"trending down"},flat:{fg:"var(--text-dim)",Icon:nn,label:"flat"}};function sr({id:s,label:t,value:a,trend:i,hint:n}){const l=i?er[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}),l&&e.jsx("span",{"aria-label":l.label,style:{display:"inline-flex",alignItems:"center",color:l.fg,transform:l.Icon===Pe&&i==="up"?"rotate(180deg)":void 0},children:e.jsx(l.Icon,{size:14})})]}),n&&e.jsx("div",{style:{fontSize:12,color:"var(--text-dim)"},children:n})]})}const tr={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)"}},Re=160,Le=56,ss=60,ts=80;function ar({id:s,steps:t,connections:a=[]}){if(t.length===0)return e.jsx("div",{id:s,"data-block-id":s,className:"glyph-workflow",children:e.jsx(nr,{id:s})});const i=new Map(t.map(u=>[u.id,u])),n=ir(t),l=Math.max(...n.map(u=>u.col))+1,d=Math.max(...n.map(u=>u.row))+1,o=l*(Re+ss)+ss,p=d*(Le+ts)+ts;function x(u){if(!i.get(u))return null;const m=n.find(h=>h.id===u);return m?{x:ss+m.col*(Re+ss)+Re/2,y:ts+m.row*(Le+ts)+Le/2}:null}return e.jsx("div",{id:s,"data-block-id":s,className:"glyph-workflow",style:{margin:"12px 0",padding:12,border:"1px solid var(--border)",borderRadius:10,background:"var(--bg-elev)",overflow:"auto"},children:e.jsxs("svg",{role:"img","aria-label":"Workflow diagram",width:o,height:p,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,c)=>{const m=x(u.from),h=x(u.to);if(!m||!h)return null;const g=h.x-m.x,j=h.y-m.y,b=g>=0?m.x+Re/2:m.x-Re/2,C=g>=0?h.x-Re/2:h.x+Re/2,k=j>=0?m.y+Le/2:m.y-Le/2,N=j>=0?h.y-Le/2:h.y+Le/2,E=(b+C)/2,$=(k+N)/2;return e.jsxs("g",{children:[e.jsx("line",{x1:b,y1:k,x2:C,y2:N,stroke:"var(--text-dim)",strokeWidth:1.5,markerEnd:`url(#arrow-${s})`}),u.label&&e.jsx("text",{x:E,y:$-4,fontSize:10,fill:"var(--text-dim)",textAnchor:"middle",fontFamily:"var(--font-mono)",children:u.label})]},c)}),t.map(u=>{const c=n.find(b=>b.id===u.id);if(!c)return null;const m=ss+c.col*(Re+ss),h=ts+c.row*(Le+ts),g=tr[u.type];if(u.type==="decision"){const b=m+Re/2,C=h+Le/2,k=[[b,h],[m+Re,C],[b,h+Le],[m,C]].map(N=>N.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:C-14,width:Re-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(tn,{size:11}),u.label]})})]},u.id)}const j=u.type==="note";return e.jsxs("g",{children:[e.jsx("rect",{x:m,y:h,width:Re,height:Le,rx:8,fill:g.fill,stroke:g.stroke,strokeWidth:j?1:2,strokeDasharray:j?"4 3":void 0}),e.jsx("foreignObject",{x:m+6,y:h+6,width:Re-12,height:Le-12,children:e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,fontSize:12,color:g.fg,textAlign:"center",lineHeight:1.25,fontStyle:j?"italic":"normal",height:"100%"},children:[j&&e.jsx(an,{size:11}),u.label]})})]},u.id)})]})})}function nr({id:s}){return e.jsx("div",{id:s,style:{padding:20,textAlign:"center",color:"var(--text-dim)",fontSize:13},children:"No workflow steps."})}function ir(s){return s.length===0?[]:s.map((t,a)=>({id:t.id,col:a,row:0}))}const pa={fontSize:14,lineHeight:1.6,color:"var(--text)"};function rr({id:s,title:t,x:a,y:i,w:n,h:l,html:d}){return e.jsxs("figure",{id:s,"data-block-id":s,className:"glyph-mockup",style:{width:n,minHeight:l},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:d}})]})]})}class lr extends qe.Component{constructor(){super(...arguments);hs(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 or(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 dr(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 mr({slug:s,onClose:t,onCommentAdded:a}){var Q,ie,je,V;const i=le(),[n,l]=r.useState(null),[d,o]=r.useState([]),[p,x]=r.useState(!0),[u,c]=r.useState(null),[m,h]=r.useState(null),[g,j]=r.useState(!1),[b,C]=r.useState(!1),[k,N]=r.useState(null),[E,$]=r.useState(null),[z,I]=r.useState(""),[f,F]=r.useState(null),[T,v]=r.useState([]),w=qe.useCallback((D,U,W)=>{v(ne=>ne.some(q=>q.blockId===D)?ne:[...ne,{blockId:D,blockType:U,message:W.message||String(W)}])},[]),P=r.useRef(null),y=r.useMemo(()=>n?dr(n.blocks):[],[n]);r.useEffect(()=>{let D=!1;const U=5e3;return(async()=>{x(!0),c(null);try{const W=new Promise((re,se)=>setTimeout(()=>se(new Error("Request timed out after 5s")),U)),[ne,q]=await Promise.race([Promise.all([S.get(`/artifacts/${encodeURIComponent(s)}/render`),S.get(`/artifacts/${encodeURIComponent(s)}`)]),W]);if(D)return;l(ne);const O=(q==null?void 0:q.comments)??[];o(Array.isArray(O)?O:[])}catch(W){if(!D){const ne=W.message;c(ne),h(ne)}}finally{D||x(!1)}})(),()=>{D=!0}},[s]);function L(D){if(!P.current)return;D.preventDefault();const U=P.current.getBoundingClientRect();N({x:D.clientX,y:D.clientY,worldX:D.clientX-U.left,worldY:D.clientY-U.top})}async function B(){if(!(!E||!z.trim()))try{const D=await S.post(`/artifacts/${encodeURIComponent(s)}/comments`,{x:E.worldX,y:E.worldY,text:z.trim(),author:"drb0rk"});o(U=>[...U,{id:D.id??`cmt_${Date.now()}`,x:E.worldX,y:E.worldY,text:z.trim(),author:"drb0rk",created:new Date().toISOString()}]),$(null),I(""),N(null),a==null||a(),i.success("Comment added")}catch(D){i.error(`Failed to add comment: ${D.message}`)}}async function R(){if(!g){j(!0);try{const D=await S.post(`/artifacts/${encodeURIComponent(s)}/submit`,{answers:[],submitter:"drb0rk"});D!=null&&D.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(D){i.error(`Submit failed: ${D.message}`)}finally{j(!1)}}}function H(){C(D=>!D)}const ae=D=>{const U=D.id,W=D.data??{},ne=or(D);return ne.ok?e.jsx(lr,{blockId:U,blockType:D.type,onError:w,children:J(D,U,W)},U):e.jsxs("div",{id:U,className:"glyph-block-error",role:"alert",style:{border:"1px solid var(--error, #f85149)",background:"rgba(248, 81, 73, 0.06)",borderRadius:8,padding:"12px 14px",margin:"12px 0",color:"var(--text)",fontFamily:"var(--font-mono, ui-monospace, monospace)",fontSize:12,lineHeight:1.55},children:[e.jsxs("strong",{style:{color:"var(--error, #f85149)",fontFamily:"var(--font-sans, system-ui, sans-serif)",display:"block",marginBottom:4},children:[D.type," block invalid"]}),e.jsxs("div",{style:{color:"var(--text-muted)",marginBottom:6},children:["block id: ",e.jsx("code",{children:U})]}),e.jsx("pre",{style:{margin:0,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:ne.error})]},U)},J=(D,U,W)=>{switch(D.type){case"RichText":return e.jsx(Wi,{id:U,children:D.childrenMarkdown??""},U);case"Callout":return e.jsx(qi,{id:U,tone:W.tone??"info",children:D.childrenMarkdown??""},U);case"Checklist":return e.jsx(Vi,{id:U,items:W.items??[]},U);case"Table":return e.jsx(Ki,{id:U,columns:W.columns??[],rows:W.rows??[]},U);case"CodeTabs":return e.jsx(Gi,{id:U,tabs:W.tabs??[]},U);case"Decision":return e.jsx(Yi,{id:U,title:W.title,question:W.question,options:W.options??[]},U);case"OpenQuestions":return e.jsx(Xi,{id:U,questions:W.questions??[]},U);case"FileTree":return e.jsx(Ji,{id:U,title:W.title,entries:W.entries??[]},U);case"Diff":return e.jsx(Zi,{id:U,filename:W.filename,language:W.language,mode:W.mode??"unified",before:W.before??"",after:W.after??""},U);case"Stat":return e.jsx(sr,{id:U,label:W.label??"",value:W.value,trend:W.trend,hint:W.hint},U);case"Workflow":return e.jsx(ar,{id:U,steps:W.steps??[],connections:W.connections},U);case"Mockup":return e.jsx(rr,{id:U,title:W.title,x:W.x,y:W.y,w:W.w,h:W.h,html:W.html??""},U);case"Diagram":return e.jsx("div",{id:U,className:"glyph-block-placeholder",children:e.jsxs("em",{children:["[Diagram] ",U]})},U)}};if(p)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(hr,{})," 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 _=((Q=n.frontmatter)==null?void 0:Q.title)??s,X=((ie=n.frontmatter)==null?void 0:ie.status)??"draft",ee=d.length;return e.jsxs("div",{className:`glyph-canvas ${b?"glyph-canvas--fullscreen":""}`,ref:P,onContextMenu:L,children:[e.jsxs("div",{className:"glyph-toolbar-floating",children:[e.jsxs("button",{className:"glyph-btn glyph-btn--primary glyph-btn--send",onClick:R,disabled:g,title:"Send comments + question answers to the agent — writes feedback.md, status=review",children:[e.jsx(Qe,{size:14}),e.jsx("span",{children:"Send to agent"}),e.jsx("span",{className:"glyph-btn-badge",children:ee})]}),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(ln,{size:15})}),e.jsx("button",{className:"glyph-icon-btn",title:"Undo",disabled:!0,children:e.jsx(on,{size:15})}),e.jsx("button",{className:"glyph-icon-btn",title:"Redo",disabled:!0,children:e.jsx(cn,{size:15})}),e.jsx("button",{className:"glyph-icon-btn",title:b?"Exit fullscreen":"Fullscreen",onClick:H,children:e.jsx(dn,{size:15})}),e.jsx("button",{className:"glyph-icon-btn",title:"More",children:e.jsx(mn,{size:15})}),e.jsx("span",{className:"glyph-toolbar-divider"}),e.jsxs("button",{className:"glyph-icon-btn",title:"Comment count","aria-label":"Comment count",children:[e.jsx(qs,{size:15}),e.jsx("span",{className:"glyph-icon-btn-count",children:ee})]}),t&&e.jsx("button",{className:"glyph-icon-btn glyph-icon-btn--close",title:"Close",onClick:t,"aria-label":"Close",children:e.jsx(ze,{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:_}),e.jsxs("div",{className:"glyph-meta",children:[e.jsx("span",{className:`glyph-status glyph-status--${X}`,children:X}),e.jsx("span",{className:"glyph-slug",children:s})]})]}),(T.length>0||((je=n.errors)==null?void 0:je.length)>0)&&e.jsxs("div",{className:"glyph-render-errors",role:"alert",style:{border:"1px solid var(--error, #f85149)",background:"rgba(248, 81, 73, 0.08)",borderRadius:8,padding:"12px 16px",margin:"0 0 16px 0",color:"var(--text)"},children:[e.jsx("strong",{style:{color:"var(--error, #f85149)",display:"block",marginBottom:8},children: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((D,U)=>e.jsxs("li",{children:[e.jsx("strong",{children:D.blockType})," (",e.jsx("code",{children:D.blockId}),"): ",D.message]},`be-${U}`)),(V=n.errors)==null?void 0:V.map((D,U)=>e.jsxs("li",{children:[D.line?`line ${D.line}: `:"",D.message]},`ce-${U}`))]})]}),e.jsx("div",{className:"glyph-sections",children:y.map((D,U)=>e.jsxs("section",{className:`glyph-section ${D.heading?"glyph-section--headed":"glyph-section--plain"}`,children:[D.heading&&e.jsx("h2",{className:"glyph-section-heading",children:D.heading}),e.jsx("div",{className:"glyph-section-blocks",children:D.blocks.map(ae)})]},`sec-${U}-${D.heading??"ungrouped"}`))})]}),d.map(D=>e.jsxs("button",{className:`glyph-pin ${f===D.id?"glyph-pin--active":""}`,style:{left:D.x,top:D.y},onClick:U=>{U.stopPropagation(),F(f===D.id?null:D.id)},title:D.text,children:[e.jsx(Mt,{size:14}),f===D.id&&e.jsxs("div",{className:"glyph-pin-thread",children:[e.jsx("div",{className:"glyph-pin-text",children:D.text}),e.jsxs("div",{className:"glyph-pin-meta",children:[D.author??"anonymous"," · ",D.created?new Date(D.created).toLocaleString():""]})]})]},D.id)),k&&e.jsx("div",{className:"glyph-ctx-menu",style:{left:k.x,top:k.y},onClick:D=>D.stopPropagation(),children:e.jsxs("button",{className:"glyph-ctx-item",onClick:()=>{$({worldX:k.worldX,worldY:k.worldY}),N(null)},children:[e.jsx(Mt,{size:14})," Add comment here"]})}),E&&e.jsx("div",{className:"glyph-modal-overlay",onClick:()=>$(null),children:e.jsxs("div",{className:"glyph-modal",onClick:D=>D.stopPropagation(),children:[e.jsxs("h3",{children:["Add comment at (",Math.round(E.worldX),", ",Math.round(E.worldY),")"]}),e.jsx("textarea",{autoFocus:!0,value:z,onChange:D=>I(D.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:()=>$(null),children:"Cancel"}),e.jsx("button",{className:"glyph-btn glyph-btn--primary",onClick:B,disabled:!z.trim(),children:"Add comment"})]})]})})]})}function hr(){return e.jsx("span",{className:"glyph-spinner","aria-label":"loading",children:"…"})}function ur(s){switch(s){case"approved":case"done":return"success";case"in-progress":case"doing":return"info";case"rejected":return"error";case"archived":return"warning";case"draft":default:return"neutral"}}function xr({snapshot:s,refreshSnapshot:t}){const a=le(),[i,n]=r.useState(s.artifacts||[]),[l,d]=r.useState(!s.artifacts),[o,p]=r.useState(null),[x,u]=r.useState(""),[c,m]=r.useState(!1);r.useEffect(()=>{s.artifacts&&(n(s.artifacts),d(!1))},[s.artifacts]);const h=async()=>{try{const C=await S.get("/artifacts");n(C.artifacts||[]),d(!1)}catch(C){a.error(`Artifacts load failed: ${C.message}`),d(!1)}},g=r.useMemo(()=>{let C=i;if(x){const k=x.toLowerCase();C=C.filter(N=>(N.slug||"").toLowerCase().includes(k)||(N.title||"").toLowerCase().includes(k))}return c||(C=C.filter(k=>k.status!=="archived")),C},[i,x,c]),j=async(C,k)=>{try{const N=await S.post("/artifacts",{slug:C,title:k});a.success(`Artifact "${N.slug}" created.`),p(N.slug),await h()}catch(N){a.error(`Create failed: ${N.message}`)}},b=async C=>{if(confirm(`Delete artifact "${C}"? This removes the directory permanently.`))try{await S.del(`/artifacts/${encodeURIComponent(C)}`),a.success("Artifact deleted."),o===C&&p(null),await h()}catch(k){a.error(`Delete failed: ${k.message}`)}};return o?e.jsxs("div",{className:"artifact-glyph-overlay",children:[e.jsx("div",{className:"artifact-glyph-toolbar",children:e.jsxs(A,{variant:"ghost",onClick:()=>{p(null),h()},children:[e.jsx(Qt,{size:14})," Back to artifacts"]})}),e.jsx(mr,{slug:o,onClose:()=>{p(null),h()},onCommentAdded:()=>h()})]}):e.jsxs("div",{className:"view view-artifacts",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(Os,{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(ve,{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:C=>u(C.target.value),"aria-label":"Search artifacts"})]}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:()=>m(C=>!C),title:c?"Hide archived":"Show archived",children:[c?e.jsx(sa,{size:14}):e.jsx(hn,{size:14}),c?"Hide archived":"Show archived"]}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:h,children:[e.jsx(oe,{size:14})," Refresh"]})]})]}),e.jsx(pr,{onCreate:j}),l?e.jsx("div",{className:"view-loading",children:e.jsx(me,{size:"lg"})}):g.length===0?e.jsx(Se,{icon:e.jsx(Os,{size:32}),title:c?"No artifacts":"No artifacts yet",message:c?"No artifacts match your filter (try Show archived off).":"Create one above to get started."}):e.jsx("div",{className:"artifacts-grid",children:g.map(C=>e.jsx(gr,{artifact:C,onOpen:()=>p(C.slug),onDelete:()=>b(C.slug)},C.slug))})]})}function pr({onCreate:s}){const[t,a]=r.useState(""),[i,n]=r.useState("");return e.jsxs(K,{className:"new-artifact",children:[e.jsxs(Z,{children:[e.jsx(Ce,{size:14})," New artifact"]}),e.jsx(te,{children:"Slug must be lowercase, may contain hyphens, 1–64 chars."}),e.jsxs("form",{className:"new-artifact-form",onSubmit:l=>{l.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:l=>a(l.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:l=>n(l.target.value)}),e.jsx(A,{variant:"primary",type:"submit",children:"Create"})]})]})}function gr({artifact:s,onOpen:t,onDelete:a}){const i=ur(s.status||"draft");return e.jsxs(K,{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(rs,{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 ",ke(s.mtime)]})]}),e.jsxs("div",{className:"artifact-card-actions",children:[e.jsxs(A,{variant:"primary",size:"sm",onClick:n=>{n.stopPropagation(),t()},children:["Open",e.jsx(Ve,{size:12})]}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:n=>{n.stopPropagation(),a()},children:[e.jsx(be,{size:12})," Delete"]})]})]})}function jr({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 fr({task:s,agents:t,onPromote:a,onDelete:i,onEdit:n,onRefresh:l}){var u;const d=le(),o=async()=>{try{await S.post(`/tasks/${encodeURIComponent(s.id)}/promote`),d.success("Promoted to queued.",1500),a(s.id)}catch(c){d.error(`Promote failed: ${c.message}`)}},p=async()=>{if(confirm("Delete this task?"))try{await S.del(`/tasks/${encodeURIComponent(s.id)}`),d.success("Deleted.",1500),i(s.id)}catch(c){d.error(`Delete failed: ${c.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:ke(s.createdAt)}),e.jsxs("div",{className:"backlog-item-actions",children:[e.jsx("button",{type:"button",className:"icon-btn",title:"Promote to queued",onClick:o,children:e.jsx(kt,{size:13})}),e.jsx("button",{type:"button",className:"icon-btn",title:"Edit",onClick:()=>n(s),children:e.jsx(Fe,{size:13})}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger",title:"Delete",onClick:p,children:e.jsx(be,{size:13})})]})]})]})}function vr({agents:s,onRefresh:t}){const a=le(),[i,n]=r.useState([]),[l,d]=r.useState(!1),o=async()=>{try{d(!0);const m=await S.get("/tasks/backlog");n(Array.isArray(m.tasks)?m.tasks:[])}catch(m){a.error(`Backlog load failed: ${m.message}`)}finally{d(!1)}};r.useEffect(()=>{o()},[]);const p=async m=>{n(h=>h.filter(g=>g.id!==m)),await t()},x=async m=>{n(h=>h.filter(g=>g.id!==m)),await t()},u=m=>{},c=async()=>{var m;if(i.length!==0)try{const g=((m=(await S.post("/tasks/promote-batch",{ids:i.map(j=>j.id)})).affected)==null?void 0:m.filter(j=>j.ok).length)??0;a.success(`Promoted ${g} task(s).`,2e3),n([]),await t()}catch(h){a.error(`Promote all failed: ${h.message}`)}};return e.jsxs("div",{className:"backlog-panel",children:[e.jsxs("div",{className:"backlog-panel-header",children:[e.jsxs("span",{className:"backlog-panel-title",children:[e.jsx(_s,{size:15}),"Backlog (",i.length,")"]}),e.jsxs("div",{className:"backlog-panel-header-actions",children:[i.length>0&&e.jsxs(A,{variant:"ghost",size:"sm",onClick:c,title:"Promote all to queued",children:[e.jsx(kt,{size:12})," Promote all"]}),e.jsx(A,{variant:"ghost",size:"sm",onClick:o,title:"Refresh backlog","aria-label":"Refresh backlog",children:e.jsx(oe,{size:12,className:l?"animate-spin":""})})]})]}),l?e.jsx("div",{className:"backlog-empty",children:"Loading…"}):i.length===0?e.jsxs("div",{className:"backlog-empty",children:[e.jsx(_s,{size:28}),e.jsx("span",{children:"Backlog is empty."})]}):e.jsx("div",{className:"backlog-list",children:i.map(m=>e.jsx(fr,{task:m,agents:s,onPromote:p,onDelete:x,onEdit:u,onRefresh:t},m.id))})]})}const Ps=[{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"}],Ct=["low","normal","high"];function yr({snapshot:s,refreshSnapshot:t,setActiveTab:a}){const i=le(),n=Te(),[l,d]=r.useState(s.tasks||[]),[o,p]=r.useState(!s.tasks),[x,u]=r.useState(""),[c,m]=r.useState(""),[h,g]=r.useState(!1),[j,b]=r.useState(0),[C,k]=r.useState(""),N=async()=>{try{const v=await S.get("/tasks");d(Array.isArray(v)?v:[])}catch(v){i.error(`Tasks load failed: ${v.message}`)}finally{p(!1)}};r.useEffect(()=>{s.tasks&&(d(s.tasks),p(!1))},[s.tasks]),r.useEffect(()=>{const v=setInterval(()=>b(w=>w+1),3e4);return()=>clearInterval(v)},[]);const E=r.useMemo(()=>{let v=l.filter(w=>w.status!=="backlog");if(c&&(v=v.filter(w=>(w.priority||"normal")===c)),x.trim()){const w=x.toLowerCase();v=v.filter(P=>(P.title||"").toLowerCase().includes(w)||(P.description||"").toLowerCase().includes(w))}return v},[l,x,c]),$=r.useMemo(()=>{const v={high:0,normal:1,low:2};return[...E].sort((w,P)=>{const y=v[w.priority]??1,L=v[P.priority]??1;return y!==L?y-L:new Date(P.createdAt).getTime()-new Date(w.createdAt).getTime()})},[E]),z=l.filter(v=>v.status==="backlog").length,I=async(v,w)=>{const P=l.find(L=>L.id===v);if(!P)return;const y=P.status;d(L=>L.map(B=>B.id===v?{...B,status:w}:B)),k(`Task ${P.title} moved to ${w}.`);try{await S.patch(`/tasks/${encodeURIComponent(v)}/status`,{status:w}),i.success(`Moved to ${w}.`,1200)}catch(L){d(B=>B.map(R=>R.id===v?{...R,status:y}:R)),k(`Failed to move task ${P.title}: ${L.message}`),i.error(`Move failed: ${L.message}`)}},f=async v=>{if(confirm("Delete this task?"))try{await S.del(`/tasks/${encodeURIComponent(v)}`),d(w=>w.filter(P=>P.id!==v)),i.success("Task deleted.",1200)}catch(w){i.error(`Delete failed: ${w.message}`)}},F=async v=>{try{const w=await S.post(`/tasks/${encodeURIComponent(v)}/start`);w&&w.task&&d(P=>P.map(y=>y.id===v?w.task:y)),i.success("Retry dispatched.",1200)}catch(w){i.error(`Retry failed: ${w.message}`)}},T=async v=>{const w=l.find(P=>P.id===v);if(w)try{const P=await S.post("/tasks/submit",{title:w.title,description:w.description,priority:w.priority,tags:w.tags}),y=(P.subtasks||[]).length;i.success(y>1?`Odin split it into ${y} subtasks.`:"Sent to Odin.",1500),P.subtasks&&P.subtasks.length>0&&d(L=>[P.main,...P.subtasks,...L.filter(B=>B.id!==w.id)]),await t()}catch(P){i.error(`Submit failed: ${P.message}`)}};return e.jsxs("div",{className:"view view-tasks",children:[e.jsx("div",{className:"sr-only",role:"status","aria-live":"polite",children:C}),e.jsx("header",{className:"view-header",children:e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(fs,{size:18})," Tasks (",$.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(ve,{size:12,"aria-hidden":!0}),e.jsx("input",{className:"input",type:"text",placeholder:"Search…",value:x,onChange:v=>u(v.target.value),"aria-label":"Search tasks"}),x&&e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Clear search",onClick:()=>u(""),children:e.jsx(ze,{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:c,onChange:v=>m(v.target.value),title:"Filter by priority",children:[e.jsx("option",{value:"",children:"All"}),Ct.map(v=>e.jsx("option",{value:v,children:v},v))]})]}),e.jsx("div",{className:"tasks-toolbar-spacer"}),e.jsxs("div",{className:"tasks-toolbar-group",children:[e.jsx(A,{variant:"ghost",size:"sm",onClick:N,title:"Refresh","aria-label":"Refresh tasks",children:e.jsx(oe,{size:14})}),z>0&&e.jsxs(A,{variant:h?"accent":"ghost",size:"sm",onClick:()=>g(v=>!v),title:h?"Hide backlog":"Show backlog",children:[e.jsx(_s,{size:14}),"Backlog",e.jsx("span",{className:"badge",children:z})]}),e.jsxs(A,{variant:"primary",size:"sm",onClick:()=>Nr(n,i,d,N,t),children:[e.jsx(Ce,{size:14})," New task"]})]})]}),h&&z>0&&e.jsx(vr,{agents:s.agents||[],onRefresh:t}),o?e.jsx("div",{className:"view-loading",children:e.jsx(me,{size:"lg"})}):e.jsx("div",{className:"kanban",children:Ps.map(v=>e.jsx(br,{column:v,tasks:$.filter(w=>w.status===v.id),onMove:I,onDelete:f,onRetry:F,onEdit:w=>wr(n,i,w,d,N,t),onSubmitToOdin:T,tick:j},v.id))})]})}function br({column:s,tasks:t,onMove:a,onDelete:i,onRetry:n,onEdit:l,onSubmitToOdin:d,tick:o}){const[p,x]=r.useState(!1);return e.jsxs("div",{className:Y("kanban-column",p&&"kanban-column-drop"),"data-column":s.id,onDragOver:u=>{u.preventDefault(),x(!0)},onDragLeave:()=>x(!1),onDrop:u=>{u.preventDefault(),x(!1);const c=u.dataTransfer.getData("text/task-id");c&&a(c,s.id)},children:[e.jsxs("div",{className:"kanban-col-header",children:[e.jsxs(Z,{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(kr,{task:u,onMove:c=>{const h=Ps.findIndex(g=>g.id===u.status)+c;h>=0&&h<Ps.length&&a(u.id,Ps[h].id)},onEdit:()=>l(u),onDelete:()=>i(u.id),onRetry:()=>n(u.id),onSubmitToOdin:()=>d(u.id),tick:o},u.id))})]})}function kr({task:s,onMove:t,onEdit:a,onDelete:i,onRetry:n,onSubmitToOdin:l,tick:d}){const o=s.workedBy||s.assignee||null;return e.jsxs("div",{className:Y("task-card",`priority-${s.priority}`),"data-task-id":s.id,draggable:!0,onDragStart:p=>{p.dataTransfer.setData("text/task-id",s.id),p.dataTransfer.effectAllowed="move"},"data-tick":d,children:[e.jsxs("div",{className:"task-card-head",children:[e.jsx("span",{className:"priority-dot",style:{background:Fa[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:[o&&e.jsxs("span",{className:"task-card-badge",title:`Auto-assigned to @${o}`,children:[e.jsx(_e,{size:10})," @",o]}),s.timeSpent?e.jsxs("span",{className:"task-card-badge",children:[e.jsx(Us,{size:10})," ",Math.round((s.timeSpent||0)/60),"m"]}):null,s.tags&&s.tags.length>0&&s.tags.slice(0,3).map(p=>e.jsx(jr,{children:p},p))]}),e.jsxs("div",{className:"task-card-footer",children:[e.jsx("span",{className:"task-card-time tabular-nums muted",children:ke(s.createdAt)}),e.jsxs("div",{className:"task-card-actions",onClick:p=>p.stopPropagation(),children:[e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Move left",title:"Move left",onClick:()=>t(-1),children:e.jsx(un,{size:14})}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Edit",title:"Edit",onClick:a,children:e.jsx(xn,{size:14})}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Submit to Odin",title:"Re-delegate to Odin",onClick:l,children:e.jsx(Qe,{size:14})}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Retry",title:"Retry",onClick:n,children:e.jsx(bt,{size:14})}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger","aria-label":"Delete",title:"Delete",onClick:i,children:e.jsx(be,{size:14})}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Move right",title:"Move right",onClick:()=>t(1),children:e.jsx(Ve,{size:14})})]})]})]})}function Nr(s,t,a,i,n){let l=null,d=null,o=null,p=null;const x=async c=>{c&&typeof c.preventDefault=="function"&&c.preventDefault();const m=((l==null?void 0:l.value)||"").trim(),h=((d==null?void 0:d.value)||"").trim();if(!m){t.warning("Title is required."),l==null||l.focus();return}const g=(p==null?void 0:p.value)||"normal",j=((o==null?void 0:o.value)||"").split(",").map(b=>b.trim()).filter(Boolean);try{const b=await S.post("/tasks",{title:m,description:h,priority:g,tags:j});s.close(),typeof window<"u"&&window.dispatchEvent(new MouseEvent("mousedown")),a(C=>[b,...C]),t.success("Task created.",1200),await n()}catch(b){t.error(`Create failed: ${b.message}`)}},u=c=>{c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),x(c))};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:c=>{l=c},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:c=>{d=c},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=d==null?void 0:d.value)!=null&&m.trim()))return;const c=await Pa(d.value);c!==d.value&&(d.value=c)},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:c=>{p=c},id:"task-priority",className:"select",defaultValue:"normal",children:Ct.map(c=>e.jsx("option",{value:c,children:c},c))})]}),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:c=>{o=c},id:"task-tags",className:"input",type:"text",placeholder:"bug, frontend, urgent"})]})]}),e.jsx("p",{className:"muted text-sm",style:{marginTop:8},children:"The agent and final priority are decided by Odin after you submit."})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx(A,{variant:"ghost",onClick:()=>s.close(),children:"Cancel"}),e.jsxs(A,{variant:"primary",type:"button",onClick:c=>x(c),children:[e.jsx(Ce,{size:14})," Create task"]})]})})}function wr(s,t,a,i,n,l){let d=null,o=null,p=null,x=null;const u=async()=>{const c=((d==null?void 0:d.value)||"").trim(),m=((o==null?void 0:o.value)||"").trim();if(!c){t.warning("Title is required."),d==null||d.focus();return}const h=(x==null?void 0:x.value)||"normal",g=((p==null?void 0:p.value)||"").split(",").map(j=>j.trim()).filter(Boolean);try{const j=await S.put(`/tasks/${encodeURIComponent(a.id)}`,{title:c,description:m,priority:h,tags:g});s.close(),typeof window<"u"&&window.dispatchEvent(new MouseEvent("mousedown")),i(b=>b.map(C=>C.id===a.id?j:C)),t.success("Task updated.",1200),await l()}catch(j){t.error(`Save failed: ${j.message}`)}};s.open({title:"Edit task",width:520,children:e.jsxs("div",{className:"task-form",children:[e.jsx("label",{className:"field-label",htmlFor:"edit-task-title",children:"Title *"}),e.jsx("input",{ref:c=>{d=c},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:c=>{o=c},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:c=>{x=c},id:"edit-task-priority",className:"select",defaultValue:a.priority||"normal",children:Ct.map(c=>e.jsx("option",{value:c,children:c},c))})]}),e.jsxs("label",{htmlFor:"edit-task-tags",className:"task-form-field",style:{flex:2},children:["Tags",e.jsx("input",{ref:c=>{p=c},id:"edit-task-tags",className:"input",type:"text",defaultValue:(a.tags||[]).join(", "),placeholder:"comma-separated"})]})]}),e.jsxs(K,{children:[e.jsxs(Z,{children:[e.jsx(ea,{size:12})," Status"]}),e.jsxs(te,{children:["Current: ",e.jsx("strong",{children:a.status}),a.workedBy&&e.jsxs(e.Fragment,{children:[" · Worked by @",a.workedBy]}),a.assignee&&!a.workedBy&&e.jsxs(e.Fragment,{children:[" · Assigned @",a.assignee]})]})]})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx(A,{variant:"ghost",onClick:()=>s.close(),children:"Cancel"}),e.jsxs(A,{variant:"primary",onClick:u,children:[e.jsx(sa,{size:14})," Save"]})]})})}const Sr=qe.memo(yr);function Cr(s){return S.urlWithToken(`/artifacts/${encodeURIComponent(s)}/content`)}function zr(s,t){const a=Cr(t);window.open(a,"_blank","noopener,noreferrer")}const Ft={"1m":60*1e3,"5m":5*60*1e3,"30m":30*60*1e3,"1h":60*60*1e3},$e=56,Oe=32,as=22,Tr=4,Rr=.9,Zs={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 et(s){return s&&Zs[s]||Zs.idle}function Ms(s,t=24){return s?s.length<=t?s:s.slice(0,t-1)+"…":""}function Hs(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 st(s){const t=s._timerStart;return typeof t=="number"&&t>0?t:Hs(s.createdAt)||Date.now()}function $r(s,t){return(s.status==="done"||s.status==="archived"||s.status==="failed"||s.status==="killed")&&(Hs(s.completedAt)||Hs(s.updatedAt))||t}function Ar(s){return typeof s.startedAt=="number"&&s.startedAt>0?s.startedAt:Date.now()}function Mr(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 Lr(s){return s<=6e4?1e4:s<=3e5?3e4:s<=18e5?3e5:6e5}function Ir(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 Er({snapshot:s,refreshSnapshot:t}){const a=le(),i=r.useRef(null),[n,l]=r.useState("live"),[d,o]=r.useState("5m"),[p,x]=r.useState(()=>typeof window>"u"?!0:window.innerWidth>900),[u,c]=r.useState([]),[m,h]=r.useState([]),[g,j]=r.useState(!0),[b,C]=r.useState(0),[k,N]=r.useState(Date.now()),[E,$]=r.useState(()=>Date.now()-Ft["5m"]*.1),[z,I]=r.useState({width:800,height:400}),[f,F]=r.useState(null),[T,v]=r.useState(""),[w,P]=r.useState([]),[y,L]=r.useState(""),[B,R]=r.useState("normal"),[H,ae]=r.useState(""),[J,_]=r.useState(""),[X,ee]=r.useState(!1),[Q,ie]=r.useState(!1),[je,V]=r.useState([]),D=Te(),U=s.agents||[],W=s.tasks||[],ne=Ft[d],q=E,O=E+ne,re=r.useCallback(async()=>{try{const[M,G]=await Promise.all([S.get("/background").catch(()=>({instances:[]})),S.get("/activity?limit=200").catch(()=>({events:[]}))]);c(M.instances||[]),h(G.events||[])}catch(M){console.warn("activity reload failed:",M)}finally{j(!1)}},[]);r.useEffect(()=>{re();const M=setInterval(re,3e3);return()=>clearInterval(M)},[re]),r.useEffect(()=>{C(M=>M+1)},[W.length,U.length]),r.useEffect(()=>{if(n==="pause")return;N(Date.now());const M=setInterval(()=>N(Date.now()),1e3);return()=>clearInterval(M)},[n,b]),r.useEffect(()=>{if(n==="pause")return;(k-E)/ne>Rr&&$(k-ne*.1)},[k,E,ne,n]),r.useEffect(()=>{$(Date.now()-ne*.1)},[d]),r.useEffect(()=>{n==="live"&&$(Date.now()-ne*.1)},[n]),r.useLayoutEffect(()=>{const M=i.current;if(!M)return;const G=new ResizeObserver(xe=>{for(const pe of xe){const{width:de,height:ge}=pe.contentRect;I({width:Math.max(200,Math.floor(de)),height:Math.max(120,Math.floor(ge))})}});return G.observe(M),()=>G.disconnect()},[]);const se=r.useMemo(()=>{const M=[];let G=0;for(const de of u){const ge=Ar(de),Me=Mr(de,k);Me<q||ge>O||M.push({kind:"bg",id:`bg:${de.instanceId}`,index:G++,label:`BG ${Ms(de.promptPreview,20)||de.instanceId.slice(0,10)}`,sub:de.status||"pending",start:ge,end:Me,data:de})}const xe=[...W].sort((de,ge)=>st(de)-st(ge)),pe=[];for(const de of xe){const ge=st(de),Me=$r(de,k);if(Me<q||ge>O)continue;let es=-1;for(let Ke=0;Ke<pe.length;Ke++)if(pe[Ke]<=ge){pe[Ke]=Me,es=Ke;break}es===-1&&(pe.push(Me),es=pe.length-1),M.push({kind:"task",id:`task:${de.id}`,index:G+es,label:Ms(de.title,32),sub:de.status,start:ge,end:Me,data:de})}return M},[u,W,k,q,O]),he=r.useMemo(()=>{const M=new Map;for(const G of se)M.set(G.id,G);return M},[se]),ce=r.useCallback(M=>ne<=0?0:(M-q)/ne*z.width,[q,ne,z.width]),Cs=r.useMemo(()=>{const M=Lr(ne),G=[],xe=Math.floor(q/M)*M;for(let pe=xe;pe<=O+M;pe+=M){if(pe<q-M)continue;if(pe>O)break;const de=ce(pe);de<-40||de>z.width+40||G.push({t:pe,x:de,label:Ir(pe,ne)})}return G},[q,O,ne,z.width,ce]),zs=r.useMemo(()=>{const M=[];for(const G of se){if(G.kind==="events")continue;const xe=Math.max(G.start,q),pe=Math.min(G.end,O);if(pe<q||xe>O)continue;const de=ce(xe),ge=ce(pe),Me=Math.max(Tr,ge-de),es=Oe+as+G.index*$e+8,Ke=$e-16;let De="doing";if(G.kind==="bg"){const ye=G.data.status||"pending";ye==="done"||ye==="success"?De="done":ye==="failed"||ye==="killed"||ye==="error"?De="failed":ye==="queued"||ye==="pending"?De="queued":ye==="blocked"||ye==="stuck"?De="blocked":De="doing"}else{const ye=G.data.status;ye==="done"||ye==="archived"?De="done":ye==="failed"||ye==="killed"?De="failed":ye==="queued"?De="queued":ye==="blocked"?De="blocked":De="doing"}const Ta=(f==null?void 0:f.id)===G.id;M.push({id:G.id,laneIndex:G.index,x:de,y:es,w:Me,h:Ke,label:G.label,statusClass:De,selected:Ta,data:G.data,kind:G.kind,start:G.start,end:G.end})}return M},[se,ce,f,q,O]),Ts=r.useMemo(()=>{const M=[];for(const G of m){const xe=Hs(G.ts);if(xe<q-5e3||xe>O+5e3)continue;const pe=ce(xe);let de=Oe+12;if(G.taskId){const ge=he.get(`task:${G.taskId}`);ge&&(de=Oe+as+ge.index*$e+$e/2)}else if(G.nodeId){const ge=String(G.nodeId),Me=he.get(ge.startsWith("task:")||ge.startsWith("bg:")?ge:`task:${ge}`);Me&&(de=Oe+as+Me.index*$e+$e/2)}M.push({id:`${G.ts}-${G.kind}-${G.author??""}-${G.taskId??""}`,x:pe,y:de,kind:G.kind||"event",ts:xe,text:String(G.text||G.kind||""),author:G.author})}return M},[m,q,O,ce,he]),Rs=r.useMemo(()=>se.map(M=>({id:M.id,y:Oe+as+M.index*$e,h:$e})),[se]),$s=r.useMemo(()=>{const M=ce(k);return Math.max(0,Math.min(z.width,M))},[ce,k,z.width]),Na=r.useCallback(M=>{const xe={id:M.id,kind:M.kind,label:M.label,status:M.statusClass,data:M.data};F(xe)},[]);r.useEffect(()=>{if(!f){P([]),_(""),V([]);return}v(""),L(""),ae(""),V([]),(async()=>{try{const M=await S.get(`/activity?nodeId=${encodeURIComponent(f.id)}&limit=50`);P(M.events||[])}catch{P([])}if(f.kind==="bg"){const M=f.data;try{const G=await S.get(`/background/${encodeURIComponent(M.instanceId)}/output?lines=80`);_(G.output||"")}catch{_("")}if(M.taskId)try{const G=await S.get(`/tasks/${encodeURIComponent(M.taskId)}/artifacts`);V((G.artifacts||[]).map(xe=>xe.id))}catch{V([])}}})()},[f]);const $t=async()=>{if(!(!f||!T.trim())){ie(!0);try{await S.post("/comments",{nodeId:f.id,text:T,author:"user"}),v("");const M=await S.get(`/activity?nodeId=${encodeURIComponent(f.id)}&limit=50`);P(M.events||[]),a.success("Comment added.")}catch(M){a.error(`Comment failed: ${M.message}`)}finally{ie(!1)}}},wa=async()=>{if(!(!f||!y.trim())){ee(!0);try{await S.post(`/nodes/${encodeURIComponent(f.id)}/tasks`,{title:y,description:`Created from timeline selection ${f.id}.`,priority:B}),L(""),a.success("Task created."),await t()}catch(M){a.error(`Task create failed: ${M.message}`)}finally{ee(!1)}}},At=async()=>{if(!f||f.kind!=="bg"||!H.trim())return;const M=f.data;try{const G=await S.post(`/background/${encodeURIComponent(M.instanceId)}/message`,{message:H});G.ok?(a.success("Message sent."),ae("")):a.warning(G.error||"Send failed")}catch(G){a.error(`Send failed: ${G.message}`)}},Sa=async()=>{if(!f||f.kind!=="bg"||!confirm("Kill this bg instance session?"))return;const M=f.data;try{const G=await S.del(`/background/${encodeURIComponent(M.instanceId)}`);G.ok?a.success("Session killed."):a.warning(G.error||"Kill failed"),await re()}catch(G){a.error(`Kill failed: ${G.message}`)}},Ca=async()=>{if(!f||f.kind!=="bg")return;const M=f.data;try{const G=await S.get(`/background/${encodeURIComponent(M.instanceId)}/output?lines=80`);_(G.output||"")}catch{}};r.useEffect(()=>{const M=G=>{G.key==="Escape"&&F(null)};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[]);const za=()=>{C(M=>M+1),re()},Ks=Oe+as+se.length*$e;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(Ae,{size:18})," Activity"]}),e.jsx("p",{className:"view-subtitle",children:"Live timeline of agents, tasks, and background sessions. Active tasks pulse; the red line marks “now”."})]}),e.jsx("div",{className:"view-actions",children:e.jsxs("div",{className:"tl-mode-toggle",children:[e.jsxs(A,{variant:n==="live"?"primary":"secondary",size:"sm",onClick:()=>l(n==="live"?"pause":"live"),title:n==="live"?"Pause timeline":"Resume timeline",children:[n==="live"?e.jsx(ta,{size:14}):e.jsx(ms,{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",d===M&&"tl-zoom-btn-active"),onClick:()=>o(M),title:`Zoom to ${M}`,children:M},M))}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:za,title:"Refresh",children:[e.jsx(oe,{size:14})," Refresh"]})]})})]}),g&&e.jsx("div",{className:"view-loading",children:e.jsx(me,{size:"lg"})}),!g&&U.length===0&&W.length===0&&u.length===0&&m.length===0?e.jsx(Se,{icon:e.jsx(Ae,{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",f&&"tl-view-detail-open"),children:e.jsxs("div",{className:Y("tl-body",!p&&"tl-body-stream-collapsed"),children:[e.jsxs("aside",{className:Y("tl-stream",!p&&"tl-stream-collapsed"),children:[e.jsxs("div",{className:"tl-stream-head",children:[e.jsxs("h3",{children:[e.jsx(vs,{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(pn,{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(xt,{items:[...m].reverse(),itemHeight:40,height:400,className:"tl-stream-virtual",renderItem:M=>{const G=M.author?_e:M.kind==="task"?fs:M.kind==="bg"?Gs:Ae;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:et(M.kind)},children:e.jsx(G,{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:[!p&&e.jsxs(A,{variant:"ghost",size:"sm",onClick:()=>x(!0),title:"Show event stream",children:[e.jsx(gn,{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(q).toLocaleTimeString("en-GB",{hour12:!1})," →"," ",new Date(O).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(jn,{size:11})," agent"]}),e.jsxs("span",{className:"tl-legend-item",children:[e.jsx(fn,{size:11})," task"]}),e.jsxs("span",{className:"tl-legend-item",children:[e.jsx(Gs,{size:11})," bg"]})]})]}),e.jsx("div",{className:"tl-canvas-scroll",children:e.jsxs("svg",{className:"tl-canvas",width:z.width,height:Math.max(z.height,Ks),role:"application","aria-label":"Activity timeline",children:[e.jsx("defs",{children:e.jsx("pattern",{id:"tl-canvas-grid",width:z.width,height:$e,patternUnits:"userSpaceOnUse",children:e.jsx("path",{d:`M 0 0 L 0 ${$e}`,fill:"none",stroke:"var(--border)",strokeWidth:.5,opacity:.35})})}),e.jsx("rect",{width:"100%",height:"100%",fill:"url(#tl-canvas-grid)"}),Rs.map(M=>e.jsx("rect",{className:"tl-lane-bg",x:0,y:M.y,width:z.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:Cs.map(M=>e.jsxs("g",{children:[e.jsx("line",{x1:M.x,y1:0,x2:M.x,y2:Ks,stroke:"var(--border)",strokeWidth:.5,strokeDasharray:"2,4",opacity:.5}),e.jsx("text",{x:M.x+4,y:Oe-8,fontSize:10,fontFamily:"var(--font-mono)",fill:"var(--text-dim)",children:M.label})]},`tick-${M.t}`))}),se.map(M=>{const G=Oe+as+M.index*$e+$e/2;return e.jsxs("g",{className:"tl-lane-label-group",children:[e.jsx("text",{x:6,y:G-2,className:"tl-lane-label",textAnchor:"start",children:Ms(M.label,28)}),e.jsx("text",{x:6,y:G+10,className:"tl-lane-label-sub",textAnchor:"start",children:M.sub})]},`label-${M.id}`)}),zs.map(M=>{const G=et(M.statusClass),xe=M.id===(f==null?void 0:f.id);return e.jsxs("g",{className:Y("tl-task-bar",`tl-task-bar-${M.statusClass}`,xe&&"tl-task-bar-selected"),onClick:()=>Na(M),children:[e.jsx("rect",{x:M.x,y:M.y,width:M.w,height:M.h,rx:6,fill:G,fillOpacity:M.statusClass==="done"?.35:M.statusClass==="queued"?.18:.85,stroke:G,strokeWidth:xe?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:Ms(M.label,Math.max(4,Math.floor(M.w/7)))})]},`bar-${M.id}`)}),Ts.map(M=>{const G=et(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:G,strokeWidth:1.2,opacity:.7}),e.jsx("circle",{cx:M.x,cy:M.y,r:4,fill:G,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:$s,y1:0,x2:$s,y2:Ks,stroke:"var(--error)",strokeWidth:1.5,opacity:.9}),e.jsxs("g",{className:"tl-now-marker",children:[e.jsx("circle",{cx:$s,cy:Oe-4,r:4,fill:"var(--error)"}),e.jsx("text",{x:$s+6,y:Oe-4,fontSize:10,fontWeight:700,fill:"var(--error)",fontFamily:"var(--font-mono)",children:"now"})]})]})})]}),f&&e.jsx("aside",{className:"tl-detail tl-detail-enter",children:e.jsxs(K,{children:[e.jsxs(Z,{children:[f.kind==="agent"&&e.jsx(_e,{size:14}),f.kind==="task"&&e.jsx(fs,{size:14}),f.kind==="bg"&&e.jsx(Gs,{size:14}),f.label,e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>F(null),title:"Close","aria-label":"Close activity detail",style:{marginLeft:"auto"},children:e.jsx(ze,{size:14})})]}),e.jsxs("div",{className:"tl-detail-meta",children:[e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"type"})," ",f.kind]}),e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"status"})," ",e.jsx("code",{children:f.status})]}),f.kind==="agent"&&(()=>{const M=f.data;return e.jsxs(e.Fragment,{children:[M.role&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"role"})," ",M.role]}),M.model&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"model"})," ",M.model]})]})})(),f.kind==="task"&&(()=>{const M=f.data;return e.jsxs(e.Fragment,{children:[M.assignee&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"assignee"})," @",M.assignee]}),M.priority&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"priority"})," ",M.priority]}),M.createdAt&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"created"})," ",new Date(M.createdAt).toLocaleString()]})]})})(),f.kind==="bg"&&(()=>{const M=f.data;return e.jsxs(e.Fragment,{children:[M.startedAt&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"started"})," ",new Date(M.startedAt).toLocaleString()]}),M.tmuxSession&&e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"tmux"})," ",e.jsx("code",{children:M.tmuxSession})," ",M.tmuxActive?e.jsx("span",{className:"tag tag-success",children:"active"}):e.jsx("span",{className:"tag",children:"inactive"})]})]})})()]}),f.kind==="task"&&f.data.description&&e.jsx("div",{className:"tl-detail-desc",children:f.data.description}),f.kind==="bg"&&f.data.promptPreview&&e.jsx("div",{className:"tl-detail-desc",children:f.data.promptPreview}),f.kind==="bg"&&e.jsxs("div",{className:"tl-detail-bg",children:[e.jsx("pre",{className:"tl-bg-output",children:J||"(no output — start the session via tmux attach)"}),e.jsxs("div",{className:"tl-bg-output-actions",children:[e.jsxs(A,{variant:"ghost",size:"sm",onClick:Ca,children:[e.jsx(oe,{size:12})," Refresh output"]}),je.length>0&&e.jsxs(A,{variant:"secondary",size:"sm",onClick:()=>zr(D,je[0]),children:[e.jsx(we,{size:12})," Open artifact"]}),e.jsxs(A,{variant:"danger",size:"sm",onClick:Sa,children:[e.jsx(be,{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:H,onChange:M=>ae(M.target.value),onKeyDown:M=>{M.key==="Enter"&&At()},"aria-label":"Send a message to this bg session"}),e.jsxs(A,{variant:"primary",size:"sm",disabled:!H.trim(),onClick:At,children:[e.jsx(Qe,{size:12})," Send"]})]})]}),f.kind!=="bg"&&e.jsxs("div",{className:"tl-detail-create",children:[e.jsx("label",{className:"field-label",htmlFor:"followup-task-title",children:"Create follow-up task"}),e.jsx("input",{id:"followup-task-title",className:"input",placeholder:"Task title",value:y,onChange:M=>L(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:B,onChange:M=>R(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(A,{variant:"primary",size:"sm",disabled:!y.trim()||X,onClick:wa,children:[e.jsx(Ce,{size:12})," Add task"]})]})]}),e.jsxs("div",{className:"tl-detail-comments",children:[e.jsxs("div",{className:"field-label",children:[e.jsx(qs,{size:12})," Comments & activity"]}),e.jsxs("ul",{className:"comment-list",children:[w.length===0&&e.jsx("li",{className:"muted",children:"No comments yet."}),w.map((M,G)=>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-${G}`))]}),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=>v(M.target.value),onKeyDown:M=>{M.key==="Enter"&&!M.shiftKey&&$t()},"aria-label":"Add a comment"}),e.jsxs(A,{variant:"secondary",size:"sm",disabled:!T.trim()||Q,onClick:$t,children:[e.jsx(Qe,{size:12})," Post"]})]})]})]})},f.id)]})})]})}function Dr(s,t){const a=s.length,i=t.length,n=Array.from({length:i+1},()=>Array(a+1).fill(0));for(let l=0;l<=a;l++)n[0][l]=l;for(let l=0;l<=i;l++)n[l][0]=l;for(let l=1;l<=i;l++)for(let d=1;d<=a;d++){const o=s[d-1]===t[l-1]?0:1;n[l][d]=Math.min(n[l][d-1]+1,n[l-1][d]+1,n[l-1][d-1]+o)}return n[i][a]}function tt(s,t){if(t===s)return 100;if(t.startsWith(s))return 90;const a=t.split(/\s+/);for(const l of a)if(l.startsWith(s))return 80;const i=Math.min(s.length,t.length);return Dr(s,t.substring(0,i))<=2?40:t.includes(s)?30:0}function Pr(s,t){const a=s.toLowerCase().trim();return a?t.map(i=>{const n=tt(a,i.label.toLowerCase()),l=i.value?tt(a,String(i.value).toLowerCase()):0,d=i.description?tt(a,i.description.toLowerCase()):0,o=Math.max(n,l,d);if(o===0)return null;const p=n>=l&&n>=d?"label":l>=n&&l>=d?"value":"description",x=p==="label"?i.label:p==="value"?String(i.value):i.description;return{...i,score:o,matchedField:p,matchedTerm:x}}).filter(i=>i!==null).sort((i,n)=>n.score-i.score):[]}const zt="bizar_settings_recent";function ga(){try{const s=localStorage.getItem(zt);return s?JSON.parse(s):[]}catch{return[]}}function Fr(s){if(s)try{const t=ga().filter(a=>a!==s);t.unshift(s),localStorage.setItem(zt,JSON.stringify(t.slice(0,5)))}catch{}}function Or(s,t){if(!t)return s;const a=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`(${a})`,"gi");return s.split(i).map((l,d)=>i.test(l)?e.jsx("mark",{children:l},d):e.jsx("span",{children:l},d))}function Br(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 Ur({sections:s,onJump:t}){const[a,i]=r.useState(""),[n,l]=r.useState([]),[d,o]=r.useState(0),[p,x]=r.useState(null),[u,c]=r.useState(!1),m=r.useRef(null),h=r.useRef(null),g=r.useRef(null),j=r.useRef([]);r.useEffect(()=>{j.current=Br(s)},[s]);const b=r.useCallback((T,v=!1)=>{if(h.current&&clearTimeout(h.current),!T.trim()){l([]),o(0);return}const w=()=>{const P=Pr(T,j.current);l(P),o(0)};v?w():h.current=setTimeout(w,150)},[]);r.useEffect(()=>{b(a)},[a,b]),r.useEffect(()=>()=>{h.current&&clearTimeout(h.current),g.current&&clearTimeout(g.current)},[]);const C=(T,v)=>{const w=document.querySelector(`[data-section="${T}"] [data-setting-id="${v}"]`);w&&(w.scrollIntoView({behavior:"smooth",block:"center"}),w.classList.add("setting-flash"),setTimeout(()=>w.classList.remove("setting-flash"),2e3));const P=document.querySelector(`[data-section="${T}"]`);P&&P.scrollIntoView({behavior:"smooth",block:w?"nearest":"start"})},k=T=>{x(T),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>x(null),1500);const v=document.querySelector(`[data-section="${T}"]`);v&&v.scrollIntoView({behavior:"smooth",block:"start"})},N=T=>{var v;Fr(a),T.key===T.section?(k(T.section),t(T.section)):(k(T.section),t(T.section,T.key),C(T.section,T.key)),i(""),(v=m.current)==null||v.blur()},E=T=>{var v;T.key==="Escape"?(i(""),(v=m.current)==null||v.blur()):T.key==="ArrowDown"?(T.preventDefault(),o(w=>Math.min(w+1,n.length-1))):T.key==="ArrowUp"?(T.preventDefault(),o(w=>Math.max(w-1,0))):T.key==="Enter"&&(T.preventDefault(),n.length===0&&a.trim()&&b(a,!0),n[d]&&N(n[d]))},$=T=>{N(T)},z=ga(),I=T=>{var v;i(T),(v=m.current)==null||v.focus()},f=()=>{try{localStorage.removeItem(zt)}catch{}c(T=>T)},F=u&&!a.trim()&&z.length>0;return e.jsxs("div",{className:"settings-search",children:[e.jsxs("div",{className:"settings-search-input-wrap",children:[e.jsx(ve,{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:()=>c(!0),onBlur:()=>setTimeout(()=>c(!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(ze,{size:12})})]}),F&&e.jsxs("div",{className:"settings-search-recent",children:[e.jsxs("div",{className:"settings-search-recent-header",children:[e.jsx("span",{className:"settings-search-recent-label",children:"Recent"}),e.jsx("button",{type:"button",className:"settings-search-recent-clear",onClick:f,tabIndex:-1,children:"Clear"})]}),z.map(T=>e.jsxs("button",{type:"button",className:"settings-search-recent-item",onMouseDown:v=>{v.preventDefault(),I(T)},children:[e.jsx(ve,{size:11}),e.jsx("span",{children:T})]},T))]}),a&&n.length>0&&e.jsx("div",{className:"settings-search-results",children:n.map((T,v)=>e.jsxs("button",{type:"button",className:Y("settings-search-result",v===d&&"settings-search-result-active"),onClick:()=>$(T),onMouseEnter:()=>o(v),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:Or(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 _r=[{id:"dark",label:"Dark",Icon:yn},{id:"light",label:"Light",Icon:bn},{id:"system",label:"System",Icon:kn}],Wr=[{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"}],Hr=["Inter","system-ui","Segoe UI","Roboto","JetBrains Mono","SF Mono","Cascadia Code"];function qr({settings:s,patchTheme:t,patchUi:a}){return e.jsxs(K,{id:"settings-theme","data-section":"theme",children:[e.jsxs(Z,{children:[e.jsx(vn,{size:14})," Theme"]}),e.jsx(te,{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:Wr.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:_r.map(({id:i,label:n,Icon:l})=>{const d=s.theme.mode===i;return e.jsxs("button",{type:"button",className:Y("theme-card",d&&"theme-card-active"),onClick:()=>t({mode:i}),children:[e.jsx(l,{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:Hr.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 at=[{id:"bizar",name:"Bizar CLI"},{id:"bizar-dash",name:"Dashboard"},{id:"bizar-plugin",name:"Opencode Plugin"}];function Vr(){const s=le(),[t,a]=r.useState({current:{},latest:null,checking:!1,updating:!1,hasUpdates:!1,requiresRestart:!1,perPackage:{}});r.useEffect(()=>{const o=new pt;return o.on(p=>{(p.type==="update:progress"||p.type==="update:log"||p.type==="update:complete")&&a(x=>{if(p.type==="update:complete")return{...x,updating:!1,requiresRestart:!!p.requiresRestart};if(p.type==="update:log"){const c=p,m=x.perPackage[c.pkg]||{logs:[]};return{...x,perPackage:{...x.perPackage,[c.pkg]:{...m,logs:[...(m.logs||[]).slice(-50),c.line]}}}}const u=p;return{...x,perPackage:{...x.perPackage,[u.pkg]:{...x.perPackage[u.pkg],status:u.status,error:u.error,newVersion:u.newVersion}}}})}),()=>o.close()},[]),r.useEffect(()=>{S.get("/updates/status").then(o=>a(p=>({...p,current:o.current}))).catch(o=>a(p=>({...p,error:o.message})))},[]);const i=async()=>{a(o=>({...o,checking:!0,error:void 0}));try{const o=await S.get("/updates/check");a(p=>({...p,checking:!1,current:o.current,latest:o.latest,hasUpdates:o.hasUpdates}))}catch(o){a(p=>({...p,checking:!1,error:o.message}))}},n=async()=>{if(confirm("Update Bizar packages? The dashboard will restart automatically.")){a(o=>({...o,updating:!0,requiresRestart:!1,perPackage:{},error:void 0}));try{await S.post("/updates/apply",{packages:["bizar","bizar-dash","bizar-plugin"]})}catch(o){a(p=>({...p,updating:!1,error:o.message}))}}},l=async()=>{if(confirm("Restart the dashboard? You will be disconnected briefly."))try{await S.post("/restart"),s.info("Restarting…",3e3),setTimeout(()=>window.location.reload(),3e3)}catch{s.error("Restart failed")}},d=t.checking||t.updating;return e.jsxs(K,{id:"settings-updates","data-section":"updates",children:[e.jsxs(Z,{children:[e.jsx(Je,{size:14})," Updates"]}),e.jsx(te,{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:at.map(o=>e.jsxs("li",{children:[e.jsx("span",{children:o.name}),e.jsx("code",{className:"mono",children:t.current[o.id]||"—"})]},o.id))})]}),t.latest&&e.jsxs("div",{className:"updates-latest",children:[e.jsx("h4",{children:"Latest available"}),e.jsx("ul",{children:at.map(o=>{var c;const p=t.current[o.id],x=(c=t.latest)==null?void 0:c[o.id],u=p&&x&&p!==x;return e.jsxs("li",{className:u?"updates-outdated":"updates-current-version",children:[e.jsx("span",{children:o.name}),e.jsxs("code",{className:"mono",children:[x||"—",u&&e.jsx("span",{className:"updates-badge",children:"update available"})]})]},o.id)})})]}),t.updating&&e.jsx("div",{className:"updates-progress-rows",children:at.map(o=>{const p=t.perPackage[o.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:o.name}),e.jsxs("div",{className:"updates-pkg-status",children:[p.status==="starting"&&e.jsx("span",{className:"btn-spinner"}),p.status==="installing"&&e.jsx("span",{className:"btn-spinner"}),p.status==="done"&&e.jsx(Es,{size:14,className:"icon-success"}),p.status==="error"&&e.jsx(gt,{size:14,className:"icon-error"}),e.jsx("span",{children:p.status}),p.newVersion&&e.jsxs("code",{className:"mono",style:{fontSize:11},children:["→ ",p.newVersion]})]})]}),p.logs.length>0&&e.jsxs("details",{className:"updates-pkg-logs",children:[e.jsxs("summary",{children:["npm output (",p.logs.length," lines)"]}),e.jsx("pre",{children:p.logs.join(`
6
- `)})]}),p.status==="error"&&p.error&&e.jsxs("div",{className:"updates-pkg-error",children:[e.jsx(Ne,{size:12})," ",p.error]})]},o.id)})}),e.jsxs("div",{className:"updates-actions",children:[e.jsxs(A,{onClick:i,disabled:d,children:[t.checking?e.jsx("span",{className:"btn-spinner"}):e.jsx(oe,{size:14}),"Check for updates"]}),e.jsxs(A,{variant:"primary",onClick:n,disabled:!t.hasUpdates||t.updating,children:[t.updating?e.jsx("span",{className:"btn-spinner"}):e.jsx(Je,{size:14}),t.updating?"Updating…":t.hasUpdates?"Update now":"Up to date"]}),t.requiresRestart&&e.jsxs(A,{variant:"danger",onClick:l,children:[e.jsx(oe,{size:14})," Restart Dashboard"]})]}),t.error&&e.jsxs("div",{className:"updates-error",children:[e.jsx(Ne,{size:14}),e.jsx("span",{children:t.error})]})]})}const Kr=[{id:"topnav",label:"Top nav"},{id:"sidebar",label:"Sidebar"},{id:"both",label:"Both"}];function Gr({settings:s,patchUi:t,patchTop:a}){return e.jsxs(e.Fragment,{children:[e.jsxs(K,{id:"settings-layout","data-section":"layout",children:[e.jsxs(Z,{children:[e.jsx(Nn,{size:14})," UI layout"]}),e.jsx(te,{children:"Choose how the dashboard's navigation is presented."}),e.jsx("div",{className:"layout-row","data-setting-id":"ui.layout",children:Kr.map(i=>e.jsx("button",{type:"button",className:Y("layout-card",s.ui.layout===i.id&&"layout-card-active"),onClick:()=>t({layout:i.id}),children:e.jsx("span",{className:"layout-card-label",children:i.label})},i.id))}),e.jsxs("label",{className:"checkbox-row","data-setting-id":"ui.showHeader",children:[e.jsx("input",{type:"checkbox",checked:s.ui.showHeader,onChange:i=>t({showHeader:i.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:i=>t({showStatusBar:i.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:i=>t({defaultTab:i.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(K,{id:"settings-general","data-section":"general",children:[e.jsx(Z,{children:"General"}),e.jsx(te,{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("input",{id:"set-default-agent",className:"input",type:"text",placeholder:"e.g. odin",value:s.defaultAgent||"",onChange:i=>a("defaultAgent",i.target.value)})]}),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("input",{id:"set-default-model",className:"input",type:"text",placeholder:"(leave empty for provider default)",value:s.defaultModel||"",onChange:i=>a("defaultModel",i.target.value)})]})]})]})}function Yr({tailscale:s,tailscaleDraft:t,setTailscaleDraft:a,onTailscaleToggle:i}){return e.jsxs(e.Fragment,{children:[e.jsxs(K,{id:"settings-service","data-section":"service",children:[e.jsxs(Z,{children:[e.jsx(ys,{size:14})," Service"]}),e.jsx(te,{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(K,{id:"settings-tailscale","data-section":"tailscale",children:[e.jsxs(Z,{children:[e.jsx(ct,{size:14})," Tailscale serve"]}),e.jsx(te,{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(l=>({...l,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(l=>({...l,https:n.target.checked}))})]})]}),e.jsx(A,{variant:"primary",onClick:i,children:s.settings.enabled?"Disable serve":"Enable serve"})]}):e.jsx("p",{className:"muted",children:"Loading Tailscale status…"})]})]})}function Xr({settings:s,patchNotifications:t}){return e.jsxs(K,{id:"settings-notifications","data-section":"notifications",children:[e.jsx(Z,{children:"Notifications"}),e.jsx(te,{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 Qr({authStatus:s,setAuthStatus:t}){const a=le(),[i,n]=r.useState(S.getToken()),[l,d]=r.useState("");r.useEffect(()=>{let u=!1;return(async()=>{try{const c=await S.probeAuthStatus();u||t(c)}catch{u||t({required:!0,loopback:!1,peer:""})}})(),()=>{u=!0}},[]);const o=async()=>{try{const u=await S.get("/auth/reveal");d(u.token),n(u.token),S.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}`)}},p=async()=>{if(confirm("Regenerate the auth token? Anything still using the old token will start getting 401 errors immediately."))try{const u=await S.post("/auth/regenerate");d(u.token),n(u.token),S.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=()=>{S.setToken(i.trim()),a.success("Token saved. The dashboard will use it on the next request.")};return e.jsxs(K,{id:"settings-auth","data-section":"auth",children:[e.jsxs(Z,{children:[e.jsx(aa,{size:14})," Authentication"]}),e.jsx(te,{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(A,{variant:"secondary",size:"sm",onClick:x,children:[e.jsx(Nt,{size:14})," Save token"]}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:o,children:[e.jsx(Ze,{size:14})," Reveal & copy server token"]}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:p,children:[e.jsx(na,{size:14})," Regenerate"]})]}),l?e.jsxs("p",{className:"muted",style:{fontSize:12,marginTop:8},children:["Last revealed token (one-time): ",e.jsx("code",{className:"mono",children:l})]}):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 Jr({settings:s,patchAgents:t,patchDashboard:a}){var p,x,u;const i=le(),[n,l]=r.useState({});r.useEffect(()=>{S.get("/settings/plugin-options").then(l).catch(()=>{})},[]);const d=async()=>{try{await S.put("/settings/plugin-options",n),i.success("Saved — restart opencode for changes to take effect.")}catch(c){i.error(`Save failed: ${c.message}`)}},o=async()=>{try{const m=await(await fetch("/api/background/cleanup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({maxAgeDays:7})})).json();i.success(`Cleaned up ${m.deleted} old instances.`)}catch(c){i.error(`Cleanup failed: ${c.message}`)}};return e.jsxs(e.Fragment,{children:[e.jsxs(K,{id:"settings-agents","data-section":"agents",children:[e.jsxs(Z,{children:[e.jsx(ys,{size:14})," Agent Behavior"]}),e.jsx(te,{children:"Limits and timeouts for background agent dispatch."}),e.jsxs("div",{className:"form-row",children:[e.jsxs("label",{htmlFor:"agents-maxParallel",children:["Max parallel agents",e.jsx("span",{className:"meta-badge",children:"default: 6"})]}),e.jsx("input",{id:"agents-maxParallel",type:"number",min:1,max:20,value:((p=s.agents)==null?void 0:p.maxParallel)??6,onChange:c=>t({maxParallel:Math.max(1,Math.min(20,parseInt(c.target.value,10)||6))})})]}),e.jsxs("div",{className:"form-row",children:[e.jsxs("label",{htmlFor:"agents-stuckThresholdMs",children:["Stuck threshold (ms)",e.jsx("span",{className:"meta-badge",children:"default: 600000 (10 min)"})]}),e.jsx("input",{id:"agents-stuckThresholdMs",type:"number",min:6e4,max:36e5,step:6e4,value:((x=s.agents)==null?void 0:x.stuckThresholdMs)??6e5,onChange:c=>t({stuckThresholdMs:Math.max(6e4,Math.min(36e5,parseInt(c.target.value,10)||6e5))})})]}),e.jsxs("label",{className:"checkbox-row","data-setting-id":"agents.autoRestart",children:[e.jsx("input",{type:"checkbox",checked:!!((u=s.agents)!=null&&u.autoRestart),onChange:c=>t({autoRestart:c.target.checked})}),e.jsx("span",{children:"Auto-restart stuck agents"})]})]}),e.jsxs(K,{id:"settings-dashboard","data-section":"dashboard",children:[e.jsxs(Z,{children:[e.jsx(Ns,{size:14})," Dashboard"]}),e.jsxs(te,{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:c=>a({autoLaunchWeb:c.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:c=>a({projectsDirectory:c.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("textarea",{id:"set-allowed-roots",className:"textarea",rows:4,placeholder:`/workspace
7
- /srv/projects`,value:(s.dashboard.allowedRoots??[]).join(`
8
- `),onChange:c=>{const m=c.target.value.split(`
9
- `).map(h=>h.trim()).filter(Boolean);a({allowedRoots:m})}}),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 c=(s.dashboard.allowedRoots??[]).join(`
10
- `).split(`
11
- `),m=[];return c.forEach((h,g)=>{h.trim()&&(/^\/|^[A-Za-z]:/.test(h)||m.push({key:`noabs-${g}`,msg:e.jsxs("p",{style:{color:"var(--warning)",fontSize:11,marginTop:2},children:["Line ",g+1,': "',h,'" — should be absolute (start with / or a drive letter).']})}),h.includes("..")&&m.push({key:`dots-${g}`,msg:e.jsxs("p",{style:{color:"var(--error)",fontSize:11,marginTop:2},children:["Line ",g+1,': "',h,`" — contains '..' (server will reject this).`]})}))}),m.map(h=>h.msg)})()]})]}),e.jsxs(K,{id:"settings-background","data-section":"background",children:[e.jsxs(Z,{children:[e.jsx(ys,{size:14})," Background Agents"]}),e.jsx(te,{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:n.maxConcurrentInstances??8,onChange:c=>l(m=>({...m,maxConcurrentInstances:Math.max(1,Math.min(32,parseInt(c.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:n.backgroundToolCallCap??500,onChange:c=>l(m=>({...m,backgroundToolCallCap:Math.max(1,Math.min(5e3,parseInt(c.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:n.backgroundStallTimeoutMs??18e4,onChange:c=>l(m=>({...m,backgroundStallTimeoutMs:Math.max(1e4,Math.min(6e5,parseInt(c.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:n.backgroundThinkingLoopTimeoutMs??3e5,onChange:c=>l(m=>({...m,backgroundThinkingLoopTimeoutMs:Math.max(3e4,Math.min(9e5,parseInt(c.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:n.backgroundMaxInterventions??1,onChange:c=>l(m=>({...m,backgroundMaxInterventions:Math.max(1,Math.min(3,parseInt(c.target.value,10)||1))}))}),e.jsxs("small",{className:"muted",children:["Plugin option: ",e.jsx("code",{children:"backgroundMaxInterventions"})]})]}),e.jsxs("div",{className:"form-row",children:[e.jsxs(A,{variant:"secondary",size:"sm",onClick:d,children:[e.jsx(ks,{size:14})," Save plugin options"]}),e.jsx(A,{variant:"secondary",size:"sm",onClick:o,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 Zr({settings:s,patchTop:t}){var a,i,n;return e.jsxs(K,{id:"settings-system-llm","data-section":"system-llm",children:[e.jsxs(Z,{children:[e.jsx(Fe,{size:14})," System LLM API"]}),e.jsx(te,{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:l=>{const d=s.systemLlm||{enabled:!0,provider:"opencode",model:"opencode/deepseek-v4-flash-free"};t("systemLlm",{...d,enabled:l.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:l=>{const d=s.systemLlm||{enabled:!0,provider:"opencode",model:"opencode/deepseek-v4-flash-free"};t("systemLlm",{...d,provider:l.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:l=>{const d=s.systemLlm||{enabled:!0,provider:"opencode",model:"opencode/deepseek-v4-flash-free"};t("systemLlm",{...d,model:l.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 el=[{value:"anthropic",label:"Anthropic"},{value:"anyllm",label:"AnyLLM"},{value:"litellm-anthropic",label:"LiteLLM (Anthropic)"},{value:"litellm-openai",label:"LiteLLM (OpenAI)"}];function sl({settings:s,onPatch:t}){const a=le(),[i,n]=r.useState(null),[l,d]=r.useState(null),[o,p]=r.useState(!1),[x,u]=r.useState(!1),[c,m]=r.useState(!1),[h,g]=r.useState(!1),[j,b]=r.useState(!1),[C,k]=r.useState(!1),N=r.useCallback(async()=>{p(!0);try{const[R,H]=await Promise.all([S.get("/headroom/status"),S.get("/headroom/stats?hours=24").catch(()=>({error:"no stats"}))]);n(R),H.error||d(H)}catch(R){a.error(`Failed to load Headroom status: ${R.message}`)}finally{p(!1)}},[a]);r.useEffect(()=>{N()},[N]);const E=async()=>{u(!0);try{const R=await S.post("/headroom/install",{force:!0});R.installed?(a.success(`Headroom installed via ${R.method}.`),await N()):a.error('Headroom install failed. Try: pip install "headroom-ai[all]"')}catch(R){a.error(`Install failed: ${R.message}`)}finally{u(!1)}},$=async()=>{m(!0);try{(await S.post("/headroom/wrap",{port:s.port})).ok?(a.success("opencode wrapped with Headroom."),await N()):a.error("Wrap failed.")}catch(R){a.error(`Wrap failed: ${R.message}`)}finally{m(!1)}},z=async()=>{g(!0);try{(await S.post("/headroom/unwrap")).ok?(a.success("opencode unwrapped from Headroom."),await N()):a.error("Unwrap failed.")}catch(R){a.error(`Unwrap failed: ${R.message}`)}finally{g(!1)}},I=async()=>{b(!0);try{(await S.post("/headroom/proxy/start",{port:s.port,host:s.host})).ok?(a.success(`Headroom proxy started on ${s.host}:${s.port}.`),await N()):a.error("Proxy start failed.")}catch(R){a.error(`Proxy start failed: ${R.message}`)}finally{b(!1)}},f=async()=>{k(!0);try{(await S.post("/headroom/proxy/stop")).ok?(a.success("Headroom proxy stopped."),await N()):a.error("Proxy stop failed.")}catch(R){a.error(`Proxy stop failed: ${R.message}`)}finally{k(!1)}},F=async()=>{try{const{spawn:R}=await Xt(async()=>{const{spawn:H}=await import("./__vite-browser-external-BIHI7g3E.js");return{spawn:H}},[]);R("headroom",["dashboard"],{detached:!0,stdio:"ignore"})}catch{a.error("Could not open Headroom dashboard. Run `headroom dashboard` manually.")}},{installed:T,version:v,proxyRunning:w,proxyPort:P,wrapped:y}=i||{},L=(l==null?void 0:l.compressionRatio)??0,B=(l==null?void 0:l.tokensSaved)??0;return e.jsx("div",{id:"settings-headroom","data-section":"headroom",children:e.jsxs(K,{children:[e.jsxs(Z,{children:[e.jsx(Ae,{size:14,style:{color:w?"var(--success)":"var(--text-dim)"}}),"Headroom",T&&v&&e.jsxs("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:6},children:["v",v," ",w?"✓":"✗"]}),!T&&e.jsx("span",{style:{fontSize:11,color:"var(--error)",marginLeft:6},children:"not installed"})]}),e.jsx(te,{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(Es,{size:12,style:{color:"var(--success)"}}):e.jsx(Xe,{size:12,style:{color:"var(--error)"}}),e.jsx("span",{children:T?"Installed":"Not installed"})]}),e.jsxs("div",{className:"headroom-status-item",children:[w?e.jsx(Es,{size:12,style:{color:"var(--success)"}}):e.jsx(Xe,{size:12,style:{color:"var(--text-dim)"}}),e.jsxs("span",{children:["Proxy ",w?`${P} ✓`:"stopped"]})]}),e.jsxs("div",{className:"headroom-status-item",children:[y?e.jsx(Es,{size:12,style:{color:"var(--success)"}}):e.jsx(Xe,{size:12,style:{color:"var(--text-dim)"}}),e.jsxs("span",{children:["opencode ",y?"wrapped":"not wrapped"]})]})]}),(B>0||L>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:L>0?`${Math.round(L*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:B>0?B.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(A,{variant:"secondary",size:"sm",onClick:$,disabled:c||y,title:y?"opencode is already wrapped":"Wrap opencode to route through Headroom proxy",children:[c?e.jsx("span",{className:"btn-spinner"}):e.jsx(yt,{size:13}),c?"Wrapping…":y?"Wrapped ✓":"Wrap opencode"]}),y&&e.jsxs(A,{variant:"ghost",size:"sm",onClick:z,disabled:h,children:[h?e.jsx("span",{className:"btn-spinner"}):e.jsx(oe,{size:13}),h?"Unwrapping…":"Unwrap"]})]}):e.jsxs(A,{variant:"primary",size:"sm",onClick:E,disabled:x,children:[x?e.jsx("span",{className:"btn-spinner"}):e.jsx(Je,{size:13}),x?"Installing…":"Install Headroom"]}),T&&e.jsxs(e.Fragment,{children:[w?e.jsxs(A,{variant:"secondary",size:"sm",onClick:f,disabled:C,children:[C?e.jsx("span",{className:"btn-spinner"}):e.jsx(ia,{size:13}),C?"Stopping…":"Stop proxy"]}):e.jsxs(A,{variant:"secondary",size:"sm",onClick:I,disabled:j,children:[j?e.jsx("span",{className:"btn-spinner"}):e.jsx(ms,{size:13}),j?"Starting…":"Start proxy"]}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:F,children:[e.jsx(ds,{size:13}),"Dashboard"]})]}),e.jsx(A,{variant:"ghost",size:"sm",onClick:N,disabled:o,children:e.jsx(oe,{size:13,className:o?"spin":""})})]}),e.jsxs("div",{style:{marginTop:16},children:[e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{type:"checkbox",checked:s.enabled,onChange:R=>t({enabled:R.target.checked})}),e.jsx("span",{children:"Enable Headroom"})]}),e.jsxs("label",{className:"checkbox-row",children:[e.jsx("input",{type:"checkbox",checked:s.autoInstall,onChange:R=>t({autoInstall:R.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:R=>t({autoStart:R.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:R=>t({autoWrap:R.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:R=>t({routeAllProviders:R.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:R=>t({port:Math.max(1,Math.min(65535,parseInt(R.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:R=>t({host:R.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:R=>t({backend:R.target.value}),children:el.map(R=>e.jsx("option",{value:R.value,children:R.label},R.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:R=>t({budget:Math.max(0,parseFloat(R.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:R=>t({outputShaper:R.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:R=>t({telemetry:R.target.checked})}),e.jsx("span",{children:"Enable telemetry"})]})]})]})})}const Ot={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 tl({settings:s,setSettings:t,setDirty:a}){return e.jsx(sl,{settings:s.headroom||Ot,onPatch:i=>{t(n=>({...n,headroom:{...n.headroom||Ot,...i}})),a(!0)}})}function al(){const s=le(),[t,a]=r.useState([]),[i,n]=r.useState(new Set),[l,d]=r.useState(!0),[o,p]=r.useState(""),[x,u]=r.useState(!0),c=r.useCallback(async()=>{d(!0);try{const[b,C]=await Promise.all([S.get("/activity"),S.get("/activity/hidden")]);a(Array.isArray(b.items)?b.items:[]),n(new Set(C.hidden||[]))}catch(b){s.error(`Load failed: ${b.message}`)}finally{d(!1)}},[s]);r.useEffect(()=>{c()},[c]);const m=(b,C)=>{const k=`${b.kind||""}|${b.ts||""}|${b.slug||""}|${C}`;let N=0;for(let E=0;E<k.length;E++)N=(N<<5)-N+k.charCodeAt(E)|0;return Math.abs(N).toString(16).padStart(8,"0").slice(0,16)},h=async()=>{try{await S.del("/activity/hide"),n(new Set),s.success("All hidden activity restored.")}catch(b){s.error(`Restore failed: ${b.message}`)}},g=async b=>{try{await S.del(`/activity/hide/${encodeURIComponent(b)}`);const C=new Set(i);C.delete(b),n(C)}catch(C){s.error(`Restore failed: ${C.message}`)}},j=t.filter((b,C)=>{const k=m(b,C);if(!x&&i.has(k))return!1;if(!o)return!0;const N=o.toLowerCase();return[b.kind,b.slug,b.message].some(E=>typeof E=="string"&&E.toLowerCase().includes(N))});return e.jsxs(K,{id:"settings-activity-log","data-section":"activity-log",children:[e.jsxs(Z,{children:[e.jsx(Ae,{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(A,{variant:"ghost",size:"sm",style:{marginLeft:"auto"},onClick:c,title:"Reload",children:e.jsx(oe,{size:12})})]}),e.jsxs(te,{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(ve,{size:12}),e.jsx("input",{type:"text",className:"input",placeholder:"Filter by kind, slug, or message…",value:o,onChange:b=>p(b.target.value)})]}),e.jsxs("label",{className:"activity-log-toggle",children:[e.jsx("input",{type:"checkbox",checked:x,onChange:b=>u(b.target.checked)}),"Show hidden"]}),e.jsxs(A,{variant:"ghost",size:"sm",disabled:i.size===0,onClick:h,title:"Restore all hidden items to the Overview",children:[e.jsx(He,{size:12})," Restore all"]})]}),l?e.jsx("div",{className:"muted",style:{padding:"12px 0",fontSize:12},children:"Loading…"}):j.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:j.slice(0,200).map((b,C)=>{const k=m(b,C),N=i.has(k);return e.jsxs("tr",{className:Y(N&&"activity-log-row-hidden"),children:[e.jsx("td",{className:"activity-log-kind",children:b.kind||"activity"}),e.jsx("td",{className:"activity-log-detail",children:b.message||b.slug||"—"}),e.jsx("td",{className:"activity-log-time mono",children:b.ts?new Date(b.ts).toLocaleString():"—"}),e.jsx("td",{children:N?e.jsx(A,{variant:"ghost",size:"sm",onClick:()=>g(k),title:"Restore to Overview",children:e.jsx(He,{size:12})}):e.jsx("span",{className:"activity-log-state-tag",children:"shown"})})]},`${b.ts}-${C}`)})})]}),j.length>200&&e.jsxs("div",{className:"muted",style:{fontSize:11,padding:"8px 0"},children:["Showing first 200 of ",j.length,"."]})]})]})}function nl({about:s}){return e.jsxs(K,{id:"settings-about","data-section":"about",children:[e.jsxs(Z,{children:[e.jsx(Vs,{size:14})," About"]}),e.jsx(te,{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 il({about:s}){return e.jsxs(e.Fragment,{children:[e.jsx(al,{}),e.jsx(nl,{about:s})]})}function rl(){return e.jsxs(K,{id:"settings-env-vars","data-section":"env-vars",children:[e.jsx(Z,{children:"Environment Variables"}),e.jsx(te,{children:"Configure environment variables for the Bizar runtime."}),e.jsx("p",{className:"muted",style:{fontSize:12},children:"Environment variable management is coming soon."})]})}function ll(){return e.jsxs(K,{id:"settings-providers","data-section":"providers",children:[e.jsx(Z,{children:"AI Providers"}),e.jsx(te,{children:"Configure API keys and endpoints for AI providers."}),e.jsx("p",{className:"muted",style:{fontSize:12},children:"Provider management is coming soon."})]})}function ol(){return e.jsxs(K,{id:"settings-memory","data-section":"memory",children:[e.jsx(Z,{children:"Memory"}),e.jsx(te,{children:"Configure LightRAG, Obsidian vault, and git integration."}),e.jsx("p",{className:"muted",style:{fontSize:12},children:"Memory configuration is coming soon."})]})}function cl(){return e.jsxs(K,{id:"settings-skills","data-section":"skills",children:[e.jsx(Z,{children:"Skills"}),e.jsx(te,{children:"Manage agent skill paths and refresh available skills."}),e.jsx("p",{className:"muted",style:{fontSize:12},children:"Skills configuration is coming soon."})]})}function dl(){return e.jsxs(K,{id:"settings-backup","data-section":"backup",children:[e.jsx(Z,{children:"Backup & Restore"}),e.jsx(te,{children:"Export and restore your Bizar configuration."}),e.jsx("p",{className:"muted",style:{fontSize:12},children:"Backup and restore is coming soon."})]})}function ml({workspaceId:s,onInviteCreated:t}){const a=Te(),[i,n]=r.useState(""),[l,d]=r.useState("editor"),[o,p]=r.useState([]),[x,u]=r.useState(!1),[c,m]=r.useState(!1),[h,g]=r.useState(null),[j,b]=r.useState(null);r.useEffect(()=>{C()},[s]);async function C(){u(!0);try{const z=await S.get(`/workspaces/${s}/invites`);p(z.invites||[])}catch{}finally{u(!1)}}async function k(z){if(z.preventDefault(),!!i.trim()){m(!0),b(null);try{const I=await S.post(`/workspaces/${s}/invites`,{email:i.trim(),role:l});n(""),await C(),t==null||t(),a.open({title:"Invite Link Created",children:e.jsxs("div",{className:"invite-link-dialog",children:[e.jsxs("p",{children:["Share this link with ",e.jsx("strong",{children:i})," to invite them as ",e.jsx("strong",{children:l}),":"]}),e.jsxs("div",{className:"invite-url-box",children:[e.jsx(Sn,{size:14}),e.jsx("input",{type:"text",readOnly:!0,value:I.url,onClick:f=>f.target.select()}),e.jsx("button",{type:"button",className:"invite-copy-btn",onClick:()=>{navigator.clipboard.writeText(I.url).catch(()=>{}),g(I.token),setTimeout(()=>g(null),2e3)},children:h===I.token?e.jsx(ls,{size:14}):e.jsx(Ze,{size:14})})]}),e.jsx("p",{className:"invite-url-note",children:"This link expires in 7 days."})]}),footer:e.jsx(A,{variant:"primary",size:"sm",onClick:()=>a.close(),children:"Done"})})}catch(I){b(I.message||"Failed to create invite")}finally{m(!1)}}}async function N(z){if(confirm("Revoke this invite?"))try{await S.del(`/workspaces/${s}/invites/${z}`),await C()}catch(I){b(I.message||"Failed to revoke invite")}}function E(z,I){navigator.clipboard.writeText(z).catch(()=>{}),g(I),setTimeout(()=>g(null),2e3)}const $={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:z=>n(z.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:l,onChange:z=>d(z.target.value),children:[e.jsx("option",{value:"viewer",children:"Viewer"}),e.jsx("option",{value:"editor",children:"Editor"}),e.jsx("option",{value:"admin",children:"Admin"})]})]}),e.jsxs(A,{type:"submit",variant:"primary",size:"sm",loading:c,disabled:!i.trim(),children:[e.jsx(wn,{size:13}),"Invite"]})]}),j&&e.jsx("p",{className:"invite-error",children:j})]}),e.jsxs("div",{className:"invite-list",children:[e.jsx("h4",{className:"invite-list-title",children:"Pending Invites"}),x&&e.jsx("p",{className:"invite-loading",children:"Loading..."}),!x&&o.length===0&&e.jsx("p",{className:"invite-empty",children:"No pending invites"}),o.map(z=>e.jsxs("div",{className:"invite-item",children:[e.jsxs("div",{className:"invite-item-info",children:[e.jsx("span",{className:"invite-item-email",children:z.email}),e.jsx("span",{className:Y("invite-item-role",$[z.role]),children:z.role})]}),e.jsxs("div",{className:"invite-item-actions",children:[e.jsx("button",{type:"button",className:"invite-action-btn",title:"Copy invite link",onClick:()=>{const I=`${window.location.origin}/accept-invite?token=${z.token}`;E(I,z.token)},children:h===z.token?e.jsx(ls,{size:13}):e.jsx(Ze,{size:13})}),e.jsx("button",{type:"button",className:"invite-action-btn invite-action-revoke",title:"Revoke invite",onClick:()=>N(z.token),children:e.jsx(be,{size:13})})]})]},z.token))]})]})}const hl={admin:Cn,editor:aa,viewer:He},ul={admin:"role-admin",editor:"role-editor",viewer:"role-viewer"};function xl(){const[s,t]=r.useState([]),[a,i]=r.useState(!0),[n,l]=r.useState(!1),[d,o]=r.useState(""),[p,x]=r.useState(null),[u,c]=r.useState(null),m=Te();r.useEffect(()=>{h()},[]);async function h(){i(!0);try{const C=await S.get("/workspaces");t(C.workspaces||[])}catch{x("Failed to load workspaces")}finally{i(!1)}}async function g(C){if(C.preventDefault(),!!d.trim()){l(!0);try{await S.post("/workspaces",{name:d.trim()}),o(""),await h()}catch(k){x(k.message||"Failed to create workspace")}finally{l(!1)}}}async function j(C,k){if(confirm(`Delete workspace "${k}"?`)&&confirm("This cannot be undone."))try{await S.del(`/workspaces/${C}`),await h()}catch(N){x(N.message||"Failed to delete workspace")}}function b(C){navigator.clipboard.writeText(`${window.location.origin}/accept-invite?workspace=${C}`).catch(()=>{}),c(C),setTimeout(()=>c(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."}),p&&e.jsxs("div",{className:"settings-section-error",children:[e.jsx("span",{children:p}),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:d,onChange:C=>o(C.target.value),maxLength:64}),e.jsxs(A,{type:"submit",variant:"primary",size:"sm",loading:n,disabled:!d.trim(),children:[e.jsx(Ce,{size:13}),"Create"]})]}),e.jsxs("div",{className:"workspace-list",children:[s.length===0&&e.jsx("p",{className:"workspace-list-empty",children:"No workspaces yet. Create one above."}),s.map(({workspace:C,role:k})=>{const N=hl[k]||He;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(Ws,{size:16})}),e.jsxs("div",{className:"workspace-item-details",children:[e.jsx("span",{className:"workspace-item-name",children:C.name}),e.jsxs("span",{className:Y("workspace-item-role",ul[k]),children:[e.jsx(N,{size:11}),k]})]})]}),e.jsxs("div",{className:"workspace-item-actions",children:[e.jsx(A,{variant:"ghost",size:"sm",iconOnly:!0,title:"Copy invite link",onClick:()=>b(C.id),children:u===C.id?e.jsx(ls,{size:13}):e.jsx(Ze,{size:13})}),k==="admin"&&e.jsx(A,{variant:"ghost",size:"sm",iconOnly:!0,title:"Manage members",onClick:()=>{m.open({title:`Manage "${C.name}"`,children:e.jsx(ml,{workspaceId:C.id,onInviteCreated:()=>h()}),width:520})},children:e.jsx(Ws,{size:13})}),k==="admin"&&s.length>1&&e.jsx(A,{variant:"ghost",size:"sm",iconOnly:!0,title:"Delete workspace",onClick:()=>j(C.id,C.name),children:e.jsx(be,{size:13})})]})]},C.id)})]})]})}const Bt=[{id:"theme",label:"Theme"},{id:"updates",label:"Updates"},{id:"layout",label:"Layout"},{id:"general",label:"General"},{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:"env-vars",label:"Env Vars"},{id:"providers",label:"Providers"},{id:"memory",label:"Memory"},{id:"skills",label:"Skills"},{id:"backup",label:"Backup"},{id:"workspaces",label:"Workspaces"}],pl=[{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:"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"}]},{id:"env-vars",label:"Env Vars",fields:[{key:"env.add",label:"Add variable",section:"env-vars"}]},{id:"providers",label:"Providers",fields:[{key:"providers.list",label:"Provider list",section:"providers"}]},{id:"memory",label:"Memory",fields:[{key:"memory.config",label:"Memory config",section:"memory"}]},{id:"skills",label:"Skills",fields:[{key:"skills.paths",label:"Skill paths",section:"skills"}]},{id:"backup",label:"Backup",fields:[{key:"backup.create",label:"Create backup",section:"backup"},{key:"backup.restore",label:"Restore backup",section:"backup"}]}];function gl({settings:s,refreshSnapshot:t}){const a=le(),[i,n]=r.useState(s),[l,d]=r.useState(!1),[o,p]=r.useState(!1),[x,u]=r.useState(null),[c,m]=r.useState({port:4321,https:!0,hostname:""}),[h,g]=r.useState(null);r.useEffect(()=>{n(s),d(!1),s.theme&&is(s.theme)},[s]),r.useEffect(()=>{x&&m({port:x.settings.port,https:x.settings.https!==!1,hostname:x.settings.hostname||""})},[x]),r.useEffect(()=>{S.get("/tailscale/status").then(u).catch(()=>{})},[]);const j=B=>{n(R=>{const H={...R,theme:{...R.theme,...B}};return is(H.theme),H}),d(!0)},b=B=>{n(R=>({...R,ui:{...R.ui,...B}})),d(!0)},C=(B,R)=>{n(H=>({...H,[B]:R})),d(!0)},k=B=>{n(R=>({...R,notifications:{...R.notifications,...B}})),d(!0)},N=B=>{n(R=>({...R,agents:{...R.agents,...B}})),d(!0)},E=B=>{n(R=>({...R,dashboard:{...R.dashboard,...B}})),d(!0)},[$,z]=r.useState(()=>{if(typeof window>"u")return null;const B=window.location.hash.replace(/^#settings-/,"");return Bt.some(R=>R.id===B)?B:null}),I=B=>{z(B);try{if(history.replaceState(null,"",B?`#settings-${B}`:window.location.pathname),B){const R=document.getElementById(`settings-${B}`);R&&R.scrollIntoView({behavior:"smooth",block:"start"})}else window.scrollTo({top:0,behavior:"smooth"})}catch{}},f=async()=>{try{x!=null&&x.settings.enabled?(await S.post("/tailscale/disable"),a.success("Tailscale serve disabled.")):(await S.post("/tailscale/enable",{port:c.port||4321,https:c.https,hostname:c.hostname||""}),a.success("Tailscale serve enabled.")),u(await S.get("/tailscale/status"))}catch(B){a.error(`Tailscale failed: ${B.message}`)}},F=async()=>{p(!0);try{const B=await S.put("/settings",i);n(B.data),d(!1),js(B.data.theme),is(B.data.theme),a.success("Settings saved."),await t()}catch(B){a.error(`Save failed: ${B.message}`)}finally{p(!1)}},T=async()=>{try{const B=await S.get("/settings");n(B.data),d(!1),js(B.data.theme),is(B.data.theme),a.info("Settings reloaded.",1500)}catch(B){a.error(`Reload failed: ${B.message}`)}},v=async()=>{if(confirm("Reset all settings to defaults?"))try{const B=await S.post("/settings/reset");n(B.data),d(!1),js(B.data.theme),is(B.data.theme),a.success("Settings reset."),await t()}catch(B){a.error(`Reset failed: ${B.message}`)}},w={settings:i,patchTheme:j,patchUi:b,patchTop:C,patchNotifications:k,patchAgents:N,patchDashboard:E},P=i.about||{version:"3.0.4",homepage:"https://github.com/DrB0rk/BizarHarness",license:"MIT"},y=$===null,L=B=>$===B;return e.jsxs("div",{className:"view view-settings",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(ft,{size:18})," Settings"]}),e.jsxs("p",{className:"view-subtitle",children:["Personal preferences. Changes are saved to ",e.jsx("code",{children:"~/.config/bizar/settings.json"}),"."]})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs(A,{variant:"ghost",size:"sm",onClick:v,children:[e.jsx(na,{size:14})," Reset"]}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:T,children:[e.jsx(oe,{size:14})," Reload"]}),e.jsxs(A,{variant:"primary",size:"sm",disabled:!l||o,onClick:F,children:[o?e.jsx("span",{className:"btn-spinner"}):e.jsx(ks,{size:14}),o?"Saving…":"Save"]})]})]}),e.jsx(Ur,{sections:pl,onJump:I}),e.jsxs("nav",{className:"settings-subnav","aria-label":"Settings sections",children:[e.jsx("button",{type:"button",className:Y("settings-subnav-button","settings-subnav-button-all",y&&"settings-subnav-button-active"),onClick:()=>I(null),title:"Show all settings sections",children:"All"}),Bt.map(B=>e.jsx("button",{type:"button",className:Y("settings-subnav-button",$===B.id&&"settings-subnav-button-active"),onClick:()=>I(B.id),children:B.label},B.id))]}),e.jsxs("div",{className:Y("settings-grid",$&&"settings-grid-filtered"),"data-active-section":$||void 0,children:[(y||L("theme"))&&e.jsx(qr,{...w}),(y||L("updates"))&&e.jsx(Vr,{}),(y||L("layout")||L("general"))&&e.jsx(Gr,{...w}),(y||L("network")||L("service")||L("tailscale"))&&e.jsx(Yr,{tailscale:x,tailscaleDraft:c,setTailscaleDraft:m,onTailscaleToggle:f}),(y||L("notifications"))&&e.jsx(Xr,{...w}),(y||L("auth"))&&e.jsx(Qr,{settings:i,authStatus:h,setAuthStatus:g}),(y||L("agents")||L("dashboard")||L("background"))&&e.jsx(Jr,{...w}),(y||L("system-llm"))&&e.jsx(Zr,{...w}),(y||L("headroom"))&&e.jsx(tl,{settings:i,setSettings:n,setDirty:d}),(y||L("activity-log")||L("about"))&&e.jsx(il,{about:P}),(y||L("env-vars"))&&e.jsx(rl,{}),(y||L("providers"))&&e.jsx(ll,{}),(y||L("memory"))&&e.jsx(ol,{}),(y||L("skills"))&&e.jsx(cl,{}),(y||L("backup"))&&e.jsx(dl,{}),(y||L("workspaces"))&&e.jsx(xl,{})]})]})}const Ut=qe.memo(gl);function jl({snapshot:s,refreshSnapshot:t}){const a=le(),i=Te(),[n,l]=r.useState(Array.isArray(s.mods)?s.mods:[]),[d,o]=r.useState(!0),[p,x]=r.useState(null),[u,c]=r.useState([]),[m,h]=r.useState(null),[g,j]=r.useState(!1),[b,C]=r.useState(null),[k,N]=r.useState(!1),[E,$]=r.useState({}),z=async()=>{var y,L,B;N(!0);try{const R=await S.get("/mods/registry");C({source:((y=R.registry)==null?void 0:y.source)||"",version:(L=R.registry)==null?void 0:L.version,updatedAt:(B=R.registry)==null?void 0:B.updatedAt,mods:R.mods||[]})}catch(R){C({source:"",mods:[],error:R.message})}finally{N(!1)}},I=async y=>{$(L=>({...L,[y]:!0}));try{const L=await S.post("/mods",{id:y});l(B=>[...B.filter(R=>R.id!==L.id),L]),a.success(`Mod "${L.id}" installed from registry.`),await t()}catch(L){a.error(`Install failed: ${L.message}`)}finally{$(L=>({...L,[y]:!1}))}},f=async(y,L=!1)=>{$(B=>({...B,[y]:!0}));try{const B=await S.post(`/mods/${encodeURIComponent(y)}/upgrade`,{backup:L});l(H=>[...H.filter(ae=>ae.id!==B.mod.id),B.mod]);const R=B.backupPath?` (backup at ${B.backupPath})`:"";a.success(`Mod "${y}" upgraded v${B.from} → v${B.to}${R}.`),await t()}catch(B){a.error(`Upgrade failed: ${B.message}`)}finally{$(B=>({...B,[y]:!1}))}},F=async()=>{try{const y=await S.get("/mods");l(y.mods||[]);try{const L=await S.get("/mods/views");c(L.views||[])}catch{c([])}}catch(y){a.error(`Mods load failed: ${y.message}`)}finally{o(!1)}};r.useEffect(()=>{F()},[]),r.useEffect(()=>{Array.isArray(s.mods)&&s.mods!==n&&l(s.mods)},[s.mods]);const T=()=>{let y=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:L=>y=L,className:"input",type:"text",placeholder:"/path/to/my-mod",autoFocus:!0})]}),footer:e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx(A,{variant:"ghost",onClick:()=>i.close(),children:"Cancel"}),e.jsx(A,{variant:"primary",onClick:async()=>{const L=((y==null?void 0:y.value)||"").trim();if(!L){a.warning("Path is required.");return}try{const B=await S.post("/mods",{path:L});l(R=>[...R,B]),a.success(`Mod "${B.id}" installed.`),i.close(),await t()}catch(B){a.error(`Install failed: ${B.message}`)}},children:"Install"})]})})},v=async y=>{if(confirm(`Uninstall mod "${y}"? This removes the folder from ~/.config/bizar/mods/.`))try{await S.del(`/mods/${encodeURIComponent(y)}`),l(L=>L.filter(B=>B.id!==y)),p===y&&x(null),a.success("Mod uninstalled.")}catch(L){a.error(`Uninstall failed: ${L.message}`)}},w=async y=>{try{const L=await S.put(`/mods/${encodeURIComponent(y.id)}`,{enabled:!y.enabled});l(B=>B.map(R=>R.id===y.id?L:R)),a.success(`Mod ${L.enabled?"enabled":"disabled"}.`)}catch(L){a.error(`Toggle failed: ${L.message}`)}},P=n.find(y=>y.id===p)||null;return d?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(Bs,{size:18})," Mods (",n.length,")"]}),e.jsxs("p",{className:"view-subtitle",children:["Extensions installed in ",e.jsx("code",{children:"~/.config/bizar/mods/"}),". Mods can add agents, commands, routes, and views."]})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs(A,{variant:"secondary",size:"sm",onClick:F,children:[e.jsx(oe,{size:14})," Refresh"]}),e.jsxs(A,{variant:"primary",size:"sm",onClick:T,children:[e.jsx(Ce,{size:14})," Install mod"]})]})]}),n.length===0?e.jsx(Se,{icon:e.jsx(Bs,{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(y=>e.jsxs("div",{className:Y("mod-list-item",p===y.id&&"mod-list-item-active"),onClick:()=>x(y.id),children:[e.jsxs("div",{className:"mod-list-item-head",children:[e.jsxs("div",{children:[e.jsx("div",{className:"mod-list-item-name",children:y.name}),e.jsxs("div",{className:"mod-list-item-meta",children:["v",y.version," · ",y.type," · ",y.author]})]}),e.jsxs("div",{className:"mod-list-item-actions",onClick:L=>L.stopPropagation(),children:[e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Toggle enabled",title:y.enabled?"Disable":"Enable",onClick:()=>w(y),children:e.jsx(vt,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger","aria-label":"Uninstall",title:"Uninstall",onClick:()=>v(y.id),children:e.jsx(be,{size:12})})]})]}),e.jsx("div",{className:"mod-list-item-desc ellipsis-2",title:y.description,children:y.description}),e.jsx("div",{className:"mod-list-item-status",children:e.jsx("span",{className:`mod-mini-pill ${y.enabled?"mod-mini-pill-on":"mod-mini-pill-off"}`,children:y.enabled?"enabled":"disabled"})})]},y.id))}),P&&e.jsx(fl,{mod:P})]}),e.jsxs(K,{className:"mods-registry-card",children:[e.jsxs("button",{type:"button",className:"mods-registry-head","aria-expanded":g,"aria-controls":"mods-registry-body",onClick:()=>{!b&&!k&&z(),j(y=>!y)},children:[e.jsx(Ns,{size:14,"aria-hidden":!0}),e.jsx("span",{className:"mods-registry-title",children:"Mod registry"}),e.jsx("span",{className:"muted",style:{fontSize:11},children:b!=null&&b.mods?`${b.mods.length} available`:"click to browse"}),e.jsx("span",{className:"mods-registry-spacer"}),g?e.jsx(Pe,{size:14,"aria-hidden":!0}):e.jsx(Ve,{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…"}):b!=null&&b.error?e.jsxs("div",{className:"mods-registry-error",children:[e.jsx(ws,{size:12})," Could not load registry: ",b.error]}):!b||b.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:[b.source&&e.jsxs("div",{className:"muted",style:{fontSize:11,marginBottom:8},children:["Source: ",e.jsx("code",{children:b.source})]}),e.jsx("div",{className:"mods-registry-grid",children:b.mods.map(y=>{const L=n.some(R=>R.id===y.id),B=!!E[y.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:y.name}),y.latest&&e.jsxs("span",{className:Y("mod-registry-version",y.upgradeAvailable&&"mod-registry-version-upgrade"),children:["v",y.latest,y.upgradeAvailable?" ↑":""]})]}),y.description&&e.jsx("div",{className:"mod-registry-card-desc",children:y.description}),e.jsxs("div",{className:"mod-registry-card-meta",children:[y.author&&e.jsxs("span",{className:"muted",children:["by ",y.author]}),y.homepage&&e.jsx("a",{href:y.homepage,target:"_blank",rel:"noopener noreferrer",className:"mod-registry-link",children:"homepage"})]}),(y.permissions||[]).length>0&&e.jsxs("div",{className:"mod-registry-perms",children:[e.jsx(ws,{size:10}),(y.permissions||[]).slice(0,4).map(R=>e.jsx("span",{className:"mod-registry-perm",children:R},R)),(y.permissions||[]).length>4&&e.jsxs("span",{className:"mod-registry-perm-more",children:["+",y.permissions.length-4]})]}),e.jsxs("div",{className:"mod-registry-card-actions",children:[!L&&e.jsx(A,{variant:"primary",size:"sm",disabled:B,onClick:()=>I(y.id),title:"Install from registry",children:B?e.jsx(me,{size:"sm"}):e.jsxs(e.Fragment,{children:[e.jsx(Je,{size:12})," Install"]})}),L&&y.upgradeAvailable&&e.jsx(A,{variant:"primary",size:"sm",disabled:B,onClick:()=>f(y.id),title:`Upgrade from v${y.installedVersion||"?"} to v${y.upgradeAvailable}`,children:B?e.jsx(me,{size:"sm"}):e.jsxs(e.Fragment,{children:[e.jsx(Je,{size:12})," Upgrade to v",y.upgradeAvailable]})}),L&&!y.upgradeAvailable&&e.jsxs(A,{variant:"ghost",size:"sm",disabled:!0,title:`Installed v${y.installedVersion||"?"}`,children:["Installed v",y.installedVersion||"?"]})]})]},y.id)})})]})})]}),u.length>0&&e.jsxs(K,{className:"mod-views-hint",children:[e.jsxs(Z,{children:[e.jsx(Ns,{size:14})," Mod views"]}),e.jsxs(te,{children:[u.length," mod-supplied view",u.length===1?"":"s"," are now available in the sidebar navigation. Look for the ",e.jsx("strong",{children:"Mods"})," section at the bottom of the sidebar."]})]}),m&&e.jsxs("div",{className:"mod-iframe-panel",children:[e.jsxs("div",{className:"mod-iframe-header",children:[e.jsxs("span",{children:["Mod view — ",e.jsx("a",{href:m,target:"_blank",rel:"noreferrer",children:m})]}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Close iframe",onClick:()=>h(null),children:e.jsx(ze,{size:14})})]}),e.jsx("iframe",{src:m,className:"mod-iframe",title:"Mod view",sandbox:"allow-scripts allow-same-origin allow-forms allow-popups"})]})]})}function fl({mod:s}){const t=le(),[a,i]=r.useState(null),[n,l]=r.useState(!1),[d,o]=r.useState(!1),[p,x]=r.useState(null),u=async()=>{l(!0);try{const m=await S.get(`/mods/${s.id}/instructions`);i(m),o(!0)}catch(m){t.error(`Failed to load instructions: ${m.message}`)}finally{l(!1)}},c=async()=>{try{const m=await S.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(K,{className:"mod-details",children:[e.jsxs(Z,{children:[e.jsx(we,{size:14})," Mod details — ",s.name]}),e.jsx(te,{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":d,"aria-controls":`mod-instructions-body-${s.id}`,onClick:()=>{!a&&!n&&u(),o(m=>!m)},children:[e.jsx(zn,{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"}),d?e.jsx(Pe,{size:14,"aria-hidden":!0}):e.jsx(Ve,{size:14,"aria-hidden":!0})]}),d&&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(Tn,{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(h=>h===m.filename?null:m.filename),children:[e.jsx("span",{className:"mono",children:m.filename}),e.jsxs("span",{className:"muted",style:{fontSize:10},children:["installed at ",m.fullPath]})]}),p===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(bs,{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(h=>h===m.filename?null:m.filename),children:[e.jsx("span",{className:"mono",children:m.filename}),e.jsxs("span",{className:"muted",style:{fontSize:10},children:["installed at ",m.fullPath]})]}),p===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(ra,{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(h=>h===m.name?null:m.name),children:[e.jsx("span",{className:"mono",children:m.name}),e.jsxs("span",{className:"muted",style:{fontSize:10},children:["installed at ",m.fullPath]})]}),p===m.name&&e.jsx("pre",{className:"mod-instructions-content",children:m.content||e.jsx("em",{className:"muted",children:"(file missing on disk)"})})]},m.name))]}),a.total===0&&e.jsxs("div",{className:"muted",style:{padding:8,fontSize:12},children:["This mod did not install any instruction files. Mods install instructions by shipping a top-level ",e.jsx("code",{children:"INSTRUCTIONS.md"}),", an ",e.jsx("code",{children:"agents/"})," directory, a ",e.jsx("code",{children:"commands/"})," directory, or a ",e.jsx("code",{children:"skills/"})," directory."]}),e.jsx("div",{className:"mod-instructions-actions",children:e.jsxs(A,{variant:"ghost",size:"sm",onClick:c,children:[e.jsx(oe,{size:11})," Reinstall from mod folder"]})})]})]})]})}function vl({viewId:s,reloadKey:t,setActiveTab:a}){const i=le(),[n,l]=r.useState(null),[d,o]=r.useState(!0),[p,x]=r.useState(0);if(r.useEffect(()=>{let u=!1;return(async()=>{try{const c=await S.get("/mods/views");if(u)return;const m=(c.views||[]).find(h=>h.id===s);l(m||null)}catch(c){i.error(`Failed to load mod view: ${c.message}`)}finally{u||o(!1)}})(),()=>{u=!0}},[s,i]),d)return e.jsx(Se,{title:"Loading mod view…"});if(!n)return e.jsx(Se,{title:"Mod view not found",message:`No view with id "${s}" is currently installed.`,action:e.jsx(A,{onClick:()=>a("mods"),variant:"primary",size:"sm",children:"Open Mods"})});if(n.kind==="iframe"){const u=`/api/mods/${n.modId}/web/index.html?t=${p+(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(Ns,{size:14}),n.label,e.jsxs("span",{className:"muted",style:{fontSize:11,fontWeight:400},children:["by ",n.modId]})]}),e.jsxs("div",{className:"mod-view-iframe-actions",children:[e.jsxs(A,{variant:"ghost",size:"sm",onClick:()=>x(c=>c+1),title:"Reload this view",children:[e.jsx(oe,{size:11})," Reload"]}),e.jsx("a",{href:u,target:"_blank",rel:"noopener noreferrer",className:"icon-btn",title:"Open in new tab",children:e.jsx(ds,{size:12})})]})]}),e.jsx("iframe",{src:u,className:"mod-view-iframe",title:n.label},p+(t||0))]})}if(n.component){const u=n.component,c=n.modId,m=r.lazy(()=>Xt(()=>import(`/api/mods/${encodeURIComponent(c)}/views/${encodeURIComponent(u)}`),[]).then(h=>({default:h.default??(()=>null)})));return e.jsxs("div",{className:"mod-view-tab-pane",children:[e.jsx("div",{className:"mod-view-iframe-header",children:e.jsxs("span",{className:"mod-view-iframe-label",children:[e.jsx(dt,{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(yl,{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(K,{children:[e.jsxs(Z,{children:[e.jsx(dt,{size:14})," ",n.label]}),e.jsxs(te,{children:["by ",n.modId]}),n.description&&e.jsx("p",{className:"muted",style:{marginTop:8},children:n.description}),e.jsxs("p",{className:"muted",style:{fontSize:12,marginTop:12},children:["This mod declared a tab view but did not provide a component path in views/registry.json. Add a ",e.jsx("code",{children:"component"})," field (e.g. ",e.jsx("code",{children:'"MyView.js"'}),") and ship the file under ",e.jsx("code",{children:"views/"}),"."]}),e.jsx("div",{style:{marginTop:12},children:e.jsx(A,{variant:"secondary",size:"sm",onClick:()=>a("mods"),children:"Open Mods page"})})]})}class yl extends r.Component{constructor(){super(...arguments);hs(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(Ne,{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}}const bl=["interval","cron","once"],kl=["command","agent","webhook"],ut=[{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)"}],Nl=Array.from({length:12},(s,t)=>t*5),Tt=Array.from({length:24},(s,t)=>({value:t,label:t===0?"12 AM":t<12?`${t} AM`:t===12?"12 PM":`${t-12} PM`})),Rt=[{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"}],ja=[{value:"s",label:"seconds"},{value:"m",label:"minutes"},{value:"h",label:"hours"},{value:"d",label:"days"}];function fa(s){if(typeof s!="string")return null;const t=s.trim().split(/\s+/);if(t.length!==5)return null;const[a,i,,,n]=t,l=parseInt(a,10),d=parseInt(i,10);if(!Number.isFinite(l)||!Number.isFinite(d)||a!==String(l)||i!==String(d))return null;const o=n==="*"?"*":parseInt(n,10);return o===null||n!=="*"&&!Number.isFinite(o)?null:{minute:l,hour:d,dow:n==="*"?"*":String(o)}}function wl(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 Sl(s){var l,d;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"?fa(s.schedule):null,a=s.type==="interval"?wl(s.schedule):null,i=s.timezone||"UTC",n=ut.some(o=>o.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"?Cl(s.schedule):"",timezone:n?i:"Other…",customTimezone:n?"":i,actionType:s.action.type,actionTarget:s.action.target||"",actionPrompt:s.action.prompt||"",skipIfBudgetLow:!!((l=s.budgetCheck)!=null&&l.skipIfBudgetLow),maxConcurrent:Number.isFinite((d=s.budgetCheck)==null?void 0:d.maxConcurrent)?s.budgetCheck.maxConcurrent:6,enabled:s.enabled!==!1,humanLabel:""}}function Cl(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 zl(s){var a,i,n;if(s.type==="cron"){if(s.showAdvanced)return{schedule:s.rawCron.trim(),humanLabel:s.humanLabel||s.rawCron.trim()};const l=`${s.cronMinute} ${s.cronHour} * * ${s.cronDow}`,d=((a=Rt.find(u=>u.value===s.cronDow))==null?void 0:a.label)||"",o=((i=Tt.find(u=>u.value===s.cronHour))==null?void 0:i.label)||`${s.cronHour}`,p=String(s.cronMinute).padStart(2,"0"),x=d==="Every day"?`Every day at ${o.replace(" ","")} (min ${p})`:`Every ${d} at ${o.replace(" ","")} (min ${p})`;return{schedule:l,humanLabel:s.humanLabel||x}}if(s.type==="interval"){const l=((n=ja.find(o=>o.value===s.intervalUnit))==null?void 0:n.label)||s.intervalUnit;return{schedule:`${s.intervalN}${s.intervalUnit}`,humanLabel:s.humanLabel||`Every ${s.intervalN} ${l}`}}return s.onceAt?{schedule:new Date(s.onceAt).toISOString(),humanLabel:s.humanLabel||new Date(s.onceAt).toLocaleString()}:{schedule:"",humanLabel:s.humanLabel||""}}function Tl({snapshot:s,refreshSnapshot:t}){var m;const a=le(),i=Te(),[n,l]=r.useState(s.schedules||[]),[d,o]=r.useState(!s.schedules),p=async()=>{try{const h=await S.get("/projects/active/schedules");l(h.schedules||[])}catch(h){a.error(`Schedules load failed: ${h.message}`)}finally{o(!1)}};r.useEffect(()=>{var h;if((h=s.schedules)!=null&&h.length||s.schedules){l(s.schedules||[]),o(!1);return}p()},[s.schedules]);const x=h=>{i.open({title:h?`Edit schedule: ${h.name}`:"New schedule",width:640,children:e.jsx(Rl,{initial:h,onClose:i.close,onSubmitted:async g=>{l(j=>{const b=j.findIndex(k=>k.id===g.id);if(b===-1)return[...j,g];const C=j.slice();return C[b]=g,C}),a.success(h?"Schedule updated.":"Schedule created."),i.close(),await t()},onError:g=>a.error(g)})})},u=async h=>{var g;try{const j=await S.post(`/schedules/${encodeURIComponent(h.id)}/run`);a.success(j.ok?"Schedule ran.":`Run failed: ${((g=j.runResult)==null?void 0:g.error)||"unknown"}`),await p()}catch(j){a.error(`Run failed: ${j.message}`)}},c=async h=>{if(confirm(`Delete schedule "${h.name}"?`))try{await S.del(`/schedules/${encodeURIComponent(h.id)}`),l(g=>g.filter(j=>j.id!==h.id)),a.success("Schedule deleted.")}catch(g){a.error(`Delete failed: ${g.message}`)}};return d?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("h2",{className:"view-title",children:[e.jsx(Us,{size:18})," Schedules (",n.length,")"]}),e.jsxs("p",{className:"view-subtitle",children:["Recurring tasks for the active project: ",e.jsx("strong",{children:((m=s.activeProject)==null?void 0:m.name)||"(none)"}),". Service daemon runs them at the right time."]})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs(A,{variant:"secondary",size:"sm",onClick:p,children:[e.jsx(oe,{size:14})," Refresh"]}),e.jsxs(A,{variant:"primary",size:"sm",onClick:()=>x(),children:[e.jsx(Ce,{size:14})," New schedule"]})]})]}),n.length===0?e.jsx(Se,{icon:e.jsx(Us,{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(h=>{var g;return e.jsxs(K,{className:"schedule-card",children:[e.jsxs("div",{className:"schedule-card-head",children:[e.jsxs("div",{children:[e.jsx(Z,{children:h.name}),e.jsxs(te,{children:[e.jsx("code",{children:h.type})," ·"," ",e.jsx("span",{title:h.schedule,children:$l(h)||h.schedule}),h.timezone&&h.timezone!=="UTC"?e.jsxs(e.Fragment,{children:[" · ",e.jsx("code",{children:h.timezone})]}):null," · ",e.jsx("span",{className:h.enabled?"status-on":"status-neutral",children:h.enabled?"enabled":"disabled"})]})]}),e.jsxs("div",{className:"schedule-card-actions",children:[e.jsxs(A,{variant:"secondary",size:"sm",onClick:()=>x(h),children:[e.jsx(Ss,{size:12})," Edit"]}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:()=>u(h),children:[e.jsx(Rn,{size:12})," Run now"]}),e.jsx("button",{type:"button",className:"icon-btn icon-btn-danger","aria-label":"Delete",title:"Delete",onClick:()=>c(h),children:e.jsx(be,{size:12})})]})]}),e.jsxs("div",{className:"schedule-card-action",children:[e.jsx("span",{className:"muted",children:"action:"})," ",e.jsxs("code",{children:[h.action.type," ",h.action.target]}),h.action.type==="agent"&&h.action.prompt&&e.jsxs("div",{className:"schedule-card-prompt",children:[e.jsx("span",{className:"muted",children:"prompt:"})," ",h.action.prompt]})]}),((g=h.budgetCheck)==null?void 0:g.skipIfBudgetLow)&&e.jsxs("div",{className:"schedule-card-budget",children:[e.jsx("span",{className:"muted",children:"budget gate:"})," ","skip if concurrent ≥ ",h.budgetCheck.maxConcurrent??6]}),e.jsxs("div",{className:"schedule-card-times",children:[e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"last"})," ",h.lastRun?ke(h.lastRun):"—",h.lastResult&&e.jsx("span",{className:`tag ${_t(h.lastResult)}`,children:h.lastResult}),h.lastError&&e.jsxs("span",{className:"muted schedule-card-error",title:h.lastError,children:[" ","— ",Wt(h.lastError,80)]})]}),e.jsxs("div",{children:[e.jsx("span",{className:"muted",children:"next"})," ",h.nextRun?e.jsx("span",{title:new Date(h.nextRun).toISOString(),children:Al(h.nextRun,h.timezone)}):"—",h.nextRun&&e.jsxs("span",{className:"muted",children:[" · ",ke(h.nextRun)]})]})]}),h.history&&h.history.length>0&&e.jsxs("details",{className:"schedule-card-history",children:[e.jsxs("summary",{children:[e.jsx(vs,{size:12})," ",h.history.length," run",h.history.length===1?"":"s"]}),e.jsx("ul",{children:h.history.slice(-10).reverse().map((j,b)=>e.jsxs("li",{children:[e.jsx("span",{className:"tabular-nums muted",children:ke(j.ts)})," ",e.jsx("span",{className:`tag ${_t(j.result)}`,children:j.result}),j.error&&e.jsxs("span",{className:"muted",children:[" — ",Wt(j.error,80)]})]},b))})]})]},h.id)})})]})}function Rl({initial:s,onClose:t,onSubmitted:a,onError:i}){const[n,l]=r.useState(()=>Sl(s)),[d,o]=r.useState(!1),p=r.useMemo(()=>ut.some(c=>c.value===n.timezone)?n.timezone:"Other…",[n.timezone]),x=(c,m)=>{l(h=>({...h,[c]:m}))},u=async c=>{c.preventDefault();const m=n.name.trim();if(!m){i("Name is required.");return}const h=zl(n);if(!h.schedule){i("Schedule value is required.");return}if(!n.actionTarget.trim()){i("Action target is required.");return}const g=n.timezone==="Other…"?n.customTimezone.trim():n.timezone,j={type:n.actionType,target:n.actionTarget.trim()};n.actionType==="agent"&&n.actionPrompt.trim()&&(j.prompt=n.actionPrompt.trim());const b={name:m,type:n.type,schedule:h.schedule,timezone:g||"UTC",action:j,budgetCheck:{maxConcurrent:n.maxConcurrent,skipIfBudgetLow:n.skipIfBudgetLow},enabled:n.enabled};o(!0);try{const C=s?await S.put(`/schedules/${encodeURIComponent(s.id)}`,b):await S.post("/schedules",b);await a(C)}catch(C){i(`${s?"Update":"Create"} failed: ${C.message}`)}finally{o(!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:c=>x("name",c.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:c=>x("type",c.target.value),children:bl.map(c=>e.jsx("option",{value:c,children:c},c))})]})}),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:c=>x("cronDow",c.target.value),children:Rt.map(c=>e.jsx("option",{value:c.value,children:c.label},c.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:c=>x("cronHour",parseInt(c.target.value,10)),children:Tt.map(c=>e.jsx("option",{value:String(c.value),children:c.label},c.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:c=>x("cronMinute",parseInt(c.target.value,10)),children:Nl.map(c=>e.jsx("option",{value:String(c),children:String(c).padStart(2,"0")},c))})]})]})}),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:c=>x("rawCron",c.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(Pe,{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:c=>x("intervalN",parseInt(c.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:c=>x("intervalUnit",c.target.value),children:ja.map(c=>e.jsx("option",{value:c.value,children:c.label},c.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:c=>x("onceAt",c.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:p,onChange:c=>x("timezone",c.target.value),children:[ut.map(c=>e.jsx("option",{value:c.value,children:c.label},c.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:c=>x("customTimezone",c.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:c=>x("actionType",c.target.value),children:kl.map(c=>e.jsx("option",{value:c,children:c},c))})]}),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:c=>x("actionTarget",c.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:c=>x("actionPrompt",c.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:c=>x("skipIfBudgetLow",c.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:c=>x("maxConcurrent",parseInt(c.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:c=>x("enabled",c.target.checked)}),e.jsx("span",{children:"Enabled"})]}),e.jsxs("div",{className:"modal-footer-actions",children:[e.jsx(A,{variant:"ghost",type:"button",onClick:t,disabled:d,children:"Cancel"}),e.jsx(A,{variant:"primary",type:"submit",disabled:d,children:s?"Save":"Create"})]})]})}function $l(s){var l,d;if(s.type!=="cron")return s.schedule;const t=fa(s.schedule);if(!t)return s.schedule;const a=((l=Rt.find(o=>o.value===t.dow))==null?void 0:l.label)||"",i=((d=Tt.find(o=>o.value===t.hour))==null?void 0:d.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 Al(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 _t(s){return s==="success"?"tag-success":s==="skipped"?"tag-warning":"tag-error"}function Wt(s,t){return s.length<=t?s:s.slice(0,t-1)+"…"}const Ml=[{id:"all",label:"All",icon:Fe},{id:"shipped",label:"Shipped",icon:wt},{id:"user",label:"User",icon:Ws},{id:"project",label:"Project",icon:Ee}],Fs={shipped:"Shipped",user:"User",project:"Project"},Ll={shipped:wt,user:Ws,project:Ee};function Il({snapshot:s,refreshSnapshot:t}){const a=le(),i=Te(),[n,l]=r.useState([]),[d,o]=r.useState({shipped:0,user:0,project:0,all:0}),[p,x]=r.useState(!0),[u,c]=r.useState("all"),[m,h]=r.useState(""),[g,j]=r.useState(null),[b,C]=r.useState(!1),k=async()=>{var z,I,f;x(!0);try{const F=await S.get("/skills");l(F.skills||[]),o({shipped:((z=F.counts)==null?void 0:z.shipped)??0,user:((I=F.counts)==null?void 0:I.user)??0,project:((f=F.counts)==null?void 0:f.project)??0,all:(F.skills||[]).length})}catch(F){a.error(`Skills load failed: ${F.message}`)}finally{x(!1)}};r.useEffect(()=>{k()},[]),r.useEffect(()=>{if(!m.trim()){j(null);return}C(!0);const z=setTimeout(async()=>{try{const I=await S.get(`/skills/search?q=${encodeURIComponent(m.trim())}`);j(I.results||[])}catch(I){a.error(`Search failed: ${I.message}`)}finally{C(!1)}},280);return()=>clearTimeout(z)},[m]);const N=r.useMemo(()=>g!==null?g:u==="all"?n:n.filter(z=>z.source===u),[n,u,g]),E=async()=>{try{await S.post("/skills/refresh",{}),a.success("Skills refreshed."),await k()}catch(z){a.error(`Refresh failed: ${z.message}`)}},$=async z=>{try{const I=await S.get(`/skills/${encodeURIComponent(z.source)}/${encodeURIComponent(z.name)}`);i.open({title:I.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":I.source,children:Fs[I.source]||I.source}),e.jsx("code",{className:"mono text-sm muted",children:I.path})]}),I.description&&e.jsx("p",{className:"skill-detail-desc",children:I.description}),I.body&&e.jsx("div",{className:"skill-detail-body",children:e.jsx("pre",{className:"skill-body-pre",children:I.body})})]}),footer:e.jsx(A,{variant:"ghost",onClick:()=>i.close(),children:"Close"})})}catch{i.open({title:z.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":z.source,children:Fs[z.source]||z.source}),e.jsx("code",{className:"mono text-sm muted",children:z.path})]}),z.description&&e.jsx("p",{className:"skill-detail-desc",children:z.description})]}),footer:e.jsx(A,{variant:"ghost",onClick:()=>i.close(),children:"Close"})})}};return e.jsxs("div",{className:"view view-skills",children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-text",children:[e.jsxs("h2",{className:"view-title",children:[e.jsx(Fe,{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(ve,{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:z=>h(z.target.value),"aria-label":"Search skills"}),m&&e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Clear search",onClick:()=>h(""),children:e.jsx(Xe,{size:12})})]}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:E,children:[e.jsx(oe,{size:14})," Refresh"]})]})]}),!m.trim()&&e.jsx("div",{className:"skills-tabs",children:Ml.map(z=>{const I=z.icon,f=z.id==="all"?d.all:d[z.id]??0;return e.jsxs("button",{type:"button",className:Y("skills-tab",u===z.id&&"skills-tab-active"),onClick:()=>c(z.id),children:[e.jsx(I,{size:14}),e.jsx("span",{children:z.label}),e.jsx("span",{className:"skills-tab-count",children:f})]},z.id)})}),m.trim()&&e.jsxs("section",{className:"skills-section",children:[e.jsxs("h3",{className:"skills-section-title",children:[e.jsx(ve,{size:14})," Search results",b&&e.jsx(me,{size:"sm"})]}),b?e.jsx("div",{className:"skills-grid",children:[0,1,2].map(z=>e.jsx("div",{className:"skill-card skill-card-skeleton"},z))}):g&&g.length===0?e.jsx(Se,{icon:e.jsx(ve,{size:28}),title:"No matches",message:`No skills match "${m}".`}):e.jsx("div",{className:"skills-grid",children:(g||[]).map((z,I)=>e.jsx(Ht,{skill:z,onShow:()=>$(z),searchQ:m},`search-${I}`))})]}),!m.trim()&&e.jsx("section",{className:"skills-section",children:p?e.jsx("div",{className:"view-loading",children:e.jsx(me,{size:"lg"})}):N.length===0?e.jsx(Se,{icon:e.jsx(ra,{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 ${Fs[u]} tab.`}):e.jsx("div",{className:"skills-grid",children:N.map((z,I)=>e.jsx(Ht,{skill:z,onShow:()=>$(z)},`${z.source}-${z.name}-${I}`))})}),!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 Ht({skill:s,onShow:t,searchQ:a=""}){const i=Ll[s.source]||wt,n=s.description?s.description.length>200?s.description.slice(0,200)+"…":s.description:"No description.";return e.jsxs(K,{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:El(s.name,a)}),e.jsx("span",{className:"skill-source-badge","data-source":s.source,children:Fs[s.source]||s.source})]})]}),e.jsx("p",{className:"skill-card-desc",children:n}),e.jsx("div",{className:"skill-card-actions",children:e.jsxs(A,{variant:"ghost",size:"sm",onClick:t,children:[e.jsx(ds,{size:12})," View"]})})]})}function El(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 Dl=qe.memo(Il);function Pl({refreshKey:s,onRefresh:t,setActiveSubPanel:a}){const i=le(),[n,l]=r.useState(null),[d,o]=r.useState(!0),p=async g=>{o(!0);try{const[j,b,C,k]=await Promise.all([S.get("/memory/health",g).catch(()=>null),S.get("/memory/status",g).catch(()=>null),S.get("/memory/lightrag/stats",g).catch(()=>null),S.get("/memory/storage",g).catch(()=>null)]);l({health:j||{score:0,status:"unconfigured",checks:[],message:"memory not initialised"},vault:{exists:!!(b!=null&&b.initialized),vaultRoot:(b==null?void 0:b.vaultRoot)||"",mode:(b==null?void 0:b.mode)||"local-only",noteCount:(b==null?void 0:b.noteCount)||0,totalSize:(k==null?void 0:k.total)||0,folderCount:0,folders:[],lastModified:null,gitClean:(b==null?void 0:b.gitClean)??null,gitBranch:(b==null?void 0:b.branch)||null},lightrag:C||{running:!1,pid:null,host:"127.0.0.1",port:9621,indexedApprox:0,queryCountLast24h:0,lastReindexAt:null},storage:k||{total:0,breakdown:[]}})}catch(j){i.error(`Memory overview failed: ${j.message}`)}finally{o(!1)}};if(r.useEffect(()=>{const g=new AbortController;return p(g.signal),()=>g.abort()},[s]),d&&!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:c,storage:m}=n,h=x.score>=80?"var(--success)":x.score>=50?"var(--warning)":"var(--error)";return e.jsxs("div",{className:"memory-overview",children:[e.jsxs(K,{variant:"elevated",className:"memory-health-hero",children:[e.jsxs("div",{className:"memory-health-score",style:{borderColor:h},children:[e.jsx("span",{className:"memory-health-score-value",style:{color:h},children: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(Ae,{size:16}),"Memory health ·"," ",e.jsx("span",{style:{color:h},children:x.status})]}),e.jsx("p",{className:"memory-health-message",children:x.message}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:t,children:[e.jsx(oe,{size:12})," Refresh"]})]})]}),e.jsxs("div",{className:"memory-source-pills",children:[e.jsxs("button",{type:"button",className:"memory-source-pill",onClick:()=>a("lightrag"),children:[e.jsx(Ie,{size:14}),e.jsx("span",{children:"LightRAG"}),e.jsx("span",{className:Y("memory-source-pill-status",c.running?"on":"off"),children:c.running?"running":"stopped"})]}),e.jsxs("button",{type:"button",className:"memory-source-pill",onClick:()=>a("obsidian"),children:[e.jsx(we,{size:14}),e.jsx("span",{children:"Obsidian Vault"}),e.jsxs("span",{className: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(os,{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(ve,{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(ns,{icon:e.jsx(Ie,{size:16}),label:"LightRAG",value:c.running?`running · ${c.queryCountLast24h} q/24h`:"stopped",sub:c.running?`${c.indexedApprox} indexed chunks`:"start from the LightRAG panel",onClick:()=>a("lightrag")}),e.jsx(ns,{icon:e.jsx(we,{size:16}),label:"Obsidian",value:`${u.noteCount} notes`,sub:u.folderCount>0?`${u.folderCount} folders`:"no folders yet",onClick:()=>a("obsidian")}),e.jsx(ns,{icon:e.jsx(os,{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(ns,{icon:e.jsx(la,{size:16}),label:"Storage",value:Fl(m.total),sub:m.breakdown.length>0?`${m.breakdown.length} dirs tracked`:"no memory data on disk"}),e.jsx(ns,{icon:e.jsx(Fe,{size:16}),label:"Last reindex",value:c.lastReindexAt?cs(c.lastReindexAt):"never",sub:"lightrag ingest",onClick:()=>a("lightrag")}),e.jsx(ns,{icon:e.jsx(ws,{size:16}),label:"Health",value:`${x.score}/100`,sub:x.status,onClick:()=>a("config")})]}),x.checks.length>0&&e.jsxs(K,{children:[e.jsx(Z,{children:"Health checks"}),e.jsx(te,{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(We,{size:14,style:{color:"var(--success)"}}):g.name.includes("secrets")||g.name.includes("schema")?e.jsx(Ne,{size:14,style:{color:"var(--warning)"}}):e.jsx(Xe,{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 ns({icon:s,label:t,value:a,sub:i,onClick:n}){const l=n?"button":"div";return e.jsxs(l,{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 Fl(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 Ol({refreshKey:s}){const t=le(),[a,i]=r.useState(null),[n,l]=r.useState(null),[d,o]=r.useState([]),[p,x]=r.useState(!0),[u,c]=r.useState(null),[m,h]=r.useState(""),[g,j]=r.useState(null),b=async()=>{x(!0);try{const[f,F,T]=await Promise.all([S.get("/memory/lightrag/stats").catch(()=>null),S.get("/memory/config").then(v=>(v==null?void 0:v.lightrag)||null).catch(()=>null),S.get("/memory/lightrag/log").catch(()=>({lines:[]}))]);i(f),l(F),o((T==null?void 0:T.lines)||[])}catch(f){t.error(`LightRAG status failed: ${f.message}`)}finally{x(!1)}};r.useEffect(()=>{b()},[s]);const C=async(f,F,T)=>{c(f);try{await F(),t.success(T),await b()}catch(v){t.error(`${f} failed: ${v.message}`)}finally{c(null)}},k=()=>C("start",()=>S.post("/memory/lightrag/start",{}),"LightRAG starting…"),N=()=>C("stop",()=>S.post("/memory/lightrag/stop",{}),"LightRAG stopping…"),E=async()=>{c("restart");try{await S.post("/memory/lightrag/stop",{}).catch(()=>{}),await new Promise(f=>setTimeout(f,600)),await S.post("/memory/lightrag/start",{}),t.success("LightRAG restarted."),await b()}catch(f){t.error(`Restart failed: ${f.message}`)}finally{c(null)}},$=()=>C("reindex",()=>S.post("/memory/lightrag/reindex",{}),"Reindex complete."),z=()=>C("rebuild",()=>S.post("/memory/lightrag/rebuild-graph",{}),"Graph rebuilt."),I=async()=>{var f,F,T;if(m.trim()){c("query");try{const v=await S.get(`/memory/query?q=${encodeURIComponent(m)}&topK=8`),w=(f=v==null?void 0:v.semantic)!=null&&f.response?typeof v.semantic.response=="string"?v.semantic.response:JSON.stringify(v.semantic.response):((F=v==null?void 0:v.semantic)==null?void 0:F.error)||"No response";j({ok:!!((T=v==null?void 0:v.semantic)!=null&&T.ok),text:w})}catch(v){j({ok:!1,text:v.message})}finally{c(null)}}};return p&&!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(K,{variant:"elevated",children:[e.jsxs(Z,{children:[e.jsx(Ie,{size:14}),"LightRAG",e.jsx("span",{className:Y("memory-source-pill-status",a.running?"on":"off"),children:a.running?"running":"stopped"})]}),e.jsx(te,{children:a.running?e.jsxs(e.Fragment,{children:["PID ",e.jsx("code",{children:a.pid})," · ",a.host,":",a.port]}):e.jsx(e.Fragment,{children:"Server is not running. Start it from the controls below."})}),e.jsxs("div",{className:"memory-action-row",children:[e.jsxs(A,{variant:"primary",size:"sm",onClick:k,disabled:!!u||a.running,children:[u==="start"?e.jsx(ue,{size:12,className:"memory-spin"}):e.jsx(ms,{size:12}),"Start"]}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:N,disabled:!!u||!a.running,children:[u==="stop"?e.jsx(ue,{size:12,className:"memory-spin"}):e.jsx($n,{size:12}),"Stop"]}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:E,disabled:!!u,children:[u==="restart"?e.jsx(ue,{size:12,className:"memory-spin"}):e.jsx(vt,{size:12}),"Restart"]}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:$,disabled:!!u,children:[u==="reindex"?e.jsx(ue,{size:12,className:"memory-spin"}):e.jsx(oe,{size:12}),"Reindex all"]}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:z,disabled:!!u,title:"Wipe working dir + reindex from scratch",children:[u==="rebuild"?e.jsx(ue,{size:12,className:"memory-spin"}):e.jsx(bt,{size:12}),"Rebuild graph"]})]})]}),e.jsxs("div",{className:"memory-stat-grid",children:[e.jsx(us,{icon:e.jsx(la,{size:14}),label:"Indexed chunks (approx)",value:String(a.indexedApprox)}),e.jsx(us,{icon:e.jsx(Bl,{n:a.noteCount}),label:"Notes in vault",value:String(a.noteCount)}),e.jsx(us,{icon:e.jsx(yt,{size:14}),label:"Queries last 24h",value:String(a.queryCountLast24h)}),e.jsx(us,{icon:e.jsx(Fe,{size:14}),label:"Avg response",value:a.avgResponseMs!==null?`${a.avgResponseMs} ms`:"—"}),e.jsx(us,{icon:a.lastReindexOk?e.jsx(We,{size:14}):a.lastReindexOk===!1?e.jsx(Xe,{size:14}):e.jsx(oe,{size:14}),label:"Last reindex",value:a.lastReindexAt?cs(a.lastReindexAt):"never",sub:a.lastReindexInserted!==null?`${a.lastReindexInserted} inserted${a.lastReindexFailed?`, ${a.lastReindexFailed} failed`:""}`:void 0})]}),e.jsxs(K,{children:[e.jsxs(Z,{children:[e.jsx(ve,{size:14})," Quick search"]}),e.jsx(te,{children:"Send a natural-language query to the LightRAG index."}),e.jsxs("div",{className:"memory-search-row",children:[e.jsx("label",{htmlFor:"lightrag-query",className:"sr-only",children:"Search LightRAG"}),e.jsx("input",{id:"lightrag-query",type:"text",className:"input",placeholder:"e.g. how does the memory service write notes?",value:m,onChange:f=>h(f.target.value),onKeyDown:f=>{f.key==="Enter"&&I()},disabled:u==="query","aria-label":"Search LightRAG"}),e.jsxs(A,{variant:"primary",onClick:I,disabled:u==="query"||!m.trim(),children:[u==="query"?e.jsx(ue,{size:12,className:"memory-spin"}):e.jsx(ve,{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(K,{children:[e.jsx(Z,{children:"Configuration"}),e.jsxs(te,{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})]})]}),d.length>0&&e.jsxs(K,{children:[e.jsxs(Z,{children:[e.jsx(oe,{size:14})," Server log (tail)"]}),e.jsxs(te,{children:["Last ",d.length," lines from ",e.jsx("code",{children:"lightrag.log"})]}),e.jsx("pre",{className:"memory-log-tail mono text-xs",children:d.join(`
12
- `)})]})]}):e.jsx("div",{className:"muted",children:"No LightRAG data available."})}function us({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 Bl({n:s}){return e.jsxs("span",{style:{position:"relative",display:"inline-block"},children:[e.jsx(ve,{size:14}),e.jsx("span",{className:"memory-mini-badge",children:s})]})}function Ul({refreshKey:s}){const t=le(),a=Te(),[i,n]=r.useState([]),[l,d]=r.useState(null),[o,p]=r.useState(!0),[x,u]=r.useState(""),[c,m]=r.useState(null),[h,g]=r.useState(!1),[j,b]=r.useState(null),[C,k]=r.useState([]),N=async()=>{var T;p(!0);try{const[v,w]=await Promise.all([S.get("/memory/notes").catch(()=>({notes:[]})),S.get("/memory/obsidian/tree").catch(()=>({tree:null}))]);n(v.notes||[]),d(w.tree),j&&!((T=v.notes)!=null&&T.find(P=>P.relPath===j))&&(b(null),k([]))}catch(v){t.error(`Vault load failed: ${v.message}`)}finally{p(!1)}};r.useEffect(()=>{N()},[s]),r.useEffect(()=>{if(!x.trim()){m(null);return}g(!0);const T=setTimeout(async()=>{try{const v=await S.get(`/memory/search?q=${encodeURIComponent(x)}&limit=50`),w=new Set((v.results||[]).map(P=>P.relPath));m(i.filter(P=>w.has(P.relPath)))}catch(v){t.error(`Search failed: ${v.message}`)}finally{g(!1)}},240);return()=>clearTimeout(T)},[x,i,t]);const E=async T=>{b(T);try{const v=await S.get(`/memory/obsidian/backlinks?note=${encodeURIComponent(T)}`);k(v.backlinks||[])}catch{k([])}},$=()=>{a.open({title:"New note",width:720,children:e.jsx(qt,{mode:"create",onSave:async(T,v,w)=>{try{await S.post("/memory/notes",{path:T,frontmatter:v,body:w}),t.success(`Created ${T}.`),a.close(),await N(),E(T)}catch(P){t.error(`Create failed: ${P.message}`)}},onCancel:()=>a.close()})})},z=async T=>{try{const v=await S.get(`/memory/notes/${T.split("/").map(encodeURIComponent).join("/")}`);a.open({title:`Edit ${T}`,width:720,children:e.jsx(qt,{mode:"edit",initial:{relPath:v.relPath,frontmatter:v.frontmatter,body:v.body},onSave:async(w,P,y)=>{try{await S.put(`/memory/notes/${w.split("/").map(encodeURIComponent).join("/")}`,{frontmatter:P,body:y}),t.success(`Saved ${w}.`),a.close(),await N(),E(w)}catch(L){t.error(`Save failed: ${L.message}`)}},onCancel:()=>a.close()})})}catch(v){t.error(`Load failed: ${v.message}`)}},I=async T=>{if(confirm(`Delete ${T}? This cannot be undone.`))try{await S.del(`/memory/notes/${T.split("/").map(encodeURIComponent).join("/")}`),t.success(`Deleted ${T}.`),j===T&&b(null),await N()}catch(v){t.error(`Delete failed: ${v.message}`)}},f=r.useMemo(()=>[...i].sort((T,v)=>v.mtime-T.mtime),[i]),F=c??f;return o&&!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(K,{variant:"outlined",className:"memory-tree-card",children:[e.jsxs(Z,{children:[e.jsx(Ee,{size:14})," Folders"]}),e.jsx(te,{children:l?`${ba(l)} folder(s)`:"no vault"}),e.jsx("div",{className:"memory-tree-body",children:l?e.jsx(ya,{node:l,depth:0,onSelect:E,selected:j}):null})]}),e.jsxs("div",{className:"memory-obsidian-list-col",children:[e.jsxs("div",{className:"memory-list-toolbar",children:[e.jsxs("div",{className:"search-input",children:[e.jsx(ve,{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(ze,{size:12})})]}),e.jsxs(A,{variant:"primary",size:"sm",onClick:$,children:[e.jsx(An,{size:12})," New note"]}),e.jsx(A,{variant:"ghost",size:"sm",onClick:N,title:"Refresh",children:e.jsx(oe,{size:12})})]}),h&&e.jsx("div",{className:"muted text-sm",children:"Searching…"}),F.length===0?e.jsx(Se,{icon:e.jsx(we,{size:28}),title:"No notes",message:i.length===0?'No notes in this vault yet. Click "New note" to create one.':`No notes match "${x}".`}):e.jsx("ul",{className:"memory-note-list",children:F.map(T=>e.jsxs("li",{className:Y("memory-note-card",j===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(we,{size:12}),e.jsx("span",{children:va(T)})]}),e.jsxs("div",{className:"memory-note-card-meta",children:[e.jsx("code",{className:"muted",children:T.relPath}),e.jsxs("span",{className:"muted",children:["· ",ke(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:()=>z(T.relPath),"aria-label":`Edit ${T.relPath}`,title:"Edit",children:e.jsx(Ss,{size:12})}),e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>I(T.relPath),"aria-label":`Delete ${T.relPath}`,title:"Delete",children:e.jsx(be,{size:12})})]})]},T.relPath))})]}),e.jsx("div",{className:"memory-obsidian-detail-col",children:j?e.jsx(_l,{relPath:j,onClose:()=>b(null)}):e.jsx(Se,{icon:e.jsx(we,{size:28}),title:"Pick a note",message:"Select a note from the list to view its content, frontmatter, and backlinks."})})]})}function va(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 ya({node:s,depth:t,onSelect:a,selected:i}){const[n,l]=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(we,{size:11}),e.jsx("span",{children:s.name})]}):e.jsxs("div",{className:"memory-tree-folder",children:[e.jsxs("button",{type:"button",className:"memory-tree-node memory-tree-node-folder",style:{paddingLeft:6+t*12},onClick:()=>l(d=>!d),children:[n?e.jsx(Pe,{size:11}):e.jsx(Ve,{size:11}),e.jsx(Ee,{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((d,o)=>e.jsx(ya,{node:d,depth:t+1,onSelect:a,selected:i},`${d.path}-${o}`))})]})}function ba(s){return s.type==="note"?0:1+(s.children||[]).reduce((t,a)=>t+ba(a),0)}function _l({relPath:s,onClose:t}){var u,c;const[a,i]=r.useState(null),[n,l]=r.useState([]),[d,o]=r.useState(!0);if(r.useEffect(()=>{let m=!1;return o(!0),(async()=>{try{const[h,g]=await Promise.all([S.get(`/memory/notes/${s.split("/").map(encodeURIComponent).join("/")}`),S.get(`/memory/obsidian/backlinks?note=${encodeURIComponent(s)}`)]);if(m)return;i(h),l(g.backlinks||[])}catch{m||i(null)}finally{m||o(!1)}})(),()=>{m=!0}},[s]),d)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 p=Array.isArray((u=a.frontmatter)==null?void 0:u.tags)?a.frontmatter.tags:[],x=Array.isArray((c=a.frontmatter)==null?void 0:c.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:va(a)}),e.jsx("button",{type:"button",className:"icon-btn",onClick:t,"aria-label":"Close",children:e.jsx(ze,{size:12})})]}),e.jsxs("div",{className:"memory-note-detail-meta",children:[e.jsx("code",{children:s}),e.jsxs("span",{className:"muted",children:["· modified ",cs(a.mtime)]})]}),p.length>0&&e.jsx("div",{className:"memory-tag-row",children:p.map((m,h)=>e.jsx("span",{className:"memory-tag",children:String(m)},h))}),e.jsx("pre",{className:"memory-note-body mono text-sm",children:a.body}),n.length>0&&e.jsxs("div",{className:"memory-backlinks",children:[e.jsx("h4",{children:"Backlinks"}),e.jsx("ul",{children:n.map(m=>e.jsxs("li",{children:[e.jsx("code",{children:m.fromRelPath}),e.jsx("p",{className:"muted text-sm",children:m.snippet})]},m.fromRelPath))})]}),x.length>0&&e.jsxs("div",{className:"memory-backlinks",children:[e.jsx("h4",{children:"Forward links"}),e.jsx("ul",{children:x.map((m,h)=>e.jsx("li",{children:e.jsx("code",{children:String(m)})},h))})]})]})}function qt({mode:s,initial:t,onSave:a,onCancel:i}){const[n,l]=r.useState((t==null?void 0:t.relPath)||"untitled.md"),[d,o]=r.useState(t!=null&&t.frontmatter?Wl(t.frontmatter):`title: ""
13
- tags: []
14
- `),[p,x]=r.useState((t==null?void 0:t.body)||""),[u,c]=r.useState(!1),m=le(),h=async()=>{if(!n.endsWith(".md")){m.error("Path must end in .md");return}let g;try{g=Hl(d)||{}}catch(j){m.error(`Frontmatter parse failed: ${j.message}`);return}c(!0);try{await a(n,g,p)}finally{c(!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=>l(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:d,onChange:g=>o(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:p,onChange:g=>x(g.target.value),"aria-label":"Body markdown"}),e.jsxs("div",{className:"modal-footer-actions",style:{marginTop:12},children:[e.jsx(A,{variant:"ghost",onClick:i,disabled:u,children:"Cancel"}),e.jsxs(A,{variant:"primary",onClick:h,disabled:u,children:[u&&e.jsx(ue,{size:12,className:"memory-spin"}),s==="create"?"Create":"Save"]})]})]})}function Wl(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(` - ${nt(n)}`)}else if(typeof i=="object"){t.push(`${a}:`);for(const[n,l]of Object.entries(i))t.push(` ${n}: ${nt(l)}`)}else t.push(`${a}: ${nt(i)}`);return t.join(`
15
- `)}function nt(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 Hl(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 l=n.match(/^([A-Za-z_][\w-]*):\s*(.*)$/);if(!l){i++;continue}const[,d,o]=l;if(o===""){const p={},x=[];let u=!1,c=!1;for(;i+1<a.length;){const m=a[i+1];if(!m.startsWith(" "))break;if(m.startsWith(" - "))u=!0,x.push(it(m.slice(4))),i++;else{c=!0;const h=m.match(/^ ([A-Za-z_][\w-]*):\s*(.*)$/);h&&(p[h[1]]=it(h[2])),i++}}t[d]=u&&!c?x:c?p:{}}else t[d]=it(o);i++}return t}function it(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 ql({refreshKey:s}){var N,E,$,z;const t=le(),[a,i]=r.useState(null),[n,l]=r.useState(null),[d,o]=r.useState(!0),[p,x]=r.useState(null),[u,c]=r.useState(null),m=async()=>{var I;o(!0);try{const[f,F,T]=await Promise.all([S.get("/memory/git/status").catch(()=>null),S.get("/memory/git/diff").catch(()=>null),S.get("/memory/config/global").catch(()=>null)]);i(f),l(F),c(((I=T==null?void 0:T.config)==null?void 0:I.git)||null)}catch(f){t.error(`Git status failed: ${f.message}`)}finally{o(!1)}};r.useEffect(()=>{m()},[s]);const h=async(I,f,F)=>{x(I);try{await f(),t.success(F),await m()}catch(T){t.error(`${I} failed: ${T.message}`)}finally{x(null)}},g=()=>h("pull",()=>S.post("/memory/git/pull",{}),"Pull complete."),j=()=>h("push",()=>S.post("/memory/git/push",{}),"Push complete."),b=()=>{const I=prompt("Commit message:",`[memory-sync] ${new Date().toISOString().slice(0,10)} vault sync`);I&&h("commit",()=>S.post("/memory/git/commit",{message:I}),"Committed.")},C=()=>h("fetch",()=>S.post("/memory/git/sync",{push:!1}),"Fetch complete.");if(d&&!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(K,{variant:"elevated",children:[e.jsxs(Z,{children:[e.jsx(os,{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(te,{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(xs,{ok:a.clean??!1,label:"Working tree"}),e.jsx(xs,{ok:(a.ahead??0)===0,label:`Ahead: ${a.ahead??0}`}),e.jsx(xs,{ok:(a.behind??0)===0,label:`Behind: ${a.behind??0}`}),e.jsx(xs,{ok:(((N=a.modified)==null?void 0:N.length)??0)===0,label:`Modified: ${((E=a.modified)==null?void 0:E.length)??0}`}),e.jsx(xs,{ok:((($=a.untracked)==null?void 0:$.length)??0)===0,label:`Untracked: ${((z=a.untracked)==null?void 0:z.length)??0}`})]}),e.jsxs("div",{className:"memory-action-row",children:[e.jsxs(A,{variant:"secondary",size:"sm",onClick:g,disabled:!!p||k,children:[p==="pull"?e.jsx(ue,{size:12,className:"memory-spin"}):e.jsx(Zt,{size:12}),"Pull"]}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:j,disabled:!!p||k,children:[p==="push"?e.jsx(ue,{size:12,className:"memory-spin"}):e.jsx(kt,{size:12}),"Push"]}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:b,disabled:!!p||k,children:[p==="commit"?e.jsx(ue,{size:12,className:"memory-spin"}):e.jsx(Mn,{size:12}),"Commit"]}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:C,disabled:!!p||k,children:[p==="fetch"?e.jsx(ue,{size:12,className:"memory-spin"}):e.jsx(Ln,{size:12}),"Fetch + sync"]}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:m,disabled:!!p,children:[e.jsx(oe,{size:12})," Refresh"]})]})]}),u&&e.jsxs(K,{children:[e.jsxs(Z,{children:[e.jsx(In,{size:14})," Repository"]}),e.jsxs(te,{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(K,{children:[e.jsxs(Z,{children:[e.jsx(En,{size:14})," Working-tree diff"]}),e.jsx(te,{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(I=>e.jsx("li",{children:e.jsx("code",{children:I})},I))}),n&&n.lines.length>1&&e.jsx("pre",{className:"memory-log-tail mono text-xs",children:n.lines.slice(0,400).join(`
16
- `)})]})]})}function xs({ok:s,label:t}){return e.jsxs("span",{className:Y("memory-git-status-pill",s?"ok":"warn"),children:[s?e.jsx(We,{size:11}):e.jsx(ue,{size:11,className:"memory-spin"}),t]})}function Vl({refreshKey:s}){const t=le(),[a,i]=r.useState(""),[n,l]=r.useState({lightrag:!0,obsidian:!0}),[d,o]=r.useState(null),[p,x]=r.useState(!1),[u,c]=r.useState(""),m=async g=>{if(g.trim()){x(!0),c(g);try{const j=[...n.lightrag?["lightrag"]:[],...n.obsidian?["obsidian"]:[]],b=await S.post("/memory/semantic-search",{query:g,limit:20,sources:j});o(b.results||[])}catch(j){t.error(`Search failed: ${j.message}`),o([])}finally{x(!1)}}};r.useEffect(()=>{u&&m(u)},[n]),r.useEffect(()=>{u&&m(u)},[s]);const h=r.useMemo(()=>{const g=(d||[]).filter(b=>b.source==="obsidian"),j=(d||[]).filter(b=>b.source==="lightrag");return{obs:g,lr:j}},[d]);return e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(K,{variant:"elevated",children:[e.jsxs(Z,{children:[e.jsx(ve,{size:14})," Semantic search"]}),e.jsx(te,{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:p,"aria-label":"Semantic search query"}),e.jsxs(A,{variant:"primary",onClick:()=>m(a),disabled:p||!a.trim(),children:[p?e.jsx(ue,{size:12,className:"memory-spin"}):e.jsx(ve,{size:12}),"Search"]})]}),e.jsxs("div",{className:"memory-source-toggle-row",children:[e.jsx(Vt,{active:n.obsidian,onToggle:()=>l(g=>({...g,obsidian:!g.obsidian})),label:"Obsidian",icon:e.jsx(we,{size:11})}),e.jsx(Vt,{active:n.lightrag,onToggle:()=>l(g=>({...g,lightrag:!g.lightrag})),label:"LightRAG",icon:e.jsx(Ie,{size:11})}),a&&e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>{i(""),o(null),c("")},"aria-label":"Clear",children:e.jsx(ze,{size:12})})]})]}),p&&e.jsx("div",{className:"view-loading",children:e.jsx(me,{size:"md"})}),!p&&d&&d.length===0&&e.jsx(Se,{icon:e.jsx(ve,{size:28}),title:"No matches",message:`Nothing in scope matched "${u}".`}),h.obs.length>0&&e.jsxs(K,{children:[e.jsxs(Z,{children:[e.jsx(we,{size:14})," Obsidian (",h.obs.length,")"]}),e.jsx("ul",{className:"memory-search-result-list",children:h.obs.map((g,j)=>e.jsxs("li",{className:"memory-search-result",children:[e.jsxs("div",{className:"memory-search-result-head",children:[e.jsx("code",{children:g.relPath}),e.jsxs("span",{className:"muted text-xs",children:["score ",g.score.toFixed(1)]})]}),e.jsx("p",{className:"muted text-sm",children:g.snippet})]},`obs-${j}`))})]}),h.lr.length>0&&e.jsxs(K,{children:[e.jsxs(Z,{children:[e.jsx(Ie,{size:14})," LightRAG (",h.lr.length,")"]}),e.jsx("div",{className:"memory-search-result-list",children:h.lr.map((g,j)=>e.jsxs("div",{className:"memory-search-result",children:[e.jsxs("div",{className:"memory-search-result-head",children:[e.jsxs("span",{className:"memory-source-pill",children:[e.jsx(Ie,{size:11})," LightRAG"]}),g.error&&e.jsxs("span",{className:"muted text-xs",children:["error: ",g.error]})]}),e.jsx("p",{className:"text-sm",children:g.snippet})]},`lr-${j}`))})]})]})}function Vt({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 Kl({refreshKey:s}){var b,C,k,N,E,$,z,I,f,F,T,v;const t=le(),[a,i]=r.useState(null),[n,l]=r.useState(!0),[d,o]=r.useState(!1),[p,x]=r.useState(null),[u,c]=r.useState(!1),m=async()=>{l(!0);try{const w=await S.get("/memory/config/global");i(w.config)}catch(w){t.error(`Config load failed: ${w.message}`)}finally{l(!1)}};r.useEffect(()=>{m()},[s]);const h=(w,P,y)=>{i(L=>L&&{...L,[w]:{...L[w]||{},[P]:y}})},g=async()=>{if(a){o(!0);try{await S.put("/memory/config/global",a),t.success("Config saved.")}catch(w){t.error(`Save failed: ${w.message}`)}finally{o(!1)}}},j=async()=>{c(!0);try{const w=await S.post("/memory/test-git",{});x(w.checks)}catch(w){t.error(`Test failed: ${w.message}`)}finally{c(!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(K,{children:[e.jsxs(Z,{children:[e.jsx(Ie,{size:14})," LightRAG"]}),e.jsxs(te,{children:["URL + model overrides. Server-side defaults from ",e.jsx("code",{children:"opencode Zen free tier"}),"."]}),e.jsxs("div",{className:"memory-config-form",children:[e.jsx(Be,{label:"Enabled",inline:!0,children:e.jsxs("label",{className:"memory-switch",children:[e.jsx("input",{type:"checkbox",checked:!!((b=a.lightrag)!=null&&b.enabled),onChange:w=>h("lightrag","enabled",w.target.checked)}),e.jsx("span",{children:(C=a.lightrag)!=null&&C.enabled?"on":"off"})]})}),e.jsx(Be,{label:"URL",children:e.jsx("input",{type:"text",className:"input mono",value:((k=a.lightrag)==null?void 0:k.url)||"",onChange:w=>h("lightrag","url",w.target.value),placeholder:"http://127.0.0.1:9621"})}),e.jsx(Be,{label:"LLM model",children:e.jsx("input",{type:"text",className:"input mono",value:((N=a.lightrag)==null?void 0:N.llm)||"",onChange:w=>h("lightrag","llm",w.target.value),placeholder:"opencode/gpt-5-nano"})}),e.jsx(Be,{label:"Embedding",children:e.jsx("input",{type:"text",className:"input mono",value:((E=a.lightrag)==null?void 0:E.embedding)||"",onChange:w=>h("lightrag","embedding",w.target.value),placeholder:"opencode/text-embedding-3-small"})})]})]}),e.jsxs(K,{children:[e.jsxs(Z,{children:[e.jsx(we,{size:14})," Obsidian vault"]}),e.jsx(te,{children:"Path + sync cadence for the markdown vault."}),e.jsxs("div",{className:"memory-config-form",children:[e.jsx(Be,{label:"Vault path",children:e.jsx("input",{type:"text",className:"input mono",value:(($=a.obsidian)==null?void 0:$.vaultPath)||"",onChange:w=>h("obsidian","vaultPath",w.target.value),placeholder:"/home/me/vault"})}),e.jsx(Be,{label:"Sync interval (seconds)",children:e.jsx("input",{type:"number",min:0,max:2592e3,className:"input mono",value:((z=a.obsidian)==null?void 0:z.syncInterval)??300,onChange:w=>h("obsidian","syncInterval",Number(w.target.value))})})]})]}),e.jsxs(K,{children:[e.jsxs(Z,{children:[e.jsx(os,{size:14})," Git sync"]}),e.jsx(te,{children:"Repo path, remote, branch, and auto-sync toggle."}),e.jsxs("div",{className:"memory-config-form",children:[e.jsx(Be,{label:"Repo path",children:e.jsx("input",{type:"text",className:"input mono",value:((I=a.git)==null?void 0:I.repoPath)||"",onChange:w=>h("git","repoPath",w.target.value),placeholder:"/path/to/repo"})}),e.jsx(Be,{label:"Remote URL",children:e.jsx("input",{type:"text",className:"input mono",value:((f=a.git)==null?void 0:f.remoteUrl)||"",onChange:w=>h("git","remoteUrl",w.target.value),placeholder:"git@github.com:org/repo.git"})}),e.jsx(Be,{label:"Branch",children:e.jsx("input",{type:"text",className:"input mono",value:((F=a.git)==null?void 0:F.branch)||"main",onChange:w=>h("git","branch",w.target.value),placeholder:"main"})}),e.jsx(Be,{label:"Auto-sync",inline:!0,children:e.jsxs("label",{className:"memory-switch",children:[e.jsx("input",{type:"checkbox",checked:!!((T=a.git)!=null&&T.autoSync),onChange:w=>h("git","autoSync",w.target.checked)}),e.jsx("span",{children:(v=a.git)!=null&&v.autoSync?"on":"off"})]})})]})]}),e.jsxs(K,{children:[e.jsxs(Z,{children:[e.jsx(Fe,{size:14})," CCR (Compress-Cache-Retrieve)"]}),e.jsx(te,{children:"Reversible compression for very long conversations. Enabled automatically when the Headroom mod is installed."}),e.jsx("div",{className:"muted text-sm",children:"See Settings → Headroom for CCR configuration. This panel will surface retention + compression-ratio controls when the mod is active."})]}),e.jsxs(K,{children:[e.jsxs(Z,{children:[e.jsx(ct,{size:14})," Connection tests"]}),e.jsx(te,{children:"Verify the configured git repo, remote, and path."}),e.jsxs("div",{className:"memory-action-row",children:[e.jsxs(A,{variant:"secondary",onClick:j,disabled:u,children:[u?e.jsx(ue,{size:12,className:"memory-spin"}):e.jsx(ct,{size:12}),"Test git connection"]}),e.jsxs(A,{variant:"primary",onClick:g,disabled:d,children:[d?e.jsx(ue,{size:12,className:"memory-spin"}):e.jsx(ks,{size:12}),"Save config"]})]}),p&&p.length>0&&e.jsx("ul",{className:"memory-check-list",style:{marginTop:12},children:p.map((w,P)=>e.jsxs("li",{className:"memory-check-row",children:[e.jsx("span",{className:"memory-check-icon",children:e.jsx("span",{className:Y("memory-pill",w.pass?"memory-pill-ok":"memory-pill-warn"),children:w.pass?"OK":"FAIL"})}),e.jsx("span",{className:"memory-check-name",children:w.name}),e.jsx("span",{className:"memory-check-detail muted",children:w.detail})]},P))})]})]}):e.jsx("div",{className:"muted",children:"No config available."})}function Be({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 Ue=800,Kt=60,rt={default:"#8b5cf6",note:"#8b5cf6",entity:"#34d399",concept:"#fbbf24",root:"#f87171"};function Gl(s,t){return rt[s]||rt[t]||rt.default}function Yl(s){return 6+Math.min(s.size*2,10)}function Xl(s,t){var l,d;if(s.length===0)return[];const a=new Map;for(const o of s)a.set(o.id,new Set);for(const o of t)(l=a.get(o.source))==null||l.add(o.target),(d=a.get(o.target))==null||d.add(o.source);const i=s.map((o,p)=>{const x=p/s.length*Math.PI*2,u=Ue*.28;return{...o,x:Ue/2+u*Math.cos(x)+(Math.random()-.5)*40,y:Ue/2+u*Math.sin(x)+(Math.random()-.5)*40,vx:0,vy:0}}),n=new Map;for(const o of i)n.set(o.id,o);for(let o=0;o<Kt;o++){const p=1-o/Kt;for(let c=0;c<i.length;c++)for(let m=c+1;m<i.length;m++){const h=i[c],g=i[m],j=g.x-h.x,b=g.y-h.y,C=Math.sqrt(j*j+b*b)||1,k=400*p/(C*C),N=j/C*k,E=b/C*k;h.vx-=N,h.vy-=E,g.vx+=N,g.vy+=E}for(const c of t){const m=n.get(c.source),h=n.get(c.target);if(!m||!h)continue;const g=h.x-m.x,j=h.y-m.y,b=Math.sqrt(g*g+j*j)||1,k=(b-80)*.08*p,N=g/b*k,E=j/b*k;m.vx+=N,m.vy+=E,h.vx-=N,h.vy-=E}const x=Ue/2,u=Ue/2;for(const c of i)c.vx+=(x-c.x)*.01*p,c.vy+=(u-c.y)*.01*p;for(const c of i)c.vx*=.85,c.vy*=.85,c.x+=c.vx,c.y+=c.vy,c.x=Math.max(20,Math.min(Ue-20,c.x)),c.y=Math.max(20,Math.min(Ue-20,c.y))}return i}function Ql({data:s,onNodeClick:t,className:a}){const i=r.useRef(null),[n,l]=r.useState({x:0,y:0,scale:1}),d=r.useRef(!1),o=r.useRef({x:0,y:0,tx:0,ty:0}),p=r.useRef(null),[x,u]=r.useState(null),[c,m]=r.useState(null),h=r.useMemo(()=>Xl(s.nodes,s.edges),[s.nodes,s.edges]),g=r.useMemo(()=>{const f=new Map;for(const F of h)f.set(F.id,F);return f},[h]),j=r.useCallback(f=>{f.target.closest(".memory-graph-node")||(d.current=!0,o.current={x:f.clientX,y:f.clientY,tx:n.x,ty:n.y})},[n]),b=r.useCallback(f=>{if(!d.current)return;const F=f.clientX-o.current.x,T=f.clientY-o.current.y;l(v=>({...v,x:o.current.tx+F,y:o.current.ty+T}))},[]),C=r.useCallback(()=>{d.current=!1},[]),k=r.useCallback(f=>{f.preventDefault();const F=f.deltaY<0?1.1:.9,T=i.current;if(!T)return;const v=T.getBoundingClientRect(),w=f.clientX-v.left,P=f.clientY-v.top;l(y=>{const L=Math.max(.2,Math.min(4,y.scale*F)),B=L/y.scale;return{x:w-(w-y.x)*B,y:P-(P-y.y)*B,scale:L}})},[]),N=r.useCallback(f=>{const F=Array.from(f.touches);if(F.length===2){const[T,v]=F;p.current=Math.hypot(v.clientX-T.clientX,v.clientY-T.clientY)}else F.length===1&&(d.current=!0,o.current={x:F[0].clientX,y:F[0].clientY,tx:n.x,ty:n.y})},[n]),E=r.useCallback(f=>{const F=Array.from(f.touches);if(F.length===2&&p.current!==null){const[T,v]=F,w=Math.hypot(v.clientX-T.clientX,v.clientY-T.clientY),P=w/p.current;p.current=w,l(y=>({...y,scale:Math.max(.2,Math.min(4,y.scale*P))}))}else if(F.length===1&&d.current){const T=F[0].clientX-o.current.x,v=F[0].clientY-o.current.y;l(w=>({...w,x:o.current.tx+T,y:o.current.ty+v}))}},[]),$=r.useCallback(()=>{d.current=!1,p.current=null},[]),z=r.useCallback(f=>{u(f.id===x?null:f.id),t==null||t(f)},[x,t]),I=Math.max(.5,1/Math.log2(n.scale+1));return e.jsx("svg",{ref:i,className:Y("memory-graph-canvas",a),viewBox:`0 0 ${Ue} ${Ue}`,style:{width:"100%",height:"100%",minHeight:400,cursor:d.current?"grabbing":"grab"},onMouseDown:j,onMouseMove:b,onMouseUp:C,onMouseLeave:C,onWheel:k,onTouchStart:N,onTouchMove:E,onTouchEnd:$,children:e.jsxs("g",{transform:`translate(${n.x},${n.y}) scale(${n.scale})`,children:[s.edges.map((f,F)=>{const T=g.get(f.source),v=g.get(f.target);if(!T||!v)return null;const w=c===f.source||c===f.target||x===f.source||x===f.target;return e.jsx("line",{x1:T.x,y1:T.y,x2:v.x,y2:v.y,stroke:w?"#8b5cf6":"#2d3648",strokeWidth:w?I*2:I,strokeOpacity:w?.9:.5},`e-${F}`)}),h.map(f=>{const F=Yl(f),T=Gl(f.group,f.type),v=x===f.id,w=c===f.id;return e.jsxs("g",{className:"memory-graph-node",transform:`translate(${f.x},${f.y})`,onClick:()=>z(f),onMouseEnter:()=>m(f.id),onMouseLeave:()=>m(null),style:{cursor:"pointer"},children:[e.jsx("circle",{r:F+6,fill:"transparent"}),(v||w)&&e.jsx("circle",{r:F+4,fill:T,fillOpacity:.2}),e.jsx("circle",{r:F,fill:T,fillOpacity:v?1:.75,stroke:v?"#fff":T,strokeWidth:v?2:1}),n.scale>.5&&e.jsx("text",{y:F+12,textAnchor:"middle",fontSize:Math.max(8,Math.min(11,10/Math.sqrt(n.scale))),fill:"var(--text-dim, #b4bcd0)",style:{pointerEvents:"none",userSelect:"none"},children:f.label.length>20?f.label.slice(0,18)+"…":f.label})]},f.id)})]})})}const Jl=[{color:"#8b5cf6",label:"Note / Default"},{color:"#34d399",label:"Entity (LightRAG)"},{color:"#fbbf24",label:"Concept (LightRAG)"},{color:"#f87171",label:"Root / Ungrouped"}];function Zl({className:s}){return e.jsx("div",{className:Y("memory-graph-legend",s),children:Jl.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 eo({refreshKey:s}){const t=le(),[a,i]=r.useState({nodes:[],edges:[]}),[n,l]=r.useState(!0),[d,o]=r.useState(null),[p,x]=r.useState(""),[u,c]=r.useState(2),[m,h]=r.useState(""),[g,j]=r.useState(null),[b,C]=r.useState(null),k=r.useCallback(async()=>{var $,z;l(!0),o(null);try{const I=new URLSearchParams({limit:"200"});m&&I.set("root",m),I.set("depth",String(u));const f=await S.get(`/memory/graph?${I}`);i({nodes:f.nodes||[],edges:f.edges||[]}),j({totalNodes:f.totalNodes??(($=f.nodes)==null?void 0:$.length)??0,totalEdges:f.totalEdges??((z=f.edges)==null?void 0:z.length)??0})}catch(I){o(I.message),t.error(`Graph load failed: ${I.message}`)}finally{l(!1)}},[m,u,t]);r.useEffect(()=>{k()},[k,s]);const N=r.useCallback($=>{C(z=>(z==null?void 0:z.id)===$.id?null:$)},[]),E=p.trim()?{nodes:a.nodes.filter($=>$.label.toLowerCase().includes(p.toLowerCase())),edges:a.edges.filter($=>a.nodes.some(z=>z.id===$.source&&z.label.toLowerCase().includes(p.toLowerCase()))||a.nodes.some(z=>z.id===$.target&&z.label.toLowerCase().includes(p.toLowerCase())))}:a;return e.jsxs("div",{className:"memory-panel-content",children:[e.jsxs(K,{children:[e.jsxs(Z,{children:[e.jsx(oa,{size:14})," Memory Graph"]}),e.jsx(te,{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:p,onChange:$=>x($.target.value),style:{maxWidth:240}}),e.jsx("input",{type:"text",className:"input",placeholder:"Root note id (optional)",value:m,onChange:$=>h($.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:$=>c(parseInt($.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(oe,{size:14,className:n?"memory-spin":""})})]}),e.jsx(Zl,{})]})]}),e.jsx(K,{children:n&&!a.nodes.length?e.jsxs("div",{className:"view-loading",children:[e.jsx(me,{size:"lg"}),e.jsx("p",{children:"Loading graph…"})]}):d&&!a.nodes.length?e.jsxs("div",{className:"muted text-sm",children:["Failed to load graph: ",d]}):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(Ql,{data:E,onNodeClick:N,className:"memory-graph-canvas-svg"}),p&&e.jsxs("div",{className:"text-xs muted",style:{marginTop:4},children:["Showing ",E.nodes.length," of ",a.nodes.length," nodes"]})]})}),b&&e.jsxs(K,{children:[e.jsx(Z,{children:b.label}),e.jsx(te,{children:e.jsx("code",{children:b.id})}),e.jsxs("dl",{className:"memory-config-row",children:[e.jsx("dt",{children:"Type"}),e.jsx("dd",{children:e.jsx("code",{children:b.type})}),e.jsx("dt",{children:"Group"}),e.jsx("dd",{children:e.jsx("code",{children:b.group})}),e.jsx("dt",{children:"Size"}),e.jsx("dd",{children:b.size})]})]}),g&&e.jsx(K,{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":""]}),p&&e.jsxs("span",{className:"muted",children:["· ",E.nodes.length," shown"]})]})})]})}function so({onTextExtracted:s}){const t=le(),[a,i]=r.useState(null),[n,l]=r.useState(!1),[d,o]=r.useState(!1),p=r.useCallback(async()=>{o(!0);try{const c=await navigator.mediaDevices.getDisplayMedia({video:{mediaSource:"screen"}}),m=document.createElement("video");m.srcObject=c,await m.play();const h=document.createElement("canvas");h.width=m.videoWidth,h.height=m.videoHeight;const g=h.getContext("2d");if(!g){t.error("Failed to get canvas context");return}g.drawImage(m,0,0),c.getTracks().forEach(j=>j.stop()),m.remove(),h.toBlob(async j=>{if(!j){t.error("Failed to capture screenshot");return}const b=URL.createObjectURL(j);i(b),await x(j)},"image/png")}catch(c){c.name!=="NotAllowedError"&&t.error(`Capture failed: ${c.message}`)}finally{o(!1)}},[t]),x=r.useCallback(async c=>{l(!0);try{const m=new FileReader,h=await new Promise((j,b)=>{m.onload=()=>{const C=m.result,k=C.includes(",")?C.split(",")[1]:C;j(k)},m.onerror=()=>b(new Error("FileReader failed")),m.readAsDataURL(c)}),g=await S.post("/ocr/process",{image:h,lang:"eng"});g.ok&&(t.success("Text extracted from screenshot"),s==null||s(g.text,g.notePath))}catch(m){t.error(`OCR failed: ${m.message}`)}finally{l(!1)}},[t,s]),u=r.useCallback(()=>{i(null)},[]);return e.jsxs(K,{variant:"outlined",className:"screenshot-capture-card",children:[e.jsxs(Z,{children:[e.jsx(Ys,{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(ue,{size:12,className:"spinner"})," Extracting text…"]}),e.jsx(A,{variant:"ghost",size:"sm",onClick:u,disabled:n,children:"Dismiss"})]})]}):e.jsxs("div",{className:"screenshot-capture-empty",children:[e.jsx(Ys,{size:32,className:"muted"}),e.jsx("p",{className:"muted text-sm",children:"Capture your screen to extract text via OCR."}),e.jsxs(A,{variant:"primary",size:"sm",onClick:p,disabled:d,children:[d?e.jsx(ue,{size:12,className:"spinner"}):e.jsx(Ys,{size:12}),d?"Selecting…":"Capture Screen"]})]})})]})}function to(){const[s,t]=r.useState(null),[a,i]=r.useState(null),n=(l,d)=>{t(l),i(d)};return e.jsxs("div",{className:"screenshot-ocr-panel",children:[e.jsx(so,{onTextExtracted:n}),s!==null&&e.jsxs(K,{variant:"outlined",className:"screenshot-ocr-result-card",children:[e.jsxs(Z,{children:[e.jsx(we,{size:14})," Extracted Text"]}),a&&e.jsxs(te,{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 ao({refreshKey:s}){return e.jsx("div",{className:"memory-panel-content",children:e.jsx(K,{variant:"outlined",className:"memory-panel-card",children:e.jsx("div",{className:"memory-panel-body",children:e.jsx(to,{})})})})}function no({refreshKey:s}){const t=le(),[a,i]=r.useState(""),[n,l]=r.useState(""),[d,o]=r.useState(""),[p,x]=r.useState(!1),u=async()=>{if(!d.trim()){t.error("Content is required");return}x(!0);try{const c=await S.post("/clipboard/save",{url:a.trim()||void 0,title:n.trim()||void 0,content:d,savedAt:new Date().toISOString()});c.ok&&(t.success(`Saved to ${c.notePath}`),i(""),l(""),o(""))}catch(c){t.error(`Save failed: ${c.message}`)}finally{x(!1)}};return e.jsx("div",{className:"memory-panel-content",children:e.jsx(K,{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(ca,{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:c=>i(c.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:c=>l(c.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:d,onChange:c=>o(c.target.value)}),e.jsx("div",{className:"vault-clipboard-actions",style:{marginTop:12},children:e.jsxs(A,{variant:"primary",size:"sm",onClick:u,disabled:p||!d.trim(),children:[p&&e.jsx(ue,{size:12,className:"spinner"}),"Save to Vault"]})})]})})})})}function io({vaultPath:s,onSaved:t}){const[a,i]=r.useState(!1),[n,l]=r.useState(!1),d=r.useRef(null),o=r.useRef([]),p=async()=>{try{const c=await navigator.mediaDevices.getUserMedia({audio:!0}),m=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"audio/webm",h=new MediaRecorder(c,{mimeType:m});h.ondataavailable=g=>{g.data&&g.data.size>0&&o.current.push(g.data)},h.onstop=async()=>{const g=new Blob(o.current,{type:"audio/webm"});o.current=[],c.getTracks().forEach(j=>j.stop()),await u(g)},h.start(1e3),d.current=h,i(!0)}catch(c){console.error("[VoiceRecorder] failed to start recording:",c)}},x=()=>{const c=d.current;c&&(c.stop(),i(!1),l(!0))},u=async c=>{try{const m=new FormData;m.append("audio",c,"voice-note.webm"),m.append("vaultPath",s||"");const h=await fetch("/api/voice/upload",{method:"POST",body:m});if(!h.ok){console.error("[VoiceRecorder] upload failed:",h.status,await h.text()),l(!1);return}const{notePath:g,transcription:j}=await h.json();t==null||t(g,j)}catch(m){console.error("[VoiceRecorder] upload error:",m)}finally{l(!1)}};return e.jsxs("div",{className:"voice-recorder",children:[!a&&!n&&e.jsxs(A,{variant:"accent",size:"sm",onClick:p,"aria-label":"Start recording",children:[e.jsx(St,{size:14})," Record"]}),a&&e.jsxs(A,{variant:"danger",size:"sm",onClick:x,"aria-label":"Stop recording",children:[e.jsx(ia,{size:14})," Stop"]}),n&&e.jsxs(A,{variant:"secondary",size:"sm",disabled:!0,children:[e.jsx(ue,{size:14,className:"spinning"})," Transcribing…"]})]})}function ro({note:s,onDelete:t}){const[a,i]=r.useState(!1),[n]=r.useState(()=>{if(!s.audioPath)return null;const o=new Audio(`/api/voice/${s.id}/audio`);return o.onended=()=>i(!1),o}),l=()=>{n&&(a?(n.pause(),n.currentTime=0,i(!1)):(n.play(),i(!0)))},d=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:d}),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:l,"aria-label":a?"Pause":"Play",title:a?"Pause":"Play",children:a?e.jsx(ta,{size:13}):e.jsx(ms,{size:13})}),e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>t(s.id),"aria-label":"Delete note",title:"Delete note",children:e.jsx(be,{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 lo({vaultPath:s,refreshKey:t=0}){const[a,i]=r.useState([]),[n,l]=r.useState(""),[d,o]=r.useState(!0),p=async()=>{o(!0);try{const c=s?`?vaultPath=${encodeURIComponent(s)}`:"",h=await(await fetch(`/api/voice/list${c}`)).json();i(h.notes||[])}catch(c){console.error("[VoiceNotesPanel] failed to load notes:",c)}finally{o(!1)}};r.useEffect(()=>{p()},[s,t]);const x=async c=>{try{const m=await fetch(`/api/voice/${c}`,{method:"DELETE"});(m.ok||m.status===204)&&i(h=>h.filter(g=>g.id!==c))}catch(m){console.error("[VoiceNotesPanel] delete failed:",m)}},u=a.filter(c=>{var m;return!n||(((m=c.transcript)==null?void 0:m.toLowerCase().includes(n.toLowerCase()))??!1)});return e.jsxs(K,{children:[e.jsxs(Z,{children:[e.jsx(St,{size:14})," Voice Notes"]}),e.jsx(te,{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:c=>l(c.target.value),placeholder:"Search transcripts…","aria-label":"Search voice notes"})}),e.jsx("div",{className:"voice-recorder-row",children:e.jsx(io,{vaultPath:s,onSaved:p})}),d?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(c=>e.jsx(ro,{note:c,onDelete:x},c.id))})]})}const oo=[{id:"overview",label:"Overview",icon:Jt},{id:"lightrag",label:"LightRAG",icon:Ie},{id:"obsidian",label:"Obsidian Vault",icon:we},{id:"git",label:"Git Sync",icon:os},{id:"semantic",label:"Semantic Search",icon:ve},{id:"config",label:"Config",icon:ft},{id:"graph",label:"Memory Graph",icon:oa},{id:"webclip",label:"Web Clip",icon:ca},{id:"screenshot",label:"Screenshot OCR",icon:Dn},{id:"voice",label:"Voice Notes",icon:St}];function co(s){const t=le(),[a,i]=r.useState("overview"),[n,l]=r.useState(0),d=r.useCallback(()=>{l(x=>x+1)},[]),o=r.useCallback(async()=>{d(),t.info("Refreshing memory…",1200)},[d,t]),p=()=>{switch(a){case"overview":return e.jsx(Pl,{refreshKey:n,onRefresh:d,setActiveSubPanel:i});case"lightrag":return e.jsx(Ol,{refreshKey:n});case"obsidian":return e.jsx(Ul,{refreshKey:n});case"git":return e.jsx(ql,{refreshKey:n});case"semantic":return e.jsx(Vl,{refreshKey:n});case"config":return e.jsx(Kl,{refreshKey:n});case"graph":return e.jsx(eo,{refreshKey:n});case"webclip":return e.jsx(no,{refreshKey:n});case"screenshot":return e.jsx(ao,{refreshKey:n});case"voice":return e.jsx(lo,{refreshKey:n});default:return e.jsxs(K,{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(Ie,{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:o,"aria-label":"Refresh memory",title:"Refresh",children:e.jsx(oe,{size:14})})})]}),e.jsxs("div",{className:"memory-tab-body",children:[e.jsx("nav",{className:"memory-source-rail","aria-label":"Memory sources",children:oo.map(x=>{const u=x.icon,c=a===x.id;return e.jsxs("button",{type:"button",role:"tab","aria-selected":c,className:Y("memory-source-button",c&&"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:p()},a)]})]})}const mo=qe.memo(co),ps=[{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 ho(s,t,a,i){const n=a.has(s.id);return e.jsxs(K,{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(Ee,{size:16})," ",s.name]}),e.jsx("div",{className:"history-project-meta",children:s.path})]}),e.jsxs("div",{className:"history-project-stats",children:[e.jsxs("span",{className:"history-project-stat",children:[e.jsx("span",{className:"history-project-stat-num",children:s.tasks.done}),e.jsxs("span",{className:"muted",children:["/ ",s.tasks.total," done"]})]}),s.tasks.doing>0&&e.jsxs("span",{className:"history-project-stat",children:[e.jsx("span",{className:"history-project-stat-num",children:s.tasks.doing}),e.jsx("span",{className:"muted",children:"doing"})]}),s.tasks.blocked>0&&e.jsxs("span",{className:"history-project-stat",children:[e.jsx("span",{className:"history-project-stat-num",children:s.tasks.blocked}),e.jsx("span",{className:"muted",children:"blocked"})]}),e.jsxs("span",{className:"history-project-stat",children:[e.jsx(we,{size:11})," ",e.jsx("span",{className:"history-project-stat-num",children:s.plans}),e.jsxs("span",{className:"muted",children:[" plan",s.plans===1?"":"s"]})]}),s.lastAccessed&&e.jsx("span",{className:"history-project-stat",children:e.jsxs("span",{className:"muted",children:["last opened ",ke(s.lastAccessed)]})})]}),e.jsx("button",{type:"button",className:"icon-btn",onClick:()=>i(s.id),"aria-label":n?"Collapse":"Expand",children:n?e.jsx(Pe,{size:14}):e.jsx(Ve,{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((l,d)=>e.jsxs("div",{className:"history-timeline-row",children:[e.jsx("span",{className:"history-timeline-ts",children:new Date(l.ts).toLocaleTimeString()}),e.jsx("span",{className:"history-timeline-kind",children:l.kind||"event"}),e.jsxs("span",{className:"history-timeline-msg",title:String(l.text||l.title||""),children:[l.author?`@${l.author} `:"",String(l.text??l.title??l.name??"")]})]},d))})]},s.id)}function uo({snapshot:s}){var b,C;const t=le(),[a,i]=r.useState(null),[n,l]=r.useState(!0),[d,o]=r.useState("1d"),[p,x]=r.useState(new Set),[u,c]=r.useState(0),m=async k=>{try{const N=k?`?since=${encodeURIComponent(k)}&limit=1000`:"?limit=1000",E=await S.get(`/history${N}`);i(E),x(new Set(E.projects.filter($=>E.events.some(z=>z.projectId===$.id)).map($=>$.id)))}catch(N){t.error(`History load failed: ${N.message}`)}finally{l(!1)}};r.useEffect(()=>{l(!0);const k=ps.find(N=>N.id===d)||ps[1];if(k.ms>0){const N=new Date(Date.now()-k.ms).toISOString();m(N)}else m()},[d]),r.useEffect(()=>{const k=setInterval(()=>c(N=>N+1),3e4);return()=>clearInterval(k)},[]);const h=new Map;for(const k of(a==null?void 0:a.events)||[]){const N=k.projectId||"global";h.has(N)||h.set(N,[]),h.get(N).push(k)}const g=k=>{x(N=>{const E=new Set(N);return E.has(k)?E.delete(k):E.add(k),E})},j=()=>{if(!a)return;const k=new Blob([JSON.stringify(a,null,2)],{type:"application/json"}),N=URL.createObjectURL(k),E=document.createElement("a");E.href=N,E.download=`bizar-history-${new Date().toISOString().replace(/[:.]/g,"-")}.json`,E.click(),URL.revokeObjectURL(N),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(vs,{size:18})," History"]}),e.jsxs("p",{className:"view-subtitle",children:["Cross-project history of events, tasks, and plans.",((b=a==null?void 0:a.stats)==null?void 0:b.lastTs)&&e.jsxs(e.Fragment,{children:[" · last event ",ke(a.stats.lastTs)]})]})]}),e.jsxs("div",{className:"view-actions",children:[e.jsxs("div",{className:"tasks-toolbar-group",children:[e.jsx(Pn,{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:d,onChange:k=>o(k.target.value),title:"Time range","aria-label":"Time range",children:ps.map(k=>e.jsx("option",{value:k.id,children:k.label},k.id))})]}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:()=>{l(!0);const k=ps.find(N=>N.id===d)||ps[1];k.ms>0?m(new Date(Date.now()-k.ms).toISOString()):m()},children:[e.jsx(oe,{size:14})," Refresh"]}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:j,children:[e.jsx(Je,{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(K,{children:[e.jsxs(Z,{children:[e.jsx(Ee,{size:14})," No projects"]}),e.jsx(te,{children:"Register a project in Overview to start tracking history."})]}),a.projects.length>0&&e.jsx(xt,{items:a.projects,itemHeight:70,height:Math.min(a.projects.length*70,500),className:"history-virtual-list",renderItem:k=>ho(k,h.get(k.id)||[],p,g)}),h.has("global")&&e.jsxs(K,{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(vs,{size:16})," Global events"]}),e.jsx("div",{className:"history-project-meta",children:"Activity not tied to a specific project"})]})}),e.jsx("div",{className:"history-timeline-mini",children:(h.get("global")||[]).slice(-100).reverse().map((k,N)=>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??"")]})]},N))})]}),((C=a.stats)==null?void 0:C.counts)&&Object.keys(a.stats.counts).length>0&&e.jsxs(K,{children:[e.jsx(Z,{children:"Event counts by kind"}),e.jsxs(te,{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,N)=>N[1]-k[1]).slice(0,30).map(([k,N])=>e.jsxs("span",{className:Y("tag","tag-neutral"),style:{fontFamily:"var(--font-mono)"},children:[k,": ",N]},k))})]})]})]})}const fe={top:16,right:20,bottom:40,left:52};function xo({series:s,height:t=280,onHover:a,className:i}){const n=r.useRef(null),[l,d]=r.useState(null),{labels:o,requests:p,tokens:x}=s,u=o.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 c=600-fe.left-fe.right,m=t-fe.top-fe.bottom,h=Math.max(...p,1),g=Math.max(...x,1),j=Math.max(4,Math.min(24,Math.floor(c/u)-4)),b=(c-j*u)/(u+1);function C(w){return fe.left+b+w*(j+b)}function k(w){return w/h*m*.75}function N(w){return fe.top+m-w/g*m*.75}const E=x.map((w,P)=>`${C(P)+j/2},${N(w)}`).join(" "),$=[0,.25,.5,.75,1].map(w=>({y:fe.top+m-w*m*.75,label:w===0?"0":`${Math.round(h*w).toLocaleString()}`})),z=[0,.25,.5,.75,1].map(w=>({y:fe.top+m-w*m*.75,label:w===0?"0":`${Math.round(g*w/1e3)}k`})),I=Math.max(1,Math.floor(u/7)),f=o.map((w,P)=>({i:P,l:w,x:C(P)+j/2})).filter((w,P)=>P%I===0),F=r.useCallback(w=>{if(!n.current)return;const P=n.current.getBoundingClientRect(),y=(w.clientX-P.left)*(600/P.width),L=(w.clientY-P.top)*(t/P.height),B=y-fe.left,R=Math.round((B-b/2)/(j+b)),H=Math.max(0,Math.min(u-1,R));d({index:H,x:w.clientX-P.left,y:w.clientY-P.top}),a==null||a(H,y,L)},[u,j,b,a,t]),T=r.useCallback(()=>{d(null),a==null||a(null,0,0)},[a]),v=l;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:F,onMouseLeave:T,children:[$.map((w,P)=>e.jsx("line",{x1:fe.left,y1:w.y,x2:600-fe.right,y2:w.y,stroke:"var(--border)",strokeWidth:1,strokeDasharray:"4,3",opacity:.5},`grid-${P}`)),$.map((w,P)=>e.jsx("text",{x:fe.left-6,y:w.y+4,textAnchor:"end",fontSize:10,fill:"var(--text-muted)",fontFamily:"var(--font-mono, ui-monospace, monospace)",children:w.label},`ly-${P}`)),z.map((w,P)=>e.jsx("text",{x:600-fe.right+6,y:w.y+4,textAnchor:"start",fontSize:10,fill:"var(--text-muted)",fontFamily:"var(--font-mono, ui-monospace, monospace)",children:w.label},`ry-${P}`)),p.map((w,P)=>{const y=k(w),L=C(P),B=fe.top+m-y;return e.jsx("rect",{x:L,y:B,width:j,height:y,rx:2,fill:((v==null?void 0:v.index)===P,"var(--accent)"),opacity:(v==null?void 0:v.index)===P?1:.75,style:{transition:"opacity 120ms ease"}},`bar-${P}`)}),e.jsx("polyline",{points:E,fill:"none",stroke:"var(--warning, #d29922)",strokeWidth:2,strokeLinejoin:"round",strokeLinecap:"round",opacity:.9}),x.map((w,P)=>e.jsx("circle",{cx:C(P)+j/2,cy:N(w),r:(v==null?void 0:v.index)===P?5:3,fill:"var(--warning, #d29922)",opacity:(v==null?void 0:v.index)===P?1:.7,style:{transition:"r 120ms ease"}},`dot-${P}`)),f.map(({i:w,l:P,x:y})=>e.jsx("text",{x:y,y:fe.top+m+18,textAnchor:"middle",fontSize:10,fill:"var(--text-muted)",fontFamily:"var(--font-mono, ui-monospace, monospace)",children:P},`xl-${w}`)),e.jsx("line",{x1:fe.left,y1:fe.top+m,x2:600-fe.right,y2:fe.top+m,stroke:"var(--border)",strokeWidth:1})]}),v!==null&&e.jsxs("div",{className:"usage-chart-tooltip",style:{left:Math.min(v.x+12,460),top:v.y-60},children:[e.jsx("div",{className:"usage-tooltip-date",children:o[v.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:p[v.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[v.index].toLocaleString()})]})]})]})}function Ge({label:s,col:t,sortKey:a,sortDir:i,onSort:n}){const l=a===t;return e.jsxs("th",{className:Y("usage-sort-header",l&&"is-active"),onClick:()=>n(t),"aria-sort":l?i==="asc"?"ascending":"descending":"none",children:[e.jsx("span",{children:s}),e.jsx("span",{className:"usage-sort-icon",children:l?i==="asc"?" ↑":" ↓":" ↕"})]})}function po({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(Ge,{label:"Model",col:"modelId",sortKey:t,sortDir:a,onSort:i}),e.jsx(Ge,{label:"Requests",col:"requests",sortKey:t,sortDir:a,onSort:i}),e.jsx(Ge,{label:"Prompt Tok",col:"promptTokens",sortKey:t,sortDir:a,onSort:i}),e.jsx(Ge,{label:"Compl Tok",col:"completionTokens",sortKey:t,sortDir:a,onSort:i}),e.jsx(Ge,{label:"Total Tok",col:"totalTokens",sortKey:t,sortDir:a,onSort:i}),e.jsx(Ge,{label:"Avg Latency",col:"avgLatencyMs",sortKey:t,sortDir:a,onSort:i}),e.jsx(Ge,{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 go({activeTab:s,setActiveTab:t}){const[a,i]=r.useState("quota"),n=le();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(jt,{size:13})," Token Plan"]}),e.jsxs("button",{className:Y("minimax-sub-tab",a==="analytics"&&"is-active"),onClick:()=>i("analytics"),children:[e.jsx(da,{size:13})," Usage Analytics"]})]}),a==="quota"?e.jsx(jo,{activeTab:s,setActiveTab:t}):e.jsx(fo,{toast:n})]})}function jo({activeTab:s,setActiveTab:t}){var ee;const a=le(),[i,n]=r.useState(null),[l,d]=r.useState(null),[o,p]=r.useState(null),[x,u]=r.useState(!0),[c,m]=r.useState(!1),[h,g]=r.useState(null),[j,b]=r.useState(null),[C,k]=r.useState(!1),[N,E]=r.useState(0),[$,z]=r.useState(!1),[I,f]=r.useState(null),[F,T]=r.useState(""),[v,w]=r.useState(!1),[P,y]=r.useState(!1),L=r.useCallback(async()=>{u(!0),g(null);try{const[Q,ie,je]=await Promise.all([S.get("/minimax/status"),S.get("/minimax/remains"),S.get("/minimax/onboarding")]);n(Q),d(ie),p(je),Q.configured&&E(4)}catch(Q){g(Q.message||"Failed to load MiniMax data")}finally{u(!1)}},[]);r.useEffect(()=>{L()},[L]);const B=r.useCallback(async()=>{try{await S.post("/minimax/onboarding",{dismissedAt:Date.now()}),p(Q=>Q&&{...Q,dismissedAt:Date.now()})}catch{}},[]),R=r.useCallback(async()=>{if(!F.trim()){a.error("Paste a Subscription Key first.");return}z(!0),f(null);try{const Q=await S.post("/minimax/test",{prompt:"Reply with a single word: pong",model:"MiniMax-M3",maxTokens:16});if(f(Q),Q.ok){E(3),a.success("Key works. Saving…");try{await S.post("/minimax/onboarding/save-key",{key:F.trim(),groupId:"default"}),ae(),a.success("Subscription Key saved.")}catch(ie){a.error(`Save failed: ${ie.message}`)}L()}else a.error(`Verification failed: ${Q.message??Q.error??"unknown"}`)}catch(Q){a.error(`Test request failed: ${Q.message}`)}finally{z(!1)}},[F,a,L]),H=r.useCallback(async()=>{if(!F.trim()){a.error("Paste a Subscription Key first.");return}y(!0);try{const Q=await S.post("/minimax/onboarding/save-key",{key:F.trim(),groupId:"default"});if(!Q.ok){a.error(`Save failed: ${Q.message??Q.error??"unknown"}`);return}T(""),ae(),a.success("Subscription Key saved. Loading quota…"),L()}catch(Q){a.error(`Save failed: ${Q.message}`)}finally{y(!1)}},[F,a,L]),ae=r.useCallback(async()=>{try{await S.del("/minimax/cache")}catch{}},[]),J=r.useCallback(async()=>{m(!0),g(null);try{await S.post("/minimax/remains/refresh"),await L(),a.success("Refreshed")}catch(Q){a.error(`Refresh failed: ${Q.message}`)}finally{m(!1)}},[L,a]),_=r.useCallback(async()=>{var Q;k(!0),b(null);try{const ie=await S.post("/minimax/test",{prompt:"Reply with a single word: pong",model:"MiniMax-M3",maxTokens:16});b(ie),ie.ok?a.success(`Test ok — used ${((Q=ie.usage)==null?void 0:Q.total_tokens)??"?"} tokens`):a.error(`Test failed: ${ie.message??ie.error??"unknown"}`)}catch(ie){a.error(`Test request failed: ${ie.message}`)}finally{k(!1)}},[a]);return x&&!i?e.jsxs("div",{className:"view-container",children:[e.jsx(me,{})," Loading MiniMax data…"]}):i?!i.configured&&(o==null?void 0:o.dismissedAt)==null&&N<4?e.jsx(bo,{step:N,setStep:E,keyDraft:F,setKeyDraft:T,showKey:v,setShowKey:w,verifying:$,verifyResult:I,onVerify:R,onSkip:async()=>{await B(),a.success("Skipped.")},onManualKeySave:H,savingKey:P,status:i}):e.jsxs(e.Fragment,{children:[e.jsxs("header",{className:"view-header",children:[e.jsxs("div",{className:"view-header-titles",children:[e.jsxs("h1",{className:"view-title",children:[e.jsx(jt,{size:20,style:{verticalAlign:"text-bottom",marginRight:6}}),"MiniMax Token Plan"]}),e.jsxs("p",{className:"view-subtitle",children:["Remaining 5-hour + weekly quota per model. Fetches live from"," ",e.jsx("code",{children:"www.minimax.io/v1/token_plan/remains"}),"."]})]}),e.jsxs("div",{className:"view-header-actions",children:[e.jsxs(A,{variant:"secondary",size:"sm",onClick:()=>t("settings"),title:"Configure your Subscription Key",children:[e.jsx(Nt,{size:14})," ",i.configured?`Key ${i.apiKeyHint}`:"Add key"]}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:J,disabled:c,children:[c?e.jsx(ue,{size:14,className:"spin"}):e.jsx(oe,{size:14})," Refresh"]})]})]}),l&&!l.ok&&e.jsxs("div",{className:"banner banner-err",children:[e.jsx(Ne,{size:16}),e.jsxs("span",{children:[e.jsx("strong",{children:"Couldn't load quota"}),": ",l.message??l.error??"unknown error"]})]}),(l==null?void 0:l.ok)&&l.models&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"minimax-stats-row",children:[e.jsx(Ls,{label:"Models tracked",value:String(l.models.length),hint:"Distinct model quotas returned by the API"}),e.jsx(Ls,{label:"Last fetched",value:l.fetchedAt?yo(l.fetchedAt):"—",hint:"Refreshed on demand + every 60s"}),e.jsx(Ls,{label:"Group",value:l.groupId??"—",hint:"Usually 'default' for an individual team"}),e.jsx(Ls,{label:"API key",value:l.apiKeyHint??"—",hint:"Masked; the real key never leaves auth.json"})]}),e.jsx("div",{className:"minimax-models-grid",children:l.models.map(Q=>e.jsx(vo,{model:Q},Q.model_name))})]}),i.configured&&e.jsxs(K,{id:"minimax-test",children:[e.jsxs(Z,{children:[e.jsx(Qe,{size:14})," Test the API key"]}),e.jsxs(te,{children:["One-shot chat completion to ",e.jsxs("code",{children:[i.chatBaseUrl,"/chat/completions"]}),"."]}),e.jsxs("div",{className:"minimax-test-actions",children:[e.jsxs(A,{onClick:_,disabled:C,variant:"primary",size:"sm",children:[C?e.jsx(ue,{size:14,className:"spin"}):e.jsx(Qe,{size:14})," Send test prompt"]}),e.jsx("code",{className:"minimax-test-prompt",children:'"Reply with a single word: pong"'})]}),j&&e.jsxs("div",{className:Y("minimax-test-result",j.ok?"ok":"err"),children:[j.ok?e.jsx(We,{size:14}):e.jsx(Ne,{size:14}),e.jsx("div",{className:"minimax-test-body",children:j.ok?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"minimax-test-line",children:[e.jsx("strong",{children:"model:"})," ",e.jsx("code",{children:j.model})," ·"," ",e.jsx("strong",{children:"finish:"})," ",j.finishReason??"—"]}),j.content&&e.jsx("div",{className:"minimax-test-content",children:e.jsx("code",{children:j.content})}),j.usage&&e.jsxs("div",{className:"minimax-test-usage",children:[e.jsx("strong",{children:"usage:"})," total ",e.jsx("code",{children:j.usage.total_tokens??"?"})," · prompt"," ",e.jsx("code",{children:j.usage.prompt_tokens??"?"})," · completion"," ",e.jsx("code",{children:j.usage.completion_tokens??"?"}),((ee=j.usage.prompt_tokens_details)==null?void 0:ee.cached_tokens)!=null&&e.jsxs(e.Fragment,{children:[" · cached ",e.jsx("code",{children:j.usage.prompt_tokens_details.cached_tokens})]})]})]}):e.jsx("pre",{children:j.message??j.error??"unknown error"})})]})]})]}):e.jsx("div",{className:"view-container",children:e.jsxs("div",{className:"error-card",children:[e.jsx(Ne,{size:20}),e.jsxs("div",{children:[e.jsx("strong",{children:"Couldn't load MiniMax status"}),e.jsx("pre",{children:h??"unknown error"})]})]})})}function fo({toast:s}){const[t,a]=r.useState("24h"),[i,n]=r.useState(""),[l,d]=r.useState(""),[o,p]=r.useState(!0),[x,u]=r.useState(null),[c,m]=r.useState([]),[h,g]=r.useState("requests"),[j,b]=r.useState("desc"),[C,k]=r.useState(!1),N=r.useCallback(async(v,w,P)=>{p(!0);try{const y=new URLSearchParams({range:v});v==="custom"&&w&&P&&(y.set("from",String(w)),y.set("to",String(P)));const[L,B]=await Promise.all([S.get(`/usage?${y.toString()}`),S.get("/usage/recent?limit=20")]);u(L),m(B.records)}catch(y){s.error(`Failed to load usage data: ${y.message}`)}finally{p(!1)}},[s]);r.useEffect(()=>{if(t==="custom"){const v=i?new Date(i).getTime():Date.now()-6048e5,w=l?new Date(l).getTime():Date.now();N("custom",v,w)}else N(t)},[t,N]);const E=r.useCallback(v=>{h===v?b(w=>w==="asc"?"desc":"asc"):(g(v),b("desc"))},[h]),$=r.useMemo(()=>x!=null&&x.perModel?[...x.perModel].sort((v,w)=>{const P=v[h]??0,y=w[h]??0,L=typeof P=="number"&&typeof y=="number"?P-y:String(P).localeCompare(String(y));return j==="asc"?L:-L}):[],[x==null?void 0:x.perModel,h,j]),z=r.useMemo(()=>x!=null&&x.daily?{labels:x.daily.map(v=>v.date.slice(5)),requests:x.daily.map(v=>v.requests),tokens:x.daily.map(v=>v.totalTokens)}:{labels:[],requests:[],tokens:[]},[x==null?void 0:x.daily]),I=r.useCallback(async()=>{k(!0),await N(t==="custom"?"custom":t,t==="custom"&&i?new Date(i).getTime():void 0,t==="custom"&&l?new Date(l).getTime():void 0),k(!1)},[N,t,i,l]);if(o&&!x)return e.jsxs("div",{className:"view-container",children:[e.jsx(me,{})," Loading usage data…"]});const f=x==null?void 0:x.totals,F=(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(da,{size:20,style:{verticalAlign:"text-bottom",marginRight:6}}),"Usage Analytics"]}),e.jsxs("p",{className:"view-subtitle",children:["Aggregated from ",e.jsx("code",{children:"~/.local/share/bizar/usage.jsonl"})," — every chatCompletion and fetchRemains call."]})]}),e.jsx("div",{className:"view-header-actions",children:e.jsxs(A,{variant:"secondary",size:"sm",onClick:I,disabled:C,children:[C?e.jsx(ue,{size:14,className:"spin"}):e.jsx(oe,{size:14})," Refresh"]})})]}),e.jsxs("div",{className:"usage-time-range",children:[["24h","7d","30d","custom"].map(v=>e.jsx("button",{className:Y("usage-range-chip",t===v&&"is-active"),onClick:()=>a(v),children:v==="custom"?"Custom":v.toUpperCase()},v)),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:v=>n(v.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:l,onChange:v=>d(v.target.value),"aria-label":"To date"})]})]}),e.jsxs("div",{className:"usage-kpi-row",children:[e.jsx(gs,{label:"Total Requests",value:(f==null?void 0:f.requests.toLocaleString())??"—",sub:f?`${f.errors} errors`:void 0,tone:f&&f.errors>f.requests*.1?"warn":void 0}),e.jsx(gs,{label:"Total Tokens",value:f?f.totalTokens>=1e3?`${Math.round(f.totalTokens/1e3)}k`:String(f.totalTokens):"—",sub:f?`${f.promptTokens.toLocaleString()} prompt · ${f.completionTokens.toLocaleString()} completion`:void 0}),e.jsx(gs,{label:"Errors",value:String((f==null?void 0:f.errors)??"—"),sub:F.length>0?`${F[0].code}: ${F[0].count}`:void 0,tone:f&&f.errors>0?"err":void 0}),e.jsx(gs,{label:"Avg Latency",value:(f==null?void 0:f.avgLatencyMs)!=null?`${f.avgLatencyMs}ms`:"—",sub:(f==null?void 0:f.p95LatencyMs)!=null?`p95 ${f.p95LatencyMs}ms`:void 0}),e.jsx(gs,{label:"Est. Cost",value:(f==null?void 0:f.costEstimate)!=null&&f.costEstimate>0?`$${f.costEstimate.toFixed(4)}`:"—",sub:"approximate USD",tone:void 0})]}),e.jsxs(K,{className:"usage-chart-card",children:[e.jsx("div",{className:"usage-chart-wrap",children:e.jsx(xo,{series:z,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(K,{children:[e.jsx(Z,{children:"Per-model breakdown"}),e.jsx(po,{rows:$,sortKey:h,sortDir:j,onSort:E})]}),T.length>0&&e.jsxs(K,{children:[e.jsx(Z,{children:"API Keys"}),e.jsx("div",{className:"usage-key-row",children:T.map(v=>e.jsxs("span",{className:Y("usage-key-badge",v.isBackup?"is-backup":"is-active"),children:[e.jsx("span",{className:"usage-key-dot"}),v.keyEnvVar,v.isBackup?" (backup)":" (active)"," · ",v.requests," req"]},v.keyEnvVar))})]}),c.length>0&&e.jsxs(K,{children:[e.jsx(Z,{children:"Recent activity"}),e.jsx("div",{className:"usage-recent-list",children:c.map((v,w)=>e.jsxs("div",{className:Y("usage-recent-item",v.error&&"is-err"),children:[e.jsx("span",{className:"usage-recent-time",children:new Date(v.ts).toLocaleTimeString()}),e.jsx("span",{className:"usage-recent-model",children:e.jsx("code",{children:v.modelId})}),e.jsxs("span",{className:"usage-recent-tokens",children:[v.totalTokens.toLocaleString()," tok"]}),e.jsxs("span",{className:"usage-recent-latency",children:[v.latencyMs,"ms"]}),e.jsx("span",{className:"usage-recent-endpoint",children:v.endpoint})]},`${v.requestId}-${w}`))})]})]})}function gs({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 Ls({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 vo({model:s}){const t=Is(s.current_interval_remaining_percent??0,0,100),a=Is(s.current_weekly_remaining_percent??0,0,100),i=Is(100-t,0,100),n=Is(100-a,0,100);return e.jsxs(K,{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(Gt,{icon:e.jsx(Ae,{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(Gt,{icon:e.jsx(Fn,{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 Gt({icon:s,label:t,remainingPct:a,consumedPct:i,used:n,total:l,resetIn:d,resetISO:o}){const p=a>=75?"good":a>=25?"warn":"low";return e.jsxs("div",{className:`minimax-quota-row is-${p}`,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.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})," / ",l||"—"," requests"]}),e.jsx("span",{title:o,children:d?`resets in ${d}`:"—"})]})]})}function Is(s,t,a){return Math.max(t,Math.min(a,s))}function yo(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 bo({step:s,setStep:t,keyDraft:a,setKeyDraft:i,showKey:n,setShowKey:l,verifying:d,verifyResult:o,onVerify:p,onSkip:x,onManualKeySave:u,savingKey:c,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(Fe,{size:20,style:{verticalAlign:"text-bottom",marginRight:6}}),"Set up MiniMax Token Plan tracking"]}),e.jsx("p",{className:"view-subtitle",children:"We'll read your Subscription Key and show your remaining quota."})]}),e.jsx("div",{className:"view-header-actions",children:e.jsxs(A,{variant:"ghost",size:"sm",onClick:x,children:[e.jsx(ze,{size:14})," Skip for now"]})})]}),e.jsx("div",{className:"minimax-wizard-stepper",children:["Welcome","Get a key","Paste & test","Done"].map((h,g)=>e.jsxs("div",{className: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(We,{size:14}):g+1}),e.jsx("div",{className:"minimax-wizard-step-label",children:h})]},h))}),e.jsxs(K,{id:"minimax-wizard-card",children:[s===0&&e.jsxs("div",{className:"minimax-wizard-body",children:[e.jsx("h3",{className:"minimax-wizard-title",children:"Welcome"}),e.jsxs("p",{className:"minimax-wizard-prose",children:["BizarHarness shows you how much of your MiniMax Token Plan quota you have left — both the ",e.jsx("strong",{children:"5-hour rolling"})," and ",e.jsx("strong",{children:"weekly"})," windows."]}),e.jsxs("ul",{className:"minimax-wizard-list",children:[e.jsxs("li",{children:["Stored in ",e.jsx("code",{children:"~/.local/share/opencode/auth.json"}),"."]}),e.jsx("li",{children:"Read fresh on every dashboard load."}),e.jsx("li",{children:"Never logged in full."})]}),e.jsx("div",{className:"minimax-wizard-actions",children:e.jsxs(A,{onClick:()=>t(1),variant:"primary",size:"md",children:["Get started ",e.jsx("span",{style:{marginLeft:6},children:"→"})]})})]}),s===1&&e.jsxs("div",{className:"minimax-wizard-body",children:[e.jsx("h3",{className:"minimax-wizard-title",children:"Get your Subscription Key"}),e.jsx("p",{className:"minimax-wizard-prose",children:"Go to the MiniMax console and copy your Subscription Key."}),e.jsxs("ol",{className:"minimax-wizard-list",children:[e.jsxs("li",{children:["Open ",e.jsxs("a",{href:"https://platform.minimax.io/user-center/payment/token-plan",target:"_blank",rel:"noreferrer",className:"minimax-wizard-link",children:[e.jsx(ds,{size:12})," platform.minimax.io"]})]}),e.jsxs("li",{children:["Click ",e.jsx("strong",{children:"Copy Subscription Key"}),"."]}),e.jsx("li",{children:"Come back here and paste it."})]}),e.jsxs("div",{className:"minimax-wizard-actions",children:[e.jsx(A,{variant:"secondary",size:"md",onClick:()=>t(0),children:"← Back"}),e.jsxs(A,{variant:"primary",size:"md",onClick:()=>t(2),children:["I have my key ",e.jsx("span",{style:{marginLeft:6},children:"→"})]})]})]}),s===2&&e.jsxs("div",{className:"minimax-wizard-body",children:[e.jsx("h3",{className:"minimax-wizard-title",children:"Paste & test"}),e.jsx("p",{className:"minimax-wizard-prose",children:"Paste your key below. We'll test it against the real API before saving."}),e.jsx("div",{className:"minimax-key-row",children:e.jsxs("div",{className:"minimax-key-input-wrap",children:[e.jsx(Nt,{size:12,className:"minimax-key-icon","aria-hidden":!0}),e.jsx("label",{htmlFor:"minimax-key-input",className:"sr-only",children:"Subscription Key"}),e.jsx("input",{id:"minimax-key-input",type:n?"text":"password",value:a,onChange:h=>i(h.target.value),placeholder:"sk-cp-...",spellCheck:!1,autoComplete:"off",className:"minimax-key-input",autoFocus:!0,"aria-label":"Subscription Key"}),e.jsx("button",{type:"button",onClick:()=>l(h=>!h),className:"minimax-key-toggle","aria-label":n?"Hide key":"Show key",children:n?e.jsx(ot,{size:13}):e.jsx(He,{size:13})})]})}),o&&!o.ok&&e.jsxs("div",{className:"minimax-wizard-error",children:[e.jsx(Ne,{size:14}),e.jsxs("span",{children:[e.jsx("strong",{children:"Verification failed:"})," ",o.message??o.error]})]}),e.jsxs("div",{className:"minimax-wizard-actions",children:[e.jsx(A,{variant:"secondary",size:"md",onClick:()=>t(1),children:"← Back"}),e.jsxs(A,{variant:"primary",size:"md",onClick:p,disabled:d||!a.trim(),children:[d?e.jsx(ue,{size:14,className:"spin"}):e.jsx(ws,{size:14}),d?"Testing…":"Test &amp; save key"]})]}),e.jsxs("p",{className:"minimax-wizard-prose minimax-wizard-prose--muted",children:["Don't want to test first? ",e.jsx("a",{href:"#",onClick:h=>{h.preventDefault(),u()},className:"minimax-wizard-link",children:"Save without testing"})]})]}),s===3&&e.jsxs("div",{className:"minimax-wizard-body",children:[e.jsxs("h3",{className:"minimax-wizard-title",children:[e.jsx(We,{size:18,style:{verticalAlign:"text-bottom",marginRight:6}}),"All set"]}),e.jsx("p",{className:"minimax-wizard-prose",children:"The key works and is saved. Reloading so you can see your live quota."}),e.jsx("div",{className:"minimax-wizard-actions",children:e.jsx(A,{variant:"primary",size:"md",onClick:()=>window.location.reload(),children:"View your quota →"})})]}),e.jsxs("div",{className:"minimax-wizard-footer",children:[e.jsx(ws,{size:11}),e.jsxs("span",{children:["Key written to ",e.jsx("code",{children:"~/.local/share/opencode/auth.json"})," with mode 0600."]})]})]})]})}const ko=qe.memo(go),No={pending:"info",running:"accent",done:"success",failed:"error",killed:"neutral",timed_out:"warning"},wo={pending:"Pending",running:"Running",done:"Done",failed:"Failed",killed:"Killed",timed_out:"Timed out"};function So({status:s,dot:t}){const a=No[s]||"neutral",i=wo[s]||s;return e.jsx(rs,{kind:a,dot:t,children:i})}function Co({instanceId:s,instanceName:t,onConfirm:a,onClose:i}){return e.jsxs("div",{children:[e.jsxs("p",{style:{marginBottom:16,lineHeight:1.6},children:["Instance ",e.jsx("code",{children:s}),t?e.jsxs(e.Fragment,{children:[" (",t,")"]}):null," will be terminated. This cannot be undone."]}),e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx(A,{variant:"ghost",onClick:i,children:"Cancel"}),e.jsx(A,{variant:"danger",onClick:async()=>{await a(),i()},children:"Kill"})]})]})}function zo(s,t,a,i,n){s.open({title:"Kill instance?",width:400,children:e.jsx(Co,{instanceId:a,instanceName:i,onConfirm:async()=>{try{const d=await(await fetch(`/api/background/${encodeURIComponent(a)}`,{method:"DELETE"})).json();d.ok?(t.success(`Instance ${a} killed.`),n==null||n()):t.error(`Kill failed: ${d.error||"unknown error"}`)}catch(l){t.error(`Kill failed: ${l.message}`)}},onClose:()=>s.close()})})}function To({instance:s}){const t=le(),[a,i]=r.useState(!1),n=s.tmuxSession,l=n?`tmux attach -t ${n}`:null,d=async()=>{if(l)try{await navigator.clipboard.writeText(l),t.success("Attach command copied")}catch{t.error("Could not copy to clipboard")}},o=async()=>{if(!(!s.instanceId||!n)){i(!0);try{const p=await S.post(`/background/${encodeURIComponent(s.instanceId)}/open-terminal`,{emulator:"system"});if(p.ok)t.success("Opening terminal…");else if(t.error(p.error||"Failed to open terminal"),l)try{await navigator.clipboard.writeText(l),t.success("Command copied to clipboard")}catch{}}catch(p){if(t.error(`Failed: ${p.message}`),l)try{await navigator.clipboard.writeText(l),t.success("Command copied to clipboard")}catch{}}finally{i(!1)}}};return n?e.jsxs(K,{variant:"outlined",className:"bg-tmux-card",children:[e.jsxs("div",{className:"bg-tmux-card-header",children:[e.jsx(bs,{size:14}),e.jsx("span",{children:"tmux session"}),s.tmuxActive!==!1?e.jsx("span",{className:"badge badge-success",children:"live"}):e.jsx("span",{className:"badge badge-warning",children:"inactive"})]}),e.jsx("code",{className:"mono bg-tmux-session-name",children:n}),e.jsx("p",{className:"muted bg-tmux-hint",children:"Attach to the agent's tmux session from a terminal on the host running the dashboard."}),e.jsxs("div",{className:"bg-tmux-card-actions",children:[e.jsxs(A,{variant:"ghost",size:"sm",onClick:d,title:"Copy attach command",children:[e.jsx(Ze,{size:14})," Copy"]}),e.jsxs(A,{variant:"primary",size:"sm",onClick:o,loading:a,title:"Open in system terminal",children:[e.jsx(bs,{size:14})," Open terminal"]})]})]}):e.jsxs(K,{variant:"outlined",className:"bg-tmux-card bg-tmux-card-warn",children:[e.jsxs("div",{className:"bg-tmux-card-header",children:[e.jsx(Ne,{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 Ro=5e3,$o=2e3,Ao=120;function Mo(s){return s.status==="pending"||s.status==="running"}function Lo(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 Io(s){const t=le(),a=Te(),[i,n]=r.useState([]),[l,d]=r.useState(!0),[o,p]=r.useState(null),[,x]=r.useState(0),u=r.useCallback(async()=>{try{const j=await S.get("/background");n(Array.isArray(j==null?void 0:j.instances)?j.instances:[]),p(null)}catch(j){p((j==null?void 0:j.message)||"Failed to load background agents.")}finally{d(!1)}},[]);r.useEffect(()=>{u();const j=setInterval(u,Ro);return()=>clearInterval(j)},[u]),r.useEffect(()=>{const j=setInterval(()=>x(b=>(b+1)%1e6),1e3);return()=>clearInterval(j)},[]),r.useEffect(()=>{const j=new pt,b=j.on(C=>{const k=C.type;(k==="background:change"||k==="background:cleanup")&&u()});return()=>{b(),j.close()}},[u]);const c=i.filter(Mo),m=j=>{Do(a,j)},h=async j=>{try{const b=await S.get(`/background/${encodeURIComponent(j.instanceId)}/tmux`);Fo(a,b)}catch(b){t.error(`Tmux info failed: ${b.message}`)}},g=j=>{zo(a,t,j.instanceId,j.agent||j.prompt,()=>{n(b=>b.filter(C=>C.instanceId!==j.instanceId))})};return l?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…"})]})}):o?e.jsx("div",{className:"bg-active-view",children:e.jsx(Se,{icon:e.jsx(Ae,{size:32}),title:"Couldn't load background agents",message:o,action:e.jsxs(A,{variant:"primary",onClick:u,children:[e.jsx(oe,{size:14})," Retry"]})})}):e.jsxs("div",{className:"bg-active-view",children:[e.jsxs("div",{className:"bg-active-header",children:[e.jsxs("div",{className:"bg-active-header-text",children:[e.jsx("h2",{className:"bg-active-title",children:"Active Background Agents"}),e.jsxs("p",{className:"bg-active-subtitle muted",children:[c.length," active · ",i.length," total in store"]})]}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:u,title:"Refresh now",children:[e.jsx(oe,{size:14})," Refresh"]})]}),c.length===0?e.jsx(Se,{icon:e.jsx(Ae,{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:c.map(j=>e.jsx(Eo,{inst:j,onViewOutput:()=>m(j),onOpenTmux:()=>h(j),onKill:()=>g(j)},j.instanceId))})]})}function Eo({inst:s,onViewOutput:t,onOpenTmux:a,onKill:i}){const n=typeof s.startedAt=="number"?s.startedAt:0,l=n?cs(n):"—",d=n?Date.now()-n:0,o=Yt(s.prompt,Ao);return e.jsxs(K,{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(So,{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"})]})]}),o&&e.jsx("div",{className:"bg-active-prompt",children:o}),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:l,children:[e.jsx("strong",{children:"Started:"})," ",l]}),e.jsxs("span",{children:[e.jsx("strong",{children:"Duration:"})," ",Lo(d)]}),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(A,{variant:"secondary",size:"sm",onClick:t,children:[e.jsx(He,{size:14})," View output"]}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:a,children:[e.jsx(bs,{size:14})," Open in tmux"]}),e.jsxs(A,{variant:"danger",size:"sm",onClick:i,children:[e.jsx(be,{size:14})," Kill"]})]}),e.jsx(To,{instance:s})]})}function Do(s,t){s.open({title:`Output — ${t.agent||t.instanceId}`,width:720,children:e.jsx(Po,{instanceId:t.instanceId})})}function Po({instanceId:s}){const t=le(),[a,i]=r.useState(""),[n,l]=r.useState(!0),[d,o]=r.useState(null),[p,x]=r.useState(!0),u=r.useRef(null),c=r.useRef(!0),m=r.useCallback(async()=>{try{const j=await S.get(`/background/${encodeURIComponent(s)}/output?lines=200`);i((j==null?void 0:j.output)??""),x((j==null?void 0:j.available)!==!1),o(null)}catch(j){o((j==null?void 0:j.message)||"Failed to load output.")}finally{l(!1)}},[s]);r.useEffect(()=>{m();const j=setInterval(m,$o);return()=>clearInterval(j)},[m]),r.useEffect(()=>{var j;c.current&&((j=u.current)==null||j.scrollIntoView({behavior:"auto",block:"end"}))},[a]);const h=j=>{const b=j.currentTarget,C=b.scrollHeight-b.scrollTop-b.clientHeight<24;c.current=C},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:p?`${a.length} chars · auto-refresh 2s`:"Output unavailable"}),e.jsxs("div",{className:"bg-output-toolbar-actions",children:[e.jsxs(A,{variant:"ghost",size:"sm",onClick:m,title:"Refresh now",children:[e.jsx(oe,{size:14})," Refresh"]}),e.jsxs(A,{variant:"ghost",size:"sm",onClick:g,disabled:!a,children:[e.jsx(Ze,{size:14})," Copy"]})]})]}),n&&!a?e.jsxs("div",{className:"bg-output-loading",children:[e.jsx(ue,{size:16,className:"spin"})," Loading…"]}):d?e.jsx("div",{className:"bg-output-error",children:d}):a?e.jsxs("div",{className:"bg-output-scroll",onScroll:h,children:[e.jsx("pre",{className:"bg-output-pre mono",children:e.jsx("code",{children:a})}),e.jsx("div",{ref:u})]}):e.jsx("div",{className:"bg-output-empty muted",children:"No output captured yet."})]})}function Fo(s,t){const a=t.attachCommand||t.session||"";s.open({title:"Attach to tmux",width:520,children:e.jsx(Oo,{info:t,cmd:a})})}function Oo({info:s,cmd:t}){const[a,i]=r.useState(!1),n=async()=>{try{await navigator.clipboard.writeText(t),i(!0),window.setTimeout(()=>i(!1),1500)}catch{}};return e.jsx("div",{className:"bg-tmux-modal",children:t?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"bg-tmux-meta",children:[s.exists?e.jsx("span",{className:"badge badge-success",children:"session live"}):e.jsxs("span",{className:"badge badge-warning",children:["session not running",s.reason?` — ${s.reason}`:""]}),s.session&&e.jsxs("span",{className:"bg-tmux-session muted",children:["· session ",e.jsx("code",{className:"mono",children:s.session})]})]}),e.jsx("label",{className:"field-label",children:"Attach command"}),e.jsxs("div",{className:"bg-tmux-command-row",children:[e.jsx("code",{className:"bg-tmux-command mono",children:t}),e.jsxs(A,{variant:"secondary",size:"sm",onClick:n,children:[e.jsx(Ze,{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 lt={overview:bi,chat:Pi,agents:Ui,artifacts:xr,memory:mo,tasks:Sr,activity:Er,background:Io,config:Ut,settings:Ut,mods:jl,schedules:Tl,skills:Dl,history:uo,minimax:ko},Bo="v4.5.0";function Uo(s,t,a,i){if(lt[s]){const d=lt[s];return e.jsx(d,{...t})}const n=a.find(d=>d.id===s);if(n)return e.jsx(vl,{viewId:n.id,reloadKey:i,activeTab:t.activeTab,setActiveTab:t.setActiveTab});const l=lt.overview;return e.jsx(l,{...t})}function _o({onSaved:s}){const[t,a]=r.useState(""),i=r.useRef(null);r.useEffect(()=>{var d;(d=i.current)==null||d.focus()},[]);const n=()=>{const d=t.trim();d&&(S.setToken(d),s())},l=d=>{d.key==="Escape"&&(d.preventDefault(),s()),d.key==="Enter"&&(d.preventDefault(),n())};return e.jsxs("form",{className:"token-entry-form",onSubmit:d=>{d.preventDefault(),n()},children:[e.jsxs("div",{className:"token-entry-row",children:[e.jsx("input",{ref:i,type:"password",className:"input mono",value:t,onChange:d=>a(d.target.value),placeholder:"Paste auth token",spellCheck:!1,autoComplete:"off",onKeyDown:l}),e.jsx(A,{type:"submit",variant:"primary",size:"sm",disabled:!t.trim(),children:"Save & retry"})]}),e.jsxs("p",{className:"token-entry-hint",children:["Where do I find this token? Check the file"," ",e.jsx("code",{children:"~/.config/bizar/dashboard-secret"})," on the machine running the dashboard, or look for it in the server output."]})]})}function Wo(){return e.jsx(Oa,{children:e.jsx(Ba,{children:e.jsx(Ho,{})})})}function Ho(){var Q,ie,je;const s=le(),t=Te(),{isModalOpen:a}=t,i=r.useRef(!1),[n,l]=r.useState("overview"),[d,o]=r.useState(null),[p,x]=r.useState(null),[u,c]=r.useState("connecting"),[m,h]=r.useState(null),[g,j]=r.useState(!1),[b,C]=r.useState(!1),[k,N]=r.useState([]),[E,$]=r.useState(!1),[z,I]=r.useState([]),[f,F]=r.useState(0),T=r.useRef(null),[v,w]=r.useState(null);r.useEffect(()=>{let V=!1;return(async()=>{try{const D=await S.get("/mods/views");if(V)return;I(D.views||[])}catch{V||I([])}})(),()=>{V=!0}},[f,d==null?void 0:d.mods]),r.useEffect(()=>{if(!v)return;const V=v.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")&&F(U=>U+1)});return()=>V()},[v]),r.useEffect(()=>{p!=null&&p.theme&&(js(p.theme),is(p.theme))},[p==null?void 0:p.theme]),r.useEffect(()=>{i.current=a},[a]),r.useEffect(()=>{var U;if(((U=p==null?void 0:p.theme)==null?void 0:U.mode)!=="system")return;const V=window.matchMedia("(prefers-color-scheme: light)"),D=()=>js(p.theme.mode);return V.addEventListener("change",D),()=>V.removeEventListener("change",D)},[(Q=p==null?void 0:p.theme)==null?void 0:Q.mode]);const P=r.useCallback(async()=>{let V=!1;const D=()=>Promise.all([S.get("/snapshot").catch(()=>null),S.get("/settings").catch(()=>null),S.get("/agents/stuck").catch(()=>null)]),U=(W,ne,q)=>{W&&o(W),ne!=null&&ne.data&&x(ne.data),q!=null&&q.stuck&&N(q.stuck)};try{const W=await S.probeAuthStatus(),[ne,q,O]=await D();if(U(ne,q,O),ne||q){h(null);return}if(!W.loopback){h("Dashboard server unreachable.");return}await new Promise(ce=>setTimeout(ce,1e3));const[re,se,he]=await D();U(re,se,he),!re&&!se&&h("Dashboard server unreachable.")}catch(W){const ne=(W==null?void 0:W.message)??"unknown error";if(W instanceof Ua&&W.status===401){h(ne),j(!0),s.error(`Auth required: ${ne}`);return}h(ne),s.error(`Failed to load: ${ne}`)}},[s]);r.useEffect(()=>{let V=!1;const D=setTimeout(()=>{V||P()},0);return()=>{V=!0,clearTimeout(D)}},[P]),r.useEffect(()=>{let V=!1;return S.get("/settings").then(D=>{var W,ne;if(V)return;const U=(ne=(W=D==null?void 0:D.data)==null?void 0:W.ui)==null?void 0:ne.defaultTab;U&&l(U)}).catch(()=>{}),()=>{V=!0}},[]),r.useEffect(()=>{let V=!1;const D=async()=>{try{const W=await S.get("/agents/stuck");V||N(ne=>{const q=W.stuck||[];return ne.length===0&&q.length>0&&s.warning(`${q.length} agent${q.length===1?"":"s"} stuck`,5e3),q})}catch{}},U=setInterval(D,3e4);return D(),()=>{V=!0,clearInterval(U)}},[]),r.useEffect(()=>{const V=new pt;T.current=V,w(V);const D=V.onStatus(W=>c(W)),U=V.on(W=>{var ne;if(W.type==="snapshot"&&"data"in W&&W.data)o(q=>({...q??{},...W.data}));else if(W.type==="change"){const q=W,O=((ne=q.path)==null?void 0:ne.split("/").pop())||q.path||"";s.info(`File changed: ${O}`,2500)}else if(W.type==="tasks:change"){const q=W;o(O=>{if(!O)return O;const re=(O.tasks||[]).map(he=>he.id===q.task.id?q.task:he),se=re.some(he=>he.id===q.task.id);return{...O,tasks:se?re:[q.task,...re]}})}else if(W.type==="tasks:delete"){const q=W;o(O=>O&&{...O,tasks:(O.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")S.get("/snapshot").then(q=>o(O=>({...O??{},...q}))).catch(()=>{});else if(W.type==="agents:change"||W.type==="schedules:change")S.get("/snapshot").then(q=>o(O=>({...O??{},...q}))).catch(()=>{});else if(W.type==="agent:status"||W.type==="agent:restarted"){const q=W;o(O=>{if(!O)return O;const re=(O.agents||[]).map(se=>se.name===q.agent.name?q.agent:se);return{...O,agents:re}})}else if(W.type==="artifact:change")S.get("/artifacts").then(q=>{o(O=>O&&{...O,artifacts:q.artifacts||[]})}).catch(()=>{});else if(W.type==="agent:stuck")N(W.agents||[]);else if(W.type==="dialog:show"){const q=W;q.dialog&&t.open({title:q.dialog.title,width:520,children:e.jsx(oi,{dialog:q.dialog,onClose:()=>t.close()})})}});return()=>{D(),U(),V.close(),w(null)}},[s]);const y=r.useCallback(V=>v?v.on(V):()=>{},[v]),L=r.useRef(0);r.useEffect(()=>{const V=()=>{L.current=Date.now()+1500};return document.addEventListener("mousedown",V,!0),document.addEventListener("click",V,!0),document.addEventListener("focusin",V,!0),document.addEventListener("keydown",V,!0),()=>{document.removeEventListener("mousedown",V,!0),document.removeEventListener("click",V,!0),document.removeEventListener("focusin",V,!0),document.removeEventListener("keydown",V,!0)}},[]),r.useEffect(()=>{const V={};mt.forEach((U,W)=>{V[String(W+1)]=U.id});const D=U=>{var ce,Cs,zs,Ts;if((U.metaKey||U.ctrlKey)&&U.key.toLowerCase()==="k"){U.preventDefault(),C(!0);return}if(U.key==="/"&&!U.metaKey&&!U.ctrlKey){const Rs=(Cs=(ce=U.target)==null?void 0:ce.tagName)==null?void 0:Cs.toLowerCase();if(Rs!=="input"&&Rs!=="textarea"&&!((zs=U.target)!=null&&zs.isContentEditable)){U.preventDefault(),C(!0);return}}const W=document.activeElement;if(!W||W===document.body||W===document.documentElement)return;const q=U.target,O=(Ts=q==null?void 0:q.tagName)==null?void 0:Ts.toLowerCase(),re=O==="input"||O==="textarea"||O==="select"||O==="button"||O==="option"||O==="label"||!!(q!=null&&q.isContentEditable);let se=!1;if(q&&typeof q.closest=="function"&&(se=!!q.closest('form, [role="dialog"], [contenteditable], [data-no-key]')),U.repeat||i.current||re||se||U.metaKey||U.ctrlKey||U.altKey||U.shiftKey||Date.now()<L.current)return;const he=V[U.key];he&&(U.preventDefault(),l(he))};return document.addEventListener("keydown",D),()=>document.removeEventListener("keydown",D)},[]);const B=r.useMemo(()=>async()=>{try{const V=await S.get("/snapshot");o(D=>({...D??{},...V}))}catch(V){s.error(`Refresh failed: ${V.message}`)}},[s]),R=r.useMemo(()=>{const V=z.map(D=>({id:D.id,label:D.label,icon:D.kind==="iframe"?Ns:dt,isMod:!0,modId:D.modId}));return[...mt,...V]},[z]),H=r.useMemo(()=>d&&p?Uo(n,{snapshot:d,settings:p,activeTab:n,setActiveTab:l,refreshSnapshot:B},z,f):null,[n,d,p,z,f,B]),ae=async()=>{try{const V=await S.get("/projects");o(D=>{var U;return D&&{...D,projects:V.projects||[],activeProject:((U=V.projects)==null?void 0:U.find(W=>W.id===V.active))||null}})}catch(V){s.error(`Projects refresh failed: ${V.message}`)}},J=async V=>{try{await S.post(`/projects/${encodeURIComponent(V)}/activate`),o(D=>D&&{...D,activeProject:D.projects.find(U=>U.id===V)||null})}catch(D){s.error(`Activate failed: ${D.message}`)}},_=V=>{const D=V.type;if(D==="agent")l("agents");else if(D==="task")l("tasks");else if(D==="mod")l("mods");else if(D==="schedule")l("schedules");else if(D==="project"){const U=V.item.id;J(U)}else if(D==="command")s.info(`/${V.item.name} — run from the TUI`,2500);else if(D==="setting"){const U=V.item.id||V.item.path||"";l("settings");const W=ne=>{if(ne<=0)return;const q=U?document.querySelector(`[data-setting-id="${CSS.escape(U)}"]`):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(ne-1),80)};window.setTimeout(()=>W(15),60)}},X=((ie=p==null?void 0:p.ui)==null?void 0:ie.layout)||"topnav",ee=((je=p==null?void 0:p.ui)==null?void 0:je.showHeader)!==!1;return e.jsxs("div",{className:"app","data-layout":X,"data-active-tab":n,children:[e.jsx("a",{className:"skip-to-main",href:"#main-content",children:"Skip to main content"}),ee&&e.jsx(Kn,{activeTab:n,onTabChange:l,wsStatus:u,version:Bo,activeProject:(d==null?void 0:d.activeProject)||null,projects:(d==null?void 0:d.projects)||[],onProjectChange:J,onProjectsRefresh:ae,onOpenSearch:()=>C(!0),settings:p,notificationsSlot:e.jsx(ei,{wsSubscribe:y}),showTabs:X==="topnav",extraTabs:R}),k.length>0&&!E&&e.jsxs("div",{className:"stuck-banner",role:"alert",children:[e.jsx(Ne,{size:16}),e.jsxs("span",{children:[e.jsx("strong",{children:k.length})," agent",k.length===1?"":"s"," stuck:"," ",e.jsx("span",{className:"mono",children:k.map(V=>V.name).join(", ")})]}),e.jsx(A,{variant:"secondary",size:"sm",onClick:()=>{l("agents"),$(!0)},children:"Review"}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Dismiss",onClick:()=>$(!0),children:e.jsx(ze,{size:14})})]}),e.jsxs("div",{className:"layout-body",children:[X!=="topnav"&&e.jsx(Xn,{tabs:R,activeTab:n,onTabChange:l}),e.jsxs("main",{className:"content",id:"main-content",tabIndex:-1,children:[m&&e.jsxs("div",{className:"boot-error",children:[e.jsx("h2",{children:"Dashboard unavailable"}),e.jsx("p",{children:m}),g&&e.jsx(_o,{onSaved:()=>{j(!1),P()}}),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&&(!d||!p)&&e.jsxs("div",{className:"loading",children:[e.jsx(me,{size:"lg"}),e.jsx("p",{children:"Loading Bizar…"})]}),H&&e.jsx(r.Suspense,{fallback:e.jsxs("div",{className:"loading",children:[e.jsx(me,{size:"lg"}),e.jsx("p",{children:"Loading…"})]}),children:e.jsx(qo,{children:H})})]})]}),e.jsx(Qn,{open:b,onClose:()=>C(!1),onSelect:_})]})}class qo extends r.Component{constructor(){super(...arguments);hs(this,"state",{err:null});hs(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(Ne,{size:20}),e.jsxs("div",{className:"view-error-body",children:[e.jsx("strong",{children:"This view crashed."}),e.jsx("pre",{children:this.state.err.message}),e.jsx(A,{variant:"secondary",size:"sm",onClick:this.reset,children:"Retry"})]})]}):this.props.children}}function Vo(){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(_a,{}):e.jsx(Wo,{})}const ka=document.getElementById("root");if(!ka)throw new Error("Root element #root not found");Ha(ka).render(e.jsx(r.StrictMode,{children:e.jsx(Vo,{})}));