@polderlabs/bizar 5.0.2 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/bizar-dash/dist/assets/MobileChat-BVojK0n5.js +1 -0
  2. package/bizar-dash/dist/assets/MobileChat-BVojK0n5.js.map +1 -0
  3. package/bizar-dash/dist/assets/MobileSettings-C85ApWKZ.js +1 -0
  4. package/bizar-dash/dist/assets/MobileSettings-C85ApWKZ.js.map +1 -0
  5. package/bizar-dash/dist/assets/{icons-Bo0iH9EC.js → icons-Clz0NR6Y.js} +20 -25
  6. package/bizar-dash/dist/assets/icons-Clz0NR6Y.js.map +1 -0
  7. package/bizar-dash/dist/assets/{main-C1cpttnv.js → main-8feQWXiF.js} +10 -10
  8. package/bizar-dash/dist/assets/main-8feQWXiF.js.map +1 -0
  9. package/bizar-dash/dist/assets/markdown-C6mXtQxD.js +1 -0
  10. package/bizar-dash/dist/assets/markdown-C6mXtQxD.js.map +1 -0
  11. package/bizar-dash/dist/assets/mobile-D2pc-iNh.js +1 -0
  12. package/bizar-dash/dist/assets/{mobile-DD-FZrTC.js.map → mobile-D2pc-iNh.js.map} +1 -1
  13. package/bizar-dash/dist/assets/mobile-IaZ47uKC.js +2 -0
  14. package/bizar-dash/dist/assets/mobile-IaZ47uKC.js.map +1 -0
  15. package/bizar-dash/dist/assets/{react-vendor-DZRUXSPQ.js → react-vendor-Dn4wqh4Z.js} +8 -8
  16. package/bizar-dash/dist/assets/react-vendor-Dn4wqh4Z.js.map +1 -0
  17. package/bizar-dash/dist/assets/useSlashCommands-DjEwHl4n.js +2 -0
  18. package/bizar-dash/dist/assets/useSlashCommands-DjEwHl4n.js.map +1 -0
  19. package/bizar-dash/dist/assets/vendor-CeHGtduv.js +29 -0
  20. package/bizar-dash/dist/assets/vendor-CeHGtduv.js.map +1 -0
  21. package/bizar-dash/dist/index.html +7 -5
  22. package/bizar-dash/dist/mobile.html +4 -5
  23. package/bizar-dash/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +1 -1
  24. package/bizar-dash/src/server/eval.mjs +93 -3
  25. package/bizar-dash/src/server/metrics.mjs +75 -0
  26. package/bizar-dash/src/server/otel.mjs +141 -14
  27. package/bizar-dash/src/server/plugins/registry.mjs +145 -43
  28. package/bizar-dash/src/server/routes/chat.mjs +46 -9
  29. package/bizar-dash/src/server/routes/opencode-session-detail.mjs +120 -17
  30. package/bizar-dash/src/server/routes/plugins.mjs +123 -16
  31. package/bizar-dash/src/server/routes/workspaces.mjs +156 -61
  32. package/bizar-dash/src/server/server.mjs +44 -15
  33. package/bizar-dash/src/web/MobileApp.tsx +18 -10
  34. package/bizar-dash/src/web/mobile/MobileChat.tsx +138 -0
  35. package/bizar-dash/src/web/mobile/MobileSettings.tsx +196 -0
  36. package/bizar-dash/tests/bundle-analysis.test.mjs +5 -4
  37. package/bizar-dash/tests/eval/fixtures-extra.test.mjs +285 -0
  38. package/bizar-dash/tests/otel-spans.test.mjs +253 -0
  39. package/bizar-dash/tests/plugins-registry-fallback.test.mjs +259 -0
  40. package/package.json +1 -1
  41. package/templates/eval-fixtures/citation.json +16 -0
  42. package/templates/eval-fixtures/code-review.json +16 -0
  43. package/templates/eval-fixtures/concise-output.json +16 -0
  44. package/templates/eval-fixtures/context-window.json +16 -0
  45. package/templates/eval-fixtures/error-recovery.json +16 -0
  46. package/templates/eval-fixtures/json-output.json +20 -0
  47. package/templates/eval-fixtures/multi-language.json +16 -0
  48. package/templates/eval-fixtures/safe-paths.json +16 -0
  49. package/templates/eval-fixtures/tool-call-multi-step.json +18 -0
  50. package/templates/eval-fixtures/unicode-handling.json +16 -0
  51. package/bizar-dash/dist/assets/icons-Bo0iH9EC.js.map +0 -1
  52. package/bizar-dash/dist/assets/index-DmpSFPJY.js +0 -9
  53. package/bizar-dash/dist/assets/index-DmpSFPJY.js.map +0 -1
  54. package/bizar-dash/dist/assets/main-C1cpttnv.js.map +0 -1
  55. package/bizar-dash/dist/assets/markdown-DIquRulQ.js +0 -29
  56. package/bizar-dash/dist/assets/markdown-DIquRulQ.js.map +0 -1
  57. package/bizar-dash/dist/assets/mobile-BtxQJftK.js +0 -2
  58. package/bizar-dash/dist/assets/mobile-BtxQJftK.js.map +0 -1
  59. package/bizar-dash/dist/assets/mobile-DD-FZrTC.js +0 -1
  60. package/bizar-dash/dist/assets/react-vendor-DZRUXSPQ.js.map +0 -1
