@adhdev/daemon-standalone 0.9.82-rc.542 → 0.9.82-rc.543

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.
@@ -50,7 +50,7 @@ ${JSON.stringify(t,null,2)}
50
50
  `),ye=((fe=ie[0])==null?void 0:fe.slice(0,80))||"(empty)";return s.jsxs("div",{className:"border border-border-default rounded overflow-hidden bg-surface-secondary",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2.5 py-1.5 hover:bg-bg-glass-hover transition-colors text-left",onClick:()=>be(U),children:[s.jsx("span",{className:"text-[10px] text-text-muted w-3",children:Z?"▾":"▸"}),s.jsx("span",{className:"font-mono text-accent-primary w-20 shrink-0 text-[11px]",children:U}),!Z&&s.jsx("span",{className:"text-text-secondary truncate font-mono text-[11px]",children:ye}),s.jsxs("span",{className:"ml-auto text-text-muted text-[10px] shrink-0",children:[ie.length,"L"]})]}),Z&&s.jsx("pre",{className:"px-3 pb-2.5 pt-1 font-mono text-[11px] text-text-secondary whitespace-pre-wrap break-all bg-bg-secondary max-h-40 overflow-y-auto border-t border-border-default",children:W||"(empty)"})]},U)})})]}),s.jsx(Nn,{}),V.stateHistory&&V.stateHistory.length>0&&s.jsxs("div",{children:[s.jsxs(kn,{children:["State History (",V.stateHistory.length,")"]}),s.jsx("div",{className:"space-y-px",children:[...V.stateHistory].reverse().slice(0,20).map((U,W)=>s.jsxs("div",{className:"rounded px-2 py-1 hover:bg-bg-glass-hover transition-colors",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:`font-mono text-[11px] font-semibold px-1.5 py-0.5 rounded shrink-0 ${Za(U.stateId)}`,children:U.stateId}),s.jsx("span",{className:"text-text-secondary text-[11px] shrink-0 tabular-nums",children:Pr(U.at)}),U.durationMs>0&&s.jsxs("span",{className:"text-text-muted text-[11px]",children:["held ",s.jsx("span",{className:"text-text-secondary",children:cc(U.durationMs)})]}),U.reason&&s.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-mono shrink-0 ${Fy[String(U.reason)]??"text-text-secondary bg-bg-glass border border-border-default"}`,children:String(U.reason)}),U.debounceKind&&String(U.debounceKind)!=="none"&&s.jsxs("span",{className:"text-text-muted text-[10px] font-mono",children:["debounce:",String(U.debounceKind)]}),U.matchedStateId&&String(U.matchedStateId)!==U.stateId&&s.jsxs("span",{className:"text-text-muted text-[10px] font-mono",children:["eval→",s.jsx("span",{className:"text-text-secondary",children:String(U.matchedStateId)})]})]}),U.matchedRules&&U.matchedRules.length>0&&s.jsxs("div",{className:"flex items-start gap-1 flex-wrap mt-0.5 ml-1 pl-1 border-l border-border-default",children:[U.matchedRules.slice(0,3).map((Z,ie)=>s.jsx("span",{className:"font-mono text-[10px] text-accent-primary bg-accent-primary/20 border border-accent px-1.5 py-0.5 rounded break-all",children:typeof Z=="string"?Z:JSON.stringify(Z)},ie)),U.matchedRules.length>3&&s.jsxs("span",{className:"text-[10px] text-text-muted",children:["+",U.matchedRules.length-3," more"]})]})]},W))})]}),s.jsx(Nn,{}),(()=>{const U=V.messages??V.committedMessages??[];if(U.length===0)return null;const W=U.filter(ye=>ye.role==="user").length,Z=U.filter(ye=>ye.role==="assistant").length,ie=[...U].reverse().find(ye=>ye.role==="assistant");return s.jsxs("div",{children:[s.jsxs(kn,{children:["Transcript (",U.length," — ",W,"u / ",Z,"a)"]}),ie&&s.jsxs("div",{className:"bg-surface-secondary border border-border-default rounded-md p-2.5 text-[11px]",children:[s.jsxs("div",{className:"text-text-muted mb-1 text-[10px]",children:["Last assistant ",ie.receivedAt?Pr(ie.receivedAt):""]}),s.jsxs("div",{className:"text-text-secondary font-mono whitespace-pre-wrap line-clamp-4 break-all",children:[ie.content.slice(0,400),ie.content.length>400?"…":""]})]})]})})(),V.specPath&&s.jsx("div",{className:"text-[10px] text-text-muted font-mono truncate border-t border-border-default pt-2 mt-1",title:V.specPath,children:V.specPath}),s.jsxs("div",{children:[s.jsxs("button",{type:"button",className:"text-[11px] text-text-secondary hover:text-text-primary transition-colors flex items-center gap-1.5",onClick:()=>u(U=>!U),children:[s.jsx("span",{className:"text-text-muted",children:p?"▾":"▸"}),s.jsxs("span",{children:["Raw screen (",V.screen?V.screen.split(`
51
51
  `).length:0," lines)"]})]}),p&&s.jsx("pre",{className:"mt-1.5 px-3 py-2 font-mono text-[11px] text-text-secondary whitespace-pre bg-bg-secondary rounded-md border border-border-default max-h-64 overflow-auto",children:V.screen||"(empty)"})]})]})]})]})})}function Ky({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,isVisible:i=!0,isInputActive:c=!0}){var Ue;hs();const{sendPtyInput:d}=xt(),[p,u]=l.useState(!1),m=l.useRef(!1);m.current=p;const[h,y]=l.useState("Runtime terminal unavailable"),[x,f]=l.useState(!1),[j,k]=l.useState(null),[b,w]=l.useState(!1),[I,v]=l.useState(!1),[g,S]=l.useState(1),[N,C]=l.useState(!1),[R,T]=l.useState(!1),[_,P]=l.useState(!1),[B,z]=l.useState(!1),[A,O]=l.useState(!1),[$,L]=l.useState({width:0,height:0}),[E,M]=l.useState({width:0,height:0}),[H,Y]=l.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[G,J]=l.useState(null),te=l.useRef(null),oe=l.useRef(null),q=l.useRef(!1),F=l.useRef(!1),V=l.useRef(i),pe=l.useRef(0),be=l.useRef(!1),ue=l.useRef(""),Ne=l.useRef(null),se=l.useRef(!1),ve=l.useRef(!1),me=l.useRef(null),U=l.useRef(null),W=l.useRef(null),Z=32*1024,ie=()=>{var ne,de,ge,$e;return((de=(ne=te.current)==null?void 0:ne.ownerDocument)==null?void 0:de.defaultView)||(($e=(ge=oe.current)==null?void 0:ge.ownerDocument)==null?void 0:$e.defaultView)||window},ye=ne=>{const de=ie();return{ownerWindow:de,frameId:de.requestAnimationFrame(ne)}},fe=()=>{const ne=me.current;if(ne){try{ne.ownerWindow.cancelAnimationFrame(ne.frameId)}catch{}me.current=null}},D=()=>{const ne=U.current;if(ne){try{ne.ownerWindow.clearTimeout(ne.timeoutId)}catch{}U.current=null}},he=()=>{const ne=W.current;if(ne){try{ne.ownerWindow.clearTimeout(ne.timeoutId)}catch{}W.current=null}},Se=()=>{i&&me.current===null&&(me.current=ye(()=>{Lt()}))},ae=e.tabKey,Q=e.sessionId||"",we=e.daemonId||((Ue=e.routeId)==null?void 0:Ue.split(":")[0])||e.routeId||"",ke=Ri(e),Le=p?o||ke:h,We=ky,ce=Ny,Ee=.05,Be=()=>{const ne=E.width,de=E.height;if(!Number.isFinite($.width)||$.width<=0||!Number.isFinite($.height)||$.height<=0||!Number.isFinite(ne)||ne<=0||!Number.isFinite(de)||de<=0)return 1;const ge=$.width/ne,$e=$.height/de;return Number(Math.min(ce,Math.max(We,Math.min(ge,$e))).toFixed(2))},Je=Be(),qe=q.current&&g>Je,je=Number.isFinite(E.width)&&E.width>0?Math.max($.width,Math.round(E.width*g)):$.width,at=Number.isFinite(E.height)&&E.height>0?Math.max($.height,Math.round(E.height*g)):$.height,Ie=()=>{ye(()=>{const ne=oe.current;ne&&(ne.scrollLeft=0,ne.scrollTop=ne.scrollHeight-ne.clientHeight)})},ot=()=>{var ne,de;pe.current=0,be.current=!1,ue.current="",Ne.current=null,se.current=!1,ve.current=!1,q.current||(F.current=!1,S(1)),me.current!==null&&fe(),u(!1),y("Runtime terminal unavailable"),he(),D(),k(null),J(null),C(!1),f(!1),w(!1),v(!1),(de=(ne=r.current)==null?void 0:ne.reset)==null||de.call(ne)},nt=()=>{var ne,de;pe.current=0,be.current=!1,ue.current="",Ne.current=null,se.current=!1,ve.current=!1,me.current!==null&&fe(),u(!0),y(""),he(),D(),k(null),J(null),C(!1),f(!1),w(!1),v(!1),(de=(ne=r.current)==null?void 0:ne.reset)==null||de.call(ne)},Qe=()=>{ve.current&&(ve.current=!1,ye(()=>{var ne,de;(de=(ne=r.current)==null?void 0:ne.scrollToTop)==null||de.call(ne)}))},Lt=()=>{if(me.current=null,!i)return;const ne=ue.current;if(!ne)return;const de=ne.slice(0,Z);ue.current=ne.slice(de.length);const ge=r.current;if(!ge){ue.current=de+ue.current,Se();return}ge.write(de,()=>{if(ue.current.length>0){Se();return}Qe()})},X=ne=>{ne&&(ue.current+=ne,Se())},ee=(ne,de=0,ge,$e,Fe={})=>{var Ze,rt,Ge,Nt;const Ye=!!Fe.force;!Ye&&de>0&&pe.current>=de||!Ye&&de===0&&be.current||(pe.current=de,de>0&&w(!0),u(!0),y(""),typeof ge=="number"&&typeof $e=="number"&&ge>0&&$e>0&&((rt=(Ze=r.current)==null?void 0:Ze.resize)==null||rt.call(Ze,ge,$e)),ue.current="",(Nt=(Ge=r.current)==null?void 0:Ge.reset)==null||Nt.call(Ge),ne?X(ne):Qe())};l.useEffect(()=>{ot()},[Q]),l.useEffect(()=>{var de;if(!Q)return;const ne=((de=bt.onRuntimeEvent)==null?void 0:de.call(bt,Q,ge=>{if(!(!ge||ge.sessionId!==Q)){if(ge.type==="runtime_snapshot"){if(!i){Ne.current={text:ge.text||"",seq:ge.seq||0,cols:ge.cols,rows:ge.rows,force:!!ge.force};return}ee(ge.text||"",ge.seq||0,ge.cols,ge.rows,{force:!!ge.force});return}if(ge.type==="session_output"){be.current=!0,typeof ge.seq=="number"&&(pe.current=Math.max(pe.current,ge.seq),ge.seq>0&&w(!0)),m.current||u(!0),m.current||y(""),typeof ge.data=="string"&&X(ge.data);return}if(ge.type==="session_cleared"){if(!i){se.current=!0,ue.current="",Ne.current=null;return}nt();return}if(ge.type==="session_io_error"){const $e=typeof ge.error=="string"&&ge.error?ge.error:typeof ge.reason=="string"&&ge.reason?ge.reason:"unknown error";u(!1),y(`Runtime input failed: ${$e}`);return}}},we))||(()=>{});return()=>{ne()}},[we,Q,r,i]);const re=async(ne={})=>{var de;if(!we||!Q)return{success:!1,error:"daemonId and sessionId are required"};ne.preserveStatus||y(ne.loadingMessage||"Loading runtime terminal...");try{const ge=await((de=bt.requestRuntimeSnapshot)==null?void 0:de.call(bt,we,Q,{sinceSeq:ne.sinceSeq,force:ne.force}));return ge&&ge.success===!1?(ne.preserveStatus||(u(!1),y(`Runtime terminal unavailable: ${ge.error}`)),ge):ge||{success:!0}}catch(ge){const $e=(ge==null?void 0:ge.message)||String(ge);return ne.preserveStatus||(u(!1),y(`Runtime terminal unavailable: ${$e}`)),{success:!1,error:$e}}},le=async ne=>{var Ye,Ze;const de=((Ye=te.current)==null?void 0:Ye.ownerDocument)||document,ge=de.defaultView||window,$e=(Ze=ge.navigator)==null?void 0:Ze.clipboard;if($e!=null&&$e.writeText&&ge.isSecureContext)try{return await $e.writeText(ne),!0}catch{}let Fe=null;try{return Fe=de.createElement("textarea"),Fe.value=ne,Fe.setAttribute("readonly","true"),Fe.style.position="fixed",Fe.style.left="-9999px",Fe.style.top="0",de.body.appendChild(Fe),Fe.focus(),Fe.select(),de.execCommand("copy")}catch{return!1}finally{Fe==null||Fe.remove()}},xe=ne=>{D(),J(ne);const de=ie();U.current={ownerWindow:de,timeoutId:de.setTimeout(()=>{U.current=null,J(ge=>ge===ne?null:ge)},2200)}},Ae=ne=>{he(),k(ne);const de=ie();W.current={ownerWindow:de,timeoutId:de.setTimeout(()=>{W.current=null,k(ge=>ge===ne?null:ge)},2200)}},De=async()=>{var Fe,Ye,Ze,rt;const ne=((Ye=(Fe=r.current)==null?void 0:Fe.getSelection)==null?void 0:Ye.call(Fe))||"",de=((rt=(Ze=r.current)==null?void 0:Ze.getVisibleText)==null?void 0:rt.call(Ze))||"",ge=ne.trimEnd()||de.trimEnd();if(!ge){xe("Nothing to copy");return}if(!await le(ge)){xe("Copy failed");return}xe(ne.trimEnd()?"Copied selection":"Copied visible terminal")},Ce=ne=>{if(!p||!i)return;((d==null?void 0:d(we,Q,ne))??!1)||xe("Terminal input failed")},Re=ne=>{Ce(Cy({ctrl:R,alt:_,shift:B},ne)),T(!1),P(!1),z(!1)},He=async()=>{if(x)return;f(!0),k("Loading older terminal output..."),ve.current=!0;const ne=await re({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:p});if(f(!1),(ne==null?void 0:ne.success)===!1){ve.current=!1,k(`Older terminal output unavailable: ${ne.error}`);return}v(!0),Ae("Older terminal output loaded"),ye(()=>{var de;(de=r.current)==null||de.bumpResize()})};l.useEffect(()=>{var de,ge;if(!Q)return;we&&((de=bt.getState)==null?void 0:de.call(bt,we))==="connected"&&re();const ne=(ge=bt.onStateChange)==null?void 0:ge.call(bt,($e,Fe)=>{$e!==we||Fe!=="connected"||re()});return()=>{ne==null||ne()}},[we,Q,r]),l.useEffect(()=>{t&&ot()},[t,ae,r]),l.useEffect(()=>{var $e,Fe;const ne=te.current,de=(Fe=($e=ne==null?void 0:ne.ownerDocument)==null?void 0:$e.defaultView)==null?void 0:Fe.ResizeObserver;if(!ne||!de)return;const ge=new de(Ye=>{const Ze=Ye[0];if(!Ze)return;const{width:rt,height:Ge}=Ze.contentRect;L(Nt=>{const Jt=Math.round(rt),Ht=Math.round(Ge);return Nt.width===Jt&&Nt.height===Ht?Nt:{width:Jt,height:Ht}})});return ge.observe(ne),()=>ge.disconnect()},[]),l.useEffect(()=>{if(q.current)return;const ne=Be();!Number.isFinite(ne)||ne<=0||S(de=>F.current?ne<de-Ee?ne:de:(F.current=!0,ne))},[E.height,E.width,$.height,$.width]),l.useEffect(()=>{qe&&Ie()},[qe,at,je]),l.useEffect(()=>{var ge;const ne=V.current;if(V.current=i,!i)return;ne||v(!1),se.current&&(se.current=!1,nt());const de=Ne.current;de&&(Ne.current=null,ee(de.text,de.seq,de.cols,de.rows,{force:!!de.force})),we&&Q&&((ge=bt.getState)==null?void 0:ge.call(bt,we))==="connected"&&re(),ue.current&&me.current===null&&Se(),ye(()=>{var $e;($e=r.current)==null||$e.bumpResize()})},[we,i,Q]),l.useEffect(()=>()=>{me.current!==null&&fe(),D(),he()},[]),l.useEffect(()=>{const ne=$e=>{var Ye;const Fe=$e.detail;Fe!=null&&Fe.sessionId&&Fe.sessionId!==Q||p&&((Ye=r.current)==null||Ye.bumpResize())},de=ie(),ge=de===window?[window]:[window,de];for(const $e of ge)$e.addEventListener("adhdev:fit-cli-terminal",ne);return()=>{for(const $e of ge)$e.removeEventListener("adhdev:fit-cli-terminal",ne)}},[p,Q,r]);const Oe=p&&b&&!I&&(H.atTop||!H.canScroll)||x||!!j;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:te,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[Oe&&s.jsxs("div",{className:"absolute left-3 top-3 z-10 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-medium text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{He()},disabled:!Q||x,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:x?"Loading older...":"Load older terminal output"}),j&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:j})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[G&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:G}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>O(ne=>!ne),title:"Spec debug — inspect current state, sections, and transition history",children:"Debug"}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{De()},disabled:!p,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:"Copy"}),s.jsxs("div",{className:"relative",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>C(ne=>!ne),disabled:!p,"aria-label":"Open terminal control keys","aria-expanded":N,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),N&&s.jsxs("div",{id:"terminal-control-keys-popover",role:"dialog","aria-label":"Terminal control keys",className:"absolute right-0 top-10 w-72 rounded-2xl border border-white/10 bg-[#0b0d12]/95 p-3 text-white/85 shadow-2xl shadow-black/40 backdrop-blur-md",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Terminal keys"}),s.jsx("button",{type:"button",className:"rounded-full px-2 py-0.5 text-[11px] text-white/55 transition-colors hover:bg-white/10 hover:text-white/85",onClick:()=>C(!1),"aria-label":"Close terminal control keys",children:"×"})]}),s.jsx("div",{className:"mb-2 grid grid-cols-3 gap-1.5",children:[["Ctrl",R,T],["Alt",_,P],["Shift",B,z]].map(([ne,de,ge])=>s.jsx("button",{type:"button","aria-pressed":de,className:`h-9 rounded-lg border text-[12px] font-semibold transition-colors ${de?"border-sky-400/50 bg-sky-400/25 text-white":"border-white/10 bg-white/[0.06] hover:bg-white/[0.12]"}`,onClick:()=>ge($e=>!$e),children:ne},ne))}),s.jsx("div",{className:"grid grid-cols-6 gap-1",children:"abcdefghijklmnopqrstuvwxyz0123456789".split("").map(ne=>s.jsx("button",{type:"button",className:"h-8 rounded-md border border-white/10 bg-white/[0.06] text-[12px] font-semibold uppercase hover:bg-white/[0.12]",onClick:()=>Re(ne),children:ne},ne))}),s.jsx("div",{className:"my-2 h-px bg-white/10"}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Re("Escape"),children:"Esc"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Re("Tab"),children:"Tab"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Re("Enter"),children:"Enter"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Re("ArrowUp"),"aria-label":"Arrow up",children:"↑"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Re("ArrowLeft"),"aria-label":"Arrow left",children:"←"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Re("ArrowDown"),"aria-label":"Arrow down",children:"↓"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Re("ArrowRight"),"aria-label":"Arrow right",children:"→"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ce(""),title:"Send SIGINT (Ctrl-C)",children:"Ctrl-C"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Re("Space"),children:"Space"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Re("Backspace"),children:"Bksp"})]})]})]}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{q.current=!0,S(ne=>{const de=Math.max(Je,Number((ne-.1).toFixed(2)));return de>Je&&Ie(),de})},title:"Shrink terminal viewport",children:"-"}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{q.current=!0,S(ne=>{const de=Math.min(ce,Number((ne+.1).toFixed(2)));return de>Je&&Ie(),de})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:oe,className:qe?"w-full h-full overflow-auto rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",children:s.jsx("div",{style:{width:je>0?`${je}px`:"100%",height:at>0?`${at}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:E.width>0?`${E.width}px`:"100%",height:E.height>0?`${E.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:g},children:s.jsx(Jd,{ref:r,readOnly:!p||!i,sizingMode:"measured",onViewportMetrics:M,onScrollMetrics:Y,onInput:ne=>{!p||(d==null||d(we,Q,ne))}})})})}),!p&&s.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:h})]}),s.jsx(hu,{contextKey:e.tabKey,panelLabel:ft(e),isSending:a,isBusy:!!ke,statusMessage:Le,inlineStatusMessage:Le,onSend:async ne=>ke?!1:n(ne),isActive:c&&i,showControlsToggle:!1,animateVisibility:!1}),A&&s.jsx(Wy,{activeConv:e,onClose:()=>O(!1)})]})}const Uy=5e3,zy=12e3;function Gy(e){return e==="disconnected"||e==="reconnecting"}function Vy({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=Uy,reconnectActionDelayMs:o=zy}){const i=Gy(e),[c,d]=l.useState(()=>!i||a<=0),[p,u]=l.useState(()=>!i||o<=0),m=l.useRef(!1);l.useEffect(()=>{if(!i){d(!1);return}if(m.current=!1,a<=0){m.current=!0,d(!0);return}d(!1);const v=setTimeout(()=>{m.current=!0,d(!0)},a);return()=>clearTimeout(v)},[a,i]),l.useEffect(()=>{if(!i){u(!1);return}if(o<=0){u(!0);return}u(!1);const v=setTimeout(()=>{u(!0)},o);return()=>clearTimeout(v)},[o,i]);const h=i?c:e==="offline"||e==="auth_failed",y=!!(n&&e!=="auth_failed"&&(!i||p)),x=l.useMemo(()=>!t||e!=="connected"?!1:a<=0||m.current,[a,t,e]),f=e==="auth_failed"?"red":e==="offline"?"orange":"accent",j={red:"linear-gradient(90deg, rgba(239,68,68,0.12), rgba(239,68,68,0.04))",orange:"linear-gradient(90deg, rgba(255,107,53,0.12), rgba(255,107,53,0.04))",accent:"linear-gradient(90deg, color-mix(in srgb, var(--accent-primary) 18%, transparent), color-mix(in srgb, var(--accent-primary) 6%, transparent))"},k={red:"1px solid rgba(239,68,68,0.2)",orange:"1px solid rgba(255,107,53,0.2)",accent:"1px solid color-mix(in srgb, var(--accent-primary) 28%, transparent)"},b={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},w="fixed left-1/2 top-4 z-[var(--z-toast)] flex items-center justify-center pointer-events-none",I={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[h&&s.jsx("div",{className:w,style:I,children:s.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-3 py-2.5 sm:px-4 sm:py-3 text-[13px] font-semibold flex flex-wrap items-center gap-x-2.5 gap-y-2 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:j[f],border:k[f],color:b[f]},children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5 shrink-0",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),s.jsxs("span",{className:"min-w-0 text-center whitespace-nowrap",children:[e==="offline"&&"Network offline",e==="disconnected"&&"Reconnecting",e==="reconnecting"&&"Reconnecting",e==="auth_failed"&&(r?s.jsxs(s.Fragment,{children:["Session expired."," ",s.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — refresh the page or try again shortly.")]}),y&&s.jsx("button",{type:"button",className:"basis-full sm:basis-auto mx-auto sm:mx-0 sm:ml-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-[12px] font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>n==null?void 0:n(),disabled:e==="offline",children:"Reconnect now"})]})}),x&&s.jsx("div",{className:w,style:I,children:s.jsxs("div",{className:"pointer-events-none rounded-2xl border px-4 py-2 text-xs font-semibold flex items-center gap-2 justify-center bg-gradient-to-r from-green-500/[0.12] to-green-500/[0.04] text-green-400 border-green-500/15 shadow-[0_18px_40px_rgba(2,6,23,0.2)] backdrop-blur-xl animate-[fadeIn_0.3s_ease]",children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})})]})}function Qu({mode:e,onChange:t,compact:r=!1}){const n=r?14:15;return s.jsx("button",{type:"button",onClick:()=>t(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:e==="chat"?"Switch to Terminal view":"Switch to Chat view",children:e==="chat"?s.jsx(vi,{size:n}):s.jsx(Xs,{size:n})})}const us="New session",Zu="A connected machine is ready. Start a new session with any installed provider — CLI, ACP, or IDE.";function qy(e){if(!e||e.isGitRepo===!1||e.reason==="not_git_repo")return null;if(e.hasConflicts)return`${e.branch||"Git"} · conflicts${e.changedFiles>0?` ${e.changedFiles}`:""}`;const t=[e.branch||"Git"];return e.changedFiles>0&&t.push(`±${e.changedFiles}`),e.ahead>0&&t.push(`↑${e.ahead}`),e.behind>0&&t.push(`↓${e.behind}`),t.length===1&&e.dirty&&t.push("dirty"),t.join(" ")}function Yy(e){return!e||e.isGitRepo===!1||e.reason==="not_git_repo"?null:e.hasConflicts?"conflict":e.error?"error":e.dirty||e.changedFiles>0||e.ahead>0||e.behind>0?"dirty":"quiet"}function Jy(e){switch(e){case"conflict":return"border-status-error/40 bg-status-error/10 text-status-error";case"error":return"border-yellow-500/25 bg-yellow-500/[0.08] text-yellow-500";case"dirty":return"border-orange-500/25 bg-orange-500/[0.08] text-orange-400";case"quiet":default:return"border-status-online/40 bg-status-online/10 text-status-online"}}function aa({git:e,className:t="",compact:r=!1}){const n=qy(e),a=Yy(e);if(!n||!a)return null;const o=[e!=null&&e.branch?`Branch: ${e.branch}`:null,e!=null&&e.changedFiles?`Changed files: ${e.changedFiles}`:null,e!=null&&e.ahead?`Ahead: ${e.ahead}`:null,e!=null&&e.behind?`Behind: ${e.behind}`:null,e!=null&&e.hasConflicts?"Conflicts detected":null,e!=null&&e.error?`Git error: ${e.error}`:null].filter(Boolean);return s.jsxs("span",{className:`inline-flex min-w-0 max-w-[12rem] items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-semibold leading-none ${Jy(a)} ${t}`.trim(),title:o.join(" · ")||n,"data-git-tone":a,children:[s.jsx("span",{"aria-hidden":"true",children:"⑂"}),s.jsx("span",{className:"truncate",children:n})]})}function Xy({wsStatus:e,isConnected:t,daemonCount:r,p2pStates:n={}}){if(e!=="connected")return{tone:"disconnected",title:"Disconnected",subtitle:null};const a=Object.values(n),o=a.filter(c=>c==="connected").length,i=a.filter(c=>c==="connecting"||c==="new"||c==="checking").length;return r>0&&i>0&&o===0?{tone:"limited",title:"Connected to dashboard",subtitle:"Connecting to machine..."}:t?{tone:"connected",title:"Connected",subtitle:null}:{tone:"limited",title:"Connected to dashboard",subtitle:null}}function dc({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function uc({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:o}){const i=wa(e.updatedAt),c=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${c?"is-attention":""}`.trim(),children:[s.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:r,children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[t?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",t]}):null,[e.type==="needs_attention"?"Action needed":"Task complete",i].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[c?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),n()},children:"Mark read"}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),a()},children:"Mark unread"}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),o()},children:"Delete"})]})]})}function Qy({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:o,onStopCli:i,activeCliViewMode:c,onSetCliViewMode:d,onHideConversation:p,hiddenConversations:u=[],onShowConversation:m,onShowAllHidden:h,onResetPanelsToMain:y,inboxOpen:x,onInboxOpenChange:f,hiddenOpen:j,onHiddenOpenChange:k,onOpenNewSession:b,onOpenDashboardGuide:w,guideNudgeVisible:I=!1,actionShortcuts:v,notifications:g,notificationUnreadCount:S,onOpenNotification:N,onMarkNotificationRead:C,onMarkNotificationUnread:R,onDeleteNotification:T,onOpenGitDialog:_,onOpenMeshGraph:P}){var Ne;const{ides:B,p2pStates:z={}}=hs(),A=!!e&&lt(e)&&!it(e),O=!!e&&it(e),$=!!(e!=null&&e.daemonId)&&!!((Ne=e==null?void 0:e.coordinator)!=null&&Ne.meshId),L=c||(e?ju(e)?"terminal":"chat":null),[E,M]=l.useState(!1),H=l.useRef(null),Y=l.useRef(null),G=B.filter(se=>se.type==="adhdev-daemon"),J=Xy({wsStatus:t,isConnected:r,daemonCount:G.length,p2pStates:z}),te=J.subtitle,oe=J.tone==="connected"?"#22c55e":J.tone==="limited"?"#eab308":"#ef4444",q=J.tone==="connected"?"0 0 4px #22c55e80":J.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",F=l.useMemo(()=>g.filter(se=>!se.readAt),[g]),V=l.useMemo(()=>g.filter(se=>!!se.readAt),[g]),pe=l.useMemo(()=>F.slice(0,9),[F]),be=S;l.useEffect(()=>{if(!x)return;const se=ve=>{var me;(me=H.current)!=null&&me.contains(ve.target)||f(!1)};return document.addEventListener("mousedown",se),()=>document.removeEventListener("mousedown",se)},[x,f]),l.useEffect(()=>{if(!j)return;const se=ve=>{var me;(me=Y.current)!=null&&me.contains(ve.target)||k(!1)};return document.addEventListener("mousedown",se),()=>document.removeEventListener("mousedown",se)},[j,k]),l.useEffect(()=>{if(!j&&!x)return;const se=ve=>{if(!ve.altKey)return;const me=ve.code.match(/^Digit([1-9])$/);if(!me)return;const U=Number(me[1])-1,W=j?u[U]:void 0,Z=x?pe[U]:void 0;if(!(!W&&!Z)){if(ve.preventDefault(),ve.stopPropagation(),W){m==null||m(W),k(!1);return}Z&&(N(Z),f(!1))}};return window.addEventListener("keydown",se,!0),()=>window.removeEventListener("keydown",se,!0)},[u,j,x,pe,k,f,N,m]);const ue=se=>{if(!se)return;const ve=n.find(me=>me.tabKey===se);ve&&(p==null||p(ve))};return s.jsxs("div",{className:"dashboard-header",children:[s.jsx("div",{className:"flex items-center gap-3",children:s.jsx("div",{className:"header-title-block",children:s.jsxs("div",{className:"header-title-row",children:[s.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[s.jsx(Xs,{size:18}),s.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),s.jsx("span",{className:"header-title-mobile",children:e?ft(e):"Dashboard"}),s.jsx("span",{title:J.title,"aria-label":J.title,className:"header-title-status-dot",style:{background:oe,boxShadow:q}}),s.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:s.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:oe,boxShadow:q}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[te&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",te]}),b&&s.jsx("button",{type:"button",onClick:b,className:"btn btn-secondary btn-sm ml-2",title:`${us}${v!=null&&v.openNewSession?` (${v.openNewSession})`:""}`,"aria-label":us,children:s.jsx(wi,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[w&&s.jsxs("button",{type:"button",onClick:w,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:"Dashboard guide","aria-label":"Open dashboard guide",children:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),I&&s.jsx("span",{children:"Guide"})]}),e&&(A||O||!it(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:fr(e)||ft(e),children:ft(e)}),_&&e.git&&e.daemonId&&e.workspacePath?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:()=>_(e.daemonId,e.workspacePath),children:s.jsx(aa,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(aa,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),$&&P&&s.jsxs("button",{type:"button",onClick:()=>P(e),className:"btn btn-secondary btn-sm dashboard-header-mesh-button",title:"Open live repo mesh graph",children:[s.jsx(ss,{size:14}),s.jsx("span",{className:"hidden lg:inline",children:"Mesh graph"})]}),(A||O)&&i&&s.jsxs(s.Fragment,{children:[A&&d&&L&&s.jsx(Qu,{mode:L,onChange:d,compact:!0}),s.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:O?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(wt,{size:14})})]}),!it(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx(gi,{size:14})}),!A&&!it(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(os,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:H,children:[s.jsxs("div",{className:`dashboard-header-hidden${E?" is-drop-target":""}`,ref:Y,onDragEnter:se=>{se.dataTransfer.types.includes("text/tab-key")&&(se.preventDefault(),M(!0))},onDragOver:se=>{se.dataTransfer.types.includes("text/tab-key")&&(se.preventDefault(),se.dataTransfer.dropEffect="move",M(!0))},onDragLeave:se=>{se.currentTarget.contains(se.relatedTarget)||M(!1)},onDrop:se=>{const ve=se.dataTransfer.getData("text/tab-key");se.preventDefault(),M(!1),ue(ve)},children:[s.jsxs("button",{type:"button",onClick:()=>k(!j),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${v!=null&&v.toggleHiddenTabs?` (${v.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[s.jsx(yi,{size:16}),u.length>0&&s.jsx("span",{className:"dashboard-header-hidden-badge",children:u.length})]}),j&&s.jsxs("div",{className:"dashboard-header-hidden-popover",children:[s.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),s.jsx(dc,{value:v==null?void 0:v.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[y&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:y,children:"Reset panels"}),u.length>0&&h&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{h(),k(!1)},children:"Restore all"})]})]}),e&&p&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>p(e),children:[s.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[s.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),s.jsx(dc,{value:v==null?void 0:v.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:ft(e)})]}),u.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(se=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{m==null||m(se),k(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:ft(se)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(se)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(se)+1]}):null,fr(se)]})]},se.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>f(!x),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(wr,{size:16}),be>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:be})]}),x&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[F.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),F.map(se=>s.jsx(uc,{notification:se,shortcutIndex:pe.indexOf(se)>=0?pe.indexOf(se)+1:void 0,onOpen:()=>N(se),onMarkRead:()=>C(se.id),onMarkUnread:()=>R(se.id),onDelete:()=>T(se.id)},se.id))]}),V.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),V.map(se=>s.jsx(uc,{notification:se,onOpen:()=>N(se),onMarkRead:()=>C(se.id),onMarkUnread:()=>R(se.id),onDelete:()=>T(se.id)},se.id))]}),g.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function Dt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function Zy(e,t){return String(e||"")!==String(t||"")}function e0(e,t={}){const r=String(t.textQuery||"").trim().toLowerCase(),n=String(t.workspaceQuery||"").trim().toLowerCase(),a=String(t.modelQuery||"").trim().toLowerCase(),o=!!t.resumableOnly;return!r&&!n&&!a&&!o?e:e.filter(i=>!(o&&!i.canResume||r&&![i.title,i.preview].map(d=>String(d||"").toLowerCase()).join(`
52
52
  `).includes(r)||n&&!String(i.workspace||"").toLowerCase().includes(n)||a&&!lu(i.summaryMetadata).map(d=>d.toLowerCase()).join(`
53
- `).includes(a)))}function t0(e,t="recent"){const r=e.slice();return r.sort((n,a)=>{if(t==="oldest")return(Number(n.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(t==="messages"){const o=(Number(a.messageCount)||0)-(Number(n.messageCount)||0);if(o!==0)return o}return(Number(a.lastMessageAt)||0)-(Number(n.lastMessageAt)||0)}),r}function ep(e,t={}){return t0(e0(e,t),t.sortMode||"recent")}function oa(e){return e?"Resume saved history":"Start fresh"}function Ei(e){return e?"Resuming saved history…":"Starting fresh…"}function s0(){return"Start fresh"}function r0(e,t=!1){return e==="cli"?oa(t):e==="ide"?"Start IDE":"Start ACP session"}function n0(e,t=!1){return e==="cli"?Ei(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function a0(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function o0(){return"Open saved history"}function i0(){return"Saved History"}function Bi(){return"Use saved history when you want continuity in the same provider conversation."}function l0(){return"No saved history found yet."}function c0(){return"Refresh saved history"}function d0(){return"Refreshing saved history…"}function ia(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function la(e){return e==="start-fresh"?"Review the provider and target folder before starting fresh.":e==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function ca(e){return e==="start-fresh"?"Start fresh":"Restart"}function da(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function tp(e){return`Resume saved history with ${e}?`}function sp(){return"Review or change the target workspace before resuming saved history."}function u0(e){if(!e)return"";try{return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(e))}catch{return new Date(e).toLocaleString()}}function rp({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:c,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:p,onClose:u,onNewChat:m,onSwitchSession:h,onRefreshHistory:y,onResumeSavedSession:x}){var T;const f=t.find(_=>_.id===e.routeId),j=(f==null?void 0:f.chats)||[],k=(T=f==null?void 0:f.activeChat)==null?void 0:T.id,b=lt(e)&&!it(e),[w,I]=l.useState(()=>Dt()),v=c||w,g=String(d||"").trim(),S=_=>{if(p){p(_);return}I(_)},N=l.useMemo(()=>a.map(_=>{const P=String(_.workspace||"").trim();return _.canResume||P||!g?_:{..._,workspace:g,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[g,a]),C=l.useMemo(()=>ep(N,{textQuery:v.textQuery,workspaceQuery:v.workspaceQuery,modelQuery:v.modelQuery,resumableOnly:v.resumableOnly,sortMode:v.sortMode}),[N,v.modelQuery,v.resumableOnly,v.sortMode,v.textQuery,v.workspaceQuery]),R=s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:u,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:b?i0():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Ty(e)}),b&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Bi()})]}),s.jsx("button",{onClick:u,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(wt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!b&&s.jsx("button",{onClick:m,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),b?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[s.jsx("input",{type:"text",value:v.textQuery,onChange:_=>S({...v,textQuery:_.target.value}),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:v.workspaceQuery,onChange:_=>S({...v,workspaceQuery:_.target.value}),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:v.modelQuery,onChange:_=>S({...v,modelQuery:_.target.value}),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsxs("select",{value:v.sortMode,onChange:_=>S({...v,sortMode:_.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:v.resumableOnly,onChange:_=>S({...v,resumableOnly:_.target.checked})}),"Resume-ready only"]})]}),C.map(_=>{const P=e.providerSessionId===_.providerSessionId,B=P||!_.canResume||!!i,z=_.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{B||!x||x(_)},disabled:B,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${P?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${B?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${P?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:_.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:_.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:u0(_.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:_.preview||"No saved preview yet"}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[_.workspace||"Workspace unknown",z?" · selected workspace":"",qs(_.summaryMetadata)?` · ${qs(_.summaryMetadata)}`:"",_.messageCount>0?` · ${_.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:P?"ACTIVE":_.canResume?z?"RESUME IN SELECTED WORKSPACE":i===_.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},_.id)})]}):j.map(_=>s.jsxs("div",{onClick:()=>{h(e.routeId,_.id),u()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${k===_.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[s.jsx("div",{className:`font-bold text-sm mb-1 ${k===_.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:_.title||"Untitled Session"}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[_.id.substring(0,12),"..."]}),k===_.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},_.id)),(b&&!o&&C.length===0||!b&&j.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(Cf,{size:32})}),s.jsx("div",{className:"text-[13px]",children:b?a.length>0?"No saved history matches these filters.":l0():"No recent chat sessions found."})]}),b&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:d0()})})]}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:s.jsx("button",{onClick:y,disabled:n||o,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||o?"⌛ Refreshing...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(va,{size:13})," ",b?c0():"Refresh History"]})})})]})]});return typeof document>"u"?R:dr.createPortal(R,document.body)}const pc={success:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Done"},warning:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Attention"},info:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Update"}};function np({toasts:e,onDismiss:t,onClickToast:r}){return s.jsx("div",{className:"fixed right-4 z-[var(--z-toast)] flex flex-col gap-2 pointer-events-none",style:{top:"calc(env(safe-area-inset-top, 0px) + 16px)"},children:e.map(n=>{const a=pc[n.type]||pc.info;return s.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var o;(o=n.actions)!=null&&o.length||r&&r(n)},children:[s.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${a.accent}, color-mix(in srgb, ${a.accent} 55%, transparent))`}}),s.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:o=>{o.stopPropagation(),t(n.id)},"aria-label":"Dismiss",children:s.jsx(wt,{size:14})}),s.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[s.jsx("div",{className:"flex items-center gap-2 pr-8",children:s.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:a.chipBg,color:a.chipText,border:`1px solid color-mix(in srgb, ${a.accent} 22%, transparent)`},children:a.label})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((o,i)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${o.variant==="primary"||o.variant==="danger",""}`,style:o.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:o.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:c=>{c.stopPropagation(),o.onClick(),t(n.id)},children:o.label},i))})]})]},n.id)})})}const p0=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function m0(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function h0(e,t){return ap(e)||t}function ap(e){var a,o,i;const t=(o=(a=e.summaryMetadata)==null?void 0:a.items)==null?void 0:o.find(c=>(c==null?void 0:c.id)==="model"),r=((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim();if(r)return r;const n=(i=e.controlValues)==null?void 0:i.model;return typeof n=="string"&&n.trim()?n.trim():""}function f0(e){return ap(e)||void 0}function x0(e){return e.sessionId||e.instanceId||e.agentType}function op(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=Yt(r,{fallbackId:r.id}));return t}function ip(e,t={}){var n;const r=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:Px(e,t.machineNames),connectionState:t.connectionStates?t.connectionStates[r]||t.defaultConnectionState||"new":t.defaultConnectionState}}function Fi(e,t={}){return b0(e,ip(e,t))}function b0(e,t={}){var h,y,x,f,j,k,b,w,I;const r=[],n=t.machineName,a=t.connectionState,o=m0(e),i=e.workspace||"",c=Ox(e.type,{agentName:e.cliName}),d=lt(e)||it(e)?c:Tt(e.type),p=h0(e,d),u=Array.isArray(e.childSessions)?e.childSessions.map(v=>{var g,S,N;return{sessionId:v.id,instanceId:v.id,providerSessionId:v.providerSessionId,activeChatId:(g=v.activeChat)==null?void 0:g.id,transport:v.transport,sessionCapabilities:v.capabilities,agentType:v.providerType,agentName:v.providerName||Tt(v.providerType),model:f0(v),status:v.status,title:v.title,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,messages:((S=v.activeChat)==null?void 0:S.messages)||[],activeModal:((N=v.activeChat)==null?void 0:N.activeModal)||void 0,unread:v.unread,lastSeenAt:v.lastSeenAt,lastUpdated:v.lastUpdated,inboxBucket:v.inboxBucket,completionMarker:v.completionMarker,surfaceHidden:v.surfaceHidden,muted:v.muted,git:v.git,settings:v.settings,coordinator:v.coordinator,messageInput:v.messageInput}}):[],m=p0(e);if(m){const v=e.sessionId||e.instanceId,g=(h=e.settings)==null?void 0:h.meshCoordinatorFor,S=((y=e.settings)==null?void 0:y.meshNodeFor)||!((x=e.settings)!=null&&x.meshCoordinatorFor)&&((f=e.settings)==null?void 0:f.launchedByCoordinator),N=g?" (Coordinator)":S?" (Mesh Node)":"",C=c+N,R=(j=e.activeChat)==null?void 0:j.activeModal,T=R&&Array.isArray(R.buttons)&&R.buttons.length>0,_=Hx(e.activeChat,[{status:e.status,activeModal:(k=e.activeChat)==null?void 0:k.activeModal}],e.agents||[]),P=e.activeChat||{title:"",messages:[]};let B=P.title&&String(P.title).trim()?String(P.title).trim():"";const z=(b=e.activeChat)==null?void 0:b.id,A=e.chats;if(z&&Array.isArray(A)&&A.length>0){const G=A.find(J=>J.id===z||J.id&&String(J.id)===String(z));G!=null&&G.title&&String(G.title).trim()&&(B=String(G.title).trim())}const O=(lt(e)||it(e),e.type),$=(lt(e)||it(e))&&$l(B,C,O)?"":B,L=P.messages||[],E=typeof z=="string"?z.trim():"",M=(lt(e)||it(e))&&E===String(e.type||"").trim(),H=E&&!M?E:e.providerSessionId,Y=e.coordinator||(typeof((w=e.settings)==null?void 0:w.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);r.push({routeId:e.id,sessionId:v,providerSessionId:e.providerSessionId,historySessionId:H,nativeSessionId:v,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:lt(e)&&e.mode||"chat",agentName:C,agentType:O,status:_,title:$,messages:L,resume:e.resume,hostIdeType:!lt(e)&&!it(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||$||(lt(e)?e.mode==="chat"?C:`Terminal${N}`:C),displaySecondary:p,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,inboxBucket:e.inboxBucket,completionMarker:e.completionMarker,modalButtons:T?R.buttons:void 0,modalMessage:T?R.message:void 0,streamSource:"native",tabKey:za(v,e.id),machineName:n,connectionState:a,settings:e.settings,coordinator:Y,messageInput:e.messageInput})}if(m&&(lt(e)||it(e)))return r;for(const v of u){const g=v.activeModal&&Array.isArray(v.activeModal.buttons)&&v.activeModal.buttons.length>0,S=Wx(v),N=x0(v),C=`${e.id}:${N}`,R=v.title&&String(v.title).trim()||"",T=$l(R,v.agentName,v.agentType)?"":R,_=v.messages||[];if(!(v.transport==="cdp-webview"||!!v.sessionId||!!v.providerSessionId||_.length>0||g||!!T||!["idle","panel_hidden","disconnected","not_monitored"].includes(S)))continue;const B=v.coordinator||(typeof((I=v.settings)==null?void 0:I.meshCoordinatorFor)=="string"&&v.settings.meshCoordinatorFor?{meshId:v.settings.meshCoordinatorFor,role:"coordinator"}:void 0);r.push({routeId:e.id,sessionId:v.sessionId||v.instanceId,providerSessionId:v.providerSessionId,historySessionId:v.activeChatId||v.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:v.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:v.sessionCapabilities,mode:"chat",agentName:v.agentName,agentType:v.agentType,status:S,title:T,messages:_,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:v.git||e.git,displayPrimary:o||T||v.agentName||d,displaySecondary:v.model&&v.model.trim()?v.model.trim():`${d} · ${v.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,lastUpdated:v.lastUpdated||e.lastUpdated,inboxBucket:v.inboxBucket,completionMarker:v.completionMarker,modalButtons:g?v.activeModal.buttons:void 0,modalMessage:g?v.activeModal.message:void 0,streamSource:"agent-stream",tabKey:za(v.sessionId||v.instanceId,C),machineName:n,connectionState:a,settings:v.settings,coordinator:B,messageInput:v.messageInput})}return r.length===0&&r.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:c,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||d,displaySecondary:p,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:za(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings,messageInput:e.messageInput}),r}function lp(e){return String(e.type||e.id||"").trim()}function ua(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()).map(t=>t.trim()):[]}function g0(e,t){const r=(t||"").trim();if(!r)return[];const n=(e||[]).find(a=>a.type===r);return ua(n==null?void 0:n.modelOptions)}function y0(e,t){const r=(t||"").trim();if(!r)return[];const n=(e||[]).find(a=>a.type===r);return ua(n==null?void 0:n.thinkingLevelOptions)}function cp(e){const t=new Map;for(const r of e||[])r!=null&&r.type&&t.set(r.type,{models:ua(r.modelOptions),thinking:ua(r.thinkingLevelOptions)});return t}function v0(e){var t;return e.category!=="cli"||!lp(e)||e.enabled===!1?!1:e.machineStatus?e.machineStatus==="detected":((t=e.lastDetection)==null?void 0:t.ok)===!0||e.installed===!0||!!e.detectedPath}function xr(e){var n;const t=new Set,r=[];for(const a of e||[]){if(!v0(a))continue;const o=lp(a);if(!o||t.has(o))continue;t.add(o);const i=String(a.displayName||a.name||o),c=a.detectedPath||((n=a.lastDetection)==null?void 0:n.path)||null;r.push({type:o,label:i,icon:a.icon,statusLabel:c?`Detected at ${c}`:"Detected on this machine",detectedPath:c,...Array.isArray(a.modelOptions)&&a.modelOptions.length?{modelOptions:a.modelOptions}:{},...Array.isArray(a.thinkingLevelOptions)&&a.thinkingLevelOptions.length?{thinkingLevelOptions:a.thinkingLevelOptions}:{}})}return r}function br(e){const t=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],r=new Set,n=[];for(const a of t){const o=typeof a=="string"?a.trim():"";!o||r.has(o)||(r.add(o),n.push(o))}return n}function nn(e){return e.map(t=>t.type)}function w0(e,t){const r=br(e),n=t.trim();return!n||r.includes(n)?r:[...r,n]}function j0(e,t){return br(e).filter(r=>r!==t)}function mc(e,t,r){const n=br(e),a=n.indexOf(t);if(a<0)return n;const o=n.filter(c=>c!==t);if(r==="top")return[t,...o];if(r==="bottom")return[...o,t];const i=r==="up"?Math.max(0,a-1):Math.min(o.length,a+1);return o.splice(i,0,t),o}function hc({direction:e}){return s.jsx("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e==="up"?s.jsx("polyline",{points:"18 15 12 9 6 15"}):s.jsx("polyline",{points:"6 9 12 15 18 9"})})}function k0({value:e,availableProviders:t,onChange:r,disabled:n=!1,saveButton:a}){const[o,i]=l.useState(""),c=l.useMemo(()=>new Map(t.map(h=>[h.type,h])),[t]),d=l.useMemo(()=>br(e),[e]),p=d.filter(h=>!c.has(h)).length,u=t.filter(h=>!d.includes(h.type)),m=()=>{o&&(r(w0(d,o)),i(""))};return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[s.jsx("div",{className:"flex flex-col gap-2",children:d.length===0?s.jsx("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:"No provider priority configured. Launches without an explicit CLI provider will fail closed."}):d.map((h,y)=>{const x=c.get(h),f=!!x;return s.jsxs("div",{className:`flex flex-col gap-2 rounded-md border border-border-subtle px-3 py-2 sm:flex-row sm:items-center sm:justify-between ${f?"bg-bg-primary":"bg-bg-primary/40"}`,children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("span",{className:"text-[10px] font-semibold text-text-muted",children:["#",y+1]}),(x==null?void 0:x.icon)&&s.jsx("span",{"aria-hidden":"true",children:x.icon}),s.jsx("span",{className:`font-mono text-[12px] ${f?"text-text-primary":"text-text-muted"}`,children:h}),f?s.jsx("span",{className:"rounded border border-green-500/20 bg-green-500/10 px-1.5 py-px text-[9px] font-semibold text-green-400",children:"available"}):s.jsx("span",{className:"rounded border border-amber-500/25 bg-amber-500/10 px-1.5 py-px text-[9px] font-semibold text-amber-400",children:"not on this machine"})]}),s.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:x?`${x.label} · ${x.statusLabel}`:"Kept in order; skipped at launch until detected here."})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move up",disabled:n||y===0,title:"Move up",onClick:()=>r(mc(d,h,"up")),children:s.jsx(hc,{direction:"up"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move down",disabled:n||y===d.length-1,title:"Move down",onClick:()=>r(mc(d,h,"down")),children:s.jsx(hc,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:n,onClick:()=>r(j0(d,h)),children:"Remove"})]})]},h)})}),s.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-end",children:[s.jsxs("label",{className:"flex-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"mb-1 block font-medium text-text-primary",children:"Add available CLI provider"}),s.jsxs("select",{className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-sm text-text-primary",value:o,onChange:h=>i(h.target.value),disabled:n||u.length===0,children:[s.jsx("option",{value:"",children:u.length?"Select provider…":"No additional detected CLI providers"}),u.map(h=>s.jsxs("option",{value:h.type,children:[h.label," (",h.type,")"]},h.type))]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:n||!o,onClick:m,children:"Add provider"}),a]}),s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:["Launches use this order, top to bottom.",p>0?` ${p} provider${p===1?"":"s"} not detected here — kept in order, skipped until available.`:""]})]})}function N0(e){const t=e.split(":");return t.length>=3&&(t[1]==="ide"||t[1]==="cli"||t[1]==="acp")?{daemonId:t[0],targetSessionId:t.slice(2).join(":")||void 0}:{daemonId:e}}function dp(e,t){const r=N0(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const up=[{id:"antigravity",name:"Antigravity",icon:"🌀"},{id:"cursor",name:"Cursor",icon:"⚡"},{id:"kiro",name:"Kiro",icon:"🎯"},{id:"pearai",name:"PearAI",icon:"🍐"},{id:"trae",name:"Trae",icon:"🔮"},{id:"vscode",name:"VS Code",icon:"💙"},{id:"vscodium",name:"VSCodium",icon:"💚"},{id:"windsurf",name:"Windsurf",icon:"🏄"}],pp=[{id:"aider-cli",name:"Aider",icon:"🛠️"},{id:"claude-cli",name:"Claude Code",icon:"🟠"},{id:"codex-cli",name:"Codex CLI",icon:"📦"},{id:"cursor-cli",name:"Cursor CLI",icon:"⚡"},{id:"gemini-cli",name:"Gemini CLI",icon:"✨"},{id:"github-copilot-cli",name:"GitHub Copilot CLI",icon:"🤖"},{id:"goose-cli",name:"Goose",icon:"🪿"},{id:"opencode-cli",name:"OpenCode CLI",icon:"🧩"}],mp=[{id:"cline",name:"Cline",icon:"🧠"},{id:"codex",name:"Codex",icon:"📦"},{id:"roo-code",name:"Roo Code",icon:"🦘"},{id:"claude-code-vscode",name:"Claude Code (VS Code)",icon:"🟠"}],S0=up,C0=pp,I0=mp;function A0({icon:e,title:t,subtitle:r,badge:n,actions:a,className:o}){return s.jsxs("div",{className:$t("dashboard-header",o),children:[s.jsxs("div",{children:[s.jsxs("h1",{className:"header-title flex items-center gap-2",children:[s.jsx("span",{className:"flex items-center text-lg",children:e})," ",t,n&&s.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[n.count!==void 0?n.count:""," ",n.text]})]}),r&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),a&&s.jsx("div",{className:"flex gap-2",children:a})]})}function mn({icon:e,title:t,subtitle:r,badge:n,actions:a,widthClassName:o="max-w-6xl",contentClassName:i,children:c}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(A0,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:$t("mx-auto flex w-full flex-col gap-4",o,i),children:c})})]})}const Qo="adhdev:themechange";function M0(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function nr(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function ar(e){return e==="system"?M0():e}function hp(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Wn(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(Qo,{detail:{preference:e,theme:t}}))}function _0(){const e=nr(),t=ar(e);hp(t),Wn(e,t)}function Ts(){const[e,t]=l.useState(nr),[r,n]=l.useState(()=>ar(nr()));l.useEffect(()=>{hp(r)},[r]),l.useEffect(()=>{const i=window.matchMedia("(prefers-color-scheme: light)"),c=d=>{if(e==="system"){const p=d.matches?"light":"dark";n(p),Wn("system",p)}};return i.addEventListener("change",c),()=>i.removeEventListener("change",c)},[e]),l.useEffect(()=>{const i=d=>{const p=d.detail||{},u=p.preference,m=p.theme;t(u==="dark"||u==="light"||u==="system"?u:nr()),n(m==="dark"||m==="light"?m:ar(nr()))},c=d=>{if(d.key!=="theme")return;const p=nr(),u=ar(p);t(p),n(u)};return window.addEventListener(Qo,i),window.addEventListener("storage",c),()=>{window.removeEventListener(Qo,i),window.removeEventListener("storage",c)}},[]);const a=l.useCallback(i=>{const c=ar(i);t(i),n(c);try{localStorage.setItem("theme",i)}catch{}Wn(i,c)},[]),o=l.useCallback(()=>{t(i=>{const c=i==="dark"?"light":i==="light"?"system":"dark",d=ar(c);n(d);try{localStorage.setItem("theme",c)}catch{}return Wn(c,d),c})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:o,isDark:r==="dark"}}const fc={dark:"Dark",light:"Light",system:"System"};function T0({collapsed:e}){const{preference:t,cycleTheme:r}=Ts(),n=t==="dark"?s.jsx(Af,{size:16}):t==="light"?s.jsx(If,{size:16}):s.jsx(Mf,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${fc[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:fc[t]})]})}function eo(e,t){return e?typeof e=="function"?e(t):e:null}function L0({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:o,footerActions:i,preMainContent:c,collapsedStorageKey:d="sidebar-collapsed"}){const[p,u]=l.useState(!1),[m,h]=l.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),y=()=>u(!0),x=()=>u(!1),f=()=>{h(w=>{const I=!w;try{localStorage.setItem(d,I?"1":"0")}catch{}return I})},j=l.useMemo(()=>({collapsed:m,mobileMenuOpen:p,openMobileMenu:y,closeMobileMenu:x,toggleCollapsed:f}),[m,p]),k=w=>`nav-item${w.active?" active":""} cursor-pointer ${m?"justify-center py-2.5 px-0":""}${w.className?` ${w.className}`:""}`,b=w=>s.jsxs("div",{className:k(w),id:`nav-${w.id}`,onClick:()=>{w.onSelect(),x()},title:m?w.title??(typeof w.label=="string"?w.label:void 0):w.title,children:[s.jsx("span",{className:"nav-icon",children:w.icon}),!m&&w.label]},w.id);return s.jsxs("div",{className:`app-layout${p?" mobile-menu-open":""}${m?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:y,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),p&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:x,onKeyDown:w=>w.key==="Escape"&&x()}),s.jsxs("aside",{className:`sidebar ${p?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${m?"justify-center gap-0":""}`,children:eo(t,j)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:x,children:s.jsx(wt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(b)}),n.map(w=>s.jsxs("div",{className:w.className??"border-t border-border-subtle pt-2 mt-2",children:[!m&&w.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:w.title}):null,w.items.map(b)]},w.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(b),eo(o,j),s.jsx(T0,{collapsed:m}),eo(i,j)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function mt({title:e,icon:t,description:r,accentColor:n,className:a,collapsible:o,defaultOpen:i=!0,badge:c,children:d}){const[p,u]=l.useState(i),m=o?p:!0,h=(e||r)&&s.jsxs("div",{className:$t("flex items-start justify-between gap-3",m&&"mb-4"),children:[s.jsxs("div",{className:"min-w-0",children:[e&&s.jsxs("h3",{className:"text-base font-semibold text-text-primary flex items-center gap-1.5",children:[t&&s.jsx("span",{children:t}),s.jsx("span",{children:e}),c]}),r&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),o&&s.jsx("span",{className:$t("mt-0.5 shrink-0 text-text-muted transition-transform select-none",m?"rotate-90":"rotate-0"),"aria-hidden":!0,children:"▸"})]});return s.jsxs("div",{className:$t("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",n&&"border-l-[3px]",a),style:n?{borderLeftColor:n}:void 0,children:[o&&h?s.jsx("button",{type:"button",className:"w-full bg-transparent border-none p-0 text-left cursor-pointer",onClick:()=>u(y=>!y),"aria-expanded":m,children:h}):h,m&&d]})}function Ma({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:$t("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[s.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),s.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:t}),s.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const R0={error:"bg-red-500/10 border-red-500/30 text-red-400",warning:"bg-yellow-500/10 border-yellow-500/30 text-yellow-400",success:"bg-green-500/10 border-green-500/30 text-green-400",info:"bg-indigo-500/10 border-indigo-500/30 text-indigo-400"},P0={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Ft({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:$t("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",R0[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:P0[e]}),s.jsx("span",{children:t})]}),r&&s.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}function vt({label:e,hint:t,children:r,className:n}){return s.jsxs("div",{className:$t("mb-5",n),children:[s.jsx("label",{className:"block text-xs font-semibold text-text-muted uppercase tracking-wider mb-2",children:e}),r,t&&s.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:t})]})}function ts(e){const{className:t,...r}=e;return s.jsx("input",{...r,className:$t("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none","focus:border-accent transition-colors",t)})}const D0={primary:"btn-primary",secondary:"btn-secondary",warning:"btn-warning",danger:"btn-danger",ghost:"btn-ghost"},gs=l.forwardRef(function({variant:t="secondary",size:r="md",type:n,className:a,...o},i){return s.jsx("button",{ref:i,type:n??"button",className:$t("btn",D0[t],r==="sm"&&"btn-sm",a),...o})}),$0=l.forwardRef(function({options:t,children:r,className:n,...a},o){return s.jsx("select",{ref:o,className:$t("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none cursor-pointer","focus:border-accent transition-colors",n),...a,children:r??(t==null?void 0:t.map(i=>s.jsx("option",{value:i.value,disabled:i.disabled,children:i.label},i.value)))})}),E0={online:"bg-green-500/10 text-green-400 border-green-500/30",idle:"bg-yellow-500/10 text-yellow-400 border-yellow-500/30",busy:"bg-orange-500/10 text-orange-400 border-orange-500/30",error:"bg-red-500/10 text-red-400 border-red-500/30",offline:"bg-gray-500/10 text-text-secondary border-gray-500/30"},B0={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function F0({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:$t("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",E0[e],r),children:[s.jsx("span",{className:$t("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",B0[e])}),n]})}function Es({label:e,description:t,checked:r,disabled:n,onChange:a,extra:o}){return s.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[s.jsxs("div",{className:"pr-4",children:[s.jsx("div",{className:"font-medium text-sm",children:e}),s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:t})]}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[o,s.jsxs("button",{type:"button",role:"switch","aria-checked":r,"aria-disabled":n,disabled:n,onClick:()=>a(!r),className:`relative inline-flex items-center ${n?"cursor-not-allowed":"cursor-pointer"}`,children:[s.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:r?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),s.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${r?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function O0({onPrefChange:e}){const[t,r]=Qx(),[n,a]=l.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);l.useEffect(()=>{const i=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return i(),window.addEventListener("focus",i),document.addEventListener("visibilitychange",i),()=>{window.removeEventListener("focus",i),document.removeEventListener("visibilitychange",i)}},[]);const o=(i,c)=>{r({[i]:c}),e==null||e(i,c)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Es,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(wr,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:t.globalEnabled,onChange:i=>o("globalEnabled",i)}),t.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),t.globalEnabled&&s.jsx(Es,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(os,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:t.browserNotifications,onChange:i=>o("browserNotifications",i)}),t.globalEnabled&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:"Browser alerts only fire while this dashboard tab stays open in the background. If you close it, standalone cannot deliver hosted push notifications for you."}),n==="default"&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-status-warning",children:[s.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),s.jsx("button",{onClick:()=>{uu().then(a)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:"Allow notifications"})]}),n==="denied"&&s.jsx("div",{className:"text-[11px] text-status-warning",children:"Browser notifications are blocked in site or browser settings. Re-enable them there to receive standalone desktop alerts."}),n==="unsupported"&&s.jsx("div",{className:"text-[11px] text-status-warning",children:"This browser cannot show desktop notifications here. Keep the dashboard visible, or use another supported browser on this device."})]}),t.globalEnabled&&t.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(Es,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Kd,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:i=>o("completionAlert",i)}),s.jsx(Es,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(_f,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:i=>o("approvalAlert",i)}),s.jsx(Es,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(tn,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:t.disconnectAlert,onChange:i=>o("disconnectAlert",i)})]}),!t.globalEnabled&&s.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function Zo(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/);if(!t)return null;const r=t[4]??null;let n=null;if(r){const a=r.match(/(?:^|\.)(\d+)$/);n=a?Number(a[1]):null}return{base:[Number(t[1]),Number(t[2]),Number(t[3])],prereleaseNumber:n,isPrerelease:r!==null}}function pa(e){var t;return((t=Zo(e))==null?void 0:t.base)??null}function H0(e,t){const r=pa(e),n=pa(t);if(!r||!n)return e.localeCompare(t);for(let a=0;a<3;a+=1){if(r[a]<n[a])return-1;if(r[a]>n[a])return 1}return 0}function W0(e,t){const r=Zo(e),n=Zo(t);if(!r||!n)return e!==t;for(let a=0;a<3;a+=1){if(r.base[a]<n.base[a])return!0;if(r.base[a]>n.base[a])return!1}return r.isPrerelease&&n.isPrerelease?r.prereleaseNumber===null||n.prereleaseNumber===null?!1:r.prereleaseNumber<n.prereleaseNumber:!1}function Oi(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:W0(r,t)}function Jr(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||H0(r,t)>=0)return!1;const n=pa(r),a=pa(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function K0(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function to(e,t){return e instanceof Error?e.message:t}function U0({ides:e,emptyMessage:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const o=e.filter(i=>i.type==="adhdev-daemon");return o.length===0?s.jsx(Ma,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:"No machines connected",description:t||"Install ADHDev on a machine and sign in to connect it here."}):s.jsx("div",{className:"flex flex-col gap-2",children:o.map(i=>s.jsx(G0,{ide:i,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},i.id))})}function xc({title:e,message:t,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:o}){const i=n==="red"?"bg-status-error/20 text-status-error border-status-error/40 hover:bg-status-error/30":"";return dr.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:"var(--z-modal)"},onClick:o,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:c=>c.stopPropagation(),children:[s.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),s.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:t}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.jsx("button",{onClick:o,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:"Cancel"}),s.jsx("button",{onClick:a,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${i}`,style:n==="amber"?{background:"color-mix(in srgb, var(--status-warning) 20%, transparent)",color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"}:void 0,children:r})]})]})}),document.body)}function z0(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...S0,...C0,...I0].find(a=>a.id===t||t.includes(a.id)||a.id.includes(t));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:e}}function G0({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var B,z;const[o,i]=l.useState("idle"),[c,d]=l.useState(""),[p,u]=l.useState(null),[m,h]=l.useState("idle"),[y,x]=l.useState(""),f=e.version||null,j=((B=e.machine)==null?void 0:B.platform)||((z=e.system)==null?void 0:z.platform)||"",k=Yt(e,{fallbackId:e.id}),b=j==="win32"?"🪟":j==="darwin"?"🍎":"🐧",w=t.filter(A=>A.daemonId===e.id&&A.transport==="cdp-page"),I=t.filter(A=>A.daemonId===e.id&&A.transport==="pty"),v=t.filter(A=>A.daemonId===e.id&&A.transport==="acp"),g=e.p2p,S=async()=>{if(r){i("upgrading"),d("Starting upgrade...");try{const A=K0(await r(e.id,"daemon_upgrade",{}));A.alreadyLatest?(i("done"),d(`Already on v${A.version||"latest"}.`)):A.upgraded||A.success?(i("done"),d(`Upgrade to v${A.version||"latest"} started. Daemon is restarting...`)):(i("error"),d(A.error||"Upgrade failed"))}catch(A){i("error"),d(to(A,"Connection lost during upgrade"))}}},N=async()=>{if(u(null),!!n){h("loading");try{await n(e.id),h("done"),x("Machine disconnected.")}catch(A){h("error"),x(to(A,"Failed to disconnect"))}}},C=async()=>{if(u(null),!!a){h("loading");try{await a(e.id),h("done"),x("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(A){h("error"),x(to(A,"Failed to revoke token"))}}},R="0.9.82",T=Oi(e,R),_=Jr(e,R),P=w.length+I.length+v.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xl",children:b}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:k}),s.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[s.jsxs("span",{children:[e.id.substring(0,12),"…"]}),f&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${T?"":"bg-bg-secondary"}`,style:T?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",f,!T&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&T&&s.jsx("button",{onClick:S,disabled:o==="upgrading"||o==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${R}`,children:o==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):o==="done"?"✓ Updated":`${_?"↑ Update now":`↑ Update${` to v${R}`}`}`}),n&&s.jsx("button",{onClick:()=>u("disconnect"),disabled:m==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&s.jsx("button",{onClick:()=>u("revoke"),disabled:m==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(F0,{status:e.status==="online"?"online":"error"})]})]}),s.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[g&&s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${g.state==="connected"?"bg-status-online":"bg-text-muted/30"} ${g.state==="connecting"||g.state==="new"?"animate-pulse":""}`,style:g.state==="connecting"||g.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",g.state==="connected"?"connected":g.state==="connecting"||g.state==="new"?"connecting...":g.state||"off"]}),g.peers!==void 0&&g.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",g.peers," peer",g.peers!==1?"s":"",")"]})]}),g&&P>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),P>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[w.map(A=>{const O=z0(A.type),$=A.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:O.icon}),s.jsx("span",{children:O.name}),$!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${$?"bg-status-online":"animate-pulse"}`,style:$?void 0:{background:"var(--status-warning)"},title:$?"CDP connected":"CDP connecting..."})]},A.id)}),I.map(A=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"⌨️"}),s.jsx("span",{children:A.cliName||"CLI"})]},A.id)),v.map(A=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"🔗"}),s.jsx("span",{children:A.cliName||"ACP"})]},A.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(c||y)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${o==="error"||m==="error"?"text-status-error":o==="done"||m==="done"?"text-status-online":"text-text-muted"}`,children:y||c})]}),p==="disconnect"&&s.jsx(xc,{title:"🔌 Disconnect Machine",message:`Disconnect "${k}" from ADHDev?
53
+ `).includes(a)))}function t0(e,t="recent"){const r=e.slice();return r.sort((n,a)=>{if(t==="oldest")return(Number(n.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(t==="messages"){const o=(Number(a.messageCount)||0)-(Number(n.messageCount)||0);if(o!==0)return o}return(Number(a.lastMessageAt)||0)-(Number(n.lastMessageAt)||0)}),r}function ep(e,t={}){return t0(e0(e,t),t.sortMode||"recent")}function oa(e){return e?"Resume saved history":"Start fresh"}function Ei(e){return e?"Resuming saved history…":"Starting fresh…"}function s0(){return"Start fresh"}function r0(e,t=!1){return e==="cli"?oa(t):e==="ide"?"Start IDE":"Start ACP session"}function n0(e,t=!1){return e==="cli"?Ei(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function a0(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function o0(){return"Open saved history"}function i0(){return"Saved History"}function Bi(){return"Use saved history when you want continuity in the same provider conversation."}function l0(){return"No saved history found yet."}function c0(){return"Refresh saved history"}function d0(){return"Refreshing saved history…"}function ia(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function la(e){return e==="start-fresh"?"Review the provider and target folder before starting fresh.":e==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function ca(e){return e==="start-fresh"?"Start fresh":"Restart"}function da(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function tp(e){return`Resume saved history with ${e}?`}function sp(){return"Review or change the target workspace before resuming saved history."}function u0(e){if(!e)return"";try{return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(e))}catch{return new Date(e).toLocaleString()}}function rp({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:c,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:p,onClose:u,onNewChat:m,onSwitchSession:h,onRefreshHistory:y,onResumeSavedSession:x}){var T;const f=t.find(_=>_.id===e.routeId),j=(f==null?void 0:f.chats)||[],k=(T=f==null?void 0:f.activeChat)==null?void 0:T.id,b=lt(e)&&!it(e),[w,I]=l.useState(()=>Dt()),v=c||w,g=String(d||"").trim(),S=_=>{if(p){p(_);return}I(_)},N=l.useMemo(()=>a.map(_=>{const P=String(_.workspace||"").trim();return _.canResume||P||!g?_:{..._,workspace:g,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[g,a]),C=l.useMemo(()=>ep(N,{textQuery:v.textQuery,workspaceQuery:v.workspaceQuery,modelQuery:v.modelQuery,resumableOnly:v.resumableOnly,sortMode:v.sortMode}),[N,v.modelQuery,v.resumableOnly,v.sortMode,v.textQuery,v.workspaceQuery]),R=s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:u,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:b?i0():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Ty(e)}),b&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Bi()})]}),s.jsx("button",{onClick:u,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(wt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!b&&s.jsx("button",{onClick:m,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),b?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[s.jsx("input",{type:"text",value:v.textQuery,onChange:_=>S({...v,textQuery:_.target.value}),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:v.workspaceQuery,onChange:_=>S({...v,workspaceQuery:_.target.value}),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:v.modelQuery,onChange:_=>S({...v,modelQuery:_.target.value}),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsxs("select",{value:v.sortMode,onChange:_=>S({...v,sortMode:_.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:v.resumableOnly,onChange:_=>S({...v,resumableOnly:_.target.checked})}),"Resume-ready only"]})]}),C.map(_=>{const P=e.providerSessionId===_.providerSessionId,B=P||!_.canResume||!!i,z=_.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{B||!x||x(_)},disabled:B,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${P?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${B?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${P?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:_.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:_.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:u0(_.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:_.preview||"No saved preview yet"}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[_.workspace||"Workspace unknown",z?" · selected workspace":"",qs(_.summaryMetadata)?` · ${qs(_.summaryMetadata)}`:"",_.messageCount>0?` · ${_.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:P?"ACTIVE":_.canResume?z?"RESUME IN SELECTED WORKSPACE":i===_.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},_.id)})]}):j.map(_=>s.jsxs("div",{onClick:()=>{h(e.routeId,_.id),u()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${k===_.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[s.jsx("div",{className:`font-bold text-sm mb-1 ${k===_.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:_.title||"Untitled Session"}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[_.id.substring(0,12),"..."]}),k===_.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},_.id)),(b&&!o&&C.length===0||!b&&j.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(Cf,{size:32})}),s.jsx("div",{className:"text-[13px]",children:b?a.length>0?"No saved history matches these filters.":l0():"No recent chat sessions found."})]}),b&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:d0()})})]}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:s.jsx("button",{onClick:y,disabled:n||o,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||o?"⌛ Refreshing...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(va,{size:13})," ",b?c0():"Refresh History"]})})})]})]});return typeof document>"u"?R:dr.createPortal(R,document.body)}const pc={success:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Done"},warning:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Attention"},info:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Update"}};function np({toasts:e,onDismiss:t,onClickToast:r}){return s.jsx("div",{className:"fixed right-4 z-[var(--z-toast)] flex flex-col gap-2 pointer-events-none",style:{top:"calc(env(safe-area-inset-top, 0px) + 16px)"},children:e.map(n=>{const a=pc[n.type]||pc.info;return s.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var o;(o=n.actions)!=null&&o.length||r&&r(n)},children:[s.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${a.accent}, color-mix(in srgb, ${a.accent} 55%, transparent))`}}),s.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:o=>{o.stopPropagation(),t(n.id)},"aria-label":"Dismiss",children:s.jsx(wt,{size:14})}),s.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[s.jsx("div",{className:"flex items-center gap-2 pr-8",children:s.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:a.chipBg,color:a.chipText,border:`1px solid color-mix(in srgb, ${a.accent} 22%, transparent)`},children:a.label})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((o,i)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${o.variant==="primary"||o.variant==="danger",""}`,style:o.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:o.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:c=>{c.stopPropagation(),o.onClick(),t(n.id)},children:o.label},i))})]})]},n.id)})})}const p0=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function m0(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function h0(e,t){return ap(e)||t}function ap(e){var a,o,i;const t=(o=(a=e.summaryMetadata)==null?void 0:a.items)==null?void 0:o.find(c=>(c==null?void 0:c.id)==="model"),r=((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim();if(r)return r;const n=(i=e.controlValues)==null?void 0:i.model;return typeof n=="string"&&n.trim()?n.trim():""}function f0(e){return ap(e)||void 0}function x0(e){return e.sessionId||e.instanceId||e.agentType}function op(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=Yt(r,{fallbackId:r.id}));return t}function ip(e,t={}){var n;const r=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:Px(e,t.machineNames),connectionState:t.connectionStates?t.connectionStates[r]||t.defaultConnectionState||"new":t.defaultConnectionState}}function Fi(e,t={}){return b0(e,ip(e,t))}function b0(e,t={}){var h,y,x,f,j,k,b,w,I;const r=[],n=t.machineName,a=t.connectionState,o=m0(e),i=e.workspace||"",c=Ox(e.type,{agentName:e.cliName}),d=lt(e)||it(e)?c:Tt(e.type),p=h0(e,d),u=Array.isArray(e.childSessions)?e.childSessions.map(v=>{var g,S,N;return{sessionId:v.id,instanceId:v.id,providerSessionId:v.providerSessionId,activeChatId:(g=v.activeChat)==null?void 0:g.id,transport:v.transport,sessionCapabilities:v.capabilities,agentType:v.providerType,agentName:v.providerName||Tt(v.providerType),model:f0(v),status:v.status,title:v.title,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,messages:((S=v.activeChat)==null?void 0:S.messages)||[],activeModal:((N=v.activeChat)==null?void 0:N.activeModal)||void 0,unread:v.unread,lastSeenAt:v.lastSeenAt,lastUpdated:v.lastUpdated,inboxBucket:v.inboxBucket,completionMarker:v.completionMarker,surfaceHidden:v.surfaceHidden,muted:v.muted,git:v.git,settings:v.settings,coordinator:v.coordinator,messageInput:v.messageInput}}):[],m=p0(e);if(m){const v=e.sessionId||e.instanceId,g=(h=e.settings)==null?void 0:h.meshCoordinatorFor,S=((y=e.settings)==null?void 0:y.meshNodeFor)||!((x=e.settings)!=null&&x.meshCoordinatorFor)&&((f=e.settings)==null?void 0:f.launchedByCoordinator),N=g?" (Coordinator)":S?" (Mesh Node)":"",C=c+N,R=(j=e.activeChat)==null?void 0:j.activeModal,T=R&&Array.isArray(R.buttons)&&R.buttons.length>0,_=Hx(e.activeChat,[{status:e.status,activeModal:(k=e.activeChat)==null?void 0:k.activeModal}],e.agents||[]),P=e.activeChat||{title:"",messages:[]};let B=P.title&&String(P.title).trim()?String(P.title).trim():"";const z=(b=e.activeChat)==null?void 0:b.id,A=e.chats;if(z&&Array.isArray(A)&&A.length>0){const G=A.find(J=>J.id===z||J.id&&String(J.id)===String(z));G!=null&&G.title&&String(G.title).trim()&&(B=String(G.title).trim())}const O=(lt(e)||it(e),e.type),$=(lt(e)||it(e))&&$l(B,C,O)?"":B,L=P.messages||[],E=typeof z=="string"?z.trim():"",M=(lt(e)||it(e))&&E===String(e.type||"").trim(),H=E&&!M?E:e.providerSessionId,Y=e.coordinator||(typeof((w=e.settings)==null?void 0:w.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);r.push({routeId:e.id,sessionId:v,providerSessionId:e.providerSessionId,historySessionId:H,nativeSessionId:v,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:lt(e)&&e.mode||"chat",agentName:C,agentType:O,status:_,title:$,messages:L,resume:e.resume,hostIdeType:!lt(e)&&!it(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||$||(lt(e)?e.mode==="chat"?C:`Terminal${N}`:C),displaySecondary:p,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,inboxBucket:e.inboxBucket,completionMarker:e.completionMarker,modalButtons:T?R.buttons:void 0,modalMessage:T?R.message:void 0,streamSource:"native",tabKey:za(v,e.id),machineName:n,connectionState:a,settings:e.settings,coordinator:Y,messageInput:e.messageInput})}if(m&&(lt(e)||it(e)))return r;for(const v of u){const g=v.activeModal&&Array.isArray(v.activeModal.buttons)&&v.activeModal.buttons.length>0,S=Wx(v),N=x0(v),C=`${e.id}:${N}`,R=v.title&&String(v.title).trim()||"",T=$l(R,v.agentName,v.agentType)?"":R,_=v.messages||[];if(!(v.transport==="cdp-webview"||!!v.sessionId||!!v.providerSessionId||_.length>0||g||!!T||!["idle","panel_hidden","disconnected","not_monitored"].includes(S)))continue;const B=v.coordinator||(typeof((I=v.settings)==null?void 0:I.meshCoordinatorFor)=="string"&&v.settings.meshCoordinatorFor?{meshId:v.settings.meshCoordinatorFor,role:"coordinator"}:void 0);r.push({routeId:e.id,sessionId:v.sessionId||v.instanceId,providerSessionId:v.providerSessionId,historySessionId:v.activeChatId||v.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:v.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:v.sessionCapabilities,mode:"chat",agentName:v.agentName,agentType:v.agentType,status:S,title:T,messages:_,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:v.git||e.git,displayPrimary:o||T||v.agentName||d,displaySecondary:v.model&&v.model.trim()?v.model.trim():`${d} · ${v.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,lastUpdated:v.lastUpdated||e.lastUpdated,inboxBucket:v.inboxBucket,completionMarker:v.completionMarker,modalButtons:g?v.activeModal.buttons:void 0,modalMessage:g?v.activeModal.message:void 0,streamSource:"agent-stream",tabKey:za(v.sessionId||v.instanceId,C),machineName:n,connectionState:a,settings:v.settings,coordinator:B,messageInput:v.messageInput})}return r.length===0&&r.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:c,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||d,displaySecondary:p,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:za(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings,messageInput:e.messageInput}),r}function lp(e){return String(e.type||e.id||"").trim()}function ua(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()).map(t=>t.trim()):[]}function g0(e,t){const r=(t||"").trim();if(!r)return[];const n=(e||[]).find(a=>a.type===r);return ua(n==null?void 0:n.modelOptions)}function y0(e,t){const r=(t||"").trim();if(!r)return[];const n=(e||[]).find(a=>a.type===r);return ua(n==null?void 0:n.thinkingLevelOptions)}function cp(e){const t=new Map;for(const r of e||[])r!=null&&r.type&&t.set(r.type,{models:ua(r.modelOptions),thinking:ua(r.thinkingLevelOptions)});return t}function v0(e){var t;return e.category!=="cli"||!lp(e)||e.enabled===!1?!1:e.machineStatus?e.machineStatus==="detected":((t=e.lastDetection)==null?void 0:t.ok)===!0||e.installed===!0||!!e.detectedPath}function xr(e){var n;const t=new Set,r=[];for(const a of e||[]){if(!v0(a))continue;const o=lp(a);if(!o||t.has(o))continue;t.add(o);const i=String(a.displayName||a.name||o),c=a.detectedPath||((n=a.lastDetection)==null?void 0:n.path)||null;r.push({type:o,label:i,icon:a.icon,statusLabel:c?`Detected at ${c}`:"Detected on this machine",detectedPath:c,...Array.isArray(a.modelOptions)&&a.modelOptions.length?{modelOptions:a.modelOptions}:{},...Array.isArray(a.thinkingLevelOptions)&&a.thinkingLevelOptions.length?{thinkingLevelOptions:a.thinkingLevelOptions}:{}})}return r}function br(e){const t=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],r=new Set,n=[];for(const a of t){const o=typeof a=="string"?a.trim():"";!o||r.has(o)||(r.add(o),n.push(o))}return n}function nn(e){return e.map(t=>t.type)}function w0(e,t){const r=br(e),n=t.trim();return!n||r.includes(n)?r:[...r,n]}function j0(e,t){return br(e).filter(r=>r!==t)}function mc(e,t,r){const n=br(e),a=n.indexOf(t);if(a<0)return n;const o=n.filter(c=>c!==t);if(r==="top")return[t,...o];if(r==="bottom")return[...o,t];const i=r==="up"?Math.max(0,a-1):Math.min(o.length,a+1);return o.splice(i,0,t),o}function hc({direction:e}){return s.jsx("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e==="up"?s.jsx("polyline",{points:"18 15 12 9 6 15"}):s.jsx("polyline",{points:"6 9 12 15 18 9"})})}function k0({value:e,availableProviders:t,onChange:r,disabled:n=!1,saveButton:a}){const[o,i]=l.useState(""),c=l.useMemo(()=>new Map(t.map(h=>[h.type,h])),[t]),d=l.useMemo(()=>br(e),[e]),p=d.filter(h=>!c.has(h)).length,u=t.filter(h=>!d.includes(h.type)),m=()=>{o&&(r(w0(d,o)),i(""))};return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[s.jsx("div",{className:"flex flex-col gap-2",children:d.length===0?s.jsx("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:"No provider priority configured. Launches without an explicit CLI provider will fail closed."}):d.map((h,y)=>{const x=c.get(h),f=!!x;return s.jsxs("div",{className:`flex flex-col gap-2 rounded-md border border-border-subtle px-3 py-2 sm:flex-row sm:items-center sm:justify-between ${f?"bg-bg-primary":"bg-bg-primary/40"}`,children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("span",{className:"text-[10px] font-semibold text-text-muted",children:["#",y+1]}),(x==null?void 0:x.icon)&&s.jsx("span",{"aria-hidden":"true",children:x.icon}),s.jsx("span",{className:`font-mono text-[12px] ${f?"text-text-primary":"text-text-muted"}`,children:h}),f?s.jsx("span",{className:"rounded border border-green-500/20 bg-green-500/10 px-1.5 py-px text-[9px] font-semibold text-green-400",children:"available"}):s.jsx("span",{className:"rounded border border-amber-500/25 bg-amber-500/10 px-1.5 py-px text-[9px] font-semibold text-amber-400",children:"not on this machine"})]}),s.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:x?`${x.label} · ${x.statusLabel}`:"Kept in order; skipped at launch until detected here."})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move up",disabled:n||y===0,title:"Move up",onClick:()=>r(mc(d,h,"up")),children:s.jsx(hc,{direction:"up"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move down",disabled:n||y===d.length-1,title:"Move down",onClick:()=>r(mc(d,h,"down")),children:s.jsx(hc,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:n,onClick:()=>r(j0(d,h)),children:"Remove"})]})]},h)})}),s.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-end",children:[s.jsxs("label",{className:"flex-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"mb-1 block font-medium text-text-primary",children:"Add available CLI provider"}),s.jsxs("select",{className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-sm text-text-primary",value:o,onChange:h=>i(h.target.value),disabled:n||u.length===0,children:[s.jsx("option",{value:"",children:u.length?"Select provider…":"No additional detected CLI providers"}),u.map(h=>s.jsxs("option",{value:h.type,children:[h.label," (",h.type,")"]},h.type))]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:n||!o,onClick:m,children:"Add provider"}),a]}),s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:["Launches use this order, top to bottom.",p>0?` ${p} provider${p===1?"":"s"} not detected here — kept in order, skipped until available.`:""]})]})}function N0(e){const t=e.split(":");return t.length>=3&&(t[1]==="ide"||t[1]==="cli"||t[1]==="acp")?{daemonId:t[0],targetSessionId:t.slice(2).join(":")||void 0}:{daemonId:e}}function dp(e,t){const r=N0(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const up=[{id:"antigravity",name:"Antigravity",icon:"🌀"},{id:"cursor",name:"Cursor",icon:"⚡"},{id:"kiro",name:"Kiro",icon:"🎯"},{id:"pearai",name:"PearAI",icon:"🍐"},{id:"trae",name:"Trae",icon:"🔮"},{id:"vscode",name:"VS Code",icon:"💙"},{id:"vscodium",name:"VSCodium",icon:"💚"},{id:"windsurf",name:"Windsurf",icon:"🏄"}],pp=[{id:"aider-cli",name:"Aider",icon:"🛠️"},{id:"claude-cli",name:"Claude Code",icon:"🟠"},{id:"codex-cli",name:"Codex CLI",icon:"📦"},{id:"cursor-cli",name:"Cursor CLI",icon:"⚡"},{id:"gemini-cli",name:"Gemini CLI",icon:"✨"},{id:"github-copilot-cli",name:"GitHub Copilot CLI",icon:"🤖"},{id:"goose-cli",name:"Goose",icon:"🪿"},{id:"opencode-cli",name:"OpenCode CLI",icon:"🧩"}],mp=[{id:"cline",name:"Cline",icon:"🧠"},{id:"codex",name:"Codex",icon:"📦"},{id:"roo-code",name:"Roo Code",icon:"🦘"},{id:"claude-code-vscode",name:"Claude Code (VS Code)",icon:"🟠"}],S0=up,C0=pp,I0=mp;function A0({icon:e,title:t,subtitle:r,badge:n,actions:a,className:o}){return s.jsxs("div",{className:$t("dashboard-header",o),children:[s.jsxs("div",{children:[s.jsxs("h1",{className:"header-title flex items-center gap-2",children:[s.jsx("span",{className:"flex items-center text-lg",children:e})," ",t,n&&s.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[n.count!==void 0?n.count:""," ",n.text]})]}),r&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),a&&s.jsx("div",{className:"flex gap-2",children:a})]})}function mn({icon:e,title:t,subtitle:r,badge:n,actions:a,widthClassName:o="max-w-6xl",contentClassName:i,children:c}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(A0,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:$t("mx-auto flex w-full flex-col gap-4",o,i),children:c})})]})}const Qo="adhdev:themechange";function M0(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function nr(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function ar(e){return e==="system"?M0():e}function hp(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Wn(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(Qo,{detail:{preference:e,theme:t}}))}function _0(){const e=nr(),t=ar(e);hp(t),Wn(e,t)}function Ts(){const[e,t]=l.useState(nr),[r,n]=l.useState(()=>ar(nr()));l.useEffect(()=>{hp(r)},[r]),l.useEffect(()=>{const i=window.matchMedia("(prefers-color-scheme: light)"),c=d=>{if(e==="system"){const p=d.matches?"light":"dark";n(p),Wn("system",p)}};return i.addEventListener("change",c),()=>i.removeEventListener("change",c)},[e]),l.useEffect(()=>{const i=d=>{const p=d.detail||{},u=p.preference,m=p.theme;t(u==="dark"||u==="light"||u==="system"?u:nr()),n(m==="dark"||m==="light"?m:ar(nr()))},c=d=>{if(d.key!=="theme")return;const p=nr(),u=ar(p);t(p),n(u)};return window.addEventListener(Qo,i),window.addEventListener("storage",c),()=>{window.removeEventListener(Qo,i),window.removeEventListener("storage",c)}},[]);const a=l.useCallback(i=>{const c=ar(i);t(i),n(c);try{localStorage.setItem("theme",i)}catch{}Wn(i,c)},[]),o=l.useCallback(()=>{t(i=>{const c=i==="dark"?"light":i==="light"?"system":"dark",d=ar(c);n(d);try{localStorage.setItem("theme",c)}catch{}return Wn(c,d),c})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:o,isDark:r==="dark"}}const fc={dark:"Dark",light:"Light",system:"System"};function T0({collapsed:e}){const{preference:t,cycleTheme:r}=Ts(),n=t==="dark"?s.jsx(Af,{size:16}):t==="light"?s.jsx(If,{size:16}):s.jsx(Mf,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${fc[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:fc[t]})]})}function eo(e,t){return e?typeof e=="function"?e(t):e:null}function L0({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:o,footerActions:i,preMainContent:c,collapsedStorageKey:d="sidebar-collapsed"}){const[p,u]=l.useState(!1),[m,h]=l.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),y=()=>u(!0),x=()=>u(!1),f=()=>{h(w=>{const I=!w;try{localStorage.setItem(d,I?"1":"0")}catch{}return I})},j=l.useMemo(()=>({collapsed:m,mobileMenuOpen:p,openMobileMenu:y,closeMobileMenu:x,toggleCollapsed:f}),[m,p]),k=w=>`nav-item${w.active?" active":""} cursor-pointer ${m?"justify-center py-2.5 px-0":""}${w.className?` ${w.className}`:""}`,b=w=>s.jsxs("div",{className:k(w),id:`nav-${w.id}`,onClick:()=>{w.onSelect(),x()},title:m?w.title??(typeof w.label=="string"?w.label:void 0):w.title,children:[s.jsx("span",{className:"nav-icon",children:w.icon}),!m&&w.label]},w.id);return s.jsxs("div",{className:`app-layout${p?" mobile-menu-open":""}${m?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:y,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),p&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:x,onKeyDown:w=>w.key==="Escape"&&x()}),s.jsxs("aside",{className:`sidebar ${p?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${m?"justify-center gap-0":""}`,children:eo(t,j)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:x,children:s.jsx(wt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(b)}),n.map(w=>s.jsxs("div",{className:w.className??"border-t border-border-subtle pt-2 mt-2",children:[!m&&w.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:w.title}):null,w.items.map(b)]},w.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(b),eo(o,j),s.jsx(T0,{collapsed:m}),eo(i,j)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function mt({title:e,icon:t,description:r,accentColor:n,className:a,collapsible:o,defaultOpen:i=!0,badge:c,children:d}){const[p,u]=l.useState(i),m=o?p:!0,h=(e||r)&&s.jsxs("div",{className:$t("flex items-start justify-between gap-3",m&&"mb-4"),children:[s.jsxs("div",{className:"min-w-0",children:[e&&s.jsxs("h3",{className:"text-base font-semibold text-text-primary flex items-center gap-1.5",children:[t&&s.jsx("span",{children:t}),s.jsx("span",{children:e}),c]}),r&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),o&&s.jsx("span",{className:$t("mt-0.5 shrink-0 text-text-muted transition-transform select-none",m?"rotate-90":"rotate-0"),"aria-hidden":!0,children:"▸"})]});return s.jsxs("div",{className:$t("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",n&&"border-l-[3px]",a),style:n?{borderLeftColor:n}:void 0,children:[o&&h?s.jsx("button",{type:"button",className:"w-full bg-transparent border-none p-0 text-left cursor-pointer",onClick:()=>u(y=>!y),"aria-expanded":m,children:h}):h,m&&d]})}function Ma({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:$t("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[s.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),s.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:t}),s.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const R0={error:"bg-red-500/10 border-red-500/30 text-red-400",warning:"bg-yellow-500/10 border-yellow-500/30 text-yellow-400",success:"bg-green-500/10 border-green-500/30 text-green-400",info:"bg-indigo-500/10 border-indigo-500/30 text-indigo-400"},P0={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Ft({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:$t("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",R0[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:P0[e]}),s.jsx("span",{children:t})]}),r&&s.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}function yt({label:e,hint:t,children:r,className:n}){return s.jsxs("div",{className:$t("mb-5",n),children:[s.jsx("label",{className:"block text-xs font-semibold text-text-muted uppercase tracking-wider mb-2",children:e}),r,t&&s.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:t})]})}function ts(e){const{className:t,...r}=e;return s.jsx("input",{...r,className:$t("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none","focus:border-accent transition-colors",t)})}const D0={primary:"btn-primary",secondary:"btn-secondary",warning:"btn-warning",danger:"btn-danger",ghost:"btn-ghost"},gs=l.forwardRef(function({variant:t="secondary",size:r="md",type:n,className:a,...o},i){return s.jsx("button",{ref:i,type:n??"button",className:$t("btn",D0[t],r==="sm"&&"btn-sm",a),...o})}),$0=l.forwardRef(function({options:t,children:r,className:n,...a},o){return s.jsx("select",{ref:o,className:$t("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none cursor-pointer","focus:border-accent transition-colors",n),...a,children:r??(t==null?void 0:t.map(i=>s.jsx("option",{value:i.value,disabled:i.disabled,children:i.label},i.value)))})}),E0={online:"bg-green-500/10 text-green-400 border-green-500/30",idle:"bg-yellow-500/10 text-yellow-400 border-yellow-500/30",busy:"bg-orange-500/10 text-orange-400 border-orange-500/30",error:"bg-red-500/10 text-red-400 border-red-500/30",offline:"bg-gray-500/10 text-text-secondary border-gray-500/30"},B0={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function F0({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:$t("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",E0[e],r),children:[s.jsx("span",{className:$t("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",B0[e])}),n]})}function Es({label:e,description:t,checked:r,disabled:n,onChange:a,extra:o}){return s.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[s.jsxs("div",{className:"pr-4",children:[s.jsx("div",{className:"font-medium text-sm",children:e}),s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:t})]}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[o,s.jsxs("button",{type:"button",role:"switch","aria-checked":r,"aria-disabled":n,disabled:n,onClick:()=>a(!r),className:`relative inline-flex items-center ${n?"cursor-not-allowed":"cursor-pointer"}`,children:[s.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:r?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),s.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${r?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function O0({onPrefChange:e}){const[t,r]=Qx(),[n,a]=l.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);l.useEffect(()=>{const i=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return i(),window.addEventListener("focus",i),document.addEventListener("visibilitychange",i),()=>{window.removeEventListener("focus",i),document.removeEventListener("visibilitychange",i)}},[]);const o=(i,c)=>{r({[i]:c}),e==null||e(i,c)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Es,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(wr,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:t.globalEnabled,onChange:i=>o("globalEnabled",i)}),t.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),t.globalEnabled&&s.jsx(Es,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(os,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:t.browserNotifications,onChange:i=>o("browserNotifications",i)}),t.globalEnabled&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:"Browser alerts only fire while this dashboard tab stays open in the background. If you close it, standalone cannot deliver hosted push notifications for you."}),n==="default"&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-status-warning",children:[s.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),s.jsx("button",{onClick:()=>{uu().then(a)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:"Allow notifications"})]}),n==="denied"&&s.jsx("div",{className:"text-[11px] text-status-warning",children:"Browser notifications are blocked in site or browser settings. Re-enable them there to receive standalone desktop alerts."}),n==="unsupported"&&s.jsx("div",{className:"text-[11px] text-status-warning",children:"This browser cannot show desktop notifications here. Keep the dashboard visible, or use another supported browser on this device."})]}),t.globalEnabled&&t.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(Es,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Kd,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:i=>o("completionAlert",i)}),s.jsx(Es,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(_f,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:i=>o("approvalAlert",i)}),s.jsx(Es,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(tn,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:t.disconnectAlert,onChange:i=>o("disconnectAlert",i)})]}),!t.globalEnabled&&s.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function Zo(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/);if(!t)return null;const r=t[4]??null;let n=null;if(r){const a=r.match(/(?:^|\.)(\d+)$/);n=a?Number(a[1]):null}return{base:[Number(t[1]),Number(t[2]),Number(t[3])],prereleaseNumber:n,isPrerelease:r!==null}}function pa(e){var t;return((t=Zo(e))==null?void 0:t.base)??null}function H0(e,t){const r=pa(e),n=pa(t);if(!r||!n)return e.localeCompare(t);for(let a=0;a<3;a+=1){if(r[a]<n[a])return-1;if(r[a]>n[a])return 1}return 0}function W0(e,t){const r=Zo(e),n=Zo(t);if(!r||!n)return e!==t;for(let a=0;a<3;a+=1){if(r.base[a]<n.base[a])return!0;if(r.base[a]>n.base[a])return!1}return r.isPrerelease&&n.isPrerelease?r.prereleaseNumber===null||n.prereleaseNumber===null?!1:r.prereleaseNumber<n.prereleaseNumber:!1}function Oi(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:W0(r,t)}function Jr(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||H0(r,t)>=0)return!1;const n=pa(r),a=pa(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function K0(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function to(e,t){return e instanceof Error?e.message:t}function U0({ides:e,emptyMessage:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const o=e.filter(i=>i.type==="adhdev-daemon");return o.length===0?s.jsx(Ma,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:"No machines connected",description:t||"Install ADHDev on a machine and sign in to connect it here."}):s.jsx("div",{className:"flex flex-col gap-2",children:o.map(i=>s.jsx(G0,{ide:i,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},i.id))})}function xc({title:e,message:t,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:o}){const i=n==="red"?"bg-status-error/20 text-status-error border-status-error/40 hover:bg-status-error/30":"";return dr.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:"var(--z-modal)"},onClick:o,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:c=>c.stopPropagation(),children:[s.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),s.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:t}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.jsx("button",{onClick:o,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:"Cancel"}),s.jsx("button",{onClick:a,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${i}`,style:n==="amber"?{background:"color-mix(in srgb, var(--status-warning) 20%, transparent)",color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"}:void 0,children:r})]})]})}),document.body)}function z0(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...S0,...C0,...I0].find(a=>a.id===t||t.includes(a.id)||a.id.includes(t));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:e}}function G0({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var B,z;const[o,i]=l.useState("idle"),[c,d]=l.useState(""),[p,u]=l.useState(null),[m,h]=l.useState("idle"),[y,x]=l.useState(""),f=e.version||null,j=((B=e.machine)==null?void 0:B.platform)||((z=e.system)==null?void 0:z.platform)||"",k=Yt(e,{fallbackId:e.id}),b=j==="win32"?"🪟":j==="darwin"?"🍎":"🐧",w=t.filter(A=>A.daemonId===e.id&&A.transport==="cdp-page"),I=t.filter(A=>A.daemonId===e.id&&A.transport==="pty"),v=t.filter(A=>A.daemonId===e.id&&A.transport==="acp"),g=e.p2p,S=async()=>{if(r){i("upgrading"),d("Starting upgrade...");try{const A=K0(await r(e.id,"daemon_upgrade",{}));A.alreadyLatest?(i("done"),d(`Already on v${A.version||"latest"}.`)):A.upgraded||A.success?(i("done"),d(`Upgrade to v${A.version||"latest"} started. Daemon is restarting...`)):(i("error"),d(A.error||"Upgrade failed"))}catch(A){i("error"),d(to(A,"Connection lost during upgrade"))}}},N=async()=>{if(u(null),!!n){h("loading");try{await n(e.id),h("done"),x("Machine disconnected.")}catch(A){h("error"),x(to(A,"Failed to disconnect"))}}},C=async()=>{if(u(null),!!a){h("loading");try{await a(e.id),h("done"),x("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(A){h("error"),x(to(A,"Failed to revoke token"))}}},R="0.9.82",T=Oi(e,R),_=Jr(e,R),P=w.length+I.length+v.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xl",children:b}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:k}),s.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[s.jsxs("span",{children:[e.id.substring(0,12),"…"]}),f&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${T?"":"bg-bg-secondary"}`,style:T?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",f,!T&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&T&&s.jsx("button",{onClick:S,disabled:o==="upgrading"||o==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${R}`,children:o==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):o==="done"?"✓ Updated":`${_?"↑ Update now":`↑ Update${` to v${R}`}`}`}),n&&s.jsx("button",{onClick:()=>u("disconnect"),disabled:m==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&s.jsx("button",{onClick:()=>u("revoke"),disabled:m==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(F0,{status:e.status==="online"?"online":"error"})]})]}),s.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[g&&s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${g.state==="connected"?"bg-status-online":"bg-text-muted/30"} ${g.state==="connecting"||g.state==="new"?"animate-pulse":""}`,style:g.state==="connecting"||g.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",g.state==="connected"?"connected":g.state==="connecting"||g.state==="new"?"connecting...":g.state||"off"]}),g.peers!==void 0&&g.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",g.peers," peer",g.peers!==1?"s":"",")"]})]}),g&&P>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),P>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[w.map(A=>{const O=z0(A.type),$=A.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:O.icon}),s.jsx("span",{children:O.name}),$!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${$?"bg-status-online":"animate-pulse"}`,style:$?void 0:{background:"var(--status-warning)"},title:$?"CDP connected":"CDP connecting..."})]},A.id)}),I.map(A=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"⌨️"}),s.jsx("span",{children:A.cliName||"CLI"})]},A.id)),v.map(A=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"🔗"}),s.jsx("span",{children:A.cliName||"ACP"})]},A.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(c||y)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${o==="error"||m==="error"?"text-status-error":o==="done"||m==="done"?"text-status-online":"text-text-muted"}`,children:y||c})]}),p==="disconnect"&&s.jsx(xc,{title:"🔌 Disconnect Machine",message:`Disconnect "${k}" from ADHDev?
54
54
 
55
55
  This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
56
56
 
@@ -80,7 +80,7 @@ Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Mach
80
80
  `);return s.jsxs("div",{className:`rounded-2xl border px-4 py-3 backdrop-blur-sm transition-all ${zc(o,t,r.isDark)}${Dk(o)?" mesh-node-generating":""}`,style:{width:on(o)},title:g,children:[s.jsx(xn,{type:"target",position:a==="TB"?js.Top:js.Left,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}}),s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${r.textPrimary}`,children:o.label}),s.jsx("div",{className:`truncate text-[11px] ${r.textMuted}`,children:p})]}),s.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5 shrink-0",children:[k&&s.jsx("span",{className:`h-2 w-2 rounded-full ${r.isDark?"bg-emerald-400":"bg-emerald-500"} animate-pulse`,"aria-label":"active session"}),s.jsx("span",{className:"h-2.5 w-2.5 rounded-full",style:{backgroundColor:Vc(o.health)},"aria-hidden":!0})]})]}),f?s.jsx("div",{className:`mt-2 inline-flex min-w-0 max-w-full items-center rounded-full border px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] ${Gc(f.tone,r.isDark)}`,title:f.label,children:s.jsx("span",{className:"truncate",children:f.label})}):o.branch&&!c?s.jsx("div",{className:`mt-2 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[10px] ${Ct("meta",r.isDark)}`,title:o.branch,children:s.jsx("span",{className:"truncate",children:o.branch})}):null,I&&s.jsx("div",{className:`mt-2 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[10px] font-medium ${r.isDark?"border-cyan-400/20 bg-cyan-500/8 text-cyan-100":"border-sky-300 bg-sky-50 text-sky-700"}`,title:v.join(`
81
81
  `),children:s.jsx("span",{className:"truncate",children:I})}),w.length>0&&s.jsx("div",{className:"mt-2 flex max-h-44 min-w-0 flex-col gap-1.5 overflow-y-auto pr-1",children:w.map(S=>{const N=Br(S);return s.jsxs("div",{className:`min-w-0 rounded-lg border px-2.5 py-1.5 ${r.isDark?"border-cyan-400/15 bg-cyan-500/[0.055]":"border-sky-200 bg-white/85"}`,title:[`Session ID: ${S.sessionId}`,S.providerType?`Provider: ${S.providerType}`:null,`Status: ${ls(S)}`,`Role: ${N}`].filter(Boolean).join(`
82
82
  `),children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2",children:[s.jsx("span",{className:`min-w-0 truncate text-[10px] ${r.textMuted}`,children:S.providerType||"provider unknown"}),s.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-[0.12em] ${yo(S,r.isDark)}`,children:ls(S)})]}),s.jsxs("div",{className:`mt-0.5 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 text-[9px] ${r.textMuted}`,children:[s.jsx("span",{className:"min-w-0 truncate font-mono",children:vo(S.sessionId)}),s.jsx("span",{children:N})]})]},S.sessionId)})}),s.jsxs("div",{className:"mt-3",children:[s.jsxs("div",{className:"flex min-w-0 flex-wrap gap-1.5 text-[10px]",children:[o.health==="unknown"?s.jsx("span",{className:`rounded-full border px-2 py-0.5 italic ${Ct("health",r.isDark)}`,children:"connecting..."}):s.jsx("span",{className:`rounded-full border px-2 py-0.5 capitalize ${Ct("health",r.isDark)}`,children:Pk(o.health)}),c&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Ct("submodule",r.isDark)}`,children:"submodule"}),!i&&o.health==="unknown"&&!o.locality&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 italic ${Ct("health",r.isDark)}`,children:"..."}),!i&&(o.health!=="unknown"||o.locality)&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Ct(Bk(o),r.isDark)}`,children:Yc(o.locality)}),y&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Ct("meta",r.isDark)}`,title:y==="relay"?"P2P link relayed through TURN (slower path)":`P2P transport: ${y}`,children:y}),x&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Ct("meta",r.isDark)}`,title:"P2P round-trip latency",children:x}),u&&c&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Ct("meta",r.isDark)}`,children:u}),o.dirty&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Ct("dirty",r.isDark)}`,children:c?"local changes":`${o.dirtyFiles} dirty`}),o.outOfSync&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Ct("conflict",r.isDark)}`,children:"out of sync"}),o.hasConflicts&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Ct("conflict",r.isDark)}`,children:"conflicts"}),!c&&o.upstream&&o.upstreamStatus!=="fresh"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Ct("orphan",r.isDark)}`,children:"upstream unverified"}),o.isOrphan&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Ct("orphan",r.isDark)}`,children:"needs follow-up"}),!c&&o.refineJobStatus==="completed"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Ct("refineDone",r.isDark)}`,title:o.refineJobBranch?`refined ${o.refineJobBranch}${o.refineJobInto?` → ${o.refineJobInto}`:""}`:"refine completed",children:"refined"})]}),s.jsx("div",{className:`mt-3 text-[11px] leading-5 ${r.textSecondary}`,style:Tk,children:Vn(o)}),b.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[9px] font-semibold uppercase tracking-[0.16em] ${r.textMuted}`,children:"Attached Chats"}),s.jsx("div",{className:"flex max-h-56 flex-col gap-1.5 overflow-y-auto pr-1",children:b.map(S=>{const N=S.startedAt||S.createdAt||null,C=Br(S);return s.jsxs("div",{className:`min-w-0 rounded-lg border px-2.5 py-1.5 ${r.isDark?"border-white/8 bg-white/[0.035]":"border-slate-200 bg-white/80"}`,title:[`Session ID: ${S.sessionId}`,S.providerType?`Provider: ${S.providerType}`:null,`Status: ${ls(S)}`,`Role: ${C}`,N?`Started: ${N}`:"Started: not reported",S.statusNote?`Note: ${S.statusNote}`:null].filter(Boolean).join(`
83
- `),children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2",children:[s.jsx("span",{className:`min-w-0 truncate font-mono text-[10px] select-text ${r.textPrimary}`,children:vo(S.sessionId)}),s.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-[0.12em] ${yo(S,r.isDark)}`,children:ls(S)})]}),s.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 text-[9px] ${r.textMuted}`,children:[s.jsx("span",{className:"truncate",children:S.providerType||"provider unknown"}),s.jsx("span",{children:C}),s.jsx("span",{children:qc(N)})]}),S.statusNote&&s.jsx("div",{className:`mt-1 text-[9px] leading-4 ${r.textMuted}`,children:S.statusNote})]},S.sessionId)})})]}),d&&j&&s.jsx("div",{className:`mt-3 rounded-xl border px-3 py-2 text-[10px] leading-4 ${r.isDark?"border-cyan-400/15 bg-cyan-500/8 text-cyan-50/90":"border-sky-300 bg-sky-50 text-sky-700"}`,style:Lk,children:j})]}),s.jsx(xn,{type:"source",position:a==="TB"?js.Bottom:js.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const Ok={meshNode:Fk},Hk=8;function Wk(e){if(e.length<2)return null;if(e.length===2){const[p,u]=e;return{d:`M ${p.x},${p.y} L ${u.x},${u.y}`,labelX:(p.x+u.x)/2,labelY:(p.y+u.y)/2}}const t=Hk,r=[`M ${e[0].x},${e[0].y}`];for(let p=1;p<e.length-1;p+=1){const u=e[p-1],m=e[p],h=e[p+1],y=Math.sign(m.x-u.x),x=Math.sign(m.y-u.y),f=Math.sign(h.x-m.x),j=Math.sign(h.y-m.y),k=Math.hypot(m.x-u.x,m.y-u.y),b=Math.hypot(h.x-m.x,h.y-m.y),w=Math.min(t,k/2,b/2);if(w<1||y===f&&x===j){r.push(`L ${m.x},${m.y}`);continue}const I=m.x-y*w,v=m.y-x*w,g=m.x+f*w,S=m.y+j*w;r.push(`L ${I},${v}`),r.push(`Q ${m.x},${m.y} ${g},${S}`)}const n=e[e.length-1];r.push(`L ${n.x},${n.y}`);let a=0;const o=[0];for(let p=1;p<e.length;p+=1)a+=Math.hypot(e[p].x-e[p-1].x,e[p].y-e[p-1].y),o.push(a);const i=a/2;let c=e[0].x,d=e[0].y;for(let p=1;p<e.length;p+=1)if(o[p]>=i){const u=o[p]-o[p-1],m=u===0?0:(i-o[p-1])/u;c=e[p-1].x+(e[p].x-e[p-1].x)*m,d=e[p-1].y+(e[p].y-e[p-1].y)*m;break}return{d:r.join(" "),labelX:c,labelY:d}}function Kk(e){const t=e.data.routePoints;if(t&&t.length>=2){const o=Wk(t);if(o)return[o.d,o.labelX,o.labelY]}const r={sourceX:e.sourceX,sourceY:e.sourceY,sourcePosition:e.sourcePosition,targetX:e.targetX,targetY:e.targetY,targetPosition:e.targetPosition},n=e.data.graphEdge;let a;return n.type==="parentBranch"?a=Sh(r):n.type==="worktreeLink"||n.type==="submoduleLink"||n.type==="cloneLink"?a=kh(r):a=Nh(r),[a[0],a[1],a[2]]}function Uk(e,t){const r="nodrag nopan rounded-md border px-2 py-1 text-[10px] font-semibold shadow-sm backdrop-blur-sm";switch(e.type){case"orphanLink":return t?`${r} border-orange-400/35 bg-orange-500/14 text-orange-100`:`${r} border-orange-300 bg-orange-50 text-orange-700`;case"submoduleLink":return t?`${r} border-violet-400/30 bg-violet-500/14 text-violet-100`:`${r} border-violet-300 bg-violet-50 text-violet-700`;case"sessionLink":return t?`${r} border-emerald-400/30 bg-emerald-500/14 text-emerald-100`:`${r} border-emerald-300 bg-emerald-50 text-emerald-700`;case"cloneLink":return t?`${r} border-teal-400/30 bg-teal-500/14 text-teal-100`:`${r} border-teal-300 bg-teal-50 text-teal-700`;default:return t?`${r} border-sky-400/25 bg-slate-950/78 text-sky-100`:`${r} border-sky-300 bg-white/95 text-sky-700`}}function zk(e){const t=l.useContext(sl),r=e.data.graphEdge,[n,a,o]=Kk(e),i=typeof e.label=="string"?e.label:void 0;return s.jsxs(s.Fragment,{children:[s.jsx(gh,{id:e.id,path:n,markerEnd:e.markerEnd,style:e.style,interactionWidth:24}),e.label&&s.jsx(yh,{children:s.jsx("div",{className:Uk(r,t.isDark),title:i,style:{position:"absolute",transform:`translate(-50%, -50%) translate(${a}px, ${o}px)`,pointerEvents:"none",maxWidth:Uj.maxWidth},children:s.jsx("span",{className:"block truncate",children:e.label})})})]})}const Gk={meshEdge:zk};async function Vk(e,t,r,n,a){const o=await lm(e,r,n,a);return jm(e,o,t,r)}async function qk(e,t=Ls("dark"),r=!1,n="LR"){const a=await lm(e,r,n);return jm(e,a,t,r)}function jm(e,t,r,n=!1){const a=new Set(t.nodes.map(p=>p.id)),o=t.nodes.map(p=>({id:p.id,type:p.type,position:p.position,data:{graphNode:p.graphNode,compact:n},selected:p.selected,draggable:p.draggable,selectable:p.selectable})),i=e.edges.filter(p=>a.has(p.source)&&a.has(p.target)),c=Xk(i),d=i.map(p=>{var u;return{id:p.id,source:p.source,target:p.target,label:c.has(p.id)?p.label:void 0,type:"meshEdge",data:{graphEdge:p,routePoints:(u=t.edgeRoutes.get(p.id))==null?void 0:u.points},animated:p.type==="orphanLink",markerEnd:p.direction==="directed"?{type:jh.ArrowClosed,width:p.type==="submoduleLink"?16:18,height:p.type==="submoduleLink"?16:18,color:Xc(p)}:void 0,style:{stroke:Xc(p),strokeWidth:p.type==="orphanLink"?2.25:p.type==="submoduleLink"?1.7:p.type==="worktreeLink"?1.8:p.type==="cloneLink"?1.6:2,strokeDasharray:p.type==="orphanLink"?"5 4":p.type==="submoduleLink"?"4 3":p.type==="cloneLink"?"6 3":void 0},labelStyle:{fill:r.edgeLabelTextColor,fontSize:10,fontWeight:600},labelBgStyle:{fill:r.edgeLabelBackgroundColor,fillOpacity:1,stroke:r.edgeLabelBorderColor},labelBgPadding:[6,4],labelBgBorderRadius:7}});return{nodes:o,edges:d}}const Yk=3,Jk=2;function Jc(e){switch(e.type){case"orphanLink":return 5;case"parentBranch":return 4;case"submoduleLink":return 3;case"cloneLink":return 2;case"worktreeLink":return 1;case"sessionLink":return 0;default:return 0}}function Xk(e){const t=new Set,r=new Map;for(const n of e){if(!n.label)continue;const a=r.get(n.source);a?a.push(n):r.set(n.source,[n])}for(const n of r.values()){if(n.length<Yk){for(const o of n)t.add(o.id);continue}const a=[...n].sort((o,i)=>{const c=Jc(i)-Jc(o);return c!==0?c:o.id.localeCompare(i.id)});for(const o of a.slice(0,Jk))t.add(o.id)}return t}function Xc(e){switch(e.type){case"parentBranch":return"#38bdf8";case"worktreeLink":return"#a78bfa";case"sessionLink":return"#34d399";case"orphanLink":return"#f97316";case"submoduleLink":return"#c084fc";case"cloneLink":return"#2dd4bf";default:return"#64748b"}}function Qk(e){const t=e.data.graphNode;if(t.locality==="local")return"#38bdf8";switch(t.health){case"online":return"#34d399";case"dirty":return"#fbbf24";case"degraded":case"offline":return"#fb7185";case"wrong_branch":return"#a78bfa";default:return"#94a3b8"}}function Zk(e){const t=e.data.graphNode;return["mesh-minimap-node",`mesh-minimap-node--${t.type}`,`mesh-minimap-node--${t.health}`,t.isOrphan?"mesh-minimap-node--attention":null,t.dirty?"mesh-minimap-node--dirty":null,t.outOfSync?"mesh-minimap-node--out-of-sync":null].filter(Boolean).join(" ")}function e1({data:e,viewportKey:t}){const r=vh(),n=wh(),a=l.useRef(null),o=l.useMemo(()=>am(e),[e]),i=l.useMemo(()=>Bj(e),[e]);return l.useEffect(()=>{if(!r||e.nodes.length===0||a.current===t)return;let c=!1;const d=requestAnimationFrame(()=>{if(c)return;const p=i.length>0&&i.length<e.nodes.length;n.fitView({nodes:p?i.map(u=>({id:u})):void 0,padding:p?.24:.2,maxZoom:p?.98:.9,duration:260}),a.current=t});return()=>{c=!0,cancelAnimationFrame(d)}},[e.nodes.length,i,o,r,n,t]),null}const t1=12;function s1(e){return e>=16?"min-h-[720px]":e>=10?"min-h-[580px]":"min-h-[460px]"}function r1({data:e,selectedNodeId:t=null,directionPref:r,onNodeClick:n,onEdgeClick:a,onNodeHoverChange:o,onEdgeHoverChange:i}){const{theme:c}=Ts(),d=l.useMemo(()=>Ls(c),[c]),p=l.useMemo(()=>nk(e),[e]),u=l.useMemo(()=>ak(e),[e]),m=l.useRef(null),[h,y]=l.useState({width:0,height:0}),x=h.width>0&&h.width<_k,f=e.nodes.length>=Mk||x,[j]=l.useState("LR"),k=r??j,b=l.useMemo(()=>r==="LR"||r==="TB"?r:x?"TB":k==="auto"?Vj(e):k,[k,r,p,e,x]),w=e.nodes.length>=t1,[I,v]=l.useState({nodes:[],edges:[]}),g=l.useMemo(()=>`${Fj(e,h.width,h.height)}::${b}`,[p,e,h.height,h.width,b]);l.useEffect(()=>{let N=!1;return qk(e,d,f,b).then(C=>{if(N)return;v(C);const R=requestAnimationFrame(()=>{if(N)return;const T=m.current;if(!T)return;const _=new Map;for(const P of C.nodes){const B=T.querySelector(`.react-flow__node[data-id="${CSS.escape(P.id)}"]`);B&&B.offsetHeight>0&&_.set(P.id,B.offsetHeight)}_.size!==0&&Vk(e,d,f,b,_).then(P=>{N||v(P)})});return()=>cancelAnimationFrame(R)}),()=>{N=!0}},[e,u,d,f,b]);const S=l.useMemo(()=>I.nodes.map(N=>({...N,selected:N.id===t})),[I.nodes,t]);return l.useEffect(()=>{const N=m.current;if(!N)return;const C=()=>{const T=Math.max(0,Math.round(N.clientWidth)),_=Math.max(0,Math.round(N.clientHeight));y(P=>P.width===T&&P.height===_?P:{width:T,height:_})};C();const R=typeof ResizeObserver=="function"?new ResizeObserver(()=>C()):null;return R==null||R.observe(N),window.addEventListener("resize",C),()=>{R==null||R.disconnect(),window.removeEventListener("resize",C)}},[]),s.jsx(sl.Provider,{value:d,children:s.jsx(gm.Provider,{value:f,children:s.jsx(ym.Provider,{value:b,children:s.jsxs("div",{ref:m,className:`${d.graphShellClass} ${s1(e.nodes.length)}`,style:{height:"100%"},children:[s.jsx("div",{className:`pointer-events-none absolute left-1/2 top-2 z-10 -translate-x-1/2 px-3 py-1 text-[10px] ${d.graphStatChipClass}`,children:"drag or scroll to pan"}),s.jsx("div",{className:"w-full min-w-0 flex-1",style:{height:"100%"},children:s.jsxs(mh,{nodes:S,edges:I.edges,nodeTypes:Ok,edgeTypes:Gk,minZoom:x?.3:.18,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!0,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(N,C)=>n==null?void 0:n(C.data.graphNode),onEdgeClick:(N,C)=>{var T;const R=(T=C.data)==null?void 0:T.graphEdge;R&&(a==null||a(R))},onNodeMouseEnter:(N,C)=>o==null?void 0:o(C.data.graphNode),onNodeMouseLeave:()=>o==null?void 0:o(null),onEdgeMouseEnter:(N,C)=>{var R;return i==null?void 0:i(((R=C.data)==null?void 0:R.graphEdge)??null)},onEdgeMouseLeave:()=>i==null?void 0:i(null),className:"h-full w-full",colorMode:d.flowColorMode,proOptions:{hideAttribution:!0},children:[s.jsx(e1,{data:e,viewportKey:g}),s.jsx(hh,{className:d.graphControlsClass,position:"bottom-left",showZoom:!0,showFitView:!0,showInteractive:!1}),w&&s.jsx(fh,{position:"bottom-right",pannable:!0,zoomable:!0,nodeColor:Qk,nodeClassName:Zk,nodeStrokeWidth:3,className:d.isDark?"overflow-hidden rounded-xl border border-white/10 bg-slate-950/85":"overflow-hidden rounded-xl border border-slate-200 bg-white/95"}),s.jsx(xh,{variant:bh.Dots,gap:18,size:1.2,color:d.graphBackgroundDotColor})]})})]})})})})}const n1="You are one independent member of a multi-agent cross-verification quorum";function a1(e){var n,a;const t=(e??"").trim();if(!t)return"";if(!t.startsWith(n1))return t;const r=(a=(n=t.match(/\n## Question\n([\s\S]*?)(?:\n## |$)/))==null?void 0:n[1])==null?void 0:a.trim().replace(/\s+/g," ");return r?`MAGI cross-verify — ${r}`:"MAGI cross-verification task"}function o1(e){return`${e.state??""} ${e.chatStatus??""} ${e.lifecycle??""}`.toLowerCase()}function i1(e){if(!Array.isArray(e))return[];const t=[];for(const r of e){const n=r.activeSessionDetails;if(Array.isArray(n))for(const a of n)a!=null&&a.sessionId&&o1(a).includes("approval")&&t.push({nodeId:r.nodeId,sessionId:a.sessionId,providerType:a.providerType,machineLabel:r.machineLabel||r.nodeId,detail:a.statusNote??a.title??null})}return t}function l1({approvals:e,nodes:t,onResolve:r,hideWhenEmpty:n=!0}){const a=l.useMemo(()=>e??i1(t),[e,t]),[o,i]=l.useState({});if(n&&a.length===0)return null;const c=(d,p)=>{o[d.sessionId]||(i(u=>({...u,[d.sessionId]:p})),Promise.resolve(r(d.nodeId,d.sessionId,p)).finally(()=>{i(u=>{const m={...u};return delete m[d.sessionId],m})}))};return s.jsxs("div",{className:"rounded-lg border p-3",style:{borderColor:"color-mix(in srgb, var(--status-warning) 40%, transparent)",background:"color-mix(in srgb, var(--status-warning) 8%, transparent)"},children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2 font-black text-xs",style:{color:"var(--status-warning)"},children:[s.jsx(Vs,{size:14}),"PENDING APPROVALS",s.jsxs("span",{className:"opacity-70 font-semibold",children:["(",a.length,")"]})]}),a.length===0?s.jsx("div",{className:"text-[11px] opacity-70",children:"No sessions are awaiting an approval decision."}):s.jsx("ul",{className:"flex flex-col gap-2",children:a.map(d=>{const p=o[d.sessionId]??null,u=p!==null;return s.jsxs("li",{className:"flex items-center justify-between gap-3 rounded-md px-2.5 py-2",style:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)"},children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"text-xs font-semibold truncate",children:[d.machineLabel||d.nodeId,d.providerType&&s.jsx("span",{className:"ml-2 opacity-60 font-normal",children:d.providerType})]}),s.jsx("div",{className:"text-[10px] opacity-60 truncate",children:d.detail?d.detail.replace(/[\n\r]+/g," ").slice(0,120):`session ${d.sessionId}`})]}),s.jsxs("div",{className:"flex gap-2 shrink-0",children:[s.jsx("button",{onClick:()=>c(d,"approve"),disabled:u,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 font-extrabold ${u?"cursor-not-allowed opacity-60":"cursor-pointer"}`,style:{color:"var(--status-warning)",background:"var(--surface-primary)"},children:p==="approve"?"⏳ ...":"Approve"}),s.jsx("button",{onClick:()=>c(d,"reject"),disabled:u,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 font-semibold text-white bg-red-500/30 ${u?"cursor-not-allowed opacity-60":"cursor-pointer"}`,children:p==="reject"?"⏳ ...":"Reject"})]})]},`${d.nodeId}:${d.sessionId}`)})})]})}const c1=5,d1=40,u1={meshId:"",totalEntries:0,taskDispatched:0,taskCompleted:0,taskFailed:0,taskStalled:0,sessionLaunched:0,checkpointCreated:0,lastActivityAt:null,recentFailures:0};function Ta(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function km(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const r=t.toLowerCase().replace(/[\s-]+/g,"_");return r.includes("approval")?"awaiting approval":r.includes("generating")||r.includes("running")||r.includes("busy")?"generating":r.includes("idle")||r.includes("ready")||r.includes("waiting_input")?"idle":r.replace(/_/g," ")}function Nm(e){return e.includes("approval")?"amber":e.includes("generating")?"sky":e.includes("idle")?"emerald":e.includes("failed")||e.includes("stopped")||e.includes("interrupted")?"rose":"muted"}function p1(e){const t=e.git;if(!t)return e.gitProbePending?"git probe pending":"no git probe";const r=(t.staged??0)+(t.modified??0)+(t.untracked??0)+(t.deleted??0)+(t.renamed??0),n=[];return t.upstreamStatus==="fresh"&&((t.ahead??0)>0||(t.behind??0)>0)&&n.push(`↑${t.ahead??0}/↓${t.behind??0}`),r>0&&n.push(`✎${r}`),t.hasConflicts&&n.push("conflicts"),n.join(" · ")||"clean"}function Sm(e){switch(e){case"active":return"emerald";case"paused":return"amber";case"completed":return"sky";case"abandoned":return"rose";default:return"muted"}}function m1(e){switch(e){case"online":return"emerald";case"dirty":return"amber";case"degraded":case"offline":return"rose";case"wrong_branch":return"sky";default:return"muted"}}function Cm(e){switch(e){case"completed":return"emerald";case"failed":return"rose";case"cancelled":return"muted";case"assigned":return"sky";case"pending":return"amber";default:return"muted"}}function Qc(e){switch(e){case"assigned":return 0;case"pending":return 1;case"completed":case"failed":case"cancelled":return 2;default:return 3}}function as(e){if(!e)return null;const t=Date.parse(e);if(!Number.isFinite(t))return null;const r=Math.max(0,Math.floor((Date.now()-t)/1e3));if(r<60)return`${r}s ago`;const n=Math.floor(r/60);if(n<60)return`${n}m ago`;const a=Math.floor(n/60);return a<48?`${a}h ago`:`${Math.floor(a/24)}d ago`}function Zc(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return null;if(e<1e3)return`${Math.round(e)}ms`;const t=Math.round(e/1e3),r=t%60,n=Math.floor(t/60),a=n%60,o=Math.floor(n/60),i=[];return o>0&&i.push(`${o}h`),a>0&&i.push(`${a}m`),(r>0||i.length===0)&&i.push(`${r}s`),i.join(" ")}function rl(e){return e.replace(/[_-]+/g," ")}function Im(e){const t=e.toLowerCase();return t.includes("fail")||t.includes("stall")||t.includes("error")?"rose":t.includes("complete")?"emerald":t.includes("dispatch")||t.includes("launch")||t.includes("assign")?"sky":t.includes("checkpoint")?"amber":"muted"}function Am(e){if(!e)return null;const t=e.message??e.summary??e.reason??e.title;return typeof t=="string"&&t.trim()?t.trim():null}function h1({status:e,daemonId:t=null,meshId:r=null,sendDaemonCommand:n=null}){var I,v,g,S;const{theme:a}=Ts(),o=l.useMemo(()=>Ls(a),[a]),i=((I=e.queue)==null?void 0:I.summary)??null,c=((v=e.queue)==null?void 0:v.tasks)??[],d=((g=e.ledger)==null?void 0:g.summary)??u1,p=((S=e.ledger)==null?void 0:S.entries)??[],u=e.missions??[],m=u.filter(N=>N.status==="active"||N.status==="paused"),h=u.filter(N=>N.status==="completed"||N.status==="abandoned"),y=e.asyncRefineJobs??[],[x,f]=l.useState(null),j=l.useCallback(()=>f(null),[]),k=l.useCallback(async(N,C,R)=>{!t||!n||await n(t,"mesh_approve",{meshId:r??void 0,node_id:N,session_id:C,action:R})},[t,r,n]),b=l.useCallback(N=>{if(!N)return"";const C=e.nodes.find(R=>R.nodeId===N);return(C==null?void 0:C.machineLabel)||N},[e.nodes]),w=l.useMemo(()=>{const N=[];for(const C of e.nodes){const R=C.activeSessionDetails&&C.activeSessionDetails.length>0?C.activeSessionDetails:(C.activeSessions??[]).map(T=>({sessionId:T,workspace:C.workspace,isCached:!0}));for(const T of R)N.push({node:C,session:T})}return N},[e.nodes]);return s.jsxs("div",{className:"flex flex-col gap-3 pb-2",children:[s.jsx(l1,{nodes:e.nodes,onResolve:k}),s.jsx(k1,{meshTheme:o,liveMissions:m,historyMissions:h,hasMissionField:Array.isArray(e.missions),onSelect:N=>f({kind:"mission",mission:N})}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsx(N1,{meshTheme:o,ledgerSummary:d,entries:p,resolveNodeLabel:b,onSelect:N=>f({kind:"ledger",entry:N})}),s.jsx(S1,{meshTheme:o,queueSummary:i,tasks:c,onSelect:N=>f({kind:"queue",task:N})})]}),s.jsx(I1,{meshTheme:o,nodes:e.nodes}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsx(A1,{meshTheme:o,entries:w,onSelect:(N,C)=>f({kind:"session",node:N,session:C})}),s.jsx(M1,{meshTheme:o,jobs:y})]}),x&&s.jsx(x1,{meshTheme:o,detail:x,onClose:j,daemonId:t,meshId:r??e.meshId??null,sendDaemonCommand:n,resolveNodeLabel:b})]})}function Ys({meshTheme:e,title:t,count:r,children:n,action:a}){const o=e.isDark;return s.jsxs("div",{className:`flex min-w-0 flex-col overflow-hidden rounded-2xl border p-4 ${o?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-white/80"}`,children:[s.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[s.jsx("span",{className:`text-[11px] font-semibold uppercase tracking-[0.14em] ${e.textSecondary}`,children:t}),r!==void 0&&s.jsx("span",{className:`tabular-nums text-[11px] ${e.textMuted}`,children:r}),a&&s.jsx("span",{className:"ml-auto",children:a})]}),n]})}function Ot({meshTheme:e,label:t,tone:r}){const n=e.isDark,a=r==="rose"?n?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700":r==="sky"?n?"border-sky-400/25 bg-sky-500/10 text-sky-200":"border-sky-300 bg-sky-50 text-sky-700":r==="amber"?n?"border-amber-400/25 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700":r==="emerald"?n?"border-emerald-400/25 bg-emerald-500/10 text-emerald-200":"border-emerald-300 bg-emerald-50 text-emerald-700":n?"border-white/10 bg-white/[0.04] text-slate-300":"border-slate-200 bg-slate-50 text-slate-600";return s.jsx("span",{className:`shrink-0 rounded-full border px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] ${a}`,children:t})}function gt({meshTheme:e,label:t,value:r,tone:n}){const a=e.isDark,o=n==="rose"?a?"text-rose-300":"text-rose-600":n==="sky"?a?"text-sky-300":"text-sky-600":n==="amber"?a?"text-amber-300":"text-amber-600":n==="emerald"?a?"text-emerald-300":"text-emerald-600":n==="muted"?e.textMuted:e.textPrimary;return s.jsxs("div",{className:`flex flex-col items-center rounded-lg border px-2 py-2 ${a?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-white/70"}`,children:[s.jsx("span",{className:`tabular-nums text-base font-semibold leading-none ${o}`,children:r}),s.jsx("span",{className:`mt-1 text-[9px] uppercase tracking-wide ${e.textMuted}`,children:t})]})}function fn({meshTheme:e,children:t}){return s.jsx("div",{className:`text-xs ${e.textMuted}`,children:t})}function La({meshTheme:e,onClick:t,children:r}){const n=e.isDark,a=t?n?"hover:bg-white/[0.05]":"hover:bg-slate-100/70":"";return s.jsx("button",{type:"button",onClick:t,disabled:!t,className:`flex w-full min-w-0 items-center gap-2 overflow-hidden rounded-md px-1.5 py-1 text-left text-xs transition ${a} ${t?"cursor-pointer":"cursor-default"}`,children:r})}function Ra({meshTheme:e,expanded:t,hiddenCount:r,onToggle:n}){return r<=0?null:s.jsx("button",{type:"button",onClick:n,className:`mt-1 self-start rounded-md px-1.5 py-0.5 text-[11px] font-medium ${e.textSecondary} hover:underline`,children:t?"Show fewer":`+${r} more`})}function Pa(e,t=c1){const[r,n]=l.useState(!1),a=r?e:e.slice(0,t),o=Math.max(0,e.length-t),i=l.useCallback(()=>n(c=>!c),[]);return{visible:a,hiddenCount:o,expanded:r,toggle:i}}function ht({meshTheme:e,label:t,value:r}){return s.jsxs("div",{className:e.rowClass,children:[s.jsx("span",{className:e.rowLabelClass,children:t}),s.jsx("span",{className:e.rowValueClass,children:r})]})}function f1(e){switch(e.kind){case"mission":return{kicker:"Mission",title:e.mission.title};case"ledger":return{kicker:"Ledger entry",title:rl(e.entry.kind)};case"queue":return{kicker:"Queue task",title:e.task.id};case"session":return{kicker:"Session",title:Ta(e.session.sessionId)}}}function x1({meshTheme:e,detail:t,onClose:r,daemonId:n,meshId:a,sendDaemonCommand:o,resolveNodeLabel:i}){l.useEffect(()=>{const h=y=>{y.key==="Escape"&&r()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[r]);const c=e.isDark,{kicker:d,title:p}=f1(t),u=c?"bg-[#030617]/[0.92]":"bg-[rgba(15,23,42,0.82)]",m=c?"border-white/10 bg-slate-950 md:bg-slate-950/98 shadow-[0_28px_120px_rgba(2,6,23,0.5)]":"border-slate-200 bg-white md:bg-white/98 shadow-[0_28px_120px_rgba(148,163,184,0.3)]";return s.jsx("div",{className:`fixed inset-0 z-[var(--z-modal)] flex items-stretch justify-center p-0 md:items-center md:p-4 ${u}`,role:"dialog","aria-modal":"true",onClick:r,children:s.jsxs("div",{className:`flex h-[100dvh] max-h-[100dvh] w-full flex-col overflow-hidden border ${m} md:h-auto md:max-h-[88dvh] md:max-w-[min(640px,calc(100vw-32px))] md:rounded-2xl`,onClick:h=>h.stopPropagation(),children:[s.jsxs("div",{className:`sticky top-0 z-10 flex shrink-0 items-start justify-between gap-3 border-b px-4 py-3 ${c?"border-white/8":"border-slate-200"}`,children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`text-[10px] font-semibold uppercase tracking-[0.16em] ${e.textMuted}`,children:d}),s.jsx("div",{className:`mt-0.5 break-all text-sm font-semibold ${e.textPrimary}`,children:p})]}),s.jsx("button",{type:"button",onClick:r,"aria-label":"Close detail",className:c?"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-xl border border-white/10 bg-white/[0.04] text-slate-300 transition hover:bg-white/[0.08] hover:text-white":"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-xl border border-slate-200 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",children:"✕"})]}),s.jsxs("div",{className:"min-h-0 min-w-0 flex-1 overflow-y-auto px-4 py-4",children:[t.kind==="mission"&&s.jsx(y1,{meshTheme:e,mission:t.mission,daemonId:n,meshId:a,sendDaemonCommand:o}),t.kind==="ledger"&&s.jsx(v1,{meshTheme:e,entry:t.entry,resolveNodeLabel:i}),t.kind==="queue"&&s.jsx(w1,{meshTheme:e,task:t.task}),t.kind==="session"&&s.jsx(j1,{meshTheme:e,node:t.node,session:t.session})]})]})})}const b1=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function g1(e){const t=b1(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function y1({meshTheme:e,mission:t,daemonId:r,meshId:n,sendDaemonCommand:a}){var I;const o=t.tasks,i="goal"in t&&typeof t.goal=="string"&&t.goal?t.goal:"goalPreview"in t?t.goalPreview:"",c="goalTruncated"in t?t.goalTruncated===!0:!1,[d,p]=l.useState(null),[u,m]=l.useState(!1),[h,y]=l.useState(null),x=c&&!d&&!!r&&!!a,f=l.useCallback(async()=>{if(!(!r||!a)){m(!0),y(null);try{const v=await a(r,"mesh_status",{meshId:n??void 0,verbose:!0}),g=g1(v),N=(Array.isArray(g==null?void 0:g.missions)?g.missions:[]).find(R=>(R==null?void 0:R.id)===t.id),C=typeof(N==null?void 0:N.goal)=="string"&&N.goal?N.goal:null;C?p(C):y("Full goal unavailable")}catch(v){y(v instanceof Error?v.message:"Failed to fetch full mission goal")}finally{m(!1)}}},[r,n,a,t.id]),j=d??i,k=c&&!d,b=t.stats??null,w=((I=b==null?void 0:b.incompleteTaskIds)==null?void 0:I.length)??0;return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx(Ot,{meshTheme:e,label:t.status,tone:Sm(t.status)}),s.jsx(Ot,{meshTheme:e,label:`${o.total} tasks`,tone:"muted"})]}),j&&s.jsxs("div",{className:`max-h-64 overflow-y-auto whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:[j,k&&!x&&s.jsx("span",{className:e.textMuted,children:" … (truncated)"})]}),h&&s.jsx("div",{className:"text-[11px] text-amber-400",children:h}),x&&s.jsx("button",{type:"button",className:"self-start text-[12px] text-accent-primary hover:underline disabled:opacity-50",onClick:f,disabled:u,children:u?"Loading…":"Show full goal"}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5 sm:grid-cols-6",children:[s.jsx(gt,{meshTheme:e,label:"Completed",value:o.completed,tone:"emerald"}),s.jsx(gt,{meshTheme:e,label:"Assigned",value:o.assigned,tone:o.assigned>0?"sky":void 0}),s.jsx(gt,{meshTheme:e,label:"Pending",value:o.pending}),s.jsx(gt,{meshTheme:e,label:"Failed",value:o.failed,tone:o.failed>0?"rose":void 0}),s.jsx(gt,{meshTheme:e,label:"Blocked",value:o.blocked,tone:o.blocked>0?"amber":void 0}),s.jsx(gt,{meshTheme:e,label:"Cancelled",value:o.cancelled,tone:"muted"})]}),b&&s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(gt,{meshTheme:e,label:"Wall clock",value:Zc(b.wallClockMs)??"—"}),s.jsx(gt,{meshTheme:e,label:"Total runtime",value:Zc(b.totalDurationMs)??"—"}),s.jsx(gt,{meshTheme:e,label:"Retries",value:b.retries,tone:b.retries>0?"amber":void 0})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(ht,{meshTheme:e,label:"Mission id",value:t.id}),s.jsx(ht,{meshTheme:e,label:"Created",value:as(t.createdAt)??t.createdAt}),s.jsx(ht,{meshTheme:e,label:"Updated",value:as(t.updatedAt)??t.updatedAt}),o.lastActivityAt&&s.jsx(ht,{meshTheme:e,label:"Last task activity",value:as(o.lastActivityAt)??o.lastActivityAt}),w>0&&b&&s.jsx(ht,{meshTheme:e,label:"Incomplete evidence",value:s.jsxs("details",{children:[s.jsxs("summary",{className:"cursor-pointer select-none",children:[w," task",w===1?"":"s"]}),s.jsx("div",{className:"mt-1 flex flex-col gap-0.5 break-all",children:b.incompleteTaskIds.map(v=>s.jsx("span",{className:`font-mono text-[10px] ${e.textMuted}`,children:v},v))})]})})]})]})}function v1({meshTheme:e,entry:t,resolveNodeLabel:r}){const n=Am(t.payload);let a="";try{a=JSON.stringify(t.payload??{},null,2)}catch{a=String(t.payload)}return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:s.jsx(Ot,{meshTheme:e,label:rl(t.kind),tone:Im(t.kind)})}),n&&s.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:n}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(ht,{meshTheme:e,label:"Entry id",value:t.id}),s.jsx(ht,{meshTheme:e,label:"When",value:as(t.timestamp)??t.timestamp}),t.nodeId&&s.jsx(ht,{meshTheme:e,label:"Node",value:r(t.nodeId)}),t.sessionId&&s.jsx(ht,{meshTheme:e,label:"Session",value:Ta(t.sessionId)}),t.providerType&&s.jsx(ht,{meshTheme:e,label:"Provider",value:t.providerType})]}),a&&a!=="{}"&&s.jsxs("div",{children:[s.jsx("div",{className:`mb-1 text-[10px] uppercase tracking-wide ${e.textMuted}`,children:"Payload"}),s.jsx("pre",{className:`max-h-60 max-w-full overflow-auto rounded-lg border p-2 text-[10px] leading-4 ${e.isDark?"border-white/8 bg-black/30 text-slate-300":"border-slate-200 bg-slate-50 text-slate-700"}`,children:a})]})]})}function w1({meshTheme:e,task:t}){return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx(Ot,{meshTheme:e,label:t.status,tone:Cm(t.status)}),(t.requeueCount??0)>0&&s.jsx(Ot,{meshTheme:e,label:`requeued ${t.requeueCount}`,tone:"amber"})]}),t.message&&s.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:t.message}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(ht,{meshTheme:e,label:"Task id",value:t.id}),s.jsx(ht,{meshTheme:e,label:"Created",value:as(t.createdAt)??t.createdAt}),s.jsx(ht,{meshTheme:e,label:"Updated",value:as(t.updatedAt)??t.updatedAt}),(t.assignedNodeId||t.targetNodeId)&&s.jsx(ht,{meshTheme:e,label:"Node",value:t.assignedNodeId||t.targetNodeId}),(t.assignedSessionId||t.targetSessionId)&&s.jsx(ht,{meshTheme:e,label:"Session",value:Ta(t.assignedSessionId||t.targetSessionId)}),t.cancelReason&&s.jsx(ht,{meshTheme:e,label:"Cancel reason",value:t.cancelReason}),t.requeueReason&&s.jsx(ht,{meshTheme:e,label:"Requeue reason",value:t.requeueReason}),t.autoLaunch&&s.jsx(ht,{meshTheme:e,label:"Auto launch",value:`${t.autoLaunch.status}${t.autoLaunch.reason?` · ${t.autoLaunch.reason}`:""}`})]})]})}function j1({meshTheme:e,node:t,session:r}){var a,o;const n=km(r);return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx(Ot,{meshTheme:e,label:n,tone:Nm(n)}),s.jsx(Ot,{meshTheme:e,label:r.providerType||"provider unknown",tone:"muted"})]}),r.statusNote&&s.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:r.statusNote}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(ht,{meshTheme:e,label:"Session id",value:r.sessionId}),s.jsx(ht,{meshTheme:e,label:"Node",value:t.machineLabel}),s.jsx(ht,{meshTheme:e,label:"Workspace",value:r.workspace||t.workspace}),(((a=t.git)==null?void 0:a.branch)??t.worktreeBranch)&&s.jsx(ht,{meshTheme:e,label:"Branch",value:((o=t.git)==null?void 0:o.branch)??t.worktreeBranch}),typeof r.role=="string"&&r.role&&s.jsx(ht,{meshTheme:e,label:"Role",value:r.role}),(r.startedAt||r.createdAt)&&s.jsx(ht,{meshTheme:e,label:"Started",value:as(r.startedAt||r.createdAt)??(r.startedAt||r.createdAt)})]})]})}function ed({meshTheme:e,mission:t,onSelect:r}){const n=t.tasks,a=as(n.lastActivityAt);return s.jsxs(La,{meshTheme:e,onClick:r,children:[s.jsx(Ot,{meshTheme:e,label:t.status,tone:Sm(t.status)}),s.jsx("span",{className:`min-w-0 flex-1 truncate font-medium ${e.textPrimary}`,children:t.title}),s.jsxs("span",{className:`shrink-0 tabular-nums text-[11px] ${e.textMuted}`,children:["✓",n.completed,"/",n.total]}),a&&s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:a})]})}function k1({meshTheme:e,liveMissions:t,historyMissions:r,hasMissionField:n,onSelect:a}){const[o,i]=l.useState(!1),c=e.isDark,d=Pa(t);return s.jsxs(Ys,{meshTheme:e,title:"Missions",count:t.length||void 0,children:[t.length>0?s.jsxs("div",{className:"flex flex-col gap-0.5",children:[d.visible.map(p=>s.jsx(ed,{meshTheme:e,mission:p,onSelect:()=>a(p)},p.id)),s.jsx(Ra,{meshTheme:e,expanded:d.expanded,hiddenCount:d.hiddenCount,onToggle:d.toggle})]}):s.jsx(fn,{meshTheme:e,children:n?"No active missions. The coordinator creates a mission for multi-task work.":"Mission data unavailable from this daemon — update the daemon to see missions."}),r.length>0&&s.jsxs("div",{className:`mt-3 border-t pt-2 ${c?"border-white/8":"border-slate-200"}`,children:[s.jsxs("button",{type:"button",onClick:()=>i(p=>!p),className:`flex w-full items-center gap-1.5 text-[11px] font-medium ${e.textSecondary}`,children:[s.jsx("span",{className:`inline-block transition-transform ${o?"rotate-90":""}`,children:"▸"}),s.jsx("span",{children:"Completed / abandoned history"}),s.jsx("span",{className:`tabular-nums ${e.textMuted}`,children:r.length})]}),o&&s.jsx("div",{className:"mt-2 flex flex-col gap-0.5",children:r.map(p=>s.jsx(ed,{meshTheme:e,mission:p,onSelect:()=>a(p)},p.id))})]})]})}function N1({meshTheme:e,ledgerSummary:t,entries:r,resolveNodeLabel:n,onSelect:a}){const o=as(t.lastActivityAt),i=l.useMemo(()=>[...r].reverse(),[r]),c=Pa(i);return s.jsxs(Ys,{meshTheme:e,title:"Ledger",children:[s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(gt,{meshTheme:e,label:"Dispatched",value:t.taskDispatched}),s.jsx(gt,{meshTheme:e,label:"Completed",value:t.taskCompleted,tone:"emerald"}),s.jsx(gt,{meshTheme:e,label:"Failed",value:t.taskFailed,tone:t.taskFailed>0?"rose":void 0}),s.jsx(gt,{meshTheme:e,label:"Stalled",value:t.taskStalled,tone:t.taskStalled>0?"amber":void 0}),s.jsx(gt,{meshTheme:e,label:"Sessions",value:t.sessionLaunched}),s.jsx(gt,{meshTheme:e,label:"Checkpoints",value:t.checkpointCreated})]}),i.length>0&&s.jsxs("div",{className:`mt-3 border-t pt-2 ${e.isDark?"border-white/8":"border-slate-200"}`,children:[s.jsx("div",{className:`mb-1 text-[10px] uppercase tracking-wide ${e.textMuted}`,children:"Recent activity"}),s.jsxs("div",{className:"flex flex-col gap-0.5",children:[c.visible.map(d=>{const p=Am(d.payload);return s.jsxs(La,{meshTheme:e,onClick:()=>a(d),children:[s.jsx(Ot,{meshTheme:e,label:rl(d.kind),tone:Im(d.kind)}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${e.textSecondary}`,title:d.nodeId||void 0,children:p||n(d.nodeId)||d.sessionId||"—"}),s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:as(d.timestamp)??""})]},d.id)}),s.jsx(Ra,{meshTheme:e,expanded:c.expanded,hiddenCount:c.hiddenCount,onToggle:c.toggle})]})]}),(t.recentFailures>0||o&&i.length===0)&&s.jsxs("div",{className:`mt-2 flex items-center justify-between text-[11px] ${e.textMuted}`,children:[t.recentFailures>0?s.jsxs("span",{className:e.isDark?"text-amber-300":"text-amber-600",children:[t.recentFailures," recent failures"]}):s.jsx("span",{}),o&&i.length===0&&s.jsx("span",{children:o})]})]})}function S1({meshTheme:e,queueSummary:t,tasks:r,onSelect:n}){const a=l.useMemo(()=>[...r].sort((i,c)=>{const d=Qc(i.status)-Qc(c.status);return d!==0?d:(c.updatedAt||"").localeCompare(i.updatedAt||"")}).slice(0,d1),[r]),o=Pa(a);return t?s.jsxs(Ys,{meshTheme:e,title:"Queue",count:t.active>0?`${t.active} active`:void 0,children:[s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(gt,{meshTheme:e,label:"Pending",value:t.pending}),s.jsx(gt,{meshTheme:e,label:"Assigned",value:t.assigned,tone:t.assigned>0?"sky":void 0}),s.jsx(gt,{meshTheme:e,label:"Active",value:t.active,tone:t.active>0?"sky":void 0}),s.jsx(gt,{meshTheme:e,label:"Completed",value:t.completed,tone:"emerald"}),s.jsx(gt,{meshTheme:e,label:"Failed",value:t.failed,tone:t.failed>0?"rose":void 0}),s.jsx(gt,{meshTheme:e,label:"Cancelled",value:t.cancelled,tone:"muted"})]}),a.length>0&&s.jsxs("div",{className:`mt-3 border-t pt-2 ${e.isDark?"border-white/8":"border-slate-200"}`,children:[s.jsx("div",{className:`mb-1 text-[10px] uppercase tracking-wide ${e.textMuted}`,children:"Recent tasks"}),s.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.visible.map(i=>s.jsxs(La,{meshTheme:e,onClick:()=>n(i),children:[s.jsx(Ot,{meshTheme:e,label:i.status,tone:Cm(i.status)}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${e.textSecondary}`,title:i.message||void 0,children:a1(i.message)||i.id}),s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:as(i.updatedAt)??""})]},i.id)),s.jsx(Ra,{meshTheme:e,expanded:o.expanded,hiddenCount:o.hiddenCount,onToggle:o.toggle})]})]})]}):s.jsx(Ys,{meshTheme:e,title:"Queue",children:s.jsx(fn,{meshTheme:e,children:"No queue activity."})})}function C1(e){return e.autoFastForwardEligible||e.suggestedAction==="auto_fast_forward"?{label:"fast-forward",tone:"sky"}:e.launchBlockedReason?{label:"blocked",tone:"rose"}:null}function I1({meshTheme:e,nodes:t}){const r=e.isDark;return s.jsx(Ys,{meshTheme:e,title:"Nodes",count:t.length,children:t.length===0?s.jsx(fn,{meshTheme:e,children:"No nodes in this mesh yet."}):s.jsx("div",{className:"flex flex-col gap-1.5",children:t.map(n=>{var c,d,p;const a=(((c=n.activeSessionDetails)==null?void 0:c.length)??0)||(((d=n.activeSessions)==null?void 0:d.length)??0),o=C1(n),i=((p=n.git)==null?void 0:p.branch)??n.worktreeBranch??null;return s.jsxs("div",{className:`flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 overflow-hidden rounded-xl border px-3 py-2 ${r?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsx(Ot,{meshTheme:e,label:n.health,tone:m1(n.health)}),s.jsx("span",{className:`min-w-0 max-w-full flex-1 truncate text-sm font-medium ${e.textPrimary}`,title:n.workspace,children:n.machineLabel}),i&&s.jsx("span",{className:`max-w-full truncate font-mono text-[11px] ${e.textSecondary}`,title:i,children:i}),s.jsx("span",{className:`max-w-full truncate font-mono text-[10px] ${e.textMuted}`,children:p1(n)}),a>0&&s.jsxs("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:[a," session",a>1?"s":""]}),typeof n.daemonBuildVersion=="string"&&n.daemonBuildVersion&&s.jsxs("span",{className:`shrink-0 font-mono text-[10px] ${e.textMuted}`,title:"Daemon build version reported by this node",children:["v",n.daemonBuildVersion]}),o&&s.jsx(Ot,{meshTheme:e,label:o.label,tone:o.tone})]},n.nodeId)})})})}function A1({meshTheme:e,entries:t,onSelect:r}){const n=Pa(t);return s.jsx(Ys,{meshTheme:e,title:"Active sessions",count:t.length||void 0,children:t.length===0?s.jsx(fn,{meshTheme:e,children:"No active sessions."}):s.jsxs("div",{className:"flex flex-col gap-0.5",children:[n.visible.map(({node:a,session:o})=>{const i=km(o);return s.jsxs(La,{meshTheme:e,onClick:()=>r(a,o),children:[s.jsx("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${e.textMuted}`,children:Ta(o.sessionId)}),s.jsx("span",{className:`shrink-0 ${e.textMuted}`,children:o.providerType||"?"}),s.jsx(Ot,{meshTheme:e,label:i,tone:Nm(i)})]},o.sessionId)}),s.jsx(Ra,{meshTheme:e,expanded:n.expanded,hiddenCount:n.hiddenCount,onToggle:n.toggle})]})})}function M1({meshTheme:e,jobs:t}){const r=e.isDark,n=t.filter(a=>a.status==="failed").length;return s.jsx(Ys,{meshTheme:e,title:"Refine jobs",count:t.length||void 0,action:n>0?s.jsx(Ot,{meshTheme:e,label:`${n} failed`,tone:"rose"}):void 0,children:t.length===0?s.jsx(fn,{meshTheme:e,children:"No refine jobs."}):s.jsx("div",{className:"flex flex-col gap-1",children:t.slice(0,8).map(a=>s.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[s.jsxs("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${e.textMuted}`,children:[a.branch??a.jobId.slice(0,14),a.into?` → ${a.into}`:""]}),s.jsx("span",{className:`shrink-0 text-[10px] font-semibold ${a.status==="failed"?r?"text-rose-300":"text-rose-600":a.status==="running"||a.status==="accepted"?r?"text-sky-300":"text-sky-600":r?"text-emerald-300":"text-emerald-600"}`,children:a.status})]},a.jobId))})})}const _1=[{term:"Node",summary:"A workspace participating in the mesh — a repo checkout or an isolated git worktree.",details:["Base node vs worktree clone node — a clone isolates parallel work without conflicts.","Shows health (online/offline) alongside git state (branch · ahead/behind · dirty).","Multiple nodes can share the same daemon."]},{term:"P2P connection",summary:"How the selected coordinator reaches each remote node over WebRTC.",details:["direct — a direct host/STUN path; lowest latency.","relay — TURN-relayed; works through restrictive networks but is slower.","disconnected / failed — no live P2P link from the coordinator right now.","P2P connectivity is shown as transport and RTT chips on each node card (and in the node detail panel), not as a graph edge."]},{term:"Session",summary:"An agent CLI session running on a node.",details:["status = idle / generating / waiting_approval.","Distinguishes coordinator sessions (which dispatch and collect work) from delegated worker sessions (which do the work)."]},{term:"Task",summary:"A single unit of work handled by the queue-based pull model.",details:["States: pending → assigned → completed / failed / cancelled.","Idle nodes claim from the queue automatically; direct dispatch targets a specific session."]},{term:"Mission",summary:"A multi-task batch aimed at one goal, and the durable record of that effort.",details:["States: active / paused / completed / abandoned.","Progress is derived from the states of its member tasks."]},{term:"Refinery (refine)",summary:"The process of safely converging and merging a worktree branch into the base.",details:["Config-driven (.adhdev/refine.*) — guarded by a patch-equivalence preflight and a no-op guard.","ff-only by principle; no force-push.","If a submodule commit is unreachable from origin it must be published → classified as blocked_review."]},{term:"Completion model",summary:"Completion of delegated work is persisted to the queue (pending-events).",details:["The coordinator learns of completion via periodic polling or events.","Because it is persisted to the queue, completion signals are never lost."]},{term:"MAGI",summary:"Cross-verification: several independent AI agents answer the same question in parallel.",details:["Confidence comes from independence — different AIs on different machines fail in different ways.","When the agents disagree, the disagreement itself flags what to double-check.","Run via mesh_magi_review; the synthesis weighs agreement against source coupling."]},{term:"MAGI panel",summary:"A saved, reusable team of (machine × AI) members you invoke by name across investigations.",details:["Each member is one provider (AI) optionally pinned to a node (machine), with a replica count.","independent — spans ≥2 providers AND ≥2 machines, so agreement adds real confidence.","coupled — collapses to one AI or one machine; repeated members repeat the same mistakes.","Managed machine-locally from the Panels tab; defined in ~/.adhdev/meshes.json."]},{term:"Branch convergence states",summary:"After worktree work, each branch is classified into exactly one final state.",details:["merged_to_main — merged into the base.","pushed_feature_branch_needs_merge — pushed, awaiting merge.","blocked_review — held back by review/reachability issues.","cleanup_candidate — ready to clean up.","not_mergeable — cannot be merged."]}];function T1({meshTheme:e,open:t,onToggle:r}){const n=e.isDark,a="inline-flex h-7 w-7 items-center justify-center rounded-lg border transition",o=t?n?"border-sky-400/40 bg-sky-500/15 text-sky-100":"border-sky-400 bg-sky-100 text-sky-800":n?"border-white/10 bg-white/[0.04] text-slate-400 hover:bg-white/[0.08] hover:text-slate-100":"border-slate-200 bg-white text-slate-400 hover:bg-slate-50 hover:text-slate-700";return s.jsx("button",{type:"button",onClick:r,"aria-label":"Mesh help","aria-expanded":t,title:"Mesh concept help",className:`${a} ${o}`,children:s.jsx(gf,{size:15})})}function L1({meshTheme:e,onClose:t}){const r=e.isDark;return l.useEffect(()=>{const n=a=>{a.key==="Escape"&&t()};return window.addEventListener("keydown",n),()=>window.removeEventListener("keydown",n)},[t]),s.jsxs("div",{className:`shrink-0 rounded-2xl border p-4 ${r?"border-white/10 bg-white/[0.03]":"border-slate-200 bg-white/80"}`,role:"region","aria-label":"Mesh concept help",children:[s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`text-[10px] font-semibold uppercase tracking-[0.16em] ${e.textMuted}`,children:"Help"}),s.jsx("div",{className:`mt-0.5 text-sm font-semibold ${e.textPrimary}`,children:"Mesh concepts at a glance"})]}),s.jsx("button",{type:"button",onClick:t,"aria-label":"Close help",className:r?"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border border-white/10 bg-white/[0.04] text-slate-300 transition hover:bg-white/[0.08] hover:text-white":"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border border-slate-200 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",children:s.jsx(wt,{size:14})})]}),s.jsx("dl",{className:"grid gap-3 sm:grid-cols-2",children:_1.map(n=>s.jsxs("div",{className:`rounded-xl border p-3 ${r?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsx("dt",{className:`text-xs font-semibold ${e.textPrimary}`,children:n.term}),s.jsx("dd",{className:`mt-1 text-[11px] leading-5 ${e.textSecondary}`,children:n.summary}),n.details&&n.details.length>0&&s.jsx("ul",{className:`mt-1.5 flex flex-col gap-1 text-[11px] leading-5 ${e.textMuted}`,children:n.details.map((a,o)=>s.jsxs("li",{className:"flex gap-1.5",children:[s.jsx("span",{"aria-hidden":!0,className:"select-none",children:"·"}),s.jsx("span",{className:"min-w-0",children:a})]},o))})]},n.term))})]})}const Zs=l.createContext(Ls("dark"));function Ke({label:e,tone:t="default",className:r,title:n}){const a=l.useContext(Zs);return s.jsx("span",{title:n,className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.16em] ${a.badge(t)}${r?` ${r}`:""}`,children:e})}function St({label:e,value:t}){const r=l.useContext(Zs);return s.jsxs("div",{className:r.rowClass,children:[s.jsx("span",{className:r.rowLabelClass,children:e}),s.jsx("span",{className:r.rowValueClass,children:t})]})}const R1={meshId:"",totalEntries:0,taskDispatched:0,taskCompleted:0,taskFailed:0,taskStalled:0,sessionLaunched:0,checkpointCreated:0,lastActivityAt:null,recentFailures:0};function Mm(e){switch(e){case"online":return"good";case"dirty":return"warn";case"degraded":case"offline":return"danger";case"wrong_branch":return"info";default:return"default"}}function wo(e){switch((e||"").toLowerCase()){case"idle":return"good";case"generating":case"running":return"info";case"waiting_approval":case"starting":case"pending":return"warn";case"failed":case"stopped":case"interrupted":return"danger";default:return"default"}}function qn(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const r=t.toLowerCase().replace(/[\s-]+/g,"_");return r.includes("approval")?"awaiting approval":r.includes("generating")||r.includes("running")||r.includes("busy")?"generating":r.includes("idle")||r.includes("ready")||r.includes("waiting_input")?"idle":r.replace(/_/g," ")}function P1(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function D1(e){return e.startedAt||e.createdAt||null}function $1(e){const t=D1(e);if(!t)return"runtime age not reported";const r=Date.parse(t);if(!Number.isFinite(r))return"runtime age not reported";const n=Math.max(0,Math.floor((Date.now()-r)/1e3));if(n<60)return`${n}s`;const a=Math.floor(n/60);if(a<60)return`${a}m`;const o=Math.floor(a/60);return o<48?`${o}h ${a%60}m`:`${Math.floor(o/24)}d ${o%24}h`}function _m(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function E1(e){if(!e)return"default";if(e.state==="self")return"info";if(e.transport==="direct"&&e.state==="connected")return"good";if(e.transport==="relay"&&e.state==="connected")return"info";switch(e.state){case"connected":return"good";case"connecting":return"warn";case"disconnected":case"failed":case"closed":return"danger";default:return"default"}}function B1(e){return e?e.state==="self"?"mesh self":e.transport==="direct"&&e.state==="connected"?"mesh direct":e.transport==="relay"&&e.state==="connected"?"mesh relay":!e.reported&&e.source==="not_reported"?"mesh unknown / not reported":`mesh ${e.state}`:"mesh unknown"}function F1(e){const t=e.git;if(!t)return e.gitProbePending?"Git probe pending":"No git probe";const r=(t.staged??0)+(t.modified??0)+(t.untracked??0)+(t.deleted??0)+(t.renamed??0),n=[];t.branch&&n.push(t.branch),t.upstream&&t.upstreamStatus!=="fresh"&&n.push("upstream unverified"),t.upstreamStatus==="fresh"&&((t.ahead??0)>0||(t.behind??0)>0)&&n.push(`↑${t.ahead??0}/↓${t.behind??0}`),r>0&&n.push(`${r} dirty`);const a=(t.submodules??[]).filter(i=>i.dirty),o=(t.submodules??[]).filter(i=>i.outOfSync||i.error);return a.length>0&&n.push(`${a.length} submodule dirty`),o.length>0&&n.push(`${o.length} submodule drift`),t.hasConflicts&&n.push("conflicts"),n.join(" · ")||"Clean"}const O1={first_eligible:"In order",least_loaded:"Spread",round_robin:"Spread (round-robin)",priority_only:"Spread (priority)"};function H1(e){if(e.startsWith("max_provider_parallel_reached:"))return`provider cap reached (${e.slice(30)})`;switch(e){case"global_max_parallel_tasks_reached":return"global parallel cap reached";case"node_has_active_assignment":return"already running a write task";default:return e.replace(/_/g," ")}}function W1(e){var r;const t=[];for(const n of e.nodes){const a=n.activeSessionDetails&&n.activeSessionDetails.length>0?n.activeSessionDetails:(n.activeSessions??[]).map(o=>({sessionId:o,workspace:n.workspace,isCached:!0}));for(const o of a)t.push({nodeId:n.nodeId,machineLabel:n.machineLabel,workspace:n.workspace,branch:((r=n.git)==null?void 0:r.branch)??null,nodeHealth:n.health,session:o})}return t}function K1(e){return e.assignedNodeId||e.targetNodeId||null}function oi(e){return e?e.slice(0,7):null}function U1(e,t){var o,i,c;const r=oi((o=e==null?void 0:e.git)==null?void 0:o.headCommit),n=((c=(i=e==null?void 0:e.git)==null?void 0:i.headMessage)==null?void 0:c.trim())||"";if(r||n)return[r,n].filter(Boolean).join(" · ");const a=t[0];return a?[oi(a.commit),a.message].filter(Boolean).join(" · "):null}function z1(e,t){const r=U1(e,t);return r||(e!=null&&e.gitProbePending?"Pending live git probe":null)}function G1(e){const t=(e==null?void 0:e.result)??e,r=(t==null?void 0:t.log)??(e==null?void 0:e.log)??t;return Array.isArray(r==null?void 0:r.entries)?r.entries:[]}function V1(e){var r,n,a,o,i,c;const t=((r=e.selectedSessionEntry)==null?void 0:r.session.workspace)||((n=e.selectedSessionEntry)==null?void 0:n.workspace)||((o=(a=e.selectedNodeStatus)==null?void 0:a.git)==null?void 0:o.workspace)||((i=e.selectedNodeStatus)==null?void 0:i.workspace)||null;if(t&&e.selectedSessionEntry){const d=((c=e.selectedNodeStatus)==null?void 0:c.daemonId)||e.coordinatorDaemonId;return d?{daemonId:d,workspace:t}:null}if(t&&e.selectedNodeStatus){const d=e.selectedNodeStatus.daemonId||e.coordinatorDaemonId;return d?{daemonId:d,workspace:t}:null}return null}function q1(e){return e.gitProbePending&&(!e.connection||e.connection.state==="unknown")?"mesh pending":B1(e.connection)}function Y1(e){var r;const t=e.source;return t!=null&&t.kind?t.kind:((r=t==null?void 0:t.connection)==null?void 0:r.source)??"mesh_status"}function td(e){switch(e.type){case"parentBranch":return"default branch link";case"worktreeLink":return"worktree relationship";case"sessionLink":return"session relationship";case"orphanLink":return"orphan relationship";case"submoduleLink":return"submodule relationship";case"cloneLink":return"clone relationship";default:return e.type}}function J1(e){return e.direction==="directed"?"directed":"undirected"}function X1(e,t){return t?e.nodes.find(r=>r.id===t)??null:null}function Q1(e){var t,r,n,a;return[e.meshId,e.refreshedAt,e.nodes.length,((r=(t=e.queue)==null?void 0:t.summary)==null?void 0:r.active)??"",((a=(n=e.ledger)==null?void 0:n.summary)==null?void 0:a.recentFailures)??"",...e.nodes.map(o=>{var i,c,d,p,u,m,h,y,x,f,j,k,b,w,I,v,g,S,N,C,R,T;return[o.nodeId,o.daemonId??"",o.machineId??"",o.machineLabel,o.machineStatus??"",((i=o.connection)==null?void 0:i.state)??"",((c=o.connection)==null?void 0:c.transport)??"",((d=o.connection)==null?void 0:d.source)??"",o.health,o.gitProbePending?1:0,((p=o.git)==null?void 0:p.branch)??"",((u=o.git)==null?void 0:u.upstream)??"",((m=o.git)==null?void 0:m.upstreamStatus)??"",((h=o.git)==null?void 0:h.ahead)??"",((y=o.git)==null?void 0:y.behind)??"",((x=o.git)==null?void 0:x.headCommit)??"",((f=o.git)==null?void 0:f.staged)??"",((j=o.git)==null?void 0:j.modified)??"",((k=o.git)==null?void 0:k.untracked)??"",((b=o.git)==null?void 0:b.deleted)??"",((w=o.git)==null?void 0:w.renamed)??"",(I=o.git)!=null&&I.hasConflicts?1:0,((v=o.git)==null?void 0:v.lastCheckedAt)??"",((g=o.activeSessions)==null?void 0:g.join(","))??"",((S=o.activeSessionDetails)==null?void 0:S.length)??"",((N=o.activeSessionDetails)==null?void 0:N.map(_=>[_.sessionId,_.providerType??"",_.state??"",_.chatStatus??"",_.lifecycle??"",_.role??"",_.isSelfCoordinator?1:0,_.statusNote??"",_.startedAt??"",_.createdAt??""].join("/")).join(","))??"",((C=o.providers)==null?void 0:C.join(","))??"",((R=o.providerPriority)==null?void 0:R.join(","))??"",o.error??"",(((T=o.git)==null?void 0:T.submodules)??[]).map(_=>[_.path,_.commit,_.dirty?1:0,_.outOfSync?1:0,_.error??""].join("/")).join(",")].join("|")})].join("::")}function Z1(e){return e.nodes.length===0?!1:e.nodes.every(t=>t.health==="unknown"&&(!t.connection||t.connection.state==="unknown"))}function eN({scheduling:e}){const t=l.useContext(Zs);if(!e)return s.jsx("div",{className:`${t.cardClass} rounded-2xl p-4 text-[12px] ${t.textSecondary}`,children:"Scheduling runtime not reported by this daemon (older build). Update the coordinator daemon to surface distribution, parallel caps, and per-node load."});const r=e.globalWriteCapReached?"warn":"good";return s.jsxs("div",{className:`${t.cardClass} rounded-2xl p-4`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[12px] font-semibold ${t.textPrimary}`,children:"Scheduling"}),s.jsx(Ke,{label:O1[e.strategy]??e.strategy,tone:"info"}),s.jsx(Ke,{label:`write ${e.activeWriteAssigned}/${e.maxParallelTasks}`,tone:r,title:"Active write (non-readonly) assigned tasks vs the global parallel cap"}),s.jsx(Ke,{label:`readonly ${e.activeReadonlyAssigned}/${e.maxReadonlyParallelTasks}`,tone:e.globalReadonlyCapReached?"warn":"default",title:"Active read-only diagnosis tasks vs their (2× write) cap"})]}),s.jsx("p",{className:`mt-2 text-[11px] ${t.textSecondary}`,children:"Distribution only governs how untargeted work is spread across eligible nodes. Per-node load, priority, and provider caps are below."})]})}function tN({scheduling:e}){return e?s.jsxs(s.Fragment,{children:[s.jsx(Ke,{label:`load ${e.load}`,tone:e.load>0?"info":"default",title:"Active assigned tasks on this node"}),typeof e.schedulingPriority=="number"&&e.schedulingPriority!==0&&s.jsx(Ke,{label:`priority ${e.schedulingPriority}`,tone:"default",title:"Soft scheduling priority (higher = preferred)"}),(e.providerRoles??[]).map(t=>s.jsx(Ke,{label:`${t.providerType} ${t.activeAssigned}${typeof t.maxParallel=="number"?`/${t.maxParallel}`:""}`,tone:t.capReached?"warn":"default",title:"Per-(node, provider) active assignments vs declared maxParallel cap"},t.providerType)),e.capReached&&(e.capReasons??[]).map(t=>s.jsx(Ke,{label:H1(t),tone:"warn",title:"Why this node cannot currently claim a new write task"},t))]}):null}function sN({node:e}){var u,m,h,y;const t=l.useContext(Zs),r=((u=e.activeSessionDetails)==null?void 0:u.length)??((m=e.activeSessions)==null?void 0:m.length)??0,n=oi((h=e.git)==null?void 0:h.headCommit),a=e.isLocalWorktree===!0,o=e.worktreeBootstrap,i=e.staleDaemonBuild,c=e.providerVersions&&typeof e.providerVersions=="object"?e.providerVersions:void 0,d=c?Object.entries(c).filter(([,x])=>typeof x=="string"&&x):[],p=typeof e.daemonBuildVersion=="string"&&e.daemonBuildVersion?e.daemonBuildVersion:void 0;return s.jsxs("div",{className:`rounded-xl border p-3 ${t.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[12px] font-semibold ${t.textPrimary}`,children:e.machineLabel||e.nodeId}),s.jsx(Ke,{label:e.health,tone:Mm(e.health)}),a&&s.jsx(Ke,{label:"worktree",tone:"info",title:e.worktreeBranch?`Worktree branch ${e.worktreeBranch}`:"Local worktree node"}),(o==null?void 0:o.status)&&o.status!=="ready"&&s.jsx(Ke,{label:`bootstrap ${o.status}`,tone:"warn",title:"Worktree bootstrap is still in progress"}),((y=e.connection)==null?void 0:y.state)&&e.connection.state!=="self"&&s.jsx(Ke,{label:e.connection.state,tone:e.connection.state==="connected"?"good":"warn",title:"Mesh peer connection state"}),r>0&&s.jsx(Ke,{label:`${r} session${r===1?"":"s"}`,tone:"default"}),e.autoFastForwardEligible&&s.jsx(Ke,{label:"fast-forward ready",tone:"info",title:"Clean, behind upstream — safe for fast-forward"}),!!i&&s.jsx(Ke,{label:"stale build",tone:"warn",title:"Live daemon was built behind workspace HEAD — merged fixes may not be live"}),p&&s.jsx(Ke,{label:`build ${p}`,tone:"default",title:"Daemon build version reported by this node"}),s.jsx(tN,{scheduling:e.scheduling})]}),d.length>0&&s.jsx("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:d.map(([x,f])=>s.jsx(Ke,{label:`${x}@${f}`,tone:"info",title:"Detected provider version on this node"},x))}),s.jsxs("div",{className:`mt-1.5 text-[11px] ${t.textSecondary}`,children:[F1(e),n?s.jsxs("span",{className:"ml-2 font-mono opacity-70",children:["@",n]}):null]})]})}function rN({status:e}){const t=l.useContext(Zs),r=e.meshProtocolMetrics,n=Array.isArray(e.providerVersionSkew)?e.providerVersionSkew:[];return!r&&n.length===0?null:s.jsxs("div",{className:`${t.cardClass} rounded-2xl p-4`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[12px] font-semibold ${t.textPrimary}`,children:"Protocol & provider versions"}),r&&s.jsx(Ke,{label:`v2 ${Math.round(r.v2Ratio*100)}% (${r.v2}/${r.total})`,tone:r.total>0&&r.v2===r.total?"good":"info",title:"Share of pending coordinator events carrying a mesh-protocol-v2 envelope in this drain"}),n.length>0&&s.jsx(Ke,{label:`${n.length} provider skew`,tone:"warn",title:"Providers running different versions across nodes"})]}),r&&Object.keys(r.scopes).length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1.5",children:Object.entries(r.scopes).map(([a,o])=>s.jsx(Ke,{label:`${a}: ${o}`,tone:"default",title:"v2 event scope breakdown"},a))}),n.length>0&&s.jsx("div",{className:"mt-2 flex flex-col gap-1.5",children:n.map(a=>s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx("span",{className:`text-[11px] font-semibold ${t.textPrimary}`,children:a.provider}),a.versions.map(o=>s.jsx(Ke,{label:`${o.version} · ${o.nodeIds.length} node${o.nodeIds.length===1?"":"s"}`,tone:"default",title:o.nodeIds.join(", ")},o.version))]},a.provider))}),e.providerVersionSkewWarning&&s.jsx("p",{className:`mt-2 text-[11px] ${t.textSecondary}`,children:e.providerVersionSkewWarning})]})}function nN({canonicalStatus:e}){const t=l.useContext(Zs);return s.jsxs("div",{className:"flex flex-col gap-3 p-1",children:[s.jsx(eN,{scheduling:e.scheduling}),s.jsx(rN,{status:e}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx("span",{className:`px-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${t.textSecondary}`,children:"Nodes — runtime"}),e.nodes.length===0?s.jsx("div",{className:`rounded-xl border p-3 text-[12px] ${t.textSecondary} ${t.isDark?"border-white/10":"border-slate-200"}`,children:"No nodes reporting runtime yet."}):e.nodes.map(r=>s.jsx(sN,{node:r},r.nodeId))]})]})}function aN({canonicalStatus:e,queueSummary:t,ledgerSummary:r,isBootstrapMode:n,meshTheme:a,sessionEntries:o,inlineMode:i=!1}){var v;const c=t&&(t.active>0||t.historical>0),d=r.recentFailures>0||r.taskFailed>0,p=(v=e.queue)!=null&&v.tasks?e.queue.tasks.filter(g=>g.status==="failed"||g.status==="cancelled").slice(0,5):[],u=e.asyncRefineJobs,m=(u==null?void 0:u.filter(g=>g.status==="running"||g.status==="accepted"))??[],h=(u==null?void 0:u.filter(g=>g.status==="failed"))??[],y=e.staleDirectWorkSummary,x=y&&y.count>0;if(!c&&!d&&e.nodes.length===0&&!n&&m.length===0&&h.length===0&&!x&&o.length===0)return null;const f=a.isDark,j=`border-t ${f?"border-white/8":"border-slate-200"}`,k=`group w-full rounded-lg border text-xs ${f?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,b=`flex cursor-pointer list-none items-center gap-1.5 px-2.5 py-1.5 [&::-webkit-details-marker]:hidden ${a.textSecondary}`;function w({label:g,value:S,tone:N}){const C=N==="rose"?f?"text-rose-300":"text-rose-600":N==="sky"?f?"text-sky-300":"text-sky-600":N==="amber"?f?"text-amber-300":"text-amber-600":N==="emerald"?f?"text-emerald-300":"text-emerald-600":N==="muted"?a.textMuted:a.textPrimary;return s.jsxs("div",{className:`flex flex-col items-center rounded-lg border px-2 py-1.5 ${f?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-white/70"}`,children:[s.jsx("span",{className:`tabular-nums text-sm font-semibold leading-none ${C}`,children:S}),s.jsx("span",{className:`mt-0.5 text-[9px] uppercase tracking-wide ${a.textMuted}`,children:g})]})}const I=s.jsxs("div",{className:"flex flex-col gap-3 text-xs",children:[s.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t?s.jsxs(s.Fragment,{children:[s.jsx(w,{label:"Pending",value:t.pending}),s.jsx(w,{label:"Active",value:t.active,tone:t.active>0?"sky":void 0}),s.jsx(w,{label:"Done",value:t.completed,tone:"emerald"}),s.jsx(w,{label:"Failed",value:t.failed,tone:t.failed>0?"rose":void 0})]}):s.jsxs(s.Fragment,{children:[s.jsx(w,{label:"Done",value:r.taskCompleted,tone:"emerald"}),s.jsx(w,{label:"Failed",value:r.taskFailed,tone:r.taskFailed>0?"rose":void 0}),s.jsx(w,{label:"Sessions",value:r.sessionLaunched}),s.jsx(w,{label:"Recent↯",value:r.recentFailures,tone:r.recentFailures>0?"amber":"muted"})]})}),t&&s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(w,{label:"Ledger done",value:r.taskCompleted,tone:"emerald"}),s.jsx(w,{label:"Sessions",value:r.sessionLaunched}),s.jsx(w,{label:"Recent↯",value:r.recentFailures,tone:r.recentFailures>0?"amber":"muted"})]}),r.lastActivityAt&&s.jsxs("div",{className:`flex items-center justify-between ${a.textMuted}`,children:[s.jsx("span",{children:"Last activity"}),s.jsx("span",{className:"font-mono text-[10px]",children:r.lastActivityAt.slice(5,16)})]}),e.nodes.length>0&&s.jsx("div",{className:`pt-2.5 ${j}`,children:s.jsx("div",{className:"flex flex-col gap-1",children:e.nodes.map(g=>{var _;const S=((_=g.connection)==null?void 0:_.state)??"unknown",N=S==="unknown"||S==="connecting",T=N?"bg-amber-400":S==="failed"||S==="closed"||S==="disconnected"?f?"bg-rose-400":"bg-rose-500":S==="connected"||S==="self"?f?"bg-emerald-400":"bg-emerald-500":f?"bg-slate-500":"bg-slate-400";return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`size-1.5 shrink-0 rounded-full ${T}`}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${a.textSecondary}`,title:g.workspace,children:g.machineLabel}),s.jsx("span",{className:`shrink-0 font-mono text-[10px] ${a.textMuted}`,children:N?"…":S})]},g.nodeId)})})}),u&&u.length>0&&s.jsx("div",{className:`pt-2.5 ${j}`,children:s.jsxs("details",{className:k,children:[s.jsxs("summary",{className:b,children:[s.jsx("span",{className:"flex-1",children:"Refine jobs"}),s.jsx("span",{className:`tabular-nums ${f?"text-slate-400":"text-slate-500"}`,children:u.length}),h.length>0&&s.jsxs("span",{className:f?"text-rose-300":"text-rose-600",children:[h.length," failed"]})]}),s.jsx("div",{className:"flex flex-col gap-0.5 px-2.5 pb-2",children:u.slice(0,8).map(g=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${a.textMuted}`,children:[g.branch??g.jobId.slice(0,14),g.into?` → ${g.into}`:""]}),s.jsx("span",{className:`shrink-0 text-[9px] font-semibold ${g.status==="failed"?f?"text-rose-300":"text-rose-600":g.status==="running"||g.status==="accepted"?f?"text-sky-300":"text-sky-600":f?"text-emerald-300":"text-emerald-600"}`,children:g.status})]},g.jobId))})]})}),p.length>0&&s.jsx("div",{className:u&&u.length>0?"":`pt-2.5 ${j}`,children:s.jsxs("details",{className:k,children:[s.jsxs("summary",{className:b,children:[s.jsx("span",{className:`flex-1 ${f?"text-rose-300":"text-rose-600"}`,children:"Failed tasks"}),s.jsx("span",{className:`tabular-nums ${f?"text-rose-400":"text-rose-500"}`,children:p.length})]}),s.jsx("div",{className:"flex flex-col gap-1 px-2.5 pb-2",children:p.map(g=>s.jsxs("div",{className:"flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`font-mono text-[10px] ${a.textMuted}`,children:g.id.slice(0,10)}),g.message&&s.jsx("span",{className:`flex-1 truncate ${f?"text-slate-300":"text-slate-700"}`,children:g.message.slice(0,55)})]}),g.cancelReason&&s.jsx("div",{className:`truncate text-[10px] ${a.textMuted}`,children:g.cancelReason.slice(0,55)})]},g.id))})]})}),x&&s.jsxs("div",{className:`flex items-center justify-between pt-2.5 ${j}`,children:[s.jsx("span",{className:a.textMuted,children:"Stale work"}),s.jsx("span",{className:`tabular-nums ${f?"text-amber-300":"text-amber-600"}`,children:y.count})]}),o.length>0&&s.jsx("div",{className:`pt-2.5 ${j}`,children:s.jsxs("details",{className:k,children:[s.jsxs("summary",{className:b,children:[s.jsx("span",{className:"flex-1",children:"Sessions"}),s.jsx("span",{className:`tabular-nums ${f?"text-slate-400":"text-slate-500"}`,children:o.length})]}),s.jsx("div",{className:"flex flex-col gap-0.5 px-2.5 pb-2",children:o.map(g=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${a.textMuted}`,title:g.session.sessionId,children:_m(g.session.sessionId)}),s.jsx("span",{className:`shrink-0 ${a.textMuted}`,children:g.session.providerType||"?"}),s.jsx("span",{className:`shrink-0 text-[9px] font-semibold ${a.textMuted}`,children:qn(g.session)})]},g.session.sessionId))})]})})]});return i?I:s.jsxs("details",{className:`rounded-2xl border text-xs ${a.isDark?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsxs("summary",{className:`flex cursor-pointer list-none items-center gap-2 px-4 py-3 font-medium [&::-webkit-details-marker]:hidden ${a.textSecondary}`,children:[s.jsx("span",{className:"flex-1",children:"Mesh Health Panel"}),m.length>0&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${a.isDark?"border-sky-400/25 bg-sky-500/10 text-sky-200":"border-sky-300 bg-sky-50 text-sky-700"}`,children:[m.length," refining"]}),h.length>0&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${a.isDark?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700"}`,children:[h.length," refine failed"]}),d&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${a.isDark?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700"}`,children:[r.recentFailures," recent failures"]}),n&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${a.isDark?"border-amber-400/20 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700"}`,children:"awaiting live data"})]}),I]})}const oN={merged_to_main:"Merged to main",pushed_feature_branch_needs_merge:"Needs merge",blocked_review:"Blocked — needs review",cleanup_candidate:"Ready to clean up",not_mergeable:"Not mergeable"};function Tm({meshTheme:e,activeTab:t,onActiveTabChange:r,helpOpen:n,onHelpOpenChange:a}){const o=i=>i?e.isDark?"rounded-lg px-3.5 py-1.5 text-xs font-semibold text-slate-100 bg-white/[0.08] border border-white/12":"rounded-lg px-3.5 py-1.5 text-xs font-semibold text-slate-900 bg-white border border-slate-300 shadow-sm":`rounded-lg px-3.5 py-1.5 text-xs font-medium ${e.textSecondary} border border-transparent hover:bg-white/[0.04]`;return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("div",{className:`inline-flex w-fit items-center gap-1 rounded-xl border p-1 ${e.isDark?"border-white/10 bg-slate-950/40":"border-slate-200 bg-slate-50"}`,role:"tablist","aria-label":"Mesh view",children:[s.jsx("button",{type:"button",role:"tab","aria-selected":t==="overview",className:o(t==="overview"),onClick:()=>r("overview"),children:"Overview"}),s.jsx("button",{type:"button",role:"tab","aria-selected":t==="status",className:o(t==="status"),onClick:()=>r("status"),children:"Status"}),s.jsx("button",{type:"button",role:"tab","aria-selected":t==="graph",className:o(t==="graph"),onClick:()=>r("graph"),children:"Graph"})]}),s.jsx(T1,{meshTheme:e,open:n,onToggle:()=>a(!n)})]})}function iN({status:e,emptyMessage:t="No live mesh graph is available for this coordinator yet.",daemonId:r=null,sendDaemonCommand:n=null,bootstrapFallback:a,activeTab:o,onActiveTabChange:i,helpOpen:c,onHelpOpenChange:d,hideControls:p=!1}){var ke,Le,We;const{theme:u}=Ts(),m=l.useMemo(()=>Ls(u),[u]),h=l.useMemo(()=>gu(e),[e]),y=a??Z1(h),x=l.useMemo(()=>Q1(h),[h]),f=l.useMemo(()=>bm(h),[x]),[j,k]=l.useState("overview"),[b,w]=l.useState(!1),I=o??j,v=c??b,g=l.useCallback(ce=>{i?i(ce):k(ce)},[i]),S=l.useCallback(ce=>{d?d(ce):w(ce)},[d]),[N,C]=l.useState(!1);l.useEffect(()=>{I==="graph"&&C(!0)},[I]);const[R,T]=l.useState(null),[_,P]=l.useState(null),[B,z]=l.useState(null),[A,O]=l.useState({}),[$,L]=l.useState(null),[E,M]=l.useState(null),H=l.useMemo(()=>new Map(h.nodes.map(ce=>[ce.nodeId,ce])),[h.nodes]),Y=l.useMemo(()=>new Map(f.nodes.map(ce=>[ce.id,ce])),[f.nodes]),G=((ke=h.queue)==null?void 0:ke.summary)??null,J=((Le=h.ledger)==null?void 0:Le.summary)??R1,te=l.useMemo(()=>W1(h),[h]),oe=l.useMemo(()=>{const ce=new Map;for(const Ee of te){const Be=qn(Ee.session);ce.set(Be,(ce.get(Be)??0)+1)}return[...ce.entries()].sort((Ee,Be)=>Be[1]-Ee[1])},[te]);l.useEffect(()=>{R&&(Y.has(R)||(T(null),z(ce=>!ce||"nodeId"in ce&&ce.nodeId===R?null:ce)))},[Y,R]);const q=R?H.get(R)??null:null,F=X1(f,R),V=(B==null?void 0:B.kind)==="edge"&&_?f.edges.find(ce=>ce.id===_)??null:null,pe=V?f.nodes.find(ce=>ce.id===V.source)??null:null,be=V?f.nodes.find(ce=>ce.id===V.target)??null:null;l.useEffect(()=>{var ce,Ee,Be;if(R)try{console.info("[RepoMeshGraphDebug]",{event:"selected_canonical_node",meshId:h.meshId,selectedNodeId:R,canonicalNode:Ob(q),graphNode:F?{id:F.id,branch:F.branch,upstream:F.upstream,headCommit:F.submoduleCommit,submoduleCount:((Ee=(ce=q==null?void 0:q.git)==null?void 0:ce.submodules)==null?void 0:Ee.length)??0,snapshotCompleteness:F.snapshotCompleteness,snapshotWarnings:F.snapshotWarnings,branchConvergence:((Be=F.branchConvergence)==null?void 0:Be.status)??null}:null})}catch{}},[h.meshId,F,R,q]);const ue=(B==null?void 0:B.kind)==="session"?te.find(ce=>ce.nodeId===B.nodeId&&ce.session.sessionId===B.sessionId)??null:null,Ne=l.useMemo(()=>te.filter(ce=>ce.nodeId===R),[R,te]),se=V1({coordinatorDaemonId:r,selectedNodeStatus:q,selectedSessionEntry:ue}),ve=(se==null?void 0:se.workspace)??null,me=ve?A[ve]??null:null,U=z1(q,(me==null?void 0:me.entries)??[]),W=(F==null?void 0:F.daemonId)??(q==null?void 0:q.daemonId)??r??null,Z=!!(F&&n&&W&&F.type!=="submoduleNode"&&F.behind>0&&F.ahead===0&&F.dirtyFiles===0&&!F.dirty&&!F.hasConflicts&&F.upstreamStatus==="fresh"),ie=l.useCallback(()=>{T(null),P(null),z(null),L(null)},[]);l.useEffect(()=>{L(null)},[R]);const ye=l.useCallback(async()=>{if(!F||!W||!n||!Z)return;M(F.id),L(null);const ce=(q==null?void 0:q.workspace)??F.workspace??"";try{const Ee=await n(W,"fast_forward_mesh_node",{meshId:h.meshId,nodeId:F.id,workspace:ce,updateSubmodules:!0,dryRun:!0,execute:!1}),Be=(Ee==null?void 0:Ee.result)??Ee;if(L({phase:"dry_run",code:typeof(Be==null?void 0:Be.code)=="string"?Be.code:void 0,error:typeof(Be==null?void 0:Be.operationError)=="string"?Be.operationError:null,executed:(Be==null?void 0:Be.executed)===!0}),!(Be!=null&&Be.success)||Be.code!=="fast_forward_available"||!window.confirm(`Apply fast-forward for ${F.label}?`))return;const qe=await n(W,"fast_forward_mesh_node",{meshId:h.meshId,nodeId:F.id,workspace:ce,updateSubmodules:!0,dryRun:!1,execute:!0}),je=(qe==null?void 0:qe.result)??qe;L({phase:"execute",code:typeof(je==null?void 0:je.code)=="string"?je.code:void 0,error:typeof(je==null?void 0:je.operationError)=="string"?je.operationError:null,executed:(je==null?void 0:je.executed)===!0})}catch(Ee){L({phase:"dry_run",error:Ee instanceof Error?Ee.message:"fast-forward failed"})}finally{M(null)}},[Z,h.meshId,F,W,n]);l.useEffect(()=>{if(!F&&!V)return;const ce=Ee=>{Ee.key==="Escape"&&ie()};return window.addEventListener("keydown",ce),()=>window.removeEventListener("keydown",ce)},[ie,V,F]),l.useEffect(()=>{if(!se||!n)return;const{daemonId:ce,workspace:Ee}=se,Be=A[Ee];if(Be!=null&&Be.loading||Be&&(Be.entries.length>0||Be.error))return;let Je=!1;return O(qe=>{var je;return{...qe,[Ee]:{loading:!0,error:null,entries:((je=qe[Ee])==null?void 0:je.entries)??[]}}}),n(ce,"git_log",{workspace:Ee,limit:5}).then(qe=>{Je||O(je=>({...je,[Ee]:{loading:!1,error:null,entries:G1(qe)}}))}).catch(qe=>{Je||O(je=>({...je,[Ee]:{loading:!1,error:qe instanceof Error?qe.message:"git_log failed",entries:[]}}))}),()=>{Je=!0}},[A,se,n]);const fe=[...f.warnings??[],...h.nodes.filter(ce=>ce.machineStatus&&ce.machineStatus!=="online").map(ce=>`${ce.machineLabel}: ${ce.machineStatus}`)],D=f.stats.incompleteSnapshotNodes>0,he=f.stats.followUpNodes>0?`${f.stats.followUpNodes} need follow-up`:D?"mesh visibility incomplete":"mesh converged",Se=f.stats.followUpNodes>0?"danger":D?"warn":"good",[ae,Q]=l.useState("LR"),we=ce=>ce?m.isDark?"rounded-md border border-cyan-400/40 bg-cyan-500/15 px-2 py-0.5 text-cyan-100":"rounded-md border border-sky-400 bg-sky-100 px-2 py-0.5 text-sky-800":m.isDark?"rounded-md border border-white/10 bg-white/[0.03] px-2 py-0.5 text-slate-400 hover:text-slate-200":"rounded-md border border-slate-300 bg-white/80 px-2 py-0.5 text-slate-500 hover:text-slate-800";return s.jsx(Zs.Provider,{value:m,children:s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[!p&&s.jsx("div",{className:"shrink-0 flex items-center justify-end",children:s.jsx(Tm,{meshTheme:m,activeTab:I,onActiveTabChange:g,helpOpen:v,onHelpOpenChange:S})}),v&&s.jsx(L1,{meshTheme:m,onClose:()=>S(!1)}),s.jsx("div",{className:`${I==="overview"?"flex":"hidden"} min-h-0 flex-1 flex-col gap-3 overflow-y-auto`,children:I==="overview"&&s.jsx(h1,{status:h,daemonId:r,meshId:h.meshId,sendDaemonCommand:n})}),s.jsx("div",{className:`${I==="status"?"flex":"hidden"} min-h-0 flex-1 flex-col overflow-y-auto`,children:I==="status"&&s.jsx(nN,{canonicalStatus:h})}),s.jsx("div",{className:`${I==="graph"?"flex":"hidden"} min-h-0 flex-1 flex-col gap-4`,children:s.jsxs("div",{className:`${m.cardClass} relative flex min-h-0 flex-1 flex-col rounded-[28px]`,style:{minHeight:480},children:[s.jsxs("div",{className:`relative z-30 max-h-[42dvh] overflow-y-auto sm:max-h-none sm:mb-3 sm:overflow-visible shrink-0 flex flex-wrap items-start justify-between gap-2 px-4 pt-3 pb-2.5 border-b ${m.isDark?"border-white/8":"border-slate-200"}`,children:[s.jsxs("div",{className:`flex min-w-0 flex-1 flex-nowrap overflow-x-auto sm:flex-wrap sm:overflow-visible gap-2 text-xs ${m.textSecondary}`,children:[s.jsx(Ke,{label:he,tone:Se,className:"shrink-0"}),f.stats.blockedReviewNodes>0&&s.jsx(Ke,{label:`${f.stats.blockedReviewNodes} blocked`,title:`${f.stats.blockedReviewNodes} blocked review`,tone:"danger",className:"shrink-0"}),f.stats.notMergeableNodes>0&&s.jsx(Ke,{label:`${f.stats.notMergeableNodes} not mergeable`,tone:"danger",className:"shrink-0"}),f.stats.mergeReadyNodes>0&&s.jsx(Ke,{label:`${f.stats.mergeReadyNodes} need merge`,tone:"warn",className:"shrink-0"}),f.stats.cleanupCandidateNodes>0&&s.jsx(Ke,{label:`${f.stats.cleanupCandidateNodes} cleanup`,title:`${f.stats.cleanupCandidateNodes} refine/cleanup`,tone:"info",className:"shrink-0"}),f.stats.offlineNodes>0&&s.jsx(Ke,{label:`${f.stats.offlineNodes} offline`,tone:"danger",className:"shrink-0"}),f.stats.incompleteSnapshotNodes>0&&s.jsx(Ke,{label:`${f.stats.incompleteSnapshotNodes} incomplete`,title:`${f.stats.incompleteSnapshotNodes} incomplete peer snapshot`,tone:"warn",className:"shrink-0"}),f.stats.missingGitSnapshotNodes>0&&s.jsx(Ke,{label:`${f.stats.missingGitSnapshotNodes} no-git`,title:`${f.stats.missingGitSnapshotNodes} no git snapshot`,tone:"warn",className:"shrink-0"}),f.stats.missingSubmoduleSnapshotNodes>0&&s.jsx(Ke,{label:`${f.stats.missingSubmoduleSnapshotNodes} no-submod`,title:`${f.stats.missingSubmoduleSnapshotNodes} missing submodule visibility`,tone:"warn",className:"shrink-0"}),f.stats.staleGitSnapshotNodes>0&&s.jsx(Ke,{label:`${f.stats.staleGitSnapshotNodes} stale`,title:`${f.stats.staleGitSnapshotNodes} stale peer snapshot`,tone:"warn",className:"shrink-0"}),((G==null?void 0:G.active)??0)>0&&s.jsx(Ke,{label:`${(G==null?void 0:G.active)??0} active queue`,tone:"info",className:"shrink-0 hidden sm:inline-flex"}),s.jsx(Ke,{label:`${f.stats.totalNodes} nodes`,tone:"default",className:"shrink-0 hidden sm:inline-flex"}),f.stats.totalActiveSessions>0&&s.jsx(Ke,{label:`${f.stats.totalActiveSessions} attached chats`,tone:"info",className:"shrink-0 hidden sm:inline-flex"})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[s.jsxs("div",{className:m.isDark?"flex items-center gap-0.5 rounded-md border border-white/10 bg-slate-950/40 p-0.5 text-[10px]":"flex items-center gap-0.5 rounded-md border border-slate-300 bg-white/70 p-0.5 text-[10px]",role:"group","aria-label":"Graph layout direction",children:[s.jsx("button",{type:"button",onClick:()=>Q("auto"),className:we(ae==="auto"),title:"Auto-detect direction",children:"Auto"}),s.jsx("button",{type:"button",onClick:()=>Q("LR"),className:we(ae==="LR"),title:"Left to right",children:"LR"}),s.jsx("button",{type:"button",onClick:()=>Q("TB"),className:we(ae==="TB"),title:"Top to bottom",children:"TB"})]}),s.jsx("div",{className:"relative",children:s.jsxs("details",{className:`rounded-xl px-3 py-1.5 text-xs ${m.isDark?"border border-white/10 bg-white/[0.03] text-slate-300":"border border-slate-200 bg-slate-50 text-slate-600"}`,children:[s.jsx("summary",{className:`cursor-pointer list-none font-medium ${m.textSecondary} [&::-webkit-details-marker]:hidden`,children:(()=>{var Be;const ce=((Be=h.asyncRefineJobs)==null?void 0:Be.filter(Je=>Je.status==="failed").length)??0,Ee=J.recentFailures;return ce>0?s.jsxs("span",{className:m.isDark?"text-rose-300":"text-rose-600",children:[ce," refine failed"]}):Ee>0?s.jsxs("span",{className:m.isDark?"text-amber-300":"text-amber-600",children:[Ee," failures"]}):"Health"})()}),s.jsx("div",{className:`absolute right-0 z-40 mt-2 w-72 max-h-[70vh] overflow-y-auto rounded-xl border p-4 shadow-xl backdrop-blur-xl ${m.isDark?"border-white/10 bg-slate-950/96":"border-slate-200 bg-white/98 shadow-slate-900/10"}`,children:s.jsx(aN,{canonicalStatus:h,queueSummary:G,ledgerSummary:J,isBootstrapMode:y,meshTheme:m,sessionEntries:te,inlineMode:!0})})]})}),s.jsx("div",{className:"relative",children:s.jsxs("details",{className:`rounded-xl px-3 py-1.5 text-xs ${m.isDark?"border border-white/10 bg-white/[0.03] text-slate-300":"border border-slate-200 bg-slate-50 text-slate-600"}`,children:[s.jsx("summary",{className:`cursor-pointer list-none font-medium ${m.textSecondary} [&::-webkit-details-marker]:hidden`,children:"Legend"}),s.jsx("div",{className:`absolute right-0 z-40 mt-2 w-72 rounded-xl border p-3 shadow-xl backdrop-blur-xl ${m.isDark?"border-white/10 bg-slate-950/96":"border-slate-200 bg-white/98 shadow-slate-900/10"}`,children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ke,{label:`${f.stats.dirtyNodes} dirty`,tone:f.stats.dirtyNodes>0?"warn":"good"}),s.jsx(Ke,{label:`${f.stats.orphanNodes} orphan`,tone:f.stats.orphanNodes>0?"warn":"good"}),s.jsx(Ke,{label:`${J.recentFailures} recent failures`,tone:J.recentFailures>0?"danger":"good"}),oe.length===0?s.jsx(Ke,{label:"no session metadata"}):oe.slice(0,2).map(([ce,Ee])=>s.jsx(Ke,{label:`${Ee} ${ce}`,tone:wo(ce)},ce))]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ke,{label:"Anchor = default branch",tone:"info"}),s.jsx(Ke,{label:"Peer link = same-branch worktree",tone:"default"}),s.jsx(Ke,{label:"Submodule link = child checkout",tone:"warn"})]}),fe.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:fe.map(ce=>s.jsx("span",{className:m.isDark?"rounded-full border border-amber-400/20 bg-amber-500/10 px-3 py-1 text-xs text-amber-100":"rounded-full border border-amber-300 bg-amber-50 px-3 py-1 text-xs text-amber-700",children:ce},ce))}),s.jsx("div",{className:`text-xs ${m.textMuted}`,children:"Click a node or edge to pin its drill-down details in the side panel. Click it again to close."})]})})]})})]})]}),y&&f.nodes.length>0&&s.jsxs("div",{className:`shrink-0 mx-4 mt-2 flex items-center gap-2 rounded-xl border px-3.5 py-2 text-xs ${m.isDark?"border-amber-400/20 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700"}`,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full animate-pulse ${m.isDark?"bg-amber-400":"bg-amber-500"}`,"aria-hidden":!0}),s.jsx("span",{children:"Awaiting live data — showing setup inventory until peer mesh_status probes succeed."})]}),s.jsxs("div",{className:"relative flex flex-1 min-w-0",style:{minHeight:360},children:[s.jsx("div",{className:"flex-1 min-w-0",children:N?f.nodes.length>0?s.jsx(r1,{data:f,selectedNodeId:R,directionPref:ae,onNodeClick:ce=>{if((B==null?void 0:B.kind)==="node"&&R===ce.id){ie();return}P(null),T(ce.id),z({kind:"node",nodeId:ce.id})},onEdgeClick:ce=>{if((B==null?void 0:B.kind)==="edge"&&_===ce.id){ie();return}T(null),P(ce.id),z({kind:"edge",edgeId:ce.id})}}):s.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:t}):s.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:"Loading graph…"})}),F&&(B==null?void 0:B.kind)==="node"&&s.jsxs("div",{role:"dialog",className:`absolute inset-x-3 bottom-3 top-20 z-20 rounded-2xl border shadow-2xl sm:relative sm:inset-auto sm:z-auto sm:w-72 sm:shrink-0 sm:rounded-none sm:border-0 sm:border-l sm:shadow-none overflow-y-auto p-4 ${m.isDark?"border-white/10 bg-slate-950 sm:bg-transparent":"border-slate-200 bg-white sm:bg-transparent"}`,children:[s.jsx("div",{className:`mb-2 text-[10px] font-semibold uppercase tracking-wide ${m.textMuted}`,children:"Selected node"}),s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${m.textPrimary}`,children:F.label}),s.jsx("div",{className:`mt-0.5 font-mono text-[11px] ${m.textMuted}`,children:F.id.slice(0,16)})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[F.behind>0&&s.jsx("button",{type:"button",onClick:()=>{ye()},disabled:!Z||E===F.id,className:m.isDark?"rounded-full border border-emerald-400/25 bg-emerald-500/10 px-2 py-0.5 text-xs font-semibold text-emerald-100 transition hover:bg-emerald-500/18 disabled:cursor-not-allowed disabled:opacity-45":"rounded-full border border-emerald-300 bg-emerald-50 px-2 py-0.5 text-xs font-semibold text-emerald-700 transition hover:bg-emerald-100 disabled:cursor-not-allowed disabled:opacity-45",children:E===F.id?"Checking":"Heal"}),s.jsx("button",{type:"button",onClick:ie,"aria-label":"Close detail panel",className:m.isDark?"rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-xs text-slate-200 transition hover:bg-white/[0.08]":"rounded-full border border-slate-200 bg-white px-2 py-0.5 text-xs text-slate-600 transition hover:bg-slate-50",children:"✕"})]})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-1.5",children:[(()=>{const ce=(q==null?void 0:q.health)??F.health;return ce==="unknown"?s.jsx(Ke,{label:"connecting...",tone:"default"}):s.jsx(Ke,{label:ce,tone:Mm(ce)})})(),F.branch&&s.jsx(Ke,{label:F.branch,tone:"default"}),F.ahead>0&&s.jsx(Ke,{label:`ahead ${F.ahead}`,tone:"warn"}),F.behind>0&&s.jsx(Ke,{label:`behind ${F.behind}`,tone:"warn"}),F.dirtyFiles>0&&s.jsx(Ke,{label:`${F.dirtyFiles} dirty`,tone:"warn"}),(q==null?void 0:q.connection)&&q.connection.state!=="unknown"&&s.jsx(Ke,{label:q1(q),tone:E1(q.connection)}),((We=q==null?void 0:q.connection)==null?void 0:We.state)==="unknown"&&s.jsx(Ke,{label:"mesh connecting...",tone:"warn"}),Ne.length>0&&s.jsx(Ke,{label:`${Ne.length} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[F.machineLabel&&s.jsx(St,{label:"Machine",value:F.machineLabel}),F.locality&&F.locality!=="unknown"&&s.jsx(St,{label:"Locality",value:F.locality}),s.jsx(St,{label:"Workspace",value:(q==null?void 0:q.workspace)??F.workspace}),U&&s.jsx(St,{label:"HEAD",value:U}),(F.dirtyFiles>0||F.ahead>0||F.behind>0)&&s.jsx(St,{label:"Dirty/ahead/behind",value:`${F.dirtyFiles}/${F.ahead}/${F.behind}`}),Ne.length>0&&s.jsx(St,{label:"Sessions",value:String(Ne.length)}),F.upstream&&s.jsx(St,{label:"Upstream",value:F.upstream}),(()=>{var Ee;const ce=((Ee=q==null?void 0:q.connection)==null?void 0:Ee.source)??Y1(F);return ce&&ce!=="unknown"?s.jsx(St,{label:"Source",value:String(ce)}):null})(),(()=>{var Ee;const ce=(Ee=q==null?void 0:q.connection)==null?void 0:Ee.transport;return ce&&ce!=="unknown"?s.jsx(St,{label:"Transport",value:ce}):null})(),(()=>{const ce=F.machineId??(q==null?void 0:q.machineId);return ce?s.jsx(St,{label:"Machine id",value:ce}):null})(),(()=>{const ce=F.daemonId??(q==null?void 0:q.daemonId);return ce?s.jsx(St,{label:"Daemon id",value:ce}):null})()]}),Ne.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${m.textMuted}`,children:"Active Sessions"}),s.jsx("div",{className:"flex flex-col gap-1.5",children:Ne.map(ce=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${m.isDark?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-slate-50/80"}`,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`min-w-0 truncate font-mono select-text ${m.textMuted}`,title:ce.session.sessionId,children:_m(ce.session.sessionId)}),s.jsx(Ke,{label:qn(ce.session),tone:wo(qn(ce.session))})]}),s.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 ${m.textMuted}`,children:[s.jsx("span",{className:"truncate",children:ce.session.providerType||"provider unknown"}),s.jsx("span",{children:P1(ce.session)}),s.jsx("span",{children:$1(ce.session)})]}),ce.session.statusNote&&s.jsx("div",{className:`mt-1 text-[10px] leading-4 ${m.textMuted}`,children:ce.session.statusNote}),s.jsxs("div",{className:`mt-0.5 truncate ${m.textMuted}`,title:ce.session.workspace||ce.workspace,children:[(ce.session.workspace||ce.workspace).slice(0,38),ce.branch?` · ${ce.branch}`:""]})]},ce.session.sessionId))})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${m.textMuted}`,children:"Ledger (mesh-wide)"}),s.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[s.jsx(St,{label:"Completed",value:String(J.taskCompleted)}),s.jsx(St,{label:"Failed",value:s.jsx("span",{className:J.taskFailed>0?m.isDark?"text-rose-300":"text-rose-600":"",children:J.taskFailed})}),s.jsx(St,{label:"Launched",value:String(J.sessionLaunched)}),s.jsx(St,{label:"Recent failures",value:s.jsx("span",{className:J.recentFailures>0?m.isDark?"text-amber-300":"text-amber-600":"",children:J.recentFailures})})]})]}),(()=>{var Be,Je;const ce=((Be=h.queue)==null?void 0:Be.tasks)??((Je=h.queue)==null?void 0:Je.items)??null;if(!Array.isArray(ce)||ce.length===0)return null;const Ee=ce.filter(qe=>K1(qe)===R).slice(0,3);return Ee.length===0?null:s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${m.textMuted}`,children:"Queue tasks"}),s.jsx("div",{className:"flex flex-col gap-1.5",children:Ee.map(qe=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${m.isDark?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-slate-50/80"}`,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`font-mono ${m.textMuted}`,children:qe.id.slice(0,12)}),s.jsx(Ke,{label:qe.status??"unknown",tone:wo(qe.status)})]}),qe.message&&s.jsx("div",{className:`mt-0.5 truncate ${m.textMuted}`,children:qe.message.slice(0,48)})]},qe.id))})]})})(),F.snapshotWarnings.length>0&&s.jsxs("div",{className:m.isDark?"mt-3 rounded-xl border border-amber-400/20 bg-amber-500/10 p-3 text-xs text-amber-100":"mt-3 rounded-xl border border-amber-300 bg-amber-50 p-3 text-xs text-amber-800",children:[s.jsx("div",{className:"font-medium",children:"Key warning"}),s.jsx("div",{className:"mt-1",children:F.snapshotWarnings[0]})]}),F.branchConvergence&&(F.branchConvergence.reason||F.branchConvergence.nextStep)&&s.jsxs("div",{className:m.isDark?"mt-3 rounded-xl border border-sky-400/20 bg-sky-500/10 p-3 text-xs text-sky-100":"mt-3 rounded-xl border border-sky-300 bg-sky-50 p-3 text-xs text-sky-800",children:[s.jsxs("div",{className:"font-medium",children:["Follow-up — ",oN[F.branchConvergence.status]??F.branchConvergence.status]}),F.branchConvergence.reason&&s.jsx("div",{className:"mt-1",children:F.branchConvergence.reason}),F.branchConvergence.nextStep&&s.jsx("div",{className:`${F.branchConvergence.reason?"mt-1.5 pt-1.5 border-t border-sky-400/20":"mt-1"}`,children:F.branchConvergence.nextStep})]}),$&&s.jsxs("div",{className:m.isDark?"mt-3 rounded-xl border border-emerald-400/20 bg-emerald-500/10 p-3 text-xs text-emerald-100":"mt-3 rounded-xl border border-emerald-300 bg-emerald-50 p-3 text-xs text-emerald-800",children:[s.jsx("div",{className:"font-medium",children:$.phase==="execute"?"Heal result":"Heal preview"}),s.jsx("div",{className:"mt-1",children:$.code??$.error??"No result code returned."})]})]}),V&&(B==null?void 0:B.kind)==="edge"&&s.jsxs("div",{role:"dialog",className:`absolute inset-x-3 bottom-3 top-20 z-20 rounded-2xl border shadow-2xl sm:relative sm:inset-auto sm:z-auto sm:w-72 sm:shrink-0 sm:rounded-none sm:border-0 sm:border-l sm:shadow-none overflow-y-auto p-4 ${m.isDark?"border-white/10 bg-slate-950 sm:bg-transparent":"border-slate-200 bg-white sm:bg-transparent"}`,children:[s.jsx("div",{className:`mb-2 text-[10px] font-semibold uppercase tracking-wide ${m.textMuted}`,children:"Selected edge"}),s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${m.textPrimary}`,children:V.label||td(V)}),s.jsx("div",{className:`mt-0.5 break-all font-mono text-[11px] ${m.textMuted}`,children:V.id})]}),s.jsx("button",{type:"button",onClick:ie,"aria-label":"Close detail panel",className:m.isDark?"shrink-0 rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-xs text-slate-200 transition hover:bg-white/[0.08]":"shrink-0 rounded-full border border-slate-200 bg-white px-2 py-0.5 text-xs text-slate-600 transition hover:bg-slate-50",children:"✕"})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-1.5",children:[s.jsx(Ke,{label:td(V),tone:"default"}),s.jsx(Ke,{label:J1(V),tone:"info"})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(St,{label:"From",value:(pe==null?void 0:pe.label)??V.source}),s.jsx(St,{label:"To",value:(be==null?void 0:be.label)??V.target}),s.jsx(St,{label:"Label",value:V.label??"none"})]})]})]})]})})]})})}function yt(e){return typeof e=="string"?e.trim():""}function ii(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function nl(...e){const t=new Set;for(const r of e){const n=yt(r);n&&t.add(n)}return[...t]}function lN(e,t){var m,h;const r=ii(e==null?void 0:e.settings),n=yt((m=e==null?void 0:e.coordinator)==null?void 0:m.meshId)||yt(r.meshCoordinatorFor),a=yt(r.meshNodeFor),o=!!n||!!a,i=n===t||a===t;if(o&&!i)return null;const c=ii(e==null?void 0:e.activeChat),d=nl(e==null?void 0:e.id,e==null?void 0:e.sessionId,e==null?void 0:e.session_id,e==null?void 0:e.providerSessionId,e==null?void 0:e.provider_session_id,e==null?void 0:e.targetSessionId,e==null?void 0:e.target_session_id,c.sessionId,c.session_id,c.providerSessionId,c.provider_session_id),p=d[0]||"";if(!p)return null;const u=n===t?yt((h=e==null?void 0:e.coordinator)==null?void 0:h.role)||"coordinator":a===t?yt(r.meshNodeRole)||"worker":yt(e==null?void 0:e.role)||yt(r.meshNodeRole)||void 0;return{sessionId:p,aliases:d,meshId:t,nodeId:i&&yt(r.meshNodeId)||null,providerType:yt(e==null?void 0:e.providerType)||void 0,state:yt(e==null?void 0:e.status)||void 0,chatStatus:yt(c.status)||void 0,lifecycle:yt(e==null?void 0:e.runtimeLifecycle)||void 0,surfaceKind:yt(e==null?void 0:e.runtimeSurfaceKind)||void 0,recoveryState:yt(e==null?void 0:e.runtimeRecoveryState)||void 0,...u?{role:u}:{},...i?{isSelfCoordinator:n===t}:{},workspace:yt(e==null?void 0:e.workspace)||null}}function Lm(e,t){var n;return t?(Array.isArray((n=e.status)==null?void 0:n.sessions)?e.status.sessions:[]).map(a=>lN(a,t)).filter(a=>a!==null):[]}function xa(e){return e.aliases&&e.aliases.length>0?e.aliases:[e.sessionId]}function cN(e,t){const r=new Set(xa(t));return xa(e).some(n=>r.has(n))}function dN(e,t){const r=t.filter(a=>!!a);return r.length===0?e:[...e.filter(a=>!r.some(o=>cN(a,o))),...r]}function uN(e,t){if(t.length===0)return e;const r=new Map;for(const i of t)for(const c of xa(i))r.set(c,i);let n=!1;const o=(e.nodes??[]).map((i,c)=>{const d=Array.isArray(i.activeSessionDetails)?i.activeSessionDetails:Array.isArray(i.sessions)?i.sessions:[],p=new Map;for(const h of d){const y=nl(h==null?void 0:h.sessionId,h==null?void 0:h.session_id,h==null?void 0:h.id,h==null?void 0:h.providerSessionId,h==null?void 0:h.provider_session_id),x=y[0]||"";if(!x)continue;const f=y.map(j=>r.get(j)).find(Boolean);f&&(n=!0),p.set(x,f?{...h,sessionId:x,providerType:f.providerType||h.providerType,state:f.state||h.state,chatStatus:f.chatStatus||h.chatStatus,lifecycle:f.lifecycle||h.lifecycle,surfaceKind:f.surfaceKind||h.surfaceKind,recoveryState:f.recoveryState||h.recoveryState,role:f.role||h.role,isSelfCoordinator:f.isSelfCoordinator??h.isSelfCoordinator,workspace:f.workspace||h.workspace}:{...h,sessionId:x})}for(const h of i.activeSessions??[])p.has(h)||p.set(h,{sessionId:h,workspace:i.workspace,isCached:!0});const u=c===0;for(const h of t){if(xa(h).some(j=>p.has(j)))continue;const x=h.nodeId!=null&&h.nodeId===i.nodeId,f=h.isSelfCoordinator&&!h.nodeId&&u;!x&&!f||(n=!0,p.set(h.sessionId,{sessionId:h.sessionId,providerType:h.providerType,state:h.state,chatStatus:h.chatStatus,lifecycle:h.lifecycle,surfaceKind:h.surfaceKind,recoveryState:h.recoveryState,role:h.role,isSelfCoordinator:h.isSelfCoordinator,workspace:h.workspace||i.workspace}))}const m=[...p.values()];return m.length===0?i:{...i,activeSessionDetails:m,activeSessions:m.map(h=>h.sessionId)}});return n?{...e,nodes:o}:e}function pN(e,t){const n=Lm(e,t).map(a=>{var d;const o=(Array.isArray((d=e.status)==null?void 0:d.sessions)?e.status.sessions:[]).find(p=>yt(p==null?void 0:p.id)===a.sessionId),i=ii(o==null?void 0:o.activeInteractivePrompt),c=o!=null&&o.meshQueueStats&&typeof o.meshQueueStats=="object"?JSON.stringify(o.meshQueueStats):"";return[a.sessionId,a.providerType??"",a.state??"",a.chatStatus??"",a.lifecycle??"",a.surfaceKind??"",a.recoveryState??"",yt(i.status)||yt(i.kind)||yt(i.type),a.nodeId??"",a.isSelfCoordinator?"coordinator":"worker",c].join("|")}).filter(a=>!!a).sort();return n.length>0?n.join(`
83
+ `),children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2",children:[s.jsx("span",{className:`min-w-0 truncate font-mono text-[10px] select-text ${r.textPrimary}`,children:vo(S.sessionId)}),s.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-[0.12em] ${yo(S,r.isDark)}`,children:ls(S)})]}),s.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 text-[9px] ${r.textMuted}`,children:[s.jsx("span",{className:"truncate",children:S.providerType||"provider unknown"}),s.jsx("span",{children:C}),s.jsx("span",{children:qc(N)})]}),S.statusNote&&s.jsx("div",{className:`mt-1 text-[9px] leading-4 ${r.textMuted}`,children:S.statusNote})]},S.sessionId)})})]}),d&&j&&s.jsx("div",{className:`mt-3 rounded-xl border px-3 py-2 text-[10px] leading-4 ${r.isDark?"border-cyan-400/15 bg-cyan-500/8 text-cyan-50/90":"border-sky-300 bg-sky-50 text-sky-700"}`,style:Lk,children:j})]}),s.jsx(xn,{type:"source",position:a==="TB"?js.Bottom:js.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const Ok={meshNode:Fk},Hk=8;function Wk(e){if(e.length<2)return null;if(e.length===2){const[p,u]=e;return{d:`M ${p.x},${p.y} L ${u.x},${u.y}`,labelX:(p.x+u.x)/2,labelY:(p.y+u.y)/2}}const t=Hk,r=[`M ${e[0].x},${e[0].y}`];for(let p=1;p<e.length-1;p+=1){const u=e[p-1],m=e[p],h=e[p+1],y=Math.sign(m.x-u.x),x=Math.sign(m.y-u.y),f=Math.sign(h.x-m.x),j=Math.sign(h.y-m.y),k=Math.hypot(m.x-u.x,m.y-u.y),b=Math.hypot(h.x-m.x,h.y-m.y),w=Math.min(t,k/2,b/2);if(w<1||y===f&&x===j){r.push(`L ${m.x},${m.y}`);continue}const I=m.x-y*w,v=m.y-x*w,g=m.x+f*w,S=m.y+j*w;r.push(`L ${I},${v}`),r.push(`Q ${m.x},${m.y} ${g},${S}`)}const n=e[e.length-1];r.push(`L ${n.x},${n.y}`);let a=0;const o=[0];for(let p=1;p<e.length;p+=1)a+=Math.hypot(e[p].x-e[p-1].x,e[p].y-e[p-1].y),o.push(a);const i=a/2;let c=e[0].x,d=e[0].y;for(let p=1;p<e.length;p+=1)if(o[p]>=i){const u=o[p]-o[p-1],m=u===0?0:(i-o[p-1])/u;c=e[p-1].x+(e[p].x-e[p-1].x)*m,d=e[p-1].y+(e[p].y-e[p-1].y)*m;break}return{d:r.join(" "),labelX:c,labelY:d}}function Kk(e){const t=e.data.routePoints;if(t&&t.length>=2){const o=Wk(t);if(o)return[o.d,o.labelX,o.labelY]}const r={sourceX:e.sourceX,sourceY:e.sourceY,sourcePosition:e.sourcePosition,targetX:e.targetX,targetY:e.targetY,targetPosition:e.targetPosition},n=e.data.graphEdge;let a;return n.type==="parentBranch"?a=Sh(r):n.type==="worktreeLink"||n.type==="submoduleLink"||n.type==="cloneLink"?a=kh(r):a=Nh(r),[a[0],a[1],a[2]]}function Uk(e,t){const r="nodrag nopan rounded-md border px-2 py-1 text-[10px] font-semibold shadow-sm backdrop-blur-sm";switch(e.type){case"orphanLink":return t?`${r} border-orange-400/35 bg-orange-500/14 text-orange-100`:`${r} border-orange-300 bg-orange-50 text-orange-700`;case"submoduleLink":return t?`${r} border-violet-400/30 bg-violet-500/14 text-violet-100`:`${r} border-violet-300 bg-violet-50 text-violet-700`;case"sessionLink":return t?`${r} border-emerald-400/30 bg-emerald-500/14 text-emerald-100`:`${r} border-emerald-300 bg-emerald-50 text-emerald-700`;case"cloneLink":return t?`${r} border-teal-400/30 bg-teal-500/14 text-teal-100`:`${r} border-teal-300 bg-teal-50 text-teal-700`;default:return t?`${r} border-sky-400/25 bg-slate-950/78 text-sky-100`:`${r} border-sky-300 bg-white/95 text-sky-700`}}function zk(e){const t=l.useContext(sl),r=e.data.graphEdge,[n,a,o]=Kk(e),i=typeof e.label=="string"?e.label:void 0;return s.jsxs(s.Fragment,{children:[s.jsx(gh,{id:e.id,path:n,markerEnd:e.markerEnd,style:e.style,interactionWidth:24}),e.label&&s.jsx(yh,{children:s.jsx("div",{className:Uk(r,t.isDark),title:i,style:{position:"absolute",transform:`translate(-50%, -50%) translate(${a}px, ${o}px)`,pointerEvents:"none",maxWidth:Uj.maxWidth},children:s.jsx("span",{className:"block truncate",children:e.label})})})]})}const Gk={meshEdge:zk};async function Vk(e,t,r,n,a){const o=await lm(e,r,n,a);return jm(e,o,t,r)}async function qk(e,t=Ls("dark"),r=!1,n="LR"){const a=await lm(e,r,n);return jm(e,a,t,r)}function jm(e,t,r,n=!1){const a=new Set(t.nodes.map(p=>p.id)),o=t.nodes.map(p=>({id:p.id,type:p.type,position:p.position,data:{graphNode:p.graphNode,compact:n},selected:p.selected,draggable:p.draggable,selectable:p.selectable})),i=e.edges.filter(p=>a.has(p.source)&&a.has(p.target)),c=Xk(i),d=i.map(p=>{var u;return{id:p.id,source:p.source,target:p.target,label:c.has(p.id)?p.label:void 0,type:"meshEdge",data:{graphEdge:p,routePoints:(u=t.edgeRoutes.get(p.id))==null?void 0:u.points},animated:p.type==="orphanLink",markerEnd:p.direction==="directed"?{type:jh.ArrowClosed,width:p.type==="submoduleLink"?16:18,height:p.type==="submoduleLink"?16:18,color:Xc(p)}:void 0,style:{stroke:Xc(p),strokeWidth:p.type==="orphanLink"?2.25:p.type==="submoduleLink"?1.7:p.type==="worktreeLink"?1.8:p.type==="cloneLink"?1.6:2,strokeDasharray:p.type==="orphanLink"?"5 4":p.type==="submoduleLink"?"4 3":p.type==="cloneLink"?"6 3":void 0},labelStyle:{fill:r.edgeLabelTextColor,fontSize:10,fontWeight:600},labelBgStyle:{fill:r.edgeLabelBackgroundColor,fillOpacity:1,stroke:r.edgeLabelBorderColor},labelBgPadding:[6,4],labelBgBorderRadius:7}});return{nodes:o,edges:d}}const Yk=3,Jk=2;function Jc(e){switch(e.type){case"orphanLink":return 5;case"parentBranch":return 4;case"submoduleLink":return 3;case"cloneLink":return 2;case"worktreeLink":return 1;case"sessionLink":return 0;default:return 0}}function Xk(e){const t=new Set,r=new Map;for(const n of e){if(!n.label)continue;const a=r.get(n.source);a?a.push(n):r.set(n.source,[n])}for(const n of r.values()){if(n.length<Yk){for(const o of n)t.add(o.id);continue}const a=[...n].sort((o,i)=>{const c=Jc(i)-Jc(o);return c!==0?c:o.id.localeCompare(i.id)});for(const o of a.slice(0,Jk))t.add(o.id)}return t}function Xc(e){switch(e.type){case"parentBranch":return"#38bdf8";case"worktreeLink":return"#a78bfa";case"sessionLink":return"#34d399";case"orphanLink":return"#f97316";case"submoduleLink":return"#c084fc";case"cloneLink":return"#2dd4bf";default:return"#64748b"}}function Qk(e){const t=e.data.graphNode;if(t.locality==="local")return"#38bdf8";switch(t.health){case"online":return"#34d399";case"dirty":return"#fbbf24";case"degraded":case"offline":return"#fb7185";case"wrong_branch":return"#a78bfa";default:return"#94a3b8"}}function Zk(e){const t=e.data.graphNode;return["mesh-minimap-node",`mesh-minimap-node--${t.type}`,`mesh-minimap-node--${t.health}`,t.isOrphan?"mesh-minimap-node--attention":null,t.dirty?"mesh-minimap-node--dirty":null,t.outOfSync?"mesh-minimap-node--out-of-sync":null].filter(Boolean).join(" ")}function e1({data:e,viewportKey:t}){const r=vh(),n=wh(),a=l.useRef(null),o=l.useMemo(()=>am(e),[e]),i=l.useMemo(()=>Bj(e),[e]);return l.useEffect(()=>{if(!r||e.nodes.length===0||a.current===t)return;let c=!1;const d=requestAnimationFrame(()=>{if(c)return;const p=i.length>0&&i.length<e.nodes.length;n.fitView({nodes:p?i.map(u=>({id:u})):void 0,padding:p?.24:.2,maxZoom:p?.98:.9,duration:260}),a.current=t});return()=>{c=!0,cancelAnimationFrame(d)}},[e.nodes.length,i,o,r,n,t]),null}const t1=12;function s1(e){return e>=16?"min-h-[720px]":e>=10?"min-h-[580px]":"min-h-[460px]"}function r1({data:e,selectedNodeId:t=null,directionPref:r,onNodeClick:n,onEdgeClick:a,onNodeHoverChange:o,onEdgeHoverChange:i}){const{theme:c}=Ts(),d=l.useMemo(()=>Ls(c),[c]),p=l.useMemo(()=>nk(e),[e]),u=l.useMemo(()=>ak(e),[e]),m=l.useRef(null),[h,y]=l.useState({width:0,height:0}),x=h.width>0&&h.width<_k,f=e.nodes.length>=Mk||x,[j]=l.useState("LR"),k=r??j,b=l.useMemo(()=>r==="LR"||r==="TB"?r:x?"TB":k==="auto"?Vj(e):k,[k,r,p,e,x]),w=e.nodes.length>=t1,[I,v]=l.useState({nodes:[],edges:[]}),g=l.useMemo(()=>`${Fj(e,h.width,h.height)}::${b}`,[p,e,h.height,h.width,b]);l.useEffect(()=>{let N=!1;return qk(e,d,f,b).then(C=>{if(N)return;v(C);const R=requestAnimationFrame(()=>{if(N)return;const T=m.current;if(!T)return;const _=new Map;for(const P of C.nodes){const B=T.querySelector(`.react-flow__node[data-id="${CSS.escape(P.id)}"]`);B&&B.offsetHeight>0&&_.set(P.id,B.offsetHeight)}_.size!==0&&Vk(e,d,f,b,_).then(P=>{N||v(P)})});return()=>cancelAnimationFrame(R)}),()=>{N=!0}},[e,u,d,f,b]);const S=l.useMemo(()=>I.nodes.map(N=>({...N,selected:N.id===t})),[I.nodes,t]);return l.useEffect(()=>{const N=m.current;if(!N)return;const C=()=>{const T=Math.max(0,Math.round(N.clientWidth)),_=Math.max(0,Math.round(N.clientHeight));y(P=>P.width===T&&P.height===_?P:{width:T,height:_})};C();const R=typeof ResizeObserver=="function"?new ResizeObserver(()=>C()):null;return R==null||R.observe(N),window.addEventListener("resize",C),()=>{R==null||R.disconnect(),window.removeEventListener("resize",C)}},[]),s.jsx(sl.Provider,{value:d,children:s.jsx(gm.Provider,{value:f,children:s.jsx(ym.Provider,{value:b,children:s.jsxs("div",{ref:m,className:`${d.graphShellClass} ${s1(e.nodes.length)}`,style:{height:"100%"},children:[s.jsx("div",{className:`pointer-events-none absolute left-1/2 top-2 z-10 -translate-x-1/2 px-3 py-1 text-[10px] ${d.graphStatChipClass}`,children:"drag or scroll to pan"}),s.jsx("div",{className:"w-full min-w-0 flex-1",style:{height:"100%"},children:s.jsxs(mh,{nodes:S,edges:I.edges,nodeTypes:Ok,edgeTypes:Gk,minZoom:x?.3:.18,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!0,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(N,C)=>n==null?void 0:n(C.data.graphNode),onEdgeClick:(N,C)=>{var T;const R=(T=C.data)==null?void 0:T.graphEdge;R&&(a==null||a(R))},onNodeMouseEnter:(N,C)=>o==null?void 0:o(C.data.graphNode),onNodeMouseLeave:()=>o==null?void 0:o(null),onEdgeMouseEnter:(N,C)=>{var R;return i==null?void 0:i(((R=C.data)==null?void 0:R.graphEdge)??null)},onEdgeMouseLeave:()=>i==null?void 0:i(null),className:"h-full w-full",colorMode:d.flowColorMode,proOptions:{hideAttribution:!0},children:[s.jsx(e1,{data:e,viewportKey:g}),s.jsx(hh,{className:d.graphControlsClass,position:"bottom-left",showZoom:!0,showFitView:!0,showInteractive:!1}),w&&s.jsx(fh,{position:"bottom-right",pannable:!0,zoomable:!0,nodeColor:Qk,nodeClassName:Zk,nodeStrokeWidth:3,className:d.isDark?"overflow-hidden rounded-xl border border-white/10 bg-slate-950/85":"overflow-hidden rounded-xl border border-slate-200 bg-white/95"}),s.jsx(xh,{variant:bh.Dots,gap:18,size:1.2,color:d.graphBackgroundDotColor})]})})]})})})})}const n1="You are one independent member of a multi-agent cross-verification quorum";function a1(e){var n,a;const t=(e??"").trim();if(!t)return"";if(!t.startsWith(n1))return t;const r=(a=(n=t.match(/\n## Question\n([\s\S]*?)(?:\n## |$)/))==null?void 0:n[1])==null?void 0:a.trim().replace(/\s+/g," ");return r?`MAGI cross-verify — ${r}`:"MAGI cross-verification task"}function o1(e){return`${e.state??""} ${e.chatStatus??""} ${e.lifecycle??""}`.toLowerCase()}function i1(e){if(!Array.isArray(e))return[];const t=[];for(const r of e){const n=r.activeSessionDetails;if(Array.isArray(n))for(const a of n)a!=null&&a.sessionId&&o1(a).includes("approval")&&t.push({nodeId:r.nodeId,sessionId:a.sessionId,providerType:a.providerType,machineLabel:r.machineLabel||r.nodeId,detail:a.statusNote??a.title??null})}return t}function l1({approvals:e,nodes:t,onResolve:r,hideWhenEmpty:n=!0}){const a=l.useMemo(()=>e??i1(t),[e,t]),[o,i]=l.useState({});if(n&&a.length===0)return null;const c=(d,p)=>{o[d.sessionId]||(i(u=>({...u,[d.sessionId]:p})),Promise.resolve(r(d.nodeId,d.sessionId,p)).finally(()=>{i(u=>{const m={...u};return delete m[d.sessionId],m})}))};return s.jsxs("div",{className:"rounded-lg border p-3",style:{borderColor:"color-mix(in srgb, var(--status-warning) 40%, transparent)",background:"color-mix(in srgb, var(--status-warning) 8%, transparent)"},children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2 font-black text-xs",style:{color:"var(--status-warning)"},children:[s.jsx(Vs,{size:14}),"PENDING APPROVALS",s.jsxs("span",{className:"opacity-70 font-semibold",children:["(",a.length,")"]})]}),a.length===0?s.jsx("div",{className:"text-[11px] opacity-70",children:"No sessions are awaiting an approval decision."}):s.jsx("ul",{className:"flex flex-col gap-2",children:a.map(d=>{const p=o[d.sessionId]??null,u=p!==null;return s.jsxs("li",{className:"flex items-center justify-between gap-3 rounded-md px-2.5 py-2",style:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)"},children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"text-xs font-semibold truncate",children:[d.machineLabel||d.nodeId,d.providerType&&s.jsx("span",{className:"ml-2 opacity-60 font-normal",children:d.providerType})]}),s.jsx("div",{className:"text-[10px] opacity-60 truncate",children:d.detail?d.detail.replace(/[\n\r]+/g," ").slice(0,120):`session ${d.sessionId}`})]}),s.jsxs("div",{className:"flex gap-2 shrink-0",children:[s.jsx("button",{onClick:()=>c(d,"approve"),disabled:u,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 font-extrabold ${u?"cursor-not-allowed opacity-60":"cursor-pointer"}`,style:{color:"var(--status-warning)",background:"var(--surface-primary)"},children:p==="approve"?"⏳ ...":"Approve"}),s.jsx("button",{onClick:()=>c(d,"reject"),disabled:u,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 font-semibold text-white bg-red-500/30 ${u?"cursor-not-allowed opacity-60":"cursor-pointer"}`,children:p==="reject"?"⏳ ...":"Reject"})]})]},`${d.nodeId}:${d.sessionId}`)})})]})}const c1=5,d1=40,u1={meshId:"",totalEntries:0,taskDispatched:0,taskCompleted:0,taskFailed:0,taskStalled:0,sessionLaunched:0,checkpointCreated:0,lastActivityAt:null,recentFailures:0};function Ta(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function km(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const r=t.toLowerCase().replace(/[\s-]+/g,"_");return r.includes("approval")?"awaiting approval":r.includes("generating")||r.includes("running")||r.includes("busy")?"generating":r.includes("idle")||r.includes("ready")||r.includes("waiting_input")?"idle":r.replace(/_/g," ")}function Nm(e){return e.includes("approval")?"amber":e.includes("generating")?"sky":e.includes("idle")?"emerald":e.includes("failed")||e.includes("stopped")||e.includes("interrupted")?"rose":"muted"}function p1(e){const t=e.git;if(!t)return e.gitProbePending?"git probe pending":"no git probe";const r=(t.staged??0)+(t.modified??0)+(t.untracked??0)+(t.deleted??0)+(t.renamed??0),n=[];return t.upstreamStatus==="fresh"&&((t.ahead??0)>0||(t.behind??0)>0)&&n.push(`↑${t.ahead??0}/↓${t.behind??0}`),r>0&&n.push(`✎${r}`),t.hasConflicts&&n.push("conflicts"),n.join(" · ")||"clean"}function Sm(e){switch(e){case"active":return"emerald";case"paused":return"amber";case"completed":return"sky";case"abandoned":return"rose";default:return"muted"}}function m1(e){switch(e){case"online":return"emerald";case"dirty":return"amber";case"degraded":case"offline":return"rose";case"wrong_branch":return"sky";default:return"muted"}}function Cm(e){switch(e){case"completed":return"emerald";case"failed":return"rose";case"cancelled":return"muted";case"assigned":return"sky";case"pending":return"amber";default:return"muted"}}function Qc(e){switch(e){case"assigned":return 0;case"pending":return 1;case"completed":case"failed":case"cancelled":return 2;default:return 3}}function as(e){if(!e)return null;const t=Date.parse(e);if(!Number.isFinite(t))return null;const r=Math.max(0,Math.floor((Date.now()-t)/1e3));if(r<60)return`${r}s ago`;const n=Math.floor(r/60);if(n<60)return`${n}m ago`;const a=Math.floor(n/60);return a<48?`${a}h ago`:`${Math.floor(a/24)}d ago`}function Zc(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return null;if(e<1e3)return`${Math.round(e)}ms`;const t=Math.round(e/1e3),r=t%60,n=Math.floor(t/60),a=n%60,o=Math.floor(n/60),i=[];return o>0&&i.push(`${o}h`),a>0&&i.push(`${a}m`),(r>0||i.length===0)&&i.push(`${r}s`),i.join(" ")}function rl(e){return e.replace(/[_-]+/g," ")}function Im(e){const t=e.toLowerCase();return t.includes("fail")||t.includes("stall")||t.includes("error")?"rose":t.includes("complete")?"emerald":t.includes("dispatch")||t.includes("launch")||t.includes("assign")?"sky":t.includes("checkpoint")?"amber":"muted"}function Am(e){if(!e)return null;const t=e.message??e.summary??e.reason??e.title;return typeof t=="string"&&t.trim()?t.trim():null}function h1({status:e,daemonId:t=null,meshId:r=null,sendDaemonCommand:n=null}){var I,v,g,S;const{theme:a}=Ts(),o=l.useMemo(()=>Ls(a),[a]),i=((I=e.queue)==null?void 0:I.summary)??null,c=((v=e.queue)==null?void 0:v.tasks)??[],d=((g=e.ledger)==null?void 0:g.summary)??u1,p=((S=e.ledger)==null?void 0:S.entries)??[],u=e.missions??[],m=u.filter(N=>N.status==="active"||N.status==="paused"),h=u.filter(N=>N.status==="completed"||N.status==="abandoned"),y=e.asyncRefineJobs??[],[x,f]=l.useState(null),j=l.useCallback(()=>f(null),[]),k=l.useCallback(async(N,C,R)=>{!t||!n||await n(t,"mesh_approve",{meshId:r??void 0,node_id:N,session_id:C,action:R})},[t,r,n]),b=l.useCallback(N=>{if(!N)return"";const C=e.nodes.find(R=>R.nodeId===N);return(C==null?void 0:C.machineLabel)||N},[e.nodes]),w=l.useMemo(()=>{const N=[];for(const C of e.nodes){const R=C.activeSessionDetails&&C.activeSessionDetails.length>0?C.activeSessionDetails:(C.activeSessions??[]).map(T=>({sessionId:T,workspace:C.workspace,isCached:!0}));for(const T of R)N.push({node:C,session:T})}return N},[e.nodes]);return s.jsxs("div",{className:"flex flex-col gap-3 pb-2",children:[s.jsx(l1,{nodes:e.nodes,onResolve:k}),s.jsx(k1,{meshTheme:o,liveMissions:m,historyMissions:h,hasMissionField:Array.isArray(e.missions),onSelect:N=>f({kind:"mission",mission:N})}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsx(N1,{meshTheme:o,ledgerSummary:d,entries:p,resolveNodeLabel:b,onSelect:N=>f({kind:"ledger",entry:N})}),s.jsx(S1,{meshTheme:o,queueSummary:i,tasks:c,onSelect:N=>f({kind:"queue",task:N})})]}),s.jsx(I1,{meshTheme:o,nodes:e.nodes}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsx(A1,{meshTheme:o,entries:w,onSelect:(N,C)=>f({kind:"session",node:N,session:C})}),s.jsx(M1,{meshTheme:o,jobs:y})]}),x&&s.jsx(x1,{meshTheme:o,detail:x,onClose:j,daemonId:t,meshId:r??e.meshId??null,sendDaemonCommand:n,resolveNodeLabel:b})]})}function Ys({meshTheme:e,title:t,count:r,children:n,action:a}){const o=e.isDark;return s.jsxs("div",{className:`flex min-w-0 flex-col overflow-hidden rounded-2xl border p-4 ${o?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-white/80"}`,children:[s.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[s.jsx("span",{className:`text-[11px] font-semibold uppercase tracking-[0.14em] ${e.textSecondary}`,children:t}),r!==void 0&&s.jsx("span",{className:`tabular-nums text-[11px] ${e.textMuted}`,children:r}),a&&s.jsx("span",{className:"ml-auto",children:a})]}),n]})}function Ot({meshTheme:e,label:t,tone:r}){const n=e.isDark,a=r==="rose"?n?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700":r==="sky"?n?"border-sky-400/25 bg-sky-500/10 text-sky-200":"border-sky-300 bg-sky-50 text-sky-700":r==="amber"?n?"border-amber-400/25 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700":r==="emerald"?n?"border-emerald-400/25 bg-emerald-500/10 text-emerald-200":"border-emerald-300 bg-emerald-50 text-emerald-700":n?"border-white/10 bg-white/[0.04] text-slate-300":"border-slate-200 bg-slate-50 text-slate-600";return s.jsx("span",{className:`shrink-0 rounded-full border px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] ${a}`,children:t})}function gt({meshTheme:e,label:t,value:r,tone:n}){const a=e.isDark,o=n==="rose"?a?"text-rose-300":"text-rose-600":n==="sky"?a?"text-sky-300":"text-sky-600":n==="amber"?a?"text-amber-300":"text-amber-600":n==="emerald"?a?"text-emerald-300":"text-emerald-600":n==="muted"?e.textMuted:e.textPrimary;return s.jsxs("div",{className:`flex flex-col items-center rounded-lg border px-2 py-2 ${a?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-white/70"}`,children:[s.jsx("span",{className:`tabular-nums text-base font-semibold leading-none ${o}`,children:r}),s.jsx("span",{className:`mt-1 text-[9px] uppercase tracking-wide ${e.textMuted}`,children:t})]})}function fn({meshTheme:e,children:t}){return s.jsx("div",{className:`text-xs ${e.textMuted}`,children:t})}function La({meshTheme:e,onClick:t,children:r}){const n=e.isDark,a=t?n?"hover:bg-white/[0.05]":"hover:bg-slate-100/70":"";return s.jsx("button",{type:"button",onClick:t,disabled:!t,className:`flex w-full min-w-0 items-center gap-2 overflow-hidden rounded-md px-1.5 py-1 text-left text-xs transition ${a} ${t?"cursor-pointer":"cursor-default"}`,children:r})}function Ra({meshTheme:e,expanded:t,hiddenCount:r,onToggle:n}){return r<=0?null:s.jsx("button",{type:"button",onClick:n,className:`mt-1 self-start rounded-md px-1.5 py-0.5 text-[11px] font-medium ${e.textSecondary} hover:underline`,children:t?"Show fewer":`+${r} more`})}function Pa(e,t=c1){const[r,n]=l.useState(!1),a=r?e:e.slice(0,t),o=Math.max(0,e.length-t),i=l.useCallback(()=>n(c=>!c),[]);return{visible:a,hiddenCount:o,expanded:r,toggle:i}}function ht({meshTheme:e,label:t,value:r}){return s.jsxs("div",{className:e.rowClass,children:[s.jsx("span",{className:e.rowLabelClass,children:t}),s.jsx("span",{className:e.rowValueClass,children:r})]})}function f1(e){switch(e.kind){case"mission":return{kicker:"Mission",title:e.mission.title};case"ledger":return{kicker:"Ledger entry",title:rl(e.entry.kind)};case"queue":return{kicker:"Queue task",title:e.task.id};case"session":return{kicker:"Session",title:Ta(e.session.sessionId)}}}function x1({meshTheme:e,detail:t,onClose:r,daemonId:n,meshId:a,sendDaemonCommand:o,resolveNodeLabel:i}){l.useEffect(()=>{const h=y=>{y.key==="Escape"&&r()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[r]);const c=e.isDark,{kicker:d,title:p}=f1(t),u=c?"bg-[#030617]/[0.92]":"bg-[rgba(15,23,42,0.82)]",m=c?"border-white/10 bg-slate-950 md:bg-slate-950/98 shadow-[0_28px_120px_rgba(2,6,23,0.5)]":"border-slate-200 bg-white md:bg-white/98 shadow-[0_28px_120px_rgba(148,163,184,0.3)]";return s.jsx("div",{className:`fixed inset-0 z-[var(--z-modal)] flex items-stretch justify-center p-0 md:items-center md:p-4 ${u}`,role:"dialog","aria-modal":"true",onClick:r,children:s.jsxs("div",{className:`flex h-[100dvh] max-h-[100dvh] w-full flex-col overflow-hidden border ${m} md:h-auto md:max-h-[88dvh] md:max-w-[min(640px,calc(100vw-32px))] md:rounded-2xl`,onClick:h=>h.stopPropagation(),children:[s.jsxs("div",{className:`sticky top-0 z-10 flex shrink-0 items-start justify-between gap-3 border-b px-4 py-3 ${c?"border-white/8":"border-slate-200"}`,children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`text-[10px] font-semibold uppercase tracking-[0.16em] ${e.textMuted}`,children:d}),s.jsx("div",{className:`mt-0.5 break-all text-sm font-semibold ${e.textPrimary}`,children:p})]}),s.jsx("button",{type:"button",onClick:r,"aria-label":"Close detail",className:c?"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-xl border border-white/10 bg-white/[0.04] text-slate-300 transition hover:bg-white/[0.08] hover:text-white":"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-xl border border-slate-200 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",children:"✕"})]}),s.jsxs("div",{className:"min-h-0 min-w-0 flex-1 overflow-y-auto px-4 py-4",children:[t.kind==="mission"&&s.jsx(y1,{meshTheme:e,mission:t.mission,daemonId:n,meshId:a,sendDaemonCommand:o}),t.kind==="ledger"&&s.jsx(v1,{meshTheme:e,entry:t.entry,resolveNodeLabel:i}),t.kind==="queue"&&s.jsx(w1,{meshTheme:e,task:t.task}),t.kind==="session"&&s.jsx(j1,{meshTheme:e,node:t.node,session:t.session})]})]})})}const b1=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function g1(e){const t=b1(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function y1({meshTheme:e,mission:t,daemonId:r,meshId:n,sendDaemonCommand:a}){var I;const o=t.tasks,i="goal"in t&&typeof t.goal=="string"&&t.goal?t.goal:"goalPreview"in t?t.goalPreview:"",c="goalTruncated"in t?t.goalTruncated===!0:!1,[d,p]=l.useState(null),[u,m]=l.useState(!1),[h,y]=l.useState(null),x=c&&!d&&!!r&&!!a,f=l.useCallback(async()=>{if(!(!r||!a)){m(!0),y(null);try{const v=await a(r,"mesh_status",{meshId:n??void 0,verbose:!0}),g=g1(v),N=(Array.isArray(g==null?void 0:g.missions)?g.missions:[]).find(R=>(R==null?void 0:R.id)===t.id),C=typeof(N==null?void 0:N.goal)=="string"&&N.goal?N.goal:null;C?p(C):y("Full goal unavailable")}catch(v){y(v instanceof Error?v.message:"Failed to fetch full mission goal")}finally{m(!1)}}},[r,n,a,t.id]),j=d??i,k=c&&!d,b=t.stats??null,w=((I=b==null?void 0:b.incompleteTaskIds)==null?void 0:I.length)??0;return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx(Ot,{meshTheme:e,label:t.status,tone:Sm(t.status)}),s.jsx(Ot,{meshTheme:e,label:`${o.total} tasks`,tone:"muted"})]}),j&&s.jsxs("div",{className:`max-h-64 overflow-y-auto whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:[j,k&&!x&&s.jsx("span",{className:e.textMuted,children:" … (truncated)"})]}),h&&s.jsx("div",{className:"text-[11px] text-amber-400",children:h}),x&&s.jsx("button",{type:"button",className:"self-start text-[12px] text-accent-primary hover:underline disabled:opacity-50",onClick:f,disabled:u,children:u?"Loading…":"Show full goal"}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5 sm:grid-cols-6",children:[s.jsx(gt,{meshTheme:e,label:"Completed",value:o.completed,tone:"emerald"}),s.jsx(gt,{meshTheme:e,label:"Assigned",value:o.assigned,tone:o.assigned>0?"sky":void 0}),s.jsx(gt,{meshTheme:e,label:"Pending",value:o.pending}),s.jsx(gt,{meshTheme:e,label:"Failed",value:o.failed,tone:o.failed>0?"rose":void 0}),s.jsx(gt,{meshTheme:e,label:"Blocked",value:o.blocked,tone:o.blocked>0?"amber":void 0}),s.jsx(gt,{meshTheme:e,label:"Cancelled",value:o.cancelled,tone:"muted"})]}),b&&s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(gt,{meshTheme:e,label:"Wall clock",value:Zc(b.wallClockMs)??"—"}),s.jsx(gt,{meshTheme:e,label:"Total runtime",value:Zc(b.totalDurationMs)??"—"}),s.jsx(gt,{meshTheme:e,label:"Retries",value:b.retries,tone:b.retries>0?"amber":void 0})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(ht,{meshTheme:e,label:"Mission id",value:t.id}),s.jsx(ht,{meshTheme:e,label:"Created",value:as(t.createdAt)??t.createdAt}),s.jsx(ht,{meshTheme:e,label:"Updated",value:as(t.updatedAt)??t.updatedAt}),o.lastActivityAt&&s.jsx(ht,{meshTheme:e,label:"Last task activity",value:as(o.lastActivityAt)??o.lastActivityAt}),w>0&&b&&s.jsx(ht,{meshTheme:e,label:"Incomplete evidence",value:s.jsxs("details",{children:[s.jsxs("summary",{className:"cursor-pointer select-none",children:[w," task",w===1?"":"s"]}),s.jsx("div",{className:"mt-1 flex flex-col gap-0.5 break-all",children:b.incompleteTaskIds.map(v=>s.jsx("span",{className:`font-mono text-[10px] ${e.textMuted}`,children:v},v))})]})})]})]})}function v1({meshTheme:e,entry:t,resolveNodeLabel:r}){const n=Am(t.payload);let a="";try{a=JSON.stringify(t.payload??{},null,2)}catch{a=String(t.payload)}return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:s.jsx(Ot,{meshTheme:e,label:rl(t.kind),tone:Im(t.kind)})}),n&&s.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:n}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(ht,{meshTheme:e,label:"Entry id",value:t.id}),s.jsx(ht,{meshTheme:e,label:"When",value:as(t.timestamp)??t.timestamp}),t.nodeId&&s.jsx(ht,{meshTheme:e,label:"Node",value:r(t.nodeId)}),t.sessionId&&s.jsx(ht,{meshTheme:e,label:"Session",value:Ta(t.sessionId)}),t.providerType&&s.jsx(ht,{meshTheme:e,label:"Provider",value:t.providerType})]}),a&&a!=="{}"&&s.jsxs("div",{children:[s.jsx("div",{className:`mb-1 text-[10px] uppercase tracking-wide ${e.textMuted}`,children:"Payload"}),s.jsx("pre",{className:`max-h-60 max-w-full overflow-auto rounded-lg border p-2 text-[10px] leading-4 ${e.isDark?"border-white/8 bg-black/30 text-slate-300":"border-slate-200 bg-slate-50 text-slate-700"}`,children:a})]})]})}function w1({meshTheme:e,task:t}){return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx(Ot,{meshTheme:e,label:t.status,tone:Cm(t.status)}),(t.requeueCount??0)>0&&s.jsx(Ot,{meshTheme:e,label:`requeued ${t.requeueCount}`,tone:"amber"})]}),t.message&&s.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:t.message}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(ht,{meshTheme:e,label:"Task id",value:t.id}),s.jsx(ht,{meshTheme:e,label:"Created",value:as(t.createdAt)??t.createdAt}),s.jsx(ht,{meshTheme:e,label:"Updated",value:as(t.updatedAt)??t.updatedAt}),(t.assignedNodeId||t.targetNodeId)&&s.jsx(ht,{meshTheme:e,label:"Node",value:t.assignedNodeId||t.targetNodeId}),(t.assignedSessionId||t.targetSessionId)&&s.jsx(ht,{meshTheme:e,label:"Session",value:Ta(t.assignedSessionId||t.targetSessionId)}),t.cancelReason&&s.jsx(ht,{meshTheme:e,label:"Cancel reason",value:t.cancelReason}),t.requeueReason&&s.jsx(ht,{meshTheme:e,label:"Requeue reason",value:t.requeueReason}),t.autoLaunch&&s.jsx(ht,{meshTheme:e,label:"Auto launch",value:`${t.autoLaunch.status}${t.autoLaunch.reason?` · ${t.autoLaunch.reason}`:""}`})]})]})}function j1({meshTheme:e,node:t,session:r}){var a,o;const n=km(r);return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx(Ot,{meshTheme:e,label:n,tone:Nm(n)}),s.jsx(Ot,{meshTheme:e,label:r.providerType||"provider unknown",tone:"muted"})]}),r.statusNote&&s.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:r.statusNote}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(ht,{meshTheme:e,label:"Session id",value:r.sessionId}),s.jsx(ht,{meshTheme:e,label:"Node",value:t.machineLabel}),s.jsx(ht,{meshTheme:e,label:"Workspace",value:r.workspace||t.workspace}),(((a=t.git)==null?void 0:a.branch)??t.worktreeBranch)&&s.jsx(ht,{meshTheme:e,label:"Branch",value:((o=t.git)==null?void 0:o.branch)??t.worktreeBranch}),typeof r.role=="string"&&r.role&&s.jsx(ht,{meshTheme:e,label:"Role",value:r.role}),(r.startedAt||r.createdAt)&&s.jsx(ht,{meshTheme:e,label:"Started",value:as(r.startedAt||r.createdAt)??(r.startedAt||r.createdAt)})]})]})}function ed({meshTheme:e,mission:t,onSelect:r}){const n=t.tasks,a=as(n.lastActivityAt);return s.jsxs(La,{meshTheme:e,onClick:r,children:[s.jsx(Ot,{meshTheme:e,label:t.status,tone:Sm(t.status)}),s.jsx("span",{className:`min-w-0 flex-1 truncate font-medium ${e.textPrimary}`,children:t.title}),s.jsxs("span",{className:`shrink-0 tabular-nums text-[11px] ${e.textMuted}`,children:["✓",n.completed,"/",n.total]}),a&&s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:a})]})}function k1({meshTheme:e,liveMissions:t,historyMissions:r,hasMissionField:n,onSelect:a}){const[o,i]=l.useState(!1),c=e.isDark,d=Pa(t);return s.jsxs(Ys,{meshTheme:e,title:"Missions",count:t.length||void 0,children:[t.length>0?s.jsxs("div",{className:"flex flex-col gap-0.5",children:[d.visible.map(p=>s.jsx(ed,{meshTheme:e,mission:p,onSelect:()=>a(p)},p.id)),s.jsx(Ra,{meshTheme:e,expanded:d.expanded,hiddenCount:d.hiddenCount,onToggle:d.toggle})]}):s.jsx(fn,{meshTheme:e,children:n?"No active missions. The coordinator creates a mission for multi-task work.":"Mission data unavailable from this daemon — update the daemon to see missions."}),r.length>0&&s.jsxs("div",{className:`mt-3 border-t pt-2 ${c?"border-white/8":"border-slate-200"}`,children:[s.jsxs("button",{type:"button",onClick:()=>i(p=>!p),className:`flex w-full items-center gap-1.5 text-[11px] font-medium ${e.textSecondary}`,children:[s.jsx("span",{className:`inline-block transition-transform ${o?"rotate-90":""}`,children:"▸"}),s.jsx("span",{children:"Completed / abandoned history"}),s.jsx("span",{className:`tabular-nums ${e.textMuted}`,children:r.length})]}),o&&s.jsx("div",{className:"mt-2 flex flex-col gap-0.5",children:r.map(p=>s.jsx(ed,{meshTheme:e,mission:p,onSelect:()=>a(p)},p.id))})]})]})}function N1({meshTheme:e,ledgerSummary:t,entries:r,resolveNodeLabel:n,onSelect:a}){const o=as(t.lastActivityAt),i=l.useMemo(()=>[...r].reverse(),[r]),c=Pa(i);return s.jsxs(Ys,{meshTheme:e,title:"Ledger",children:[s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(gt,{meshTheme:e,label:"Dispatched",value:t.taskDispatched}),s.jsx(gt,{meshTheme:e,label:"Completed",value:t.taskCompleted,tone:"emerald"}),s.jsx(gt,{meshTheme:e,label:"Failed",value:t.taskFailed,tone:t.taskFailed>0?"rose":void 0}),s.jsx(gt,{meshTheme:e,label:"Stalled",value:t.taskStalled,tone:t.taskStalled>0?"amber":void 0}),s.jsx(gt,{meshTheme:e,label:"Sessions",value:t.sessionLaunched}),s.jsx(gt,{meshTheme:e,label:"Checkpoints",value:t.checkpointCreated})]}),i.length>0&&s.jsxs("div",{className:`mt-3 border-t pt-2 ${e.isDark?"border-white/8":"border-slate-200"}`,children:[s.jsx("div",{className:`mb-1 text-[10px] uppercase tracking-wide ${e.textMuted}`,children:"Recent activity"}),s.jsxs("div",{className:"flex flex-col gap-0.5",children:[c.visible.map(d=>{const p=Am(d.payload);return s.jsxs(La,{meshTheme:e,onClick:()=>a(d),children:[s.jsx(Ot,{meshTheme:e,label:rl(d.kind),tone:Im(d.kind)}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${e.textSecondary}`,title:d.nodeId||void 0,children:p||n(d.nodeId)||d.sessionId||"—"}),s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:as(d.timestamp)??""})]},d.id)}),s.jsx(Ra,{meshTheme:e,expanded:c.expanded,hiddenCount:c.hiddenCount,onToggle:c.toggle})]})]}),(t.recentFailures>0||o&&i.length===0)&&s.jsxs("div",{className:`mt-2 flex items-center justify-between text-[11px] ${e.textMuted}`,children:[t.recentFailures>0?s.jsxs("span",{className:e.isDark?"text-amber-300":"text-amber-600",children:[t.recentFailures," recent failures"]}):s.jsx("span",{}),o&&i.length===0&&s.jsx("span",{children:o})]})]})}function S1({meshTheme:e,queueSummary:t,tasks:r,onSelect:n}){const a=l.useMemo(()=>[...r].sort((i,c)=>{const d=Qc(i.status)-Qc(c.status);return d!==0?d:(c.updatedAt||"").localeCompare(i.updatedAt||"")}).slice(0,d1),[r]),o=Pa(a);return t?s.jsxs(Ys,{meshTheme:e,title:"Queue",count:t.active>0?`${t.active} active`:void 0,children:[s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(gt,{meshTheme:e,label:"Pending",value:t.pending}),s.jsx(gt,{meshTheme:e,label:"Assigned",value:t.assigned,tone:t.assigned>0?"sky":void 0}),s.jsx(gt,{meshTheme:e,label:"Active",value:t.active,tone:t.active>0?"sky":void 0}),s.jsx(gt,{meshTheme:e,label:"Completed",value:t.completed,tone:"emerald"}),s.jsx(gt,{meshTheme:e,label:"Failed",value:t.failed,tone:t.failed>0?"rose":void 0}),s.jsx(gt,{meshTheme:e,label:"Cancelled",value:t.cancelled,tone:"muted"})]}),a.length>0&&s.jsxs("div",{className:`mt-3 border-t pt-2 ${e.isDark?"border-white/8":"border-slate-200"}`,children:[s.jsx("div",{className:`mb-1 text-[10px] uppercase tracking-wide ${e.textMuted}`,children:"Recent tasks"}),s.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.visible.map(i=>s.jsxs(La,{meshTheme:e,onClick:()=>n(i),children:[s.jsx(Ot,{meshTheme:e,label:i.status,tone:Cm(i.status)}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${e.textSecondary}`,title:i.message||void 0,children:a1(i.message)||i.id}),s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:as(i.updatedAt)??""})]},i.id)),s.jsx(Ra,{meshTheme:e,expanded:o.expanded,hiddenCount:o.hiddenCount,onToggle:o.toggle})]})]})]}):s.jsx(Ys,{meshTheme:e,title:"Queue",children:s.jsx(fn,{meshTheme:e,children:"No queue activity."})})}function C1(e){return e.autoFastForwardEligible||e.suggestedAction==="auto_fast_forward"?{label:"fast-forward",tone:"sky"}:e.launchBlockedReason?{label:"blocked",tone:"rose"}:null}function I1({meshTheme:e,nodes:t}){const r=e.isDark;return s.jsx(Ys,{meshTheme:e,title:"Nodes",count:t.length,children:t.length===0?s.jsx(fn,{meshTheme:e,children:"No nodes in this mesh yet."}):s.jsx("div",{className:"flex flex-col gap-1.5",children:t.map(n=>{var c,d,p;const a=(((c=n.activeSessionDetails)==null?void 0:c.length)??0)||(((d=n.activeSessions)==null?void 0:d.length)??0),o=C1(n),i=((p=n.git)==null?void 0:p.branch)??n.worktreeBranch??null;return s.jsxs("div",{className:`flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 overflow-hidden rounded-xl border px-3 py-2 ${r?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsx(Ot,{meshTheme:e,label:n.health,tone:m1(n.health)}),s.jsx("span",{className:`min-w-0 max-w-full flex-1 truncate text-sm font-medium ${e.textPrimary}`,title:n.workspace,children:n.machineLabel}),i&&s.jsx("span",{className:`max-w-full truncate font-mono text-[11px] ${e.textSecondary}`,title:i,children:i}),s.jsx("span",{className:`max-w-full truncate font-mono text-[10px] ${e.textMuted}`,children:p1(n)}),a>0&&s.jsxs("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:[a," session",a>1?"s":""]}),typeof n.daemonBuildVersion=="string"&&n.daemonBuildVersion&&s.jsxs("span",{className:`shrink-0 font-mono text-[10px] ${e.textMuted}`,title:"Daemon build version reported by this node",children:["v",n.daemonBuildVersion]}),o&&s.jsx(Ot,{meshTheme:e,label:o.label,tone:o.tone})]},n.nodeId)})})})}function A1({meshTheme:e,entries:t,onSelect:r}){const n=Pa(t);return s.jsx(Ys,{meshTheme:e,title:"Active sessions",count:t.length||void 0,children:t.length===0?s.jsx(fn,{meshTheme:e,children:"No active sessions."}):s.jsxs("div",{className:"flex flex-col gap-0.5",children:[n.visible.map(({node:a,session:o})=>{const i=km(o);return s.jsxs(La,{meshTheme:e,onClick:()=>r(a,o),children:[s.jsx("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${e.textMuted}`,children:Ta(o.sessionId)}),s.jsx("span",{className:`shrink-0 ${e.textMuted}`,children:o.providerType||"?"}),s.jsx(Ot,{meshTheme:e,label:i,tone:Nm(i)})]},o.sessionId)}),s.jsx(Ra,{meshTheme:e,expanded:n.expanded,hiddenCount:n.hiddenCount,onToggle:n.toggle})]})})}function M1({meshTheme:e,jobs:t}){const r=e.isDark,n=t.filter(a=>a.status==="failed").length;return s.jsx(Ys,{meshTheme:e,title:"Refine jobs",count:t.length||void 0,action:n>0?s.jsx(Ot,{meshTheme:e,label:`${n} failed`,tone:"rose"}):void 0,children:t.length===0?s.jsx(fn,{meshTheme:e,children:"No refine jobs."}):s.jsx("div",{className:"flex flex-col gap-1",children:t.slice(0,8).map(a=>s.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[s.jsxs("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${e.textMuted}`,children:[a.branch??a.jobId.slice(0,14),a.into?` → ${a.into}`:""]}),s.jsx("span",{className:`shrink-0 text-[10px] font-semibold ${a.status==="failed"?r?"text-rose-300":"text-rose-600":a.status==="running"||a.status==="accepted"?r?"text-sky-300":"text-sky-600":r?"text-emerald-300":"text-emerald-600"}`,children:a.status})]},a.jobId))})})}const _1=[{term:"Node",summary:"A workspace participating in the mesh — a repo checkout or an isolated git worktree.",details:["Base node vs worktree clone node — a clone isolates parallel work without conflicts.","Shows health (online/offline) alongside git state (branch · ahead/behind · dirty).","Multiple nodes can share the same daemon."]},{term:"P2P connection",summary:"How the selected coordinator reaches each remote node over WebRTC.",details:["direct — a direct host/STUN path; lowest latency.","relay — TURN-relayed; works through restrictive networks but is slower.","disconnected / failed — no live P2P link from the coordinator right now.","P2P connectivity is shown as transport and RTT chips on each node card (and in the node detail panel), not as a graph edge."]},{term:"Session",summary:"An agent CLI session running on a node.",details:["status = idle / generating / waiting_approval.","Distinguishes coordinator sessions (which dispatch and collect work) from delegated worker sessions (which do the work)."]},{term:"Task",summary:"A single unit of work handled by the queue-based pull model.",details:["States: pending → assigned → completed / failed / cancelled.","Idle nodes claim from the queue automatically; direct dispatch targets a specific session."]},{term:"Mission",summary:"A multi-task batch aimed at one goal, and the durable record of that effort.",details:["States: active / paused / completed / abandoned.","Progress is derived from the states of its member tasks."]},{term:"Refinery (refine)",summary:"The process of safely converging and merging a worktree branch into the base.",details:["Config-driven (.adhdev/refine.*) — guarded by a patch-equivalence preflight and a no-op guard.","ff-only by principle; no force-push.","If a submodule commit is unreachable from origin it must be published → classified as blocked_review."]},{term:"Completion model",summary:"Completion of delegated work is persisted to the queue (pending-events).",details:["The coordinator learns of completion via periodic polling or events.","Because it is persisted to the queue, completion signals are never lost."]},{term:"MAGI",summary:"Cross-verification: several independent AI agents answer the same question in parallel.",details:["Confidence comes from independence — different AIs on different machines fail in different ways.","When the agents disagree, the disagreement itself flags what to double-check.","Run via mesh_magi_review; the synthesis weighs agreement against source coupling."]},{term:"MAGI panel",summary:"A saved, reusable team of (machine × AI) members you invoke by name across investigations.",details:["Each member is one provider (AI) optionally pinned to a node (machine), with a replica count.","independent — spans ≥2 providers AND ≥2 machines, so agreement adds real confidence.","coupled — collapses to one AI or one machine; repeated members repeat the same mistakes.","Managed machine-locally from the Panels tab; defined in ~/.adhdev/meshes.json."]},{term:"Branch convergence states",summary:"After worktree work, each branch is classified into exactly one final state.",details:["merged_to_main — merged into the base.","pushed_feature_branch_needs_merge — pushed, awaiting merge.","blocked_review — held back by review/reachability issues.","cleanup_candidate — ready to clean up.","not_mergeable — cannot be merged."]}];function T1({meshTheme:e,open:t,onToggle:r}){const n=e.isDark,a="inline-flex h-7 w-7 items-center justify-center rounded-lg border transition",o=t?n?"border-sky-400/40 bg-sky-500/15 text-sky-100":"border-sky-400 bg-sky-100 text-sky-800":n?"border-white/10 bg-white/[0.04] text-slate-400 hover:bg-white/[0.08] hover:text-slate-100":"border-slate-200 bg-white text-slate-400 hover:bg-slate-50 hover:text-slate-700";return s.jsx("button",{type:"button",onClick:r,"aria-label":"Mesh help","aria-expanded":t,title:"Mesh concept help",className:`${a} ${o}`,children:s.jsx(gf,{size:15})})}function L1({meshTheme:e,onClose:t}){const r=e.isDark;return l.useEffect(()=>{const n=a=>{a.key==="Escape"&&t()};return window.addEventListener("keydown",n),()=>window.removeEventListener("keydown",n)},[t]),s.jsxs("div",{className:`shrink-0 rounded-2xl border p-4 ${r?"border-white/10 bg-white/[0.03]":"border-slate-200 bg-white/80"}`,role:"region","aria-label":"Mesh concept help",children:[s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`text-[10px] font-semibold uppercase tracking-[0.16em] ${e.textMuted}`,children:"Help"}),s.jsx("div",{className:`mt-0.5 text-sm font-semibold ${e.textPrimary}`,children:"Mesh concepts at a glance"})]}),s.jsx("button",{type:"button",onClick:t,"aria-label":"Close help",className:r?"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border border-white/10 bg-white/[0.04] text-slate-300 transition hover:bg-white/[0.08] hover:text-white":"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border border-slate-200 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",children:s.jsx(wt,{size:14})})]}),s.jsx("dl",{className:"grid gap-3 sm:grid-cols-2",children:_1.map(n=>s.jsxs("div",{className:`rounded-xl border p-3 ${r?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsx("dt",{className:`text-xs font-semibold ${e.textPrimary}`,children:n.term}),s.jsx("dd",{className:`mt-1 text-[11px] leading-5 ${e.textSecondary}`,children:n.summary}),n.details&&n.details.length>0&&s.jsx("ul",{className:`mt-1.5 flex flex-col gap-1 text-[11px] leading-5 ${e.textMuted}`,children:n.details.map((a,o)=>s.jsxs("li",{className:"flex gap-1.5",children:[s.jsx("span",{"aria-hidden":!0,className:"select-none",children:"·"}),s.jsx("span",{className:"min-w-0",children:a})]},o))})]},n.term))})]})}const Zs=l.createContext(Ls("dark"));function Ke({label:e,tone:t="default",className:r,title:n}){const a=l.useContext(Zs);return s.jsx("span",{title:n,className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.16em] ${a.badge(t)}${r?` ${r}`:""}`,children:e})}function St({label:e,value:t}){const r=l.useContext(Zs);return s.jsxs("div",{className:r.rowClass,children:[s.jsx("span",{className:r.rowLabelClass,children:e}),s.jsx("span",{className:r.rowValueClass,children:t})]})}const R1={meshId:"",totalEntries:0,taskDispatched:0,taskCompleted:0,taskFailed:0,taskStalled:0,sessionLaunched:0,checkpointCreated:0,lastActivityAt:null,recentFailures:0};function Mm(e){switch(e){case"online":return"good";case"dirty":return"warn";case"degraded":case"offline":return"danger";case"wrong_branch":return"info";default:return"default"}}function wo(e){switch((e||"").toLowerCase()){case"idle":return"good";case"generating":case"running":return"info";case"waiting_approval":case"starting":case"pending":return"warn";case"failed":case"stopped":case"interrupted":return"danger";default:return"default"}}function qn(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const r=t.toLowerCase().replace(/[\s-]+/g,"_");return r.includes("approval")?"awaiting approval":r.includes("generating")||r.includes("running")||r.includes("busy")?"generating":r.includes("idle")||r.includes("ready")||r.includes("waiting_input")?"idle":r.replace(/_/g," ")}function P1(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function D1(e){return e.startedAt||e.createdAt||null}function $1(e){const t=D1(e);if(!t)return"runtime age not reported";const r=Date.parse(t);if(!Number.isFinite(r))return"runtime age not reported";const n=Math.max(0,Math.floor((Date.now()-r)/1e3));if(n<60)return`${n}s`;const a=Math.floor(n/60);if(a<60)return`${a}m`;const o=Math.floor(a/60);return o<48?`${o}h ${a%60}m`:`${Math.floor(o/24)}d ${o%24}h`}function _m(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function E1(e){if(!e)return"default";if(e.state==="self")return"info";if(e.transport==="direct"&&e.state==="connected")return"good";if(e.transport==="relay"&&e.state==="connected")return"info";switch(e.state){case"connected":return"good";case"connecting":return"warn";case"disconnected":case"failed":case"closed":return"danger";default:return"default"}}function B1(e){return e?e.state==="self"?"mesh self":e.transport==="direct"&&e.state==="connected"?"mesh direct":e.transport==="relay"&&e.state==="connected"?"mesh relay":!e.reported&&e.source==="not_reported"?"mesh unknown / not reported":`mesh ${e.state}`:"mesh unknown"}function F1(e){const t=e.git;if(!t)return e.gitProbePending?"Git probe pending":"No git probe";const r=(t.staged??0)+(t.modified??0)+(t.untracked??0)+(t.deleted??0)+(t.renamed??0),n=[];t.branch&&n.push(t.branch),t.upstream&&t.upstreamStatus!=="fresh"&&n.push("upstream unverified"),t.upstreamStatus==="fresh"&&((t.ahead??0)>0||(t.behind??0)>0)&&n.push(`↑${t.ahead??0}/↓${t.behind??0}`),r>0&&n.push(`${r} dirty`);const a=(t.submodules??[]).filter(i=>i.dirty),o=(t.submodules??[]).filter(i=>i.outOfSync||i.error);return a.length>0&&n.push(`${a.length} submodule dirty`),o.length>0&&n.push(`${o.length} submodule drift`),t.hasConflicts&&n.push("conflicts"),n.join(" · ")||"Clean"}const O1={first_eligible:"In order",least_loaded:"Spread",round_robin:"Spread (round-robin)",priority_only:"Spread (priority)"};function H1(e){if(e.startsWith("max_provider_parallel_reached:"))return`provider cap reached (${e.slice(30)})`;switch(e){case"global_max_parallel_tasks_reached":return"global parallel cap reached";case"node_has_active_assignment":return"already running a write task";default:return e.replace(/_/g," ")}}function W1(e){var r;const t=[];for(const n of e.nodes){const a=n.activeSessionDetails&&n.activeSessionDetails.length>0?n.activeSessionDetails:(n.activeSessions??[]).map(o=>({sessionId:o,workspace:n.workspace,isCached:!0}));for(const o of a)t.push({nodeId:n.nodeId,machineLabel:n.machineLabel,workspace:n.workspace,branch:((r=n.git)==null?void 0:r.branch)??null,nodeHealth:n.health,session:o})}return t}function K1(e){return e.assignedNodeId||e.targetNodeId||null}function oi(e){return e?e.slice(0,7):null}function U1(e,t){var o,i,c;const r=oi((o=e==null?void 0:e.git)==null?void 0:o.headCommit),n=((c=(i=e==null?void 0:e.git)==null?void 0:i.headMessage)==null?void 0:c.trim())||"";if(r||n)return[r,n].filter(Boolean).join(" · ");const a=t[0];return a?[oi(a.commit),a.message].filter(Boolean).join(" · "):null}function z1(e,t){const r=U1(e,t);return r||(e!=null&&e.gitProbePending?"Pending live git probe":null)}function G1(e){const t=(e==null?void 0:e.result)??e,r=(t==null?void 0:t.log)??(e==null?void 0:e.log)??t;return Array.isArray(r==null?void 0:r.entries)?r.entries:[]}function V1(e){var r,n,a,o,i,c;const t=((r=e.selectedSessionEntry)==null?void 0:r.session.workspace)||((n=e.selectedSessionEntry)==null?void 0:n.workspace)||((o=(a=e.selectedNodeStatus)==null?void 0:a.git)==null?void 0:o.workspace)||((i=e.selectedNodeStatus)==null?void 0:i.workspace)||null;if(t&&e.selectedSessionEntry){const d=((c=e.selectedNodeStatus)==null?void 0:c.daemonId)||e.coordinatorDaemonId;return d?{daemonId:d,workspace:t}:null}if(t&&e.selectedNodeStatus){const d=e.selectedNodeStatus.daemonId||e.coordinatorDaemonId;return d?{daemonId:d,workspace:t}:null}return null}function q1(e){return e.gitProbePending&&(!e.connection||e.connection.state==="unknown")?"mesh pending":B1(e.connection)}function Y1(e){var r;const t=e.source;return t!=null&&t.kind?t.kind:((r=t==null?void 0:t.connection)==null?void 0:r.source)??"mesh_status"}function td(e){switch(e.type){case"parentBranch":return"default branch link";case"worktreeLink":return"worktree relationship";case"sessionLink":return"session relationship";case"orphanLink":return"orphan relationship";case"submoduleLink":return"submodule relationship";case"cloneLink":return"clone relationship";default:return e.type}}function J1(e){return e.direction==="directed"?"directed":"undirected"}function X1(e,t){return t?e.nodes.find(r=>r.id===t)??null:null}function Q1(e){var t,r,n,a;return[e.meshId,e.refreshedAt,e.nodes.length,((r=(t=e.queue)==null?void 0:t.summary)==null?void 0:r.active)??"",((a=(n=e.ledger)==null?void 0:n.summary)==null?void 0:a.recentFailures)??"",...e.nodes.map(o=>{var i,c,d,p,u,m,h,y,x,f,j,k,b,w,I,v,g,S,N,C,R,T;return[o.nodeId,o.daemonId??"",o.machineId??"",o.machineLabel,o.machineStatus??"",((i=o.connection)==null?void 0:i.state)??"",((c=o.connection)==null?void 0:c.transport)??"",((d=o.connection)==null?void 0:d.source)??"",o.health,o.gitProbePending?1:0,((p=o.git)==null?void 0:p.branch)??"",((u=o.git)==null?void 0:u.upstream)??"",((m=o.git)==null?void 0:m.upstreamStatus)??"",((h=o.git)==null?void 0:h.ahead)??"",((y=o.git)==null?void 0:y.behind)??"",((x=o.git)==null?void 0:x.headCommit)??"",((f=o.git)==null?void 0:f.staged)??"",((j=o.git)==null?void 0:j.modified)??"",((k=o.git)==null?void 0:k.untracked)??"",((b=o.git)==null?void 0:b.deleted)??"",((w=o.git)==null?void 0:w.renamed)??"",(I=o.git)!=null&&I.hasConflicts?1:0,((v=o.git)==null?void 0:v.lastCheckedAt)??"",((g=o.activeSessions)==null?void 0:g.join(","))??"",((S=o.activeSessionDetails)==null?void 0:S.length)??"",((N=o.activeSessionDetails)==null?void 0:N.map(_=>[_.sessionId,_.providerType??"",_.state??"",_.chatStatus??"",_.lifecycle??"",_.role??"",_.isSelfCoordinator?1:0,_.statusNote??"",_.startedAt??"",_.createdAt??""].join("/")).join(","))??"",((C=o.providers)==null?void 0:C.join(","))??"",((R=o.providerPriority)==null?void 0:R.join(","))??"",o.error??"",(((T=o.git)==null?void 0:T.submodules)??[]).map(_=>[_.path,_.commit,_.dirty?1:0,_.outOfSync?1:0,_.error??""].join("/")).join(",")].join("|")})].join("::")}function Z1(e){return e.nodes.length===0?!1:e.nodes.every(t=>t.health==="unknown"&&(!t.connection||t.connection.state==="unknown"))}function eN({scheduling:e}){const t=l.useContext(Zs);if(!e)return s.jsx("div",{className:`${t.cardClass} rounded-2xl p-4 text-[12px] ${t.textSecondary}`,children:"Scheduling runtime not reported by this daemon (older build). Update the coordinator daemon to surface distribution, parallel caps, and per-node load."});const r=e.globalWriteCapReached?"warn":"good";return s.jsxs("div",{className:`${t.cardClass} rounded-2xl p-4`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[12px] font-semibold ${t.textPrimary}`,children:"Scheduling"}),s.jsx(Ke,{label:O1[e.strategy]??e.strategy,tone:"info"}),s.jsx(Ke,{label:`write ${e.activeWriteAssigned}/${e.maxParallelTasks}`,tone:r,title:"Active write (non-readonly) assigned tasks vs the global parallel cap"}),s.jsx(Ke,{label:`readonly ${e.activeReadonlyAssigned}/${e.maxReadonlyParallelTasks}`,tone:e.globalReadonlyCapReached?"warn":"default",title:"Active read-only diagnosis tasks vs their (2× write) cap"})]}),s.jsx("p",{className:`mt-2 text-[11px] ${t.textSecondary}`,children:"Distribution only governs how untargeted work is spread across eligible nodes. Per-node load, priority, and provider caps are below."})]})}function tN({scheduling:e}){return e?s.jsxs(s.Fragment,{children:[s.jsx(Ke,{label:`load ${e.load}`,tone:e.load>0?"info":"default",title:"Active assigned tasks on this node"}),typeof e.schedulingPriority=="number"&&e.schedulingPriority!==0&&s.jsx(Ke,{label:`priority ${e.schedulingPriority}`,tone:"default",title:"Soft scheduling priority (higher = preferred)"}),(e.providerRoles??[]).map(t=>s.jsx(Ke,{label:`${t.providerType} ${t.activeAssigned}${typeof t.maxParallel=="number"?`/${t.maxParallel}`:""}`,tone:t.capReached?"warn":"default",title:"Per-(node, provider) active assignments vs declared maxParallel cap"},t.providerType)),e.capReached&&(e.capReasons??[]).map(t=>s.jsx(Ke,{label:H1(t),tone:"warn",title:"Why this node cannot currently claim a new write task"},t))]}):null}function sN({node:e}){var u,m,h,y;const t=l.useContext(Zs),r=((u=e.activeSessionDetails)==null?void 0:u.length)??((m=e.activeSessions)==null?void 0:m.length)??0,n=oi((h=e.git)==null?void 0:h.headCommit),a=e.isLocalWorktree===!0,o=e.worktreeBootstrap,i=e.staleDaemonBuild,c=e.providerVersions&&typeof e.providerVersions=="object"?e.providerVersions:void 0,d=c?Object.entries(c).filter(([,x])=>typeof x=="string"&&x):[],p=typeof e.daemonBuildVersion=="string"&&e.daemonBuildVersion?e.daemonBuildVersion:void 0;return s.jsxs("div",{className:`rounded-xl border p-3 ${t.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[12px] font-semibold ${t.textPrimary}`,children:e.machineLabel||e.nodeId}),s.jsx(Ke,{label:e.health,tone:Mm(e.health)}),a&&s.jsx(Ke,{label:"worktree",tone:"info",title:e.worktreeBranch?`Worktree branch ${e.worktreeBranch}`:"Local worktree node"}),(o==null?void 0:o.status)&&o.status!=="ready"&&s.jsx(Ke,{label:`bootstrap ${o.status}`,tone:"warn",title:"Worktree bootstrap is still in progress"}),((y=e.connection)==null?void 0:y.state)&&e.connection.state!=="self"&&s.jsx(Ke,{label:e.connection.state,tone:e.connection.state==="connected"?"good":"warn",title:"Mesh peer connection state"}),r>0&&s.jsx(Ke,{label:`${r} session${r===1?"":"s"}`,tone:"default"}),e.autoFastForwardEligible&&s.jsx(Ke,{label:"fast-forward ready",tone:"info",title:"Clean, behind upstream — safe for fast-forward"}),!!i&&s.jsx(Ke,{label:"stale build",tone:"warn",title:"Live daemon was built behind workspace HEAD — merged fixes may not be live"}),p&&s.jsx(Ke,{label:`build ${p}`,tone:"default",title:"Daemon build version reported by this node"}),s.jsx(tN,{scheduling:e.scheduling})]}),d.length>0&&s.jsx("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:d.map(([x,f])=>s.jsx(Ke,{label:`${x}@${f}`,tone:"info",title:"Detected provider version on this node"},x))}),s.jsxs("div",{className:`mt-1.5 text-[11px] ${t.textSecondary}`,children:[F1(e),n?s.jsxs("span",{className:"ml-2 font-mono opacity-70",children:["@",n]}):null]})]})}function rN({status:e}){const t=l.useContext(Zs),r=e.meshProtocolMetrics,n=Array.isArray(e.providerVersionSkew)?e.providerVersionSkew:[];return!r&&n.length===0?null:s.jsxs("div",{className:`${t.cardClass} rounded-2xl p-4`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[12px] font-semibold ${t.textPrimary}`,children:"Protocol & provider versions"}),r&&s.jsx(Ke,{label:`v2 ${Math.round(r.v2Ratio*100)}% (${r.v2}/${r.total})`,tone:r.total>0&&r.v2===r.total?"good":"info",title:"Share of pending coordinator events carrying a mesh-protocol-v2 envelope in this drain"}),n.length>0&&s.jsx(Ke,{label:`${n.length} provider skew`,tone:"warn",title:"Providers running different versions across nodes"})]}),r&&Object.keys(r.scopes).length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1.5",children:Object.entries(r.scopes).map(([a,o])=>s.jsx(Ke,{label:`${a}: ${o}`,tone:"default",title:"v2 event scope breakdown"},a))}),n.length>0&&s.jsx("div",{className:"mt-2 flex flex-col gap-1.5",children:n.map(a=>s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx("span",{className:`text-[11px] font-semibold ${t.textPrimary}`,children:a.provider}),a.versions.map(o=>s.jsx(Ke,{label:`${o.version} · ${o.nodeIds.length} node${o.nodeIds.length===1?"":"s"}`,tone:"default",title:o.nodeIds.join(", ")},o.version))]},a.provider))}),e.providerVersionSkewWarning&&s.jsx("p",{className:`mt-2 text-[11px] ${t.textSecondary}`,children:e.providerVersionSkewWarning})]})}function nN({canonicalStatus:e}){const t=l.useContext(Zs);return s.jsxs("div",{className:"flex flex-col gap-3 p-1",children:[s.jsx(eN,{scheduling:e.scheduling}),s.jsx(rN,{status:e}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx("span",{className:`px-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${t.textSecondary}`,children:"Nodes — runtime"}),e.nodes.length===0?s.jsx("div",{className:`rounded-xl border p-3 text-[12px] ${t.textSecondary} ${t.isDark?"border-white/10":"border-slate-200"}`,children:"No nodes reporting runtime yet."}):e.nodes.map(r=>s.jsx(sN,{node:r},r.nodeId))]})]})}function aN({canonicalStatus:e,queueSummary:t,ledgerSummary:r,isBootstrapMode:n,meshTheme:a,sessionEntries:o,inlineMode:i=!1}){var v;const c=t&&(t.active>0||t.historical>0),d=r.recentFailures>0||r.taskFailed>0,p=(v=e.queue)!=null&&v.tasks?e.queue.tasks.filter(g=>g.status==="failed"||g.status==="cancelled").slice(0,5):[],u=e.asyncRefineJobs,m=(u==null?void 0:u.filter(g=>g.status==="running"||g.status==="accepted"))??[],h=(u==null?void 0:u.filter(g=>g.status==="failed"))??[],y=e.staleDirectWorkSummary,x=y&&y.count>0;if(!c&&!d&&e.nodes.length===0&&!n&&m.length===0&&h.length===0&&!x&&o.length===0)return null;const f=a.isDark,j=`border-t ${f?"border-white/8":"border-slate-200"}`,k=`group w-full rounded-lg border text-xs ${f?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,b=`flex cursor-pointer list-none items-center gap-1.5 px-2.5 py-1.5 [&::-webkit-details-marker]:hidden ${a.textSecondary}`;function w({label:g,value:S,tone:N}){const C=N==="rose"?f?"text-rose-300":"text-rose-600":N==="sky"?f?"text-sky-300":"text-sky-600":N==="amber"?f?"text-amber-300":"text-amber-600":N==="emerald"?f?"text-emerald-300":"text-emerald-600":N==="muted"?a.textMuted:a.textPrimary;return s.jsxs("div",{className:`flex flex-col items-center rounded-lg border px-2 py-1.5 ${f?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-white/70"}`,children:[s.jsx("span",{className:`tabular-nums text-sm font-semibold leading-none ${C}`,children:S}),s.jsx("span",{className:`mt-0.5 text-[9px] uppercase tracking-wide ${a.textMuted}`,children:g})]})}const I=s.jsxs("div",{className:"flex flex-col gap-3 text-xs",children:[s.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t?s.jsxs(s.Fragment,{children:[s.jsx(w,{label:"Pending",value:t.pending}),s.jsx(w,{label:"Active",value:t.active,tone:t.active>0?"sky":void 0}),s.jsx(w,{label:"Done",value:t.completed,tone:"emerald"}),s.jsx(w,{label:"Failed",value:t.failed,tone:t.failed>0?"rose":void 0})]}):s.jsxs(s.Fragment,{children:[s.jsx(w,{label:"Done",value:r.taskCompleted,tone:"emerald"}),s.jsx(w,{label:"Failed",value:r.taskFailed,tone:r.taskFailed>0?"rose":void 0}),s.jsx(w,{label:"Sessions",value:r.sessionLaunched}),s.jsx(w,{label:"Recent↯",value:r.recentFailures,tone:r.recentFailures>0?"amber":"muted"})]})}),t&&s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(w,{label:"Ledger done",value:r.taskCompleted,tone:"emerald"}),s.jsx(w,{label:"Sessions",value:r.sessionLaunched}),s.jsx(w,{label:"Recent↯",value:r.recentFailures,tone:r.recentFailures>0?"amber":"muted"})]}),r.lastActivityAt&&s.jsxs("div",{className:`flex items-center justify-between ${a.textMuted}`,children:[s.jsx("span",{children:"Last activity"}),s.jsx("span",{className:"font-mono text-[10px]",children:r.lastActivityAt.slice(5,16)})]}),e.nodes.length>0&&s.jsx("div",{className:`pt-2.5 ${j}`,children:s.jsx("div",{className:"flex flex-col gap-1",children:e.nodes.map(g=>{var _;const S=((_=g.connection)==null?void 0:_.state)??"unknown",N=S==="unknown"||S==="connecting",T=N?"bg-amber-400":S==="failed"||S==="closed"||S==="disconnected"?f?"bg-rose-400":"bg-rose-500":S==="connected"||S==="self"?f?"bg-emerald-400":"bg-emerald-500":f?"bg-slate-500":"bg-slate-400";return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`size-1.5 shrink-0 rounded-full ${T}`}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${a.textSecondary}`,title:g.workspace,children:g.machineLabel}),s.jsx("span",{className:`shrink-0 font-mono text-[10px] ${a.textMuted}`,children:N?"…":S})]},g.nodeId)})})}),u&&u.length>0&&s.jsx("div",{className:`pt-2.5 ${j}`,children:s.jsxs("details",{className:k,children:[s.jsxs("summary",{className:b,children:[s.jsx("span",{className:"flex-1",children:"Refine jobs"}),s.jsx("span",{className:`tabular-nums ${f?"text-slate-400":"text-slate-500"}`,children:u.length}),h.length>0&&s.jsxs("span",{className:f?"text-rose-300":"text-rose-600",children:[h.length," failed"]})]}),s.jsx("div",{className:"flex flex-col gap-0.5 px-2.5 pb-2",children:u.slice(0,8).map(g=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${a.textMuted}`,children:[g.branch??g.jobId.slice(0,14),g.into?` → ${g.into}`:""]}),s.jsx("span",{className:`shrink-0 text-[9px] font-semibold ${g.status==="failed"?f?"text-rose-300":"text-rose-600":g.status==="running"||g.status==="accepted"?f?"text-sky-300":"text-sky-600":f?"text-emerald-300":"text-emerald-600"}`,children:g.status})]},g.jobId))})]})}),p.length>0&&s.jsx("div",{className:u&&u.length>0?"":`pt-2.5 ${j}`,children:s.jsxs("details",{className:k,children:[s.jsxs("summary",{className:b,children:[s.jsx("span",{className:`flex-1 ${f?"text-rose-300":"text-rose-600"}`,children:"Failed tasks"}),s.jsx("span",{className:`tabular-nums ${f?"text-rose-400":"text-rose-500"}`,children:p.length})]}),s.jsx("div",{className:"flex flex-col gap-1 px-2.5 pb-2",children:p.map(g=>s.jsxs("div",{className:"flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`font-mono text-[10px] ${a.textMuted}`,children:g.id.slice(0,10)}),g.message&&s.jsx("span",{className:`flex-1 truncate ${f?"text-slate-300":"text-slate-700"}`,children:g.message.slice(0,55)})]}),g.cancelReason&&s.jsx("div",{className:`truncate text-[10px] ${a.textMuted}`,children:g.cancelReason.slice(0,55)})]},g.id))})]})}),x&&s.jsxs("div",{className:`flex items-center justify-between pt-2.5 ${j}`,children:[s.jsx("span",{className:a.textMuted,children:"Stale work"}),s.jsx("span",{className:`tabular-nums ${f?"text-amber-300":"text-amber-600"}`,children:y.count})]}),o.length>0&&s.jsx("div",{className:`pt-2.5 ${j}`,children:s.jsxs("details",{className:k,children:[s.jsxs("summary",{className:b,children:[s.jsx("span",{className:"flex-1",children:"Sessions"}),s.jsx("span",{className:`tabular-nums ${f?"text-slate-400":"text-slate-500"}`,children:o.length})]}),s.jsx("div",{className:"flex flex-col gap-0.5 px-2.5 pb-2",children:o.map(g=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${a.textMuted}`,title:g.session.sessionId,children:_m(g.session.sessionId)}),s.jsx("span",{className:`shrink-0 ${a.textMuted}`,children:g.session.providerType||"?"}),s.jsx("span",{className:`shrink-0 text-[9px] font-semibold ${a.textMuted}`,children:qn(g.session)})]},g.session.sessionId))})]})})]});return i?I:s.jsxs("details",{className:`rounded-2xl border text-xs ${a.isDark?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsxs("summary",{className:`flex cursor-pointer list-none items-center gap-2 px-4 py-3 font-medium [&::-webkit-details-marker]:hidden ${a.textSecondary}`,children:[s.jsx("span",{className:"flex-1",children:"Mesh Health Panel"}),m.length>0&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${a.isDark?"border-sky-400/25 bg-sky-500/10 text-sky-200":"border-sky-300 bg-sky-50 text-sky-700"}`,children:[m.length," refining"]}),h.length>0&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${a.isDark?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700"}`,children:[h.length," refine failed"]}),d&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${a.isDark?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700"}`,children:[r.recentFailures," recent failures"]}),n&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${a.isDark?"border-amber-400/20 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700"}`,children:"awaiting live data"})]}),I]})}const oN={merged_to_main:"Merged to main",pushed_feature_branch_needs_merge:"Needs merge",blocked_review:"Blocked — needs review",cleanup_candidate:"Ready to clean up",not_mergeable:"Not mergeable"};function Tm({meshTheme:e,activeTab:t,onActiveTabChange:r,helpOpen:n,onHelpOpenChange:a}){const o=i=>i?e.isDark?"rounded-lg px-3.5 py-1.5 text-xs font-semibold text-slate-100 bg-white/[0.08] border border-white/12":"rounded-lg px-3.5 py-1.5 text-xs font-semibold text-slate-900 bg-white border border-slate-300 shadow-sm":`rounded-lg px-3.5 py-1.5 text-xs font-medium ${e.textSecondary} border border-transparent hover:bg-white/[0.04]`;return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("div",{className:`inline-flex w-fit items-center gap-1 rounded-xl border p-1 ${e.isDark?"border-white/10 bg-slate-950/40":"border-slate-200 bg-slate-50"}`,role:"tablist","aria-label":"Mesh view",children:[s.jsx("button",{type:"button",role:"tab","aria-selected":t==="overview",className:o(t==="overview"),onClick:()=>r("overview"),children:"Overview"}),s.jsx("button",{type:"button",role:"tab","aria-selected":t==="status",className:o(t==="status"),onClick:()=>r("status"),children:"Status"}),s.jsx("button",{type:"button",role:"tab","aria-selected":t==="graph",className:o(t==="graph"),onClick:()=>r("graph"),children:"Graph"})]}),s.jsx(T1,{meshTheme:e,open:n,onToggle:()=>a(!n)})]})}function iN({status:e,emptyMessage:t="No live mesh graph is available for this coordinator yet.",daemonId:r=null,sendDaemonCommand:n=null,bootstrapFallback:a,activeTab:o,onActiveTabChange:i,helpOpen:c,onHelpOpenChange:d,hideControls:p=!1}){var ke,Le,We;const{theme:u}=Ts(),m=l.useMemo(()=>Ls(u),[u]),h=l.useMemo(()=>gu(e),[e]),y=a??Z1(h),x=l.useMemo(()=>Q1(h),[h]),f=l.useMemo(()=>bm(h),[x]),[j,k]=l.useState("overview"),[b,w]=l.useState(!1),I=o??j,v=c??b,g=l.useCallback(ce=>{i?i(ce):k(ce)},[i]),S=l.useCallback(ce=>{d?d(ce):w(ce)},[d]),[N,C]=l.useState(!1);l.useEffect(()=>{I==="graph"&&C(!0)},[I]);const[R,T]=l.useState(null),[_,P]=l.useState(null),[B,z]=l.useState(null),[A,O]=l.useState({}),[$,L]=l.useState(null),[E,M]=l.useState(null),H=l.useMemo(()=>new Map(h.nodes.map(ce=>[ce.nodeId,ce])),[h.nodes]),Y=l.useMemo(()=>new Map(f.nodes.map(ce=>[ce.id,ce])),[f.nodes]),G=((ke=h.queue)==null?void 0:ke.summary)??null,J=((Le=h.ledger)==null?void 0:Le.summary)??R1,te=l.useMemo(()=>W1(h),[h]),oe=l.useMemo(()=>{const ce=new Map;for(const Ee of te){const Be=qn(Ee.session);ce.set(Be,(ce.get(Be)??0)+1)}return[...ce.entries()].sort((Ee,Be)=>Be[1]-Ee[1])},[te]);l.useEffect(()=>{R&&(Y.has(R)||(T(null),z(ce=>!ce||"nodeId"in ce&&ce.nodeId===R?null:ce)))},[Y,R]);const q=R?H.get(R)??null:null,F=X1(f,R),V=(B==null?void 0:B.kind)==="edge"&&_?f.edges.find(ce=>ce.id===_)??null:null,pe=V?f.nodes.find(ce=>ce.id===V.source)??null:null,be=V?f.nodes.find(ce=>ce.id===V.target)??null:null;l.useEffect(()=>{var ce,Ee,Be;if(R)try{console.info("[RepoMeshGraphDebug]",{event:"selected_canonical_node",meshId:h.meshId,selectedNodeId:R,canonicalNode:Ob(q),graphNode:F?{id:F.id,branch:F.branch,upstream:F.upstream,headCommit:F.submoduleCommit,submoduleCount:((Ee=(ce=q==null?void 0:q.git)==null?void 0:ce.submodules)==null?void 0:Ee.length)??0,snapshotCompleteness:F.snapshotCompleteness,snapshotWarnings:F.snapshotWarnings,branchConvergence:((Be=F.branchConvergence)==null?void 0:Be.status)??null}:null})}catch{}},[h.meshId,F,R,q]);const ue=(B==null?void 0:B.kind)==="session"?te.find(ce=>ce.nodeId===B.nodeId&&ce.session.sessionId===B.sessionId)??null:null,Ne=l.useMemo(()=>te.filter(ce=>ce.nodeId===R),[R,te]),se=V1({coordinatorDaemonId:r,selectedNodeStatus:q,selectedSessionEntry:ue}),ve=(se==null?void 0:se.workspace)??null,me=ve?A[ve]??null:null,U=z1(q,(me==null?void 0:me.entries)??[]),W=(F==null?void 0:F.daemonId)??(q==null?void 0:q.daemonId)??r??null,Z=!!(F&&n&&W&&F.type!=="submoduleNode"&&F.behind>0&&F.ahead===0&&F.dirtyFiles===0&&!F.dirty&&!F.hasConflicts&&F.upstreamStatus==="fresh"),ie=l.useCallback(()=>{T(null),P(null),z(null),L(null)},[]);l.useEffect(()=>{L(null)},[R]);const ye=l.useCallback(async()=>{if(!F||!W||!n||!Z)return;M(F.id),L(null);const ce=(q==null?void 0:q.workspace)??F.workspace??"";try{const Ee=await n(W,"fast_forward_mesh_node",{meshId:h.meshId,nodeId:F.id,workspace:ce,updateSubmodules:!0,dryRun:!0,execute:!1}),Be=(Ee==null?void 0:Ee.result)??Ee;if(L({phase:"dry_run",code:typeof(Be==null?void 0:Be.code)=="string"?Be.code:void 0,error:typeof(Be==null?void 0:Be.operationError)=="string"?Be.operationError:null,executed:(Be==null?void 0:Be.executed)===!0}),!(Be!=null&&Be.success)||Be.code!=="fast_forward_available"||!window.confirm(`Apply fast-forward for ${F.label}?`))return;const qe=await n(W,"fast_forward_mesh_node",{meshId:h.meshId,nodeId:F.id,workspace:ce,updateSubmodules:!0,dryRun:!1,execute:!0}),je=(qe==null?void 0:qe.result)??qe;L({phase:"execute",code:typeof(je==null?void 0:je.code)=="string"?je.code:void 0,error:typeof(je==null?void 0:je.operationError)=="string"?je.operationError:null,executed:(je==null?void 0:je.executed)===!0})}catch(Ee){L({phase:"dry_run",error:Ee instanceof Error?Ee.message:"fast-forward failed"})}finally{M(null)}},[Z,h.meshId,F,W,n]);l.useEffect(()=>{if(!F&&!V)return;const ce=Ee=>{Ee.key==="Escape"&&ie()};return window.addEventListener("keydown",ce),()=>window.removeEventListener("keydown",ce)},[ie,V,F]),l.useEffect(()=>{if(!se||!n)return;const{daemonId:ce,workspace:Ee}=se,Be=A[Ee];if(Be!=null&&Be.loading||Be&&(Be.entries.length>0||Be.error))return;let Je=!1;return O(qe=>{var je;return{...qe,[Ee]:{loading:!0,error:null,entries:((je=qe[Ee])==null?void 0:je.entries)??[]}}}),n(ce,"git_log",{workspace:Ee,limit:5}).then(qe=>{Je||O(je=>({...je,[Ee]:{loading:!1,error:null,entries:G1(qe)}}))}).catch(qe=>{Je||O(je=>({...je,[Ee]:{loading:!1,error:qe instanceof Error?qe.message:"git_log failed",entries:[]}}))}),()=>{Je=!0}},[A,se,n]);const fe=[...f.warnings??[],...h.nodes.filter(ce=>ce.machineStatus&&ce.machineStatus!=="online").map(ce=>`${ce.machineLabel}: ${ce.machineStatus}`)],D=f.stats.incompleteSnapshotNodes>0,he=f.stats.followUpNodes>0?`${f.stats.followUpNodes} need follow-up`:D?"mesh visibility incomplete":"mesh converged",Se=f.stats.followUpNodes>0?"danger":D?"warn":"good",[ae,Q]=l.useState("LR"),we=ce=>ce?m.isDark?"rounded-md border border-cyan-400/40 bg-cyan-500/15 px-2 py-0.5 text-cyan-100":"rounded-md border border-sky-400 bg-sky-100 px-2 py-0.5 text-sky-800":m.isDark?"rounded-md border border-white/10 bg-white/[0.03] px-2 py-0.5 text-slate-400 hover:text-slate-200":"rounded-md border border-slate-300 bg-white/80 px-2 py-0.5 text-slate-500 hover:text-slate-800";return s.jsx(Zs.Provider,{value:m,children:s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[!p&&s.jsx("div",{className:"shrink-0 flex items-center justify-end",children:s.jsx(Tm,{meshTheme:m,activeTab:I,onActiveTabChange:g,helpOpen:v,onHelpOpenChange:S})}),v&&s.jsx(L1,{meshTheme:m,onClose:()=>S(!1)}),s.jsx("div",{className:`${I==="overview"?"flex":"hidden"} min-h-0 flex-1 flex-col gap-3 overflow-y-auto`,children:I==="overview"&&s.jsx(h1,{status:h,daemonId:r,meshId:h.meshId,sendDaemonCommand:n})}),s.jsx("div",{className:`${I==="status"?"flex":"hidden"} min-h-0 flex-1 flex-col overflow-y-auto`,children:I==="status"&&s.jsx(nN,{canonicalStatus:h})}),s.jsx("div",{className:`${I==="graph"?"flex":"hidden"} min-h-0 flex-1 flex-col gap-4`,children:s.jsxs("div",{className:`${m.cardClass} relative flex min-h-0 flex-1 flex-col rounded-[28px]`,style:{minHeight:480},children:[s.jsxs("div",{className:`relative z-30 max-h-[42dvh] overflow-y-auto sm:max-h-none sm:mb-3 sm:overflow-visible shrink-0 flex flex-wrap items-start justify-between gap-2 px-4 pt-3 pb-2.5 border-b ${m.isDark?"border-white/8":"border-slate-200"}`,children:[s.jsxs("div",{className:`flex min-w-0 flex-1 flex-nowrap overflow-x-auto sm:flex-wrap sm:overflow-visible gap-2 text-xs ${m.textSecondary}`,children:[s.jsx(Ke,{label:he,tone:Se,className:"shrink-0"}),f.stats.blockedReviewNodes>0&&s.jsx(Ke,{label:`${f.stats.blockedReviewNodes} blocked`,title:`${f.stats.blockedReviewNodes} blocked review`,tone:"danger",className:"shrink-0"}),f.stats.notMergeableNodes>0&&s.jsx(Ke,{label:`${f.stats.notMergeableNodes} not mergeable`,tone:"danger",className:"shrink-0"}),f.stats.mergeReadyNodes>0&&s.jsx(Ke,{label:`${f.stats.mergeReadyNodes} need merge`,tone:"warn",className:"shrink-0"}),f.stats.cleanupCandidateNodes>0&&s.jsx(Ke,{label:`${f.stats.cleanupCandidateNodes} cleanup`,title:`${f.stats.cleanupCandidateNodes} refine/cleanup`,tone:"info",className:"shrink-0"}),f.stats.offlineNodes>0&&s.jsx(Ke,{label:`${f.stats.offlineNodes} offline`,tone:"danger",className:"shrink-0"}),f.stats.incompleteSnapshotNodes>0&&s.jsx(Ke,{label:`${f.stats.incompleteSnapshotNodes} incomplete`,title:`${f.stats.incompleteSnapshotNodes} incomplete peer snapshot`,tone:"warn",className:"shrink-0"}),f.stats.missingGitSnapshotNodes>0&&s.jsx(Ke,{label:`${f.stats.missingGitSnapshotNodes} no-git`,title:`${f.stats.missingGitSnapshotNodes} no git snapshot`,tone:"warn",className:"shrink-0"}),f.stats.missingSubmoduleSnapshotNodes>0&&s.jsx(Ke,{label:`${f.stats.missingSubmoduleSnapshotNodes} no-submod`,title:`${f.stats.missingSubmoduleSnapshotNodes} missing submodule visibility`,tone:"warn",className:"shrink-0"}),f.stats.staleGitSnapshotNodes>0&&s.jsx(Ke,{label:`${f.stats.staleGitSnapshotNodes} stale`,title:`${f.stats.staleGitSnapshotNodes} stale peer snapshot`,tone:"warn",className:"shrink-0"}),((G==null?void 0:G.active)??0)>0&&s.jsx(Ke,{label:`${(G==null?void 0:G.active)??0} active queue`,tone:"info",className:"shrink-0 hidden sm:inline-flex"}),s.jsx(Ke,{label:`${f.stats.totalNodes} nodes`,tone:"default",className:"shrink-0 hidden sm:inline-flex"}),f.stats.totalActiveSessions>0&&s.jsx(Ke,{label:`${f.stats.totalActiveSessions} attached chats`,tone:"info",className:"shrink-0 hidden sm:inline-flex"})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[s.jsxs("div",{className:m.isDark?"flex items-center gap-0.5 rounded-md border border-white/10 bg-slate-950/40 p-0.5 text-[10px]":"flex items-center gap-0.5 rounded-md border border-slate-300 bg-white/70 p-0.5 text-[10px]",role:"group","aria-label":"Graph layout direction",children:[s.jsx("button",{type:"button",onClick:()=>Q("auto"),className:we(ae==="auto"),title:"Auto-detect direction",children:"Auto"}),s.jsx("button",{type:"button",onClick:()=>Q("LR"),className:we(ae==="LR"),title:"Left to right",children:"LR"}),s.jsx("button",{type:"button",onClick:()=>Q("TB"),className:we(ae==="TB"),title:"Top to bottom",children:"TB"})]}),s.jsx("div",{className:"relative",children:s.jsxs("details",{className:`rounded-xl px-3 py-1.5 text-xs ${m.isDark?"border border-white/10 bg-white/[0.03] text-slate-300":"border border-slate-200 bg-slate-50 text-slate-600"}`,children:[s.jsx("summary",{className:`cursor-pointer list-none font-medium ${m.textSecondary} [&::-webkit-details-marker]:hidden`,children:(()=>{var Be;const ce=((Be=h.asyncRefineJobs)==null?void 0:Be.filter(Je=>Je.status==="failed").length)??0,Ee=J.recentFailures;return ce>0?s.jsxs("span",{className:m.isDark?"text-rose-300":"text-rose-600",children:[ce," refine failed"]}):Ee>0?s.jsxs("span",{className:m.isDark?"text-amber-300":"text-amber-600",children:[Ee," failures"]}):"Health"})()}),s.jsx("div",{className:`absolute right-0 z-40 mt-2 w-72 max-h-[70vh] overflow-y-auto rounded-xl border p-4 shadow-xl backdrop-blur-xl ${m.isDark?"border-white/10 bg-slate-950/96":"border-slate-200 bg-white/98 shadow-slate-900/10"}`,children:s.jsx(aN,{canonicalStatus:h,queueSummary:G,ledgerSummary:J,isBootstrapMode:y,meshTheme:m,sessionEntries:te,inlineMode:!0})})]})}),s.jsx("div",{className:"relative",children:s.jsxs("details",{className:`rounded-xl px-3 py-1.5 text-xs ${m.isDark?"border border-white/10 bg-white/[0.03] text-slate-300":"border border-slate-200 bg-slate-50 text-slate-600"}`,children:[s.jsx("summary",{className:`cursor-pointer list-none font-medium ${m.textSecondary} [&::-webkit-details-marker]:hidden`,children:"Legend"}),s.jsx("div",{className:`absolute right-0 z-40 mt-2 w-72 rounded-xl border p-3 shadow-xl backdrop-blur-xl ${m.isDark?"border-white/10 bg-slate-950/96":"border-slate-200 bg-white/98 shadow-slate-900/10"}`,children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ke,{label:`${f.stats.dirtyNodes} dirty`,tone:f.stats.dirtyNodes>0?"warn":"good"}),s.jsx(Ke,{label:`${f.stats.orphanNodes} orphan`,tone:f.stats.orphanNodes>0?"warn":"good"}),s.jsx(Ke,{label:`${J.recentFailures} recent failures`,tone:J.recentFailures>0?"danger":"good"}),oe.length===0?s.jsx(Ke,{label:"no session metadata"}):oe.slice(0,2).map(([ce,Ee])=>s.jsx(Ke,{label:`${Ee} ${ce}`,tone:wo(ce)},ce))]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ke,{label:"Anchor = default branch",tone:"info"}),s.jsx(Ke,{label:"Peer link = same-branch worktree",tone:"default"}),s.jsx(Ke,{label:"Submodule link = child checkout",tone:"warn"})]}),fe.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:fe.map(ce=>s.jsx("span",{className:m.isDark?"rounded-full border border-amber-400/20 bg-amber-500/10 px-3 py-1 text-xs text-amber-100":"rounded-full border border-amber-300 bg-amber-50 px-3 py-1 text-xs text-amber-700",children:ce},ce))}),s.jsx("div",{className:`text-xs ${m.textMuted}`,children:"Click a node or edge to pin its drill-down details in the side panel. Click it again to close."})]})})]})})]})]}),y&&f.nodes.length>0&&s.jsxs("div",{className:`shrink-0 mx-4 mt-2 flex items-center gap-2 rounded-xl border px-3.5 py-2 text-xs ${m.isDark?"border-amber-400/20 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700"}`,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full animate-pulse ${m.isDark?"bg-amber-400":"bg-amber-500"}`,"aria-hidden":!0}),s.jsx("span",{children:"Awaiting live data — showing setup inventory until peer mesh_status probes succeed."})]}),s.jsxs("div",{className:"relative flex flex-1 min-w-0",style:{minHeight:360},children:[s.jsx("div",{className:"flex-1 min-w-0",children:N?f.nodes.length>0?s.jsx(r1,{data:f,selectedNodeId:R,directionPref:ae,onNodeClick:ce=>{if((B==null?void 0:B.kind)==="node"&&R===ce.id){ie();return}P(null),T(ce.id),z({kind:"node",nodeId:ce.id})},onEdgeClick:ce=>{if((B==null?void 0:B.kind)==="edge"&&_===ce.id){ie();return}T(null),P(ce.id),z({kind:"edge",edgeId:ce.id})}}):s.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:t}):s.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:"Loading graph…"})}),F&&(B==null?void 0:B.kind)==="node"&&s.jsxs("div",{role:"dialog",className:`absolute inset-x-3 bottom-3 top-20 z-20 rounded-2xl border shadow-2xl sm:relative sm:inset-auto sm:z-auto sm:w-72 sm:shrink-0 sm:rounded-none sm:border-0 sm:border-l sm:shadow-none overflow-y-auto p-4 ${m.isDark?"border-white/10 bg-slate-950 sm:bg-transparent":"border-slate-200 bg-white sm:bg-transparent"}`,children:[s.jsx("div",{className:`mb-2 text-[10px] font-semibold uppercase tracking-wide ${m.textMuted}`,children:"Selected node"}),s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${m.textPrimary}`,children:F.label}),s.jsx("div",{className:`mt-0.5 font-mono text-[11px] ${m.textMuted}`,children:F.id.slice(0,16)})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[F.behind>0&&s.jsx("button",{type:"button",onClick:()=>{ye()},disabled:!Z||E===F.id,className:m.isDark?"rounded-full border border-emerald-400/25 bg-emerald-500/10 px-2 py-0.5 text-xs font-semibold text-emerald-100 transition hover:bg-emerald-500/18 disabled:cursor-not-allowed disabled:opacity-45":"rounded-full border border-emerald-300 bg-emerald-50 px-2 py-0.5 text-xs font-semibold text-emerald-700 transition hover:bg-emerald-100 disabled:cursor-not-allowed disabled:opacity-45",children:E===F.id?"Checking":"Heal"}),s.jsx("button",{type:"button",onClick:ie,"aria-label":"Close detail panel",className:m.isDark?"rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-xs text-slate-200 transition hover:bg-white/[0.08]":"rounded-full border border-slate-200 bg-white px-2 py-0.5 text-xs text-slate-600 transition hover:bg-slate-50",children:"✕"})]})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-1.5",children:[(()=>{const ce=(q==null?void 0:q.health)??F.health;return ce==="unknown"?s.jsx(Ke,{label:"connecting...",tone:"default"}):s.jsx(Ke,{label:ce,tone:Mm(ce)})})(),F.branch&&s.jsx(Ke,{label:F.branch,tone:"default"}),F.ahead>0&&s.jsx(Ke,{label:`ahead ${F.ahead}`,tone:"warn"}),F.behind>0&&s.jsx(Ke,{label:`behind ${F.behind}`,tone:"warn"}),F.dirtyFiles>0&&s.jsx(Ke,{label:`${F.dirtyFiles} dirty`,tone:"warn"}),(q==null?void 0:q.connection)&&q.connection.state!=="unknown"&&s.jsx(Ke,{label:q1(q),tone:E1(q.connection)}),((We=q==null?void 0:q.connection)==null?void 0:We.state)==="unknown"&&s.jsx(Ke,{label:"mesh connecting...",tone:"warn"}),Ne.length>0&&s.jsx(Ke,{label:`${Ne.length} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[F.machineLabel&&s.jsx(St,{label:"Machine",value:F.machineLabel}),F.locality&&F.locality!=="unknown"&&s.jsx(St,{label:"Locality",value:F.locality}),s.jsx(St,{label:"Workspace",value:(q==null?void 0:q.workspace)??F.workspace}),U&&s.jsx(St,{label:"HEAD",value:U}),(F.dirtyFiles>0||F.ahead>0||F.behind>0)&&s.jsx(St,{label:"Dirty/ahead/behind",value:`${F.dirtyFiles}/${F.ahead}/${F.behind}`}),Ne.length>0&&s.jsx(St,{label:"Sessions",value:String(Ne.length)}),F.upstream&&s.jsx(St,{label:"Upstream",value:F.upstream}),(()=>{var Ee;const ce=((Ee=q==null?void 0:q.connection)==null?void 0:Ee.source)??Y1(F);return ce&&ce!=="unknown"?s.jsx(St,{label:"Source",value:String(ce)}):null})(),(()=>{var Ee;const ce=(Ee=q==null?void 0:q.connection)==null?void 0:Ee.transport;return ce&&ce!=="unknown"?s.jsx(St,{label:"Transport",value:ce}):null})(),(()=>{const ce=F.machineId??(q==null?void 0:q.machineId);return ce?s.jsx(St,{label:"Machine id",value:ce}):null})(),(()=>{const ce=F.daemonId??(q==null?void 0:q.daemonId);return ce?s.jsx(St,{label:"Daemon id",value:ce}):null})()]}),Ne.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${m.textMuted}`,children:"Active Sessions"}),s.jsx("div",{className:"flex flex-col gap-1.5",children:Ne.map(ce=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${m.isDark?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-slate-50/80"}`,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`min-w-0 truncate font-mono select-text ${m.textMuted}`,title:ce.session.sessionId,children:_m(ce.session.sessionId)}),s.jsx(Ke,{label:qn(ce.session),tone:wo(qn(ce.session))})]}),s.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 ${m.textMuted}`,children:[s.jsx("span",{className:"truncate",children:ce.session.providerType||"provider unknown"}),s.jsx("span",{children:P1(ce.session)}),s.jsx("span",{children:$1(ce.session)})]}),ce.session.statusNote&&s.jsx("div",{className:`mt-1 text-[10px] leading-4 ${m.textMuted}`,children:ce.session.statusNote}),s.jsxs("div",{className:`mt-0.5 truncate ${m.textMuted}`,title:ce.session.workspace||ce.workspace,children:[(ce.session.workspace||ce.workspace).slice(0,38),ce.branch?` · ${ce.branch}`:""]})]},ce.session.sessionId))})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${m.textMuted}`,children:"Ledger (mesh-wide)"}),s.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[s.jsx(St,{label:"Completed",value:String(J.taskCompleted)}),s.jsx(St,{label:"Failed",value:s.jsx("span",{className:J.taskFailed>0?m.isDark?"text-rose-300":"text-rose-600":"",children:J.taskFailed})}),s.jsx(St,{label:"Launched",value:String(J.sessionLaunched)}),s.jsx(St,{label:"Recent failures",value:s.jsx("span",{className:J.recentFailures>0?m.isDark?"text-amber-300":"text-amber-600":"",children:J.recentFailures})})]})]}),(()=>{var Be,Je;const ce=((Be=h.queue)==null?void 0:Be.tasks)??((Je=h.queue)==null?void 0:Je.items)??null;if(!Array.isArray(ce)||ce.length===0)return null;const Ee=ce.filter(qe=>K1(qe)===R).slice(0,3);return Ee.length===0?null:s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${m.textMuted}`,children:"Queue tasks"}),s.jsx("div",{className:"flex flex-col gap-1.5",children:Ee.map(qe=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${m.isDark?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-slate-50/80"}`,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`font-mono ${m.textMuted}`,children:qe.id.slice(0,12)}),s.jsx(Ke,{label:qe.status??"unknown",tone:wo(qe.status)})]}),qe.message&&s.jsx("div",{className:`mt-0.5 truncate ${m.textMuted}`,children:qe.message.slice(0,48)})]},qe.id))})]})})(),F.snapshotWarnings.length>0&&s.jsxs("div",{className:m.isDark?"mt-3 rounded-xl border border-amber-400/20 bg-amber-500/10 p-3 text-xs text-amber-100":"mt-3 rounded-xl border border-amber-300 bg-amber-50 p-3 text-xs text-amber-800",children:[s.jsx("div",{className:"font-medium",children:"Key warning"}),s.jsx("div",{className:"mt-1",children:F.snapshotWarnings[0]})]}),F.branchConvergence&&(F.branchConvergence.reason||F.branchConvergence.nextStep)&&s.jsxs("div",{className:m.isDark?"mt-3 rounded-xl border border-sky-400/20 bg-sky-500/10 p-3 text-xs text-sky-100":"mt-3 rounded-xl border border-sky-300 bg-sky-50 p-3 text-xs text-sky-800",children:[s.jsxs("div",{className:"font-medium",children:["Follow-up — ",oN[F.branchConvergence.status]??F.branchConvergence.status]}),F.branchConvergence.reason&&s.jsx("div",{className:"mt-1",children:F.branchConvergence.reason}),F.branchConvergence.nextStep&&s.jsx("div",{className:`${F.branchConvergence.reason?"mt-1.5 pt-1.5 border-t border-sky-400/20":"mt-1"}`,children:F.branchConvergence.nextStep})]}),$&&s.jsxs("div",{className:m.isDark?"mt-3 rounded-xl border border-emerald-400/20 bg-emerald-500/10 p-3 text-xs text-emerald-100":"mt-3 rounded-xl border border-emerald-300 bg-emerald-50 p-3 text-xs text-emerald-800",children:[s.jsx("div",{className:"font-medium",children:$.phase==="execute"?"Heal result":"Heal preview"}),s.jsx("div",{className:"mt-1",children:$.code??$.error??"No result code returned."})]})]}),V&&(B==null?void 0:B.kind)==="edge"&&s.jsxs("div",{role:"dialog",className:`absolute inset-x-3 bottom-3 top-20 z-20 rounded-2xl border shadow-2xl sm:relative sm:inset-auto sm:z-auto sm:w-72 sm:shrink-0 sm:rounded-none sm:border-0 sm:border-l sm:shadow-none overflow-y-auto p-4 ${m.isDark?"border-white/10 bg-slate-950 sm:bg-transparent":"border-slate-200 bg-white sm:bg-transparent"}`,children:[s.jsx("div",{className:`mb-2 text-[10px] font-semibold uppercase tracking-wide ${m.textMuted}`,children:"Selected edge"}),s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${m.textPrimary}`,children:V.label||td(V)}),s.jsx("div",{className:`mt-0.5 break-all font-mono text-[11px] ${m.textMuted}`,children:V.id})]}),s.jsx("button",{type:"button",onClick:ie,"aria-label":"Close detail panel",className:m.isDark?"shrink-0 rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-xs text-slate-200 transition hover:bg-white/[0.08]":"shrink-0 rounded-full border border-slate-200 bg-white px-2 py-0.5 text-xs text-slate-600 transition hover:bg-slate-50",children:"✕"})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-1.5",children:[s.jsx(Ke,{label:td(V),tone:"default"}),s.jsx(Ke,{label:J1(V),tone:"info"})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(St,{label:"From",value:(pe==null?void 0:pe.label)??V.source}),s.jsx(St,{label:"To",value:(be==null?void 0:be.label)??V.target}),s.jsx(St,{label:"Label",value:V.label??"none"})]})]})]})]})})]})})}function vt(e){return typeof e=="string"?e.trim():""}function ii(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function nl(...e){const t=new Set;for(const r of e){const n=vt(r);n&&t.add(n)}return[...t]}function lN(e,t){var m,h;const r=ii(e==null?void 0:e.settings),n=vt((m=e==null?void 0:e.coordinator)==null?void 0:m.meshId)||vt(r.meshCoordinatorFor),a=vt(r.meshNodeFor),o=!!n||!!a,i=n===t||a===t;if(o&&!i)return null;const c=ii(e==null?void 0:e.activeChat),d=nl(e==null?void 0:e.id,e==null?void 0:e.sessionId,e==null?void 0:e.session_id,e==null?void 0:e.providerSessionId,e==null?void 0:e.provider_session_id,e==null?void 0:e.targetSessionId,e==null?void 0:e.target_session_id,c.sessionId,c.session_id,c.providerSessionId,c.provider_session_id),p=d[0]||"";if(!p)return null;const u=n===t?vt((h=e==null?void 0:e.coordinator)==null?void 0:h.role)||"coordinator":a===t?vt(r.meshNodeRole)||"worker":vt(e==null?void 0:e.role)||vt(r.meshNodeRole)||void 0;return{sessionId:p,aliases:d,meshId:t,nodeId:i&&vt(r.meshNodeId)||null,providerType:vt(e==null?void 0:e.providerType)||void 0,state:vt(e==null?void 0:e.status)||void 0,chatStatus:vt(c.status)||void 0,lifecycle:vt(e==null?void 0:e.runtimeLifecycle)||void 0,surfaceKind:vt(e==null?void 0:e.runtimeSurfaceKind)||void 0,recoveryState:vt(e==null?void 0:e.runtimeRecoveryState)||void 0,...u?{role:u}:{},...i?{isSelfCoordinator:n===t}:{},workspace:vt(e==null?void 0:e.workspace)||null}}function Lm(e,t){var n;return t?(Array.isArray((n=e.status)==null?void 0:n.sessions)?e.status.sessions:[]).map(a=>lN(a,t)).filter(a=>a!==null):[]}function xa(e){return e.aliases&&e.aliases.length>0?e.aliases:[e.sessionId]}function cN(e,t){const r=new Set(xa(t));return xa(e).some(n=>r.has(n))}function dN(e,t){const r=t.filter(a=>!!a);return r.length===0?e:[...e.filter(a=>!r.some(o=>cN(a,o))),...r]}function uN(e,t){if(t.length===0)return e;const r=new Map;for(const i of t)for(const c of xa(i))r.set(c,i);let n=!1;const o=(e.nodes??[]).map((i,c)=>{const d=Array.isArray(i.activeSessionDetails)?i.activeSessionDetails:Array.isArray(i.sessions)?i.sessions:[],p=new Map;for(const h of d){const y=nl(h==null?void 0:h.sessionId,h==null?void 0:h.session_id,h==null?void 0:h.id,h==null?void 0:h.providerSessionId,h==null?void 0:h.provider_session_id),x=y[0]||"";if(!x)continue;const f=y.map(j=>r.get(j)).find(Boolean);f&&(n=!0),p.set(x,f?{...h,sessionId:x,providerType:f.providerType||h.providerType,state:f.state||h.state,chatStatus:f.chatStatus||h.chatStatus,lifecycle:f.lifecycle||h.lifecycle,surfaceKind:f.surfaceKind||h.surfaceKind,recoveryState:f.recoveryState||h.recoveryState,role:f.role||h.role,isSelfCoordinator:f.isSelfCoordinator??h.isSelfCoordinator,workspace:f.workspace||h.workspace}:{...h,sessionId:x})}for(const h of i.activeSessions??[])p.has(h)||p.set(h,{sessionId:h,workspace:i.workspace,isCached:!0});const u=c===0;for(const h of t){if(xa(h).some(j=>p.has(j)))continue;const x=h.nodeId!=null&&h.nodeId===i.nodeId,f=h.isSelfCoordinator&&!h.nodeId&&u;!x&&!f||(n=!0,p.set(h.sessionId,{sessionId:h.sessionId,providerType:h.providerType,state:h.state,chatStatus:h.chatStatus,lifecycle:h.lifecycle,surfaceKind:h.surfaceKind,recoveryState:h.recoveryState,role:h.role,isSelfCoordinator:h.isSelfCoordinator,workspace:h.workspace||i.workspace}))}const m=[...p.values()];return m.length===0?i:{...i,activeSessionDetails:m,activeSessions:m.map(h=>h.sessionId)}});return n?{...e,nodes:o}:e}function pN(e,t){const n=Lm(e,t).map(a=>{var d;const o=(Array.isArray((d=e.status)==null?void 0:d.sessions)?e.status.sessions:[]).find(p=>vt(p==null?void 0:p.id)===a.sessionId),i=ii(o==null?void 0:o.activeInteractivePrompt),c=o!=null&&o.meshQueueStats&&typeof o.meshQueueStats=="object"?JSON.stringify(o.meshQueueStats):"";return[a.sessionId,a.providerType??"",a.state??"",a.chatStatus??"",a.lifecycle??"",a.surfaceKind??"",a.recoveryState??"",vt(i.status)||vt(i.kind)||vt(i.type),a.nodeId??"",a.isSelfCoordinator?"coordinator":"worker",c].join("|")}).filter(a=>!!a).sort();return n.length>0?n.join(`
84
84
  `):null}function Rm({status:e,daemonId:t,extraDaemonIds:r,meshId:n,sendData:a,extraLiveSessions:o=[]}){const[i,c]=l.useState(new Map),d=l.useRef(new Map),p=l.useMemo(()=>{const y=new Set;if(t&&y.add(t),r)for(const x of r)x&&y.add(x);return[...y].sort()},[t,r]),u=p.join(",");l.useEffect(()=>{d.current=new Map,c(new Map)},[t,n]),l.useEffect(()=>{if(!n||!a||p.length===0)return;const y=p.map(x=>rs.subscribe({sendData:a},x,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${x}`,params:{includeSessions:!0}},f=>{if(f.topic!=="daemon.metadata")return;const j=pN(f,n);if(j===(d.current.get(x)??null))return;d.current.set(x,j);const k=Lm(f,n);c(b=>{const w=new Map(b);return w.set(x,k),w})}));return()=>{for(const x of y)x()}},[u,n,a]);const m=l.useMemo(()=>{const y=[];for(const x of i.values())y.push(...x);return y},[i]),h=l.useMemo(()=>dN(m,o),[o,m]);return l.useMemo(()=>e?uN(e,h):null,[h,e])}const sd=[1500,4e3,9e3];function mN(e){var t,r,n,a,o,i;return!!(((t=e.git)==null?void 0:t.isGitRepo)===!0||(r=e.git)!=null&&r.branch||(n=e.git)!=null&&n.upstream||(a=e.git)!=null&&a.headCommit||(o=e.git)!=null&&o.workspace||(i=e.git)!=null&&i.repoRoot)}function hN(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>{var r;return mN(t)?!1:t.gitProbePending||((r=t.connection)==null?void 0:r.state)==="connecting"?!0:t.machineStatus==="online"||t.launchReady===!0})}function fN(e){return!Number.isInteger(e)||e<0?sd[0]:sd[e]??null}const jo=new Map;function xN(e,t){return!e||!t?null:`${e}::${t}`}function bN(e,t){var o,i,c,d;if(!t||!e.sessionId)return null;const r=((o=e.coordinator)==null?void 0:o.meshId)??(typeof((i=e.settings)==null?void 0:i.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null),n=typeof((c=e.settings)==null?void 0:c.meshNodeFor)=="string"?e.settings.meshNodeFor:null;if(r!==t&&n!==t)return null;const a=typeof((d=e.settings)==null?void 0:d.meshNodeId)=="string"?e.settings.meshNodeId:null;return{sessionId:e.sessionId,aliases:nl(e.sessionId,e.providerSessionId,e.historySessionId,e.nativeSessionId),meshId:t,nodeId:a,providerType:e.agentType,state:e.status,chatStatus:e.status,role:r===t?"coordinator":"worker",isSelfCoordinator:r===t,workspace:e.workspacePath??null}}function Pm({activeConv:e,sendDaemonCommand:t,onClose:r}){var J,te,oe,q,F,V;const n=((J=e.coordinator)==null?void 0:J.meshId)??(typeof((te=e.settings)==null?void 0:te.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null),a=e.daemonId??null,o=xN(a,n),i=o?jo.get(o)??null:null,c=Mi(),{sendData:d}=xt(),{theme:p}=Ts(),u=l.useMemo(()=>Ls(p),[p]),[m,h]=l.useState("overview"),[y,x]=l.useState(!1),f=l.useMemo(()=>bN(e,n),[e.agentType,(oe=e.coordinator)==null?void 0:oe.meshId,e.sessionId,(q=e.settings)==null?void 0:q.meshCoordinatorFor,(F=e.settings)==null?void 0:F.meshNodeFor,(V=e.settings)==null?void 0:V.meshNodeId,e.status,e.workspacePath,n]),[j,k]=l.useState(i),[b,w]=l.useState(!1),[I,v]=l.useState(!1),[g,S]=l.useState(!1),[N,C]=l.useState(null),[R,T]=l.useState((i==null?void 0:i.refreshedAt)??null),_=l.useRef(i!==null),P=l.useRef(!1),B=l.useRef(!1),z=l.useRef(!0),A=l.useRef(0),O=l.useRef(null);l.useEffect(()=>{_.current=j!==null},[j]);const $=l.useCallback(()=>{O.current!==null&&(clearTimeout(O.current),O.current=null)},[]);l.useEffect(()=>{$(),A.current=0;const pe=o?jo.get(o)??null:null;k(pe),T((pe==null?void 0:pe.refreshedAt)??null),_.current=pe!==null,B.current=!1,v(!1),C(null)},[o,$]);const L=l.useCallback(async(pe=!1,be=!1)=>{if(!a||!n){C("This coordinator does not expose a live mesh id."),k(null);return}if(P.current){pe&&(B.current=!0);return}be||($(),A.current=0),P.current=!0;const ue=!_.current;w(ue),v(pe&&_.current),C(null);try{const Ne=c!=null&&c.loadMeshStatus?await c.loadMeshStatus(a,n,{refresh:pe,retryProfile:be?"interactive":"settled"}):await t(a,"mesh_status",{meshId:n,refresh:pe}),se=Ti(Ne);if(!se){C("mesh_status returned an unexpected payload.");return}if(o&&jo.set(o,se),k(se),_.current=!0,T(se.refreshedAt||new Date().toISOString()),hN(se.nodes)){const ve=fN(A.current);ve!==null&&z.current&&(A.current+=1,O.current=setTimeout(()=>{z.current&&L(!0,!0)},ve))}else A.current=0}catch(Ne){C(Ne instanceof Error?Ne.message:"Failed to load live mesh status")}finally{P.current=!1,w(!1),v(!1),B.current&&z.current&&(B.current=!1,window.setTimeout(()=>{z.current&&L(!0)},0))}},[o,$,a,n,c,t]);l.useEffect(()=>(z.current=!0,A.current=0,(async()=>(await L(!1,!0),z.current&&O.current===null&&!P.current&&L(!0,!0)))(),()=>{z.current=!1,$()}),[L,$]),l.useEffect(()=>{const pe=be=>{be.key==="Escape"&&r()};return window.addEventListener("keydown",pe),()=>window.removeEventListener("keydown",pe)},[r]);const E=(j==null?void 0:j.meshName)||n||"Repo Mesh",M=l.useMemo(()=>f?[f]:[],[f]),H=Rm({status:j,daemonId:a,meshId:n,sendData:d,extraLiveSessions:M}),Y=R?new Date(R).toLocaleTimeString():null,G=l.useMemo(()=>b?"Loading live mesh status…":"No live mesh graph is available for this coordinator yet.",[b]);return s.jsx("div",{className:u.dialogOverlayClass,onClick:r,children:s.jsxs("div",{role:"dialog","aria-modal":"true",className:u.dialogShellClass,onClick:pe=>pe.stopPropagation(),children:[s.jsxs("div",{className:`relative ${u.dialogHeaderClass}`,children:[s.jsx("button",{type:"button",onClick:r,className:`absolute right-4 top-[calc(16px+env(safe-area-inset-top,0px))] z-10 md:right-5 md:top-1/2 md:-translate-y-1/2 ${u.dialogCloseButtonClass}`,"aria-label":"Close mesh graph",children:s.jsx(wt,{size:16})}),s.jsx("div",{className:"min-w-0 flex-1 pr-12 md:pr-0",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl border border-sky-400/20 bg-sky-500/12 text-sky-200 shadow-[0_12px_30px_rgba(14,165,233,0.18)]",children:s.jsx(ss,{size:18})}),s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("h2",{className:u.dialogTitleClass,children:E}),s.jsx("span",{className:u.dialogKickerClass,children:"Mesh observability"}),s.jsx("button",{type:"button",onClick:()=>S(pe=>!pe),"aria-expanded":g,"aria-label":g?"Hide mesh details":"Show mesh details",className:"btn btn-secondary btn-sm rounded-lg px-1.5 py-1 md:hidden",title:g?"Hide mesh details":"Show mesh details",children:s.jsx(bi,{size:14})})]}),s.jsxs("p",{className:`${u.dialogSubtitleClass} ${g?"block":"hidden"} md:block`,children:[ft(e),e.workspaceName?` · ${e.workspaceName}`:"",j!=null&&j.repoIdentity?` · ${j.repoIdentity}`:""]})]})]})}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 md:justify-end md:pr-12",children:[s.jsx(Tm,{meshTheme:u,activeTab:m,onActiveTabChange:h,helpOpen:y,onHelpOpenChange:x}),Y&&s.jsx("span",{className:`${u.dialogRefreshedChipClass} ${g?"inline-flex":"hidden"} md:inline-flex`,children:`Refreshed ${Y}`}),!I&&j&&s.jsx("span",{className:`${u.dialogRefreshedChipClass} ${g?"inline-flex":"hidden"} md:inline-flex`,children:d&&!N?"Live daemon metadata":"Metadata subscription unavailable"}),s.jsx("button",{type:"button",onClick:()=>{L(!0)},disabled:b||I,className:"btn btn-secondary btn-sm rounded-xl px-3.5",title:"Refresh live mesh graph",children:b||I?"Refreshing…":"Refresh"})]})]}),N&&s.jsx("div",{className:u.isDark?"shrink-0 border-b border-rose-400/20 bg-rose-500/12 px-4 py-2 text-sm text-rose-200 md:px-5":"shrink-0 border-b border-rose-300 bg-rose-50 px-4 py-2 text-sm text-rose-700 md:px-5",children:N}),s.jsx("div",{className:u.dialogBodyClass,children:H?s.jsx(iN,{status:H,emptyMessage:G,daemonId:a,sendDaemonCommand:t,activeTab:m,onActiveTabChange:h,helpOpen:y,onHelpOpenChange:x,hideControls:!0}):s.jsx("div",{className:u.dialogEmptyClass,children:G})})]})})}function gN(e,t){const{sendCommand:r}=xt(),[n,a]=l.useState(null),[o,i]=l.useState(!1);l.useEffect(()=>{if(!e||!t){a(null);return}i(!0),r(e,"git_remote_url",{workspace:t}).then(d=>{const p=(d==null?void 0:d.result)??d;a(typeof(p==null?void 0:p.remoteUrl)=="string"?p.remoteUrl:null)}).catch(()=>{a(null)}).finally(()=>i(!1))},[e,t,r]);const c=yN(n);return{remoteUrl:n,githubUrl:c,loading:o}}function yN(e){if(!e)return null;const t=e.match(/git@github\.com[:/](.+?)(?:\.git)?$/);if(t)return`https://github.com/${t[1]}`;const r=e.match(/https?:\/\/github\.com\/(.+?)(?:\.git)?$/);return r?`https://github.com/${r[1]}`:null}const Dm=5e3;function vN(e){return`git:${e}`}function wN({workspace:e,includeDiffSummary:t=!1,intervalMs:r=Dm}){return{type:"subscribe",topic:"workspace.git",key:vN(e),params:{workspace:e,includeDiffSummary:t,intervalMs:r}}}function al(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Js(e,t){if(e instanceof Error)return e.message;if(e&&typeof e=="object"){const r=e;if(typeof r.error=="string"&&r.error.trim())return r.error;if(typeof r.message=="string"&&r.message.trim())return r.message}return t}function jN(e){const t=al(e);return(t==null?void 0:t.success)===!1?{status:null,error:Js(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:Js(t,"Git status response did not include status")}}function kN(e){const t=al(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:Js(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:Js(t,"Git diff summary response did not include diffSummary")}}function ko(e){return e===void 0||typeof e=="boolean"}function NN(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&ko(t.binary)&&ko(t.truncated)&&ko(t.staged)}function SN(e){const t=al(e);return(t==null?void 0:t.success)===!1?{diff:null,error:Js(t,"Git file diff request failed")}:NN(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:Js(t,"Git file diff response did not include a valid diff object")}}function CN({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=Dm}){const{sendCommand:o,sendData:i}=xt(),c=typeof t=="string"?t.trim():"",d=!!(r&&e&&c),[p,u]=l.useState(null),[m,h]=l.useState(null),[y,x]=l.useState(!1),[f,j]=l.useState(null),k=l.useCallback(async()=>{if(!(!d||!e||!c)){x(!0),j(null);try{const w=jN(await o(e,"git_status",{workspace:c}));if(w.error){u(null),h(null),j(w.error);return}if(u(w.status),!n){h(null);return}const I=kN(await o(e,"git_diff_summary",{workspace:c}));if(I.error){h(null),j(I.error);return}h(I.diffSummary)}catch(w){j(Js(w,"Git status request failed"))}finally{x(!1)}}},[d,e,n,o,c]),b=l.useMemo(()=>c?wN({workspace:c,includeDiffSummary:n,intervalMs:a}):null,[n,a,c]);return l.useEffect(()=>{if(!d||!e||!c||!b){u(null),h(null),x(!1),j(null);return}const w=i?rs.subscribe({sendData:i},e,b,I=>{var v,g;I.workspace===c&&(u(I.status),h(I.diffSummary??null),j(((v=I.status)==null?void 0:v.error)||((g=I.diffSummary)==null?void 0:g.error)||null),x(!1))},{retryIntervalMs:1e3}):null;return k(),()=>{w==null||w()}},[d,e,k,b,i,c]),{status:p,diffSummary:m,loading:y,error:f,refresh:k}}const IN={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},AN={added:"text-status-online",modified:"text-orange-400",deleted:"text-status-error",renamed:"text-accent-primary",copied:"text-accent-primary",untracked:"text-text-muted",conflict:"text-status-error font-bold"};function rd(e){return e.split("/").pop()??e}function MN(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function _N({files:e,truncated:t,onFileClick:r,selectedPath:n,className:a=""}){return e.length===0?s.jsx("p",{className:"px-3 py-2 text-xs text-text-secondary",children:"No changed files."}):s.jsxs("div",{className:`flex flex-col ${a}`,children:[s.jsx("ul",{className:"min-w-0 divide-y divide-border/30",children:e.map(o=>{const i=n===o.path,c=IN[o.status]??"?",d=AN[o.status]??"text-text-muted",p=MN(o.path),u=rd(o.path),m=o.staged?s.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-status-online align-middle",title:"Staged"}):null;return s.jsxs("li",{className:`flex cursor-pointer items-center gap-2 px-3 py-1.5 text-xs hover:bg-surface-elevated/60 ${i?"bg-surface-elevated":""}`,onClick:()=>r==null?void 0:r(o),children:[s.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${d}`,title:o.status,children:c}),s.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[p&&s.jsxs("span",{className:"text-text-secondary",children:[p,"/"]}),s.jsx("span",{className:"text-text-primary",children:u}),o.oldPath&&s.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",rd(o.oldPath)]}),m]}),!o.binary&&(o.insertions>0||o.deletions>0)&&s.jsxs("span",{className:"shrink-0 font-mono text-[10px]",children:[o.insertions>0&&s.jsxs("span",{className:"text-status-online",children:["+",o.insertions]}),o.insertions>0&&o.deletions>0&&s.jsx("span",{className:"text-text-secondary",children:" "}),o.deletions>0&&s.jsxs("span",{className:"text-status-error",children:["-",o.deletions]})]}),o.binary&&s.jsx("span",{className:"shrink-0 text-[10px] text-text-secondary",children:"bin"})]},`${o.path}-${o.staged?"S":"U"}`)})}),t&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary",children:["File list truncated — run ",s.jsx("code",{className:"font-mono",children:"git status"})," locally for full output."]})]})}function TN(e,t){let r="text-text-secondary";return e.startsWith("+")&&!e.startsWith("+++")?r="bg-status-online/10 text-status-online":e.startsWith("-")&&!e.startsWith("---")?r="bg-status-error/10 text-status-error":e.startsWith("@@")?r="text-accent-primary":(e.startsWith("diff ")||e.startsWith("index ")||e.startsWith("--- ")||e.startsWith("+++ "))&&(r="text-text-secondary"),s.jsx("div",{className:`px-3 ${r}`,children:s.jsx("code",{className:"whitespace-pre font-mono text-[11px] leading-5",children:e})},t)}function LN({diff:e,binary:t,truncated:r,loading:n,error:a,className:o=""}){const i=l.useRef(null);if(l.useEffect(()=>{i.current&&(i.current.scrollTop=0)},[e]),n)return s.jsx("div",{className:`flex items-center justify-center py-8 text-xs text-text-secondary ${o}`,children:"Loading diff…"});if(a)return s.jsx("div",{className:`px-3 py-4 text-xs text-status-error ${o}`,children:a});if(t)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${o}`,children:"Binary file — diff not available."});if(!e)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${o}`,children:"No diff available."});const c=e.split(`
85
85
  `);return s.jsxs("div",{ref:i,className:`overflow-auto ${o}`,children:[s.jsx("div",{className:"py-1",children:c.map((d,p)=>TN(d,p))}),r&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary border-t border-border/30",children:["Diff truncated — run ",s.jsx("code",{className:"font-mono",children:"git diff"})," locally for full output."]})]})}function RN(e,t){const r=[`Branch: ${e||"unknown"}`];r.push(`Changed: ${t.files.length} file(s) +${t.totalInsertions}/-${t.totalDeletions}`);const n={};for(const a of t.files)n[a.status]||(n[a.status]=[]),n[a.status].push(a.path);for(const[a,o]of Object.entries(n))r.push(`${a}: ${o.slice(0,5).join(", ")}${o.length>5?` (+${o.length-5} more)`:""}`);return r.join(`
86
86
  `)}function $m({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=xt(),{status:a,diffSummary:o,loading:i,error:c,refresh:d}=CN({daemonId:e,workspace:t,includeDiffSummary:!0}),[p,u]=l.useState(null),[m,h]=l.useState(null),[y,x]=l.useState(""),[f,j]=l.useState(!1),[k,b]=l.useState(!1),[w,I]=l.useState(null),[v,g]=l.useState(null),{githubUrl:S}=gN(e,t),N=l.useCallback(async B=>{if(!((p==null?void 0:p.path)===B.path&&!p.loading)){u({path:B.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const z=await n(e,"git_diff_file",{workspace:t,path:B.path,staged:B.staged}),A=SN(z);if(A.error||!A.diff){u({path:B.path,diff:"",binary:!1,truncated:!1,loading:!1,error:A.error??"Failed to load diff"});return}u({path:B.path,diff:A.diff.diff,binary:A.diff.binary??!1,truncated:A.diff.truncated??!1,loading:!1,error:null})}catch(z){const A=z instanceof Error?z.message:"Failed to load diff";u({path:B.path,diff:"",binary:!1,truncated:!1,loading:!1,error:A})}}},[e,n,p,t]),C=l.useCallback(B=>{x(""),j(!1),I(null),g(null),h(B)},[]),R=l.useCallback(()=>{h(null),I(null),b(!1)},[]),T=l.useCallback(async()=>{var B,z,A;if(m){b(!0),I(null);try{let O;m==="checkpoint"?O=await n(e,"git_checkpoint",{workspace:t,message:y,includeUntracked:f}):m==="stash"?O=await n(e,"git_stash_push",{workspace:t,message:y,includeUntracked:f}):m==="stash_pop"?O=await n(e,"git_stash_pop",{workspace:t}):m==="checkout_files"&&p&&(O=await n(e,"git_checkout_files",{workspace:t,paths:[p.path]}));const $=(O==null?void 0:O.result)??O;if(($==null?void 0:$.success)===!1||$!=null&&$.error){I(($==null?void 0:$.error)??"Action failed"),b(!1);return}m==="checkpoint"?g(`Checkpoint created: ${((z=(B=$==null?void 0:$.checkpoint)==null?void 0:B.commit)==null?void 0:z.slice(0,7))??"done"}`):m==="stash"?g(`Stashed as ${((A=$==null?void 0:$.stash)==null?void 0:A.stashRef)??"stash@{0}"}`):m==="stash_pop"?g("Stash restored"):(g("File reverted"),u(null)),h(null),await d()}catch(O){I(O instanceof Error?O.message:"Action failed")}finally{b(!1)}}},[m,n,e,t,y,f,p,d]),_=!!(a!=null&&a.hasConflicts),P=a?a.staged+a.modified+a.untracked+a.deleted+a.renamed:null;return s.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4",onClick:B=>{B.target===B.currentTarget&&r()},children:s.jsxs("div",{className:"relative flex h-[80vh] w-full max-w-3xl flex-col overflow-hidden rounded-xl border border-border bg-surface shadow-xl",children:[s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-3",children:[s.jsx("span",{"aria-hidden":"true",className:"text-sm",children:"⑂"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"truncate text-sm font-semibold text-text-primary",children:(a==null?void 0:a.branch)??"Git Status"}),s.jsx("p",{className:"truncate text-xs text-text-secondary",children:t}),S&&s.jsx("a",{href:`${S}/tree/${(a==null?void 0:a.branch)||"main"}`,target:"_blank",rel:"noopener noreferrer",className:"truncate text-[10px] text-text-secondary hover:text-accent-primary underline",title:"Open on GitHub",children:"GitHub ↗"})]}),s.jsx("button",{onClick:d,disabled:i,className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40",title:"Refresh",children:"↺"}),s.jsx("button",{onClick:r,className:"rounded p-1 text-text-secondary hover:text-text-primary","aria-label":"Close",children:s.jsx(wt,{className:"h-4 w-4"})})]}),a&&s.jsxs("div",{className:"flex shrink-0 flex-wrap gap-x-4 gap-y-1 border-b border-border/50 px-4 py-2 text-xs text-text-secondary",children:[a.headCommit&&s.jsxs("span",{title:a.headMessage??void 0,children:[s.jsx("span",{className:"font-mono",children:a.headCommit.slice(0,7)}),a.headMessage&&s.jsx("span",{className:"ml-1 truncate",children:a.headMessage.slice(0,60)})]}),a.ahead>0&&s.jsxs("span",{className:"text-orange-400",children:["↑",a.ahead," ahead"]}),a.behind>0&&s.jsxs("span",{className:"text-orange-400",children:["↓",a.behind," behind"]}),a.staged>0&&s.jsxs("span",{className:"text-status-online",children:[a.staged," staged"]}),a.modified>0&&s.jsxs("span",{children:[a.modified," modified"]}),a.untracked>0&&s.jsxs("span",{children:[a.untracked," untracked"]}),a.deleted>0&&s.jsxs("span",{className:"text-status-error",children:[a.deleted," deleted"]}),a.stashCount>0&&s.jsxs("span",{children:[a.stashCount," stashed"]}),a.hasConflicts&&s.jsx("span",{className:"font-bold text-status-error",children:"conflicts"}),P===0&&!a.error&&s.jsx("span",{className:"text-status-online",children:"clean"}),o&&o.files.length>0&&s.jsxs("span",{className:"text-text-secondary",children:[o.files.length," file",o.files.length!==1?"s":"",o.totalInsertions>0&&s.jsxs("span",{className:"text-status-online",children:[" +",o.totalInsertions]}),o.totalDeletions>0&&s.jsxs("span",{className:"text-status-error",children:[" -",o.totalDeletions]})]})]}),c&&s.jsx("div",{className:"shrink-0 border-b border-border/50 bg-status-error/10 px-4 py-2 text-xs text-status-error",children:c}),s.jsxs("div",{className:"flex min-h-0 flex-1",children:[s.jsxs("div",{className:"flex w-56 shrink-0 flex-col overflow-y-auto border-r border-border/50",children:[i&&!o&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"Loading…"}),o&&s.jsx(_N,{files:o.files,truncated:o.truncated,selectedPath:(p==null?void 0:p.path)??null,onFileClick:N}),!i&&!o&&!c&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"No diff data."})]}),s.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:p?s.jsx(LN,{diff:p.diff,binary:p.binary,truncated:p.truncated,loading:p.loading,error:p.error,className:"h-full"}):s.jsx("div",{className:"flex h-full items-center justify-center text-xs text-text-secondary",children:"Select a file to view diff"})})]}),v&&s.jsxs("div",{className:"shrink-0 border-t border-border/50 bg-status-online/10 px-4 py-2 text-xs text-status-online flex items-center justify-between",children:[s.jsx("span",{children:v}),s.jsx("button",{onClick:()=>g(null),className:"ml-2 text-status-online hover:text-text-primary",children:"×"})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-t border-border px-4 py-2",children:[s.jsx("button",{onClick:()=>C("checkpoint"),disabled:_,title:_?"Resolve conflicts before checkpointing":"Create a git commit checkpoint",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkpoint"}),s.jsx("button",{onClick:()=>C("stash"),disabled:_,title:_?"Resolve conflicts before stashing":"Stash current changes",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Stash"}),s.jsx("button",{onClick:()=>C("stash_pop"),disabled:_||!(a!=null&&a.stashCount),title:_?"Resolve conflicts before restoring a stash":a!=null&&a.stashCount?"Restore the latest stash":"No stashes to restore",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Pop stash"}),s.jsx("button",{onClick:()=>C("checkout_files"),disabled:!p,title:p?`Revert changes to ${p.path}`:"Select a file to revert",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkout selected"}),o&&o.files.length>0&&s.jsx("button",{onClick:()=>{const B=RN((a==null?void 0:a.branch)??null,o);navigator.clipboard.writeText(B),g("Copied to clipboard"),setTimeout(()=>g(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),m&&s.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-black/60",children:s.jsxs("div",{className:"flex w-80 flex-col gap-3 rounded-xl border border-border bg-surface p-4 shadow-xl",children:[s.jsxs("p",{className:"text-sm font-semibold text-text-primary",children:[m==="checkpoint"&&"Create checkpoint commit",m==="stash"&&"Stash changes",m==="stash_pop"&&"Restore latest stash?",m==="checkout_files"&&`Revert changes to ${(p==null?void 0:p.path)??"file"}?`]}),(m==="checkpoint"||m==="stash")&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:y,onChange:B=>x(B.target.value),maxLength:200,placeholder:"Message (required)",className:"rounded border border-border bg-surface-secondary px-2 py-1 text-xs text-text-primary placeholder:text-text-secondary focus:outline-none focus:ring-1 focus:ring-border",autoFocus:!0}),s.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:f,onChange:B=>j(B.target.checked)}),"Include untracked files"]})]}),w&&s.jsx("p",{className:"text-xs text-status-error",children:w}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:R,disabled:k,className:"rounded px-3 py-1 text-xs text-text-secondary hover:text-text-primary border border-border/50 disabled:opacity-40",children:"Cancel"}),s.jsx("button",{onClick:T,disabled:k||(m==="checkpoint"||m==="stash")&&!y.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:k?"Working…":"Confirm"})]})]})})]})})}function PN({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=l.useState(!1),[o,i]=l.useState(!1),[c,d]=l.useState(!1),[p,u]=l.useState(!1),[m,h]=l.useState(!1),[y,x]=l.useState("quickstart"),[f,j]=l.useState("workspace"),k=l.useMemo(()=>!t&&!e,[t,e]),b=l.useCallback(N=>{a(N),N&&i(!1)},[]),w=l.useCallback(N=>{i(N),N&&a(!1)},[]),I=l.useCallback(()=>{x(r===0?"quickstart":"shortcuts"),j("workspace"),d(!0),a(!1),i(!1)},[r]),v=l.useCallback(()=>{d(!1)},[]),g=l.useCallback(()=>{u(!0)},[]),S=l.useCallback(()=>{u(!1)},[]);return l.useEffect(()=>{if(!k){h(!1);return}h(!0);const N=window.setTimeout(()=>{h(!1)},1e4);return()=>window.clearTimeout(N)},[k]),{inboxOpen:n,hiddenOpen:o,shortcutHelpOpen:c,newSessionOpen:p,guideNudgeVisible:m,guideTab:y,shortcutSection:f,isDesktopDashboard:k,setGuideTab:x,setShortcutSection:j,handleInboxOpenChange:b,handleHiddenOpenChange:w,handleOpenShortcutHelp:I,closeShortcutHelp:v,openNewSession:g,closeNewSession:S}}function DN(e){switch(e.id){case"triggerPrimaryApprovalAction":case"triggerSecondaryApprovalAction":case"triggerTertiaryApprovalAction":return"approvals";case"splitActiveTabRight":case"splitActiveTabDown":case"focusLeftPane":case"focusRightPane":case"focusUpPane":case"focusDownPane":case"moveActiveTabToLeftPane":case"moveActiveTabToRightPane":case"moveActiveTabToUpPane":case"moveActiveTabToDownPane":return"panes";default:return"workspace"}}function $N(e){return e instanceof Error?e.message:String(e||"")}function EN(e){const t=$N(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function BN({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:o,onOpenRemote:i,onStopCli:c,activeCliViewMode:d,onSetActiveCliViewMode:p,mobileChatConversations:u,hiddenConversations:m,ides:h,actionLogs:y,sendDaemonCommand:x,setActionLogs:f,setCliViewModeOverrides:j,isStandalone:k,initialDataLoaded:b,userName:w,requestedMobileTabKey:I,onRequestedMobileTabConsumed:v,requestedMachineId:g,onRequestedMachineConsumed:S,requestedMobileSection:N,onRequestedMobileSectionConsumed:C,containerRef:R,isSplitMode:T,numGroups:_,groupSizes:P,groupedConvs:B,clearedTabs:z,focusedGroup:A,focusGroup:O,moveTabToGroup:$,splitTabRelative:L,closeGroup:E,handleResizeStart:M,groupActiveTabIds:H,setGroupActiveTab:Y,groupTabOrders:G,setGroupTabOrder:J,toggleHiddenTab:te,visibleConversations:oe,requestedDesktopTabKey:q,onRequestedDesktopTabConsumed:F,onDesktopActiveTabChange:V,onRequestScrollToBottom:pe,onHideConversation:be,onShowHiddenConversation:ue,onShowAllHiddenConversations:Ne,scrollToBottomRequest:se,machineEntries:ve,layoutProfile:me,onBrowseMachineDirectory:U,onSaveMachineWorkspace:W,onLaunchMachineIde:Z,onLaunchMachineProvider:ie,onListMachineMeshes:ye,onLaunchMeshCoordinator:fe,onListMachineSavedSessions:D,notifications:he,notificationUnreadCount:Se,liveSessionInboxState:ae,onMarkNotificationRead:Q,onMarkNotificationUnread:we,onDeleteNotification:ke}){const Le=It.useRef(null),{inboxOpen:We,hiddenOpen:ce,shortcutHelpOpen:Ee,newSessionOpen:Be,guideNudgeVisible:Je,guideTab:qe,shortcutSection:je,isDesktopDashboard:at,setGuideTab:Ie,setShortcutSection:ot,handleInboxOpenChange:nt,handleHiddenOpenChange:Qe,handleOpenShortcutHelp:Lt,closeShortcutHelp:X,openNewSession:ee,closeNewSession:re}=PN({isMobile:t,showMobileChatMode:e,visibleConversationCount:oe.length}),[le,xe]=It.useState(null),[Ae,De]=It.useState(null),Ce=It.useCallback((Te,Ve)=>{xe({daemonId:Te,workspace:Ve})},[]),Re=It.useCallback(Te=>{De(Te)},[]),He=It.useCallback(Te=>{var Ve;dr.flushSync(()=>{ue(Te)}),(Ve=Le.current)==null||Ve.restoreHiddenTabToSavedLocation(Te.tabKey)},[ue]),Xe=It.useCallback(Te=>{var Rt;const Ve=u.find(jt=>Ko(jt,Te))||m.find(jt=>Ko(jt,Te));Ve&&(m.some(jt=>jt.tabKey===Ve.tabKey)&&He(Ve),V(Ve.tabKey),(Rt=Le.current)==null||Rt.activateConversationTab(Ve.tabKey),pe(Ve.tabKey,"notification-open")),Q(Te.id),nt(!1)},[He,m,u,V,Q,pe]),Oe=It.useCallback(()=>{var Ve;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Ve=Le.current)==null||Ve.resetAllPanelsToMain(),Qe(!1))},[Qe]),Ue=It.useCallback(async Te=>{var Ut;if(!r)return;const Ve=(Ut=r.modalButtons)==null?void 0:Ut[Te];if(!Ve)return;const Rt=Hs(r);if(!Rt)return;const jt=Ve.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),Kt=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(jt);try{await x(Rt,"resolve_action",{button:Ve,action:Kt?"approve":"reject",buttonIndex:Te,...Os(r)})}catch(zt){EN(zt)||console.error("[Shortcut approval] Failed:",zt)}},[r,x]),{isMac:ne,actionDefinitions:de,actionShortcuts:ge,shortcutListening:$e,shortcutListeningDraft:Fe,setShortcutListening:Ye,setShortcutListeningDraft:Ze,saveShortcuts:rt}=mj({enabled:at&&!Ee,onTrigger:Te=>{var Ve,Rt,jt,Kt,Ut,zt,is,K,Me,Pe,dt,Et,Rs,Mt,vs,ws;if(Te==="openShortcutHelp"){Lt();return}if(Te==="openNewSession"){ee();return}if(Te==="hideCurrentTab"){r&&be(r);return}if(Te==="toggleHiddenTabs"){Qe(!ce);return}if(Te==="openHistoryForActiveTab"){r&&!it(r)&&o(r);return}if(Te==="openRemoteForActiveTab"){r&&!lt(r)&&!it(r)&&i(r);return}if(Te==="splitActiveTabRight"){(Ve=Le.current)==null||Ve.splitActiveTabRight();return}if(Te==="splitActiveTabDown"){(Rt=Le.current)==null||Rt.splitActiveTabDown();return}if(Te==="floatActiveTab"){(jt=Le.current)==null||jt.floatActiveTab();return}if(Te==="popoutActiveTab"){(Kt=Le.current)==null||Kt.popoutActiveTab();return}if(Te==="dockActiveTab"){(Ut=Le.current)==null||Ut.dockActiveTab();return}if(Te==="focusLeftPane"){(zt=Le.current)==null||zt.focusLeftPane();return}if(Te==="focusRightPane"){(is=Le.current)==null||is.focusRightPane();return}if(Te==="focusUpPane"){(K=Le.current)==null||K.focusUpPane();return}if(Te==="focusDownPane"){(Me=Le.current)==null||Me.focusDownPane();return}if(Te==="moveActiveTabToLeftPane"){(Pe=Le.current)==null||Pe.moveActiveTabToLeftPane();return}if(Te==="moveActiveTabToRightPane"){(dt=Le.current)==null||dt.moveActiveTabToRightPane();return}if(Te==="moveActiveTabToUpPane"){(Et=Le.current)==null||Et.moveActiveTabToUpPane();return}if(Te==="moveActiveTabToDownPane"){(Rs=Le.current)==null||Rs.moveActiveTabToDownPane();return}if(Te==="triggerPrimaryApprovalAction"){Ue(0);return}if(Te==="triggerSecondaryApprovalAction"){Ue(1);return}if(Te==="triggerTertiaryApprovalAction"){Ue(2);return}if(Te==="setActiveTabShortcut"){(Mt=Le.current)==null||Mt.setShortcutForActiveTab();return}if(Te==="selectPreviousGroupTab"){(vs=Le.current)==null||vs.activatePreviousTabInGroup();return}if(Te==="selectNextGroupTab"){(ws=Le.current)==null||ws.activateNextTabInGroup();return}!r||!lt(r)||it(r)||Te==="toggleCliView"&&p(d==="chat"?"terminal":"chat")}}),Ge=It.useCallback(()=>{X(),Ye(null),Ze([])},[X,Ye,Ze]),Nt=It.useMemo(()=>je==="all"?de:de.filter(Te=>DN(Te)===je),[de,je]),Jt=It.useCallback(()=>{const Te=Object.fromEntries(de.map(Ve=>[Ve.id,""]));rt(Te)},[de,rt]),Ht=It.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const Te=Object.fromEntries(de.map(Ve=>[Ve.id,Ve.defaultShortcut]));rt(Te)},[de,rt]);return It.useEffect(()=>{const Te=Ve=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Ve.metaKey&&Ve.key.toLowerCase()==="w":Ve.ctrlKey&&Ve.key.toLowerCase()==="w")&&(Ve.preventDefault(),r&&be&&be(r))};return window.addEventListener("keydown",Te),()=>window.removeEventListener("keydown",Te)},[r,be]),It.useEffect(()=>{if(!Ee||$e)return;const Te=Ve=>{Ve.key==="Escape"&&(Ve.preventDefault(),Ge())};return window.addEventListener("keydown",Te,!0),()=>window.removeEventListener("keydown",Te,!0)},[Ge,Ee,$e]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(Qy,{activeConv:r,wsStatus:n,isConnected:a,conversations:oe,hiddenConversations:m,onOpenHistory:o,onHideConversation:be,onShowConversation:He,onShowAllHidden:Ne,onResetPanelsToMain:Oe,notifications:he,notificationUnreadCount:Se,onOpenNotification:Xe,onMarkNotificationRead:Q,onMarkNotificationUnread:we,onDeleteNotification:ke,inboxOpen:We,onInboxOpenChange:nt,hiddenOpen:ce,onHiddenOpenChange:Qe,onOpenNewSession:t?void 0:ee,onOpenDashboardGuide:Lt,guideNudgeVisible:Je,actionShortcuts:ge,onOpenRemote:()=>{!r||lt(r)||it(r)||i(r)},onStopCli:c,activeCliViewMode:d,onSetCliViewMode:p,onOpenGitDialog:Ce,onOpenMeshGraph:Re}),e?s.jsx(tj,{conversations:u,hiddenConversations:m,ides:h,actionLogs:y,sendDaemonCommand:x,setActionLogs:f,setCliViewModeOverrides:j,isStandalone:k,userName:w,requestedActiveTabKey:I,onRequestedActiveTabConsumed:v,requestedMachineId:g,onRequestedMachineConsumed:S,requestedMobileSection:N,onRequestedMobileSectionConsumed:C,onOpenHistory:o,onOpenRemote:i,onStopCli:c,wsStatus:n,isConnected:a,onShowAllHiddenConversations:Ne,onHideConversation:be,onOpenMeshGraph:Re,onOpenNewSession:ee,liveSessionInboxState:ae}):t?s.jsx(cj,{containerRef:R,isSplitMode:T,numGroups:_,groupSizes:P,groupedConvs:B,clearedTabs:z,ides:h,actionLogs:y,sendDaemonCommand:x,setActionLogs:f,isStandalone:k,hasRegisteredMachines:ve.length>0,userName:w,focusedGroup:A,focusGroup:O,moveTabToGroup:$,splitTabRelative:L,closeGroup:E,handleResizeStart:M,groupActiveTabIds:H,setGroupActiveTab:Y,groupTabOrders:G,setGroupTabOrder:J,toggleHiddenTab:te,onOpenNewSession:ee,allowTabShortcuts:!1,liveSessionInboxState:ae}):s.jsx(Ij,{visibleConversations:oe,clearedTabs:z,ides:h,actionLogs:y,sendDaemonCommand:x,setActionLogs:f,isStandalone:k,hasRegisteredMachines:ve.length>0,initialDataLoaded:b,userName:w,toggleHiddenTab:te,actionShortcuts:ge,registerActionHandlers:Te=>{Le.current=Te},onActiveTabChange:V,requestedActiveTabKey:q,onRequestedActiveTabConsumed:F,onRequestScrollToBottom:pe,scrollToBottomRequest:se,onOpenNewSession:ee,liveSessionInboxState:ae,layoutProfile:me}),Be&&s.jsx(Ej,{machines:ve,ides:h,onClose:re,onBrowseDirectory:U,onSaveWorkspace:W,onLaunchIde:Z,onLaunchProvider:ie,onListMeshes:ye,onLaunchMeshCoordinator:fe,onListSavedSessions:D}),Ae&&s.jsx(Pm,{activeConv:Ae,sendDaemonCommand:x,onClose:()=>De(null)}),le&&s.jsx($m,{daemonId:le.daemonId,workspace:le.workspace,onClose:()=>xe(null)}),Ee&&s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:Ge,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl w-[min(560px,calc(100vw-32px))] max-h-[min(80vh,720px)] overflow-y-auto px-6 py-5 shadow-xl",onClick:Te=>Te.stopPropagation(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Dashboard guide"}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"A quick guide to the dashboard flow, floating and popout tabs, plus grouped shortcuts you can tune."})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center justify-center w-8 px-0",onClick:Ge,"aria-label":"Close dashboard guide",children:s.jsx(wt,{size:14})})]}),s.jsx("div",{className:"flex gap-2 mb-4 overflow-x-auto",children:[{id:"overview",label:"Overview"},{id:"quickstart",label:"Quick start"},{id:"shortcuts",label:"Shortcuts"}].map(Te=>s.jsx("button",{type:"button",className:`btn btn-sm ${qe===Te.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ie(Te.id),children:Te.label},Te.id))}),qe==="overview"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"What lives where"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Tabs:"})," active sessions across IDE, CLI, and ACP agents."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Hidden tabs:"})," stash sessions you do not want in the main strip but still want to keep around."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Activity inbox:"})," sessions waiting for approval or finished tasks you have not reviewed yet."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"CLI view toggle:"})," switch a PTY session between terminal and chat rendering without relaunching it."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Useful flows"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Review notifications:"})," open the inbox, jump to the session, then use the conversation or approval controls directly from the active pane."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Reduce clutter:"})," hide less important sessions instead of closing them, then restore from hidden tabs when needed."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Split work:"})," keep one pane active for input and let secondary panes stay read-only until you focus them."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Detached views:"})," float a tab for quick side-by-side work, or pop it into a new window when you want a separate monitor."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Docking:"})," use Dock to bring a floating tab back into the grid, or move a popped out tab back to the main dashboard."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Per-tab shortcuts:"})," right-click a Dockview tab to assign a direct shortcut for that specific session."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Approval buttons:"})," use ",ne?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),qe==="quickstart"&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Desktop quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Start from the machine or workspace flow first. Pick or save a workspace before launching CLI or ACP sessions."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Keep the main strip focused on active work and push overflow into Hidden tabs."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Use the inbox for approval-required or completed sessions instead of scanning every tab."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"4."})," Split only when you need parallel reading; float or pop out a tab when you want to detach it without losing the main layout."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Mobile quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Stay in chat mode for review and replies; use workspace mode mainly to launch or reopen sessions."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Start from the machine screen, choose a workspace, then launch IDE, CLI, or ACP from there."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Treat mobile as the simpler control surface: no split workflow, fewer tab mechanics, faster session switching."]})]})]})]}),qe==="shortcuts"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"all",label:"All"},{id:"workspace",label:"Workspace"},{id:"panes",label:"Panes"},{id:"approvals",label:"Approvals"}].map(Te=>s.jsx("button",{type:"button",className:`btn btn-sm ${je===Te.id?"btn-primary":"btn-secondary"}`,onClick:()=>ot(Te.id),children:Te.label},Te.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Jt,children:"Disable all"}),s.jsx("button",{type:"button",className:"btn btn-sm",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, var(--border-subtle, transparent))",background:"color-mix(in srgb, var(--status-error, #ef4444) 8%, var(--bg-primary, transparent))"},onClick:Ht,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:Nt.map(Te=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${$e===Te.id?"border-accent bg-bg-secondary/70":"border-border-subtle bg-bg-secondary/30"}`,children:s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Te.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Te.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:Te.defaultShortcut})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[s.jsx("span",{className:"text-[11px] font-mono px-2 py-1 rounded bg-surface-secondary border border-border-subtle min-w-[72px] text-center",children:$e===Te.id?Fe.length>0?`${Fe.join(" ")} ...`:"Listening...":ge[Te.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{Ye(Te.id),Ze([])},children:$e===Te.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Ve={...ge};Ve[Te.id]="",rt(Ve)},children:"Disable"})]})]})},Te.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",ne?"⌘⇧Enter, ⌘⇧→, ⌘Ctrl⇧↓":"Ctrl+Shift+Enter, Ctrl+Shift+→, Ctrl+Alt+Shift+↓",", or set your own combo. Dashboard action shortcuts are ignored while typing in text inputs."]})]})]})})]})}const FN=[{icon:"🦦",title:"Welcome to ADHDev",desc:"Drive any local CLI coding agent — Claude Code, Codex, Gemini — straight from your browser or phone. The agents keep running on your machine; you control them from the web.",visual:"🎉"},{icon:"💬",title:"Real-time chat",desc:"See what your AI agent is doing in real-time. Send messages, approve or reject actions — all from your browser or phone.",visual:"📱"},{icon:"👀",title:"Watch and steer, live",desc:"Follow each agent's session in real time and steer it as it works — switch sessions, take screenshots, and (for IDE sessions) view and control the screen over a P2P connection.",visual:"🖱️"},{icon:"🕸️",title:"Orchestrate your agents",desc:"Repo Mesh (Cloud Pro) lets one coordinator hand work to agents across many machines — parallel git worktrees, automatic branch convergence, and cross-checking the same repo from several angles.",visual:"🕸️"}],ON={icon:"🚀",title:"Get started",desc:"Run this on any machine you want to drive, then sign in — the daemon pairs itself to your dashboard automatically.",code:"curl -fsSL https://adhf.dev/install | sh"},HN={icon:"🚀",title:"You're all set",desc:"This dashboard is already connected to your local daemon. Start a session from the Dashboard tab, or add more providers under Burrow → Providers.",visual:"✅"};function WN({onClose:e,standalone:t=!1}){const[r,n]=l.useState(0),a=[...FN,t?HN:ON],o=a[r],i=r===a.length-1;return s.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:"var(--z-modal)",background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.3s ease-out"},onClick:c=>{c.stopPropagation()},children:[s.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[s.jsx("button",{onClick:e,className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:s.jsx(wt,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:a.map((c,d)=>s.jsx("div",{style:{width:d===r?24:8,height:8,borderRadius:4,background:d===r?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},d))}),s.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:o.visual||o.icon}),s.jsxs("div",{style:{textAlign:"center"},children:[s.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[s.jsx("span",{children:o.icon})," ",o.title]}),s.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:o.desc}),o.code&&s.jsxs("div",{style:{background:"var(--bg-primary, #111)",border:"1px solid var(--border-subtle, #333)",borderRadius:"0.5rem",padding:"0.75rem 1rem",fontFamily:"monospace",fontSize:"0.8rem",color:"var(--accent, #a78bfa)",textAlign:"left",overflowX:"auto",marginBottom:"0.5rem"},children:[s.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),o.code]}),i&&s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.75rem",color:"var(--accent, #a78bfa)",textDecoration:"none"},children:"📚 Learn more in the docs →"})]}),s.jsx("div",{className:"flex justify-end items-center mt-6",children:s.jsx("button",{onClick:()=>i?e():n(c=>c+1),className:"btn btn-primary",children:i?"Get Started →":"Next →"})})]}),s.jsx("style",{children:`
@@ -111,6 +111,6 @@ The newest runtime for each provider session will be kept and older duplicates w
111
111
  from { opacity: 0; transform: translateX(40px); }
112
112
  to { opacity: 1; transform: translateX(0); }
113
113
  }
114
- `})]})}function lC({daemonIds:e,meshId:t,sendData:r,onRevisionAdvance:n}){const a=l.useRef(new Map),o=l.useRef(n);o.current=n;const i=[...new Set(e.filter(Boolean))].sort().join(",");l.useEffect(()=>{a.current=new Map},[i,t]),l.useEffect(()=>{if(!t||!r)return;const c=[...new Set(e.filter(Boolean))];if(c.length===0)return;const d=c.map(p=>rs.subscribe({sendData:r},p,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${p}`,params:{includeSessions:!0}},u=>{if(u.topic!=="daemon.metadata")return;const m=u.meshStateRevisions;if(!m)return;const h=m[t]??m["*"];if(typeof h!="number")return;const y=a.current.get(p);a.current.set(p,h),y!==void 0&&h>y&&o.current()}));return()=>{for(const p of d)p()}},[i,t,r])}const cC={meshHostDaemonSection:!1,createDaemonPicker:!1,addNodeDaemonPicker:!1,queueSection:!0,coordinatorPrompt:!0,nodeInstruction:!0,hermesMcpConfig:!0,reviewInbox:!0},Fm=l.createContext(null);function dC(){const e=l.useContext(Fm);if(!e)throw new Error("useRepoMeshContext must be used inside RepoMeshProvider");return e}function uC({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("polyline",{points:"1 20 1 14 7 14"}),s.jsx("path",{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"})]})}function pC({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),s.jsx("circle",{cx:"18",cy:"6",r:"3"}),s.jsx("circle",{cx:"6",cy:"18",r:"3"}),s.jsx("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}function mC({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("polyline",{points:"3 6 5 6 21 6"}),s.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]})}function hC({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function fC({status:e}){const r={online:{color:"#22c55e",label:"Online"},dirty:{color:"#f59e0b",label:"Dirty",title:"Workspace has uncommitted changes"},offline:{color:"#6b7280",label:"Offline"},degraded:{color:"#ef4444",label:"Degraded",title:"P2P connection to this node is down or timed out — often transient. Wait and retry, or re-establish the node's connection."},enabled:{color:"#22c55e",label:"Enabled"},pending:{color:"#a855f7",label:"Pending"},assigned:{color:"#3b82f6",label:"Assigned"},completed:{color:"#22c55e",label:"Completed"},failed:{color:"#ef4444",label:"Failed"},unknown:{color:"#6b7280",label:"Unknown"}}[e]||{color:"#6b7280",label:e};return s.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] font-semibold px-2 py-0.5 rounded-md",style:{background:r.color+"15",color:r.color,border:`1px solid ${r.color}25`},title:r.title,children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full",style:{background:r.color}}),r.label]})}function xC(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function bC({meshes:e,loading:t,error:r,onDismissError:n,daemons:a,features:o,showCreate:i,onToggleCreate:c,createName:d,onCreateNameChange:p,createRepoIdentity:u,onCreateRepoIdentityChange:m,createRepoRemoteUrl:h,onCreateRepoRemoteUrlChange:y,newMeshDaemonId:x,onNewMeshDaemonIdChange:f,newMeshWorkspace:j,onNewMeshWorkspaceChange:k,createPickerWorkspaces:b,onSelectMesh:w,onCreate:I,onCancelCreate:v}){return s.jsxs(mn,{icon:s.jsx(ss,{}),title:"Repo Meshes",subtitle:`${e.length} mesh${e.length!==1?"es":""}`,widthClassName:"max-w-5xl",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:c,children:"+ Create Mesh"}),children:[r&&s.jsx(Ft,{variant:"error",onDismiss:n,className:"mb-4",children:r}),i&&s.jsxs(mt,{className:"mb-5 border-accent/40 animate-[fadeIn_0.3s_ease-out]",children:[s.jsx("h3",{className:"text-base font-bold mb-4",children:"Create Repo Mesh"}),o.createDaemonPicker&&s.jsx(vt,{label:"Create on machine",hint:"Mesh setup is stored by the selected daemon.",children:s.jsx("select",{className:"input w-full",value:x,onChange:g=>f(g.target.value),disabled:!a.length,children:a.length===0?s.jsx("option",{value:"",children:"No connected daemon"}):a.map(g=>s.jsx("option",{value:g.id,children:xC(g)},g.id))})}),o.createDaemonPicker&&s.jsx(vt,{label:"Workspace",hint:"Choose from workspaces registered by the selected daemon.",children:s.jsx("select",{className:"input w-full",value:j,onChange:g=>k(g.target.value),disabled:!x||!b.length,children:x?b.length===0?s.jsx("option",{value:"",children:"No registered workspaces"}):b.map(g=>s.jsx("option",{value:g.path,children:g.label?`${g.label} · ${g.path}`:g.path},g.id||g.path)):s.jsx("option",{value:"",children:"Select a machine first"})})}),s.jsx(vt,{label:"Name",children:s.jsx(ts,{value:d,onChange:g=>p(g.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(vt,{label:"Repo remote URL (optional)",hint:"Provide a remote URL OR a stable identity.",children:s.jsx(ts,{value:h,onChange:g=>y(g.target.value),placeholder:"https://github.com/user/repo"})}),s.jsx(vt,{label:"Repo identity (optional)",hint:"Provide a remote URL OR a stable identity.",children:s.jsx(ts,{value:u,onChange:g=>m(g.target.value),placeholder:"github.com/user/repo"})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:I,disabled:!d.trim()||!h.trim()&&!u.trim()||o.createDaemonPicker&&(!x||!j),children:"Create"}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:v,children:"Cancel"})]})]}),t?s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):e.length===0?s.jsx(Ma,{icon:s.jsx(ss,{}),title:"No Repo Meshes",description:a.length>0?"Create a mesh to get started.":"Connect an ADHDev daemon first.",action:s.jsx("button",{className:"btn btn-primary btn-sm",disabled:!a.length,onClick:c,children:"Create First Mesh"})}):s.jsx("div",{className:"flex flex-col gap-2.5",children:e.map(g=>{var S;return s.jsx("button",{type:"button",onClick:()=>w(g.id),className:"w-full text-left bg-bg-glass border border-border-subtle rounded-xl px-5 py-4 transition-colors hover:border-border-default hover:bg-bg-secondary/70",children:s.jsxs("div",{className:"flex justify-between items-start",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx(ss,{size:16}),s.jsx("span",{className:"font-bold text-sm",children:g.name})]}),s.jsxs("div",{className:"text-[12px] text-text-muted flex items-center gap-2",children:[s.jsx("span",{className:"font-mono",children:g.repoIdentity||g.repo_identity||"No repo identity"}),(g.defaultBranch||g.default_branch)&&s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(pC,{size:11}),g.defaultBranch||g.default_branch]})]})]}),s.jsxs("div",{className:"text-right text-[11px] text-text-muted shrink-0 ml-4",children:[s.jsx("div",{children:new Date(g.createdAt||g.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})}),s.jsxs("div",{className:"text-text-muted/60",children:[((S=g.nodes)==null?void 0:S.length)??g.nodeCount??0," node(s)"]})]})]})},g.id)})})]})}const gC=["claude-cli","codex-cli","gemini-cli","hermes-cli","antigravity-cli"],yC=[{kind:"rca",label:"Root-cause analysis",hint:"rca"},{kind:"design",label:"Design / approach review",hint:"design"},{kind:"claim_audit",label:"Verify specific claims",hint:"claim_audit"},{kind:"freeform",label:"Freeform review",hint:"freeform"}];function vC(){return{nodeId:"",provider:"",model:"",n:""}}function hd(e){var t;return(t=e.providers)!=null&&t.length?e.providers.filter(Boolean):(e.providerPriority??[]).filter(Boolean)}function wC(e){return{nodeId:e.nodeId??"",provider:e.provider??"",model:e.model??"",n:e.n!=null?String(e.n):""}}function jC(e){const t=[];for(let r=0;r<e.length;r++){const n=e[r],a=n.provider.trim();if(!a)return{error:`Slot ${r+1}: provider is required`};const o=n.nodeId.trim(),i=n.model.trim(),c=n.n.trim();let d;if(c){const p=Number(c);if(!Number.isFinite(p)||p<1)return{error:`Slot ${r+1}: replica count must be ≥ 1`};d=Math.floor(p)}t.push({provider:a,...o?{nodeId:o}:{},...i?{model:i}:{},...d!==void 0?{n:d}:{}})}return t.length===0?{error:"A kind binding needs at least one slot"}:{slots:t}}function kC({status:e,daemonId:t,sendDaemonCommand:r,availableProviders:n}){const{theme:a}=Ts(),o=l.useMemo(()=>Ls(a),[a]),i=l.useMemo(()=>cp(n),[n]),[c,d]=l.useState({}),[p,u]=l.useState(!1),[m,h]=l.useState(null),[y,x]=l.useState({}),[f,j]=l.useState(null),k=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(L=>({nodeId:L.nodeId,machineLabel:L.machineLabel,providers:L.providers,providerPriority:L.providerPriority})),[e==null?void 0:e.nodes]),b=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(L=>L.nodeId),[e==null?void 0:e.nodes]),w=l.useMemo(()=>Object.fromEntries(((e==null?void 0:e.nodes)??[]).map(L=>[L.nodeId,L.machineLabel||L.nodeId])),[e==null?void 0:e.nodes]),I=l.useMemo(()=>{const L={};for(const E of k)L[E.nodeId]=hd(E);return L},[k]),v=l.useMemo(()=>{const L=[...new Set(k.flatMap(hd).filter(Boolean))];return[...new Set([...L,...gC])].sort()},[k]),g=!!t&&!!r,S=L=>L&&typeof L=="object"&&"result"in L?L.result:L,N=l.useCallback(async()=>{if(!(!t||!r)){u(!0),h(null);try{const L=await r(t,"magi_kind_panel_list",{}),E=S(L);if((E==null?void 0:E.success)===!1)throw new Error(E.error||"Failed to load kind panels");d(E!=null&&E.kindPanels&&typeof E.kindPanels=="object"?E.kindPanels:{}),x({})}catch(L){h((L==null?void 0:L.message)||"Failed to load kind panels")}finally{u(!1)}}},[t,r]);l.useEffect(()=>{N()},[N]);const C=l.useCallback(L=>{if(y[L])return y[L];const E=c[L];return E?E.map(wC):[]},[y,c]),R=(L,E)=>{x(M=>({...M,[L]:E}))},T=(L,E,M)=>{const H=C(L);R(L,H.map((Y,G)=>G===E?{...Y,...M}:Y))},_=L=>{R(L,[...C(L),vC()])},P=(L,E)=>{R(L,C(L).filter((M,H)=>H!==E))},B=l.useCallback(async L=>{if(!t||!r)return;const E=jC(C(L));if("error"in E){h(`${L}: ${E.error}`);return}j(L),h(null);try{const M=await r(t,"magi_kind_panel_set",{kind:L,slots:E.slots}),H=S(M);if((H==null?void 0:H.success)===!1)throw new Error(H.error||"Failed to save kind binding");await N()}catch(M){h((M==null?void 0:M.message)||"Failed to save kind binding")}finally{j(null)}},[t,r,C,N]),z=l.useCallback(async L=>{if(!(!t||!r)&&confirm(`Remove the MAGI panel binding for "${L}"?`)){j(L),h(null);try{const E=await r(t,"magi_kind_panel_remove",{kind:L}),M=S(E);if((M==null?void 0:M.success)===!1)throw new Error(M.error||"Failed to remove kind binding");await N()}catch(E){h((E==null?void 0:E.message)||"Failed to remove kind binding")}finally{j(null)}}},[t,r,N]),A=`w-full rounded-lg border px-2.5 py-1.5 text-xs ${o.isDark?"border-white/10 bg-slate-950/40 text-slate-100 placeholder:text-slate-500":"border-slate-300 bg-white text-slate-900 placeholder:text-slate-400"}`,O="btn btn-primary btn-sm",$="btn btn-secondary btn-sm";return s.jsxs("div",{className:"flex flex-col gap-3 p-1",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("p",{className:`text-[12px] ${o.textSecondary}`,children:"Pick which agents review each task type. Add one row per agent."}),s.jsx("div",{className:"ml-auto flex items-center gap-2",children:s.jsx("button",{type:"button",className:$,onClick:()=>void N(),disabled:p||!g,children:p?"Loading…":"Refresh"})})]}),!g&&s.jsx("div",{className:`rounded-xl border p-3 text-[12px] ${o.textSecondary} ${o.isDark?"border-white/10":"border-slate-200"}`,children:"Connect to a coordinator daemon to manage kind → panel bindings."}),m&&s.jsx("div",{className:"rounded-xl border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-[12px] text-rose-300",children:m}),s.jsx("div",{className:"flex flex-col gap-3",children:yC.map(({kind:L,label:E,hint:M})=>{const H=C(L),Y=!!c[L],G=f===L;return s.jsxs("div",{className:`${o.cardClass} rounded-2xl p-4 flex flex-col gap-3`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[13px] font-semibold ${o.textPrimary}`,children:E}),s.jsx("span",{className:`font-mono text-[10px] ${o.textMuted}`,children:M}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${Y?"border-emerald-400/30 bg-emerald-500/10 text-emerald-300":"border-slate-400/20 bg-slate-500/10 text-slate-300"}`,children:Y?`${c[L].length} agent${c[L].length===1?"":"s"}`:"off"})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[H.length===0&&s.jsx("div",{className:`rounded-xl border p-2.5 text-[11px] ${o.textSecondary} ${o.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:"No agents yet — add one to enable this review type."}),H.map((J,te)=>{const oe=J.nodeId?I[J.nodeId]??[]:[],q=J.nodeId&&oe.length?oe:v;return s.jsxs("div",{className:`rounded-xl border p-2.5 grid grid-cols-1 sm:grid-cols-[1fr_1fr_1fr_auto_auto] gap-x-2 gap-y-1 items-start ${o.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${o.textSecondary}`,children:"Machine"}),s.jsxs("select",{className:A,value:J.nodeId,onChange:F=>T(L,te,{nodeId:F.target.value}),title:"Which machine runs this agent. Leave on “any” to let the coordinator route by tags.",children:[s.jsx("option",{value:"",children:"Any machine"}),b.map(F=>s.jsx("option",{value:F,children:w[F]??F},F)),J.nodeId&&!b.includes(J.nodeId)&&s.jsxs("option",{value:J.nodeId,children:[w[J.nodeId]??J.nodeId," (offline)"]})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${o.textSecondary}`,children:"Provider *"}),s.jsxs("select",{className:A,value:J.provider,onChange:F=>T(L,te,{provider:F.target.value}),title:"The AI agent this slot runs.",children:[s.jsx("option",{value:"",children:"Select provider…"}),q.map(F=>s.jsx("option",{value:F,children:F},F)),J.provider&&!q.includes(J.provider)&&s.jsx("option",{value:J.provider,children:J.provider})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${o.textSecondary}`,children:"Model"}),(()=>{var pe;const F=(J.provider?(pe=i.get(J.provider))==null?void 0:pe.models:void 0)??[],V=!!J.model&&F.length>0&&!F.includes(J.model);return F.length>0&&!V?s.jsxs("select",{className:A,value:F.includes(J.model)?J.model:"",title:"Optional model override (best-effort). Blank uses the provider default.",onChange:be=>T(L,te,{model:be.target.value==="__custom__"?" ":be.target.value}),children:[s.jsx("option",{value:"",children:"default"}),F.map(be=>s.jsx("option",{value:be,children:be},be)),s.jsx("option",{value:"__custom__",children:"Custom…"})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:A,value:J.model.trim(),placeholder:"default",title:"Optional model override (best-effort). Blank uses the provider default.",onChange:be=>T(L,te,{model:be.target.value})}),F.length>0&&s.jsx("button",{type:"button",className:`self-start bg-transparent border-none cursor-pointer p-0 text-[10px] ${o.textSecondary} hover:underline`,onClick:()=>T(L,te,{model:""}),children:"← Back to model list"})]})})()]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${o.textSecondary}`,children:"Copies"}),s.jsx("input",{className:`${A} sm:w-16`,value:J.n,placeholder:"1",inputMode:"numeric",title:"How many parallel copies of this agent to run. Blank = 1.",onChange:F=>T(L,te,{n:F.target.value})})]}),s.jsx("button",{type:"button",className:`${$} sm:mt-[18px] inline-flex h-8 w-8 items-center justify-center p-0`,onClick:()=>P(L,te),"aria-label":"Remove agent",title:"Remove agent",children:"✕"})]},te)}),s.jsx("div",{children:s.jsx("button",{type:"button",className:$,onClick:()=>_(L),disabled:!g,children:"+ Add agent"})})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:O,onClick:()=>void B(L),disabled:G||!g,children:G?"Saving…":"Save"}),s.jsx("button",{type:"button",className:$,onClick:()=>void z(L),disabled:G||!g||!Y,title:Y?"Clear this kind binding":"Nothing to remove — this kind is unconfigured",children:"Remove binding"})]})]},L)})})]})}function NC({daemonId:e,meshId:t,cliType:r,sendCommand:n}){const[a,o]=l.useState(!1),[i,c]=l.useState(!1),[d,p]=l.useState(null),[u,m]=l.useState(null),[h,y]=l.useState(null),x=l.useCallback(async()=>{if(!e||!t){p("Connect a daemon to preview the default.");return}c(!0),p(null);try{const j=await n(e,"coordinator_prompt_preview",{meshId:t,cliType:r}),k=j!=null&&j.result&&typeof j.result=="object"?j.result:j;if(!(k!=null&&k.success)){p((k==null?void 0:k.error)||"Failed to render the default prompt");return}m(typeof k.prompt=="string"?k.prompt:""),y(typeof k.bytes=="number"?k.bytes:null)}catch(j){p((j==null?void 0:j.message)||String(j))}finally{c(!1)}},[e,t,r,n]),f=l.useCallback(()=>{const j=!a;o(j),j&&u===null&&!i&&x()},[a,u,i,x]);return s.jsxs("div",{className:"mt-2",children:[s.jsxs("button",{type:"button",onClick:f,className:"inline-flex items-center gap-1 text-[12px] text-accent-primary bg-transparent border-none cursor-pointer p-0",children:[s.jsx("span",{className:`transition-transform ${a?"rotate-90":""}`,"aria-hidden":!0,children:"▸"}),a?"Hide the default prompt":"View the default prompt",s.jsxs("span",{className:"text-text-muted",children:["(",r,")"]})]}),a&&s.jsxs("div",{className:"mt-2",children:[i&&s.jsx("div",{className:"text-[12px] text-text-muted",children:"Rendering…"}),d&&s.jsxs("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:[d,s.jsx("button",{type:"button",onClick:()=>void x(),className:"ml-2 underline bg-transparent border-none cursor-pointer text-amber-300",children:"Retry"})]}),!i&&!d&&u!==null&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between text-[11px] text-text-muted",children:[s.jsx("span",{children:"This is what a coordinator session gets when Override is empty."}),h!==null&&s.jsxs("span",{children:[(h/1024).toFixed(1)," KB"]})]}),s.jsx("textarea",{readOnly:!0,value:u,rows:14,className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-secondary font-mono",onFocus:j=>j.currentTarget.select()})]})]})]})}const SC=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function CC(e){const t=SC(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function IC(e){const t=e==null?void 0:e.missions;return Array.isArray(t)?t:[]}function AC(e){return typeof e.goal=="string"&&e.goal?{text:e.goal,truncated:!1}:{text:e.goalPreview??"",truncated:e.goalTruncated===!0}}const MC=["active","paused","completed","abandoned"];function fd(e){return(e.status||"active").toLowerCase()}const _C=8;function TC({status:e,daemonId:t,meshId:r,sendCommand:n}){const a=l.useMemo(()=>IC(e),[e]),[o,i]=l.useState({}),[c,d]=l.useState({}),[p,u]=l.useState(!1),[m,h]=l.useState(null),[y,x]=l.useState("active"),[f,j]=l.useState(!1),k=l.useMemo(()=>{const N={};for(const C of a){const R=fd(C);N[R]=(N[R]||0)+1}return N},[a]),b=l.useMemo(()=>y==="all"?a:a.filter(N=>fd(N)===y),[a,y]),w=f?b:b.slice(0,_C),I=b.length-w.length,v=!!t&&a.length>0,g=l.useCallback(async()=>{if(t){u(!0),h(null);try{const N=await n(t,"mesh_status",{meshId:r,verbose:!0}),C=CC(N),R=Array.isArray(C==null?void 0:C.missions)?C.missions:[],T={};for(const _ of R)_.id&&typeof _.goal=="string"&&_.goal&&(T[_.id]=_.goal);i(_=>({..._,...T}))}catch(N){h(N instanceof Error?N.message:"Failed to fetch full mission goals")}finally{u(!1)}}},[t,r,n]),S=l.useCallback(N=>{d(C=>({...C,[N]:!C[N]})),!c[N]&&!o[N]&&g()},[c,o,g]);return a.length===0?null:s.jsxs(mt,{title:"Missions",description:"Active and historical missions reported by the coordinator. Expand a goal to fetch its full text on demand.",children:[m&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400",children:m}),s.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-1.5",children:[MC.filter(N=>(k[N]||0)>0).map(N=>s.jsxs("button",{type:"button",onClick:()=>{x(N),j(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] capitalize transition-colors ${y===N?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:[N," ",k[N]]},N)),s.jsxs("button",{type:"button",onClick:()=>{x("all"),j(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] transition-colors ${y==="all"?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:["All ",a.length]})]}),b.length===0&&s.jsxs("div",{className:"text-[12px] text-text-muted",children:["No ",y," missions."]}),s.jsx("div",{className:"flex flex-col gap-2",children:w.map(N=>{var z;const C=c[N.id]===!0,R=o[N.id],T=AC(N),_=C&&R?R:T.text,P=C&&!R&&T.truncated,B=((z=N.tasks)==null?void 0:z.total)??0;return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 px-3 py-2.5",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-text-primary",title:N.title,children:N.title||N.id}),N.status&&s.jsx("span",{className:"shrink-0 rounded-full border border-border-subtle px-2 py-0.5 text-[10px] uppercase tracking-wide text-text-muted",children:N.status}),B>0&&s.jsxs("span",{className:"shrink-0 text-[11px] text-text-muted",children:[B," task",B===1?"":"s"]})]}),_&&s.jsxs("div",{className:`mt-1.5 whitespace-pre-wrap text-[12px] leading-5 text-text-secondary ${C?"max-h-72 overflow-y-auto":"line-clamp-2"}`,children:[_,P&&s.jsx("span",{className:"text-text-muted",children:" … (full goal unavailable)"})]}),(T.truncated||R)&&v&&s.jsx("button",{type:"button",className:"mt-1.5 text-[12px] text-accent-primary hover:underline disabled:opacity-50",onClick:()=>S(N.id),disabled:p,children:C?"Show less":p&&!R?"Loading…":"Show full goal"})]},N.id)})}),I>0&&s.jsxs("button",{type:"button",className:"mt-2 text-[12px] text-accent-primary hover:underline",onClick:()=>j(!0),children:["Show ",I," more"]})]})}const LC=["","low","medium","high"],RC={easy:"Easy",medium:"Medium",difficult:"Difficult",freeform:"Freeform"};function xd(e){return{provider:e.provider||"",model:e.model||"",thinkingLevel:e.thinkingLevel||"",difficulty:Array.isArray(e.difficulty)?e.difficulty:[],capability:Array.isArray(e.capability)?e.capability:[],maxParallel:e.maxParallel!=null?String(e.maxParallel):""}}function bd(e){const t=e.provider.trim();if(!t)return null;const r=e.model.trim(),n=e.thinkingLevel.trim()||void 0,a=Number(e.maxParallel),o=Number.isFinite(a)&&a>0?Math.floor(a):void 0;return{provider:t,...r?{model:r}:{},...n?{thinkingLevel:n}:{},...e.difficulty.length?{difficulty:e.difficulty}:{},...e.capability.length?{capability:e.capability}:{},...o!==void 0?{maxParallel:o}:{}}}function PC(){return{provider:"",model:"",thinkingLevel:"",difficulty:[],capability:[],maxParallel:""}}const Ds="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function DC({slots:e,availableProviders:t,saving:r,onSave:n}){const[a,o]=l.useState(()=>e.map(xd)),i=l.useMemo(()=>JSON.stringify(e),[e]);l.useEffect(()=>{o(e.map(xd))},[i]);const c=l.useMemo(()=>[...new Set(t.map(k=>k.type).filter(Boolean))],[t]),d=l.useMemo(()=>cp(t),[t]),p=l.useMemo(()=>{const k=a.map(bd).filter(Boolean);return JSON.stringify(k)!==JSON.stringify(e)},[a,e]),u=(k,b)=>o(w=>w.map((I,v)=>v===k?{...I,...b}:I)),m=(k,b)=>o(w=>w.map((I,v)=>{var N;if(v!==k)return I;const g=((N=d.get(b))==null?void 0:N.models)??[],S=!I.model||g.length===0||g.includes(I.model);return{...I,provider:b,...S?{}:{model:""}}})),h=k=>o(b=>b.filter((w,I)=>I!==k)),y=()=>o(k=>[...k,PC()]),x=(k,b)=>o(w=>{const I=k+b;if(I<0||I>=w.length)return w;const v=[...w];return[v[k],v[I]]=[v[I],v[k]],v}),f=(k,b)=>o(w=>w.map((I,v)=>{if(v!==k)return I;const g=I.difficulty.includes(b);return{...I,difficulty:g?I.difficulty.filter(S=>S!==b):[...I.difficulty,b]}})),j=()=>n(a.map(bd).filter(Boolean));return s.jsxs("div",{className:"flex flex-col gap-2",onClick:k=>k.stopPropagation(),children:[a.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:"No capability slots set — that's fine. This node still runs tasks using its provider priority order (below). Slots are optional fine-tuning: add one to route specific task difficulties or capabilities to a specific tool."}),a.map((k,b)=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/40 p-2.5",children:[s.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[s.jsxs("span",{className:"text-[11px] font-semibold text-text-muted",children:["#",b+1]}),s.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:b===0,onClick:()=>x(b,-1),title:"Move up",children:"↑"}),s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:b===a.length-1,onClick:()=>x(b,1),title:"Move down",children:"↓"}),s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-status-error/30 text-status-error hover:bg-status-error/10",onClick:()=>h(b),"aria-label":`Remove slot ${b+1}`,children:s.jsx(wt,{size:12})})]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:"Provider"}),c.length>0?s.jsxs("select",{className:Ds,value:k.provider,onChange:w=>m(b,w.target.value),children:[s.jsx("option",{value:"",children:"(select)"}),c.map(w=>s.jsx("option",{value:w,children:w},w)),k.provider&&!c.includes(k.provider)&&s.jsx("option",{value:k.provider,children:k.provider})]}):s.jsx("input",{className:Ds,value:k.provider,placeholder:"claude-cli",onChange:w=>u(b,{provider:w.target.value})})]}),(()=>{var S;const w=d.get(k.provider),I=(w==null?void 0:w.models)??[],v=(S=w==null?void 0:w.thinking)!=null&&S.length?["",...w.thinking]:LC,g=!!k.model&&I.length>0&&!I.includes(k.model);return s.jsxs(s.Fragment,{children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:"Model"}),I.length>0&&!g?s.jsxs("select",{className:Ds,value:I.includes(k.model)?k.model:"",onChange:N=>u(b,{model:N.target.value==="__custom__"?" ":N.target.value}),children:[s.jsx("option",{value:"",children:"(provider default)"}),I.map(N=>s.jsx("option",{value:N,children:N},N)),s.jsx("option",{value:"__custom__",children:"Custom…"})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:Ds,value:k.model.trim(),placeholder:k.provider?`${k.provider} model`:"model",onChange:N=>u(b,{model:N.target.value})}),I.length>0&&s.jsx("button",{type:"button",className:"self-start bg-transparent border-none cursor-pointer p-0 text-[10px] text-text-muted hover:underline",onClick:()=>u(b,{model:""}),children:"← Back to model list"})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:"Thinking"}),s.jsx("select",{className:Ds,value:k.thinkingLevel,onChange:N=>u(b,{thinkingLevel:N.target.value}),children:v.map(N=>s.jsx("option",{value:N,children:N||"(default)"},N||"_default"))})]})]})})()]}),s.jsxs("div",{className:"mt-2",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:"Difficulty (blank = all)"}),s.jsx("div",{className:"mt-1 flex flex-wrap gap-1.5",children:_x.map(w=>{const I=k.difficulty.includes(w);return s.jsx("button",{type:"button",className:`rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors ${I?"border-accent-primary/60 bg-accent-primary/15 text-accent-primary":"border-border-subtle bg-bg-primary/60 text-text-muted hover:text-text-primary"}`,onClick:()=>f(b,w),children:RC[w]},w)})})]}),s.jsxs("div",{className:"mt-2 grid grid-cols-1 sm:grid-cols-2 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:"Capability tags (comma-separated)"}),s.jsx("input",{className:Ds,value:k.capability.join(", "),placeholder:"worktree, os=darwin",onChange:w=>u(b,{capability:w.target.value.split(",").map(I=>I.trim()).filter(Boolean)})})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:"Max parallel (per slot)"}),s.jsx("input",{type:"number",inputMode:"numeric",min:1,className:Ds,value:k.maxParallel,placeholder:"unlimited",onChange:w=>u(b,{maxParallel:w.target.value})})]})]})]},b)),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1",onClick:y,children:[s.jsx(wi,{size:13})," Add slot"]}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm ml-auto",onClick:j,disabled:!!r||!p,children:r?"Saving…":"Save slots"})]})]})}function $C(e){const t=new Map;for(const r of e)r!=null&&r.id&&t.set(r.id,xr(r.availableProviders||[]));return t}function EC(e,t){const r=String(e.daemon_id||e.daemonId||"");return r&&t.has(r)?t.get(r):!r&&t.size===1?[...t.values()][0]:[]}function BC(e){var d,p,u;const t=e,r=[],n=Array.isArray(t.capabilities)?t.capabilities:[];for(const m of n){const h=typeof m=="string"?m.trim():"";h&&r.push({tag:h,custom:!0})}const a=(((d=t.userOverrides)==null?void 0:d.platform)||t.reportedPlatform||"").toString().trim(),o=(((p=t.userOverrides)==null?void 0:p.arch)||t.reportedArch||"").toString().trim();a&&r.push({tag:`os=${a}`,custom:!1}),o&&r.push({tag:`arch=${o}`,custom:!1});const i=Array.isArray((u=t.policy)==null?void 0:u.providerPriority)?String(t.policy.providerPriority[0]||"").trim():"";i&&r.push({tag:`provider=${i}`,custom:!1});const c=typeof t.worktreeBranch=="string"?t.worktreeBranch.trim():"";return t.isLocalWorktree===!0&&c&&r.push({tag:`worktree=${c}`,custom:!1}),r}function FC(e){const t=e.capabilities;return Array.isArray(t)?t.map(r=>typeof r=="string"?r.trim():"").filter(Boolean):[]}const OC=["os=","arch=","provider=","worktree=","converge="];function HC({node:e,saving:t,onSave:r}){const n=l.useMemo(()=>BC(e).filter(x=>!x.custom),[e]),a=l.useMemo(()=>FC(e),[e]),[o,i]=l.useState(a),[c,d]=l.useState(""),p=JSON.stringify(o)!==JSON.stringify(a),m=(x=>{const f=x.trim();return f?/\s/.test(f)?"Tags cannot contain spaces.":OC.some(j=>f.toLowerCase().startsWith(j))?"That prefix is auto-derived — pick a different tag.":o.includes(f)?"Already added.":null:null})(c);function h(){const x=c.trim();!x||m||(i(f=>[...f,x]),d(""))}function y(x){i(f=>f.filter(j=>j!==x))}return s.jsxs("div",{className:"mt-2",onClick:x=>x.stopPropagation(),children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wide text-text-muted mr-1",children:"Routing tags"}),n.map(x=>s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-1.5 py-0.5 font-mono text-[10px] text-text-muted",title:"Auto-derived — can't be edited",children:x.tag},x.tag)),o.map(x=>s.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 font-mono text-[10px] text-accent-primary",title:"Custom tag",children:[x,s.jsx("button",{type:"button",className:"text-accent-primary/70 hover:text-accent-primary bg-transparent border-none cursor-pointer p-0 leading-none",onClick:()=>y(x),disabled:t,"aria-label":`Remove ${x}`,children:"×"})]},x))]}),s.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-2",children:[s.jsx("input",{type:"text",value:c,onChange:x=>d(x.target.value),onKeyDown:x=>{x.key==="Enter"&&(x.preventDefault(),h())},placeholder:"add a custom tag (e.g. test-runner)",disabled:t,className:"min-w-[12rem] flex-1 px-2 py-1 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-primary"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:h,disabled:t||!c.trim()||!!m,children:"Add"}),p&&s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>r(o),disabled:t,children:t?"Saving…":"Save tags"})]}),m&&s.jsx("div",{className:"mt-1 text-[11px] text-amber-400",children:m}),o.length===0&&n.length===0&&s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"No routing tags — tasks can run here without matching any specific capability. Tags are optional."})]})}function WC(e,t){return t.filter(r=>r.status!=="assigned"?!1:(r.assignedNodeId||r.nodeId)===e.id)}function KC(e){const t=e.assignedSessionId||e.sessionId||"unassigned session",r=e.message.length>80?`${e.message.slice(0,77)}…`:e.message;return`${t}: ${r}`}function UC(e){var n;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((n=e.policy)==null?void 0:n.providerPriority)?e.policy.providerPriority:[],r=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>r.has(a)?!1:(r.add(a),!0))}function zC(e){const t=UC(e);return t.length?{configured:!0,label:t.join(" → ")}:{configured:!1,label:"not configured",launchBlockedMessage:"No provider detected on this node — task launch is blocked until a provider is selected or installed. (Empty capability slots alone do not block launch; this means no provider was found.)"}}function GC(e){return e.isLocalWorktree===!0}function VC(e,t){const r=t;return[...Array.isArray(r==null?void 0:r.cliSessions)?r.cliSessions:[],...Array.isArray(r==null?void 0:r.acpSessions)?r.acpSessions:[],...Array.isArray(r==null?void 0:r.sessions)?r.sessions:[]].filter(a=>{var o;return((o=a==null?void 0:a.settings)==null?void 0:o.meshNodeId)===e.id||(a==null?void 0:a.workspace)===e.workspace}).map(a=>{var o;return{id:a.sessionId||a.id||a.instanceId||"unknown",provider:a.providerType||a.cliType||a.acpType||a.type||"unknown",status:a.status||((o=a.activeChat)==null?void 0:o.status)||"unknown"}})}function gd(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function qC(e,t){var r;return(e==null?void 0:e.ownerName)||(e==null?void 0:e.userName)||((r=e==null?void 0:e.user)==null?void 0:r.name)||t||"You"}function YC({nodes:e,meshQueue:t,activeDaemon:r,daemons:n,selectedMeshId:a,userName:o,features:i,coordinatorDaemonId:c,availableCliProviders:d,savingNodeSlotsId:p,onUpdateNodeSlots:u,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:h,nodeSystemPromptDrafts:y,onNodeSystemPromptDraftChange:x,savingNodeSystemPromptId:f,onSaveNodeSystemPrompt:j,selectedNodeId:k,onSelectNode:b,showAddNode:w,onShowAddNode:I,onCancelAddNode:v,nodeWorkspace:g,onNodeWorkspaceChange:S,nodeProviderPriority:N,onNodeProviderPriorityChange:C,nodeDaemonId:R,onNodeDaemonIdChange:T,nodeCustomPath:_,onNodeCustomPathChange:P,nodePickerWorkspaces:B,nodePickerProviders:z,attachableDaemons:A,onAddNode:O,onRemoveNode:$}){const L=l.useMemo(()=>$C(n),[n]),E=l.useMemo(()=>e.filter(M=>!GC(M)),[e]);return s.jsxs(mt,{title:i.addNodeDaemonPicker?`Nodes & Providers (${E.length})`:"Nodes & Providers",description:i.addNodeDaemonPicker?"Workspaces in this mesh and their preferred AI tools. Setup inventory only — live graph/git/session truth is owned by the Mesh Host status above.":"Workspaces participating in this mesh and their preferred AI tools.",children:[i.addNodeDaemonPicker&&s.jsxs("div",{className:"mb-4 rounded-xl border border-border-subtle bg-bg-secondary/60 p-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Machine daemon candidates"}),s.jsx("div",{className:"text-[12px] text-text-muted",children:"Choose connected daemons to attach to the selected Mesh Host setup."})]}),s.jsxs("span",{className:"text-[11px] text-text-muted",children:[A.length," available"]})]}),n.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:"No connected machine daemons are currently available."}):A.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:"All connected machine daemons are already attached."}):s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:A.map(M=>s.jsxs("button",{type:"button",className:`text-left rounded-lg border px-3 py-2 transition-colors ${M.id===c?"border-accent-primary/50 bg-accent-primary/10":"border-border-subtle bg-bg-primary hover:border-border-default"}`,onClick:()=>{T(M.id),S(""),P(!1),C(nn(xr(M.availableProviders||[]))),I()},children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-sm font-medium truncate",children:gd(M)}),M.id===c&&s.jsx("span",{className:"text-[10px] text-accent-primary",children:"selected host"})]}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted font-mono truncate",children:M.id}),s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted",children:[(M.workspaces||[]).length," workspace(s) detected"]})]},M.id))})]}),!w&&s.jsxs("button",{className:"btn btn-primary btn-sm mb-4 inline-flex items-center gap-1.5",onClick:I,children:[s.jsx(hC,{size:13})," ",i.addNodeDaemonPicker?"Attach machine":"Add node"]}),w&&s.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass animate-[fadeIn_0.3s_ease-out]",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h4",{className:"text-sm font-bold",children:i.addNodeDaemonPicker?"Attach Machine Daemon":"Add Node"}),s.jsx("button",{onClick:()=>{v(),T(""),P(!1)},className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(wt,{size:16})})]}),i.addNodeDaemonPicker&&s.jsx(vt,{label:"Machine",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:R,onChange:M=>{var H;T(M.target.value),S(""),P(!1),C(nn(xr(((H=n.find(Y=>Y.id===M.target.value))==null?void 0:H.availableProviders)||[])))},children:[s.jsx("option",{value:"",children:"Select a machine..."}),n.map(M=>s.jsx("option",{value:M.id,children:gd(M)},M.id))]})}),(i.addNodeDaemonPicker?R:!0)&&s.jsx(vt,{label:"Workspace Path",children:i.addNodeDaemonPicker&&!_&&B.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex flex-col gap-1.5 mb-2",children:B.map(M=>s.jsxs("button",{type:"button",className:`text-left text-xs px-3 py-2 rounded-lg border transition-colors ${g===M.path?"border-accent-primary bg-accent-primary/10 text-text-primary":"border-border-subtle bg-bg-primary hover:bg-violet-500/10 text-text-primary"}`,onClick:()=>S(M.path),children:[s.jsx("span",{className:"font-medium block truncate",children:M.label||M.path.split("/").pop()}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:M.path})]},M.id||M.path))}),s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{P(!0),S("")},children:"Or enter a custom path →"})]}):s.jsx(s.Fragment,{children:i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[s.jsx(ts,{value:g,onChange:M=>S(M.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:M=>{M.key==="Enter"&&O()}}),B.length>0&&s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0 mt-1",onClick:()=>{P(!1),S("")},children:"← Pick from saved workspaces"})]}):(()=>{var Y;const M=Array.isArray(r==null?void 0:r.workspaces)?r.workspaces:[],H=`mesh-add-node-workspaces-${a||"new"}`;return s.jsxs(s.Fragment,{children:[s.jsx(ts,{value:g,onChange:G=>S(G.target.value),placeholder:((Y=M[0])==null?void 0:Y.path)||"/Users/dev/projects/myapp",list:M.length>0?H:void 0,autoFocus:!0}),M.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("datalist",{id:H,children:M.map(G=>s.jsx("option",{value:G.path,children:G.label||G.path},G.id||G.path))}),s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:M.slice(0,6).map(G=>s.jsx("button",{type:"button",onClick:()=>S(G.path),className:"text-[11px] px-2 py-0.5 rounded-full border border-border-subtle hover:border-accent-primary/50 text-text-muted hover:text-text-primary transition-colors bg-transparent cursor-pointer",title:G.path,children:G.label||G.path.split("/").filter(Boolean).pop()||G.path},G.id||G.path))})]})]})})()})}),s.jsx(vt,{label:"Preferred AI tools (in order)",hint:"Order used when launching without an explicit provider.",children:s.jsx(k0,{value:N,availableProviders:i.addNodeDaemonPicker?z:d,onChange:C})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:O,disabled:!g.trim()||i.addNodeDaemonPicker&&!R,className:"btn btn-primary btn-sm",children:"Add"}),s.jsx("button",{onClick:()=>{v(),T(""),P(!1)},className:"btn btn-secondary btn-sm",children:"Cancel"})]})]}),i.addNodeDaemonPicker&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-300 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:"Setup inventory only — live git/session/branch detail is shown in the graph popup after direct aggregate mesh_status truth is available from the Mesh Host."}),E.length===0?s.jsx(Ma,{icon:s.jsx(mr,{}),title:"No nodes",description:"Add a workspace to this mesh."}):s.jsx("div",{className:"flex flex-col gap-2",children:E.map(M=>{var oe;const H=zC(M),Y=WC(M,t),G=VC(M,r),J=k===M.id,te=M.status||M.machine_status||(Y.length>0||G.length>0?"active":"enabled");return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary transition-colors ${i.addNodeDaemonPicker?"bg-bg-glass border-border-subtle rounded-xl px-5 py-4":`cursor-pointer ${J?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`}`,role:i.addNodeDaemonPicker?void 0:"button",tabIndex:i.addNodeDaemonPicker?void 0:0,onClick:i.addNodeDaemonPicker?void 0:()=>b(J?null:M.id),onKeyDown:i.addNodeDaemonPicker?void 0:q=>{(q.key==="Enter"||q.key===" ")&&(q.preventDefault(),b(J?null:M.id))},children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.addNodeDaemonPicker?s.jsx("span",{className:"font-semibold text-sm text-text-primary truncate",children:M.machine_label||M.machine_nickname||M.hostname||M.workspace}):s.jsx("span",{className:"text-sm font-medium",children:M.workspace.split("/").pop()}),i.addNodeDaemonPicker&&s.jsx(fC,{status:te}),i.addNodeDaemonPicker&&s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:"setup inventory"})]}),i.addNodeDaemonPicker&&s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Owner: ",qC(n.find(q=>q.id===String(M.daemon_id||"")),o)," · Machine: ",M.machine_label||M.daemon_id||M.workspace]}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:M.workspace}),s.jsx(HC,{node:M,saving:m===M.id,onSave:q=>h(M,q)}),i.addNodeDaemonPicker&&s.jsx("div",{className:"mt-2 text-[11px] text-amber-300",children:"Live branch/git/session detail is graph-owned; use the node popup in the live graph above."}),s.jsxs("div",{className:"mt-3 max-w-2xl",onClick:q=>q.stopPropagation(),children:[s.jsx(vt,{label:"Preferred AI tools (capability slots)",hint:"Each slot = provider + model + thinking + the task difficulty/capability it handles + a per-slot parallel cap. Tasks are matched to the best-fit slot (order = preference). With no slots, this node uses its legacy provider order.",children:s.jsx(DC,{slots:Array.isArray((oe=M.policy)==null?void 0:oe.slots)?M.policy.slots:[],availableProviders:EC(M,L),saving:p===M.id,onSave:q=>u(M,q)})}),i.nodeInstruction&&s.jsxs(vt,{label:"Node instruction (optional)",hint:"Surfaced in the coordinator system prompt as 📌 Node instruction.",children:[s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:3,value:y[M.id]??"",onChange:q=>{const F=q.target.value;x(M.id,F)},onClick:q=>q.stopPropagation(),disabled:f===M.id,placeholder:"e.g. 'Run only smoke tests here', 'Use opus on this node'"}),s.jsx("div",{className:"mt-2 flex items-center gap-2",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:q=>{q.stopPropagation(),j(M)},disabled:f===M.id,children:f===M.id?"Saving…":"Save instruction"})})]})]})]}),s.jsx("button",{className:`transition-colors bg-transparent border-none cursor-pointer ${i.addNodeDaemonPicker?"btn btn-sm text-text-muted hover:text-red-400":"text-text-muted hover:text-red-400"}`,onClick:q=>{q.stopPropagation(),$(M.id)},title:"Remove node",children:s.jsx(mC,{size:14})})]}),s.jsxs("details",{className:"mt-3 group",onClick:q=>q.stopPropagation(),children:[s.jsxs("summary",{className:"cursor-pointer select-none text-[12px] text-text-muted hover:text-text-secondary inline-flex items-center gap-1",children:[s.jsx("span",{className:"transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"})," Details"]}),s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary/60 p-3 text-[12px] text-text-muted",children:[s.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Node ID:"})," ",s.jsx("span",{className:"font-mono break-all",children:M.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Launch ready:"})," ",s.jsx("span",{className:H.configured?"text-green-400":"text-amber-400",children:H.configured?"yes":"no preferred tool configured"})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Repo root:"})," ",s.jsx("span",{className:"font-mono break-all",children:M.repoRoot||M.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Active sessions:"})," ",G.length]}),i.addNodeDaemonPicker&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Added:"})," ",new Date(M.created_at||M.createdAt||Date.now()).toLocaleDateString()]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Active queue assignments"}),Y.length===0?s.jsx("div",{children:"No active assigned queue task for this node."}):s.jsx("ul",{className:"m-0 pl-4",children:Y.map(q=>s.jsx("li",{className:"font-mono",children:KC(q)},q.id))})]}),G.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Active sessions"}),s.jsx("ul",{className:"m-0 pl-4",children:G.map(q=>s.jsxs("li",{className:"font-mono",children:[q.provider," / ",q.status," / ",q.id]},q.id))})]})]})]})]},M.id)})})]})}function $n(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function JC({daemons:e,coordinatorDaemonId:t,onCoordinatorDaemonIdChange:r,coordinatorCliType:n,onCoordinatorCliTypeChange:a,launchingCoordinator:o,launchResult:i,isHostNodeAttached:c,selectedHostNode:d,hostPinned:p,hostLabel:u,hostOnline:m,hostRebindDaemonId:h,onHostRebindDaemonIdChange:y,onLaunchCoordinator:x}){const f=s.jsx(vt,{label:"Coordinator CLI provider",hint:"Tool launched for the host coordinator session.",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:n,onChange:b=>a(b.target.value),children:[s.jsx("option",{value:"",children:"Use node provider priority"}),s.jsx("option",{value:"claude-cli",children:"Claude Code"}),s.jsx("option",{value:"codex-cli",children:"Codex"}),s.jsx("option",{value:"gemini-cli",children:"Gemini"}),s.jsx("option",{value:"hermes-cli",children:"Hermes"})]})}),j=i&&s.jsx("div",{className:"mt-3 text-[12px] text-green-400 bg-green-500/10 border border-green-500/20 rounded-lg px-3 py-2",children:i});if(p)return s.jsxs(mt,{title:"Mesh Host daemon",description:"The daemon that owns this mesh's coordinator and live truth (status, queue, graph, node detail). Fixed when the mesh is created — it cannot be reassigned here.",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsxs("span",{className:`inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-[13px] text-text-primary ${m?"border-accent-primary/40 bg-accent-primary/10":"border-amber-500/40 bg-amber-500/10"}`,children:[s.jsx("span",{className:"text-text-muted",children:"Host:"}),s.jsx("span",{className:"font-medium",children:u||"Unknown"}),s.jsxs("span",{className:m?"text-text-muted":"text-amber-400",children:["· ",m?"online":"offline"]})]}),(d==null?void 0:d.workspace)&&s.jsxs("span",{className:"text-[12px] text-text-muted",children:["Host node: ",s.jsx("span",{className:"font-mono text-text-secondary",children:d.workspace})]})]}),!m&&s.jsxs("div",{className:"mt-4",children:[s.jsxs(Ft,{variant:"warning",className:"mb-3",children:[s.jsx("strong",{children:"Host offline."})," ","The pinned host daemon is not connected. Live status/queue/graph will not load until it reconnects. You can temporarily route commands through another connected daemon below — this is a routing fallback, not a host reassignment."]}),e.length>0?s.jsx(vt,{label:"Reconnect to command",hint:"Route commands through this connected daemon until the host is back. Does not change the mesh host.",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:h,onChange:b=>y(b.target.value),children:[s.jsx("option",{value:"",children:"Wait for host to reconnect"}),e.map(b=>s.jsx("option",{value:b.id,children:$n(b)},b.id))]})}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:"No connected daemons available to route commands through. Bring the host (or another daemon) online."})]}),s.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-[180px_auto] items-end",children:[f,s.jsx("button",{className:"btn btn-primary btn-sm",onClick:x,disabled:o||!t,title:t?void 0:"No command target available — bring the host or a daemon online.",children:o?"Launching...":"Launch Host Coordinator"})]}),j]});const k=e.find(b=>b.id===t);return s.jsxs(mt,{title:"Mesh Host daemon",description:"This mesh has no host yet. Launching the coordinator on a connected daemon fixes that daemon as the mesh host (a 1:1 pin); it owns live truth thereafter.",children:[s.jsxs(Ft,{variant:"info",className:"mb-4",children:[s.jsx("strong",{children:"Set the mesh host."})," ","The host is the daemon that owns this mesh's coordinator and live truth. Launch the host coordinator below to set it — the host is fixed once established."]}),e.length>0?s.jsxs(s.Fragment,{children:[t?s.jsx("div",{className:"mb-3 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:c?s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:$n(k)}),d!=null&&d.workspace?s.jsxs(s.Fragment,{children:[" · setup node ",s.jsx("span",{className:"font-mono text-text-secondary",children:d.workspace})]}):null,". Launching sets this daemon as the mesh host."]}):s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:$n(k)}),". Attach one of its workspaces as a node first, then launch to set the host."]})}):s.jsx(vt,{label:"Host daemon",hint:"Pick the daemon that will host this mesh. Launching the coordinator on it fixes it as the host.",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:"",onChange:b=>r(b.target.value),children:[s.jsx("option",{value:"",children:"Resolving host… (or pick a daemon to host)"}),e.map(b=>s.jsx("option",{value:b.id,children:$n(b)},b.id))]})}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-[180px_auto] items-end mt-3",children:[f,s.jsx("button",{className:"btn btn-primary btn-sm",onClick:x,disabled:!t||!c||o,title:t?c?void 0:"Attach a workspace from this daemon as a node first.":"Pick a host daemon (or wait for the host pin to resolve) first.",children:o?"Launching...":"Launch Host Coordinator (sets host)"})]})]}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:"No connected daemons. Bring a daemon online to host this mesh."}),j]})}function XC({meshId:e,availableCliAgents:t}){const r=t.find(a=>{const o=a.id.toLowerCase();return o==="hermes-cli"||o.includes("hermes")||a.name.toLowerCase().includes("hermes")}),n=Lp(r==null?void 0:r.meshCoordinator,{meshId:e});return n?s.jsx(mt,{title:"Hermes MCP Config",description:"Hermes does not auto-import repo-local .mcp.json. Add this YAML under mcp_servers in Hermes config, then start a fresh Hermes session.",children:s.jsx(sm,{setup:n,providerName:(r==null?void 0:r.name)||"Hermes CLI"})}):null}const To=[{value:"preserve",label:"Preserve history and runtimes",description:"Keep completed chat history and leave live runtimes alone."},{value:"stop",label:"Stop live runtimes only",description:"Release running session processes, but keep chat records/transcripts."},{value:"delete_stopped",label:"Delete stopped sessions only",description:"Clean completed/stopped chat clutter without killing live runtimes."},{value:"stop_and_delete",label:"Stop and delete sessions",description:"Stop matching runtimes, then remove their session records/transcripts."}],QC=[{value:"smart",label:"Smart",description:"Match each task to the node whose capability slot best fits it (task difficulty + capability tags), then load-spread among ties. Auto-enabled when any node has capability slots."},{value:"spread",label:"Spread",description:"Distribute work evenly across eligible nodes (prefers the least-loaded, rotating ties fairly). Set a per-node priority below to bias the order."},{value:"in_order",label:"In order",description:"Assign to nodes in the order they were added — the first eligible node takes the work. No load-spreading."}];function ZC(e){return e==="smart"?"fitness":e==="spread"?"least_loaded":"first_eligible"}function e2(e,t){const r=e||"first_eligible";return r==="fitness"?"smart":r==="first_eligible"?"in_order":r==="priority_only"?t!=null&&t.priorityConfigured?"spread":"in_order":r==="least_loaded"||r==="round_robin"?"spread":"in_order"}const t2={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,schedulingStrategy:"first_eligible",sessionCleanupOnNodeRemove:"preserve"};function ci(e){return{...t2,...(e==null?void 0:e.policy)||{}}}function s2(e){return{routeId:`mesh-settings:${e.meshId}`,daemonId:e.daemonId,agentName:e.meshName,agentType:"mesh",status:"idle",title:e.meshName,messages:[],workspaceName:e.meshName,displayPrimary:e.meshName,displaySecondary:"Mesh observability",streamSource:"native",tabKey:`mesh-settings:${e.meshId}`,coordinator:{meshId:e.meshId,role:"coordinator"},settings:{meshCoordinatorFor:e.meshId}}}function r2({selectedMesh:e,error:t,onDismissError:r,onBack:n,onDelete:a,displayedMeshStatus:o,graphLoading:i,graphError:c,onRefreshGraph:d,savingPolicy:p,onUpdatePolicy:u,coordinatorPromptDraft:m,onCoordinatorPromptDraftChange:h,savingCoordinatorPrompt:y,onSaveCoordinatorPrompt:x,daemons:f,coordinatorDaemonId:j,onCoordinatorDaemonIdChange:k,coordinatorCliType:b,onCoordinatorCliTypeChange:w,launchingCoordinator:I,launchResult:v,isHostNodeAttached:g,selectedHostNode:S,hostPinned:N,hostLabel:C,hostOnline:R,hostRebindDaemonId:T,onHostRebindDaemonIdChange:_,onLaunchCoordinator:P,activeDaemon:B,activeDaemonId:z,meshQueue:A,userName:O,availableCliProviders:$,savingNodeSlotsId:L,onUpdateNodeSlots:E,savingNodeCapabilitiesId:M,onUpdateNodeCapabilities:H,nodeSystemPromptDrafts:Y,onNodeSystemPromptDraftChange:G,savingNodeSystemPromptId:J,onSaveNodeSystemPrompt:te,selectedNodeId:oe,onSelectNode:q,showAddNode:F,onShowAddNode:V,onCancelAddNode:pe,nodeWorkspace:be,onNodeWorkspaceChange:ue,nodeProviderPriority:Ne,onNodeProviderPriorityChange:se,nodeDaemonId:ve,onNodeDaemonIdChange:me,nodeCustomPath:U,onNodeCustomPathChange:W,nodePickerWorkspaces:Z,nodePickerProviders:ie,attachableDaemons:ye,onAddNode:fe,onRemoveNode:D,availableCliAgents:he,features:Se,sendCommand:ae}){var qe;const Q=ci(e),we=e.nodes||[],ke=we.some(je=>{var Ie;const at=Number((Ie=je.policy)==null?void 0:Ie.schedulingPriority);return Number.isFinite(at)&&at!==0}),Le=!Q.schedulingStrategy,We=l.useMemo(()=>we.some(je=>{var at;return Array.isArray((at=je.policy)==null?void 0:at.slots)&&je.policy.slots.length>0}),[we]),ce=Le?We?"smart":we.length>=2?"spread":null:null,[Ee,Be]=l.useState(!1),Je=!!z&&!!e.id;return s.jsxs(mn,{icon:s.jsx(ss,{}),title:e.name,subtitle:e.repoIdentity||e.repo_identity||"Repo Mesh",widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:n,children:"← Back"}),s.jsxs("button",{className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:()=>d(!0),disabled:i,children:[s.jsx(uC,{size:13}),i?"Probing…":"Refresh"]}),s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>a(e.id),children:"Delete"})]}),children:[t&&s.jsx(Ft,{variant:"error",onDismiss:r,className:"mb-4",children:t}),Se.meshHostDaemonSection&&s.jsx(JC,{daemons:f,coordinatorDaemonId:j,onCoordinatorDaemonIdChange:k,coordinatorCliType:b,onCoordinatorCliTypeChange:w,launchingCoordinator:I,launchResult:v,isHostNodeAttached:g,selectedHostNode:S,hostPinned:N,hostLabel:C,hostOnline:R,hostRebindDaemonId:T,onHostRebindDaemonIdChange:je=>{_(je),d()},onLaunchCoordinator:P}),s.jsxs(mt,{title:"Observability",description:"Open the live mesh graph, overview, and runtime status in the observability dialog.",children:[c&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:c}),s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsxs("button",{type:"button",className:"btn btn-primary btn-sm inline-flex items-center gap-1.5",onClick:()=>Be(!0),disabled:!Je,title:Je?"Open the mesh graph / overview / status dialog":"A coordinator daemon must be selected first",children:[s.jsx(ss,{size:14}),"Open mesh graph & status"]}),s.jsx("span",{className:"text-[12px] text-text-muted",children:"Topology graph, overview cards (missions, ledger, queue, nodes, sessions), and per-node runtime drift."})]})]}),s.jsx(YC,{nodes:we,meshQueue:A,activeDaemon:B,daemons:f,selectedMeshId:e.id,userName:O,features:{addNodeDaemonPicker:Se.addNodeDaemonPicker,nodeInstruction:Se.nodeInstruction},coordinatorDaemonId:j,availableCliProviders:$,savingNodeSlotsId:L,onUpdateNodeSlots:E,savingNodeCapabilitiesId:M,onUpdateNodeCapabilities:H,nodeSystemPromptDrafts:Y,onNodeSystemPromptDraftChange:G,savingNodeSystemPromptId:J,onSaveNodeSystemPrompt:te,selectedNodeId:oe,onSelectNode:q,showAddNode:F,onShowAddNode:V,onCancelAddNode:pe,nodeWorkspace:be,onNodeWorkspaceChange:ue,nodeProviderPriority:Ne,onNodeProviderPriorityChange:se,nodeDaemonId:ve,onNodeDaemonIdChange:me,nodeCustomPath:U,onNodeCustomPathChange:W,nodePickerWorkspaces:Z,nodePickerProviders:ie,attachableDaemons:ye,onAddNode:fe,onRemoveNode:D}),s.jsxs(mt,{title:"Scheduling",description:"How untargeted queue work is distributed across eligible nodes.",children:[s.jsxs("fieldset",{className:"border-none p-0 m-0",children:[s.jsx("legend",{className:"text-[13px] font-medium text-text-secondary mb-2",children:"Distribution"}),s.jsx("div",{className:"flex flex-col gap-2",children:QC.map(je=>{const Ie=e2(Q.schedulingStrategy,{priorityConfigured:ke})===je.value;return s.jsxs("label",{className:`flex items-start gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${Ie?"border-accent-primary/60 bg-accent-primary/10":"border-border-subtle bg-bg-secondary/60 hover:border-border-default"}`,children:[s.jsx("input",{type:"radio",name:"mesh-distribution",className:"mt-0.5 accent-[var(--accent-primary)]",value:je.value,checked:Ie,disabled:p,onChange:()=>u({schedulingStrategy:ZC(je.value)})}),s.jsxs("span",{className:"min-w-0",children:[s.jsxs("span",{className:"flex items-center gap-2 text-sm text-text-primary",children:[je.label,ce===je.value&&s.jsx("span",{className:"rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-accent-primary",children:"Recommended"})]}),s.jsx("span",{className:"block text-[12px] text-text-muted",children:je.description})]})]},je.value)})})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving…"})]}),o&&s.jsx(mt,{title:"MAGI review panels",description:"MAGI (Multi-Agent Ground-truth Insight) runs a panel of AI agents that cross-check each other's work to surface the ground truth. Choose which agents handle each review type.",children:s.jsx(kC,{status:o,daemonId:z,sendDaemonCommand:ae,availableProviders:$})}),s.jsx(TC,{status:o,daemonId:z,meshId:e.id,sendCommand:ae}),Se.coordinatorPrompt&&s.jsxs(mt,{title:"Coordinator prompt",collapsible:!0,defaultOpen:!1,badge:s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:"advanced"}),description:"Customize the system prompt for coordinator sessions. Per-mesh overrides apply to this mesh only; user-level overrides apply to every mesh this daemon coordinates.",children:[s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 p-3",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-1",children:"This mesh"}),s.jsxs("p",{className:"text-[12px] text-text-muted mb-3",children:["Applies only to coordinator sessions for ",s.jsx("span",{className:"font-mono text-[11px]",children:e.name}),". Leave empty to fall through to the user-level / daemon default."]}),s.jsxs(vt,{label:"Override (replaces default)",hint:"When set, replaces the daemon's default base prompt. Leave empty to keep the default.",children:[s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:6,value:m.override,onChange:je=>h({...m,override:je.target.value}),disabled:y,placeholder:"(empty — daemon default applies)"}),s.jsx(NC,{daemonId:z,meshId:e.id,cliType:b,sendCommand:ae})]}),s.jsx(vt,{label:"Append (added after the base)",hint:"Always added after whichever base prompt wins.",children:s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:4,value:m.append,onChange:je=>h({...m,append:je.target.value}),disabled:y,placeholder:"(empty — nothing appended)"})}),s.jsxs("details",{className:"mt-2 text-[12px] text-text-muted",children:[s.jsx("summary",{className:"cursor-pointer select-none",children:"Available placeholders"}),s.jsx("p",{className:"mt-1 font-mono break-words",children:"{{meshName}}, {{repo}}, {{defaultBranch}}, {{cliType}}, {{nodes}}, {{policy}}, {{tools}}, {{workflow}}, {{rules}}, {{toolExposurePreflight}}"})]}),s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:x,disabled:y,children:y?"Saving…":"Save coordinator prompt"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>h({override:"",append:""}),disabled:y,title:"Clear both fields. Click Save to commit.",children:"Clear"})]})]}),s.jsxs("div",{className:"mt-5 border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-1",children:"User-level (this daemon)"}),s.jsx("p",{className:"text-[12px] text-text-muted mb-3",children:"Per-machine prompt files on the coordinator daemon. They apply to every mesh this daemon coordinates and are not synced across daemons. Per-mesh overrides above win over these."}),s.jsx(q0,{daemonId:z||void 0})]})]}),s.jsxs(mt,{title:"Safety & Git",collapsible:!0,defaultOpen:!1,badge:s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:"advanced"}),description:"Checkpointing, approval gates, and git safety behavior for coordinator-driven tasks.",children:[s.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:[{label:"Auto-commit a checkpoint before each task",key:"requirePreTaskCheckpoint",opts:[["no","No"],["yes","Yes"]],val:je=>je?"yes":"no",parse:je=>je==="yes"},{label:"Auto-commit a checkpoint after each task",key:"requirePostTaskCheckpoint",opts:[["yes","Yes"],["no","No"]],val:je=>je?"yes":"no",parse:je=>je==="yes"},{label:"Push approval",key:"requireApprovalForPush",opts:[["required","Require approval before push"],["not_required","Do not require approval"]],val:je=>je?"required":"not_required",parse:je=>je==="required"},{label:"Destructive git approval",key:"requireApprovalForDestructiveGit",opts:[["required","Require approval"],["not_required","Do not require approval"]],val:je=>je?"required":"not_required",parse:je=>je==="required"},{label:"When the workspace has uncommitted changes",key:"dirtyWorkspaceBehavior",opts:[["warn","Warn and continue"],["block","Block task"],["checkpoint_then_continue","Checkpoint then continue"]],val:je=>je||"warn",parse:je=>je},{label:"Auto-publish submodule commits (advanced)",key:"allowAutoPublishSubmoduleMainCommits",opts:[["disabled","Require explicit approval"],["enabled","Allow Refinery non-force publish"]],val:je=>je?"enabled":"disabled",parse:je=>je==="enabled"},{label:"Coordinator-spawned worker sessions",key:"spawnedSessionVisibility",opts:[["hidden","Hidden (no notifications, keep inbox quiet)"],["visible","Visible (show every worker in the dashboard)"]],val:je=>je==="visible"?"visible":"hidden",parse:je=>je==="visible"?"visible":"hidden"}].map(({label:je,key:at,opts:Ie,val:ot,parse:nt})=>s.jsx(vt,{label:je,children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ot(Q[at]),onChange:Qe=>u({[at]:nt(Qe.target.value)}),disabled:p,children:Ie.map(([Qe,Lt])=>s.jsx("option",{value:Qe,children:Lt},Qe))})},at))}),(()=>{const je=Q.autoFastForward&&typeof Q.autoFastForward=="object"?Q.autoFastForward:{},at=je.enabled!==!1,Ie=je.remoteNodes===!0,ot=je.mode==="continuous"?"continuous":"idle",nt=Qe=>u({autoFastForward:{...je,...Qe}});return s.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[s.jsx(vt,{label:"Auto fast-forward idle nodes",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:at?"enabled":"disabled",onChange:Qe=>nt({enabled:Qe.target.value==="enabled"}),disabled:p,children:[s.jsx("option",{value:"enabled",children:"Enabled (catch up online, clean, behind nodes)"}),s.jsx("option",{value:"disabled",children:"Disabled"})]})}),s.jsx(vt,{label:"Include remote nodes",hint:"Off = only the coordinator's local workspace is auto fast-forwarded.",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:Ie?"yes":"no",onChange:Qe=>nt({remoteNodes:Qe.target.value==="yes"}),disabled:p||!at,children:[s.jsx("option",{value:"no",children:"No (local workspace only)"}),s.jsx("option",{value:"yes",children:"Yes (delegate to remote owning daemons)"})]})}),s.jsx(vt,{label:"Detection mode",hint:"Idle = on a node's idle edge. Continuous = also scan periodically (base nodes only).",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ot,onChange:Qe=>nt({mode:Qe.target.value==="continuous"?"continuous":"idle"}),disabled:p||!at||!Ie,children:[s.jsx("option",{value:"idle",children:"Idle edge only"}),s.jsx("option",{value:"continuous",children:"Continuous (periodic scan)"})]})})]})})(),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(vt,{label:"When removing a node, its sessions…",hint:"Separate transcript cleanup from runtime/process cleanup.",children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:Q.sessionCleanupOnNodeRemove||"preserve",onChange:je=>u({sessionCleanupOnNodeRemove:je.target.value}),disabled:p,children:To.map(je=>s.jsx("option",{value:je.value,children:je.label},je.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((qe=To.find(je=>je.value===Q.sessionCleanupOnNodeRemove))==null?void 0:qe.description)||To[0].description})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving…"})]}),Se.hermesMcpConfig&&s.jsx(XC,{meshId:e.id,availableCliAgents:he}),Se.meshHostDaemonSection&&s.jsxs(Ft,{variant:"info",className:"mt-4",children:[s.jsx("strong",{children:"MCP Mode:"})," ",s.jsxs("code",{className:"bg-bg-secondary px-1 rounded text-xs",children:["adhdev mcp --repo-mesh ",e.id]})," · The mesh MCP server can be used directly from your CLI agent."]}),Ee&&Je&&s.jsx(Pm,{activeConv:s2({meshId:e.id,daemonId:z,meshName:e.name}),sendDaemonCommand:ae,onClose:()=>Be(!1)})]})}const Fr=new Map;function n2({daemons:e,primaryDaemonId:t,sendCommand:r,unwrapResult:n,normalizeMesh:a,features:o,loadDaemonMetadata:i}){const c=e.map(E=>E.id).filter(Boolean).sort().join(","),[d,p]=l.useState(()=>Fr.get(c)??[]),[u,m]=l.useState(null),[h,y]=l.useState(()=>!Fr.has(c)),[x,f]=l.useState(null),[j,k]=l.useState(!1),[b,w]=l.useState(""),[I,v]=l.useState(""),[g,S]=l.useState(""),[N,C]=l.useState(""),[R,T]=l.useState(""),_=l.useMemo(()=>e.find(E=>E.id===N),[e,N]),P=(_==null?void 0:_.workspaces)||[],B=l.useMemo(()=>xr((_==null?void 0:_.availableProviders)||[]),[_]);l.useEffect(()=>{!o.createDaemonPicker||!i||!N||!_||!(!_.workspaces||!_.availableProviders)||Promise.resolve(i(N,{minFreshMs:3e4})).catch(()=>{})},[o.createDaemonPicker,i,N,_]);const z=l.useMemo(()=>e.map(E=>E.id).filter(Boolean).sort().join(","),[e]),A=l.useCallback(async(E=!1)=>{const M=E||Fr.has(z);y(H=>M?H:!0);try{if(o.createDaemonPicker){const H=await Promise.allSettled(e.map(async J=>{if(!J.id)return[];const te=await r(J.id,"list_meshes",{}),oe=n(te);if((oe==null?void 0:oe.success)===!1)throw new Error(oe.error||"Failed to load meshes");return(Array.isArray(oe==null?void 0:oe.meshes)?oe.meshes:[]).map(q=>a(q,J.id)).filter(q=>q.id)})),Y=new Map;for(const J of H)if(J.status==="fulfilled")for(const te of J.value)Y.has(te.id)||Y.set(te.id,te);const G=Array.from(Y.values());p(G),Fr.set(z,G),f(null)}else{if(!t)return;const H=await r(t,"list_meshes");if(H!=null&&H.success){const Y=(H.meshes||[]).map(G=>a(G,t));p(Y),Fr.set(z,Y),f(null)}else f((H==null?void 0:H.error)||"Failed to load meshes")}}catch(H){f((H==null?void 0:H.message)||"Failed to load meshes")}finally{y(!1)}},[z,t,r,n,a,o.createDaemonPicker]);async function O(){var Y,G;const E=o.createDaemonPicker?N:t;if(!E||!b.trim())return;const M=g.trim(),H=I.trim();if(!(!M&&!H))try{const J={name:b.trim()};M&&(J.repoRemoteUrl=M),H&&(J.repoIdentity=H);const te=await r(E,"create_mesh",J),oe=n(te);if((oe==null?void 0:oe.success)===!1)throw new Error(oe.error||"Create failed");const q=typeof((Y=oe==null?void 0:oe.mesh)==null?void 0:Y.id)=="string"?oe.mesh.id:"";if(q&&o.createDaemonPicker&&R){const F=await r(E,"add_mesh_node",{meshId:q,daemonId:E,machineId:_==null?void 0:_.machineId,workspace:R,role:"host",providerPriority:nn(B)}),V=n(F);if((V==null?void 0:V.success)===!1)throw new Error(V.error||"Mesh created but failed to attach workspace")}k(!1),w(""),v(""),S(""),T(""),await A(),(G=oe==null?void 0:oe.mesh)!=null&&G.id&&m(oe.mesh.id)}catch(J){f((J==null?void 0:J.message)||"Create failed")}}async function $(E){var H;if(!confirm("Delete this mesh? This cannot be undone."))return;const M=((H=d.find(Y=>Y.id===E))==null?void 0:H.__sourceDaemonId)||t;try{const Y=await r(M,"delete_mesh",{meshId:E}),G=n(Y);if((G==null?void 0:G.success)===!1)throw new Error(G.error||"Failed to delete");u===E&&m(null),await A()}catch(Y){f((Y==null?void 0:Y.message)||"Delete failed")}}function L(){k(!1),w(""),v(""),S("")}return{meshes:d,setMeshes:p,selectedMeshId:u,setSelectedMeshId:m,loading:h,error:x,setError:f,showCreate:j,setShowCreate:k,createName:b,setCreateName:w,createRepoIdentity:I,setCreateRepoIdentity:v,createRepoRemoteUrl:g,setCreateRepoRemoteUrl:S,newMeshDaemonId:N,setNewMeshDaemonId:C,newMeshWorkspace:R,setNewMeshWorkspace:T,createPickerWorkspaces:P,createPickerProviders:B,loadMeshes:A,handleCreate:O,handleDelete:$,cancelCreate:L}}function a2({selectedMesh:e,selectedMeshId:t,primaryDaemonId:r,activeDaemonId:n,daemons:a,sendCommand:o,unwrapResult:i,loadLiveMesh:c,resolveCommandTarget:d,launchCoordinator:p,features:u,loadMeshes:m,loadQueue:h,queueSection:y,setError:x}){const[f,j]=l.useState({}),[k,b]=l.useState(null),[w,I]=l.useState(null),[v,g]=l.useState(!1),[S,N]=l.useState(""),[C,R]=l.useState([]),[T,_]=l.useState(""),[P,B]=l.useState(!1),[z,A]=l.useState(""),[O,$]=l.useState(!1),[L,E]=l.useState(null),[M,H]=l.useState(!1),[Y,G]=l.useState({override:"",append:""}),[J,te]=l.useState(!1),[oe,q]=l.useState({}),[F,V]=l.useState(null),pe=l.useMemo(()=>a.find(ae=>ae.id===T),[a,T]),be=(pe==null?void 0:pe.workspaces)||[],ue=l.useMemo(()=>xr((pe==null?void 0:pe.availableProviders)||[]),[pe]);async function Ne(){const ae=(e==null?void 0:e.__sourceDaemonId)||r;if(!t||!ae)return;const Q=S.trim();if(Q)try{const we={meshId:t,workspace:Q};u.addNodeDaemonPicker&&T&&(we.daemonId=T,we.machineId=pe==null?void 0:pe.machineId),we.providerPriority=br(C);const ke=await o(ae,"add_mesh_node",we),Le=i(ke);if((Le==null?void 0:Le.success)===!1)throw new Error(Le.error||"Add node failed");g(!1),N(""),R([]),_(""),B(!1),await m(),y||await h(t)}catch(we){x((we==null?void 0:we.message)||"Add node failed")}}async function se(ae){var Le;if(!e)return;const Q=ci(e),we=((Le=[{value:"preserve",label:"Preserve history and runtimes"},{value:"stop",label:"Stop live runtimes only"},{value:"delete_stopped",label:"Delete stopped sessions only"},{value:"stop_and_delete",label:"Stop and delete sessions"}].find(We=>We.value===Q.sessionCleanupOnNodeRemove))==null?void 0:Le.label)||"Preserve history and runtimes";if(!confirm(`Remove this node?
114
+ `})]})}function lC({daemonIds:e,meshId:t,sendData:r,onRevisionAdvance:n}){const a=l.useRef(new Map),o=l.useRef(n);o.current=n;const i=[...new Set(e.filter(Boolean))].sort().join(",");l.useEffect(()=>{a.current=new Map},[i,t]),l.useEffect(()=>{if(!t||!r)return;const c=[...new Set(e.filter(Boolean))];if(c.length===0)return;const d=c.map(p=>rs.subscribe({sendData:r},p,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${p}`,params:{includeSessions:!0}},u=>{if(u.topic!=="daemon.metadata")return;const m=u.meshStateRevisions;if(!m)return;const h=m[t]??m["*"];if(typeof h!="number")return;const y=a.current.get(p);a.current.set(p,h),y!==void 0&&h>y&&o.current()}));return()=>{for(const p of d)p()}},[i,t,r])}const cC={meshHostDaemonSection:!1,createDaemonPicker:!1,addNodeDaemonPicker:!1,queueSection:!0,coordinatorPrompt:!0,nodeInstruction:!0,hermesMcpConfig:!0,reviewInbox:!0},Fm=l.createContext(null);function dC(){const e=l.useContext(Fm);if(!e)throw new Error("useRepoMeshContext must be used inside RepoMeshProvider");return e}function uC({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("polyline",{points:"1 20 1 14 7 14"}),s.jsx("path",{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"})]})}function pC({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),s.jsx("circle",{cx:"18",cy:"6",r:"3"}),s.jsx("circle",{cx:"6",cy:"18",r:"3"}),s.jsx("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}function mC({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("polyline",{points:"3 6 5 6 21 6"}),s.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]})}function hC({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function fC({status:e}){const r={online:{color:"#22c55e",label:"Online"},dirty:{color:"#f59e0b",label:"Dirty",title:"Workspace has uncommitted changes"},offline:{color:"#6b7280",label:"Offline"},degraded:{color:"#ef4444",label:"Degraded",title:"P2P connection to this node is down or timed out — often transient. Wait and retry, or re-establish the node's connection."},enabled:{color:"#22c55e",label:"Enabled"},pending:{color:"#a855f7",label:"Pending"},assigned:{color:"#3b82f6",label:"Assigned"},completed:{color:"#22c55e",label:"Completed"},failed:{color:"#ef4444",label:"Failed"},unknown:{color:"#6b7280",label:"Unknown"}}[e]||{color:"#6b7280",label:e};return s.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] font-semibold px-2 py-0.5 rounded-md",style:{background:r.color+"15",color:r.color,border:`1px solid ${r.color}25`},title:r.title,children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full",style:{background:r.color}}),r.label]})}function xC(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function bC({meshes:e,loading:t,error:r,onDismissError:n,daemons:a,features:o,showCreate:i,onToggleCreate:c,createName:d,onCreateNameChange:p,createRepoIdentity:u,onCreateRepoIdentityChange:m,createRepoRemoteUrl:h,onCreateRepoRemoteUrlChange:y,newMeshDaemonId:x,onNewMeshDaemonIdChange:f,newMeshWorkspace:j,onNewMeshWorkspaceChange:k,createPickerWorkspaces:b,onSelectMesh:w,onCreate:I,onCancelCreate:v}){return s.jsxs(mn,{icon:s.jsx(ss,{}),title:"Repo Meshes",subtitle:`${e.length} mesh${e.length!==1?"es":""}`,widthClassName:"max-w-5xl",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:c,children:"+ Create Mesh"}),children:[r&&s.jsx(Ft,{variant:"error",onDismiss:n,className:"mb-4",children:r}),i&&s.jsxs(mt,{className:"mb-5 border-accent/40 animate-[fadeIn_0.3s_ease-out]",children:[s.jsx("h3",{className:"text-base font-bold mb-4",children:"Create Repo Mesh"}),o.createDaemonPicker&&s.jsx(yt,{label:"Create on machine",hint:"Mesh setup is stored by the selected daemon.",children:s.jsx("select",{className:"input w-full",value:x,onChange:g=>f(g.target.value),disabled:!a.length,children:a.length===0?s.jsx("option",{value:"",children:"No connected daemon"}):a.map(g=>s.jsx("option",{value:g.id,children:xC(g)},g.id))})}),o.createDaemonPicker&&s.jsx(yt,{label:"Workspace",hint:"Choose from workspaces registered by the selected daemon.",children:s.jsx("select",{className:"input w-full",value:j,onChange:g=>k(g.target.value),disabled:!x||!b.length,children:x?b.length===0?s.jsx("option",{value:"",children:"No registered workspaces"}):b.map(g=>s.jsx("option",{value:g.path,children:g.label?`${g.label} · ${g.path}`:g.path},g.id||g.path)):s.jsx("option",{value:"",children:"Select a machine first"})})}),s.jsx(yt,{label:"Name",children:s.jsx(ts,{value:d,onChange:g=>p(g.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(yt,{label:"Repo remote URL (optional)",hint:"Provide a remote URL OR a stable identity.",children:s.jsx(ts,{value:h,onChange:g=>y(g.target.value),placeholder:"https://github.com/user/repo"})}),s.jsx(yt,{label:"Repo identity (optional)",hint:"Provide a remote URL OR a stable identity.",children:s.jsx(ts,{value:u,onChange:g=>m(g.target.value),placeholder:"github.com/user/repo"})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:I,disabled:!d.trim()||!h.trim()&&!u.trim()||o.createDaemonPicker&&(!x||!j),children:"Create"}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:v,children:"Cancel"})]})]}),t?s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):e.length===0?s.jsx(Ma,{icon:s.jsx(ss,{}),title:"No Repo Meshes",description:a.length>0?"Create a mesh to get started.":"Connect an ADHDev daemon first.",action:s.jsx("button",{className:"btn btn-primary btn-sm",disabled:!a.length,onClick:c,children:"Create First Mesh"})}):s.jsx("div",{className:"flex flex-col gap-2.5",children:e.map(g=>{var S;return s.jsx("button",{type:"button",onClick:()=>w(g.id),className:"w-full text-left bg-bg-glass border border-border-subtle rounded-xl px-5 py-4 transition-colors hover:border-border-default hover:bg-bg-secondary/70",children:s.jsxs("div",{className:"flex justify-between items-start",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx(ss,{size:16}),s.jsx("span",{className:"font-bold text-sm",children:g.name})]}),s.jsxs("div",{className:"text-[12px] text-text-muted flex items-center gap-2",children:[s.jsx("span",{className:"font-mono",children:g.repoIdentity||g.repo_identity||"No repo identity"}),(g.defaultBranch||g.default_branch)&&s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(pC,{size:11}),g.defaultBranch||g.default_branch]})]})]}),s.jsxs("div",{className:"text-right text-[11px] text-text-muted shrink-0 ml-4",children:[s.jsx("div",{children:new Date(g.createdAt||g.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})}),s.jsxs("div",{className:"text-text-muted/60",children:[((S=g.nodes)==null?void 0:S.length)??g.nodeCount??0," node(s)"]})]})]})},g.id)})})]})}const gC=["claude-cli","codex-cli","gemini-cli","hermes-cli","antigravity-cli"],yC=[{kind:"rca",label:"Root-cause analysis",hint:"rca"},{kind:"design",label:"Design / approach review",hint:"design"},{kind:"claim_audit",label:"Verify specific claims",hint:"claim_audit"},{kind:"freeform",label:"Freeform review",hint:"freeform"}];function vC(){return{nodeId:"",provider:"",model:"",n:""}}function hd(e){var t;return(t=e.providers)!=null&&t.length?e.providers.filter(Boolean):(e.providerPriority??[]).filter(Boolean)}function wC(e){return{nodeId:e.nodeId??"",provider:e.provider??"",model:e.model??"",n:e.n!=null?String(e.n):""}}function jC(e){const t=[];for(let r=0;r<e.length;r++){const n=e[r],a=n.provider.trim();if(!a)return{error:`Slot ${r+1}: provider is required`};const o=n.nodeId.trim(),i=n.model.trim(),c=n.n.trim();let d;if(c){const p=Number(c);if(!Number.isFinite(p)||p<1)return{error:`Slot ${r+1}: replica count must be ≥ 1`};d=Math.floor(p)}t.push({provider:a,...o?{nodeId:o}:{},...i?{model:i}:{},...d!==void 0?{n:d}:{}})}return t.length===0?{error:"A kind binding needs at least one slot"}:{slots:t}}function kC({status:e,daemonId:t,sendDaemonCommand:r,availableProviders:n}){const{theme:a}=Ts(),o=l.useMemo(()=>Ls(a),[a]),i=l.useMemo(()=>cp(n),[n]),[c,d]=l.useState({}),[p,u]=l.useState(!1),[m,h]=l.useState(null),[y,x]=l.useState({}),[f,j]=l.useState(null),k=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(L=>({nodeId:L.nodeId,machineLabel:L.machineLabel,providers:L.providers,providerPriority:L.providerPriority})),[e==null?void 0:e.nodes]),b=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(L=>L.nodeId),[e==null?void 0:e.nodes]),w=l.useMemo(()=>Object.fromEntries(((e==null?void 0:e.nodes)??[]).map(L=>[L.nodeId,L.machineLabel||L.nodeId])),[e==null?void 0:e.nodes]),I=l.useMemo(()=>{const L={};for(const E of k)L[E.nodeId]=hd(E);return L},[k]),v=l.useMemo(()=>{const L=[...new Set(k.flatMap(hd).filter(Boolean))];return[...new Set([...L,...gC])].sort()},[k]),g=!!t&&!!r,S=L=>L&&typeof L=="object"&&"result"in L?L.result:L,N=l.useCallback(async()=>{if(!(!t||!r)){u(!0),h(null);try{const L=await r(t,"magi_kind_panel_list",{}),E=S(L);if((E==null?void 0:E.success)===!1)throw new Error(E.error||"Failed to load kind panels");d(E!=null&&E.kindPanels&&typeof E.kindPanels=="object"?E.kindPanels:{}),x({})}catch(L){h((L==null?void 0:L.message)||"Failed to load kind panels")}finally{u(!1)}}},[t,r]);l.useEffect(()=>{N()},[N]);const C=l.useCallback(L=>{if(y[L])return y[L];const E=c[L];return E?E.map(wC):[]},[y,c]),R=(L,E)=>{x(M=>({...M,[L]:E}))},T=(L,E,M)=>{const H=C(L);R(L,H.map((Y,G)=>G===E?{...Y,...M}:Y))},_=L=>{R(L,[...C(L),vC()])},P=(L,E)=>{R(L,C(L).filter((M,H)=>H!==E))},B=l.useCallback(async L=>{if(!t||!r)return;const E=jC(C(L));if("error"in E){h(`${L}: ${E.error}`);return}j(L),h(null);try{const M=await r(t,"magi_kind_panel_set",{kind:L,slots:E.slots}),H=S(M);if((H==null?void 0:H.success)===!1)throw new Error(H.error||"Failed to save kind binding");await N()}catch(M){h((M==null?void 0:M.message)||"Failed to save kind binding")}finally{j(null)}},[t,r,C,N]),z=l.useCallback(async L=>{if(!(!t||!r)&&confirm(`Remove the MAGI panel binding for "${L}"?`)){j(L),h(null);try{const E=await r(t,"magi_kind_panel_remove",{kind:L}),M=S(E);if((M==null?void 0:M.success)===!1)throw new Error(M.error||"Failed to remove kind binding");await N()}catch(E){h((E==null?void 0:E.message)||"Failed to remove kind binding")}finally{j(null)}}},[t,r,N]),A=`w-full rounded-lg border px-2.5 py-1.5 text-xs ${o.isDark?"border-white/10 bg-slate-950/40 text-slate-100 placeholder:text-slate-500":"border-slate-300 bg-white text-slate-900 placeholder:text-slate-400"}`,O="btn btn-primary btn-sm",$="btn btn-secondary btn-sm";return s.jsxs("div",{className:"flex flex-col gap-3 p-1",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("p",{className:`text-[12px] ${o.textSecondary}`,children:"Pick which agents review each task type. Add one row per agent."}),s.jsx("div",{className:"ml-auto flex items-center gap-2",children:s.jsx("button",{type:"button",className:$,onClick:()=>void N(),disabled:p||!g,children:p?"Loading…":"Refresh"})})]}),!g&&s.jsx("div",{className:`rounded-xl border p-3 text-[12px] ${o.textSecondary} ${o.isDark?"border-white/10":"border-slate-200"}`,children:"Connect to a coordinator daemon to manage kind → panel bindings."}),m&&s.jsx("div",{className:"rounded-xl border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-[12px] text-rose-300",children:m}),s.jsx("div",{className:"flex flex-col gap-3",children:yC.map(({kind:L,label:E,hint:M})=>{const H=C(L),Y=!!c[L],G=f===L;return s.jsxs("div",{className:`${o.cardClass} rounded-2xl p-4 flex flex-col gap-3`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[13px] font-semibold ${o.textPrimary}`,children:E}),s.jsx("span",{className:`font-mono text-[10px] ${o.textMuted}`,children:M}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${Y?"border-emerald-400/30 bg-emerald-500/10 text-emerald-300":"border-slate-400/20 bg-slate-500/10 text-slate-300"}`,children:Y?`${c[L].length} agent${c[L].length===1?"":"s"}`:"off"})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[H.length===0&&s.jsx("div",{className:`rounded-xl border p-2.5 text-[11px] ${o.textSecondary} ${o.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:"No agents yet — add one to enable this review type."}),H.map((J,te)=>{const oe=J.nodeId?I[J.nodeId]??[]:[],q=J.nodeId&&oe.length?oe:v;return s.jsxs("div",{className:`rounded-xl border p-2.5 grid grid-cols-1 sm:grid-cols-[1fr_1fr_1fr_auto_auto] gap-x-2 gap-y-1 items-start ${o.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${o.textSecondary}`,children:"Machine"}),s.jsxs("select",{className:A,value:J.nodeId,onChange:F=>T(L,te,{nodeId:F.target.value}),title:"Which machine runs this agent. Leave on “any” to let the coordinator route by tags.",children:[s.jsx("option",{value:"",children:"Any machine"}),b.map(F=>s.jsx("option",{value:F,children:w[F]??F},F)),J.nodeId&&!b.includes(J.nodeId)&&s.jsxs("option",{value:J.nodeId,children:[w[J.nodeId]??J.nodeId," (offline)"]})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${o.textSecondary}`,children:"Provider *"}),s.jsxs("select",{className:A,value:J.provider,onChange:F=>T(L,te,{provider:F.target.value}),title:"The AI agent this slot runs.",children:[s.jsx("option",{value:"",children:"Select provider…"}),q.map(F=>s.jsx("option",{value:F,children:F},F)),J.provider&&!q.includes(J.provider)&&s.jsx("option",{value:J.provider,children:J.provider})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${o.textSecondary}`,children:"Model"}),(()=>{var pe;const F=(J.provider?(pe=i.get(J.provider))==null?void 0:pe.models:void 0)??[],V=!!J.model&&F.length>0&&!F.includes(J.model);return F.length>0&&!V?s.jsxs("select",{className:A,value:F.includes(J.model)?J.model:"",title:"Optional model override (best-effort). Blank uses the provider default.",onChange:be=>T(L,te,{model:be.target.value==="__custom__"?" ":be.target.value}),children:[s.jsx("option",{value:"",children:"default"}),F.map(be=>s.jsx("option",{value:be,children:be},be)),s.jsx("option",{value:"__custom__",children:"Custom…"})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:A,value:J.model.trim(),placeholder:"default",title:"Optional model override (best-effort). Blank uses the provider default.",onChange:be=>T(L,te,{model:be.target.value})}),F.length>0&&s.jsx("button",{type:"button",className:`self-start bg-transparent border-none cursor-pointer p-0 text-[10px] ${o.textSecondary} hover:underline`,onClick:()=>T(L,te,{model:""}),children:"← Back to model list"})]})})()]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${o.textSecondary}`,children:"Copies"}),s.jsx("input",{className:`${A} sm:w-16`,value:J.n,placeholder:"1",inputMode:"numeric",title:"How many parallel copies of this agent to run. Blank = 1.",onChange:F=>T(L,te,{n:F.target.value})})]}),s.jsx("button",{type:"button",className:`${$} sm:mt-[18px] inline-flex h-8 w-8 items-center justify-center p-0`,onClick:()=>P(L,te),"aria-label":"Remove agent",title:"Remove agent",children:"✕"})]},te)}),s.jsx("div",{children:s.jsx("button",{type:"button",className:$,onClick:()=>_(L),disabled:!g,children:"+ Add agent"})})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:O,onClick:()=>void B(L),disabled:G||!g,children:G?"Saving…":"Save"}),s.jsx("button",{type:"button",className:$,onClick:()=>void z(L),disabled:G||!g||!Y,title:Y?"Clear this kind binding":"Nothing to remove — this kind is unconfigured",children:"Remove binding"})]})]},L)})})]})}function NC({daemonId:e,meshId:t,cliType:r,sendCommand:n}){const[a,o]=l.useState(!1),[i,c]=l.useState(!1),[d,p]=l.useState(null),[u,m]=l.useState(null),[h,y]=l.useState(null),x=l.useCallback(async()=>{if(!e||!t){p("Connect a daemon to preview the default.");return}c(!0),p(null);try{const j=await n(e,"coordinator_prompt_preview",{meshId:t,cliType:r}),k=j!=null&&j.result&&typeof j.result=="object"?j.result:j;if(!(k!=null&&k.success)){p((k==null?void 0:k.error)||"Failed to render the default prompt");return}m(typeof k.prompt=="string"?k.prompt:""),y(typeof k.bytes=="number"?k.bytes:null)}catch(j){p((j==null?void 0:j.message)||String(j))}finally{c(!1)}},[e,t,r,n]),f=l.useCallback(()=>{const j=!a;o(j),j&&u===null&&!i&&x()},[a,u,i,x]);return s.jsxs("div",{className:"mt-2",children:[s.jsxs("button",{type:"button",onClick:f,className:"inline-flex items-center gap-1 text-[12px] text-accent-primary bg-transparent border-none cursor-pointer p-0",children:[s.jsx("span",{className:`transition-transform ${a?"rotate-90":""}`,"aria-hidden":!0,children:"▸"}),a?"Hide the default prompt":"View the default prompt",s.jsxs("span",{className:"text-text-muted",children:["(",r,")"]})]}),a&&s.jsxs("div",{className:"mt-2",children:[i&&s.jsx("div",{className:"text-[12px] text-text-muted",children:"Rendering…"}),d&&s.jsxs("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:[d,s.jsx("button",{type:"button",onClick:()=>void x(),className:"ml-2 underline bg-transparent border-none cursor-pointer text-amber-300",children:"Retry"})]}),!i&&!d&&u!==null&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between text-[11px] text-text-muted",children:[s.jsx("span",{children:"This is what a coordinator session gets when Override is empty."}),h!==null&&s.jsxs("span",{children:[(h/1024).toFixed(1)," KB"]})]}),s.jsx("textarea",{readOnly:!0,value:u,rows:14,className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-secondary font-mono",onFocus:j=>j.currentTarget.select()})]})]})]})}const SC=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function CC(e){const t=SC(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function IC(e){const t=e==null?void 0:e.missions;return Array.isArray(t)?t:[]}function AC(e){return typeof e.goal=="string"&&e.goal?{text:e.goal,truncated:!1}:{text:e.goalPreview??"",truncated:e.goalTruncated===!0}}const MC=["active","paused","completed","abandoned"];function fd(e){return(e.status||"active").toLowerCase()}const _C=8;function TC({status:e,daemonId:t,meshId:r,sendCommand:n}){const a=l.useMemo(()=>IC(e),[e]),[o,i]=l.useState({}),[c,d]=l.useState({}),[p,u]=l.useState(!1),[m,h]=l.useState(null),[y,x]=l.useState("active"),[f,j]=l.useState(!1),k=l.useMemo(()=>{const N={};for(const C of a){const R=fd(C);N[R]=(N[R]||0)+1}return N},[a]),b=l.useMemo(()=>y==="all"?a:a.filter(N=>fd(N)===y),[a,y]),w=f?b:b.slice(0,_C),I=b.length-w.length,v=!!t&&a.length>0,g=l.useCallback(async()=>{if(t){u(!0),h(null);try{const N=await n(t,"mesh_status",{meshId:r,verbose:!0}),C=CC(N),R=Array.isArray(C==null?void 0:C.missions)?C.missions:[],T={};for(const _ of R)_.id&&typeof _.goal=="string"&&_.goal&&(T[_.id]=_.goal);i(_=>({..._,...T}))}catch(N){h(N instanceof Error?N.message:"Failed to fetch full mission goals")}finally{u(!1)}}},[t,r,n]),S=l.useCallback(N=>{d(C=>({...C,[N]:!C[N]})),!c[N]&&!o[N]&&g()},[c,o,g]);return a.length===0?null:s.jsxs(mt,{title:"Missions",description:"Active and historical missions reported by the coordinator. Expand a goal to fetch its full text on demand.",children:[m&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400",children:m}),s.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-1.5",children:[MC.filter(N=>(k[N]||0)>0).map(N=>s.jsxs("button",{type:"button",onClick:()=>{x(N),j(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] capitalize transition-colors ${y===N?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:[N," ",k[N]]},N)),s.jsxs("button",{type:"button",onClick:()=>{x("all"),j(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] transition-colors ${y==="all"?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:["All ",a.length]})]}),b.length===0&&s.jsxs("div",{className:"text-[12px] text-text-muted",children:["No ",y," missions."]}),s.jsx("div",{className:"flex flex-col gap-2",children:w.map(N=>{var z;const C=c[N.id]===!0,R=o[N.id],T=AC(N),_=C&&R?R:T.text,P=C&&!R&&T.truncated,B=((z=N.tasks)==null?void 0:z.total)??0;return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 px-3 py-2.5",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-text-primary",title:N.title,children:N.title||N.id}),N.status&&s.jsx("span",{className:"shrink-0 rounded-full border border-border-subtle px-2 py-0.5 text-[10px] uppercase tracking-wide text-text-muted",children:N.status}),B>0&&s.jsxs("span",{className:"shrink-0 text-[11px] text-text-muted",children:[B," task",B===1?"":"s"]})]}),_&&s.jsxs("div",{className:`mt-1.5 whitespace-pre-wrap text-[12px] leading-5 text-text-secondary ${C?"max-h-72 overflow-y-auto":"line-clamp-2"}`,children:[_,P&&s.jsx("span",{className:"text-text-muted",children:" … (full goal unavailable)"})]}),(T.truncated||R)&&v&&s.jsx("button",{type:"button",className:"mt-1.5 text-[12px] text-accent-primary hover:underline disabled:opacity-50",onClick:()=>S(N.id),disabled:p,children:C?"Show less":p&&!R?"Loading…":"Show full goal"})]},N.id)})}),I>0&&s.jsxs("button",{type:"button",className:"mt-2 text-[12px] text-accent-primary hover:underline",onClick:()=>j(!0),children:["Show ",I," more"]})]})}const LC=["","low","medium","high"],RC={easy:"Easy",medium:"Medium",difficult:"Difficult",freeform:"Freeform"};function xd(e){return{provider:e.provider||"",model:e.model||"",thinkingLevel:e.thinkingLevel||"",difficulty:Array.isArray(e.difficulty)?e.difficulty:[],capability:Array.isArray(e.capability)?e.capability:[],maxParallel:e.maxParallel!=null?String(e.maxParallel):""}}function bd(e){const t=e.provider.trim();if(!t)return null;const r=e.model.trim(),n=e.thinkingLevel.trim()||void 0,a=Number(e.maxParallel),o=Number.isFinite(a)&&a>0?Math.floor(a):void 0;return{provider:t,...r?{model:r}:{},...n?{thinkingLevel:n}:{},...e.difficulty.length?{difficulty:e.difficulty}:{},...e.capability.length?{capability:e.capability}:{},...o!==void 0?{maxParallel:o}:{}}}function PC(){return{provider:"",model:"",thinkingLevel:"",difficulty:[],capability:[],maxParallel:""}}const Ds="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function DC({slots:e,availableProviders:t,saving:r,onSave:n}){const[a,o]=l.useState(()=>e.map(xd)),i=l.useMemo(()=>JSON.stringify(e),[e]);l.useEffect(()=>{o(e.map(xd))},[i]);const c=l.useMemo(()=>[...new Set(t.map(k=>k.type).filter(Boolean))],[t]),d=l.useMemo(()=>cp(t),[t]),p=l.useMemo(()=>{const k=a.map(bd).filter(Boolean);return JSON.stringify(k)!==JSON.stringify(e)},[a,e]),u=(k,b)=>o(w=>w.map((I,v)=>v===k?{...I,...b}:I)),m=(k,b)=>o(w=>w.map((I,v)=>{var N;if(v!==k)return I;const g=((N=d.get(b))==null?void 0:N.models)??[],S=!I.model||g.length===0||g.includes(I.model);return{...I,provider:b,...S?{}:{model:""}}})),h=k=>o(b=>b.filter((w,I)=>I!==k)),y=()=>o(k=>[...k,PC()]),x=(k,b)=>o(w=>{const I=k+b;if(I<0||I>=w.length)return w;const v=[...w];return[v[k],v[I]]=[v[I],v[k]],v}),f=(k,b)=>o(w=>w.map((I,v)=>{if(v!==k)return I;const g=I.difficulty.includes(b);return{...I,difficulty:g?I.difficulty.filter(S=>S!==b):[...I.difficulty,b]}})),j=()=>n(a.map(bd).filter(Boolean));return s.jsxs("div",{className:"flex flex-col gap-2",onClick:k=>k.stopPropagation(),children:[a.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:"No capability slots set — that's fine. This node still runs tasks using its provider priority order (below). Slots are optional fine-tuning: add one to route specific task difficulties or capabilities to a specific tool."}),a.map((k,b)=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/40 p-2.5",children:[s.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[s.jsxs("span",{className:"text-[11px] font-semibold text-text-muted",children:["#",b+1]}),s.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:b===0,onClick:()=>x(b,-1),title:"Move up",children:"↑"}),s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:b===a.length-1,onClick:()=>x(b,1),title:"Move down",children:"↓"}),s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-status-error/30 text-status-error hover:bg-status-error/10",onClick:()=>h(b),"aria-label":`Remove slot ${b+1}`,children:s.jsx(wt,{size:12})})]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:"Provider"}),c.length>0?s.jsxs("select",{className:Ds,value:k.provider,onChange:w=>m(b,w.target.value),children:[s.jsx("option",{value:"",children:"(select)"}),c.map(w=>s.jsx("option",{value:w,children:w},w)),k.provider&&!c.includes(k.provider)&&s.jsx("option",{value:k.provider,children:k.provider})]}):s.jsx("input",{className:Ds,value:k.provider,placeholder:"claude-cli",onChange:w=>u(b,{provider:w.target.value})})]}),(()=>{var S;const w=d.get(k.provider),I=(w==null?void 0:w.models)??[],v=(S=w==null?void 0:w.thinking)!=null&&S.length?["",...w.thinking]:LC,g=!!k.model&&I.length>0&&!I.includes(k.model);return s.jsxs(s.Fragment,{children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:"Model"}),I.length>0&&!g?s.jsxs("select",{className:Ds,value:I.includes(k.model)?k.model:"",onChange:N=>u(b,{model:N.target.value==="__custom__"?" ":N.target.value}),children:[s.jsx("option",{value:"",children:"(provider default)"}),I.map(N=>s.jsx("option",{value:N,children:N},N)),s.jsx("option",{value:"__custom__",children:"Custom…"})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:Ds,value:k.model.trim(),placeholder:k.provider?`${k.provider} model`:"model",onChange:N=>u(b,{model:N.target.value})}),I.length>0&&s.jsx("button",{type:"button",className:"self-start bg-transparent border-none cursor-pointer p-0 text-[10px] text-text-muted hover:underline",onClick:()=>u(b,{model:""}),children:"← Back to model list"})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:"Thinking"}),s.jsx("select",{className:Ds,value:k.thinkingLevel,onChange:N=>u(b,{thinkingLevel:N.target.value}),children:v.map(N=>s.jsx("option",{value:N,children:N||"(default)"},N||"_default"))})]})]})})()]}),s.jsxs("div",{className:"mt-2",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:"Difficulty (blank = all)"}),s.jsx("div",{className:"mt-1 flex flex-wrap gap-1.5",children:_x.map(w=>{const I=k.difficulty.includes(w);return s.jsx("button",{type:"button",className:`rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors ${I?"border-accent-primary/60 bg-accent-primary/15 text-accent-primary":"border-border-subtle bg-bg-primary/60 text-text-muted hover:text-text-primary"}`,onClick:()=>f(b,w),children:RC[w]},w)})})]}),s.jsxs("div",{className:"mt-2 grid grid-cols-1 sm:grid-cols-2 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:"Capability tags (comma-separated)"}),s.jsx("input",{className:Ds,value:k.capability.join(", "),placeholder:"worktree, os=darwin",onChange:w=>u(b,{capability:w.target.value.split(",").map(I=>I.trim()).filter(Boolean)})})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:"Max parallel (per slot)"}),s.jsx("input",{type:"number",inputMode:"numeric",min:1,className:Ds,value:k.maxParallel,placeholder:"unlimited",onChange:w=>u(b,{maxParallel:w.target.value})})]})]})]},b)),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1",onClick:y,children:[s.jsx(wi,{size:13})," Add slot"]}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm ml-auto",onClick:j,disabled:!!r||!p,children:r?"Saving…":"Save slots"})]})]})}function $C(e){const t=new Map;for(const r of e)r!=null&&r.id&&t.set(r.id,xr(r.availableProviders||[]));return t}function EC(e,t){const r=String(e.daemon_id||e.daemonId||"");return r&&t.has(r)?t.get(r):!r&&t.size===1?[...t.values()][0]:[]}function BC(e){var d,p,u;const t=e,r=[],n=Array.isArray(t.capabilities)?t.capabilities:[];for(const m of n){const h=typeof m=="string"?m.trim():"";h&&r.push({tag:h,custom:!0})}const a=(((d=t.userOverrides)==null?void 0:d.platform)||t.reportedPlatform||"").toString().trim(),o=(((p=t.userOverrides)==null?void 0:p.arch)||t.reportedArch||"").toString().trim();a&&r.push({tag:`os=${a}`,custom:!1}),o&&r.push({tag:`arch=${o}`,custom:!1});const i=Array.isArray((u=t.policy)==null?void 0:u.providerPriority)?String(t.policy.providerPriority[0]||"").trim():"";i&&r.push({tag:`provider=${i}`,custom:!1});const c=typeof t.worktreeBranch=="string"?t.worktreeBranch.trim():"";return t.isLocalWorktree===!0&&c&&r.push({tag:`worktree=${c}`,custom:!1}),r}function FC(e){const t=e.capabilities;return Array.isArray(t)?t.map(r=>typeof r=="string"?r.trim():"").filter(Boolean):[]}const OC=["os=","arch=","provider=","worktree=","converge="];function HC({node:e,saving:t,onSave:r}){const n=l.useMemo(()=>BC(e).filter(x=>!x.custom),[e]),a=l.useMemo(()=>FC(e),[e]),[o,i]=l.useState(a),[c,d]=l.useState(""),p=JSON.stringify(o)!==JSON.stringify(a),m=(x=>{const f=x.trim();return f?/\s/.test(f)?"Tags cannot contain spaces.":OC.some(j=>f.toLowerCase().startsWith(j))?"That prefix is auto-derived — pick a different tag.":o.includes(f)?"Already added.":null:null})(c);function h(){const x=c.trim();!x||m||(i(f=>[...f,x]),d(""))}function y(x){i(f=>f.filter(j=>j!==x))}return s.jsxs("div",{className:"mt-2",onClick:x=>x.stopPropagation(),children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wide text-text-muted mr-1",children:"Routing tags"}),n.map(x=>s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-1.5 py-0.5 font-mono text-[10px] text-text-muted",title:"Auto-derived — can't be edited",children:x.tag},x.tag)),o.map(x=>s.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 font-mono text-[10px] text-accent-primary",title:"Custom tag",children:[x,s.jsx("button",{type:"button",className:"text-accent-primary/70 hover:text-accent-primary bg-transparent border-none cursor-pointer p-0 leading-none",onClick:()=>y(x),disabled:t,"aria-label":`Remove ${x}`,children:"×"})]},x))]}),s.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-2",children:[s.jsx("input",{type:"text",value:c,onChange:x=>d(x.target.value),onKeyDown:x=>{x.key==="Enter"&&(x.preventDefault(),h())},placeholder:"add a custom tag (e.g. test-runner)",disabled:t,className:"min-w-[12rem] flex-1 px-2 py-1 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-primary"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:h,disabled:t||!c.trim()||!!m,children:"Add"}),p&&s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>r(o),disabled:t,children:t?"Saving…":"Save tags"})]}),m&&s.jsx("div",{className:"mt-1 text-[11px] text-amber-400",children:m}),o.length===0&&n.length===0&&s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"No routing tags — tasks can run here without matching any specific capability. Tags are optional."})]})}function WC(e,t){return t.filter(r=>r.status!=="assigned"?!1:(r.assignedNodeId||r.nodeId)===e.id)}function KC(e){const t=e.assignedSessionId||e.sessionId||"unassigned session",r=e.message.length>80?`${e.message.slice(0,77)}…`:e.message;return`${t}: ${r}`}function UC(e){var n;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((n=e.policy)==null?void 0:n.providerPriority)?e.policy.providerPriority:[],r=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>r.has(a)?!1:(r.add(a),!0))}function zC(e){const t=UC(e);return t.length?{configured:!0,label:t.join(" → ")}:{configured:!1,label:"not configured",launchBlockedMessage:"No provider detected on this node — task launch is blocked until a provider is selected or installed. (Empty capability slots alone do not block launch; this means no provider was found.)"}}function GC(e){return e.isLocalWorktree===!0}function VC(e,t){const r=t;return[...Array.isArray(r==null?void 0:r.cliSessions)?r.cliSessions:[],...Array.isArray(r==null?void 0:r.acpSessions)?r.acpSessions:[],...Array.isArray(r==null?void 0:r.sessions)?r.sessions:[]].filter(a=>{var o;return((o=a==null?void 0:a.settings)==null?void 0:o.meshNodeId)===e.id||(a==null?void 0:a.workspace)===e.workspace}).map(a=>{var o;return{id:a.sessionId||a.id||a.instanceId||"unknown",provider:a.providerType||a.cliType||a.acpType||a.type||"unknown",status:a.status||((o=a.activeChat)==null?void 0:o.status)||"unknown"}})}function gd(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function qC(e,t){var r;return(e==null?void 0:e.ownerName)||(e==null?void 0:e.userName)||((r=e==null?void 0:e.user)==null?void 0:r.name)||t||"You"}function YC({nodes:e,meshQueue:t,activeDaemon:r,daemons:n,selectedMeshId:a,userName:o,features:i,coordinatorDaemonId:c,availableCliProviders:d,savingNodeSlotsId:p,onUpdateNodeSlots:u,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:h,nodeSystemPromptDrafts:y,onNodeSystemPromptDraftChange:x,savingNodeSystemPromptId:f,onSaveNodeSystemPrompt:j,selectedNodeId:k,onSelectNode:b,showAddNode:w,onShowAddNode:I,onCancelAddNode:v,nodeWorkspace:g,onNodeWorkspaceChange:S,nodeProviderPriority:N,onNodeProviderPriorityChange:C,nodeDaemonId:R,onNodeDaemonIdChange:T,nodeCustomPath:_,onNodeCustomPathChange:P,nodePickerWorkspaces:B,nodePickerProviders:z,attachableDaemons:A,onAddNode:O,onRemoveNode:$}){const L=l.useMemo(()=>$C(n),[n]),E=l.useMemo(()=>e.filter(M=>!GC(M)),[e]);return s.jsxs(mt,{title:i.addNodeDaemonPicker?`Nodes & Providers (${E.length})`:"Nodes & Providers",description:i.addNodeDaemonPicker?"Workspaces in this mesh and their preferred AI tools. Setup inventory only — live graph/git/session truth is owned by the Mesh Host status above.":"Workspaces participating in this mesh and their preferred AI tools.",children:[i.addNodeDaemonPicker&&s.jsxs("div",{className:"mb-4 rounded-xl border border-border-subtle bg-bg-secondary/60 p-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Machine daemon candidates"}),s.jsx("div",{className:"text-[12px] text-text-muted",children:"Choose connected daemons to attach to the selected Mesh Host setup."})]}),s.jsxs("span",{className:"text-[11px] text-text-muted",children:[A.length," available"]})]}),n.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:"No connected machine daemons are currently available."}):A.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:"All connected machine daemons are already attached."}):s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:A.map(M=>s.jsxs("button",{type:"button",className:`text-left rounded-lg border px-3 py-2 transition-colors ${M.id===c?"border-accent-primary/50 bg-accent-primary/10":"border-border-subtle bg-bg-primary hover:border-border-default"}`,onClick:()=>{T(M.id),S(""),P(!1),C(nn(xr(M.availableProviders||[]))),I()},children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-sm font-medium truncate",children:gd(M)}),M.id===c&&s.jsx("span",{className:"text-[10px] text-accent-primary",children:"selected host"})]}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted font-mono truncate",children:M.id}),s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted",children:[(M.workspaces||[]).length," workspace(s) detected"]})]},M.id))})]}),!w&&s.jsxs("button",{className:"btn btn-primary btn-sm mb-4 inline-flex items-center gap-1.5",onClick:I,children:[s.jsx(hC,{size:13})," ",i.addNodeDaemonPicker?"Attach machine":"Add node"]}),w&&s.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass animate-[fadeIn_0.3s_ease-out]",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h4",{className:"text-sm font-bold",children:i.addNodeDaemonPicker?"Attach Machine Daemon":"Add Node"}),s.jsx("button",{onClick:()=>{v(),T(""),P(!1)},className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(wt,{size:16})})]}),i.addNodeDaemonPicker&&s.jsx(yt,{label:"Machine",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:R,onChange:M=>{var H;T(M.target.value),S(""),P(!1),C(nn(xr(((H=n.find(Y=>Y.id===M.target.value))==null?void 0:H.availableProviders)||[])))},children:[s.jsx("option",{value:"",children:"Select a machine..."}),n.map(M=>s.jsx("option",{value:M.id,children:gd(M)},M.id))]})}),(i.addNodeDaemonPicker?R:!0)&&s.jsx(yt,{label:"Workspace Path",children:i.addNodeDaemonPicker&&!_&&B.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex flex-col gap-1.5 mb-2",children:B.map(M=>s.jsxs("button",{type:"button",className:`text-left text-xs px-3 py-2 rounded-lg border transition-colors ${g===M.path?"border-accent-primary bg-accent-primary/10 text-text-primary":"border-border-subtle bg-bg-primary hover:bg-violet-500/10 text-text-primary"}`,onClick:()=>S(M.path),children:[s.jsx("span",{className:"font-medium block truncate",children:M.label||M.path.split("/").pop()}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:M.path})]},M.id||M.path))}),s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{P(!0),S("")},children:"Or enter a custom path →"})]}):s.jsx(s.Fragment,{children:i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[s.jsx(ts,{value:g,onChange:M=>S(M.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:M=>{M.key==="Enter"&&O()}}),B.length>0&&s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0 mt-1",onClick:()=>{P(!1),S("")},children:"← Pick from saved workspaces"})]}):(()=>{var Y;const M=Array.isArray(r==null?void 0:r.workspaces)?r.workspaces:[],H=`mesh-add-node-workspaces-${a||"new"}`;return s.jsxs(s.Fragment,{children:[s.jsx(ts,{value:g,onChange:G=>S(G.target.value),placeholder:((Y=M[0])==null?void 0:Y.path)||"/Users/dev/projects/myapp",list:M.length>0?H:void 0,autoFocus:!0}),M.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("datalist",{id:H,children:M.map(G=>s.jsx("option",{value:G.path,children:G.label||G.path},G.id||G.path))}),s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:M.slice(0,6).map(G=>s.jsx("button",{type:"button",onClick:()=>S(G.path),className:"text-[11px] px-2 py-0.5 rounded-full border border-border-subtle hover:border-accent-primary/50 text-text-muted hover:text-text-primary transition-colors bg-transparent cursor-pointer",title:G.path,children:G.label||G.path.split("/").filter(Boolean).pop()||G.path},G.id||G.path))})]})]})})()})}),s.jsx(yt,{label:"Preferred AI tools (in order)",hint:"Order used when launching without an explicit provider.",children:s.jsx(k0,{value:N,availableProviders:i.addNodeDaemonPicker?z:d,onChange:C})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:O,disabled:!g.trim()||i.addNodeDaemonPicker&&!R,className:"btn btn-primary btn-sm",children:"Add"}),s.jsx("button",{onClick:()=>{v(),T(""),P(!1)},className:"btn btn-secondary btn-sm",children:"Cancel"})]})]}),i.addNodeDaemonPicker&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-300 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:"Setup inventory only — live git/session/branch detail is shown in the graph popup after direct aggregate mesh_status truth is available from the Mesh Host."}),E.length===0?s.jsx(Ma,{icon:s.jsx(mr,{}),title:"No nodes",description:"Add a workspace to this mesh."}):s.jsx("div",{className:"flex flex-col gap-2",children:E.map(M=>{var oe;const H=zC(M),Y=WC(M,t),G=VC(M,r),J=k===M.id,te=M.status||M.machine_status||(Y.length>0||G.length>0?"active":"enabled");return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary transition-colors ${i.addNodeDaemonPicker?"bg-bg-glass border-border-subtle rounded-xl px-5 py-4":`cursor-pointer ${J?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`}`,role:i.addNodeDaemonPicker?void 0:"button",tabIndex:i.addNodeDaemonPicker?void 0:0,onClick:i.addNodeDaemonPicker?void 0:()=>b(J?null:M.id),onKeyDown:i.addNodeDaemonPicker?void 0:q=>{(q.key==="Enter"||q.key===" ")&&(q.preventDefault(),b(J?null:M.id))},children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.addNodeDaemonPicker?s.jsx("span",{className:"font-semibold text-sm text-text-primary truncate",children:M.machine_label||M.machine_nickname||M.hostname||M.workspace}):s.jsx("span",{className:"text-sm font-medium",children:M.workspace.split("/").pop()}),i.addNodeDaemonPicker&&s.jsx(fC,{status:te}),i.addNodeDaemonPicker&&s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:"setup inventory"})]}),i.addNodeDaemonPicker&&s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Owner: ",qC(n.find(q=>q.id===String(M.daemon_id||"")),o)," · Machine: ",M.machine_label||M.daemon_id||M.workspace]}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:M.workspace}),s.jsx(HC,{node:M,saving:m===M.id,onSave:q=>h(M,q)}),i.addNodeDaemonPicker&&s.jsx("div",{className:"mt-2 text-[11px] text-amber-300",children:"Live branch/git/session detail is graph-owned; use the node popup in the live graph above."}),s.jsxs("div",{className:"mt-3 max-w-2xl",onClick:q=>q.stopPropagation(),children:[s.jsx(yt,{label:"Preferred AI tools (capability slots)",hint:"Each slot = provider + model + thinking + the task difficulty/capability it handles + a per-slot parallel cap. Tasks are matched to the best-fit slot (order = preference). With no slots, this node uses its legacy provider order.",children:s.jsx(DC,{slots:Array.isArray((oe=M.policy)==null?void 0:oe.slots)?M.policy.slots:[],availableProviders:EC(M,L),saving:p===M.id,onSave:q=>u(M,q)})}),i.nodeInstruction&&s.jsxs(yt,{label:"Node instruction (optional)",hint:"Surfaced in the coordinator system prompt as 📌 Node instruction.",children:[s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:3,value:y[M.id]??"",onChange:q=>{const F=q.target.value;x(M.id,F)},onClick:q=>q.stopPropagation(),disabled:f===M.id,placeholder:"e.g. 'Run only smoke tests here', 'Use opus on this node'"}),s.jsx("div",{className:"mt-2 flex items-center gap-2",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:q=>{q.stopPropagation(),j(M)},disabled:f===M.id,children:f===M.id?"Saving…":"Save instruction"})})]})]})]}),s.jsx("button",{className:`transition-colors bg-transparent border-none cursor-pointer ${i.addNodeDaemonPicker?"btn btn-sm text-text-muted hover:text-red-400":"text-text-muted hover:text-red-400"}`,onClick:q=>{q.stopPropagation(),$(M.id)},title:"Remove node",children:s.jsx(mC,{size:14})})]}),s.jsxs("details",{className:"mt-3 group",onClick:q=>q.stopPropagation(),children:[s.jsxs("summary",{className:"cursor-pointer select-none text-[12px] text-text-muted hover:text-text-secondary inline-flex items-center gap-1",children:[s.jsx("span",{className:"transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"})," Details"]}),s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary/60 p-3 text-[12px] text-text-muted",children:[s.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Node ID:"})," ",s.jsx("span",{className:"font-mono break-all",children:M.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Launch ready:"})," ",s.jsx("span",{className:H.configured?"text-green-400":"text-amber-400",children:H.configured?"yes":"no preferred tool configured"})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Repo root:"})," ",s.jsx("span",{className:"font-mono break-all",children:M.repoRoot||M.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Active sessions:"})," ",G.length]}),i.addNodeDaemonPicker&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Added:"})," ",new Date(M.created_at||M.createdAt||Date.now()).toLocaleDateString()]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Active queue assignments"}),Y.length===0?s.jsx("div",{children:"No active assigned queue task for this node."}):s.jsx("ul",{className:"m-0 pl-4",children:Y.map(q=>s.jsx("li",{className:"font-mono",children:KC(q)},q.id))})]}),G.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Active sessions"}),s.jsx("ul",{className:"m-0 pl-4",children:G.map(q=>s.jsxs("li",{className:"font-mono",children:[q.provider," / ",q.status," / ",q.id]},q.id))})]})]})]})]},M.id)})})]})}function $n(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function JC({daemons:e,coordinatorDaemonId:t,onCoordinatorDaemonIdChange:r,coordinatorCliType:n,onCoordinatorCliTypeChange:a,launchingCoordinator:o,launchResult:i,isHostNodeAttached:c,selectedHostNode:d,hostPinned:p,hostLabel:u,hostOnline:m,hostRebindDaemonId:h,onHostRebindDaemonIdChange:y,onLaunchCoordinator:x}){const f=s.jsx(yt,{label:"Coordinator CLI provider",hint:"Tool launched for the host coordinator session.",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:n,onChange:b=>a(b.target.value),children:[s.jsx("option",{value:"",children:"Use node provider priority"}),s.jsx("option",{value:"claude-cli",children:"Claude Code"}),s.jsx("option",{value:"codex-cli",children:"Codex"}),s.jsx("option",{value:"gemini-cli",children:"Gemini"}),s.jsx("option",{value:"hermes-cli",children:"Hermes"})]})}),j=i&&s.jsx("div",{className:"mt-3 text-[12px] text-green-400 bg-green-500/10 border border-green-500/20 rounded-lg px-3 py-2",children:i});if(p)return s.jsxs(mt,{title:"Mesh Host daemon",description:"The daemon that owns this mesh's coordinator and live truth (status, queue, graph, node detail). Fixed when the mesh is created — it cannot be reassigned here.",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsxs("span",{className:`inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-[13px] text-text-primary ${m?"border-accent-primary/40 bg-accent-primary/10":"border-amber-500/40 bg-amber-500/10"}`,children:[s.jsx("span",{className:"text-text-muted",children:"Host:"}),s.jsx("span",{className:"font-medium",children:u||"Unknown"}),s.jsxs("span",{className:m?"text-text-muted":"text-amber-400",children:["· ",m?"online":"offline"]})]}),(d==null?void 0:d.workspace)&&s.jsxs("span",{className:"text-[12px] text-text-muted",children:["Host node: ",s.jsx("span",{className:"font-mono text-text-secondary",children:d.workspace})]})]}),!m&&s.jsxs("div",{className:"mt-4",children:[s.jsxs(Ft,{variant:"warning",className:"mb-3",children:[s.jsx("strong",{children:"Host offline."})," ","The pinned host daemon is not connected. Live status/queue/graph will not load until it reconnects. You can temporarily route commands through another connected daemon below — this is a routing fallback, not a host reassignment."]}),e.length>0?s.jsx(yt,{label:"Reconnect to command",hint:"Route commands through this connected daemon until the host is back. Does not change the mesh host.",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:h,onChange:b=>y(b.target.value),children:[s.jsx("option",{value:"",children:"Wait for host to reconnect"}),e.map(b=>s.jsx("option",{value:b.id,children:$n(b)},b.id))]})}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:"No connected daemons available to route commands through. Bring the host (or another daemon) online."})]}),s.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-[180px_auto] items-end",children:[f,s.jsx("button",{className:"btn btn-primary btn-sm",onClick:x,disabled:o||!t,title:t?void 0:"No command target available — bring the host or a daemon online.",children:o?"Launching...":"Launch Host Coordinator"})]}),j]});const k=e.find(b=>b.id===t);return s.jsxs(mt,{title:"Mesh Host daemon",description:"This mesh has no host yet. Launching the coordinator on a connected daemon fixes that daemon as the mesh host (a 1:1 pin); it owns live truth thereafter.",children:[s.jsxs(Ft,{variant:"info",className:"mb-4",children:[s.jsx("strong",{children:"Set the mesh host."})," ","The host is the daemon that owns this mesh's coordinator and live truth. Launch the host coordinator below to set it — the host is fixed once established."]}),e.length>0?s.jsxs(s.Fragment,{children:[t?s.jsx("div",{className:"mb-3 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:c?s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:$n(k)}),d!=null&&d.workspace?s.jsxs(s.Fragment,{children:[" · setup node ",s.jsx("span",{className:"font-mono text-text-secondary",children:d.workspace})]}):null,". Launching sets this daemon as the mesh host."]}):s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:$n(k)}),". Attach one of its workspaces as a node first, then launch to set the host."]})}):s.jsx(yt,{label:"Host daemon",hint:"Pick the daemon that will host this mesh. Launching the coordinator on it fixes it as the host.",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:"",onChange:b=>r(b.target.value),children:[s.jsx("option",{value:"",children:"Resolving host… (or pick a daemon to host)"}),e.map(b=>s.jsx("option",{value:b.id,children:$n(b)},b.id))]})}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-[180px_auto] items-end mt-3",children:[f,s.jsx("button",{className:"btn btn-primary btn-sm",onClick:x,disabled:!t||!c||o,title:t?c?void 0:"Attach a workspace from this daemon as a node first.":"Pick a host daemon (or wait for the host pin to resolve) first.",children:o?"Launching...":"Launch Host Coordinator (sets host)"})]})]}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:"No connected daemons. Bring a daemon online to host this mesh."}),j]})}function XC({meshId:e,availableCliAgents:t}){const r=t.find(a=>{const o=a.id.toLowerCase();return o==="hermes-cli"||o.includes("hermes")||a.name.toLowerCase().includes("hermes")}),n=Lp(r==null?void 0:r.meshCoordinator,{meshId:e});return n?s.jsx(mt,{title:"Hermes MCP Config",description:"Hermes does not auto-import repo-local .mcp.json. Add this YAML under mcp_servers in Hermes config, then start a fresh Hermes session.",children:s.jsx(sm,{setup:n,providerName:(r==null?void 0:r.name)||"Hermes CLI"})}):null}const To=[{value:"preserve",label:"Preserve history and runtimes",description:"Keep completed chat history and leave live runtimes alone."},{value:"stop",label:"Stop live runtimes only",description:"Release running session processes, but keep chat records/transcripts."},{value:"delete_stopped",label:"Delete stopped sessions only",description:"Clean completed/stopped chat clutter without killing live runtimes."},{value:"stop_and_delete",label:"Stop and delete sessions",description:"Stop matching runtimes, then remove their session records/transcripts."}],QC=[{value:"smart",label:"Smart",description:"Match each task to the node whose capability slot best fits it (task difficulty + capability tags), then load-spread among ties. Auto-enabled when any node has capability slots."},{value:"spread",label:"Spread",description:"Distribute work evenly across eligible nodes (prefers the least-loaded, rotating ties fairly). Set a per-node priority below to bias the order."},{value:"in_order",label:"In order",description:"Assign to nodes in the order they were added — the first eligible node takes the work. No load-spreading."}];function ZC(e){return e==="smart"?"fitness":e==="spread"?"least_loaded":"first_eligible"}function e2(e,t){const r=e||"first_eligible";return r==="fitness"?"smart":r==="first_eligible"?"in_order":r==="priority_only"?t!=null&&t.priorityConfigured?"spread":"in_order":r==="least_loaded"||r==="round_robin"?"spread":"in_order"}const t2={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,schedulingStrategy:"first_eligible",sessionCleanupOnNodeRemove:"preserve"};function ci(e){return{...t2,...(e==null?void 0:e.policy)||{}}}function s2(e){return{routeId:`mesh-settings:${e.meshId}`,daemonId:e.daemonId,agentName:e.meshName,agentType:"mesh",status:"idle",title:e.meshName,messages:[],workspaceName:e.meshName,displayPrimary:e.meshName,displaySecondary:"Mesh observability",streamSource:"native",tabKey:`mesh-settings:${e.meshId}`,coordinator:{meshId:e.meshId,role:"coordinator"},settings:{meshCoordinatorFor:e.meshId}}}function r2({selectedMesh:e,error:t,onDismissError:r,onBack:n,onDelete:a,displayedMeshStatus:o,graphLoading:i,graphError:c,onRefreshGraph:d,savingPolicy:p,onUpdatePolicy:u,coordinatorPromptDraft:m,onCoordinatorPromptDraftChange:h,savingCoordinatorPrompt:y,onSaveCoordinatorPrompt:x,daemons:f,coordinatorDaemonId:j,onCoordinatorDaemonIdChange:k,coordinatorCliType:b,onCoordinatorCliTypeChange:w,launchingCoordinator:I,launchResult:v,isHostNodeAttached:g,selectedHostNode:S,hostPinned:N,hostLabel:C,hostOnline:R,hostRebindDaemonId:T,onHostRebindDaemonIdChange:_,onLaunchCoordinator:P,activeDaemon:B,activeDaemonId:z,meshQueue:A,userName:O,availableCliProviders:$,savingNodeSlotsId:L,onUpdateNodeSlots:E,savingNodeCapabilitiesId:M,onUpdateNodeCapabilities:H,nodeSystemPromptDrafts:Y,onNodeSystemPromptDraftChange:G,savingNodeSystemPromptId:J,onSaveNodeSystemPrompt:te,selectedNodeId:oe,onSelectNode:q,showAddNode:F,onShowAddNode:V,onCancelAddNode:pe,nodeWorkspace:be,onNodeWorkspaceChange:ue,nodeProviderPriority:Ne,onNodeProviderPriorityChange:se,nodeDaemonId:ve,onNodeDaemonIdChange:me,nodeCustomPath:U,onNodeCustomPathChange:W,nodePickerWorkspaces:Z,nodePickerProviders:ie,attachableDaemons:ye,onAddNode:fe,onRemoveNode:D,availableCliAgents:he,features:Se,sendCommand:ae}){var qe;const Q=ci(e),we=e.nodes||[],ke=we.some(je=>{var Ie;const at=Number((Ie=je.policy)==null?void 0:Ie.schedulingPriority);return Number.isFinite(at)&&at!==0}),Le=!Q.schedulingStrategy,We=l.useMemo(()=>we.some(je=>{var at;return Array.isArray((at=je.policy)==null?void 0:at.slots)&&je.policy.slots.length>0}),[we]),ce=Le?We?"smart":we.length>=2?"spread":null:null,[Ee,Be]=l.useState(!1),Je=!!z&&!!e.id;return s.jsxs(mn,{icon:s.jsx(ss,{}),title:e.name,subtitle:e.repoIdentity||e.repo_identity||"Repo Mesh",widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:n,children:"← Back"}),s.jsxs("button",{className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:()=>d(!0),disabled:i,children:[s.jsx(uC,{size:13}),i?"Probing…":"Refresh"]}),s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>a(e.id),children:"Delete"})]}),children:[t&&s.jsx(Ft,{variant:"error",onDismiss:r,className:"mb-4",children:t}),Se.meshHostDaemonSection&&s.jsx(JC,{daemons:f,coordinatorDaemonId:j,onCoordinatorDaemonIdChange:k,coordinatorCliType:b,onCoordinatorCliTypeChange:w,launchingCoordinator:I,launchResult:v,isHostNodeAttached:g,selectedHostNode:S,hostPinned:N,hostLabel:C,hostOnline:R,hostRebindDaemonId:T,onHostRebindDaemonIdChange:je=>{_(je),d()},onLaunchCoordinator:P}),s.jsxs(mt,{title:"Observability",description:"Open the live mesh graph, overview, and runtime status in the observability dialog.",children:[c&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:c}),s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsxs("button",{type:"button",className:"btn btn-primary btn-sm inline-flex items-center gap-1.5",onClick:()=>Be(!0),disabled:!Je,title:Je?"Open the mesh graph / overview / status dialog":"A coordinator daemon must be selected first",children:[s.jsx(ss,{size:14}),"Open mesh graph & status"]}),s.jsx("span",{className:"text-[12px] text-text-muted",children:"Topology graph, overview cards (missions, ledger, queue, nodes, sessions), and per-node runtime drift."})]})]}),s.jsx(YC,{nodes:we,meshQueue:A,activeDaemon:B,daemons:f,selectedMeshId:e.id,userName:O,features:{addNodeDaemonPicker:Se.addNodeDaemonPicker,nodeInstruction:Se.nodeInstruction},coordinatorDaemonId:j,availableCliProviders:$,savingNodeSlotsId:L,onUpdateNodeSlots:E,savingNodeCapabilitiesId:M,onUpdateNodeCapabilities:H,nodeSystemPromptDrafts:Y,onNodeSystemPromptDraftChange:G,savingNodeSystemPromptId:J,onSaveNodeSystemPrompt:te,selectedNodeId:oe,onSelectNode:q,showAddNode:F,onShowAddNode:V,onCancelAddNode:pe,nodeWorkspace:be,onNodeWorkspaceChange:ue,nodeProviderPriority:Ne,onNodeProviderPriorityChange:se,nodeDaemonId:ve,onNodeDaemonIdChange:me,nodeCustomPath:U,onNodeCustomPathChange:W,nodePickerWorkspaces:Z,nodePickerProviders:ie,attachableDaemons:ye,onAddNode:fe,onRemoveNode:D}),s.jsxs(mt,{title:"Scheduling",description:"How untargeted queue work is distributed across eligible nodes.",children:[s.jsxs("fieldset",{className:"border-none p-0 m-0",children:[s.jsx("legend",{className:"text-[13px] font-medium text-text-secondary mb-2",children:"Distribution"}),s.jsx("div",{className:"flex flex-col gap-2",children:QC.map(je=>{const Ie=e2(Q.schedulingStrategy,{priorityConfigured:ke})===je.value;return s.jsxs("label",{className:`flex items-start gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${Ie?"border-accent-primary/60 bg-accent-primary/10":"border-border-subtle bg-bg-secondary/60 hover:border-border-default"}`,children:[s.jsx("input",{type:"radio",name:"mesh-distribution",className:"mt-0.5 accent-[var(--accent-primary)]",value:je.value,checked:Ie,disabled:p,onChange:()=>u({schedulingStrategy:ZC(je.value)})}),s.jsxs("span",{className:"min-w-0",children:[s.jsxs("span",{className:"flex items-center gap-2 text-sm text-text-primary",children:[je.label,ce===je.value&&s.jsx("span",{className:"rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-accent-primary",children:"Recommended"})]}),s.jsx("span",{className:"block text-[12px] text-text-muted",children:je.description})]})]},je.value)})})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving…"})]}),s.jsx(mt,{title:"Dashboard visibility",description:"Whether the worker sessions this coordinator spawns show up in your dashboard inbox and raise notifications.",children:s.jsx(yt,{label:"Coordinator-spawned worker sessions",hint:"Hidden = keep the inbox quiet and mute their notifications; you interact through the coordinator session. Visible = show every spawned worker as its own conversation.",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:Q.spawnedSessionVisibility==="visible"?"visible":"hidden",onChange:je=>u({spawnedSessionVisibility:je.target.value==="visible"?"visible":"hidden"}),disabled:p,children:[s.jsx("option",{value:"hidden",children:"Hidden (no notifications, keep inbox quiet)"}),s.jsx("option",{value:"visible",children:"Visible (show every worker in the dashboard)"})]})})}),o&&s.jsx(mt,{title:"MAGI review panels",description:"MAGI (Multi-Agent Ground-truth Insight) runs a panel of AI agents that cross-check each other's work to surface the ground truth. Choose which agents handle each review type.",children:s.jsx(kC,{status:o,daemonId:z,sendDaemonCommand:ae,availableProviders:$})}),s.jsx(TC,{status:o,daemonId:z,meshId:e.id,sendCommand:ae}),Se.coordinatorPrompt&&s.jsxs(mt,{title:"Coordinator prompt",collapsible:!0,defaultOpen:!1,badge:s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:"advanced"}),description:"Customize the system prompt for coordinator sessions. Per-mesh overrides apply to this mesh only; user-level overrides apply to every mesh this daemon coordinates.",children:[s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 p-3",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-1",children:"This mesh"}),s.jsxs("p",{className:"text-[12px] text-text-muted mb-3",children:["Applies only to coordinator sessions for ",s.jsx("span",{className:"font-mono text-[11px]",children:e.name}),". Leave empty to fall through to the user-level / daemon default."]}),s.jsxs(yt,{label:"Override (replaces default)",hint:"When set, replaces the daemon's default base prompt. Leave empty to keep the default.",children:[s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:6,value:m.override,onChange:je=>h({...m,override:je.target.value}),disabled:y,placeholder:"(empty — daemon default applies)"}),s.jsx(NC,{daemonId:z,meshId:e.id,cliType:b,sendCommand:ae})]}),s.jsx(yt,{label:"Append (added after the base)",hint:"Always added after whichever base prompt wins.",children:s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:4,value:m.append,onChange:je=>h({...m,append:je.target.value}),disabled:y,placeholder:"(empty — nothing appended)"})}),s.jsxs("details",{className:"mt-2 text-[12px] text-text-muted",children:[s.jsx("summary",{className:"cursor-pointer select-none",children:"Available placeholders"}),s.jsx("p",{className:"mt-1 font-mono break-words",children:"{{meshName}}, {{repo}}, {{defaultBranch}}, {{cliType}}, {{nodes}}, {{policy}}, {{tools}}, {{workflow}}, {{rules}}, {{toolExposurePreflight}}"})]}),s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:x,disabled:y,children:y?"Saving…":"Save coordinator prompt"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>h({override:"",append:""}),disabled:y,title:"Clear both fields. Click Save to commit.",children:"Clear"})]})]}),s.jsxs("div",{className:"mt-5 border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-1",children:"User-level (this daemon)"}),s.jsx("p",{className:"text-[12px] text-text-muted mb-3",children:"Per-machine prompt files on the coordinator daemon. They apply to every mesh this daemon coordinates and are not synced across daemons. Per-mesh overrides above win over these."}),s.jsx(q0,{daemonId:z||void 0})]})]}),s.jsxs(mt,{title:"Safety & Git",collapsible:!0,defaultOpen:!1,badge:s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:"advanced"}),description:"Checkpointing, approval gates, and git safety behavior for coordinator-driven tasks.",children:[s.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:[{label:"Auto-commit a checkpoint before each task",key:"requirePreTaskCheckpoint",opts:[["no","No"],["yes","Yes"]],val:je=>je?"yes":"no",parse:je=>je==="yes"},{label:"Auto-commit a checkpoint after each task",key:"requirePostTaskCheckpoint",opts:[["yes","Yes"],["no","No"]],val:je=>je?"yes":"no",parse:je=>je==="yes"},{label:"Push approval",key:"requireApprovalForPush",opts:[["required","Require approval before push"],["not_required","Do not require approval"]],val:je=>je?"required":"not_required",parse:je=>je==="required"},{label:"Destructive git approval",key:"requireApprovalForDestructiveGit",opts:[["required","Require approval"],["not_required","Do not require approval"]],val:je=>je?"required":"not_required",parse:je=>je==="required"},{label:"When the workspace has uncommitted changes",key:"dirtyWorkspaceBehavior",opts:[["warn","Warn and continue"],["block","Block task"],["checkpoint_then_continue","Checkpoint then continue"]],val:je=>je||"warn",parse:je=>je},{label:"Auto-publish submodule commits (advanced)",key:"allowAutoPublishSubmoduleMainCommits",opts:[["disabled","Require explicit approval"],["enabled","Allow Refinery non-force publish"]],val:je=>je?"enabled":"disabled",parse:je=>je==="enabled"}].map(({label:je,key:at,opts:Ie,val:ot,parse:nt})=>s.jsx(yt,{label:je,children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ot(Q[at]),onChange:Qe=>u({[at]:nt(Qe.target.value)}),disabled:p,children:Ie.map(([Qe,Lt])=>s.jsx("option",{value:Qe,children:Lt},Qe))})},at))}),(()=>{const je=Q.autoFastForward&&typeof Q.autoFastForward=="object"?Q.autoFastForward:{},at=je.enabled!==!1,Ie=je.remoteNodes===!0,ot=je.mode==="continuous"?"continuous":"idle",nt=Qe=>u({autoFastForward:{...je,...Qe}});return s.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[s.jsx(yt,{label:"Auto fast-forward idle nodes",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:at?"enabled":"disabled",onChange:Qe=>nt({enabled:Qe.target.value==="enabled"}),disabled:p,children:[s.jsx("option",{value:"enabled",children:"Enabled (catch up online, clean, behind nodes)"}),s.jsx("option",{value:"disabled",children:"Disabled"})]})}),s.jsx(yt,{label:"Include remote nodes",hint:"Off = only the coordinator's local workspace is auto fast-forwarded.",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:Ie?"yes":"no",onChange:Qe=>nt({remoteNodes:Qe.target.value==="yes"}),disabled:p||!at,children:[s.jsx("option",{value:"no",children:"No (local workspace only)"}),s.jsx("option",{value:"yes",children:"Yes (delegate to remote owning daemons)"})]})}),s.jsx(yt,{label:"Detection mode",hint:"Idle = on a node's idle edge. Continuous = also scan periodically (base nodes only).",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ot,onChange:Qe=>nt({mode:Qe.target.value==="continuous"?"continuous":"idle"}),disabled:p||!at||!Ie,children:[s.jsx("option",{value:"idle",children:"Idle edge only"}),s.jsx("option",{value:"continuous",children:"Continuous (periodic scan)"})]})})]})})(),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(yt,{label:"When removing a node, its sessions…",hint:"Separate transcript cleanup from runtime/process cleanup.",children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:Q.sessionCleanupOnNodeRemove||"preserve",onChange:je=>u({sessionCleanupOnNodeRemove:je.target.value}),disabled:p,children:To.map(je=>s.jsx("option",{value:je.value,children:je.label},je.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((qe=To.find(je=>je.value===Q.sessionCleanupOnNodeRemove))==null?void 0:qe.description)||To[0].description})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving…"})]}),Se.hermesMcpConfig&&s.jsx(XC,{meshId:e.id,availableCliAgents:he}),Se.meshHostDaemonSection&&s.jsxs(Ft,{variant:"info",className:"mt-4",children:[s.jsx("strong",{children:"MCP Mode:"})," ",s.jsxs("code",{className:"bg-bg-secondary px-1 rounded text-xs",children:["adhdev mcp --repo-mesh ",e.id]})," · The mesh MCP server can be used directly from your CLI agent."]}),Ee&&Je&&s.jsx(Pm,{activeConv:s2({meshId:e.id,daemonId:z,meshName:e.name}),sendDaemonCommand:ae,onClose:()=>Be(!1)})]})}const Fr=new Map;function n2({daemons:e,primaryDaemonId:t,sendCommand:r,unwrapResult:n,normalizeMesh:a,features:o,loadDaemonMetadata:i}){const c=e.map(E=>E.id).filter(Boolean).sort().join(","),[d,p]=l.useState(()=>Fr.get(c)??[]),[u,m]=l.useState(null),[h,y]=l.useState(()=>!Fr.has(c)),[x,f]=l.useState(null),[j,k]=l.useState(!1),[b,w]=l.useState(""),[I,v]=l.useState(""),[g,S]=l.useState(""),[N,C]=l.useState(""),[R,T]=l.useState(""),_=l.useMemo(()=>e.find(E=>E.id===N),[e,N]),P=(_==null?void 0:_.workspaces)||[],B=l.useMemo(()=>xr((_==null?void 0:_.availableProviders)||[]),[_]);l.useEffect(()=>{!o.createDaemonPicker||!i||!N||!_||!(!_.workspaces||!_.availableProviders)||Promise.resolve(i(N,{minFreshMs:3e4})).catch(()=>{})},[o.createDaemonPicker,i,N,_]);const z=l.useMemo(()=>e.map(E=>E.id).filter(Boolean).sort().join(","),[e]),A=l.useCallback(async(E=!1)=>{const M=E||Fr.has(z);y(H=>M?H:!0);try{if(o.createDaemonPicker){const H=await Promise.allSettled(e.map(async J=>{if(!J.id)return[];const te=await r(J.id,"list_meshes",{}),oe=n(te);if((oe==null?void 0:oe.success)===!1)throw new Error(oe.error||"Failed to load meshes");return(Array.isArray(oe==null?void 0:oe.meshes)?oe.meshes:[]).map(q=>a(q,J.id)).filter(q=>q.id)})),Y=new Map;for(const J of H)if(J.status==="fulfilled")for(const te of J.value)Y.has(te.id)||Y.set(te.id,te);const G=Array.from(Y.values());p(G),Fr.set(z,G),f(null)}else{if(!t)return;const H=await r(t,"list_meshes");if(H!=null&&H.success){const Y=(H.meshes||[]).map(G=>a(G,t));p(Y),Fr.set(z,Y),f(null)}else f((H==null?void 0:H.error)||"Failed to load meshes")}}catch(H){f((H==null?void 0:H.message)||"Failed to load meshes")}finally{y(!1)}},[z,t,r,n,a,o.createDaemonPicker]);async function O(){var Y,G;const E=o.createDaemonPicker?N:t;if(!E||!b.trim())return;const M=g.trim(),H=I.trim();if(!(!M&&!H))try{const J={name:b.trim()};M&&(J.repoRemoteUrl=M),H&&(J.repoIdentity=H);const te=await r(E,"create_mesh",J),oe=n(te);if((oe==null?void 0:oe.success)===!1)throw new Error(oe.error||"Create failed");const q=typeof((Y=oe==null?void 0:oe.mesh)==null?void 0:Y.id)=="string"?oe.mesh.id:"";if(q&&o.createDaemonPicker&&R){const F=await r(E,"add_mesh_node",{meshId:q,daemonId:E,machineId:_==null?void 0:_.machineId,workspace:R,role:"host",providerPriority:nn(B)}),V=n(F);if((V==null?void 0:V.success)===!1)throw new Error(V.error||"Mesh created but failed to attach workspace")}k(!1),w(""),v(""),S(""),T(""),await A(),(G=oe==null?void 0:oe.mesh)!=null&&G.id&&m(oe.mesh.id)}catch(J){f((J==null?void 0:J.message)||"Create failed")}}async function $(E){var H;if(!confirm("Delete this mesh? This cannot be undone."))return;const M=((H=d.find(Y=>Y.id===E))==null?void 0:H.__sourceDaemonId)||t;try{const Y=await r(M,"delete_mesh",{meshId:E}),G=n(Y);if((G==null?void 0:G.success)===!1)throw new Error(G.error||"Failed to delete");u===E&&m(null),await A()}catch(Y){f((Y==null?void 0:Y.message)||"Delete failed")}}function L(){k(!1),w(""),v(""),S("")}return{meshes:d,setMeshes:p,selectedMeshId:u,setSelectedMeshId:m,loading:h,error:x,setError:f,showCreate:j,setShowCreate:k,createName:b,setCreateName:w,createRepoIdentity:I,setCreateRepoIdentity:v,createRepoRemoteUrl:g,setCreateRepoRemoteUrl:S,newMeshDaemonId:N,setNewMeshDaemonId:C,newMeshWorkspace:R,setNewMeshWorkspace:T,createPickerWorkspaces:P,createPickerProviders:B,loadMeshes:A,handleCreate:O,handleDelete:$,cancelCreate:L}}function a2({selectedMesh:e,selectedMeshId:t,primaryDaemonId:r,activeDaemonId:n,daemons:a,sendCommand:o,unwrapResult:i,loadLiveMesh:c,resolveCommandTarget:d,launchCoordinator:p,features:u,loadMeshes:m,loadQueue:h,queueSection:y,setError:x}){const[f,j]=l.useState({}),[k,b]=l.useState(null),[w,I]=l.useState(null),[v,g]=l.useState(!1),[S,N]=l.useState(""),[C,R]=l.useState([]),[T,_]=l.useState(""),[P,B]=l.useState(!1),[z,A]=l.useState(""),[O,$]=l.useState(!1),[L,E]=l.useState(null),[M,H]=l.useState(!1),[Y,G]=l.useState({override:"",append:""}),[J,te]=l.useState(!1),[oe,q]=l.useState({}),[F,V]=l.useState(null),pe=l.useMemo(()=>a.find(ae=>ae.id===T),[a,T]),be=(pe==null?void 0:pe.workspaces)||[],ue=l.useMemo(()=>xr((pe==null?void 0:pe.availableProviders)||[]),[pe]);async function Ne(){const ae=(e==null?void 0:e.__sourceDaemonId)||r;if(!t||!ae)return;const Q=S.trim();if(Q)try{const we={meshId:t,workspace:Q};u.addNodeDaemonPicker&&T&&(we.daemonId=T,we.machineId=pe==null?void 0:pe.machineId),we.providerPriority=br(C);const ke=await o(ae,"add_mesh_node",we),Le=i(ke);if((Le==null?void 0:Le.success)===!1)throw new Error(Le.error||"Add node failed");g(!1),N(""),R([]),_(""),B(!1),await m(),y||await h(t)}catch(we){x((we==null?void 0:we.message)||"Add node failed")}}async function se(ae){var Le;if(!e)return;const Q=ci(e),we=((Le=[{value:"preserve",label:"Preserve history and runtimes"},{value:"stop",label:"Stop live runtimes only"},{value:"delete_stopped",label:"Delete stopped sessions only"},{value:"stop_and_delete",label:"Stop and delete sessions"}].find(We=>We.value===Q.sessionCleanupOnNodeRemove))==null?void 0:Le.label)||"Preserve history and runtimes";if(!confirm(`Remove this node?
115
115
 
116
116
  Node removal cleanup policy: ${we}`))return;const ke=e.__sourceDaemonId||r;try{const We=await o(ke,"remove_mesh_node",{meshId:e.id,nodeId:ae}),ce=i(We);if((ce==null?void 0:ce.success)===!1)throw new Error(ce.error||"Remove failed");w===ae&&I(null),await m(),y||await h(t)}catch(We){x((We==null?void 0:We.message)||"Remove node failed")}}async function ve(ae){if(!e)return;const Q={...ci(e),...ae},we=e.__sourceDaemonId||r;try{H(!0),x(null);const ke=await o(we,"update_mesh",{meshId:e.id,policy:Q}),Le=i(ke);if((Le==null?void 0:Le.success)===!1)throw new Error(Le.error||"Policy update failed");await m()}catch(ke){x((ke==null?void 0:ke.message)||"Policy update failed")}finally{H(!1)}}async function me(ae){if(!t)return;const Q=(e==null?void 0:e.__sourceDaemonId)||r,we=f[ae.id]||o2(ae),ke=br(we),Le={...ae.policy||{}};delete Le.provider_priority,ke.length?Le.providerPriority=ke:delete Le.providerPriority;try{b(ae.id),x(null);const We=await o(Q,"update_mesh_node",{meshId:t,nodeId:ae.id,policy:Le,providerPriority:ke}),ce=i(We);if((ce==null?void 0:ce.success)===!1){x(ce.error||"Node policy update failed");return}await m()}catch(We){x((We==null?void 0:We.message)||"Node policy update failed")}finally{b(null)}}const[U,W]=l.useState(null);async function Z(ae,Q){if(!t)return;const we=(e==null?void 0:e.__sourceDaemonId)||r;try{W(ae.id),x(null);const ke=await o(we,"update_mesh_node",{meshId:t,nodeId:ae.id,policy:{slots:Q}}),Le=i(ke);if((Le==null?void 0:Le.success)===!1){x(Le.error||"Node slots update failed");return}await m()}catch(ke){x((ke==null?void 0:ke.message)||"Node slots update failed")}finally{W(null)}}const[ie,ye]=l.useState(null);async function fe(ae,Q){if(!t)return;const we=(e==null?void 0:e.__sourceDaemonId)||r,ke=Q.map(Le=>Le.trim()).filter(Boolean);try{ye(ae.id),x(null);const Le=await o(we,"update_mesh_node",{meshId:t,nodeId:ae.id,capabilities:ke}),We=i(Le);if((We==null?void 0:We.success)===!1){x(We.error||"Node tag update failed");return}await m()}catch(Le){x((Le==null?void 0:Le.message)||"Node tag update failed")}finally{ye(null)}}async function D(){if(!r||!t)return;const Q={...(e==null?void 0:e.coordinator)||{}};Y.override.trim()?Q.systemPromptOverride=Y.override:delete Q.systemPromptOverride,Y.append.trim()?Q.systemPromptAppend=Y.append:delete Q.systemPromptAppend,delete Q.systemPromptSuffix;try{te(!0),x(null);const we=await o(r,"update_mesh",{meshId:t,coordinator:Q}),ke=i(we);if((ke==null?void 0:ke.success)===!1){x(ke.error||"Coordinator prompt save failed");return}await m()}catch(we){x((we==null?void 0:we.message)||"Coordinator prompt save failed")}finally{te(!1)}}async function he(ae){if(!r||!t)return;const Q=(oe[ae.id]||"").trim();try{V(ae.id),x(null);const we=await o(r,"update_mesh_node",{meshId:t,nodeId:ae.id,systemPrompt:Q}),ke=i(we);if((ke==null?void 0:ke.success)===!1){x(ke.error||"Node instruction save failed");return}await m()}catch(we){x((we==null?void 0:we.message)||"Node instruction save failed")}finally{V(null)}}async function Se(){if(e){x(null),E(null);try{$(!0);const ae=c?await c(n,e.id,e):null,Q=d(n,e.id,e,e.nodes||[],ae);if("error"in Q)throw new Error(Q.error);const we=await p(Q.targetDaemonId,{meshId:e.id,inlineMesh:Q.inlineMesh,coordinatorNodeId:Q.coordinatorNodeId,cliType:z.trim()||void 0});E(we.message)}catch(ae){x((ae==null?void 0:ae.message)||"Coordinator launch failed")}finally{$(!1)}}}return{nodeProviderPriorityDrafts:f,setNodeProviderPriorityDrafts:j,savingNodePolicyId:k,selectedNodeId:w,setSelectedNodeId:I,showAddNode:v,setShowAddNode:g,nodeWorkspace:S,setNodeWorkspace:N,nodeProviderPriority:C,setNodeProviderPriority:R,nodeDaemonId:T,setNodeDaemonId:_,nodeCustomPath:P,setNodeCustomPath:B,nodePickerWorkspaces:be,nodePickerProviders:ue,coordinatorCliType:z,setCoordinatorCliType:A,launchingCoordinator:O,launchResult:L,savingPolicy:M,coordinatorPromptDraft:Y,setCoordinatorPromptDraft:G,savingCoordinatorPrompt:J,nodeSystemPromptDrafts:oe,setNodeSystemPromptDrafts:q,savingNodeSystemPromptId:F,savingNodeSlotsId:U,savingNodeCapabilitiesId:ie,handleAddNode:Ne,handleRemoveNode:se,handleUpdatePolicy:ve,handleUpdateNodeProviderPriority:me,handleUpdateNodeSlots:Z,handleUpdateNodeCapabilities:fe,handleSaveCoordinatorPrompt:D,handleSaveNodeSystemPrompt:he,handleLaunchCoordinator:Se}}function o2(e){var n;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((n=e.policy)==null?void 0:n.providerPriority)?e.policy.providerPriority:[],r=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>r.has(a)?!1:(r.add(a),!0))}function i2(e){const t=e.filter(n=>n.status==="pending"||n.status==="assigned"),r=e.filter(n=>n.status==="completed"||n.status==="failed"||n.status==="cancelled");return{active:t.length,historical:r.length,activeCounts:{pending:t.filter(n=>n.status==="pending").length,assigned:t.filter(n=>n.status==="assigned").length},historicalCounts:{completed:r.filter(n=>n.status==="completed").length,failed:r.filter(n=>n.status==="failed").length},counts:{pending:e.filter(n=>n.status==="pending").length,assigned:e.filter(n=>n.status==="assigned").length,completed:e.filter(n=>n.status==="completed").length,failed:e.filter(n=>n.status==="failed").length},staleAssignedCount:e.filter(n=>n.staleAssigned).length,recent:e.slice(0,20)}}function l2({primaryDaemonId:e,activeDaemonId:t,sendCommand:r,unwrapResult:n,loadLiveMesh:a,resolveCommandTarget:o}){const[i,c]=l.useState([]),[d,p]=l.useState(null),[u,m]=l.useState(!1),[h,y]=l.useState(null),x=l.useCallback(async j=>{if(!e||!j){c([]);return}try{const k=await r(e,"get_mesh_queue",{meshId:j});c(k!=null&&k.success?Array.isArray(k.queue)?k.queue:[]:[])}catch{c([])}},[e,r]);async function f(j){var k,b;if(j){m(!0),y(null);try{const w=a?await a(t,j.id,j):null,I=o(t,j.id,j,j.nodes||[],w);if("error"in I)throw new Error(I.error);const v=await r(I.targetDaemonId,"get_mesh_queue",{meshId:j.id}),g=n(v);if((g==null?void 0:g.success)===!1)throw new Error(g.error||"Queue load failed");const S=Array.isArray(((k=g==null?void 0:g.result)==null?void 0:k.rows)??(g==null?void 0:g.rows)??(g==null?void 0:g.queue))?((b=g==null?void 0:g.result)==null?void 0:b.rows)??(g==null?void 0:g.rows)??(g==null?void 0:g.queue):[];p(i2(S))}catch(w){y((w==null?void 0:w.message)||"Queue load failed")}finally{m(!1)}}}return{meshQueue:i,setMeshQueue:c,queueSummary:d,queueLoading:u,queueError:h,loadQueue:x,handleLoadQueue:f}}function c2(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}const Om=new Map;function Hm(e){return e?Om.get(e)??null:null}function d2(e,t){!e||!t||Om.set(e,t)}function u2({selectedMeshId:e,loadMeshStatus:t,extractStatus:r,normalizeNode:n,gateIncompleteGraph:a}){const[o,i]=l.useState(()=>Hm(e)),[c,d]=l.useState(!1),[p,u]=l.useState(null),[m,h]=l.useState("idle"),[y,x]=l.useState(!1),f=l.useRef(!1);async function j(k,b=e,w=!1){if(!(!k||!b))try{d(!w&&o===null),h(w?"settling":"first_paint"),u(null);const I=await t(k,b,{refresh:w,retryProfile:w?"settled":"interactive"});x(c2(I));const v=r(I),g=n&&v?{...v,nodes:(v.nodes??[]).map(S=>n(S,v.meshId??b,""))}:v;if(g){if(a&&!w&&o!==null&&!Ak(bm(g))){h("settling"),f.current||(f.current=!0,Promise.resolve().then(()=>j(k,b,!0)).finally(()=>{f.current=!1}));return}i(g),d2(b,g),h("settled")}else i(null),u("mesh_status returned an unexpected payload."),h("idle")}catch(I){o||i(null),u((I==null?void 0:I.message)||"Failed to load mesh graph"),h("idle")}finally{d(!1)}}return{meshGraphStatus:o,setMeshGraphStatus:i,graphLoading:c,graphError:p,setGraphError:u,graphProvenance:m,graphBootstrapFallback:y,loadGraph:j}}function p2(e,t,r,n,a){if(!e.length)return"";const o=String(a||"");if(o){const d=e.find(p=>Fs(p.id,o));return d?d.id:o}const i=t.find(d=>d.role==="host"),c=String((i==null?void 0:i.daemon_id)||(i==null?void 0:i.daemonId)||"");if(c){const d=e.find(p=>Fs(p.id,c));if(d)return d.id}return""}const m2=7e3,h2=45e3;function f2(){const e=dC(),{sendCommand:t,sendData:r,daemons:n,userName:a,loadMeshStatus:o,launchCoordinator:i,loadLiveMesh:c,extractStatus:d,unwrapResult:p,normalizeMesh:u,normalizeNode:m,resolveCommandTarget:h,features:y,gateIncompleteGraph:x}=e,f=Nr(),j=n[0],k=(j==null?void 0:j.id)||"",b=l.useMemo(()=>((j==null?void 0:j.availableProviders)||[]).filter(Me=>Me.category==="cli").map(Me=>({id:Me.type||Me.id,name:Me.displayName||Me.name||Me.type,meshCoordinator:Me.meshCoordinator})),[j]),w=l.useMemo(()=>xr((j==null?void 0:j.availableProviders)||[]),[j]),{meshes:I,selectedMeshId:v,setSelectedMeshId:g,loading:S,error:N,setError:C,showCreate:R,setShowCreate:T,createName:_,setCreateName:P,createRepoIdentity:B,setCreateRepoIdentity:z,createRepoRemoteUrl:A,setCreateRepoRemoteUrl:O,newMeshDaemonId:$,setNewMeshDaemonId:L,newMeshWorkspace:E,setNewMeshWorkspace:M,createPickerWorkspaces:H,loadMeshes:Y,handleCreate:G,handleDelete:J,cancelCreate:te}=n2({daemons:n,primaryDaemonId:k,sendCommand:t,unwrapResult:p,normalizeMesh:u,features:y,loadDaemonMetadata:f}),oe=I.find(K=>K.id===v)||null,{meshGraphStatus:q,setMeshGraphStatus:F,graphLoading:V,graphError:pe,setGraphError:be,loadGraph:ue}=u2({selectedMeshId:v,loadMeshStatus:o,extractStatus:d,normalizeNode:m,gateIncompleteGraph:x}),[Ne,se]=l.useState(""),[ve,me]=l.useState(""),U=y.meshHostDaemonSection&&Ne||k,{meshQueue:W,loadQueue:Z}=l2({primaryDaemonId:k,activeDaemonId:U,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:h}),{setNodeProviderPriorityDrafts:ie,selectedNodeId:ye,setSelectedNodeId:fe,showAddNode:D,setShowAddNode:he,nodeWorkspace:Se,setNodeWorkspace:ae,nodeProviderPriority:Q,setNodeProviderPriority:we,nodeDaemonId:ke,setNodeDaemonId:Le,nodeCustomPath:We,setNodeCustomPath:ce,nodePickerWorkspaces:Ee,nodePickerProviders:Be,coordinatorCliType:Je,setCoordinatorCliType:qe,launchingCoordinator:je,launchResult:at,savingPolicy:Ie,coordinatorPromptDraft:ot,setCoordinatorPromptDraft:nt,savingCoordinatorPrompt:Qe,nodeSystemPromptDrafts:Lt,setNodeSystemPromptDrafts:X,savingNodeSystemPromptId:ee,savingNodeSlotsId:re,savingNodeCapabilitiesId:le,handleAddNode:xe,handleRemoveNode:Ae,handleUpdatePolicy:De,handleUpdateNodeSlots:Ce,handleUpdateNodeCapabilities:Re,handleSaveCoordinatorPrompt:He,handleSaveNodeSystemPrompt:Xe,handleLaunchCoordinator:Oe}=a2({selectedMesh:oe,selectedMeshId:v,primaryDaemonId:k,activeDaemonId:U,daemons:n,availableCliProviders:w,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:h,launchCoordinator:i,features:{addNodeDaemonPicker:y.addNodeDaemonPicker},loadMeshes:Y,loadQueue:Z,queueSection:y.queueSection,setError:C}),Ue=l.useMemo(()=>n.find(K=>K.id===U)||j,[n,U,j]),ne=l.useMemo(()=>new Set(((oe==null?void 0:oe.nodes)||[]).map(K=>String(K.daemon_id||K.daemonId||""))),[oe]),de=l.useMemo(()=>n.filter(K=>K.id&&!ne.has(K.id)),[n,ne]),ge=(oe==null?void 0:oe.nodes)||[],$e=l.useMemo(()=>ge.find(K=>Fs(String(K.daemon_id||K.daemonId||""),Ne)),[ge,Ne]),Fe=y.meshHostDaemonSection?!!$e:!0,Ye=l.useMemo(()=>{if(!y.meshHostDaemonSection||!oe)return{pinned:!1,daemonId:"",label:"",online:!1};const K=oe.meshHost,Me=q!=null&&q.meshId&&String(q.meshId)===String(oe.id??"")?q.meshHost:void 0,Pe=Me!=null&&Me.hostDaemonId?Me:K??Me,dt=String((Pe==null?void 0:Pe.hostDaemonId)||""),Et=ge.find(fs=>fs.role==="host"),Rs=String((Pe==null?void 0:Pe.hostNodeId)||(Et==null?void 0:Et.id)||""),Mt=Rs?ge.find(fs=>String(fs.id)===Rs):void 0,vs=String((Mt==null?void 0:Mt.daemon_id)||(Mt==null?void 0:Mt.daemonId)||""),ws=dt||vs;if(!ws)return{pinned:!1,daemonId:"",label:"",online:!1};const Sr=n.find(fs=>dt&&Fs(fs.id,dt))||(vs?n.find(fs=>Fs(fs.id,vs)):void 0);if(Sr)return{pinned:!0,daemonId:Sr.id,label:x2(Sr),online:!0};const Ea=String((Mt==null?void 0:Mt.machineLabel)||"")||String((Mt==null?void 0:Mt.workspace)||"")||ws;return{pinned:!0,daemonId:ws,label:Ea,online:!1}},[oe,ge,n,q,y.meshHostDaemonSection]),Ze=Ye.daemonId,rt=Ye.online,Ge=l.useMemo(()=>!y.meshHostDaemonSection||!Ye.pinned?"":!rt&&ve&&n.some(K=>K.id===ve)?ve:Ze,[y.meshHostDaemonSection,Ye.pinned,rt,ve,n,Ze]),Nt=l.useMemo(()=>q?[...new Set((q.nodes??[]).map(K=>String(K.daemonId||K.daemon_id||"")).filter(Boolean))]:[],[q]),Jt=Rm({status:q,daemonId:U||null,extraDaemonIds:Nt,meshId:v,sendData:r});l.useEffect(()=>{ie(Object.fromEntries(((oe==null?void 0:oe.nodes)||[]).map(K=>[K.id,b2(K)])))},[oe]),l.useEffect(()=>{const K=(oe==null?void 0:oe.coordinator)||{};nt({override:typeof K.systemPromptOverride=="string"?K.systemPromptOverride:"",append:typeof K.systemPromptAppend=="string"?K.systemPromptAppend:typeof K.systemPromptSuffix=="string"?K.systemPromptSuffix:""}),X(Object.fromEntries(((oe==null?void 0:oe.nodes)||[]).map(Me=>[Me.id,typeof Me.systemPrompt=="string"?Me.systemPrompt:""])))},[oe]),l.useEffect(()=>{const K=y.addNodeDaemonPicker?nn(Be):nn(w);D&&Q.length===0&&K.length>0&&we(K)},[D,w,Be,Q.length,y.addNodeDaemonPicker]),l.useEffect(()=>{const K=new Set(((oe==null?void 0:oe.nodes)||[]).map(Me=>Me.id));ye&&!K.has(ye)&&fe(null)},[oe,ye]);const Ht=l.useMemo(()=>{var K;if(!(!(q!=null&&q.meshId)||String(q.meshId)!==String((oe==null?void 0:oe.id)??"")))return(K=q.meshHost)==null?void 0:K.hostDaemonId},[q,oe]),Te=l.useMemo(()=>p2(n,ge,U,k,Ht),[n,ge,U,k,Ht]);l.useEffect(()=>{if(!y.meshHostDaemonSection)return;if(!n.length&&!Ye.pinned){se("");return}const K=Ye.pinned?Ge:Te;K&&!Fs(K,Ne)&&se(K)},[n,Ne,Ye.pinned,Ge,Te,y.meshHostDaemonSection]),l.useEffect(()=>{ve&&(rt||!n.some(K=>K.id===ve))&&me("")},[rt,ve,n]),l.useEffect(()=>{if(y.createDaemonPicker){if(!n.length){L("");return}(!$||!n.some(K=>K.id===$))&&L(n[0].id)}},[n,$,y.createDaemonPicker]),l.useEffect(()=>{var K;if(!y.createDaemonPicker||!$){M("");return}if(!H.length){M("");return}H.some(Me=>Me.path===E)||M(((K=H[0])==null?void 0:K.path)||"")},[$,E,H,y.createDaemonPicker]);const Ve=l.useRef(null);l.useEffect(()=>{if(!v)return;const K=Ve.current!==v;if(Ve.current=v,K){const Me=Hm(v);F(Me),be(null),ue(U,v,Me!==null)}else be(null),ue(U,v,!0)},[v,U]);const Rt=l.useRef(ue);Rt.current=ue;const jt=l.useRef(!1),Kt=l.useRef(()=>{});Kt.current=()=>{jt.current||!v||!U||(jt.current=!0,Promise.resolve(Rt.current(U,v,!0)).finally(()=>{jt.current=!1}))};const Ut=y.meshStatePushRefresh?h2:m2;lC({daemonIds:l.useMemo(()=>[U,...Nt].filter(Boolean),[U,Nt]),meshId:v,sendData:r,onRevisionAdvance:()=>{typeof document<"u"&&document.visibilityState!=="visible"||Kt.current()}}),l.useEffect(()=>{if(!v||!U||typeof document>"u")return;let K=null;const Me=()=>{document.visibilityState==="visible"&&Kt.current()},Pe=()=>{K===null&&(K=setInterval(Me,Ut))},dt=()=>{K!==null&&(clearInterval(K),K=null)},Et=()=>{document.visibilityState==="visible"?Pe():dt()};return document.visibilityState==="visible"&&Pe(),document.addEventListener("visibilitychange",Et),()=>{dt(),document.removeEventListener("visibilitychange",Et)}},[v,U,Ut]),l.useEffect(()=>{y.queueSection||Z(v)},[v,y.queueSection]);const zt=l.useMemo(()=>n.map(K=>K.id).filter(Boolean).sort().join(","),[n]),is=l.useRef(!1);return l.useEffect(()=>{Y(is.current),is.current=!0},[zt]),k?oe?s.jsx(r2,{selectedMesh:oe,error:N,onDismissError:()=>C(null),onBack:()=>{g(null),F(null)},onDelete:J,displayedMeshStatus:Jt,graphLoading:V,graphError:pe,onRefreshGraph:()=>ue(U,v,!0),savingPolicy:Ie,onUpdatePolicy:De,coordinatorPromptDraft:ot,onCoordinatorPromptDraftChange:nt,savingCoordinatorPrompt:Qe,onSaveCoordinatorPrompt:He,daemons:n,coordinatorDaemonId:Ne,onCoordinatorDaemonIdChange:se,coordinatorCliType:Je,onCoordinatorCliTypeChange:qe,launchingCoordinator:je,launchResult:at,isHostNodeAttached:Fe,selectedHostNode:$e,hostPinned:Ye.pinned,hostLabel:Ye.label,hostOnline:rt,hostRebindDaemonId:ve,onHostRebindDaemonIdChange:K=>me(K),onLaunchCoordinator:Oe,activeDaemon:Ue,activeDaemonId:U,meshQueue:W,userName:a,availableCliProviders:w,savingNodeSlotsId:re,onUpdateNodeSlots:Ce,savingNodeCapabilitiesId:le,onUpdateNodeCapabilities:Re,nodeSystemPromptDrafts:Lt,onNodeSystemPromptDraftChange:(K,Me)=>X(Pe=>({...Pe,[K]:Me})),savingNodeSystemPromptId:ee,onSaveNodeSystemPrompt:Xe,selectedNodeId:ye,onSelectNode:fe,showAddNode:D,onShowAddNode:()=>he(!0),onCancelAddNode:()=>he(!1),nodeWorkspace:Se,onNodeWorkspaceChange:ae,nodeProviderPriority:Q,onNodeProviderPriorityChange:we,nodeDaemonId:ke,onNodeDaemonIdChange:Le,nodeCustomPath:We,onNodeCustomPathChange:ce,nodePickerWorkspaces:Ee,nodePickerProviders:Be,attachableDaemons:de,onAddNode:xe,onRemoveNode:Ae,availableCliAgents:b,features:{coordinatorPrompt:y.coordinatorPrompt,meshHostDaemonSection:y.meshHostDaemonSection,hermesMcpConfig:y.hermesMcpConfig,addNodeDaemonPicker:y.addNodeDaemonPicker,nodeInstruction:y.nodeInstruction},sendCommand:t}):s.jsx(bC,{meshes:I,loading:S,error:N,onDismissError:()=>C(null),daemons:n,features:{createDaemonPicker:y.createDaemonPicker},showCreate:R,onToggleCreate:()=>T(!R),createName:_,onCreateNameChange:P,createRepoIdentity:B,onCreateRepoIdentityChange:z,createRepoRemoteUrl:A,onCreateRepoRemoteUrlChange:O,newMeshDaemonId:$,onNewMeshDaemonIdChange:L,newMeshWorkspace:E,onNewMeshWorkspaceChange:M,createPickerWorkspaces:H,onSelectMesh:g,onCreate:G,onCancelCreate:te}):s.jsx(mn,{icon:s.jsx(ss,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})})}function x2(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function b2(e){var n;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((n=e.policy)==null?void 0:n.providerPriority)?e.policy.providerPriority:[],r=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>r.has(a)?!1:(r.add(a),!0))}function g2({children:e}){const{sendCommand:t,sendData:r}=xt(),{ides:n}=hs(),a=l.useMemo(()=>n.filter(i=>i.daemonMode||i.type==="adhdev-daemon").map(i=>i),[n]),o=l.useMemo(()=>({sendCommand:t,sendData:r,daemons:a,userName:void 0,loadMeshStatus:async(i,c)=>t(i,"mesh_status",{meshId:c}),launchCoordinator:async(i,c)=>{var h;const d={meshId:c.meshId};c.cliType&&(d.cliType=c.cliType);const p=await t(i,"launch_mesh_coordinator",d),u=(p==null?void 0:p.result)??p;if((u==null?void 0:u.success)===!1)throw new Error(u.error||"Coordinator launch failed");const m=(u==null?void 0:u.sessionId)||((h=u==null?void 0:u.session)==null?void 0:h.id)||(u==null?void 0:u.targetSessionId);return{sessionId:m,message:m?`Coordinator launched (${m})`:"Coordinator launch command sent"}},loadLiveMesh:void 0,extractStatus:Ti,unwrapResult:i=>i,normalizeMesh:(i,c)=>i,normalizeNode:(i,c,d)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:cC}),[t,r,a]);return s.jsx(Fm.Provider,{value:o,children:e})}function ll(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function y2(e){if(typeof window>"u")return e;const t=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),r=ll();return r&&!t.searchParams.has("token")&&t.searchParams.set("token",r),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function ds(e,t){return await fetch(y2(e),{credentials:"same-origin",...t})}function Wm(){if(typeof window>"u")return;const e=new URL(window.location.href);e.searchParams.has("token")&&(e.searchParams.delete("token"),window.history.replaceState({},"",`${e.pathname}${e.search}${e.hash}`))}class v2{constructor(){et(this,"adapters",new Map);et(this,"states",new Map);et(this,"runtimeListeners",new Map);et(this,"screenshotCallbacks",new Map);et(this,"statusCallbacks",new Set);et(this,"stateChangeCallbacks",new Set);et(this,"ptyInputSender",null)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(t,r){this.adapters.set(t,r),this.states.set(t,r.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,r){this.states.set(t,r);const n=this.resolveDaemonId(t)||t;this.stateChangeCallbacks.forEach(a=>a(n,r))}onStateChange(t){return this.stateChangeCallbacks.add(t),()=>{this.stateChangeCallbacks.delete(t)}}retryConnection(t){}get(t){const r=this.resolveDaemonId(t);return r?this.adapters.get(r):void 0}getState(t){const r=this.resolveDaemonId(t);return r&&this.states.get(r)||"disconnected"}registerPtyInputSender(t){this.ptyInputSender=t}sendData(t,r){return!1}sendPtyInput(t,r,n){return this.ptyInputSender?this.ptyInputSender(t,r,n):!1}onScreenshot(t,r){return this.screenshotCallbacks.set(t,r),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,r){this.screenshotCallbacks.forEach(n=>n(t,r))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,r){this.statusCallbacks.forEach(n=>n(t,r))}emitRuntimeSnapshot(t,r,n=0,a=!1,o,i){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:n,text:r,truncated:a,cols:o,rows:i})}emitSessionOutput(t,r,n){!t||typeof r!="string"||!r||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(t,r){const n=this.runtimeListeners.get(t)||new Set;return n.add(r),this.runtimeListeners.set(t,n),()=>{const a=this.runtimeListeners.get(t);a&&(a.delete(r),a.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,r,n){if(!r)return{success:!1,error:"sessionId is required"};const a=new URL(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`,window.location.origin);typeof(n==null?void 0:n.sinceSeq)=="number"&&a.searchParams.set("sinceSeq",String(n.sinceSeq));const o=await ds(`${a.pathname}${a.search}`);if(!o.ok){let c=`Runtime snapshot unavailable (${o.status})`;try{const d=await o.json();d!=null&&d.error&&(c=d.error)}catch{}return{success:!1,error:c}}const i=await o.json();return this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof i.seq=="number"?i.seq:0,text:typeof i.text=="string"?i.text:"",truncated:!!i.truncated,cols:typeof i.cols=="number"?i.cols:void 0,rows:typeof i.rows=="number"?i.rows:void 0,force:!!(n!=null&&n.force)}),{success:!0}}emitRuntimeEvent(t,r){var n;(n=this.runtimeListeners.get(t))==null||n.forEach(a=>a(r))}}const cs=new v2;function w2(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=ll();return r?`${t}?token=${encodeURIComponent(r)}`:t}const En=w2(),yd=3e3,j2=3e4;let Zt=null,k2=0;const ba=new Map;let $s=null,Qr=null;function vd(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Or(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function N2(e){return e==="connected"?"connected":e}async function Zr(e,t,r){const n=dp(e,r||{}),a=Zt;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++k2}_${Date.now()}`;return new Promise((i,c)=>{const d=setTimeout(()=>{ba.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);ba.set(o,{resolve:p=>{clearTimeout(d),i(p)},reject:p=>{clearTimeout(d),c(p)}}),a.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function di(e,t){const r=Zt;if(!r||r.readyState!==WebSocket.OPEN||!t||t.type!=="subscribe"&&t.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(t)),!0}catch{return!1}}function Km(e,t,r){const n=Zt;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=dp(e,{sessionId:t,targetSessionId:t,data:r});try{return n.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:a.payload}})),!0}catch{return!1}}cs.registerPtyInputSender(Km);class S2{constructor(t){et(this,"daemonId");et(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(Zt==null?void 0:Zt.readyState)===WebSocket.OPEN}get connectionState(){return(Zt==null?void 0:Zt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return Zr(this.daemonId,t,r)}async sendInput(t,r){return Zr(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,$s&&(clearInterval($s),$s=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Zr(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const a=await fetch(`data:image/jpeg;base64,${n.base64}`).then(o=>o.blob());cs.emitScreenshot(this.daemonId,a)}}catch{}};r(),$s=setInterval(r,2e3)}stopScreenshots(t){$s&&(clearInterval($s),$s=null)}}let Vt=null;function C2(e){return(!Vt||Vt.daemonId!==e)&&(Vt=new S2(e)),Vt}function I2({children:e}){const t=l.useRef(en()),r=en();t.current=r;const{setUserName:n}=hs(),a=l.useRef(n);a.current=n;const o=l.useRef(null),i=l.useRef(null),[,c]=l.useState("disconnected"),d=l.useCallback((f,j)=>{c(f),Qr==null||Qr(f,j)},[]),p=l.useRef(null),u=l.useRef(),m=l.useRef(yd),h=l.useRef(!0),y=l.useRef(!1),x=l.useRef("initial_connect");return l.useEffect(()=>{h.current=!0,y.current=!1;function f(){var b,w;if(!h.current||((b=p.current)==null?void 0:b.readyState)===WebSocket.OPEN||((w=p.current)==null?void 0:w.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${En}...`),Or("connect_attempt",{url:En,reason:x.current,delayMs:m.current});let k;try{k=new WebSocket(En)}catch(I){console.error("[Standalone WS] Failed to create WebSocket:",I),j();return}p.current=k,k.onopen=()=>{if(!h.current){k.close();return}d("connected"),m.current=yd,Or("open",{url:En,reason:x.current}),rs.resubscribeAll({sendData:di}),console.log("[Standalone WS] Connected")},Zt=k,k.onmessage=I=>{var v,g;try{const S=JSON.parse(I.data);if((S.type==="command_result"||S.type==="error")&&S.requestId){const N=ba.get(S.requestId);N&&(ba.delete(S.requestId),S.type==="error"?N.reject(new Error(((v=S.data)==null?void 0:v.message)||"Command failed")):N.resolve(S.data));return}if(S.type==="session_output"){const N=S.sessionId||S.cliId||S.cliType;N&&cs.emitSessionOutput(N,typeof S.data=="string"?S.data:"",typeof S.seq=="number"?S.seq:void 0);return}if(S.type==="runtime_snapshot"){cs.emitRuntimeSnapshot(S.sessionId,typeof S.text=="string"?S.text:"",typeof S.seq=="number"?S.seq:0,!!S.truncated,typeof S.cols=="number"?S.cols:void 0,typeof S.rows=="number"?S.rows:void 0);return}if(S.type==="topic_update"){const N=S.update;N&&rs.publish(N);return}if(S.type==="status"||S.type==="initial_state"){const N=S.data;if(!N)return;const{injectEntries:C,markLoaded:R,getIdes:T}=t.current,_=N.instanceId||"standalone",P=T().find(A=>A.id===_),B=C2(_);cs.register(_,B),cs.setState(_,"connected"),d("connected",_),cs.emitStatus(_,N);const z=sa(N,{daemonId:_,existingDaemon:P,existingEntries:T()});vd("ws_status",{type:S.type,daemonId:_,sessions:(N.sessions||[]).map(A=>({id:A.id,parentId:A.parentId,providerType:A.providerType,kind:A.kind,transport:A.transport,unread:A.unread,inboxBucket:A.inboxBucket,lastSeenAt:A.lastSeenAt,lastUpdated:A.lastUpdated,title:A.title})),recentLaunches:(N.recentLaunches||[]).map(A=>({id:A.id,providerType:A.providerType,kind:A.kind,workspace:A.workspace,lastLaunchedAt:A.lastLaunchedAt}))}),vd("entries",{daemonId:_,entries:z.filter(A=>A.type!=="adhdev-daemon").map(A=>({id:A.id,type:A.type,unread:A.unread,inboxBucket:A.inboxBucket,lastSeenAt:A.lastSeenAt,lastUpdated:A.lastUpdated,sessionId:A.sessionId}))}),z.length>0&&C(z,{authoritativeDaemonIds:[_]}),R(),i.current!==_&&((g=o.current)==null||g.call(o),i.current=_,o.current=rs.subscribe({sendData:di},_,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${_}`,params:{includeSessions:!0}},A=>{if(A.topic!=="daemon.metadata")return;const O=t.current.getIdes(),$=O.find(E=>E.id===_),L=sa(A.status,{daemonId:_,existingDaemon:$,existingEntries:O,timestamp:A.timestamp});L.length>0&&t.current.injectEntries(L,{authoritativeDaemonIds:[_]}),A.userName&&a.current&&a.current(A.userName)}))}}catch(S){console.error("[Standalone WS] Parse error:",S)}},k.onclose=I=>{h.current&&(Vt==null||Vt.stopScreenshots(),Vt&&cs.setState(Vt.daemonId,"disconnected"),d("disconnected"),p.current=null,x.current=`close:${I.code}${I.wasClean?":clean":":unclean"}`,Or("close",{code:I.code,reason:I.reason||"",wasClean:I.wasClean}),j())},k.onerror=I=>{y.current||!h.current||(x.current="error",Or("error",{message:I instanceof Event?"event":String(I),readyState:k.readyState}),console.warn("[Standalone WS] Error, will reconnect:",I))}}function j(){if(!h.current)return;clearTimeout(u.current);const k=m.current;console.log(`[Standalone WS] Reconnecting in ${k}ms...`),Or("schedule_reconnect",{reason:x.current,delayMs:k}),u.current=setTimeout(()=>{m.current=Math.min(m.current*1.5,j2),f()},k)}return f(),()=>{var k;h.current=!1,y.current=!0,(k=o.current)==null||k.call(o),o.current=null,i.current=null,clearTimeout(u.current),p.current&&(p.current.onerror=null,p.current.onclose=null,p.current.close(),p.current=null,Zt=null),Vt&&(Vt.stopScreenshots(),cs.unregister(Vt.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function A2({children:e}){const[t,r]=l.useState("disconnected"),[n,a]=l.useState(null);l.useEffect(()=>(Qr=(i,c)=>{r(i),c&&a(c)},()=>{Qr=null}),[]);const o=l.useMemo(()=>{const i=t==="connected",c=N2(t),d={};return n&&(d[n]=c),d.standalone=c,{wsStatus:t,isConnected:i,connectionStates:d}},[t,n]);return s.jsx(zh,{connectionOverrides:o,children:s.jsx(I2,{children:e})})}const Um="adhdev_standalone_font_preferences",Gs={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},$a=[{id:"default",label:"Default",family:"var(--font-sans)",description:"Current dashboard sans stack"},{id:"system-ui",label:"System UI",family:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Use the browser/OS default UI font"},{id:"inter",label:"Inter",family:'"Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Match the current product default explicitly"},{id:"pretendard",label:"Pretendard",family:'"Pretendard", "Noto Sans KR", system-ui, sans-serif',description:"Crisp Korean-first sans fallback stack"},{id:"noto-sans-kr",label:"Noto Sans KR",family:'"Noto Sans KR", "Apple SD Gothic Neo", "Malgun Gothic", "Segoe UI", sans-serif',description:"Wide CJK coverage with neutral metrics"},{id:"serif",label:"Serif",family:'"Iowan Old Style", "Apple Garamond", "Times New Roman", serif',description:"Reading-focused serif stack for long replies"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS font-family stack"}],ln=[{id:"default",label:"Default mono",family:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',description:"Current monospace stack"},{id:"jetbrains-mono",label:"JetBrains Mono",family:'"JetBrains Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Readable coding font with strong punctuation"},{id:"fira-code",label:"Fira Code",family:'"Fira Code", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Popular ligature-friendly code font"},{id:"cascadia-code",label:"Cascadia Code",family:'"Cascadia Code", "Cascadia Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Windows-friendly modern coding font"},{id:"berkeley-mono",label:"Berkeley Mono",family:'"Berkeley Mono", "SF Mono", ui-monospace, Menlo, Consolas, monospace',description:"Editorial-feeling mono stack if installed"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS monospace stack"}],M2=new Set($a.map(e=>e.id)),_2=new Set(ln.map(e=>e.id));function ps(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Yn("chat",t.chat),code:Yn("code",t.code),terminal:Yn("terminal",t.terminal)}}function Yn(e,t){const r=Gs[e],n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},a=typeof n.preset=="string"?n.preset.trim():"",o=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?M2:_2).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:r:{preset:a}:r}function Jn(e,t){var a;const r=Yn(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?$a:ln;return((a=n.find(o=>o.id===r.preset))==null?void 0:a.family)||n[0].family}function T2(e){const t=ps(e),r=Jn("chat",t.chat),n=Jn("code",t.code),a=Jn("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function Bs(e,t=document.documentElement){const r=ps(e),n=T2(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(n))t.style.setProperty(a,o);return r}function ui(e){const t=ps(e);try{localStorage.setItem(Um,JSON.stringify(t))}catch{}return t}function L2(){try{const e=localStorage.getItem(Um);if(e)return ps(JSON.parse(e))}catch{}return Gs}function R2(){return Bs(L2())}function Hr(e,t){var n;const r=e==="chat"?$a:ln;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const P2=[{id:"dashboard",path:"/dashboard",icon:s.jsx(Dd,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(Is,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:s.jsx(ss,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:s.jsx(ya,{}),label:"Settings"}];function D2({children:e}){const t=cn(),r=mi(),n=l.useMemo(()=>P2.map(o=>({...o,active:r.pathname.startsWith(o.path),onSelect:()=>t(o.path)})),[r.pathname,t]),a=l.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Docs"}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(Ed,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(bi,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(L0,{brand:({collapsed:o})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!o&&s.jsx("span",{children:"ADHDev"})]}),navItems:n,footerItems:a,footerInfo:({collapsed:o})=>o?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.9.82"]}),footerActions:({collapsed:o,toggleCollapsed:i})=>s.jsxs("div",{className:`nav-item cursor-pointer ${o?"justify-center py-2.5 px-0":"mt-1"}`,onClick:i,title:o?"Expand sidebar":"Collapse sidebar",children:[s.jsx("span",{className:"nav-icon text-base",children:o?"›":"‹"}),!o&&s.jsx("span",{className:"text-xs",children:"Collapse"})]}),children:e})}const $2=[{icon:s.jsx(Is,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Xs,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Fd,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(os,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(tn,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Ed,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],E2=[{icon:s.jsx(kf,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Dd,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(wr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(xf,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx($d,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(yf,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],B2=[{feature:"Agent chat relay",selfhost:!0,cloud:!0},{feature:"Live IDE screenshots",selfhost:!0,cloud:!0},{feature:"Remote IDE control",selfhost:!0,cloud:!0},{feature:"Multi-IDE monitoring",selfhost:!0,cloud:!0},{feature:"Extension and CLI agents",selfhost:!0,cloud:!0},{feature:"Access from any network",selfhost:!1,cloud:!0},{feature:"WebRTC P2P streaming",selfhost:!1,cloud:!0},{feature:"Mobile push notifications",selfhost:!1,cloud:!0},{feature:"REST API and webhooks",selfhost:!1,cloud:!0},{feature:"Team collaboration",selfhost:!1,cloud:!0},{feature:"Multi-machine burrows",selfhost:!1,cloud:!0},{feature:"SSO, RBAC, audit logs",selfhost:!1,cloud:!0}];function F2(){return s.jsxs(mn,{icon:s.jsx(bi,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"px-3 py-1 text-[11px] font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","0.9.82"]}),children:[s.jsx(mt,{children:s.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[s.jsxs("div",{className:"max-w-2xl",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),s.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:"Keep the same dashboard experience, with the runtime fully on-device."}),s.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:"Standalone keeps the browser, daemon, screenshots, and control path on your own machine. It is the same core product shape as cloud, just without the remote networking and team layers."})]}),s.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"Docs ↗"}),s.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"GitHub ↗"}),s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:"Try Cloud ↗"})]})]})}),s.jsx(mt,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:$2.map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:e.icon}),e.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(mt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:up.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:mp.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:pp.map(e=>`${e.icon} ${e.name}`)}].map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[s.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(t=>s.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:t},t))})]},e.label))})}),s.jsx(mt,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:E2.map(e=>s.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:e.icon}),e.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(mt,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:s.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:s.jsxs("table",{className:"w-full text-[13px]",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"bg-bg-secondary",children:[s.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),s.jsx("tbody",{children:B2.map((e,t)=>s.jsxs("tr",{className:t%2===0?"bg-bg-glass":"bg-transparent",children:[s.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e.feature}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:e.selfhost?s.jsx("span",{className:"text-emerald-500",children:"✓"}):s.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:s.jsx("span",{className:"text-emerald-500",children:"✓"})})]},e.feature))})]})})}),s.jsx(Ma,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:"Cloud is optional, not required",description:"You can stay fully local in standalone, and move to cloud later without changing how you use the dashboard.",action:s.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:"Compare Cloud ↗"}),s.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[s.jsx(Lf,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Lo(e,t,r){return{...e,[t]:r}}function Ro({surface:e,title:t,description:r,value:n,options:a,onChange:o}){return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:r})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx($0,{value:n.preset,onChange:i=>{const c=i.target.value;o(c==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:c})},children:a.map(i=>s.jsx("option",{value:i.id,children:i.label},i.id))}),n.preset==="custom"&&s.jsx(ts,{type:"text",className:"font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:n.customFamily||"",onChange:i=>o({preset:"custom",customFamily:i.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Resolved stack:"})," ",s.jsx("span",{className:"font-mono break-all",children:Jn(e,n)})]})]})]})}function O2({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:o,onSave:i,onResetToSaved:c,onResetToDefaults:d}){const p=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below."}),n&&s.jsx(Ft,{variant:"error",children:n}),a&&s.jsx(Ft,{variant:"success",children:a}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(Ro,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:$a,onChange:u=>o(Lo(e,"chat",u))}),s.jsx(Ro,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:ln,onChange:u=>o(Lo(e,"code",u))}),s.jsx(Ro,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:ln,onChange:u=>o(Lo(e,"terminal",u))})]}),s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",Hr("chat",e.chat.preset)," · Code: ",Hr("code",e.code.preset)," · Terminal: ",Hr("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",Hr("chat",Gs.chat.preset)," / ",Hr("code",Gs.code.preset)]})]}),s.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:s.jsxs("div",{className:"chat-container-content",children:[s.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:s.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[s.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[s.jsx("span",{className:"chat-sender",children:"Hermes"}),s.jsx("span",{className:"chat-time",children:"now"})]}),s.jsxs("div",{className:"chat-markdown",children:[s.jsxs("p",{children:["Readable prose, ",s.jsx("strong",{children:"bold text"}),", and ",s.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),s.jsx("pre",{children:s.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),s.jsxs("div",{className:"chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"▸"}),s.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),s.jsxs("div",{className:"chat-msg-terminal",children:[s.jsx("div",{className:"chat-msg-header",children:"Terminal"}),s.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx(gs,{type:"button",variant:"primary",size:"sm",onClick:i,disabled:r||!p,children:r?"Saving…":"Save font settings"}),s.jsx(gs,{type:"button",variant:"secondary",size:"sm",onClick:c,disabled:r||!p,children:"Revert to saved"}),s.jsx(gs,{type:"button",variant:"secondary",size:"sm",onClick:d,disabled:r,children:"Reset to defaults"})]})]})}function H2(){const{ides:e}=hs(),t=e.find(F=>F.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=xt(),{userName:a}=hs(),[o,i]=l.useState(a||""),[c,d]=l.useState(null),[p,u]=l.useState(null),[m,h]=l.useState(Gs),[y,x]=l.useState(!1),[f,j]=l.useState(""),[k,b]=l.useState(""),[w,I]=l.useState("127.0.0.1"),[v,g]=l.useState(""),[S,N]=l.useState(""),[C,R]=l.useState(""),[T,_]=l.useState(""),[P,B]=l.useState(""),[z,A]=l.useState(!1),O=async()=>{const V=await(await ds("/auth/session")).json();d(V)},$=async()=>{const V=await(await ds("/api/v1/standalone/preferences")).json();u(V),I(V.standaloneBindHost);const pe=ps(V.standaloneFontPreferences);h(pe),Bs(pe),ui(pe)};l.useEffect(()=>{a!==void 0&&i(a)},[a]),l.useEffect(()=>{Promise.all([O(),$()]).catch(F=>{_(F instanceof Error?F.message:String(F))})},[]),l.useEffect(()=>{Bs(m)},[m]);const L=F=>{const V=F.target.value.trim();t!=null&&t.id&&V!==a&&n(t.id,"set_user_name",{userName:V}).catch(console.error)},[E,M]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),H=F=>{M(F);try{localStorage.setItem("adhdev_sound",F?"1":"0")}catch{}},Y=async()=>{j(""),b(""),x(!0);try{const F=ps(m),V=await ds("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:F})}),pe=await V.json();if(!V.ok)throw new Error((pe==null?void 0:pe.error)||"Failed to save standalone font preferences");const be=ps(pe.standaloneFontPreferences);u(pe),h(be),Bs(be),ui(be),b("Standalone chat fonts saved for this self-hosted dashboard.")}catch(F){j(F instanceof Error?F.message:String(F))}finally{x(!1)}},G=()=>{const F=ps(p==null?void 0:p.standaloneFontPreferences);j(""),b(""),h(F),Bs(F)},J=()=>{j(""),b(""),h(Gs),Bs(Gs)},te=async()=>{_(""),B(""),A(!0);try{const F=await ds("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:w})}),V=await F.json();if(!F.ok)throw new Error((V==null?void 0:V.error)||"Failed to save standalone network preference");u(V),I(V.standaloneBindHost),B(V.standaloneBindHost==="0.0.0.0"?"Default standalone network mode set to all interfaces (0.0.0.0). Restart standalone to apply it.":"Default standalone network mode set to localhost only. Restart standalone to apply it.")}catch(F){_(F instanceof Error?F.message:String(F))}finally{A(!1)}},oe=async()=>{if(_(""),B(""),S.trim().length<4){_("Password must be at least 4 characters.");return}if(S!==C){_("New password and confirmation do not match.");return}A(!0);try{const F=await ds("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,newPassword:S})}),V=await F.json();if(!F.ok)throw new Error((V==null?void 0:V.error)||"Failed to save password");d(V),await $(),g(""),N(""),R(""),B(c!=null&&c.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Wm()}catch(F){_(F instanceof Error?F.message:String(F))}finally{A(!1)}},q=async()=>{_(""),B(""),A(!0);try{const F=await ds("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,clear:!0})}),V=await F.json();if(!F.ok)throw new Error((V==null?void 0:V.error)||"Failed to clear password");d(V),await $(),g(""),N(""),R(""),B("Standalone password disabled.")}catch(F){_(F instanceof Error?F.message:String(F))}finally{A(!1)}};return s.jsxs(mn,{icon:s.jsx(ya,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(Ft,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost or your self-hosted LAN endpoint."}),(c==null?void 0:c.publicHostWarning)&&s.jsx(Ft,{variant:"warning",children:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token."}),s.jsx(mt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:s.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[s.jsx("span",{className:"text-text-muted",children:"Version"}),s.jsxs("span",{className:"font-mono text-xs",children:["v","0.9.82"]}),s.jsx("span",{className:"text-text-muted",children:"Status"}),s.jsx("span",{className:t?"text-green-400":"text-yellow-400",children:t?"● Running":"○ Not connected"}),s.jsx("span",{className:"text-text-muted",children:"Current bind"}),s.jsx("span",{className:"font-mono text-xs",children:(p==null?void 0:p.currentBindHost)||(c==null?void 0:c.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Default bind"}),s.jsx("span",{className:"font-mono text-xs",children:(p==null?void 0:p.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Auth"}),s.jsx("span",{className:"text-xs",children:c!=null&&c.hasPasswordAuth?"Password enabled":c!=null&&c.hasTokenAuth?"Token enabled":"No auth configured"})]})}),s.jsx(mt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token."}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:w==="127.0.0.1",onChange:()=>I("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 127.0.0.1. Best when only this machine should open the dashboard."})]})]}),s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:w==="0.0.0.0",onChange:()=>I("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"All interfaces"}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points."})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx(gs,{type:"button",variant:"primary",size:"sm",onClick:()=>{te()},disabled:z,children:z?"Saving…":"Save default network mode"}),s.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(p==null?void 0:p.currentBindHost)||(c==null?void 0:c.boundHost)||"127.0.0.1","."]})]})]})}),s.jsx(mt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:c!=null&&c.hasPasswordAuth?"A local password is currently required for browser access. Existing sessions are rotated when you change it.":"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended."}),T&&s.jsx(Ft,{variant:"error",children:T}),P&&s.jsx(Ft,{variant:"success",children:P}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx(ts,{type:"password",placeholder:c!=null&&c.hasPasswordAuth?"Current password":"Current password (not needed for first setup)",value:v,onChange:F=>g(F.target.value)}),s.jsx(ts,{type:"password",placeholder:c!=null&&c.hasPasswordAuth?"New password":"New standalone password",value:S,onChange:F=>N(F.target.value)}),s.jsx(ts,{type:"password",className:"md:col-span-2",placeholder:"Confirm new password",value:C,onChange:F=>R(F.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(gs,{type:"button",variant:"primary",size:"sm",onClick:()=>{oe()},disabled:z,children:z?"Saving…":c!=null&&c.hasPasswordAuth?"Update password":"Enable password"}),(c==null?void 0:c.hasPasswordAuth)&&s.jsx(gs,{type:"button",variant:"danger",size:"sm",onClick:()=>{q()},disabled:z,children:"Disable password"})]})]})}),s.jsx(mt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):s.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(F=>s.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${F.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:F.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:F.type})]},F.type))})}),s.jsx(mt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(U0,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(mt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",children:s.jsx(dv,{themeDescription:"Choose a preset or create a custom surface, accent, and chat palette for the standalone UI.",mobileDescription:"Choose whether phones open the dashboard as a chat app first or in the full workspace layout.",fontsSlot:s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Fonts"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Standalone-only typography overrides for chat text, markdown code, and terminal output."}),s.jsx(O2,{value:m,savedValue:ps(p==null?void 0:p.standaloneFontPreferences),saving:y,error:f,notice:k,onChange:h,onSave:()=>{Y()},onResetToSaved:G,onResetToDefaults:J})]})})}),s.jsx(mt,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(O0,{}),s.jsx(Es,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Tf,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:E,onChange:H})]})}),s.jsx(mt,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:s.jsx("div",{className:"flex flex-col gap-3",children:s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[s.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[s.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[s.jsx(ff,{size:16,className:"text-text-secondary"})," Display Name"]}),s.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),s.jsx(ts,{type:"text",className:"w-48 text-right",placeholder:"Anonymous",value:o,onChange:F=>i(F.target.value),onBlur:L,onKeyDown:F=>{F.key==="Enter"&&F.currentTarget.blur()}})]})})})]})}const W2=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],zr="adhdev_onboarding_done",K2=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],U2={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function z2({onDone:e}){const[t,r]=l.useState([]),[n,a]=l.useState(new Set(W2)),[o,i]=l.useState(!0),[c,d]=l.useState(null),[p,u]=l.useState(!1),[m,h]=l.useState(null),[y,x]=l.useState("all");l.useEffect(()=>{let v=!1;const g=window.location.hostname==="localhost"?"/registry":"https://api.adhf.dev/api/v1/registry";return fetch(`${g}/providers?sort=popular&limit=100`).then(S=>{if(!S.ok)throw new Error(`HTTP ${S.status}`);return S.json()}).then(S=>{v||r(S.providers??[])}).catch(S=>{v||d(S instanceof Error?S.message:String(S))}).finally(()=>{v||i(!1)}),()=>{v=!0}},[]);const f=t.filter(v=>y==="all"||v.category===y),j=["cli","ide","extension","acp"].map(v=>({category:v,items:f.filter(g=>g.category===v)})).filter(v=>v.items.length>0),k=l.useCallback(v=>{a(g=>{const S=new Set(g);return S.has(v)?S.delete(v):S.add(v),S})},[]),b=l.useCallback(async()=>{if(n.size===0){localStorage.setItem(zr,"1"),e();return}u(!0);const v=[];for(const g of n)try{const N=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:g})})).json().catch(()=>({}));v.push({type:g,ok:!!N.success,error:N.error})}catch(S){v.push({type:g,ok:!1,error:S instanceof Error?S.message:String(S)})}h(v),u(!1),v.every(g=>g.ok)&&localStorage.setItem(zr,"1")},[n,e]),w=l.useCallback(()=>{localStorage.setItem(zr,"1"),e()},[e]),I=l.useCallback(()=>{m&&m.every(v=>v.ok)?e():p||w()},[m,p,e,w]);return s.jsx(yu,{open:!0,onClose:I,size:"lg",contentClassName:"max-w-2xl",title:"Welcome to ADHDev",footer:s.jsxs("div",{className:"flex w-full items-center gap-2",children:[s.jsxs("div",{className:"text-[11px] text-text-muted",children:[n.size," provider",n.size!==1?"s":""," selected"]}),s.jsxs("div",{className:"ml-auto flex gap-2",children:[s.jsx(gs,{variant:"secondary",size:"sm",onClick:w,disabled:p,children:"Skip"}),s.jsx(gs,{variant:"primary",size:"sm",onClick:()=>{m?(localStorage.setItem(zr,"1"),e()):b()},disabled:p||!m&&n.size===0,children:p?"Installing…":m?"Done":`Install ${n.size}`})]})]}),children:s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsxs("div",{className:"text-[12px] text-text-muted",children:["Pick the providers you want to use. Defaults to the four officially supported CLI providers; you can install IDE, ACP, or extension providers from the tabs below or later from ",s.jsx("span",{className:"text-text-secondary",children:"Burrow → Providers → Add provider"}),"."]}),!o&&!c&&t.length>0&&s.jsx("div",{className:"flex gap-1 flex-wrap border-b border-border-subtle pb-2",children:K2.map(v=>{const g=v.key==="all"?t.length:t.filter(S=>S.category===v.key).length;return g===0&&v.key!=="all"?null:s.jsxs("button",{onClick:()=>x(v.key),className:`machine-btn text-[10px] px-2 py-0.5 ${y===v.key?"bg-accent-primary/12 border-accent-primary/40 text-accent-primary":""}`,children:[v.label," ",s.jsxs("span",{className:"opacity-60",children:["(",g,")"]})]},v.key)})}),o&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:"Loading registry…"}),!o&&c&&s.jsxs(Ft,{variant:"error",children:["Failed to load registry: ",c]}),!o&&!c&&f.length===0&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:"No providers in this category."}),!o&&!c&&f.length>0&&s.jsx("div",{className:"flex flex-col gap-4",children:j.map(v=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:U2[v.category]??v.category}),s.jsx("div",{className:"grid gap-1.5",children:v.items.map(g=>{var T,_;const S=n.has(g.type),N=m==null?void 0:m.find(P=>P.type===g.type),C=((T=g.manifest)==null?void 0:T.icon)??"📦",R=((_=g.manifest)==null?void 0:_.details)??"";return s.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${S?"bg-accent-primary/[0.06] border-accent-primary/30":"bg-bg-glass border-border-subtle hover:bg-bg-glass-hover"}`,children:[s.jsx("input",{type:"checkbox",checked:S,onChange:()=>k(g.type),disabled:p,className:"shrink-0"}),s.jsx("span",{className:"text-base shrink-0",children:C}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[13px] font-medium text-text-primary truncate",children:g.displayName}),R&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:R})]}),N&&s.jsx("span",{className:`text-[10px] font-semibold ${N.ok?"text-status-online":"text-status-error"}`,children:N.ok?"✓ installed":`✗ ${N.error??"failed"}`})]},g.type)})})]},v.category))})]})})}function G2(){try{return localStorage.getItem(zr)==="1"}catch{return!1}}_0();sv();R2();const V2=Ad({baseUrl:"",getToken:ll});function q2({children:e}){const[t,r]=l.useState(null),[n,a]=l.useState(!0),[o,i]=l.useState(""),[c,d]=l.useState(""),[p,u]=l.useState(!1),m=async()=>{a(!0),d("");try{const x=await(await ds("/auth/session")).json();r(x)}catch(y){d(y instanceof Error?y.message:String(y))}finally{a(!1)}};l.useEffect(()=>{m()},[]),l.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let y=!1;return(async()=>{try{const x=await ds("/api/v1/standalone/preferences");if(!x.ok)return;const f=await x.json();if(y)return;const j=ps(f.standaloneFontPreferences);Bs(j),ui(j)}catch{}})(),()=>{y=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const h=async y=>{y.preventDefault(),u(!0),d("");try{const x=await ds("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:o})}),f=await x.json();if(!x.ok)throw new Error((f==null?void 0:f.error)||"Login failed");r(f),i(""),Wm()}catch(x){d(x instanceof Error?x.message:String(x))}finally{u(!1)}};return n?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):t?!t.required||t.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:t.hasPasswordAuth?"This self-hosted dashboard is protected by a local password.":"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session."})]}),t.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:h,children:[s.jsx(ts,{type:"password",value:o,onChange:y=>i(y.target.value),placeholder:"Enter standalone password",autoFocus:!0}),s.jsx(gs,{type:"submit",variant:"primary",disabled:p||!o,className:"justify-center",children:p?"Signing in…":"Unlock dashboard"})]}):s.jsx(Ft,{variant:"warning",children:"Password login is not enabled on this server."}),c&&s.jsx(Ft,{variant:"error",children:c})]})}):s.jsxs("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:["Failed to load standalone auth status: ",c||"unknown error"]})}function wd(){const{ides:e,initialLoaded:t}=hs();if(!t)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const r=e.find(n=>n.daemonMode||n.type==="adhdev-daemon");return r?s.jsx($o,{to:`/machines/${r.id}`,replace:!0}):s.jsx($o,{to:"/dashboard",replace:!0})}function Y2(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let r=!1;if(!G2())return fetch("/api/v1/providers/installed").then(n=>n.ok?n.json():{providers:[]}).then(n=>{r||(n.providers??[]).length===0&&t(!0)}).catch(()=>{}),()=>{r=!0}},[]),e?s.jsx(z2,{onDone:()=>t(!1)}):null}function J2(){const{ides:e}=hs(),t=l.useMemo(()=>{for(const p of e)if(p.activeInteractivePrompt)return p.instanceId??p.id;return null},[e]),{promptSession:r,hasActivePrompt:n,responseError:a,isSubmitting:o,submit:i,cancel:c,reopen:d}=vp(t);return n?s.jsxs("div",{className:"relative",children:[!r&&s.jsx("button",{type:"button",onClick:d,className:"fixed bottom-4 right-4 z-[79] btn btn-primary btn-sm shadow-lg",children:"Awaiting your input ↑"}),s.jsx(Zd,{promptSession:r,isSubmitting:o,error:a,onSubmit:i,onCancel:c})]}):null}function X2(){const e=l.useMemo(()=>({sendCommand:Zr,sendData:di,sendPtyInput:Km}),[]);return s.jsx(Ah,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(qh,{client:V2,children:s.jsx(q2,{children:s.jsx(A2,{children:s.jsx(Jh,{value:e,children:s.jsxs(ef,{sendDaemonCommand:Zr,children:[s.jsx(J2,{}),s.jsxs(D2,{children:[s.jsx(Y2,{}),s.jsxs(Mh,{children:[s.jsx(ks,{path:"/dashboard",element:s.jsx(QN,{})}),s.jsx(ks,{path:"/machine",element:s.jsx(wd,{})}),s.jsx(ks,{path:"/machines/:id",element:s.jsx(iC,{})}),s.jsx(ks,{path:"/machines",element:s.jsx(wd,{})}),s.jsx(ks,{path:"/about",element:s.jsx(F2,{})}),s.jsx(ks,{path:"/settings",element:s.jsx(H2,{})}),s.jsx(ks,{path:"/mesh",element:s.jsx(g2,{children:s.jsx(f2,{})})}),s.jsx(ks,{path:"*",element:s.jsx($o,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}jy({connectionManager:cs});_h(document.getElementById("root")).render(s.jsx(X2,{}));