@@ -1,2 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-DmpSFPJY.js","assets/react-vendor-DZRUXSPQ.js"])))=>i.map(i=>d[i]);
2
- var Ft=Object.defineProperty;var _t=(t,s,i)=>s in t?Ft(t,s,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[s]=i;var ne=(t,s,i)=>_t(t,typeof s!="symbol"?s+"":s,i);import{r as a,j as e,a as qt}from"./react-vendor-DZRUXSPQ.js";import{X as xe,z as Wt,C as Ht,D as Vt,I as Yt,b as Ye,d as Be,b9 as Kt,aP as Gt,ba as Qt,bb as Jt,aD as Xt,R as re,bc as Zt,W as ke,B as we,bd as Ze,i as Me,O as xt,x as et,be as es,a9 as Le,ap as ts,g as We,r as ie,a0 as ss,E as ns,M as pe,a3 as Ke,a1 as as,T as is,a7 as gt,o as Ne,aE as ls,l as He,Y as jt,J as fe,k as Ve,aZ as vt,e as tt,ab as st,bf as os,S as Pe,p as nt,au as cs,av as rs,aw as ds,bg as at,w as ms,bh as us}from"./icons-Bo0iH9EC.js";import{M as hs,r as bs}from"./markdown-DIquRulQ.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))c(o);new MutationObserver(o=>{for(const d of o)if(d.type==="childList")for(const r of d.addedNodes)r.tagName==="LINK"&&r.rel==="modulepreload"&&c(r)}).observe(document,{childList:!0,subtree:!0});function i(o){const d={};return o.integrity&&(d.integrity=o.integrity),o.referrerPolicy&&(d.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?d.credentials="include":o.crossOrigin==="anonymous"?d.credentials="omit":d.credentials="same-origin",d}function c(o){if(o.ep)return;o.ep=!0;const d=i(o);fetch(o.href,d)}})();function Ge(...t){return t.filter(Boolean).join(" ")}function ye(t){if(!t&&t!==0)return"";const s=typeof t=="number"?t:new Date(t).getTime();if(Number.isNaN(s))return"";const i=Date.now()-s;return i<0||i<6e4?"just now":i<36e5?`${Math.floor(i/6e4)}m ago`:i<864e5?`${Math.floor(i/36e5)}h ago`:i<7*864e5?`${Math.floor(i/864e5)}d ago`:new Date(s).toLocaleDateString()}function ps(t){if(!t)return"";const s=typeof t=="number"?new Date(t):new Date(t);return Number.isNaN(s.getTime())?"":s.toLocaleString()}function Wn(t,s=160){return t?t.length>s?t.slice(0,s)+"…":t:""}const fs={low:"var(--text-dim)",normal:"var(--info)",high:"var(--error)"},De="bizar-auth-token",it="bizar-loopback-trusted";class Ee extends Error{constructor(i,c,o){super(i);ne(this,"status");ne(this,"data");this.name="ApiError",this.status=c,this.data=o}}class xs{constructor(){ne(this,"base","/api")}getToken(){try{return localStorage.getItem(De)||""}catch{return""}}setToken(s){try{s?localStorage.setItem(De,s):localStorage.removeItem(De)}catch{}}pickupTokenFromUrl(){try{const s=new URLSearchParams(window.location.search),i=s.get("token");if(!i)return!1;this.setToken(i),s.delete("token");const c=s.toString(),o=c?`${window.location.pathname}?${c}`:window.location.pathname;return history.replaceState(null,"",o),!0}catch{return!1}}urlWithToken(s){const i=this.base+s,c=this.getToken();if(!c)return i;const o=i.includes("?")?"&":"?";return`${i}${o}token=${encodeURIComponent(c)}`}async probeAuthStatus(){try{const s=await this.get("/auth/status");try{localStorage.setItem(it,s.loopback?"1":"0")}catch{}return s}catch{return{required:!1,loopback:!0,peer:""}}}isLoopbackTrusted(){try{return localStorage.getItem(it)!=="0"}catch{return!0}}async get(s,i){return this.req("GET",s,void 0,i)}async post(s,i,c){return this.req("POST",s,i,c)}async put(s,i,c){return this.req("PUT",s,i,c)}async patch(s,i,c){return this.req("PATCH",s,i,c)}async del(s,i){return this.req("DELETE",s,void 0,i)}async req(s,i,c,o){const d={"Content-Type":"application/json"},r=this.getToken();r&&(d.Authorization=`Bearer ${r}`);const l={method:s,headers:d};c!=null&&(l.body=typeof c=="string"?c:JSON.stringify(c)),o&&(l.signal=o);const m=await fetch(this.base+i,l);if((m.headers.get("content-type")||"").includes("application/json")){const f=await m.json();if(!m.ok){const v=(f&&typeof f=="object"&&"message"in f?f.message:void 0)||`${s} ${i}: ${m.status}`;throw new Ee(v,m.status,f)}return f}const n=await m.text();if(!m.ok)throw new Ee(`${s} ${i}: ${m.status} — ${n.slice(0,200)}`,m.status,n);try{return JSON.parse(n)}catch{return n}}}const $=new xs;$.pickupTokenFromUrl();async function gs(t){return t}const yt=a.createContext(null),js=["button:not([disabled])","[href]","input:not([disabled])","select:not([disabled])","textarea:not([disabled])",'[tabindex]:not([tabindex="-1"])'].join(", ");function vs(){const t=a.useContext(yt);return t||{open:()=>"",close:()=>{},isModalOpen:!1}}function Hn({children:t}){const[s,i]=a.useState([]),c=a.useCallback(d=>{i(r=>{if(!d)return r.slice(0,-1);const l=r.findIndex(m=>m.id===d);return l===-1||l!==r.length-1?r:r.slice(0,-1)})},[]),o=a.useCallback(d=>{const r=`m${Math.random().toString(36).slice(2,9)}`;return i(l=>[...l,{...d,id:r}]),r},[]);return a.useEffect(()=>{if(s.length===0)return;const d=r=>{r.key==="Escape"&&(r.stopPropagation(),c())};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[s.length,c]),e.jsxs(yt.Provider,{value:{open:o,close:c,isModalOpen:s.length>0},children:[t,typeof document<"u"&&qt.createPortal(e.jsx("div",{className:"modal-stack","aria-hidden":s.length===0,children:s.map((d,r)=>e.jsx(ys,{modal:d,onClose:()=>{var l;(l=d.onClose)==null||l.call(d),c(d.id)},depth:r},d.id))}),document.body)]})}function ys({modal:t,onClose:s,depth:i}){const c=a.useRef(null),o=a.useRef(null),d=a.useId(),r=()=>{const l=c.current;return l?Array.from(l.querySelectorAll(js)).filter(m=>!m.hasAttribute("disabled")&&m.tabIndex!==-1):[]};return a.useEffect(()=>{var x;o.current=document.activeElement instanceof HTMLElement?document.activeElement:null,(x=r()[0]??c.current)==null||x.focus();const m=n=>{var b,k,g;if(n.key!=="Tab")return;const f=r();if(f.length===0){n.preventDefault(),(b=c.current)==null||b.focus();return}const v=f[0],p=f[f.length-1],h=document.activeElement instanceof HTMLElement?document.activeElement:null;if(n.shiftKey){(!h||h===v||!((k=c.current)!=null&&k.contains(h)))&&(n.preventDefault(),p.focus());return}(!h||h===p||!((g=c.current)!=null&&g.contains(h)))&&(n.preventDefault(),v.focus())};return document.addEventListener("keydown",m),()=>{document.removeEventListener("keydown",m);const n=o.current;n&&n.isConnected&&n.focus()}},[]),e.jsx("div",{className:"modal-backdrop",onClick:l=>{l.stopPropagation(),l.target===l.currentTarget&&s()},style:i>0?{background:"rgba(0,0,0,0.4)"}:void 0,children:e.jsxs("div",{ref:c,className:"modal",role:"dialog","aria-modal":"true","aria-labelledby":t.title?d:void 0,tabIndex:-1,onClick:l=>l.stopPropagation(),style:t.width?{maxWidth:t.width}:void 0,children:[t.title&&e.jsxs("header",{className:"modal-header",children:[e.jsx("h2",{id:d,className:"modal-title",children:t.title}),e.jsx("button",{type:"button",className:"icon-btn","aria-label":"Close",onClick:s,children:e.jsx(xe,{size:16})})]}),e.jsx("div",{className:"modal-body",children:t.children}),t.footer&&e.jsx("footer",{className:"modal-footer",children:t.footer})]})})}const ve=a.forwardRef(function({variant:s="secondary",size:i="md",iconOnly:c=!1,loading:o=!1,disabled:d,className:r,children:l,...m},x){return e.jsxs("button",{ref:x,type:m.type??"button",disabled:d||o,className:Ge("btn",`btn-${s}`,`btn-size-${i}`,c&&"btn-icon",o&&"btn-loading",r),...m,children:[o?e.jsx("span",{className:"btn-spinner","aria-hidden":!0}):null,l]})}),Nt=a.createContext(null);function Ns(){const t=a.useContext(Nt);return t||{show:()=>{},info:()=>{},success:()=>{},error:()=>{},warning:()=>{},dismiss:()=>{},toasts:[]}}const ks={info:Yt,success:Vt,error:Ht,warning:Wt};function Vn({children:t}){const[s,i]=a.useState([]),c=a.useRef(1),o=a.useRef(new Map),d=a.useCallback(m=>{i(n=>n.filter(f=>f.id!==m));const x=o.current.get(m);x&&(clearTimeout(x),o.current.delete(m))},[]),r=a.useCallback((m,x="info",n=4e3)=>{const f=c.current++;if(i(v=>[...v,{id:f,kind:x,message:m}]),n>0){const v=setTimeout(()=>d(f),n);o.current.set(f,v)}},[d]);a.useEffect(()=>()=>{for(const m of o.current.values())clearTimeout(m);o.current.clear()},[]);const l=a.useMemo(()=>({show:r,info:(m,x)=>r(m,"info",x),success:(m,x)=>r(m,"success",x),error:(m,x)=>r(m,"error",x),warning:(m,x)=>r(m,"warning",x),dismiss:d,toasts:s}),[r,d,s]);return e.jsxs(Nt.Provider,{value:l,children:[t,e.jsx(ws,{toasts:s,onDismiss:d})]})}function ws({toasts:t,onDismiss:s}){return e.jsx("div",{className:"toast-stack","aria-live":"polite",children:t.map(i=>e.jsx(Ss,{toast:i,onDismiss:s},i.id))})}function Ss({toast:t,onDismiss:s}){const i=ks[t.kind];return e.jsxs("div",{className:`toast toast-${t.kind}`,role:"alert","aria-live":"assertive","aria-atomic":"true",children:[e.jsx(i,{size:16,className:"toast-icon"}),e.jsx("span",{className:"toast-message",children:t.message}),e.jsx("button",{type:"button",className:"toast-close","aria-label":"Dismiss",onClick:()=>s(t.id),children:e.jsx(xe,{size:14})})]})}function Cs(){if(typeof location>"u")return"ws://localhost/ws";const t=`${location.protocol==="https:"?"wss":"ws"}://${location.host}/ws`;let s="";try{s=localStorage.getItem(De)||""}catch{}return s?`${t}?token=${encodeURIComponent(s)}`:t}class kt{constructor(s){ne(this,"urlOverride");ne(this,"handlers",new Set);ne(this,"statusHandlers",new Set);ne(this,"ws",null);ne(this,"reconnectDelay",1e3);ne(this,"maxReconnectDelay",15e3);ne(this,"reconnectTimer",null);ne(this,"_status","connecting");ne(this,"pingTimer",null);ne(this,"closed",!1);this.urlOverride=s,this.connect()}on(s){return this.handlers.add(s),()=>{this.handlers.delete(s)}}onStatus(s){return this.statusHandlers.add(s),s(this._status),()=>{this.statusHandlers.delete(s)}}get status(){return this._status}send(s){return this.ws&&this.ws.readyState===WebSocket.OPEN?(this.ws.send(JSON.stringify(s)),!0):!1}close(){var s;this.closed=!0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.pingTimer&&clearInterval(this.pingTimer),this.pingTimer=null;try{(s=this.ws)==null||s.close()}catch{}this.ws=null,this.setStatus("disconnected")}connect(){if(this.closed)return;this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.setStatus("connecting");const s=this.urlOverride??Cs();let i;try{i=new WebSocket(s),this.ws=i}catch(c){console.warn("[ws] construct failed:",c),this.scheduleReconnect();return}i.addEventListener("open",()=>{this.ws!==i||this.closed||(this.reconnectDelay=1e3,this.setStatus("connected"),this.pingTimer&&clearInterval(this.pingTimer),this.pingTimer=setInterval(()=>{this._status==="connected"&&this.send({type:"ping"})},3e4))}),i.addEventListener("close",()=>{this.ws===i&&(this.ws=null,this.setStatus("disconnected"),this.pingTimer&&(clearInterval(this.pingTimer),this.pingTimer=null),this.closed||this.scheduleReconnect())}),i.addEventListener("error",()=>{this.ws===i&&console.warn("[ws] error")}),i.addEventListener("message",c=>{let o;try{o=JSON.parse(c.data)}catch{console.warn("[ws] bad message");return}for(const d of this.handlers)try{d(o)}catch(r){console.error("[ws] handler error:",r)}})}scheduleReconnect(){this.closed||this.reconnectTimer||(this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},this.reconnectDelay),this.reconnectDelay=Math.min(this.reconnectDelay*1.6,this.maxReconnectDelay))}setStatus(s){this._status=s;for(const i of this.statusHandlers)try{i(s)}catch(c){console.error("[ws] status handler error:",c)}}}const Ts=Object.freeze(Object.defineProperty({__proto__:null,Ws:kt},Symbol.toStringTag,{value:"Module"}));function Oe(t){const s=typeof t=="string"?t:t.mode,i=s==="system"?typeof window<"u"&&window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark":s==="light"?"light":"dark";return typeof document<"u"&&(i==="light"?document.documentElement.setAttribute("data-theme","light"):document.documentElement.removeAttribute("data-theme")),i}function Ie(t){if(typeof document>"u")return;const s=document.documentElement;s.style.setProperty("--accent",t.accent),s.style.setProperty("--success",t.success),s.style.setProperty("--warning",t.warning),s.style.setProperty("--error",t.error),s.style.setProperty("--info",t.info),s.style.setProperty("--accent-bg",lt(t.accent,.12)),s.style.setProperty("--accent-border",lt(t.accent,.4)),t.fontFamily&&s.style.setProperty("--font-sans",`'${t.fontFamily}', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif`),t.fontSize&&s.style.setProperty("--base-font-size",`${t.fontSize}px`),s.dataset.compactMode=t.compactMode?"true":"false",s.dataset.animations=t.animations?"true":"false"}function lt(t,s){const i=/^#?([0-9a-f]{6})$/i.exec(t||"");if(!i)return`rgba(139, 92, 246, ${s})`;const c=parseInt(i[1],16),o=c>>16&255,d=c>>8&255,r=c&255;return`rgba(${o}, ${d}, ${r}, ${s})`}function wt({size:t="md",className:s,label:i}){return e.jsx("span",{className:Ge("spinner",`spinner-${t}`,s),role:"status","aria-label":i||"Loading"})}function Es({items:t,renderItem:s,itemHeight:i=80,height:c=400,overscan:o=5,className:d}){const[r,l]=a.useState(0),m=a.useRef(null),x=a.useMemo(()=>{const p=Math.max(0,Math.floor(r/i)-o),h=Math.min(t.length,Math.ceil((r+c)/i)+o);return{start:p,end:h}},[r,i,c,o,t.length]),n=t.length*i,f=x.start*i,v=t.slice(x.start,x.end);return e.jsx("div",{ref:m,onScroll:p=>l(p.currentTarget.scrollTop),style:{height:c,overflowY:"auto"},className:d,children:e.jsx("div",{style:{height:n,position:"relative"},children:e.jsx("div",{style:{transform:`translateY(${f}px)`},children:v.map((p,h)=>e.jsx("div",{style:{height:i},children:s(p,x.start+h)},x.start+h))})})})}function Is({activeProject:t,sessionCount:s,sessionsOpen:i,infoOpen:c,onToggleSessions:o,onToggleInfo:d,onOpenOverview:r}){return e.jsxs("header",{className:"chat-topbar",children:[e.jsxs("button",{type:"button",className:"chat-topbar-project",onClick:r,children:[e.jsx(Ye,{size:14}),e.jsx("span",{className:"chat-topbar-project-name",children:(t==null?void 0:t.name)??"No project"}),e.jsx(Be,{size:12})]}),e.jsx("div",{className:"chat-topbar-spacer"}),e.jsxs("button",{type:"button",className:`chat-topbar-btn ${i?"active":""}`,onClick:o,"aria-pressed":i,children:["Sessions (",s,")"]}),e.jsx("button",{type:"button",className:`chat-topbar-btn ${c?"active":""}`,onClick:d,"aria-pressed":c,children:"Info"})]})}function $s({icon:t,title:s,message:i,action:c}){return e.jsxs("div",{className:"chat-empty-state",children:[t&&e.jsx("div",{className:"chat-empty-state-icon",children:t}),e.jsx("h2",{className:"chat-empty-state-title",children:s}),e.jsx("p",{className:"chat-empty-state-message",children:i}),c&&e.jsx("div",{className:"chat-empty-state-action",children:c})]})}function As({count:t=3}){return e.jsx("div",{className:"chat-loading-skeleton","aria-label":"Loading messages",children:Array.from({length:t}).map((s,i)=>e.jsxs("div",{className:"chat-loading-skeleton-bubble",children:[e.jsx("div",{className:"chat-loading-skeleton-meta"}),e.jsx("div",{className:"chat-loading-skeleton-line"}),e.jsx("div",{className:"chat-loading-skeleton-line short"})]},i))})}function zs({projectName:t,onPickSuggestion:s}){const i=[{icon:e.jsx(Kt,{size:16}),title:t?`Explain ${t}`:"Explain this project",preview:"Give me a tour of the codebase, highlight the architecture, and call out any anti-patterns or hotspots.",prompt:t?`Explain the ${t} project. Give me a tour of the codebase, highlight the architecture, and call out any anti-patterns or hotspots.`:"Explain the current project. Give me a tour of the codebase, highlight the architecture, and call out any anti-patterns or hotspots."},{icon:e.jsx(Gt,{size:16}),title:"Summarize recent sessions",preview:"Read my last 5 chat sessions and give me a 3-bullet summary of what I worked on and what got stuck.",prompt:"Read my last 5 chat sessions and give me a 3-bullet summary of what I worked on and what got stuck."},{icon:e.jsx(Qt,{size:16}),title:"Suggest a refactor",preview:"Look for the largest, most painful files in this project and propose a concrete refactor for the worst one.",prompt:"Look for the largest, most painful files in this project and propose a concrete refactor for the worst one."},{icon:e.jsx(Jt,{size:16}),title:"Find visual regressions",preview:"Open the dashboard, screenshot the Chat tab, and flag any layout problems or anti-patterns you see.",prompt:"Open the dashboard, screenshot the Chat tab, and flag any layout problems or anti-patterns you see."}];return e.jsx("div",{className:"chat-suggestions",children:i.map((c,o)=>e.jsxs("button",{type:"button",className:"chat-suggestion",onClick:()=>s(c.prompt),children:[e.jsxs("div",{className:"chat-suggestion-title",children:[c.icon,e.jsx("span",{children:c.title})]}),e.jsx("div",{className:"chat-suggestion-preview",children:c.preview})]},o))})}function ot({variant:t,projectName:s,onPickSuggestion:i}){if(t==="no-project")return e.jsxs("div",{className:"chat-welcome",children:[e.jsx("h1",{className:"chat-welcome-h1",children:e.jsx("span",{className:"chat-greeting-hello",children:"No project selected."})}),e.jsx("p",{className:"chat-welcome-subtitle",children:"Pick a project in Overview to scope chat sessions."})]});const c=s||"there";return e.jsxs("div",{className:"chat-welcome",children:[e.jsxs("h1",{className:"chat-welcome-h1",children:[e.jsx("span",{className:"chat-greeting-hello",children:"Hello, "}),e.jsxs("span",{className:"chat-greeting-name",children:[c,"."]})]}),e.jsx("p",{className:"chat-welcome-subtitle",children:"How can I help you today?"}),e.jsx(zs,{projectName:s,onPickSuggestion:i})]})}function Rs({message:t,pinned:s,onCopy:i,onDelete:c,onTogglePin:o,onRegenerate:d}){const r=(t.role||"assistant").toLowerCase(),l=t.ts?ps(t.ts):"",m=t.content||t.message||"",x=r==="user";return e.jsxs("article",{className:`chat-message ${x?"chat-message-user":"chat-message-assistant"} ${s?"chat-message-pinned":""}`,children:[e.jsxs("header",{className:"chat-message-meta",children:[e.jsx("span",{className:"chat-message-role",children:r}),t.agent&&e.jsxs("span",{className:"chat-message-agent",children:["@",t.agent]}),l&&e.jsx("time",{className:"chat-message-time",children:l}),s&&e.jsx("span",{className:"chat-message-pin",children:"pinned"}),e.jsxs("div",{className:"chat-message-actions",children:[e.jsx("button",{type:"button",className:"chat-msg-action-btn",onClick:i,title:"Copy","aria-label":"Copy",children:e.jsx(Xt,{size:12})}),!x&&e.jsx("button",{type:"button",className:"chat-msg-action-btn",onClick:d,title:"Regenerate","aria-label":"Regenerate",children:e.jsx(re,{size:12})}),e.jsx("button",{type:"button",className:"chat-msg-action-btn",onClick:o,title:"Pin","aria-label":"Pin",children:e.jsx(Zt,{size:12})}),e.jsx("button",{type:"button",className:"chat-msg-action-btn chat-msg-action-btn-danger",onClick:c,title:"Delete","aria-label":"Delete",children:e.jsx(ke,{size:12})})]})]}),e.jsx("div",{className:"chat-message-content markdown-body",children:e.jsx(hs,{remarkPlugins:[bs],children:m})})]})}function Ds({messages:t,loading:s,activeProject:i,sessionId:c,pinned:o,activeSource:d,onPickSuggestion:r,onCopy:l,onDelete:m,onTogglePin:x,onRegenerate:n}){const f=a.useRef(null);a.useEffect(()=>{const p=f.current;if(!p)return;let h=p.parentElement,b=!1;for(;h;){if(h.classList.contains("chat-thread-scroll")){b=!0;break}h=h.parentElement}b||(p.scrollTop=p.scrollHeight)},[t]);const v=d==="opencode"?"opencode":"bizar";return s?e.jsx("div",{className:"chat-thread legacy",ref:f,"data-stream":v,children:e.jsx(As,{count:3})}):i?t.length===0?e.jsx("div",{className:"chat-thread legacy",ref:f,"data-stream":v,children:e.jsx(ot,{variant:"empty",projectName:i.name,onPickSuggestion:r})}):e.jsx("div",{className:"chat-thread legacy",ref:f,children:e.jsx(Es,{items:t,itemHeight:120,height:800,className:"chat-thread-virtual",renderItem:(p,h)=>e.jsx(Rs,{message:p,pinned:o.has(h),onCopy:()=>l(p),onDelete:()=>m(h),onTogglePin:()=>x(h),onRegenerate:()=>n(String(p.ts??h))})})}):e.jsx("div",{className:"chat-thread legacy",ref:f,"data-stream":v,children:e.jsx(ot,{variant:"no-project",projectName:"",onPickSuggestion:r})})}function Ms({agent:t,setAgent:s,agents:i}){const[c,o]=a.useState(!1),d=a.useRef(null);a.useEffect(()=>{if(!c)return;const m=x=>{d.current&&!d.current.contains(x.target)&&o(!1)};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[c]);const r=t||"no agent",l=r.startsWith("@")?r.slice(1):r;return e.jsxs("div",{className:"chat-agent-chip",ref:d,children:[e.jsxs("button",{type:"button",className:"chat-agent-chip-btn",onClick:()=>o(m=>!m),"aria-haspopup":"listbox","aria-expanded":c,children:[e.jsx(we,{size:14}),e.jsx("span",{children:l}),e.jsx(Be,{size:12,className:c?"rotated":""})]}),c&&e.jsxs("div",{className:"chat-agent-chip-menu",role:"listbox",children:[e.jsx("button",{type:"button",role:"option","aria-selected":!t,onClick:()=>{s(""),o(!1)},children:e.jsx("span",{children:"no agent"})}),i.map(m=>e.jsx("button",{type:"button",role:"option","aria-selected":t===m.name,onClick:()=>{s(m.name),o(!1)},children:e.jsxs("span",{children:["@",m.name]})},m.name))]})]})}function Ls(t,s,i=240){a.useLayoutEffect(()=>{const c=t.current;if(!c)return;c.style.height="auto";const o=Math.min(c.scrollHeight,i);c.style.height=`${o}px`,c.style.overflowY=c.scrollHeight>i?"auto":"hidden"},[t,s,i])}function Ps({agent:t,setAgent:s,model:i,setModel:c,text:o,setText:d,sending:r,onSend:l,attachments:m,setAttachments:x,suggestions:n,onPickSuggestion:f,agents:v,onAttach:p}){const h=a.useRef(null),b=a.useRef(null);Ls(h,o,160);const k=u=>{if(u.key==="Enter"&&(u.metaKey||u.ctrlKey))u.preventDefault(),l();else if(u.key==="Enter"&&!u.shiftKey)u.preventDefault(),l();else if(u.key==="Tab"&&n.length){u.preventDefault();const S=n[0].cmd.split(" ")[0];d(`${S} `)}},g=u=>{const S=u.target.files;if(!S)return;const C=[];for(let _=0;_<S.length;_++)C.push(S[_].name);x(_=>[..._,...C]),u.target.value=""};return e.jsxs("div",{className:"chat-composer",children:[n.length>0&&e.jsx("div",{className:"chat-composer-suggestions",children:n.map(u=>e.jsxs("button",{type:"button",className:"chat-composer-suggestion",onClick:()=>{var C;const S=u.cmd.split(" ")[0];d(`${S} `),(C=h.current)==null||C.focus()},children:[e.jsx("span",{className:"mono",children:u.cmd}),e.jsx("span",{children:u.desc})]},u.cmd))}),m.length>0&&e.jsx("div",{className:"chat-composer-attachments",children:m.map((u,S)=>e.jsxs("span",{className:"chat-composer-attachment-tag",children:[e.jsx(Ze,{size:10})," ",u,e.jsx("button",{type:"button",className:"chat-composer-attachment-remove",onClick:()=>x(C=>C.filter((_,O)=>O!==S)),"aria-label":`Remove ${u}`,children:e.jsx(xe,{size:10})})]},S))}),e.jsxs("div",{className:"chat-composer-input",children:[e.jsx(Ms,{agent:t,setAgent:s,agents:v}),e.jsx("textarea",{ref:h,className:"chat-composer-textarea",placeholder:r?"Sending…":"Send a message…",rows:1,value:o,onChange:u=>d(u.target.value),onKeyDown:k,disabled:r,"aria-label":"Message"}),e.jsx("input",{ref:b,type:"file",multiple:!0,style:{display:"none"},onChange:g,"aria-label":"Attach files",tabIndex:-1}),e.jsx("button",{type:"button",className:"chat-attach-btn",onClick:p,title:"Attach files","aria-label":"Attach files",children:e.jsx(Ze,{size:14})}),e.jsx("button",{type:"button",className:"chat-attach-btn",onClick:async()=>{if(!o.trim())return;const u=await gs(o);u!==o&&d(u)},title:"Enhance prompt with AI","aria-label":"Enhance prompt",children:e.jsx(Me,{size:14})}),e.jsx("button",{type:"button",className:"chat-send-btn",onClick:l,disabled:r||!o.trim(),title:"Send (Enter)","aria-label":"Send message",children:e.jsx(xt,{size:16})})]})]})}const Os="modulepreload",Bs=function(t){return"/"+t},ct={},St=function(s,i,c){let o=Promise.resolve();if(i&&i.length>0){document.getElementsByTagName("link");const r=document.querySelector("meta[property=csp-nonce]"),l=(r==null?void 0:r.nonce)||(r==null?void 0:r.getAttribute("nonce"));o=Promise.allSettled(i.map(m=>{if(m=Bs(m),m in ct)return;ct[m]=!0;const x=m.endsWith(".css"),n=x?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${m}"]${n}`))return;const f=document.createElement("link");if(f.rel=x?"stylesheet":Os,x||(f.as="script"),f.crossOrigin="",f.href=m,l&&f.setAttribute("nonce",l),document.head.appendChild(f),x)return new Promise((v,p)=>{f.addEventListener("load",v),f.addEventListener("error",()=>p(new Error(`Unable to preload CSS for ${m}`)))})}))}function d(r){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=r,window.dispatchEvent(l),!l.defaultPrevented)throw r}return o.then(r=>{for(const l of r||[])l.status==="rejected"&&d(l.reason);return s().catch(d)})};function Us(t,s,i){const[c,o]=a.useState([]),[d,r]=a.useState([]),[l,m]=a.useState(""),[x,n]=a.useState(!0),[f,v]=a.useState({create:!1,send:!1,rename:!1,delete:!1}),[p,h]=a.useState([]),[b,k]=a.useState([]),[g,u]=a.useState(null),[S,C]=a.useState(null),[_,O]=a.useState(null),[I,L]=a.useState(null),[j,w]=a.useState(null),[y,R]=a.useState({}),[B,z]=a.useState(!0),[G,le]=a.useState(0),[te,ge]=a.useState(new Set),[Se,Ue]=a.useState(new Set),me=a.useRef(null),K=a.useRef(null),Z=a.useRef(null),je=a.useRef(0),ee=a.useRef(null),ue=a.useRef(null),de=a.useRef(!1),T=a.useCallback(N=>{N&&k(A=>{if(N.id&&A.some(D=>D.id===N.id))return A;const E=A.findIndex(D=>typeof D.id=="string"&&D.id.startsWith("msg_")&&D.role===N.role&&(D.content||"")===(N.content||""));if(E>=0){const D=A.slice();return D[E]={...N,id:N.id??A[E].id},D}return[...A,N]})},[]),W=a.useCallback(N=>{N&&ge(A=>{if(A.has(N))return A;const E=new Set(A);return E.add(N),E})},[]),U=a.useCallback((N,A)=>{R(E=>{const D=E[N]??{state:"idle",unread:0,pinned:!1};return{...E,[N]:{...D,...A}}})},[]),Y=a.useCallback((N,A)=>{U(N,{state:A?"streaming":"idle"})},[U]),Ce=a.useCallback(N=>{K.current=N},[]),oe=a.useCallback(async N=>{var A;try{const E=N?`/chat?session=${encodeURIComponent(N)}`:"/chat?limit=200",D=await $.get(E);o(D.messages||[]),r(D.sessions||[])}catch(E){(A=K.current)==null||A.error(`Chat load failed: ${E.message}`)}finally{n(!1)}},[]),$e=a.useCallback(async N=>{var A;n(!0);try{const E=await $.get(`/tasks/${encodeURIComponent(N)}/chat`);o(E.messages||[]),m(E.sessionId||N)}catch(E){(A=K.current)==null||A.error(`Task chat load failed: ${E.message}`)}finally{n(!1)}},[]),Fe=a.useCallback(async()=>{try{const N=await $.get("/chat/sessions");r(N.sessions||[])}catch{}},[]),Ae=a.useCallback(async()=>{try{const A=((await $.get("/opencode-sessions")).sessions||[]).map(E=>({...E,source:"opencode",title:E.title||E.id}));h(A)}catch{}},[]),Je=a.useCallback(N=>{if(Z.current){try{Z.current.close()}catch{}Z.current=null}ee.current!==null&&(clearTimeout(ee.current),ee.current=null);const A=$.getToken(),E=A?`/api/opencode-sessions/${encodeURIComponent(N)}/stream?token=${encodeURIComponent(A)}`:`/api/opencode-sessions/${encodeURIComponent(N)}/stream`;ue.current=N,de.current=!0,je.current=0,O(null),L(null),w(null);const D=()=>{if(!de.current||ue.current!==N)return;const M=new EventSource(E);Z.current=M;const H=P=>{var Q,se,ae,he;if(!P||!P.type||P.sessionID&&P.sessionID!==N)return;const q=new Date().toISOString(),V=N;if(P.type==="message.user.created"||P.type==="message.user.updated"){const F=P.data;T({id:(F==null?void 0:F.messageID)??P.messageID,role:"user",content:((Q=F==null?void 0:F.data)==null?void 0:Q.content)??"",ts:q}),W((F==null?void 0:F.messageID)??P.messageID);return}if(P.type==="message.assistant.created"||P.type==="message.assistant.updated"){const F=P.data;T({id:(F==null?void 0:F.messageID)??P.messageID,role:"assistant",content:((se=F==null?void 0:F.data)==null?void 0:se.content)??"",ts:q}),W((F==null?void 0:F.messageID)??P.messageID),Y(V,!0);return}if(P.type==="message.part.updated"){const F=P.data,Xe=((ae=F==null?void 0:F.part)==null?void 0:ae.text)??"";if(!Xe)return;T({id:(F==null?void 0:F.id)??(F==null?void 0:F.messageID)??P.messageID,role:"assistant",content:Xe,ts:q}),W((F==null?void 0:F.id)??(F==null?void 0:F.messageID)??P.messageID),Y(V,!0);return}if(P.type==="session.idle"||P.type==="message.assistant.completed"||P.type==="session.completed"){Y(V,!1);return}if(P.type==="session.awaiting"||P.type==="session.awaiting_input"||P.type==="message.assistant.awaiting"){U(V,{state:"awaiting"});return}if(P.type==="session.error"){O(((he=P.data)==null?void 0:he.message)||"opencode session error");return}},J=P=>{if(!P)return null;try{const q=JSON.parse(P);if(typeof q.type=="string"){const V=q.properties,Q=q.data??V,se=typeof q.sessionID=="string"?q.sessionID:typeof(V==null?void 0:V.sessionID)=="string"?V.sessionID:typeof(Q==null?void 0:Q.sessionID)=="string"?Q.sessionID:void 0,ae=typeof q.messageID=="string"?q.messageID:typeof(V==null?void 0:V.messageID)=="string"?V.messageID:typeof(Q==null?void 0:Q.messageID)=="string"?Q.messageID:void 0;let he=q.type;const F=/\.\d+$/.exec(he);return F&&(he=he.slice(0,F.index)),{type:he,sessionID:se,messageID:ae,data:q}}if(q.type==="sync"&&q.syncEvent&&typeof q.syncEvent=="object"){const V=q.syncEvent;let Q=V.type||"";const se=/\.\d+$/.exec(Q);se&&(Q=Q.slice(0,se.index));const ae=V.data||{};return{type:Q,sessionID:typeof ae.sessionID=="string"?ae.sessionID:void 0,messageID:typeof ae.messageID=="string"?ae.messageID:void 0,data:V}}return null}catch{return null}},X=["message.user.created","message.user.updated","message.assistant.created","message.assistant.updated","message.part.updated","session.idle","message.assistant.completed","session.completed","session.awaiting","session.awaiting_input","message.assistant.awaiting","session.error"];for(const P of X)M.addEventListener(P,q=>{H(J(q.data))});M.onerror=()=>{if(ue.current!==N)return;if(!de.current){try{M.close()}catch{}Z.current=null;return}try{M.close()}catch{}Z.current=null;const P=je.current+1;je.current=P;const q=Math.min(3e4,1e3*2**(P-1));ee.current!==null&&clearTimeout(ee.current),ee.current=window.setTimeout(()=>{ee.current=null,de.current&&ue.current===N&&D()},q)},M.onopen=()=>{je.current=0,O(null),L(null),w(null)}};D()},[T,W,Y,U]),Te=a.useCallback(()=>{if(de.current=!1,ue.current=null,ee.current!==null&&(clearTimeout(ee.current),ee.current=null),Z.current){try{Z.current.close()}catch{}Z.current=null}k([]),ge(new Set),O(null),L(null),w(null),C(null),u("bizar")},[]),ze=a.useCallback(async N=>{var A;if(de.current=!1,Z.current){try{Z.current.close()}catch{}Z.current=null}ee.current!==null&&(clearTimeout(ee.current),ee.current=null),O(null),L(null),w(null),n(!0);try{const E=await $.get(`/opencode-sessions/${encodeURIComponent(N)}/messages`);k(E.messages||[])}catch(E){const D=E.message;let M=null;if(E instanceof Ee&&E.data&&typeof E.data=="object"){const H=E.data,J=H.error||"unknown",X=J!=="bad_request"&&J!=="too_many_subscribers"&&J!=="unauthorized";M={type:"session_load_failed",code:J,message:H.message||D,cause:H.cause,status:H.status,suggestion:H.suggestion??null,canRetry:X}}else E instanceof Ee&&(M={type:"session_load_failed",code:"unknown",message:D,suggestion:null,canRetry:!0});O(M?`Opencode session load failed (${M.code}): ${M.message}`:`Opencode session load failed: ${D}`),L((M==null?void 0:M.suggestion)??null),w(M),(A=K.current)==null||A.error(M?`Opencode session load failed: ${M.message}`:`Opencode session load failed: ${D}`),k([])}finally{n(!1)}C(N),u("opencode"),Y(N,!1),Je(N)},[Y,Je]),$t=a.useCallback(N=>{Te(),m(N),u("bizar"),oe(N),U(N,{unread:0})},[Te,oe,U]),At=a.useCallback(async()=>{var A,E,D,M,H;if(f.create)return{ok:!1};const N=s.defaultAgent||"odin";v(J=>({...J,create:!0}));try{try{const X=await $.post("/opencode-sessions/new",{agent:N});return await Ae(),await ze(X.id),(A=K.current)==null||A.success(`Session ${X.id} created.`),{ok:!0,source:"opencode",id:X.id}}catch(X){if(!(X instanceof Ee)||X.status!==503)return(E=K.current)==null||E.error(`Create failed: ${X.message}`),{ok:!1}}if(!t.activeProject)return(D=K.current)==null||D.error("Pick a project in Overview to scope chat sessions."),{ok:!1};const J=await $.post("/chat/sessions",{});return m(J.id),o([]),Ue(new Set),U(J.id,{state:"idle",unread:0}),await oe(J.id),Fe().catch(()=>{}),(M=K.current)==null||M.success(`Session ${J.id} created.`),{ok:!0,source:"bizar",id:J.id}}catch(J){return(H=K.current)==null||H.error(`Create failed: ${J.message}`),{ok:!1}}finally{v(J=>({...J,create:!1}))}},[f.create,s.defaultAgent,t.activeProject,Ae,ze,oe,Fe,U]),zt=a.useCallback(async(N,A,E,D)=>{var J,X,P;if(f.send)return{ok:!1};const M=N.trim();if(!M)return{ok:!1};if(g==="opencode"&&S){const q=S,V=`msg_${Date.now().toString(36)}${Math.random().toString(36).slice(2,8)}`,Q={id:V,role:"user",content:M,agent:A,ts:new Date().toISOString()};T(Q),W(V),v(se=>({...se,send:!0}));try{return await $.post(`/opencode-sessions/${encodeURIComponent(q)}/send`,{message:M,agent:A}),Y(q,!0),{ok:!0}}catch(se){return k(ae=>ae.filter(he=>he.id!==V)),(J=K.current)==null||J.error(`Send failed: ${se.message}`),{ok:!1}}finally{v(se=>({...se,send:!1}))}}const H={role:"user",content:M,agent:A,ts:new Date().toISOString()};o(q=>[...q,H]),v(q=>({...q,send:!0})),Y(l,!0);try{const q=await $.post("/chat",{message:M,agent:A,model:E,attachments:D||[]});if(q!=null&&q.messages)for(const V of q.messages)V.role==="assistant"&&o(Q=>Q.some(ae=>ae.ts===V.ts)?Q:[...Q,V]);else(X=K.current)==null||X.info("Still processing… the response will appear shortly.");return{ok:!0}}catch(q){return o(V=>V.filter(Q=>Q!==H)),(P=K.current)==null||P.error(`Send failed: ${q.message}`),{ok:!1}}finally{v(q=>({...q,send:!1})),Y(l,!1)}},[g,S,T,W,Y,l,f.send]),Rt=a.useCallback(async N=>{var A,E;if(!l){(A=K.current)==null||A.error("No active session to regenerate.");return}try{await $.post("/chat/regenerate",{sessionId:l,messageId:N}),await oe(l)}catch(D){(E=K.current)==null||E.error(`Regenerate failed: ${D.message}`)}},[l,oe]),Dt=a.useCallback(N=>{g==="opencode"?k(A=>A.filter((E,D)=>D!==N)):o(A=>A.filter((E,D)=>D!==N))},[g]),Mt=a.useCallback(N=>{Ue(A=>{const E=new Set(A);return E.has(N)?E.delete(N):E.add(N),E})},[]),Lt=a.useCallback(N=>{var E,D;const A=N.content||N.message||"";try{(E=navigator.clipboard)==null||E.writeText(A).then(()=>{var M;return(M=K.current)==null?void 0:M.success("Copied.")},()=>{var M;return(M=K.current)==null?void 0:M.error("Copy failed.")})}catch{(D=K.current)==null||D.error("Copy failed.")}},[]),Pt=a.useCallback(()=>{const N=me.current;if(!N)return;const E=N.scrollHeight-N.scrollTop-N.clientHeight<32;z(E),E&&le(0)},[]),Ot=a.useCallback(()=>{const N=me.current;N&&(N.scrollTop=N.scrollHeight,z(!0),le(0))},[]),Bt=a.useCallback(async(N,A)=>{var E,D,M;if(f.rename)return!1;v(H=>({...H,rename:!0}));try{const H=A.trim();return H?(p.some(X=>X.id===N)?(await $.patch(`/opencode-sessions/${encodeURIComponent(N)}`,{title:H}),h(X=>X.map(P=>P.id===N?{...P,title:H}:P))):(await $.post(`/chat/sessions/${encodeURIComponent(N)}/rename`,{title:H}),r(X=>X.map(P=>P.id===N?{...P,title:H}:P))),(D=K.current)==null||D.success("Renamed."),!0):((E=K.current)==null||E.error("Title cannot be empty."),!1)}catch(H){return(M=K.current)==null||M.error(`Rename failed: ${H.message}`),!1}finally{v(H=>({...H,rename:!1}))}},[f.rename,p]),Ut=a.useCallback(async N=>{var A,E;if(f.delete)return!1;v(D=>({...D,delete:!0}));try{return p.some(M=>M.id===N)?(await $.del(`/opencode-sessions/${encodeURIComponent(N)}`),h(M=>M.filter(H=>H.id!==N)),S===N&&Te()):(await $.del(`/chat/sessions/${encodeURIComponent(N)}`),r(M=>M.filter(H=>H.id!==N)),l===N&&(m(""),o([]))),R(M=>{const H={...M};return delete H[N],H}),(A=K.current)==null||A.success("Session deleted."),!0}catch(D){return(E=K.current)==null||E.error(`Delete failed: ${D.message}`),!1}finally{v(D=>({...D,delete:!1}))}},[f.delete,p,S,Te,l]);return a.useEffect(()=>{me.current&&(B?me.current.scrollTop=me.current.scrollHeight:le(N=>N+1))},[c,b]),a.useEffect(()=>()=>{if(de.current=!1,ue.current=null,ee.current!==null&&(clearTimeout(ee.current),ee.current=null),Z.current){try{Z.current.close()}catch{}Z.current=null}},[]),a.useEffect(()=>{i?$e(i):oe(),Ae()},[]),a.useEffect(()=>{const N=A=>{var D;const E=(D=A.detail)==null?void 0:D.taskId;E&&$e(E)};return window.addEventListener("bizar:setChatTask",N),()=>window.removeEventListener("bizar:setChatTask",N)},[$e]),a.useEffect(()=>{let N=!1;return St(async()=>{const{Ws:A}=await Promise.resolve().then(()=>Ts);return{Ws:A}},void 0).then(({Ws:A})=>{if(N)return;new A().on(D=>{if(D.type!=="chat:message")return;const M=D.message;M&&o(H=>H.some(X=>X.ts===M.ts)?H:[...H,M])})}),()=>{N=!0}},[]),{messages:g==="opencode"?b:c,bizarMessages:c,opencodeMessages:b,sessions:d,opencodeSessions:p,sessionId:l,setSessionId:m,loading:x,sending:f.send,pinned:Se,listRef:me,activeSource:g,activeOpencodeSessionId:S,opencodeError:_,opencodeSuggestion:I,opencodeErrorInfo:j,retryOpencodeSession:()=>{S&&ze(S)},sessionStates:y,busy:f,getSessionDisplay:N=>{var A,E,D,M;return{...N,state:((A=y[N.id])==null?void 0:A.state)??"idle",unread:((E=y[N.id])==null?void 0:E.unread)??0,pinned:((D=y[N.id])==null?void 0:D.pinned)??!1,tree:(M=y[N.id])==null?void 0:M.tree}},stickToBottom:B,newMessageCount:G,handleScroll:Pt,jumpToLatest:Ot,setToast:Ce,loadChat:oe,loadTaskChat:$e,refreshSessions:Fe,refreshOpencodeSessions:Ae,loadOpencodeSession:ze,closeOpencodeSession:Te,selectBizarSession:$t,onCreateSession:At,onSend:zt,onRegenerate:Rt,deleteMessage:Dt,togglePin:Mt,copyMessage:Lt,renameSession:Bt,deleteSession:Ut,seenOpencodeMessages:te}}const Fs=[{cmd:"/visual-plan [on|off|status]",desc:"Toggle or view visual plan mode"},{cmd:"/plan new <slug> [template]",desc:"Create a new plan"},{cmd:"/plan list",desc:"List all plans"},{cmd:"/plan open <slug>",desc:"Open a plan in the viewer"},{cmd:"/plan status <slug> <status>",desc:"Set plan status"},{cmd:"/plan get <slug>",desc:"Fetch plan canvas"},{cmd:"/plan add <slug> --title T --type kind",desc:"Add element to a plan"},{cmd:"/plan update <slug> <id>",desc:"Update a plan element"},{cmd:"/plan delete <slug> <id>",desc:"Delete a plan element"},{cmd:'/plan comment <slug> [id] "text"',desc:"Add a comment"},{cmd:"/plan comments <slug> [id]",desc:"Read plan comments"},{cmd:"/bizar",desc:"Launch Bizar dashboard"},{cmd:"/bizar <args>",desc:"Route via Bizar menu"},{cmd:"/audit",desc:"Run security audit"},{cmd:"/explain <q>",desc:"Read-only code Q&A"},{cmd:"/init",desc:"Initialize .bizar/ in this project"},{cmd:"/learn",desc:"Extract patterns from session"},{cmd:"/pr-review",desc:"PR review"},{cmd:"/help | /commands",desc:"Show all Bizar commands"}];function _s(t){const[s,i]=a.useState(""),c=a.useMemo(()=>[...Fs,...(t.mods||[]).flatMap(d=>{var r;return(r=d.entry)!=null&&r.command?[{cmd:`/${d.id}`,desc:d.description||d.name,mod:d.id}]:[]})],[t.mods]),o=a.useMemo(()=>{if(!s.startsWith("/")||s.includes(" "))return[];const d=s.toLowerCase();return c.filter(r=>r.cmd.toLowerCase().startsWith(d)).slice(0,6)},[s,c]);return{allCommands:c,suggestions:o,setQuery:i}}function qs({tabs:t,activeTab:s,onChange:i}){return e.jsx("nav",{className:"mobile-bottom-nav",role:"navigation","aria-label":"Mobile navigation",children:t.map(c=>{const o=c.icon;return e.jsxs("button",{type:"button",className:Ge("mobile-nav-btn",s===c.id&&"mobile-nav-btn-active"),onClick:()=>i(c.id),"aria-label":c.label,"aria-current":s===c.id?"page":void 0,children:[e.jsx(o,{size:22}),e.jsx("span",{className:"mobile-nav-label",children:c.label})]},c.id)})})}function ce({open:t,onClose:s,title:i,children:c,actions:o,maxHeight:d="85vh"}){const r=a.useRef(null),l=a.useRef(null),m=a.useId(),x=a.useRef(null),n=a.useRef(null),f=a.useRef(0),v=a.useRef(0),p=()=>{var g;return((g=r.current)==null?void 0:g.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'))??[]};if(a.useEffect(()=>{if(!t)return;x.current=document.activeElement instanceof HTMLElement?document.activeElement:null;const g=u=>{var I;if(u.key==="Escape"&&s(),u.key!=="Tab")return;const S=Array.from(p());if(S.length===0){u.preventDefault(),(I=r.current)==null||I.focus();return}const C=S[0],_=S[S.length-1],O=document.activeElement;if(u.shiftKey){(!O||O===C||O===r.current)&&(u.preventDefault(),_==null||_.focus());return}O===_&&(u.preventDefault(),C==null||C.focus())};return window.addEventListener("keydown",g),requestAnimationFrame(()=>{var u,S;((u=l.current)==null?void 0:u.focus())??((S=r.current)==null||S.focus())}),()=>{var u;window.removeEventListener("keydown",g),(u=x.current)==null||u.focus()}},[t,s]),a.useEffect(()=>(t?(v.current=window.scrollY,document.documentElement.style.overflow="hidden",document.body.style.overflow="hidden",document.body.style.position="fixed",document.body.style.top=`-${v.current}px`,document.body.style.left="0",document.body.style.right="0",document.body.style.width="100%"):(document.documentElement.style.overflow="",document.body.style.overflow="",document.body.style.position="",document.body.style.top="",document.body.style.left="",document.body.style.right="",document.body.style.width=""),()=>{document.documentElement.style.overflow="",document.body.style.overflow="",document.body.style.position="",document.body.style.top="",document.body.style.left="",document.body.style.right="",document.body.style.width="",window.scrollTo(0,v.current)}),[t]),!t)return null;const h=g=>{var u;g.isPrimary&&(n.current=g.clientY,f.current=0,(u=r.current)==null||u.setPointerCapture(g.pointerId))},b=g=>{if(n.current==null||!r.current)return;const u=Math.max(0,g.clientY-n.current);f.current=u,r.current.style.transform=`translateY(${u}px)`},k=g=>{if(!r.current)return;g&&r.current.hasPointerCapture(g.pointerId)&&r.current.releasePointerCapture(g.pointerId);const u=f.current;r.current.style.transform="",n.current=null,f.current=0,u>72&&s()};return e.jsx("div",{className:"mobile-sheet-overlay",onClick:s,children:e.jsxs("div",{ref:r,className:"mobile-sheet",style:{maxHeight:d},onClick:g=>g.stopPropagation(),role:"dialog","aria-modal":!0,"aria-label":i?void 0:"Sheet","aria-labelledby":i?m:void 0,tabIndex:-1,children:[e.jsx("div",{className:"mobile-sheet-handle",onPointerDown:h,onPointerMove:b,onPointerUp:k,onPointerCancel:k,"aria-hidden":"true"}),e.jsxs("div",{className:"mobile-sheet-header",children:[i?e.jsx("h3",{id:m,className:"mobile-sheet-title",children:i}):e.jsx("div",{}),e.jsx("button",{ref:l,type:"button",className:"mobile-icon-btn",onClick:s,"aria-label":"Close",children:e.jsx(xe,{size:18})})]}),e.jsx("div",{className:"mobile-sheet-content",children:c}),o&&e.jsx("div",{className:"mobile-sheet-actions",children:o})]})})}function Ws(t){switch(t){case"success":return"✓";case"error":return"✗";case"warning":return"⚠";default:return"ℹ"}}function Hs(t){const s=new Date(t),c=Date.now()-s.getTime();return c<6e4?"just now":c<36e5?`${Math.floor(c/6e4)}m ago`:c<864e5?`${Math.floor(c/36e5)}h ago`:s.toLocaleDateString()}function Vs({onSelect:t}){const[s,i]=a.useState(!1),[c,o]=a.useState([]),[d,r]=a.useState(0),l=async()=>{var n;try{const f=await $.get("/notifications");o(f.notifications||[]),r(((n=f.stats)==null?void 0:n.unread)||0)}catch{}};a.useEffect(()=>{l()},[]),a.useEffect(()=>{s&&l()},[s]);const m=async()=>{try{await $.post("/notifications/read-all"),o(n=>n.map(f=>({...f,read:!0}))),r(0)}catch{}},x=async n=>{try{await $.post(`/notifications/${encodeURIComponent(n)}/read`),o(f=>f.map(v=>v.id===n?{...v,read:!0}:v)),r(f=>Math.max(0,f-1))}catch{}};return e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",className:"mobile-icon-btn mobile-notif-btn",onClick:()=>i(!0),"aria-label":`Notifications${d>0?` (${d} unread)`:""}`,children:[e.jsx(et,{size:20}),d>0&&e.jsx("span",{className:"mobile-notif-badge",children:d>9?"9+":d})]}),e.jsx(ce,{open:s,onClose:()=>i(!1),title:"Notifications",actions:d>0?e.jsxs("button",{type:"button",className:"mobile-btn mobile-btn-secondary",style:{width:"100%"},onClick:m,children:[e.jsx(es,{size:14})," Mark all read"]}):void 0,children:e.jsxs("div",{className:"mobile-notif-list",children:[c.length===0&&e.jsxs("div",{className:"mobile-empty",children:[e.jsx(et,{size:32}),e.jsx("p",{children:"No notifications"})]}),c.map(n=>e.jsxs("button",{type:"button",className:`mobile-notif-item ${n.read?"read":"unread"}`,onClick:()=>{n.read||x(n.id),t(n),i(!1)},children:[e.jsx("span",{className:`mobile-notif-icon severity-${n.severity}`,children:Ws(n.severity)}),e.jsxs("div",{className:"mobile-notif-body",children:[e.jsx("span",{className:"mobile-notif-title",children:n.title||n.message}),n.message&&n.title&&e.jsx("span",{className:"mobile-notif-text",children:n.message}),e.jsx("span",{className:"mobile-notif-time",children:Hs(n.ts)})]}),!n.read&&e.jsx("span",{className:"mobile-notif-dot"})]},n.id))]})})]})}const Ys={activity:"Activity",chat:"Chat",tasks:"Tasks",settings:"Settings",more:"More",plans:"Plans",agents:"Agents",skills:"Skills",mods:"Mods",schedules:"Schedules",history:"History",config:"Config","plan-detail":"Plan","agent-detail":"Agent","task-detail":"Task"};function Ks({activeTab:t,snapshot:s,onSearch:i,onNavigate:c}){const[o,d]=a.useState(!1),r=async l=>{try{await $.post(`/projects/${encodeURIComponent(l)}/activate`),d(!1),window.location.reload()}catch{}};return e.jsxs("header",{className:"mobile-topbar",children:[e.jsxs("div",{className:"mobile-topbar-left",children:[e.jsx("span",{className:"mobile-logo",children:"ᛒ"}),(s==null?void 0:s.activeProject)&&e.jsxs("button",{type:"button",className:"mobile-project-btn",onClick:()=>d(!0),"aria-label":"Select project",children:[e.jsx("span",{className:"mobile-project-name",children:s.activeProject.name}),e.jsx(Be,{size:14})]}),e.jsx("span",{className:"mobile-title",children:Ys[t]||"Bizar"})]}),e.jsxs("div",{className:"mobile-topbar-right",children:[e.jsx("button",{type:"button",className:"mobile-icon-btn",onClick:i,"aria-label":"Search",children:e.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("circle",{cx:"11",cy:"11",r:"8"}),e.jsx("path",{d:"m21 21-4.35-4.35"})]})}),e.jsx(Vs,{onSelect:l=>{c("notification",l.link||"",l.meta??null)}}),(s==null?void 0:s.activeProject)&&e.jsx(ce,{open:o,onClose:()=>d(!1),title:"Projects",children:e.jsx("div",{className:"mobile-project-list",children:(s.projects||[]).map(l=>{var m,x;return e.jsxs("button",{type:"button",className:`mobile-project-item ${l.id===((m=s.activeProject)==null?void 0:m.id)?"active":""}`,onClick:()=>r(l.id),children:[e.jsx("div",{className:"mobile-project-status","data-status":l.status}),e.jsxs("div",{className:"mobile-project-info",children:[e.jsx("span",{className:"mobile-project-item-name",children:l.name}),e.jsx("span",{className:"mobile-project-item-path",children:l.path})]}),l.id===((x=s.activeProject)==null?void 0:x.id)&&e.jsx("span",{className:"mobile-active-badge",children:"active"})]},l.id)})})})]})]})}const Gs=["all","tasks","agents","bg","artifacts","mods"],_e={all:"All",tasks:"Tasks",agents:"Agents",bg:"Background",artifacts:"Plans",mods:"Mods"};function Qs({snapshot:t,onRefresh:s}){var L;const[i,c]=a.useState(((L=t.overview)==null?void 0:L.recentActivity)||[]),[o,d]=a.useState(!0),[r,l]=a.useState("all"),[m,x]=a.useState(!1),[n,f]=a.useState(null),[v,p]=a.useState(""),[h,b]=a.useState(!1);a.useEffect(()=>{var j;(j=t.overview)!=null&&j.recentActivity?(c(t.overview.recentActivity),d(!1)):k()},[t.overview]);const k=async()=>{var j;try{const w=await $.get("/snapshot");c(((j=w.overview)==null?void 0:j.recentActivity)||[])}catch{}finally{d(!1)}},g=r==="all"?i:i.filter(j=>{var w,y,R,B,z,G;return r==="tasks"?(w=j.kind)==null?void 0:w.startsWith("task"):r==="agents"?(y=j.kind)==null?void 0:y.startsWith("agent"):r==="bg"?((R=j.kind)==null?void 0:R.includes("bg"))||((B=j.kind)==null?void 0:B.includes("schedule")):r==="artifacts"?(z=j.kind)==null?void 0:z.includes("artifacts"):r==="mods"?(G=j.kind)==null?void 0:G.includes("mod"):!0}),u=t.agents||[],S=t.tasks||[],C=S.filter(j=>j.status==="doing"||j.status==="queued"),_=S.filter(j=>j.status==="done"),O=async()=>{if(!(!v.trim()||h)){b(!0);try{await $.post("/chat",{message:v.trim(),agent:"odin"}),p(""),await s().catch(()=>{}),await k()}catch{}finally{b(!1)}}},I=async()=>{await s().catch(()=>{}),await k()};return e.jsxs("div",{className:"mobile-view",children:[e.jsxs("div",{className:"mobile-submit-hero",children:[e.jsx("textarea",{className:"mobile-submit-input",placeholder:"What needs to be done? Describe a task, bug, or refactor for Odin to artifacts…",value:v,onChange:j=>p(j.target.value),rows:2}),e.jsxs("div",{className:"mobile-submit-actions",children:[e.jsx("div",{className:"mobile-submit-chips",children:["Implement feature","Fix bug","Refactor","Investigate","Write tests"].map(j=>e.jsx("button",{type:"button",className:"mobile-submit-chip",onClick:()=>p(w=>w?`${w} ${j}`:j),children:j},j))}),e.jsxs("button",{type:"button",className:"mobile-btn",disabled:!v.trim()||h,onClick:O,children:[e.jsx(xt,{size:14})," Submit to Odin"]})]})]}),e.jsxs("div",{className:"mobile-stats",children:[e.jsxs("div",{className:"mobile-stat",children:[e.jsx("div",{className:"mobile-stat-value",children:u.length}),e.jsx("div",{className:"mobile-stat-label",children:"Agents"})]}),e.jsxs("div",{className:"mobile-stat",children:[e.jsx("div",{className:"mobile-stat-value",children:C.length}),e.jsx("div",{className:"mobile-stat-label",children:"Active"})]}),e.jsxs("div",{className:"mobile-stat",children:[e.jsx("div",{className:"mobile-stat-value",children:_.length}),e.jsx("div",{className:"mobile-stat-label",children:"Done"})]}),e.jsxs("div",{className:"mobile-stat",children:[e.jsx("div",{className:"mobile-stat-value",children:t.artifacts.length||0}),e.jsx("div",{className:"mobile-stat-label",children:"Plans"})]})]}),o&&i.length===0&&e.jsx("div",{className:"mobile-loading mobile-loading-inline",children:e.jsx("p",{children:"Loading activity…"})}),e.jsxs("div",{className:"mobile-activity-header",children:[e.jsx("h3",{className:"mobile-section-title",style:{margin:0},children:"Recent Activity"}),e.jsxs("div",{style:{display:"flex",gap:4},children:[e.jsx("button",{type:"button",className:"mobile-icon-btn",onClick:()=>x(j=>!j),"aria-label":m?"Resume":"Pause",children:m?e.jsx(Le,{size:14}):e.jsx(ts,{size:14})}),e.jsx("button",{type:"button",className:"mobile-icon-btn",onClick:I,"aria-label":"Refresh",children:e.jsx(re,{size:14})})]})]}),e.jsx("div",{className:"mobile-search-scopes",children:Gs.map(j=>e.jsx("button",{type:"button",className:`mobile-scope-chip ${r===j?"active":""}`,onClick:()=>l(j),children:_e[j]},j))}),u.length>0&&e.jsxs("section",{className:"mobile-section",children:[e.jsxs("h3",{className:"mobile-section-title",children:[e.jsx(we,{size:14})," Agents"]}),e.jsx("div",{className:"mobile-card-list",children:u.slice(0,6).map(j=>e.jsxs("div",{className:"mobile-agent-card",children:[e.jsx("div",{className:"mobile-agent-dot","data-status":j.status||"idle"}),e.jsxs("div",{className:"mobile-agent-info",children:[e.jsx("span",{className:"mobile-agent-name",children:j.name}),e.jsx("span",{className:"mobile-agent-meta",children:j.status||"idle"})]})]},j.name))})]}),!m&&g.length>0&&e.jsx("section",{className:"mobile-section",children:e.jsx("div",{className:"mobile-card-list",children:g.slice(0,30).map((j,w)=>e.jsxs("button",{type:"button",className:"mobile-event-item",onClick:()=>f(j),children:[e.jsx("span",{className:"mobile-event-kind","data-kind":j.kind,children:_e[j.kind]||j.kind}),e.jsx("span",{className:"mobile-event-msg",children:Js(j)}),e.jsx("span",{className:"mobile-event-time",children:ye(j.ts)})]},`${j.ts}-${j.kind}-${w}`))})}),!m&&g.length===0&&i.length>0&&e.jsxs("div",{className:"mobile-empty",children:[e.jsx(We,{size:40}),e.jsx("p",{children:"No matching activity."}),e.jsx("p",{className:"muted",children:"Try a different filter."})]}),n&&e.jsx(ce,{open:!0,onClose:()=>f(null),title:_e[n.kind]||n.kind,children:e.jsxs("div",{className:"mobile-agent-detail-meta",children:[e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Kind"}),e.jsx("span",{children:n.kind})]}),e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Time"}),e.jsx("span",{children:new Date(n.ts).toLocaleString()})]}),Object.entries(n).filter(([j])=>!["ts","kind"].includes(j)).map(([j,w])=>e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:j}),e.jsx("span",{style:{fontSize:12,maxWidth:200,wordBreak:"break-all"},children:typeof w=="object"?JSON.stringify(w):String(w)})]},j))]})}),u.length===0&&C.length===0&&e.jsxs("div",{className:"mobile-empty",children:[e.jsx(We,{size:40}),e.jsx("p",{children:"No activity yet."}),e.jsx("p",{className:"muted",children:"Start a task or chat to see things here."})]})]})}function Js(t){const s=t.kind||"";return s.includes("task")?`Task: ${t.title||t.id||"updated"}`:s.includes("agent")?`Agent: ${t.name||"status changed"}`:s.includes("artifacts")?`Plan: ${t.slug||"changed"}`:s.includes("mod")?`Mod: ${t.name||"changed"}`:s.includes("schedule")?`Schedule: ${t.name||"triggered"}`:JSON.stringify(t).slice(0,80)}function be({open:t,onClose:s,title:i,children:c,actions:o}){const d=a.useRef(null),r=a.useRef(null),l=a.useRef(null),m=a.useId(),x=a.useRef(0);return a.useEffect(()=>{if(!t)return;l.current=document.activeElement instanceof HTMLElement?document.activeElement:null;const n='button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',f=v=>{var g,u;if(v.key==="Escape"&&s(),v.key!=="Tab")return;const p=Array.from(((g=d.current)==null?void 0:g.querySelectorAll(n))??[]);if(p.length===0){v.preventDefault(),(u=d.current)==null||u.focus();return}const h=p[0],b=p[p.length-1],k=document.activeElement;if(v.shiftKey){(!k||k===h||k===d.current)&&(v.preventDefault(),b==null||b.focus());return}k===b&&(v.preventDefault(),h==null||h.focus())};return window.addEventListener("keydown",f),x.current=window.scrollY,document.documentElement.style.overflow="hidden",document.body.style.overflow="hidden",document.body.style.position="fixed",document.body.style.top=`-${x.current}px`,document.body.style.left="0",document.body.style.right="0",document.body.style.width="100%",requestAnimationFrame(()=>{var v,p;((v=r.current)==null?void 0:v.focus())??((p=d.current)==null||p.focus())}),()=>{var v;window.removeEventListener("keydown",f),document.documentElement.style.overflow="",document.body.style.overflow="",document.body.style.position="",document.body.style.top="",document.body.style.left="",document.body.style.right="",document.body.style.width="",window.scrollTo(0,x.current),(v=l.current)==null||v.focus()}},[t,s]),t?e.jsx("div",{className:"mobile-modal-overlay",onClick:n=>{n.target===n.currentTarget&&s()},children:e.jsxs("div",{ref:d,className:"mobile-modal",onClick:n=>n.stopPropagation(),role:"dialog","aria-modal":!0,"aria-label":i?void 0:"Modal","aria-labelledby":i?m:void 0,tabIndex:-1,children:[e.jsxs("div",{className:"mobile-modal-header",children:[i?e.jsx("h2",{id:m,className:"mobile-modal-title",children:i}):e.jsx("div",{}),e.jsx("button",{ref:r,type:"button",className:"mobile-icon-btn",onClick:s,"aria-label":"Close",children:e.jsx(xe,{size:20})})]}),e.jsx("div",{className:"mobile-modal-content",children:c}),o&&e.jsx("div",{className:"mobile-modal-actions",children:o})]})}):null}const Ct=["reasoning","code","design","planning","gitops","analysis"],rt={reasoning:"var(--accent)",code:"var(--info)",design:"var(--success)",planning:"var(--warning)",gitops:"var(--error)",analysis:"var(--text-dim)"};function dt({snapshot:t,onBack:s,onOpenAgent:i,selectedAgent:c,onRefresh:o}){const[d,r]=a.useState(t.agents||[]),[l,m]=a.useState(!t.agents),[x,n]=a.useState(""),[f,v]=a.useState(""),[p,h]=a.useState(null),[b,k]=a.useState(!1),[g,u]=a.useState(""),[S,C]=a.useState(!1);a.useEffect(()=>{if(c){const y=d.find(R=>R.name===c);y&&h(y)}},[c,d]);const _=async()=>{try{const y=await $.get("/agents");r(y.agents||[])}catch{}finally{m(!1)}},O=d.filter(y=>{if(x&&y.category!==x)return!1;if(f){const R=f.toLowerCase();if(!y.name.toLowerCase().includes(R)&&!(y.description||"").toLowerCase().includes(R))return!1}return!0}),I=async(y,R)=>{try{await $.post(`/agents/${encodeURIComponent(y)}/invoke`,{prompt:R}),C(!1),u("")}catch{}},L=async y=>{try{await $.post(`/agents/${encodeURIComponent(y)}/restart`),await _()}catch{}},j=async y=>{if(confirm(`Delete agent "${y}"?`))try{await $.del(`/agents/${encodeURIComponent(y)}`),r(R=>R.filter(B=>B.name!==y)),h(null),o==null||o()}catch{}},w=async y=>{try{const R=await $.post("/agents",y);r(B=>[...B,R]),k(!1),o==null||o()}catch{}};return e.jsxs("div",{className:"mobile-view",children:[e.jsxs("div",{className:"mobile-tasks-toolbar",children:[e.jsx("input",{className:"mobile-search-input",type:"text",placeholder:"Search agents…",value:f,onChange:y=>v(y.target.value),style:{flex:1}}),e.jsx("button",{type:"button",className:"mobile-icon-btn",onClick:()=>_(),"aria-label":"Refresh",children:e.jsx(re,{size:16})}),e.jsx("button",{type:"button",className:"mobile-icon-btn",onClick:()=>k(!0),"aria-label":"New agent",children:e.jsx(ie,{size:16})})]}),e.jsxs("div",{className:"mobile-search-scopes",children:[e.jsx("button",{type:"button",className:`mobile-scope-chip ${x?"":"active"}`,onClick:()=>n(""),children:"All"}),Ct.map(y=>e.jsx("button",{type:"button",className:`mobile-scope-chip ${x===y?"active":""}`,onClick:()=>n(y),children:y},y))]}),l?e.jsx("div",{className:"mobile-loading",children:e.jsx("p",{children:"Loading…"})}):O.length===0?e.jsxs("div",{className:"mobile-empty",children:[e.jsx(we,{size:40}),e.jsx("p",{children:"No agents found."})]}):e.jsx("div",{className:"mobile-card-list",children:O.map(y=>e.jsxs("button",{type:"button",className:"mobile-list-item mobile-list-item-interactive",onClick:()=>{h(y),i(y.name)},children:[e.jsx("div",{className:"mobile-agent-dot","data-status":y.status||"idle"}),e.jsxs("div",{className:"mobile-list-content",children:[e.jsx("span",{className:"mobile-list-title",children:y.name}),e.jsx("span",{className:"mobile-list-meta",children:y.model||y.mode||"—"})]}),y.category&&e.jsx("span",{className:"mobile-list-badge",style:{color:rt[y.category]||"var(--text-dim)"},children:y.category}),e.jsx("span",{className:"mobile-list-badge","data-status":y.status||"idle",children:y.status||"idle"})]},y.name))}),p&&e.jsx(ce,{open:!0,onClose:()=>h(null),title:p.name,actions:e.jsxs("div",{className:"mobile-task-detail-actions",children:[e.jsxs("button",{type:"button",className:"mobile-btn",onClick:()=>{u(""),C(!0)},children:[e.jsx(Le,{size:14})," Invoke"]}),(p.isStuck||p.status==="error"||p.status==="working")&&e.jsxs("button",{type:"button",className:"mobile-btn mobile-btn-secondary",onClick:()=>L(p.name),children:[e.jsx(ss,{size:14})," Restart"]}),e.jsx("button",{type:"button",className:"mobile-btn mobile-btn-danger",onClick:()=>j(p.name),children:e.jsx(ke,{size:14})})]}),children:e.jsxs("div",{className:"mobile-agent-detail",children:[e.jsxs("div",{className:"mobile-agent-detail-status",children:[e.jsx("span",{className:"mobile-agent-dot","data-status":p.status||"idle"}),e.jsx("span",{className:"mobile-agent-detail-status-text",children:p.status||"idle"}),p.category&&e.jsx("span",{className:"mobile-list-badge",style:{color:rt[p.category]},children:p.category})]}),e.jsx("p",{className:"mobile-agent-detail-desc",children:p.description||"No description."}),e.jsxs("div",{className:"mobile-agent-detail-meta",children:[e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Model"}),e.jsx("span",{className:"mono",children:p.model||"—"})]}),e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Mode"}),e.jsx("span",{children:p.mode||"subagent"})]}),e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Path"}),e.jsx("span",{className:"mono",style:{fontSize:11},children:p.path})]}),p.lastError&&e.jsxs("div",{className:"mobile-task-detail-row",style:{color:"var(--error)"},children:[e.jsx("span",{children:"Last error"}),e.jsx("span",{children:p.lastError.message})]}),p.tasksTotal!=null&&p.tasksTotal>0&&e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Success rate"}),e.jsxs("span",{children:[Math.round((p.successRate||0)*100),"%"]})]}),e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Last modified"}),e.jsx("span",{children:ye(p.mtime)})]})]})]})}),e.jsxs(be,{open:S,onClose:()=>C(!1),title:`Invoke ${p==null?void 0:p.name}`,actions:e.jsxs("button",{type:"button",className:"mobile-btn",style:{width:"100%"},disabled:!g.trim(),onClick:()=>{p&&I(p.name,g.trim())},children:[e.jsx(Le,{size:14})," Invoke"]}),children:[e.jsxs("p",{className:"muted",style:{marginBottom:12},children:["Model: ",e.jsx("span",{className:"mono",children:(p==null?void 0:p.model)||"—"})]}),e.jsx("textarea",{className:"mobile-input",rows:5,placeholder:"What should this agent do?",value:g,onChange:y=>u(y.target.value),autoFocus:!0})]}),e.jsx(Xs,{open:b,onClose:()=>k(!1),onCreate:w})]})}function Xs({open:t,onClose:s,onCreate:i}){const[c,o]=a.useState(""),[d,r]=a.useState(""),[l,m]=a.useState(""),[x,n]=a.useState("subagent"),[f,v]=a.useState("#8b5cf6"),[p,h]=a.useState(""),[b,k]=a.useState(""),[g,u]=a.useState(""),S=C=>{C.preventDefault(),c.trim()&&(i({name:c.trim(),description:d.trim(),model:l,mode:x,color:f,tools:[],tags:b.split(",").map(_=>_.trim()).filter(Boolean),category:p,prompt:g}),o(""),r(""),m(""),n("subagent"),v("#8b5cf6"),h(""),k(""),u(""))};return e.jsx(be,{open:t,onClose:s,title:"New Agent",actions:e.jsxs("button",{type:"submit",form:"new-agent-form",className:"mobile-btn",style:{width:"100%"},children:[e.jsx(ie,{size:14})," Create"]}),children:e.jsxs("form",{id:"new-agent-form",onSubmit:S,className:"mobile-task-form",children:[e.jsx("label",{className:"mobile-field-label",children:"Name *"}),e.jsx("input",{className:"mobile-input",type:"text",placeholder:"my-agent",pattern:"[a-z0-9][a-z0-9-]{0,63}",value:c,onChange:C=>o(C.target.value),autoFocus:!0,required:!0}),e.jsx("label",{className:"mobile-field-label",children:"Description"}),e.jsx("input",{className:"mobile-input",type:"text",placeholder:"What does this agent do?",value:d,onChange:C=>r(C.target.value)}),e.jsx("label",{className:"mobile-field-label",children:"Model"}),e.jsx("input",{className:"mobile-input",type:"text",placeholder:"(provider default)",value:l,onChange:C=>m(C.target.value)}),e.jsx("label",{className:"mobile-field-label",children:"Category"}),e.jsxs("select",{className:"mobile-input",value:p,onChange:C=>h(C.target.value),children:[e.jsx("option",{value:"",children:"None"}),Ct.map(C=>e.jsx("option",{value:C,children:C},C))]}),e.jsx("label",{className:"mobile-field-label",children:"Tags (comma-separated)"}),e.jsx("input",{className:"mobile-input",type:"text",placeholder:"tag1, tag2",value:b,onChange:C=>k(C.target.value)})]})})}function Zs({sessions:t,opencodeSessions:s,activeSessionId:i,activeOpencodeSessionId:c,activeProject:o,creating:d,onCreateSession:r,onSelectSession:l,onSelectOpencodeSession:m}){const[x,n]=a.useState("all"),[f,v]=a.useState(!1),p=30,h=x==="all"?[...t,...s].sort((u,S)=>Number(S.mtime)-Number(u.mtime)):t,b=f?h:h.slice(0,p),k=s.length,g=u=>{if(u.source==="opencode"){m(u);return}l(u.id)};return e.jsxs("div",{className:"chat-sessions",children:[e.jsxs("div",{className:"chat-sessions-header",children:[e.jsx("span",{className:"chat-sessions-header-title",children:"Sessions"}),e.jsx("span",{className:"chat-sessions-count",children:b.length})]}),k>0&&e.jsxs("div",{className:"chat-sessions-toggle",children:[e.jsx("button",{type:"button",className:`chat-sessions-toggle-btn ${x==="bizar"?"active":""}`,onClick:()=>n("bizar"),children:"Bizar"}),e.jsxs("button",{type:"button",className:`chat-sessions-toggle-btn ${x==="all"?"active":""}`,onClick:()=>n("all"),children:["All (",k," opencode)"]})]}),e.jsxs("button",{type:"button",className:"chat-sessions-new",onClick:r,disabled:d||!o,title:o?"Create new session":"Pick a project first","aria-label":"Create new session",children:[d?e.jsx(wt,{size:"sm"}):e.jsx(ie,{size:14}),e.jsx("span",{children:d?"Creating…":"New session"})]}),t.length===0?e.jsx("div",{className:"chat-sessions-empty",children:e.jsx($s,{icon:e.jsx(Me,{size:20}),title:o?"No sessions yet":"No project",message:o?"Create your first session to start chatting.":"Pick a project in Overview to scope chat sessions.",action:o?e.jsxs(ve,{variant:"primary",size:"sm",onClick:r,loading:d,children:[e.jsx(ie,{size:12})," New session"]}):e.jsxs(ve,{variant:"secondary",size:"sm",onClick:()=>{window.location.hash="#overview"},children:[e.jsx(Ye,{size:12})," Open Overview"]})})}):e.jsx("ul",{className:"chat-sessions-list",children:b.map(u=>{const S=u.source==="opencode",C=S?c===u.id:i===u.id;return e.jsxs("li",{className:`chat-sessions-item ${C?"active":""} ${S?"chat-sessions-item-opencode":""}`,onClick:()=>g(u),title:S?`Open in dashboard: ${u.title||u.id}`:u.id,children:[S&&e.jsx(ns,{size:10,className:"chat-sessions-item-icon"}),e.jsx("span",{className:"chat-sessions-item-id",children:u.title||u.id}),e.jsx("span",{className:"chat-sessions-item-meta",children:new Date(Number(u.mtime)).toLocaleDateString()})]},S?`oc-${u.id}`:u.id)})}),h.length>p&&e.jsx("button",{type:"button",className:"chat-sessions-show-more",onClick:()=>v(u=>!u),children:f?`Show less (${h.length-p} hidden)`:`Show all ${h.length} sessions`})]})}function en(t){const{activeSource:s}=t;return e.jsx("div",{className:`chat-composer-wrap chat-composer-source-${s??"none"} legacy`,children:e.jsx("div",{className:"chat-composer-pill",children:e.jsx(Ps,{...t})})})}function tn({sessionId:t,messages:s,pinned:i,agent:c,model:o,agents:d,mcps:r,allCommands:l,activeSource:m="bizar",onRename:x,onDelete:n}){const[f,v]=a.useState(!1),[p,h]=a.useState(!1),b=f?d:d.slice(0,4),k=p?l:l.slice(0,4),g=o.includes("/")?o.split("/")[0]:"";return e.jsxs("div",{className:"chat-info",children:[e.jsxs("div",{className:"chat-info-card",children:[e.jsxs("div",{className:"chat-info-card-title",children:[e.jsx(pe,{size:14})," Session",e.jsx("span",{className:`chat-source-badge chat-source-${m??"none"}`,style:{marginLeft:"auto"},children:m==="opencode"?"opencode":"bizar chat"})]}),e.jsxs("dl",{className:"env-table",children:[e.jsx("dt",{children:"id"}),e.jsx("dd",{className:"mono",children:t||"Live"}),e.jsx("dt",{children:"Messages"}),e.jsx("dd",{className:"mono",children:s.length}),e.jsx("dt",{children:"Pinned"}),e.jsx("dd",{className:"mono",children:i.size}),e.jsx("dt",{children:"Agent"}),e.jsx("dd",{className:"mono",children:c||"—"}),e.jsx("dt",{children:"Model"}),e.jsx("dd",{className:"mono ellipsis",title:o,children:o||"—"}),g&&e.jsxs(e.Fragment,{children:[e.jsx("dt",{children:"Provider"}),e.jsx("dd",{className:"mono",children:g})]})]}),(x||n)&&e.jsxs("div",{className:"chat-info-actions",children:[x&&e.jsxs("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:x,children:[e.jsx(Ke,{size:12,"aria-hidden":!0})," Rename"]}),n&&e.jsxs("button",{type:"button",className:"btn btn-ghost btn-danger btn-sm",onClick:n,children:[e.jsx(ke,{size:12,"aria-hidden":!0})," Delete"]})]})]}),e.jsxs("div",{className:"chat-info-card",children:[e.jsxs("div",{className:"chat-info-card-title",children:[e.jsx(we,{size:14})," Agents",e.jsx("span",{className:"chat-info-card-count",children:d.length})]}),e.jsx("ul",{className:"mod-mini-list",children:b.map(u=>e.jsxs("li",{className:"mod-mini",children:[e.jsxs("span",{className:"mod-mini-name",children:["@",u.name]}),e.jsx("span",{className:"mod-mini-meta",children:u.model||u.mode||""})]},u.name))}),d.length>4&&e.jsx("button",{type:"button",className:"chat-info-card-toggle",onClick:()=>v(u=>!u),children:f?"− Show fewer":`+ ${d.length-4} more`})]}),e.jsxs("div",{className:"chat-info-card",children:[e.jsxs("div",{className:"chat-info-card-title",children:[e.jsx(as,{size:14})," MCPs",e.jsx("span",{className:"chat-info-card-count",children:r.length})]}),e.jsxs("ul",{className:"mod-mini-list",children:[r.length===0?e.jsx("li",{className:"muted",children:"No MCPs configured."}):null,r.map(u=>e.jsxs("li",{className:"mod-mini",children:[e.jsx("span",{className:"mod-mini-name",children:u.id}),e.jsx("span",{className:`mod-mini-pill ${u.enabled?"on":"off"}`,children:u.enabled?"on":"off"})]},u.id))]})]}),e.jsxs("div",{className:"chat-info-card",children:[e.jsxs("button",{type:"button",className:"chat-info-card-title chat-info-card-title-button",onClick:()=>h(u=>!u),"aria-expanded":p,children:[e.jsx(is,{size:14})," Slash commands",e.jsx("span",{className:"chat-info-card-count",children:l.length}),e.jsx(Be,{size:12,className:`chat-info-card-chevron ${p?"open":""}`})]}),p&&e.jsx("ul",{className:"mod-mini-list",children:k.map(u=>e.jsxs("li",{children:[e.jsx("code",{children:u.cmd}),e.jsx("span",{className:"muted",children:u.desc})]},u.cmd))})]})]})}function sn({snapshot:t,settings:s,setActiveTab:i,initialTaskId:c,onClearTaskId:o}){const d=Ns(),r=vs(),l=Us(t,s,c??"");a.useEffect(()=>{l.setToast({error:z=>d.error(z),success:z=>d.success(z),info:z=>d.info(z),warning:z=>d.warning(z)})},[l,d]);const[m,x]=a.useState(""),[n,f]=a.useState(s.defaultAgent||"odin"),[v,p]=a.useState(s.defaultModel||""),[h,b]=a.useState([]),[k,g]=a.useState(!1),[u,S]=a.useState(!1),C=a.useRef(null),{allCommands:_,suggestions:O,setQuery:I}=_s(t);a.useEffect(()=>{I(m)},[m,I]);const L=()=>{var z;return(z=C.current)==null?void 0:z.click()},j=z=>{const G=z.target.files;if(!G)return;const le=[];for(let te=0;te<G.length;te++)le.push(G[te].name);b(te=>{const ge=le.filter(Se=>!te.includes(Se));return[...te,...ge]}),C.current&&(C.current.value="")},w=async()=>{const z=m.trim();if(!z)return;x(""),I(""),(await l.onSend(z,n,v,h)).ok&&l.jumpToLatest()},y=async()=>{l.busy.create||(await l.onCreateSession(),g(!1))},R=z=>{r.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(ve,{variant:"secondary",size:"sm",onClick:()=>r.close(),children:"Cancel"}),e.jsx(ve,{variant:"danger",size:"sm",onClick:()=>{r.close(),l.deleteMessage(z)},children:"Delete"})]})})},B=(z,G)=>{r.open({title:"Delete session?",children:e.jsxs("p",{style:{margin:0},children:["Delete ",e.jsx("strong",{children:G}),"? This cannot be undone."]}),footer:e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[e.jsx(ve,{variant:"secondary",size:"sm",onClick:()=>r.close(),children:"Cancel"}),e.jsx(ve,{variant:"danger",size:"sm",onClick:async()=>{r.close(),await l.deleteSession(z)},children:"Delete"})]})})};return e.jsxs("div",{className:"chat-shell",children:[e.jsx(Is,{activeProject:t.activeProject,sessionCount:l.sessions.length,sessionsOpen:k,infoOpen:u,onToggleSessions:()=>g(z=>!z),onToggleInfo:()=>S(z=>!z),onOpenOverview:()=>i==null?void 0:i("overview")}),e.jsxs("div",{className:"chat-body",children:[e.jsx("aside",{className:`chat-sessions ${k?"":"chat-sessions-hidden"}`,children:e.jsx(Zs,{sessions:l.sessions,opencodeSessions:l.opencodeSessions,activeSessionId:l.sessionId,activeOpencodeSessionId:l.activeOpencodeSessionId,activeProject:t.activeProject,onCreateSession:y,onSelectSession:l.selectBizarSession,onSelectOpencodeSession:z=>l.loadOpencodeSession(z.id),creating:l.busy.create})}),e.jsxs("main",{className:"chat-main",children:[e.jsx(Ds,{messages:l.activeSource==="opencode"?l.opencodeMessages:l.bizarMessages,loading:l.loading,activeProject:t.activeProject,sessionId:l.activeSource==="opencode"?l.activeOpencodeSessionId??l.sessionId:l.sessionId,pinned:l.pinned,activeSource:l.activeSource,onPickSuggestion:z=>x(z),onCopy:z=>l.copyMessage(z),onDelete:R,onTogglePin:l.togglePin,onRegenerate:l.onRegenerate}),e.jsx(en,{agent:n,setAgent:f,model:v,setModel:p,text:m,setText:x,sending:l.sending,activeSource:l.activeSource,onSend:w,attachments:h,setAttachments:b,suggestions:O,onPickSuggestion:z=>x(`${z.split(" ")[0]} `),agents:t.agents||[],onAttach:L,sessionsOpen:k,infoOpen:u}),e.jsx("input",{ref:C,type:"file",multiple:!0,style:{display:"none"},onChange:j})]}),e.jsx("aside",{className:`chat-info ${u?"":"chat-info-hidden"}`,children:e.jsx(tn,{sessionId:l.activeSource==="opencode"?l.activeOpencodeSessionId??l.sessionId:l.sessionId,messages:l.activeSource==="opencode"?l.opencodeMessages:l.bizarMessages,pinned:l.pinned,agent:n,model:v,agents:t.agents||[],mcps:t.mcps||[],allCommands:_,activeSource:l.activeSource,onDelete:()=>{const z=l.activeSource==="opencode"?l.activeOpencodeSessionId:l.sessionId;z&&B(z,z)}})})]})]})}function nn({onBack:t}){const[s,i]=a.useState([]),[c,o]=a.useState(!0),[d,r]=a.useState({}),[l,m]=a.useState(!1),x=async()=>{try{const b=await $.get("/config"),k=Object.entries(b).map(([g,u])=>({key:g,value:u,type:n(u)}));i(k),r(Object.fromEntries(Object.entries(b).map(([g,u])=>[g,u])))}catch{}finally{o(!1)}};a.useEffect(()=>{x()},[]);const n=b=>typeof b=="boolean"?"boolean":typeof b=="number"?"number":typeof b=="string"?"string":Array.isArray(b)?"array":b&&typeof b=="object"?"object":"unknown",f=(b,k)=>{r(g=>({...g,[b]:k}))},v=async()=>{m(!0);try{await $.patch("/config",d),await x()}catch{}finally{m(!1)}},p=(b,k)=>{r(g=>({...g,[b]:k}))},h=b=>{const k=d[b.key];switch(b.type){case"boolean":return e.jsxs("label",{className:"mobile-toggle",children:[e.jsx("input",{type:"checkbox",checked:!!k,onChange:g=>f(b.key,g.target.checked)}),e.jsx("span",{className:"mobile-toggle-slider"})]});case"number":return e.jsx("input",{className:"mobile-input mobile-input-sm",type:"number",inputMode:"numeric",value:String(k??""),onChange:g=>f(b.key,Number(g.target.value))});case"string":return e.jsx("input",{className:"mobile-input mobile-input-sm",type:"text",value:String(k??""),onChange:g=>f(b.key,g.target.value)});case"object":case"array":return e.jsx("textarea",{className:"mobile-input mobile-input-sm",rows:2,value:JSON.stringify(k??null,null,2),onChange:g=>{try{f(b.key,JSON.parse(g.target.value))}catch{}}});default:return e.jsx("span",{className:"mobile-setting-value mono",children:String(k??"null")})}};return e.jsxs("div",{className:"mobile-view",children:[e.jsxs("div",{className:"mobile-tasks-toolbar",children:[e.jsxs("span",{style:{fontSize:14,color:"var(--text-muted)",flex:1},children:[s.length," config entries"]}),e.jsx("button",{type:"button",className:"mobile-icon-btn",onClick:()=>x(),"aria-label":"Refresh",children:e.jsx(re,{size:16})}),e.jsxs("button",{type:"button",className:"mobile-btn",disabled:l,onClick:()=>v(),children:[e.jsx(gt,{size:14})," ",l?"Saving…":"Save all"]})]}),c?e.jsx("div",{className:"mobile-loading",children:e.jsx("p",{children:"Loading…"})}):s.length===0?e.jsxs("div",{className:"mobile-empty",children:[e.jsx(Ne,{size:40}),e.jsx("p",{children:"No config entries."})]}):e.jsx("div",{className:"mobile-config-list",children:s.map(b=>e.jsxs("div",{className:"mobile-config-row",children:[e.jsxs("div",{className:"mobile-config-key",children:[e.jsx("span",{className:"mono",children:b.key}),e.jsx("span",{className:"mobile-config-type",children:b.type})]}),e.jsx("div",{className:"mobile-config-value",children:h(b)}),e.jsx("button",{type:"button",className:"mobile-icon-btn",onClick:()=>p(b.key,b.defaultValue),"aria-label":"Reset to default",title:"Reset",children:e.jsx(ls,{size:14})})]},b.key))})]})}function an({onBack:t}){const[s,i]=a.useState([]),[c,o]=a.useState(!0),[d,r]=a.useState(null),[l,m]=a.useState(""),x=async()=>{try{const p=await $.get("/history");if(Array.isArray(p.history)){i(p.history);return}if(Array.isArray(p.projects)){const h=new Map;for(const b of p.events||[]){const k=b.projectId;if(!k)continue;const g=h.get(k);(!g||new Date(b.ts).getTime()>new Date(g.ts).getTime())&&h.set(k,b)}i(p.projects.map(b=>{const k=h.get(b.id);return{id:b.id,ts:b.lastAccessed||(k==null?void 0:k.ts)||new Date(0).toISOString(),agent:b.name,taskCount:b.tasks.total,summary:`${b.path} · ${b.tasks.done}/${b.tasks.total} done · ${b.plans} plan${b.plans===1?"":"s"}`,output:k?`${k.kind}${k.text?` — ${k.text}`:""}`:"No recent events."}}));return}i([])}catch{}finally{o(!1)}};a.useEffect(()=>{x()},[]);const n=p=>{if(!p)return"—";const h=Math.floor(p/1e3);if(h<60)return`${h}s`;const b=Math.floor(h/60),k=h%60;return`${b}m ${k}s`},f=p=>new Date(p).toLocaleString(),v=l.trim()?s.filter(p=>{const h=l.toLowerCase();return(p.agent||"session").toLowerCase().includes(h)||(p.summary||"").toLowerCase().includes(h)||(p.output||"").toLowerCase().includes(h)}):s;return e.jsxs("div",{className:"mobile-view",children:[e.jsxs("div",{className:"mobile-tasks-toolbar",children:[e.jsx("input",{className:"mobile-search-input",type:"text",placeholder:"Search history…",value:l,onChange:p=>m(p.target.value),style:{flex:1}}),e.jsx("button",{type:"button",className:"mobile-icon-btn",onClick:()=>x(),"aria-label":"Refresh",children:e.jsx(re,{size:16})})]}),c?e.jsx("div",{className:"mobile-loading",children:e.jsx("p",{children:"Loading…"})}):v.length===0?e.jsxs("div",{className:"mobile-empty",children:[e.jsx(He,{size:40}),e.jsx("p",{children:s.length===0?"No history yet.":"No matching sessions."})]}):e.jsx("div",{className:"mobile-card-list",children:v.map(p=>e.jsxs("button",{type:"button",className:"mobile-list-item mobile-list-item-interactive",onClick:()=>r(p),children:[e.jsx("div",{className:"mobile-list-icon",children:e.jsx(He,{size:16})}),e.jsxs("div",{className:"mobile-list-content",children:[e.jsx("span",{className:"mobile-list-title",children:p.agent||"Session"}),e.jsxs("span",{className:"mobile-list-meta",children:[f(p.ts),p.duration?` · ${n(p.duration)}`:"",p.taskCount?` · ${p.taskCount} tasks`:""]})]})]},p.id))}),d&&e.jsxs(ce,{open:!0,onClose:()=>r(null),title:"Session Detail",children:[e.jsxs("div",{className:"mobile-agent-detail-meta",children:[e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Agent"}),e.jsx("span",{children:d.agent||"—"})]}),e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Started"}),e.jsx("span",{children:f(d.ts)})]}),e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Duration"}),e.jsx("span",{children:n(d.duration)})]}),e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Tasks"}),e.jsx("span",{children:d.taskCount||0})]})]}),d.summary&&e.jsxs("div",{style:{marginTop:12},children:[e.jsx("h4",{style:{fontSize:12,color:"var(--text-muted)",marginBottom:4},children:"Summary"}),e.jsx("p",{style:{fontSize:13},children:d.summary})]}),d.output&&e.jsxs("div",{style:{marginTop:12},children:[e.jsx("h4",{style:{fontSize:12,color:"var(--text-muted)",marginBottom:4},children:"Output"}),e.jsxs("pre",{className:"mono",style:{fontSize:11,whiteSpace:"pre-wrap",wordBreak:"break-all",background:"var(--bg-elev-2)",padding:8,borderRadius:6},children:[d.output.slice(0,1e3),d.output.length>1e3?"…":""]})]})]})]})}function ln({snapshot:t,onBack:s}){const[i,c]=a.useState(t.mods||[]),[o,d]=a.useState(!t.mods),[r,l]=a.useState(""),[m,x]=a.useState("all"),[n,f]=a.useState(null),v=async()=>{try{const b=await $.get("/mods");c(b.mods||[])}catch{}finally{d(!1)}};a.useEffect(()=>{t.mods?(c(t.mods),d(!1)):v()},[t.mods]);const p=async(b,k)=>{try{await $.patch(`/mods/${encodeURIComponent(b)}`,{enabled:k}),c(g=>g.map(u=>u.id===b?{...u,enabled:k}:u)),(n==null?void 0:n.id)===b&&f(g=>g&&{...g,enabled:k})}catch{}},h=i.filter(b=>{if(m==="enabled"&&!b.enabled||m==="disabled"&&b.enabled)return!1;if(r){const k=r.toLowerCase();return b.name.toLowerCase().includes(k)||b.description.toLowerCase().includes(k)}return!0});return e.jsxs("div",{className:"mobile-view",children:[e.jsxs("div",{className:"mobile-tasks-toolbar",children:[e.jsx("input",{className:"mobile-search-input",type:"text",placeholder:"Search mods…",value:r,onChange:b=>l(b.target.value),style:{flex:1}}),e.jsx("button",{type:"button",className:"mobile-icon-btn",onClick:()=>v(),"aria-label":"Refresh",children:e.jsx(re,{size:16})})]}),e.jsx("div",{className:"mobile-search-scopes",children:["all","enabled","disabled"].map(b=>e.jsx("button",{type:"button",className:`mobile-scope-chip ${m===b?"active":""}`,onClick:()=>x(b),children:b.charAt(0).toUpperCase()+b.slice(1)},b))}),o?e.jsx("div",{className:"mobile-loading",children:e.jsx("p",{children:"Loading…"})}):h.length===0?e.jsxs("div",{className:"mobile-empty",children:[e.jsx(Ne,{size:40}),e.jsx("p",{children:"No mods found."})]}):e.jsx("div",{className:"mobile-card-list",children:h.map(b=>e.jsxs("button",{type:"button",className:"mobile-list-item mobile-list-item-interactive",onClick:()=>f(b),children:[e.jsx("div",{className:"mobile-list-icon",children:e.jsx(Ne,{size:16})}),e.jsxs("div",{className:"mobile-list-content",children:[e.jsx("span",{className:"mobile-list-title",children:b.name}),e.jsxs("span",{className:"mobile-list-meta",children:["v",b.version," · ",b.author]})]}),e.jsx("span",{className:`mobile-list-badge ${b.enabled?"badge-on":"badge-off"}`,children:b.enabled?"on":"off"})]},b.id))}),n&&e.jsx(ce,{open:!0,onClose:()=>f(null),title:n.name,actions:e.jsx("div",{className:"mobile-task-detail-actions",children:e.jsxs("button",{type:"button",className:"mobile-btn",style:{flex:1},onClick:()=>{n&&p(n.id,!n.enabled)},children:[e.jsx(jt,{size:14})," ",n.enabled?"Disable":"Enable"]})}),children:e.jsxs("div",{className:"mobile-agent-detail",children:[e.jsx("p",{className:"mobile-agent-detail-desc",children:n.description||"No description."}),e.jsxs("div",{className:"mobile-agent-detail-meta",children:[e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Version"}),e.jsx("span",{className:"mono",children:n.version})]}),e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Author"}),e.jsx("span",{children:n.author})]}),e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Bizar"}),e.jsx("span",{className:"mono",children:n.bizar})]}),e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Type"}),e.jsx("span",{children:n.type})]}),e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Permissions"}),e.jsx("span",{children:n.permissions.length})]}),n.installedAt&&e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Installed"}),e.jsx("span",{children:new Date(n.installedAt).toLocaleDateString()})]})]})]})})]})}function on({snapshot:t,onNavigate:s}){var r,l,m;const[i,c]=a.useState(""),o=[{id:"artifacts",icon:fe,label:"Plans",count:t.artifacts.length||0,desc:"Visual artifacts with elements & comments"},{id:"agents",icon:we,label:"Agents",count:((r=t.agents)==null?void 0:r.length)||0,desc:"The Norse pantheon"},{id:"skills",icon:Ne,label:"Skills",count:null,desc:"Agent capabilities & tools"},{id:"mods",icon:Ne,label:"Mods",count:((l=t.mods)==null?void 0:l.length)||0,desc:"Installed modifications"},{id:"schedules",icon:Ve,label:"Schedules",count:((m=t.schedules)==null?void 0:m.length)||0,desc:"Cron jobs & automated tasks"},{id:"history",icon:He,label:"History",count:null,desc:"Past sessions & outputs"},{id:"config",icon:vt,label:"Config",count:null,desc:"Key-value configuration editor"}],d=i.trim()?o.filter(x=>x.label.toLowerCase().includes(i.toLowerCase())||x.desc.toLowerCase().includes(i.toLowerCase())):o;return e.jsxs("div",{className:"mobile-view",children:[e.jsx("div",{className:"mobile-tasks-toolbar",children:e.jsx("input",{className:"mobile-search-input",type:"text",placeholder:"Search…",value:i,onChange:x=>c(x.target.value),style:{flex:1}})}),e.jsx("div",{className:"mobile-card-list",children:d.map(x=>{const n=x.icon;return e.jsxs("button",{type:"button",className:"mobile-more-nav-item",onClick:()=>s(x.id),children:[e.jsx("div",{className:"mobile-more-nav-icon",children:e.jsx(n,{size:20})}),e.jsxs("div",{className:"mobile-more-nav-content",children:[e.jsxs("span",{className:"mobile-more-nav-label",children:[x.label,x.count!=null&&e.jsx("span",{className:"mobile-more-nav-count",children:x.count})]}),e.jsx("span",{className:"mobile-more-nav-desc",children:x.desc})]}),e.jsx(tt,{size:16,className:"mobile-more-nav-arrow"})]},x.id)})}),e.jsx("div",{className:"mobile-more-footer",children:e.jsxs("a",{href:"/?desktop=1",className:"mobile-more-link",children:["Switch to Desktop ",e.jsx(tt,{size:14})]})})]})}const Qe=[{id:"task",label:"Task",color:"var(--info)"},{id:"note",label:"Note",color:"var(--text-dim)"},{id:"decision",label:"Decision",color:"var(--accent)"},{id:"question",label:"Question",color:"var(--warning)"}];function qe(t){var s;return((s=Qe.find(i=>i.id===t))==null?void 0:s.color)||"var(--text-dim)"}function cn({type:t,size:s=12}){switch(t){case"task":return e.jsx(Pe,{size:s,style:{color:"var(--info)"}});case"note":return e.jsx(st,{size:s,style:{color:"var(--text-dim)"}});case"decision":return e.jsx(Pe,{size:s,style:{color:"var(--accent)"}});case"question":return e.jsx(os,{size:s,style:{color:"var(--warning)"}});default:return e.jsx(st,{size:s})}}function rn({slug:t,onBack:s}){const[i,c]=a.useState(null),[o,d]=a.useState(null),[r,l]=a.useState(!0),[m,x]=a.useState(!1),[n,f]=a.useState(null),[v,p]=a.useState(!1),[h,b]=a.useState(!1),[k,g]=a.useState(!1),[u,S]=a.useState(""),C=async()=>{l(!0);try{const j=await $.get(`/plans/${encodeURIComponent(t)}`);c(j.canvas),d(j.meta)}catch{}finally{l(!1)}};a.useEffect(()=>{C()},[t]);const _=async(j,w,y)=>{try{const R=((i==null?void 0:i.elements)||[]).reduce((z,G)=>Math.max(z,G.x||0),40),B=((i==null?void 0:i.elements)||[]).reduce((z,G)=>Math.max(z,G.y||0),40);await $.post(`/plans/${encodeURIComponent(t)}/elements`,{type:j,title:w,content:y,x:20+R,y:20+B,width:240,height:120}),await C(),b(!1)}catch{}},O=async(j,w)=>{try{await $.put(`/plans/${encodeURIComponent(t)}/elements/${encodeURIComponent(j)}`,w),await C(),f(null)}catch{}},I=async j=>{if(confirm("Delete this element?"))try{await $.del(`/plans/${encodeURIComponent(t)}/elements/${encodeURIComponent(j)}`),f(null),await C()}catch{}},L=async(j,w)=>{try{const y=w?`/plans/${encodeURIComponent(t)}/elements/${encodeURIComponent(w)}/comments`:`/plans/${encodeURIComponent(t)}/comments`;await $.post(y,{text:j,elementId:w}),await C(),S(""),g(!1)}catch{}};return r||!i||!o?e.jsx("div",{className:"mobile-view",children:e.jsx("div",{className:"mobile-loading",children:e.jsx("p",{children:"Loading canvas…"})})}):e.jsxs("div",{className:"mobile-view mobile-view-canvas",children:[e.jsxs("div",{className:"mobile-canvas-bar",children:[e.jsxs("div",{className:"mobile-canvas-meta",children:[e.jsx("span",{className:"mobile-canvas-title",children:o.title||t}),e.jsx("span",{className:"mobile-canvas-status","data-status":o.status,children:o.status})]}),e.jsxs("div",{className:"mobile-canvas-actions",children:[e.jsx("button",{type:"button",className:`mobile-icon-btn ${m?"active":""}`,onClick:()=>x(j=>!j),"aria-label":m?"Done editing":"Edit",children:e.jsx(Ke,{size:16})}),e.jsxs("button",{type:"button",className:"mobile-icon-btn",onClick:()=>p(j=>!j),"aria-label":"Comments",children:[e.jsx(pe,{size:16}),i.comments.length>0&&e.jsx("span",{className:"mobile-canvas-comment-count",children:i.comments.length})]}),m&&e.jsx("button",{type:"button",className:"mobile-icon-btn",onClick:()=>b(!0),"aria-label":"Add element",children:e.jsx(ie,{size:16})})]})]}),e.jsxs("div",{className:"mobile-canvas-elements",children:[i.elements.length===0&&e.jsxs("div",{className:"mobile-empty",children:[e.jsx("p",{children:"No elements yet."}),m&&e.jsxs("button",{type:"button",className:"mobile-btn",onClick:()=>b(!0),children:[e.jsx(ie,{size:14})," Add Element"]})]}),i.elements.map(j=>e.jsxs("button",{type:"button",className:`mobile-canvas-element ${(n==null?void 0:n.id)===j.id?"selected":""}`,style:{borderColor:qe(j.type)},onClick:()=>{m&&f(j)},"aria-pressed":(n==null?void 0:n.id)===j.id,children:[e.jsxs("div",{className:"mobile-canvas-el-header",style:{background:`${qe(j.type)}18`},children:[e.jsx(cn,{type:j.type,size:12}),e.jsx("span",{className:"mobile-canvas-el-type",style:{color:qe(j.type)},children:j.type}),j.status&&j.status!=="open"&&e.jsx("span",{className:"mobile-canvas-el-status",children:j.status})]}),e.jsx("div",{className:"mobile-canvas-el-title",children:j.title||"Untitled"}),j.content&&e.jsxs("div",{className:"mobile-canvas-el-content",children:[j.content.slice(0,120),j.content.length>120?"…":""]}),e.jsxs("div",{className:"mobile-canvas-el-comments",children:[e.jsx(pe,{size:10}),i.comments.filter(w=>w.elementId===j.id).length]})]},j.id))]}),v&&e.jsxs("div",{className:"mobile-canvas-comments",children:[e.jsxs("div",{className:"mobile-canvas-comments-header",children:[e.jsxs("h4",{children:["Comments (",i.comments.length,")"]}),e.jsx("button",{type:"button",className:"mobile-icon-btn",onClick:()=>p(!1),children:e.jsx(xe,{size:16})})]}),e.jsxs("div",{className:"mobile-canvas-comment-list",children:[i.comments.length===0&&e.jsx("p",{className:"mobile-empty-inline",children:"No comments yet."}),i.comments.map(j=>e.jsxs("div",{className:"mobile-canvas-comment",children:[e.jsxs("div",{className:"mobile-canvas-comment-head",children:[e.jsx("span",{className:"mono",children:j.author}),e.jsx("span",{className:"muted",children:ye(j.created)})]}),e.jsx("div",{className:"mobile-canvas-comment-text",children:j.text})]},j.id))]}),e.jsxs("div",{className:"mobile-canvas-comment-input",children:[e.jsx("textarea",{className:"mobile-input",rows:2,placeholder:"Add a comment…",value:u,onChange:j=>S(j.target.value)}),e.jsx("button",{type:"button",className:"mobile-btn",disabled:!u.trim(),onClick:()=>{L(u.trim(),null)},children:"Post"})]})]}),n&&e.jsx(ce,{open:!0,onClose:()=>f(null),title:`Edit ${n.title||n.type}`,actions:e.jsxs("div",{className:"mobile-task-detail-actions",children:[e.jsxs("button",{type:"button",className:"mobile-btn mobile-btn-danger",onClick:()=>I(n.id),children:[e.jsx(ke,{size:14})," Delete"]}),e.jsxs("button",{type:"button",className:"mobile-btn",onClick:()=>g(!0),children:[e.jsx(pe,{size:14})," Comment"]})]}),children:e.jsx(dn,{element:n,onSave:j=>O(n.id,j),onClose:()=>f(null)})}),e.jsx(mn,{open:h,onClose:()=>b(!1),onAdd:_}),e.jsx(be,{open:k,onClose:()=>g(!1),title:"Add Comment",actions:e.jsxs("button",{type:"button",className:"mobile-btn",style:{width:"100%"},disabled:!u.trim(),onClick:()=>{L(u.trim(),(n==null?void 0:n.id)||null),g(!1)},children:[e.jsx(pe,{size:14})," Post"]}),children:e.jsx("textarea",{className:"mobile-input",rows:3,placeholder:"Your comment…",value:u,onChange:j=>S(j.target.value),autoFocus:!0})})]})}function dn({element:t,onSave:s,onClose:i}){const[c,o]=a.useState(t.type),[d,r]=a.useState(t.title||""),[l,m]=a.useState(t.content||""),[x,n]=a.useState(t.status||"open");return e.jsxs("form",{className:"mobile-task-form",onSubmit:f=>{f.preventDefault(),s({type:c,title:d,content:l,status:x}),i()},children:[e.jsx("label",{className:"mobile-field-label",children:"Type"}),e.jsx("select",{className:"mobile-input",value:c,onChange:f=>o(f.target.value),children:Qe.map(f=>e.jsx("option",{value:f.id,children:f.label},f.id))}),e.jsx("label",{className:"mobile-field-label",children:"Title"}),e.jsx("input",{className:"mobile-input",type:"text",value:d,onChange:f=>r(f.target.value)}),e.jsx("label",{className:"mobile-field-label",children:"Status"}),e.jsx("input",{className:"mobile-input",type:"text",value:x,onChange:f=>n(f.target.value),placeholder:"open / done / blocked"}),e.jsx("label",{className:"mobile-field-label",children:"Content (markdown)"}),e.jsx("textarea",{className:"mobile-input",rows:4,value:l,onChange:f=>m(f.target.value)}),e.jsx("button",{type:"submit",className:"mobile-btn",style:{width:"100%",marginTop:8},children:"Save"})]})}function mn({open:t,onClose:s,onAdd:i}){const[c,o]=a.useState("task"),[d,r]=a.useState(""),[l,m]=a.useState(""),x=n=>{n.preventDefault(),d.trim()&&(i(c,d.trim(),l.trim()),r(""),m(""))};return e.jsx(be,{open:t,onClose:s,title:"Add Element",actions:e.jsxs("button",{type:"submit",form:"add-el-form",className:"mobile-btn",style:{width:"100%"},children:[e.jsx(ie,{size:14})," Add"]}),children:e.jsxs("form",{id:"add-el-form",onSubmit:x,className:"mobile-task-form",children:[e.jsx("label",{className:"mobile-field-label",children:"Type"}),e.jsx("select",{className:"mobile-input",value:c,onChange:n=>o(n.target.value),children:Qe.map(n=>e.jsx("option",{value:n.id,children:n.label},n.id))}),e.jsx("label",{className:"mobile-field-label",children:"Title *"}),e.jsx("input",{className:"mobile-input",type:"text",placeholder:"Element title",value:d,onChange:n=>r(n.target.value),autoFocus:!0,required:!0}),e.jsx("label",{className:"mobile-field-label",children:"Content (markdown)"}),e.jsx("textarea",{className:"mobile-input",rows:3,placeholder:"Description…",value:l,onChange:n=>m(n.target.value)})]})})}function un({snapshot:t,onBack:s,onOpenArtifact:i}){const[c,o]=a.useState(t.artifacts||[]),[d,r]=a.useState(!t.artifacts),[l,m]=a.useState(""),[x,n]=a.useState(!1),[f,v]=a.useState(""),[p,h]=a.useState(""),b=async()=>{try{const u=await $.get("/artifacts");o(u.artifacts||[])}catch{}finally{r(!1)}},k=async()=>{if(f.trim())try{const u=await $.post("/artifacts",{slug:f.trim(),title:p.trim()||void 0});n(!1),v(""),h(""),i(u.slug)}catch{}},g=l.trim()?c.filter(u=>(u.title||u.slug||"").toLowerCase().includes(l.toLowerCase())):c;return e.jsxs("div",{className:"mobile-view",children:[e.jsxs("div",{className:"mobile-tasks-toolbar",children:[e.jsx("input",{className:"mobile-search-input",type:"text",placeholder:"Search artifacts…",value:l,onChange:u=>m(u.target.value),style:{flex:1}}),e.jsx("button",{type:"button",className:"mobile-icon-btn",onClick:()=>b(),"aria-label":"Refresh",children:e.jsx(re,{size:16})})]}),e.jsx("div",{style:{marginBottom:12},children:e.jsxs("button",{type:"button",className:"mobile-btn",style:{width:"100%"},onClick:()=>n(!0),children:[e.jsx(ie,{size:14})," New Artifact"]})}),d?e.jsx("div",{className:"mobile-loading",children:e.jsx("p",{children:"Loading…"})}):g.length===0?e.jsxs("div",{className:"mobile-empty",children:[e.jsx(fe,{size:40}),e.jsx("p",{children:"No artifacts yet."})]}):e.jsx("div",{className:"mobile-card-list",children:g.map(u=>e.jsxs("button",{type:"button",className:"mobile-list-item mobile-list-item-interactive",onClick:()=>i(u.slug),children:[e.jsx("div",{className:"mobile-list-icon",children:e.jsx(fe,{size:16})}),e.jsxs("div",{className:"mobile-list-content",children:[e.jsx("span",{className:"mobile-list-title",children:u.title||u.slug}),e.jsxs("span",{className:"mobile-list-meta",children:[u.status," · ",u.source,u.elementCount!=null?` · ${u.elementCount} elements`:"",u.commentCount!=null?` · ${u.commentCount} comments`:""]})]}),e.jsx("span",{className:"mobile-list-badge","data-status":u.status,children:u.status})]},u.slug))}),e.jsx(be,{open:x,onClose:()=>n(!1),title:"New Artifact",actions:e.jsxs("button",{type:"submit",form:"new-plan-form",className:"mobile-btn",style:{width:"100%"},children:[e.jsx(ie,{size:14})," Create"]}),children:e.jsxs("form",{id:"new-plan-form",onSubmit:u=>{u.preventDefault(),k()},className:"mobile-task-form",children:[e.jsx("label",{className:"mobile-field-label",children:"Slug *"}),e.jsx("input",{className:"mobile-input",type:"text",placeholder:"my-plan",pattern:"[a-z0-9][a-z0-9-]{0,63}",value:f,onChange:u=>v(u.target.value),autoFocus:!0,required:!0}),e.jsx("label",{className:"mobile-field-label",children:"Title (optional)"}),e.jsx("input",{className:"mobile-input",type:"text",placeholder:"My Artifact",value:p,onChange:u=>h(u.target.value)})]})})]})}const hn=["cron","interval","once"],bn=["command","agent","webhook"],mt=["UTC","America/New_York","America/Los_Angeles","Europe/London","Europe/Berlin","Asia/Tokyo"],Tt=Array.from({length:24},(t,s)=>({value:s,label:s===0?"12 AM":s<12?`${s} AM`:s===12?"12 PM":`${s-12} PM`})),pn=Array.from({length:12},(t,s)=>s*5),Et=[{value:"*",label:"Every day"},{value:"0",label:"Sun"},{value:"1",label:"Mon"},{value:"2",label:"Tue"},{value:"3",label:"Wed"},{value:"4",label:"Thu"},{value:"5",label:"Fri"},{value:"6",label:"Sat"}],fn=[{value:"s",label:"sec"},{value:"m",label:"min"},{value:"h",label:"hr"},{value:"d",label:"day"}];function xn({snapshot:t}){var k;const[s,i]=a.useState(t.schedules||[]),[c,o]=a.useState(!t.schedules),[d,r]=a.useState(""),[l,m]=a.useState(null),[x,n]=a.useState({open:!1}),f=async()=>{try{const g=await $.get("/schedules");i(g.schedules||[])}catch{}finally{o(!1)}};a.useEffect(()=>{t.schedules?(i(t.schedules),o(!1)):f()},[t.schedules]);const v=async(g,u)=>{try{await $.patch(`/schedules/${encodeURIComponent(g)}`,{enabled:u}),i(S=>S.map(C=>C.id===g?{...C,enabled:u}:C)),(l==null?void 0:l.id)===g&&m(S=>S&&{...S,enabled:u})}catch{}},p=async g=>{if(confirm("Delete this schedule?"))try{await $.del(`/schedules/${encodeURIComponent(g)}`),i(u=>u.filter(S=>S.id!==g)),(l==null?void 0:l.id)===g&&m(null)}catch{}},h=async g=>{try{await $.post(`/schedules/${encodeURIComponent(g)}/trigger`)}catch{}},b=d.trim()?s.filter(g=>g.name.toLowerCase().includes(d.toLowerCase())):s;return e.jsxs("div",{className:"mobile-view",children:[e.jsxs("div",{className:"mobile-tasks-toolbar",children:[e.jsx("input",{className:"mobile-search-input",type:"text",placeholder:"Search schedules…",value:d,onChange:g=>r(g.target.value),style:{flex:1}}),e.jsx("button",{type:"button",className:"mobile-icon-btn",onClick:()=>f(),"aria-label":"Refresh",children:e.jsx(re,{size:16})}),e.jsx("button",{type:"button",className:"mobile-icon-btn",onClick:()=>n({open:!0}),"aria-label":"New schedule",children:e.jsx(ie,{size:16})})]}),c?e.jsx("div",{className:"mobile-loading",children:e.jsx("p",{children:"Loading…"})}):b.length===0?e.jsxs("div",{className:"mobile-empty",children:[e.jsx(Ve,{size:40}),e.jsx("p",{children:"No schedules found."})]}):e.jsx("div",{className:"mobile-card-list",children:b.map(g=>e.jsxs("button",{type:"button",className:"mobile-list-item mobile-list-item-interactive",onClick:()=>m(g),children:[e.jsx("div",{className:"mobile-list-icon",children:e.jsx(Ve,{size:16})}),e.jsxs("div",{className:"mobile-list-content",children:[e.jsx("span",{className:"mobile-list-title",children:g.name}),e.jsxs("span",{className:"mobile-list-meta",children:[bt(g)," ·"," ",g.nextRun?`next ${ht(g.nextRun,g.timezone)}`:"no next run"]})]}),e.jsx("span",{className:`mobile-list-badge ${g.enabled?"badge-on":"badge-off"}`,children:g.enabled?"on":"off"})]},g.id))}),l&&e.jsx(ce,{open:!0,onClose:()=>m(null),title:l.name,actions:e.jsxs("div",{className:"mobile-task-detail-actions",children:[e.jsxs("button",{type:"button",className:"mobile-btn",onClick:()=>{l&&h(l.id)},children:[e.jsx(Le,{size:14})," Trigger now"]}),e.jsx("button",{type:"button",className:`mobile-btn ${l.enabled?"mobile-btn-secondary":""}`,onClick:()=>{l&&v(l.id,!l.enabled)},children:l.enabled?"Disable":"Enable"}),e.jsxs("button",{type:"button",className:"mobile-btn",onClick:()=>{l&&(n({open:!0,initial:l}),m(null))},children:[e.jsx(Ke,{size:14})," Edit"]}),e.jsx("button",{type:"button",className:"mobile-btn mobile-btn-danger",onClick:()=>{l&&p(l.id)},children:e.jsx(ke,{size:14})})]}),children:e.jsx("div",{className:"mobile-agent-detail",children:e.jsxs("div",{className:"mobile-agent-detail-meta",children:[e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Type"}),e.jsx("span",{children:l.type})]}),e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Schedule"}),e.jsx("span",{className:"mono",children:bt(l)||l.schedule})]}),l.timezone&&e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Timezone"}),e.jsx("span",{className:"mono",children:l.timezone})]}),e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Action"}),e.jsxs("span",{children:[l.action.type,": ",l.action.target]})]}),l.action.type==="agent"&&l.action.prompt&&e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Prompt"}),e.jsx("span",{style:{fontSize:12},children:l.action.prompt})]}),((k=l.budgetCheck)==null?void 0:k.skipIfBudgetLow)&&e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Budget gate"}),e.jsxs("span",{children:["skip if ≥ ",l.budgetCheck.maxConcurrent??6," concurrent"]})]}),e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Next run"}),e.jsx("span",{children:l.nextRun?ht(l.nextRun,l.timezone):"—"})]}),e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Last run"}),e.jsx("span",{children:l.lastRun?vn(l.lastRun):"—"})]}),l.lastResult&&e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Last result"}),e.jsx("span",{style:{fontSize:12},children:l.lastResult})]}),l.lastError&&e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Last error"}),e.jsx("span",{style:{fontSize:12},children:l.lastError})]})]})})}),e.jsx(jn,{open:x.open,initial:x.initial,onClose:()=>n({open:!1}),onSaved:()=>{n({open:!1}),f()}})]})}function ut(t){var c,o;if(!t)return{name:"",type:"cron",cronMinute:0,cronHour:13,cronDow:"0",intervalN:30,intervalUnit:"m",onceAt:"",timezone:"UTC",actionType:"agent",actionTarget:"",actionPrompt:"",skipIfBudgetLow:!1,maxConcurrent:6,enabled:!0};const s=t.type==="cron"?It(t.schedule):null,i=t.type==="interval"?yn(t.schedule):null;return{name:t.name||"",type:t.type,cronMinute:(s==null?void 0:s.minute)??0,cronHour:(s==null?void 0:s.hour)??9,cronDow:(s==null?void 0:s.dow)??"*",intervalN:(i==null?void 0:i.n)??30,intervalUnit:(i==null?void 0:i.unit)??"m",onceAt:t.type==="once"?Nn(t.schedule):"",timezone:t.timezone||"UTC",actionType:t.action.type,actionTarget:t.action.target||"",actionPrompt:t.action.prompt||"",skipIfBudgetLow:!!((c=t.budgetCheck)!=null&&c.skipIfBudgetLow),maxConcurrent:Number.isFinite((o=t.budgetCheck)==null?void 0:o.maxConcurrent)?t.budgetCheck.maxConcurrent:6,enabled:t.enabled!==!1}}function gn(t){if(t.type==="cron")return`${t.cronMinute} ${t.cronHour} * * ${t.cronDow}`;if(t.type==="interval")return`${t.intervalN}${t.intervalUnit}`;if(!t.onceAt)return"";try{return new Date(t.onceAt).toISOString()}catch{return t.onceAt}}function jn({open:t,initial:s,onClose:i,onSaved:c}){const[o,d]=a.useState(()=>ut(s)),[r,l]=a.useState(!1);a.useEffect(()=>{t&&d(ut(s))},[t,s]);const m=(n,f)=>{d(v=>({...v,[n]:f}))},x=async n=>{if(n.preventDefault(),!o.name.trim())return;const f=gn(o);if(f){l(!0);try{const v={name:o.name.trim(),type:o.type,schedule:f,timezone:o.timezone,action:{type:o.actionType,target:o.actionTarget.trim(),...o.actionType==="agent"&&o.actionPrompt.trim()?{prompt:o.actionPrompt.trim()}:{}},budgetCheck:{maxConcurrent:o.maxConcurrent,skipIfBudgetLow:o.skipIfBudgetLow},enabled:o.enabled};s?await $.put(`/schedules/${encodeURIComponent(s.id)}`,v):await $.post("/schedules",v),c()}catch{}finally{l(!1)}}};return e.jsx(be,{open:t,onClose:i,title:s?`Edit ${s.name}`:"New schedule",actions:e.jsxs("button",{type:"submit",form:"mobile-schedule-form",className:"mobile-btn",style:{width:"100%"},disabled:r,children:[e.jsx(ie,{size:14})," ",s?"Save":"Create"]}),children:e.jsxs("form",{id:"mobile-schedule-form",onSubmit:x,className:"mobile-task-form",children:[e.jsx("label",{className:"mobile-field-label",children:"Name *"}),e.jsx("input",{className:"mobile-input",type:"text",placeholder:"Weekly review",value:o.name,onChange:n=>m("name",n.target.value),autoFocus:!0,required:!0}),e.jsx("label",{className:"mobile-field-label",children:"Type"}),e.jsx("select",{className:"mobile-input",value:o.type,onChange:n=>m("type",n.target.value),children:hn.map(n=>e.jsx("option",{value:n,children:n},n))}),o.type==="cron"&&e.jsxs(e.Fragment,{children:[e.jsx("label",{className:"mobile-field-label",children:"Day of week"}),e.jsx("select",{className:"mobile-input",value:o.cronDow,onChange:n=>m("cronDow",n.target.value),children:Et.map(n=>e.jsx("option",{value:n.value,children:n.label},n.value))}),e.jsxs("div",{className:"mobile-form-row",children:[e.jsxs("div",{style:{flex:1},children:[e.jsx("label",{className:"mobile-field-label",children:"Hour"}),e.jsx("select",{className:"mobile-input",value:String(o.cronHour),onChange:n=>m("cronHour",parseInt(n.target.value,10)),children:Tt.map(n=>e.jsx("option",{value:String(n.value),children:n.label},n.value))})]}),e.jsxs("div",{style:{flex:1},children:[e.jsx("label",{className:"mobile-field-label",children:"Minute"}),e.jsx("select",{className:"mobile-input",value:String(o.cronMinute),onChange:n=>m("cronMinute",parseInt(n.target.value,10)),children:pn.map(n=>e.jsx("option",{value:String(n),children:String(n).padStart(2,"0")},n))})]})]})]}),o.type==="interval"&&e.jsxs("div",{className:"mobile-form-row",children:[e.jsxs("div",{style:{flex:1},children:[e.jsx("label",{className:"mobile-field-label",children:"Every"}),e.jsx("input",{className:"mobile-input",type:"number",min:1,value:o.intervalN,onChange:n=>m("intervalN",parseInt(n.target.value,10)||1)})]}),e.jsxs("div",{style:{flex:1},children:[e.jsx("label",{className:"mobile-field-label",children:"Unit"}),e.jsx("select",{className:"mobile-input",value:o.intervalUnit,onChange:n=>m("intervalUnit",n.target.value),children:fn.map(n=>e.jsx("option",{value:n.value,children:n.label},n.value))})]})]}),o.type==="once"&&e.jsxs(e.Fragment,{children:[e.jsx("label",{className:"mobile-field-label",children:"Run at"}),e.jsx("input",{className:"mobile-input",type:"datetime-local",value:o.onceAt,onChange:n=>m("onceAt",n.target.value)})]}),e.jsx("label",{className:"mobile-field-label",children:"Timezone"}),e.jsx("select",{className:"mobile-input",value:mt.includes(o.timezone)?o.timezone:"UTC",onChange:n=>m("timezone",n.target.value),children:mt.map(n=>e.jsx("option",{value:n,children:n},n))}),e.jsx("label",{className:"mobile-field-label",children:"Action type"}),e.jsx("select",{className:"mobile-input",value:o.actionType,onChange:n=>m("actionType",n.target.value),children:bn.map(n=>e.jsx("option",{value:n,children:n},n))}),e.jsx("label",{className:"mobile-field-label",children:"Target"}),e.jsx("input",{className:"mobile-input",type:"text",placeholder:o.actionType==="webhook"?"https://...":o.actionType==="agent"?"agent or task ref":"echo hello",value:o.actionTarget,onChange:n=>m("actionTarget",n.target.value)}),o.actionType==="agent"&&e.jsxs(e.Fragment,{children:[e.jsx("label",{className:"mobile-field-label",children:"Prompt"}),e.jsx("textarea",{className:"mobile-input",rows:3,placeholder:"What should the agent do?",value:o.actionPrompt,onChange:n=>m("actionPrompt",n.target.value)})]}),e.jsxs("fieldset",{className:"mobile-budget-card",children:[e.jsx("legend",{children:"Budget pre-flight"}),e.jsxs("label",{className:"mobile-checkbox-row",children:[e.jsx("input",{type:"checkbox",checked:o.skipIfBudgetLow,onChange:n=>m("skipIfBudgetLow",n.target.checked)}),e.jsx("span",{children:"Skip if too many bg tasks are running"})]}),e.jsx("label",{className:"mobile-field-label",children:"Cap"}),e.jsx("input",{className:"mobile-input",type:"number",min:1,max:64,value:o.maxConcurrent,onChange:n=>m("maxConcurrent",parseInt(n.target.value,10)||6),disabled:!o.skipIfBudgetLow})]}),e.jsxs("label",{className:"mobile-checkbox-row",children:[e.jsx("input",{type:"checkbox",checked:o.enabled,onChange:n=>m("enabled",n.target.checked)}),e.jsx("span",{children:"Enabled"})]})]})})}function vn(t){const s=Date.now()-new Date(t).getTime();return s<6e4?"just now":s<36e5?`${Math.floor(s/6e4)}m ago`:s<864e5?`${Math.floor(s/36e5)}h ago`:new Date(t).toLocaleDateString()}function ht(t,s){try{return new Date(t).toLocaleString(void 0,{timeZone:s||void 0,weekday:"short",hour:"numeric",minute:"2-digit",month:"short",day:"numeric"})}catch{return new Date(t).toLocaleString()}}function It(t){if(typeof t!="string")return null;const s=t.trim().split(/\s+/);if(s.length!==5)return null;const[i,c,,,o]=s,d=parseInt(i,10),r=parseInt(c,10);return!Number.isFinite(d)||!Number.isFinite(r)||i!==String(d)||c!==String(r)?null:{minute:d,hour:r,dow:o==="*"?"*":Number.isFinite(parseInt(o,10))?o:"*"}}function yn(t){if(typeof t!="string")return null;const s=/^(\d+)([smhd])$/i.exec(t.trim());return s?{n:parseInt(s[1],10),unit:s[2].toLowerCase()}:null}function Nn(t){if(!t)return"";try{const s=new Date(t);if(Number.isNaN(s.getTime()))return"";const i=c=>String(c).padStart(2,"0");return`${s.getFullYear()}-${i(s.getMonth()+1)}-${i(s.getDate())}T${i(s.getHours())}:${i(s.getMinutes())}`}catch{return""}}function bt(t){var d,r;if(t.type!=="cron")return t.schedule;const s=It(t.schedule);if(!s)return t.schedule;const i=((d=Et.find(l=>l.value===s.dow))==null?void 0:d.label)||s.dow,c=((r=Tt.find(l=>l.value===s.hour))==null?void 0:r.label)||`${s.hour}`,o=String(s.minute).padStart(2,"0");return i==="Every day"?`Every day ${c} :${o}`:`Every ${i} ${c} :${o}`}const kn=["all","tasks","agents","artifacts","projects","settings"],wn={tasks:Pe,agents:we,plans:fe,projects:Ye,settings:Ne};function Sn({open:t,onClose:s,onNavigate:i}){const[c,o]=a.useState(""),[d,r]=a.useState("all"),[l,m]=a.useState([]),[x,n]=a.useState(!1),f=a.useRef(null);a.useEffect(()=>{t&&(o(""),m([]),requestAnimationFrame(()=>{var h;return(h=f.current)==null?void 0:h.focus()}))},[t]),a.useEffect(()=>{if(!c.trim()){m([]);return}const h=setTimeout(async()=>{n(!0);try{const b=await $.get(`/search?q=${encodeURIComponent(c)}&scope=${d}`);m(b.results||[])}catch{m([])}finally{n(!1)}},250);return()=>clearTimeout(h)},[c,d]);const v=h=>{const b=h.item,k=b.id||b.slug||b.name||"";i(h.type,k),s()},p=l.reduce((h,b)=>(h[b.type]||(h[b.type]=[]),h[b.type].push(b),h),{});return e.jsx(be,{open:t,onClose:s,title:"Search",children:e.jsxs("div",{className:"mobile-search-container",children:[e.jsxs("div",{className:"mobile-search-input-row",children:[e.jsx(nt,{size:16,style:{color:"var(--text-muted)",flexShrink:0}}),e.jsx("input",{ref:f,className:"mobile-search-field",type:"text",placeholder:"Search…",value:c,onChange:h=>o(h.target.value),enterKeyHint:"search",onKeyDown:h=>{h.key==="Escape"&&s(),h.key==="Enter"&&l.length>0&&v(l[0])}}),c&&e.jsx("button",{type:"button",className:"mobile-icon-btn",onClick:()=>o(""),"aria-label":"Clear",children:e.jsx(xe,{size:16})})]}),e.jsx("div",{className:"mobile-search-scopes",children:kn.map(h=>e.jsx("button",{type:"button",className:`mobile-scope-chip ${d===h?"active":""}`,onClick:()=>r(h),children:h==="all"?"All":h.charAt(0).toUpperCase()+h.slice(1)},h))}),e.jsxs("div",{className:"mobile-search-results",children:[x&&e.jsx("div",{className:"mobile-search-loading",children:"Searching…"}),!x&&c&&l.length===0&&e.jsxs("div",{className:"mobile-empty",children:[e.jsx(nt,{size:32}),e.jsx("p",{children:"No results found"})]}),!x&&!c&&e.jsx("div",{className:"mobile-empty",children:e.jsx("p",{children:"Type to search across tasks, agents, plans, and more."})}),Object.entries(p).map(([h,b])=>{const k=wn[h]||fe;return e.jsxs("div",{className:"mobile-search-group",children:[e.jsxs("h4",{className:"mobile-search-group-title",children:[e.jsx(k,{size:12})," ",h.charAt(0).toUpperCase()+h.slice(1)," (",b.length,")"]}),b.map((g,u)=>{const S=g.item;return e.jsxs("button",{type:"button",className:"mobile-search-result-item",onClick:()=>v(g),children:[e.jsx("span",{className:"mobile-search-result-title",children:S.title||S.name||S.slug||"(unnamed)"}),S.description&&e.jsx("span",{className:"mobile-search-result-meta",children:S.description.slice(0,80)})]},u)})]},h)})]})]})})}function Cn(t){if(t<=0)return"expired";const s=Math.floor(t/1e3),i=Math.floor(s/60),c=s%60;return`${i}:${String(c).padStart(2,"0")}`}function Tn({pair:t,onStart:s}){const[i,c]=a.useState(null),[o,d]=a.useState(()=>t.expiresAt-Date.now()),r=o<=0;return a.useEffect(()=>{St(()=>import("./index-DmpSFPJY.js"),__vite__mapDeps([0,1])).then(l=>{c(l.QRCodeSVG)})},[]),a.useEffect(()=>{if(!t)return;const l=setInterval(()=>{d(t.expiresAt-Date.now())},1e3);return()=>clearInterval(l)},[t]),i?e.jsxs("div",{style:{textAlign:"center"},children:[e.jsx("div",{style:{background:"#fff",padding:12,borderRadius:12,display:"inline-block"},children:e.jsx(i,{value:t.qrPayload,size:180,level:"M"})}),e.jsxs("div",{style:{marginTop:8,fontSize:12},children:["Expires in ",e.jsx("strong",{children:Cn(o)})]}),e.jsx("div",{className:"mono",style:{fontSize:10,wordBreak:"break-all",marginTop:4},children:t.publicUrl}),r&&e.jsxs("button",{type:"button",className:"mobile-btn",onClick:s,style:{marginTop:12,width:"100%"},children:[e.jsx(re,{size:14})," Generate new QR"]})]}):e.jsx("div",{style:{textAlign:"center",padding:"16px"},children:e.jsx("span",{style:{color:"var(--text-dim)",fontSize:13},children:"Loading QR library…"})})}const En=[{id:"dark",label:"Dark",Icon:cs},{id:"light",label:"Light",Icon:rs},{id:"system",label:"System",Icon:ds}],In=[{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"}];function $n({settings:t,snapshot:s,onRefresh:i}){var g,u,S,C,_,O;const[c,o]=a.useState(t),[d,r]=a.useState(!1),[l,m]=a.useState(!1),[x,n]=a.useState(null),[f,v]=a.useState(!1);a.useEffect(()=>{o(t),r(!1),t.theme&&Ie(t.theme)},[t]);const p=I=>{o(L=>{const j={...L,theme:{...L.theme,...I}};return Oe(j.theme),Ie(j.theme),j}),r(!0)},h=(I,L)=>{o(j=>({...j,[I]:L})),r(!0)},b=async()=>{m(!0);try{const I=await $.put("/settings",c);o(I.data),r(!1),Oe(I.data.theme),Ie(I.data.theme),i()}catch{}finally{m(!1)}},k=async()=>{v(!0);try{const I=await $.post("/pair/start");n(I)}catch{}finally{v(!1)}};return e.jsxs("div",{className:"mobile-view",children:[d&&e.jsxs("div",{className:"mobile-settings-save-bar",children:[e.jsx("span",{children:"Unsaved changes"}),e.jsxs("button",{type:"button",className:"mobile-btn",disabled:l,onClick:b,children:[e.jsx(gt,{size:14})," ",l?"Saving…":"Save"]})]}),e.jsxs("section",{className:"mobile-section",children:[e.jsx("h3",{className:"mobile-section-title",children:"Appearance"}),e.jsxs("div",{className:"mobile-card",children:[e.jsxs("div",{className:"mobile-setting-row",children:[e.jsx("span",{className:"mobile-setting-label",children:"Theme"}),e.jsx("div",{className:"mobile-theme-btns",children:En.map(({id:I,label:L,Icon:j})=>e.jsxs("button",{type:"button",className:`mobile-theme-btn ${c.theme.mode===I?"active":""}`,onClick:()=>p({mode:I}),children:[e.jsx(j,{size:14})," ",L]},I))})]}),e.jsxs("div",{className:"mobile-setting-row",style:{flexDirection:"column",alignItems:"flex-start",gap:8},children:[e.jsx("span",{className:"mobile-setting-label",children:"Accent color"}),e.jsx("div",{className:"mobile-accent-swatches",children:In.map(I=>e.jsx("button",{type:"button",className:`mobile-accent-swatch ${c.theme.accent===I.accent?"active":""}`,style:{background:I.accent},onClick:()=>p({accent:I.accent}),title:I.name},I.name))})]}),e.jsxs("div",{className:"mobile-setting-row",style:{flexDirection:"column",alignItems:"flex-start",gap:8},children:[e.jsxs("span",{className:"mobile-setting-label",children:["Font size: ",c.theme.fontSize,"px"]}),e.jsx("input",{type:"range",min:12,max:20,value:c.theme.fontSize,onChange:I=>p({fontSize:Number(I.target.value)}),style:{width:"100%"}})]}),e.jsxs("div",{className:"mobile-setting-row",children:[e.jsx("span",{className:"mobile-setting-label",children:"Compact mode"}),e.jsxs("label",{className:"mobile-toggle",children:[e.jsx("input",{type:"checkbox",checked:c.theme.compactMode,onChange:I=>p({compactMode:I.target.checked})}),e.jsx("span",{className:"mobile-toggle-slider"})]})]}),e.jsxs("div",{className:"mobile-setting-row",children:[e.jsx("span",{className:"mobile-setting-label",children:"Animations"}),e.jsxs("label",{className:"mobile-toggle",children:[e.jsx("input",{type:"checkbox",checked:c.theme.animations,onChange:I=>p({animations:I.target.checked})}),e.jsx("span",{className:"mobile-toggle-slider"})]})]})]})]}),e.jsxs("section",{className:"mobile-section",children:[e.jsx("h3",{className:"mobile-section-title",children:"Chat Defaults"}),e.jsxs("div",{className:"mobile-card",children:[e.jsx("label",{className:"mobile-field-label",children:"Default Agent"}),e.jsx("select",{className:"mobile-input",value:c.defaultAgent||"odin",onChange:I=>h("defaultAgent",I.target.value),children:((s==null?void 0:s.agents)||[]).map(I=>e.jsxs("option",{value:I.name,children:["@",I.name]},I.name))}),e.jsx("label",{className:"mobile-field-label",style:{marginTop:8},children:"Default Model"}),e.jsx("input",{className:"mobile-input",type:"text",placeholder:"(auto)",value:c.defaultModel||"",onChange:I=>h("defaultModel",I.target.value)})]})]}),e.jsxs("section",{className:"mobile-section",children:[e.jsx("h3",{className:"mobile-section-title",children:"Notifications"}),e.jsxs("div",{className:"mobile-card",children:[e.jsxs("div",{className:"mobile-setting-row",children:[e.jsx("span",{className:"mobile-setting-label",children:"Agent completion"}),e.jsxs("label",{className:"mobile-toggle",children:[e.jsx("input",{type:"checkbox",checked:!!c.notifications.onAgentComplete,onChange:I=>{o(L=>({...L,notifications:{...L.notifications,onAgentComplete:I.target.checked}})),r(!0)}}),e.jsx("span",{className:"mobile-toggle-slider"})]})]}),e.jsxs("div",{className:"mobile-setting-row",children:[e.jsx("span",{className:"mobile-setting-label",children:"Plan approval"}),e.jsxs("label",{className:"mobile-toggle",children:[e.jsx("input",{type:"checkbox",checked:!!c.notifications.onPlanApproval,onChange:I=>{o(L=>({...L,notifications:{...L.notifications,onPlanApproval:I.target.checked}})),r(!0)}}),e.jsx("span",{className:"mobile-toggle-slider"})]})]})]})]}),e.jsxs("section",{className:"mobile-section",children:[e.jsx("h3",{className:"mobile-section-title",children:"Agent Behavior"}),e.jsxs("div",{className:"mobile-card",children:[e.jsx("label",{className:"mobile-field-label",children:"Max parallel agents"}),e.jsx("input",{className:"mobile-input",type:"number",inputMode:"numeric",min:1,max:20,value:((g=c.agents)==null?void 0:g.maxParallel)??6,onChange:I=>{o(L=>({...L,agents:{...L.agents,maxParallel:Math.max(1,Math.min(20,parseInt(I.target.value,10)||6))}})),r(!0)}}),e.jsx("label",{className:"mobile-field-label",style:{marginTop:8},children:"Stuck threshold (ms)"}),e.jsx("input",{className:"mobile-input",type:"number",inputMode:"numeric",min:6e4,max:36e5,step:6e4,value:((u=c.agents)==null?void 0:u.stuckThresholdMs)??6e5,onChange:I=>{o(L=>({...L,agents:{...L.agents,stuckThresholdMs:Math.max(6e4,parseInt(I.target.value,10)||6e5)}})),r(!0)}}),e.jsxs("div",{className:"mobile-setting-row",style:{marginTop:8},children:[e.jsx("span",{className:"mobile-setting-label",children:"Auto-restart stuck agents"}),e.jsxs("label",{className:"mobile-toggle",children:[e.jsx("input",{type:"checkbox",checked:!!((S=c.agents)!=null&&S.autoRestart),onChange:I=>{o(L=>({...L,agents:{...L.agents,autoRestart:I.target.checked}})),r(!0)}}),e.jsx("span",{className:"mobile-toggle-slider"})]})]})]})]}),e.jsxs("section",{className:"mobile-section",children:[e.jsx("h3",{className:"mobile-section-title",children:"Tailscale Serve"}),e.jsx("div",{className:"mobile-card",children:e.jsxs("p",{className:"muted",style:{fontSize:13},children:["Use ",e.jsx("code",{children:"bizar service"})," commands in the terminal to configure Tailscale serve."]})})]}),e.jsxs("section",{className:"mobile-section",children:[e.jsxs("h3",{className:"mobile-section-title",children:[e.jsx(at,{size:14})," Companion App"]}),e.jsxs("div",{className:"mobile-card",children:[!x&&e.jsxs("button",{type:"button",className:"mobile-btn",onClick:k,disabled:f,style:{width:"100%"},children:[e.jsx(at,{size:14})," ",f?"Generating…":"Generate QR Code"]}),x&&e.jsx(Tn,{pair:x,onStart:k})]})]}),e.jsxs("section",{className:"mobile-section",children:[e.jsx("h3",{className:"mobile-section-title",children:"About"}),e.jsxs("div",{className:"mobile-card",children:[e.jsxs("div",{className:"mobile-setting-row",children:[e.jsx("span",{className:"mobile-setting-label",children:"Version"}),e.jsx("span",{className:"mobile-setting-value mono",children:((C=c.about)==null?void 0:C.version)||"—"})]}),e.jsxs("div",{className:"mobile-setting-row",children:[e.jsx("span",{className:"mobile-setting-label",children:"Agents"}),e.jsx("span",{className:"mobile-setting-value",children:((_=s==null?void 0:s.agents)==null?void 0:_.length)||0})]}),e.jsxs("div",{className:"mobile-setting-row",children:[e.jsx("span",{className:"mobile-setting-label",children:"Tasks"}),e.jsx("span",{className:"mobile-setting-value",children:((O=s==null?void 0:s.tasks)==null?void 0:O.length)||0})]}),e.jsxs("div",{className:"mobile-setting-row",children:[e.jsx("span",{className:"mobile-setting-label",children:"Plans"}),e.jsx("span",{className:"mobile-setting-value",children:(s==null?void 0:s.artifacts.length)||0})]})]})]}),e.jsx("div",{className:"mobile-view-footer",children:e.jsx("a",{href:"/?desktop=1",className:"mobile-btn mobile-btn-secondary",children:"Switch to Desktop"})})]})}const An=["languages","framework","design","testing","devops","data","security","integration"];function zn({snapshot:t,onBack:s}){const[i,c]=a.useState([]),[o,d]=a.useState(!0),[r,l]=a.useState(""),[m,x]=a.useState(""),[n,f]=a.useState(null),v=async()=>{try{const b=await $.get("/skills");c(b.skills||[])}catch{}finally{d(!1)}};a.useEffect(()=>{v()},[]);const p=async(b,k)=>{try{await $.patch(`/skills/${encodeURIComponent(b)}`,{enabled:k}),c(g=>g.map(u=>u.id===b?{...u,enabled:k}:u)),(n==null?void 0:n.id)===b&&f(g=>g&&{...g,enabled:k})}catch{}},h=i.filter(b=>{if(m&&b.category!==m)return!1;if(r){const k=r.toLowerCase();return b.name.toLowerCase().includes(k)||b.description.toLowerCase().includes(k)}return!0});return e.jsxs("div",{className:"mobile-view",children:[e.jsxs("div",{className:"mobile-tasks-toolbar",children:[e.jsx("input",{className:"mobile-search-input",type:"text",placeholder:"Search skills…",value:r,onChange:b=>l(b.target.value),style:{flex:1}}),e.jsx("button",{type:"button",className:"mobile-icon-btn",onClick:()=>v(),"aria-label":"Refresh",children:e.jsx(re,{size:16})})]}),e.jsxs("div",{className:"mobile-search-scopes",children:[e.jsx("button",{type:"button",className:`mobile-scope-chip ${m?"":"active"}`,onClick:()=>x(""),children:"All"}),An.map(b=>e.jsx("button",{type:"button",className:`mobile-scope-chip ${m===b?"active":""}`,onClick:()=>x(b),children:b},b))]}),o?e.jsx("div",{className:"mobile-loading",children:e.jsx("p",{children:"Loading…"})}):h.length===0?e.jsxs("div",{className:"mobile-empty",children:[e.jsx(Me,{size:40}),e.jsx("p",{children:"No skills found."})]}):e.jsx("div",{className:"mobile-card-list",children:h.map(b=>e.jsxs("button",{type:"button",className:"mobile-list-item mobile-list-item-interactive",onClick:()=>f(b),children:[e.jsx("div",{className:"mobile-list-icon",children:e.jsx(Me,{size:16})}),e.jsxs("div",{className:"mobile-list-content",children:[e.jsx("span",{className:"mobile-list-title",children:b.name}),e.jsxs("span",{className:"mobile-list-meta",children:[b.category," · v",b.version]})]}),e.jsx("span",{className:`mobile-list-badge ${b.enabled?"badge-on":"badge-off"}`,children:b.enabled?"on":"off"})]},b.id))}),n&&e.jsx(ce,{open:!0,onClose:()=>f(null),title:n.name,actions:e.jsxs("button",{type:"button",className:`mobile-btn ${n.enabled?"mobile-btn-secondary":""}`,style:{width:"100%"},onClick:()=>{n&&p(n.id,!n.enabled)},children:[e.jsx(jt,{size:14})," ",n.enabled?"Disable":"Enable"]}),children:e.jsxs("div",{className:"mobile-agent-detail",children:[e.jsx("p",{className:"mobile-agent-detail-desc",children:n.description||"No description."}),e.jsxs("div",{className:"mobile-agent-detail-meta",children:[e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Category"}),e.jsx("span",{children:n.category})]}),e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Version"}),e.jsx("span",{className:"mono",children:n.version})]}),e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Source"}),e.jsx("span",{children:n.source})]}),n.tags.length>0&&e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Tags"}),e.jsx("span",{children:n.tags.join(", ")})]})]})]})})]})}const Rn=["queued","doing","blocked","done"],Re={queued:"Queued",doing:"Doing",blocked:"Blocked",done:"Done"},pt={queued:"doing",doing:"done",blocked:"queued",done:"queued"};function Dn(t){const s=t.metadata??{};return!!(s.sessionId||s.bgInstanceId)}function Mn(t){var i;const s=t.metadata??{};return!!((i=s.artifactIds)!=null&&i.length||s.artifactId)}function ft({snapshot:t,onRefresh:s,selectedTaskId:i,onCloseDetail:c,onOpenChat:o,onOpenArtifact:d}){var ue,de;const[r,l]=a.useState(t.tasks||[]),[m,x]=a.useState(!t.tasks),[n,f]=a.useState(""),[v,p]=a.useState("queued"),[h,b]=a.useState(null),[k,g]=a.useState(!1),[u,S]=a.useState(null),[C,_]=a.useState([]),[O,I]=a.useState(""),[L,j]=a.useState(null),[w,y]=a.useState(!1),[R,B]=a.useState(""),[z,G]=a.useState("updated");a.useEffect(()=>{var T;if(t.tasks&&(l(t.tasks),x(!1)),i){const W=(T=t.tasks)==null?void 0:T.find(U=>U.id===i);W&&b(W)}},[t.tasks,i]),a.useEffect(()=>{if(i){const T=r.find(W=>W.id===i);T&&b(T)}},[i,r]);const le=async()=>{try{const T=await $.get("/tasks");l(Array.isArray(T)?T:[])}catch{}finally{x(!1)}},te=async(T,W)=>{l(U=>U.map(Y=>Y.id===T?{...Y,status:W}:Y)),(h==null?void 0:h.id)===T&&b(U=>U&&{...U,status:W});try{await $.patch(`/tasks/${encodeURIComponent(T)}/status`,{status:W})}catch{await le()}},ge=async T=>{if(confirm("Delete this task?"))try{await $.del(`/tasks/${encodeURIComponent(T)}`),l(W=>W.filter(U=>U.id!==T)),(h==null?void 0:h.id)===T&&b(null)}catch{await le()}},Se=async T=>{try{await $.post(`/tasks/${encodeURIComponent(T)}/archive`),l(W=>W.filter(U=>U.id!==T)),(h==null?void 0:h.id)===T&&b(null)}catch{}},me=[...r.filter(T=>{var W,U;if(n.trim()){const Y=n.toLowerCase();if(!(T.title||"").toLowerCase().includes(Y)&&!(T.description||"").toLowerCase().includes(Y))return!1}if(R.trim()){const Y=R==="mine"?((U=(W=t.settings)==null?void 0:W.data)==null?void 0:U.defaultAgent)||Ln(t):R.replace(/^@/,"");if((T.assignee||"").toLowerCase()!==Y.toLowerCase())return!1}return!0})].sort((T,W)=>{switch(z){case"priority":{const U={high:0,normal:1,low:2};return(U[T.priority]??1)-(U[W.priority]??1)}case"created":return new Date(W.createdAt).getTime()-new Date(T.createdAt).getTime();case"updated":default:return new Date(W.updatedAt).getTime()-new Date(T.updatedAt).getTime()}}),K=me.filter(T=>T.status===v),Z=t.agents||[],je=async(T,W,U,Y)=>{try{const Ce=await $.post("/tasks",{title:T,description:W,assignee:U||null,priority:Y});l(oe=>[Ce,...oe]),g(!1)}catch{}},ee=async T=>{y(!0),I(""),j(null),S(T);try{const U=((await $.get(`/tasks/${encodeURIComponent(T)}/artifacts`)).artifacts||[]).map(Y=>Y.id);if(_(U),U.length>0){const[Y,Ce]=await Promise.all([$.get(`/artifacts/${encodeURIComponent(U[0])}`),fetch($.urlWithToken(`/artifacts/${encodeURIComponent(U[0])}/content`)).then(oe=>oe.text())]);j(Y),I(Ce)}}catch{}finally{y(!1)}};return m?e.jsx("div",{className:"mobile-loading",children:e.jsx("p",{children:"Loading…"})}):e.jsxs("div",{className:"mobile-view mobile-view-tasks",children:[e.jsxs("div",{className:"mobile-tasks-toolbar",children:[e.jsx("input",{className:"mobile-search-input",type:"text",placeholder:"Search tasks…",value:n,onChange:T=>f(T.target.value),style:{flex:1}}),e.jsx("button",{type:"button",className:"mobile-icon-btn",onClick:()=>le(),"aria-label":"Refresh",children:e.jsx(re,{size:16})})]}),e.jsxs("div",{className:"mobile-tasks-filters",children:[e.jsxs("select",{className:"mobile-filter-select",value:R,onChange:T=>B(T.target.value),children:[e.jsx("option",{value:"",children:"All"}),e.jsx("option",{value:"mine",children:"Mine"}),Z.map(T=>e.jsxs("option",{value:`@${T.name}`,children:["@",T.name]},T.name))]}),e.jsxs("select",{className:"mobile-filter-select",value:z,onChange:T=>G(T.target.value),children:[e.jsx("option",{value:"updated",children:"Updated"}),e.jsx("option",{value:"created",children:"Created"}),e.jsx("option",{value:"priority",children:"Priority"})]})]}),e.jsx("div",{className:"mobile-kanban-tabs",children:Rn.map(T=>{const W=me.filter(U=>U.status===T).length;return e.jsxs("button",{type:"button",className:`mobile-kanban-tab ${v===T?"active":""}`,onClick:()=>p(T),children:[Re[T]," (",W,")"]},T)})}),e.jsxs("div",{className:"mobile-card-list",children:[K.length===0&&e.jsxs("div",{className:"mobile-empty mobile-empty-compact",children:[e.jsxs("p",{children:["No ",Re[v].toLowerCase()," tasks."]}),e.jsx("p",{className:"muted",children:"Create one or switch columns."})]}),K.map(T=>{var W;return e.jsxs("button",{type:"button",className:"mobile-task-card",onClick:()=>b(T),children:[e.jsx("div",{className:"priority-dot",style:{background:fs[T.priority]||"var(--info)"}}),e.jsxs("div",{className:"task-content",children:[e.jsx("div",{className:"task-title",children:T.title}),e.jsxs("div",{className:"task-meta",children:[T.assignee?`@${T.assignee}`:"unassigned"," · ",ye(T.updatedAt||T.createdAt),(W=T.dependencies)!=null&&W.length?` · ${T.dependencies.length} deps`:""]})]})]},T.id)})]}),e.jsx("button",{type:"button",className:"mobile-fab",onClick:()=>g(!0),"aria-label":"Add task",children:e.jsx(ie,{size:24})}),e.jsx(ce,{open:!!h,onClose:()=>{b(null),c==null||c()},title:"Task Detail",actions:h&&e.jsxs("div",{className:"mobile-task-detail-actions",children:[h.status!=="done"&&e.jsxs("button",{type:"button",className:"mobile-btn",style:{flex:1},onClick:()=>{h&&te(h.id,pt[h.status])},children:["Move to ",Re[pt[h.status]||"queued"]]}),e.jsxs("button",{type:"button",className:"mobile-btn mobile-btn-secondary",onClick:()=>{h&&Se(h.id)},children:[e.jsx(ms,{size:14})," Archive"]}),Dn(h)&&e.jsxs("button",{type:"button",className:"mobile-btn mobile-btn-secondary",onClick:()=>{o==null||o(h.id)},children:[e.jsx(pe,{size:14})," Chat"]}),Mn(h)&&e.jsxs("button",{type:"button",className:"mobile-btn mobile-btn-secondary",onClick:()=>{ee(h.id)},children:[e.jsx(fe,{size:14})," Artifact"]}),e.jsx("button",{type:"button",className:"mobile-btn mobile-btn-danger",onClick:()=>{h&&ge(h.id)},children:e.jsx(ke,{size:14})})]}),children:h&&e.jsxs("div",{className:"mobile-task-detail",children:[e.jsxs("div",{className:"mobile-task-detail-header",children:[e.jsx("span",{className:`mobile-task-status-badge status-${h.status}`,children:Re[h.status]||h.status}),e.jsx("span",{className:`mobile-task-priority priority-${h.priority}`,children:h.priority})]}),e.jsx("h3",{className:"mobile-task-detail-title",children:h.title}),h.description&&e.jsx("p",{className:"mobile-task-detail-desc",children:h.description}),e.jsxs("div",{className:"mobile-task-detail-meta",children:[h.assignee&&e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Assignee"}),e.jsxs("span",{children:["@",h.assignee]})]}),h.dueDate&&e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Due"}),e.jsx("span",{children:new Date(h.dueDate).toLocaleDateString()})]}),h.timeSpent!=null&&e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Time spent"}),e.jsxs("span",{children:[Math.round(h.timeSpent/6e4),"min"]})]}),(ue=h.dependencies)!=null&&ue.length?e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Dependencies"}),e.jsx("span",{children:h.dependencies.length})]}):null,(de=h.comments)!=null&&de.length?e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Comments"}),e.jsx("span",{children:h.comments.length})]}):null,e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Created"}),e.jsx("span",{children:ye(h.createdAt)})]}),e.jsxs("div",{className:"mobile-task-detail-row",children:[e.jsx("span",{children:"Updated"}),e.jsx("span",{children:ye(h.updatedAt)})]})]})]})}),e.jsx(Pn,{open:k,onClose:()=>g(!1),onCreate:je,agents:Z}),e.jsx(ce,{open:!!u,onClose:()=>{S(null),I(""),j(null)},title:(L==null?void 0:L.name)||"Artifact",actions:C.length>1?e.jsx("div",{className:"mobile-task-detail-actions",children:C.map((T,W)=>e.jsxs("button",{type:"button",className:"mobile-btn mobile-btn-secondary",style:{flex:1},onClick:()=>{y(!0),Promise.all([$.get(`/artifacts/${encodeURIComponent(T)}`),fetch($.urlWithToken(`/artifacts/${encodeURIComponent(T)}/content`)).then(U=>U.text())]).then(([U,Y])=>{j(U),I(Y),y(!1)}).catch(()=>y(!1))},children:["Artifact ",W+1]},T))}):null,children:e.jsx("div",{className:"mobile-artifact-viewer",children:w?e.jsx("div",{className:"mobile-loading",children:e.jsx("p",{children:"Loading artifact…"})}):O?e.jsx("iframe",{srcDoc:O,className:"mobile-artifact-iframe",sandbox:"allow-scripts allow-forms allow-popups allow-same-origin",title:(L==null?void 0:L.name)||"Artifact",loading:"lazy"}):e.jsxs("div",{className:"mobile-empty",children:[e.jsx(fe,{size:32}),e.jsx("p",{className:"muted",children:"No artifact content available."})]})})})]})}function Ln(t){var s,i;return((i=(s=t.settings)==null?void 0:s.data)==null?void 0:i.defaultAgent)||"odin"}function Pn({open:t,onClose:s,onCreate:i,agents:c}){const[o,d]=a.useState(""),[r,l]=a.useState(""),[m,x]=a.useState(""),[n,f]=a.useState("normal"),v=p=>{p.preventDefault(),o.trim()&&(i(o.trim(),r.trim(),m,n),d(""),l(""),x(""),f("normal"))};return e.jsx(be,{open:t,onClose:s,title:"New Task",actions:e.jsxs("button",{type:"submit",form:"new-task-form",className:"mobile-btn",style:{width:"100%"},children:[e.jsx(ie,{size:14})," Create Task"]}),children:e.jsxs("form",{id:"new-task-form",onSubmit:v,className:"mobile-task-form",children:[e.jsx("label",{className:"mobile-field-label",children:"Title *"}),e.jsx("input",{className:"mobile-input",type:"text",placeholder:"Task title",value:o,onChange:p=>d(p.target.value),autoFocus:!0,required:!0}),e.jsx("label",{className:"mobile-field-label",children:"Description"}),e.jsx("textarea",{className:"mobile-input",rows:3,placeholder:"Optional description",value:r,onChange:p=>l(p.target.value)}),e.jsx("label",{className:"mobile-field-label",children:"Assignee"}),e.jsxs("select",{className:"mobile-input",value:m,onChange:p=>x(p.target.value),children:[e.jsx("option",{value:"",children:"Unassigned"}),c.map(p=>e.jsxs("option",{value:p.name,children:["@",p.name]},p.name))]}),e.jsx("label",{className:"mobile-field-label",children:"Priority"}),e.jsxs("select",{className:"mobile-input",value:n,onChange:p=>f(p.target.value),children:[e.jsx("option",{value:"low",children:"Low"}),e.jsx("option",{value:"normal",children:"Normal"}),e.jsx("option",{value:"high",children:"High"})]})]})})}const On=[{id:"activity",label:"Activity",icon:We},{id:"chat",label:"Chat",icon:pe},{id:"tasks",label:"Tasks",icon:Pe},{id:"settings",label:"Settings",icon:vt},{id:"more",label:"More",icon:us}];function Bn(t){const s=t.meta??{},i=typeof s.taskId=="string"?s.taskId:null,c=typeof s.slug=="string"?s.slug:null,o=typeof s.agent=="string"?s.agent:null;if(i)return{id:"task-detail",taskId:i};if(c)return{id:"artifacts?-detail",slug:c};if(o)return{id:"agent-detail",name:o};const d=t.link??"";return d.startsWith("/artifacts?/")?{id:"artifacts?-detail",slug:decodeURIComponent(d.slice(12))}:d.startsWith("/tasks/")?{id:"task-detail",taskId:decodeURIComponent(d.slice(7))}:d.startsWith("/agents/")?{id:"agent-detail",name:decodeURIComponent(d.slice(8))}:null}function Yn(){const[t,s]=a.useState("activity"),[i,c]=a.useState([]),[o,d]=a.useState(!1),[r,l]=a.useState(null),[m,x]=a.useState(null),[n,f]=a.useState(null),[v,p]=a.useState(null),[h,b]=a.useState(!0),[k,g]=a.useState(0),u=a.useMemo(()=>i[i.length-1]??{id:t},[t,i]),S=a.useCallback(w=>{c(y=>[...y,w])},[]),C=a.useCallback(()=>{c(w=>w.slice(0,-1))},[]),_=a.useCallback(w=>{c([]),s(w)},[]),O=a.useCallback(async()=>{var w;try{const y=await $.get("/snapshot");x(y),(w=y.settings)!=null&&w.data&&f(y.settings.data),p(null)}catch(y){throw p(y.message||"Dashboard server unreachable."),y}},[]);a.useEffect(()=>{let w=!1;return Promise.all([$.get("/snapshot").catch(()=>null),$.get("/settings").catch(()=>null),$.probeAuthStatus().catch(()=>null)]).then(([y,R])=>{var z;if(w)return;const B=(R==null?void 0:R.data)??((z=y==null?void 0:y.settings)==null?void 0:z.data)??null;y&&x(y),B&&f(B),p(!y&&!B?"Dashboard server unreachable.":null)}).catch(y=>{w||p(y.message||"Dashboard server unreachable.")}).finally(()=>{w||b(!1)}),()=>{w=!0}},[]),a.useEffect(()=>{n!=null&&n.theme&&(Oe(n.theme),Ie(n.theme))},[n==null?void 0:n.theme]),a.useEffect(()=>{var R;if(((R=n==null?void 0:n.theme)==null?void 0:R.mode)!=="system")return;const w=window.matchMedia("(prefers-color-scheme: light)"),y=()=>{n!=null&&n.theme&&(Oe(n.theme),Ie(n.theme))};return w.addEventListener("change",y),()=>w.removeEventListener("change",y)},[n==null?void 0:n.theme]),a.useEffect(()=>{const w=()=>{g(R=>R+1),O().catch(()=>{})},y=()=>{document.visibilityState==="visible"&&w()};return window.addEventListener("online",w),window.addEventListener("pageshow",w),document.addEventListener("visibilitychange",y),()=>{window.removeEventListener("online",w),window.removeEventListener("pageshow",w),document.removeEventListener("visibilitychange",y)}},[O]),a.useEffect(()=>{const w=new kt,y=w.on(R=>{if(R.type==="snapshot"&&"data"in R&&R.data)x(B=>({...B??{},...R.data}));else if(R.type==="change")O().catch(()=>{});else if(R.type==="tasks:change"){const B=R.task;x(z=>{if(!z)return z;const G=(z.tasks||[]).map(te=>te.id===B.id?B:te),le=G.some(te=>te.id===B.id);return{...z,tasks:le?G:[B,...G]}})}else R.type==="tasks:delete"?x(B=>B&&{...B,tasks:(B.tasks||[]).filter(z=>z.id!==R.id)}):R.type==="settings:change"?R.settings&&f(R.settings):R.type==="project:change"||R.type==="agents:change"||R.type==="schedules:change"||R.type==="artifact:change"?O().catch(()=>{}):(R.type==="agent:status"||R.type==="agent:restarted")&&x(B=>{if(!B)return B;const z=(B.agents||[]).map(G=>G.name===R.agent.name?R.agent:G);return{...B,agents:z}})});return()=>{y(),w.close()}},[O,k]);const I=a.useCallback(w=>{(w==="activity"||w==="chat"||w==="tasks"||w==="settings"||w==="more")&&_(w)},[_]),L=a.useCallback((w,y,R)=>{if(w==="notification"){const B=Bn({link:y||null,meta:R??null});B&&S(B);return}if(w==="task"&&y){S({id:"task-detail",taskId:y});return}if(w==="artifacts?"&&y){S({id:"artifacts?-detail",slug:y});return}if(w==="agent"&&y){S({id:"agent-detail",name:y});return}if(w==="project"){_("activity");return}w==="setting"&&_("settings")},[_,S]),j=()=>{if(!m||!n)return null;if(i.length>0){const w=i[i.length-1];switch(w.id){case"artifacts?":return e.jsx(un,{snapshot:m,onBack:C,onOpenArtifact:y=>S({id:"artifacts?-detail",slug:y})});case"agents":return e.jsx(dt,{snapshot:m,onBack:C,onOpenAgent:y=>S({id:"agent-detail",name:y}),onRefresh:O});case"skills":return e.jsx(zn,{snapshot:m,onBack:C});case"mods":return e.jsx(ln,{snapshot:m,onBack:C});case"schedules":return e.jsx(xn,{snapshot:m,onBack:C});case"history":return e.jsx(an,{onBack:C});case"config":return e.jsx(nn,{onBack:C});case"artifacts?-detail":return e.jsx(rn,{slug:w.slug,onBack:C});case"agent-detail":return e.jsx(dt,{snapshot:m,onBack:C,onOpenAgent:()=>{},onRefresh:O,selectedAgent:w.name});case"task-detail":return e.jsx(ft,{snapshot:m,onRefresh:O,selectedTaskId:w.taskId,onCloseDetail:C,onOpenChat:y=>{l(y),_("chat")}});default:return null}}switch(t){case"activity":return e.jsx(Qs,{snapshot:m,onRefresh:O});case"chat":return e.jsx(sn,{snapshot:m,settings:n,initialTaskId:r,onClearTaskId:()=>l(null)});case"tasks":return e.jsx(ft,{snapshot:m,onRefresh:O,onOpenChat:w=>{l(w),_("chat")}});case"settings":return e.jsx($n,{settings:n,snapshot:m,onRefresh:O});case"more":return e.jsx(on,{snapshot:m,onNavigate:w=>{(w==="artifacts?"||w==="agents"||w==="skills"||w==="mods"||w==="schedules"||w==="history"||w==="config")&&S({id:w})}});default:return null}};return h?e.jsxs("div",{className:"mobile-loading",children:[e.jsx(wt,{size:"lg"}),e.jsx("p",{children:"Loading Bizar…"})]}):v||!m||!n?e.jsxs("div",{className:"mobile-loading",children:[e.jsx("h2",{children:"Dashboard unavailable"}),e.jsx("p",{children:v||"Dashboard server unreachable."}),e.jsx("p",{className:"muted",children:"Make sure the Bizar dashboard server is running."})]}):e.jsxs("div",{className:"mobile-app",children:[e.jsx(Ks,{activeTab:u.id,snapshot:m,onSearch:()=>d(!0),onNavigate:L}),e.jsx("main",{className:"mobile-content",children:j()}),i.length===0&&e.jsx(qs,{tabs:On,activeTab:t,onChange:I}),i.length>0&&e.jsx("button",{type:"button",className:"mobile-back-btn",onClick:C,"aria-label":"Go back",children:"← Back"}),e.jsx(Sn,{open:o,onClose:()=>d(!1),onNavigate:L})]})}export{Ee as A,ve as B,Ps as C,$s as E,Hn as M,wt as S,Vn as T,Es as V,kt as W,St as _,$ as a,Ns as b,Ge as c,ps as d,Us as e,ye as f,_s as g,Is as h,Ds as i,gs as j,Ie as k,Oe as l,Yn as m,fs as p,Wn as t,vs as u};