@adhdev/daemon-standalone 1.0.54-rc.9 → 1.0.56-rc.1
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
|
`),le=((se=pe[0])==null?void 0:se.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:()=>X(V),children:[s.jsx("span",{className:"text-[10px] text-text-muted w-3",children:ee?"▾":"▸"}),s.jsx("span",{className:"font-mono text-accent-primary w-20 shrink-0 text-[11px]",children:V}),!ee&&s.jsx("span",{className:"text-text-secondary truncate font-mono text-[11px]",children:le}),s.jsxs("span",{className:"ml-auto text-text-muted text-[10px] shrink-0",children:[pe.length,"L"]})]}),ee&&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:q||"(empty)"})]},V)})})]}),s.jsx(ir,{}),O.nativeSource&&s.jsxs("div",{children:[s.jsxs($n,{children:["Status History",O.statusHistory&&O.statusHistory.length>0?` (${O.statusHistory.length})`:""]}),O.statusHistory&&O.statusHistory.length>0?s.jsx("div",{className:"space-y-px",children:[...O.statusHistory].reverse().slice(0,20).map((V,q)=>s.jsx("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 ${or(V.status)}`,children:V.status}),s.jsx("span",{className:"text-text-secondary text-[11px] shrink-0 tabular-nums",children:Hn(V.at)}),V.trigger&&s.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded font-mono shrink-0 text-text-secondary bg-bg-glass border border-border-default",children:V.trigger})]})},q))}):s.jsx("div",{className:"text-text-muted text-[11px] italic px-1",children:"N/A (native-source provider — no state-machine rules)"})]}),!O.nativeSource&&O.stateHistory&&O.stateHistory.length>0&&s.jsxs("div",{children:[s.jsxs($n,{children:["State History (",O.stateHistory.length,")"]}),s.jsx("div",{className:"space-y-px",children:[...O.stateHistory].reverse().slice(0,20).map((V,q)=>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 ${or(V.stateId)}`,children:V.stateId}),s.jsx("span",{className:"text-text-secondary text-[11px] shrink-0 tabular-nums",children:Hn(V.at)}),V.durationMs>0&&s.jsxs("span",{className:"text-text-muted text-[11px]",children:["held ",s.jsx("span",{className:"text-text-secondary",children:Id(V.durationMs)})]}),V.reason&&s.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-mono shrink-0 ${aj[String(V.reason)]??"text-text-secondary bg-bg-glass border border-border-default"}`,children:String(V.reason)}),V.debounceKind&&String(V.debounceKind)!=="none"&&s.jsxs("span",{className:"text-text-muted text-[10px] font-mono",children:["debounce:",String(V.debounceKind)]}),V.matchedStateId&&String(V.matchedStateId)!==V.stateId&&s.jsxs("span",{className:"text-text-muted text-[10px] font-mono",children:["eval→",s.jsx("span",{className:"text-text-secondary",children:String(V.matchedStateId)})]})]}),V.matchedRules&&V.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:[V.matchedRules.slice(0,3).map((ee,pe)=>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 ee=="string"?ee:JSON.stringify(ee)},pe)),V.matchedRules.length>3&&s.jsxs("span",{className:"text-[10px] text-text-muted",children:["+",V.matchedRules.length-3," more"]})]})]},q))})]}),s.jsx(ir,{}),(()=>{const V=O.messages??O.committedMessages??[];if(V.length===0)return null;const q=V.filter(le=>le.role==="user").length,ee=V.filter(le=>le.role==="assistant").length,pe=[...V].reverse().find(le=>le.role==="assistant");return s.jsxs("div",{children:[s.jsxs($n,{children:["Transcript (",V.length," — ",q,"u / ",ee,"a)"]}),pe&&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 ",pe.receivedAt?Hn(pe.receivedAt):""]}),s.jsxs("div",{className:"text-text-secondary font-mono whitespace-pre-wrap line-clamp-4 break-all",children:[pe.content.slice(0,400),pe.content.length>400?"…":""]})]})]})})(),O.specPath&&s.jsx("div",{className:"text-[10px] text-text-muted font-mono truncate border-t border-border-default pt-2 mt-1",title:O.specPath,children:O.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(V=>!V),children:[s.jsx("span",{className:"text-text-muted",children:p?"▾":"▸"}),s.jsxs("span",{children:["Raw screen (",O.screen?O.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:O.screen||"(empty)"})]})]})]})]})})})}function lj({activeConv:e,clearToken:t=0,terminalRef:n,handleSendChat:a,isSendingChat:r=!1,sendFeedbackMessage:o=null,isVisible:i=!0,isInputActive:c=!0}){var Be;const{t:d}=ke("common");Ss();const{sendPtyInput:p}=St(),[u,m]=l.useState(!1),f=l.useRef(!1);f.current=u;const[g,k]=l.useState("Runtime terminal unavailable"),[h,x]=l.useState(!1),[S,b]=l.useState(null),[w,C]=l.useState(!1),[v,y]=l.useState(!1),[j,N]=l.useState(1),[T,A]=l.useState(!1),[I,D]=l.useState(!1),[M,E]=l.useState(!1),[P,B]=l.useState(!1),[R,W]=l.useState(!1),[_,H]=l.useState({width:0,height:0}),[L,F]=l.useState({width:0,height:0}),[$,K]=l.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[z,ne]=l.useState(null),ie=l.useRef(null),Ce=l.useRef(null),me=l.useRef(!1),O=l.useRef(!1),Y=l.useRef(i),X=l.useRef(0),Q=l.useRef(!1),ve=l.useRef(""),he=l.useRef(null),Z=l.useRef(!1),fe=l.useRef(!1),V=l.useRef(null),q=l.useRef(null),ee=l.useRef(null),pe=32*1024,le=()=>{var ge,je,Te,Fe;return((je=(ge=ie.current)==null?void 0:ge.ownerDocument)==null?void 0:je.defaultView)||((Fe=(Te=Ce.current)==null?void 0:Te.ownerDocument)==null?void 0:Fe.defaultView)||window},se=ge=>{const je=le();return{ownerWindow:je,frameId:je.requestAnimationFrame(ge)}},te=()=>{const ge=V.current;if(ge){try{ge.ownerWindow.cancelAnimationFrame(ge.frameId)}catch{}V.current=null}},ue=()=>{const ge=q.current;if(ge){try{ge.ownerWindow.clearTimeout(ge.timeoutId)}catch{}q.current=null}},ye=()=>{const ge=ee.current;if(ge){try{ge.ownerWindow.clearTimeout(ge.timeoutId)}catch{}ee.current=null}},Me=()=>{i&&V.current===null&&(V.current=se(()=>{oe()}))},re=e.tabKey,ce=e.sessionId||"",Ae=e.daemonId||((Be=e.routeId)==null?void 0:Be.split(":")[0])||e.routeId||"",be=Xl(e),we=u?be?Tm:o:g,_e=u&&o||null,U=FC,Ne=BC,Ie=.05,We=()=>{const ge=L.width,je=L.height;if(!Number.isFinite(_.width)||_.width<=0||!Number.isFinite(_.height)||_.height<=0||!Number.isFinite(ge)||ge<=0||!Number.isFinite(je)||je<=0)return 1;const Te=_.width/ge,Fe=_.height/je;return Number(Math.min(Ne,Math.max(U,Math.min(Te,Fe))).toFixed(2))},Xe=We(),et=me.current&&j>Xe,J=Number.isFinite(L.width)&&L.width>0?Math.max(_.width,Math.round(L.width*j)):_.width,Le=Number.isFinite(L.height)&&L.height>0?Math.max(_.height,Math.round(L.height*j)):_.height,$e=()=>{se(()=>{const ge=Ce.current;ge&&(ge.scrollLeft=0,ge.scrollTop=ge.scrollHeight-ge.clientHeight)})},at=()=>{var ge,je;X.current=0,Q.current=!1,ve.current="",he.current=null,Z.current=!1,fe.current=!1,me.current||(O.current=!1,N(1)),V.current!==null&&te(),m(!1),k("Runtime terminal unavailable"),ye(),ue(),b(null),ne(null),A(!1),x(!1),C(!1),y(!1),(je=(ge=n.current)==null?void 0:ge.reset)==null||je.call(ge)},rt=()=>{var ge,je;X.current=0,Q.current=!1,ve.current="",he.current=null,Z.current=!1,fe.current=!1,V.current!==null&&te(),m(!0),k(""),ye(),ue(),b(null),ne(null),A(!1),x(!1),C(!1),y(!1),(je=(ge=n.current)==null?void 0:ge.reset)==null||je.call(ge)},G=()=>{fe.current&&(fe.current=!1,se(()=>{var ge,je;(je=(ge=n.current)==null?void 0:ge.scrollToTop)==null||je.call(ge)}))},oe=()=>{if(V.current=null,!i)return;const ge=ve.current;if(!ge)return;const je=ge.slice(0,pe);ve.current=ge.slice(je.length);const Te=n.current;if(!Te){ve.current=je+ve.current,Me();return}Te.write(je,()=>{if(ve.current.length>0){Me();return}G()})},de=ge=>{ge&&(ve.current+=ge,Me())},xe=(ge,je=0,Te,Fe,Ge={})=>{var Ve,ut,zt,Et;const dt=!!Ge.force;!dt&&je>0&&X.current>=je||!dt&&je===0&&Q.current||(X.current=je,je>0&&C(!0),m(!0),k(""),typeof Te=="number"&&typeof Fe=="number"&&Te>0&&Fe>0&&((ut=(Ve=n.current)==null?void 0:Ve.resize)==null||ut.call(Ve,Te,Fe)),ve.current="",(Et=(zt=n.current)==null?void 0:zt.reset)==null||Et.call(zt),ge?de(ge):G())};l.useEffect(()=>{at()},[ce]),l.useEffect(()=>{var je;if(!ce)return;const ge=((je=Ct.onRuntimeEvent)==null?void 0:je.call(Ct,ce,Te=>{if(!(!Te||Te.sessionId!==ce)){if(Te.type==="runtime_snapshot"){if(!i){he.current={text:Te.text||"",seq:Te.seq||0,cols:Te.cols,rows:Te.rows,force:!!Te.force};return}xe(Te.text||"",Te.seq||0,Te.cols,Te.rows,{force:!!Te.force});return}if(Te.type==="session_output"){Q.current=!0,typeof Te.seq=="number"&&(X.current=Math.max(X.current,Te.seq),Te.seq>0&&C(!0)),f.current||m(!0),f.current||k(""),typeof Te.data=="string"&&de(Te.data);return}if(Te.type==="session_cleared"){if(!i){Z.current=!0,ve.current="",he.current=null;return}rt();return}if(Te.type==="session_io_error"){const Fe=typeof Te.error=="string"&&Te.error?Te.error:typeof Te.reason=="string"&&Te.reason?Te.reason:"unknown error";m(!1),k(`Runtime input failed: ${Fe}`);return}}},Ae))||(()=>{});return()=>{ge()}},[Ae,ce,n,i]);const Se=async(ge={})=>{var je;if(!Ae||!ce)return{success:!1,error:"daemonId and sessionId are required"};ge.preserveStatus||k(ge.loadingMessage||"Loading runtime terminal...");try{const Te=await((je=Ct.requestRuntimeSnapshot)==null?void 0:je.call(Ct,Ae,ce,{sinceSeq:ge.sinceSeq,force:ge.force}));return Te&&Te.success===!1?(ge.preserveStatus||(m(!1),k(`Runtime terminal unavailable: ${Te.error}`)),Te):Te||{success:!0}}catch(Te){const Fe=(Te==null?void 0:Te.message)||String(Te);return ge.preserveStatus||(m(!1),k(`Runtime terminal unavailable: ${Fe}`)),{success:!1,error:Fe}}},Pe=async ge=>{var dt,Ve;const je=((dt=ie.current)==null?void 0:dt.ownerDocument)||document,Te=je.defaultView||window,Fe=(Ve=Te.navigator)==null?void 0:Ve.clipboard;if(Fe!=null&&Fe.writeText&&Te.isSecureContext)try{return await Fe.writeText(ge),!0}catch{}let Ge=null;try{return Ge=je.createElement("textarea"),Ge.value=ge,Ge.setAttribute("readonly","true"),Ge.style.position="fixed",Ge.style.left="-9999px",Ge.style.top="0",je.body.appendChild(Ge),Ge.focus(),Ge.select(),je.execCommand("copy")}catch{return!1}finally{Ge==null||Ge.remove()}},He=ge=>{ue(),ne(ge);const je=le();q.current={ownerWindow:je,timeoutId:je.setTimeout(()=>{q.current=null,ne(Te=>Te===ge?null:Te)},2200)}},Ee=ge=>{ye(),b(ge);const je=le();ee.current={ownerWindow:je,timeoutId:je.setTimeout(()=>{ee.current=null,b(Te=>Te===ge?null:Te)},2200)}},Je=async()=>{var Ge,dt,Ve,ut;const ge=((dt=(Ge=n.current)==null?void 0:Ge.getSelection)==null?void 0:dt.call(Ge))||"",je=((ut=(Ve=n.current)==null?void 0:Ve.getVisibleText)==null?void 0:ut.call(Ve))||"",Te=ge.trimEnd()||je.trimEnd();if(!Te){He("Nothing to copy");return}if(!await Pe(Te)){He("Copy failed");return}He(ge.trimEnd()?"Copied selection":"Copied visible terminal")},st=ge=>{if(!u||!i)return;((p==null?void 0:p(Ae,ce,ge))??!1)||He("Terminal input failed")},Ze=ge=>{st(OC({ctrl:I,alt:M,shift:P},ge)),D(!1),E(!1),B(!1)},Ue=async()=>{if(h)return;x(!0),b("Loading older terminal output..."),fe.current=!0;const ge=await Se({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:u});if(x(!1),(ge==null?void 0:ge.success)===!1){fe.current=!1,b(`Older terminal output unavailable: ${ge.error}`);return}y(!0),Ee("Older terminal output loaded"),se(()=>{var je;(je=n.current)==null||je.bumpResize()})};l.useEffect(()=>{var je,Te;if(!ce)return;Ae&&((je=Ct.getState)==null?void 0:je.call(Ct,Ae))==="connected"&&Se();const ge=(Te=Ct.onStateChange)==null?void 0:Te.call(Ct,(Fe,Ge)=>{Fe!==Ae||Ge!=="connected"||Se()});return()=>{ge==null||ge()}},[Ae,ce,n]),l.useEffect(()=>{t&&at()},[t,re,n]),l.useEffect(()=>{var Fe,Ge;const ge=ie.current,je=(Ge=(Fe=ge==null?void 0:ge.ownerDocument)==null?void 0:Fe.defaultView)==null?void 0:Ge.ResizeObserver;if(!ge||!je)return;const Te=new je(dt=>{const Ve=dt[0];if(!Ve)return;const{width:ut,height:zt}=Ve.contentRect;H(Et=>{const ps=Math.round(ut),Zt=Math.round(zt);return Et.width===ps&&Et.height===Zt?Et:{width:ps,height:Zt}})});return Te.observe(ge),()=>Te.disconnect()},[]),l.useEffect(()=>{if(me.current)return;const ge=We();!Number.isFinite(ge)||ge<=0||N(je=>O.current?ge<je-Ie?ge:je:(O.current=!0,ge))},[L.height,L.width,_.height,_.width]),l.useEffect(()=>{et&&$e()},[et,Le,J]),l.useEffect(()=>{var Te;const ge=Y.current;if(Y.current=i,!i)return;ge||y(!1),Z.current&&(Z.current=!1,rt());const je=he.current;je&&(he.current=null,xe(je.text,je.seq,je.cols,je.rows,{force:!!je.force})),Ae&&ce&&((Te=Ct.getState)==null?void 0:Te.call(Ct,Ae))==="connected"&&Se(),ve.current&&V.current===null&&Me(),se(()=>{var Fe;(Fe=n.current)==null||Fe.bumpResize()})},[Ae,i,ce]),l.useEffect(()=>()=>{V.current!==null&&te(),ue(),ye()},[]),l.useEffect(()=>{const ge=Fe=>{var dt;const Ge=Fe.detail;Ge!=null&&Ge.sessionId&&Ge.sessionId!==ce||u&&((dt=n.current)==null||dt.bumpResize())},je=le(),Te=je===window?[window]:[window,je];for(const Fe of Te)Fe.addEventListener("adhdev:fit-cli-terminal",ge);return()=>{for(const Fe of Te)Fe.removeEventListener("adhdev:fit-cli-terminal",ge)}},[u,ce,n]);const nt=u&&w&&!v&&($.atTop||!$.canScroll)||h||!!S;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:ie,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[nt&&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:()=>{Ue()},disabled:!ce||h,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:d(h?"terminal.loadingOlder":"terminal.loadOlderOutput")}),S&&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:S})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[z&&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:z}),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:()=>W(ge=>!ge),title:"Spec debug — inspect current state, sections, and transition history",children:d("terminal.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:()=>{Je()},disabled:!u,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:d("terminal.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:()=>A(ge=>!ge),disabled:!u,"aria-label":d(T?"terminal.closeControlKeys":"terminal.openControlKeys"),"aria-expanded":T,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),T&&s.jsxs("div",{id:"terminal-control-keys-popover",role:"dialog","aria-label":d("terminal.openControlKeys"),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:()=>A(!1),"aria-label":d("terminal.closeControlKeys"),children:"×"})]}),s.jsx("div",{className:"mb-2 grid grid-cols-3 gap-1.5",children:[["Ctrl",I,D],["Alt",M,E],["Shift",P,B]].map(([ge,je,Te])=>s.jsx("button",{type:"button","aria-pressed":je,className:`h-9 rounded-lg border text-[12px] font-semibold transition-colors ${je?"border-sky-400/50 bg-sky-400/25 text-white":"border-white/10 bg-white/[0.06] hover:bg-white/[0.12]"}`,onClick:()=>Te(Fe=>!Fe),children:ge},ge))}),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:()=>Ze("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:()=>Ze("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:()=>Ze("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:()=>Ze("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:()=>Ze("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:()=>Ze("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:()=>Ze("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:()=>st(""),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:()=>Ze("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:()=>Ze("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:()=>{me.current=!0,N(ge=>{const je=Math.max(Xe,Number((ge-.1).toFixed(2)));return je>Xe&&$e(),je})},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:()=>{me.current=!0,N(ge=>{const je=Math.min(Ne,Number((ge+.1).toFixed(2)));return je>Xe&&$e(),je})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:Ce,className:et?"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:J>0?`${J}px`:"100%",height:Le>0?`${Le}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:L.width>0?`${L.width}px`:"100%",height:L.height>0?`${L.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:j},children:s.jsx(Up,{ref:n,readOnly:!u||!i,sizingMode:"measured",onViewportMetrics:F,onScrollMetrics:K,onInput:ge=>{!u||(p==null||p(Ae,ce,ge))}})})})}),!u&&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:g})]}),s.jsx(mm,{contextKey:e.tabKey,panelLabel:kt(e),isSending:r,isBusy:!!be,statusMessage:we,inlineStatusMessage:_e,onSend:async ge=>be?!1:a(ge),isActive:c&&i,showControlsToggle:!1,animateVisibility:!1}),R&&s.jsx(ij,{activeConv:e,onClose:()=>W(!1)})]})}const cj={accent:{track:"--accent-primary",head:"--accent-primary-light"},success:{track:"--status-online",head:"--status-online"},muted:{track:"--text-muted",head:"--text-muted"}};function ls({size:e=28,thickness:t=2.5,color:n="accent",className:a,label:r}){const o=cj[n],i={width:e,height:e,border:`${t}px solid color-mix(in srgb, var(${o.track}) 20%, transparent)`,borderTopColor:`var(${o.head})`};return s.jsx("span",{className:Pt("block shrink-0 rounded-full animate-spin",a),style:i,role:r?"status":void 0,"aria-label":r,"aria-hidden":r?void 0:!0})}const dj=5e3,uj=12e3,pj=15e3;function mj(e){return e==="disconnected"||e==="reconnecting"}function hj({wsStatus:e,showReconnected:t,loginUrl:n,onReconnect:a,reconnectDelayMs:r=dj,reconnectActionDelayMs:o=uj}){const{t:i}=ke(),c=mj(e),[d,p]=l.useState(()=>!c||r<=0),[u,m]=l.useState(()=>!c||o<=0),f=l.useRef(!1),[g,k]=l.useState(!1);l.useEffect(()=>{if(!c){p(!1);return}if(f.current=!1,r<=0){f.current=!0,p(!0);return}p(!1);const T=setTimeout(()=>{f.current=!0,p(!0)},r);return()=>clearTimeout(T)},[r,c]),l.useEffect(()=>{if(!c){m(!1);return}if(o<=0){m(!0);return}m(!1);const T=setTimeout(()=>{m(!0)},o);return()=>clearTimeout(T)},[o,c]),l.useEffect(()=>{e!=="reconnecting"&&k(!1)},[e]),l.useEffect(()=>{if(!g)return;const T=setTimeout(()=>k(!1),pj);return()=>clearTimeout(T)},[g]);const h=()=>{k(!0),a==null||a()},x=c?d:e==="offline"||e==="auth_failed",S=!!(a&&e!=="auth_failed"&&(!c||u)),b=l.useMemo(()=>!t||e!=="connected"?!1:r<=0||f.current,[r,t,e]),w=e==="auth_failed"?"red":e==="offline"?"orange":"accent",C={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))"},v={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)"},y={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},j="fixed left-1/2 top-[calc(env(safe-area-inset-top,0px)+64px)] sm:top-[calc(env(safe-area-inset-top,0px)+16px)] z-[var(--z-toast)] flex items-center justify-center pointer-events-none",N={transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[x&&s.jsx("div",{className:j,style:N,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:C[w],border:v[w],color:y[w]},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"&&i("connection.networkOffline"),e==="disconnected"&&i("connection.reconnecting"),e==="reconnecting"&&i("connection.reconnecting"),e==="auth_failed"&&(n?s.jsxs(s.Fragment,{children:[i("connection.sessionExpired")," ",s.jsx("a",{href:n,className:"text-inherit underline",children:i("connection.logInAgain")})]}):i("connection.connectionFailed"))]}),S&&s.jsxs("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 inline-flex items-center gap-1.5",onClick:h,disabled:e==="offline"||g,children:[g&&s.jsx(ls,{size:11,thickness:2,color:"muted"}),i(g?"connection.reconnecting":"connection.reconnectNow")]})]})}),b&&s.jsx("div",{className:j,style:N,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"}),i("connection.connected")]})})]})}function eh({mode:e,onChange:t,compact:n=!1}){const{t:a}=ke("common"),r=n?14:15;return s.jsx("button",{type:"button",onClick:()=>t(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:a(e==="chat"?"cliView.switchToTerminal":"cliView.switchToChat"),children:e==="chat"?s.jsx(_l,{size:r}):s.jsx(Ds,{size:r})})}function fj(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 gj(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 bj(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 Gr({git:e,className:t="",compact:n=!1}){const a=fj(e),r=gj(e);if(!a||!r)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 ${bj(r)} ${t}`.trim(),title:o.join(" · ")||a,"data-git-tone":r,children:[s.jsx("span",{"aria-hidden":"true",children:"⑂"}),s.jsx("span",{className:"truncate",children:a})]})}function xj({wsStatus:e,isConnected:t,daemonCount:n,p2pStates:a={},usesP2P:r=!0}){if(e!=="connected")return{tone:"disconnected",titleKey:"connection.disconnected",subtitleKey:null};if(n>0&&!r)return t?{tone:"connected",titleKey:"connection.connected",subtitleKey:null}:{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:null};const i=Object.values(a).filter(c=>c==="connected").length;return n>0?i>=n?{tone:"connected",titleKey:"connection.connected",subtitleKey:null}:{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:"connection.machinesConnectedCount",subtitleParams:{connected:i,total:n}}:t?{tone:"connected",titleKey:"connection.connected",subtitleKey:null}:{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:null}}function Ld({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Rd({notification:e,shortcutIndex:t,onOpen:n,onMarkRead:a,onMarkUnread:r,onDelete:o}){const{t:i}=ke(),c=qa(e.updatedAt),d=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${d?"is-attention":""}`.trim(),children:[s.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:n,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"?i("notification.actionNeeded"):i("notification.taskComplete"),c].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:[d?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:p=>{p.stopPropagation(),a()},children:i("notification.markRead")}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:p=>{p.stopPropagation(),r()},children:i("notification.markUnread")}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:p=>{p.stopPropagation(),o()},children:i("notification.delete")})]})]})}function vj({activeConv:e,wsStatus:t,isConnected:n,conversations:a,onOpenHistory:r,onOpenRemote:o,onStopCli:i,activeCliViewMode:c,onSetCliViewMode:d,onHideConversation:p,hiddenConversations:u=[],onShowConversation:m,onShowAllHidden:f,onResetPanelsToMain:g,inboxOpen:k,onInboxOpenChange:h,hiddenOpen:x,onHiddenOpenChange:S,onOpenNewSession:b,onOpenDashboardGuide:w,guideNudgeVisible:C=!1,actionShortcuts:v,notifications:y,notificationUnreadCount:j,onOpenNotification:N,onMarkNotificationRead:T,onMarkNotificationUnread:A,onDeleteNotification:I,onOpenGitDialog:D,onOpenMeshGraph:M}){var pe;const{t:E}=ke(),{ides:P,p2pStates:B={},usesP2P:R=!0}=Ss(),W=!!e&&bt(e)&&!ht(e),_=!!e&&ht(e),H=!!(e!=null&&e.daemonId)&&!!((pe=e==null?void 0:e.coordinator)!=null&&pe.meshId),L=c||(e?km(e)?"terminal":"chat":null),[F,$]=l.useState(!1),[K,z]=l.useState(!1),ne=l.useRef(null),ie=l.useRef(null),Ce=l.useRef(null),me=P.filter(le=>le.type==="adhdev-daemon"),O=xj({wsStatus:t,isConnected:n,daemonCount:me.length,p2pStates:B,usesP2P:R}),Y=E(O.titleKey),X=O.subtitleKey?E(O.subtitleKey,O.subtitleParams):null,Q=O.tone==="connected"?"#22c55e":O.tone==="limited"?"#eab308":"#ef4444",ve=O.tone==="connected"?"0 0 4px #22c55e80":O.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",he=l.useMemo(()=>y.filter(le=>!le.readAt),[y]),Z=l.useMemo(()=>y.filter(le=>!!le.readAt),[y]),fe=l.useMemo(()=>he.slice(0,9),[he]),V=j;l.useEffect(()=>{if(!k)return;const le=se=>{var te;(te=ie.current)!=null&&te.contains(se.target)||h(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[k,h]),l.useEffect(()=>{if(!x)return;const le=se=>{var te;(te=Ce.current)!=null&&te.contains(se.target)||S(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[x,S]),l.useEffect(()=>{if(!x&&!k)return;const le=se=>{if(!se.altKey)return;const te=se.code.match(/^Digit([1-9])$/);if(!te)return;const ue=Number(te[1])-1,ye=x?u[ue]:void 0,Me=k?fe[ue]:void 0;if(!(!ye&&!Me)){if(se.preventDefault(),se.stopPropagation(),ye){m==null||m(ye),S(!1);return}Me&&(N(Me),h(!1))}};return window.addEventListener("keydown",le,!0),()=>window.removeEventListener("keydown",le,!0)},[u,x,k,fe,S,h,N,m]),l.useEffect(()=>{const le=u.length;if(ne.current===null){ne.current=le;return}le>ne.current&&z(!0),ne.current=le},[u.length]);const q=()=>z(!1),ee=le=>{if(!le)return;const se=a.find(te=>te.tabKey===le);se&&(p==null||p(se))};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(Ds,{size:18}),s.jsx("span",{className:"header-title-desktop",children:E("dashboard.header.title")}),s.jsx("span",{className:"header-title-mobile",children:e?kt(e):E("dashboard.header.title")}),s.jsx("span",{title:Y,"aria-label":Y,className:"header-title-status-dot",style:{background:Q,boxShadow:ve}}),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:Q,boxShadow:ve}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[X&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",X]}),b&&s.jsx("button",{type:"button",onClick:b,className:"btn btn-secondary btn-sm ml-2",title:`${E("paneGroup.newSession")}${v!=null&&v.openNewSession?` (${v.openNewSession})`:""}`,"aria-label":E("paneGroup.newSession"),children:s.jsx(Hl,{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:E("dashboard.header.guide"),"aria-label":E("dashboard.header.guideOpen"),children:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),C&&s.jsx("span",{children:E("dashboard.header.guideShort")})]}),e&&(W||_||!ht(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:sa(e)||kt(e),children:kt(e)}),D&&e.git&&e.daemonId&&e.workspacePath?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:E("dashboard.header.openGitStatus"),onClick:()=>D(e.daemonId,e.workspacePath),children:s.jsx(Gr,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(Gr,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),H&&M&&s.jsxs("button",{type:"button",onClick:()=>M(e),className:"btn btn-secondary btn-sm dashboard-header-mesh-button",title:E("dashboard.header.openMeshGraph"),children:[s.jsx(cs,{size:14}),s.jsx("span",{className:"hidden lg:inline",children:E("dashboard.header.meshGraph")})]}),(W||_)&&i&&s.jsxs(s.Fragment,{children:[W&&d&&L&&s.jsx(eh,{mode:L,onChange:d,compact:!0}),s.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:E(_?"dashboard.header.stopAcpSession":"dashboard.header.stopCliProcess"),style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(Dt,{size:14})})]}),!ht(e)&&s.jsx("button",{onClick:()=>r(e),className:"btn btn-secondary btn-sm",title:E("dashboard.header.chatHistory"),children:s.jsx(Rl,{size:14})}),!W&&!ht(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:E("dashboard.header.remoteControl"),children:s.jsx(us,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:ie,children:[s.jsxs("div",{className:`dashboard-header-hidden${F?" is-drop-target":""}${K?" hidden-spawn-flash":""}${(u??[]).some(_a)?" hidden-generating-spin":""}`,onAnimationEnd:q,ref:Ce,onDragEnter:le=>{le.dataTransfer.types.includes("text/tab-key")&&(le.preventDefault(),$(!0))},onDragOver:le=>{le.dataTransfer.types.includes("text/tab-key")&&(le.preventDefault(),le.dataTransfer.dropEffect="move",$(!0))},onDragLeave:le=>{le.currentTarget.contains(le.relatedTarget)||$(!1)},onDrop:le=>{const se=le.dataTransfer.getData("text/tab-key");le.preventDefault(),$(!1),ee(se)},children:[s.jsxs("button",{type:"button",onClick:()=>S(!x),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`${E("dashboard.hidden.title")}${v!=null&&v.toggleHiddenTabs?` (${v.toggleHiddenTabs})`:""}. ${E("dashboard.hidden.dragHint")}`,children:[s.jsx(po,{size:16}),u.length>0&&s.jsx("span",{className:`dashboard-header-hidden-badge${K?" hidden-badge-pop":""}`,children:u.length})]}),x&&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:E("dashboard.hidden.title")}),s.jsx(Ld,{value:v==null?void 0:v.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[g&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:g,children:E("dashboard.hidden.resetPanels")}),u.length>0&&f&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{f(),S(!1)},children:E("dashboard.hidden.restoreAll")})]})]}),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:E("dashboard.hidden.hideCurrentTab")}),s.jsx(Ld,{value:v==null?void 0:v.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:kt(e)})]}),u.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(le=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{m==null||m(le),S(!1)},children:[s.jsxs("span",{className:"dashboard-header-inbox-item-title",children:[_a(le)&&s.jsx(ls,{size:12,thickness:2,color:"success",label:E("dashboard.header.generating")}),kt(le)]}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(le)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(le)+1]}):null,sa(le)]})]},le.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:E("dashboard.hidden.empty")})]})]}),s.jsxs("button",{type:"button",onClick:()=>h(!k),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:E("dashboard.header.activityInbox"),children:[s.jsx(ia,{size:16}),V>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:V})]}),k&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[he.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:E("dashboard.inbox.unread")}),he.map(le=>s.jsx(Rd,{notification:le,shortcutIndex:fe.indexOf(le)>=0?fe.indexOf(le)+1:void 0,onOpen:()=>N(le),onMarkRead:()=>T(le.id),onMarkUnread:()=>A(le.id),onDelete:()=>I(le.id)},le.id))]}),Z.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:E("dashboard.inbox.read")}),Z.map(le=>s.jsx(Rd,{notification:le,onOpen:()=>N(le),onMarkRead:()=>T(le.id),onMarkUnread:()=>A(le.id),onDelete:()=>I(le.id)},le.id))]}),y.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:E("dashboard.inbox.empty")})]})]})]})]})}function qt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function yj(e,t){return String(e||"")!==String(t||"")}function wj(e,t={}){const n=String(t.textQuery||"").trim().toLowerCase(),a=String(t.workspaceQuery||"").trim().toLowerCase(),r=String(t.modelQuery||"").trim().toLowerCase(),o=!!t.resumableOnly;return!n&&!a&&!r&&!o?e:e.filter(i=>!(o&&!i.canResume||n&&![i.title,i.preview].map(d=>String(d||"").toLowerCase()).join(`
|
|
52
52
|
`).includes(n)||a&&!String(i.workspace||"").toLowerCase().includes(a)||r&&!im(i.summaryMetadata).map(d=>d.toLowerCase()).join(`
|
|
53
|
-
`).includes(r)))}function kj(e,t="recent"){const n=e.slice();return n.sort((a,r)=>{if(t==="oldest")return(Number(a.lastMessageAt)||0)-(Number(r.lastMessageAt)||0);if(t==="messages"){const o=(Number(r.messageCount)||0)-(Number(a.messageCount)||0);if(o!==0)return o}return(Number(r.lastMessageAt)||0)-(Number(a.lastMessageAt)||0)}),n}function th(e,t={}){return kj(wj(e,t),t.sortMode||"recent")}function rl(e,t){return typeof e=="function"?e(t??!1?"launch.resumeSavedHistory":"launch.startFresh"):e?"Resume saved history":"Start fresh"}function sh(e,t){return typeof e=="function"?e(t??!1?"launch.resumingSavedHistory":"launch.startingFresh"):e?"Resuming saved history…":"Starting fresh…"}function Sj(e){return e?e("launch.startFresh"):"Start fresh"}function Cj(e){return e?e("launch.hostedRuntimeRecoveryDescription"):"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function jj(e){return e?e("launch.openSavedHistory"):"Open saved history"}function Nj(e){return e?e("launch.savedHistoryTitle"):"Saved History"}function sc(e){return e?e("launch.savedHistoryHelper"):"Use saved history when you want continuity in the same provider conversation."}function Aj(e){return e?e("launch.savedHistoryEmpty"):"No saved history found yet."}function Tj(e){return e?e("launch.refreshSavedHistory"):"Refresh saved history"}function Mj(e){return e?e("launch.refreshingSavedHistory"):"Refreshing saved history…"}function qr(e,t,n){if(typeof e=="function"){const o=t,i=n;return o==="start-fresh"?e("launch.startFreshWith",{label:i}):e("launch.restart",{label:i})}const a=e,r=t;return a==="start-fresh"?`Start fresh with ${r}?`:`Restart ${r}?`}function zr(e,t){if(typeof e=="function"){const a=t;return e(a==="start-fresh"?"launch.startFreshReview":a==="restart-ide"?"launch.restartIdeReview":"launch.restartStoppedReview")}const n=e;return n==="start-fresh"?"Review the provider and target folder before starting fresh.":n==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function Kr(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartFresh":"launch.confirmRestart"):e==="start-fresh"?"Start fresh":"Restart"}function Vr(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartingFresh":"launch.confirmRestarting"):e==="start-fresh"?"Starting fresh…":"Restarting…"}function nh(e,t){return typeof e=="function"?e("launch.resumeWith",{label:t}):`Resume saved history with ${e}?`}function ah(e){return e?e("launch.resumeReview"):"Review or change the target workspace before resuming saved history."}function Ed(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 rh({activeConv:e,ides:t,isCreatingChat:n,isRefreshingHistory:a,savedSessions:r=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:c,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:p,onClose:u,onNewChat:m,onSwitchSession:f,onRefreshHistory:g,onResumeSavedSession:k}){var E;const{t:h}=ke("common"),x=t.find(P=>P.id===e.routeId),S=(x==null?void 0:x.chats)||[],b=(E=x==null?void 0:x.activeChat)==null?void 0:E.id,w=bt(e)&&!ht(e),[C,v]=l.useState(()=>qt()),[y,j]=l.useState(null),N=c||C,T=String(d||"").trim(),A=P=>{if(p){p(P);return}v(P)},I=l.useMemo(()=>r.map(P=>{const B=String(P.workspace||"").trim();return P.canResume||B||!T?P:{...P,workspace:T,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[T,r]),D=l.useMemo(()=>th(I,{textQuery:N.textQuery,workspaceQuery:N.workspaceQuery,modelQuery:N.modelQuery,resumableOnly:N.resumableOnly,sortMode:N.sortMode}),[I,N.modelQuery,N.resumableOnly,N.sortMode,N.textQuery,N.workspaceQuery]),M=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:w?Nj(h):h("historyModal.chatHistory")}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:KC(e)}),w&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:sc(h)})]}),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(Dt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!w&&s.jsx("button",{onClick:m,disabled:n,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:h(n?"historyModal.creating":"historyModal.startNewChat")}),w?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:N.textQuery,onChange:P=>A({...N,textQuery:P.target.value}),placeholder:h("historyModal.searchPlaceholder"),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:N.workspaceQuery,onChange:P=>A({...N,workspaceQuery:P.target.value}),placeholder:h("historyModal.filterWorkspace"),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:N.modelQuery,onChange:P=>A({...N,modelQuery:P.target.value}),placeholder:h("historyModal.filterModel"),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:N.sortMode,onChange:P=>A({...N,sortMode:P.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:h("historyModal.sortRecent")}),s.jsx("option",{value:"oldest",children:h("historyModal.sortOldest")}),s.jsx("option",{value:"messages",children:h("historyModal.sortMessages")})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:N.resumableOnly,onChange:P=>A({...N,resumableOnly:P.target.checked})}),h("historyModal.resumeReadyOnly")]})]}),D.map(P=>{const B=e.providerSessionId===P.providerSessionId,R=B||!P.canResume||!!i,W=P.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{R||!k||j({kind:"saved",session:P})},disabled:R,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${B?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${R?"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 ${B?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:P.title||h("historyModal.untitledSession")}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:P.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Ed(P.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:P.preview||h("historyModal.noSavedPreview")}),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:[P.workspace||h("historyModal.workspaceUnknown"),W?h("historyModal.selectedWorkspaceSuffix"):"",Tn(P.summaryMetadata)?` · ${Tn(P.summaryMetadata)}`:"",P.messageCount>0?` · ${h("historyModal.msgCount",{count:P.messageCount})}`:""]}),s.jsx("div",{className:"shrink-0",children:B?h("historyModal.statusActive"):P.canResume?W?h("historyModal.statusResumeSelectedWorkspace"):i===P.providerSessionId?h("historyModal.statusResuming"):h("historyModal.statusResume"):h("historyModal.statusMissingWorkspace")})]})]},P.id)})]}):S.map(P=>s.jsxs("div",{onClick:()=>{P.id!==b&&j({kind:"chat",id:P.id,title:P.title||h("historyModal.untitledSession")})},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${b===P.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 ${b===P.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:P.title||h("historyModal.untitledSession")}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[P.id.substring(0,12),"..."]}),b===P.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:h("historyModal.statusActive")})]})]},P.id)),(w&&!o&&D.length===0||!w&&S.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(bb,{size:32})}),s.jsx("div",{className:"text-[13px]",children:w?r.length>0?h("historyModal.noMatchingHistory"):Aj(h):h("historyModal.noRecentChats")})]}),w&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:Mj(h)})})]}),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:g,disabled:a||o,className:"btn btn-secondary btn-sm rounded-[10px]",children:a||o?h("historyModal.refreshing"):s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(uo,{size:13})," ",w?Tj(h):h("historyModal.refreshHistory")]})})})]}),y&&s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center p-4",children:[s.jsx("div",{onClick:()=>j(null),className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true",className:"card fade-in relative w-full sm:w-[min(92vw,420px)] max-w-[420px] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-bg-primary",children:[s.jsx("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:h("historyModal.confirmSwitchTitle")}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:h("historyModal.confirmSwitchDescription",{target:y.kind==="chat"?y.title:y.session.title||h("historyModal.untitledSession")})}),y.kind==="saved"&&s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted font-mono truncate",children:[y.session.workspace||h("historyModal.workspaceUnknown"),y.session.lastMessageAt?` · ${Ed(y.session.lastMessageAt)}`:""]})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[s.jsx("button",{onClick:()=>{const P=y;j(null),P.kind==="chat"?(f(e.routeId,P.id),u()):k&&k(P.session)},className:"btn btn-primary w-full justify-center min-h-[42px]",children:h("historyModal.confirmSwitchAction")}),s.jsx("button",{onClick:()=>j(null),className:"btn btn-secondary w-full justify-center min-h-[42px]",children:h("common.cancel")})]})]})]})]});return typeof document>"u"?M:qs.createPortal(M,document.body)}const _d={success:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",labelKey:"toast.label.success"},warning:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",labelKey:"toast.label.warning"},info:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",labelKey:"toast.label.info"}};function oh({toasts:e,onDismiss:t,onClickToast:n}){const{t:a}=ke();return s.jsx("div",{className:"fixed right-4 top-[calc(env(safe-area-inset-top,0px)+64px)] z-[var(--z-toast)] flex flex-col gap-2 pointer-events-none sm:top-[calc(env(safe-area-inset-top,0px)+16px)]",children:e.map(r=>{const o=_d[r.type]||_d.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 i;(i=r.actions)!=null&&i.length||n&&n(r)},children:[s.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${o.accent}, color-mix(in srgb, ${o.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:i=>{i.stopPropagation(),t(r.id)},"aria-label":a("toast.dismiss"),children:s.jsx(Dt,{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:o.chipBg,color:o.chipText,border:`1px solid color-mix(in srgb, ${o.accent} 22%, transparent)`},children:a(o.labelKey)})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:r.message}),r.actions&&r.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:r.actions.map((i,c)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.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)"}:i.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:d=>{d.stopPropagation(),i.onClick(),t(r.id)},children:i.label},c))})]})]},r.id)})})}const Pj=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Dj(e){const t=e.workspace||"";if(!t)return"";const n=t.split(/[/\\]/).filter(Boolean);return n.length>0?n[n.length-1]:t}function Ij(e,t){return ih(e)||t}function ih(e){var r,o,i;const t=(o=(r=e.summaryMetadata)==null?void 0:r.items)==null?void 0:o.find(c=>(c==null?void 0:c.id)==="model"),n=((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim();if(n)return n;const a=(i=e.controlValues)==null?void 0:i.model;return typeof a=="string"&&a.trim()?a.trim():""}function Lj(e){return ih(e)||void 0}function Rj(e){return e.sessionId||e.instanceId||e.agentType}function lh(e=[]){const t={};for(const n of e)n.type==="adhdev-daemon"&&(t[n.id]=ds(n,{fallbackId:n.id}));return t}function ch(e,t={}){var a;const n=e.daemonId||((a=e.id)==null?void 0:a.split(":")[0])||e.id;return{machineName:U0(e,t.machineNames),connectionState:t.connectionStates?t.connectionStates[n]||t.defaultConnectionState||"new":t.defaultConnectionState}}function nc(e,t={}){return Ej(e,ch(e,t))}function Ej(e,t={}){var f,g,k,h,x,S,b,w,C;const n=[],a=t.machineName,r=t.connectionState,o=Dj(e),i=e.workspace||"",c=Y0(e.type,{agentName:e.cliName}),d=bt(e)||ht(e)?c:Ot(e.type),p=Ij(e,d),u=Array.isArray(e.childSessions)?e.childSessions.map(v=>{var y,j,N;return{sessionId:v.id,instanceId:v.id,providerSessionId:v.providerSessionId,activeChatId:(y=v.activeChat)==null?void 0:y.id,transport:v.transport,sessionCapabilities:v.capabilities,agentType:v.providerType,agentName:v.providerName||Ot(v.providerType),model:Lj(v),status:v.status,title:v.title,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,messages:((j=v.activeChat)==null?void 0:j.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=Pj(e);if(m){const v=e.sessionId||e.instanceId,y=(f=e.settings)==null?void 0:f.meshCoordinatorFor,j=((g=e.settings)==null?void 0:g.meshNodeFor)||!((k=e.settings)!=null&&k.meshCoordinatorFor)&&((h=e.settings)==null?void 0:h.launchedByCoordinator),N=y?" (Coordinator)":j?" (Mesh Node)":"",T=c+N,A=(x=e.activeChat)==null?void 0:x.activeModal,I=A&&Array.isArray(A.buttons)&&A.buttons.length>0,D=Q0(e.activeChat,[{status:e.status,activeModal:(S=e.activeChat)==null?void 0:S.activeModal}],e.agents||[]),M=e.activeChat||{title:"",messages:[]};let E=M.title&&String(M.title).trim()?String(M.title).trim():"";const P=(b=e.activeChat)==null?void 0:b.id,B=e.chats;if(P&&Array.isArray(B)&&B.length>0){const K=B.find(z=>z.id===P||z.id&&String(z.id)===String(P));K!=null&&K.title&&String(K.title).trim()&&(E=String(K.title).trim())}const R=(bt(e)||ht(e),e.type),W=(bt(e)||ht(e))&&ad(E,T,R)?"":E,_=M.messages||[],H=typeof P=="string"?P.trim():"",L=(bt(e)||ht(e))&&H===String(e.type||"").trim(),F=H&&!L?H:e.providerSessionId,$=e.coordinator||(typeof((w=e.settings)==null?void 0:w.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:v,providerSessionId:e.providerSessionId,historySessionId:F,nativeSessionId:v,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:bt(e)&&e.mode||"chat",agentName:T,agentType:R,status:D,title:W,messages:_,resume:e.resume,hostIdeType:!bt(e)&&!ht(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||W||(bt(e)?e.mode==="chat"?T:`Terminal${N}`:T),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:I?A.buttons:void 0,modalMessage:I?A.message:void 0,streamSource:"native",tabKey:Wo(v,e.id),machineName:a,connectionState:r,settings:e.settings,coordinator:$,messageInput:e.messageInput})}if(m&&(bt(e)||ht(e)))return n;for(const v of u){const y=v.activeModal&&Array.isArray(v.activeModal.buttons)&&v.activeModal.buttons.length>0,j=J0(v),N=Rj(v),T=`${e.id}:${N}`,A=v.title&&String(v.title).trim()||"",I=ad(A,v.agentName,v.agentType)?"":A,D=v.messages||[];if(!(v.transport==="cdp-webview"||!!v.sessionId||!!v.providerSessionId||D.length>0||y||!!I||!["idle","panel_hidden","disconnected","not_monitored"].includes(j)))continue;const E=v.coordinator||(typeof((C=v.settings)==null?void 0:C.meshCoordinatorFor)=="string"&&v.settings.meshCoordinatorFor?{meshId:v.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.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:j,title:I,messages:D,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:v.git||e.git,displayPrimary:o||I||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:y?v.activeModal.buttons:void 0,modalMessage:y?v.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Wo(v.sessionId||v.instanceId,T),machineName:a,connectionState:r,settings:v.settings,coordinator:E,messageInput:v.messageInput})}return n.length===0&&n.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:Wo(e.sessionId||e.instanceId,e.id),connectionState:r,settings:e.settings,messageInput:e.messageInput}),n}function dh(e){return String(e.type||e.id||"").trim()}function Yr(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()).map(t=>t.trim()):[]}function _j(e,t){const n=(t||"").trim();if(!n)return[];const a=(e||[]).find(r=>r.type===n);return Yr(a==null?void 0:a.modelOptions)}function Hj(e,t){const n=(t||"").trim();if(!n)return[];const a=(e||[]).find(r=>r.type===n);return Yr(a==null?void 0:a.thinkingLevelOptions)}function uh(e){const t=new Map;for(const n of e||[])n!=null&&n.type&&t.set(n.type,{models:Yr(n.modelOptions),thinking:Yr(n.thinkingLevelOptions)});return t}function $j(e){var t;return e.category!=="cli"||!dh(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 ln(e){var a;const t=new Set,n=[];for(const r of e||[]){if(!$j(r))continue;const o=dh(r);if(!o||t.has(o))continue;t.add(o);const i=String(r.displayName||r.name||o),c=r.detectedPath||((a=r.lastDetection)==null?void 0:a.path)||null;n.push({type:o,label:i,icon:r.icon,statusLabel:c?`Detected at ${c}`:"Detected on this machine",detectedPath:c,...Array.isArray(r.modelOptions)&&r.modelOptions.length?{modelOptions:r.modelOptions}:{},...Array.isArray(r.thinkingLevelOptions)&&r.thinkingLevelOptions.length?{thinkingLevelOptions:r.thinkingLevelOptions}:{}})}return n}function Va(e){const t=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],n=new Set,a=[];for(const r of t){const o=typeof r=="string"?r.trim():"";!o||n.has(o)||(n.add(o),a.push(o))}return a}function Pn(e){return e.map(t=>t.type)}function Fj(e,t){const n=Va(e),a=t.trim();return!a||n.includes(a)?n:[...n,a]}function Bj(e,t){return Va(e).filter(n=>n!==t)}function Hd(e,t,n){const a=Va(e),r=a.indexOf(t);if(r<0)return a;const o=a.filter(c=>c!==t);if(n==="top")return[t,...o];if(n==="bottom")return[...o,t];const i=n==="up"?Math.max(0,r-1):Math.min(o.length,r+1);return o.splice(i,0,t),o}const Wj={"claude-cli":{monogram:"CL",hue:"#D97757"},"codex-cli":{monogram:"CX",hue:"#10A37F"},"gemini-cli":{monogram:"GM",hue:"#4285F4"},"kimi-cli":{monogram:"KM",hue:"#6366F1"},"antigravity-cli":{monogram:"AG",hue:"#8B5CF6"},"cursor-cli":{monogram:"CU",hue:"#64748B"},"opencode-cli":{monogram:"OC",hue:"#CA8A04"},"hermes-cli":{monogram:"HM",hue:"#14B8A6"},"grok-cli":{monogram:"GK",hue:"#475569"},antigravity:{monogram:"AG",hue:"#8B5CF6"},cursor:{monogram:"CU",hue:"#64748B"},kiro:{monogram:"KI",hue:"#F59E0B"},pearai:{monogram:"PA",hue:"#22C55E"},trae:{monogram:"TR",hue:"#EF4444"},vscode:{monogram:"VS",hue:"#3B82F6"},vscodium:{monogram:"VC",hue:"#2DD4BF"},windsurf:{monogram:"WS",hue:"#0EA5E9"},cline:{monogram:"CN",hue:"#0284C7"},"roo-code":{monogram:"RC",hue:"#F97316"}},$d=["#0EA5E9","#8B5CF6","#10B981","#F59E0B","#EF4444","#14B8A6","#6366F1","#EC4899","#84CC16","#F97316","#06B6D4","#A855F7"];function Oj(e){let t=0;for(let n=0;n<e.length;n+=1)t=(t<<5)-t+e.charCodeAt(n)|0;return Math.abs(t)}function Uj(e){const t=e.replace(/[-_./]+/g," ").split(/\s+/).map(n=>n.trim()).filter(Boolean);return t.length===0?"?":t.length===1?t[0].slice(0,2).toUpperCase():(t[0][0]+t[1][0]).toUpperCase()}function Ya({type:e,label:t,size:n=16,className:a}){const r=(e||"").trim().toLowerCase(),o=(t==null?void 0:t.trim())||r;if(!o)return s.jsx(Tb,{size:n,className:a});const i=Wj[r],c=(i==null?void 0:i.monogram)??Uj((t==null?void 0:t.trim())||r.replace(/-cli$/,"")),d=(i==null?void 0:i.hue)??$d[Oj(r||o)%$d.length];return s.jsx("span",{"aria-hidden":!0,className:`inline-flex shrink-0 select-none items-center justify-center font-semibold ${a??""}`,style:{width:n,height:n,borderRadius:Math.max(4,Math.round(n*.3)),backgroundColor:`${d}21`,border:`1px solid ${d}4D`,color:d,fontSize:Math.max(7,Math.round(n*.42)),letterSpacing:"0.02em",lineHeight:1},children:c})}function Fd({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 Gj({value:e,availableProviders:t,onChange:n,disabled:a=!1,saveButton:r}){const{t:o}=ke("common"),[i,c]=l.useState(""),d=l.useMemo(()=>new Map(t.map(g=>[g.type,g])),[t]),p=l.useMemo(()=>Va(e),[e]),u=p.filter(g=>!d.has(g)).length,m=t.filter(g=>!p.includes(g.type)),f=()=>{i&&(n(Fj(p,i)),c(""))};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:p.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."}):p.map((g,k)=>{const h=d.get(g),x=!!h;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 ${x?"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:["#",k+1]}),s.jsx(Ya,{type:g,label:h==null?void 0:h.label,size:14}),s.jsx("span",{className:`font-mono text-[12px] ${x?"text-text-primary":"text-text-muted"}`,children:g}),x?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:o("settings.providerPriority.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:o("settings.providerPriority.notOnMachine")})]}),s.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:h?`${h.label} · ${h.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:a||k===0,title:"Move up",onClick:()=>n(Hd(p,g,"up")),children:s.jsx(Fd,{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:a||k===p.length-1,title:"Move down",onClick:()=>n(Hd(p,g,"down")),children:s.jsx(Fd,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:a,onClick:()=>n(Bj(p,g)),children:o("settings.providerPriority.remove")})]})]},g)})}),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:o("settings.providerPriority.addCliLabel")}),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:i,onChange:g=>c(g.target.value),disabled:a||m.length===0,children:[s.jsx("option",{value:"",children:m.length?"Select provider…":"No additional detected CLI providers"}),m.map(g=>s.jsxs("option",{value:g.type,children:[g.label," (",g.type,")"]},g.type))]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:a||!i,onClick:f,children:o("settings.providerPriority.addProvider")}),r]}),s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:["Launches use this order, top to bottom.",u>0?` ${u} provider${u===1?"":"s"} not detected here — kept in order, skipped until available.`:""]})]})}function qj(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 ph(e,t){const n=qj(e);return{daemonId:n.daemonId,payload:{...t,...n.targetSessionId&&!t.targetSessionId?{targetSessionId:n.targetSessionId}:{}}}}const mh=[{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:"🏄"}],hh=[{id:"antigravity-cli",name:"Antigravity CLI",icon:"🪐"},{id:"claude-cli",name:"Claude Code",icon:"🟠"},{id:"codex-cli",name:"Codex CLI",icon:"📦"},{id:"cursor-cli",name:"Cursor CLI",icon:"⚡"},{id:"grok-cli",name:"Grok",icon:"🛰️"},{id:"hermes-cli",name:"Hermes",icon:"⚕️"},{id:"kimi",name:"Kimi",icon:"🌙"},{id:"opencode",name:"OpenCode CLI",icon:"◆"}],fh=[{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:"🟠"}],zj=mh,Kj=hh,Vj=fh;function Yj({icon:e,title:t,subtitle:n,badge:a,actions:r,className:o}){return s.jsxs("div",{className:Pt("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,a&&s.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[a.count!==void 0?a.count:""," ",a.text]})]}),n&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:n})]}),r&&s.jsx("div",{className:"flex gap-2",children:r})]})}function Qa({icon:e,title:t,subtitle:n,badge:a,actions:r,widthClassName:o="max-w-6xl",contentClassName:i,children:c}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(Yj,{icon:e,title:t,subtitle:n,badge:a,actions:r}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Pt("mx-auto flex w-full flex-col gap-4",o,i),children:c})})]})}const ol="adhdev:themechange";function Qj(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function qn(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function zn(e){return e==="system"?Qj():e}function gh(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Tr(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(ol,{detail:{preference:e,theme:t}}))}function Jj(){const e=qn(),t=zn(e);gh(t),Tr(e,t)}function Ls(){const[e,t]=l.useState(qn),[n,a]=l.useState(()=>zn(qn()));l.useEffect(()=>{gh(n)},[n]),l.useEffect(()=>{const i=window.matchMedia("(prefers-color-scheme: light)"),c=d=>{if(e==="system"){const p=d.matches?"light":"dark";a(p),Tr("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:qn()),a(m==="dark"||m==="light"?m:zn(qn()))},c=d=>{if(d.key!=="theme")return;const p=qn(),u=zn(p);t(p),a(u)};return window.addEventListener(ol,i),window.addEventListener("storage",c),()=>{window.removeEventListener(ol,i),window.removeEventListener("storage",c)}},[]);const r=l.useCallback(i=>{const c=zn(i);t(i),a(c);try{localStorage.setItem("theme",i)}catch{}Tr(i,c)},[]),o=l.useCallback(()=>{t(i=>{const c=i==="dark"?"light":i==="light"?"system":"dark",d=zn(c);a(d);try{localStorage.setItem("theme",c)}catch{}return Tr(c,d),c})},[]);return{theme:n,preference:e,setPreference:r,cycleTheme:o,isDark:n==="dark"}}const Bd={dark:"Dark",light:"Light",system:"System"};function Xj({collapsed:e}){const{preference:t,cycleTheme:n}=Ls(),a=t==="dark"?s.jsx(Tp,{size:16}):t==="light"?s.jsx(Ap,{size:16}):s.jsx(Mp,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:n,title:`Theme: ${Bd[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:a}),!e&&s.jsx("span",{className:"text-xs",children:Bd[t]})]})}const il="adhdev:langchange";function Zj(){const e=wt.language;return Vn(e)?e:Jp()}function e1(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(il,{detail:{language:e}}))}function t1(){const[e,t]=l.useState(Zj);l.useEffect(()=>{const a=i=>{Vn(i)&&t(i)},r=i=>{const c=i.detail||{};Vn(c.language)&&t(c.language)},o=i=>{if(i.key!==qi)return;const c=i.newValue;Vn(c)&&c!==wt.language&&(wt.changeLanguage(c),zi(c))};return wt.on("languageChanged",a),window.addEventListener(il,r),window.addEventListener("storage",o),()=>{wt.off("languageChanged",a),window.removeEventListener(il,r),window.removeEventListener("storage",o)}},[]);const n=l.useCallback(a=>{if(Vn(a)){t(a);try{localStorage.setItem(qi,a)}catch{}wt.changeLanguage(a),zi(a),e1(a)}},[]);return{language:e,setLanguage:n}}function s1({trigger:e,viewport:t,menu:n,variant:a,gap:r=6,margin:o=8}){const i=e.top-o,c=t.height-e.bottom-o,d=a==="sidebar";let p=d;d&&i<n.height&&c>i&&(p=!1),!d&&c<n.height&&i>c&&(p=!0);const u=p?i:c,m=Math.max(80,Math.min(n.height,u));let f;p?f=e.top-r-m:f=e.bottom+r,f=Wd(f,o,Math.max(o,t.height-m-o));const g=Wd(e.left,o,Math.max(o,t.width-n.width-o));return{top:f,left:g,maxHeight:m}}function Wd(e,t,n){return Math.min(Math.max(e,t),n)}function n1({open:e}){return s.jsx("svg",{width:12,height:12,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:`lang-switch-caret${e?" open":""}`,children:s.jsx("polyline",{points:"6 9 12 15 18 9"})})}function a1({collapsed:e,variant:t="sidebar"}){const{language:n,setLanguage:a}=t1(),{t:r}=ke("common"),[o,i]=l.useState(!1),[c,d]=l.useState(0),p=l.useRef(null),u=l.useRef(null),m=l.useRef(null),f=l.useId(),[g,k]=l.useState(null),h=l.useCallback(()=>{const D=u.current;if(!D)return;const M=D.getBoundingClientRect(),E=m.current,P=Math.max((E==null?void 0:E.offsetWidth)??0,168),B=(E==null?void 0:E.scrollHeight)??un.length*36+12;k(s1({trigger:{top:M.top,left:M.left,right:M.right,bottom:M.bottom,width:M.width,height:M.height},viewport:{width:window.innerWidth,height:window.innerHeight},menu:{width:P,height:B},variant:t}))},[t]),x=Math.max(0,un.findIndex(D=>D.code===n)),S=un[x]??un[0],b=r("language.label",{defaultValue:"Language"}),w=r("language.select",{defaultValue:"Select language"}),C=D=>`${f}-opt-${D}`,v=l.useCallback(()=>{d(x),i(!0)},[x]),y=l.useCallback((D=!0)=>{var M;i(!1),D&&((M=u.current)==null||M.focus())},[]),j=l.useCallback(D=>{const M=un[D];M&&a(M.code),y()},[a,y]);l.useEffect(()=>{if(!o)return;const D=P=>{var B,R;return!!((B=p.current)!=null&&B.contains(P)||(R=m.current)!=null&&R.contains(P))},M=P=>{D(P.target)||i(!1)},E=P=>{D(P.target)||i(!1)};return document.addEventListener("pointerdown",M,!0),document.addEventListener("focusin",E,!0),()=>{document.removeEventListener("pointerdown",M,!0),document.removeEventListener("focusin",E,!0)}},[o]),l.useLayoutEffect(()=>{if(!o){k(null);return}h();const D=()=>h();return window.addEventListener("resize",D),window.addEventListener("scroll",D,!0),()=>{window.removeEventListener("resize",D),window.removeEventListener("scroll",D,!0)}},[o,h]),l.useEffect(()=>{var D;o&&g&&((D=m.current)==null||D.focus())},[o,g]);const N=D=>{const M=un.length-1;switch(D.key){case"ArrowDown":D.preventDefault(),d(E=>E>=M?0:E+1);break;case"ArrowUp":D.preventDefault(),d(E=>E<=0?M:E-1);break;case"Home":D.preventDefault(),d(0);break;case"End":D.preventDefault(),d(M);break;case"Enter":case" ":D.preventDefault(),j(c);break;case"Escape":D.preventDefault(),y();break;case"Tab":i(!1);break}},T=D=>{o||(D.key==="ArrowDown"||D.key==="ArrowUp"||D.key==="Enter"||D.key===" ")&&(D.preventDefault(),v())},A=t==="landing"?"lang-switch-trigger lang-switch-trigger--landing":`lang-switch-trigger lang-switch-trigger--sidebar nav-item cursor-pointer${e?" justify-center py-2.5 px-0":""}`,I=t==="landing"||!e;return s.jsxs("div",{ref:p,className:"lang-switch",children:[s.jsxs("button",{ref:u,type:"button",className:A,"aria-haspopup":"listbox","aria-expanded":o,"aria-label":`${b}: ${S.label}`,title:`${b}: ${S.label}`,onClick:()=>o?y(!1):v(),onKeyDown:T,children:[s.jsx("span",{className:"nav-icon lang-switch-icon",children:s.jsx(Pp,{size:16})}),I&&s.jsx("span",{className:"lang-switch-label text-xs",children:S.label}),I&&s.jsx(n1,{open:o})]}),o&&typeof document<"u"&&qs.createPortal(s.jsx("ul",{ref:m,role:"listbox",tabIndex:-1,"aria-label":w,"aria-activedescendant":C(c),className:`lang-switch-menu lang-switch-menu--${t}`,style:{position:"fixed",top:(g==null?void 0:g.top)??0,left:(g==null?void 0:g.left)??0,maxHeight:g==null?void 0:g.maxHeight,overflowY:"auto",visibility:g?"visible":"hidden"},onKeyDown:N,children:un.map((D,M)=>{const E=D.code===S.code,P=M===c;return s.jsxs("li",{id:C(M),role:"option","aria-selected":E,className:`lang-switch-option${P?" is-active":""}${E?" is-selected":""}`,onMouseEnter:()=>d(M),onClick:()=>j(M),children:[s.jsx("span",{className:"lang-switch-check","aria-hidden":"true",children:E?s.jsx(lo,{size:14}):null}),s.jsx("span",{className:"lang-switch-option-label",children:D.label})]},D.code)})}),document.body)]})}const r1=[],o1=[];function Qo(e,t){return e?typeof e=="function"?e(t):e:null}const i1=l.memo(function({renderState:t,brand:n,navItems:a,sidebarSections:r,footerItems:o,footerInfo:i,footerActions:c,closeMobileMenu:d}){const{t:p}=ke("common"),{collapsed:u,mobileMenuOpen:m}=t,f=k=>`nav-item${k.active?" active":""} cursor-pointer ${u?"justify-center py-2.5 px-0":""}${k.className?` ${k.className}`:""}`,g=k=>s.jsxs("div",{className:f(k),id:`nav-${k.id}`,onClick:()=>{k.onSelect(),d()},title:u?k.title??(typeof k.label=="string"?k.label:void 0):k.title,children:[s.jsx("span",{className:"nav-icon",children:k.icon}),!u&&k.label]},k.id);return s.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${u?"justify-center gap-0":""}`,children:Qo(n,t)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":p("app.closeMenu"),onClick:d,children:s.jsx(Dt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:a.map(g)}),r.map(k=>s.jsxs("div",{className:k.className??"border-t border-border-subtle pt-2 mt-2",children:[!u&&k.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:k.title}):null,k.items.map(g)]},k.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[o.map(g),Qo(i,t),s.jsx(Xj,{collapsed:u}),s.jsx(a1,{collapsed:u}),Qo(c,t)]})]})});function l1({children:e,brand:t,navItems:n,sidebarSections:a=r1,footerItems:r=o1,footerInfo:o,footerActions:i,preMainContent:c,collapsedStorageKey:d="sidebar-collapsed"}){const{t:p}=ke("common"),[u,m]=l.useState(!1),[f,g]=l.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),k=l.useCallback(()=>m(!0),[]),h=l.useCallback(()=>m(!1),[]),x=l.useCallback(()=>{g(b=>{const w=!b;try{localStorage.setItem(d,w?"1":"0")}catch{}return w})},[d]),S=l.useMemo(()=>({collapsed:f,mobileMenuOpen:u,openMobileMenu:k,closeMobileMenu:h,toggleCollapsed:x}),[f,u,k,h,x]);return s.jsxs("div",{className:`app-layout${u?" mobile-menu-open":""}${f?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":p("app.openMenu"),onClick:k,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),u&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":p("app.closeMenu"),onClick:h,onKeyDown:b=>b.key==="Escape"&&h()}),s.jsx(i1,{renderState:S,brand:t,navItems:n,sidebarSections:a,footerItems:r,footerInfo:o,footerActions:i,closeMobileMenu:h}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function xt({title:e,icon:t,description:n,accentColor:a,className:r,collapsible:o,defaultOpen:i=!0,badge:c,children:d}){const[p,u]=l.useState(i),m=o?p:!0,f=(e||n)&&s.jsxs("div",{className:Pt("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]}),n&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:n})]}),o&&s.jsx("span",{className:Pt("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:Pt("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",a&&"border-l-[3px]",r),style:a?{borderLeftColor:a}:void 0,children:[o&&f?s.jsx("button",{type:"button",className:"w-full bg-transparent border-none p-0 text-left cursor-pointer",onClick:()=>u(g=>!g),"aria-expanded":m,children:f}):f,m&&d]})}function Ja({icon:e,title:t,description:n,action:a,className:r}){return s.jsxs("div",{className:Pt("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",r),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:n}),a]})}const c1={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"},d1={error:Is,warning:Is,success:Ua,info:co};function Mt({variant:e,children:t,onDismiss:n,className:a}){return s.jsxs("div",{className:Pt("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",c1[e],a),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[(()=>{const r=d1[e];return s.jsx(r,{size:14})})(),s.jsx("span",{children:t})]}),n&&s.jsx("button",{onClick:n,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}function Tt({label:e,hint:t,children:n,className:a}){return s.jsxs("div",{className:Pt("mb-5",a),children:[s.jsx("label",{className:"block text-xs font-semibold text-text-muted uppercase tracking-wider mb-2",children:e}),n,t&&s.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:t})]})}function xs(e){const{className:t,...n}=e;return s.jsx("input",{...n,className:Pt("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 u1={primary:"btn-primary",secondary:"btn-secondary",warning:"btn-warning",danger:"btn-danger",ghost:"btn-ghost"},Us=l.forwardRef(function({variant:t="secondary",size:n="md",type:a,className:r,...o},i){return s.jsx("button",{ref:i,type:a??"button",className:Pt("btn",u1[t],n==="sm"&&"btn-sm",r),...o})}),p1=l.forwardRef(function({options:t,children:n,className:a,...r},o){return s.jsx("select",{ref:o,className:Pt("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",a),...r,children:n??(t==null?void 0:t.map(i=>s.jsx("option",{value:i.value,disabled:i.disabled,children:i.label},i.value)))})}),m1={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"},h1={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function f1({status:e,label:t,className:n}){const a=t||e;return s.jsxs("span",{className:Pt("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",m1[e],n),children:[s.jsx("span",{className:Pt("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",h1[e])}),a]})}function g1({tabs:e,defaultTabKey:t,activeKey:n,onTabChange:a,variant:r="pill",ariaLabel:o,className:i,tabListClassName:c,panelClassName:d,tabIdPrefix:p,unmountInactivePanels:u=!1}){var S;const[m,f]=l.useState(t??((S=e[0])==null?void 0:S.key)),g=n!==void 0,k=g?n:m,h=b=>{g||f(b),a==null||a(b)},x=r==="underline";return s.jsxs("div",{className:i,children:[s.jsx("div",{className:Pt(x?"flex shrink-0 items-center gap-1 border-b border-border-subtle px-4 md:px-6":"mb-5 inline-flex w-full flex-wrap items-center gap-1 rounded-xl border border-border-subtle bg-bg-secondary/60 p-1 sm:w-fit",c),role:"tablist","aria-label":o,children:e.map(b=>{const w=b.key===k;return s.jsxs("button",{id:p?`${p}-${b.key}`:void 0,type:"button",role:"tab","aria-selected":w,className:Pt(x?["-mb-px flex cursor-pointer items-center gap-1.5 border-b-2 px-3 py-2.5 text-[13px] font-medium transition-colors",w?"border-accent text-accent":"border-transparent text-text-muted hover:text-text-secondary"]:["flex flex-1 items-center justify-center gap-1.5 rounded-lg px-3.5 py-1.5 text-[13px] font-medium transition-colors sm:flex-none",w?"bg-bg-card text-text-primary shadow-sm border border-border-default":"text-text-muted border border-transparent hover:text-text-secondary hover:bg-white/[0.03]"]),onClick:()=>h(b.key),children:[b.icon,b.label]},b.key)})}),e.map(b=>{const w=b.key===k;return u&&!w?null:s.jsx("div",{className:w?Pt("flex flex-col gap-4",d):"hidden",children:b.content},b.key)})]})}function bn({label:e,description:t,checked:n,disabled:a,onChange:r,extra:o}){return s.jsxs("div",{className:`flex justify-between items-center ${a?"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":n,"aria-disabled":a,disabled:a,onClick:()=>r(!n),className:`relative inline-flex items-center ${a?"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:n?"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)] ${n?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function b1({onPrefChange:e}){const{t}=ke("common"),[n,a]=ik(),[r,o]=l.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);l.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){o("unsupported");return}o(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,d)=>{a({[c]:d}),e==null||e(c,d)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(bn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ia,{size:15})," ",t("notifications.masterToggleLabel")]}),description:t("notifications.masterToggleDesc"),checked:n.globalEnabled,onChange:c=>i("globalEnabled",c)}),n.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),n.globalEnabled&&s.jsx(bn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(us,{size:15})," ",t("notifications.browserNotificationsLabel")]}),description:t("notifications.browserNotificationsDesc"),checked:n.browserNotifications,onChange:c=>i("browserNotifications",c)}),n.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:t("notifications.standaloneBackgroundInfo")}),r==="default"&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-status-warning",children:[s.jsx("span",{children:t("notifications.standalonePermissionDefault")}),s.jsx("button",{onClick:()=>{dm().then(o)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:t("notifications.allowNotifications")})]}),r==="denied"&&s.jsx("div",{className:"text-[11px] text-status-warning",children:t("notifications.permissionDenied")}),r==="unsupported"&&s.jsx("div",{className:"text-[11px] text-status-warning",children:t("notifications.standalonePermissionUnsupported")})]}),n.globalEnabled&&n.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(bn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ua,{size:15})," ",t("notifications.completionAlertsLabel")]}),description:t("notifications.completionAlertsDesc"),checked:n.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(bn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(xb,{size:15})," ",t("notifications.approvalAlertsLabel")]}),description:t("notifications.approvalAlertsDesc"),checked:n.approvalAlert,onChange:c=>i("approvalAlert",c)}),s.jsx(bn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ea,{size:15})," ",t("notifications.connectionAlertsLabel")]}),description:t("notifications.connectionAlertsDesc"),checked:n.disconnectAlert,onChange:c=>i("disconnectAlert",c)})]}),!n.globalEnabled&&s.jsx("p",{className:"text-[11px] text-text-muted italic",children:t("notifications.allDisabled")})]})}function Qr(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/);if(!t)return null;const n=t[4]??null;let a=null;if(n){const r=n.match(/(?:^|\.)(\d+)$/);a=r?Number(r[1]):null}return{base:[Number(t[1]),Number(t[2]),Number(t[3])],prereleaseNumber:a,isPrerelease:n!==null}}function Od(e){var t;return((t=Qr(e))==null?void 0:t.base)??null}function bh(e,t){const n=Qr(e),a=Qr(t);if(!n||!a)return e!==t;for(let r=0;r<3;r+=1){if(n.base[r]<a.base[r])return!0;if(n.base[r]>a.base[r])return!1}return n.isPrerelease&&a.isPrerelease?n.prereleaseNumber===null||a.prereleaseNumber===null?!1:n.prereleaseNumber<a.prereleaseNumber:!1}function So(e,t){const n=e.version||null;return!n||!t||e.versionMismatch===!0&&!Qr(t)?!1:bh(n,t)}function Pa(e,t){if(e.versionUpdateRequired===!0)return!0;const n=e.version||null;if(!n||!t||!bh(n,t))return!1;const a=Od(n),r=Od(t);return!a||!r?!1:a[0]!==r[0]||a[1]!==r[1]}function Jo(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="stable"||t==="latest"?"stable":t==="preview"||t==="next"?"preview":null}function x1(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="latest"||t==="stable"?"latest":t==="next"||t==="preview"?"next":null}function Ca(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function ac(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},n=Jo(t.channel)||Jo(e.updateChannel)||Jo(e.releaseChannel)||void 0,a=x1(t.npmTag)||(n==="preview"?"next":n==="stable"?"latest":void 0),r=Ca(t.targetVersion)||Ca(e.serverVersion)||void 0,o=Ca(t.minVersion)||void 0,i=Ca(t.updateCommand)||(n?"adhdev update":void 0);return{...n?{channel:n}:{},...a?{npmTag:a}:{},...r?{targetVersion:r}:{},...o?{minVersion:o}:{},...i?{updateCommand:i}:{}}}function Qs(e,t=null){return ac(e).targetVersion||t}function v1(e){return ac(e).channel||null}function Co(e){return!e||!ac(e).channel?null:{}}function xh(e,t={}){const n=Ca(t.targetVersion);return n?`Update to v${n}`:t.fallback||(t.required?"Update now":"Upgrade")}const vh="Cannot update: node update policy unavailable; refresh and try again";async function y1(e,t,n){var r,o,i,c,d,p;const a=Co(n);if(!a)return{state:"error",message:vh};try{const u=await e(t,"daemon_upgrade",a);return(r=u==null?void 0:u.result)!=null&&r.alreadyLatest?{state:"done",message:`Already on v${((o=u==null?void 0:u.result)==null?void 0:o.version)||"latest"}.`}:(i=u==null?void 0:u.result)!=null&&i.upgraded||(c=u==null?void 0:u.result)!=null&&c.success?{state:"done",message:`Upgrade to v${((d=u==null?void 0:u.result)==null?void 0:d.version)||"latest"} started. Daemon is restarting…`}:{state:"error",message:((p=u==null?void 0:u.result)==null?void 0:p.error)||"Upgrade failed"}}catch(u){return{state:"error",message:u instanceof Error?u.message:"Upgrade failed"}}}function w1(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Xo(e,t){return e instanceof Error?e.message:t}function k1({ides:e,emptyMessage:t,sendDaemonCommand:n,onDisconnect:a,onRevokeToken:r}){const{t:o}=ke("common"),i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?s.jsx(Ja,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:o("machine.connectedMachines.noMachines"),description:t||o("machine.connectedMachines.defaultDescription")}):s.jsx("div",{className:"flex flex-col gap-2",children:i.map(c=>s.jsx(C1,{ide:c,allIdes:e,sendDaemonCommand:n,onDisconnect:a,onRevokeToken:r},c.id))})}function Ud({title:e,message:t,confirmLabel:n,confirmColor:a,onConfirm:r,onCancel:o}){const{t:i}=ke("common"),c=a==="red"?"bg-status-error/20 text-status-error border-status-error/40 hover:bg-status-error/30":"";return qs.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:d=>d.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:i("common.cancel")}),s.jsx("button",{onClick:r,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,style:a==="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:n})]})]})}),document.body)}function S1(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),a=[...zj,...Kj,...Vj].find(r=>r.id===t||t.includes(r.id)||r.id.includes(t));return a?{icon:a.icon,name:a.name}:{icon:"",name:e}}function C1({ide:e,allIdes:t,sendDaemonCommand:n,onDisconnect:a,onRevokeToken:r}){var P,B;const{t:o}=ke("common"),[i,c]=l.useState("idle"),[d,p]=l.useState(""),[u,m]=l.useState(null),[f,g]=l.useState("idle"),[k,h]=l.useState(""),x=e.version||null,S=((P=e.machine)==null?void 0:P.platform)||((B=e.system)==null?void 0:B.platform)||"",b=ds(e,{fallbackId:e.id}),w=t.filter(R=>R.daemonId===e.id&&R.transport==="cdp-page"),C=t.filter(R=>R.daemonId===e.id&&R.transport==="pty"),v=t.filter(R=>R.daemonId===e.id&&R.transport==="acp"),y=e.p2p,j=async()=>{if(!n)return;const R=Co(e);if(!R){c("error"),p(vh);return}c("upgrading"),p(o("machine.connectedMachines.startingUpgrade"));try{const W=w1(await n(e.id,"daemon_upgrade",R));W.alreadyLatest?(c("done"),p(`Already on v${W.version||"latest"}.`)):W.upgraded||W.success?(c("done"),p(`Upgrade to v${W.version||"latest"} started. Daemon is restarting...`)):(c("error"),p(W.error||"Upgrade failed"))}catch(W){c("error"),p(Xo(W,"Connection lost during upgrade"))}},N=async()=>{if(m(null),!!a){g("loading");try{await a(e.id),g("done"),h(o("machine.connectedMachines.machineDisconnected"))}catch(R){g("error"),h(Xo(R,o("machine.connectedMachines.failedToDisconnect")))}}},T=async()=>{if(m(null),!!r){g("loading");try{await r(e.id),g("done"),h(o("machine.connectedMachines.tokenRevoked"))}catch(R){g("error"),h(Xo(R,o("machine.connectedMachines.failedToRevokeToken")))}}},A="1.0.53",I=Qs(e,A),D=So(e,I),M=Pa(e,I),E=w.length+C.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-text-muted",title:S,children:s.jsx(us,{size:18})}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:b}),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),"…"]}),x&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${D?"":"bg-bg-secondary"}`,style:D?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",x,!D&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[n&&D&&s.jsx("button",{onClick:j,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${A}`,children:i==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(ls,{size:12,thickness:2})," ",o("machine.connectedMachines.upgrading")]}):i==="done"?o("machine.connectedMachines.updated"):M?o("machine.connectedMachines.updateNow"):o("machine.connectedMachines.updateTo",{version:A})}),a&&s.jsx("button",{onClick:()=>m("disconnect"),disabled:f==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:o("machine.connectedMachines.disconnect")}),r&&s.jsx("button",{onClick:()=>m("revoke"),disabled:f==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:o("machine.connectedMachines.remove")}),s.jsx(f1,{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:[y&&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 ${y.state==="connected"?"bg-status-online":"bg-text-muted/30"} ${y.state==="connecting"||y.state==="new"?"animate-pulse":""}`,style:y.state==="connecting"||y.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",y.state==="connected"?"connected":y.state==="connecting"||y.state==="new"?o("machine.connectedMachines.connecting"):y.state||"off"]}),y.peers!==void 0&&y.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",y.peers," peer",y.peers!==1?"s":"",")"]})]}),y&&E>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),E>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[w.map(R=>{const W=S1(R.type),_=R.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx(Ya,{type:R.type,label:W.name,size:13}),s.jsx("span",{children:W.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:o(_?"machine.connectedMachines.cdpConnected":"machine.connectedMachines.cdpConnecting")})]},R.id)}),C.map(R=>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:R.cliName||"CLI"})]},R.id)),v.map(R=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{className:"inline-flex",children:s.jsx(Nb,{size:12})}),s.jsx("span",{children:R.cliName||"ACP"})]},R.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:o("machine.connectedMachines.noIdesConnected")})]}),(d||k)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||f==="error"?"text-status-error":i==="done"||f==="done"?"text-status-online":"text-text-muted"}`,children:k||d})]}),u==="disconnect"&&s.jsx(Ud,{title:o("machine.connectedMachines.disconnectTitle"),message:`Disconnect "${b}" from ADHDev?
|
|
53
|
+
`).includes(r)))}function kj(e,t="recent"){const n=e.slice();return n.sort((a,r)=>{if(t==="oldest")return(Number(a.lastMessageAt)||0)-(Number(r.lastMessageAt)||0);if(t==="messages"){const o=(Number(r.messageCount)||0)-(Number(a.messageCount)||0);if(o!==0)return o}return(Number(r.lastMessageAt)||0)-(Number(a.lastMessageAt)||0)}),n}function th(e,t={}){return kj(wj(e,t),t.sortMode||"recent")}function rl(e,t){return typeof e=="function"?e(t??!1?"launch.resumeSavedHistory":"launch.startFresh"):e?"Resume saved history":"Start fresh"}function sh(e,t){return typeof e=="function"?e(t??!1?"launch.resumingSavedHistory":"launch.startingFresh"):e?"Resuming saved history…":"Starting fresh…"}function Sj(e){return e?e("launch.startFresh"):"Start fresh"}function Cj(e){return e?e("launch.hostedRuntimeRecoveryDescription"):"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function jj(e){return e?e("launch.openSavedHistory"):"Open saved history"}function Nj(e){return e?e("launch.savedHistoryTitle"):"Saved History"}function sc(e){return e?e("launch.savedHistoryHelper"):"Use saved history when you want continuity in the same provider conversation."}function Aj(e){return e?e("launch.savedHistoryEmpty"):"No saved history found yet."}function Tj(e){return e?e("launch.refreshSavedHistory"):"Refresh saved history"}function Mj(e){return e?e("launch.refreshingSavedHistory"):"Refreshing saved history…"}function qr(e,t,n){if(typeof e=="function"){const o=t,i=n;return o==="start-fresh"?e("launch.startFreshWith",{label:i}):e("launch.restart",{label:i})}const a=e,r=t;return a==="start-fresh"?`Start fresh with ${r}?`:`Restart ${r}?`}function zr(e,t){if(typeof e=="function"){const a=t;return e(a==="start-fresh"?"launch.startFreshReview":a==="restart-ide"?"launch.restartIdeReview":"launch.restartStoppedReview")}const n=e;return n==="start-fresh"?"Review the provider and target folder before starting fresh.":n==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function Kr(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartFresh":"launch.confirmRestart"):e==="start-fresh"?"Start fresh":"Restart"}function Vr(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartingFresh":"launch.confirmRestarting"):e==="start-fresh"?"Starting fresh…":"Restarting…"}function nh(e,t){return typeof e=="function"?e("launch.resumeWith",{label:t}):`Resume saved history with ${e}?`}function ah(e){return e?e("launch.resumeReview"):"Review or change the target workspace before resuming saved history."}function Ed(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 rh({activeConv:e,ides:t,isCreatingChat:n,isRefreshingHistory:a,savedSessions:r=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:c,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:p,onClose:u,onNewChat:m,onSwitchSession:f,onRefreshHistory:g,onResumeSavedSession:k}){var E;const{t:h}=ke("common"),x=t.find(P=>P.id===e.routeId),S=(x==null?void 0:x.chats)||[],b=(E=x==null?void 0:x.activeChat)==null?void 0:E.id,w=bt(e)&&!ht(e),[C,v]=l.useState(()=>qt()),[y,j]=l.useState(null),N=c||C,T=String(d||"").trim(),A=P=>{if(p){p(P);return}v(P)},I=l.useMemo(()=>r.map(P=>{const B=String(P.workspace||"").trim();return P.canResume||B||!T?P:{...P,workspace:T,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[T,r]),D=l.useMemo(()=>th(I,{textQuery:N.textQuery,workspaceQuery:N.workspaceQuery,modelQuery:N.modelQuery,resumableOnly:N.resumableOnly,sortMode:N.sortMode}),[I,N.modelQuery,N.resumableOnly,N.sortMode,N.textQuery,N.workspaceQuery]),M=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:w?Nj(h):h("historyModal.chatHistory")}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:KC(e)}),w&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:sc(h)})]}),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(Dt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!w&&s.jsx("button",{onClick:m,disabled:n,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:h(n?"historyModal.creating":"historyModal.startNewChat")}),w?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:N.textQuery,onChange:P=>A({...N,textQuery:P.target.value}),placeholder:h("historyModal.searchPlaceholder"),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:N.workspaceQuery,onChange:P=>A({...N,workspaceQuery:P.target.value}),placeholder:h("historyModal.filterWorkspace"),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:N.modelQuery,onChange:P=>A({...N,modelQuery:P.target.value}),placeholder:h("historyModal.filterModel"),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:N.sortMode,onChange:P=>A({...N,sortMode:P.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:h("historyModal.sortRecent")}),s.jsx("option",{value:"oldest",children:h("historyModal.sortOldest")}),s.jsx("option",{value:"messages",children:h("historyModal.sortMessages")})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:N.resumableOnly,onChange:P=>A({...N,resumableOnly:P.target.checked})}),h("historyModal.resumeReadyOnly")]})]}),D.map(P=>{const B=e.providerSessionId===P.providerSessionId,R=B||!P.canResume||!!i,W=P.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{R||!k||j({kind:"saved",session:P})},disabled:R,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${B?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${R?"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 ${B?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:P.title||h("historyModal.untitledSession")}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:P.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Ed(P.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:P.preview||h("historyModal.noSavedPreview")}),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:[P.workspace||h("historyModal.workspaceUnknown"),W?h("historyModal.selectedWorkspaceSuffix"):"",Tn(P.summaryMetadata)?` · ${Tn(P.summaryMetadata)}`:"",P.messageCount>0?` · ${h("historyModal.msgCount",{count:P.messageCount})}`:""]}),s.jsx("div",{className:"shrink-0",children:B?h("historyModal.statusActive"):P.canResume?W?h("historyModal.statusResumeSelectedWorkspace"):i===P.providerSessionId?h("historyModal.statusResuming"):h("historyModal.statusResume"):h("historyModal.statusMissingWorkspace")})]})]},P.id)})]}):S.map(P=>s.jsxs("div",{onClick:()=>{P.id!==b&&j({kind:"chat",id:P.id,title:P.title||h("historyModal.untitledSession")})},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${b===P.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 ${b===P.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:P.title||h("historyModal.untitledSession")}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[P.id.substring(0,12),"..."]}),b===P.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:h("historyModal.statusActive")})]})]},P.id)),(w&&!o&&D.length===0||!w&&S.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(bb,{size:32})}),s.jsx("div",{className:"text-[13px]",children:w?r.length>0?h("historyModal.noMatchingHistory"):Aj(h):h("historyModal.noRecentChats")})]}),w&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:Mj(h)})})]}),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:g,disabled:a||o,className:"btn btn-secondary btn-sm rounded-[10px]",children:a||o?h("historyModal.refreshing"):s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(uo,{size:13})," ",w?Tj(h):h("historyModal.refreshHistory")]})})})]}),y&&s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center p-4",children:[s.jsx("div",{onClick:()=>j(null),className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true",className:"card fade-in relative w-full sm:w-[min(92vw,420px)] max-w-[420px] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-bg-primary",children:[s.jsx("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:h("historyModal.confirmSwitchTitle")}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:h("historyModal.confirmSwitchDescription",{target:y.kind==="chat"?y.title:y.session.title||h("historyModal.untitledSession")})}),y.kind==="saved"&&s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted font-mono truncate",children:[y.session.workspace||h("historyModal.workspaceUnknown"),y.session.lastMessageAt?` · ${Ed(y.session.lastMessageAt)}`:""]})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[s.jsx("button",{onClick:()=>{const P=y;j(null),P.kind==="chat"?(f(e.routeId,P.id),u()):k&&k(P.session)},className:"btn btn-primary w-full justify-center min-h-[42px]",children:h("historyModal.confirmSwitchAction")}),s.jsx("button",{onClick:()=>j(null),className:"btn btn-secondary w-full justify-center min-h-[42px]",children:h("common.cancel")})]})]})]})]});return typeof document>"u"?M:qs.createPortal(M,document.body)}const _d={success:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",labelKey:"toast.label.success"},warning:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",labelKey:"toast.label.warning"},info:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",labelKey:"toast.label.info"}};function oh({toasts:e,onDismiss:t,onClickToast:n}){const{t:a}=ke();return s.jsx("div",{className:"fixed right-4 top-[calc(env(safe-area-inset-top,0px)+64px)] z-[var(--z-toast)] flex flex-col gap-2 pointer-events-none sm:top-[calc(env(safe-area-inset-top,0px)+16px)]",children:e.map(r=>{const o=_d[r.type]||_d.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 i;(i=r.actions)!=null&&i.length||n&&n(r)},children:[s.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${o.accent}, color-mix(in srgb, ${o.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:i=>{i.stopPropagation(),t(r.id)},"aria-label":a("toast.dismiss"),children:s.jsx(Dt,{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:o.chipBg,color:o.chipText,border:`1px solid color-mix(in srgb, ${o.accent} 22%, transparent)`},children:a(o.labelKey)})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:r.message}),r.actions&&r.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:r.actions.map((i,c)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.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)"}:i.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:d=>{d.stopPropagation(),i.onClick(),t(r.id)},children:i.label},c))})]})]},r.id)})})}const Pj=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Dj(e){const t=e.workspace||"";if(!t)return"";const n=t.split(/[/\\]/).filter(Boolean);return n.length>0?n[n.length-1]:t}function Ij(e,t){return ih(e)||t}function ih(e){var r,o,i;const t=(o=(r=e.summaryMetadata)==null?void 0:r.items)==null?void 0:o.find(c=>(c==null?void 0:c.id)==="model"),n=((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim();if(n)return n;const a=(i=e.controlValues)==null?void 0:i.model;return typeof a=="string"&&a.trim()?a.trim():""}function Lj(e){return ih(e)||void 0}function Rj(e){return e.sessionId||e.instanceId||e.agentType}function lh(e=[]){const t={};for(const n of e)n.type==="adhdev-daemon"&&(t[n.id]=ds(n,{fallbackId:n.id}));return t}function ch(e,t={}){var a;const n=e.daemonId||((a=e.id)==null?void 0:a.split(":")[0])||e.id;return{machineName:U0(e,t.machineNames),connectionState:t.connectionStates?t.connectionStates[n]||t.defaultConnectionState||"new":t.defaultConnectionState}}function nc(e,t={}){return Ej(e,ch(e,t))}function Ej(e,t={}){var f,g,k,h,x,S,b,w,C;const n=[],a=t.machineName,r=t.connectionState,o=Dj(e),i=e.workspace||"",c=Y0(e.type,{agentName:e.cliName}),d=bt(e)||ht(e)?c:Ot(e.type),p=Ij(e,d),u=Array.isArray(e.childSessions)?e.childSessions.map(v=>{var y,j,N;return{sessionId:v.id,instanceId:v.id,providerSessionId:v.providerSessionId,activeChatId:(y=v.activeChat)==null?void 0:y.id,transport:v.transport,sessionCapabilities:v.capabilities,agentType:v.providerType,agentName:v.providerName||Ot(v.providerType),model:Lj(v),status:v.status,title:v.title,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,messages:((j=v.activeChat)==null?void 0:j.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=Pj(e);if(m){const v=e.sessionId||e.instanceId,y=(f=e.settings)==null?void 0:f.meshCoordinatorFor,j=((g=e.settings)==null?void 0:g.meshNodeFor)||!((k=e.settings)!=null&&k.meshCoordinatorFor)&&((h=e.settings)==null?void 0:h.launchedByCoordinator),N=y?" (Coordinator)":j?" (Mesh Node)":"",T=c+N,A=(x=e.activeChat)==null?void 0:x.activeModal,I=A&&Array.isArray(A.buttons)&&A.buttons.length>0,D=Q0(e.activeChat,[{status:e.status,activeModal:(S=e.activeChat)==null?void 0:S.activeModal}],e.agents||[]),M=e.activeChat||{title:"",messages:[]};let E=M.title&&String(M.title).trim()?String(M.title).trim():"";const P=(b=e.activeChat)==null?void 0:b.id,B=e.chats;if(P&&Array.isArray(B)&&B.length>0){const K=B.find(z=>z.id===P||z.id&&String(z.id)===String(P));K!=null&&K.title&&String(K.title).trim()&&(E=String(K.title).trim())}const R=(bt(e)||ht(e),e.type),W=(bt(e)||ht(e))&&ad(E,T,R)?"":E,_=M.messages||[],H=typeof P=="string"?P.trim():"",L=(bt(e)||ht(e))&&H===String(e.type||"").trim(),F=H&&!L?H:e.providerSessionId,$=e.coordinator||(typeof((w=e.settings)==null?void 0:w.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:v,providerSessionId:e.providerSessionId,historySessionId:F,nativeSessionId:v,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:bt(e)&&e.mode||"chat",agentName:T,agentType:R,status:D,title:W,messages:_,resume:e.resume,hostIdeType:!bt(e)&&!ht(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||W||(bt(e)?e.mode==="chat"?T:`Terminal${N}`:T),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:I?A.buttons:void 0,modalMessage:I?A.message:void 0,streamSource:"native",tabKey:Wo(v,e.id),machineName:a,connectionState:r,settings:e.settings,coordinator:$,messageInput:e.messageInput})}if(m&&(bt(e)||ht(e)))return n;for(const v of u){const y=v.activeModal&&Array.isArray(v.activeModal.buttons)&&v.activeModal.buttons.length>0,j=J0(v),N=Rj(v),T=`${e.id}:${N}`,A=v.title&&String(v.title).trim()||"",I=ad(A,v.agentName,v.agentType)?"":A,D=v.messages||[];if(!(v.transport==="cdp-webview"||!!v.sessionId||!!v.providerSessionId||D.length>0||y||!!I||!["idle","panel_hidden","disconnected","not_monitored"].includes(j)))continue;const E=v.coordinator||(typeof((C=v.settings)==null?void 0:C.meshCoordinatorFor)=="string"&&v.settings.meshCoordinatorFor?{meshId:v.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.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:j,title:I,messages:D,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:v.git||e.git,displayPrimary:o||I||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:y?v.activeModal.buttons:void 0,modalMessage:y?v.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Wo(v.sessionId||v.instanceId,T),machineName:a,connectionState:r,settings:v.settings,coordinator:E,messageInput:v.messageInput})}return n.length===0&&n.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:Wo(e.sessionId||e.instanceId,e.id),connectionState:r,settings:e.settings,messageInput:e.messageInput}),n}function dh(e){return String(e.type||e.id||"").trim()}function Yr(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()).map(t=>t.trim()):[]}function _j(e,t){const n=(t||"").trim();if(!n)return[];const a=(e||[]).find(r=>r.type===n);return Yr(a==null?void 0:a.modelOptions)}function Hj(e,t){const n=(t||"").trim();if(!n)return[];const a=(e||[]).find(r=>r.type===n);return Yr(a==null?void 0:a.thinkingLevelOptions)}function uh(e){const t=new Map;for(const n of e||[])n!=null&&n.type&&t.set(n.type,{models:Yr(n.modelOptions),thinking:Yr(n.thinkingLevelOptions)});return t}function $j(e){var t;return e.category!=="cli"||!dh(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 ln(e){var a;const t=new Set,n=[];for(const r of e||[]){if(!$j(r))continue;const o=dh(r);if(!o||t.has(o))continue;t.add(o);const i=String(r.displayName||r.name||o),c=r.detectedPath||((a=r.lastDetection)==null?void 0:a.path)||null;n.push({type:o,label:i,icon:r.icon,statusLabel:c?`Detected at ${c}`:"Detected on this machine",detectedPath:c,...Array.isArray(r.modelOptions)&&r.modelOptions.length?{modelOptions:r.modelOptions}:{},...Array.isArray(r.thinkingLevelOptions)&&r.thinkingLevelOptions.length?{thinkingLevelOptions:r.thinkingLevelOptions}:{}})}return n}function Va(e){const t=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],n=new Set,a=[];for(const r of t){const o=typeof r=="string"?r.trim():"";!o||n.has(o)||(n.add(o),a.push(o))}return a}function Pn(e){return e.map(t=>t.type)}function Fj(e,t){const n=Va(e),a=t.trim();return!a||n.includes(a)?n:[...n,a]}function Bj(e,t){return Va(e).filter(n=>n!==t)}function Hd(e,t,n){const a=Va(e),r=a.indexOf(t);if(r<0)return a;const o=a.filter(c=>c!==t);if(n==="top")return[t,...o];if(n==="bottom")return[...o,t];const i=n==="up"?Math.max(0,r-1):Math.min(o.length,r+1);return o.splice(i,0,t),o}const Wj={"claude-cli":{monogram:"CL",hue:"#D97757"},"codex-cli":{monogram:"CX",hue:"#10A37F"},"gemini-cli":{monogram:"GM",hue:"#4285F4"},"kimi-cli":{monogram:"KM",hue:"#6366F1"},"antigravity-cli":{monogram:"AG",hue:"#8B5CF6"},"cursor-cli":{monogram:"CU",hue:"#64748B"},"opencode-cli":{monogram:"OC",hue:"#CA8A04"},"hermes-cli":{monogram:"HM",hue:"#14B8A6"},"grok-cli":{monogram:"GK",hue:"#475569"},antigravity:{monogram:"AG",hue:"#8B5CF6"},cursor:{monogram:"CU",hue:"#64748B"},kiro:{monogram:"KI",hue:"#F59E0B"},pearai:{monogram:"PA",hue:"#22C55E"},trae:{monogram:"TR",hue:"#EF4444"},vscode:{monogram:"VS",hue:"#3B82F6"},vscodium:{monogram:"VC",hue:"#2DD4BF"},windsurf:{monogram:"WS",hue:"#0EA5E9"},cline:{monogram:"CN",hue:"#0284C7"},"roo-code":{monogram:"RC",hue:"#F97316"}},$d=["#0EA5E9","#8B5CF6","#10B981","#F59E0B","#EF4444","#14B8A6","#6366F1","#EC4899","#84CC16","#F97316","#06B6D4","#A855F7"];function Oj(e){let t=0;for(let n=0;n<e.length;n+=1)t=(t<<5)-t+e.charCodeAt(n)|0;return Math.abs(t)}function Uj(e){const t=e.replace(/[-_./]+/g," ").split(/\s+/).map(n=>n.trim()).filter(Boolean);return t.length===0?"?":t.length===1?t[0].slice(0,2).toUpperCase():(t[0][0]+t[1][0]).toUpperCase()}function Ya({type:e,label:t,size:n=16,className:a}){const r=(e||"").trim().toLowerCase(),o=(t==null?void 0:t.trim())||r;if(!o)return s.jsx(Tb,{size:n,className:a});const i=Wj[r],c=(i==null?void 0:i.monogram)??Uj((t==null?void 0:t.trim())||r.replace(/-cli$/,"")),d=(i==null?void 0:i.hue)??$d[Oj(r||o)%$d.length];return s.jsx("span",{"aria-hidden":!0,className:`inline-flex shrink-0 select-none items-center justify-center font-semibold ${a??""}`,style:{width:n,height:n,borderRadius:Math.max(4,Math.round(n*.3)),backgroundColor:`${d}21`,border:`1px solid ${d}4D`,color:d,fontSize:Math.max(7,Math.round(n*.42)),letterSpacing:"0.02em",lineHeight:1},children:c})}function Fd({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 Gj({value:e,availableProviders:t,onChange:n,disabled:a=!1,saveButton:r}){const{t:o}=ke("common"),[i,c]=l.useState(""),d=l.useMemo(()=>new Map(t.map(g=>[g.type,g])),[t]),p=l.useMemo(()=>Va(e),[e]),u=p.filter(g=>!d.has(g)).length,m=t.filter(g=>!p.includes(g.type)),f=()=>{i&&(n(Fj(p,i)),c(""))};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:p.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."}):p.map((g,k)=>{const h=d.get(g),x=!!h;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 ${x?"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:["#",k+1]}),s.jsx(Ya,{type:g,label:h==null?void 0:h.label,size:14}),s.jsx("span",{className:`font-mono text-[12px] ${x?"text-text-primary":"text-text-muted"}`,children:g}),x?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:o("settings.providerPriority.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:o("settings.providerPriority.notOnMachine")})]}),s.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:h?`${h.label} · ${h.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:a||k===0,title:"Move up",onClick:()=>n(Hd(p,g,"up")),children:s.jsx(Fd,{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:a||k===p.length-1,title:"Move down",onClick:()=>n(Hd(p,g,"down")),children:s.jsx(Fd,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:a,onClick:()=>n(Bj(p,g)),children:o("settings.providerPriority.remove")})]})]},g)})}),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:o("settings.providerPriority.addCliLabel")}),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:i,onChange:g=>c(g.target.value),disabled:a||m.length===0,children:[s.jsx("option",{value:"",children:m.length?"Select provider…":"No additional detected CLI providers"}),m.map(g=>s.jsxs("option",{value:g.type,children:[g.label," (",g.type,")"]},g.type))]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:a||!i,onClick:f,children:o("settings.providerPriority.addProvider")}),r]}),s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:["Launches use this order, top to bottom.",u>0?` ${u} provider${u===1?"":"s"} not detected here — kept in order, skipped until available.`:""]})]})}function qj(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 ph(e,t){const n=qj(e);return{daemonId:n.daemonId,payload:{...t,...n.targetSessionId&&!t.targetSessionId?{targetSessionId:n.targetSessionId}:{}}}}const mh=[{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:"🏄"}],hh=[{id:"antigravity-cli",name:"Antigravity CLI",icon:"🪐"},{id:"claude-cli",name:"Claude Code",icon:"🟠"},{id:"codex-cli",name:"Codex CLI",icon:"📦"},{id:"cursor-cli",name:"Cursor CLI",icon:"⚡"},{id:"grok-cli",name:"Grok",icon:"🛰️"},{id:"hermes-cli",name:"Hermes",icon:"⚕️"},{id:"kimi",name:"Kimi",icon:"🌙"},{id:"opencode",name:"OpenCode CLI",icon:"◆"}],fh=[{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:"🟠"}],zj=mh,Kj=hh,Vj=fh;function Yj({icon:e,title:t,subtitle:n,badge:a,actions:r,className:o}){return s.jsxs("div",{className:Pt("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,a&&s.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[a.count!==void 0?a.count:""," ",a.text]})]}),n&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:n})]}),r&&s.jsx("div",{className:"flex gap-2",children:r})]})}function Qa({icon:e,title:t,subtitle:n,badge:a,actions:r,widthClassName:o="max-w-6xl",contentClassName:i,children:c}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(Yj,{icon:e,title:t,subtitle:n,badge:a,actions:r}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Pt("mx-auto flex w-full flex-col gap-4",o,i),children:c})})]})}const ol="adhdev:themechange";function Qj(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function qn(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function zn(e){return e==="system"?Qj():e}function gh(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Tr(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(ol,{detail:{preference:e,theme:t}}))}function Jj(){const e=qn(),t=zn(e);gh(t),Tr(e,t)}function Ls(){const[e,t]=l.useState(qn),[n,a]=l.useState(()=>zn(qn()));l.useEffect(()=>{gh(n)},[n]),l.useEffect(()=>{const i=window.matchMedia("(prefers-color-scheme: light)"),c=d=>{if(e==="system"){const p=d.matches?"light":"dark";a(p),Tr("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:qn()),a(m==="dark"||m==="light"?m:zn(qn()))},c=d=>{if(d.key!=="theme")return;const p=qn(),u=zn(p);t(p),a(u)};return window.addEventListener(ol,i),window.addEventListener("storage",c),()=>{window.removeEventListener(ol,i),window.removeEventListener("storage",c)}},[]);const r=l.useCallback(i=>{const c=zn(i);t(i),a(c);try{localStorage.setItem("theme",i)}catch{}Tr(i,c)},[]),o=l.useCallback(()=>{t(i=>{const c=i==="dark"?"light":i==="light"?"system":"dark",d=zn(c);a(d);try{localStorage.setItem("theme",c)}catch{}return Tr(c,d),c})},[]);return{theme:n,preference:e,setPreference:r,cycleTheme:o,isDark:n==="dark"}}const Bd={dark:"Dark",light:"Light",system:"System"};function Xj({collapsed:e}){const{preference:t,cycleTheme:n}=Ls(),a=t==="dark"?s.jsx(Tp,{size:16}):t==="light"?s.jsx(Ap,{size:16}):s.jsx(Mp,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:n,title:`Theme: ${Bd[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:a}),!e&&s.jsx("span",{className:"text-xs",children:Bd[t]})]})}const il="adhdev:langchange";function Zj(){const e=wt.language;return Vn(e)?e:Jp()}function e1(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(il,{detail:{language:e}}))}function t1(){const[e,t]=l.useState(Zj);l.useEffect(()=>{const a=i=>{Vn(i)&&t(i)},r=i=>{const c=i.detail||{};Vn(c.language)&&t(c.language)},o=i=>{if(i.key!==qi)return;const c=i.newValue;Vn(c)&&c!==wt.language&&(wt.changeLanguage(c),zi(c))};return wt.on("languageChanged",a),window.addEventListener(il,r),window.addEventListener("storage",o),()=>{wt.off("languageChanged",a),window.removeEventListener(il,r),window.removeEventListener("storage",o)}},[]);const n=l.useCallback(a=>{if(Vn(a)){t(a);try{localStorage.setItem(qi,a)}catch{}wt.changeLanguage(a),zi(a),e1(a)}},[]);return{language:e,setLanguage:n}}function s1({trigger:e,viewport:t,menu:n,variant:a,gap:r=6,margin:o=8}){const i=e.top-o,c=t.height-e.bottom-o,d=a==="sidebar";let p=d;d&&i<n.height&&c>i&&(p=!1),!d&&c<n.height&&i>c&&(p=!0);const u=p?i:c,m=Math.max(80,Math.min(n.height,u));let f;p?f=e.top-r-m:f=e.bottom+r,f=Wd(f,o,Math.max(o,t.height-m-o));const g=Wd(e.left,o,Math.max(o,t.width-n.width-o));return{top:f,left:g,maxHeight:m}}function Wd(e,t,n){return Math.min(Math.max(e,t),n)}function n1({open:e}){return s.jsx("svg",{width:12,height:12,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:`lang-switch-caret${e?" open":""}`,children:s.jsx("polyline",{points:"6 9 12 15 18 9"})})}function a1({collapsed:e,variant:t="sidebar"}){const{language:n,setLanguage:a}=t1(),{t:r}=ke("common"),[o,i]=l.useState(!1),[c,d]=l.useState(0),p=l.useRef(null),u=l.useRef(null),m=l.useRef(null),f=l.useId(),[g,k]=l.useState(null),h=l.useCallback(()=>{const D=u.current;if(!D)return;const M=D.getBoundingClientRect(),E=m.current,P=Math.max((E==null?void 0:E.offsetWidth)??0,168),B=(E==null?void 0:E.scrollHeight)??un.length*36+12;k(s1({trigger:{top:M.top,left:M.left,right:M.right,bottom:M.bottom,width:M.width,height:M.height},viewport:{width:window.innerWidth,height:window.innerHeight},menu:{width:P,height:B},variant:t}))},[t]),x=Math.max(0,un.findIndex(D=>D.code===n)),S=un[x]??un[0],b=r("language.label",{defaultValue:"Language"}),w=r("language.select",{defaultValue:"Select language"}),C=D=>`${f}-opt-${D}`,v=l.useCallback(()=>{d(x),i(!0)},[x]),y=l.useCallback((D=!0)=>{var M;i(!1),D&&((M=u.current)==null||M.focus())},[]),j=l.useCallback(D=>{const M=un[D];M&&a(M.code),y()},[a,y]);l.useEffect(()=>{if(!o)return;const D=P=>{var B,R;return!!((B=p.current)!=null&&B.contains(P)||(R=m.current)!=null&&R.contains(P))},M=P=>{D(P.target)||i(!1)},E=P=>{D(P.target)||i(!1)};return document.addEventListener("pointerdown",M,!0),document.addEventListener("focusin",E,!0),()=>{document.removeEventListener("pointerdown",M,!0),document.removeEventListener("focusin",E,!0)}},[o]),l.useLayoutEffect(()=>{if(!o){k(null);return}h();const D=()=>h();return window.addEventListener("resize",D),window.addEventListener("scroll",D,!0),()=>{window.removeEventListener("resize",D),window.removeEventListener("scroll",D,!0)}},[o,h]),l.useEffect(()=>{var D;o&&g&&((D=m.current)==null||D.focus())},[o,g]);const N=D=>{const M=un.length-1;switch(D.key){case"ArrowDown":D.preventDefault(),d(E=>E>=M?0:E+1);break;case"ArrowUp":D.preventDefault(),d(E=>E<=0?M:E-1);break;case"Home":D.preventDefault(),d(0);break;case"End":D.preventDefault(),d(M);break;case"Enter":case" ":D.preventDefault(),j(c);break;case"Escape":D.preventDefault(),y();break;case"Tab":i(!1);break}},T=D=>{o||(D.key==="ArrowDown"||D.key==="ArrowUp"||D.key==="Enter"||D.key===" ")&&(D.preventDefault(),v())},A=t==="landing"?"lang-switch-trigger lang-switch-trigger--landing":`lang-switch-trigger lang-switch-trigger--sidebar nav-item cursor-pointer${e?" justify-center py-2.5 px-0":""}`,I=t==="landing"||!e;return s.jsxs("div",{ref:p,className:"lang-switch",children:[s.jsxs("button",{ref:u,type:"button",className:A,"aria-haspopup":"listbox","aria-expanded":o,"aria-label":`${b}: ${S.label}`,title:`${b}: ${S.label}`,onClick:()=>o?y(!1):v(),onKeyDown:T,children:[s.jsx("span",{className:"nav-icon lang-switch-icon",children:s.jsx(Pp,{size:16})}),I&&s.jsx("span",{className:"lang-switch-label text-xs",children:S.label}),I&&s.jsx(n1,{open:o})]}),o&&typeof document<"u"&&qs.createPortal(s.jsx("ul",{ref:m,role:"listbox",tabIndex:-1,"aria-label":w,"aria-activedescendant":C(c),className:`lang-switch-menu lang-switch-menu--${t}`,style:{position:"fixed",top:(g==null?void 0:g.top)??0,left:(g==null?void 0:g.left)??0,maxHeight:g==null?void 0:g.maxHeight,overflowY:"auto",visibility:g?"visible":"hidden"},onKeyDown:N,children:un.map((D,M)=>{const E=D.code===S.code,P=M===c;return s.jsxs("li",{id:C(M),role:"option","aria-selected":E,className:`lang-switch-option${P?" is-active":""}${E?" is-selected":""}`,onMouseEnter:()=>d(M),onClick:()=>j(M),children:[s.jsx("span",{className:"lang-switch-check","aria-hidden":"true",children:E?s.jsx(lo,{size:14}):null}),s.jsx("span",{className:"lang-switch-option-label",children:D.label})]},D.code)})}),document.body)]})}const r1=[],o1=[];function Qo(e,t){return e?typeof e=="function"?e(t):e:null}const i1=l.memo(function({renderState:t,brand:n,navItems:a,sidebarSections:r,footerItems:o,footerInfo:i,footerActions:c,closeMobileMenu:d}){const{t:p}=ke("common"),{collapsed:u,mobileMenuOpen:m}=t,f=k=>`nav-item${k.active?" active":""} cursor-pointer ${u?"justify-center py-2.5 px-0":""}${k.className?` ${k.className}`:""}`,g=k=>s.jsxs("div",{className:f(k),id:`nav-${k.id}`,onClick:()=>{k.onSelect(),d()},title:u?k.title??(typeof k.label=="string"?k.label:void 0):k.title,children:[s.jsx("span",{className:"nav-icon",children:k.icon}),!u&&k.label]},k.id);return s.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${u?"justify-center gap-0":""}`,children:Qo(n,t)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":p("app.closeMenu"),onClick:d,children:s.jsx(Dt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:a.map(g)}),r.map(k=>s.jsxs("div",{className:k.className??"border-t border-border-subtle pt-2 mt-2",children:[!u&&k.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:k.title}):null,k.items.map(g)]},k.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[o.map(g),Qo(i,t),s.jsx(Xj,{collapsed:u}),s.jsx(a1,{collapsed:u}),Qo(c,t)]})]})});function l1({children:e,brand:t,navItems:n,sidebarSections:a=r1,footerItems:r=o1,footerInfo:o,footerActions:i,preMainContent:c,collapsedStorageKey:d="sidebar-collapsed"}){const{t:p}=ke("common"),[u,m]=l.useState(!1),[f,g]=l.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),k=l.useCallback(()=>m(!0),[]),h=l.useCallback(()=>m(!1),[]),x=l.useCallback(()=>{g(b=>{const w=!b;try{localStorage.setItem(d,w?"1":"0")}catch{}return w})},[d]),S=l.useMemo(()=>({collapsed:f,mobileMenuOpen:u,openMobileMenu:k,closeMobileMenu:h,toggleCollapsed:x}),[f,u,k,h,x]);return s.jsxs("div",{className:`app-layout${u?" mobile-menu-open":""}${f?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":p("app.openMenu"),onClick:k,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),u&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":p("app.closeMenu"),onClick:h,onKeyDown:b=>b.key==="Escape"&&h()}),s.jsx(i1,{renderState:S,brand:t,navItems:n,sidebarSections:a,footerItems:r,footerInfo:o,footerActions:i,closeMobileMenu:h}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function xt({title:e,icon:t,description:n,accentColor:a,className:r,collapsible:o,defaultOpen:i=!0,badge:c,children:d}){const[p,u]=l.useState(i),m=o?p:!0,f=(e||n)&&s.jsxs("div",{className:Pt("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]}),n&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:n})]}),o&&s.jsx("span",{className:Pt("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:Pt("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",a&&"border-l-[3px]",r),style:a?{borderLeftColor:a}:void 0,children:[o&&f?s.jsx("button",{type:"button",className:"w-full bg-transparent border-none p-0 text-left cursor-pointer",onClick:()=>u(g=>!g),"aria-expanded":m,children:f}):f,m&&d]})}function Ja({icon:e,title:t,description:n,action:a,className:r}){return s.jsxs("div",{className:Pt("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",r),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:n}),a]})}const c1={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"},d1={error:Is,warning:Is,success:Ua,info:co};function Mt({variant:e,children:t,onDismiss:n,className:a}){return s.jsxs("div",{className:Pt("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",c1[e],a),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[(()=>{const r=d1[e];return s.jsx(r,{size:14})})(),s.jsx("span",{children:t})]}),n&&s.jsx("button",{onClick:n,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}function Tt({label:e,hint:t,children:n,className:a}){return s.jsxs("div",{className:Pt("mb-5",a),children:[s.jsx("label",{className:"block text-xs font-semibold text-text-muted uppercase tracking-wider mb-2",children:e}),n,t&&s.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:t})]})}function xs(e){const{className:t,...n}=e;return s.jsx("input",{...n,className:Pt("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 u1={primary:"btn-primary",secondary:"btn-secondary",warning:"btn-warning",danger:"btn-danger",ghost:"btn-ghost"},Us=l.forwardRef(function({variant:t="secondary",size:n="md",type:a,className:r,...o},i){return s.jsx("button",{ref:i,type:a??"button",className:Pt("btn",u1[t],n==="sm"&&"btn-sm",r),...o})}),p1=l.forwardRef(function({options:t,children:n,className:a,...r},o){return s.jsx("select",{ref:o,className:Pt("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",a),...r,children:n??(t==null?void 0:t.map(i=>s.jsx("option",{value:i.value,disabled:i.disabled,children:i.label},i.value)))})}),m1={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"},h1={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function f1({status:e,label:t,className:n}){const a=t||e;return s.jsxs("span",{className:Pt("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",m1[e],n),children:[s.jsx("span",{className:Pt("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",h1[e])}),a]})}function g1({tabs:e,defaultTabKey:t,activeKey:n,onTabChange:a,variant:r="pill",ariaLabel:o,className:i,tabListClassName:c,panelClassName:d,tabIdPrefix:p,unmountInactivePanels:u=!1}){var S;const[m,f]=l.useState(t??((S=e[0])==null?void 0:S.key)),g=n!==void 0,k=g?n:m,h=b=>{g||f(b),a==null||a(b)},x=r==="underline";return s.jsxs("div",{className:i,children:[s.jsx("div",{className:Pt(x?"flex shrink-0 items-center gap-1 border-b border-border-subtle px-4 md:px-6":"mb-5 inline-flex w-full flex-wrap items-center gap-1 rounded-xl border border-border-subtle bg-bg-secondary/60 p-1 sm:w-fit",c),role:"tablist","aria-label":o,children:e.map(b=>{const w=b.key===k;return s.jsxs("button",{id:p?`${p}-${b.key}`:void 0,type:"button",role:"tab","aria-selected":w,className:Pt(x?["-mb-px flex cursor-pointer items-center gap-1.5 border-b-2 px-3 py-2.5 text-[13px] font-medium transition-colors",w?"border-accent text-accent":"border-transparent text-text-muted hover:text-text-secondary"]:["flex flex-1 items-center justify-center gap-1.5 rounded-lg px-3.5 py-1.5 text-[13px] font-medium transition-colors sm:flex-none",w?"bg-bg-card text-text-primary shadow-sm border border-border-default":"text-text-muted border border-transparent hover:text-text-secondary hover:bg-white/[0.03]"]),onClick:()=>h(b.key),children:[b.icon,b.label]},b.key)})}),e.map(b=>{const w=b.key===k;return u&&!w?null:s.jsx("div",{className:w?Pt("flex flex-col gap-4",d):"hidden",children:b.content},b.key)})]})}function bn({label:e,description:t,checked:n,disabled:a,onChange:r,extra:o}){return s.jsxs("div",{className:`flex justify-between items-center ${a?"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":n,"aria-disabled":a,disabled:a,onClick:()=>r(!n),className:`relative inline-flex items-center ${a?"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:n?"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)] ${n?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function b1({onPrefChange:e}){const{t}=ke("common"),[n,a]=ik(),[r,o]=l.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);l.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){o("unsupported");return}o(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,d)=>{a({[c]:d}),e==null||e(c,d)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(bn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ia,{size:15})," ",t("notifications.masterToggleLabel")]}),description:t("notifications.masterToggleDesc"),checked:n.globalEnabled,onChange:c=>i("globalEnabled",c)}),n.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),n.globalEnabled&&s.jsx(bn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(us,{size:15})," ",t("notifications.browserNotificationsLabel")]}),description:t("notifications.browserNotificationsDesc"),checked:n.browserNotifications,onChange:c=>i("browserNotifications",c)}),n.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:t("notifications.standaloneBackgroundInfo")}),r==="default"&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-status-warning",children:[s.jsx("span",{children:t("notifications.standalonePermissionDefault")}),s.jsx("button",{onClick:()=>{dm().then(o)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:t("notifications.allowNotifications")})]}),r==="denied"&&s.jsx("div",{className:"text-[11px] text-status-warning",children:t("notifications.permissionDenied")}),r==="unsupported"&&s.jsx("div",{className:"text-[11px] text-status-warning",children:t("notifications.standalonePermissionUnsupported")})]}),n.globalEnabled&&n.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(bn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ua,{size:15})," ",t("notifications.completionAlertsLabel")]}),description:t("notifications.completionAlertsDesc"),checked:n.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(bn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(xb,{size:15})," ",t("notifications.approvalAlertsLabel")]}),description:t("notifications.approvalAlertsDesc"),checked:n.approvalAlert,onChange:c=>i("approvalAlert",c)}),s.jsx(bn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ea,{size:15})," ",t("notifications.connectionAlertsLabel")]}),description:t("notifications.connectionAlertsDesc"),checked:n.disconnectAlert,onChange:c=>i("disconnectAlert",c)})]}),!n.globalEnabled&&s.jsx("p",{className:"text-[11px] text-text-muted italic",children:t("notifications.allDisabled")})]})}function Qr(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/);if(!t)return null;const n=t[4]??null;let a=null;if(n){const r=n.match(/(?:^|\.)(\d+)$/);a=r?Number(r[1]):null}return{base:[Number(t[1]),Number(t[2]),Number(t[3])],prereleaseNumber:a,isPrerelease:n!==null}}function Od(e){var t;return((t=Qr(e))==null?void 0:t.base)??null}function bh(e,t){const n=Qr(e),a=Qr(t);if(!n||!a)return e!==t;for(let r=0;r<3;r+=1){if(n.base[r]<a.base[r])return!0;if(n.base[r]>a.base[r])return!1}return n.isPrerelease&&a.isPrerelease?n.prereleaseNumber===null||a.prereleaseNumber===null?!1:n.prereleaseNumber<a.prereleaseNumber:!1}function So(e,t){const n=e.version||null;return!n||!t||e.versionMismatch===!0&&!Qr(t)?!1:bh(n,t)}function Pa(e,t){if(e.versionUpdateRequired===!0)return!0;const n=e.version||null;if(!n||!t||!bh(n,t))return!1;const a=Od(n),r=Od(t);return!a||!r?!1:a[0]!==r[0]||a[1]!==r[1]}function Jo(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="stable"||t==="latest"?"stable":t==="preview"||t==="next"?"preview":null}function x1(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="latest"||t==="stable"?"latest":t==="next"||t==="preview"?"next":null}function Ca(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function ac(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},n=Jo(t.channel)||Jo(e.updateChannel)||Jo(e.releaseChannel)||void 0,a=x1(t.npmTag)||(n==="preview"?"next":n==="stable"?"latest":void 0),r=Ca(t.targetVersion)||Ca(e.serverVersion)||void 0,o=Ca(t.minVersion)||void 0,i=Ca(t.updateCommand)||(n?"adhdev update":void 0);return{...n?{channel:n}:{},...a?{npmTag:a}:{},...r?{targetVersion:r}:{},...o?{minVersion:o}:{},...i?{updateCommand:i}:{}}}function Qs(e,t=null){return ac(e).targetVersion||t}function v1(e){return ac(e).channel||null}function Co(e){return!e||!ac(e).channel?null:{}}function xh(e,t={}){const n=Ca(t.targetVersion);return n?`Update to v${n}`:t.fallback||(t.required?"Update now":"Upgrade")}const vh="Cannot update: node update policy unavailable; refresh and try again";async function y1(e,t,n){var r,o,i,c,d,p;const a=Co(n);if(!a)return{state:"error",message:vh};try{const u=await e(t,"daemon_upgrade",a);return(r=u==null?void 0:u.result)!=null&&r.alreadyLatest?{state:"done",message:`Already on v${((o=u==null?void 0:u.result)==null?void 0:o.version)||"latest"}.`}:(i=u==null?void 0:u.result)!=null&&i.upgraded||(c=u==null?void 0:u.result)!=null&&c.success?{state:"done",message:`Upgrade to v${((d=u==null?void 0:u.result)==null?void 0:d.version)||"latest"} started. Daemon is restarting…`}:{state:"error",message:((p=u==null?void 0:u.result)==null?void 0:p.error)||"Upgrade failed"}}catch(u){return{state:"error",message:u instanceof Error?u.message:"Upgrade failed"}}}function w1(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Xo(e,t){return e instanceof Error?e.message:t}function k1({ides:e,emptyMessage:t,sendDaemonCommand:n,onDisconnect:a,onRevokeToken:r}){const{t:o}=ke("common"),i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?s.jsx(Ja,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:o("machine.connectedMachines.noMachines"),description:t||o("machine.connectedMachines.defaultDescription")}):s.jsx("div",{className:"flex flex-col gap-2",children:i.map(c=>s.jsx(C1,{ide:c,allIdes:e,sendDaemonCommand:n,onDisconnect:a,onRevokeToken:r},c.id))})}function Ud({title:e,message:t,confirmLabel:n,confirmColor:a,onConfirm:r,onCancel:o}){const{t:i}=ke("common"),c=a==="red"?"bg-status-error/20 text-status-error border-status-error/40 hover:bg-status-error/30":"";return qs.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:d=>d.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:i("common.cancel")}),s.jsx("button",{onClick:r,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,style:a==="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:n})]})]})}),document.body)}function S1(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),a=[...zj,...Kj,...Vj].find(r=>r.id===t||t.includes(r.id)||r.id.includes(t));return a?{icon:a.icon,name:a.name}:{icon:"",name:e}}function C1({ide:e,allIdes:t,sendDaemonCommand:n,onDisconnect:a,onRevokeToken:r}){var P,B;const{t:o}=ke("common"),[i,c]=l.useState("idle"),[d,p]=l.useState(""),[u,m]=l.useState(null),[f,g]=l.useState("idle"),[k,h]=l.useState(""),x=e.version||null,S=((P=e.machine)==null?void 0:P.platform)||((B=e.system)==null?void 0:B.platform)||"",b=ds(e,{fallbackId:e.id}),w=t.filter(R=>R.daemonId===e.id&&R.transport==="cdp-page"),C=t.filter(R=>R.daemonId===e.id&&R.transport==="pty"),v=t.filter(R=>R.daemonId===e.id&&R.transport==="acp"),y=e.p2p,j=async()=>{if(!n)return;const R=Co(e);if(!R){c("error"),p(vh);return}c("upgrading"),p(o("machine.connectedMachines.startingUpgrade"));try{const W=w1(await n(e.id,"daemon_upgrade",R));W.alreadyLatest?(c("done"),p(`Already on v${W.version||"latest"}.`)):W.upgraded||W.success?(c("done"),p(`Upgrade to v${W.version||"latest"} started. Daemon is restarting...`)):(c("error"),p(W.error||"Upgrade failed"))}catch(W){c("error"),p(Xo(W,"Connection lost during upgrade"))}},N=async()=>{if(m(null),!!a){g("loading");try{await a(e.id),g("done"),h(o("machine.connectedMachines.machineDisconnected"))}catch(R){g("error"),h(Xo(R,o("machine.connectedMachines.failedToDisconnect")))}}},T=async()=>{if(m(null),!!r){g("loading");try{await r(e.id),g("done"),h(o("machine.connectedMachines.tokenRevoked"))}catch(R){g("error"),h(Xo(R,o("machine.connectedMachines.failedToRevokeToken")))}}},A="1.0.55",I=Qs(e,A),D=So(e,I),M=Pa(e,I),E=w.length+C.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-text-muted",title:S,children:s.jsx(us,{size:18})}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:b}),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),"…"]}),x&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${D?"":"bg-bg-secondary"}`,style:D?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",x,!D&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[n&&D&&s.jsx("button",{onClick:j,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${A}`,children:i==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(ls,{size:12,thickness:2})," ",o("machine.connectedMachines.upgrading")]}):i==="done"?o("machine.connectedMachines.updated"):M?o("machine.connectedMachines.updateNow"):o("machine.connectedMachines.updateTo",{version:A})}),a&&s.jsx("button",{onClick:()=>m("disconnect"),disabled:f==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:o("machine.connectedMachines.disconnect")}),r&&s.jsx("button",{onClick:()=>m("revoke"),disabled:f==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:o("machine.connectedMachines.remove")}),s.jsx(f1,{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:[y&&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 ${y.state==="connected"?"bg-status-online":"bg-text-muted/30"} ${y.state==="connecting"||y.state==="new"?"animate-pulse":""}`,style:y.state==="connecting"||y.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",y.state==="connected"?"connected":y.state==="connecting"||y.state==="new"?o("machine.connectedMachines.connecting"):y.state||"off"]}),y.peers!==void 0&&y.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",y.peers," peer",y.peers!==1?"s":"",")"]})]}),y&&E>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),E>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[w.map(R=>{const W=S1(R.type),_=R.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx(Ya,{type:R.type,label:W.name,size:13}),s.jsx("span",{children:W.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:o(_?"machine.connectedMachines.cdpConnected":"machine.connectedMachines.cdpConnecting")})]},R.id)}),C.map(R=>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:R.cliName||"CLI"})]},R.id)),v.map(R=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{className:"inline-flex",children:s.jsx(Nb,{size:12})}),s.jsx("span",{children:R.cliName||"ACP"})]},R.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:o("machine.connectedMachines.noIdesConnected")})]}),(d||k)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||f==="error"?"text-status-error":i==="done"||f==="done"?"text-status-online":"text-text-muted"}`,children:k||d})]}),u==="disconnect"&&s.jsx(Ud,{title:o("machine.connectedMachines.disconnectTitle"),message:`Disconnect "${b}" 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
|
|
|
@@ -61,8 +61,8 @@ This will:
|
|
|
61
61
|
• Delete the machine registration
|
|
62
62
|
• Require running \`adhdev setup\` again on that machine
|
|
63
63
|
|
|
64
|
-
The machine's IDE, workspace and provider settings are kept.`,confirmLabel:o("machine.connectedMachines.remove"),confirmColor:"red",onConfirm:T,onCancel:()=>m(null)})]})}const j1=[{id:"dark",label:"Dark",icon:Tp},{id:"light",label:"Light",icon:Ap},{id:"system",label:"System",icon:Mp}];function N1(){const{preference:e,setPreference:t}=Ls();return s.jsx("div",{className:"flex gap-2",children:j1.map(n=>s.jsxs("button",{onClick:()=>t(n.id),className:`px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors flex items-center gap-1.5 ${e===n.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:e===n.id?{color:"var(--accent-on-primary)"}:void 0,children:[s.jsx(n.icon,{size:14}),n.label]},n.id))})}function A1(e){const t=e.trim();return/^#[0-9a-fA-F]{6}$/.test(t)?t:/^#[0-9a-fA-F]{3}$/.test(t)?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:null}function T1(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Zo(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Gd(e){const{r:t,g:n,b:a}=T1(e);return .2126*Zo(t)+.7152*Zo(n)+.0722*Zo(a)}function qd(e,t){const n=Gd(e),a=Gd(t),r=Math.max(n,a),o=Math.min(n,a);return(r+.05)/(o+.05)}function yh(e){const t=A1(e);if(!t)return"#111827";const n="#111827",a="#ffffff";return qd(t,n)>=qd(t,a)?n:a}const ll={bgPrimary:"#0a0e1a",bgSecondary:"#0f1320",surfacePrimary:"#111726",textPrimary:"#f0f0f5",textSecondary:"#9ca3af",textMuted:"#6b7280",borderSubtle:"#1d2536",borderDefault:"#313c52",accentColor:"#d97706",userBubble:"#f59e0b",userText:"#1a1a1a",assistantBubble:"#111726",assistantText:"#f0f0f5",containerBg:"#0f1320",sendButton:"#d97706",inputBorder:"#313c52",bubbleRadius:16},cl={bgPrimary:"#fff8ee",bgSecondary:"#fff1de",surfacePrimary:"#ffffff",textPrimary:"#24160f",textSecondary:"#6f6255",textMuted:"#938374",borderSubtle:"#e7d3ba",borderDefault:"#d7b892",accentColor:"#d97706",userBubble:"#f59e0b",userText:"#1a1a1a",assistantBubble:"#fffaf4",assistantText:"#24160f",containerBg:"#fff8ee",sendButton:"#d97706",inputBorder:"#d7b892",bubbleRadius:16},M1=[{id:"midnight",name:"Midnight",description:"Classic violet theme",preview:{dark:{userBubble:"#8b5cf6",assistantBubble:"#18181d",assistantBorder:"1px solid rgba(255,255,255,0.08)",containerBg:"#0f0f13",textColor:"rgba(255,255,255,0.7)"},light:{userBubble:"#7c3aed",assistantBubble:"#ffffff",assistantBorder:"1px solid rgba(0,0,0,0.08)",containerBg:"#f0f1f5",textColor:"#52525b"}}},{id:"ember",name:"Ember",description:"Default landing-inspired amber theme",preview:{dark:{userBubble:"#f59e0b",assistantBubble:"#111726",assistantBorder:"1px solid rgba(255,255,255,0.08)",containerBg:"#0a0e1a",textColor:"#9ca3af"},light:{userBubble:"#f59e0b",assistantBubble:"#fffaf4",assistantBorder:"1px solid rgba(146,64,14,0.10)",containerBg:"#fff8ee",textColor:"#6f6255"}}},{id:"aurora",name:"Aurora",description:"Pink accent theme",preview:{dark:{userBubble:"#ec4899",assistantBubble:"#1e1b2e",assistantBorder:"1px solid rgba(236,72,153,0.12)",containerBg:"#0f0d17",textColor:"rgba(255,255,255,0.7)"},light:{userBubble:"#ec4899",assistantBubble:"#fef2f8",assistantBorder:"1px solid rgba(236,72,153,0.15)",containerBg:"#f0f1f5",textColor:"#1a1a2e"}}},{id:"honey",name:"Honey",description:"Warm yellow accents",preview:{dark:{userBubble:"#fbbf24",assistantBubble:"#1c1c1e",assistantBorder:"1px solid rgba(255,255,255,0.06)",containerBg:"#111113",textColor:"rgba(255,255,255,0.7)"},light:{userBubble:"#fbbf24",assistantBubble:"#fffbeb",assistantBorder:"1px solid rgba(251,191,36,0.15)",containerBg:"#f0f1f5",textColor:"#1a1a2e"}}}],wh="adhdev-chat-theme",kh="adhdev-chat-theme-custom";function Mr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(wh)||"ember"}catch{return"ember"}}function bs(e){try{const t=localStorage.getItem(kh);if(t){const n=JSON.parse(t);return{...e==="dark"?ll:cl,...n[e]}}}catch{}return e==="dark"?ll:cl}function lr(e,t){try{localStorage.setItem(kh,JSON.stringify({dark:e,light:t}))}catch{}}function as(e,t){const n=parseInt(e.slice(1,3),16),a=parseInt(e.slice(3,5),16),r=parseInt(e.slice(5,7),16);return`rgba(${n}, ${a}, ${r}, ${t})`}function Jr(e,t){const n=Math.min(255,parseInt(e.slice(1,3),16)+t),a=Math.min(255,parseInt(e.slice(3,5),16)+t),r=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}`}const P1={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Da(e,t){var r;const n=(r=P1[e])==null?void 0:r[t];if(!n)return;const a=document.documentElement;a.style.setProperty("--accent-primary",n),a.style.setProperty("--accent-primary-light",Jr(n,24)),a.style.setProperty("--accent-on-primary",yh(n)),a.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${n}, ${Jr(n,18)})`),a.style.setProperty("--border-accent",as(n,.35)),a.style.setProperty("--nav-active-bg",as(n,.1)),a.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${n}, 0 0 12px ${as(n,.06)}`)}function Sn(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",as(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",as(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",as(e.borderSubtle,.25)),t.style.setProperty("--text-primary",e.textPrimary),t.style.setProperty("--text-secondary",e.textSecondary),t.style.setProperty("--text-muted",e.textMuted),t.style.setProperty("--border-subtle",as(e.borderSubtle,.5)),t.style.setProperty("--border-default",as(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",Jr(e.accentColor,30)),t.style.setProperty("--accent-on-primary",yh(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Jr(e.accentColor,40)})`),t.style.setProperty("--border-accent",as(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",as(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${as(e.accentColor,.06)}`),t.style.setProperty("--chat-user-bg",e.userBubble),t.style.setProperty("--chat-user-color",e.userText),t.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),t.style.setProperty("--chat-assistant-bg",e.assistantBubble),t.style.setProperty("--chat-assistant-color",e.assistantText),t.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),t.style.setProperty("--chat-assistant-border",`1px solid ${as(e.accentColor,.12)}`),t.style.setProperty("--chat-container-bg",e.containerBg),t.style.setProperty("--dashboard-pane-bg",e.containerBg),t.style.setProperty("--chat-thought-accent",e.accentColor),t.style.setProperty("--chat-tool-accent",e.accentColor),t.style.setProperty("--chat-action-color",e.accentColor),t.style.setProperty("--chat-send-bg",e.sendButton),t.style.setProperty("--chat-input-border",e.inputBorder)}function rc(){const e=document.documentElement;["--bg-primary","--bg-secondary","--bg-card","--surface-primary","--surface-secondary","--bg-glass","--bg-glass-hover","--text-primary","--text-secondary","--text-muted","--border-subtle","--border-default","--accent-primary","--accent-primary-light","--accent-on-primary","--accent-gradient","--border-accent","--nav-active-bg","--nav-active-shadow","--chat-user-bg","--chat-user-color","--chat-user-radius","--chat-assistant-bg","--chat-assistant-color","--chat-assistant-radius","--chat-assistant-border","--chat-container-bg","--dashboard-pane-bg","--chat-thought-accent","--chat-tool-accent","--chat-action-color","--chat-send-bg","--chat-input-border"].forEach(n=>e.style.removeProperty(n))}function D1(e){try{localStorage.setItem(wh,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=Cn()?"dark":"light";Sn(bs(t))}else rc(),Da(e,Cn()?"dark":"light")}function I1(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Mr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=Cn()?"dark":"light";Sn(bs(t))}else rc(),Da(e,Cn()?"dark":"light")}function Cn(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Gt({label:e,value:t,onChange:n}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[s.jsx("input",{type:"color",value:t,onChange:a=>n(a.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),s.jsx("input",{type:"text",value:t,onChange:a=>{/^#[0-9a-fA-F]{0,6}$/.test(a.target.value)&&n(a.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function ba({title:e,children:t}){return s.jsxs("div",{style:{marginBottom:14},children:[s.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:e}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:t})]})}function L1({dark:e,onColorsChange:t}){const{t:n}=ke("common"),a=e?"dark":"light",[r,o]=l.useState(()=>bs(a));l.useEffect(()=>{o(bs(a))},[a]);const i=l.useCallback((c,d)=>{o(p=>{const u={...p,[c]:d},f=bs(a==="dark"?"light":"dark");return a==="dark"?lr(u,f):lr(f,u),Sn(u),t(u),u})},[a,t]);return s.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[s.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[n("settings.theme.customEditorTitle"),s.jsx("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:n(e?"settings.theme.darkMode":"settings.theme.lightMode")})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs(ba,{title:n("settings.theme.sectionAppBackground"),children:[s.jsx(Gt,{label:n("settings.theme.colorBackground"),value:r.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(Gt,{label:n("settings.theme.colorSurface"),value:r.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(Gt,{label:n("settings.theme.colorCard"),value:r.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(ba,{title:n("settings.theme.sectionAppText"),children:[s.jsx(Gt,{label:n("settings.theme.colorPrimary"),value:r.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(Gt,{label:n("settings.theme.colorSecondary"),value:r.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(Gt,{label:n("settings.theme.colorMuted"),value:r.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(ba,{title:n("settings.theme.sectionBordersAccent"),children:[s.jsx(Gt,{label:n("settings.theme.colorBorderSubtle"),value:r.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(Gt,{label:n("settings.theme.colorBorderDefault"),value:r.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(Gt,{label:n("settings.theme.colorAccent"),value:r.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(ba,{title:n("settings.theme.sectionChatBubbles"),children:[s.jsx(Gt,{label:n("settings.theme.colorUserBubble"),value:r.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(Gt,{label:n("settings.theme.colorUserText"),value:r.userText,onChange:c=>i("userText",c)}),s.jsx(Gt,{label:n("settings.theme.colorAgentBubble"),value:r.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(Gt,{label:n("settings.theme.colorAgentText"),value:r.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(ba,{title:n("settings.theme.sectionChatLayout"),children:[s.jsx(Gt,{label:n("settings.theme.colorChatBg"),value:r.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(Gt,{label:n("settings.theme.colorSendButton"),value:r.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(Gt,{label:n("settings.theme.colorInputBorder"),value:r.inputBorder,onChange:c=>i("inputBorder",c)}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:n("settings.theme.labelBubbleRadius")}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[s.jsx("input",{type:"range",min:4,max:24,value:r.bubbleRadius,onChange:c=>i("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),s.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[r.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const c=e?ll:cl,p=bs(e?"light":"dark");e?lr(c,p):lr(p,c),o(c),Sn(c),t(c)},style:{marginTop:10,fontSize:"0.7rem",color:"var(--text-muted)",background:"transparent",border:"1px solid var(--border-subtle)",borderRadius:6,padding:"4px 10px",cursor:"pointer"},children:n("settings.theme.resetToDefaults")})]})}function R1(){const{t:e}=ke("common"),[t,n]=l.useState(Mr),[a,r]=l.useState(!0),[o,i]=l.useState(()=>bs("dark"));l.useEffect(()=>{r(Cn());const p=new MutationObserver(()=>{const f=Cn();r(f);const g=Mr();g==="custom"?Sn(bs(f?"dark":"light")):Da(g,f?"dark":"light")});p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const u=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const f=Cn();r(f);const g=Mr();g==="custom"?Sn(bs(f?"dark":"light")):Da(g,f?"dark":"light")};return u.addEventListener("change",m),()=>{p.disconnect(),u.removeEventListener("change",m)}},[]),l.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?Sn(bs(a?"dark":"light")):(rc(),Da(t,a?"dark":"light"))},[t,a]),l.useEffect(()=>{i(bs(a?"dark":"light"))},[a]);const c=p=>{n(p),D1(p)},d=[...M1,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText},light:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:d.map(p=>{const u=t===p.id,m=a?p.preview.dark:p.preview.light,f=p.id==="honey"||p.id==="ember"?"#1a1a1a":p.id==="custom"?o.userText:"#fff";return s.jsxs("button",{onClick:()=>c(p.id),className:"text-left rounded-xl p-3 transition-all",style:{background:u?"var(--bg-glass-hover)":"var(--bg-glass)",border:u?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:u?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:m.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:e("settings.theme.helloHelp")}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.userBubble,color:f},children:e("settings.theme.fixBug")}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:e("settings.theme.onIt")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[u&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:p.id==="custom"?e("settings.theme.customLabel"):p.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:p.description})]})]})]},p.id)})}),t==="custom"&&s.jsx(L1,{dark:a,onColorsChange:p=>i(p)})]})}const oc="adhdev_mobileDashboardMode_v1",dl="adhdev:mobile-dashboard-mode-change";function ic(){try{return localStorage.getItem(oc)==="workspace"?"workspace":"chat"}catch{return"chat"}}function E1(e){if(typeof window>"u")return()=>{};const t=r=>{e(r??ic())},n=r=>{const o=r.detail;t(o)},a=r=>{r.key&&r.key!==oc||t()};return window.addEventListener(dl,n),window.addEventListener("storage",a),()=>{window.removeEventListener(dl,n),window.removeEventListener("storage",a)}}function _1(e){try{localStorage.setItem(oc,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(dl,{detail:e}))}function H1(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(ic()==="chat")},[]),s.jsx(bn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ds,{size:15})," Mobile Inbox (Chat Mode)"]}),description:e?"Use the chat-first mobile inbox layout. This keeps mobile closer to a messaging app.":"Use the full workspace layout on phones and tablets.",checked:e,onChange:n=>{t(n),_1(n?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const $1="Choose a preset or create a fully custom theme. Custom themes control the entire app — backgrounds, text, borders, and chat bubbles.",F1="Choose whether the dashboard opens like a chat app on phones or keeps the full workspace layout.";function B1({themeDescription:e=$1,mobileDescription:t=F1,fontsSlot:n}){const{t:a}=ke("common");return s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:a("settings.appearance.modeLabel")}),s.jsx(N1,{})]}),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:a("settings.appearance.themeLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:e}),s.jsx(R1,{})]}),n,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:a("settings.appearance.mobileLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:t}),s.jsx(H1,{})]})]})}const ei=new Map,zd=new Map;function W1(e){if(!e||typeof e!="object")return null;const t=e,n=t.result&&typeof t.result=="object"?t.result:t,a=n.machine;return!a||typeof a!="object"?null:{machine:a,timestamp:typeof n.timestamp=="number"?n.timestamp:void 0}}function O1(e,t,n,a){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:a,platform:n.platform,machine:n}}function Sh(){const{sendCommand:e}=St(),{injectEntries:t,getIdes:n}=Ra();return l.useCallback(async(a,r)=>{if(!a)return;const o=(r==null?void 0:r.minFreshMs)??qS,i=zd.get(a)||0;if(!(r!=null&&r.force)&&i>0&&Date.now()-i<o)return;const c=ei.get(a);if(c)return c;const d=(async()=>{const p=await e(a,"get_machine_runtime_stats"),u=W1(p);if(!u)return;const m=n().find(g=>g.id===a),f=O1(m,a,u.machine,u.timestamp||Date.now());t([f]),zd.set(a,Date.now())})().finally(()=>{ei.delete(a)});return ei.set(a,d),d},[n,t,e])}function U1(e,t,n){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:n.timestamp,platform:n.machine.platform,machine:{...(e==null?void 0:e.machine)||{},...n.machine}}}function G1(e,t){const{sendData:n}=St(),{injectEntries:a,getIdes:r}=Ra(),o=Array.from(new Set(e.filter(Boolean))).join("|");l.useEffect(()=>{if(!(t!=null&&t.enabled)||!n)return;const i=o?o.split("|"):[];if(i.length===0)return;const c=i.map(d=>ys.subscribe({sendData:n},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const m=r().find(g=>g.id===d),f=U1(m,d,u);a([f])}));return()=>{c.forEach(d=>d())}},[o,r,a,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,n])}function q1(e,t){const{sendData:n}=St(),[a,r]=l.useState(null),[o,i]=l.useState(!1);return l.useEffect(()=>{if(!e){r(null),i(!1);return}if(!(t!=null&&t.enabled)||!n){i(!1);return}r(null),i(!0);let c=null;const d=ys.subscribe({sendData:n},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},p=>{c&&(clearTimeout(c),c=null),r(p.diagnostics),i(!1)});return d.initialSendAccepted?c=setTimeout(()=>{i(!1)},VS):i(!1),()=>{c&&clearTimeout(c),d()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,n]),{diagnostics:a,loading:o,applyDiagnostics:r}}function z1(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Ch(e){const{sendData:t}=St(),[n,a]=l.useState({});return l.useEffect(()=>{const r=z1(e);if(!r||!e.sessionId||!t){a({});return}const o=ys.subscribe({sendData:t},r,{type:"subscribe",topic:"session.modal",key:`daemon:${r}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},i=>{a({status:i.status,modalMessage:i.modalMessage,modalButtons:i.modalButtons}),Zn.record({interactionId:i.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:i.status,modalButtonCount:Array.isArray(i.modalButtons)?i.modalButtons.length:0}})});return o.initialSendAccepted||a({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,t]),n}function K1(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function V1(e){const t=(e==null?void 0:e.result)??e;return typeof(t==null?void 0:t.error)=="string"?t.error:"Interactive prompt response failed"}async function Y1(e,t,n){const a=await n(`/api/v1/sessions/${encodeURIComponent(e)}/interactive-prompt/resolve`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(!a.ok){let r=`HTTP ${a.status}`;try{const o=await a.json();typeof(o==null?void 0:o.error)=="string"&&(r=o.error)}catch{}throw new Error(r)}}async function Q1({promptSession:e,response:t,useP2PCommand:n,sendCommand:a,fetchImpl:r=fetch}){if(n){const o=await a(e.routeId,"interactive_prompt_response",{targetSessionId:e.sessionId,sessionId:e.sessionId,response:t});if(!K1(o))throw new Error(V1(o));return}await Y1(e.sessionId,t,r)}function jh(e){const{ides:t,isP2PActive:n,p2pStates:a}=Ss(),{sendCommand:r}=St(),[o,i]=l.useState(null),[c,d]=l.useState(!1),[p,u]=l.useState(null),m=l.useRef(!1),f=l.useMemo(()=>yx(t,e),[t,e]),g=!!f,k=l.useMemo(()=>f?f.prompt.promptId===o?null:f:null,[o,f]),h=l.useCallback(async b=>{if(!k||m.current)return;m.current=!0;const w=qp(k.prompt,b);d(!0),u(null);try{const C=(a==null?void 0:a[k.daemonId])==="connected"||n===!0;await Q1({promptSession:k,response:w,useP2PCommand:C,sendCommand:r}),i(k.prompt.promptId)}catch(C){throw u(C instanceof Error?C.message:String(C)),C}finally{d(!1),m.current=!1}},[n,a,k,r]),x=l.useCallback(()=>{k&&i(k.prompt.promptId)},[k]),S=l.useCallback(()=>{i(null),u(null)},[]);return{promptSession:k,hasActivePrompt:g,responseError:p,isSubmitting:c,submit:h,cancel:x,reopen:S}}function Nh(e){return e instanceof Error?e.message:String(e||"")}function J1(e){const t=Nh(e);return t.includes("P2P command timeout")||t.includes("P2P not connected")||t.includes("P2P channel not open")||t.includes("P2P not available")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}function X1(e){const t=Nh(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Ah({conversation:e,mode:t,ides:n,sendDaemonCommand:a,setCliViewModeOverrides:r}){if(!e||!bt(e)||ht(e))return;const o=la(e);if(o===t)return;const i=e.sessionId;i&&r(c=>({...c,[i]:t}));try{await a(Ks(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Ps(e),mode:t})}catch(c){const d=X1(c);i&&!d&&r(p=>{const u={...p};return o===eN(n,i)?delete u[i]:u[i]=o,u}),J1(c)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",c instanceof Error?c.message:String(c)):console.error("Failed to switch CLI view mode:",c)}}function Kd(e,t){const n=typeof e.sessionId=="string"&&e.sessionId?e.sessionId:typeof e.id=="string"?e.id:"";if(!n||e.transport!=="pty")return e;const a=t[n];return!a||e.mode===a?e:{...e,mode:a}}function Z1(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let n=!1;const a=e.map(r=>{const o=Kd(r,t),i=Array.isArray(r.childSessions)?r.childSessions.map(d=>Kd(d,t)):r.childSessions,c=i!==r.childSessions;return o!==r||c?(n=!0,{...o,...c?{childSessions:i}:{}}):r});return n?a:e}function eN(e,t){if(!t)return null;for(const n of e){if(n.sessionId===t&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal";for(const a of n.childSessions||[])if(a.id===t&&a.transport==="pty")return a.mode==="chat"?"chat":"terminal"}return null}function tN({visibleConversations:e,clearedTabs:t,setClearedTabs:n,setActionLogs:a,isConversationMuted:r}){l.useEffect(()=>{dm()},[]);const o=l.useMemo(()=>e.map(i=>({id:i.tabKey,name:Jm(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null,target:{providerSessionId:i.providerSessionId,sessionId:i.sessionId,tabKey:i.tabKey,routeId:i.routeId},muted:r?r(i):!1})),[e,r]);return pk(o),l.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{n(d=>{const p=Date.now(),u={};for(const[m,f]of Object.entries(d))p-f<5e3&&(u[m]=f);return Object.keys(u).length===Object.keys(d).length?d:u})},5500);return()=>clearTimeout(c)},[t,n]),l.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;a(d=>{const p=d.filter(u=>u.timestamp>c).slice(-100);return p.length===d.length?d:p})},6e4);return()=>clearInterval(i)},[a]),null}function Vd(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function jn(e){const t=[...e.messages].reverse().find(r=>!(r!=null&&r._localId))||e.messages[e.messages.length-1],n=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,a=Vd(t==null?void 0:t.receivedAt)||Vd(t==null?void 0:t.timestamp)||0;return Math.max(n,a)}function ul(e,t=0){return jn(e)||e.lastUpdated||t||0}function Th(e){return jn(e)||e.lastUpdated||0}function Mh(e,t,n=Th){const a=n(t)-n(e);if(a!==0)return a;const r=(e.machineName||"").localeCompare(t.machineName||"");if(r!==0)return r;const o=e.displayPrimary.localeCompare(t.displayPrimary);if(o!==0)return o;const i=e.displaySecondary.localeCompare(t.displaySecondary);return i!==0?i:e.tabKey.localeCompare(t.tabKey)}function pl(e){var n;const t=os(e.status,{activeModal:(n=e.modalButtons)!=null&&n.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function sN(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!pl(e)&&!e.title.trim()}function nN(e){return e.length===0?null:[...e].sort((t,n)=>{const a=Number(pl(n))-Number(pl(t));if(a!==0)return a;const r=n.messages.length-t.messages.length;return r!==0?r:Mh(t,n)})[0]||null}function ws(e,t){const n=e.filter(i=>i.routeId===t);if(n.length===0)return null;const a=n.find(i=>i.streamSource==="native")||null,r=n.filter(i=>i.streamSource==="agent-stream"),o=nN(r);return a?o&&sN(a)?o:a:o||n[0]||null}function aN(e){const t=e.filter(r=>r.type!=="adhdev-daemon"),n=new Set;for(const r of t){if(!Ji(r))continue;const o=am(r);o&&n.add(o)}const a=new Map;for(const r of t){const o=O0(r,n),i=a.get(o);if(!i){a.set(o,r);continue}const c=m=>(m.workspace?1:0)+(m.activeChat?1:0)+(m.lastMessagePreview?1:0),d=c(i),p=c(r),u=p>d||p===d&&(r.timestamp||0)>(i.timestamp||0)?r:i;a.set(o,rN(u,u===r?i:r))}return Array.from(a.values())}function rN(e,t){const n=Ji(t),a=Ji(e);if(!n&&!a)return e;const r=a?n?void 0:t:e,o=a?e:n?t:void 0,i=r&&String(r.daemonId||"").trim()||String(e.ownerDaemonId||"").trim()||String(t.ownerDaemonId||"").trim()||void 0,c=String(e.ownerMachineName||"").trim()||String(t.ownerMachineName||"").trim()||void 0,d=o==null?void 0:o.settings;return{...e,...i&&{ownerDaemonId:i},...c&&!e.ownerMachineName&&{ownerMachineName:c},...d&&!a&&{settings:{...d,...e.settings??{}}}}}function ti(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function oN(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function Yd(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],n=t[t.length-1],a=n?oN(ea(n.content)):"";return[e.id||"",e.title||"",e.status||"",t.length,String((n==null?void 0:n.id)||""),String((n==null?void 0:n.index)??""),String((n==null?void 0:n.receivedAt)??(n==null?void 0:n.timestamp)??""),a].join(":")}function iN(e){const t=Array.isArray(e.childSessions)?e.childSessions:[];return[e.id,e.sessionId||"",e.providerSessionId||"",e.transport||"",e.mode||"",e.status||"",e.workspace||"",e.lastMessageHash||"",String(e.lastMessageAt||""),e.lastMessagePreview||"",e.lastMessageRole||"",String(e.lastUpdated||""),Yd(e.activeChat),...t.map(n=>[n.id||"",n.providerSessionId||"",n.transport||"",n.mode||"",n.status||"",n.title||"",n.lastMessageHash||"",String(n.lastMessageAt||""),n.lastMessagePreview||"",n.lastMessageRole||"",String(n.lastUpdated||""),Yd(n.activeChat)].join(":"))].join("|")}function lN(e,t){const n=Date.now();return e.map(a=>{const r=t[a.tabKey];return r&&n-r<5e3?{...a,messages:[],title:""}:a})}function cN(e,t){const n=new Map;for(const a of e){const r=t.get(a.routeId)||a;for(const o of Ta({routeId:a.routeId}))n.set(o,r);for(const o of Ta({providerSessionId:a.providerSessionId,sessionId:a.sessionId}))n.set(o,a.streamSource==="native"?r:a);for(const o of Ta({tabKey:a.tabKey}))n.set(o,a)}return n}function dN(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function uN(e){const t=dN(e);if(!t)return`empty:${e.messages.length}`;if(t.id)return`id:${String(t.id)}`;if(t._localId)return`local:${String(t._localId)}`;const n=String(t.role||""),a=ea(t.content).slice(0,240);return`${e.messages.length}:${n}:${a}`}function pN({ides:e,connectionStates:t,clearedTabs:n}){const a=l.useMemo(()=>aN(e),[e]),r=l.useMemo(()=>Vp(e),[e]),o=l.useMemo(()=>lh(e),[e]),i=l.useRef([]),c=l.useRef([]),d=l.useRef([]),p=l.useRef(new Map),u=l.useRef(new Map),m=l.useMemo(()=>{const C=new Map,v=[];for(const T of a){const{connectionState:A="new",machineName:I}=ch(T,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),D=iN(T),M=p.current.get(T.id);if(M&&M.ide===T&&M.sourceSignature===D&&M.connectionState===A&&M.machineName===I){C.set(T.id,M),v.push(...M.conversations);continue}const E=nc(T,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),P={ide:T,sourceSignature:D,connectionState:A,machineName:I,conversations:E};C.set(T.id,P),v.push(...E)}p.current=C;const y=new Map,j=T=>{const A=uN(T),I=u.current.get(T.tabKey);if(I&&I.signature===A)return y.set(T.tabKey,I),I.timestamp;const D={signature:A,timestamp:Th(T)||(I==null?void 0:I.timestamp)||0};return y.set(T.tabKey,D),D.timestamp},N=[...v].sort((T,A)=>Mh(T,A,j));return u.current=y,N},[a,t,o]),f=l.useMemo(()=>{const C=lN(m,n);return ti(i.current,C)?i.current:(i.current=C,C)},[m,n]),g=l.useMemo(()=>{const C=new Map,v=Array.from(new Set(f.map(y=>y.routeId)));for(const y of v){const j=ws(f,y);j&&C.set(y,j)}return C},[f]),k=l.useMemo(()=>{const C=new Map;for(const v of f){const y=g.get(v.routeId),j=v.streamSource==="native"&&y?y:v;for(const N of Ta({providerSessionId:v.providerSessionId,sessionId:v.sessionId,tabKey:v.tabKey}))C.set(N,j)}return C},[f,g]),h=l.useMemo(()=>cN(f,g),[f,g]),x=l.useCallback(C=>{if(C)return k.get(C)},[k]),S=l.useCallback(C=>{if(C)return h.get(C)},[h]),b=l.useMemo(()=>{const C=f.filter(v=>!an(v,r).surfaceHidden);return ti(c.current,C)?c.current:(c.current=C,C)},[f,r]),w=l.useMemo(()=>{const C=b.map(v=>v.tabKey);return ti(d.current,C)?d.current:(d.current=C,C)},[b]);return{chatIdes:a,conversations:f,visibleConversations:b,visibleTabKeys:w,resolveConversationBySessionId:x,resolveConversationByTarget:S}}function mN({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:n,setSearchParams:a}){const r=l.useMemo(()=>{var c;return e||!t?null:((c=n(t))==null?void 0:c.tabKey)??null},[e,n,t]),o=l.useMemo(()=>{var c;return!e||!t?null:((c=n(t))==null?void 0:c.tabKey)??null},[e,n,t]),i=l.useCallback(()=>{t&&a(c=>{const d=new URLSearchParams(c);return d.delete("activeTab"),d},{replace:!0})},[a,t]);return{requestedDesktopTabKey:r,requestedMobileTabKey:o,consumeRequestedActiveTab:i}}function hN({ides:e,sendDaemonCommand:t,setToasts:n,resolveConversationByTarget:a}){l.useEffect(()=>{ft.setIdes(e)},[e]),l.useEffect(()=>{ft.setResolveAction((r,o,i)=>{t(r,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const r=ft.onToast(o=>{n(c=>c.some(p=>p.message===o.message&&o.timestamp-p.timestamp<3e3)?c:[...c.slice(-4),{id:o.id,message:o.message,type:o.type,timestamp:o.timestamp,targetKey:o.targetKey,actions:o.actions}]);const i=o.duration||5e3;setTimeout(()=>n(c=>c.filter(d=>d.id!==o.id)),i)});return()=>{r()}},[n]),l.useEffect(()=>{const r=Km.on("status_event",o=>{ft.handleRawEvent(o,"ws")});return()=>{r()}},[]),l.useEffect(()=>{var o;const r=i=>{var h;const c=i.data;if((c==null?void 0:c.type)!=="notification_action"||typeof c.action!="string"||!c.action.startsWith("approval_")||!(c.daemonId||c.targetSessionId||c.targetKey))return;const d=c.targetSessionId||c.targetKey||c.daemonId,p=a(d),u=(p==null?void 0:p.routeId)||c.daemonId;if(!u)return;const m=Number(c.buttonIndex),f=c.button||((h=p==null?void 0:p.modalButtons)==null?void 0:h[m])||"Approve",g=String(f).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),k=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(g);t(u,"resolve_action",{action:k?"approve":"reject",button:f,...Number.isFinite(m)&&{buttonIndex:m},...(p==null?void 0:p.sessionId)&&{targetSessionId:p.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(x=>console.error("[SW Action] approval failed:",x))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",r),()=>{var i;return(i=navigator.serviceWorker)==null?void 0:i.removeEventListener("message",r)}},[a,t])}const fN="adhdev_dashboardLayout_v1",gN="adhdev_dashboardDockview_v1",bN="adhdev_dashboardDockviewHiddenRestore_v1",xa={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function lc(e,t){try{const n=localStorage.getItem(e);return n?JSON.parse(n):t}catch{return t}}function xN(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Ph(e){return`${fN}:${e}`}function vN(e){const t=Ph(e);return lc(t,null)}function yN(e,t){try{const n=t.groupAssignments.length===0&&t.focusedGroup===0&&Object.keys(t.groupActiveTabIds).length===0&&Object.keys(t.groupTabOrders).length===0&&t.groupSizes.length===0,a=Ph(e);if(n){localStorage.removeItem(a);return}localStorage.setItem(a,JSON.stringify(t))}catch{}}function Dh(e){return`${gN}:${e}`}function wN(e){const t=Dh(e);return lc(t,null)}function kN(e,t){try{const n=Dh(e);if(!t){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Ih(e){return`${bN}:${e}`}function SN(e){const t=Ih(e);return lc(t,{})}function CN(e,t){try{const n=Ih(e);if(Object.keys(t).length===0){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function jN(){return{groupAssignments:[...xa.groupAssignments],focusedGroup:xa.focusedGroup,groupActiveTabIds:{...xa.groupActiveTabIds},groupTabOrders:{...xa.groupTabOrders},groupSizes:[...xa.groupSizes]}}function NN(e,t){return e?e.length===t.length&&e.every((n,a)=>n===t[a]):t.length===0}function AN(){const[e]=l.useState(()=>xN(typeof window<"u"?window.innerWidth:1280)),[t,n]=l.useState(()=>new Map),[a,r]=l.useState(0),[o,i]=l.useState({}),[c,d]=l.useState({}),[p,u]=l.useState([]),[m,f]=l.useState(()=>typeof window<"u"&&window.innerWidth<768),[g,k]=l.useState(!1),h=l.useCallback(()=>{if(g)return;const T=vN(e)??jN();n(new Map(T.groupAssignments)),r(T.focusedGroup),i(T.groupActiveTabIds),d(T.groupTabOrders),u(T.groupSizes),k(!0)},[g,e]);l.useEffect(()=>{g&&yN(e,{groupAssignments:[...t.entries()],focusedGroup:a,groupActiveTabIds:o,groupTabOrders:c,groupSizes:p})},[g,e,t,a,o,c,p]),l.useEffect(()=>{const T=window.matchMedia("(max-width: 767px)"),A=I=>f(I.matches);return T.addEventListener("change",A),()=>T.removeEventListener("change",A)},[]);const x=l.useCallback(T=>{n(T)},[]),S=l.useCallback(T=>{r(T)},[]),b=l.useCallback(T=>{i(T)},[]),w=l.useCallback(T=>{d(T)},[]),C=l.useCallback(T=>{u(T)},[]),v=l.useCallback(T=>{S(T)},[S]),y=l.useCallback((T,A)=>{i(I=>(I[T]??null)===(A??null)?I:{...I,[T]:A})},[]),j=l.useCallback((T,A)=>{d(I=>{const D=I[T];return NN(D,A)?I:{...I,[T]:A}})},[]),N=l.useCallback((T,A)=>{const I=A.get(T)??0;return y(I,T),v(I),I},[v,y]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:x,focusedGroup:a,updateFocusedGroup:S,focusGroup:v,groupActiveTabIds:o,updateGroupActiveTabIds:b,setGroupActiveTab:y,groupTabOrders:c,updateGroupTabOrders:w,setGroupTabOrder:j,groupSizes:p,updateGroupSizes:C,isMobile:m,hasHydratedStoredLayout:g,hydrateStoredLayout:h,focusConversationTab:N}}function TN(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0],a=go(t);return typeof(n==null?void 0:n.id)=="string"&&a.includes(n.id)}function MN({urlActiveTab:e,conversations:t,resolveConversationBySessionId:n,normalizedGroupAssignments:a,hasHydratedStoredLayout:r,hydrateStoredLayout:o,focusConversationTab:i,setSearchParams:c,historyModalOpen:d,activeConv:p,isRefreshingHistory:u,ides:m,handleRefreshHistory:f}){const g=l.useRef(!1),k=l.useRef(!1),h=l.useRef(null),x=l.useRef(!1);l.useEffect(()=>{if(!e||g.current||t.length===0)return;if(!r){o();return}const S=n(e);S&&(i(S.tabKey,a),g.current=!0,k.current=!0,h.current!=null&&(window.clearTimeout(h.current),h.current=null),c(b=>{const w=new URLSearchParams(b);return w.delete("activeTab"),w},{replace:!0}))},[e,t,n,a,r,o,i,c]),l.useEffect(()=>{if(!(k.current||r)&&t.length!==0){if(!e){o(),k.current=!0;return}if(g.current){k.current=!0;return}if(h.current==null)return h.current=window.setTimeout(()=>{h.current=null,!(k.current||r)&&(o(),k.current=!0)},1500),()=>{h.current!=null&&(window.clearTimeout(h.current),h.current=null)}}},[e,t.length,r,o]),l.useEffect(()=>{if(!d){x.current=!1;return}if(!p||x.current||u)return;const S=m.find(b=>b.id===p.routeId);S&&(!S.chats||S.chats.length===0||TN(S.chats,p))&&(x.current=!0,f())},[d,p,u,m,f])}function si(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0];if((n==null?void 0:n.active)===!0)return!0;const a=go(t);return typeof(n==null?void 0:n.id)=="string"&&a.includes(n.id)}function Lh({sendDaemonCommand:e,activeConv:t,chats:n,updateRouteChats:a,setToasts:r,setClearedTabs:o}){const[i,c]=l.useState(!1),[d,p]=l.useState(!1),u=l.useCallback(async k=>{try{await e("standalone","launch_ide",{ideType:k,enableCdp:!0})}catch(h){console.error("Launch failed",h)}},[e]),m=l.useCallback(async(k,h)=>{try{const x=k||(t==null?void 0:t.daemonId)||"",S=await e(x,"switch_chat",{id:h,sessionId:h,...yn(t)}),b=S==null?void 0:S.result;if((S==null?void 0:S.success)===!0||b==="switched"||b==="switched-by-title")return;b===!1||b==="not_found"?Gn(r,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?Gn(r,`⚠️ Switch error: ${b}`):Gn(r,"⚠️ Session switch failed")}catch(x){console.error("Switch failed",x),Gn(r,`❌ Switch failed: ${x.message||"connection error"}`)}},[t,e,r]),f=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const k=wn(t);await e(k,"new_chat",{...yn(t)}),mC(k,t.sessionId,go(t)[0]),o(h=>({...h,[t.tabKey]:Date.now()}))}catch(k){console.error("New chat failed",k)}finally{c(!1)}}},[t,i,e,o]),g=l.useCallback(async()=>{var k,h;if(!(!t||d)){p(!0);try{const x=wn(t),S=async()=>e(x,"list_chats",{forceExpand:!0,...yn(t)});let b=await S(),w=(b==null?void 0:b.chats)||((k=b==null?void 0:b.result)==null?void 0:k.chats);si(w,t)&&(await new Promise(C=>setTimeout(C,450)),b=await S(),w=(b==null?void 0:b.chats)||((h=b==null?void 0:b.result)==null?void 0:h.chats)),b!=null&&b.success&&Array.isArray(w)&&(a(t.routeId,w),si(w,t)&&!si(n,t)&&Gn(r,"⚠️ History dialog did not fully open — try once more"))}catch(x){console.error("Refresh history failed",x)}finally{p(!1)}}},[t,n,d,e,a,r]);return{isCreatingChat:i,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:m,handleNewChat:f,handleRefreshHistory:g}}function PN(e,t){if(e.size!==t.size)return!1;for(const[n,a]of e)if(t.get(n)!==a)return!1;return!0}function DN(e,t){return e.length!==t.length?!1:e.every((n,a)=>n===t[a])}function Qd(e,t){const n=Object.keys(e),a=Object.keys(t);return n.length!==a.length?!1:n.every(r=>t[Number(r)]===e[Number(r)])}function cr(e,t){const n=new Set(t),a=t.length>0?[0]:[];for(const[i,c]of e)!n.has(i)||c<=0||a.includes(c)||a.push(c);a.sort((i,c)=>i-c);const r={};a.forEach((i,c)=>{r[i]=c}),a.length===0&&(r[0]=0);const o=new Map;for(const[i,c]of e){if(!n.has(i)||c<=0)continue;const d=r[c];typeof d=="number"&&d>0&&o.set(i,d)}return{assignments:o,groupCount:Math.max(1,a.length),mapping:r,usedGroups:a}}function Jd(e,t){const n={};for(const[a,r]of Object.entries(e)){const o=t[Number(a)];typeof o=="number"&&(n[o]=r)}return n}function IN(e,t,n){if(t.length===0)return 0;if(typeof n[e]=="number")return n[e];const a=[...t].reverse().find(r=>r<e)??t[0];return n[a]??0}function LN(e,t,n){if(t.length<=1)return[];const a=t.map(i=>e[i]).filter(i=>Number.isFinite(i)),r=a.length===t.length?a:Array(n).fill(100/n),o=r.reduce((i,c)=>i+c,0);return o>0?r.map(i=>i/o*100):Array(n).fill(100/n)}function Xd(e,t){const n={};for(const[a,r]of Object.entries(e)){const o=Number(a);n[o>=t?o+1:o]=r}return n}function Zd(e){return Array(e).fill(100/e)}function RN({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:n,updateGroupActiveTabIds:a,updateGroupTabOrders:r,groupSizes:o,updateGroupSizes:i,isMobile:c,visibleConversations:d,visibleTabKeys:p}){const u=l.useRef(null),m=l.useMemo(()=>cr(e,p),[e,p]),f=m.assignments,g=l.useMemo(()=>c?1:m.groupCount,[m.groupCount,c]),k=g>1,h=l.useCallback((v,y)=>{t(j=>{const N=new Map(cr(j,p).assignments);return y===0?N.delete(v):N.set(v,y),N}),a(j=>({...j,[y]:v})),n(y)},[t,p,a,n]),x=l.useCallback(v=>{t(y=>{const j=cr(y,p).assignments,N=new Map;for(const[T,A]of j)A!==v&&(A>v?N.set(T,A-1):N.set(T,A));return N}),i(y=>{if(y.length<=1)return[];const j=[...y];j.splice(v,1);const N=j.reduce((T,A)=>T+A,0);return N>0?j.map(T=>T/N*100):[]}),n(0)},[t,p,i,n]),S=l.useCallback((v,y)=>{y.preventDefault();const j=u.current;if(!j)return;const N=y.clientX,T=j.offsetWidth,A=o.length===g?[...o]:Zd(g),I=M=>{const P=(M.clientX-N)/T*100,B=[...A];B[v]=Math.max(15,A[v]+P),B[v+1]=Math.max(15,A[v+1]-P),i(B)},D=()=>{document.removeEventListener("mousemove",I),document.removeEventListener("mouseup",D),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",I),document.addEventListener("mouseup",D)},[o,g,i]),b=l.useCallback((v,y,j)=>{if(g>=4)return;const N=j==="left"?y:y+1;t(T=>{const A=cr(T,p).assignments,I=new Map;for(const D of d){const M=A.get(D.tabKey)??0,E=M>=N?M+1:M;E>0&&I.set(D.tabKey,E)}return N>0&&I.set(v,N),I}),i(T=>{const A=T.length===g?[...T]:Zd(g),I=A[y]??100/g,D=Math.max(15,I/2),M=Math.max(15,I/2),E=[...A];E[y]=D,E.splice(N,0,M);const P=E.reduce((B,R)=>B+R,0);return E.map(B=>B/P*100)}),a(T=>{const A=Xd(T,N);return A[N]=v,A}),r(T=>{const A=Xd(T,N);return A[N]=[v],A}),n(N)},[g,t,p,d,i,a,r,n]);l.useEffect(()=>{PN(e,f)||t(f)},[e,f,t]),l.useEffect(()=>{const{mapping:v,usedGroups:y}=m;a(j=>{const N=Jd(j,v);return Qd(j,N)?j:N}),r(j=>{const N=Jd(j,v);return Qd(j,N)?j:N}),n(j=>{const N=c?0:IN(j,y,v);return j===N?j:N}),i(j=>{const N=c?[]:LN(j,y,m.groupCount);return DN(j,N)?j:N})},[m,c,a,r,n,i]);const w=l.useMemo(()=>{const v=Array.from({length:g},()=>[]);for(const y of d){const j=f.get(y.tabKey)??0,N=Math.min(j,g-1);v[N].push(y)}return v},[d,f,g]),C=l.useCallback(()=>{t(new Map),n(0)},[t,n]);return{containerRef:u,normalizedGroupAssignments:f,numGroups:g,isSplitMode:k,groupedConvs:w,moveTabToGroup:h,closeGroup:x,handleResizeStart:S,splitTabRelative:b,clearAllSplits:C}}function EN({ides:e,sendDaemonCommand:t}){const n="1.0.53",a=l.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:So(m,Qs(m,n))).sort((m,f)=>Number(Pa(f,Qs(f,n)))-Number(Pa(m,Qs(m,n)))),[n,e]),r=l.useMemo(()=>a.some(m=>Pa(m,Qs(m,n))),[n,a]),o=l.useMemo(()=>a.map(m=>Qs(m,n)).find(m=>typeof m=="string"&&m.trim().length>0)||n,[n,a]),[i,c]=l.useState(!1),[d,p]=l.useState({}),u=l.useCallback(async m=>{var k,h;const f=e.find(x=>x.id===m);if(!f)return;p(x=>({...x,[m]:"upgrading"}));const g=Co(f);if(!g){p(x=>({...x,[m]:"error"}));return}try{const x=await t(m,"daemon_upgrade",g);(k=x==null?void 0:x.result)!=null&&k.upgraded||(h=x==null?void 0:x.result)!=null&&h.success?p(S=>({...S,[m]:"done"})):p(S=>({...S,[m]:"error"}))}catch{p(x=>({...x,[m]:"error"}))}},[e,t]);return{versionMismatchDaemons:a,hasRequiredVersionDaemons:r,targetVersion:o,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:u}}const Rh=80;function Pr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function _N(e){return{...e,createdAt:Pr(e.createdAt),updatedAt:Pr(e.updatedAt,e.createdAt),lastEventAt:Pr(e.lastEventAt,e.updatedAt||e.createdAt)}}function HN(e){const t=nm(e);return t==="unknown:"?e.id:t}function $N(e){return[e.type,sm(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function FN(e,t=Rh){const n=new Map;for(const a of e){if(a.deletedAt)continue;const r=HN(a),o=n.get(r);if(!o){n.set(r,a);continue}(a.updatedAt>o.updatedAt||a.updatedAt===o.updatedAt&&a.createdAt>o.createdAt)&&n.set(r,a)}return Array.from(n.values()).sort((a,r)=>{const o=r.updatedAt-a.updatedAt;return o!==0?o:r.createdAt-a.createdAt}).slice(0,Math.max(0,t))}function BN(e,t){const n=Date.now(),a=[];for(const r of e){const o=r.sessionId?t.get(r.sessionId):void 0;if(o!=null&&o.surfaceHidden||o!=null&&o.muted)continue;const i=fo(r,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const d=Pr(r.lastMessageAt||(o==null?void 0:o.lastUpdated)||r.lastUpdated,n),p=$N({type:c,sessionId:r.sessionId,providerSessionId:r.providerSessionId,tabKey:r.tabKey,lastMessageHash:r.lastMessageHash,lastMessageAt:r.lastMessageAt,lastUpdated:(o==null?void 0:o.lastUpdated)||r.lastUpdated});a.push(_N({id:p,dedupKey:p,type:c,routeId:r.routeId,machineId:r.daemonId||r.routeId,sessionId:r.sessionId,providerSessionId:r.providerSessionId,tabKey:r.tabKey,title:Cm(r),preview:jS(r),createdAt:d,updatedAt:d,lastEventAt:d}))}return FN(a)}function WN(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function ON(e){const{conversations:t,liveSessionInboxState:n,maxItems:a=Rh}=e,r=l.useMemo(()=>BN(t,n).slice(0,Math.max(0,a)),[t,n,a]),o=l.useMemo(()=>WN(r),[r]);return{notifications:r,unreadCount:o}}function UN({notifications:e,sendDaemonCommand:t}){const n=l.useCallback(o=>{const i=e.find(d=>d.id===o),c=Math.max(Date.now(),(i==null?void 0:i.updatedAt)||0);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_session_seen",{sessionId:i.sessionId,seenAt:c}).catch(()=>{})},[e,t]),a=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_notification_unread",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]),r=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"delete_notification",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:n,handleMarkDashboardNotificationUnread:a,handleDeleteDashboardNotification:r}}function cc(...e){const t=new Set,n=[],a=r=>{const o=typeof r=="string"?r.trim():"";if(!o)return;const i=o.toLowerCase();t.has(i)||(t.add(i),n.push(o))};for(const r of e){if(Array.isArray(r)){for(const o of r)a(o);continue}a(r)}return n}function GN(e){const t=e.trim();if(!t)return null;if(t.startsWith("~"))return t;if(/^[A-Za-z]:$/.test(t))return`${t[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(t))return`${t[0].toUpperCase()}:${t.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(t))return`${t[0].toUpperCase()}:\\${t.slice(2).replace(/[\\/]+/g,"\\")}`;const n=t.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(n){const a=n[1].toUpperCase(),r=(n[2]||"").replace(/[\\/]+/g,"\\");return r?`${a}:\\${r}`:`${a}:\\`}return null}function dc(e,t=[]){if(e==="win32"){for(const n of t){if(typeof n!="string")continue;const a=GN(n);if(a)return a}return"C:\\"}for(const n of t){const a=typeof n=="string"?n.trim():"";if(a)return a}return"~"}function qN(e){const t=e.replace(/[\\/]+$/,"");if(!t||t==="/"||/^[A-Za-z]:$/.test(t))return null;const n=t.includes("\\")?"\\":"/",a=t.split(/[\\/]/);return/^[A-Za-z]:$/.test(a[0]||"")?a.length<=2?`${a[0]}\\`:a.slice(0,-1).join("\\"):a.length<=2?n:a.slice(0,-1).join(n)||n}function zN(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function uc(e,t,n){const a=await e(t,"file_list_browse",{path:n}),r=zN(a);if(!(r!=null&&r.success))throw new Error((r==null?void 0:r.error)||(a==null?void 0:a.error)||"Could not browse folder");const o=typeof(r==null?void 0:r.path)=="string"?r.path:n,i=o.includes("\\")?"\\":"/",c=(p,u)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${u}`:p==="/"||p==="\\"?`${i}${u}`:`${p.replace(/[\\/]+$/,"")}${i}${u}`,d=Array.isArray(r==null?void 0:r.files)?r.files.filter(p=>(p==null?void 0:p.type)==="directory"&&typeof(p==null?void 0:p.name)=="string").map(p=>({name:p.name,path:typeof(p==null?void 0:p.path)=="string"&&p.path.trim()?p.path:c(o,p.name)})).sort((p,u)=>p.name.localeCompare(u.name)):[];return{path:o,directories:d}}function eu(e,t){const n=t.meshId||"",a={meshId:n,workspace:t.workspace||"",serverName:t.serverName||"adhdev-mesh",adhdevMcpCommand:t.adhdevMcpCommand||"adhdev-mcp",adhdevMcpArgs:t.adhdevMcpArgs||`mcp --mode ipc --repo-mesh ${n}`};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand|adhdevMcpArgs)\s*\}\}/g,(r,o)=>a[o]||"")}function Eh(e,t={}){const n=e==null?void 0:e.mcpConfig;if((n==null?void 0:n.mode)!=="manual")return null;const r=eu(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"}).trim();return!r.includes(`
|
|
65
|
-
`)&&!r.startsWith("{")?null:{serverName:n.serverName||"adhdev-mesh",configFormat:n.format,configPathCommand:n.configPathCommand,requiresRestart:n.requiresRestart===!0,instructions:n.instructions||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:eu(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"})}}function KN(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.instructions=="string"?t.instructions:"",a=typeof t.template=="string"?t.template:"";return!n&&!a?null:{serverName:typeof t.serverName=="string"?t.serverName:void 0,configFormat:typeof t.configFormat=="string"?t.configFormat:void 0,configPathCommand:typeof t.configPathCommand=="string"?t.configPathCommand:void 0,requiresRestart:t.requiresRestart===!0,instructions:n||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:a}}function Ba(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function _h(e){return bo(e)||e.tabKey||e.routeId||null}function Hh(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"",n=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"",a=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"",r=e.conversations.find(o=>{if(a&&o.routeId!==a)return!1;const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey].map(c=>typeof c=="string"?c.trim():"").filter(Boolean);return!!(t&&i.includes(t)||n&&i.includes(n)||a&&o.routeId===a)});if(r!=null&&r.tabKey)return r.tabKey;if(a){const o=ws(e.conversations,a)||e.conversations.find(i=>i.routeId===a);if(o!=null&&o.tabKey)return o.tabKey}return t||n||a||null}function Js(e){return String(e||"").trim()}function $h(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Xr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function VN(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function YN(e,t){const n=Js(e.providerSessionId),a=Js(e.targetSessionId),r=t.find(o=>{const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(Js).filter(Boolean);return!!(n&&i.includes(n)||a&&i.includes(a))});return r?r.tabKey:a||n||null}function QN(e,t,n){if(t.event!=="agent:generating_completed")return null;const a=$h(t.daemonId);if(a&&a!==e.machineId)return null;const r=Js(t.providerType);if(e.providerType&&r!==e.providerType)return null;const o=Js(e.resumeSessionId),i=Js(e.launchedSessionId),c=Js(t.providerSessionId),d=Js(t.targetSessionId);if(o&&o!==c&&o!==d||i&&i!==c&&i!==d)return null;const p=Xr(e.workspacePath);if(p){const u=Xr(t.workspaceName);if(u&&!VN(u,p))return null}return YN(t,n)}function tu(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function JN({ides:e,conversations:t,onOpenSession:n}){const[a,r]=l.useState(null),o=l.useRef(null),i=l.useCallback(()=>{o.current=null,r(null)},[]),c=l.useCallback(d=>{o.current=d,r(d)},[]);return l.useEffect(()=>{if(!a)return;const d=Xr(a.workspacePath),p=e.find(m=>{var x,S,b,w;if(!m||m.type==="adhdev-daemon"||$h(m.daemonId||m.id)!==a.machineId||($a(m)?"cli":Jn(m)?"acp":"ide")!==a.kind)return!1;const k=String(m.agentType||m.type||"");if(a.providerType&&k!==a.providerType)return!1;if(a.resumeSessionId)return String(m.providerSessionId||"")===a.resumeSessionId;if(a.launchedSessionId){const C=String(a.launchedSessionId||"");return[m.providerSessionId,m.sessionId,m.instanceId,m.id].map(y=>String(y||"")).filter(Boolean).includes(C)}if(d){const C=Xr(m.workspace||m.runtimeWorkspaceLabel);return C?C===d:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((w=(b=(S=(x=m.activeChat)==null?void 0:x.messages)==null?void 0:S.at)==null?void 0:b.call(S,-1))==null?void 0:w.timestamp)||0)>=a.startedAt-5e3});if(!p)return;const u=Hh({entrySessionId:p.sessionId,entryInstanceId:p.instanceId,entryRouteId:p.id,conversations:t});u&&(i(),n(u))},[i,t,e,n,a]),l.useEffect(()=>ft.onStatusEvent(d=>{const p=o.current;if(!p)return;const u=QN(p,d,t);u&&(i(),n(u))}),[i,t,n]),l.useEffect(()=>{if(!a)return;const d=window.setTimeout(()=>{r(p=>!p||p.startedAt!==a.startedAt?p:(o.current=null,null))},45e3);return()=>window.clearTimeout(d)},[a]),{trackPendingLaunch:c}}function XN(e,t){var a,r,o,i;const n={cliType:e};return(a=t==null?void 0:t.workspacePath)!=null&&a.trim()?n.dir=t.workspacePath.trim():t!=null&&t.workspaceId?n.workspaceId=t.workspaceId:t!=null&&t.useHome&&(n.useHome=!0),(r=t==null?void 0:t.resumeSessionId)!=null&&r.trim()&&(n.resumeSessionId=t.resumeSessionId.trim()),Array.isArray(t==null?void 0:t.cliArgs)&&t.cliArgs.length>0&&(n.cliArgs=t.cliArgs),(o=t==null?void 0:t.initialModel)!=null&&o.trim()&&(n.initialModel=t.initialModel.trim()),(i=t==null?void 0:t.initialThinkingLevel)!=null&&i.trim()&&(n.initialThinkingLevel=t.initialThinkingLevel.trim()),t!=null&&t.settings&&(n.settings=t.settings),n}function ZN(e,t,n){var i,c,d,p;const a={meshId:e.trim()};t.trim()&&(a.cliType=t.trim());const r=(i=n==null?void 0:n.initialModel)==null?void 0:i.trim(),o=(c=n==null?void 0:n.initialThinkingLevel)==null?void 0:c.trim();return r&&(a.initialModel=r),o&&(a.initialThinkingLevel=o),(d=n==null?void 0:n.settings)!=null&&d.autoApproveMode?a.autoApproveMode=n.settings.autoApproveMode:typeof((p=n==null?void 0:n.settings)==null?void 0:p.autoApprove)=="boolean"&&(a.autoApprove=n.settings.autoApprove),a}function eA({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:n,activeConv:a,ides:r,setCliViewModeOverrides:o}){const i=zl(),{launchCli:c}=ho(),d=l.useCallback(async(x,S)=>uc(e,x,S),[e]),p=l.useCallback(async(x,S)=>{if(!S.trim())return{ok:!1,error:"Choose a workspace path first."};try{const b=await e(x,"workspace_add",{path:S.trim()});return b!=null&&b.success?{ok:!0}:{ok:!1,error:(b==null?void 0:b.error)||"Could not save workspace"}}catch(b){return{ok:!1,error:b instanceof Error?b.message:"Could not save workspace"}}},[e]),u=l.useCallback(async(x,S,b)=>{var w;try{const C={ideType:S,enableCdp:!0};(w=b==null?void 0:b.workspacePath)!=null&&w.trim()&&(C.workspace=b.workspacePath.trim());const v=await e(x,"launch_ide",C);return!(v!=null&&v.success)&&(v==null?void 0:v.success)!==void 0?{ok:!1,error:(v==null?void 0:v.error)||"Could not launch IDE"}:(t({machineId:x,kind:"ide",providerType:S,workspacePath:(b==null?void 0:b.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(C){return{ok:!1,error:C instanceof Error?C.message:"Could not launch IDE"}}},[e,t]),m=l.useCallback(async(x,S,b,w)=>{const C=Date.now();try{const v=XN(b,w),y=await c(x,v),j=(y==null?void 0:y.result)||y,N=(j==null?void 0:j.sessionId)||(j==null?void 0:j.id);return y!=null&&y.success&&N?(t({machineId:x,kind:S,providerType:b,workspacePath:(w==null?void 0:w.workspacePath)||null,resumeSessionId:(w==null?void 0:w.resumeSessionId)||null,launchedSessionId:N,startedAt:C}),{ok:!0}):y!=null&&y.success?(t({machineId:x,kind:S,providerType:b,workspacePath:(w==null?void 0:w.workspacePath)||null,resumeSessionId:(w==null?void 0:w.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:(y==null?void 0:y.error)||(j==null?void 0:j.error)||`Could not launch ${S.toUpperCase()} session`,code:(y==null?void 0:y.code)||(j==null?void 0:j.code)||void 0}}catch(v){return tu(v)?(t({machineId:x,kind:S,providerType:b,workspacePath:(w==null?void 0:w.workspacePath)||null,resumeSessionId:(w==null?void 0:w.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:v instanceof Error?v.message:`Could not launch ${S.toUpperCase()} session`}}},[c,e,t]),f=l.useCallback(async x=>{var S;if(i!=null&&i.listMeshes)return i.listMeshes(x);if(!x)return[];try{const b=await e(x,"list_meshes",{}),w=(b==null?void 0:b.result)??b;if((w==null?void 0:w.success)===!1)throw new Error((w==null?void 0:w.error)||"Could not load meshes");return(Array.isArray(w==null?void 0:w.meshes)?w.meshes:Array.isArray((S=w==null?void 0:w.result)==null?void 0:S.meshes)?w.result.meshes:[]).map(v=>{var y;return{id:String((v==null?void 0:v.id)||""),name:String((v==null?void 0:v.name)||(v==null?void 0:v.id)||"Untitled mesh"),repoIdentity:(v==null?void 0:v.repoIdentity)||(v==null?void 0:v.repo_identity)||null,workspace:Array.isArray(v==null?void 0:v.nodes)&&v.nodes.length>0?String(((y=v.nodes[0])==null?void 0:y.workspace)||""):null,nodesCount:Array.isArray(v==null?void 0:v.nodes)?v.nodes.length:void 0,status:(v==null?void 0:v.status)||null}}).filter(v=>v.id)}catch(b){throw console.error("List meshes failed",b),b}},[i,e]),g=l.useCallback(async(x,S,b,w)=>{if(!S.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(x,S,b,w);const C=Date.now();try{const v=ZN(S,b,w),y=await e(x,"launch_mesh_coordinator",v),j=(y==null?void 0:y.result)??y;if((j==null?void 0:j.success)===!1||(y==null?void 0:y.success)===!1){const T=String((j==null?void 0:j.code)||(y==null?void 0:y.code)||""),A=KN((j==null?void 0:j.meshCoordinatorSetup)||(j==null?void 0:j.manualSetup)||(y==null?void 0:y.meshCoordinatorSetup)||(y==null?void 0:y.manualSetup));return{ok:!1,error:(j==null?void 0:j.error)||(y==null?void 0:y.error)||"Could not launch mesh coordinator",code:T||void 0,manualSetup:A}}const N=(j==null?void 0:j.sessionId)||(j==null?void 0:j.id);return N?n(N):t({machineId:x,kind:"cli",providerType:(j==null?void 0:j.cliType)||b.trim()||void 0,workspacePath:(j==null?void 0:j.workspace)||null,startedAt:C}),{ok:!0}}catch(v){return tu(v)?(t({machineId:x,kind:"cli",providerType:b.trim()||void 0,startedAt:C}),{ok:!0}):{ok:!1,error:v instanceof Error?v.message:"Could not launch mesh coordinator"}}},[i,n,e,t]),k=l.useCallback(async(x,S)=>{if(!x||!S)return[];try{const b=await e(x,"list_saved_sessions",{providerType:S,kind:"cli",limit:30}),w=(b==null?void 0:b.result)??b;return Array.isArray(w==null?void 0:w.sessions)?w.sessions:[]}catch(b){return console.error("List saved sessions failed",b),[]}},[e]),h=l.useCallback(async x=>{await Ah({conversation:a,mode:x,ides:r,sendDaemonCommand:e,setCliViewModeOverrides:o})},[a,r,e,o]);return{handleBrowseMachineDirectory:d,handleSaveMachineWorkspace:p,handleLaunchMachineIde:u,handleLaunchMachineProvider:m,handleListMachineMeshes:f,handleLaunchMeshCoordinator:g,handleListMachineSavedSessions:k,setActiveCliViewMode:h}}function tA(e){switch(e){case"notification-open":case"toast-open":case"conversation-open":case"requested-tab":return!0;case"dockview-shortcut":case"dockview-focus":case"dockview-move":case"dockview-split":case"stored-layout-restore":case"passive-tab-sync":return!1;default:return!1}}function sA(e,t,n=Date.now()){return!e||!tA(t)?null:{tabKey:e,nonce:n}}function nA({isMobile:e,conversations:t,visibleConversations:n,groupActiveTabIds:a,focusedGroup:r,groupedConvs:o,setSearchParams:i}){const[c,d]=l.useState(null),[p,u]=l.useState(null),m=l.useMemo(()=>{var x,S;if(!e){if(c){const b=t.find(w=>w.tabKey===c);if(b)return b}return n[0]}const h=a[r];if(h){const b=t.find(w=>w.tabKey===h);if(b)return b}return((x=o[r])==null?void 0:x[0])||((S=o[0])==null?void 0:S[0])},[t,c,r,a,o,e,n]),f=l.useCallback(h=>{d(h)},[]),g=l.useCallback(h=>{d(h.tabKey),i(x=>{const S=new URLSearchParams(x),b=AS(h);return b?S.set("activeTab",b):S.delete("activeTab"),S},{replace:!0})},[i]),k=l.useCallback((h,x)=>{const S=sA(h,x);S&&u(S)},[]);return{activeConv:m,openDesktopConversation:g,requestScrollToBottom:k,scrollToBottomRequest:p,setDesktopActiveTab:f}}function aA(e){const t=e.completedKey||null,n=e.pendingKey||null;return e.shouldMarkSeen?t===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:n!==null&&n!==e.autoReadKey,nextPendingKey:n===e.autoReadKey?n:null}:n===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:!1,nextPendingKey:n}:{shouldSchedule:!0,shouldCancelPending:n!==null&&n!==e.autoReadKey,nextPendingKey:e.autoReadKey}:{shouldSchedule:!1,shouldCancelPending:!!n,nextPendingKey:null}}function rA(e){const t=String(e.liveState.completionMarker||""),n=String(e.liveState.seenCompletionMarker||""),a=String(e.liveState.inboxBucket||"idle"),r=!!e.liveState.unread,o=[e.tabKey,e.historySessionId||"",t,n,a,r?"1":"0"].join(":");return{shouldMarkSeen:!!(a==="task_complete"&&r&&(!t||t!==n)),autoReadKey:o,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function oA({activeConv:e,isMobile:t,liveSessionInboxState:n,sendDaemonCommand:a}){const r=l.useRef(null),o=l.useRef(null),i=l.useRef(null),c=l.useRef(null),d=l.useRef(null);l.useEffect(()=>{const p=()=>{i.current&&(clearTimeout(i.current),i.current=null),c.current&&(clearTimeout(c.current),c.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),o.current=null};if(t){p(),r.current=null;return}if(!(e!=null&&e.sessionId)){p(),r.current=null;return}const u=an(e,n),m=rA({tabKey:e.tabKey,historySessionId:bo(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:jn(e),liveState:u}),f=m.autoReadKey,g=aA({autoReadKey:f,shouldMarkSeen:m.shouldMarkSeen,completedKey:r.current,pendingKey:o.current});if(!m.shouldMarkSeen){g.shouldCancelPending&&p(),r.current=f;return}if(!g.shouldSchedule)return;g.shouldCancelPending&&p();const k=()=>{if(document.visibilityState!=="visible"||r.current===f)return;r.current=f,o.current=null,i.current=null,c.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const x=m.readAt;a(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:x,completionMarker:m.completionMarker}).catch(()=>{})};if(o.current=g.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(k,1500);const x=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};d.current=x,document.addEventListener("visibilitychange",x);return}const h=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(k,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=h,document.addEventListener("visibilitychange",h)},[e,t,n,a]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current),c.current&&clearTimeout(c.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function ni(e){if(!e)return"";const t=String(e.workspacePath||"").trim();if(t)return t;const n=String(e.workspaceName||"").trim();return/^(?:~\/|\/|[A-Za-z]:[\\/])/.test(n)?n:""}function iA({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:n,ides:a,sendDaemonCommand:r,updateRouteChats:o,setToasts:i,setClearedTabs:c,setSearchParams:d}){var W;const{launchCli:p}=ho(),[u,m]=l.useState(!1),[f,g]=l.useState([]),[k,h]=l.useState(()=>qt()),[x,S]=l.useState(!1),[b,w]=l.useState(null),C=l.useRef(null),v=l.useMemo(()=>n||t||e,[e,n,t]),y=!!v&&bt(v)&&!ht(v),j=l.useMemo(()=>{if(!v||!y)return null;const _=v.daemonId||v.routeId||"",H=Ps(v),L=ni(v);return`${_}:${H}:${v.providerSessionId||""}:${L}`},[v,y]),N=l.useMemo(()=>!v||!y?"":ni(v),[v,y]),{isCreatingChat:T,isRefreshingHistory:A,handleSwitchSession:I,handleNewChat:D,handleRefreshHistory:M}=Lh({sendDaemonCommand:r,activeConv:v,chats:(W=a.find(_=>_.id===(v==null?void 0:v.routeId)))==null?void 0:W.chats,updateRouteChats:o,setToasts:i,setClearedTabs:c}),E=l.useCallback(()=>{m(!0)},[]),P=l.useCallback(()=>{m(!1)},[]),B=l.useCallback(async()=>{if(!(!v||!y||x)){S(!0);try{const _=v.daemonId||v.routeId,H=Ps(v),L=ni(v),F=await r(_,"list_saved_sessions",{agentType:H,providerType:H,kind:"cli",limit:50,...v.providerSessionId?{providerSessionId:v.providerSessionId}:{},...L?{workspace:L}:{}}),$=(F==null?void 0:F.result)??F;g(Array.isArray($==null?void 0:$.sessions)?$.sessions:[])}catch(_){console.error("Refresh saved sessions failed",_),g([])}finally{S(!1)}}},[v,x,y,r]);l.useEffect(()=>{if(!u){C.current=null;return}if(!y){C.current=null,g([]),S(!1);return}!j||x||C.current!==j&&(C.current=j,B())},[B,u,x,y,j]);const R=l.useCallback(async _=>{if(!v||!y||!_.providerSessionId||!_.workspace)return;const H=v.daemonId||v.routeId,L=Ps(v);try{w(_.providerSessionId);const F=await p(H,{cliType:L,dir:_.workspace,resumeSessionId:_.providerSessionId,initialModel:lm(_.summaryMetadata,"model",{preferShortValue:!0})||void 0}),$=(F==null?void 0:F.result)??F,K=typeof($==null?void 0:$.sessionId)=="string"?$.sessionId:typeof($==null?void 0:$.id)=="string"?$.id:"";K&&d(z=>{const ne=new URLSearchParams(z);return ne.set("activeTab",K),ne},{replace:!0}),P()}catch(F){console.error("Resume saved session failed",F)}finally{w(null)}},[P,v,y,r,d]);return{historyModalOpen:u,openHistoryModal:E,closeHistoryModal:P,historyTargetConv:v,isSavedSessionHistoryTarget:y,isHistoryCreatingChat:T,isHistoryRefreshingHistory:A,handleHistorySwitchSession:I,handleHistoryNewChat:D,handleHistoryRefresh:M,savedHistorySessions:f,savedHistoryFilters:k,setSavedHistoryFilters:h,missingWorkspaceResumePath:N,isSavedHistoryLoading:x,resumingSavedHistorySessionId:b,handleRefreshSavedHistory:B,handleResumeSavedHistorySession:R}}function lA({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c}){const[d,p]=l.useState(null),[u,m]=l.useState(null),f=l.useMemo(()=>{if(e||!a)return null;const S=c(a);return S&&!bt(S)&&!ht(S)?S:null},[e,a,c]),g=l.useMemo(()=>{const S=d==null?void 0:d.routeId;if(!S)return null;const b=d!=null&&d.tabKey?o.find(w=>w.tabKey===d.tabKey):r?o.find(w=>w.tabKey===r):null;return(b==null?void 0:b.routeId)===S?b:ws(o,S)},[o,d,r]),k=l.useMemo(()=>{if(g)return i.find(S=>S.id===g.routeId)},[i,g]);l.useEffect(()=>{f&&(p({routeId:f.routeId,tabKey:pd(f)}),m(f),n({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,n,f]);const h=l.useCallback(S=>{S&&(p({routeId:S.routeId,tabKey:pd(S)}),m(S))},[]),x=l.useCallback(()=>{p(null),m(null)},[]);return{remoteDialogConv:g,remoteDialogIdeEntry:k,remoteDialogActiveConv:u,setRemoteDialogActiveConv:m,openRemoteDialog:h,closeRemoteDialog:x}}function cA({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c,activeConv:d,sendDaemonCommand:p}){const{remoteDialogConv:u,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:g,openRemoteDialog:k,closeRemoteDialog:h}=lA({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c}),[x,S]=l.useState(!1),[b,w]=l.useState(null),C=l.useCallback(async j=>{const N=j||d;!N||!bt(N)&&!ht(N)||(w(N),S(!0))},[d]),v=l.useCallback(()=>{S(!1),w(null)},[]),y=l.useCallback(async j=>{const N=b||d;if(!N||!bt(N)&&!ht(N)){v();return}S(!1);try{const T=Ps(N),A=N.routeId||N.daemonId||"";await p(A,"stop_cli",{cliType:T,targetSessionId:N.sessionId,mode:j,...yo(N)})}catch(T){console.error("Stop CLI failed:",T)}finally{w(null)}},[d,v,b,p]);return{remoteDialogConv:u,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:g,openRemoteDialog:k,closeRemoteDialog:h,cliStopDialogOpen:x,cliStopTargetConv:b,requestCliStop:C,cancelCliStop:v,confirmCliStop:y}}function ai(e,t=!0){return(e??!0)&&t}const pc=l.memo(function({activeConv:t,clearToken:n,isCliTerminal:a,ideEntry:r,terminalRef:o,handleModalButton:i,handleRelaunch:c,handleSendChat:d,handleForceSendChat:p,isSendingChat:u,sendFeedbackMessage:m=null,handleFocusAgent:f,isFocusingAgent:g,actionLogs:k,userName:h,scrollToBottomRequestNonce:x,isInputActive:S=!0,isVisible:b=!0}){const w=a,C=!a,v=ai(b,w),y=ai(b,C),j=ai(b),N=Ch(t),T=N.status||N.modalMessage||N.modalButtons?{...t,...N.status?{status:N.status}:{},...N.modalMessage!==void 0?{modalMessage:N.modalMessage}:{},...N.modalButtons!==void 0?{modalButtons:N.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(Yp,{activeConv:T,onModalButton:i}),T.transport!=="pty"&&T.transport!=="acp"&&T.cdpConnected===!1?s.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:s.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[s.jsx("span",{className:"text-sm",children:s.jsx(Is,{size:14})}),s.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),s.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:c,children:"Relaunch with CDP"})]})}):null,T.transport==="pty"?s.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[s.jsx("div",{"aria-hidden":!a,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:w?"visible":"hidden",pointerEvents:w?"auto":"none"},children:s.jsx(lj,{activeConv:T,clearToken:n,terminalRef:o,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:m,isVisible:v,isInputActive:S&&v})}),s.jsx("div",{"aria-hidden":a,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:C?"visible":"hidden",pointerEvents:C?"auto":"none"},children:s.jsx(al,{activeConv:T,ideEntry:r,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:k,userName:h,scrollToBottomRequestNonce:x,isInputActive:S&&y,isVisible:y})})]}):s.jsx(al,{activeConv:T,ideEntry:r,handleSendChat:d,handleForceSendChat:p,isSendingChat:u,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:k,userName:h,scrollToBottomRequestNonce:x,isInputActive:S&&j,isVisible:j})]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.handleModalButton===t.handleModalButton&&e.handleRelaunch===t.handleRelaunch&&e.handleSendChat===t.handleSendChat&&e.handleForceSendChat===t.handleForceSendChat&&e.isSendingChat===t.isSendingChat&&e.sendFeedbackMessage===t.sendFeedbackMessage&&e.handleFocusAgent===t.handleFocusAgent&&e.isFocusingAgent===t.isFocusingAgent&&e.actionLogs===t.actionLogs&&e.userName===t.userName&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isInputActive===t.isInputActive&&e.isVisible===t.isVisible);function dA({conversation:e,className:t="",onOpenNativeConversation:n,onOpenMachine:a,interactive:r=!0,meshOnly:o=!1}){var C,v,y;const{t:i}=ke("common"),c=oa(),d=Ks(e),p=o?null:Sm(e),u=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),m=!o&&e.streamSource==="agent-stream"&&!!e.agentName,f=!o&&!m&&(e.transport==="pty"||e.transport==="acp"),g=ta(e),k=NS(e),h=(C=e.settings)==null?void 0:C.meshNodeFor,x=e.meshQueueStats,S=((v=e.coordinator)==null?void 0:v.meshId)||((y=e.settings)==null?void 0:y.meshCoordinatorFor),b=l.useCallback(()=>{if(a){a();return}d&&c("/dashboard",{state:{openMachineId:d}})},[d,c,a]),w=l.useCallback(()=>{if(n){n();return}const j=_h(e);j&&c(Ba(j))},[e,c,n]);return!u&&!m&&!f&&!p&&!h&&!x?null:s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[u&&(r?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:w,title:k,children:[s.jsx(us,{size:12}),s.jsx("span",{children:k})]}):s.jsxs("span",{className:"conversation-meta-chip",title:k,children:[s.jsx(us,{size:12}),s.jsx("span",{children:k})]})),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(Ea,{size:12}),s.jsx("span",{children:g})]}),f&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(Ea,{size:12}),s.jsx("span",{children:g})]}),p&&(r?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:b,title:p,children:[s.jsx(sn,{size:12}),s.jsx("span",{children:p})]}):s.jsxs("span",{className:"conversation-meta-chip",title:p,children:[s.jsx(sn,{size:12}),s.jsx("span",{children:p})]})),h&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(sn,{size:12}),s.jsx("span",{children:i("dashboard.metaChips.meshNode")})]}),S&&x&&s.jsxs("span",{className:`conversation-meta-chip ${x.pending>0?"is-active":""}`,style:x.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${x.pending} pending, ${x.assigned} assigned, ${x.completed} completed, ${x.failed} failed`,children:[s.jsx(pb,{size:12}),s.jsxs("span",{children:[x.pending," Pending"]})]})]})}function uA({selectedConversation:e,isAcp:t,isStandalone:n,selectedIdeEntry:a,actionLogs:r,userName:o,isSendingChat:i,sendFeedbackMessage:c=null,isFocusingAgent:d,onBack:p,onOpenNativeConversation:u,onOpenMachine:m,onOpenHistory:f,onOpenRemote:g,onOpenMeshGraph:k,onStopCli:h,cliViewMode:x,onSetCliViewMode:S,handleSendChat:b,handleForceSendChat:w,handleFocusAgent:C,handleModalButton:v,handleRelaunch:y}){var D,M;const j=l.useRef(null),N=bt(e)&&!t,T=N&&x==="terminal",A=!!e.daemonId&&!!((D=e.coordinator)!=null&&D.meshId||(M=e.settings)!=null&&M.meshCoordinatorFor),I=n?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`flex items-center justify-between gap-3 ${I} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:p,type:"button","aria-label":"Back",children:s.jsx(Il,{size:18})}),s.jsxs("div",{className:"min-w-0 flex-1 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:kt(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(dA,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>m(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[N&&x&&s.jsx(eh,{mode:x,onChange:S,compact:!0}),N&&h&&s.jsx("button",{onClick:()=>{h(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(Dt,{size:14})}),A&&k&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>k(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(cs,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",children:s.jsx(Rl,{size:14})}),!t&&!N&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",children:s.jsx(us,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(pc,{activeConv:e,clearToken:0,isCliTerminal:T,ideEntry:a,terminalRef:j,handleModalButton:v,handleRelaunch:y,handleSendChat:b,handleForceSendChat:w,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:C,isFocusingAgent:d,actionLogs:r,userName:o})})]})}const ri={unix:{cmd:"curl -fsSL https://adhf.dev/install | sh",shell:"Terminal",prompt:"$ "},powershell:{cmd:"irm https://adhf.dev/install.ps1 | iex",shell:"PowerShell",prompt:"PS> "},cmd:{cmd:"curl -fsSL https://adhf.dev/install.cmd -o %TEMP%\\adhdev.cmd && %TEMP%\\adhdev.cmd",shell:"CMD",prompt:"> "}};function pA(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Fh(){const[e,t]=l.useState("unix"),[n,a]=l.useState("powershell"),[r,o]=l.useState(!1),i=e==="unix"?"unix":n;l.useEffect(()=>{t(pA())},[]);const c=l.useCallback(()=>{navigator.clipboard.writeText(ri[i].cmd).catch(()=>{}),o(!0),setTimeout(()=>o(!1),2e3)},[i]);return s.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("unix"),children:"macOS / Linux"}),s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("windows"),children:"Windows"})]}),e==="windows"&&s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${n==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>a("powershell"),children:"PowerShell"}),s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${n==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>a("cmd"),children:">_ CMD"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:c,title:"Click to copy",children:[s.jsx("span",{className:"text-text-muted select-none",children:ri[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:ri[i].cmd}),s.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:r?s.jsx(lo,{size:12}):s.jsx(Ll,{size:12})})]}),s.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",s.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function Bh({section:e,onSectionChange:t}){const{t:n}=ke("common"),a=[{key:"machines",label:n("nav.machines"),icon:us},{key:"chats",label:n("nav.chats"),icon:Ds}];return s.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:s.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:a.map(({key:r,label:o,icon:i})=>{const c=e===r;return s.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${c?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>t(r),type:"button","aria-pressed":c,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${c?"text-accent-primary":"bg-transparent text-current"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:s.jsx(i,{size:15})}),s.jsx("span",{children:o})]},r)})})})}function dr({title:e,className:t=""}){return s.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${t}`,children:s.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function Fn({children:e,className:t=""}){return s.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${t}`,children:e})}function mn({icon:e,title:t,subtitle:n,children:a}){return s.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[s.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),s.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:t}),s.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:n}),a]})}function mA({conversation:e,onCancel:t,onConfirm:n}){const{t:a}=ke(),r=kt(e);return s.jsx(Vt,{children: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:t,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"mobile-hide-confirm-title",className:"card fade-in mobile-compact-dialog relative w-full sm:w-[min(92vw,420px)] md:w-[92%] md:max-w-[420px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-bg-primary",children:[s.jsx("h3",{id:"mobile-hide-confirm-title",className:"m-0 text-base md:text-lg font-extrabold",children:a("mobileInbox.hideTitle",{title:r})}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:a("mobileInbox.hideDescription")})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[s.jsx("button",{onClick:n,className:"btn btn-primary w-full justify-center min-h-[42px]",children:a("mobileInbox.hide")}),s.jsx("button",{onClick:t,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:a("common.cancel")})]})]})]})})}function ur({item:e,type:t,getAvatarText:n,onOpenConversation:a,onRequestHideConversation:r,onRequestStopCli:o,onOpenMeshGraph:i,onCollectChatDebugBundle:c,isMuted:d,onToggleMute:p}){const{t:u}=ke(),m=t==="needs_attention"||t==="task_complete",f=t==="working",g=t==="earlier",k=t==="task_complete",{isReconnecting:h,isConnecting:x}=Rn(e.conversation),S=kt(e.conversation),b=sa(e.conversation),w=Qm(e.conversation,{requiresAction:t==="needs_attention"}),C=m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":f?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":g?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",v=m?"bg-accent-primary shadow-glow":f?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":g?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",y=g?"text-text-secondary":"text-text-primary",j=g?"text-text-muted":"text-text-secondary",N=g?"text-text-secondary opacity-80":"text-text-muted",T=g?"text-text-muted opacity-80":"text-text-muted",A=!f&&!k,I=Vm(e.conversation),D="text-[color:var(--status-warning)]",M=E=>{if(!c)return;E.preventDefault(),E.stopPropagation();const P=c==null?void 0:c(e.conversation);Promise.resolve(P).catch(B=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",B)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${C}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[m||f?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${v}`,style:m?{color:"var(--accent-on-primary)"}:void 0,children:n(S)}),I&&i&&s.jsx("button",{type:"button",className:"mobile-inbox-mesh-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:E=>{E.preventDefault(),E.stopPropagation(),i(e.conversation)},"aria-label":u("mobileInbox.openMeshGraphFor",{title:S}),title:u("mobileInbox.openLiveMeshGraph"),children:s.jsx(cs,{size:13})})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>a(e.conversation),onContextMenu:M,type:"button",children:[s.jsx("div",{className:"flex items-center gap-2 pr-[124px]",children:s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${y}`,children:S})}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${j}`,children:[s.jsx("span",{className:"truncate",children:b}),s.jsx(Gr,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),h?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${D} animate-pulse`,children:u("mobileInbox.reconnectingItem")})]}):x?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:u("mobileInbox.connectingItem")})]}):w==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:D,children:u("mobileInbox.actionNeeded")})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${N}`,children:e.preview})]}),s.jsxs("div",{className:"mobile-inbox-corner-actions absolute top-3 right-3 flex items-center gap-1.5",children:[A&&s.jsx("span",{className:`mr-0.5 text-[11px] font-medium shrink-0 ${T}`,children:Kp(e.timestamp)}),k&&s.jsx("span",{className:"rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:u("mobileInbox.done")}),p&&s.jsx("button",{type:"button",className:`mobile-inbox-mute-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border transition-colors ${d?"border-amber-500/60 bg-amber-500 text-white hover:bg-amber-600":"border-border-subtle bg-bg-primary/70 text-text-muted hover:border-border-default hover:text-text-primary"}`,onClick:E=>{E.preventDefault(),E.stopPropagation(),p()},"aria-label":d?u("mobileInbox.unmute",{title:S}):u("mobileInbox.mute",{title:S}),title:u(d?"mobileInbox.mutedTitle":"mobileInbox.muteNotifications"),children:d?s.jsx(Np,{size:13}):s.jsx(ia,{size:13})}),r&&s.jsx("button",{type:"button",className:"mobile-inbox-hide-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:E=>{E.preventDefault(),E.stopPropagation(),r()},"aria-label":u("mobileInbox.hideConversationAria",{title:S}),title:u("mobileInbox.hideConversationTitle"),children:s.jsx(po,{size:13})}),o&&s.jsx("button",{type:"button",className:"mobile-inbox-stop-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-status-error/30 bg-bg-primary/70 text-status-error transition-colors hover:border-status-error/60 hover:bg-status-error/10",onClick:E=>{E.preventDefault(),E.stopPropagation(),o()},"aria-label":u("mobileInbox.stopSessionAria",{title:S}),title:u("mobileInbox.stopSessionTitle"),children:s.jsx(Dt,{size:13})})]})]})},e.conversation.tabKey)}function su({count:e,label:t}){return e<=0?null:s.jsxs("span",{className:"inline-flex items-center gap-1.5 text-accent-primary","aria-live":"polite",children:[s.jsxs("span",{className:"relative flex h-2 w-2 shrink-0",children:[s.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-accent-primary/60"}),s.jsx("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-accent-primary"})]}),s.jsx("span",{className:"font-semibold",children:t})]})}function hA({section:e,attentionItems:t,unreadItems:n,workingItems:a,completedItems:r,hiddenConversations:o,machineCards:i,getAvatarText:c,actionLogs:d,sendDaemonCommand:p,onOpenConversation:u,onShowAllHidden:m,onHideConversation:f,onOpenMeshGraph:g,onStopCli:k,onOpenNewSession:h,onOpenMachine:x,onOpenSettings:S,onSectionChange:b,wsStatus:w="connected",initialDataLoaded:C=!0,conversationsLoaded:v,isStandalone:y=!1,onCollectChatDebugBundle:j,isConversationMuted:N,onToggleMuteConversation:T}){const{t:A}=ke(),[I,D]=l.useState(null),M=w==="disconnected"||w==="reconnecting"||w==="offline"||w==="auth_failed",E=!M&&!C,P=!M&&!(v??C),B=i.length>0,R=t.length>0||n.length>0||a.length>0||r.length>0,W=A(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),_=y?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",H=y?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",L=l.useCallback(async K=>{const z=wn(K);if(!z)return;const ne=Array.isArray(K.messages)?K.messages:[],ie=Pm({activeConv:K,visibleMessages:ne,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:ne.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),Ce=await p(z,"get_chat_debug_bundle",{...yn(K),delivery:"daemon_file",frontendSnapshot:ie}),me=Ma(Ce),O=Lm(me),Y=await Im(O);Y==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),ft.showToast(Dm(me,{locatorCopyStatus:Y}),Y==="failed"?"warning":"success")},[d,p]),F=j||L,$=l.useCallback(()=>{I&&(f==null||f(I),D(null))},[I,f]);return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${_}`,children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:W}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||n.length>0)&&s.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[s.jsx(ia,{size:13}),s.jsx("span",{children:t.length+n.length})]}),s.jsx("button",{onClick:S,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:s.jsx(Oa,{size:18})})]})]})}),s.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${H}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:M?s.jsx(mn,{icon:s.jsx(ls,{size:32}),title:A(w==="offline"?"mobileInbox.networkOffline":w==="auth_failed"?"mobileInbox.sessionExpired":"mobileInbox.reconnecting"),subtitle:A(w==="offline"?"mobileInbox.waitingForNetwork":w==="auth_failed"?"mobileInbox.pleaseLogInAgain":"mobileInbox.restoringConnection")}):E?s.jsx(mn,{icon:s.jsx(ls,{size:32}),title:A("mobileInbox.loading"),subtitle:A("mobileInbox.loadingSubtitle")}):i.length===0?s.jsx(mn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:A(y?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:A(y?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!y&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(Fh,{})})}):s.jsx(Fn,{children:i.map((K,z)=>s.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${z>0?"border-t border-border-subtle/70":""}`,onClick:()=>x(K.id),type:"button",children:[s.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:c(K.label)}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:K.label}),s.jsxs("span",{className:"flex items-center gap-2 text-[11px] font-medium text-text-muted shrink-0",children:[s.jsx(su,{count:K.generatingCount,label:A("mobileInbox.generatingCount",{count:K.generatingCount})}),K.unread>0?s.jsx("span",{className:"text-accent-primary",children:A("mobileInbox.newCount",{count:K.unread})}):K.total>0?A("mobileInbox.chatCount",{count:K.total}):A("mobileInbox.idle")]})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:K.subtitle}),K.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[A("mobileInbox.chatCount",{count:K.total}),K.unread>0?A("mobileInbox.unreadSuffix",{count:K.unread}):"",K.generatingCount>0?A("mobileInbox.collapsedGeneratingSuffix",{count:K.generatingCount}):""]}):K.generatingCount>0?s.jsx("div",{className:"text-[13px] text-accent-primary mt-0.5 font-medium",children:A("mobileInbox.generatingCount",{count:K.generatingCount})}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:A("mobileInbox.noActiveChats")})]})]},K.id))})}),e==="chats"&&t.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(dr,{title:A("mobileInbox.needsAttention"),className:"mb-0"}),s.jsx(Fn,{children:t.map((K,z)=>s.jsx("div",{className:z>0?"border-t border-border-subtle/70":"",children:s.jsx(ur,{item:K,type:"needs_attention",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>D(K.conversation):void 0,onRequestStopCli:k?()=>k(K.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:F,isMuted:N==null?void 0:N(K.conversation),onToggleMute:T?()=>T(K.conversation):void 0})},K.conversation.tabKey))})]}),e==="chats"&&n.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(dr,{title:A("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),s.jsx(Fn,{children:n.map((K,z)=>s.jsx("div",{className:z>0?"border-t border-border-subtle/70":"",children:s.jsx(ur,{item:K,type:"task_complete",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>D(K.conversation):void 0,onRequestStopCli:k?()=>k(K.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:F,isMuted:N==null?void 0:N(K.conversation),onToggleMute:T?()=>T(K.conversation):void 0})},K.conversation.tabKey))})]}),e==="chats"&&a.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(dr,{title:A("mobileInbox.workingNow"),className:"mb-0 mt-2"}),s.jsx(Fn,{children:a.map((K,z)=>s.jsx("div",{className:z>0?"border-t border-border-subtle/70":"",children:s.jsx(ur,{item:K,type:"working",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>D(K.conversation):void 0,onRequestStopCli:k?()=>k(K.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:F,isMuted:N==null?void 0:N(K.conversation),onToggleMute:T?()=>T(K.conversation):void 0})},K.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[r.length>0&&s.jsx(dr,{title:A("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),r.length>0?s.jsx(Fn,{children:r.map((K,z)=>s.jsx("div",{className:z>0?"border-t border-border-subtle/70":"",children:s.jsx(ur,{item:K,type:"earlier",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>D(K.conversation):void 0,onRequestStopCli:k?()=>k(K.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:F,isMuted:N==null?void 0:N(K.conversation),onToggleMute:T?()=>T(K.conversation):void 0})},K.conversation.tabKey))}):R?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:A("mobileInbox.allCaughtUp")}):M?s.jsx(mn,{icon:s.jsx(ls,{size:28}),title:A("mobileInbox.connecting"),subtitle:A("mobileInbox.connectingSubtitle")}):P?s.jsx(mn,{icon:s.jsx(ls,{size:28}),title:A("mobileInbox.loading"),subtitle:A("mobileInbox.loadingSubtitle")}):B?s.jsx(mn,{icon:s.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:s.jsx(Ds,{size:20})}),title:A("mobileInbox.noConversations"),subtitle:A("paneGroup.newSessionDescription"),children:h&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:h,"aria-label":A("paneGroup.newSession"),title:A("paneGroup.newSession"),children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",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"})]}),s.jsx("span",{children:A("paneGroup.newSession")})]})}):s.jsx(mn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:A("mobileInbox.noMachinesConnected"),subtitle:A("mobileInbox.noMachinesSubtitle")})]}),e==="chats"&&o.length>0&&(()=>{const K=Nx(o);return s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(Fn,{className:"mt-4 border-dashed bg-bg-secondary/20",children:s.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:A("mobileInbox.hiddenTabs")}),s.jsx(su,{count:K,label:A("mobileInbox.generatingCount",{count:K})})]}),s.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[A("mobileInbox.collapsedCount",{count:o.length}),K>0?A("mobileInbox.collapsedGeneratingSuffix",{count:K}):""]})]}),s.jsx("button",{type:"button",className:"shrink-0 rounded-full border border-border-subtle bg-bg-primary/70 px-3 py-1.5 text-[12px] font-semibold text-accent-primary hover:border-border-default",onClick:m,children:A("mobileInbox.restoreAll")})]})})})})()]}),e==="chats"&&h&&R&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:h,"aria-label":A("paneGroup.newSession"),title:A("paneGroup.newSession"),children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",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"})]})}),I&&s.jsx(mA,{conversation:I,onCancel:()=>D(null),onConfirm:$}),s.jsx(Bh,{section:e,onSectionChange:b})]})}function fA(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 Wh(e){const t=[e.workspace||"Workspace unknown"],n=Tn(e.summaryMetadata);n&&t.push(n),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const a=fA(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:a?`Updated ${a}`:"",preview:(e.preview||"").trim()}}function mc({title:e,description:t,currentPath:n,directories:a,busy:r=!1,error:o="",confirmLabel:i="Use this folder",onClose:c,onNavigate:d,onConfirm:p}){const[u,m]=l.useState(n),{t:f}=ke("common");l.useEffect(()=>{m(n)},[n]);const g=qN(n),k=u.trim();return s.jsx(Vt,{children:s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] 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",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:s.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:c,"aria-label":"Close folder browser",children:s.jsx(Dt,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!g||r||d(g)},disabled:!g||r,children:[s.jsx(Il,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:f("machine.workspaceBrowse.currentFolder")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:u,onChange:h=>m(h.target.value),onKeyDown:h=>{h.key!=="Enter"||!k||r||(h.preventDefault(),d(k))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!k||r||d(k)},disabled:!k||r,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:r?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):o?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:o}):a.length===0?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):s.jsx("div",{className:"p-3",children:a.map(h=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>d(h.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(An,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:h.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:h.path})]})]},h.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:c,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>p(k||n),disabled:!k&&!n||r,children:i})]})]})})})}function jo({title:e,description:t,details:n,workspaceOptions:a,selectedWorkspaceKey:r,onWorkspaceChange:o,confirmLabel:i,busyLabel:c,busy:d=!1,showArgsInput:p,argsValue:u,onArgsChange:m,showModelInput:f,modelValue:g,onModelChange:k,historyProviderNode:h,onConfirm:x,onCancel:S}){const{t:b}=ke("common"),w=i??b("machine.launchConfirm.launch"),C=c??b("machine.launchConfirm.launching"),v=a==null?void 0:a.find(j=>j.key===r),y=s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] 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",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:S,"aria-label":b("machine.launchConfirm.closeAria"),children:s.jsx(Dt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[a&&a.length>0&&o&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.workspace")}),s.jsx("select",{value:r||"",onChange:j=>o(j.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:d,children:a.map(j=>s.jsx("option",{value:j.key,children:j.label},j.key))}),(v==null?void 0:v.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:v.description})]}),h,n.map(j=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:j.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:j.value})]},`${j.label}:${j.value}`)),f&&k&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.languageModel")}),s.jsx("input",{type:"text",value:g||"",onChange:j=>k(j.target.value),placeholder:b("machine.launchConfirm.autoDetect"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]}),p&&m&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.cliArgs")}),s.jsx("input",{type:"text",value:u||"",onChange:j=>m(j.target.value),placeholder:b("machine.launchConfirm.cliArgsPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:S,disabled:d,children:b("machine.launchConfirm.cancel")}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:x,disabled:d,children:[s.jsx(jp,{size:14}),d?C:w]})]})]})});return typeof document>"u"?y:qs.createPortal(y,document.body)}function nu(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function Oh(e){const{machine:t,currentWorkspacePath:n,currentWorkspaceId:a,includeHome:r=!0,homeLabel:o="Home directory",homeDescription:i="Launch without a workspace"}=e,c=[];r&&c.push({key:"__home__",label:o,description:i,workspaceId:null,workspacePath:null});for(const u of t.workspaces||[])c.push({key:`saved:${u.id}`,label:`${u.id===t.defaultWorkspaceId?"⭐ ":""}${nu(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const d=(n==null?void 0:n.trim())||"",p=d?(t.workspaces||[]).find(u=>u.path===d):null;if(d&&!p&&c.push({key:`custom:${d}`,label:nu(d),description:d,workspaceId:null,workspacePath:d}),a){const u=`saved:${a}`;if(c.some(m=>m.key===u))return{options:c,selectedKey:u}}return p?{options:c,selectedKey:`saved:${p.id}`}:d?{options:c,selectedKey:`custom:${d}`}:{options:c,selectedKey:"__home__"}}function gA(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function bA(e){return[gA(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function xA(e){return e.lastLaunchedAt?qa(e.lastLaunchedAt):""}function Uh(e){return{metaText:bA(e),updatedLabel:xA(e)}}function oi(e,t,n){return e?"ide":t>0?"cli":n>0?"acp":null}function vA({selectedMachineEntry:e,cliProviders:t,acpProviders:n,machineAction:a,onBrowseDirectory:r,onListSavedSessions:o}){var Ie,We,Xe,et;const i=ca(),[c,d]=l.useState(!1),p=(((Ie=e.detectedIdes)==null?void 0:Ie.length)||0)>0,u=l.useMemo(()=>(e.workspaces||[]).map(J=>({id:J.id,path:J.path,label:J.label})),[e]),m=e.defaultWorkspaceId||null,[f,g]=l.useState(m||((We=u[0])==null?void 0:We.id)||""),[k,h]=l.useState(""),[x,S]=l.useState(""),[b,w]=l.useState([]),[C,v]=l.useState(!1),[y,j]=l.useState(""),[N,T]=l.useState(!1),[A,I]=l.useState(oi(p,t.length,n.length)),D=l.useRef(null),[M,E]=l.useState(null),P=l.useRef("__home__"),[B,R]=l.useState("__home__"),[W,_]=l.useState(""),[H,L]=l.useState(""),[F,$]=l.useState(""),[K,z]=l.useState([]),[ne,ie]=l.useState(()=>qt().textQuery),[Ce,me]=l.useState(()=>qt().workspaceQuery),[O,Y]=l.useState(()=>qt().modelQuery),[X,Q]=l.useState(()=>qt().resumableOnly),[ve,he]=l.useState(()=>qt().sortMode),[Z,fe]=l.useState(!1),[V,q]=l.useState(!1),ee=l.useRef(null),pe=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const le=f==="__custom__"?k.trim():((Xe=u.find(J=>J.id===f))==null?void 0:Xe.path)||"",se=f==="__custom__"&&!!le&&a.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(a.message),te=f!=="__custom__"&&((et=u.find(J=>J.id===f))==null?void 0:et.path)||"",ue=l.useMemo(()=>(e.recentLaunches||[]).map(J=>J.workspace),[e]),ye=l.useCallback(async J=>{v(!0),j("");try{const Le=await r(J);S(Le.path),h(Le.path),w(Le.directories)}catch(Le){j(Le instanceof Error?Le.message:"Could not load folder")}finally{v(!1)}},[r]),Me=l.useCallback(()=>{var Le;g("__custom__"),T(!0);const J=dc(e.platform,cc(k.trim(),te,ue,e.defaultWorkspacePath,(Le=u.find($e=>$e.id===m))==null?void 0:Le.path,u.map($e=>$e.path)));ye(J)},[k,m,ye,ue,te,e.platform,u]),re=l.useCallback(J=>{if(J!=null&&J.workspaceId){g(J.workspaceId),h("");return}if(J!=null&&J.workspacePath){g("__custom__"),h(J.workspacePath);return}g(""),h("")},[]),ce=l.useCallback(J=>{if(g(J),J==="__custom__"){Me();return}h("")},[Me]),Ae=l.useCallback(J=>{g("__custom__"),h(J)},[]),be=l.useCallback((J,Le)=>{D.current=Le,P.current=J.selectedWorkspaceKey||"__home__",R(J.selectedWorkspaceKey||"__home__"),_(J.initialArgs||""),L(J.initialModel||""),$(""),z([]);const $e=J.providerType?`${e.id}:${J.providerType}`:null;if(yj(pe.current,$e)){const at=qt();ie(at.textQuery),me(at.workspaceQuery),Y(at.modelQuery),Q(at.resumableOnly),he(at.sortMode)}pe.current=$e,E(J),J.providerType&&o&&(fe(!0),o(J.providerType).then(at=>z(at||[])).catch(at=>console.warn("Failed to load saved sessions",at)).finally(()=>fe(!1)))},[o,e.id]),we=l.useMemo(()=>th(K,{textQuery:ne,workspaceQuery:Ce,modelQuery:O,resumableOnly:X,sortMode:ve}),[O,X,K,ve,ne,Ce]);l.useEffect(()=>{F&&(we.some(J=>J.providerSessionId===F)||$(""))},[we,F]);const _e=l.useCallback(()=>{D.current&&(q(!0),D.current().finally(()=>{D.current=null,q(!1),E(null)}))},[]),U=l.useCallback(()=>{D.current=null,E(null)},[]),Ne=l.useCallback(J=>{P.current=J,R(J)},[]);return l.useEffect(()=>{var J;ee.current!==e.id&&(ee.current=e.id,g(m||((J=u[0])==null?void 0:J.id)||"__custom__"),h(""),S(""),w([]),j(""),T(!1),ie(qt().textQuery),me(qt().workspaceQuery),Y(qt().modelQuery),Q(qt().resumableOnly),he(qt().sortMode),pe.current=null,I(oi(p,t.length,n.length)))},[n.length,t.length,m,p,e.id,u]),l.useEffect(()=>{var J;f!=="__custom__"&&(f&&u.some(Le=>Le.id===f)||g(m||((J=u[0])==null?void 0:J.id)||"__custom__"))},[m,f,u]),l.useEffect(()=>{A==="ide"&&p||A==="cli"&&t.length>0||A==="acp"&&n.length>0||I(oi(p,t.length,n.length))},[A,n.length,t.length,p]),{showAllRecent:c,setShowAllRecent:d,hasIdeOptions:p,workspaceRows:u,defaultWorkspaceId:m,workspaceChoice:f,customWorkspacePath:k,browseCurrentPath:x,browseDirectories:b,browseBusy:C,browseError:y,browseDialogOpen:N,activeLauncherKind:A,launchConfirm:M,launchConfirmWorkspaceKeyRef:P,launchConfirmWorkspaceKey:B,launchConfirmArgs:W,launchConfirmModel:H,launchConfirmResumeId:F,launchConfirmSavedSessions:K,launchConfirmTextFilter:ne,launchConfirmWorkspaceFilter:Ce,launchConfirmModelFilter:O,launchConfirmResumableOnly:X,launchConfirmSortMode:ve,filteredLaunchConfirmSavedSessions:we,launchConfirmSessionsLoading:Z,launchConfirmBusy:V,resolvedWorkspacePath:le,canCreateMissingWorkspace:se,openBrowseDialog:Me,loadBrowsePath:ye,handleWorkspaceChoiceChange:ce,chooseCustomWorkspacePath:Ae,setCustomWorkspacePath:h,setBrowseDialogOpen:T,setActiveLauncherKind:I,openLaunchConfirm:be,handleConfirmLaunch:_e,closeLaunchConfirm:U,setWorkspaceSelectionFromOption:re,setLaunchConfirmWorkspaceKeyAndSync:Ne,setLaunchConfirmArgs:_,setLaunchConfirmModel:L,setLaunchConfirmResumeId:$,setLaunchConfirmTextFilter:ie,setLaunchConfirmWorkspaceFilter:me,setLaunchConfirmModelFilter:Y,setLaunchConfirmResumableOnly:Q,setLaunchConfirmSortMode:he}}function yA({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:n,cliProviders:a,acpProviders:r,selectedMachineNeedsUpgrade:o,appVersion:i,machineAction:c,isStandalone:d,section:p,showBottomNav:u,onBack:m,onSectionChange:f,onOpenConversation:g,onOpenRecent:k,onOpenMachineDetails:h,onMachineUpgrade:x,onLaunchDetectedIde:S,onAddWorkspace:b,onBrowseDirectory:w,onLaunchWorkspaceProvider:C,onListSavedSessions:v}){const{t:y}=ke("common"),j=R=>R==="ide"?"IDE":R==="cli"?"CLI":"ACP",N=n.slice(0,4),T=t.slice(0,3),A=vA({selectedMachineEntry:e,cliProviders:a,acpProviders:r,machineAction:c,onBrowseDirectory:w,onListSavedSessions:v}),I=l.useMemo(()=>N.map(R=>{const{metaText:W,updatedLabel:_}=Uh(R);return{key:`recent-launch:${R.id}`,primary:R.label,secondary:W,updatedLabel:_,onClick:()=>{const{options:H,selectedKey:L}=Oh({machine:{workspaces:A.workspaceRows,defaultWorkspaceId:A.defaultWorkspaceId},currentWorkspacePath:R.workspace,homeLabel:y("newSession.homeDirectory"),homeDescription:y("newSession.launchWithoutWorkspace")});A.openLaunchConfirm({title:R.kind==="ide"?qr(y,"restart-ide",R.label):R.providerSessionId?nh(y,R.label):qr(y,"start-fresh",R.label),description:R.kind==="ide"?zr(y,"restart-ide"):R.providerSessionId?ah(y):zr(y,"start-fresh"),confirmLabel:R.kind==="ide"?Kr(y,"restart-ide"):R.providerSessionId?rl(y,!0):Kr(y,"start-fresh"),busyLabel:R.kind==="ide"?Vr(y,"restart-ide"):R.providerSessionId?sh(y,!0):Vr(y,"start-fresh"),workspaceOptions:H,selectedWorkspaceKey:L,details:[{label:"Mode",value:j(R.kind)},...R.providerType?[{label:"Provider",value:R.providerType}]:[]]},async()=>{const F=H.find($=>$.key===A.launchConfirmWorkspaceKeyRef.current);A.setWorkspaceSelectionFromOption(F),await k({...R,workspace:(F==null?void 0:F.workspacePath)??null})})}}}),[A,k,N,y]),D=l.useMemo(()=>T.map(R=>({key:`recent-chat:${R.conversation.tabKey}`,primary:kt(R.conversation),secondary:qC(R.conversation,{timestampLabel:R.timestamp?Kp(R.timestamp):null}),unread:R.unread,onClick:()=>g(R.conversation)})),[g,T]),M=A.showAllRecent?I:I.slice(0,4),E=I.length>0,P=D.length>0,B=d?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${B} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:m,type:"button","aria-label":"Back",children:s.jsx(Il,{size:18})}),s.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:ds(e,{fallbackId:e.id})}),s.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[P&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:D.map(R=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${R.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:R.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:R.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:R.secondary})]},R.key))})]}),E&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:M.map(R=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:R.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:R.primary}),R.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:R.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:R.secondary})]},R.key))}),I.length>4&&s.jsx("div",{className:"flex justify-center px-4 pt-2",children:s.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>A.setShowAllRecent(R=>!R),children:A.showAllRecent?"Show fewer":`Show ${I.length-4} more`})})]}),!1,s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[o&&s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:x,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",i]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:h,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),A.browseDialogOpen&&s.jsx(mc,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:A.browseCurrentPath,directories:A.browseDirectories,busy:A.browseBusy,error:A.browseError,confirmLabel:"Use this folder",onClose:()=>A.setBrowseDialogOpen(!1),onNavigate:R=>{A.loadBrowsePath(R)},onConfirm:R=>{A.chooseCustomWorkspacePath(R),A.setBrowseDialogOpen(!1)}}),A.launchConfirm&&s.jsx(jo,{title:A.launchConfirm.title,description:A.launchConfirm.description,details:A.launchConfirm.details,workspaceOptions:A.launchConfirm.workspaceOptions,selectedWorkspaceKey:A.launchConfirmWorkspaceKey,onWorkspaceChange:A.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:A.launchConfirm.providerType?rl(y,!!A.launchConfirmResumeId):A.launchConfirm.confirmLabel,busyLabel:A.launchConfirm.providerType?void 0:A.launchConfirm.busyLabel,busy:A.launchConfirmBusy,showArgsInput:A.launchConfirm.showArgsInput,argsValue:A.launchConfirmArgs,onArgsChange:A.setLaunchConfirmArgs,showModelInput:A.launchConfirm.showModelInput,modelValue:A.launchConfirmModel,onModelChange:A.setLaunchConfirmModel,historyProviderNode:A.launchConfirm.providerType&&(A.launchConfirmSessionsLoading||A.launchConfirmSavedSessions.length>0)&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),A.launchConfirmSessionsLoading&&s.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:sc(y)}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:A.launchConfirmTextFilter,onChange:R=>A.setLaunchConfirmTextFilter(R.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:A.launchConfirmBusy||A.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:A.launchConfirmWorkspaceFilter,onChange:R=>A.setLaunchConfirmWorkspaceFilter(R.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:A.launchConfirmBusy||A.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:A.launchConfirmModelFilter,onChange:R=>A.setLaunchConfirmModelFilter(R.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:A.launchConfirmBusy||A.launchConfirmSessionsLoading}),s.jsxs("select",{value:A.launchConfirmSortMode,onChange:R=>A.setLaunchConfirmSortMode(R.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:A.launchConfirmBusy||A.launchConfirmSessionsLoading,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:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:A.launchConfirmResumableOnly,onChange:R=>A.setLaunchConfirmResumableOnly(R.target.checked),disabled:A.launchConfirmBusy||A.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:A.launchConfirmResumeId,onChange:R=>A.setLaunchConfirmResumeId(R.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:A.launchConfirmBusy||A.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:Sj(y)}),A.filteredLaunchConfirmSavedSessions.map(R=>s.jsxs("option",{value:R.providerSessionId,disabled:!R.canResume,children:[R.title||R.providerSessionId," ",R.canResume?"":"(workspace missing)"]},R.providerSessionId))]}),!A.launchConfirmSessionsLoading&&A.launchConfirmSavedSessions.length>0&&A.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),A.launchConfirmResumeId&&(()=>{const R=A.filteredLaunchConfirmSavedSessions.find(_=>_.providerSessionId===A.launchConfirmResumeId);if(!R)return null;const W=Wh(R);return s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:W.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:W.providerSessionId}),s.jsx("div",{className:"mt-1",children:W.metaLine}),W.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:W.updatedLabel}),W.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:W.preview})]})})()]}),onConfirm:A.handleConfirmLaunch,onCancel:A.closeLaunchConfirm}),u&&s.jsx(Bh,{section:p,onSectionChange:f})]})}const au=8e3;function wA(e){const t=e&&typeof e=="object"&&"result"in e?e.result:e,n=t&&typeof t=="object",a=n&&t.success===!1,r=n&&t.mirrorStale===!0;return!a&&!r?{confirmed:!0}:{confirmed:!1,reason:a&&typeof t.error=="string"?t.error:r?"the coordinator did not confirm the change":"command was rejected"}}function Gh(e,t,n){const a=l.useRef(new Map),[,r]=l.useState(0),o=l.useCallback(()=>r(g=>g+1),[]);l.useEffect(()=>{const g=a.current;if(g.size===0)return;const k=Date.now();let h=!1;for(const[x,S]of g){const b=e.get(x),w=S.muted===void 0||(b?b.muted===S.muted:!1),C=S.hidden===void 0||(b?b.surfaceHidden===S.hidden:!1),v=k-S.at>au;(w&&C||v)&&(g.delete(x),h=!0)}h&&o()},[e,o]),l.useEffect(()=>{if(a.current.size===0)return;const g=setInterval(()=>{const k=a.current,h=Date.now();let x=!1;for(const[S,b]of k)h-b.at>au&&(k.delete(S),x=!0);x&&o(),k.size===0&&clearInterval(g)},1e3);return()=>clearInterval(g)});const i=l.useCallback((g,k)=>{const h=a.current.get(g);a.current.set(g,{...h,...k,at:Date.now()}),o()},[o]),c=l.useCallback(g=>{const k=g.sessionId,h=k?a.current.get(k):void 0;return(h==null?void 0:h.muted)!==void 0?h.muted:an(g,e).muted??!1},[e]),d=l.useCallback(g=>{const k=g.sessionId,h=k?a.current.get(k):void 0;return(h==null?void 0:h.hidden)!==void 0?h.hidden:an(g,e).surfaceHidden??!1},[e]),p=l.useCallback((g,k)=>{const h=Ks(g),x=g.sessionId;!h||!x||(i(x,k),t(h,"set_conversation_prefs",{sessionId:x,...k,...yo(g)}).then(S=>{const b=wA(S);b.confirmed||(console.warn("[conversation-prefs] set_conversation_prefs not confirmed",b.reason),a.current.delete(x),o(),n==null||n(`Couldn't update conversation — ${b.reason}`))}).catch(S=>{console.warn("[conversation-prefs] set_conversation_prefs failed",S),a.current.delete(x),o();const b=S instanceof Error?S.message:String(S??"the daemon is unreachable");n==null||n(`Couldn't update conversation — ${b}`)}))},[t,i,o,n]),u=l.useCallback(g=>{p(g,{muted:!c(g)})},[p,c]),m=l.useCallback((g,k)=>{p(g,{hidden:k})},[p]),f=l.useCallback(g=>{p(g,{hidden:!d(g)})},[p,d]);return{isMuted:c,isHidden:d,toggleMute:u,setHidden:m,toggleHidden:f}}function Dr(e){return[...e].sort((t,n)=>{const a=n.timestamp-t.timestamp;return a!==0?a:t.conversation.tabKey.localeCompare(n.conversation.tabKey)})}function kA(e,t=[]){const n=new Map(e.map(r=>[r.conversation.tabKey,r])),a=t.map(r=>n.get(r)).filter(r=>!!r);return a.length===e.length?a:Dr(e)}function SA(e,t=[]){const n=e.filter(i=>i.requiresAction),a=e.filter(i=>i.unread&&!i.requiresAction),r=e.filter(i=>!i.unread&&!i.requiresAction&&i.isWorking),o=e.filter(i=>!i.unread&&!i.requiresAction&&!i.isWorking);return{attentionItems:Dr(n),unreadItems:Dr(a),workingItems:kA(r,t),completedItems:Dr(o)}}function No(e,t){if(!t)return!1;const n=e.filter(a=>a.type==="adhdev-daemon"&&qh(a)==="Connected");return n.length===0?!0:n.every(a=>a._sessionListAuthoritative===!0)}function qh(e){var a,r,o;const t=((a=e.p2p)==null?void 0:a.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":!(!!((r=e.p2p)!=null&&r.available)||!!((o=e.p2p)!=null&&o.state))&&e.status&&e.status!=="offline"?"Connected":"Offline"}function CA(e,t){if(!e)return[];const n=e.recentLaunches||[];return n.length>0?n.map(a=>({id:a.id,label:a.title||a.providerName||a.providerType,kind:a.kind,providerType:a.providerType,providerSessionId:a.providerSessionId,subtitle:Tn(a.summaryMetadata)||a.workspace||void 0,workspace:a.workspace,summaryMetadata:a.summaryMetadata})):t.filter(a=>a.type!=="adhdev-daemon"&&a.daemonId===e.id).map(a=>{var i;const r=$a(a)?"cli":Jn(a)?"acp":"ide",o=Tn(a.summaryMetadata);return{id:`${r}:${a.type}:${a.workspace||""}`,label:((i=a.activeChat)==null?void 0:i.title)||($a(a)?a.cliName||a.type:Jn(a)&&a.cliName||a.type),kind:r,providerType:a.type,providerSessionId:a.providerSessionId,subtitle:Jn(a)?o||a.workspace||void 0:a.workspace||void 0,workspace:a.workspace||void 0,timestamp:a.lastMessageAt||0}}).sort((a,r)=>r.timestamp-a.timestamp).map(({timestamp:a,...r})=>r)}function jA(e,t,n=[]){const a=new Map;for(const o of t){const i=Ks(o.conversation),c=a.get(i);c?c.push(o):a.set(i,[o])}const r=new Map;for(const o of n){const i=Ks(o),c=r.get(i);c?c.push(o):r.set(i,[o])}return e.map(o=>{const i=a.get(o.id)||[],c=r.get(o.id)||[],d=[...i].sort((h,x)=>x.timestamp-h.timestamp)[0]||null,p=(d==null?void 0:d.conversation)||null,u=Xi(o),m=i.filter(h=>h.unread||h.requiresAction).length,f=i.filter(h=>_a(h.conversation)).length+c.filter(_a).length,g=qh(o),k=[o.platform||"machine",g].filter(Boolean);return{id:o.id,label:ds(o,{fallbackId:o.id}),subtitle:k.join(" · "),unread:m,total:i.length,generatingCount:f,latestConversation:p,latestTimestamp:(d==null?void 0:d.timestamp)||0,fallbackActivityAt:u,preview:p?zC(p,Om(p)):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((o,i)=>{const c=o.latestTimestamp||o.fallbackActivityAt||0,d=i.latestTimestamp||i.fallbackActivityAt||0;return d!==c?d-c:o.label.localeCompare(i.label)})}function NA(e){return e==="chat"}function pr(e,t){var n;if(!(typeof window>"u"))try{if(!(!!((n=import.meta.env)!=null&&n.DEV)||window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[mobile-read] ${e}`,t)}catch{}}function AA({conversations:e,machineEntries:t,items:n,selectedConversation:a,selectedTabKey:r,screen:o,liveSessionInboxState:i,sendDaemonCommand:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,setSelectedTabKey:k,setScreen:h,setSelectedMachineId:x,setSection:S,setMachineBackTarget:b,resetMachineAction:w}){const C=l.useRef(null),v=l.useCallback(y=>{if(!(y!=null&&y.sessionId))return;const j=an(y,i),N=Math.max(Date.now(),jn(y),j.lastUpdated||0);pr("mark_read:start",{tabKey:y.tabKey,sessionId:y.sessionId,displayPrimary:kt(y),inboxBucket:j.inboxBucket,unread:j.unread,lastSeenAt:j.lastSeenAt,lastUpdated:j.lastUpdated,activityAt:jn(y),readAt:N}),c(Ks(y)||y.routeId,"mark_session_seen",{sessionId:y.sessionId,providerSessionId:y.providerSessionId,seenAt:N,completionMarker:j.completionMarker}).then(T=>{pr("mark_read:result",{tabKey:y.tabKey,sessionId:y.sessionId,result:T})}).catch(T=>{pr("mark_read:error",{tabKey:y.tabKey,sessionId:y.sessionId,error:T instanceof Error?T.message:String(T)})})},[i,c]);return l.useEffect(()=>{var j;if(!a){NA(o)&&h("inbox"),k(((j=e[0])==null?void 0:j.tabKey)||null),C.current=null;return}if(o!=="chat"){C.current=null;return}const y=`${a.tabKey}:${a.sessionId||""}`;C.current!==y&&(C.current=y,v(a))},[e,v,o,a,h,k]),l.useEffect(()=>{if(!d)return;const y=e.find(j=>j.tabKey===d);y&&(k(y.tabKey),h("chat"),p==null||p())},[e,p,d,h,k]),l.useEffect(()=>{if(!u)return;const y=t.find(j=>j.id===u);y&&(x(y.id),w(),S("machines"),b("inbox"),h("machine"),m==null||m())},[t,m,u,w,b,h,S,x]),l.useEffect(()=>{f&&(S(f),h("inbox"),g==null||g())},[g,f,h,S]),l.useEffect(()=>{const y=n.filter(j=>j.inboxBucket==="task_complete"||j.unread);y.length!==0&&pr("inbox_state",{screen:o,selectedTabKey:r,items:y.map(j=>{const N=an(j.conversation,i);return{liveState:N,tabKey:j.conversation.tabKey,sessionId:j.conversation.sessionId,displayPrimary:kt(j.conversation),serverBucket:N.inboxBucket,computedBucket:j.inboxBucket,serverUnread:N.unread,computedUnread:j.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:jn(j.conversation)}})})},[n,i,o,r]),{markConversationRead:v}}function TA(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function ru(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function MA(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function PA({sendDaemonCommand:e,navigate:t,ides:n,conversations:a}){const{launchCli:r}=ho(),[o,i]=l.useState("idle"),[c,d]=l.useState(""),[p,u]=l.useState(null),m=l.useCallback(()=>{i("idle"),d(""),u(null)},[]),f=l.useCallback(async(w,C,v)=>{var y;try{i("loading"),d(`Launching ${C}…`);const j={ideType:C,enableCdp:!0};(y=v==null?void 0:v.workspacePath)!=null&&y.trim()&&(j.workspace=v.workspacePath.trim()),await e(w,"launch_ide",j),i("done"),d(`${C} launch requested`)}catch(j){i("error"),d(j instanceof Error?j.message:"Launch IDE failed"),console.error("Launch IDE failed",j)}},[e]),g=l.useCallback(async(w,C,v)=>{if(C.trim())try{i("loading"),d(v!=null&&v.createIfMissing?"Creating folder…":"Saving workspace…");const y=await e(w,"workspace_add",{path:C.trim(),createIfMissing:(v==null?void 0:v.createIfMissing)===!0});if(y!=null&&y.success){i("done"),d(v!=null&&v.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),d((y==null?void 0:y.error)||"Could not save workspace")}catch(y){i("error"),d(y instanceof Error?y.message:"Could not save workspace")}},[e]),k=l.useCallback(async w=>{i("loading"),d("Starting daemon upgrade…");const C=n.find(y=>y.id===w||y.daemonId===w),v=await y1(e,w,C);i(v.state),d(v.message)},[n,e]),h=l.useCallback(async(w,C,v,y)=>{var T,A,I;const j=Date.now(),N={machineId:w,kind:C,providerType:v,workspaceId:(y==null?void 0:y.workspaceId)||null,workspacePath:(y==null?void 0:y.workspacePath)||null,resumeSessionId:(y==null?void 0:y.resumeSessionId)||null,startedAt:j};try{i("loading"),d(`Launching ${v}…`),u(N);const D={cliType:v};(T=y==null?void 0:y.workspacePath)!=null&&T.trim()?D.dir=y.workspacePath.trim():y!=null&&y.workspaceId?D.workspaceId=y.workspaceId:y!=null&&y.useHome&&(D.useHome=!0),y!=null&&y.resumeSessionId&&(D.resumeSessionId=y.resumeSessionId),(A=y==null?void 0:y.args)!=null&&A.trim()&&(D.cliArgs=y.args.trim().split(/\s+/).filter(Boolean)),(I=y==null?void 0:y.model)!=null&&I.trim()&&(D.initialModel=y.model.trim());const M=await r(w,D),E=(M==null?void 0:M.result)||M,P=(E==null?void 0:E.sessionId)||(E==null?void 0:E.id);if(M!=null&&M.success&&P){u(null),i("done"),d(`${v} launched`),t(Ba(P));return}if(M!=null&&M.success){i("loading"),d(`${v} launch requested — waiting for session…`);return}u(null),i("error"),d((M==null?void 0:M.error)||(E==null?void 0:E.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(D){if(MA(D)){i("loading"),d(`${v} launch requested — waiting for session…`);return}u(null),i("error"),d(D instanceof Error?D.message:`Could not launch ${C.toUpperCase()} workspace`)}},[t,e]),x=l.useCallback(async(w,C)=>{try{const v=await e(w,"list_saved_sessions",{providerType:C,kind:"cli",limit:30}),y=(v==null?void 0:v.result)??v;return Array.isArray(y==null?void 0:y.sessions)?y.sessions:[]}catch(v){return console.error("Failed to list saved sessions on mobile:",v),[]}},[e]),S=l.useCallback(async(w,C)=>uc(e,w,C),[e]);l.useEffect(()=>{if(!p)return;const w=ru(p.workspacePath),C=n.find(y=>{var D,M,E,P;if(!y||y.type==="adhdev-daemon"||TA(y.daemonId||y.id)!==p.machineId||(y.transport==="acp"?"acp":y.transport==="pty"?"cli":null)!==p.kind||String(y.agentType||y.type||"")!==p.providerType)return!1;const A=String(y.providerSessionId||"");if(p.resumeSessionId&&A)return A===p.resumeSessionId;if(w){const B=ru(y.workspace||y.runtimeWorkspaceLabel);return B?B===w:!1}return Number(y.lastUpdated||y._lastUpdate||y.timestamp||((P=(E=(M=(D=y.activeChat)==null?void 0:D.messages)==null?void 0:M.at)==null?void 0:E.call(M,-1))==null?void 0:P.timestamp)||0)>=p.startedAt-5e3});if(!C)return;const v=Hh({entrySessionId:C.sessionId,entryInstanceId:C.instanceId,entryRouteId:C.id,conversations:a});v&&(u(null),i("done"),d(`${p.providerType} launched`),t(Ba(v)))},[a,n,t,p]),l.useEffect(()=>{if(!p)return;const w=window.setTimeout(()=>{u(C=>!C||C.startedAt!==p.startedAt?C:(i("error"),d("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(w)},[p]);const b=l.useCallback(async(w,C)=>{var v;if(C.kind==="ide"&&C.providerType){await f(w,C.providerType,{workspacePath:C.workspace||null});return}if((C.kind==="cli"||C.kind==="acp")&&C.providerType){const y=((v=C.workspace)==null?void 0:v.trim())||"";await h(w,C.kind,C.providerType,{workspacePath:y||null,useHome:!y,resumeSessionId:C.providerSessionId||null})}},[f,h]);return{machineAction:{state:o,message:c},resetMachineAction:m,handleLaunchDetectedIde:f,handleAddWorkspace:g,handleMachineUpgrade:k,handleLaunchWorkspaceProvider:h,handleListSavedSessions:x,handleBrowseDirectory:S,handleOpenRecent:b}}function DA({conversations:e,selectedConversation:t,machineBackTarget:n,markConversationRead:a,resetMachineAction:r,setSelectedTabKey:o,setScreen:i,setSelectedMachineId:c,setSection:d,setMachineBackTarget:p}){const u=l.useCallback(S=>{o(S.tabKey),i("chat"),a(S)},[a,i,o]),m=l.useCallback(S=>{const b=e.find(w=>w.routeId===S.routeId&&w.streamSource==="native");b&&(o(b.tabKey),i("chat"),a(b))},[e,a,i,o]),f=l.useCallback(()=>{a(t),i("inbox")},[a,t,i]),g=l.useCallback((S,b="inbox")=>{c(S),r(),d("machines"),p(b),i("machine")},[r,p,i,d,c]),k=l.useCallback(S=>{const b=Ks(S);b&&g(b,"chat")},[g]),h=l.useCallback(()=>{r(),i(n)},[n,r,i]),x=l.useCallback(S=>{d(S),i("inbox")},[i,d]);return{openConversation:u,openNativeConversation:m,backFromConversation:f,openMachine:g,openConversationMachine:k,backFromMachine:h,changeMachineSection:x}}function na(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function IA(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function LA({conversations:e,hiddenConversations:t,ides:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,userName:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,onOpenHistory:k,onOpenRemote:h,onStopCli:x,wsStatus:S,isConnected:b,initialDataLoaded:w=!0,onShowAllHiddenConversations:C,onHideConversation:v,onOpenMeshGraph:y,onOpenNewSession:j,liveSessionInboxState:N,setCliViewModeOverrides:T}){const[A,I]=l.useState(()=>{var ce;return((ce=e[0])==null?void 0:ce.tabKey)||null}),[D,M]=l.useState(()=>e[0]?"chat":"inbox"),[E,P]=l.useState("chats"),[B,R]=l.useState(null),[W,_]=l.useState("inbox"),H=l.useRef([]),L=oa(),F="1.0.53",$=l.useMemo(()=>e.find(ce=>ce.tabKey===A)||e[0]||null,[e,A]),K=l.useMemo(()=>$?n.find(ce=>ce.id===$.routeId):void 0,[n,$]),z=l.useMemo(()=>!$||ht($)||!bt($)?null:la($),[$]),ne=l.useMemo(()=>n.filter(ce=>ce.type==="adhdev-daemon").sort(Ul),[n]),ie=l.useMemo(()=>ne.find(ce=>ce.id===B)||null,[ne,B]),Ce=wo({sendDaemonCommand:r,activeConv:$||void 0,setActionLogs:o,isStandalone:i}),me=PA({sendDaemonCommand:r,navigate:L,ides:n,conversations:e}),O=wC(e),Y=l.useMemo(()=>e.map(ce=>{const Ae=D==="chat"&&($==null?void 0:$.tabKey)===ce.tabKey,be=fo(ce,N,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Ae}),we=jn(ce),_e=Om(ce),U=Ym(ce,_e);return{conversation:ce,timestamp:we,preview:U,unread:be.unread,requiresAction:be.requiresAction,isWorking:be.isWorking,inboxBucket:be.inboxBucket}}),[e,N,D,$,O]),{markConversationRead:X}=AA({conversations:e,machineEntries:ne,items:Y,selectedConversation:$,selectedTabKey:A,screen:D,liveSessionInboxState:N,sendDaemonCommand:r,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,setSelectedTabKey:I,setScreen:M,setSelectedMachineId:R,setSection:P,setMachineBackTarget:_,resetMachineAction:me.resetMachineAction}),Q=DA({conversations:e,selectedConversation:$,machineBackTarget:W,markConversationRead:X,resetMachineAction:me.resetMachineAction,setSelectedTabKey:I,setScreen:M,setSelectedMachineId:R,setSection:P,setMachineBackTarget:_}),{isMuted:ve,toggleMute:he}=Gh(N,r),{attentionItems:Z,unreadItems:fe,workingItems:V,completedItems:q}=l.useMemo(()=>SA(Y,H.current),[Y]);l.useEffect(()=>{H.current=V.map(ce=>ce.conversation.tabKey)},[V]);const ee=l.useMemo(()=>ie?Y.filter(ce=>Ks(ce.conversation)===ie.id):[],[Y,ie]),pe=l.useMemo(()=>CA(ie,n),[n,ie]),le=!!ie&&So(ie,Qs(ie,F)),se=l.useMemo(()=>(ie==null?void 0:ie.availableProviders)||[],[ie]),te=l.useMemo(()=>se.filter(ce=>na(ce,"cli")).map(ce=>({type:ce.type,displayName:ce.displayName||ce.type,icon:ce.icon})),[se]),ue=l.useMemo(()=>se.filter(ce=>na(ce,"acp")).map(ce=>({type:ce.type,displayName:ce.displayName||ce.type,icon:ce.icon})),[se]),ye=l.useMemo(()=>jA(ne,Y,t),[Y,ne,t]),Me=l.useMemo(()=>No(n,w),[n,w]),re=l.useCallback(async ce=>{ie&&await me.handleOpenRecent(ie.id,ce)},[me,ie]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:D==="chat"&&$?s.jsx(uA,{selectedConversation:$,isAcp:ht($),isStandalone:i,selectedIdeEntry:K,actionLogs:a,userName:c,isSendingChat:Ce.isSendingChat,sendFeedbackMessage:Ce.sendFeedbackMessage,isFocusingAgent:Ce.isFocusingAgent,handleModalButton:Ce.handleModalButton,handleRelaunch:Ce.handleRelaunch,onBack:Q.backFromConversation,onOpenNativeConversation:Q.openNativeConversation,onOpenMachine:Q.openConversationMachine,onOpenHistory:k,onOpenRemote:h,onOpenMeshGraph:y,onStopCli:x,cliViewMode:z,onSetCliViewMode:async ce=>{await Ah({conversation:$,mode:ce,ides:n,sendDaemonCommand:r,setCliViewModeOverrides:T})},handleSendChat:Ce.handleSendChat,handleForceSendChat:Ce.handleForceSendChat,handleFocusAgent:Ce.handleFocusAgent}):D==="machine"&&ie?s.jsx(yA,{selectedMachineEntry:ie,selectedMachineConversations:ee,selectedMachineRecentLaunches:pe,cliProviders:te,acpProviders:ue,selectedMachineNeedsUpgrade:le,appVersion:F,machineAction:me.machineAction,isStandalone:i,section:E,showBottomNav:W==="inbox",onBack:Q.backFromMachine,onSectionChange:Q.changeMachineSection,onOpenConversation:Q.openConversation,onOpenRecent:re,onOpenMachineDetails:()=>L(`/machines/${ie.id}`),onMachineUpgrade:()=>me.handleMachineUpgrade(ie.id),onLaunchDetectedIde:(ce,Ae)=>me.handleLaunchDetectedIde(ie.id,ce,Ae),onAddWorkspace:(ce,Ae)=>me.handleAddWorkspace(ie.id,ce,Ae),onBrowseDirectory:ce=>me.handleBrowseDirectory(ie.id,ce),onLaunchWorkspaceProvider:(ce,Ae,be)=>me.handleLaunchWorkspaceProvider(ie.id,ce,Ae,be),onListSavedSessions:ce=>me.handleListSavedSessions(ie.id,ce)}):s.jsx(hA,{section:E,attentionItems:Z,unreadItems:fe,workingItems:V,completedItems:q,hiddenConversations:t,machineCards:ye,getAvatarText:IA,actionLogs:a,sendDaemonCommand:r,onOpenConversation:Q.openConversation,onShowAllHidden:C,onHideConversation:v,onOpenMeshGraph:y,onStopCli:x,onOpenNewSession:j,onOpenMachine:Q.openMachine,onOpenSettings:()=>L("/settings"),onSectionChange:P,wsStatus:S,isConnected:b,initialDataLoaded:w,conversationsLoaded:Me,isStandalone:i,isConversationMuted:ve,onToggleMuteConversation:he})})}function ii(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function RA({conversations:e,numGroups:t,onMoveTab:n,onReceiveTab:a,onOwnTabDrop:r,onClearPreviewOrder:o}){const i=l.useRef(0),[c,d]=l.useState(!1),[p,u]=l.useState(null),m=l.useCallback(()=>{i.current=0,d(!1),u(null)},[]);l.useEffect(()=>(window.addEventListener("dragend",m),window.addEventListener("drop",m),()=>{window.removeEventListener("dragend",m),window.removeEventListener("drop",m)}),[m]);const f=l.useCallback(x=>{x.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,d(!0))},[]),g=l.useCallback(x=>{if(!x.dataTransfer.types.includes("text/tab-key"))return;if(x.preventDefault(),!ii(t,n)){u("merge");return}const S=x.currentTarget.getBoundingClientRect(),b=x.clientX-S.left,w=S.width/3;b<w?u("split-left"):b>w*2?u("split-right"):u("merge")},[t,n]),k=l.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,d(!1),u(null))},[]),h=l.useCallback(x=>{i.current=0,d(!1);const S=x.dataTransfer.getData("text/tab-key"),b=S?e.some(C=>C.tabKey===S):!1,w=p;if(u(null),o(),!!S){if(x.preventDefault(),w==="split-left"&&ii(t,n)){n==null||n(S,"split-left");return}if(w==="split-right"&&ii(t,n)){n==null||n(S,"split-right");return}if(b){r(S);return}a==null||a(S)}},[e,p,t,n,a,r,o]);return{dragOver:c,dropAction:p,resetDragState:m,handleDragEnter:f,handleDragOver:g,handleDragLeave:k,handleDrop:h}}function EA(e,t){const n=new Set(t.map(o=>o.tabKey)),a=e.filter(o=>n.has(o)),r=t.filter(o=>!e.includes(o.tabKey)).map(o=>o.tabKey);return[...a,...r]}function _A({conversations:e,initialActiveTabId:t,initialTabOrder:n,onActiveTabChange:a,onTabOrderChange:r}){const[o,i]=l.useState(t??null),[c,d]=l.useState(n??[]),[p,u]=l.useState(null),m=l.useRef(null),f=l.useRef(null),g=l.useRef(a),k=l.useRef(r);l.useEffect(()=>{g.current=a},[a]),l.useEffect(()=>{k.current=r},[r]),l.useEffect(()=>{t&&t!==o&&i(t)},[t,o]),l.useEffect(()=>{d(j=>{const N=EA(j,e);return N.length===j.length&&N.every((T,A)=>T===j[A])?j:N})},[e]);const h=l.useMemo(()=>{const j=p??c;if(j.length===0)return e;const N=new Map(j.map((T,A)=>[T,A]));return[...e].sort((T,A)=>{const I=N.get(T.tabKey)??999,D=N.get(A.tabKey)??999;return I-D})},[e,p,c]);l.useEffect(()=>{var N,T;if(h.length===0){o!==null&&(i(null),(N=g.current)==null||N.call(g,null));return}if(o&&h.some(A=>A.tabKey===o))return;const j=h[0].tabKey;j!==o&&(i(j),(T=g.current)==null||T.call(g,j))},[h,o]);const x=l.useMemo(()=>h.find(j=>j.tabKey===o),[h,o]),S=l.useCallback(j=>{var N;i(j),(N=g.current)==null||N.call(g,j)},[]),b=l.useCallback((j,N,T)=>{d(A=>{var E;const I=A.filter(P=>P!==j),D=I.indexOf(N);if(D<0)return A;const M=T==="left"?D:D+1;return I.splice(M,0,j),(E=k.current)==null||E.call(k,I),I}),u(null)},[]),w=l.useCallback((j,N,T)=>{const I=(c.length>0?c:e.map(E=>E.tabKey)).filter(E=>E!==j),D=I.indexOf(N);if(D<0)return;const M=T==="left"?D:D+1;I.splice(M,0,j),m.current=I,u(I)},[c,e]),C=l.useCallback(()=>{var N;const j=m.current;j&&(d(j),(N=k.current)==null||N.call(k,j))},[]),v=l.useCallback(()=>{m.current=null,u(null)},[]),y=l.useCallback(j=>{d(N=>{var A;const T=N.filter(I=>I!==j);return T.push(j),(A=k.current)==null||A.call(k,T),T})},[]);return{activeTabId:o,activeConv:x,sortedConversations:h,previewOrderRef:m,draggingTabRef:f,selectTab:S,handleTabReorder:b,updatePreviewOrder:w,commitPreviewOrder:C,clearPreviewOrder:v,moveTabToEnd:y,setDraggingTabKey:j=>{f.current=j}}}function HA({dropAction:e,canSplit:t}){return s.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[s.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-left"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-left"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Left"})}),s.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="merge"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="merge"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)"},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Move Here"})}),s.jsx("div",{className:"flex-1 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-right"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-right"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Right"})})]})}function hc({conversationsCount:e,isSplitMode:t,isStandalone:n,hasRegisteredMachines:a=!1,suppressGuide:r=!1,onOpenNewSession:o,isLoading:i=!1}){const{t:c}=ke("common");if(r)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});if(i)return s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center gap-3 -mt-8 text-text-muted",children:[s.jsx(ls,{}),s.jsx("p",{className:"text-sm",children:c("paneGroup.loadingSessions")})]});const d=!n&&!a,p=a&&!!o,u=c(a?"paneGroup.noConversations":n?"paneGroup.waitingForDaemon":"paneGroup.connectYourMachines"),m=c(a?"paneGroup.newSessionDescription":n?"paneGroup.daemonDescription":"paneGroup.installDescription");return e===0&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:u}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:m}),p&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:o,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:c("paneGroup.newSession"),"aria-label":c("paneGroup.newSession"),children:[s.jsx(Hl,{size:14}),s.jsx("span",{children:c("paneGroup.newSession")})]})}),d&&s.jsx(Fh,{}),d&&s.jsx("div",{className:"mt-8",children:s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:"Read the documentation →"})})]})]}):s.jsx("div",{className:"text-sm text-text-muted opacity-50",children:t?"Move a tab here to view":"No active agent"})}const zh="adhdev-tab-shortcuts";function Kh(){try{return JSON.parse(localStorage.getItem(zh)||"{}")}catch{return{}}}function Vh({enabled:e=!0,sortedTabKeys:t,onFocus:n,onSelectTab:a}){const r=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>Kh()),[c,d]=l.useState(null),p=l.useCallback(m=>{const f=[];return m.metaKey&&f.push(r?"⌘":"Meta"),m.ctrlKey&&f.push("Ctrl"),m.altKey&&f.push(r?"⌥":"Alt"),m.shiftKey&&f.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(m.key)?null:(f.push(m.key.length===1?m.key.toUpperCase():m.key),f.join("+"))},[r]),u=l.useCallback(m=>{i(m);try{localStorage.setItem(zh,JSON.stringify(m))}catch{}},[]);return l.useEffect(()=>{if(!e||!c)return;const m=f=>{if(f.preventDefault(),f.stopPropagation(),f.key==="Escape"){d(null);return}const g=p(f);if(!g)return;const k={...o};for(const[h,x]of Object.entries(k))x===g&&delete k[h];k[c]=g,u(k),d(null)};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[e,c,o,u,p]),l.useEffect(()=>{if(!e)return;const m=f=>{if(!(!f.ctrlKey&&!f.metaKey&&!f.altKey)){for(const[g,k]of Object.entries(o))if(t.includes(g)&&p(f)===k){f.preventDefault(),n(),a(g);return}}};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[e,o,t,n,a,p]),{isMac:r,tabShortcuts:o,shortcutListening:c,setShortcutListening:d,saveShortcuts:u}}const li=e=>{e.preventDefault()},$A=l.memo(function({conv:t,isActive:n,isDraggedTab:a,isTaskCompleteUnread:r,shortcut:o,conversationKeys:i,draggingTabRef:c,onFocus:d,onSelectTab:p,onConversationActivated:u,onPreviewReorder:m,onReorderTab:f,onCommitPreviewOrder:g,onClearPreviewOrder:k,onDragStateReset:h,onDragTabKeyChange:x,onReceiveTab:S,onOpenContextMenu:b,longPressTimer:w,isGroupActive:C}){const v=Rn(t),y=v.isGenerating?"agent-tab-generating":v.isWaiting?"agent-tab-waiting":"",j=v.isReconnecting,N=UC(t),T=GC(t),A=Vm(t),I=l.useCallback(H=>{c.current=t.tabKey,x(t.tabKey),H.dataTransfer.setData("text/tab-key",t.tabKey),H.dataTransfer.effectAllowed="move"},[t.tabKey,c,x]),D=l.useCallback(()=>{c.current=null,x(null),g(),k(),h()},[c,x,g,k,h]),M=l.useCallback(H=>{const L=c.current;if(!(!L||L===t.tabKey)&&H.dataTransfer.types.includes("text/tab-key")){H.preventDefault(),H.stopPropagation();const F=H.currentTarget.getBoundingClientRect(),$=H.clientX<F.left+F.width/2?"left":"right";m(L,t.tabKey,$)}},[t.tabKey,c,m]),E=l.useCallback(H=>{H.preventDefault(),H.stopPropagation();const L=H.dataTransfer.getData("text/tab-key");if(L&&L!==t.tabKey){const F=H.currentTarget.getBoundingClientRect(),$=H.clientX<F.left+F.width/2?"left":"right";i.includes(L)?f(L,t.tabKey,$):S&&S(L)}k()},[t.tabKey,i,f,S,k]),P=l.useCallback(H=>{H.stopPropagation(),d(),p(t.tabKey),u(t)},[t,u,d,p]),B=l.useCallback(H=>{H.preventDefault(),b(H.clientX,H.clientY,t.tabKey)},[t.tabKey,b]),R=l.useCallback(H=>{const L=H.touches[0];w.current=setTimeout(()=>{b(L.clientX,L.clientY,t.tabKey)},600)},[t.tabKey,w,b]),W=l.useCallback(()=>{w.current&&clearTimeout(w.current)},[w]),_=["adhdev-dockview-tab",y,n&&"is-active",C&&"is-group-active",j&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:_,draggable:!0,onDragStart:I,onDragEnd:D,onDragOver:M,onDrop:E,onClick:P,onContextMenu:B,onTouchStart:R,onTouchEnd:W,onTouchMove:W,style:{position:"relative",cursor:"pointer",opacity:a?.4:void 0},children:[A&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-badge pointer-events-none absolute top-0.5 right-0.5 text-text-muted",title:"Mesh chat","aria-label":"Mesh chat",children:s.jsx(cs,{size:11})}),r&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:v.isGenerating?s.jsx(ls,{size:12,thickness:2,color:"success"}):v.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):j?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):v.isConnecting?s.jsx(ls,{size:12,thickness:2}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),N.length>0&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-role",title:T,"aria-label":T||N.join(" · "),children:N.join(" · ")}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:kt(t),children:kt(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[j?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:kn(t)}):v.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[kn(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:kn(t)}),s.jsx(Gr,{git:t.git,compact:!0,className:"max-w-[6.5rem] shrink-0"})]})]}),o&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${o}`,children:o})]})},(e,t)=>e.conv===t.conv&&e.isActive===t.isActive&&e.isDraggedTab===t.isDraggedTab&&e.isTaskCompleteUnread===t.isTaskCompleteUnread&&e.shortcut===t.shortcut&&e.conversationKeys===t.conversationKeys&&e.isGroupActive===t.isGroupActive);function FA({conversations:e,activeTabId:t,groupIndex:n,unreadTabKeys:a,draggingTabRef:r,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:m,onDragStateReset:f,onDragTabKeyChange:g,onReceiveTab:k,onHideTab:h,isGroupActive:x,allowTabShortcuts:S=!0}){const{t:b}=ke("common"),[w,C]=l.useState(null),v=l.useRef(null),y=l.useRef(null),j=l.useMemo(()=>e.map(E=>E.tabKey),[e]);Ga("PaneGroupTabBar",{groupIndex:n,activeTabId:t,tabCount:e.length,ctxMenuTab:(w==null?void 0:w.tabKey)||null});const{isMac:N,tabShortcuts:T,shortcutListening:A,setShortcutListening:I,saveShortcuts:D}=Vh({enabled:S,sortedTabKeys:e.map(E=>E.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!w)return;const E=P=>{const B=document.querySelector("[data-pane-context-menu]");B&&B.contains(P.target)||C(null)};return window.addEventListener("mousedown",E,!0),()=>window.removeEventListener("mousedown",E,!0)},[w]),l.useEffect(()=>{const E=y.current;if(!E)return;const P=B=>{Math.abs(B.deltaY)<=Math.abs(B.deltaX)||(B.preventDefault(),E.scrollLeft+=B.deltaY)};return E.addEventListener("wheel",P,{passive:!1}),()=>E.removeEventListener("wheel",P)},[]);const M=l.useCallback((E,P,B)=>{C({x:E,y:P,tabKey:B})},[]);return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:s.jsxs("div",{ref:y,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(E=>s.jsx($A,{conv:E,isActive:t===E.tabKey,isDraggedTab:r.current===E.tabKey,isTaskCompleteUnread:a.has(E.tabKey),shortcut:S?T[E.tabKey]:void 0,conversationKeys:j,draggingTabRef:r,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:m,onDragStateReset:f,onDragTabKeyChange:g,onReceiveTab:k,onOpenContextMenu:M,longPressTimer:v,isGroupActive:x},E.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:b("paneGroup.noTabsInGroup")})]})}),w&&s.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:w.x,top:w.y},children:[S&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:li,onClick:E=>{E.stopPropagation(),I(w.tabKey),C(null)},children:["⌨ ",T[w.tabKey]?`Change shortcut (${T[w.tabKey]})`:"Set shortcut"]}),T[w.tabKey]&&s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onMouseDown:li,onClick:()=>{const E={...T};delete E[w.tabKey],D(E),C(null)},children:"✕ Remove shortcut"})]}),h&&s.jsxs(s.Fragment,{children:[S&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onMouseDown:li,onClick:()=>{h(w.tabKey),C(null)},children:s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx(po,{size:12}),"Hide from Dashboard"]})})]})]}),S&&A&&s.jsx(Vt,{children:s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:()=>I(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:E=>E.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",N?"⌘+1":"Ctrl+1",", ",N?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:b("paneGroup.pressEscToCancel")})]})})})]})}function BA({conversations:e,ides:t,clearedTabs:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:d=!0,userName:p,groupIndex:u,onFocus:m,isSplitMode:f,numGroups:g,onMoveTab:k,onReceiveTab:h,style:x,onActiveTabChange:S,initialActiveTabId:b,initialTabOrder:w,onTabOrderChange:C,onHideTab:v,isFocused:y,allowTabShortcuts:j=!0,onOpenNewSession:N,liveSessionInboxState:T}){const{sendCommand:A}=St(),I=l.useRef(null),{activeTabId:D,activeConv:M,sortedConversations:E,draggingTabRef:P,selectTab:B,handleTabReorder:R,updatePreviewOrder:W,commitPreviewOrder:_,clearPreviewOrder:H,moveTabToEnd:L,setDraggingTabKey:F}=_A({conversations:e,initialActiveTabId:b,initialTabOrder:w,onActiveTabChange:S,onTabOrderChange:C}),$=wo({sendDaemonCommand:r,activeConv:M,setActionLogs:o,isStandalone:i}),{dragOver:K,dropAction:z,resetDragState:ne,handleDragEnter:ie,handleDragOver:Ce,handleDragLeave:me,handleDrop:O}=RA({conversations:e,numGroups:g,onMoveTab:k,onReceiveTab:h,onOwnTabDrop:L,onClearPreviewOrder:H}),Y=M&&!ht(M)&&la(M)==="terminal",X=l.useMemo(()=>M?t.find(Z=>Z.id===M.routeId):void 0,[t,M]),Q=l.useMemo(()=>M?a.filter(Z=>Z.routeId===M.tabKey):[],[a,M]),ve=l.useMemo(()=>new Set(E.filter(Z=>Tx(Z,T,{isOpenConversation:Z.tabKey===D})).map(Z=>Z.tabKey)),[D,T,E]);Ga("PaneGroup",{groupIndex:u,conversationCount:e.length,activeTabId:D,dragOver:K});const he=l.useCallback(Z=>{Z.streamSource==="agent-stream"&&Z.agentType&&A(Z.routeId,Mm(),{agentType:Z.agentType,...Z.sessionId&&{targetSessionId:Z.sessionId}}).catch(()=>{})},[A]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:m,style:{...x,outline:K?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(FA,{conversations:E,activeTabId:D,groupIndex:u,numGroups:g,unreadTabKeys:ve,draggingTabRef:P,onFocus:m,onSelectTab:B,onConversationActivated:he,onPreviewReorder:W,onReorderTab:R,onCommitPreviewOrder:_,onClearPreviewOrder:H,onDragStateReset:ne,onDragTabKeyChange:F,onMoveTab:k,onReceiveTab:h,onHideTab:v,isGroupActive:y??!1,allowTabShortcuts:j}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:ie,onDragOver:Ce,onDragLeave:me,onDrop:O,children:[K&&s.jsx(HA,{dropAction:z,canSplit:!!(g<4&&k)}),M?s.jsx(pc,{activeConv:M,clearToken:n[M.tabKey]||0,isCliTerminal:!!Y,ideEntry:X,terminalRef:I,handleModalButton:$.handleModalButton,handleRelaunch:$.handleRelaunch,handleSendChat:$.handleSendChat,handleForceSendChat:$.handleForceSendChat,isSendingChat:$.isSendingChat,sendFeedbackMessage:$.sendFeedbackMessage,handleFocusAgent:$.handleFocusAgent,isFocusingAgent:$.isFocusingAgent,actionLogs:Q,userName:p,isInputActive:!f||!!y}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(hc,{conversationsCount:e.length,isSplitMode:f,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:N,isLoading:!No(t,d)})})]})]})}function WA({containerRef:e,isSplitMode:t,numGroups:n,groupSizes:a,groupedConvs:r,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:p,isStandalone:u,hasRegisteredMachines:m,initialDataLoaded:f,userName:g,focusedGroup:k,focusGroup:h,moveTabToGroup:x,splitTabRelative:S,closeGroup:b,handleResizeStart:w,groupActiveTabIds:C,setGroupActiveTab:v,groupTabOrders:y,setGroupTabOrder:j,toggleHiddenTab:N,onOpenNewSession:T,allowTabShortcuts:A=!0,liveSessionInboxState:I}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:r.map((D,M)=>{const E=t&&a.length===n?`${a[M]}%`:void 0;return s.jsxs(Rt.Fragment,{children:[t&&M>0&&s.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:P=>w(M-1,P),onDoubleClick:()=>b(M),title:"Drag to resize · Double-click to merge",children:s.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),s.jsx(BA,{style:t?{flexBasis:E??`${100/n}%`,flexGrow:E?0:1,flexShrink:E?0:1}:void 0,conversations:D,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:p,isStandalone:u,hasRegisteredMachines:m,initialDataLoaded:f,userName:g,groupIndex:M,isFocused:t&&k===M,onFocus:()=>h(M),isSplitMode:t,numGroups:n,onMoveTab:(P,B)=>{B==="left"&&M>0?x(P,M-1):B==="right"&&M<n-1?x(P,M+1):B==="split-left"&&n<4?S(P,M,"left"):B==="split-right"&&n<4&&S(P,M,"right")},onReceiveTab:P=>x(P,M),onActiveTabChange:P=>v(M,P),initialActiveTabId:C[M],initialTabOrder:y[M],onTabOrderChange:P=>j(M,P),onHideTab:N,onOpenNewSession:T,allowTabShortcuts:A,liveSessionInboxState:I})]},M)})})}const Yh="adhdev-dashboard-action-shortcuts",OA=1200,UA=[["toggleHiddenTabs","G H"],["openNewSession","N"],["setActiveTabShortcut","G S"],["selectPreviousGroupTab","G K"],["selectPreviousGroupTab","T ←"],["selectPreviousGroupTab","⌥+["],["selectPreviousGroupTab","Ctrl+Alt+["],["selectNextGroupTab","G J"],["selectNextGroupTab","T →"],["selectNextGroupTab","⌥+]"],["selectNextGroupTab","Ctrl+Alt+]"],["splitActiveTabDown","S ↓"],["splitActiveTabDown","⌘+⌥+-"],["splitActiveTabDown","Ctrl+Alt+-"],["splitActiveTabRight","S →"],["splitActiveTabRight","⌘+⌥+\\"],["splitActiveTabRight","⌘+⌥+="],["splitActiveTabRight","Ctrl+Alt+\\"],["focusLeftPane","F ←"],["focusLeftPane","⌘+⌥+←"],["focusLeftPane","⌘+⌥+["],["focusLeftPane","Ctrl+Alt+←"],["focusRightPane","F →"],["focusRightPane","⌘+⌥+→"],["focusRightPane","⌘+⌥+]"],["focusRightPane","Ctrl+Alt+→"],["focusUpPane","F ↑"],["focusUpPane","⌘+⌥+U"],["focusUpPane","Ctrl+Alt+↑"],["focusDownPane","F ↓"],["focusDownPane","⌘+⌥+J"],["focusDownPane","Ctrl+Alt+↓"],["moveActiveTabToLeftPane","M ←"],["moveActiveTabToLeftPane","⌘+⌥+⇧+←"],["moveActiveTabToLeftPane","⌘+⌥+,"],["moveActiveTabToLeftPane","Ctrl+Alt+Shift+←"],["moveActiveTabToRightPane","M →"],["moveActiveTabToRightPane","⌘+⌥+⇧+→"],["moveActiveTabToRightPane","⌘+⌥+."],["moveActiveTabToRightPane","Ctrl+Alt+Shift+→"],["moveActiveTabToUpPane","M ↑"],["moveActiveTabToUpPane","⌘+⌥+I"],["moveActiveTabToUpPane","Ctrl+Alt+Shift+↑"],["moveActiveTabToDownPane","M ↓"],["moveActiveTabToDownPane","⌘+⌥+K"],["moveActiveTabToDownPane","Ctrl+Alt+Shift+↓"],["triggerPrimaryApprovalAction","⌥+A"],["triggerSecondaryApprovalAction","⌥+D"],["toggleCliView","T"]];function GA(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function gt(e,t){switch(e){case"openShortcutHelp":return"?";case"openNewSession":return t?"⌘+⇧+Enter":"Ctrl+Shift+Enter";case"hideCurrentTab":return t?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return t?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return t?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return t?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return t?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return t?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return t?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return t?"⌘+Ctrl+⇧+→":"Ctrl+Alt+Shift+→";case"splitActiveTabDown":return t?"⌘+Ctrl+⇧+↓":"Ctrl+Alt+Shift+↓";case"focusLeftPane":return"";case"focusRightPane":return"";case"focusUpPane":return"";case"focusDownPane":return"";case"moveActiveTabToLeftPane":return"";case"moveActiveTabToRightPane":return"";case"moveActiveTabToUpPane":return"";case"moveActiveTabToDownPane":return"";case"triggerPrimaryApprovalAction":return t?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return t?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return t?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return t?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return t?"⌘+⇧+←":"Ctrl+Shift+←";case"selectNextGroupTab":return t?"⌘+⇧+→":"Ctrl+Shift+→";case"toggleCliView":return t?"⌥+T":"Ctrl+Alt+T"}}function Qh(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:gt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:gt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:gt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:gt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:gt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:gt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:gt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:gt("popoutActiveTab",e)},{id:"dockActiveTab",label:"Dock active tab",description:"Dock a floating tab back into the grid, or move a popout tab back to the main window.",defaultShortcut:gt("dockActiveTab",e)},{id:"splitActiveTabRight",label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it.",defaultShortcut:gt("splitActiveTabRight",e)},{id:"splitActiveTabDown",label:"Move active tab to new lower pane",description:"Create a pane below and move the active tab into it.",defaultShortcut:gt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:gt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:gt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:gt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:gt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:gt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:gt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:gt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:gt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:gt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:gt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:gt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:gt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:gt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:gt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:gt("toggleCliView",e)}]}function ml(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function Zr(e){const t=Object.fromEntries(Qh(e).map(n=>[n.id,n.defaultShortcut]));try{const n=JSON.parse(localStorage.getItem(Yh)||"{}"),a={...t,...n};for(const[r,o]of UA)a[r]===o&&(a[r]=t[r]);return a}catch{return t}}function Jh(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function qA({enabled:e=!0,onTrigger:t}){const n=GA(),[a,r]=l.useState(()=>Zr(n)),[o,i]=l.useState(null),[c,d]=l.useState([]),p=l.useRef({parts:[],timer:null}),u=l.useCallback(h=>{const x=[];return h.metaKey&&x.push(n?"⌘":"Meta"),h.ctrlKey&&x.push("Ctrl"),h.altKey&&x.push(n?"⌥":"Alt"),h.shiftKey&&h.key.length!==1&&x.push(n?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(x.push(Jh(h.key)),x.join("+"))},[n]),m=l.useCallback(h=>{r(h);try{localStorage.setItem(Yh,JSON.stringify(h))}catch{}},[]);l.useEffect(()=>{const h=Zr(n),x=Object.entries(a),S=Object.entries(h);x.length===S.length&&x.every(([b,w])=>h[b]===w)||m(h)},[a,n,m]);const f=l.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),g=l.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},OA))},[]);l.useEffect(()=>{if(!o)return;const h=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){i(null),d([]);return}const S=u(x);if(!S)return;const w=!(x.metaKey||x.ctrlKey||x.altKey)&&/^[A-Z0-9]$/.test(S);if(c.length===0&&w){d([S]);return}const v=[...c,S].slice(0,2).join(" "),y={...a};for(const[j,N]of Object.entries(y))N===v&&delete y[j];y[o]=v,m(y),i(null),d([])};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[a,u,m,o,c]),l.useEffect(()=>{if(!e||o)return;const h=x=>{if(x.defaultPrevented)return;const S=u(x);if(!S)return;const b=x.metaKey||x.ctrlKey||x.altKey;if(ml(x.target))return;const w=p.current.parts,C=b?[S]:[...w.slice(-1),S].slice(-2),v=C.join(" "),y=C[C.length-1],j=Object.entries(a).filter(([,D])=>!!D),N=j.find(([,D])=>D===v);if(N){x.preventDefault(),f(),t(N[0]);return}if(j.some(([,D])=>D.startsWith(`${v} `))){x.preventDefault(),p.current.parts=C,g();return}const A=j.find(([,D])=>D===y);if(A){x.preventDefault(),f(),t(A[0]);return}if(j.some(([,D])=>D.startsWith(`${y} `))){x.preventDefault(),p.current.parts=[y],g();return}f()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[a,g,e,u,t,f,o]),l.useEffect(()=>()=>f(),[f]);const k=l.useMemo(()=>Qh(n),[n]);return{isMac:n,actionDefinitions:k,actionShortcuts:a,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:d,saveShortcuts:m}}function zA({isTabInPopout:e,isTabFloating:t,tabShortcut:n,actionShortcuts:a}){const r=[];return e?(t&&r.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:a.dockActiveTab}),r.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:a.dockActiveTab})):t?r.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:a.dockActiveTab}):r.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:a.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:a.popoutActiveTab}),r.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:n?`Change shortcut (${n})`:"Set shortcut",shortcut:a.setActiveTabShortcut}),n&&r.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),r.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:a.hideCurrentTab,tone:"muted"}),r}function Xh(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function ou({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:n,ides:a}){return!e||n>0?!1:t?!Xh(a):!0}function KA({previousVisibleConversationCount:e,visibleConversationCount:t,ides:n}){return t>0||e<=0?!1:Xh(n)}const Zh=1e3,VA=4;function iu(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function lu(e,t,n){return Math.abs(t.clientX-e.clientX)>n||Math.abs(t.clientY-e.clientY)>n}function YA({detachDelayMs:e=Zh,stillnessThresholdPx:t=VA,onDetach:n,setTimeoutFn:a=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:r=globalThis.clearTimeout.bind(globalThis)}){let o=null,i=null,c=null,d=null,p=null,u=!1;const m=()=>{p!=null&&(r(p),p=null)},f=()=>{m(),c=null},g=()=>{m(),o=null,i=null,c=null,d=null,u=!1},k=()=>{!o||!c||!d||u||p!=null||(p=a(()=>{p=null,!(!o||!c||!d||u)&&iu(d,i)&&(lu(c,d,t)||(u=!0,n({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},h=S=>{if(!(!o||u)){if(!iu(S,i)){d={clientX:S.clientX,clientY:S.clientY},f();return}(!c||lu(c,S,t))&&(m(),c={clientX:S.clientX,clientY:S.clientY}),d={clientX:S.clientX,clientY:S.clientY},k()}},x=S=>{!o||u||(S&&(d={clientX:S.clientX,clientY:S.clientY}),f())};return{startDrag:S=>{m(),o=S.panelId,i=S.selfPanelBounds??null,c=null,d={clientX:S.clientX,clientY:S.clientY},u=!1},markSelfPanel:h,markNonSelfPanel:x,markNoDropTarget:x,markDockTarget:x,endDrag:g,isDragging:()=>o!=null,hasDetached:()=>u,dispose:g}}function QA(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function Ir(e){return kt(e)||e.tabKey}function JA(e){return`remote:${e}`}function fs(e){return e.startsWith("remote:")}function cu(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function ci(e){var a;const t=e==null?void 0:e.defaultView;if(!t)return;const n=r=>{if(r)try{r.focus({preventScroll:!0})}catch{try{r.focus()}catch{}}};try{t.focus(),n(e==null?void 0:e.body),n(e==null?void 0:e.documentElement),(a=t.requestAnimationFrame)==null||a.call(t,()=>{try{t.focus(),n(e==null?void 0:e.body)}catch{}})}catch{}}function di(e,t){e.classList.remove(Hi.className,$i.className),e.classList.add(t==="light"?Hi.className:$i.className)}function du(e){return e?Array.from(new Set(e.groups.map(t=>{var n,a;return(a=(n=t.element)==null?void 0:n.ownerDocument)==null?void 0:a.defaultView}).filter(t=>!!t&&t!==window))):[]}function XA(e,t,n){var i;const a=[t];let r;for(const c of a){let d;for(const p of c){const u=e.addPanel({id:p.tabKey,component:"conversation",title:Ir(p),params:{kind:"conversation",tabKey:p.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:r?{position:{referencePanel:r,direction:"right"},inactive:!0}:{}});d||(d=u.id)}r=d??r}return n??((i=t[0])==null?void 0:i.tabKey)??null}function uu(e,t){const n=new Set(t.map(r=>r.tabKey)),a=new Map;for(const r of t)a.set(r.tabKey,(a.get(r.tabKey)||0)+1);for(const r of[...e.panels])fs(r.id)||n.has(r.id)||e.removePanel(r);for(const r of t){const o=e.getPanel(r.tabKey);if(o){(a.get(r.tabKey)||0)>1&&console.warn("[dashboard-conversations] Dockview panel already exists for duplicate tabKey",{tabKey:r.tabKey,daemonId:r.daemonId,sessionId:r.sessionId,providerSessionId:r.providerSessionId,panelId:o.id}),o.update({params:{tabKey:r.tabKey}}),o.title!==Ir(r)&&o.api.setTitle(Ir(r));continue}e.addPanel({id:r.tabKey,component:"conversation",title:Ir(r),params:{kind:"conversation",tabKey:r.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function pu(e,t,n){var d,p;const a=n?JA(n):null;for(const u of[...e.panels])fs(u.id)&&(!a||u.id!==a)&&e.removePanel(u);if(!n||!a)return;const r=ws(t,n);if(!r&&e.totalPanels===0)return;const o=e.getPanel(a),i=Xm(r);if(o){o.title!==i&&o.api.setTitle(i);return}const c=(r==null?void 0:r.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((p=e.panels.find(u=>!fs(u.id)))==null?void 0:p.id);e.addPanel({id:a,component:"remote",title:i,params:{kind:"remote",routeId:n},...c?{position:{referencePanel:c,direction:"right"},inactive:!0}:{}})}function ef({doId:e,targetSessionId:t,connState:n,viewMode:a}){const[r,o]=l.useState(null),[i,c]=l.useState(null);l.useEffect(()=>e?Ct.onScreenshot("ide-page",(u,m)=>{if(u!==e)return;const f=new FileReader;f.onload=()=>o(f.result),f.readAsDataURL(m)}):void 0,[e]),l.useEffect(()=>{n!=="connected"&&o(null)},[n]),l.useEffect(()=>{var u;return e?((u=Ct.onStatus)==null?void 0:u.call(Ct,(m,f)=>{m===e&&f!=null&&f.screenshotUsage&&c(f.screenshotUsage)}))||(()=>{}):void 0},[e]),l.useEffect(()=>{o(null)},[e,t]),l.useEffect(()=>{const p=e?Ct.get(e):null;if(!(!p||n!=="connected"))return a!=="chat"&&t?p.startScreenshots(t):p.stopScreenshots(t),()=>{p.stopScreenshots(t)}},[a,n,t,e]);const d=l.useCallback(async(p,u)=>{const m=e?Ct.get(e):null;return!m||n!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):m.sendInput(p,u,t)},[e,n,t]);return{connScreenshot:r,screenshotUsage:i,handleRemoteAction:d}}const tf=l.createContext(null);function Ao(){const e=l.useContext(tf);if(!e)throw new Error("DashboardDockviewContext missing");return e}function ZA(e){const[,t]=l.useState(0);l.useEffect(()=>{const n=()=>t(r=>r+1),a=[e.api.onDidActiveGroupChange(n),e.api.onDidTitleChange(n),e.api.onDidGroupChange(n),e.containerApi.onDidActivePanelChange(n)];return()=>{for(const r of a)r.dispose()}},[e.api,e.containerApi])}function eT({params:e}){var d;const t=Ao(),n=l.useMemo(()=>ws([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),a=l.useMemo(()=>t.ides.find(p=>p.id===e.routeId),[t.ides,e.routeId]),r=(n==null?void 0:n.daemonId)||((d=n==null?void 0:n.routeId)==null?void 0:d.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:i,handleRemoteAction:c}=ef({doId:r,targetSessionId:n?Am(n):(a==null?void 0:a.sessionId)||(a==null?void 0:a.instanceId),connState:(n==null?void 0:n.connectionState)||"new",viewMode:"remote"});return n?s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:s.jsx(Gp,{addLog:()=>{},connState:n.connectionState||"new",connScreenshot:o,screenshotUsage:i,transportType:n.transport,onAction:c})}):s.jsx("div",{className:"h-full min-h-0 min-w-0 flex items-center justify-center text-sm text-text-muted",children:"Remote view unavailable"})}function tT(){const e=Ao();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(hc,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels,isLoading:!No(e.ides,e.initialDataLoaded)})})}function sT(e){var b,w;ZA(e);const t=Ao(),n=l.useCallback(C=>{"button"in C&&C.button!==0||e.api.setActive()},[e.api]),a=e.params.kind==="remote"?void 0:t.conversationsByTabKey.get(e.params.tabKey),r=a==null?void 0:a.sessionId,o=l.useCallback(C=>jC(C),[]),i=l.useCallback(()=>CC(r),[r]),c=l.useSyncExternalStore(o,i,i);if(e.params.kind==="remote"){const C=ws([...t.conversationsByTabKey.values()],e.params.routeId),v=((b=e.api.group.activePanel)==null?void 0:b.id)===e.api.id,y=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${v?" is-active":""}${y?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(C==null?void 0:C.tabKey)||"",onMouseDown:n,onTouchStart:n,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:C!=null&&C.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:C.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const d=t.conversationsByTabKey.get(e.params.tabKey);if(!d)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const p=((w=e.api.group.activePanel)==null?void 0:w.id)===e.api.id,u=e.api.isGroupActive,m=fo(d,t.liveSessionInboxState,{isOpenConversation:p}),f=m.isReconnecting,g=m.isConnecting,k=m.isGenerating||c,h=m.isWaiting,x=m.unread,S=t.tabShortcuts[d.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${p?" is-active":""}${u?" is-group-active":""}${f?" is-reconnecting":""}`,title:kt(d),"data-tab-key":e.params.tabKey,onMouseDown:n,onTouchStart:n,onContextMenu:C=>{var v;C.preventDefault(),n(C),t.openTabContextMenu({x:C.clientX,y:C.clientY,tabKey:d.tabKey,sourceDocument:((v=C.target)==null?void 0:v.ownerDocument)??document})},children:[x&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:k?s.jsx(ls,{size:12,thickness:2,color:"success"}):h?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):f?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):g?s.jsx(ls,{size:12,thickness:2}):d.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:kt(d)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:f?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:kn(d)}):g?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:kn(d)}):s.jsx("span",{children:kn(d)})})]}),S&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:S,children:S})]})}function mr(e){return e.isActive}function mu(e){return e.isVisible}function nT(e){e.preventDefault()}function aT({params:e,api:t}){var g;const n=Ao(),a=l.useRef(null),[r,o]=l.useState(()=>mr(t)),[i,c]=l.useState(()=>mu(t)),d=n.conversationsByTabKey.get(e.tabKey),p=wo({sendDaemonCommand:n.sendDaemonCommand,activeConv:d,setActionLogs:n.setActionLogs,isStandalone:n.isStandalone});l.useEffect(()=>{o(mr(t)),c(mu(t));const k=[t.onDidActiveChange(h=>o(h.isActive)),t.onDidActiveGroupChange(h=>{if(!mr(t)&&!h.isActive){o(!1);return}o(mr(t))}),t.onDidVisibilityChange(h=>c(h.isVisible))];return()=>{for(const h of k)h.dispose()}},[t]);const u=l.useMemo(()=>d?n.ides.find(k=>k.id===d.routeId):void 0,[n.ides,d]),m=l.useMemo(()=>d?n.actionLogs.filter(k=>k.routeId===d.tabKey):[],[n.actionLogs,d]);if(!d)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(hc,{conversationsCount:0,isSplitMode:!1,isStandalone:n.isStandalone,hasRegisteredMachines:n.hasRegisteredMachines,onOpenNewSession:n.onOpenNewSession,suppressGuide:n.hasDetachedConversationPanels,isLoading:!No(n.ides,n.initialDataLoaded)})});const f=!ht(d)&&la(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(pc,{activeConv:d,clearToken:n.clearedTabs[d.tabKey]||0,isCliTerminal:f,ideEntry:u,terminalRef:a,handleModalButton:p.handleModalButton,handleRelaunch:p.handleRelaunch,handleSendChat:p.handleSendChat,handleForceSendChat:p.handleForceSendChat,isSendingChat:p.isSendingChat,handleFocusAgent:p.handleFocusAgent,isFocusingAgent:p.isFocusingAgent,actionLogs:m,userName:n.userName,scrollToBottomRequestNonce:((g=n.scrollToBottomRequest)==null?void 0:g.tabKey)===d.tabKey?n.scrollToBottomRequest.nonce:void 0,isInputActive:r,isVisible:i})})}function rT({visibleConversations:e,clearedTabs:t,ides:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:d,userName:p,toggleHiddenTab:u,actionShortcuts:m,registerActionHandlers:f,onActiveTabChange:g,onOpenNewSession:k,onRequestScrollToBottom:h,requestedActiveTabKey:x,requestedRemoteIdeId:S,onRequestedActiveTabConsumed:b,scrollToBottomRequest:w,liveSessionInboxState:C,layoutProfile:v}){var $e,at,rt;const{theme:y}=Ls(),{sendCommand:j}=St(),N=l.useRef(null),T=l.useRef(null),A=l.useRef(null),I=l.useRef(!1),D=l.useRef(!1),M=l.useRef(!1),E=l.useRef(null),P=l.useRef([]),[B,R]=l.useState(null),[W,_]=l.useState(0),H=l.useRef(typeof window>"u"?{}:SN(v)),L=l.useMemo(()=>new Map(e.map(G=>[G.tabKey,G])),[e]),F=l.useMemo(()=>{const G=N.current;return G?G.groups.some(oe=>{try{const de=oe.model.location.type;return de!=="floating"&&de!=="popout"?!1:oe.panels.some(xe=>L.has(xe.id))}catch{return!1}}):!1},[L,W,e]),$=l.useCallback(()=>{var G;(G=N.current)==null||G.focus()},[]),K=l.useCallback((G,oe)=>{h==null||h(G,oe)},[h]),z=l.useCallback(G=>{const oe=document,de=G.document;for(const Ee of oe.querySelectorAll('link[rel="stylesheet"]')){const Je=de.createElement("link");Je.rel="stylesheet",Je.href=Ee.href,Ee.crossOrigin&&(Je.crossOrigin=Ee.crossOrigin),de.head.appendChild(Je)}for(const Ee of oe.querySelectorAll("style")){const Je=de.createElement("style");Je.textContent=Ee.textContent,de.head.appendChild(Je)}const xe=[];for(const Ee of oe.styleSheets)try{for(const Je of Ee.cssRules)Je instanceof CSSStyleRule&&(Je.selectorText===":root"||Je.selectorText==="html")&&xe.push(Je.cssText)}catch{}if(xe.length>0){const Ee=de.createElement("style");Ee.textContent=xe.join(`
|
|
64
|
+
The machine's IDE, workspace and provider settings are kept.`,confirmLabel:o("machine.connectedMachines.remove"),confirmColor:"red",onConfirm:T,onCancel:()=>m(null)})]})}const j1=[{id:"dark",label:"Dark",icon:Tp},{id:"light",label:"Light",icon:Ap},{id:"system",label:"System",icon:Mp}];function N1(){const{preference:e,setPreference:t}=Ls();return s.jsx("div",{className:"flex gap-2",children:j1.map(n=>s.jsxs("button",{onClick:()=>t(n.id),className:`px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors flex items-center gap-1.5 ${e===n.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:e===n.id?{color:"var(--accent-on-primary)"}:void 0,children:[s.jsx(n.icon,{size:14}),n.label]},n.id))})}function A1(e){const t=e.trim();return/^#[0-9a-fA-F]{6}$/.test(t)?t:/^#[0-9a-fA-F]{3}$/.test(t)?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:null}function T1(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Zo(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Gd(e){const{r:t,g:n,b:a}=T1(e);return .2126*Zo(t)+.7152*Zo(n)+.0722*Zo(a)}function qd(e,t){const n=Gd(e),a=Gd(t),r=Math.max(n,a),o=Math.min(n,a);return(r+.05)/(o+.05)}function yh(e){const t=A1(e);if(!t)return"#111827";const n="#111827",a="#ffffff";return qd(t,n)>=qd(t,a)?n:a}const ll={bgPrimary:"#0a0e1a",bgSecondary:"#0f1320",surfacePrimary:"#111726",textPrimary:"#f0f0f5",textSecondary:"#9ca3af",textMuted:"#6b7280",borderSubtle:"#1d2536",borderDefault:"#313c52",accentColor:"#d97706",userBubble:"#f59e0b",userText:"#1a1a1a",assistantBubble:"#111726",assistantText:"#f0f0f5",containerBg:"#0f1320",sendButton:"#d97706",inputBorder:"#313c52",bubbleRadius:16},cl={bgPrimary:"#fff8ee",bgSecondary:"#fff1de",surfacePrimary:"#ffffff",textPrimary:"#24160f",textSecondary:"#6f6255",textMuted:"#938374",borderSubtle:"#e7d3ba",borderDefault:"#d7b892",accentColor:"#d97706",userBubble:"#f59e0b",userText:"#1a1a1a",assistantBubble:"#fffaf4",assistantText:"#24160f",containerBg:"#fff8ee",sendButton:"#d97706",inputBorder:"#d7b892",bubbleRadius:16},M1=[{id:"midnight",name:"Midnight",description:"Classic violet theme",preview:{dark:{userBubble:"#8b5cf6",assistantBubble:"#18181d",assistantBorder:"1px solid rgba(255,255,255,0.08)",containerBg:"#0f0f13",textColor:"rgba(255,255,255,0.7)"},light:{userBubble:"#7c3aed",assistantBubble:"#ffffff",assistantBorder:"1px solid rgba(0,0,0,0.08)",containerBg:"#f0f1f5",textColor:"#52525b"}}},{id:"ember",name:"Ember",description:"Default landing-inspired amber theme",preview:{dark:{userBubble:"#f59e0b",assistantBubble:"#111726",assistantBorder:"1px solid rgba(255,255,255,0.08)",containerBg:"#0a0e1a",textColor:"#9ca3af"},light:{userBubble:"#f59e0b",assistantBubble:"#fffaf4",assistantBorder:"1px solid rgba(146,64,14,0.10)",containerBg:"#fff8ee",textColor:"#6f6255"}}},{id:"aurora",name:"Aurora",description:"Pink accent theme",preview:{dark:{userBubble:"#ec4899",assistantBubble:"#1e1b2e",assistantBorder:"1px solid rgba(236,72,153,0.12)",containerBg:"#0f0d17",textColor:"rgba(255,255,255,0.7)"},light:{userBubble:"#ec4899",assistantBubble:"#fef2f8",assistantBorder:"1px solid rgba(236,72,153,0.15)",containerBg:"#f0f1f5",textColor:"#1a1a2e"}}},{id:"honey",name:"Honey",description:"Warm yellow accents",preview:{dark:{userBubble:"#fbbf24",assistantBubble:"#1c1c1e",assistantBorder:"1px solid rgba(255,255,255,0.06)",containerBg:"#111113",textColor:"rgba(255,255,255,0.7)"},light:{userBubble:"#fbbf24",assistantBubble:"#fffbeb",assistantBorder:"1px solid rgba(251,191,36,0.15)",containerBg:"#f0f1f5",textColor:"#1a1a2e"}}}],wh="adhdev-chat-theme",kh="adhdev-chat-theme-custom";function Mr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(wh)||"ember"}catch{return"ember"}}function bs(e){try{const t=localStorage.getItem(kh);if(t){const n=JSON.parse(t);return{...e==="dark"?ll:cl,...n[e]}}}catch{}return e==="dark"?ll:cl}function lr(e,t){try{localStorage.setItem(kh,JSON.stringify({dark:e,light:t}))}catch{}}function as(e,t){const n=parseInt(e.slice(1,3),16),a=parseInt(e.slice(3,5),16),r=parseInt(e.slice(5,7),16);return`rgba(${n}, ${a}, ${r}, ${t})`}function Jr(e,t){const n=Math.min(255,parseInt(e.slice(1,3),16)+t),a=Math.min(255,parseInt(e.slice(3,5),16)+t),r=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}`}const P1={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Da(e,t){var r;const n=(r=P1[e])==null?void 0:r[t];if(!n)return;const a=document.documentElement;a.style.setProperty("--accent-primary",n),a.style.setProperty("--accent-primary-light",Jr(n,24)),a.style.setProperty("--accent-on-primary",yh(n)),a.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${n}, ${Jr(n,18)})`),a.style.setProperty("--border-accent",as(n,.35)),a.style.setProperty("--nav-active-bg",as(n,.1)),a.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${n}, 0 0 12px ${as(n,.06)}`)}function Sn(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",as(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",as(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",as(e.borderSubtle,.25)),t.style.setProperty("--text-primary",e.textPrimary),t.style.setProperty("--text-secondary",e.textSecondary),t.style.setProperty("--text-muted",e.textMuted),t.style.setProperty("--border-subtle",as(e.borderSubtle,.5)),t.style.setProperty("--border-default",as(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",Jr(e.accentColor,30)),t.style.setProperty("--accent-on-primary",yh(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Jr(e.accentColor,40)})`),t.style.setProperty("--border-accent",as(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",as(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${as(e.accentColor,.06)}`),t.style.setProperty("--chat-user-bg",e.userBubble),t.style.setProperty("--chat-user-color",e.userText),t.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),t.style.setProperty("--chat-assistant-bg",e.assistantBubble),t.style.setProperty("--chat-assistant-color",e.assistantText),t.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),t.style.setProperty("--chat-assistant-border",`1px solid ${as(e.accentColor,.12)}`),t.style.setProperty("--chat-container-bg",e.containerBg),t.style.setProperty("--dashboard-pane-bg",e.containerBg),t.style.setProperty("--chat-thought-accent",e.accentColor),t.style.setProperty("--chat-tool-accent",e.accentColor),t.style.setProperty("--chat-action-color",e.accentColor),t.style.setProperty("--chat-send-bg",e.sendButton),t.style.setProperty("--chat-input-border",e.inputBorder)}function rc(){const e=document.documentElement;["--bg-primary","--bg-secondary","--bg-card","--surface-primary","--surface-secondary","--bg-glass","--bg-glass-hover","--text-primary","--text-secondary","--text-muted","--border-subtle","--border-default","--accent-primary","--accent-primary-light","--accent-on-primary","--accent-gradient","--border-accent","--nav-active-bg","--nav-active-shadow","--chat-user-bg","--chat-user-color","--chat-user-radius","--chat-assistant-bg","--chat-assistant-color","--chat-assistant-radius","--chat-assistant-border","--chat-container-bg","--dashboard-pane-bg","--chat-thought-accent","--chat-tool-accent","--chat-action-color","--chat-send-bg","--chat-input-border"].forEach(n=>e.style.removeProperty(n))}function D1(e){try{localStorage.setItem(wh,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=Cn()?"dark":"light";Sn(bs(t))}else rc(),Da(e,Cn()?"dark":"light")}function I1(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Mr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=Cn()?"dark":"light";Sn(bs(t))}else rc(),Da(e,Cn()?"dark":"light")}function Cn(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Gt({label:e,value:t,onChange:n}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[s.jsx("input",{type:"color",value:t,onChange:a=>n(a.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),s.jsx("input",{type:"text",value:t,onChange:a=>{/^#[0-9a-fA-F]{0,6}$/.test(a.target.value)&&n(a.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function ba({title:e,children:t}){return s.jsxs("div",{style:{marginBottom:14},children:[s.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:e}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:t})]})}function L1({dark:e,onColorsChange:t}){const{t:n}=ke("common"),a=e?"dark":"light",[r,o]=l.useState(()=>bs(a));l.useEffect(()=>{o(bs(a))},[a]);const i=l.useCallback((c,d)=>{o(p=>{const u={...p,[c]:d},f=bs(a==="dark"?"light":"dark");return a==="dark"?lr(u,f):lr(f,u),Sn(u),t(u),u})},[a,t]);return s.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[s.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[n("settings.theme.customEditorTitle"),s.jsx("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:n(e?"settings.theme.darkMode":"settings.theme.lightMode")})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs(ba,{title:n("settings.theme.sectionAppBackground"),children:[s.jsx(Gt,{label:n("settings.theme.colorBackground"),value:r.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(Gt,{label:n("settings.theme.colorSurface"),value:r.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(Gt,{label:n("settings.theme.colorCard"),value:r.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(ba,{title:n("settings.theme.sectionAppText"),children:[s.jsx(Gt,{label:n("settings.theme.colorPrimary"),value:r.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(Gt,{label:n("settings.theme.colorSecondary"),value:r.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(Gt,{label:n("settings.theme.colorMuted"),value:r.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(ba,{title:n("settings.theme.sectionBordersAccent"),children:[s.jsx(Gt,{label:n("settings.theme.colorBorderSubtle"),value:r.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(Gt,{label:n("settings.theme.colorBorderDefault"),value:r.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(Gt,{label:n("settings.theme.colorAccent"),value:r.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(ba,{title:n("settings.theme.sectionChatBubbles"),children:[s.jsx(Gt,{label:n("settings.theme.colorUserBubble"),value:r.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(Gt,{label:n("settings.theme.colorUserText"),value:r.userText,onChange:c=>i("userText",c)}),s.jsx(Gt,{label:n("settings.theme.colorAgentBubble"),value:r.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(Gt,{label:n("settings.theme.colorAgentText"),value:r.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(ba,{title:n("settings.theme.sectionChatLayout"),children:[s.jsx(Gt,{label:n("settings.theme.colorChatBg"),value:r.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(Gt,{label:n("settings.theme.colorSendButton"),value:r.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(Gt,{label:n("settings.theme.colorInputBorder"),value:r.inputBorder,onChange:c=>i("inputBorder",c)}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:n("settings.theme.labelBubbleRadius")}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[s.jsx("input",{type:"range",min:4,max:24,value:r.bubbleRadius,onChange:c=>i("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),s.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[r.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const c=e?ll:cl,p=bs(e?"light":"dark");e?lr(c,p):lr(p,c),o(c),Sn(c),t(c)},style:{marginTop:10,fontSize:"0.7rem",color:"var(--text-muted)",background:"transparent",border:"1px solid var(--border-subtle)",borderRadius:6,padding:"4px 10px",cursor:"pointer"},children:n("settings.theme.resetToDefaults")})]})}function R1(){const{t:e}=ke("common"),[t,n]=l.useState(Mr),[a,r]=l.useState(!0),[o,i]=l.useState(()=>bs("dark"));l.useEffect(()=>{r(Cn());const p=new MutationObserver(()=>{const f=Cn();r(f);const g=Mr();g==="custom"?Sn(bs(f?"dark":"light")):Da(g,f?"dark":"light")});p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const u=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const f=Cn();r(f);const g=Mr();g==="custom"?Sn(bs(f?"dark":"light")):Da(g,f?"dark":"light")};return u.addEventListener("change",m),()=>{p.disconnect(),u.removeEventListener("change",m)}},[]),l.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?Sn(bs(a?"dark":"light")):(rc(),Da(t,a?"dark":"light"))},[t,a]),l.useEffect(()=>{i(bs(a?"dark":"light"))},[a]);const c=p=>{n(p),D1(p)},d=[...M1,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText},light:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:d.map(p=>{const u=t===p.id,m=a?p.preview.dark:p.preview.light,f=p.id==="honey"||p.id==="ember"?"#1a1a1a":p.id==="custom"?o.userText:"#fff";return s.jsxs("button",{onClick:()=>c(p.id),className:"text-left rounded-xl p-3 transition-all",style:{background:u?"var(--bg-glass-hover)":"var(--bg-glass)",border:u?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:u?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:m.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:e("settings.theme.helloHelp")}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.userBubble,color:f},children:e("settings.theme.fixBug")}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:e("settings.theme.onIt")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[u&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:p.id==="custom"?e("settings.theme.customLabel"):p.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:p.description})]})]})]},p.id)})}),t==="custom"&&s.jsx(L1,{dark:a,onColorsChange:p=>i(p)})]})}const oc="adhdev_mobileDashboardMode_v1",dl="adhdev:mobile-dashboard-mode-change";function ic(){try{return localStorage.getItem(oc)==="workspace"?"workspace":"chat"}catch{return"chat"}}function E1(e){if(typeof window>"u")return()=>{};const t=r=>{e(r??ic())},n=r=>{const o=r.detail;t(o)},a=r=>{r.key&&r.key!==oc||t()};return window.addEventListener(dl,n),window.addEventListener("storage",a),()=>{window.removeEventListener(dl,n),window.removeEventListener("storage",a)}}function _1(e){try{localStorage.setItem(oc,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(dl,{detail:e}))}function H1(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(ic()==="chat")},[]),s.jsx(bn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ds,{size:15})," Mobile Inbox (Chat Mode)"]}),description:e?"Use the chat-first mobile inbox layout. This keeps mobile closer to a messaging app.":"Use the full workspace layout on phones and tablets.",checked:e,onChange:n=>{t(n),_1(n?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const $1="Choose a preset or create a fully custom theme. Custom themes control the entire app — backgrounds, text, borders, and chat bubbles.",F1="Choose whether the dashboard opens like a chat app on phones or keeps the full workspace layout.";function B1({themeDescription:e=$1,mobileDescription:t=F1,fontsSlot:n}){const{t:a}=ke("common");return s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:a("settings.appearance.modeLabel")}),s.jsx(N1,{})]}),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:a("settings.appearance.themeLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:e}),s.jsx(R1,{})]}),n,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:a("settings.appearance.mobileLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:t}),s.jsx(H1,{})]})]})}const ei=new Map,zd=new Map;function W1(e){if(!e||typeof e!="object")return null;const t=e,n=t.result&&typeof t.result=="object"?t.result:t,a=n.machine;return!a||typeof a!="object"?null:{machine:a,timestamp:typeof n.timestamp=="number"?n.timestamp:void 0}}function O1(e,t,n,a){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:a,platform:n.platform,machine:n}}function Sh(){const{sendCommand:e}=St(),{injectEntries:t,getIdes:n}=Ra();return l.useCallback(async(a,r)=>{if(!a)return;const o=(r==null?void 0:r.minFreshMs)??qS,i=zd.get(a)||0;if(!(r!=null&&r.force)&&i>0&&Date.now()-i<o)return;const c=ei.get(a);if(c)return c;const d=(async()=>{const p=await e(a,"get_machine_runtime_stats"),u=W1(p);if(!u)return;const m=n().find(g=>g.id===a),f=O1(m,a,u.machine,u.timestamp||Date.now());t([f]),zd.set(a,Date.now())})().finally(()=>{ei.delete(a)});return ei.set(a,d),d},[n,t,e])}function U1(e,t,n){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:n.timestamp,platform:n.machine.platform,machine:{...(e==null?void 0:e.machine)||{},...n.machine}}}function G1(e,t){const{sendData:n}=St(),{injectEntries:a,getIdes:r}=Ra(),o=Array.from(new Set(e.filter(Boolean))).join("|");l.useEffect(()=>{if(!(t!=null&&t.enabled)||!n)return;const i=o?o.split("|"):[];if(i.length===0)return;const c=i.map(d=>ys.subscribe({sendData:n},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const m=r().find(g=>g.id===d),f=U1(m,d,u);a([f])}));return()=>{c.forEach(d=>d())}},[o,r,a,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,n])}function q1(e,t){const{sendData:n}=St(),[a,r]=l.useState(null),[o,i]=l.useState(!1);return l.useEffect(()=>{if(!e){r(null),i(!1);return}if(!(t!=null&&t.enabled)||!n){i(!1);return}r(null),i(!0);let c=null;const d=ys.subscribe({sendData:n},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},p=>{c&&(clearTimeout(c),c=null),r(p.diagnostics),i(!1)});return d.initialSendAccepted?c=setTimeout(()=>{i(!1)},VS):i(!1),()=>{c&&clearTimeout(c),d()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,n]),{diagnostics:a,loading:o,applyDiagnostics:r}}function z1(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Ch(e){const{sendData:t}=St(),[n,a]=l.useState({});return l.useEffect(()=>{const r=z1(e);if(!r||!e.sessionId||!t){a({});return}const o=ys.subscribe({sendData:t},r,{type:"subscribe",topic:"session.modal",key:`daemon:${r}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},i=>{a({status:i.status,modalMessage:i.modalMessage,modalButtons:i.modalButtons}),Zn.record({interactionId:i.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:i.status,modalButtonCount:Array.isArray(i.modalButtons)?i.modalButtons.length:0}})});return o.initialSendAccepted||a({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,t]),n}function K1(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function V1(e){const t=(e==null?void 0:e.result)??e;return typeof(t==null?void 0:t.error)=="string"?t.error:"Interactive prompt response failed"}async function Y1(e,t,n){const a=await n(`/api/v1/sessions/${encodeURIComponent(e)}/interactive-prompt/resolve`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(!a.ok){let r=`HTTP ${a.status}`;try{const o=await a.json();typeof(o==null?void 0:o.error)=="string"&&(r=o.error)}catch{}throw new Error(r)}}async function Q1({promptSession:e,response:t,useP2PCommand:n,sendCommand:a,fetchImpl:r=fetch}){if(n){const o=await a(e.routeId,"interactive_prompt_response",{targetSessionId:e.sessionId,sessionId:e.sessionId,response:t});if(!K1(o))throw new Error(V1(o));return}await Y1(e.sessionId,t,r)}function jh(e){const{ides:t,isP2PActive:n,p2pStates:a}=Ss(),{sendCommand:r}=St(),[o,i]=l.useState(null),[c,d]=l.useState(!1),[p,u]=l.useState(null),m=l.useRef(!1),f=l.useMemo(()=>yx(t,e),[t,e]),g=!!f,k=l.useMemo(()=>f?f.prompt.promptId===o?null:f:null,[o,f]),h=l.useCallback(async b=>{if(!k||m.current)return;m.current=!0;const w=qp(k.prompt,b);d(!0),u(null);try{const C=(a==null?void 0:a[k.daemonId])==="connected"||n===!0;await Q1({promptSession:k,response:w,useP2PCommand:C,sendCommand:r}),i(k.prompt.promptId)}catch(C){throw u(C instanceof Error?C.message:String(C)),C}finally{d(!1),m.current=!1}},[n,a,k,r]),x=l.useCallback(()=>{k&&i(k.prompt.promptId)},[k]),S=l.useCallback(()=>{i(null),u(null)},[]);return{promptSession:k,hasActivePrompt:g,responseError:p,isSubmitting:c,submit:h,cancel:x,reopen:S}}function Nh(e){return e instanceof Error?e.message:String(e||"")}function J1(e){const t=Nh(e);return t.includes("P2P command timeout")||t.includes("P2P not connected")||t.includes("P2P channel not open")||t.includes("P2P not available")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}function X1(e){const t=Nh(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Ah({conversation:e,mode:t,ides:n,sendDaemonCommand:a,setCliViewModeOverrides:r}){if(!e||!bt(e)||ht(e))return;const o=la(e);if(o===t)return;const i=e.sessionId;i&&r(c=>({...c,[i]:t}));try{await a(Ks(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Ps(e),mode:t})}catch(c){const d=X1(c);i&&!d&&r(p=>{const u={...p};return o===eN(n,i)?delete u[i]:u[i]=o,u}),J1(c)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",c instanceof Error?c.message:String(c)):console.error("Failed to switch CLI view mode:",c)}}function Kd(e,t){const n=typeof e.sessionId=="string"&&e.sessionId?e.sessionId:typeof e.id=="string"?e.id:"";if(!n||e.transport!=="pty")return e;const a=t[n];return!a||e.mode===a?e:{...e,mode:a}}function Z1(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let n=!1;const a=e.map(r=>{const o=Kd(r,t),i=Array.isArray(r.childSessions)?r.childSessions.map(d=>Kd(d,t)):r.childSessions,c=i!==r.childSessions;return o!==r||c?(n=!0,{...o,...c?{childSessions:i}:{}}):r});return n?a:e}function eN(e,t){if(!t)return null;for(const n of e){if(n.sessionId===t&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal";for(const a of n.childSessions||[])if(a.id===t&&a.transport==="pty")return a.mode==="chat"?"chat":"terminal"}return null}function tN({visibleConversations:e,clearedTabs:t,setClearedTabs:n,setActionLogs:a,isConversationMuted:r}){l.useEffect(()=>{dm()},[]);const o=l.useMemo(()=>e.map(i=>({id:i.tabKey,name:Jm(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null,target:{providerSessionId:i.providerSessionId,sessionId:i.sessionId,tabKey:i.tabKey,routeId:i.routeId},muted:r?r(i):!1})),[e,r]);return pk(o),l.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{n(d=>{const p=Date.now(),u={};for(const[m,f]of Object.entries(d))p-f<5e3&&(u[m]=f);return Object.keys(u).length===Object.keys(d).length?d:u})},5500);return()=>clearTimeout(c)},[t,n]),l.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;a(d=>{const p=d.filter(u=>u.timestamp>c).slice(-100);return p.length===d.length?d:p})},6e4);return()=>clearInterval(i)},[a]),null}function Vd(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function jn(e){const t=[...e.messages].reverse().find(r=>!(r!=null&&r._localId))||e.messages[e.messages.length-1],n=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,a=Vd(t==null?void 0:t.receivedAt)||Vd(t==null?void 0:t.timestamp)||0;return Math.max(n,a)}function ul(e,t=0){return jn(e)||e.lastUpdated||t||0}function Th(e){return jn(e)||e.lastUpdated||0}function Mh(e,t,n=Th){const a=n(t)-n(e);if(a!==0)return a;const r=(e.machineName||"").localeCompare(t.machineName||"");if(r!==0)return r;const o=e.displayPrimary.localeCompare(t.displayPrimary);if(o!==0)return o;const i=e.displaySecondary.localeCompare(t.displaySecondary);return i!==0?i:e.tabKey.localeCompare(t.tabKey)}function pl(e){var n;const t=os(e.status,{activeModal:(n=e.modalButtons)!=null&&n.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function sN(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!pl(e)&&!e.title.trim()}function nN(e){return e.length===0?null:[...e].sort((t,n)=>{const a=Number(pl(n))-Number(pl(t));if(a!==0)return a;const r=n.messages.length-t.messages.length;return r!==0?r:Mh(t,n)})[0]||null}function ws(e,t){const n=e.filter(i=>i.routeId===t);if(n.length===0)return null;const a=n.find(i=>i.streamSource==="native")||null,r=n.filter(i=>i.streamSource==="agent-stream"),o=nN(r);return a?o&&sN(a)?o:a:o||n[0]||null}function aN(e){const t=e.filter(r=>r.type!=="adhdev-daemon"),n=new Set;for(const r of t){if(!Ji(r))continue;const o=am(r);o&&n.add(o)}const a=new Map;for(const r of t){const o=O0(r,n),i=a.get(o);if(!i){a.set(o,r);continue}const c=m=>(m.workspace?1:0)+(m.activeChat?1:0)+(m.lastMessagePreview?1:0),d=c(i),p=c(r),u=p>d||p===d&&(r.timestamp||0)>(i.timestamp||0)?r:i;a.set(o,rN(u,u===r?i:r))}return Array.from(a.values())}function rN(e,t){const n=Ji(t),a=Ji(e);if(!n&&!a)return e;const r=a?n?void 0:t:e,o=a?e:n?t:void 0,i=r&&String(r.daemonId||"").trim()||String(e.ownerDaemonId||"").trim()||String(t.ownerDaemonId||"").trim()||void 0,c=String(e.ownerMachineName||"").trim()||String(t.ownerMachineName||"").trim()||void 0,d=o==null?void 0:o.settings;return{...e,...i&&{ownerDaemonId:i},...c&&!e.ownerMachineName&&{ownerMachineName:c},...d&&!a&&{settings:{...d,...e.settings??{}}}}}function ti(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function oN(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function Yd(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],n=t[t.length-1],a=n?oN(ea(n.content)):"";return[e.id||"",e.title||"",e.status||"",t.length,String((n==null?void 0:n.id)||""),String((n==null?void 0:n.index)??""),String((n==null?void 0:n.receivedAt)??(n==null?void 0:n.timestamp)??""),a].join(":")}function iN(e){const t=Array.isArray(e.childSessions)?e.childSessions:[];return[e.id,e.sessionId||"",e.providerSessionId||"",e.transport||"",e.mode||"",e.status||"",e.workspace||"",e.lastMessageHash||"",String(e.lastMessageAt||""),e.lastMessagePreview||"",e.lastMessageRole||"",String(e.lastUpdated||""),Yd(e.activeChat),...t.map(n=>[n.id||"",n.providerSessionId||"",n.transport||"",n.mode||"",n.status||"",n.title||"",n.lastMessageHash||"",String(n.lastMessageAt||""),n.lastMessagePreview||"",n.lastMessageRole||"",String(n.lastUpdated||""),Yd(n.activeChat)].join(":"))].join("|")}function lN(e,t){const n=Date.now();return e.map(a=>{const r=t[a.tabKey];return r&&n-r<5e3?{...a,messages:[],title:""}:a})}function cN(e,t){const n=new Map;for(const a of e){const r=t.get(a.routeId)||a;for(const o of Ta({routeId:a.routeId}))n.set(o,r);for(const o of Ta({providerSessionId:a.providerSessionId,sessionId:a.sessionId}))n.set(o,a.streamSource==="native"?r:a);for(const o of Ta({tabKey:a.tabKey}))n.set(o,a)}return n}function dN(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function uN(e){const t=dN(e);if(!t)return`empty:${e.messages.length}`;if(t.id)return`id:${String(t.id)}`;if(t._localId)return`local:${String(t._localId)}`;const n=String(t.role||""),a=ea(t.content).slice(0,240);return`${e.messages.length}:${n}:${a}`}function pN({ides:e,connectionStates:t,clearedTabs:n}){const a=l.useMemo(()=>aN(e),[e]),r=l.useMemo(()=>Vp(e),[e]),o=l.useMemo(()=>lh(e),[e]),i=l.useRef([]),c=l.useRef([]),d=l.useRef([]),p=l.useRef(new Map),u=l.useRef(new Map),m=l.useMemo(()=>{const C=new Map,v=[];for(const T of a){const{connectionState:A="new",machineName:I}=ch(T,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),D=iN(T),M=p.current.get(T.id);if(M&&M.ide===T&&M.sourceSignature===D&&M.connectionState===A&&M.machineName===I){C.set(T.id,M),v.push(...M.conversations);continue}const E=nc(T,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),P={ide:T,sourceSignature:D,connectionState:A,machineName:I,conversations:E};C.set(T.id,P),v.push(...E)}p.current=C;const y=new Map,j=T=>{const A=uN(T),I=u.current.get(T.tabKey);if(I&&I.signature===A)return y.set(T.tabKey,I),I.timestamp;const D={signature:A,timestamp:Th(T)||(I==null?void 0:I.timestamp)||0};return y.set(T.tabKey,D),D.timestamp},N=[...v].sort((T,A)=>Mh(T,A,j));return u.current=y,N},[a,t,o]),f=l.useMemo(()=>{const C=lN(m,n);return ti(i.current,C)?i.current:(i.current=C,C)},[m,n]),g=l.useMemo(()=>{const C=new Map,v=Array.from(new Set(f.map(y=>y.routeId)));for(const y of v){const j=ws(f,y);j&&C.set(y,j)}return C},[f]),k=l.useMemo(()=>{const C=new Map;for(const v of f){const y=g.get(v.routeId),j=v.streamSource==="native"&&y?y:v;for(const N of Ta({providerSessionId:v.providerSessionId,sessionId:v.sessionId,tabKey:v.tabKey}))C.set(N,j)}return C},[f,g]),h=l.useMemo(()=>cN(f,g),[f,g]),x=l.useCallback(C=>{if(C)return k.get(C)},[k]),S=l.useCallback(C=>{if(C)return h.get(C)},[h]),b=l.useMemo(()=>{const C=f.filter(v=>!an(v,r).surfaceHidden);return ti(c.current,C)?c.current:(c.current=C,C)},[f,r]),w=l.useMemo(()=>{const C=b.map(v=>v.tabKey);return ti(d.current,C)?d.current:(d.current=C,C)},[b]);return{chatIdes:a,conversations:f,visibleConversations:b,visibleTabKeys:w,resolveConversationBySessionId:x,resolveConversationByTarget:S}}function mN({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:n,setSearchParams:a}){const r=l.useMemo(()=>{var c;return e||!t?null:((c=n(t))==null?void 0:c.tabKey)??null},[e,n,t]),o=l.useMemo(()=>{var c;return!e||!t?null:((c=n(t))==null?void 0:c.tabKey)??null},[e,n,t]),i=l.useCallback(()=>{t&&a(c=>{const d=new URLSearchParams(c);return d.delete("activeTab"),d},{replace:!0})},[a,t]);return{requestedDesktopTabKey:r,requestedMobileTabKey:o,consumeRequestedActiveTab:i}}function hN({ides:e,sendDaemonCommand:t,setToasts:n,resolveConversationByTarget:a}){l.useEffect(()=>{ft.setIdes(e)},[e]),l.useEffect(()=>{ft.setResolveAction((r,o,i)=>{t(r,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const r=ft.onToast(o=>{n(c=>c.some(p=>p.message===o.message&&o.timestamp-p.timestamp<3e3)?c:[...c.slice(-4),{id:o.id,message:o.message,type:o.type,timestamp:o.timestamp,targetKey:o.targetKey,actions:o.actions}]);const i=o.duration||5e3;setTimeout(()=>n(c=>c.filter(d=>d.id!==o.id)),i)});return()=>{r()}},[n]),l.useEffect(()=>{const r=Km.on("status_event",o=>{ft.handleRawEvent(o,"ws")});return()=>{r()}},[]),l.useEffect(()=>{var o;const r=i=>{var h;const c=i.data;if((c==null?void 0:c.type)!=="notification_action"||typeof c.action!="string"||!c.action.startsWith("approval_")||!(c.daemonId||c.targetSessionId||c.targetKey))return;const d=c.targetSessionId||c.targetKey||c.daemonId,p=a(d),u=(p==null?void 0:p.routeId)||c.daemonId;if(!u)return;const m=Number(c.buttonIndex),f=c.button||((h=p==null?void 0:p.modalButtons)==null?void 0:h[m])||"Approve",g=String(f).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),k=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(g);t(u,"resolve_action",{action:k?"approve":"reject",button:f,...Number.isFinite(m)&&{buttonIndex:m},...(p==null?void 0:p.sessionId)&&{targetSessionId:p.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(x=>console.error("[SW Action] approval failed:",x))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",r),()=>{var i;return(i=navigator.serviceWorker)==null?void 0:i.removeEventListener("message",r)}},[a,t])}const fN="adhdev_dashboardLayout_v1",gN="adhdev_dashboardDockview_v1",bN="adhdev_dashboardDockviewHiddenRestore_v1",xa={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function lc(e,t){try{const n=localStorage.getItem(e);return n?JSON.parse(n):t}catch{return t}}function xN(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Ph(e){return`${fN}:${e}`}function vN(e){const t=Ph(e);return lc(t,null)}function yN(e,t){try{const n=t.groupAssignments.length===0&&t.focusedGroup===0&&Object.keys(t.groupActiveTabIds).length===0&&Object.keys(t.groupTabOrders).length===0&&t.groupSizes.length===0,a=Ph(e);if(n){localStorage.removeItem(a);return}localStorage.setItem(a,JSON.stringify(t))}catch{}}function Dh(e){return`${gN}:${e}`}function wN(e){const t=Dh(e);return lc(t,null)}function kN(e,t){try{const n=Dh(e);if(!t){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Ih(e){return`${bN}:${e}`}function SN(e){const t=Ih(e);return lc(t,{})}function CN(e,t){try{const n=Ih(e);if(Object.keys(t).length===0){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function jN(){return{groupAssignments:[...xa.groupAssignments],focusedGroup:xa.focusedGroup,groupActiveTabIds:{...xa.groupActiveTabIds},groupTabOrders:{...xa.groupTabOrders},groupSizes:[...xa.groupSizes]}}function NN(e,t){return e?e.length===t.length&&e.every((n,a)=>n===t[a]):t.length===0}function AN(){const[e]=l.useState(()=>xN(typeof window<"u"?window.innerWidth:1280)),[t,n]=l.useState(()=>new Map),[a,r]=l.useState(0),[o,i]=l.useState({}),[c,d]=l.useState({}),[p,u]=l.useState([]),[m,f]=l.useState(()=>typeof window<"u"&&window.innerWidth<768),[g,k]=l.useState(!1),h=l.useCallback(()=>{if(g)return;const T=vN(e)??jN();n(new Map(T.groupAssignments)),r(T.focusedGroup),i(T.groupActiveTabIds),d(T.groupTabOrders),u(T.groupSizes),k(!0)},[g,e]);l.useEffect(()=>{g&&yN(e,{groupAssignments:[...t.entries()],focusedGroup:a,groupActiveTabIds:o,groupTabOrders:c,groupSizes:p})},[g,e,t,a,o,c,p]),l.useEffect(()=>{const T=window.matchMedia("(max-width: 767px)"),A=I=>f(I.matches);return T.addEventListener("change",A),()=>T.removeEventListener("change",A)},[]);const x=l.useCallback(T=>{n(T)},[]),S=l.useCallback(T=>{r(T)},[]),b=l.useCallback(T=>{i(T)},[]),w=l.useCallback(T=>{d(T)},[]),C=l.useCallback(T=>{u(T)},[]),v=l.useCallback(T=>{S(T)},[S]),y=l.useCallback((T,A)=>{i(I=>(I[T]??null)===(A??null)?I:{...I,[T]:A})},[]),j=l.useCallback((T,A)=>{d(I=>{const D=I[T];return NN(D,A)?I:{...I,[T]:A}})},[]),N=l.useCallback((T,A)=>{const I=A.get(T)??0;return y(I,T),v(I),I},[v,y]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:x,focusedGroup:a,updateFocusedGroup:S,focusGroup:v,groupActiveTabIds:o,updateGroupActiveTabIds:b,setGroupActiveTab:y,groupTabOrders:c,updateGroupTabOrders:w,setGroupTabOrder:j,groupSizes:p,updateGroupSizes:C,isMobile:m,hasHydratedStoredLayout:g,hydrateStoredLayout:h,focusConversationTab:N}}function TN(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0],a=go(t);return typeof(n==null?void 0:n.id)=="string"&&a.includes(n.id)}function MN({urlActiveTab:e,conversations:t,resolveConversationBySessionId:n,normalizedGroupAssignments:a,hasHydratedStoredLayout:r,hydrateStoredLayout:o,focusConversationTab:i,setSearchParams:c,historyModalOpen:d,activeConv:p,isRefreshingHistory:u,ides:m,handleRefreshHistory:f}){const g=l.useRef(!1),k=l.useRef(!1),h=l.useRef(null),x=l.useRef(!1);l.useEffect(()=>{if(!e||g.current||t.length===0)return;if(!r){o();return}const S=n(e);S&&(i(S.tabKey,a),g.current=!0,k.current=!0,h.current!=null&&(window.clearTimeout(h.current),h.current=null),c(b=>{const w=new URLSearchParams(b);return w.delete("activeTab"),w},{replace:!0}))},[e,t,n,a,r,o,i,c]),l.useEffect(()=>{if(!(k.current||r)&&t.length!==0){if(!e){o(),k.current=!0;return}if(g.current){k.current=!0;return}if(h.current==null)return h.current=window.setTimeout(()=>{h.current=null,!(k.current||r)&&(o(),k.current=!0)},1500),()=>{h.current!=null&&(window.clearTimeout(h.current),h.current=null)}}},[e,t.length,r,o]),l.useEffect(()=>{if(!d){x.current=!1;return}if(!p||x.current||u)return;const S=m.find(b=>b.id===p.routeId);S&&(!S.chats||S.chats.length===0||TN(S.chats,p))&&(x.current=!0,f())},[d,p,u,m,f])}function si(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0];if((n==null?void 0:n.active)===!0)return!0;const a=go(t);return typeof(n==null?void 0:n.id)=="string"&&a.includes(n.id)}function Lh({sendDaemonCommand:e,activeConv:t,chats:n,updateRouteChats:a,setToasts:r,setClearedTabs:o}){const[i,c]=l.useState(!1),[d,p]=l.useState(!1),u=l.useCallback(async k=>{try{await e("standalone","launch_ide",{ideType:k,enableCdp:!0})}catch(h){console.error("Launch failed",h)}},[e]),m=l.useCallback(async(k,h)=>{try{const x=k||(t==null?void 0:t.daemonId)||"",S=await e(x,"switch_chat",{id:h,sessionId:h,...yn(t)}),b=S==null?void 0:S.result;if((S==null?void 0:S.success)===!0||b==="switched"||b==="switched-by-title")return;b===!1||b==="not_found"?Gn(r,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?Gn(r,`⚠️ Switch error: ${b}`):Gn(r,"⚠️ Session switch failed")}catch(x){console.error("Switch failed",x),Gn(r,`❌ Switch failed: ${x.message||"connection error"}`)}},[t,e,r]),f=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const k=wn(t);await e(k,"new_chat",{...yn(t)}),mC(k,t.sessionId,go(t)[0]),o(h=>({...h,[t.tabKey]:Date.now()}))}catch(k){console.error("New chat failed",k)}finally{c(!1)}}},[t,i,e,o]),g=l.useCallback(async()=>{var k,h;if(!(!t||d)){p(!0);try{const x=wn(t),S=async()=>e(x,"list_chats",{forceExpand:!0,...yn(t)});let b=await S(),w=(b==null?void 0:b.chats)||((k=b==null?void 0:b.result)==null?void 0:k.chats);si(w,t)&&(await new Promise(C=>setTimeout(C,450)),b=await S(),w=(b==null?void 0:b.chats)||((h=b==null?void 0:b.result)==null?void 0:h.chats)),b!=null&&b.success&&Array.isArray(w)&&(a(t.routeId,w),si(w,t)&&!si(n,t)&&Gn(r,"⚠️ History dialog did not fully open — try once more"))}catch(x){console.error("Refresh history failed",x)}finally{p(!1)}}},[t,n,d,e,a,r]);return{isCreatingChat:i,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:m,handleNewChat:f,handleRefreshHistory:g}}function PN(e,t){if(e.size!==t.size)return!1;for(const[n,a]of e)if(t.get(n)!==a)return!1;return!0}function DN(e,t){return e.length!==t.length?!1:e.every((n,a)=>n===t[a])}function Qd(e,t){const n=Object.keys(e),a=Object.keys(t);return n.length!==a.length?!1:n.every(r=>t[Number(r)]===e[Number(r)])}function cr(e,t){const n=new Set(t),a=t.length>0?[0]:[];for(const[i,c]of e)!n.has(i)||c<=0||a.includes(c)||a.push(c);a.sort((i,c)=>i-c);const r={};a.forEach((i,c)=>{r[i]=c}),a.length===0&&(r[0]=0);const o=new Map;for(const[i,c]of e){if(!n.has(i)||c<=0)continue;const d=r[c];typeof d=="number"&&d>0&&o.set(i,d)}return{assignments:o,groupCount:Math.max(1,a.length),mapping:r,usedGroups:a}}function Jd(e,t){const n={};for(const[a,r]of Object.entries(e)){const o=t[Number(a)];typeof o=="number"&&(n[o]=r)}return n}function IN(e,t,n){if(t.length===0)return 0;if(typeof n[e]=="number")return n[e];const a=[...t].reverse().find(r=>r<e)??t[0];return n[a]??0}function LN(e,t,n){if(t.length<=1)return[];const a=t.map(i=>e[i]).filter(i=>Number.isFinite(i)),r=a.length===t.length?a:Array(n).fill(100/n),o=r.reduce((i,c)=>i+c,0);return o>0?r.map(i=>i/o*100):Array(n).fill(100/n)}function Xd(e,t){const n={};for(const[a,r]of Object.entries(e)){const o=Number(a);n[o>=t?o+1:o]=r}return n}function Zd(e){return Array(e).fill(100/e)}function RN({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:n,updateGroupActiveTabIds:a,updateGroupTabOrders:r,groupSizes:o,updateGroupSizes:i,isMobile:c,visibleConversations:d,visibleTabKeys:p}){const u=l.useRef(null),m=l.useMemo(()=>cr(e,p),[e,p]),f=m.assignments,g=l.useMemo(()=>c?1:m.groupCount,[m.groupCount,c]),k=g>1,h=l.useCallback((v,y)=>{t(j=>{const N=new Map(cr(j,p).assignments);return y===0?N.delete(v):N.set(v,y),N}),a(j=>({...j,[y]:v})),n(y)},[t,p,a,n]),x=l.useCallback(v=>{t(y=>{const j=cr(y,p).assignments,N=new Map;for(const[T,A]of j)A!==v&&(A>v?N.set(T,A-1):N.set(T,A));return N}),i(y=>{if(y.length<=1)return[];const j=[...y];j.splice(v,1);const N=j.reduce((T,A)=>T+A,0);return N>0?j.map(T=>T/N*100):[]}),n(0)},[t,p,i,n]),S=l.useCallback((v,y)=>{y.preventDefault();const j=u.current;if(!j)return;const N=y.clientX,T=j.offsetWidth,A=o.length===g?[...o]:Zd(g),I=M=>{const P=(M.clientX-N)/T*100,B=[...A];B[v]=Math.max(15,A[v]+P),B[v+1]=Math.max(15,A[v+1]-P),i(B)},D=()=>{document.removeEventListener("mousemove",I),document.removeEventListener("mouseup",D),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",I),document.addEventListener("mouseup",D)},[o,g,i]),b=l.useCallback((v,y,j)=>{if(g>=4)return;const N=j==="left"?y:y+1;t(T=>{const A=cr(T,p).assignments,I=new Map;for(const D of d){const M=A.get(D.tabKey)??0,E=M>=N?M+1:M;E>0&&I.set(D.tabKey,E)}return N>0&&I.set(v,N),I}),i(T=>{const A=T.length===g?[...T]:Zd(g),I=A[y]??100/g,D=Math.max(15,I/2),M=Math.max(15,I/2),E=[...A];E[y]=D,E.splice(N,0,M);const P=E.reduce((B,R)=>B+R,0);return E.map(B=>B/P*100)}),a(T=>{const A=Xd(T,N);return A[N]=v,A}),r(T=>{const A=Xd(T,N);return A[N]=[v],A}),n(N)},[g,t,p,d,i,a,r,n]);l.useEffect(()=>{PN(e,f)||t(f)},[e,f,t]),l.useEffect(()=>{const{mapping:v,usedGroups:y}=m;a(j=>{const N=Jd(j,v);return Qd(j,N)?j:N}),r(j=>{const N=Jd(j,v);return Qd(j,N)?j:N}),n(j=>{const N=c?0:IN(j,y,v);return j===N?j:N}),i(j=>{const N=c?[]:LN(j,y,m.groupCount);return DN(j,N)?j:N})},[m,c,a,r,n,i]);const w=l.useMemo(()=>{const v=Array.from({length:g},()=>[]);for(const y of d){const j=f.get(y.tabKey)??0,N=Math.min(j,g-1);v[N].push(y)}return v},[d,f,g]),C=l.useCallback(()=>{t(new Map),n(0)},[t,n]);return{containerRef:u,normalizedGroupAssignments:f,numGroups:g,isSplitMode:k,groupedConvs:w,moveTabToGroup:h,closeGroup:x,handleResizeStart:S,splitTabRelative:b,clearAllSplits:C}}function EN({ides:e,sendDaemonCommand:t}){const n="1.0.55",a=l.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:So(m,Qs(m,n))).sort((m,f)=>Number(Pa(f,Qs(f,n)))-Number(Pa(m,Qs(m,n)))),[n,e]),r=l.useMemo(()=>a.some(m=>Pa(m,Qs(m,n))),[n,a]),o=l.useMemo(()=>a.map(m=>Qs(m,n)).find(m=>typeof m=="string"&&m.trim().length>0)||n,[n,a]),[i,c]=l.useState(!1),[d,p]=l.useState({}),u=l.useCallback(async m=>{var k,h;const f=e.find(x=>x.id===m);if(!f)return;p(x=>({...x,[m]:"upgrading"}));const g=Co(f);if(!g){p(x=>({...x,[m]:"error"}));return}try{const x=await t(m,"daemon_upgrade",g);(k=x==null?void 0:x.result)!=null&&k.upgraded||(h=x==null?void 0:x.result)!=null&&h.success?p(S=>({...S,[m]:"done"})):p(S=>({...S,[m]:"error"}))}catch{p(x=>({...x,[m]:"error"}))}},[e,t]);return{versionMismatchDaemons:a,hasRequiredVersionDaemons:r,targetVersion:o,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:u}}const Rh=80;function Pr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function _N(e){return{...e,createdAt:Pr(e.createdAt),updatedAt:Pr(e.updatedAt,e.createdAt),lastEventAt:Pr(e.lastEventAt,e.updatedAt||e.createdAt)}}function HN(e){const t=nm(e);return t==="unknown:"?e.id:t}function $N(e){return[e.type,sm(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function FN(e,t=Rh){const n=new Map;for(const a of e){if(a.deletedAt)continue;const r=HN(a),o=n.get(r);if(!o){n.set(r,a);continue}(a.updatedAt>o.updatedAt||a.updatedAt===o.updatedAt&&a.createdAt>o.createdAt)&&n.set(r,a)}return Array.from(n.values()).sort((a,r)=>{const o=r.updatedAt-a.updatedAt;return o!==0?o:r.createdAt-a.createdAt}).slice(0,Math.max(0,t))}function BN(e,t){const n=Date.now(),a=[];for(const r of e){const o=r.sessionId?t.get(r.sessionId):void 0;if(o!=null&&o.surfaceHidden||o!=null&&o.muted)continue;const i=fo(r,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const d=Pr(r.lastMessageAt||(o==null?void 0:o.lastUpdated)||r.lastUpdated,n),p=$N({type:c,sessionId:r.sessionId,providerSessionId:r.providerSessionId,tabKey:r.tabKey,lastMessageHash:r.lastMessageHash,lastMessageAt:r.lastMessageAt,lastUpdated:(o==null?void 0:o.lastUpdated)||r.lastUpdated});a.push(_N({id:p,dedupKey:p,type:c,routeId:r.routeId,machineId:r.daemonId||r.routeId,sessionId:r.sessionId,providerSessionId:r.providerSessionId,tabKey:r.tabKey,title:Cm(r),preview:jS(r),createdAt:d,updatedAt:d,lastEventAt:d}))}return FN(a)}function WN(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function ON(e){const{conversations:t,liveSessionInboxState:n,maxItems:a=Rh}=e,r=l.useMemo(()=>BN(t,n).slice(0,Math.max(0,a)),[t,n,a]),o=l.useMemo(()=>WN(r),[r]);return{notifications:r,unreadCount:o}}function UN({notifications:e,sendDaemonCommand:t}){const n=l.useCallback(o=>{const i=e.find(d=>d.id===o),c=Math.max(Date.now(),(i==null?void 0:i.updatedAt)||0);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_session_seen",{sessionId:i.sessionId,seenAt:c}).catch(()=>{})},[e,t]),a=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_notification_unread",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]),r=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"delete_notification",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:n,handleMarkDashboardNotificationUnread:a,handleDeleteDashboardNotification:r}}function cc(...e){const t=new Set,n=[],a=r=>{const o=typeof r=="string"?r.trim():"";if(!o)return;const i=o.toLowerCase();t.has(i)||(t.add(i),n.push(o))};for(const r of e){if(Array.isArray(r)){for(const o of r)a(o);continue}a(r)}return n}function GN(e){const t=e.trim();if(!t)return null;if(t.startsWith("~"))return t;if(/^[A-Za-z]:$/.test(t))return`${t[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(t))return`${t[0].toUpperCase()}:${t.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(t))return`${t[0].toUpperCase()}:\\${t.slice(2).replace(/[\\/]+/g,"\\")}`;const n=t.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(n){const a=n[1].toUpperCase(),r=(n[2]||"").replace(/[\\/]+/g,"\\");return r?`${a}:\\${r}`:`${a}:\\`}return null}function dc(e,t=[]){if(e==="win32"){for(const n of t){if(typeof n!="string")continue;const a=GN(n);if(a)return a}return"C:\\"}for(const n of t){const a=typeof n=="string"?n.trim():"";if(a)return a}return"~"}function qN(e){const t=e.replace(/[\\/]+$/,"");if(!t||t==="/"||/^[A-Za-z]:$/.test(t))return null;const n=t.includes("\\")?"\\":"/",a=t.split(/[\\/]/);return/^[A-Za-z]:$/.test(a[0]||"")?a.length<=2?`${a[0]}\\`:a.slice(0,-1).join("\\"):a.length<=2?n:a.slice(0,-1).join(n)||n}function zN(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function uc(e,t,n){const a=await e(t,"file_list_browse",{path:n}),r=zN(a);if(!(r!=null&&r.success))throw new Error((r==null?void 0:r.error)||(a==null?void 0:a.error)||"Could not browse folder");const o=typeof(r==null?void 0:r.path)=="string"?r.path:n,i=o.includes("\\")?"\\":"/",c=(p,u)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${u}`:p==="/"||p==="\\"?`${i}${u}`:`${p.replace(/[\\/]+$/,"")}${i}${u}`,d=Array.isArray(r==null?void 0:r.files)?r.files.filter(p=>(p==null?void 0:p.type)==="directory"&&typeof(p==null?void 0:p.name)=="string").map(p=>({name:p.name,path:typeof(p==null?void 0:p.path)=="string"&&p.path.trim()?p.path:c(o,p.name)})).sort((p,u)=>p.name.localeCompare(u.name)):[];return{path:o,directories:d}}function eu(e,t){const n=t.meshId||"",a={meshId:n,workspace:t.workspace||"",serverName:t.serverName||"adhdev-mesh",adhdevMcpCommand:t.adhdevMcpCommand||"adhdev-mcp",adhdevMcpArgs:t.adhdevMcpArgs||`mcp --mode ipc --repo-mesh ${n}`};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand|adhdevMcpArgs)\s*\}\}/g,(r,o)=>a[o]||"")}function Eh(e,t={}){const n=e==null?void 0:e.mcpConfig;if((n==null?void 0:n.mode)!=="manual")return null;const r=eu(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"}).trim();return!r.includes(`
|
|
65
|
+
`)&&!r.startsWith("{")?null:{serverName:n.serverName||"adhdev-mesh",configFormat:n.format,configPathCommand:n.configPathCommand,requiresRestart:n.requiresRestart===!0,instructions:n.instructions||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:eu(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"})}}function KN(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.instructions=="string"?t.instructions:"",a=typeof t.template=="string"?t.template:"";return!n&&!a?null:{serverName:typeof t.serverName=="string"?t.serverName:void 0,configFormat:typeof t.configFormat=="string"?t.configFormat:void 0,configPathCommand:typeof t.configPathCommand=="string"?t.configPathCommand:void 0,requiresRestart:t.requiresRestart===!0,instructions:n||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:a}}function Ba(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function _h(e){return bo(e)||e.tabKey||e.routeId||null}function Hh(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"",n=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"",a=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"",r=e.conversations.find(o=>{if(a&&o.routeId!==a)return!1;const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey].map(c=>typeof c=="string"?c.trim():"").filter(Boolean);return!!(t&&i.includes(t)||n&&i.includes(n)||a&&o.routeId===a)});if(r!=null&&r.tabKey)return r.tabKey;if(a){const o=ws(e.conversations,a)||e.conversations.find(i=>i.routeId===a);if(o!=null&&o.tabKey)return o.tabKey}return t||n||a||null}function Js(e){return String(e||"").trim()}function $h(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Xr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function VN(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function YN(e,t){const n=Js(e.providerSessionId),a=Js(e.targetSessionId),r=t.find(o=>{const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(Js).filter(Boolean);return!!(n&&i.includes(n)||a&&i.includes(a))});return r?r.tabKey:a||n||null}function QN(e,t,n){if(t.event!=="agent:generating_completed")return null;const a=$h(t.daemonId);if(a&&a!==e.machineId)return null;const r=Js(t.providerType);if(e.providerType&&r!==e.providerType)return null;const o=Js(e.resumeSessionId),i=Js(e.launchedSessionId),c=Js(t.providerSessionId),d=Js(t.targetSessionId);if(o&&o!==c&&o!==d||i&&i!==c&&i!==d)return null;const p=Xr(e.workspacePath);if(p){const u=Xr(t.workspaceName);if(u&&!VN(u,p))return null}return YN(t,n)}function tu(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function JN({ides:e,conversations:t,onOpenSession:n}){const[a,r]=l.useState(null),o=l.useRef(null),i=l.useCallback(()=>{o.current=null,r(null)},[]),c=l.useCallback(d=>{o.current=d,r(d)},[]);return l.useEffect(()=>{if(!a)return;const d=Xr(a.workspacePath),p=e.find(m=>{var x,S,b,w;if(!m||m.type==="adhdev-daemon"||$h(m.daemonId||m.id)!==a.machineId||($a(m)?"cli":Jn(m)?"acp":"ide")!==a.kind)return!1;const k=String(m.agentType||m.type||"");if(a.providerType&&k!==a.providerType)return!1;if(a.resumeSessionId)return String(m.providerSessionId||"")===a.resumeSessionId;if(a.launchedSessionId){const C=String(a.launchedSessionId||"");return[m.providerSessionId,m.sessionId,m.instanceId,m.id].map(y=>String(y||"")).filter(Boolean).includes(C)}if(d){const C=Xr(m.workspace||m.runtimeWorkspaceLabel);return C?C===d:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((w=(b=(S=(x=m.activeChat)==null?void 0:x.messages)==null?void 0:S.at)==null?void 0:b.call(S,-1))==null?void 0:w.timestamp)||0)>=a.startedAt-5e3});if(!p)return;const u=Hh({entrySessionId:p.sessionId,entryInstanceId:p.instanceId,entryRouteId:p.id,conversations:t});u&&(i(),n(u))},[i,t,e,n,a]),l.useEffect(()=>ft.onStatusEvent(d=>{const p=o.current;if(!p)return;const u=QN(p,d,t);u&&(i(),n(u))}),[i,t,n]),l.useEffect(()=>{if(!a)return;const d=window.setTimeout(()=>{r(p=>!p||p.startedAt!==a.startedAt?p:(o.current=null,null))},45e3);return()=>window.clearTimeout(d)},[a]),{trackPendingLaunch:c}}function XN(e,t){var a,r,o,i;const n={cliType:e};return(a=t==null?void 0:t.workspacePath)!=null&&a.trim()?n.dir=t.workspacePath.trim():t!=null&&t.workspaceId?n.workspaceId=t.workspaceId:t!=null&&t.useHome&&(n.useHome=!0),(r=t==null?void 0:t.resumeSessionId)!=null&&r.trim()&&(n.resumeSessionId=t.resumeSessionId.trim()),Array.isArray(t==null?void 0:t.cliArgs)&&t.cliArgs.length>0&&(n.cliArgs=t.cliArgs),(o=t==null?void 0:t.initialModel)!=null&&o.trim()&&(n.initialModel=t.initialModel.trim()),(i=t==null?void 0:t.initialThinkingLevel)!=null&&i.trim()&&(n.initialThinkingLevel=t.initialThinkingLevel.trim()),t!=null&&t.settings&&(n.settings=t.settings),n}function ZN(e,t,n){var i,c,d,p;const a={meshId:e.trim()};t.trim()&&(a.cliType=t.trim());const r=(i=n==null?void 0:n.initialModel)==null?void 0:i.trim(),o=(c=n==null?void 0:n.initialThinkingLevel)==null?void 0:c.trim();return r&&(a.initialModel=r),o&&(a.initialThinkingLevel=o),(d=n==null?void 0:n.settings)!=null&&d.autoApproveMode?a.autoApproveMode=n.settings.autoApproveMode:typeof((p=n==null?void 0:n.settings)==null?void 0:p.autoApprove)=="boolean"&&(a.autoApprove=n.settings.autoApprove),a}function eA({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:n,activeConv:a,ides:r,setCliViewModeOverrides:o}){const i=zl(),{launchCli:c}=ho(),d=l.useCallback(async(x,S)=>uc(e,x,S),[e]),p=l.useCallback(async(x,S)=>{if(!S.trim())return{ok:!1,error:"Choose a workspace path first."};try{const b=await e(x,"workspace_add",{path:S.trim()});return b!=null&&b.success?{ok:!0}:{ok:!1,error:(b==null?void 0:b.error)||"Could not save workspace"}}catch(b){return{ok:!1,error:b instanceof Error?b.message:"Could not save workspace"}}},[e]),u=l.useCallback(async(x,S,b)=>{var w;try{const C={ideType:S,enableCdp:!0};(w=b==null?void 0:b.workspacePath)!=null&&w.trim()&&(C.workspace=b.workspacePath.trim());const v=await e(x,"launch_ide",C);return!(v!=null&&v.success)&&(v==null?void 0:v.success)!==void 0?{ok:!1,error:(v==null?void 0:v.error)||"Could not launch IDE"}:(t({machineId:x,kind:"ide",providerType:S,workspacePath:(b==null?void 0:b.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(C){return{ok:!1,error:C instanceof Error?C.message:"Could not launch IDE"}}},[e,t]),m=l.useCallback(async(x,S,b,w)=>{const C=Date.now();try{const v=XN(b,w),y=await c(x,v),j=(y==null?void 0:y.result)||y,N=(j==null?void 0:j.sessionId)||(j==null?void 0:j.id);return y!=null&&y.success&&N?(t({machineId:x,kind:S,providerType:b,workspacePath:(w==null?void 0:w.workspacePath)||null,resumeSessionId:(w==null?void 0:w.resumeSessionId)||null,launchedSessionId:N,startedAt:C}),{ok:!0}):y!=null&&y.success?(t({machineId:x,kind:S,providerType:b,workspacePath:(w==null?void 0:w.workspacePath)||null,resumeSessionId:(w==null?void 0:w.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:(y==null?void 0:y.error)||(j==null?void 0:j.error)||`Could not launch ${S.toUpperCase()} session`,code:(y==null?void 0:y.code)||(j==null?void 0:j.code)||void 0}}catch(v){return tu(v)?(t({machineId:x,kind:S,providerType:b,workspacePath:(w==null?void 0:w.workspacePath)||null,resumeSessionId:(w==null?void 0:w.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:v instanceof Error?v.message:`Could not launch ${S.toUpperCase()} session`}}},[c,e,t]),f=l.useCallback(async x=>{var S;if(i!=null&&i.listMeshes)return i.listMeshes(x);if(!x)return[];try{const b=await e(x,"list_meshes",{}),w=(b==null?void 0:b.result)??b;if((w==null?void 0:w.success)===!1)throw new Error((w==null?void 0:w.error)||"Could not load meshes");return(Array.isArray(w==null?void 0:w.meshes)?w.meshes:Array.isArray((S=w==null?void 0:w.result)==null?void 0:S.meshes)?w.result.meshes:[]).map(v=>{var y;return{id:String((v==null?void 0:v.id)||""),name:String((v==null?void 0:v.name)||(v==null?void 0:v.id)||"Untitled mesh"),repoIdentity:(v==null?void 0:v.repoIdentity)||(v==null?void 0:v.repo_identity)||null,workspace:Array.isArray(v==null?void 0:v.nodes)&&v.nodes.length>0?String(((y=v.nodes[0])==null?void 0:y.workspace)||""):null,nodesCount:Array.isArray(v==null?void 0:v.nodes)?v.nodes.length:void 0,status:(v==null?void 0:v.status)||null}}).filter(v=>v.id)}catch(b){throw console.error("List meshes failed",b),b}},[i,e]),g=l.useCallback(async(x,S,b,w)=>{if(!S.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(x,S,b,w);const C=Date.now();try{const v=ZN(S,b,w),y=await e(x,"launch_mesh_coordinator",v),j=(y==null?void 0:y.result)??y;if((j==null?void 0:j.success)===!1||(y==null?void 0:y.success)===!1){const T=String((j==null?void 0:j.code)||(y==null?void 0:y.code)||""),A=KN((j==null?void 0:j.meshCoordinatorSetup)||(j==null?void 0:j.manualSetup)||(y==null?void 0:y.meshCoordinatorSetup)||(y==null?void 0:y.manualSetup));return{ok:!1,error:(j==null?void 0:j.error)||(y==null?void 0:y.error)||"Could not launch mesh coordinator",code:T||void 0,manualSetup:A}}const N=(j==null?void 0:j.sessionId)||(j==null?void 0:j.id);return N?n(N):t({machineId:x,kind:"cli",providerType:(j==null?void 0:j.cliType)||b.trim()||void 0,workspacePath:(j==null?void 0:j.workspace)||null,startedAt:C}),{ok:!0}}catch(v){return tu(v)?(t({machineId:x,kind:"cli",providerType:b.trim()||void 0,startedAt:C}),{ok:!0}):{ok:!1,error:v instanceof Error?v.message:"Could not launch mesh coordinator"}}},[i,n,e,t]),k=l.useCallback(async(x,S)=>{if(!x||!S)return[];try{const b=await e(x,"list_saved_sessions",{providerType:S,kind:"cli",limit:30}),w=(b==null?void 0:b.result)??b;return Array.isArray(w==null?void 0:w.sessions)?w.sessions:[]}catch(b){return console.error("List saved sessions failed",b),[]}},[e]),h=l.useCallback(async x=>{await Ah({conversation:a,mode:x,ides:r,sendDaemonCommand:e,setCliViewModeOverrides:o})},[a,r,e,o]);return{handleBrowseMachineDirectory:d,handleSaveMachineWorkspace:p,handleLaunchMachineIde:u,handleLaunchMachineProvider:m,handleListMachineMeshes:f,handleLaunchMeshCoordinator:g,handleListMachineSavedSessions:k,setActiveCliViewMode:h}}function tA(e){switch(e){case"notification-open":case"toast-open":case"conversation-open":case"requested-tab":return!0;case"dockview-shortcut":case"dockview-focus":case"dockview-move":case"dockview-split":case"stored-layout-restore":case"passive-tab-sync":return!1;default:return!1}}function sA(e,t,n=Date.now()){return!e||!tA(t)?null:{tabKey:e,nonce:n}}function nA({isMobile:e,conversations:t,visibleConversations:n,groupActiveTabIds:a,focusedGroup:r,groupedConvs:o,setSearchParams:i}){const[c,d]=l.useState(null),[p,u]=l.useState(null),m=l.useMemo(()=>{var x,S;if(!e){if(c){const b=t.find(w=>w.tabKey===c);if(b)return b}return n[0]}const h=a[r];if(h){const b=t.find(w=>w.tabKey===h);if(b)return b}return((x=o[r])==null?void 0:x[0])||((S=o[0])==null?void 0:S[0])},[t,c,r,a,o,e,n]),f=l.useCallback(h=>{d(h)},[]),g=l.useCallback(h=>{d(h.tabKey),i(x=>{const S=new URLSearchParams(x),b=AS(h);return b?S.set("activeTab",b):S.delete("activeTab"),S},{replace:!0})},[i]),k=l.useCallback((h,x)=>{const S=sA(h,x);S&&u(S)},[]);return{activeConv:m,openDesktopConversation:g,requestScrollToBottom:k,scrollToBottomRequest:p,setDesktopActiveTab:f}}function aA(e){const t=e.completedKey||null,n=e.pendingKey||null;return e.shouldMarkSeen?t===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:n!==null&&n!==e.autoReadKey,nextPendingKey:n===e.autoReadKey?n:null}:n===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:!1,nextPendingKey:n}:{shouldSchedule:!0,shouldCancelPending:n!==null&&n!==e.autoReadKey,nextPendingKey:e.autoReadKey}:{shouldSchedule:!1,shouldCancelPending:!!n,nextPendingKey:null}}function rA(e){const t=String(e.liveState.completionMarker||""),n=String(e.liveState.seenCompletionMarker||""),a=String(e.liveState.inboxBucket||"idle"),r=!!e.liveState.unread,o=[e.tabKey,e.historySessionId||"",t,n,a,r?"1":"0"].join(":");return{shouldMarkSeen:!!(a==="task_complete"&&r&&(!t||t!==n)),autoReadKey:o,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function oA({activeConv:e,isMobile:t,liveSessionInboxState:n,sendDaemonCommand:a}){const r=l.useRef(null),o=l.useRef(null),i=l.useRef(null),c=l.useRef(null),d=l.useRef(null);l.useEffect(()=>{const p=()=>{i.current&&(clearTimeout(i.current),i.current=null),c.current&&(clearTimeout(c.current),c.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),o.current=null};if(t){p(),r.current=null;return}if(!(e!=null&&e.sessionId)){p(),r.current=null;return}const u=an(e,n),m=rA({tabKey:e.tabKey,historySessionId:bo(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:jn(e),liveState:u}),f=m.autoReadKey,g=aA({autoReadKey:f,shouldMarkSeen:m.shouldMarkSeen,completedKey:r.current,pendingKey:o.current});if(!m.shouldMarkSeen){g.shouldCancelPending&&p(),r.current=f;return}if(!g.shouldSchedule)return;g.shouldCancelPending&&p();const k=()=>{if(document.visibilityState!=="visible"||r.current===f)return;r.current=f,o.current=null,i.current=null,c.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const x=m.readAt;a(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:x,completionMarker:m.completionMarker}).catch(()=>{})};if(o.current=g.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(k,1500);const x=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};d.current=x,document.addEventListener("visibilitychange",x);return}const h=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(k,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=h,document.addEventListener("visibilitychange",h)},[e,t,n,a]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current),c.current&&clearTimeout(c.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function ni(e){if(!e)return"";const t=String(e.workspacePath||"").trim();if(t)return t;const n=String(e.workspaceName||"").trim();return/^(?:~\/|\/|[A-Za-z]:[\\/])/.test(n)?n:""}function iA({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:n,ides:a,sendDaemonCommand:r,updateRouteChats:o,setToasts:i,setClearedTabs:c,setSearchParams:d}){var W;const{launchCli:p}=ho(),[u,m]=l.useState(!1),[f,g]=l.useState([]),[k,h]=l.useState(()=>qt()),[x,S]=l.useState(!1),[b,w]=l.useState(null),C=l.useRef(null),v=l.useMemo(()=>n||t||e,[e,n,t]),y=!!v&&bt(v)&&!ht(v),j=l.useMemo(()=>{if(!v||!y)return null;const _=v.daemonId||v.routeId||"",H=Ps(v),L=ni(v);return`${_}:${H}:${v.providerSessionId||""}:${L}`},[v,y]),N=l.useMemo(()=>!v||!y?"":ni(v),[v,y]),{isCreatingChat:T,isRefreshingHistory:A,handleSwitchSession:I,handleNewChat:D,handleRefreshHistory:M}=Lh({sendDaemonCommand:r,activeConv:v,chats:(W=a.find(_=>_.id===(v==null?void 0:v.routeId)))==null?void 0:W.chats,updateRouteChats:o,setToasts:i,setClearedTabs:c}),E=l.useCallback(()=>{m(!0)},[]),P=l.useCallback(()=>{m(!1)},[]),B=l.useCallback(async()=>{if(!(!v||!y||x)){S(!0);try{const _=v.daemonId||v.routeId,H=Ps(v),L=ni(v),F=await r(_,"list_saved_sessions",{agentType:H,providerType:H,kind:"cli",limit:50,...v.providerSessionId?{providerSessionId:v.providerSessionId}:{},...L?{workspace:L}:{}}),$=(F==null?void 0:F.result)??F;g(Array.isArray($==null?void 0:$.sessions)?$.sessions:[])}catch(_){console.error("Refresh saved sessions failed",_),g([])}finally{S(!1)}}},[v,x,y,r]);l.useEffect(()=>{if(!u){C.current=null;return}if(!y){C.current=null,g([]),S(!1);return}!j||x||C.current!==j&&(C.current=j,B())},[B,u,x,y,j]);const R=l.useCallback(async _=>{if(!v||!y||!_.providerSessionId||!_.workspace)return;const H=v.daemonId||v.routeId,L=Ps(v);try{w(_.providerSessionId);const F=await p(H,{cliType:L,dir:_.workspace,resumeSessionId:_.providerSessionId,initialModel:lm(_.summaryMetadata,"model",{preferShortValue:!0})||void 0}),$=(F==null?void 0:F.result)??F,K=typeof($==null?void 0:$.sessionId)=="string"?$.sessionId:typeof($==null?void 0:$.id)=="string"?$.id:"";K&&d(z=>{const ne=new URLSearchParams(z);return ne.set("activeTab",K),ne},{replace:!0}),P()}catch(F){console.error("Resume saved session failed",F)}finally{w(null)}},[P,v,y,r,d]);return{historyModalOpen:u,openHistoryModal:E,closeHistoryModal:P,historyTargetConv:v,isSavedSessionHistoryTarget:y,isHistoryCreatingChat:T,isHistoryRefreshingHistory:A,handleHistorySwitchSession:I,handleHistoryNewChat:D,handleHistoryRefresh:M,savedHistorySessions:f,savedHistoryFilters:k,setSavedHistoryFilters:h,missingWorkspaceResumePath:N,isSavedHistoryLoading:x,resumingSavedHistorySessionId:b,handleRefreshSavedHistory:B,handleResumeSavedHistorySession:R}}function lA({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c}){const[d,p]=l.useState(null),[u,m]=l.useState(null),f=l.useMemo(()=>{if(e||!a)return null;const S=c(a);return S&&!bt(S)&&!ht(S)?S:null},[e,a,c]),g=l.useMemo(()=>{const S=d==null?void 0:d.routeId;if(!S)return null;const b=d!=null&&d.tabKey?o.find(w=>w.tabKey===d.tabKey):r?o.find(w=>w.tabKey===r):null;return(b==null?void 0:b.routeId)===S?b:ws(o,S)},[o,d,r]),k=l.useMemo(()=>{if(g)return i.find(S=>S.id===g.routeId)},[i,g]);l.useEffect(()=>{f&&(p({routeId:f.routeId,tabKey:pd(f)}),m(f),n({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,n,f]);const h=l.useCallback(S=>{S&&(p({routeId:S.routeId,tabKey:pd(S)}),m(S))},[]),x=l.useCallback(()=>{p(null),m(null)},[]);return{remoteDialogConv:g,remoteDialogIdeEntry:k,remoteDialogActiveConv:u,setRemoteDialogActiveConv:m,openRemoteDialog:h,closeRemoteDialog:x}}function cA({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c,activeConv:d,sendDaemonCommand:p}){const{remoteDialogConv:u,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:g,openRemoteDialog:k,closeRemoteDialog:h}=lA({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c}),[x,S]=l.useState(!1),[b,w]=l.useState(null),C=l.useCallback(async j=>{const N=j||d;!N||!bt(N)&&!ht(N)||(w(N),S(!0))},[d]),v=l.useCallback(()=>{S(!1),w(null)},[]),y=l.useCallback(async j=>{const N=b||d;if(!N||!bt(N)&&!ht(N)){v();return}S(!1);try{const T=Ps(N),A=N.routeId||N.daemonId||"";await p(A,"stop_cli",{cliType:T,targetSessionId:N.sessionId,mode:j,...yo(N)})}catch(T){console.error("Stop CLI failed:",T)}finally{w(null)}},[d,v,b,p]);return{remoteDialogConv:u,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:g,openRemoteDialog:k,closeRemoteDialog:h,cliStopDialogOpen:x,cliStopTargetConv:b,requestCliStop:C,cancelCliStop:v,confirmCliStop:y}}function ai(e,t=!0){return(e??!0)&&t}const pc=l.memo(function({activeConv:t,clearToken:n,isCliTerminal:a,ideEntry:r,terminalRef:o,handleModalButton:i,handleRelaunch:c,handleSendChat:d,handleForceSendChat:p,isSendingChat:u,sendFeedbackMessage:m=null,handleFocusAgent:f,isFocusingAgent:g,actionLogs:k,userName:h,scrollToBottomRequestNonce:x,isInputActive:S=!0,isVisible:b=!0}){const w=a,C=!a,v=ai(b,w),y=ai(b,C),j=ai(b),N=Ch(t),T=N.status||N.modalMessage||N.modalButtons?{...t,...N.status?{status:N.status}:{},...N.modalMessage!==void 0?{modalMessage:N.modalMessage}:{},...N.modalButtons!==void 0?{modalButtons:N.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(Yp,{activeConv:T,onModalButton:i}),T.transport!=="pty"&&T.transport!=="acp"&&T.cdpConnected===!1?s.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:s.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[s.jsx("span",{className:"text-sm",children:s.jsx(Is,{size:14})}),s.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),s.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:c,children:"Relaunch with CDP"})]})}):null,T.transport==="pty"?s.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[s.jsx("div",{"aria-hidden":!a,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:w?"visible":"hidden",pointerEvents:w?"auto":"none"},children:s.jsx(lj,{activeConv:T,clearToken:n,terminalRef:o,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:m,isVisible:v,isInputActive:S&&v})}),s.jsx("div",{"aria-hidden":a,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:C?"visible":"hidden",pointerEvents:C?"auto":"none"},children:s.jsx(al,{activeConv:T,ideEntry:r,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:k,userName:h,scrollToBottomRequestNonce:x,isInputActive:S&&y,isVisible:y})})]}):s.jsx(al,{activeConv:T,ideEntry:r,handleSendChat:d,handleForceSendChat:p,isSendingChat:u,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:k,userName:h,scrollToBottomRequestNonce:x,isInputActive:S&&j,isVisible:j})]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.handleModalButton===t.handleModalButton&&e.handleRelaunch===t.handleRelaunch&&e.handleSendChat===t.handleSendChat&&e.handleForceSendChat===t.handleForceSendChat&&e.isSendingChat===t.isSendingChat&&e.sendFeedbackMessage===t.sendFeedbackMessage&&e.handleFocusAgent===t.handleFocusAgent&&e.isFocusingAgent===t.isFocusingAgent&&e.actionLogs===t.actionLogs&&e.userName===t.userName&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isInputActive===t.isInputActive&&e.isVisible===t.isVisible);function dA({conversation:e,className:t="",onOpenNativeConversation:n,onOpenMachine:a,interactive:r=!0,meshOnly:o=!1}){var C,v,y;const{t:i}=ke("common"),c=oa(),d=Ks(e),p=o?null:Sm(e),u=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),m=!o&&e.streamSource==="agent-stream"&&!!e.agentName,f=!o&&!m&&(e.transport==="pty"||e.transport==="acp"),g=ta(e),k=NS(e),h=(C=e.settings)==null?void 0:C.meshNodeFor,x=e.meshQueueStats,S=((v=e.coordinator)==null?void 0:v.meshId)||((y=e.settings)==null?void 0:y.meshCoordinatorFor),b=l.useCallback(()=>{if(a){a();return}d&&c("/dashboard",{state:{openMachineId:d}})},[d,c,a]),w=l.useCallback(()=>{if(n){n();return}const j=_h(e);j&&c(Ba(j))},[e,c,n]);return!u&&!m&&!f&&!p&&!h&&!x?null:s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[u&&(r?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:w,title:k,children:[s.jsx(us,{size:12}),s.jsx("span",{children:k})]}):s.jsxs("span",{className:"conversation-meta-chip",title:k,children:[s.jsx(us,{size:12}),s.jsx("span",{children:k})]})),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(Ea,{size:12}),s.jsx("span",{children:g})]}),f&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(Ea,{size:12}),s.jsx("span",{children:g})]}),p&&(r?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:b,title:p,children:[s.jsx(sn,{size:12}),s.jsx("span",{children:p})]}):s.jsxs("span",{className:"conversation-meta-chip",title:p,children:[s.jsx(sn,{size:12}),s.jsx("span",{children:p})]})),h&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(sn,{size:12}),s.jsx("span",{children:i("dashboard.metaChips.meshNode")})]}),S&&x&&s.jsxs("span",{className:`conversation-meta-chip ${x.pending>0?"is-active":""}`,style:x.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${x.pending} pending, ${x.assigned} assigned, ${x.completed} completed, ${x.failed} failed`,children:[s.jsx(pb,{size:12}),s.jsxs("span",{children:[x.pending," Pending"]})]})]})}function uA({selectedConversation:e,isAcp:t,isStandalone:n,selectedIdeEntry:a,actionLogs:r,userName:o,isSendingChat:i,sendFeedbackMessage:c=null,isFocusingAgent:d,onBack:p,onOpenNativeConversation:u,onOpenMachine:m,onOpenHistory:f,onOpenRemote:g,onOpenMeshGraph:k,onStopCli:h,cliViewMode:x,onSetCliViewMode:S,handleSendChat:b,handleForceSendChat:w,handleFocusAgent:C,handleModalButton:v,handleRelaunch:y}){var D,M;const j=l.useRef(null),N=bt(e)&&!t,T=N&&x==="terminal",A=!!e.daemonId&&!!((D=e.coordinator)!=null&&D.meshId||(M=e.settings)!=null&&M.meshCoordinatorFor),I=n?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`flex items-center justify-between gap-3 ${I} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:p,type:"button","aria-label":"Back",children:s.jsx(Il,{size:18})}),s.jsxs("div",{className:"min-w-0 flex-1 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:kt(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(dA,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>m(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[N&&x&&s.jsx(eh,{mode:x,onChange:S,compact:!0}),N&&h&&s.jsx("button",{onClick:()=>{h(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(Dt,{size:14})}),A&&k&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>k(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(cs,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",children:s.jsx(Rl,{size:14})}),!t&&!N&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",children:s.jsx(us,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(pc,{activeConv:e,clearToken:0,isCliTerminal:T,ideEntry:a,terminalRef:j,handleModalButton:v,handleRelaunch:y,handleSendChat:b,handleForceSendChat:w,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:C,isFocusingAgent:d,actionLogs:r,userName:o})})]})}const ri={unix:{cmd:"curl -fsSL https://adhf.dev/install | sh",shell:"Terminal",prompt:"$ "},powershell:{cmd:"irm https://adhf.dev/install.ps1 | iex",shell:"PowerShell",prompt:"PS> "},cmd:{cmd:"curl -fsSL https://adhf.dev/install.cmd -o %TEMP%\\adhdev.cmd && %TEMP%\\adhdev.cmd",shell:"CMD",prompt:"> "}};function pA(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Fh(){const[e,t]=l.useState("unix"),[n,a]=l.useState("powershell"),[r,o]=l.useState(!1),i=e==="unix"?"unix":n;l.useEffect(()=>{t(pA())},[]);const c=l.useCallback(()=>{navigator.clipboard.writeText(ri[i].cmd).catch(()=>{}),o(!0),setTimeout(()=>o(!1),2e3)},[i]);return s.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("unix"),children:"macOS / Linux"}),s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("windows"),children:"Windows"})]}),e==="windows"&&s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${n==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>a("powershell"),children:"PowerShell"}),s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${n==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>a("cmd"),children:">_ CMD"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:c,title:"Click to copy",children:[s.jsx("span",{className:"text-text-muted select-none",children:ri[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:ri[i].cmd}),s.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:r?s.jsx(lo,{size:12}):s.jsx(Ll,{size:12})})]}),s.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",s.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function Bh({section:e,onSectionChange:t}){const{t:n}=ke("common"),a=[{key:"machines",label:n("nav.machines"),icon:us},{key:"chats",label:n("nav.chats"),icon:Ds}];return s.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:s.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:a.map(({key:r,label:o,icon:i})=>{const c=e===r;return s.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${c?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>t(r),type:"button","aria-pressed":c,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${c?"text-accent-primary":"bg-transparent text-current"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:s.jsx(i,{size:15})}),s.jsx("span",{children:o})]},r)})})})}function dr({title:e,className:t=""}){return s.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${t}`,children:s.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function Fn({children:e,className:t=""}){return s.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${t}`,children:e})}function mn({icon:e,title:t,subtitle:n,children:a}){return s.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[s.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),s.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:t}),s.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:n}),a]})}function mA({conversation:e,onCancel:t,onConfirm:n}){const{t:a}=ke(),r=kt(e);return s.jsx(Vt,{children: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:t,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"mobile-hide-confirm-title",className:"card fade-in mobile-compact-dialog relative w-full sm:w-[min(92vw,420px)] md:w-[92%] md:max-w-[420px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-bg-primary",children:[s.jsx("h3",{id:"mobile-hide-confirm-title",className:"m-0 text-base md:text-lg font-extrabold",children:a("mobileInbox.hideTitle",{title:r})}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:a("mobileInbox.hideDescription")})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[s.jsx("button",{onClick:n,className:"btn btn-primary w-full justify-center min-h-[42px]",children:a("mobileInbox.hide")}),s.jsx("button",{onClick:t,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:a("common.cancel")})]})]})]})})}function ur({item:e,type:t,getAvatarText:n,onOpenConversation:a,onRequestHideConversation:r,onRequestStopCli:o,onOpenMeshGraph:i,onCollectChatDebugBundle:c,isMuted:d,onToggleMute:p}){const{t:u}=ke(),m=t==="needs_attention"||t==="task_complete",f=t==="working",g=t==="earlier",k=t==="task_complete",{isReconnecting:h,isConnecting:x}=Rn(e.conversation),S=kt(e.conversation),b=sa(e.conversation),w=Qm(e.conversation,{requiresAction:t==="needs_attention"}),C=m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":f?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":g?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",v=m?"bg-accent-primary shadow-glow":f?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":g?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",y=g?"text-text-secondary":"text-text-primary",j=g?"text-text-muted":"text-text-secondary",N=g?"text-text-secondary opacity-80":"text-text-muted",T=g?"text-text-muted opacity-80":"text-text-muted",A=!f&&!k,I=Vm(e.conversation),D="text-[color:var(--status-warning)]",M=E=>{if(!c)return;E.preventDefault(),E.stopPropagation();const P=c==null?void 0:c(e.conversation);Promise.resolve(P).catch(B=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",B)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${C}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[m||f?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${v}`,style:m?{color:"var(--accent-on-primary)"}:void 0,children:n(S)}),I&&i&&s.jsx("button",{type:"button",className:"mobile-inbox-mesh-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:E=>{E.preventDefault(),E.stopPropagation(),i(e.conversation)},"aria-label":u("mobileInbox.openMeshGraphFor",{title:S}),title:u("mobileInbox.openLiveMeshGraph"),children:s.jsx(cs,{size:13})})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>a(e.conversation),onContextMenu:M,type:"button",children:[s.jsx("div",{className:"flex items-center gap-2 pr-[124px]",children:s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${y}`,children:S})}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${j}`,children:[s.jsx("span",{className:"truncate",children:b}),s.jsx(Gr,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),h?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${D} animate-pulse`,children:u("mobileInbox.reconnectingItem")})]}):x?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:u("mobileInbox.connectingItem")})]}):w==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:D,children:u("mobileInbox.actionNeeded")})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${N}`,children:e.preview})]}),s.jsxs("div",{className:"mobile-inbox-corner-actions absolute top-3 right-3 flex items-center gap-1.5",children:[A&&s.jsx("span",{className:`mr-0.5 text-[11px] font-medium shrink-0 ${T}`,children:Kp(e.timestamp)}),k&&s.jsx("span",{className:"rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:u("mobileInbox.done")}),p&&s.jsx("button",{type:"button",className:`mobile-inbox-mute-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border transition-colors ${d?"border-amber-500/60 bg-amber-500 text-white hover:bg-amber-600":"border-border-subtle bg-bg-primary/70 text-text-muted hover:border-border-default hover:text-text-primary"}`,onClick:E=>{E.preventDefault(),E.stopPropagation(),p()},"aria-label":d?u("mobileInbox.unmute",{title:S}):u("mobileInbox.mute",{title:S}),title:u(d?"mobileInbox.mutedTitle":"mobileInbox.muteNotifications"),children:d?s.jsx(Np,{size:13}):s.jsx(ia,{size:13})}),r&&s.jsx("button",{type:"button",className:"mobile-inbox-hide-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:E=>{E.preventDefault(),E.stopPropagation(),r()},"aria-label":u("mobileInbox.hideConversationAria",{title:S}),title:u("mobileInbox.hideConversationTitle"),children:s.jsx(po,{size:13})}),o&&s.jsx("button",{type:"button",className:"mobile-inbox-stop-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-status-error/30 bg-bg-primary/70 text-status-error transition-colors hover:border-status-error/60 hover:bg-status-error/10",onClick:E=>{E.preventDefault(),E.stopPropagation(),o()},"aria-label":u("mobileInbox.stopSessionAria",{title:S}),title:u("mobileInbox.stopSessionTitle"),children:s.jsx(Dt,{size:13})})]})]})},e.conversation.tabKey)}function su({count:e,label:t}){return e<=0?null:s.jsxs("span",{className:"inline-flex items-center gap-1.5 text-accent-primary","aria-live":"polite",children:[s.jsxs("span",{className:"relative flex h-2 w-2 shrink-0",children:[s.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-accent-primary/60"}),s.jsx("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-accent-primary"})]}),s.jsx("span",{className:"font-semibold",children:t})]})}function hA({section:e,attentionItems:t,unreadItems:n,workingItems:a,completedItems:r,hiddenConversations:o,machineCards:i,getAvatarText:c,actionLogs:d,sendDaemonCommand:p,onOpenConversation:u,onShowAllHidden:m,onHideConversation:f,onOpenMeshGraph:g,onStopCli:k,onOpenNewSession:h,onOpenMachine:x,onOpenSettings:S,onSectionChange:b,wsStatus:w="connected",initialDataLoaded:C=!0,conversationsLoaded:v,isStandalone:y=!1,onCollectChatDebugBundle:j,isConversationMuted:N,onToggleMuteConversation:T}){const{t:A}=ke(),[I,D]=l.useState(null),M=w==="disconnected"||w==="reconnecting"||w==="offline"||w==="auth_failed",E=!M&&!C,P=!M&&!(v??C),B=i.length>0,R=t.length>0||n.length>0||a.length>0||r.length>0,W=A(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),_=y?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",H=y?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",L=l.useCallback(async K=>{const z=wn(K);if(!z)return;const ne=Array.isArray(K.messages)?K.messages:[],ie=Pm({activeConv:K,visibleMessages:ne,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:ne.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),Ce=await p(z,"get_chat_debug_bundle",{...yn(K),delivery:"daemon_file",frontendSnapshot:ie}),me=Ma(Ce),O=Lm(me),Y=await Im(O);Y==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),ft.showToast(Dm(me,{locatorCopyStatus:Y}),Y==="failed"?"warning":"success")},[d,p]),F=j||L,$=l.useCallback(()=>{I&&(f==null||f(I),D(null))},[I,f]);return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${_}`,children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:W}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||n.length>0)&&s.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[s.jsx(ia,{size:13}),s.jsx("span",{children:t.length+n.length})]}),s.jsx("button",{onClick:S,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:s.jsx(Oa,{size:18})})]})]})}),s.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${H}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:M?s.jsx(mn,{icon:s.jsx(ls,{size:32}),title:A(w==="offline"?"mobileInbox.networkOffline":w==="auth_failed"?"mobileInbox.sessionExpired":"mobileInbox.reconnecting"),subtitle:A(w==="offline"?"mobileInbox.waitingForNetwork":w==="auth_failed"?"mobileInbox.pleaseLogInAgain":"mobileInbox.restoringConnection")}):E?s.jsx(mn,{icon:s.jsx(ls,{size:32}),title:A("mobileInbox.loading"),subtitle:A("mobileInbox.loadingSubtitle")}):i.length===0?s.jsx(mn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:A(y?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:A(y?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!y&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(Fh,{})})}):s.jsx(Fn,{children:i.map((K,z)=>s.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${z>0?"border-t border-border-subtle/70":""}`,onClick:()=>x(K.id),type:"button",children:[s.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:c(K.label)}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:K.label}),s.jsxs("span",{className:"flex items-center gap-2 text-[11px] font-medium text-text-muted shrink-0",children:[s.jsx(su,{count:K.generatingCount,label:A("mobileInbox.generatingCount",{count:K.generatingCount})}),K.unread>0?s.jsx("span",{className:"text-accent-primary",children:A("mobileInbox.newCount",{count:K.unread})}):K.total>0?A("mobileInbox.chatCount",{count:K.total}):A("mobileInbox.idle")]})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:K.subtitle}),K.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[A("mobileInbox.chatCount",{count:K.total}),K.unread>0?A("mobileInbox.unreadSuffix",{count:K.unread}):"",K.generatingCount>0?A("mobileInbox.collapsedGeneratingSuffix",{count:K.generatingCount}):""]}):K.generatingCount>0?s.jsx("div",{className:"text-[13px] text-accent-primary mt-0.5 font-medium",children:A("mobileInbox.generatingCount",{count:K.generatingCount})}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:A("mobileInbox.noActiveChats")})]})]},K.id))})}),e==="chats"&&t.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(dr,{title:A("mobileInbox.needsAttention"),className:"mb-0"}),s.jsx(Fn,{children:t.map((K,z)=>s.jsx("div",{className:z>0?"border-t border-border-subtle/70":"",children:s.jsx(ur,{item:K,type:"needs_attention",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>D(K.conversation):void 0,onRequestStopCli:k?()=>k(K.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:F,isMuted:N==null?void 0:N(K.conversation),onToggleMute:T?()=>T(K.conversation):void 0})},K.conversation.tabKey))})]}),e==="chats"&&n.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(dr,{title:A("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),s.jsx(Fn,{children:n.map((K,z)=>s.jsx("div",{className:z>0?"border-t border-border-subtle/70":"",children:s.jsx(ur,{item:K,type:"task_complete",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>D(K.conversation):void 0,onRequestStopCli:k?()=>k(K.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:F,isMuted:N==null?void 0:N(K.conversation),onToggleMute:T?()=>T(K.conversation):void 0})},K.conversation.tabKey))})]}),e==="chats"&&a.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(dr,{title:A("mobileInbox.workingNow"),className:"mb-0 mt-2"}),s.jsx(Fn,{children:a.map((K,z)=>s.jsx("div",{className:z>0?"border-t border-border-subtle/70":"",children:s.jsx(ur,{item:K,type:"working",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>D(K.conversation):void 0,onRequestStopCli:k?()=>k(K.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:F,isMuted:N==null?void 0:N(K.conversation),onToggleMute:T?()=>T(K.conversation):void 0})},K.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[r.length>0&&s.jsx(dr,{title:A("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),r.length>0?s.jsx(Fn,{children:r.map((K,z)=>s.jsx("div",{className:z>0?"border-t border-border-subtle/70":"",children:s.jsx(ur,{item:K,type:"earlier",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>D(K.conversation):void 0,onRequestStopCli:k?()=>k(K.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:F,isMuted:N==null?void 0:N(K.conversation),onToggleMute:T?()=>T(K.conversation):void 0})},K.conversation.tabKey))}):R?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:A("mobileInbox.allCaughtUp")}):M?s.jsx(mn,{icon:s.jsx(ls,{size:28}),title:A("mobileInbox.connecting"),subtitle:A("mobileInbox.connectingSubtitle")}):P?s.jsx(mn,{icon:s.jsx(ls,{size:28}),title:A("mobileInbox.loading"),subtitle:A("mobileInbox.loadingSubtitle")}):B?s.jsx(mn,{icon:s.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:s.jsx(Ds,{size:20})}),title:A("mobileInbox.noConversations"),subtitle:A("paneGroup.newSessionDescription"),children:h&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:h,"aria-label":A("paneGroup.newSession"),title:A("paneGroup.newSession"),children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",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"})]}),s.jsx("span",{children:A("paneGroup.newSession")})]})}):s.jsx(mn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:A("mobileInbox.noMachinesConnected"),subtitle:A("mobileInbox.noMachinesSubtitle")})]}),e==="chats"&&o.length>0&&(()=>{const K=Nx(o);return s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(Fn,{className:"mt-4 border-dashed bg-bg-secondary/20",children:s.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:A("mobileInbox.hiddenTabs")}),s.jsx(su,{count:K,label:A("mobileInbox.generatingCount",{count:K})})]}),s.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[A("mobileInbox.collapsedCount",{count:o.length}),K>0?A("mobileInbox.collapsedGeneratingSuffix",{count:K}):""]})]}),s.jsx("button",{type:"button",className:"shrink-0 rounded-full border border-border-subtle bg-bg-primary/70 px-3 py-1.5 text-[12px] font-semibold text-accent-primary hover:border-border-default",onClick:m,children:A("mobileInbox.restoreAll")})]})})})})()]}),e==="chats"&&h&&R&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:h,"aria-label":A("paneGroup.newSession"),title:A("paneGroup.newSession"),children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",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"})]})}),I&&s.jsx(mA,{conversation:I,onCancel:()=>D(null),onConfirm:$}),s.jsx(Bh,{section:e,onSectionChange:b})]})}function fA(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 Wh(e){const t=[e.workspace||"Workspace unknown"],n=Tn(e.summaryMetadata);n&&t.push(n),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const a=fA(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:a?`Updated ${a}`:"",preview:(e.preview||"").trim()}}function mc({title:e,description:t,currentPath:n,directories:a,busy:r=!1,error:o="",confirmLabel:i="Use this folder",onClose:c,onNavigate:d,onConfirm:p}){const[u,m]=l.useState(n),{t:f}=ke("common");l.useEffect(()=>{m(n)},[n]);const g=qN(n),k=u.trim();return s.jsx(Vt,{children:s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] 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",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:s.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:c,"aria-label":"Close folder browser",children:s.jsx(Dt,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!g||r||d(g)},disabled:!g||r,children:[s.jsx(Il,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:f("machine.workspaceBrowse.currentFolder")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:u,onChange:h=>m(h.target.value),onKeyDown:h=>{h.key!=="Enter"||!k||r||(h.preventDefault(),d(k))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!k||r||d(k)},disabled:!k||r,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:r?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):o?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:o}):a.length===0?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):s.jsx("div",{className:"p-3",children:a.map(h=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>d(h.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(An,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:h.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:h.path})]})]},h.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:c,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>p(k||n),disabled:!k&&!n||r,children:i})]})]})})})}function jo({title:e,description:t,details:n,workspaceOptions:a,selectedWorkspaceKey:r,onWorkspaceChange:o,confirmLabel:i,busyLabel:c,busy:d=!1,showArgsInput:p,argsValue:u,onArgsChange:m,showModelInput:f,modelValue:g,onModelChange:k,historyProviderNode:h,onConfirm:x,onCancel:S}){const{t:b}=ke("common"),w=i??b("machine.launchConfirm.launch"),C=c??b("machine.launchConfirm.launching"),v=a==null?void 0:a.find(j=>j.key===r),y=s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] 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",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:S,"aria-label":b("machine.launchConfirm.closeAria"),children:s.jsx(Dt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[a&&a.length>0&&o&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.workspace")}),s.jsx("select",{value:r||"",onChange:j=>o(j.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:d,children:a.map(j=>s.jsx("option",{value:j.key,children:j.label},j.key))}),(v==null?void 0:v.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:v.description})]}),h,n.map(j=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:j.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:j.value})]},`${j.label}:${j.value}`)),f&&k&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.languageModel")}),s.jsx("input",{type:"text",value:g||"",onChange:j=>k(j.target.value),placeholder:b("machine.launchConfirm.autoDetect"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]}),p&&m&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.cliArgs")}),s.jsx("input",{type:"text",value:u||"",onChange:j=>m(j.target.value),placeholder:b("machine.launchConfirm.cliArgsPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:S,disabled:d,children:b("machine.launchConfirm.cancel")}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:x,disabled:d,children:[s.jsx(jp,{size:14}),d?C:w]})]})]})});return typeof document>"u"?y:qs.createPortal(y,document.body)}function nu(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function Oh(e){const{machine:t,currentWorkspacePath:n,currentWorkspaceId:a,includeHome:r=!0,homeLabel:o="Home directory",homeDescription:i="Launch without a workspace"}=e,c=[];r&&c.push({key:"__home__",label:o,description:i,workspaceId:null,workspacePath:null});for(const u of t.workspaces||[])c.push({key:`saved:${u.id}`,label:`${u.id===t.defaultWorkspaceId?"⭐ ":""}${nu(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const d=(n==null?void 0:n.trim())||"",p=d?(t.workspaces||[]).find(u=>u.path===d):null;if(d&&!p&&c.push({key:`custom:${d}`,label:nu(d),description:d,workspaceId:null,workspacePath:d}),a){const u=`saved:${a}`;if(c.some(m=>m.key===u))return{options:c,selectedKey:u}}return p?{options:c,selectedKey:`saved:${p.id}`}:d?{options:c,selectedKey:`custom:${d}`}:{options:c,selectedKey:"__home__"}}function gA(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function bA(e){return[gA(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function xA(e){return e.lastLaunchedAt?qa(e.lastLaunchedAt):""}function Uh(e){return{metaText:bA(e),updatedLabel:xA(e)}}function oi(e,t,n){return e?"ide":t>0?"cli":n>0?"acp":null}function vA({selectedMachineEntry:e,cliProviders:t,acpProviders:n,machineAction:a,onBrowseDirectory:r,onListSavedSessions:o}){var Ie,We,Xe,et;const i=ca(),[c,d]=l.useState(!1),p=(((Ie=e.detectedIdes)==null?void 0:Ie.length)||0)>0,u=l.useMemo(()=>(e.workspaces||[]).map(J=>({id:J.id,path:J.path,label:J.label})),[e]),m=e.defaultWorkspaceId||null,[f,g]=l.useState(m||((We=u[0])==null?void 0:We.id)||""),[k,h]=l.useState(""),[x,S]=l.useState(""),[b,w]=l.useState([]),[C,v]=l.useState(!1),[y,j]=l.useState(""),[N,T]=l.useState(!1),[A,I]=l.useState(oi(p,t.length,n.length)),D=l.useRef(null),[M,E]=l.useState(null),P=l.useRef("__home__"),[B,R]=l.useState("__home__"),[W,_]=l.useState(""),[H,L]=l.useState(""),[F,$]=l.useState(""),[K,z]=l.useState([]),[ne,ie]=l.useState(()=>qt().textQuery),[Ce,me]=l.useState(()=>qt().workspaceQuery),[O,Y]=l.useState(()=>qt().modelQuery),[X,Q]=l.useState(()=>qt().resumableOnly),[ve,he]=l.useState(()=>qt().sortMode),[Z,fe]=l.useState(!1),[V,q]=l.useState(!1),ee=l.useRef(null),pe=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const le=f==="__custom__"?k.trim():((Xe=u.find(J=>J.id===f))==null?void 0:Xe.path)||"",se=f==="__custom__"&&!!le&&a.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(a.message),te=f!=="__custom__"&&((et=u.find(J=>J.id===f))==null?void 0:et.path)||"",ue=l.useMemo(()=>(e.recentLaunches||[]).map(J=>J.workspace),[e]),ye=l.useCallback(async J=>{v(!0),j("");try{const Le=await r(J);S(Le.path),h(Le.path),w(Le.directories)}catch(Le){j(Le instanceof Error?Le.message:"Could not load folder")}finally{v(!1)}},[r]),Me=l.useCallback(()=>{var Le;g("__custom__"),T(!0);const J=dc(e.platform,cc(k.trim(),te,ue,e.defaultWorkspacePath,(Le=u.find($e=>$e.id===m))==null?void 0:Le.path,u.map($e=>$e.path)));ye(J)},[k,m,ye,ue,te,e.platform,u]),re=l.useCallback(J=>{if(J!=null&&J.workspaceId){g(J.workspaceId),h("");return}if(J!=null&&J.workspacePath){g("__custom__"),h(J.workspacePath);return}g(""),h("")},[]),ce=l.useCallback(J=>{if(g(J),J==="__custom__"){Me();return}h("")},[Me]),Ae=l.useCallback(J=>{g("__custom__"),h(J)},[]),be=l.useCallback((J,Le)=>{D.current=Le,P.current=J.selectedWorkspaceKey||"__home__",R(J.selectedWorkspaceKey||"__home__"),_(J.initialArgs||""),L(J.initialModel||""),$(""),z([]);const $e=J.providerType?`${e.id}:${J.providerType}`:null;if(yj(pe.current,$e)){const at=qt();ie(at.textQuery),me(at.workspaceQuery),Y(at.modelQuery),Q(at.resumableOnly),he(at.sortMode)}pe.current=$e,E(J),J.providerType&&o&&(fe(!0),o(J.providerType).then(at=>z(at||[])).catch(at=>console.warn("Failed to load saved sessions",at)).finally(()=>fe(!1)))},[o,e.id]),we=l.useMemo(()=>th(K,{textQuery:ne,workspaceQuery:Ce,modelQuery:O,resumableOnly:X,sortMode:ve}),[O,X,K,ve,ne,Ce]);l.useEffect(()=>{F&&(we.some(J=>J.providerSessionId===F)||$(""))},[we,F]);const _e=l.useCallback(()=>{D.current&&(q(!0),D.current().finally(()=>{D.current=null,q(!1),E(null)}))},[]),U=l.useCallback(()=>{D.current=null,E(null)},[]),Ne=l.useCallback(J=>{P.current=J,R(J)},[]);return l.useEffect(()=>{var J;ee.current!==e.id&&(ee.current=e.id,g(m||((J=u[0])==null?void 0:J.id)||"__custom__"),h(""),S(""),w([]),j(""),T(!1),ie(qt().textQuery),me(qt().workspaceQuery),Y(qt().modelQuery),Q(qt().resumableOnly),he(qt().sortMode),pe.current=null,I(oi(p,t.length,n.length)))},[n.length,t.length,m,p,e.id,u]),l.useEffect(()=>{var J;f!=="__custom__"&&(f&&u.some(Le=>Le.id===f)||g(m||((J=u[0])==null?void 0:J.id)||"__custom__"))},[m,f,u]),l.useEffect(()=>{A==="ide"&&p||A==="cli"&&t.length>0||A==="acp"&&n.length>0||I(oi(p,t.length,n.length))},[A,n.length,t.length,p]),{showAllRecent:c,setShowAllRecent:d,hasIdeOptions:p,workspaceRows:u,defaultWorkspaceId:m,workspaceChoice:f,customWorkspacePath:k,browseCurrentPath:x,browseDirectories:b,browseBusy:C,browseError:y,browseDialogOpen:N,activeLauncherKind:A,launchConfirm:M,launchConfirmWorkspaceKeyRef:P,launchConfirmWorkspaceKey:B,launchConfirmArgs:W,launchConfirmModel:H,launchConfirmResumeId:F,launchConfirmSavedSessions:K,launchConfirmTextFilter:ne,launchConfirmWorkspaceFilter:Ce,launchConfirmModelFilter:O,launchConfirmResumableOnly:X,launchConfirmSortMode:ve,filteredLaunchConfirmSavedSessions:we,launchConfirmSessionsLoading:Z,launchConfirmBusy:V,resolvedWorkspacePath:le,canCreateMissingWorkspace:se,openBrowseDialog:Me,loadBrowsePath:ye,handleWorkspaceChoiceChange:ce,chooseCustomWorkspacePath:Ae,setCustomWorkspacePath:h,setBrowseDialogOpen:T,setActiveLauncherKind:I,openLaunchConfirm:be,handleConfirmLaunch:_e,closeLaunchConfirm:U,setWorkspaceSelectionFromOption:re,setLaunchConfirmWorkspaceKeyAndSync:Ne,setLaunchConfirmArgs:_,setLaunchConfirmModel:L,setLaunchConfirmResumeId:$,setLaunchConfirmTextFilter:ie,setLaunchConfirmWorkspaceFilter:me,setLaunchConfirmModelFilter:Y,setLaunchConfirmResumableOnly:Q,setLaunchConfirmSortMode:he}}function yA({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:n,cliProviders:a,acpProviders:r,selectedMachineNeedsUpgrade:o,appVersion:i,machineAction:c,isStandalone:d,section:p,showBottomNav:u,onBack:m,onSectionChange:f,onOpenConversation:g,onOpenRecent:k,onOpenMachineDetails:h,onMachineUpgrade:x,onLaunchDetectedIde:S,onAddWorkspace:b,onBrowseDirectory:w,onLaunchWorkspaceProvider:C,onListSavedSessions:v}){const{t:y}=ke("common"),j=R=>R==="ide"?"IDE":R==="cli"?"CLI":"ACP",N=n.slice(0,4),T=t.slice(0,3),A=vA({selectedMachineEntry:e,cliProviders:a,acpProviders:r,machineAction:c,onBrowseDirectory:w,onListSavedSessions:v}),I=l.useMemo(()=>N.map(R=>{const{metaText:W,updatedLabel:_}=Uh(R);return{key:`recent-launch:${R.id}`,primary:R.label,secondary:W,updatedLabel:_,onClick:()=>{const{options:H,selectedKey:L}=Oh({machine:{workspaces:A.workspaceRows,defaultWorkspaceId:A.defaultWorkspaceId},currentWorkspacePath:R.workspace,homeLabel:y("newSession.homeDirectory"),homeDescription:y("newSession.launchWithoutWorkspace")});A.openLaunchConfirm({title:R.kind==="ide"?qr(y,"restart-ide",R.label):R.providerSessionId?nh(y,R.label):qr(y,"start-fresh",R.label),description:R.kind==="ide"?zr(y,"restart-ide"):R.providerSessionId?ah(y):zr(y,"start-fresh"),confirmLabel:R.kind==="ide"?Kr(y,"restart-ide"):R.providerSessionId?rl(y,!0):Kr(y,"start-fresh"),busyLabel:R.kind==="ide"?Vr(y,"restart-ide"):R.providerSessionId?sh(y,!0):Vr(y,"start-fresh"),workspaceOptions:H,selectedWorkspaceKey:L,details:[{label:"Mode",value:j(R.kind)},...R.providerType?[{label:"Provider",value:R.providerType}]:[]]},async()=>{const F=H.find($=>$.key===A.launchConfirmWorkspaceKeyRef.current);A.setWorkspaceSelectionFromOption(F),await k({...R,workspace:(F==null?void 0:F.workspacePath)??null})})}}}),[A,k,N,y]),D=l.useMemo(()=>T.map(R=>({key:`recent-chat:${R.conversation.tabKey}`,primary:kt(R.conversation),secondary:qC(R.conversation,{timestampLabel:R.timestamp?Kp(R.timestamp):null}),unread:R.unread,onClick:()=>g(R.conversation)})),[g,T]),M=A.showAllRecent?I:I.slice(0,4),E=I.length>0,P=D.length>0,B=d?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${B} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:m,type:"button","aria-label":"Back",children:s.jsx(Il,{size:18})}),s.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:ds(e,{fallbackId:e.id})}),s.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[P&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:D.map(R=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${R.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:R.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:R.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:R.secondary})]},R.key))})]}),E&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:M.map(R=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:R.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:R.primary}),R.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:R.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:R.secondary})]},R.key))}),I.length>4&&s.jsx("div",{className:"flex justify-center px-4 pt-2",children:s.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>A.setShowAllRecent(R=>!R),children:A.showAllRecent?"Show fewer":`Show ${I.length-4} more`})})]}),!1,s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[o&&s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:x,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",i]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:h,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),A.browseDialogOpen&&s.jsx(mc,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:A.browseCurrentPath,directories:A.browseDirectories,busy:A.browseBusy,error:A.browseError,confirmLabel:"Use this folder",onClose:()=>A.setBrowseDialogOpen(!1),onNavigate:R=>{A.loadBrowsePath(R)},onConfirm:R=>{A.chooseCustomWorkspacePath(R),A.setBrowseDialogOpen(!1)}}),A.launchConfirm&&s.jsx(jo,{title:A.launchConfirm.title,description:A.launchConfirm.description,details:A.launchConfirm.details,workspaceOptions:A.launchConfirm.workspaceOptions,selectedWorkspaceKey:A.launchConfirmWorkspaceKey,onWorkspaceChange:A.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:A.launchConfirm.providerType?rl(y,!!A.launchConfirmResumeId):A.launchConfirm.confirmLabel,busyLabel:A.launchConfirm.providerType?void 0:A.launchConfirm.busyLabel,busy:A.launchConfirmBusy,showArgsInput:A.launchConfirm.showArgsInput,argsValue:A.launchConfirmArgs,onArgsChange:A.setLaunchConfirmArgs,showModelInput:A.launchConfirm.showModelInput,modelValue:A.launchConfirmModel,onModelChange:A.setLaunchConfirmModel,historyProviderNode:A.launchConfirm.providerType&&(A.launchConfirmSessionsLoading||A.launchConfirmSavedSessions.length>0)&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),A.launchConfirmSessionsLoading&&s.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:sc(y)}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:A.launchConfirmTextFilter,onChange:R=>A.setLaunchConfirmTextFilter(R.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:A.launchConfirmBusy||A.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:A.launchConfirmWorkspaceFilter,onChange:R=>A.setLaunchConfirmWorkspaceFilter(R.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:A.launchConfirmBusy||A.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:A.launchConfirmModelFilter,onChange:R=>A.setLaunchConfirmModelFilter(R.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:A.launchConfirmBusy||A.launchConfirmSessionsLoading}),s.jsxs("select",{value:A.launchConfirmSortMode,onChange:R=>A.setLaunchConfirmSortMode(R.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:A.launchConfirmBusy||A.launchConfirmSessionsLoading,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:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:A.launchConfirmResumableOnly,onChange:R=>A.setLaunchConfirmResumableOnly(R.target.checked),disabled:A.launchConfirmBusy||A.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:A.launchConfirmResumeId,onChange:R=>A.setLaunchConfirmResumeId(R.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:A.launchConfirmBusy||A.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:Sj(y)}),A.filteredLaunchConfirmSavedSessions.map(R=>s.jsxs("option",{value:R.providerSessionId,disabled:!R.canResume,children:[R.title||R.providerSessionId," ",R.canResume?"":"(workspace missing)"]},R.providerSessionId))]}),!A.launchConfirmSessionsLoading&&A.launchConfirmSavedSessions.length>0&&A.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),A.launchConfirmResumeId&&(()=>{const R=A.filteredLaunchConfirmSavedSessions.find(_=>_.providerSessionId===A.launchConfirmResumeId);if(!R)return null;const W=Wh(R);return s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:W.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:W.providerSessionId}),s.jsx("div",{className:"mt-1",children:W.metaLine}),W.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:W.updatedLabel}),W.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:W.preview})]})})()]}),onConfirm:A.handleConfirmLaunch,onCancel:A.closeLaunchConfirm}),u&&s.jsx(Bh,{section:p,onSectionChange:f})]})}const au=8e3;function wA(e){const t=e&&typeof e=="object"&&"result"in e?e.result:e,n=t&&typeof t=="object",a=n&&t.success===!1,r=n&&t.mirrorStale===!0;return!a&&!r?{confirmed:!0}:{confirmed:!1,reason:a&&typeof t.error=="string"?t.error:r?"the coordinator did not confirm the change":"command was rejected"}}function Gh(e,t,n){const a=l.useRef(new Map),[,r]=l.useState(0),o=l.useCallback(()=>r(g=>g+1),[]);l.useEffect(()=>{const g=a.current;if(g.size===0)return;const k=Date.now();let h=!1;for(const[x,S]of g){const b=e.get(x),w=S.muted===void 0||(b?b.muted===S.muted:!1),C=S.hidden===void 0||(b?b.surfaceHidden===S.hidden:!1),v=k-S.at>au;(w&&C||v)&&(g.delete(x),h=!0)}h&&o()},[e,o]),l.useEffect(()=>{if(a.current.size===0)return;const g=setInterval(()=>{const k=a.current,h=Date.now();let x=!1;for(const[S,b]of k)h-b.at>au&&(k.delete(S),x=!0);x&&o(),k.size===0&&clearInterval(g)},1e3);return()=>clearInterval(g)});const i=l.useCallback((g,k)=>{const h=a.current.get(g);a.current.set(g,{...h,...k,at:Date.now()}),o()},[o]),c=l.useCallback(g=>{const k=g.sessionId,h=k?a.current.get(k):void 0;return(h==null?void 0:h.muted)!==void 0?h.muted:an(g,e).muted??!1},[e]),d=l.useCallback(g=>{const k=g.sessionId,h=k?a.current.get(k):void 0;return(h==null?void 0:h.hidden)!==void 0?h.hidden:an(g,e).surfaceHidden??!1},[e]),p=l.useCallback((g,k)=>{const h=Ks(g),x=g.sessionId;!h||!x||(i(x,k),t(h,"set_conversation_prefs",{sessionId:x,...k,...yo(g)}).then(S=>{const b=wA(S);b.confirmed||(console.warn("[conversation-prefs] set_conversation_prefs not confirmed",b.reason),a.current.delete(x),o(),n==null||n(`Couldn't update conversation — ${b.reason}`))}).catch(S=>{console.warn("[conversation-prefs] set_conversation_prefs failed",S),a.current.delete(x),o();const b=S instanceof Error?S.message:String(S??"the daemon is unreachable");n==null||n(`Couldn't update conversation — ${b}`)}))},[t,i,o,n]),u=l.useCallback(g=>{p(g,{muted:!c(g)})},[p,c]),m=l.useCallback((g,k)=>{p(g,{hidden:k})},[p]),f=l.useCallback(g=>{p(g,{hidden:!d(g)})},[p,d]);return{isMuted:c,isHidden:d,toggleMute:u,setHidden:m,toggleHidden:f}}function Dr(e){return[...e].sort((t,n)=>{const a=n.timestamp-t.timestamp;return a!==0?a:t.conversation.tabKey.localeCompare(n.conversation.tabKey)})}function kA(e,t=[]){const n=new Map(e.map(r=>[r.conversation.tabKey,r])),a=t.map(r=>n.get(r)).filter(r=>!!r);return a.length===e.length?a:Dr(e)}function SA(e,t=[]){const n=e.filter(i=>i.requiresAction),a=e.filter(i=>i.unread&&!i.requiresAction),r=e.filter(i=>!i.unread&&!i.requiresAction&&i.isWorking),o=e.filter(i=>!i.unread&&!i.requiresAction&&!i.isWorking);return{attentionItems:Dr(n),unreadItems:Dr(a),workingItems:kA(r,t),completedItems:Dr(o)}}function No(e,t){if(!t)return!1;const n=e.filter(a=>a.type==="adhdev-daemon"&&qh(a)==="Connected");return n.length===0?!0:n.every(a=>a._sessionListAuthoritative===!0)}function qh(e){var a,r,o;const t=((a=e.p2p)==null?void 0:a.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":!(!!((r=e.p2p)!=null&&r.available)||!!((o=e.p2p)!=null&&o.state))&&e.status&&e.status!=="offline"?"Connected":"Offline"}function CA(e,t){if(!e)return[];const n=e.recentLaunches||[];return n.length>0?n.map(a=>({id:a.id,label:a.title||a.providerName||a.providerType,kind:a.kind,providerType:a.providerType,providerSessionId:a.providerSessionId,subtitle:Tn(a.summaryMetadata)||a.workspace||void 0,workspace:a.workspace,summaryMetadata:a.summaryMetadata})):t.filter(a=>a.type!=="adhdev-daemon"&&a.daemonId===e.id).map(a=>{var i;const r=$a(a)?"cli":Jn(a)?"acp":"ide",o=Tn(a.summaryMetadata);return{id:`${r}:${a.type}:${a.workspace||""}`,label:((i=a.activeChat)==null?void 0:i.title)||($a(a)?a.cliName||a.type:Jn(a)&&a.cliName||a.type),kind:r,providerType:a.type,providerSessionId:a.providerSessionId,subtitle:Jn(a)?o||a.workspace||void 0:a.workspace||void 0,workspace:a.workspace||void 0,timestamp:a.lastMessageAt||0}}).sort((a,r)=>r.timestamp-a.timestamp).map(({timestamp:a,...r})=>r)}function jA(e,t,n=[]){const a=new Map;for(const o of t){const i=Ks(o.conversation),c=a.get(i);c?c.push(o):a.set(i,[o])}const r=new Map;for(const o of n){const i=Ks(o),c=r.get(i);c?c.push(o):r.set(i,[o])}return e.map(o=>{const i=a.get(o.id)||[],c=r.get(o.id)||[],d=[...i].sort((h,x)=>x.timestamp-h.timestamp)[0]||null,p=(d==null?void 0:d.conversation)||null,u=Xi(o),m=i.filter(h=>h.unread||h.requiresAction).length,f=i.filter(h=>_a(h.conversation)).length+c.filter(_a).length,g=qh(o),k=[o.platform||"machine",g].filter(Boolean);return{id:o.id,label:ds(o,{fallbackId:o.id}),subtitle:k.join(" · "),unread:m,total:i.length,generatingCount:f,latestConversation:p,latestTimestamp:(d==null?void 0:d.timestamp)||0,fallbackActivityAt:u,preview:p?zC(p,Om(p)):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((o,i)=>{const c=o.latestTimestamp||o.fallbackActivityAt||0,d=i.latestTimestamp||i.fallbackActivityAt||0;return d!==c?d-c:o.label.localeCompare(i.label)})}function NA(e){return e==="chat"}function pr(e,t){var n;if(!(typeof window>"u"))try{if(!(!!((n=import.meta.env)!=null&&n.DEV)||window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[mobile-read] ${e}`,t)}catch{}}function AA({conversations:e,machineEntries:t,items:n,selectedConversation:a,selectedTabKey:r,screen:o,liveSessionInboxState:i,sendDaemonCommand:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,setSelectedTabKey:k,setScreen:h,setSelectedMachineId:x,setSection:S,setMachineBackTarget:b,resetMachineAction:w}){const C=l.useRef(null),v=l.useCallback(y=>{if(!(y!=null&&y.sessionId))return;const j=an(y,i),N=Math.max(Date.now(),jn(y),j.lastUpdated||0);pr("mark_read:start",{tabKey:y.tabKey,sessionId:y.sessionId,displayPrimary:kt(y),inboxBucket:j.inboxBucket,unread:j.unread,lastSeenAt:j.lastSeenAt,lastUpdated:j.lastUpdated,activityAt:jn(y),readAt:N}),c(Ks(y)||y.routeId,"mark_session_seen",{sessionId:y.sessionId,providerSessionId:y.providerSessionId,seenAt:N,completionMarker:j.completionMarker}).then(T=>{pr("mark_read:result",{tabKey:y.tabKey,sessionId:y.sessionId,result:T})}).catch(T=>{pr("mark_read:error",{tabKey:y.tabKey,sessionId:y.sessionId,error:T instanceof Error?T.message:String(T)})})},[i,c]);return l.useEffect(()=>{var j;if(!a){NA(o)&&h("inbox"),k(((j=e[0])==null?void 0:j.tabKey)||null),C.current=null;return}if(o!=="chat"){C.current=null;return}const y=`${a.tabKey}:${a.sessionId||""}`;C.current!==y&&(C.current=y,v(a))},[e,v,o,a,h,k]),l.useEffect(()=>{if(!d)return;const y=e.find(j=>j.tabKey===d);y&&(k(y.tabKey),h("chat"),p==null||p())},[e,p,d,h,k]),l.useEffect(()=>{if(!u)return;const y=t.find(j=>j.id===u);y&&(x(y.id),w(),S("machines"),b("inbox"),h("machine"),m==null||m())},[t,m,u,w,b,h,S,x]),l.useEffect(()=>{f&&(S(f),h("inbox"),g==null||g())},[g,f,h,S]),l.useEffect(()=>{const y=n.filter(j=>j.inboxBucket==="task_complete"||j.unread);y.length!==0&&pr("inbox_state",{screen:o,selectedTabKey:r,items:y.map(j=>{const N=an(j.conversation,i);return{liveState:N,tabKey:j.conversation.tabKey,sessionId:j.conversation.sessionId,displayPrimary:kt(j.conversation),serverBucket:N.inboxBucket,computedBucket:j.inboxBucket,serverUnread:N.unread,computedUnread:j.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:jn(j.conversation)}})})},[n,i,o,r]),{markConversationRead:v}}function TA(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function ru(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function MA(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function PA({sendDaemonCommand:e,navigate:t,ides:n,conversations:a}){const{launchCli:r}=ho(),[o,i]=l.useState("idle"),[c,d]=l.useState(""),[p,u]=l.useState(null),m=l.useCallback(()=>{i("idle"),d(""),u(null)},[]),f=l.useCallback(async(w,C,v)=>{var y;try{i("loading"),d(`Launching ${C}…`);const j={ideType:C,enableCdp:!0};(y=v==null?void 0:v.workspacePath)!=null&&y.trim()&&(j.workspace=v.workspacePath.trim()),await e(w,"launch_ide",j),i("done"),d(`${C} launch requested`)}catch(j){i("error"),d(j instanceof Error?j.message:"Launch IDE failed"),console.error("Launch IDE failed",j)}},[e]),g=l.useCallback(async(w,C,v)=>{if(C.trim())try{i("loading"),d(v!=null&&v.createIfMissing?"Creating folder…":"Saving workspace…");const y=await e(w,"workspace_add",{path:C.trim(),createIfMissing:(v==null?void 0:v.createIfMissing)===!0});if(y!=null&&y.success){i("done"),d(v!=null&&v.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),d((y==null?void 0:y.error)||"Could not save workspace")}catch(y){i("error"),d(y instanceof Error?y.message:"Could not save workspace")}},[e]),k=l.useCallback(async w=>{i("loading"),d("Starting daemon upgrade…");const C=n.find(y=>y.id===w||y.daemonId===w),v=await y1(e,w,C);i(v.state),d(v.message)},[n,e]),h=l.useCallback(async(w,C,v,y)=>{var T,A,I;const j=Date.now(),N={machineId:w,kind:C,providerType:v,workspaceId:(y==null?void 0:y.workspaceId)||null,workspacePath:(y==null?void 0:y.workspacePath)||null,resumeSessionId:(y==null?void 0:y.resumeSessionId)||null,startedAt:j};try{i("loading"),d(`Launching ${v}…`),u(N);const D={cliType:v};(T=y==null?void 0:y.workspacePath)!=null&&T.trim()?D.dir=y.workspacePath.trim():y!=null&&y.workspaceId?D.workspaceId=y.workspaceId:y!=null&&y.useHome&&(D.useHome=!0),y!=null&&y.resumeSessionId&&(D.resumeSessionId=y.resumeSessionId),(A=y==null?void 0:y.args)!=null&&A.trim()&&(D.cliArgs=y.args.trim().split(/\s+/).filter(Boolean)),(I=y==null?void 0:y.model)!=null&&I.trim()&&(D.initialModel=y.model.trim());const M=await r(w,D),E=(M==null?void 0:M.result)||M,P=(E==null?void 0:E.sessionId)||(E==null?void 0:E.id);if(M!=null&&M.success&&P){u(null),i("done"),d(`${v} launched`),t(Ba(P));return}if(M!=null&&M.success){i("loading"),d(`${v} launch requested — waiting for session…`);return}u(null),i("error"),d((M==null?void 0:M.error)||(E==null?void 0:E.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(D){if(MA(D)){i("loading"),d(`${v} launch requested — waiting for session…`);return}u(null),i("error"),d(D instanceof Error?D.message:`Could not launch ${C.toUpperCase()} workspace`)}},[t,e]),x=l.useCallback(async(w,C)=>{try{const v=await e(w,"list_saved_sessions",{providerType:C,kind:"cli",limit:30}),y=(v==null?void 0:v.result)??v;return Array.isArray(y==null?void 0:y.sessions)?y.sessions:[]}catch(v){return console.error("Failed to list saved sessions on mobile:",v),[]}},[e]),S=l.useCallback(async(w,C)=>uc(e,w,C),[e]);l.useEffect(()=>{if(!p)return;const w=ru(p.workspacePath),C=n.find(y=>{var D,M,E,P;if(!y||y.type==="adhdev-daemon"||TA(y.daemonId||y.id)!==p.machineId||(y.transport==="acp"?"acp":y.transport==="pty"?"cli":null)!==p.kind||String(y.agentType||y.type||"")!==p.providerType)return!1;const A=String(y.providerSessionId||"");if(p.resumeSessionId&&A)return A===p.resumeSessionId;if(w){const B=ru(y.workspace||y.runtimeWorkspaceLabel);return B?B===w:!1}return Number(y.lastUpdated||y._lastUpdate||y.timestamp||((P=(E=(M=(D=y.activeChat)==null?void 0:D.messages)==null?void 0:M.at)==null?void 0:E.call(M,-1))==null?void 0:P.timestamp)||0)>=p.startedAt-5e3});if(!C)return;const v=Hh({entrySessionId:C.sessionId,entryInstanceId:C.instanceId,entryRouteId:C.id,conversations:a});v&&(u(null),i("done"),d(`${p.providerType} launched`),t(Ba(v)))},[a,n,t,p]),l.useEffect(()=>{if(!p)return;const w=window.setTimeout(()=>{u(C=>!C||C.startedAt!==p.startedAt?C:(i("error"),d("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(w)},[p]);const b=l.useCallback(async(w,C)=>{var v;if(C.kind==="ide"&&C.providerType){await f(w,C.providerType,{workspacePath:C.workspace||null});return}if((C.kind==="cli"||C.kind==="acp")&&C.providerType){const y=((v=C.workspace)==null?void 0:v.trim())||"";await h(w,C.kind,C.providerType,{workspacePath:y||null,useHome:!y,resumeSessionId:C.providerSessionId||null})}},[f,h]);return{machineAction:{state:o,message:c},resetMachineAction:m,handleLaunchDetectedIde:f,handleAddWorkspace:g,handleMachineUpgrade:k,handleLaunchWorkspaceProvider:h,handleListSavedSessions:x,handleBrowseDirectory:S,handleOpenRecent:b}}function DA({conversations:e,selectedConversation:t,machineBackTarget:n,markConversationRead:a,resetMachineAction:r,setSelectedTabKey:o,setScreen:i,setSelectedMachineId:c,setSection:d,setMachineBackTarget:p}){const u=l.useCallback(S=>{o(S.tabKey),i("chat"),a(S)},[a,i,o]),m=l.useCallback(S=>{const b=e.find(w=>w.routeId===S.routeId&&w.streamSource==="native");b&&(o(b.tabKey),i("chat"),a(b))},[e,a,i,o]),f=l.useCallback(()=>{a(t),i("inbox")},[a,t,i]),g=l.useCallback((S,b="inbox")=>{c(S),r(),d("machines"),p(b),i("machine")},[r,p,i,d,c]),k=l.useCallback(S=>{const b=Ks(S);b&&g(b,"chat")},[g]),h=l.useCallback(()=>{r(),i(n)},[n,r,i]),x=l.useCallback(S=>{d(S),i("inbox")},[i,d]);return{openConversation:u,openNativeConversation:m,backFromConversation:f,openMachine:g,openConversationMachine:k,backFromMachine:h,changeMachineSection:x}}function na(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function IA(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function LA({conversations:e,hiddenConversations:t,ides:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,userName:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,onOpenHistory:k,onOpenRemote:h,onStopCli:x,wsStatus:S,isConnected:b,initialDataLoaded:w=!0,onShowAllHiddenConversations:C,onHideConversation:v,onOpenMeshGraph:y,onOpenNewSession:j,liveSessionInboxState:N,setCliViewModeOverrides:T}){const[A,I]=l.useState(()=>{var ce;return((ce=e[0])==null?void 0:ce.tabKey)||null}),[D,M]=l.useState(()=>e[0]?"chat":"inbox"),[E,P]=l.useState("chats"),[B,R]=l.useState(null),[W,_]=l.useState("inbox"),H=l.useRef([]),L=oa(),F="1.0.55",$=l.useMemo(()=>e.find(ce=>ce.tabKey===A)||e[0]||null,[e,A]),K=l.useMemo(()=>$?n.find(ce=>ce.id===$.routeId):void 0,[n,$]),z=l.useMemo(()=>!$||ht($)||!bt($)?null:la($),[$]),ne=l.useMemo(()=>n.filter(ce=>ce.type==="adhdev-daemon").sort(Ul),[n]),ie=l.useMemo(()=>ne.find(ce=>ce.id===B)||null,[ne,B]),Ce=wo({sendDaemonCommand:r,activeConv:$||void 0,setActionLogs:o,isStandalone:i}),me=PA({sendDaemonCommand:r,navigate:L,ides:n,conversations:e}),O=wC(e),Y=l.useMemo(()=>e.map(ce=>{const Ae=D==="chat"&&($==null?void 0:$.tabKey)===ce.tabKey,be=fo(ce,N,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Ae}),we=jn(ce),_e=Om(ce),U=Ym(ce,_e);return{conversation:ce,timestamp:we,preview:U,unread:be.unread,requiresAction:be.requiresAction,isWorking:be.isWorking,inboxBucket:be.inboxBucket}}),[e,N,D,$,O]),{markConversationRead:X}=AA({conversations:e,machineEntries:ne,items:Y,selectedConversation:$,selectedTabKey:A,screen:D,liveSessionInboxState:N,sendDaemonCommand:r,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,setSelectedTabKey:I,setScreen:M,setSelectedMachineId:R,setSection:P,setMachineBackTarget:_,resetMachineAction:me.resetMachineAction}),Q=DA({conversations:e,selectedConversation:$,machineBackTarget:W,markConversationRead:X,resetMachineAction:me.resetMachineAction,setSelectedTabKey:I,setScreen:M,setSelectedMachineId:R,setSection:P,setMachineBackTarget:_}),{isMuted:ve,toggleMute:he}=Gh(N,r),{attentionItems:Z,unreadItems:fe,workingItems:V,completedItems:q}=l.useMemo(()=>SA(Y,H.current),[Y]);l.useEffect(()=>{H.current=V.map(ce=>ce.conversation.tabKey)},[V]);const ee=l.useMemo(()=>ie?Y.filter(ce=>Ks(ce.conversation)===ie.id):[],[Y,ie]),pe=l.useMemo(()=>CA(ie,n),[n,ie]),le=!!ie&&So(ie,Qs(ie,F)),se=l.useMemo(()=>(ie==null?void 0:ie.availableProviders)||[],[ie]),te=l.useMemo(()=>se.filter(ce=>na(ce,"cli")).map(ce=>({type:ce.type,displayName:ce.displayName||ce.type,icon:ce.icon})),[se]),ue=l.useMemo(()=>se.filter(ce=>na(ce,"acp")).map(ce=>({type:ce.type,displayName:ce.displayName||ce.type,icon:ce.icon})),[se]),ye=l.useMemo(()=>jA(ne,Y,t),[Y,ne,t]),Me=l.useMemo(()=>No(n,w),[n,w]),re=l.useCallback(async ce=>{ie&&await me.handleOpenRecent(ie.id,ce)},[me,ie]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:D==="chat"&&$?s.jsx(uA,{selectedConversation:$,isAcp:ht($),isStandalone:i,selectedIdeEntry:K,actionLogs:a,userName:c,isSendingChat:Ce.isSendingChat,sendFeedbackMessage:Ce.sendFeedbackMessage,isFocusingAgent:Ce.isFocusingAgent,handleModalButton:Ce.handleModalButton,handleRelaunch:Ce.handleRelaunch,onBack:Q.backFromConversation,onOpenNativeConversation:Q.openNativeConversation,onOpenMachine:Q.openConversationMachine,onOpenHistory:k,onOpenRemote:h,onOpenMeshGraph:y,onStopCli:x,cliViewMode:z,onSetCliViewMode:async ce=>{await Ah({conversation:$,mode:ce,ides:n,sendDaemonCommand:r,setCliViewModeOverrides:T})},handleSendChat:Ce.handleSendChat,handleForceSendChat:Ce.handleForceSendChat,handleFocusAgent:Ce.handleFocusAgent}):D==="machine"&&ie?s.jsx(yA,{selectedMachineEntry:ie,selectedMachineConversations:ee,selectedMachineRecentLaunches:pe,cliProviders:te,acpProviders:ue,selectedMachineNeedsUpgrade:le,appVersion:F,machineAction:me.machineAction,isStandalone:i,section:E,showBottomNav:W==="inbox",onBack:Q.backFromMachine,onSectionChange:Q.changeMachineSection,onOpenConversation:Q.openConversation,onOpenRecent:re,onOpenMachineDetails:()=>L(`/machines/${ie.id}`),onMachineUpgrade:()=>me.handleMachineUpgrade(ie.id),onLaunchDetectedIde:(ce,Ae)=>me.handleLaunchDetectedIde(ie.id,ce,Ae),onAddWorkspace:(ce,Ae)=>me.handleAddWorkspace(ie.id,ce,Ae),onBrowseDirectory:ce=>me.handleBrowseDirectory(ie.id,ce),onLaunchWorkspaceProvider:(ce,Ae,be)=>me.handleLaunchWorkspaceProvider(ie.id,ce,Ae,be),onListSavedSessions:ce=>me.handleListSavedSessions(ie.id,ce)}):s.jsx(hA,{section:E,attentionItems:Z,unreadItems:fe,workingItems:V,completedItems:q,hiddenConversations:t,machineCards:ye,getAvatarText:IA,actionLogs:a,sendDaemonCommand:r,onOpenConversation:Q.openConversation,onShowAllHidden:C,onHideConversation:v,onOpenMeshGraph:y,onStopCli:x,onOpenNewSession:j,onOpenMachine:Q.openMachine,onOpenSettings:()=>L("/settings"),onSectionChange:P,wsStatus:S,isConnected:b,initialDataLoaded:w,conversationsLoaded:Me,isStandalone:i,isConversationMuted:ve,onToggleMuteConversation:he})})}function ii(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function RA({conversations:e,numGroups:t,onMoveTab:n,onReceiveTab:a,onOwnTabDrop:r,onClearPreviewOrder:o}){const i=l.useRef(0),[c,d]=l.useState(!1),[p,u]=l.useState(null),m=l.useCallback(()=>{i.current=0,d(!1),u(null)},[]);l.useEffect(()=>(window.addEventListener("dragend",m),window.addEventListener("drop",m),()=>{window.removeEventListener("dragend",m),window.removeEventListener("drop",m)}),[m]);const f=l.useCallback(x=>{x.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,d(!0))},[]),g=l.useCallback(x=>{if(!x.dataTransfer.types.includes("text/tab-key"))return;if(x.preventDefault(),!ii(t,n)){u("merge");return}const S=x.currentTarget.getBoundingClientRect(),b=x.clientX-S.left,w=S.width/3;b<w?u("split-left"):b>w*2?u("split-right"):u("merge")},[t,n]),k=l.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,d(!1),u(null))},[]),h=l.useCallback(x=>{i.current=0,d(!1);const S=x.dataTransfer.getData("text/tab-key"),b=S?e.some(C=>C.tabKey===S):!1,w=p;if(u(null),o(),!!S){if(x.preventDefault(),w==="split-left"&&ii(t,n)){n==null||n(S,"split-left");return}if(w==="split-right"&&ii(t,n)){n==null||n(S,"split-right");return}if(b){r(S);return}a==null||a(S)}},[e,p,t,n,a,r,o]);return{dragOver:c,dropAction:p,resetDragState:m,handleDragEnter:f,handleDragOver:g,handleDragLeave:k,handleDrop:h}}function EA(e,t){const n=new Set(t.map(o=>o.tabKey)),a=e.filter(o=>n.has(o)),r=t.filter(o=>!e.includes(o.tabKey)).map(o=>o.tabKey);return[...a,...r]}function _A({conversations:e,initialActiveTabId:t,initialTabOrder:n,onActiveTabChange:a,onTabOrderChange:r}){const[o,i]=l.useState(t??null),[c,d]=l.useState(n??[]),[p,u]=l.useState(null),m=l.useRef(null),f=l.useRef(null),g=l.useRef(a),k=l.useRef(r);l.useEffect(()=>{g.current=a},[a]),l.useEffect(()=>{k.current=r},[r]),l.useEffect(()=>{t&&t!==o&&i(t)},[t,o]),l.useEffect(()=>{d(j=>{const N=EA(j,e);return N.length===j.length&&N.every((T,A)=>T===j[A])?j:N})},[e]);const h=l.useMemo(()=>{const j=p??c;if(j.length===0)return e;const N=new Map(j.map((T,A)=>[T,A]));return[...e].sort((T,A)=>{const I=N.get(T.tabKey)??999,D=N.get(A.tabKey)??999;return I-D})},[e,p,c]);l.useEffect(()=>{var N,T;if(h.length===0){o!==null&&(i(null),(N=g.current)==null||N.call(g,null));return}if(o&&h.some(A=>A.tabKey===o))return;const j=h[0].tabKey;j!==o&&(i(j),(T=g.current)==null||T.call(g,j))},[h,o]);const x=l.useMemo(()=>h.find(j=>j.tabKey===o),[h,o]),S=l.useCallback(j=>{var N;i(j),(N=g.current)==null||N.call(g,j)},[]),b=l.useCallback((j,N,T)=>{d(A=>{var E;const I=A.filter(P=>P!==j),D=I.indexOf(N);if(D<0)return A;const M=T==="left"?D:D+1;return I.splice(M,0,j),(E=k.current)==null||E.call(k,I),I}),u(null)},[]),w=l.useCallback((j,N,T)=>{const I=(c.length>0?c:e.map(E=>E.tabKey)).filter(E=>E!==j),D=I.indexOf(N);if(D<0)return;const M=T==="left"?D:D+1;I.splice(M,0,j),m.current=I,u(I)},[c,e]),C=l.useCallback(()=>{var N;const j=m.current;j&&(d(j),(N=k.current)==null||N.call(k,j))},[]),v=l.useCallback(()=>{m.current=null,u(null)},[]),y=l.useCallback(j=>{d(N=>{var A;const T=N.filter(I=>I!==j);return T.push(j),(A=k.current)==null||A.call(k,T),T})},[]);return{activeTabId:o,activeConv:x,sortedConversations:h,previewOrderRef:m,draggingTabRef:f,selectTab:S,handleTabReorder:b,updatePreviewOrder:w,commitPreviewOrder:C,clearPreviewOrder:v,moveTabToEnd:y,setDraggingTabKey:j=>{f.current=j}}}function HA({dropAction:e,canSplit:t}){return s.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[s.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-left"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-left"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Left"})}),s.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="merge"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="merge"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)"},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Move Here"})}),s.jsx("div",{className:"flex-1 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-right"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-right"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Right"})})]})}function hc({conversationsCount:e,isSplitMode:t,isStandalone:n,hasRegisteredMachines:a=!1,suppressGuide:r=!1,onOpenNewSession:o,isLoading:i=!1}){const{t:c}=ke("common");if(r)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});if(i)return s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center gap-3 -mt-8 text-text-muted",children:[s.jsx(ls,{}),s.jsx("p",{className:"text-sm",children:c("paneGroup.loadingSessions")})]});const d=!n&&!a,p=a&&!!o,u=c(a?"paneGroup.noConversations":n?"paneGroup.waitingForDaemon":"paneGroup.connectYourMachines"),m=c(a?"paneGroup.newSessionDescription":n?"paneGroup.daemonDescription":"paneGroup.installDescription");return e===0&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:u}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:m}),p&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:o,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:c("paneGroup.newSession"),"aria-label":c("paneGroup.newSession"),children:[s.jsx(Hl,{size:14}),s.jsx("span",{children:c("paneGroup.newSession")})]})}),d&&s.jsx(Fh,{}),d&&s.jsx("div",{className:"mt-8",children:s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:"Read the documentation →"})})]})]}):s.jsx("div",{className:"text-sm text-text-muted opacity-50",children:t?"Move a tab here to view":"No active agent"})}const zh="adhdev-tab-shortcuts";function Kh(){try{return JSON.parse(localStorage.getItem(zh)||"{}")}catch{return{}}}function Vh({enabled:e=!0,sortedTabKeys:t,onFocus:n,onSelectTab:a}){const r=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>Kh()),[c,d]=l.useState(null),p=l.useCallback(m=>{const f=[];return m.metaKey&&f.push(r?"⌘":"Meta"),m.ctrlKey&&f.push("Ctrl"),m.altKey&&f.push(r?"⌥":"Alt"),m.shiftKey&&f.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(m.key)?null:(f.push(m.key.length===1?m.key.toUpperCase():m.key),f.join("+"))},[r]),u=l.useCallback(m=>{i(m);try{localStorage.setItem(zh,JSON.stringify(m))}catch{}},[]);return l.useEffect(()=>{if(!e||!c)return;const m=f=>{if(f.preventDefault(),f.stopPropagation(),f.key==="Escape"){d(null);return}const g=p(f);if(!g)return;const k={...o};for(const[h,x]of Object.entries(k))x===g&&delete k[h];k[c]=g,u(k),d(null)};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[e,c,o,u,p]),l.useEffect(()=>{if(!e)return;const m=f=>{if(!(!f.ctrlKey&&!f.metaKey&&!f.altKey)){for(const[g,k]of Object.entries(o))if(t.includes(g)&&p(f)===k){f.preventDefault(),n(),a(g);return}}};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[e,o,t,n,a,p]),{isMac:r,tabShortcuts:o,shortcutListening:c,setShortcutListening:d,saveShortcuts:u}}const li=e=>{e.preventDefault()},$A=l.memo(function({conv:t,isActive:n,isDraggedTab:a,isTaskCompleteUnread:r,shortcut:o,conversationKeys:i,draggingTabRef:c,onFocus:d,onSelectTab:p,onConversationActivated:u,onPreviewReorder:m,onReorderTab:f,onCommitPreviewOrder:g,onClearPreviewOrder:k,onDragStateReset:h,onDragTabKeyChange:x,onReceiveTab:S,onOpenContextMenu:b,longPressTimer:w,isGroupActive:C}){const v=Rn(t),y=v.isGenerating?"agent-tab-generating":v.isWaiting?"agent-tab-waiting":"",j=v.isReconnecting,N=UC(t),T=GC(t),A=Vm(t),I=l.useCallback(H=>{c.current=t.tabKey,x(t.tabKey),H.dataTransfer.setData("text/tab-key",t.tabKey),H.dataTransfer.effectAllowed="move"},[t.tabKey,c,x]),D=l.useCallback(()=>{c.current=null,x(null),g(),k(),h()},[c,x,g,k,h]),M=l.useCallback(H=>{const L=c.current;if(!(!L||L===t.tabKey)&&H.dataTransfer.types.includes("text/tab-key")){H.preventDefault(),H.stopPropagation();const F=H.currentTarget.getBoundingClientRect(),$=H.clientX<F.left+F.width/2?"left":"right";m(L,t.tabKey,$)}},[t.tabKey,c,m]),E=l.useCallback(H=>{H.preventDefault(),H.stopPropagation();const L=H.dataTransfer.getData("text/tab-key");if(L&&L!==t.tabKey){const F=H.currentTarget.getBoundingClientRect(),$=H.clientX<F.left+F.width/2?"left":"right";i.includes(L)?f(L,t.tabKey,$):S&&S(L)}k()},[t.tabKey,i,f,S,k]),P=l.useCallback(H=>{H.stopPropagation(),d(),p(t.tabKey),u(t)},[t,u,d,p]),B=l.useCallback(H=>{H.preventDefault(),b(H.clientX,H.clientY,t.tabKey)},[t.tabKey,b]),R=l.useCallback(H=>{const L=H.touches[0];w.current=setTimeout(()=>{b(L.clientX,L.clientY,t.tabKey)},600)},[t.tabKey,w,b]),W=l.useCallback(()=>{w.current&&clearTimeout(w.current)},[w]),_=["adhdev-dockview-tab",y,n&&"is-active",C&&"is-group-active",j&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:_,draggable:!0,onDragStart:I,onDragEnd:D,onDragOver:M,onDrop:E,onClick:P,onContextMenu:B,onTouchStart:R,onTouchEnd:W,onTouchMove:W,style:{position:"relative",cursor:"pointer",opacity:a?.4:void 0},children:[A&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-badge pointer-events-none absolute top-0.5 right-0.5 text-text-muted",title:"Mesh chat","aria-label":"Mesh chat",children:s.jsx(cs,{size:11})}),r&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:v.isGenerating?s.jsx(ls,{size:12,thickness:2,color:"success"}):v.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):j?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):v.isConnecting?s.jsx(ls,{size:12,thickness:2}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),N.length>0&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-role",title:T,"aria-label":T||N.join(" · "),children:N.join(" · ")}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:kt(t),children:kt(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[j?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:kn(t)}):v.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[kn(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:kn(t)}),s.jsx(Gr,{git:t.git,compact:!0,className:"max-w-[6.5rem] shrink-0"})]})]}),o&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${o}`,children:o})]})},(e,t)=>e.conv===t.conv&&e.isActive===t.isActive&&e.isDraggedTab===t.isDraggedTab&&e.isTaskCompleteUnread===t.isTaskCompleteUnread&&e.shortcut===t.shortcut&&e.conversationKeys===t.conversationKeys&&e.isGroupActive===t.isGroupActive);function FA({conversations:e,activeTabId:t,groupIndex:n,unreadTabKeys:a,draggingTabRef:r,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:m,onDragStateReset:f,onDragTabKeyChange:g,onReceiveTab:k,onHideTab:h,isGroupActive:x,allowTabShortcuts:S=!0}){const{t:b}=ke("common"),[w,C]=l.useState(null),v=l.useRef(null),y=l.useRef(null),j=l.useMemo(()=>e.map(E=>E.tabKey),[e]);Ga("PaneGroupTabBar",{groupIndex:n,activeTabId:t,tabCount:e.length,ctxMenuTab:(w==null?void 0:w.tabKey)||null});const{isMac:N,tabShortcuts:T,shortcutListening:A,setShortcutListening:I,saveShortcuts:D}=Vh({enabled:S,sortedTabKeys:e.map(E=>E.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!w)return;const E=P=>{const B=document.querySelector("[data-pane-context-menu]");B&&B.contains(P.target)||C(null)};return window.addEventListener("mousedown",E,!0),()=>window.removeEventListener("mousedown",E,!0)},[w]),l.useEffect(()=>{const E=y.current;if(!E)return;const P=B=>{Math.abs(B.deltaY)<=Math.abs(B.deltaX)||(B.preventDefault(),E.scrollLeft+=B.deltaY)};return E.addEventListener("wheel",P,{passive:!1}),()=>E.removeEventListener("wheel",P)},[]);const M=l.useCallback((E,P,B)=>{C({x:E,y:P,tabKey:B})},[]);return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:s.jsxs("div",{ref:y,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(E=>s.jsx($A,{conv:E,isActive:t===E.tabKey,isDraggedTab:r.current===E.tabKey,isTaskCompleteUnread:a.has(E.tabKey),shortcut:S?T[E.tabKey]:void 0,conversationKeys:j,draggingTabRef:r,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:m,onDragStateReset:f,onDragTabKeyChange:g,onReceiveTab:k,onOpenContextMenu:M,longPressTimer:v,isGroupActive:x},E.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:b("paneGroup.noTabsInGroup")})]})}),w&&s.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:w.x,top:w.y},children:[S&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:li,onClick:E=>{E.stopPropagation(),I(w.tabKey),C(null)},children:["⌨ ",T[w.tabKey]?`Change shortcut (${T[w.tabKey]})`:"Set shortcut"]}),T[w.tabKey]&&s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onMouseDown:li,onClick:()=>{const E={...T};delete E[w.tabKey],D(E),C(null)},children:"✕ Remove shortcut"})]}),h&&s.jsxs(s.Fragment,{children:[S&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onMouseDown:li,onClick:()=>{h(w.tabKey),C(null)},children:s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx(po,{size:12}),"Hide from Dashboard"]})})]})]}),S&&A&&s.jsx(Vt,{children:s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:()=>I(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:E=>E.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",N?"⌘+1":"Ctrl+1",", ",N?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:b("paneGroup.pressEscToCancel")})]})})})]})}function BA({conversations:e,ides:t,clearedTabs:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:d=!0,userName:p,groupIndex:u,onFocus:m,isSplitMode:f,numGroups:g,onMoveTab:k,onReceiveTab:h,style:x,onActiveTabChange:S,initialActiveTabId:b,initialTabOrder:w,onTabOrderChange:C,onHideTab:v,isFocused:y,allowTabShortcuts:j=!0,onOpenNewSession:N,liveSessionInboxState:T}){const{sendCommand:A}=St(),I=l.useRef(null),{activeTabId:D,activeConv:M,sortedConversations:E,draggingTabRef:P,selectTab:B,handleTabReorder:R,updatePreviewOrder:W,commitPreviewOrder:_,clearPreviewOrder:H,moveTabToEnd:L,setDraggingTabKey:F}=_A({conversations:e,initialActiveTabId:b,initialTabOrder:w,onActiveTabChange:S,onTabOrderChange:C}),$=wo({sendDaemonCommand:r,activeConv:M,setActionLogs:o,isStandalone:i}),{dragOver:K,dropAction:z,resetDragState:ne,handleDragEnter:ie,handleDragOver:Ce,handleDragLeave:me,handleDrop:O}=RA({conversations:e,numGroups:g,onMoveTab:k,onReceiveTab:h,onOwnTabDrop:L,onClearPreviewOrder:H}),Y=M&&!ht(M)&&la(M)==="terminal",X=l.useMemo(()=>M?t.find(Z=>Z.id===M.routeId):void 0,[t,M]),Q=l.useMemo(()=>M?a.filter(Z=>Z.routeId===M.tabKey):[],[a,M]),ve=l.useMemo(()=>new Set(E.filter(Z=>Tx(Z,T,{isOpenConversation:Z.tabKey===D})).map(Z=>Z.tabKey)),[D,T,E]);Ga("PaneGroup",{groupIndex:u,conversationCount:e.length,activeTabId:D,dragOver:K});const he=l.useCallback(Z=>{Z.streamSource==="agent-stream"&&Z.agentType&&A(Z.routeId,Mm(),{agentType:Z.agentType,...Z.sessionId&&{targetSessionId:Z.sessionId}}).catch(()=>{})},[A]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:m,style:{...x,outline:K?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(FA,{conversations:E,activeTabId:D,groupIndex:u,numGroups:g,unreadTabKeys:ve,draggingTabRef:P,onFocus:m,onSelectTab:B,onConversationActivated:he,onPreviewReorder:W,onReorderTab:R,onCommitPreviewOrder:_,onClearPreviewOrder:H,onDragStateReset:ne,onDragTabKeyChange:F,onMoveTab:k,onReceiveTab:h,onHideTab:v,isGroupActive:y??!1,allowTabShortcuts:j}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:ie,onDragOver:Ce,onDragLeave:me,onDrop:O,children:[K&&s.jsx(HA,{dropAction:z,canSplit:!!(g<4&&k)}),M?s.jsx(pc,{activeConv:M,clearToken:n[M.tabKey]||0,isCliTerminal:!!Y,ideEntry:X,terminalRef:I,handleModalButton:$.handleModalButton,handleRelaunch:$.handleRelaunch,handleSendChat:$.handleSendChat,handleForceSendChat:$.handleForceSendChat,isSendingChat:$.isSendingChat,sendFeedbackMessage:$.sendFeedbackMessage,handleFocusAgent:$.handleFocusAgent,isFocusingAgent:$.isFocusingAgent,actionLogs:Q,userName:p,isInputActive:!f||!!y}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(hc,{conversationsCount:e.length,isSplitMode:f,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:N,isLoading:!No(t,d)})})]})]})}function WA({containerRef:e,isSplitMode:t,numGroups:n,groupSizes:a,groupedConvs:r,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:p,isStandalone:u,hasRegisteredMachines:m,initialDataLoaded:f,userName:g,focusedGroup:k,focusGroup:h,moveTabToGroup:x,splitTabRelative:S,closeGroup:b,handleResizeStart:w,groupActiveTabIds:C,setGroupActiveTab:v,groupTabOrders:y,setGroupTabOrder:j,toggleHiddenTab:N,onOpenNewSession:T,allowTabShortcuts:A=!0,liveSessionInboxState:I}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:r.map((D,M)=>{const E=t&&a.length===n?`${a[M]}%`:void 0;return s.jsxs(Rt.Fragment,{children:[t&&M>0&&s.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:P=>w(M-1,P),onDoubleClick:()=>b(M),title:"Drag to resize · Double-click to merge",children:s.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),s.jsx(BA,{style:t?{flexBasis:E??`${100/n}%`,flexGrow:E?0:1,flexShrink:E?0:1}:void 0,conversations:D,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:p,isStandalone:u,hasRegisteredMachines:m,initialDataLoaded:f,userName:g,groupIndex:M,isFocused:t&&k===M,onFocus:()=>h(M),isSplitMode:t,numGroups:n,onMoveTab:(P,B)=>{B==="left"&&M>0?x(P,M-1):B==="right"&&M<n-1?x(P,M+1):B==="split-left"&&n<4?S(P,M,"left"):B==="split-right"&&n<4&&S(P,M,"right")},onReceiveTab:P=>x(P,M),onActiveTabChange:P=>v(M,P),initialActiveTabId:C[M],initialTabOrder:y[M],onTabOrderChange:P=>j(M,P),onHideTab:N,onOpenNewSession:T,allowTabShortcuts:A,liveSessionInboxState:I})]},M)})})}const Yh="adhdev-dashboard-action-shortcuts",OA=1200,UA=[["toggleHiddenTabs","G H"],["openNewSession","N"],["setActiveTabShortcut","G S"],["selectPreviousGroupTab","G K"],["selectPreviousGroupTab","T ←"],["selectPreviousGroupTab","⌥+["],["selectPreviousGroupTab","Ctrl+Alt+["],["selectNextGroupTab","G J"],["selectNextGroupTab","T →"],["selectNextGroupTab","⌥+]"],["selectNextGroupTab","Ctrl+Alt+]"],["splitActiveTabDown","S ↓"],["splitActiveTabDown","⌘+⌥+-"],["splitActiveTabDown","Ctrl+Alt+-"],["splitActiveTabRight","S →"],["splitActiveTabRight","⌘+⌥+\\"],["splitActiveTabRight","⌘+⌥+="],["splitActiveTabRight","Ctrl+Alt+\\"],["focusLeftPane","F ←"],["focusLeftPane","⌘+⌥+←"],["focusLeftPane","⌘+⌥+["],["focusLeftPane","Ctrl+Alt+←"],["focusRightPane","F →"],["focusRightPane","⌘+⌥+→"],["focusRightPane","⌘+⌥+]"],["focusRightPane","Ctrl+Alt+→"],["focusUpPane","F ↑"],["focusUpPane","⌘+⌥+U"],["focusUpPane","Ctrl+Alt+↑"],["focusDownPane","F ↓"],["focusDownPane","⌘+⌥+J"],["focusDownPane","Ctrl+Alt+↓"],["moveActiveTabToLeftPane","M ←"],["moveActiveTabToLeftPane","⌘+⌥+⇧+←"],["moveActiveTabToLeftPane","⌘+⌥+,"],["moveActiveTabToLeftPane","Ctrl+Alt+Shift+←"],["moveActiveTabToRightPane","M →"],["moveActiveTabToRightPane","⌘+⌥+⇧+→"],["moveActiveTabToRightPane","⌘+⌥+."],["moveActiveTabToRightPane","Ctrl+Alt+Shift+→"],["moveActiveTabToUpPane","M ↑"],["moveActiveTabToUpPane","⌘+⌥+I"],["moveActiveTabToUpPane","Ctrl+Alt+Shift+↑"],["moveActiveTabToDownPane","M ↓"],["moveActiveTabToDownPane","⌘+⌥+K"],["moveActiveTabToDownPane","Ctrl+Alt+Shift+↓"],["triggerPrimaryApprovalAction","⌥+A"],["triggerSecondaryApprovalAction","⌥+D"],["toggleCliView","T"]];function GA(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function gt(e,t){switch(e){case"openShortcutHelp":return"?";case"openNewSession":return t?"⌘+⇧+Enter":"Ctrl+Shift+Enter";case"hideCurrentTab":return t?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return t?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return t?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return t?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return t?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return t?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return t?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return t?"⌘+Ctrl+⇧+→":"Ctrl+Alt+Shift+→";case"splitActiveTabDown":return t?"⌘+Ctrl+⇧+↓":"Ctrl+Alt+Shift+↓";case"focusLeftPane":return"";case"focusRightPane":return"";case"focusUpPane":return"";case"focusDownPane":return"";case"moveActiveTabToLeftPane":return"";case"moveActiveTabToRightPane":return"";case"moveActiveTabToUpPane":return"";case"moveActiveTabToDownPane":return"";case"triggerPrimaryApprovalAction":return t?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return t?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return t?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return t?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return t?"⌘+⇧+←":"Ctrl+Shift+←";case"selectNextGroupTab":return t?"⌘+⇧+→":"Ctrl+Shift+→";case"toggleCliView":return t?"⌥+T":"Ctrl+Alt+T"}}function Qh(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:gt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:gt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:gt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:gt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:gt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:gt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:gt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:gt("popoutActiveTab",e)},{id:"dockActiveTab",label:"Dock active tab",description:"Dock a floating tab back into the grid, or move a popout tab back to the main window.",defaultShortcut:gt("dockActiveTab",e)},{id:"splitActiveTabRight",label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it.",defaultShortcut:gt("splitActiveTabRight",e)},{id:"splitActiveTabDown",label:"Move active tab to new lower pane",description:"Create a pane below and move the active tab into it.",defaultShortcut:gt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:gt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:gt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:gt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:gt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:gt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:gt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:gt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:gt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:gt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:gt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:gt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:gt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:gt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:gt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:gt("toggleCliView",e)}]}function ml(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function Zr(e){const t=Object.fromEntries(Qh(e).map(n=>[n.id,n.defaultShortcut]));try{const n=JSON.parse(localStorage.getItem(Yh)||"{}"),a={...t,...n};for(const[r,o]of UA)a[r]===o&&(a[r]=t[r]);return a}catch{return t}}function Jh(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function qA({enabled:e=!0,onTrigger:t}){const n=GA(),[a,r]=l.useState(()=>Zr(n)),[o,i]=l.useState(null),[c,d]=l.useState([]),p=l.useRef({parts:[],timer:null}),u=l.useCallback(h=>{const x=[];return h.metaKey&&x.push(n?"⌘":"Meta"),h.ctrlKey&&x.push("Ctrl"),h.altKey&&x.push(n?"⌥":"Alt"),h.shiftKey&&h.key.length!==1&&x.push(n?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(x.push(Jh(h.key)),x.join("+"))},[n]),m=l.useCallback(h=>{r(h);try{localStorage.setItem(Yh,JSON.stringify(h))}catch{}},[]);l.useEffect(()=>{const h=Zr(n),x=Object.entries(a),S=Object.entries(h);x.length===S.length&&x.every(([b,w])=>h[b]===w)||m(h)},[a,n,m]);const f=l.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),g=l.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},OA))},[]);l.useEffect(()=>{if(!o)return;const h=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){i(null),d([]);return}const S=u(x);if(!S)return;const w=!(x.metaKey||x.ctrlKey||x.altKey)&&/^[A-Z0-9]$/.test(S);if(c.length===0&&w){d([S]);return}const v=[...c,S].slice(0,2).join(" "),y={...a};for(const[j,N]of Object.entries(y))N===v&&delete y[j];y[o]=v,m(y),i(null),d([])};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[a,u,m,o,c]),l.useEffect(()=>{if(!e||o)return;const h=x=>{if(x.defaultPrevented)return;const S=u(x);if(!S)return;const b=x.metaKey||x.ctrlKey||x.altKey;if(ml(x.target))return;const w=p.current.parts,C=b?[S]:[...w.slice(-1),S].slice(-2),v=C.join(" "),y=C[C.length-1],j=Object.entries(a).filter(([,D])=>!!D),N=j.find(([,D])=>D===v);if(N){x.preventDefault(),f(),t(N[0]);return}if(j.some(([,D])=>D.startsWith(`${v} `))){x.preventDefault(),p.current.parts=C,g();return}const A=j.find(([,D])=>D===y);if(A){x.preventDefault(),f(),t(A[0]);return}if(j.some(([,D])=>D.startsWith(`${y} `))){x.preventDefault(),p.current.parts=[y],g();return}f()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[a,g,e,u,t,f,o]),l.useEffect(()=>()=>f(),[f]);const k=l.useMemo(()=>Qh(n),[n]);return{isMac:n,actionDefinitions:k,actionShortcuts:a,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:d,saveShortcuts:m}}function zA({isTabInPopout:e,isTabFloating:t,tabShortcut:n,actionShortcuts:a}){const r=[];return e?(t&&r.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:a.dockActiveTab}),r.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:a.dockActiveTab})):t?r.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:a.dockActiveTab}):r.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:a.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:a.popoutActiveTab}),r.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:n?`Change shortcut (${n})`:"Set shortcut",shortcut:a.setActiveTabShortcut}),n&&r.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),r.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:a.hideCurrentTab,tone:"muted"}),r}function Xh(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function ou({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:n,ides:a}){return!e||n>0?!1:t?!Xh(a):!0}function KA({previousVisibleConversationCount:e,visibleConversationCount:t,ides:n}){return t>0||e<=0?!1:Xh(n)}const Zh=1e3,VA=4;function iu(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function lu(e,t,n){return Math.abs(t.clientX-e.clientX)>n||Math.abs(t.clientY-e.clientY)>n}function YA({detachDelayMs:e=Zh,stillnessThresholdPx:t=VA,onDetach:n,setTimeoutFn:a=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:r=globalThis.clearTimeout.bind(globalThis)}){let o=null,i=null,c=null,d=null,p=null,u=!1;const m=()=>{p!=null&&(r(p),p=null)},f=()=>{m(),c=null},g=()=>{m(),o=null,i=null,c=null,d=null,u=!1},k=()=>{!o||!c||!d||u||p!=null||(p=a(()=>{p=null,!(!o||!c||!d||u)&&iu(d,i)&&(lu(c,d,t)||(u=!0,n({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},h=S=>{if(!(!o||u)){if(!iu(S,i)){d={clientX:S.clientX,clientY:S.clientY},f();return}(!c||lu(c,S,t))&&(m(),c={clientX:S.clientX,clientY:S.clientY}),d={clientX:S.clientX,clientY:S.clientY},k()}},x=S=>{!o||u||(S&&(d={clientX:S.clientX,clientY:S.clientY}),f())};return{startDrag:S=>{m(),o=S.panelId,i=S.selfPanelBounds??null,c=null,d={clientX:S.clientX,clientY:S.clientY},u=!1},markSelfPanel:h,markNonSelfPanel:x,markNoDropTarget:x,markDockTarget:x,endDrag:g,isDragging:()=>o!=null,hasDetached:()=>u,dispose:g}}function QA(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function Ir(e){return kt(e)||e.tabKey}function JA(e){return`remote:${e}`}function fs(e){return e.startsWith("remote:")}function cu(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function ci(e){var a;const t=e==null?void 0:e.defaultView;if(!t)return;const n=r=>{if(r)try{r.focus({preventScroll:!0})}catch{try{r.focus()}catch{}}};try{t.focus(),n(e==null?void 0:e.body),n(e==null?void 0:e.documentElement),(a=t.requestAnimationFrame)==null||a.call(t,()=>{try{t.focus(),n(e==null?void 0:e.body)}catch{}})}catch{}}function di(e,t){e.classList.remove(Hi.className,$i.className),e.classList.add(t==="light"?Hi.className:$i.className)}function du(e){return e?Array.from(new Set(e.groups.map(t=>{var n,a;return(a=(n=t.element)==null?void 0:n.ownerDocument)==null?void 0:a.defaultView}).filter(t=>!!t&&t!==window))):[]}function XA(e,t,n){var i;const a=[t];let r;for(const c of a){let d;for(const p of c){const u=e.addPanel({id:p.tabKey,component:"conversation",title:Ir(p),params:{kind:"conversation",tabKey:p.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:r?{position:{referencePanel:r,direction:"right"},inactive:!0}:{}});d||(d=u.id)}r=d??r}return n??((i=t[0])==null?void 0:i.tabKey)??null}function uu(e,t){const n=new Set(t.map(r=>r.tabKey)),a=new Map;for(const r of t)a.set(r.tabKey,(a.get(r.tabKey)||0)+1);for(const r of[...e.panels])fs(r.id)||n.has(r.id)||e.removePanel(r);for(const r of t){const o=e.getPanel(r.tabKey);if(o){(a.get(r.tabKey)||0)>1&&console.warn("[dashboard-conversations] Dockview panel already exists for duplicate tabKey",{tabKey:r.tabKey,daemonId:r.daemonId,sessionId:r.sessionId,providerSessionId:r.providerSessionId,panelId:o.id}),o.update({params:{tabKey:r.tabKey}}),o.title!==Ir(r)&&o.api.setTitle(Ir(r));continue}e.addPanel({id:r.tabKey,component:"conversation",title:Ir(r),params:{kind:"conversation",tabKey:r.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function pu(e,t,n){var d,p;const a=n?JA(n):null;for(const u of[...e.panels])fs(u.id)&&(!a||u.id!==a)&&e.removePanel(u);if(!n||!a)return;const r=ws(t,n);if(!r&&e.totalPanels===0)return;const o=e.getPanel(a),i=Xm(r);if(o){o.title!==i&&o.api.setTitle(i);return}const c=(r==null?void 0:r.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((p=e.panels.find(u=>!fs(u.id)))==null?void 0:p.id);e.addPanel({id:a,component:"remote",title:i,params:{kind:"remote",routeId:n},...c?{position:{referencePanel:c,direction:"right"},inactive:!0}:{}})}function ef({doId:e,targetSessionId:t,connState:n,viewMode:a}){const[r,o]=l.useState(null),[i,c]=l.useState(null);l.useEffect(()=>e?Ct.onScreenshot("ide-page",(u,m)=>{if(u!==e)return;const f=new FileReader;f.onload=()=>o(f.result),f.readAsDataURL(m)}):void 0,[e]),l.useEffect(()=>{n!=="connected"&&o(null)},[n]),l.useEffect(()=>{var u;return e?((u=Ct.onStatus)==null?void 0:u.call(Ct,(m,f)=>{m===e&&f!=null&&f.screenshotUsage&&c(f.screenshotUsage)}))||(()=>{}):void 0},[e]),l.useEffect(()=>{o(null)},[e,t]),l.useEffect(()=>{const p=e?Ct.get(e):null;if(!(!p||n!=="connected"))return a!=="chat"&&t?p.startScreenshots(t):p.stopScreenshots(t),()=>{p.stopScreenshots(t)}},[a,n,t,e]);const d=l.useCallback(async(p,u)=>{const m=e?Ct.get(e):null;return!m||n!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):m.sendInput(p,u,t)},[e,n,t]);return{connScreenshot:r,screenshotUsage:i,handleRemoteAction:d}}const tf=l.createContext(null);function Ao(){const e=l.useContext(tf);if(!e)throw new Error("DashboardDockviewContext missing");return e}function ZA(e){const[,t]=l.useState(0);l.useEffect(()=>{const n=()=>t(r=>r+1),a=[e.api.onDidActiveGroupChange(n),e.api.onDidTitleChange(n),e.api.onDidGroupChange(n),e.containerApi.onDidActivePanelChange(n)];return()=>{for(const r of a)r.dispose()}},[e.api,e.containerApi])}function eT({params:e}){var d;const t=Ao(),n=l.useMemo(()=>ws([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),a=l.useMemo(()=>t.ides.find(p=>p.id===e.routeId),[t.ides,e.routeId]),r=(n==null?void 0:n.daemonId)||((d=n==null?void 0:n.routeId)==null?void 0:d.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:i,handleRemoteAction:c}=ef({doId:r,targetSessionId:n?Am(n):(a==null?void 0:a.sessionId)||(a==null?void 0:a.instanceId),connState:(n==null?void 0:n.connectionState)||"new",viewMode:"remote"});return n?s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:s.jsx(Gp,{addLog:()=>{},connState:n.connectionState||"new",connScreenshot:o,screenshotUsage:i,transportType:n.transport,onAction:c})}):s.jsx("div",{className:"h-full min-h-0 min-w-0 flex items-center justify-center text-sm text-text-muted",children:"Remote view unavailable"})}function tT(){const e=Ao();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(hc,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels,isLoading:!No(e.ides,e.initialDataLoaded)})})}function sT(e){var b,w;ZA(e);const t=Ao(),n=l.useCallback(C=>{"button"in C&&C.button!==0||e.api.setActive()},[e.api]),a=e.params.kind==="remote"?void 0:t.conversationsByTabKey.get(e.params.tabKey),r=a==null?void 0:a.sessionId,o=l.useCallback(C=>jC(C),[]),i=l.useCallback(()=>CC(r),[r]),c=l.useSyncExternalStore(o,i,i);if(e.params.kind==="remote"){const C=ws([...t.conversationsByTabKey.values()],e.params.routeId),v=((b=e.api.group.activePanel)==null?void 0:b.id)===e.api.id,y=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${v?" is-active":""}${y?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(C==null?void 0:C.tabKey)||"",onMouseDown:n,onTouchStart:n,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:C!=null&&C.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:C.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const d=t.conversationsByTabKey.get(e.params.tabKey);if(!d)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const p=((w=e.api.group.activePanel)==null?void 0:w.id)===e.api.id,u=e.api.isGroupActive,m=fo(d,t.liveSessionInboxState,{isOpenConversation:p}),f=m.isReconnecting,g=m.isConnecting,k=m.isGenerating||c,h=m.isWaiting,x=m.unread,S=t.tabShortcuts[d.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${p?" is-active":""}${u?" is-group-active":""}${f?" is-reconnecting":""}`,title:kt(d),"data-tab-key":e.params.tabKey,onMouseDown:n,onTouchStart:n,onContextMenu:C=>{var v;C.preventDefault(),n(C),t.openTabContextMenu({x:C.clientX,y:C.clientY,tabKey:d.tabKey,sourceDocument:((v=C.target)==null?void 0:v.ownerDocument)??document})},children:[x&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:k?s.jsx(ls,{size:12,thickness:2,color:"success"}):h?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):f?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):g?s.jsx(ls,{size:12,thickness:2}):d.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:kt(d)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:f?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:kn(d)}):g?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:kn(d)}):s.jsx("span",{children:kn(d)})})]}),S&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:S,children:S})]})}function mr(e){return e.isActive}function mu(e){return e.isVisible}function nT(e){e.preventDefault()}function aT({params:e,api:t}){var g;const n=Ao(),a=l.useRef(null),[r,o]=l.useState(()=>mr(t)),[i,c]=l.useState(()=>mu(t)),d=n.conversationsByTabKey.get(e.tabKey),p=wo({sendDaemonCommand:n.sendDaemonCommand,activeConv:d,setActionLogs:n.setActionLogs,isStandalone:n.isStandalone});l.useEffect(()=>{o(mr(t)),c(mu(t));const k=[t.onDidActiveChange(h=>o(h.isActive)),t.onDidActiveGroupChange(h=>{if(!mr(t)&&!h.isActive){o(!1);return}o(mr(t))}),t.onDidVisibilityChange(h=>c(h.isVisible))];return()=>{for(const h of k)h.dispose()}},[t]);const u=l.useMemo(()=>d?n.ides.find(k=>k.id===d.routeId):void 0,[n.ides,d]),m=l.useMemo(()=>d?n.actionLogs.filter(k=>k.routeId===d.tabKey):[],[n.actionLogs,d]);if(!d)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(hc,{conversationsCount:0,isSplitMode:!1,isStandalone:n.isStandalone,hasRegisteredMachines:n.hasRegisteredMachines,onOpenNewSession:n.onOpenNewSession,suppressGuide:n.hasDetachedConversationPanels,isLoading:!No(n.ides,n.initialDataLoaded)})});const f=!ht(d)&&la(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(pc,{activeConv:d,clearToken:n.clearedTabs[d.tabKey]||0,isCliTerminal:f,ideEntry:u,terminalRef:a,handleModalButton:p.handleModalButton,handleRelaunch:p.handleRelaunch,handleSendChat:p.handleSendChat,handleForceSendChat:p.handleForceSendChat,isSendingChat:p.isSendingChat,handleFocusAgent:p.handleFocusAgent,isFocusingAgent:p.isFocusingAgent,actionLogs:m,userName:n.userName,scrollToBottomRequestNonce:((g=n.scrollToBottomRequest)==null?void 0:g.tabKey)===d.tabKey?n.scrollToBottomRequest.nonce:void 0,isInputActive:r,isVisible:i})})}function rT({visibleConversations:e,clearedTabs:t,ides:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:d,userName:p,toggleHiddenTab:u,actionShortcuts:m,registerActionHandlers:f,onActiveTabChange:g,onOpenNewSession:k,onRequestScrollToBottom:h,requestedActiveTabKey:x,requestedRemoteIdeId:S,onRequestedActiveTabConsumed:b,scrollToBottomRequest:w,liveSessionInboxState:C,layoutProfile:v}){var $e,at,rt;const{theme:y}=Ls(),{sendCommand:j}=St(),N=l.useRef(null),T=l.useRef(null),A=l.useRef(null),I=l.useRef(!1),D=l.useRef(!1),M=l.useRef(!1),E=l.useRef(null),P=l.useRef([]),[B,R]=l.useState(null),[W,_]=l.useState(0),H=l.useRef(typeof window>"u"?{}:SN(v)),L=l.useMemo(()=>new Map(e.map(G=>[G.tabKey,G])),[e]),F=l.useMemo(()=>{const G=N.current;return G?G.groups.some(oe=>{try{const de=oe.model.location.type;return de!=="floating"&&de!=="popout"?!1:oe.panels.some(xe=>L.has(xe.id))}catch{return!1}}):!1},[L,W,e]),$=l.useCallback(()=>{var G;(G=N.current)==null||G.focus()},[]),K=l.useCallback((G,oe)=>{h==null||h(G,oe)},[h]),z=l.useCallback(G=>{const oe=document,de=G.document;for(const Ee of oe.querySelectorAll('link[rel="stylesheet"]')){const Je=de.createElement("link");Je.rel="stylesheet",Je.href=Ee.href,Ee.crossOrigin&&(Je.crossOrigin=Ee.crossOrigin),de.head.appendChild(Je)}for(const Ee of oe.querySelectorAll("style")){const Je=de.createElement("style");Je.textContent=Ee.textContent,de.head.appendChild(Je)}const xe=[];for(const Ee of oe.styleSheets)try{for(const Je of Ee.cssRules)Je instanceof CSSStyleRule&&(Je.selectorText===":root"||Je.selectorText==="html")&&xe.push(Je.cssText)}catch{}if(xe.length>0){const Ee=de.createElement("style");Ee.textContent=xe.join(`
|
|
66
66
|
`),de.head.appendChild(Ee)}const Se=oe.documentElement.getAttribute("data-theme");Se&&de.documentElement.setAttribute("data-theme",Se),de.documentElement.style.colorScheme=Se==="light"?"light":"dark",de.body.className=oe.body.className;const Pe=oe.documentElement.getAttribute("style");Pe&&de.documentElement.setAttribute("style",Pe);const He=de.getElementById("dv-popout-window");He instanceof HTMLElement&&(He.classList.add("adhdev-dockview"),di(He,y))},[y]),ne=l.useCallback(()=>{var oe;const G=N.current;if(G)for(const de of G.groups)try{const xe=(oe=de.element)==null?void 0:oe.ownerDocument;if(!xe||xe===document)continue;const Se=xe.getElementById("dv-popout-window");Se instanceof HTMLElement&&(Se.classList.add("adhdev-dockview"),di(Se,y));const Pe=document.documentElement.getAttribute("data-theme");Pe&&xe.documentElement.setAttribute("data-theme",Pe),xe.documentElement.style.colorScheme=Pe==="light"?"light":"dark",xe.body.className=document.body.className;const He=document.documentElement.getAttribute("style");He?xe.documentElement.setAttribute("style",He):xe.documentElement.removeAttribute("style")}catch{}},[y]),ie=l.useCallback(G=>{const oe=N.current;if(!oe)return;const de=oe.getPanel(G);de&&oe.addPopoutGroup(de,{popoutUrl:"/popout.html",onDidOpen:({window:xe})=>{z(xe),Z();const Se=L.get(G);xe.document.title=Se?`${kt(Se)} — ADHDev`:"ADHDev — Popout"}})},[L,z]),Ce=l.useCallback(G=>{const oe=N.current,de=oe==null?void 0:oe.getPanel(G);if(!oe||!de)return;const xe=oe.groups.filter(Se=>{var Pe;try{return((Pe=Se.element)==null?void 0:Pe.ownerDocument)===document}catch{return!0}});xe.length>0?de.api.moveTo({group:xe[0],position:"center"}):de.api.moveTo({position:"center"}),de.api.setActive()},[]),me=l.useCallback(G=>{var xe;const oe=N.current;if(!oe)return!1;const de=oe.getPanel(G);if(!de)return!1;try{return((xe=de.group.element)==null?void 0:xe.ownerDocument)!==document}catch{return!1}},[]),O=l.useCallback(G=>{me(G)&&Ce(G),u(G)},[me,Ce,u]),Y=l.useCallback(G=>{const oe=N.current,de=oe==null?void 0:oe.getPanel(G);!oe||!de||oe.addFloatingGroup(de,{width:600,height:500})},[]),X=l.useCallback(G=>{var de;const oe=(de=N.current)==null?void 0:de.getPanel(G);if(!oe)return!1;try{return oe.group.model.location.type==="floating"}catch{return!1}},[]),Q=l.useCallback(()=>{var oe,de;const G=(de=(oe=N.current)==null?void 0:oe.activePanel)==null?void 0:de.id;return!G||fs(G)?null:L.has(G)?G:null},[L]),ve=l.useCallback(G=>{const oe=N.current,de=oe==null?void 0:oe.getPanel(G);if(!oe||!de)return;const xe=oe.groups.filter(Se=>{try{return Se.model.location.type==="grid"}catch{return!0}});xe.length>0?de.api.moveTo({group:xe[0],position:"center"}):de.api.moveTo({position:"center"}),de.api.setActive()},[]),he=l.useCallback(()=>{var Pe;const G=N.current;if(!G)return;const de=G.groups.filter(He=>{var Ee;try{return((Ee=He.element)==null?void 0:Ee.ownerDocument)===document&&He.model.location.type==="grid"}catch{return!1}})[0]||null,xe=[...G.panels];for(const He of xe){const Ee=(Pe=He.group.element)==null?void 0:Pe.ownerDocument,Je=He.group.model.location.type;Ee===document&&Je==="grid"||(de&&de.id!==He.group.id?He.api.moveTo({group:de,position:"center"}):He.api.moveTo({position:"center"}))}const Se=G.activePanel;Se&&(Se.group.model.openPanel(Se),Se.api.setActive()),ci(document)},[]),Z=l.useCallback(()=>{var oe,de;const G=N.current;if(G)for(const xe of G.groups){const Se=(oe=xe.element)==null?void 0:oe.ownerDocument;if(!Se||Se===document)continue;const Pe=Se.getElementById("dv-popout-window");if(!(Pe instanceof HTMLElement))continue;let He=null,Ee=Se.title||"ADHDev",Je="Popout workspace";const st=xe.activePanel;if(st)if(He=st.id,fs(st.id)){const Be=((de=st.params)==null?void 0:de.routeId)||st.id.slice(7),ge=ws([...L.values()],Be);Ee=Xm(ge),Je=ge!=null&&ge.machineName?`Remote view · ${ge.machineName}`:"Remote view"}else{const Be=L.get(st.id);Ee=Be?kt(Be):st.title||st.id,Je=Be?kn(Be):"Dockview panel"}Se.title=`${Ee} — ADHDev`;const Ze=Array.from(Se.querySelectorAll("#adhdev-popout-header"));for(const Be of Ze)Be.remove();const Ue=Se.createElement("div");Ue.id="adhdev-popout-header",Se.body.appendChild(Ue),Ue.setAttribute("style",["position:absolute","top:0","left:0","right:0","height:52px","display:flex","align-items:center","justify-content:space-between","gap:12px","padding:0 14px","box-sizing:border-box","background:var(--surface-secondary)","border-bottom:1px solid var(--border-subtle)","z-index:5","backdrop-filter:blur(14px)"].join(";")),Ue.innerHTML=`
|
|
67
67
|
<div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
|
|
68
68
|
<div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
|
|
@@ -111,11 +111,11 @@ This will disconnect CDP and optionally kill the process.`))try{const L=await n(
|
|
|
111
111
|
|
|
112
112
|
`)}function iL(e,t){return t==="issues"?e.filter(n=>n.level==="warn"||n.level==="error"):t==="info"?e.filter(n=>n.level!=="debug"):e}function lL(e,t){return t==="issues"?e.filter(n=>n.level==="warn"||n.level==="error"):t==="info"?e.filter(n=>n.level!=="debug"):e}function cL({daemonLogs:e,daemonRawText:t,daemonLogKind:n,debugTrace:a,webEvents:r,traceCategory:o,quickFilter:i,searchQuery:c,daemonLoading:d,traceLoading:p,daemonFetchError:u,traceFetchError:m}){const f=FI(a,o),g=OI(e,c),k=qI(t,c),h=zI(f,c),x=KI(r,c),S=iL(g,i),b=i==="all"?k:[],w=lL(h,i),C=i==="issues"?[]:x,v=VI({daemonLogs:g,daemonRawLines:k,trace:h,webEvents:x}),y=sL({daemonLogs:S,daemonRawLines:b,trace:w,webEvents:C}),j=aL(y),N=JI({daemonLoading:d,traceLoading:p,daemonFetchError:u,traceFetchError:m,daemonLogKind:n,daemonLogsCount:g.length,daemonRawLineCount:k.length,traceCount:h.length,webEventCount:x.length});return{filteredDaemonLogs:g,filteredDaemonRawLines:k,filteredTraceEntries:h,filteredWebEvents:x,visibleDaemonLogs:S,visibleDaemonRawLines:b,visibleTraceEntries:w,visibleWebEvents:C,quickFilterCounts:v,diagnosticEvents:y,diagnosticsSummary:j,sourceStates:N}}function dL(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Qf(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function vl(e){return e==="error"?"text-red-300 border-red-500/25 bg-red-500/[0.05]":e==="warn"?"text-amber-200 border-amber-500/25 bg-amber-500/[0.05]":e==="debug"?"text-slate-300 border-slate-500/25 bg-slate-500/[0.05]":"text-text-secondary border-border-subtle bg-bg-primary"}function Ti(e){return e==="good"?"border-emerald-500/20 bg-emerald-500/[0.05]":e==="warning"?"border-amber-500/20 bg-amber-500/[0.05]":e==="danger"?"border-red-500/20 bg-red-500/[0.05]":"border-border-subtle bg-bg-secondary"}function Ac(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function uL({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${vl(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:Qf(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:Ac(e.source)}),e.category&&e.stage&&s.jsxs("span",{children:[e.category,".",e.stage]}),e.topic&&s.jsxs("span",{children:["topic=",e.topic]}),e.interactionId&&s.jsxs("span",{children:["ix=",e.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:e.message})]})}function pL({quickFilter:e,quickFilterCounts:t,searchQuery:n,autoRefresh:a,onQuickFilterChange:r,onSearchQueryChange:o,onCopyDiagnostics:i,onCopyVisible:c,onToggleAutoRefresh:d,onRefresh:p,onClear:u}){return s.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"View"}),s.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${t.info})`},{id:"issues",label:`Issues (${t.issues})`},{id:"all",label:`All (${t.all})`}].map(m=>s.jsx("button",{type:"button",onClick:()=>r(m.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===m.id?"bg-accent-primary/15 text-accent-primary border border-accent-primary/30":"text-text-secondary hover:text-text-primary"}`,children:m.label},m.id))}),s.jsx("input",{value:n,onChange:m=>o(m.target.value),placeholder:"Search diagnostics…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{onClick:i,className:"machine-btn",children:"Copy diagnostics"}),s.jsx("button",{onClick:c,className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:d,className:`machine-btn ${a?"text-green-500 border-green-500/30":""}`,children:a?"Pause":"Resume"}),s.jsx("button",{onClick:p,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:u,className:"machine-btn",children:"Clear"})]})]})}function mL({logLevel:e,traceCategory:t,onLogLevelChange:n,onTraceCategoryChange:a}){return s.jsx(vs,{padding:"sm",children:s.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wider text-text-muted font-semibold",children:"Advanced source scope"}),["debug","info","warn","error"].map(r=>s.jsxs("button",{onClick:()=>n(r),className:`machine-btn text-[10px] px-2 py-0.5 ${e===r?"bg-accent-primary/15 border-accent-primary/40 text-accent-primary":""}`,children:["Daemon ",r.toUpperCase(),"+"]},r))]}),s.jsx("div",{className:"flex flex-wrap gap-2 items-center",children:HI.map(r=>s.jsx("button",{onClick:()=>a(r.value),className:`machine-btn text-[10px] px-2 py-0.5 ${t===r.value?"bg-accent-primary/15 border-accent-primary/40 text-accent-primary":""}`,children:r.label},r.value))})]})})}function hL({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:n,searchQuery:a,lastUpdatedAt:r,autoRefresh:o,daemonFetchError:i,traceFetchError:c}){var u,m;const d=((u=e.latestIssue)==null?void 0:u.severity)==="error"?"danger":((m=e.latestIssue)==null?void 0:m.severity)==="warn"?"warning":"good",p=i||c?"danger":o?"good":"neutral";return s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${Ti(e.issueCount>0?"warning":"good")}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Diagnostics timeline"}),s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[t," visible event(s) · ",e.issueCount," issue signal(s)"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:a.trim()?`Filtered by “${a.trim()}”`:"Daemon, trace, and browser signals merged by time"})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${Ti(d)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Latest issue"}),e.latestIssue?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[Ac(e.latestIssue.source)," · ",e.latestIssue.severity.toUpperCase()]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:e.latestIssue.message}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2",children:Qf(e.latestIssue.ts)})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No visible warn/error signal"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use Issues or All if you need a narrower or rawer view."})]})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${Ti(p)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Source status"}),s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:i||c?"Needs attention":o?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",dL(r)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:n.map(f=>s.jsxs("div",{children:[f.label,": ",f.status]},f.id))})]})]})}function fL({patterns:e}){return e.length===0?null:s.jsxs("div",{className:"rounded-xl border border-amber-500/20 bg-amber-500/[0.04] p-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Repeated issue patterns"}),s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:e.map(t=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-primary px-3 py-2",children:[s.jsxs("div",{className:"text-[12px] text-text-primary font-medium",children:[t.count,"× ",t.severity.toUpperCase()," · ",Ac(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function gL({streams:e,sectionsOpen:t,setSectionsOpen:n,diagnosticEvents:a,visibleDaemonLogs:r,visibleDaemonRawLines:o,visibleTraceEntries:i,visibleWebEvents:c,quickFilter:d,searchQuery:p}){return s.jsxs("div",{className:"grid gap-3",children:[s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>n(u=>({...u,timeline:!u.timeline})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Unified timeline"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[a.length," visible diagnostic event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.timeline?"Hide":"Show"})]}),t.timeline&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[180px] max-h-[440px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[(e.daemonLoading||e.traceLoading)&&a.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&a.length===0&&s.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&s.jsxs("div",{children:["Daemon logs: ",e.daemonFetchError]}),e.traceFetchError&&s.jsxs("div",{children:["Daemon trace: ",e.traceFetchError]})]}),!e.daemonLoading&&!e.traceLoading&&a.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),a.map(u=>s.jsx(uL,{event:u},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>n(u=>({...u,daemon:!u.daemon})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · daemon logs"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:e.daemonLogKind==="text"?`${o.length} visible raw line(s) from file fallback`:`${r.length} visible structured line(s)`})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.daemon?"Hide":"Show"})]}),t.daemon&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.daemonLoading&&r.length===0&&o.length===0&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),e.daemonLogKind==="text"&&o.length===0&&e.daemonRawText&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:d==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),e.daemonLogKind==="structured"&&r.length===0&&e.daemonLogs.length>0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),e.daemonLogKind==="text"&&o.map((u,m)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:u},`raw-${m}`)),e.daemonLogKind!=="text"&&r.map((u,m)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${vl(u.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(u.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:u.level==="error"?"ERR":u.level==="warn"?"WRN":u.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:u.message})]},`log-${m}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>n(u=>({...u,trace:!u.trace})),children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Raw source · daemon trace",e.traceCategory==="session_host"?" · session_host only":""]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[i.length," visible trace event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.trace?"Hide":"Show"})]}),t.trace&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.traceLoading&&i.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&i.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&i.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:p.trim()?"No trace entries match the current search.":e.traceCategory==="session_host"?"No session_host trace entries yet. This filter uses get_debug_trace(category=session_host).":"No trace entries yet. Run daemon with --dev or --trace."}),i.map(u=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${vl(u.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),s.jsx("span",{children:u.level.toUpperCase()}),s.jsxs("span",{children:[u.category,".",u.stage]}),u.interactionId&&s.jsxs("span",{children:["ix=",u.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:ra(u.payload,360)||"No payload"})]},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>n(u=>({...u,web:!u.web})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · browser debug events"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[c.length," visible browser event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.web?"Hide":"Show"})]}),t.web&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[c.length===0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:p.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),c.map(u=>s.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),s.jsx("span",{children:u.kind}),u.topic&&s.jsxs("span",{children:["topic=",u.topic]}),u.interactionId&&s.jsxs("span",{children:["ix=",u.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:ra(u.payload,360)||"No payload"})]},u.id))]})]})]})}function bL({machineId:e,sendDaemonCommand:t}){const n=QI({machineId:e,sendDaemonCommand:t}),[a,r]=l.useState("info"),[o,i]=l.useState(""),[c,d]=l.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),p=l.useRef(null),u=l.useRef(!1),m=l.useMemo(()=>cL({daemonLogs:n.daemonLogs,daemonRawText:n.daemonRawText,daemonLogKind:n.daemonLogKind,debugTrace:n.debugTrace,webEvents:n.webEvents,traceCategory:n.traceCategory,quickFilter:a,searchQuery:o,daemonLoading:n.daemonLoading,traceLoading:n.traceLoading,daemonFetchError:n.daemonFetchError,traceFetchError:n.traceFetchError}),[a,o,n.daemonFetchError,n.daemonLoading,n.daemonLogKind,n.daemonLogs,n.daemonRawText,n.debugTrace,n.traceCategory,n.traceFetchError,n.traceLoading,n.webEvents]);l.useEffect(()=>{if(n.autoRefresh&&m.diagnosticEvents.length>0){const k=u.current?"smooth":"instant";setTimeout(()=>{var h;(h=p.current)==null||h.scrollIntoView({behavior:k}),u.current=!0},50)}},[m.diagnosticEvents.length,n.autoRefresh]);const f=l.useCallback(async()=>{var h;const k=YI({daemonLogs:m.visibleDaemonLogs,daemonRawLines:m.visibleDaemonRawLines,trace:m.visibleTraceEntries,webEvents:m.visibleWebEvents});if(!k.trim()){ft.showToast("No visible logs to copy.","info");return}try{await((h=navigator.clipboard)==null?void 0:h.writeText(k)),ft.showToast("Copied visible logs to clipboard.","success")}catch(x){ft.showToast(x instanceof Error?x.message:"Could not copy visible logs","warning")}},[m.visibleDaemonLogs,m.visibleDaemonRawLines,m.visibleTraceEntries,m.visibleWebEvents]),g=l.useCallback(async()=>{var h;const k=oL({events:m.diagnosticEvents,summary:m.diagnosticsSummary,sources:m.sourceStates});try{await((h=navigator.clipboard)==null?void 0:h.writeText(k)),ft.showToast("Copied diagnostic bundle to clipboard.","success")}catch(x){ft.showToast(x instanceof Error?x.message:"Could not copy diagnostic bundle","warning")}},[m.diagnosticEvents,m.diagnosticsSummary,m.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(pL,{quickFilter:a,quickFilterCounts:m.quickFilterCounts,searchQuery:o,autoRefresh:n.autoRefresh,onQuickFilterChange:r,onSearchQueryChange:i,onCopyDiagnostics:()=>{g()},onCopyVisible:()=>{f()},onToggleAutoRefresh:()=>n.setAutoRefresh(k=>!k),onRefresh:n.refresh,onClear:n.clear}),s.jsx(mL,{logLevel:n.logLevel,traceCategory:n.traceCategory,onLogLevelChange:n.setLogLevel,onTraceCategoryChange:n.setTraceCategory}),s.jsx(hL,{diagnosticsSummary:m.diagnosticsSummary,diagnosticEventsCount:m.diagnosticEvents.length,sourceStates:m.sourceStates,searchQuery:o,lastUpdatedAt:n.lastUpdatedAt,autoRefresh:n.autoRefresh,daemonFetchError:n.daemonFetchError,traceFetchError:n.traceFetchError}),s.jsx(fL,{patterns:m.diagnosticsSummary.repeatedPatterns}),s.jsx(gL,{streams:n,sectionsOpen:c,setSectionsOpen:d,diagnosticEvents:m.diagnosticEvents,visibleDaemonLogs:m.visibleDaemonLogs,visibleDaemonRawLines:m.visibleDaemonRawLines,visibleTraceEntries:m.visibleTraceEntries,visibleWebEvents:m.visibleWebEvents,quickFilter:a,searchQuery:o}),s.jsx("div",{ref:p})]})}function xL(e){return e.diagnostics?{label:"Managed",toneClass:"bg-green-500/[0.08] text-green-500"}:e.loading||e.refreshing?{label:"Checking…",toneClass:"bg-sky-500/[0.08] text-sky-400"}:e.error?{label:"Diagnostics issue",toneClass:"bg-amber-500/[0.08] text-amber-400"}:{label:"Unavailable",toneClass:"bg-red-500/[0.08] text-red-400"}}function Jf(e){const t=typeof(e==null?void 0:e.runtimeRecoveryState)=="string"?String(e.runtimeRecoveryState).trim():"";return t?t==="auto_resumed"?"restored after restart":t==="resume_failed"?"restore failed":t==="host_restart_interrupted"?"host restart interrupted":t==="orphan_snapshot"?"snapshot recovered":t.replace(/_/g," "):null}function vL(e){var r;const t=[],n=[],a=[];for(const o of e||[]){const i=String((o==null?void 0:o.lifecycle)||"").trim(),c=Jf((o==null?void 0:o.meta)||void 0),d=((r=o==null?void 0:o.meta)==null?void 0:r.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(i)?t.push(o):(i==="stopped"||i==="failed")&&(d||c)?n.push(o):a.push(o)}return{liveRuntimes:t,recoverySnapshots:n,inactiveRecords:a}}function yL(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Mi(e){return e==="live"?"These runtimes are live now and are the only attachable targets.":e==="recovery"?"These records were restored from session-host state and are not live attach targets until you explicitly recover or restart them.":"These inactive records are shown for reference and usually need restart before they are useful again."}function Pi(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Di(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function zu(e){if(!e)return"unknown";const t=Date.now()-e,n=Math.max(0,Math.round(t/1e3));if(n<60)return`${n}s ago`;const a=Math.round(n/60);if(a<60)return`${a}m ago`;const r=Math.round(a/60);return r<48?`${r}h ago`:`${Math.round(r/24)}d ago`}function wL(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function kL(e){switch(e){case"running":return"bg-green-500/[0.08] text-green-500";case"starting":return"bg-sky-500/[0.08] text-sky-400";case"stopping":return"bg-orange-500/[0.08] text-orange-400";case"interrupted":return"bg-amber-500/[0.08] text-amber-400";case"failed":return"bg-red-500/[0.08] text-red-500";default:return"bg-bg-glass text-text-muted"}}function SL(e){var n;const t=new Map;for(const a of e){if(!["starting","running","stopping","interrupted"].includes(a.lifecycle))continue;const r=typeof((n=a.meta)==null?void 0:n.providerSessionId)=="string"?String(a.meta.providerSessionId).trim():"";if(!r)continue;const o=`${a.providerType}::${a.workspace}::${r}`;t.set(o,(t.get(o)||0)+1)}return Array.from(t.values()).filter(a=>a>1).length}function CL({machineId:e,cliSessions:t,sendDaemonCommand:n}){const[a,r]=l.useState(""),[o,i]=l.useState(null),[c,d]=l.useState(!1),p=q1(e,{enabled:!!e,includeSessions:!0,limit:xd,intervalMs:KS}),u=p.diagnostics,m=p.loading,f=p.applyDiagnostics,g=l.useMemo(()=>xL({diagnostics:u,loading:m,refreshing:c,error:a}),[u,m,c,a]),k=l.useMemo(()=>new Map(t.map(I=>[I.sessionId||I.id,I])),[t]),h=l.useCallback(async()=>{if(e){d(!0);try{const I=await n(e,"session_host_get_diagnostics",{includeSessions:!0,limit:xd}),D=Pi(I);if(!(D!=null&&D.success))throw new Error((D==null?void 0:D.error)||"Could not load hosted runtime diagnostics");f(D.diagnostics||D.result||null),r("")}catch(I){const D=I instanceof Error?I.message:"Could not load hosted runtime diagnostics";r(D)}finally{d(!1)}}},[f,e,n]);l.useEffect(()=>{!e||u||m||c||h()},[u,m,e,h,c]);const x=l.useCallback(async(I,D)=>{const M=`${I}:${D.sessionId}`;if(!(I==="session_host_stop_session"&&!window.confirm(`Stop ${D.displayName}?
|
|
113
113
|
This will terminate the hosted runtime.`))){i(M);try{const E=await n(e,I,{sessionId:D.sessionId}),P=Pi(E);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Session host action failed");const B=I==="session_host_resume_session"?"resumed":I==="session_host_restart_session"?"restarted":"stopped";ft.showToast(`Session host ${B}: ${D.displayName}`,"success"),await h()}catch(E){const P=E instanceof Error?E.message:"Session host action failed";ft.showToast(P,"warning"),r(P)}finally{i(E=>E===M?null:E)}}},[e,h,n]),S=l.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
|
|
114
|
-
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){i("session_host_prune_duplicate_sessions");try{const D=await n(e,"session_host_prune_duplicate_sessions",{}),M=Pi(D);if(!(M!=null&&M.success))throw new Error((M==null?void 0:M.error)||"Duplicate prune failed");const E=M.result||{},P=Array.isArray(E.prunedSessionIds)?E.prunedSessionIds.length:0,B=typeof E.duplicateGroupCount=="number"?E.duplicateGroupCount:0;ft.showToast(`Pruned ${P} duplicate runtime(s) across ${B} group(s)`,"success"),await h()}catch(D){const M=D instanceof Error?D.message:"Duplicate prune failed";ft.showToast(M,"warning"),r(M)}finally{i(D=>D==="session_host_prune_duplicate_sessions"?null:D)}}},[e,h,n]),b=l.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((I,D)=>(D.lastActivityAt||0)-(I.lastActivityAt||0)),[u==null?void 0:u.sessions]),w=l.useMemo(()=>u!=null&&u.liveRuntimes||u!=null&&u.recoverySnapshots||u!=null&&u.inactiveRecords?{liveRuntimes:(u==null?void 0:u.liveRuntimes)||[],recoverySnapshots:(u==null?void 0:u.recoverySnapshots)||[],inactiveRecords:(u==null?void 0:u.inactiveRecords)||[]}:vL(b),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,b]),C=w.liveRuntimes,v=w.recoverySnapshots,y=w.inactiveRecords,j=l.useMemo(()=>SL(C),[C]),N=l.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),T=l.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(I=>I.level==="warn"||I.level==="error")||null,[u==null?void 0:u.recentLogs]),A=(I,D)=>{var L;const M=o===`session_host_resume_session:${I.sessionId}`,E=o===`session_host_restart_session:${I.sessionId}`,P=o===`session_host_stop_session:${I.sessionId}`,B=Jf(I.meta),R=k.get(I.sessionId),W=I.attachedClients.length===1?"1 client":`${I.attachedClients.length} clients`,_=D==="recovery"?"Recover":"Resume",H=yL(D);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:I.displayName||(R==null?void 0:R.cliName)||I.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${kL(I.lifecycle)}`,children:I.lifecycle}),B&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:B})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:I.workspaceLabel||(R==null?void 0:R.runtimeWorkspaceLabel)||I.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:I.runtimeKey}),I.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",I.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((L=I.writeOwner)==null?void 0:L.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:wL(I.writeOwner)}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[s.jsx(ib,{size:11})," ",W]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",zu(I.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",H]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[D==="recovery"&&(I.lifecycle==="interrupted"||I.lifecycle==="failed"||I.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{x("session_host_resume_session",I)},children:M?`${_}ing…`:_}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{x("session_host_restart_session",I)},children:E?"Restarting…":"Restart"}),D==="live"&&(I.lifecycle==="running"||I.lifecycle==="starting"||I.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!o,onClick:()=>{x("session_host_stop_session",I)},children:P?"Stopping…":"Stop"})]})]})},I.sessionId)};return s.jsxs(vs,{padding:"lg",className:"mb-5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(sn,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Cj()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[j>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{S()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${j})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${g.toneClass}`,children:g.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{h()},disabled:m||c,children:[s.jsx(uo,{size:13}),m||c?"Refreshing…":"Refresh"]})]})]}),a&&!u&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(Is,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:a})]})]})}),u&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:v.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:zu(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Di(u.hostStartedAt)})]})]}),T&&s.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[s.jsx(Is,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:T.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Di(T.timestamp),T.sessionId?` · ${T.sessionId}`:""]})]}),s.jsxs("div",{className:"mb-4 space-y-4",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(_l,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Mi("live")}),C.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):s.jsx("div",{className:"space-y-2",children:C.map(I=>A(I,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(sn,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Mi("recovery")}),v.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):s.jsx("div",{className:"space-y-2",children:v.map(I=>A(I,"recovery"))})]}),y.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Mi("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:y.map(I=>A(I,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),N.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:N.map(I=>{var M;const D=b.find(E=>E.sessionId===I.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(D==null?void 0:D.displayName)||((M=k.get(I.sessionId))==null?void 0:M.cliName)||I.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[I.action,I.lifecycle?` · ${I.lifecycle}`:"",I.detail?` · ${I.detail}`:"",I.error?` · ${I.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${I.success===!1?"text-red-300":"text-text-secondary"}`,children:Di(I.timestamp)})]},`${I.sessionId}:${I.timestamp}:${I.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:u.endpoint||"unknown"}),a?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",a]}):null]})]})]})}function jL({machine:e,launchPick:t,actions:n}){const{t:a}=ke("common"),{runLaunchCliCore:r,setLaunchPick:o}=n;return l.useEffect(()=>{const i=c=>{c.key==="Escape"&&o(null)};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[o]),s.jsx(Vt,{children:s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] 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",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",onClick:()=>o(null),children:s.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",onClick:i=>i.stopPropagation(),children:[s.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),s.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),s.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?s.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(i=>s.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-accent-primary/10 transition-colors",onClick:()=>{o(null),r({cliType:t.cliType,workspaceId:i.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{o(null),r({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:a("newSession.defaultWorkspace")}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{o(null),r({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:a("newSession.homeDirectory")}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>o(null),children:"Cancel"})]})]})})})}function NL(e,t){const n=v1(e),a=Qs(e,t),r=So(e,a),o=Pa(e,a),i=xh(e,{targetVersion:a,required:o,fallback:"Update daemon"});return r?{visible:!0,showButton:!0,title:o?"Daemon update required":"Version mismatch detected",description:o?"This machine is on an incompatible daemon version. Update it before starting more sessions.":n==="preview"?"This machine can be upgraded to the current preview daemon without opening a remote shell.":"This machine is running a different daemon version than the current app. Update it before starting more sessions.",buttonLabel:i,targetVersion:a,channel:n,required:o,tone:"warn"}:n==="preview"?{visible:!0,showButton:!1,title:a?"Preview daemon is up to date":"Preview update status unknown",description:a?"This machine is already on the current preview daemon target.":"The app is connected to preview, but the server did not report a preview target version yet.",buttonLabel:i,targetVersion:a,channel:n,required:!1,tone:a?"good":"info"}:{visible:!1,showButton:!1,title:"",description:"",buttonLabel:i,targetVersion:a,channel:n,required:!1,tone:"info"}}function Ii({icon:e,children:t}){return s.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,s.jsx("span",{children:t})]})}function Li({children:e,className:t=""}){return s.jsx("div",{className:`rounded-2xl border border-border-subtle bg-bg-surface/70 backdrop-blur-sm p-3 ${t}`,children:e})}function AL({machineEntry:e,providers:t,recentLaunches:n,currentConversations:a,onUpgradeDaemon:r,onOpenRecent:o,onOpenConversation:i}){const{t:c}=ke("common"),d=a.slice(0,6),p=n.slice(0,4),m=NL(e,"1.0.53");return s.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ii,{icon:s.jsx(Ds,{size:13}),children:c("machine.commandCenter.currentChats")}),s.jsx(Li,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(f=>{const g=ul(f);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>i(f),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate min-w-0 group-hover:text-accent-primary transition-colors",children:kt(f)}),g>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:qa(g)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:sa(f)})]},f.tabKey)})})})]}),p.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ii,{icon:s.jsx(Cp,{size:13}),children:c("machine.commandCenter.recentLaunches")}),s.jsx(Li,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:p.map(f=>{const{metaText:g,updatedLabel:k}=Uh(f);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>o(f),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate min-w-0 group-hover:text-accent-primary transition-colors",children:f.label}),k&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:k})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:g})]},f.id)})})})]}),m.visible&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ii,{icon:s.jsx(Is,{size:13}),children:c("machine.commandCenter.daemonUpdate")}),s.jsx(Li,{className:m.tone==="good"?"border-emerald-500/20 bg-emerald-500/5":m.tone==="info"?"border-sky-500/20 bg-sky-500/5":"border-amber-500/20 bg-amber-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:m.title}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[m.description,m.targetVersion&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",m.targetVersion,m.channel?` (${m.channel})`:""]})]}),m.showButton?s.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:r,children:[s.jsx(uo,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:m.buttonLabel})]}):s.jsx("div",{className:m.tone==="good"?"text-xs font-medium text-emerald-300":"text-xs font-medium text-sky-300",children:"No preview update action is needed."})]})})]})]})}function TL({machineId:e,machine:t,ideSessions:n,cliSessions:a,acpSessions:r,actions:o,sendDaemonCommand:i}){const{workspaceBusy:c,handleWorkspaceAdd:d,handleWorkspaceRemove:p,handleWorkspaceSetDefault:u}=o,{t:m}=ke("common"),[f,g]=l.useState(!1),[k,h]=l.useState(""),[x,S]=l.useState([]),[b,w]=l.useState(!1),[C,v]=l.useState(""),y=l.useCallback(async N=>{w(!0),v("");try{const T=await uc(i,e,N);h(T.path),S(T.directories)}catch(T){v(T instanceof Error?T.message:"Could not load folder")}finally{w(!1)}},[e,i]),j=l.useCallback(()=>{g(!0);const N=[...n.map(A=>A.workspace),...a.map(A=>A.workspace),...r.map(A=>A.workspace)],T=dc(t.platform,cc(N,t.defaultWorkspacePath,(t.workspaces||[]).map(A=>A.path)));y(T)},[r,a,n,y,t.defaultWorkspacePath,t.platform,t.workspaces]);return s.jsxs(s.Fragment,{children:[s.jsxs(vs,{padding:"lg",className:"mb-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(An,{size:14})," Workspaces"]}),s.jsx("button",{type:"button",className:"btn bg-bg-glass hover:bg-bg-glass-hover text-text-muted hover:text-text-primary px-3 py-1 rounded transition-colors text-xs",disabled:c,onClick:j,children:"+ Add workspace"})]}),(t.workspaces||[]).length===0?s.jsxs("div",{className:"text-[11px] text-text-muted py-4 text-center",children:["No saved workspaces yet. Click ",s.jsx("span",{className:"text-text-secondary",children:"+ Add workspace"})," to pick a folder."]}):s.jsx("ul",{className:"space-y-1.5 max-h-72 overflow-y-auto",children:(t.workspaces||[]).map(N=>{const T=N.id===t.defaultWorkspaceId;return s.jsxs("li",{className:`flex items-start gap-2 text-[11px] rounded-lg border px-2.5 py-2 transition-colors ${T?"border-yellow-500/30 bg-yellow-500/[0.05]":"border-border-subtle bg-bg-primary"}`,children:[s.jsx("button",{type:"button",title:T?"Default workspace — click to unset":"Set as default workspace",disabled:c,onClick:()=>void u(T?null:N.id),className:`text-base leading-none shrink-0 transition-colors ${T?"text-yellow-400 hover:text-yellow-300":"text-text-muted/40 hover:text-yellow-400"}`,children:"★"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"font-medium text-text-primary truncate",children:rm(N.path,N.label)}),s.jsx("div",{className:"font-mono text-text-muted truncate text-[10px]",title:N.path,children:N.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void p(N.id),children:m("machine.managedWorkspaces.remove")})]},N.id)})})]}),f&&s.jsx(mc,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:k,directories:x,busy:b,error:C,confirmLabel:"Add workspace",onClose:()=>g(!1),onNavigate:N=>{y(N)},onConfirm:N=>{(async()=>{if(!N)return;await d(N)&&g(!1)})()}})]})}function ML({machine:e,machineId:t,ideSessions:n,cliSessions:a,acpSessions:r,actions:o,sendDaemonCommand:i}){return s.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[s.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-border-subtle mb-4",children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspaces"}),s.jsx("div",{className:"text-sm text-text-secondary",children:'Save folders as workspaces on this machine. Use the dashboard "+" button to launch a session.'})]}),i&&s.jsx(TL,{machineId:t,machine:e,ideSessions:n,cliSessions:a,acpSessions:r,actions:o,sendDaemonCommand:i})]})}const PL="activate_provider_updates";function Xf(e){if(!e||typeof e!="object")return;const t=e;return"result"in t&&t.result&&typeof t.result=="object"?t.result:t}function DL(e){var r;const t=Xf(e);if(!t)return{ok:!1,error:"empty response"};if(t.success===!1)return{ok:!1,error:typeof t.error=="string"&&t.error.trim()?t.error:"sync failed"};const n=t.channelSync;if(n&&typeof n=="object"&&n.status==="error"){const o=Array.isArray(n.errors)?(r=n.errors[0])==null?void 0:r.message:void 0;return{ok:!1,error:typeof o=="string"&&o.trim()?o:"channel sync failed"}}return{ok:!0,activatedCount:Array.isArray(t.activated)?t.activated.length:0}}function IL(e){const t=[];for(const n of(e==null?void 0:e.newTypes)??[])typeof n=="string"&&n.trim()&&t.push(n.trim());return t}function LL({onNicknameSynced:e}={}){var se,te,ue,ye,Me,re,ce,Ae,be,we,_e;const{t}=ke("common"),{id:n}=Eg(),a=oa(),r=Pl(),{sendCommand:o}=St(),i=ca(),c=Sh(),d=zm(),p=d.ides||[],u=d.initialLoaded??!0,m=p.find(U=>U.id===n&&U.type==="adhdev-daemon"),f=p.some(U=>U.type==="adhdev-daemon"),g=n?(se=d.connectionRetryStatuses)==null?void 0:se[n]:void 0,k=!!(g!=null&&g.blocked),[h,x]=l.useState("workspace"),[S,b]=l.useState(null),[w,C]=l.useState(!1),[v,y]=l.useState(0),[j,N]=l.useState(null);l.useCallback((U,Ne)=>{N({daemonId:U,workspace:Ne})},[]);const[,T]=l.useState("ide"),A=l.useRef(null),[I,D]=l.useState(null),M=l.useRef("__home__"),[E,P]=l.useState("__home__"),[B,R]=l.useState(!1),W=l.useRef(null);l.useEffect(()=>{!n||!m||!(!m.workspaces||!m.availableProviders||!m.detectedIdes||!m.recentLaunches)||i(n,{minFreshMs:3e4}).catch(()=>{})},[i,m,n]);const _=l.useCallback(U=>{const Ne=Xf(U),Ie=Ne==null?void 0:Ne.providerChannelStaleness;Ie&&!Ie.error&&b({staleTypes:Array.isArray(Ie.staleTypes)?Ie.staleTypes:[],newTypes:Array.isArray(Ie.newTypes)?Ie.newTypes:[]})},[]);l.useEffect(()=>{if(!n||!m)return;let U=!1;return(async()=>{try{const Ne=await o(n,"get_status_metadata");U||_(Ne)}catch{}})(),()=>{U=!0}},[_,n,m==null?void 0:m.id,o]);const H=l.useCallback(async U=>{if(U.preventDefault(),U.stopPropagation(),!(!n||w)){x("providers"),C(!0);try{const Ne=IL(S),Ie=await o(n,PL,Ne.length>0?{types:Ne}:{}),We=DL(Ie);"error"in We?ft.showToast(t("machine.detail.providerSyncFailed",{error:We.error}),"warning"):ft.showToast(We.activatedCount>0?t("machine.detail.providerSyncSuccess",{count:We.activatedCount}):t("machine.detail.providerSyncAlreadyCurrent"),"success"),y(Xe=>Xe+1);try{_(await o(n,"get_status_metadata"))}catch{}}catch(Ne){const Ie=Ne instanceof Error?Ne.message:String(Ne);ft.showToast(t("machine.detail.providerSyncFailed",{error:Ie}),"warning")}finally{C(!1)}}},[_,n,S,w,o,t]);l.useEffect(()=>{if(!n||!m||h!=="overview"&&h!=="providers")return;const U=m.machine;(typeof(U==null?void 0:U.cpus)!="number"||typeof(U==null?void 0:U.totalMem)!="number"||typeof(U==null?void 0:U.arch)!="string"||typeof(U==null?void 0:U.release)!="string"||h==="providers"&&!(U!=null&&U.quota))&&c(n,{minFreshMs:3e4}).catch(()=>{})},[h,c,m,n]),G1(n&&h==="overview"?[n]:[],{enabled:h==="overview",intervalMs:GS});const L=()=>{if(f){a("/dashboard",{state:{mobileSection:"machines"}});return}a("/machines")},F=wI({machineId:n,registeredMachineId:(m==null?void 0:m.machineId)||null,sendDaemonCommand:o,onNicknameSynced:e,logsEndRef:W});l.useEffect(()=>ft.onToast(Ne=>{d.setToasts(We=>{if(We.some(J=>J.message===Ne.message&&Ne.timestamp-J.timestamp<3e3))return We;const et={id:Ne.id,message:Ne.message,type:Ne.type,timestamp:Ne.timestamp,targetKey:Ne.targetKey,actions:Ne.actions};return[...We.slice(-4),et]});const Ie=Ne.duration||5e3;setTimeout(()=>d.setToasts(We=>We.filter(Xe=>Xe.id!==Ne.id)),Ie)}),[d]);const $=(m==null?void 0:m.availableProviders)||[],K={};for(const U of $)K[U.type]=U.icon;const z=m?{id:m.id,hostname:om(m,{fallbackId:m.id}),platform:((te=m.machine)==null?void 0:te.platform)||"unknown",arch:((ue=m.machine)==null?void 0:ue.arch)||"",cpus:((ye=m.machine)==null?void 0:ye.cpus)||0,totalMem:((Me=m.machine)==null?void 0:Me.totalMem)||0,freeMem:(re=m.machine)==null?void 0:re.freeMem,availableMem:(ce=m.machine)==null?void 0:ce.availableMem,loadavg:(Ae=m.machine)==null?void 0:Ae.loadavg,uptime:(be=m.machine)==null?void 0:be.uptime,release:((we=m.machine)==null?void 0:we.release)||"",cdpConnected:!!m.cdpConnected,machineNickname:m.machineNickname||null,...(_e=m.machine)!=null&&_e.quota?{quota:m.machine.quota}:{},p2p:m.p2p?{screenshotActive:!1,...m.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:m.detectedIdes||[],workspaces:m.workspaces||[],defaultWorkspaceId:m.defaultWorkspaceId??m.activeWorkspaceId??null,defaultWorkspacePath:m.defaultWorkspacePath??m.activeWorkspacePath??null}:null,ne=p.filter(U=>U.daemonId===n&&U.type!=="adhdev-daemon").filter(U=>!$a(U)&&!Jn(U)).map(U=>({id:U.id,sessionId:U.sessionId,type:U.type,version:U.version||"",instanceId:U.instanceId||"",status:U.status,workspace:U.workspace||null,terminals:U.terminals||0,aiAgents:X0(U.aiAgents||(U.agents||[]).map(Ne=>({id:Ne.name,name:Ne.name,status:Ne.status,version:Ne.version}))),activeChat:U.activeChat||null,chats:U.chats||[],childSessions:U.childSessions||[],cdpConnected:U.cdpConnected||!1,daemonId:n,lastMessageAt:U.lastMessageAt})),ie=p.filter(U=>U.daemonId===n&&$a(U)).map(U=>({id:U.id,sessionId:U.sessionId,type:U.type,cliName:U.cliName||U.type,status:U.status,workspace:U.workspace||"",activeChat:U.activeChat||null,providerSessionId:U.providerSessionId,mode:U.mode,runtimeKey:U.runtimeKey,runtimeDisplayName:U.runtimeDisplayName,runtimeWorkspaceLabel:U.runtimeWorkspaceLabel,runtimeWriteOwner:U.runtimeWriteOwner||null,runtimeAttachedClients:U.runtimeAttachedClients||[],daemonId:n,lastMessageAt:U.lastMessageAt})),Ce=p.filter(U=>U.daemonId===n&&Jn(U)).map(U=>({id:U.id,sessionId:U.sessionId,type:U.type,acpName:U.cliName||U.type,status:U.status,workspace:U.workspace||"",activeChat:U.activeChat||null,providerSessionId:U.providerSessionId,daemonId:n,lastMessageAt:U.lastMessageAt})),me=m?ds(m,{fallbackId:n}):"",O="workspace",Y=r.state,X=Y==null?void 0:Y.initialMachineTab,Q=Y==null?void 0:Y.initialWorkspaceCategory;Y==null||Y.initialWorkspaceId,Y==null||Y.initialWorkspacePath;const ve=X==="ides"||X==="clis"||X==="acps"?"workspace":X||O,he=X==="ides"?"ide":X==="clis"?"cli":X==="acps"?"acp":Q,Z=[...ne.map(U=>{var Ne;return{id:`ide:${U.type}:${U.workspace||""}`,label:((Ne=U.activeChat)==null?void 0:Ne.title)||U.type,kind:"ide",providerType:U.type,subtitle:U.workspace||void 0,workspace:U.workspace||void 0,lastLaunchedAt:U.lastMessageAt||0}}),...ie.map(U=>{var Ne;return{id:`cli:${U.type}:${U.workspace||""}`,label:((Ne=U.activeChat)==null?void 0:Ne.title)||U.cliName,kind:"cli",providerType:U.type,providerSessionId:U.providerSessionId,subtitle:U.workspace||void 0,workspace:U.workspace||void 0,lastLaunchedAt:U.lastMessageAt||0}}),...Ce.map(U=>{var Ne;return{id:`acp:${U.type}:${U.workspace||""}`,label:((Ne=U.activeChat)==null?void 0:Ne.title)||U.acpName,kind:"acp",providerType:U.type,providerSessionId:U.providerSessionId,subtitle:Tn(U.summaryMetadata)||U.workspace||void 0,workspace:U.workspace||void 0,lastLaunchedAt:U.lastMessageAt||0}})].sort((U,Ne)=>(Ne.lastLaunchedAt||0)-(U.lastLaunchedAt||0)),fe=((m==null?void 0:m.recentLaunches)||[]).length>0?((m==null?void 0:m.recentLaunches)||[]).map(U=>({id:U.id,label:U.title||U.providerName||U.providerType,kind:U.kind,providerType:U.providerType,providerSessionId:U.providerSessionId,subtitle:Tn(U.summaryMetadata)||U.workspace||void 0,workspace:U.workspace,summaryMetadata:U.summaryMetadata,lastLaunchedAt:U.lastLaunchedAt})):Z,V=l.useMemo(()=>{var Ne;const U=((Ne=d.connectionStates)==null?void 0:Ne[n||""])||void 0;return p.filter(Ie=>Ie.daemonId===n&&Ie.type!=="adhdev-daemon").flatMap(Ie=>nc(Ie,{connectionStates:n&&U?{[n]:U}:void 0,defaultConnectionState:U})).filter(Ie=>!(Ie.transport==="pty"&&Ie.mode==="terminal")).sort((Ie,We)=>ul(We)-ul(Ie))},[p,d.connectionStates,n]),q=l.useCallback(U=>{const Ne=_h(U);Ne&&a(Ba(Ne))},[a]),ee=l.useCallback(()=>{A.current&&(R(!0),A.current().finally(()=>{A.current=null,R(!1),D(null)}))},[]),pe=l.useCallback(U=>{if(!z)return;const{options:Ne,selectedKey:Ie}=Oh({machine:z,currentWorkspacePath:U.workspace,homeLabel:t("newSession.homeDirectory"),homeDescription:t("newSession.launchWithoutWorkspace")}),We=async()=>{T(U.kind),x("workspace")};A.current=async()=>{const Xe=Ne.find(Le=>Le.key===M.current),et=(Xe==null?void 0:Xe.workspacePath)??null,J=(Xe==null?void 0:Xe.workspaceId)??null;if(U.kind==="ide"&&U.providerType){await F.handleLaunchIde(U.providerType,et?{workspace:et}:void 0);return}if((U.kind==="cli"||U.kind==="acp")&&U.providerType){await F.runLaunchCliCore({cliType:U.providerType,dir:J?void 0:et||"",workspaceId:J||void 0,model:U.kind==="acp"&&lm(U.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:U.providerSessionId});return}await We()},M.current=Ie,P(Ie),D({title:U.kind==="ide"?qr(t,"restart-ide",U.label):U.providerSessionId?nh(t,U.label):qr(t,"start-fresh",U.label),description:U.kind==="ide"?zr(t,"restart-ide"):U.providerSessionId?ah(t):zr(t,"start-fresh"),confirmLabel:U.kind==="ide"?Kr(t,"restart-ide"):U.providerSessionId?rl(t,!0):Kr(t,"start-fresh"),busyLabel:U.kind==="ide"?Vr(t,"restart-ide"):U.providerSessionId?sh(t,!0):Vr(t,"start-fresh"),workspaceOptions:Ne,details:[{label:"Mode",value:U.kind.toUpperCase()},...U.providerType?[{label:"Provider",value:U.providerType}]:[]]})},[F,z]);if(l.useEffect(()=>{x(ve)},[O,ve,n]),l.useEffect(()=>{he&&T(he)},[he,n]),!z)return u?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:t("machine.detail.notFound")}),s.jsx("p",{className:"mt-3",children:t("machine.detail.offlineHint")}),s.jsx("button",{onClick:L,className:"machine-btn-back",children:t("machine.detail.back")})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:t("machine.detail.loading")})});const le=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(us,{size:14})," ",t("machine.detail.tabWorkspace")]}),count:ne.length+ie.length+Ce.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(sn,{size:14})," ",t("machine.detail.tabHostedRuntimes")]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Oa,{size:14})," ",t("machine.detail.tabProviders")]}),...S&&S.staleTypes.length+S.newTypes.length>0?{count:S.staleTypes.length+S.newTypes.length}:{}},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(mb,{size:14})," ",t("machine.detail.tabSystem")]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ll,{size:14})," ",t("machine.detail.tabLogs")]})}];return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-border-subtle",children:[s.jsx("div",{className:"flex items-center justify-between w-full",children:s.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[s.jsx("button",{onClick:L,className:"flex items-center justify-center w-8 h-8 rounded-full bg-bg-glass hover:bg-bg-glass-hover text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[F.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:F.nicknameInput,onChange:U=>F.setNicknameInput(U.target.value),onKeyDown:U=>{U.key==="Enter"&&F.handleSaveNickname(),U.key==="Escape"&&F.setEditingNickname(!1)},placeholder:t("machine.detail.nicknamePlaceholder"),className:"px-2.5 py-1 rounded-md border border-accent/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:F.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:t("machine.detail.save")}),s.jsx("button",{onClick:()=>F.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-bg-glass text-text-muted hover:bg-bg-glass-hover hover:text-text-primary text-sm font-medium transition-colors",children:t("machine.detail.cancel")})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{F.setEditingNickname(!0),F.setNicknameInput(z.machineNickname||"")},title:t("machine.detail.clickToSetNickname"),children:me}),k?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),d.retryConnection&&n&&s.jsx("button",{onClick:()=>d.retryConnection(n),className:"px-2.5 py-0.5 rounded text-[11px] font-semibold bg-red-500/10 border border-red-500/20 text-red-400 hover:bg-red-500/20 transition-colors",children:t("machine.detail.reconnect")})]}):s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[s.jsxs("span",{className:"font-mono bg-bg-glass px-1.5 py-0.5 rounded",children:[z.platform," · ",z.arch]}),s.jsx("span",{children:t("machine.detail.coresCount",{count:z.cpus})}),(m==null?void 0:m.version)&&s.jsxs("span",{children:["v",m.version]}),z.p2p.available&&s.jsx("span",{children:t("machine.detail.p2pState",{state:z.p2p.state==="connected"?t("machine.detail.p2pConnected"):z.p2p.state})}),z.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:z.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-border-subtle",children:le.map(U=>s.jsxs("button",{onClick:()=>x(U.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${h===U.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[U.label,U.count!==void 0&&U.id==="providers"&&S?s.jsx("span",{role:"button",title:t("machine.detail.providerStaleBadgeHint"),"aria-label":t("machine.detail.providerStaleBadgeHint"),onClick:H,className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 cursor-pointer ${w?"bg-amber-500/20 text-amber-300":"bg-amber-500/15 text-amber-400 hover:bg-amber-500/30"}`,children:w?"…":U.count}):U.count!==void 0?s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${h===U.id?"bg-accent-primary/20 text-accent-primary":"bg-bg-glass-hover text-text-muted"}`,children:U.count}):null]},U.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[h==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(AL,{machineEntry:m,providers:$,recentLaunches:fe,currentConversations:V,onUpgradeDaemon:async()=>{const U=Co(m);if(U)try{await o(n,"daemon_upgrade",U)}catch{}},onOpenRecent:pe,onOpenConversation:q}),s.jsx(ML,{machine:z,machineId:n,ideSessions:ne,cliSessions:ie,acpSessions:Ce,actions:F,sendDaemonCommand:o})]}),h==="providers"&&s.jsx(_I,{machineId:n,providers:$,sendDaemonCommand:o,quota:z.quota,refreshNonce:v}),h==="overview"&&s.jsx(SI,{machine:z,ideSessions:ne,cliSessions:ie,acpSessions:Ce}),h==="session-host"&&s.jsx(CL,{machineId:n,cliSessions:ie,sendDaemonCommand:o}),h==="logs"&&s.jsx(bL,{machineId:n,sendDaemonCommand:o})]})})}),F.launchPick&&z&&s.jsx(jL,{machine:z,launchPick:F.launchPick,actions:F}),I&&s.jsx(jo,{title:I.title,description:I.description,details:I.details,workspaceOptions:I.workspaceOptions,selectedWorkspaceKey:E,onWorkspaceChange:U=>{M.current=U,P(U)},confirmLabel:I.confirmLabel,busyLabel:I.busyLabel,busy:B,onConfirm:ee,onCancel:()=>{A.current=null,D(null)}}),j&&s.jsx(Yf,{daemonId:j.daemonId,workspace:j.workspace,onClose:()=>N(null)}),s.jsx(oh,{toasts:d.toasts||[],onDismiss:U=>d.setToasts(Ne=>Ne.filter(Ie=>Ie.id!==U)),onClickToast:U=>{U.targetKey&&a(Ba(U.targetKey))}}),s.jsx("style",{children:`
|
|
114
|
+
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){i("session_host_prune_duplicate_sessions");try{const D=await n(e,"session_host_prune_duplicate_sessions",{}),M=Pi(D);if(!(M!=null&&M.success))throw new Error((M==null?void 0:M.error)||"Duplicate prune failed");const E=M.result||{},P=Array.isArray(E.prunedSessionIds)?E.prunedSessionIds.length:0,B=typeof E.duplicateGroupCount=="number"?E.duplicateGroupCount:0;ft.showToast(`Pruned ${P} duplicate runtime(s) across ${B} group(s)`,"success"),await h()}catch(D){const M=D instanceof Error?D.message:"Duplicate prune failed";ft.showToast(M,"warning"),r(M)}finally{i(D=>D==="session_host_prune_duplicate_sessions"?null:D)}}},[e,h,n]),b=l.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((I,D)=>(D.lastActivityAt||0)-(I.lastActivityAt||0)),[u==null?void 0:u.sessions]),w=l.useMemo(()=>u!=null&&u.liveRuntimes||u!=null&&u.recoverySnapshots||u!=null&&u.inactiveRecords?{liveRuntimes:(u==null?void 0:u.liveRuntimes)||[],recoverySnapshots:(u==null?void 0:u.recoverySnapshots)||[],inactiveRecords:(u==null?void 0:u.inactiveRecords)||[]}:vL(b),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,b]),C=w.liveRuntimes,v=w.recoverySnapshots,y=w.inactiveRecords,j=l.useMemo(()=>SL(C),[C]),N=l.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),T=l.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(I=>I.level==="warn"||I.level==="error")||null,[u==null?void 0:u.recentLogs]),A=(I,D)=>{var L;const M=o===`session_host_resume_session:${I.sessionId}`,E=o===`session_host_restart_session:${I.sessionId}`,P=o===`session_host_stop_session:${I.sessionId}`,B=Jf(I.meta),R=k.get(I.sessionId),W=I.attachedClients.length===1?"1 client":`${I.attachedClients.length} clients`,_=D==="recovery"?"Recover":"Resume",H=yL(D);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:I.displayName||(R==null?void 0:R.cliName)||I.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${kL(I.lifecycle)}`,children:I.lifecycle}),B&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:B})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:I.workspaceLabel||(R==null?void 0:R.runtimeWorkspaceLabel)||I.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:I.runtimeKey}),I.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",I.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((L=I.writeOwner)==null?void 0:L.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:wL(I.writeOwner)}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[s.jsx(ib,{size:11})," ",W]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",zu(I.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",H]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[D==="recovery"&&(I.lifecycle==="interrupted"||I.lifecycle==="failed"||I.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{x("session_host_resume_session",I)},children:M?`${_}ing…`:_}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{x("session_host_restart_session",I)},children:E?"Restarting…":"Restart"}),D==="live"&&(I.lifecycle==="running"||I.lifecycle==="starting"||I.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!o,onClick:()=>{x("session_host_stop_session",I)},children:P?"Stopping…":"Stop"})]})]})},I.sessionId)};return s.jsxs(vs,{padding:"lg",className:"mb-5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(sn,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Cj()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[j>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{S()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${j})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${g.toneClass}`,children:g.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{h()},disabled:m||c,children:[s.jsx(uo,{size:13}),m||c?"Refreshing…":"Refresh"]})]})]}),a&&!u&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(Is,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:a})]})]})}),u&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:v.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:zu(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Di(u.hostStartedAt)})]})]}),T&&s.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[s.jsx(Is,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:T.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Di(T.timestamp),T.sessionId?` · ${T.sessionId}`:""]})]}),s.jsxs("div",{className:"mb-4 space-y-4",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(_l,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Mi("live")}),C.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):s.jsx("div",{className:"space-y-2",children:C.map(I=>A(I,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(sn,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Mi("recovery")}),v.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):s.jsx("div",{className:"space-y-2",children:v.map(I=>A(I,"recovery"))})]}),y.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Mi("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:y.map(I=>A(I,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),N.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:N.map(I=>{var M;const D=b.find(E=>E.sessionId===I.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(D==null?void 0:D.displayName)||((M=k.get(I.sessionId))==null?void 0:M.cliName)||I.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[I.action,I.lifecycle?` · ${I.lifecycle}`:"",I.detail?` · ${I.detail}`:"",I.error?` · ${I.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${I.success===!1?"text-red-300":"text-text-secondary"}`,children:Di(I.timestamp)})]},`${I.sessionId}:${I.timestamp}:${I.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:u.endpoint||"unknown"}),a?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",a]}):null]})]})]})}function jL({machine:e,launchPick:t,actions:n}){const{t:a}=ke("common"),{runLaunchCliCore:r,setLaunchPick:o}=n;return l.useEffect(()=>{const i=c=>{c.key==="Escape"&&o(null)};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[o]),s.jsx(Vt,{children:s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] 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",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",onClick:()=>o(null),children:s.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",onClick:i=>i.stopPropagation(),children:[s.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),s.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),s.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?s.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(i=>s.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-accent-primary/10 transition-colors",onClick:()=>{o(null),r({cliType:t.cliType,workspaceId:i.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{o(null),r({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:a("newSession.defaultWorkspace")}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{o(null),r({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:a("newSession.homeDirectory")}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>o(null),children:"Cancel"})]})]})})})}function NL(e,t){const n=v1(e),a=Qs(e,t),r=So(e,a),o=Pa(e,a),i=xh(e,{targetVersion:a,required:o,fallback:"Update daemon"});return r?{visible:!0,showButton:!0,title:o?"Daemon update required":"Version mismatch detected",description:o?"This machine is on an incompatible daemon version. Update it before starting more sessions.":n==="preview"?"This machine can be upgraded to the current preview daemon without opening a remote shell.":"This machine is running a different daemon version than the current app. Update it before starting more sessions.",buttonLabel:i,targetVersion:a,channel:n,required:o,tone:"warn"}:n==="preview"?{visible:!0,showButton:!1,title:a?"Preview daemon is up to date":"Preview update status unknown",description:a?"This machine is already on the current preview daemon target.":"The app is connected to preview, but the server did not report a preview target version yet.",buttonLabel:i,targetVersion:a,channel:n,required:!1,tone:a?"good":"info"}:{visible:!1,showButton:!1,title:"",description:"",buttonLabel:i,targetVersion:a,channel:n,required:!1,tone:"info"}}function Ii({icon:e,children:t}){return s.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,s.jsx("span",{children:t})]})}function Li({children:e,className:t=""}){return s.jsx("div",{className:`rounded-2xl border border-border-subtle bg-bg-surface/70 backdrop-blur-sm p-3 ${t}`,children:e})}function AL({machineEntry:e,providers:t,recentLaunches:n,currentConversations:a,onUpgradeDaemon:r,onOpenRecent:o,onOpenConversation:i}){const{t:c}=ke("common"),d=a.slice(0,6),p=n.slice(0,4),m=NL(e,"1.0.55");return s.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ii,{icon:s.jsx(Ds,{size:13}),children:c("machine.commandCenter.currentChats")}),s.jsx(Li,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(f=>{const g=ul(f);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>i(f),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate min-w-0 group-hover:text-accent-primary transition-colors",children:kt(f)}),g>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:qa(g)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:sa(f)})]},f.tabKey)})})})]}),p.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ii,{icon:s.jsx(Cp,{size:13}),children:c("machine.commandCenter.recentLaunches")}),s.jsx(Li,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:p.map(f=>{const{metaText:g,updatedLabel:k}=Uh(f);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>o(f),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate min-w-0 group-hover:text-accent-primary transition-colors",children:f.label}),k&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:k})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:g})]},f.id)})})})]}),m.visible&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ii,{icon:s.jsx(Is,{size:13}),children:c("machine.commandCenter.daemonUpdate")}),s.jsx(Li,{className:m.tone==="good"?"border-emerald-500/20 bg-emerald-500/5":m.tone==="info"?"border-sky-500/20 bg-sky-500/5":"border-amber-500/20 bg-amber-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:m.title}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[m.description,m.targetVersion&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",m.targetVersion,m.channel?` (${m.channel})`:""]})]}),m.showButton?s.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:r,children:[s.jsx(uo,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:m.buttonLabel})]}):s.jsx("div",{className:m.tone==="good"?"text-xs font-medium text-emerald-300":"text-xs font-medium text-sky-300",children:"No preview update action is needed."})]})})]})]})}function TL({machineId:e,machine:t,ideSessions:n,cliSessions:a,acpSessions:r,actions:o,sendDaemonCommand:i}){const{workspaceBusy:c,handleWorkspaceAdd:d,handleWorkspaceRemove:p,handleWorkspaceSetDefault:u}=o,{t:m}=ke("common"),[f,g]=l.useState(!1),[k,h]=l.useState(""),[x,S]=l.useState([]),[b,w]=l.useState(!1),[C,v]=l.useState(""),y=l.useCallback(async N=>{w(!0),v("");try{const T=await uc(i,e,N);h(T.path),S(T.directories)}catch(T){v(T instanceof Error?T.message:"Could not load folder")}finally{w(!1)}},[e,i]),j=l.useCallback(()=>{g(!0);const N=[...n.map(A=>A.workspace),...a.map(A=>A.workspace),...r.map(A=>A.workspace)],T=dc(t.platform,cc(N,t.defaultWorkspacePath,(t.workspaces||[]).map(A=>A.path)));y(T)},[r,a,n,y,t.defaultWorkspacePath,t.platform,t.workspaces]);return s.jsxs(s.Fragment,{children:[s.jsxs(vs,{padding:"lg",className:"mb-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(An,{size:14})," Workspaces"]}),s.jsx("button",{type:"button",className:"btn bg-bg-glass hover:bg-bg-glass-hover text-text-muted hover:text-text-primary px-3 py-1 rounded transition-colors text-xs",disabled:c,onClick:j,children:"+ Add workspace"})]}),(t.workspaces||[]).length===0?s.jsxs("div",{className:"text-[11px] text-text-muted py-4 text-center",children:["No saved workspaces yet. Click ",s.jsx("span",{className:"text-text-secondary",children:"+ Add workspace"})," to pick a folder."]}):s.jsx("ul",{className:"space-y-1.5 max-h-72 overflow-y-auto",children:(t.workspaces||[]).map(N=>{const T=N.id===t.defaultWorkspaceId;return s.jsxs("li",{className:`flex items-start gap-2 text-[11px] rounded-lg border px-2.5 py-2 transition-colors ${T?"border-yellow-500/30 bg-yellow-500/[0.05]":"border-border-subtle bg-bg-primary"}`,children:[s.jsx("button",{type:"button",title:T?"Default workspace — click to unset":"Set as default workspace",disabled:c,onClick:()=>void u(T?null:N.id),className:`text-base leading-none shrink-0 transition-colors ${T?"text-yellow-400 hover:text-yellow-300":"text-text-muted/40 hover:text-yellow-400"}`,children:"★"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"font-medium text-text-primary truncate",children:rm(N.path,N.label)}),s.jsx("div",{className:"font-mono text-text-muted truncate text-[10px]",title:N.path,children:N.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void p(N.id),children:m("machine.managedWorkspaces.remove")})]},N.id)})})]}),f&&s.jsx(mc,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:k,directories:x,busy:b,error:C,confirmLabel:"Add workspace",onClose:()=>g(!1),onNavigate:N=>{y(N)},onConfirm:N=>{(async()=>{if(!N)return;await d(N)&&g(!1)})()}})]})}function ML({machine:e,machineId:t,ideSessions:n,cliSessions:a,acpSessions:r,actions:o,sendDaemonCommand:i}){return s.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[s.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-border-subtle mb-4",children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspaces"}),s.jsx("div",{className:"text-sm text-text-secondary",children:'Save folders as workspaces on this machine. Use the dashboard "+" button to launch a session.'})]}),i&&s.jsx(TL,{machineId:t,machine:e,ideSessions:n,cliSessions:a,acpSessions:r,actions:o,sendDaemonCommand:i})]})}const PL="activate_provider_updates";function Xf(e){if(!e||typeof e!="object")return;const t=e;return"result"in t&&t.result&&typeof t.result=="object"?t.result:t}function DL(e){var r;const t=Xf(e);if(!t)return{ok:!1,error:"empty response"};if(t.success===!1)return{ok:!1,error:typeof t.error=="string"&&t.error.trim()?t.error:"sync failed"};const n=t.channelSync;if(n&&typeof n=="object"&&n.status==="error"){const o=Array.isArray(n.errors)?(r=n.errors[0])==null?void 0:r.message:void 0;return{ok:!1,error:typeof o=="string"&&o.trim()?o:"channel sync failed"}}return{ok:!0,activatedCount:Array.isArray(t.activated)?t.activated.length:0}}function IL(e){const t=[];for(const n of(e==null?void 0:e.newTypes)??[])typeof n=="string"&&n.trim()&&t.push(n.trim());return t}function LL({onNicknameSynced:e}={}){var se,te,ue,ye,Me,re,ce,Ae,be,we,_e;const{t}=ke("common"),{id:n}=Eg(),a=oa(),r=Pl(),{sendCommand:o}=St(),i=ca(),c=Sh(),d=zm(),p=d.ides||[],u=d.initialLoaded??!0,m=p.find(U=>U.id===n&&U.type==="adhdev-daemon"),f=p.some(U=>U.type==="adhdev-daemon"),g=n?(se=d.connectionRetryStatuses)==null?void 0:se[n]:void 0,k=!!(g!=null&&g.blocked),[h,x]=l.useState("workspace"),[S,b]=l.useState(null),[w,C]=l.useState(!1),[v,y]=l.useState(0),[j,N]=l.useState(null);l.useCallback((U,Ne)=>{N({daemonId:U,workspace:Ne})},[]);const[,T]=l.useState("ide"),A=l.useRef(null),[I,D]=l.useState(null),M=l.useRef("__home__"),[E,P]=l.useState("__home__"),[B,R]=l.useState(!1),W=l.useRef(null);l.useEffect(()=>{!n||!m||!(!m.workspaces||!m.availableProviders||!m.detectedIdes||!m.recentLaunches)||i(n,{minFreshMs:3e4}).catch(()=>{})},[i,m,n]);const _=l.useCallback(U=>{const Ne=Xf(U),Ie=Ne==null?void 0:Ne.providerChannelStaleness;Ie&&!Ie.error&&b({staleTypes:Array.isArray(Ie.staleTypes)?Ie.staleTypes:[],newTypes:Array.isArray(Ie.newTypes)?Ie.newTypes:[]})},[]);l.useEffect(()=>{if(!n||!m)return;let U=!1;return(async()=>{try{const Ne=await o(n,"get_status_metadata");U||_(Ne)}catch{}})(),()=>{U=!0}},[_,n,m==null?void 0:m.id,o]);const H=l.useCallback(async U=>{if(U.preventDefault(),U.stopPropagation(),!(!n||w)){x("providers"),C(!0);try{const Ne=IL(S),Ie=await o(n,PL,Ne.length>0?{types:Ne}:{}),We=DL(Ie);"error"in We?ft.showToast(t("machine.detail.providerSyncFailed",{error:We.error}),"warning"):ft.showToast(We.activatedCount>0?t("machine.detail.providerSyncSuccess",{count:We.activatedCount}):t("machine.detail.providerSyncAlreadyCurrent"),"success"),y(Xe=>Xe+1);try{_(await o(n,"get_status_metadata"))}catch{}}catch(Ne){const Ie=Ne instanceof Error?Ne.message:String(Ne);ft.showToast(t("machine.detail.providerSyncFailed",{error:Ie}),"warning")}finally{C(!1)}}},[_,n,S,w,o,t]);l.useEffect(()=>{if(!n||!m||h!=="overview"&&h!=="providers")return;const U=m.machine;(typeof(U==null?void 0:U.cpus)!="number"||typeof(U==null?void 0:U.totalMem)!="number"||typeof(U==null?void 0:U.arch)!="string"||typeof(U==null?void 0:U.release)!="string"||h==="providers"&&!(U!=null&&U.quota))&&c(n,{minFreshMs:3e4}).catch(()=>{})},[h,c,m,n]),G1(n&&h==="overview"?[n]:[],{enabled:h==="overview",intervalMs:GS});const L=()=>{if(f){a("/dashboard",{state:{mobileSection:"machines"}});return}a("/machines")},F=wI({machineId:n,registeredMachineId:(m==null?void 0:m.machineId)||null,sendDaemonCommand:o,onNicknameSynced:e,logsEndRef:W});l.useEffect(()=>ft.onToast(Ne=>{d.setToasts(We=>{if(We.some(J=>J.message===Ne.message&&Ne.timestamp-J.timestamp<3e3))return We;const et={id:Ne.id,message:Ne.message,type:Ne.type,timestamp:Ne.timestamp,targetKey:Ne.targetKey,actions:Ne.actions};return[...We.slice(-4),et]});const Ie=Ne.duration||5e3;setTimeout(()=>d.setToasts(We=>We.filter(Xe=>Xe.id!==Ne.id)),Ie)}),[d]);const $=(m==null?void 0:m.availableProviders)||[],K={};for(const U of $)K[U.type]=U.icon;const z=m?{id:m.id,hostname:om(m,{fallbackId:m.id}),platform:((te=m.machine)==null?void 0:te.platform)||"unknown",arch:((ue=m.machine)==null?void 0:ue.arch)||"",cpus:((ye=m.machine)==null?void 0:ye.cpus)||0,totalMem:((Me=m.machine)==null?void 0:Me.totalMem)||0,freeMem:(re=m.machine)==null?void 0:re.freeMem,availableMem:(ce=m.machine)==null?void 0:ce.availableMem,loadavg:(Ae=m.machine)==null?void 0:Ae.loadavg,uptime:(be=m.machine)==null?void 0:be.uptime,release:((we=m.machine)==null?void 0:we.release)||"",cdpConnected:!!m.cdpConnected,machineNickname:m.machineNickname||null,...(_e=m.machine)!=null&&_e.quota?{quota:m.machine.quota}:{},p2p:m.p2p?{screenshotActive:!1,...m.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:m.detectedIdes||[],workspaces:m.workspaces||[],defaultWorkspaceId:m.defaultWorkspaceId??m.activeWorkspaceId??null,defaultWorkspacePath:m.defaultWorkspacePath??m.activeWorkspacePath??null}:null,ne=p.filter(U=>U.daemonId===n&&U.type!=="adhdev-daemon").filter(U=>!$a(U)&&!Jn(U)).map(U=>({id:U.id,sessionId:U.sessionId,type:U.type,version:U.version||"",instanceId:U.instanceId||"",status:U.status,workspace:U.workspace||null,terminals:U.terminals||0,aiAgents:X0(U.aiAgents||(U.agents||[]).map(Ne=>({id:Ne.name,name:Ne.name,status:Ne.status,version:Ne.version}))),activeChat:U.activeChat||null,chats:U.chats||[],childSessions:U.childSessions||[],cdpConnected:U.cdpConnected||!1,daemonId:n,lastMessageAt:U.lastMessageAt})),ie=p.filter(U=>U.daemonId===n&&$a(U)).map(U=>({id:U.id,sessionId:U.sessionId,type:U.type,cliName:U.cliName||U.type,status:U.status,workspace:U.workspace||"",activeChat:U.activeChat||null,providerSessionId:U.providerSessionId,mode:U.mode,runtimeKey:U.runtimeKey,runtimeDisplayName:U.runtimeDisplayName,runtimeWorkspaceLabel:U.runtimeWorkspaceLabel,runtimeWriteOwner:U.runtimeWriteOwner||null,runtimeAttachedClients:U.runtimeAttachedClients||[],daemonId:n,lastMessageAt:U.lastMessageAt})),Ce=p.filter(U=>U.daemonId===n&&Jn(U)).map(U=>({id:U.id,sessionId:U.sessionId,type:U.type,acpName:U.cliName||U.type,status:U.status,workspace:U.workspace||"",activeChat:U.activeChat||null,providerSessionId:U.providerSessionId,daemonId:n,lastMessageAt:U.lastMessageAt})),me=m?ds(m,{fallbackId:n}):"",O="workspace",Y=r.state,X=Y==null?void 0:Y.initialMachineTab,Q=Y==null?void 0:Y.initialWorkspaceCategory;Y==null||Y.initialWorkspaceId,Y==null||Y.initialWorkspacePath;const ve=X==="ides"||X==="clis"||X==="acps"?"workspace":X||O,he=X==="ides"?"ide":X==="clis"?"cli":X==="acps"?"acp":Q,Z=[...ne.map(U=>{var Ne;return{id:`ide:${U.type}:${U.workspace||""}`,label:((Ne=U.activeChat)==null?void 0:Ne.title)||U.type,kind:"ide",providerType:U.type,subtitle:U.workspace||void 0,workspace:U.workspace||void 0,lastLaunchedAt:U.lastMessageAt||0}}),...ie.map(U=>{var Ne;return{id:`cli:${U.type}:${U.workspace||""}`,label:((Ne=U.activeChat)==null?void 0:Ne.title)||U.cliName,kind:"cli",providerType:U.type,providerSessionId:U.providerSessionId,subtitle:U.workspace||void 0,workspace:U.workspace||void 0,lastLaunchedAt:U.lastMessageAt||0}}),...Ce.map(U=>{var Ne;return{id:`acp:${U.type}:${U.workspace||""}`,label:((Ne=U.activeChat)==null?void 0:Ne.title)||U.acpName,kind:"acp",providerType:U.type,providerSessionId:U.providerSessionId,subtitle:Tn(U.summaryMetadata)||U.workspace||void 0,workspace:U.workspace||void 0,lastLaunchedAt:U.lastMessageAt||0}})].sort((U,Ne)=>(Ne.lastLaunchedAt||0)-(U.lastLaunchedAt||0)),fe=((m==null?void 0:m.recentLaunches)||[]).length>0?((m==null?void 0:m.recentLaunches)||[]).map(U=>({id:U.id,label:U.title||U.providerName||U.providerType,kind:U.kind,providerType:U.providerType,providerSessionId:U.providerSessionId,subtitle:Tn(U.summaryMetadata)||U.workspace||void 0,workspace:U.workspace,summaryMetadata:U.summaryMetadata,lastLaunchedAt:U.lastLaunchedAt})):Z,V=l.useMemo(()=>{var Ne;const U=((Ne=d.connectionStates)==null?void 0:Ne[n||""])||void 0;return p.filter(Ie=>Ie.daemonId===n&&Ie.type!=="adhdev-daemon").flatMap(Ie=>nc(Ie,{connectionStates:n&&U?{[n]:U}:void 0,defaultConnectionState:U})).filter(Ie=>!(Ie.transport==="pty"&&Ie.mode==="terminal")).sort((Ie,We)=>ul(We)-ul(Ie))},[p,d.connectionStates,n]),q=l.useCallback(U=>{const Ne=_h(U);Ne&&a(Ba(Ne))},[a]),ee=l.useCallback(()=>{A.current&&(R(!0),A.current().finally(()=>{A.current=null,R(!1),D(null)}))},[]),pe=l.useCallback(U=>{if(!z)return;const{options:Ne,selectedKey:Ie}=Oh({machine:z,currentWorkspacePath:U.workspace,homeLabel:t("newSession.homeDirectory"),homeDescription:t("newSession.launchWithoutWorkspace")}),We=async()=>{T(U.kind),x("workspace")};A.current=async()=>{const Xe=Ne.find(Le=>Le.key===M.current),et=(Xe==null?void 0:Xe.workspacePath)??null,J=(Xe==null?void 0:Xe.workspaceId)??null;if(U.kind==="ide"&&U.providerType){await F.handleLaunchIde(U.providerType,et?{workspace:et}:void 0);return}if((U.kind==="cli"||U.kind==="acp")&&U.providerType){await F.runLaunchCliCore({cliType:U.providerType,dir:J?void 0:et||"",workspaceId:J||void 0,model:U.kind==="acp"&&lm(U.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:U.providerSessionId});return}await We()},M.current=Ie,P(Ie),D({title:U.kind==="ide"?qr(t,"restart-ide",U.label):U.providerSessionId?nh(t,U.label):qr(t,"start-fresh",U.label),description:U.kind==="ide"?zr(t,"restart-ide"):U.providerSessionId?ah(t):zr(t,"start-fresh"),confirmLabel:U.kind==="ide"?Kr(t,"restart-ide"):U.providerSessionId?rl(t,!0):Kr(t,"start-fresh"),busyLabel:U.kind==="ide"?Vr(t,"restart-ide"):U.providerSessionId?sh(t,!0):Vr(t,"start-fresh"),workspaceOptions:Ne,details:[{label:"Mode",value:U.kind.toUpperCase()},...U.providerType?[{label:"Provider",value:U.providerType}]:[]]})},[F,z]);if(l.useEffect(()=>{x(ve)},[O,ve,n]),l.useEffect(()=>{he&&T(he)},[he,n]),!z)return u?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:t("machine.detail.notFound")}),s.jsx("p",{className:"mt-3",children:t("machine.detail.offlineHint")}),s.jsx("button",{onClick:L,className:"machine-btn-back",children:t("machine.detail.back")})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:t("machine.detail.loading")})});const le=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(us,{size:14})," ",t("machine.detail.tabWorkspace")]}),count:ne.length+ie.length+Ce.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(sn,{size:14})," ",t("machine.detail.tabHostedRuntimes")]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Oa,{size:14})," ",t("machine.detail.tabProviders")]}),...S&&S.staleTypes.length+S.newTypes.length>0?{count:S.staleTypes.length+S.newTypes.length}:{}},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(mb,{size:14})," ",t("machine.detail.tabSystem")]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ll,{size:14})," ",t("machine.detail.tabLogs")]})}];return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-border-subtle",children:[s.jsx("div",{className:"flex items-center justify-between w-full",children:s.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[s.jsx("button",{onClick:L,className:"flex items-center justify-center w-8 h-8 rounded-full bg-bg-glass hover:bg-bg-glass-hover text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[F.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:F.nicknameInput,onChange:U=>F.setNicknameInput(U.target.value),onKeyDown:U=>{U.key==="Enter"&&F.handleSaveNickname(),U.key==="Escape"&&F.setEditingNickname(!1)},placeholder:t("machine.detail.nicknamePlaceholder"),className:"px-2.5 py-1 rounded-md border border-accent/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:F.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:t("machine.detail.save")}),s.jsx("button",{onClick:()=>F.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-bg-glass text-text-muted hover:bg-bg-glass-hover hover:text-text-primary text-sm font-medium transition-colors",children:t("machine.detail.cancel")})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{F.setEditingNickname(!0),F.setNicknameInput(z.machineNickname||"")},title:t("machine.detail.clickToSetNickname"),children:me}),k?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),d.retryConnection&&n&&s.jsx("button",{onClick:()=>d.retryConnection(n),className:"px-2.5 py-0.5 rounded text-[11px] font-semibold bg-red-500/10 border border-red-500/20 text-red-400 hover:bg-red-500/20 transition-colors",children:t("machine.detail.reconnect")})]}):s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[s.jsxs("span",{className:"font-mono bg-bg-glass px-1.5 py-0.5 rounded",children:[z.platform," · ",z.arch]}),s.jsx("span",{children:t("machine.detail.coresCount",{count:z.cpus})}),(m==null?void 0:m.version)&&s.jsxs("span",{children:["v",m.version]}),z.p2p.available&&s.jsx("span",{children:t("machine.detail.p2pState",{state:z.p2p.state==="connected"?t("machine.detail.p2pConnected"):z.p2p.state})}),z.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:z.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-border-subtle",children:le.map(U=>s.jsxs("button",{onClick:()=>x(U.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${h===U.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[U.label,U.count!==void 0&&U.id==="providers"&&S?s.jsx("span",{role:"button",title:t("machine.detail.providerStaleBadgeHint"),"aria-label":t("machine.detail.providerStaleBadgeHint"),onClick:H,className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 cursor-pointer ${w?"bg-amber-500/20 text-amber-300":"bg-amber-500/15 text-amber-400 hover:bg-amber-500/30"}`,children:w?"…":U.count}):U.count!==void 0?s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${h===U.id?"bg-accent-primary/20 text-accent-primary":"bg-bg-glass-hover text-text-muted"}`,children:U.count}):null]},U.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[h==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(AL,{machineEntry:m,providers:$,recentLaunches:fe,currentConversations:V,onUpgradeDaemon:async()=>{const U=Co(m);if(U)try{await o(n,"daemon_upgrade",U)}catch{}},onOpenRecent:pe,onOpenConversation:q}),s.jsx(ML,{machine:z,machineId:n,ideSessions:ne,cliSessions:ie,acpSessions:Ce,actions:F,sendDaemonCommand:o})]}),h==="providers"&&s.jsx(_I,{machineId:n,providers:$,sendDaemonCommand:o,quota:z.quota,refreshNonce:v}),h==="overview"&&s.jsx(SI,{machine:z,ideSessions:ne,cliSessions:ie,acpSessions:Ce}),h==="session-host"&&s.jsx(CL,{machineId:n,cliSessions:ie,sendDaemonCommand:o}),h==="logs"&&s.jsx(bL,{machineId:n,sendDaemonCommand:o})]})})}),F.launchPick&&z&&s.jsx(jL,{machine:z,launchPick:F.launchPick,actions:F}),I&&s.jsx(jo,{title:I.title,description:I.description,details:I.details,workspaceOptions:I.workspaceOptions,selectedWorkspaceKey:E,onWorkspaceChange:U=>{M.current=U,P(U)},confirmLabel:I.confirmLabel,busyLabel:I.busyLabel,busy:B,onConfirm:ee,onCancel:()=>{A.current=null,D(null)}}),j&&s.jsx(Yf,{daemonId:j.daemonId,workspace:j.workspace,onClose:()=>N(null)}),s.jsx(oh,{toasts:d.toasts||[],onDismiss:U=>d.setToasts(Ne=>Ne.filter(Ie=>Ie.id!==U)),onClickToast:U=>{U.targetKey&&a(Ba(U.targetKey))}}),s.jsx("style",{children:`
|
|
115
115
|
@keyframes toast-in {
|
|
116
116
|
from { opacity: 0; transform: translateX(40px); }
|
|
117
117
|
to { opacity: 1; transform: translateX(0); }
|
|
118
118
|
}
|
|
119
119
|
`})]})}function RL({daemonIds:e,meshId:t,sendData:n,onRevisionAdvance:a}){const r=l.useRef(new Map),o=l.useRef(a);o.current=a;const i=[...new Set(e.filter(Boolean))].sort().join(",");l.useEffect(()=>{r.current=new Map},[i,t]),l.useEffect(()=>{if(!t||!n)return;const c=[...new Set(e.filter(Boolean))];if(c.length===0)return;const d=c.map(p=>ys.subscribe({sendData:n},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 f=m[t]??m["*"];if(typeof f!="number")return;const g=r.current.get(p);r.current.set(p,f),g!==void 0&&f>g&&o.current()}));return()=>{for(const p of d)p()}},[i,t,n])}const Zf={meshHostDaemonSection:!1,createDaemonPicker:!1,addNodeDaemonPicker:!1,queueSection:!0,coordinatorPrompt:!0,nodeInstruction:!0,hermesMcpConfig:!0,reviewInbox:!0},eg=l.createContext(null);function EL(){const e=l.useContext(eg);if(!e)throw new Error("useRepoMeshContext must be used inside RepoMeshProvider");return e}const ao="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function yl({workspaces:e,value:t,onChange:n,autoFocus:a}){const{t:r}=ke("common"),[o,i]=l.useState(!1),c=new Set(e.map(p=>p.path)),d=o?"__custom":c.has(t)?t:"";return e.length===0||o?s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx("input",{type:"text",className:ao,value:t,autoFocus:a,placeholder:r("setupWizard.machines.workspacePlaceholder"),onChange:p=>n(p.target.value)}),e.length>0&&s.jsx("button",{type:"button",className:"self-start text-[10px] text-accent-primary hover:underline",onClick:()=>i(!1),children:r("setupWizard.machines.pickFromKnown")})]}):s.jsxs("select",{className:ao,value:d,onChange:p=>{p.target.value==="__custom"?(i(!0),n("")):n(p.target.value)},children:[s.jsx("option",{value:"",children:r("setupWizard.machines.workspaceSelectPlaceholder")}),e.map(p=>s.jsx("option",{value:p.path,children:p.label||p.path},p.path)),s.jsx("option",{value:"__custom",children:r("setupWizard.machines.workspaceCustom")})]})}function ro(e){var t;return!!(e!=null&&e.success)&&((t=e==null?void 0:e.plan)==null?void 0:t.kind)!==void 0&&e.plan.kind!=="create_mesh_and_onboard"}function tg(e,t){const[n,a]=l.useState(!1),r=l.useRef(null);return l.useEffect(()=>(e?r.current=setTimeout(()=>a(!0),t):a(!1),()=>{r.current&&clearTimeout(r.current)}),[e,t]),e&&n}function sg({plan:e,loading:t}){var i,c,d;const{t:n}=ke("common"),a=tg(t,250);let r=null,o="text-[11px] text-text-muted";return a?r=n("setupWizard.machines.planChecking"):(e==null?void 0:e.success)===!1?(o="text-[11px] text-red-400",r=s.jsxs(s.Fragment,{children:[e.error,e.action?` ${e.action}`:""]})):ro(e)?(o="text-[11px] text-amber-400",r=((i=e.plan)==null?void 0:i.summary)||n("setupWizard.machines.planExists")):e&&(o="text-[11px] text-emerald-400",r=n("setupWizard.machines.planOk",{identity:((c=e.discovery)==null?void 0:c.repoIdentity)||((d=e.discovery)==null?void 0:d.repoRoot)||""})),s.jsx("p",{className:`${o} min-h-[1.4em]`,children:r})}function _L(e){var t;return e.creating||e.planLoading||!e.name.trim()||e.showDaemonPicker&&!e.daemonId||((t=e.plan)==null?void 0:t.success)===!1||ro(e.plan)?!0:e.workspace.trim()?!1:!e.repoRemoteUrl.trim()&&!e.repoIdentity.trim()}function ng(e){var E,P;const{variant:t="page",showDaemonPicker:n,daemons:a,daemonLabel:r,name:o,onNameChange:i,daemonId:c,onDaemonIdChange:d,workspace:p,onWorkspaceChange:u,workspaces:m,plan:f,planLoading:g,repoRemoteUrl:k,onRepoRemoteUrlChange:h,repoIdentity:x,onRepoIdentityChange:S,manualOpen:b,onManualOpenChange:w,creating:C,warning:v,onCreate:y,onCancel:j}=e,{t:N}=ke("common"),T=_L({creating:C,planLoading:g,plan:f,name:o,workspace:p,showDaemonPicker:n,daemonId:c,repoRemoteUrl:k,repoIdentity:x}),A=tg(g,250),I=b||!!k.trim()||!!x.trim(),D=n&&a.length>0&&s.jsxs("select",{className:t==="wizard"?ao:"input w-full",value:c,onChange:B=>d(B.target.value),children:[s.jsx("option",{value:"",children:N("setupWizard.machines.machineSelectPlaceholder")}),a.map(B=>s.jsx("option",{value:B.id,children:r(B)},B.id))]}),M=I?s.jsxs(s.Fragment,{children:[s.jsx(Tt,{label:N("repoMesh.list.remoteUrl"),hint:N("repoMesh.list.remoteUrlHint"),children:s.jsx(xs,{value:k,onChange:B=>h(B.target.value),placeholder:"https://github.com/user/repo"})}),s.jsx(Tt,{label:N("repoMesh.list.repoIdentity"),hint:N("repoMesh.list.repoIdentityHint"),children:s.jsx(xs,{value:x,onChange:B=>S(B.target.value),placeholder:"github.com/user/repo"})})]}):s.jsx("button",{type:"button",className:"self-start text-xs text-text-muted hover:text-text-primary underline underline-offset-2 mb-3 bg-transparent border-none cursor-pointer p-0",onClick:()=>w(!0),children:N("repoMesh.list.advancedIdentityToggle")});return t==="wizard"?s.jsxs("div",{className:"flex flex-col gap-2.5 rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2.5",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:N("setupWizard.machines.meshName")}),s.jsx("input",{type:"text",className:ao,value:o,onChange:B=>i(B.target.value)})]}),n&&a.length>1&&s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:N("setupWizard.machines.machine")}),D]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:N("setupWizard.machines.workspace")}),s.jsx(yl,{workspaces:m,value:p,onChange:u})]}),s.jsx(sg,{plan:f,loading:g}),v&&s.jsx("p",{className:"text-[11px] text-amber-400",children:v}),s.jsx("div",{className:"flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:y,disabled:T,children:N(C?"setupWizard.machines.creating":"setupWizard.machines.create")})})]}):s.jsxs(s.Fragment,{children:[s.jsx("h3",{className:"text-base font-bold mb-4",children:N("repoMesh.list.createTitle")}),n&&s.jsx(Tt,{label:N("repoMesh.list.createOnMachine"),hint:N("repoMesh.list.createOnMachineHint"),children:a.length===0?s.jsx("select",{className:"input w-full",disabled:!0,children:s.jsx("option",{value:"",children:N("repoMesh.list.noConnectedDaemon")})}):D}),s.jsx(Tt,{label:N("repoMesh.list.workspace"),hint:N("repoMesh.list.workspaceHint"),children:s.jsx(yl,{workspaces:m,value:p,onChange:u})}),(A||f)&&s.jsx(Mt,{variant:(f==null?void 0:f.success)===!1?"error":ro(f)?"warning":"info",className:"mb-4",children:A?N("setupWizard.machines.planChecking"):(f==null?void 0:f.success)===!1?`${(f==null?void 0:f.code)||"onboarding_blocked"}: ${(f==null?void 0:f.error)||"Git discovery failed"} ${(f==null?void 0:f.action)||""}`:ro(f)?((E=f.plan)==null?void 0:E.summary)||N("setupWizard.machines.planExists"):`${((P=f.plan)==null?void 0:P.summary)||"Git repository detected."} No changes will be made until you click Create.`}),s.jsx(Tt,{label:N("repoMesh.list.name"),children:s.jsx(xs,{value:o,onChange:B=>i(B.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx("div",{className:"flex flex-col",children:M}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:y,disabled:T,children:N(C?"repoMesh.list.creating":"repoMesh.list.create")}),j&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:j,disabled:C,children:N("repoMesh.list.cancel")})]})]})}function HL({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 $L({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 FL({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 BL({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 WL({status:e}){const n={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:n.color+"15",color:n.color,border:`1px solid ${n.color}25`},title:n.title,children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full",style:{background:n.color}}),n.label]})}function OL(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function UL({meshes:e,loading:t,error:n,onDismissError:a,daemons:r,features:o,showCreate:i,onToggleCreate:c,createName:d,onCreateNameChange:p,createRepoIdentity:u,onCreateRepoIdentityChange:m,createRepoRemoteUrl:f,onCreateRepoRemoteUrlChange:g,newMeshDaemonId:k,onNewMeshDaemonIdChange:h,newMeshWorkspace:x,onNewMeshWorkspaceChange:S,createPickerWorkspaces:b,createOnboardingPlan:w,createPlanLoading:C,creating:v,createWarning:y,onDismissCreateWarning:j,onSelectMesh:N,onCreate:T,onCancelCreate:A}){const{t:I}=ke("common"),D=o.maxMeshes!=null&&e.length>=o.maxMeshes,[M,E]=l.useState(!1);return s.jsxs(Qa,{icon:s.jsx(cs,{}),title:I("repoMesh.list.title"),subtitle:I("repoMesh.list.count",{count:e.length}),widthClassName:"max-w-5xl",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:c,disabled:D,title:D?I("repoMesh.list.meshLimitReached",{max:o.maxMeshes}):void 0,children:I("repoMesh.list.createMesh")}),children:[D&&s.jsx(Mt,{variant:"info",className:"mb-4",children:I("repoMesh.list.meshLimitBanner",{max:o.maxMeshes})}),n&&s.jsx(Mt,{variant:"error",onDismiss:a,className:"mb-4",children:n}),y&&s.jsx(Mt,{variant:"warning",onDismiss:j,className:"mb-4",children:y}),i&&s.jsx(xt,{className:"mb-5 border-accent/40 animate-[fadeIn_0.3s_ease-out]",children:s.jsx(ng,{variant:"page",showDaemonPicker:o.createDaemonPicker,daemons:r,daemonLabel:OL,name:d,onNameChange:p,daemonId:k,onDaemonIdChange:h,workspace:x,onWorkspaceChange:S,workspaces:b,plan:w,planLoading:C,repoRemoteUrl:f,onRepoRemoteUrlChange:g,repoIdentity:u,onRepoIdentityChange:m,manualOpen:M,onManualOpenChange:E,creating:v,onCreate:T,onCancel:A})}),t?s.jsx("div",{className:"text-sm text-text-muted p-4",children:I("repoMesh.list.loading")}):e.length===0?s.jsx(Ja,{icon:s.jsx(cs,{}),title:I("repoMesh.list.emptyTitle"),description:r.length>0?I("repoMesh.list.emptyWithDaemons"):I("repoMesh.list.emptyNoDaemons"),action:s.jsx("button",{className:"btn btn-primary btn-sm",disabled:!r.length,onClick:c,children:I("repoMesh.list.createFirst")})}):s.jsx("div",{className:"flex flex-col gap-2.5",children:e.map(P=>{var B;return s.jsx("button",{type:"button",onClick:()=>N(P.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(cs,{size:16}),s.jsx("span",{className:"font-bold text-sm",children:P.name})]}),s.jsxs("div",{className:"text-[12px] text-text-muted flex items-center gap-2",children:[s.jsx("span",{className:"font-mono",children:P.repoIdentity||P.repo_identity||I("repoMesh.list.noRepoIdentity")}),(P.defaultBranch||P.default_branch)&&s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx($L,{size:11}),P.defaultBranch||P.default_branch]})]})]}),s.jsxs("div",{className:"text-right text-[11px] text-text-muted shrink-0 ml-4",children:[s.jsx("div",{children:new Date(P.createdAt||P.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})}),s.jsxs("div",{className:"text-text-muted/60",children:[((B=P.nodes)==null?void 0:B.length)??P.nodeCount??0," ",I("repoMesh.list.nodesSuffix")]})]})]})},P.id)})})]})}function GL(e){const t=new Map;for(const n of e)n!=null&&n.id&&t.set(n.id,ln(n.availableProviders||[]));return t}function qL(e,t){const n=String(e.daemon_id||e.daemonId||"");return n&&t.has(n)?t.get(n):!n&&t.size===1?[...t.values()][0]:[]}function zL(e,t){const n=new Map;for(const c of t)c!=null&&c.id&&n.set(c.id,Array.isArray(c.availableProviders)?c.availableProviders:[]);const a=new Set,r=[];let o=0,i=0;for(const c of Array.isArray(e)?e:[]){const d=String((c==null?void 0:c.daemon_id)||(c==null?void 0:c.daemonId)||""),p=d?n.get(d):n.size===1?[...n.values()][0]:void 0;if(!p||p.length===0){i++;continue}o++;for(const u of p){const m=String((u==null?void 0:u.type)||(u==null?void 0:u.id)||"").trim();!m||a.has(m)||(a.add(m),r.push(u))}}return r.sort((c,d)=>String((c==null?void 0:c.type)||(c==null?void 0:c.id)||"").localeCompare(String((d==null?void 0:d.type)||(d==null?void 0:d.id)||""))),{providers:r,reportedNodeCount:o,unreportedNodeCount:i}}function KL(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{},n=new Set,a=[],r=o=>{const i=typeof o=="string"?o.trim():"";!i||n.has(i)||(n.add(i),a.push(i))};for(const o of tm(t.slots))r(o.provider);if(Array.isArray(t.providerPriority))for(const o of t.providerPriority)r(o);return a}function VL(e){var d,p;const t=e,n=[],a=Array.isArray(t.capabilities)?t.capabilities:[];for(const u of a){const m=typeof u=="string"?u.trim():"";m&&n.push({tag:m,custom:!0})}const r=(((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();r&&n.push({tag:`os=${r}`,custom:!1}),o&&n.push({tag:`arch=${o}`,custom:!1});for(const u of KL(t.policy))n.push({tag:`provider=${u}`,custom:!1});const i=typeof t.worktreeBranch=="string"?t.worktreeBranch.trim():"";t.isLocalWorktree===!0&&i&&n.push({tag:`worktree=${i}`,custom:!1});const c=new Set;return n.filter(u=>c.has(u.tag)?!1:(c.add(u.tag),!0))}const YL=["","low","medium","high"],QL={easy:"Easy",medium:"Medium",difficult:"Difficult",freeform:"Freeform"};function Ku(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 Vu(e){const t=e.provider.trim();if(!t)return null;const n=e.model.trim(),a=e.thinkingLevel.trim()||void 0,r=Number(e.maxParallel),o=Number.isFinite(r)&&r>0?Math.floor(r):void 0;return{provider:t,...n?{model:n}:{},...a?{thinkingLevel:a}:{},...e.difficulty.length?{difficulty:e.difficulty}:{},...e.capability.length?{capability:e.capability}:{},...o!==void 0?{maxParallel:o}:{}}}function JL(){return{provider:"",model:"",thinkingLevel:"",difficulty:[],capability:[],maxParallel:""}}const fn="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function XL({slots:e,availableProviders:t,saving:n,onSave:a}){const{t:r}=ke("common"),[o,i]=l.useState(()=>e.map(Ku)),c=l.useMemo(()=>JSON.stringify(e),[e]);l.useEffect(()=>{i(e.map(Ku))},[c]);const d=l.useMemo(()=>[...new Set(t.map(b=>b.type).filter(Boolean))],[t]),p=l.useMemo(()=>uh(t),[t]),u=l.useMemo(()=>{const b=o.map(Vu).filter(Boolean);return JSON.stringify(b)!==JSON.stringify(e)},[o,e]),m=(b,w)=>i(C=>C.map((v,y)=>y===b?{...v,...w}:v)),f=(b,w)=>i(C=>C.map((v,y)=>{var T;if(y!==b)return v;const j=((T=p.get(w))==null?void 0:T.models)??[],N=!v.model||j.length===0||j.includes(v.model);return{...v,provider:w,...N?{}:{model:""}}})),g=b=>i(w=>w.filter((C,v)=>v!==b)),k=()=>i(b=>[...b,JL()]),h=(b,w)=>i(C=>{const v=b+w;if(v<0||v>=C.length)return C;const y=[...C];return[y[b],y[v]]=[y[v],y[b]],y}),x=(b,w)=>i(C=>C.map((v,y)=>{if(y!==b)return v;const j=v.difficulty.includes(w);return{...v,difficulty:j?v.difficulty.filter(N=>N!==w):[...v.difficulty,w]}})),S=()=>a(o.map(Vu).filter(Boolean));return s.jsxs("div",{className:"flex flex-col gap-2",onClick:b=>b.stopPropagation(),children:[o.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:r("repoMesh.slotEditor.empty")}),o.map((b,w)=>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:["#",w+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:w===0,onClick:()=>h(w,-1),title:r("repoMesh.slotEditor.moveUp"),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:w===o.length-1,onClick:()=>h(w,1),title:r("repoMesh.slotEditor.moveDown"),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:()=>g(w),"aria-label":r("repoMesh.slotEditor.removeSlot"),children:s.jsx(Dt,{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:r("repoMesh.slotEditor.provider")}),d.length>0?s.jsxs("select",{className:fn,value:b.provider,onChange:C=>f(w,C.target.value),children:[s.jsx("option",{value:"",children:r("repoMesh.slotEditor.select")}),d.map(C=>s.jsx("option",{value:C,children:C},C)),b.provider&&!d.includes(b.provider)&&s.jsx("option",{value:b.provider,children:b.provider})]}):s.jsx("input",{className:fn,value:b.provider,placeholder:"claude-cli",onChange:C=>m(w,{provider:C.target.value})})]}),(()=>{var N;const C=p.get(b.provider),v=(C==null?void 0:C.models)??[],y=(N=C==null?void 0:C.thinking)!=null&&N.length?["",...C.thinking]:YL,j=!!b.model&&v.length>0&&!v.includes(b.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:r("repoMesh.slotEditor.model")}),v.length>0&&!j?s.jsxs("select",{className:fn,value:v.includes(b.model)?b.model:"",onChange:T=>m(w,{model:T.target.value==="__custom__"?" ":T.target.value}),children:[s.jsx("option",{value:"",children:r("repoMesh.slotEditor.providerDefault")}),v.map(T=>s.jsx("option",{value:T,children:T},T)),s.jsx("option",{value:"__custom__",children:r("repoMesh.slotEditor.custom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:fn,value:b.model.trim(),placeholder:b.provider?`${b.provider} model`:r("repoMesh.slotEditor.modelPlaceholder"),onChange:T=>m(w,{model:T.target.value})}),v.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:()=>m(w,{model:""}),children:r("repoMesh.slotEditor.backToModelList")})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.thinking")}),s.jsx("select",{className:fn,value:b.thinkingLevel,onChange:T=>m(w,{thinkingLevel:T.target.value}),children:y.map(T=>s.jsx("option",{value:T,children:T||r("repoMesh.slotEditor.thinkingDefault")},T||"_default"))})]})]})})()]}),s.jsxs("div",{className:"mt-2",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.difficulty")}),s.jsx("div",{className:"mt-1 flex flex-wrap gap-1.5",children:em.map(C=>{const v=b.difficulty.includes(C);return s.jsx("button",{type:"button",className:`rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors ${v?"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:()=>x(w,C),children:QL[C]},C)})})]}),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:r("repoMesh.slotEditor.capabilityTags")}),s.jsx("input",{className:fn,value:b.capability.join(", "),placeholder:"worktree, os=darwin",onChange:C=>m(w,{capability:C.target.value.split(",").map(v=>v.trim()).filter(Boolean)})})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.maxParallel")}),s.jsx("input",{type:"number",inputMode:"numeric",min:1,className:fn,value:b.maxParallel,placeholder:r("repoMesh.slotEditor.maxParallelPlaceholder"),onChange:C=>m(w,{maxParallel:C.target.value})})]})]})]},w)),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:k,children:[s.jsx(Hl,{size:13})," ",r("repoMesh.slotEditor.addSlot")]}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm ml-auto",onClick:S,disabled:!!n||!u,children:r(n?"repoMesh.slotEditor.saving":"repoMesh.slotEditor.saveSlots")})]})]})}function ZL(e){const t=e.capabilities;return Array.isArray(t)?t.map(n=>typeof n=="string"?n.trim():"").filter(Boolean):[]}const e2=["os=","arch=","provider=","worktree=","converge="];function t2({node:e,saving:t,onSave:n}){const{t:a}=ke("common"),r=l.useMemo(()=>VL(e).filter(h=>!h.custom),[e]),o=l.useMemo(()=>ZL(e),[e]),[i,c]=l.useState(o),[d,p]=l.useState(""),u=JSON.stringify(i)!==JSON.stringify(o),f=(h=>{const x=h.trim();return x?/\s/.test(x)?a("repoMesh.tagEditor.noSpaces"):e2.some(S=>x.toLowerCase().startsWith(S))?a("repoMesh.tagEditor.reservedPrefix"):i.includes(x)?a("repoMesh.tagEditor.alreadyAdded"):null:null})(d);function g(){const h=d.trim();!h||f||(c(x=>[...x,h]),p(""))}function k(h){c(x=>x.filter(S=>S!==h))}return s.jsxs("div",{className:"mt-2",onClick:h=>h.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:a("repoMesh.tagEditor.routingTags")}),r.map(h=>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:a("repoMesh.tagEditor.autoDerivedTitle"),children:h.tag},h.tag)),i.map(h=>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:a("repoMesh.tagEditor.customTagTitle"),children:[h,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:()=>k(h),disabled:t,"aria-label":a("repoMesh.tagEditor.remove",{tag:h}),children:"×"})]},h))]}),s.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-2",children:[s.jsx("input",{type:"text",value:d,onChange:h=>p(h.target.value),onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),g())},placeholder:a("repoMesh.tagEditor.addPlaceholder"),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:g,disabled:t||!d.trim()||!!f,children:a("repoMesh.tagEditor.add")}),u&&s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>n(i),disabled:t,children:a(t?"repoMesh.tagEditor.saving":"repoMesh.tagEditor.saveTags")})]}),f&&s.jsx("div",{className:"mt-1 text-[11px] text-amber-400",children:f}),i.length===0&&r.length===0&&s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:a("repoMesh.tagEditor.empty")})]})}function s2(e,t){const n=t;return[...Array.isArray(n==null?void 0:n.cliSessions)?n.cliSessions:[],...Array.isArray(n==null?void 0:n.acpSessions)?n.acpSessions:[],...Array.isArray(n==null?void 0:n.sessions)?n.sessions:[]].filter(r=>{var o;return((o=r==null?void 0:r.settings)==null?void 0:o.meshNodeId)===e.id||(r==null?void 0:r.workspace)===e.workspace}).map(r=>{var o;return{id:r.sessionId||r.id||r.instanceId||"unknown",provider:r.providerType||r.cliType||r.acpType||r.type||"unknown",status:r.status||((o=r.activeChat)==null?void 0:o.status)||"unknown"}})}function n2(e,t){var n;return(e==null?void 0:e.ownerName)||(e==null?void 0:e.userName)||((n=e==null?void 0:e.user)==null?void 0:n.name)||t||"You"}function Yu({nodes:e,meshQueue:t,activeDaemon:n,daemons:a,userName:r,features:o,providersByDaemonId:i,savingNodeSlotsId:c,onUpdateNodeSlots:d,savingNodeCapabilitiesId:p,onUpdateNodeCapabilities:u,nodeSystemPromptDrafts:m,onNodeSystemPromptDraftChange:f,savingNodeSystemPromptId:g,onSaveNodeSystemPrompt:k,selectedNodeId:h,onSelectNode:x,onRemoveNode:S}){const{t:b}=ke("common");return e.length===0?s.jsx(Ja,{icon:s.jsx(An,{}),title:b("repoMesh.nodeList.emptyTitle"),description:b("repoMesh.nodeList.emptyDescription")}):s.jsx("div",{className:"flex flex-col gap-2",children:e.map(w=>{var T;const C=i2(w),v=a2(w,t),y=s2(w,n),j=h===w.id,N=w.status||w.machine_status||(v.length>0||y.length>0?"active":"enabled");return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary transition-colors ${o.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:o.addNodeDaemonPicker?void 0:"button",tabIndex:o.addNodeDaemonPicker?void 0:0,onClick:o.addNodeDaemonPicker?void 0:()=>x(j?null:w.id),onKeyDown:o.addNodeDaemonPicker?void 0:A=>{(A.key==="Enter"||A.key===" ")&&(A.preventDefault(),x(j?null:w.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:[o.addNodeDaemonPicker?s.jsx("span",{className:"font-semibold text-sm text-text-primary truncate",children:w.machine_label||w.machine_nickname||w.hostname||w.workspace}):s.jsx("span",{className:"text-sm font-medium",children:w.workspace.split("/").pop()}),o.addNodeDaemonPicker&&s.jsx(WL,{status:N}),o.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:b("repoMesh.nodeList.setupInventory")})]}),o.addNodeDaemonPicker&&s.jsx("div",{className:"text-[11px] text-text-muted",children:b("repoMesh.nodeList.ownerMachine",{owner:n2(a.find(A=>A.id===String(w.daemon_id||"")),r),machine:w.machine_label||w.daemon_id||w.workspace})}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:w.workspace}),s.jsx(t2,{node:w,saving:p===w.id,onSave:A=>u(w,A)}),o.addNodeDaemonPicker&&s.jsx("div",{className:"mt-2 text-[11px] text-amber-300",children:b("repoMesh.nodeList.liveDetailGraphOwned")}),s.jsxs("div",{className:"mt-3 max-w-2xl",onClick:A=>A.stopPropagation(),children:[s.jsx(Tt,{label:b("repoMesh.nodeList.slotsLabel"),hint:b("repoMesh.nodeList.slotsHint"),children:s.jsx(XL,{slots:Array.isArray((T=w.policy)==null?void 0:T.slots)?w.policy.slots:[],availableProviders:qL(w,i),saving:c===w.id,onSave:A=>d(w,A)})}),o.nodeInstruction&&s.jsxs(Tt,{label:b("repoMesh.nodeList.nodeInstruction"),hint:b("repoMesh.nodeList.nodeInstructionHint"),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:m[w.id]??"",onChange:A=>{const I=A.target.value;f(w.id,I)},onClick:A=>A.stopPropagation(),disabled:g===w.id,placeholder:b("repoMesh.nodeList.nodeInstructionPlaceholder")}),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:A=>{A.stopPropagation(),k(w)},disabled:g===w.id,children:g===w.id?b("repoMesh.nodeList.saving"):b("repoMesh.nodeList.saveInstruction")})})]})]})]}),s.jsx("button",{className:`transition-colors bg-transparent border-none cursor-pointer ${o.addNodeDaemonPicker?"btn btn-sm text-text-muted hover:text-red-400":"text-text-muted hover:text-red-400"}`,onClick:A=>{A.stopPropagation(),S(w.id)},title:b("repoMesh.nodeList.removeNode"),children:s.jsx(FL,{size:14})})]}),s.jsxs("details",{className:"mt-3 group",onClick:A=>A.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:"▸"})," ",b("repoMesh.nodeList.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:b("repoMesh.nodeList.nodeId")})," ",s.jsx("span",{className:"font-mono break-all",children:w.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:b("repoMesh.nodeList.launchReady")})," ",s.jsx("span",{className:C.configured?"text-green-400":"text-amber-400",children:C.configured?b("repoMesh.nodeList.launchReadyYes"):b("repoMesh.nodeList.launchReadyNo")})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:b("repoMesh.nodeList.repoRoot")})," ",s.jsx("span",{className:"font-mono break-all",children:w.repoRoot||w.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:b("repoMesh.nodeList.activeSessionsLabel")})," ",y.length]}),o.addNodeDaemonPicker&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:b("repoMesh.nodeList.added")})," ",new Date(w.created_at||w.createdAt||Date.now()).toLocaleDateString()]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:b("repoMesh.nodeList.activeQueueAssignments")}),v.length===0?s.jsx("div",{children:b("repoMesh.nodeList.noActiveAssignment")}):s.jsx("ul",{className:"m-0 pl-4",children:v.map(A=>s.jsx("li",{className:"font-mono",children:r2(A)},A.id))})]}),y.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:b("repoMesh.nodeList.activeSessions")}),s.jsx("ul",{className:"m-0 pl-4",children:y.map(A=>s.jsxs("li",{className:"font-mono",children:[A.provider," / ",A.status," / ",A.id]},A.id))})]})]})]})]},w.id)})})}function a2(e,t){return t.filter(n=>n.status!=="assigned"?!1:(n.assignedNodeId||n.nodeId)===e.id)}function r2(e){const t=e.assignedSessionId||e.sessionId||"unassigned session",n=e.message.length>80?`${e.message.slice(0,77)}…`:e.message;return`${t}: ${n}`}function o2(e){var r,o;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set,a=t.map(i=>typeof i=="string"?i.trim():"").filter(Boolean).filter(i=>n.has(i)?!1:(n.add(i),!0));return a.length?a:F0((o=e.policy)==null?void 0:o.slots)}function i2(e){const t=o2(e);return t.length?{configured:!0,label:t.join(" → ")}:{configured:!1,label:"not configured",launchBlockedMessage:"No provider configured on this node — task launch is blocked until a capability slot or provider priority is set."}}function wl(e){return e.isLocalWorktree===!0}function oo(e){return e&&(e.machineNickname||e.nickname||e.hostname||(e.id?Tf(e.id):void 0))||"Unknown"}function l2(e){return String(e.daemon_id||e.daemonId||"")}function c2(e,t){const n=new Map(t.map(o=>[o.id,o])),a=[],r=new Map;for(const o of e){const i=l2(o);r.has(i)||(r.set(i,[]),a.push(i)),r.get(i).push(o)}return a.map(o=>{const i=r.get(o),c=o?n.get(o):void 0,d=i[0],p=o?c?oo(c):(d==null?void 0:d.machine_label)||(d==null?void 0:d.machine_nickname)||(d==null?void 0:d.hostname)||o:oo(c),u=(c==null?void 0:c.status)==="online",m=i.reduce((f,g)=>{var k;return f+(Array.isArray((k=g.policy)==null?void 0:k.slots)?g.policy.slots.length:0)},0);return{key:o,label:p,online:u,nodes:i,slotCount:m}})}function d2({groups:e,activeKey:t,onChange:n}){const{t:a}=ke("common");return s.jsx("div",{className:"flex items-center gap-1 px-1 border-b border-border-subtle mb-4 overflow-x-auto",role:"tablist","aria-label":a("repoMesh.nodeList.machineTabsLabel"),children:e.map(r=>{const o=r.key===t;return s.jsxs("button",{type:"button",role:"tab","aria-selected":o,onClick:()=>n(r.key),className:`flex items-center gap-2 px-3 py-2.5 text-[13px] font-medium border-b-2 -mb-px transition-colors cursor-pointer whitespace-nowrap ${o?"border-accent text-accent":"border-transparent text-text-muted hover:text-text-secondary"}`,children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${r.online?"bg-green-400":"bg-neutral-500"}`}),s.jsx("span",{className:"truncate max-w-[160px]",children:r.label}),s.jsx("span",{className:"text-[11px] text-text-muted font-normal",children:a("repoMesh.nodeList.machineTabCounts",{nodes:r.nodes.length,slots:r.slotCount})})]},r.key)})})}function u2({nodes:e,meshQueue:t,activeDaemon:n,daemons:a,selectedMeshId:r,userName:o,features:i,coordinatorDaemonId:c,availableCliProviders:d,savingNodeSlotsId:p,onUpdateNodeSlots:u,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:f,nodeSystemPromptDrafts:g,onNodeSystemPromptDraftChange:k,savingNodeSystemPromptId:h,onSaveNodeSystemPrompt:x,selectedNodeId:S,onSelectNode:b,showAddNode:w,onShowAddNode:C,onCancelAddNode:v,nodeWorkspace:y,onNodeWorkspaceChange:j,nodeProviderPriority:N,onNodeProviderPriorityChange:T,nodeDaemonId:A,onNodeDaemonIdChange:I,nodeCustomPath:D,onNodeCustomPathChange:M,nodePickerWorkspaces:E,nodePickerProviders:P,nodeOnboardingPlan:B,nodePlanLoading:R,attachableDaemons:W,onAddNode:_,onRemoveNode:H}){var Ce,me,O;const{t:L}=ke("common"),F=l.useMemo(()=>GL(a),[a]),$=l.useMemo(()=>e.filter(Y=>!wl(Y)),[e]),K=l.useMemo(()=>i.addNodeDaemonPicker?c2($,a):[],[i.addNodeDaemonPicker,$,a]),[z,ne]=l.useState(null),ie=K.some(Y=>Y.key===z)?z:((Ce=K[0])==null?void 0:Ce.key)??"";return s.jsxs(xt,{title:i.addNodeDaemonPicker?L("repoMesh.nodeList.title",{count:$.length}):L("repoMesh.nodeList.titleNoCount"),description:i.addNodeDaemonPicker?L("repoMesh.nodeList.descriptionCloud"):L("repoMesh.nodeList.descriptionStandalone"),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",{className:"min-w-0",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:L("repoMesh.nodeList.daemonCandidates")}),s.jsx("div",{className:"text-[12px] text-text-muted",children:L("repoMesh.nodeList.daemonCandidatesHint")})]}),s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:L("repoMesh.nodeList.available",{count:W.length})})]}),a.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:L("repoMesh.nodeList.noDaemonsAvailable")}):W.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:L("repoMesh.nodeList.allDaemonsAttached")}):s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:W.map(Y=>s.jsxs("button",{type:"button",className:`text-left rounded-lg border px-3 py-2 transition-colors min-w-0 ${Y.id===c?"border-accent-primary/50 bg-accent-primary/10":"border-border-subtle bg-bg-primary hover:border-border-default"}`,onClick:()=>{I(Y.id),j(""),M(!1),T(Pn(ln(Y.availableProviders||[]))),C()},children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-sm font-medium truncate min-w-0",children:oo(Y)}),Y.id===c&&s.jsx("span",{className:"text-[10px] text-accent-primary shrink-0",children:L("repoMesh.nodeList.selectedHost")})]}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted font-mono truncate",children:Y.id}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:L("repoMesh.nodeList.workspacesDetected",{count:(Y.workspaces||[]).length})})]},Y.id))})]}),!w&&s.jsxs("button",{className:"btn btn-primary btn-sm mb-4 inline-flex items-center gap-1.5",onClick:C,children:[s.jsx(BL,{size:13})," ",i.addNodeDaemonPicker?L("repoMesh.nodeList.attachMachine"):L("repoMesh.nodeList.addNode")]}),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?L("repoMesh.nodeList.attachMachineTitle"):L("repoMesh.nodeList.addNodeTitle")}),s.jsx("button",{onClick:()=>{v(),I(""),M(!1)},className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(Dt,{size:16})})]}),i.addNodeDaemonPicker&&s.jsx(Tt,{label:L("repoMesh.nodeList.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:A,onChange:Y=>{var X;I(Y.target.value),j(""),M(!1),T(Pn(ln(((X=a.find(Q=>Q.id===Y.target.value))==null?void 0:X.availableProviders)||[])))},children:[s.jsx("option",{value:"",children:L("repoMesh.nodeList.selectMachine")}),a.map(Y=>s.jsx("option",{value:Y.id,children:oo(Y)},Y.id))]})}),(i.addNodeDaemonPicker?A:!0)&&s.jsx(Tt,{label:L("repoMesh.nodeList.workspacePath"),children:i.addNodeDaemonPicker&&!D&&E.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex flex-col gap-1.5 mb-2",children:E.map(Y=>s.jsxs("button",{type:"button",className:`text-left text-xs px-3 py-2 rounded-lg border transition-colors ${y===Y.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:()=>j(Y.path),children:[s.jsx("span",{className:"font-medium block truncate",children:Y.label||Y.path.split("/").pop()}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:Y.path})]},Y.id||Y.path))}),s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{M(!0),j("")},children:L("repoMesh.nodeList.enterCustomPath")})]}):s.jsx(s.Fragment,{children:i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[s.jsx(xs,{value:y,onChange:Y=>j(Y.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:Y=>{Y.key==="Enter"&&_()}}),E.length>0&&s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0 mt-1",onClick:()=>{M(!1),j("")},children:L("repoMesh.nodeList.pickFromSaved")})]}):(()=>{var Q;const Y=Array.isArray(n==null?void 0:n.workspaces)?n.workspaces:[],X=`mesh-add-node-workspaces-${r||"new"}`;return s.jsxs(s.Fragment,{children:[s.jsx(xs,{value:y,onChange:ve=>j(ve.target.value),placeholder:((Q=Y[0])==null?void 0:Q.path)||"/Users/dev/projects/myapp",list:Y.length>0?X:void 0,autoFocus:!0}),Y.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("datalist",{id:X,children:Y.map(ve=>s.jsx("option",{value:ve.path,children:ve.label||ve.path},ve.id||ve.path))}),s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:Y.slice(0,6).map(ve=>s.jsx("button",{type:"button",onClick:()=>j(ve.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:ve.path,children:ve.label||ve.path.split("/").filter(Boolean).pop()||ve.path},ve.id||ve.path))})]})]})})()})}),(R||B)&&s.jsx(Mt,{variant:(B==null?void 0:B.success)===!1?"error":"info",className:"mb-4",children:R?"Inspecting Git repository (read-only)…":B!=null&&B.success?`${((me=B.plan)==null?void 0:me.summary)||"Compatible Git workspace detected."} Adding remains an explicit action.`:`${(B==null?void 0:B.code)||"onboarding_blocked"}: ${(B==null?void 0:B.error)||"Git discovery failed"} ${(B==null?void 0:B.action)||""}`}),s.jsx(Tt,{label:L("repoMesh.nodeList.preferredTools"),hint:L("repoMesh.nodeList.preferredToolsHint"),children:s.jsx(Gj,{value:N,availableProviders:i.addNodeDaemonPicker?P:d,onChange:T})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:_,disabled:R||(B==null?void 0:B.success)===!1||!y.trim()||i.addNodeDaemonPicker&&!A,className:"btn btn-primary btn-sm",children:L("repoMesh.nodeList.add")}),s.jsx("button",{onClick:()=>{v(),I(""),M(!1)},className:"btn btn-secondary btn-sm",children:L("repoMesh.nodeList.cancel")})]})]}),$.length===0?s.jsx(Ja,{icon:s.jsx(An,{}),title:L("repoMesh.nodeList.emptyTitle"),description:L("repoMesh.nodeList.emptyDescription")}):i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[K.length>1&&s.jsx(d2,{groups:K,activeKey:ie,onChange:ne}),s.jsx(Yu,{nodes:((O=K.find(Y=>Y.key===ie))==null?void 0:O.nodes)||$,meshQueue:t,activeDaemon:n,daemons:a,userName:o,features:i,providersByDaemonId:F,savingNodeSlotsId:p,onUpdateNodeSlots:u,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:f,nodeSystemPromptDrafts:g,onNodeSystemPromptDraftChange:k,savingNodeSystemPromptId:h,onSaveNodeSystemPrompt:x,selectedNodeId:S,onSelectNode:b,onRemoveNode:H})]}):s.jsx(Yu,{nodes:$,meshQueue:t,activeDaemon:n,daemons:a,userName:o,features:i,providersByDaemonId:F,savingNodeSlotsId:p,onUpdateNodeSlots:u,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:f,nodeSystemPromptDrafts:g,onNodeSystemPromptDraftChange:k,savingNodeSystemPromptId:h,onSaveNodeSystemPrompt:x,selectedNodeId:S,onSelectNode:b,onRemoveNode:H})]})}const p2=["claude-cli","codex-cli","gemini-cli","hermes-cli","antigravity-cli"],m2=[{kind:"rca",labelKey:"meshGraph.magiKind.kindRca",hint:"rca"},{kind:"design",labelKey:"meshGraph.magiKind.kindDesign",hint:"design"},{kind:"claim_audit",labelKey:"meshGraph.magiKind.kindClaimAudit",hint:"claim_audit"},{kind:"freeform",labelKey:"meshGraph.magiKind.kindFreeform",hint:"freeform"}];function h2(){return{nodeId:"",provider:"",model:"",n:""}}function Qu(e){var t;return(t=e.providers)!=null&&t.length?e.providers.filter(Boolean):(e.providerPriority??[]).filter(Boolean)}function f2(e){return{nodeId:e.nodeId??"",provider:e.provider??"",model:e.model??"",n:e.n!=null?String(e.n):""}}function g2(e){const t=[];for(let n=0;n<e.length;n++){const a=e[n],r=a.provider.trim();if(!r)return{error:{code:"provider_required",slot:n+1}};const o=a.nodeId.trim(),i=a.model.trim(),c=a.n.trim();let d;if(c){const p=Number(c);if(!Number.isFinite(p)||p<1)return{error:{code:"replica_min",slot:n+1}};d=Math.floor(p)}t.push({provider:r,...o?{nodeId:o}:{},...i?{model:i}:{},...d!==void 0?{n:d}:{}})}return t.length===0?{error:{code:"no_slot"}}:{slots:t}}function b2({status:e,daemonId:t,sendDaemonCommand:n,availableProviders:a}){const{t:r}=ke(),{theme:o}=Ls(),i=l.useMemo(()=>Rs(o),[o]),c=l.useMemo(()=>uh(a),[a]),[d,p]=l.useState({}),[u,m]=l.useState(!1),[f,g]=l.useState(null),[k,h]=l.useState({}),[x,S]=l.useState(null),b=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map($=>({nodeId:$.nodeId,machineLabel:$.machineLabel,providers:$.providers,providerPriority:$.providerPriority,isLocalWorktree:$.isLocalWorktree,worktreeBranch:$.worktreeBranch})),[e==null?void 0:e.nodes]),w=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map($=>$.nodeId),[e==null?void 0:e.nodes]),C=l.useMemo(()=>new Set(b.filter(wl).map($=>$.nodeId)),[b]),v=l.useMemo(()=>Object.fromEntries(b.filter(wl).map($=>[$.nodeId,$.worktreeBranch])),[b]),y=l.useMemo(()=>Object.fromEntries(((e==null?void 0:e.nodes)??[]).map($=>[$.nodeId,$.machineLabel||$.nodeId])),[e==null?void 0:e.nodes]),j=l.useMemo(()=>{const $={};for(const K of b)$[K.nodeId]=Qu(K);return $},[b]),N=l.useMemo(()=>{const $=[...new Set(b.flatMap(Qu).filter(Boolean))];return[...new Set([...$,...p2])].sort()},[b]),T=!!t&&!!n,A=$=>$&&typeof $=="object"&&"result"in $?$.result:$,I=e==null?void 0:e.meshId,D=l.useCallback(async()=>{if(!(!t||!n)){m(!0),g(null);try{const $=await n(t,"magi_kind_panel_list",{...I?{meshId:I}:{}}),K=A($);if((K==null?void 0:K.success)===!1)throw new Error(K.error||r("meshGraph.magiKind.errorLoad"));p(K!=null&&K.kindPanels&&typeof K.kindPanels=="object"?K.kindPanels:{}),h({})}catch($){g(($==null?void 0:$.message)||r("meshGraph.magiKind.errorLoad"))}finally{m(!1)}}},[t,n,I,r]);l.useEffect(()=>{D()},[D]);const M=l.useCallback($=>{if(k[$])return k[$];const K=d[$];return K?K.map(f2):[]},[k,d]),E=($,K)=>{h(z=>({...z,[$]:K}))},P=($,K,z)=>{const ne=M($);E($,ne.map((ie,Ce)=>Ce===K?{...ie,...z}:ie))},B=$=>{E($,[...M($),h2()])},R=($,K)=>{E($,M($).filter((z,ne)=>ne!==K))},W=l.useCallback(async $=>{if(!t||!n)return;const K=g2(M($));if("error"in K){const z=K.error,ne=z.code==="provider_required"?r("meshGraph.magiKind.errorSlotProvider",{slot:z.slot}):z.code==="replica_min"?r("meshGraph.magiKind.errorSlotReplica",{slot:z.slot}):r("meshGraph.magiKind.errorNoSlot");g(`${$}: ${ne}`);return}S($),g(null);try{const z=await n(t,"magi_kind_panel_set",{kind:$,slots:K.slots,...I?{meshId:I}:{}}),ne=A(z);if((ne==null?void 0:ne.success)===!1)throw new Error(ne.error||r("meshGraph.magiKind.errorSave"));await D()}catch(z){g((z==null?void 0:z.message)||r("meshGraph.magiKind.errorSave"))}finally{S(null)}},[t,n,M,D,I,r]),_=l.useCallback(async $=>{if(!(!t||!n)&&confirm(r("meshGraph.magiKind.removeConfirm",{kind:$}))){S($),g(null);try{const K=await n(t,"magi_kind_panel_remove",{kind:$,...I?{meshId:I}:{}}),z=A(K);if((z==null?void 0:z.success)===!1)throw new Error(z.error||r("meshGraph.magiKind.errorRemove"));await D()}catch(K){g((K==null?void 0:K.message)||r("meshGraph.magiKind.errorRemove"))}finally{S(null)}}},[t,n,D,I,r]),H=`w-full rounded-lg border px-2.5 py-1.5 text-xs ${i.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"}`,L="btn btn-primary btn-sm",F="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] ${i.textSecondary}`,children:r("meshGraph.magiKind.intro")}),s.jsx("div",{className:"ml-auto flex items-center gap-2",children:s.jsx("button",{type:"button",className:F,onClick:()=>void D(),disabled:u||!T,children:r(u?"meshGraph.magiKind.loading":"meshGraph.magiKind.refresh")})})]}),!T&&s.jsx("div",{className:`rounded-xl border p-3 text-[12px] ${i.textSecondary} ${i.isDark?"border-white/10":"border-slate-200"}`,children:r("meshGraph.magiKind.connectPrompt")}),f&&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:f}),s.jsx("div",{className:"flex flex-col gap-3",children:m2.map(({kind:$,labelKey:K,hint:z})=>{const ne=M($),ie=!!d[$],Ce=x===$;return s.jsxs("div",{className:`${i.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 ${i.textPrimary}`,children:r(K)}),s.jsx("span",{className:`font-mono text-[10px] ${i.textMuted}`,children:z}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${ie?"border-emerald-400/30 bg-emerald-500/10 text-emerald-300":"border-slate-400/20 bg-slate-500/10 text-slate-300"}`,children:ie?r("meshGraph.magiKind.agentCount",{count:d[$].length}):r("meshGraph.magiKind.off")})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[ne.length===0&&s.jsx("div",{className:`rounded-xl border p-2.5 text-[11px] ${i.textSecondary} ${i.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:r("meshGraph.magiKind.noAgents")}),ne.map((me,O)=>{const Y=me.nodeId?j[me.nodeId]??[]:[],X=me.nodeId&&Y.length?Y:N;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 ${i.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 ${i.textSecondary}`,children:r("meshGraph.magiKind.machine")}),s.jsxs("select",{className:H,value:me.nodeId,onChange:Q=>P($,O,{nodeId:Q.target.value}),title:r("meshGraph.magiKind.machineTitle"),children:[s.jsx("option",{value:"",children:r("meshGraph.magiKind.anyMachine")}),w.map(Q=>{const ve=C.has(Q),he=ve?r("meshGraph.magiKind.worktreeSuffix",{label:y[Q]??Q,branch:v[Q]||r("meshGraph.magiKind.worktreeUnknownBranch")}):y[Q]??Q;return s.jsx("option",{value:Q,disabled:ve,title:ve?r("meshGraph.magiKind.worktreeDisabledTitle"):void 0,children:he},Q)}),me.nodeId&&!w.includes(me.nodeId)&&s.jsx("option",{value:me.nodeId,children:r("meshGraph.magiKind.offlineSuffix",{label:y[me.nodeId]??me.nodeId})})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsxs("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:[r("meshGraph.magiKind.provider")," *"]}),s.jsxs("select",{className:H,value:me.provider,onChange:Q=>P($,O,{provider:Q.target.value}),title:r("meshGraph.magiKind.providerTitle"),children:[s.jsx("option",{value:"",children:r("meshGraph.magiKind.selectProvider")}),X.map(Q=>s.jsx("option",{value:Q,children:Q},Q)),me.provider&&!X.includes(me.provider)&&s.jsx("option",{value:me.provider,children:me.provider})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:r("meshGraph.magiKind.model")}),(()=>{var he;const Q=(me.provider?(he=c.get(me.provider))==null?void 0:he.models:void 0)??[],ve=!!me.model&&Q.length>0&&!Q.includes(me.model);return Q.length>0&&!ve?s.jsxs("select",{className:H,value:Q.includes(me.model)?me.model:"",title:r("meshGraph.magiKind.modelTitle"),onChange:Z=>P($,O,{model:Z.target.value==="__custom__"?" ":Z.target.value}),children:[s.jsx("option",{value:"",children:r("meshGraph.magiKind.modelDefault")}),Q.map(Z=>s.jsx("option",{value:Z,children:Z},Z)),s.jsx("option",{value:"__custom__",children:r("meshGraph.magiKind.modelCustom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:H,value:me.model.trim(),placeholder:r("meshGraph.magiKind.modelDefault"),title:r("meshGraph.magiKind.modelTitle"),onChange:Z=>P($,O,{model:Z.target.value})}),Q.length>0&&s.jsx("button",{type:"button",className:`self-start bg-transparent border-none cursor-pointer p-0 text-[10px] ${i.textSecondary} hover:underline`,onClick:()=>P($,O,{model:""}),children:r("meshGraph.magiKind.backToModelList")})]})})()]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:r("meshGraph.magiKind.copies")}),s.jsx("input",{className:`${H} sm:w-16`,value:me.n,placeholder:"1",inputMode:"numeric",title:r("meshGraph.magiKind.copiesTitle"),onChange:Q=>P($,O,{n:Q.target.value})})]}),s.jsx("button",{type:"button",className:`${F} sm:mt-[18px] inline-flex h-8 w-8 items-center justify-center p-0`,onClick:()=>R($,O),"aria-label":r("meshGraph.magiKind.removeAgent"),title:r("meshGraph.magiKind.removeAgent"),children:"✕"})]},O)}),s.jsx("div",{children:s.jsx("button",{type:"button",className:F,onClick:()=>B($),disabled:!T,children:r("meshGraph.magiKind.addAgent")})})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:L,onClick:()=>void W($),disabled:Ce||!T,children:r(Ce?"meshGraph.magiKind.saving":"meshGraph.magiKind.save")}),s.jsx("button",{type:"button",className:F,onClick:()=>void _($),disabled:Ce||!T||!ie,title:r(ie?"meshGraph.magiKind.removeBindingTitle":"meshGraph.magiKind.removeBindingDisabledTitle"),children:r("meshGraph.magiKind.removeBinding")})]})]},$)})})]})}const Wn={sessionMinRemainingPercent:10,weeklyMinRemainingPercent:15,sessionResetImminentMinutes:5,staleAfterMinutes:30,spreadBonusMax:30,sessionAxisWeeklyHeadroomPercent:40},kl=60*1e3;function Ju(e){return e===void 0||!Number.isFinite(e)?"":String(e/kl)}function Sl(e){const t=e??{};return{sessionMinRemainingPercent:t.sessionMinRemainingPercent!==void 0?String(t.sessionMinRemainingPercent):"",weeklyMinRemainingPercent:t.weeklyMinRemainingPercent!==void 0?String(t.weeklyMinRemainingPercent):"",sessionResetImminentMinutes:Ju(t.sessionResetImminentMs),staleAfterMinutes:Ju(t.staleAfterMs),spreadBonusMax:t.spreadBonusMax!==void 0?String(t.spreadBonusMax):"",sessionAxisWeeklyHeadroomPercent:t.sessionAxisWeeklyHeadroomPercent!==void 0?String(t.sessionAxisWeeklyHeadroomPercent):""}}function x2(e,t){const n=t.trim();if(!n)return null;const a=Number(n);if(!Number.isFinite(a))return"notANumber";const r=e==="sessionMinRemainingPercent"||e==="weeklyMinRemainingPercent"||e==="sessionAxisWeeklyHeadroomPercent";return r&&(a<0||a>100)?"percentRange":!r&&a<0?"negative":null}function Cl(e){const t={},n=p=>{const u=p.trim();if(!u)return;const m=Number(u);return Number.isFinite(m)?m:void 0},a=n(e.sessionMinRemainingPercent);a!==void 0&&(t.sessionMinRemainingPercent=a);const r=n(e.weeklyMinRemainingPercent);r!==void 0&&(t.weeklyMinRemainingPercent=r);const o=n(e.sessionResetImminentMinutes);o!==void 0&&(t.sessionResetImminentMs=o*kl);const i=n(e.staleAfterMinutes);i!==void 0&&(t.staleAfterMs=i*kl);const c=n(e.spreadBonusMax);c!==void 0&&(t.spreadBonusMax=c);const d=n(e.sessionAxisWeeklyHeadroomPercent);return d!==void 0&&(t.sessionAxisWeeklyHeadroomPercent=d),t}const v2="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs",y2="w-full rounded-lg border border-red-500/60 bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function w2({quotaRouting:e,saving:t,error:n,onSave:a}){const{t:r}=ke("common"),[o,i]=l.useState(()=>Sl(e)),c=l.useCallback((k,h)=>{i(x=>({...x,[k]:h}))},[]),d=l.useMemo(()=>{const k={};for(const h of Object.keys(o)){const x=x2(h,o[h]);x&&(k[h]=x)}return k},[o]),p=Object.keys(d).length>0,u=l.useMemo(()=>JSON.stringify(Cl(o))!==JSON.stringify(k2(e)),[o,e]),m=l.useCallback(()=>{p||a(Cl(o))},[o,p,a]),f=l.useCallback(()=>{i(Sl(null))},[]),g=[{key:"sessionMinRemainingPercent",label:r("setupWizard.quotaPolicy.sessionMin"),hint:r("setupWizard.quotaPolicy.sessionMinHint"),placeholder:Wn.sessionMinRemainingPercent,unit:"%"},{key:"weeklyMinRemainingPercent",label:r("setupWizard.quotaPolicy.weeklyMin"),hint:r("setupWizard.quotaPolicy.weeklyMinHint"),placeholder:Wn.weeklyMinRemainingPercent,unit:"%"},{key:"sessionResetImminentMinutes",label:r("setupWizard.quotaPolicy.resetImminent"),hint:r("setupWizard.quotaPolicy.resetImminentHint"),placeholder:Wn.sessionResetImminentMinutes,unit:r("setupWizard.quotaPolicy.minutes")},{key:"staleAfterMinutes",label:r("setupWizard.quotaPolicy.staleAfter"),hint:r("setupWizard.quotaPolicy.staleAfterHint"),placeholder:Wn.staleAfterMinutes,unit:r("setupWizard.quotaPolicy.minutes")},{key:"spreadBonusMax",label:r("setupWizard.quotaPolicy.spreadBonus"),hint:r("setupWizard.quotaPolicy.spreadBonusHint"),placeholder:Wn.spreadBonusMax,unit:""},{key:"sessionAxisWeeklyHeadroomPercent",label:r("setupWizard.quotaPolicy.sessionAxisWeeklyHeadroom"),hint:r("setupWizard.quotaPolicy.sessionAxisWeeklyHeadroomHint"),placeholder:Wn.sessionAxisWeeklyHeadroomPercent,unit:"%"}];return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:r("setupWizard.quotaPolicy.title")}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-text-muted",children:r("setupWizard.quotaPolicy.description")})]}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 sm:grid-cols-2",children:g.map(k=>{const h=d[k.key];return s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsxs("span",{className:"text-[11px] text-text-muted",children:[k.label,k.unit?` (${k.unit})`:""]}),s.jsx("input",{type:"number",inputMode:"decimal",className:h?y2:v2,value:o[k.key],placeholder:String(k.placeholder),onChange:x=>c(k.key,x.target.value)}),s.jsx("span",{className:`text-[10px] leading-snug ${h?"text-red-400":"text-text-muted"}`,children:h?r(`setupWizard.quotaPolicy.errors.${h}`):k.hint})]},k.key)})}),s.jsx("p",{className:"text-[10px] leading-relaxed text-text-muted",children:r("setupWizard.quotaPolicy.blankMeansDefault")}),n?s.jsx("p",{className:"text-[11px] text-red-400",children:n}):null,s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:f,children:r("setupWizard.quotaPolicy.useDefaults")}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm ml-auto",onClick:m,disabled:!!t||p||!u,children:r(t?"setupWizard.quotaPolicy.saving":"setupWizard.quotaPolicy.save")})]})]})}function k2(e){return Cl(Sl(e))}function ag(e,t,n,a){const{t:r}=ke(),[o,i]=l.useState(!1),[c,d]=l.useState(null),[p,u]=l.useState(null),[m,f]=l.useState(null),g=l.useCallback(async()=>{if(!e||!t){d(r("repoMesh.promptPreview.connectPrompt"));return}i(!0),d(null);try{const k=await a(e,"coordinator_prompt_preview",{meshId:t,cliType:n}),h=k!=null&&k.result&&typeof k.result=="object"?k.result:k;if(!(h!=null&&h.success))return d((h==null?void 0:h.error)||r("repoMesh.promptPreview.errorRender")),null;const x=typeof h.prompt=="string"?h.prompt:"";return u(x),f(typeof h.bytes=="number"?h.bytes:null),x}catch(k){return d((k==null?void 0:k.message)||String(k)),null}finally{i(!1)}},[e,t,n,a,r]);return{loading:o,error:c,prompt:p,bytes:m,load:g}}function S2({daemonId:e,meshId:t,cliType:n,sendCommand:a,defaultOpen:r=!1}){const{t:o}=ke(),[i,c]=l.useState(r),{loading:d,error:p,prompt:u,bytes:m,load:f}=ag(e,t,n,a),g=l.useRef(!1);l.useEffect(()=>{i&&!g.current&&(g.current=!0,f())},[i,f]);const k=l.useCallback(()=>{c(h=>!h)},[]);return s.jsxs("div",{className:"mt-2",children:[s.jsxs("button",{type:"button",onClick:k,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 ${i?"rotate-90":""}`,"aria-hidden":!0,children:"▸"}),o(i?"repoMesh.promptPreview.hide":"repoMesh.promptPreview.view"),s.jsxs("span",{className:"text-text-muted",children:["(",n,")"]})]}),i&&s.jsxs("div",{className:"mt-2",children:[d&&s.jsx("div",{className:"text-[12px] text-text-muted",children:o("repoMesh.promptPreview.rendering")}),p&&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:[p,s.jsx("button",{type:"button",onClick:()=>void f(),className:"ml-2 underline bg-transparent border-none cursor-pointer text-amber-300",children:o("repoMesh.promptPreview.retry")})]}),!d&&!p&&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:o("repoMesh.promptPreview.info")}),m!==null&&s.jsxs("span",{children:[(m/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:h=>h.currentTarget.select()})]})]})]})}function C2({daemonId:e,meshId:t,cliType:n,sendCommand:a,disabled:r,hasContent:o,onApply:i}){const{t:c}=ke(),{loading:d,load:p}=ag(e,t,n,a),u=l.useCallback(async()=>{if(o&&!window.confirm(c("repoMesh.detail.startFromDefaultConfirm")))return;const m=await p();typeof m=="string"&&i(m)},[o,p,i,c]);return s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm mt-2",onClick:()=>void u(),disabled:r||d||!e||!t,title:c("repoMesh.detail.startFromDefaultTitle"),children:c(d?"repoMesh.promptPreview.rendering":"repoMesh.detail.startFromDefault")})}const j2=[{token:"meshName",description:"This mesh's display name.",example:"my-app"},{token:"repo",description:"Repo identity (owner/repo or workspace path).",example:"vilmire/adhdev"},{token:"defaultBranch",description:"The mesh's default branch.",example:"main"},{token:"cliType",description:"The coordinator CLI type this prompt is being rendered for.",example:"claude-cli"},{token:"nodes",description:"Live node status table, or the configured node list if no live status is available.",example:"(rendered node table)"},{token:"mission",description:"Current mission section, when a mission is active. Empty otherwise.",example:"(mission summary or empty)"},{token:"recentActivity",description:"Recent mesh activity summary. Empty when none.",example:"(recent activity or empty)"},{token:"operatingNotes",description:"Accumulated operating notes for this mesh. Empty when none.",example:"(operating notes or empty)"},{token:"policy",description:"The mesh's effective policy section (safety, scheduling, etc.).",example:"(rendered policy section)"},{token:"tools",description:"The canonical MCP tools reference table.",example:"(tools table)"},{token:"workflow",description:"The standard coordinator workflow guidance section.",example:"(workflow section)"},{token:"onboarding",description:"Onboarding/reinit guidance section.",example:"(onboarding section)"},{token:"rules",description:"CLI-type-specific and policy-derived rules section.",example:"(rules section)"},{token:"toolExposurePreflight",description:"Preflight guidance for verifying tool exposure before relying on it.",example:"(preflight section)"}],N2=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function A2(e){const t=N2(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function T2(e){const t=e==null?void 0:e.missions;return Array.isArray(t)?t:[]}function M2(e){return typeof e.goal=="string"&&e.goal?{text:e.goal,truncated:!1}:{text:e.goalPreview??"",truncated:e.goalTruncated===!0}}const P2=["active","paused","completed","abandoned"];function Xu(e){return(e.status||"active").toLowerCase()}const D2=8;function I2({status:e,daemonId:t,meshId:n,sendCommand:a}){const{t:r}=ke("common"),o=l.useMemo(()=>T2(e),[e]),[i,c]=l.useState({}),[d,p]=l.useState({}),[u,m]=l.useState(!1),[f,g]=l.useState(null),[k,h]=l.useState("active"),[x,S]=l.useState(!1),b=l.useMemo(()=>{const T={};for(const A of o){const I=Xu(A);T[I]=(T[I]||0)+1}return T},[o]),w=l.useMemo(()=>k==="all"?o:o.filter(T=>Xu(T)===k),[o,k]),C=x?w:w.slice(0,D2),v=w.length-C.length,y=!!t&&o.length>0,j=l.useCallback(async()=>{if(t){m(!0),g(null);try{const T=await a(t,"mesh_status",{meshId:n,verbose:!0}),A=A2(T),I=Array.isArray(A==null?void 0:A.missions)?A.missions:[],D={};for(const M of I)M.id&&typeof M.goal=="string"&&M.goal&&(D[M.id]=M.goal);c(M=>({...M,...D}))}catch(T){g(T instanceof Error?T.message:r("repoMesh.missions.errorFetch"))}finally{m(!1)}}},[t,n,a,r]),N=l.useCallback(T=>{p(A=>({...A,[T]:!A[T]})),!d[T]&&!i[T]&&j()},[d,i,j]);return o.length===0?null:s.jsxs(xt,{title:r("repoMesh.missions.title"),description:r("repoMesh.missions.description"),children:[f&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400",children:f}),s.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-1.5",children:[P2.filter(T=>(b[T]||0)>0).map(T=>s.jsxs("button",{type:"button",onClick:()=>{h(T),S(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] capitalize transition-colors ${k===T?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:[T," ",b[T]]},T)),s.jsxs("button",{type:"button",onClick:()=>{h("all"),S(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] transition-colors ${k==="all"?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:["All ",o.length]})]}),w.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:r("repoMesh.missions.empty",{status:k})}),s.jsx("div",{className:"flex flex-col gap-2",children:C.map(T=>{var B;const A=d[T.id]===!0,I=i[T.id],D=M2(T),M=A&&I?I:D.text,E=A&&!I&&D.truncated,P=((B=T.tasks)==null?void 0:B.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:T.title,children:T.title||T.id}),T.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:T.status}),P>0&&s.jsx("span",{className:"shrink-0 text-[11px] text-text-muted",children:r("repoMesh.missions.taskCount",{count:P})})]}),M&&s.jsxs("div",{className:`mt-1.5 whitespace-pre-wrap text-[12px] leading-5 text-text-secondary ${A?"max-h-72 overflow-y-auto":"line-clamp-2"}`,children:[M,E&&s.jsx("span",{className:"text-text-muted",children:r("repoMesh.missions.goalUnavailable")})]}),(D.truncated||I)&&y&&s.jsx("button",{type:"button",className:"mt-1.5 text-[12px] text-accent-primary hover:underline disabled:opacity-50",onClick:()=>N(T.id),disabled:u,children:r(A?"repoMesh.missions.showLess":u&&!I?"repoMesh.missions.loading":"repoMesh.missions.showFullGoal")})]},T.id)})}),v>0&&s.jsx("button",{type:"button",className:"mt-2 text-[12px] text-accent-primary hover:underline",onClick:()=>S(!0),children:r("repoMesh.missions.showMore",{count:v})})]})}function Zu(e,t){if(t)return e.modes.find(n=>n.id===t)}function L2(e){return e.modes.find(t=>t.strategy==="pty-parse-default"&&Gs(t)!=="dangerous")}function R2({config:e,requestedModeId:t,machineAutoApproveEnabled:n,machineDangerousAllowed:a}){const r=Zu(e,e.default),o=r==null?void 0:r.id,i=(t==null?void 0:t.trim())||void 0;if(!n)return{status:"disabled",requestedModeId:i,providerDefaultModeId:o,requestedModeUnknown:!1,downgraded:!1};const c=Zu(e,i),d=!!i&&!c,p=c??r;if(!p||p.strategy==="post-boot-command")return{status:"none",requestedModeId:i,providerDefaultModeId:o,requestedModeUnknown:d,downgraded:!1};if(Gs(p)==="dangerous"&&!a){const u=L2(e);return{status:u?"downgraded":"none",requestedModeId:i,providerDefaultModeId:o,effectiveMode:u,requestedModeUnknown:d,downgraded:!0}}return{status:d?"invalid_fallback":"requested",requestedModeId:i,providerDefaultModeId:o,effectiveMode:p,requestedModeUnknown:d,downgraded:!1}}function E2(e){const t=[];for(const n of e||[]){if(!n||n.category!=="cli")continue;const a=n.autoApproveModes;if(!a||!Array.isArray(a.modes)||a.modes.length===0)continue;const r=String(n.type||n.id||"").trim();r&&t.push({type:r,label:String(n.displayName||n.name||r),autoApproveModes:a})}return t}function _2({hostDaemonId:e,hostOnline:t,hostWorkspace:n,meshProviders:a,unreportedNodeCount:r=0,machineAutoApproveEnabled:o,machineDangerousAllowed:i,onUpdatePolicy:c,savingPolicy:d,sendCommand:p}){const{t:u}=ke("common"),m=l.useMemo(()=>E2(a),[a]),[f,g]=l.useState({}),[k,h]=l.useState(!1),[x,S]=l.useState(null),[b,w]=l.useState(!1),[C,v]=l.useState(null),[y,j]=l.useState(!1),[N,T]=l.useState(null),[A,I]=l.useState(!1),D=!!e&&t&&!!n,M=!!c&&!d,E=l.useCallback(async()=>{var _,H,L;if(D){h(!0),S(null);try{const F=await p(e,"read_mesh_json_config",{workspace:n}),$=(F==null?void 0:F.result)??F,K=((_=$==null?void 0:$.providerDefaults)==null?void 0:_.autoApproveModes)||((L=(H=$==null?void 0:$.config)==null?void 0:H.providerDefaults)==null?void 0:L.autoApproveModes),z={};if(K&&typeof K=="object")for(const[ne,ie]of Object.entries(K))typeof ie=="string"&&ie.trim()&&(z[ne]=ie.trim());g(z)}catch(F){S((F==null?void 0:F.message)||u("repoMesh.providerAutoApprove.loadError"))}finally{h(!1)}}},[D,e,n,p,u]);l.useEffect(()=>{E()},[E]);const P=l.useCallback((_,H)=>{j(!1),g(L=>{const F={...L};return H&&H.trim()?F[_]=H.trim():delete F[_],F})},[]),B=l.useCallback((_,H)=>{if(Gs(H)==="dangerous"){T({type:_,mode:H});return}P(_,H.id)},[P]),R=l.useCallback(()=>{N&&P(N.type,N.mode.id),T(null)},[P,N]),W=l.useCallback(async()=>{if(D){w(!0),v(null),j(!1);try{const _=await p(e,"set_mesh_provider_defaults",{workspace:n,autoApproveModes:f,merge:!1,write:!0}),H=(_==null?void 0:_.result)??_;if((H==null?void 0:H.success)===!1)throw new Error((H==null?void 0:H.error)||u("repoMesh.providerAutoApprove.saveError"));j(!0),await E()}catch(_){v((_==null?void 0:_.message)||u("repoMesh.providerAutoApprove.saveError"))}finally{w(!1)}}},[D,e,n,E,f,p,u]);return s.jsxs(xt,{title:u("repoMesh.providerAutoApprove.title"),description:u("repoMesh.providerAutoApprove.subtitle"),collapsible:!0,defaultOpen:!1,children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/40 p-3.5",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:u("repoMesh.providerAutoApprove.machineSection.title")}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:u("repoMesh.providerAutoApprove.machineSection.hint")}),s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2 text-[11px]",children:[s.jsx("span",{className:`rounded-full border px-2 py-0.5 font-semibold ${o?"border-status-online/25 bg-status-online/10 text-status-online":"border-border-subtle bg-surface-secondary/40 text-text-muted"}`,children:u(o?"repoMesh.providerAutoApprove.machineSection.autoApproveOn":"repoMesh.providerAutoApprove.machineSection.autoApproveOff")}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 font-semibold ${i?"border-status-error/30 bg-status-error/10 text-status-error":"border-border-subtle bg-surface-secondary/40 text-text-muted"}`,children:u(i?"repoMesh.providerAutoApprove.machineSection.dangerousOn":"repoMesh.providerAutoApprove.machineSection.dangerousOff")})]}),s.jsxs("div",{className:"mt-3 space-y-2",children:[s.jsx(ep,{label:u("repoMesh.providerAutoApprove.machineSection.autoApproveToggleLabel"),hint:u("repoMesh.providerAutoApprove.machineSection.autoApproveToggleHint"),checked:o,disabled:!M,onChange:_=>c==null?void 0:c({delegatedWorkerAutoApprove:_})}),s.jsx(ep,{label:u("repoMesh.providerAutoApprove.machineSection.dangerousToggleLabel"),hint:u(o?"repoMesh.providerAutoApprove.machineSection.dangerousToggleHint":"repoMesh.providerAutoApprove.machineSection.dangerousDisabledHint"),checked:i,disabled:!M||!o,onChange:_=>{_?I(!0):c==null||c({delegatedWorkerDangerousModeAllow:!1})}})]})]}),D?k?s.jsx("div",{className:"text-[13px] text-text-muted",children:u("repoMesh.providerAutoApprove.loading")}):m.length===0?s.jsx("div",{className:"text-[13px] text-text-muted",children:r>0?u("repoMesh.providerAutoApprove.awaitingNodes",{count:r}):u("repoMesh.providerAutoApprove.noProviders")}):s.jsxs("div",{className:"space-y-6",children:[x&&s.jsx(Mt,{variant:"error",onDismiss:()=>S(null),children:x}),r>0&&s.jsx("div",{className:"text-[11px] text-text-muted",children:u("repoMesh.providerAutoApprove.partialInventory",{count:r})}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:u("repoMesh.providerAutoApprove.repoSection.title")}),s.jsx("div",{className:"text-[11px] text-text-muted",children:u("repoMesh.providerAutoApprove.repoSection.hint")})]}),s.jsx("div",{className:"space-y-5",children:m.map(_=>{const H=f[_.type],L=R2({config:_.autoApproveModes,requestedModeId:H,machineAutoApproveEnabled:o,machineDangerousAllowed:i});return s.jsxs("div",{className:"rounded-xl border border-border-subtle p-3.5",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary",children:_.label}),s.jsx("button",{type:"button",className:"text-[11px] text-text-muted underline decoration-dotted hover:text-text-primary disabled:opacity-40",onClick:()=>P(_.type,void 0),disabled:!H||b,children:u("repoMesh.providerAutoApprove.repoSection.clear")})]}),s.jsx(lf,{config:_.autoApproveModes,selectedModeId:H||"",disabled:b,onSelectMode:F=>B(_.type,F)}),!H&&s.jsx("div",{className:"mt-1.5 text-[11px] text-text-muted",children:u("repoMesh.providerAutoApprove.repoSection.usesProviderDefault")}),s.jsx(H2,{effective:L,config:_.autoApproveModes})]},_.type)})}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:u("repoMesh.providerAutoApprove.effectiveSection.title")}),s.jsx("div",{className:"text-[11px] text-text-muted",children:u("repoMesh.providerAutoApprove.effectiveSection.hint")})]}),C&&s.jsx(Mt,{variant:"error",onDismiss:()=>v(null),children:C}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("button",{type:"button",className:"rounded-lg bg-accent-primary px-4 py-2 text-sm font-semibold text-white disabled:opacity-50",onClick:()=>void W(),disabled:b,children:u(b?"repoMesh.providerAutoApprove.saving":"repoMesh.providerAutoApprove.save")}),y&&s.jsx("span",{className:"text-[12px] text-status-online",children:u("repoMesh.providerAutoApprove.saved")})]})]}):s.jsx("div",{className:"text-[13px] text-text-muted",children:u("repoMesh.providerAutoApprove.noHostDaemon")}),A&&s.jsx(jo,{title:u("repoMesh.providerAutoApprove.machineSection.confirmTitle"),description:u("repoMesh.providerAutoApprove.machineSection.confirmDescription"),details:[{label:u("repoMesh.providerAutoApprove.machineSection.confirmScopeLabel"),value:u("repoMesh.providerAutoApprove.machineSection.confirmScopeValue")},{label:u("repoMesh.providerAutoApprove.machineSection.confirmEffectLabel"),value:u("repoMesh.providerAutoApprove.machineSection.confirmEffectValue")}],confirmLabel:u("repoMesh.providerAutoApprove.machineSection.confirmConfirm"),onConfirm:()=>{I(!1),c==null||c({delegatedWorkerDangerousModeAllow:!0})},onCancel:()=>I(!1)}),N&&s.jsx(cf,{mode:N.mode,onConfirm:R,onCancel:()=>T(null)}),N&&s.jsx("div",{className:"fixed inset-x-0 bottom-6 z-[60] mx-auto max-w-lg px-4",children:s.jsxs("div",{className:"rounded-xl border border-status-error/40 bg-bg-primary p-3.5 shadow-lg",children:[s.jsx("div",{className:"text-sm font-semibold text-status-error",children:u("repoMesh.providerAutoApprove.dangerous.sharedWarningTitle")}),s.jsx("div",{className:"mt-1 text-[12px] text-text-muted",children:u("repoMesh.providerAutoApprove.dangerous.sharedWarning")})]})})]})}function H2({effective:e,config:t}){var c,d,p;const{t:n}=ke("common"),a=u=>{var m;return(u?(m=t.modes.find(f=>f.id===u))==null?void 0:m.label:void 0)||u||""};let r,o="ok";switch(e.status){case"requested":r=n("repoMesh.providerAutoApprove.effectiveSection.statusRequested",{mode:((c=e.effectiveMode)==null?void 0:c.label)||""});break;case"invalid_fallback":r=n("repoMesh.providerAutoApprove.effectiveSection.statusInvalidFallback",{mode:((d=e.effectiveMode)==null?void 0:d.label)||""}),o="warn";break;case"downgraded":r=n("repoMesh.providerAutoApprove.effectiveSection.statusDowngraded",{requested:a(e.requestedModeId)||a(e.providerDefaultModeId),mode:((p=e.effectiveMode)==null?void 0:p.label)||""}),o="warn";break;case"disabled":r=n("repoMesh.providerAutoApprove.effectiveSection.statusDisabled"),o="muted";break;default:r=n("repoMesh.providerAutoApprove.effectiveSection.statusNone"),o="muted"}const i=o==="ok"?"border-status-online/25 bg-status-online/5 text-text-secondary":o==="warn"?"border-status-warning/30 bg-status-warning/5 text-status-warning":"border-border-subtle bg-surface-secondary/30 text-text-muted";return s.jsxs("div",{className:`mt-3 flex items-center gap-2 rounded-lg border px-3 py-2 text-[12px] ${i}`,children:[e.effectiveMode&&s.jsx(of,{risk:Gs(e.effectiveMode)}),s.jsx("span",{className:"min-w-0",children:r})]})}function ep({label:e,hint:t,checked:n,disabled:a=!1,onChange:r}){return s.jsxs("button",{type:"button",role:"switch","aria-checked":n,className:"flex w-full items-center justify-between gap-3 rounded-xl border border-border-subtle bg-bg-primary/60 px-3.5 py-2.5 text-left disabled:opacity-50",onClick:()=>r(!n),disabled:a,children:[s.jsxs("span",{children:[s.jsx("span",{className:"block text-[13px] font-semibold text-text-primary",children:e}),s.jsx("span",{className:"mt-0.5 block text-[11px] text-text-muted",children:t})]}),s.jsx("span",{className:`relative h-6 w-11 shrink-0 rounded-full transition-colors ${n?"bg-accent-primary":"bg-surface-secondary"}`,children:s.jsx("span",{className:`absolute top-0.5 h-5 w-5 rounded-full bg-white shadow transition-transform ${n?"translate-x-5":"translate-x-0.5"}`})})]})}function kr(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function $2({daemons:e,coordinatorDaemonId:t,onCoordinatorDaemonIdChange:n,isHostNodeAttached:a,selectedHostNode:r,hostPinned:o,hostLabel:i,hostOnline:c,hostRebindDaemonId:d,onHostRebindDaemonIdChange:p,settingMeshHost:u,onSetMeshHost:m}){const{t:f}=ke("common");if(o)return s.jsxs(xt,{title:f("repoMesh.host.title"),description:f("repoMesh.host.descriptionSet"),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 ${c?"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:f("repoMesh.host.hostLabel")}),s.jsx("span",{className:"font-medium",children:i||f("repoMesh.host.unknown")}),s.jsxs("span",{className:c?"text-text-muted":"text-amber-400",children:["· ",f(c?"repoMesh.host.online":"repoMesh.host.offline")]})]}),(r==null?void 0:r.workspace)&&s.jsxs("span",{className:"text-[12px] text-text-muted",children:[f("repoMesh.host.hostNode")," ",s.jsx("span",{className:"font-mono text-text-secondary",children:r.workspace})]})]}),!c&&s.jsxs("div",{className:"mt-4",children:[s.jsxs(Mt,{variant:"warning",className:"mb-3",children:[s.jsx("strong",{children:f("repoMesh.host.hostOffline")})," ",f("repoMesh.host.hostOfflineText")]}),e.length>0?s.jsx(Tt,{label:f("repoMesh.host.reconnectToCommand"),hint:f("repoMesh.host.reconnectToCommandHint"),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:d,onChange:h=>p(h.target.value),children:[s.jsx("option",{value:"",children:f("repoMesh.host.waitForHost")}),e.map(h=>s.jsx("option",{value:h.id,children:kr(h)},h.id))]})}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:f("repoMesh.host.noDaemonsToRoute")})]})]});const g=e.find(h=>h.id===t),k=m&&t?s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>m(t),disabled:!!u,children:f(u?"repoMesh.host.settingHost":"repoMesh.host.setHostAction")}):null;return s.jsxs(xt,{title:f("repoMesh.host.title"),description:f("repoMesh.host.descriptionUnset"),children:[s.jsxs(Mt,{variant:"info",className:"mb-4",children:[s.jsx("strong",{children:f("repoMesh.host.setHostBanner")})," ",f("repoMesh.host.setHostBannerText")]}),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:a?s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:kr(g)}),r!=null&&r.workspace?s.jsxs(s.Fragment,{children:[" · setup node ",s.jsx("span",{className:"font-mono text-text-secondary",children:r.workspace})]}):null,". ",f("repoMesh.host.confirmSetsHost")]}):s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:kr(g)}),". ",f("repoMesh.host.attachNodeThenSetHost")]})}):s.jsx(Tt,{label:f("repoMesh.host.hostDaemon"),hint:f("repoMesh.host.hostDaemonHint"),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:h=>n(h.target.value),children:[s.jsx("option",{value:"",children:f("repoMesh.host.resolvingHost")}),e.map(h=>s.jsx("option",{value:h.id,children:kr(h)},h.id))]})}),k&&s.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[k,s.jsx("span",{className:"text-[12px] text-text-muted",children:f("repoMesh.host.setHostActionHint")})]})]}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:f("repoMesh.host.noDaemonsToHost")})]})}function F2({meshId:e,availableCliAgents:t}){const{t:n}=ke(),a=t.find(o=>{const i=o.id.toLowerCase();return i==="hermes-cli"||i.includes("hermes")||o.name.toLowerCase().includes("hermes")}),r=Eh(a==null?void 0:a.meshCoordinator,{meshId:e});return r?s.jsx(xt,{title:n("repoMesh.hermesMcp.title"),description:n("repoMesh.hermesMcp.description"),children:s.jsx(rf,{setup:r,providerName:(a==null?void 0:a.name)||n("repoMesh.hermesMcp.fallbackProvider")})}):null}const Ri=[{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."}],B2=[{value:"smart",labelKey:"repoMesh.detail.distributionSmart",descriptionKey:"repoMesh.detail.distributionSmartDescription"},{value:"in_order",labelKey:"repoMesh.detail.distributionInOrder",descriptionKey:"repoMesh.detail.distributionInOrderDescription"}];function W2(e){return e==="smart"?"fitness":"first_eligible"}function O2(e,t){const n=e||"first_eligible";return n==="fitness"||n==="least_loaded"||n==="round_robin"||n==="priority_only"&&t!=null&&t.priorityConfigured?"smart":"in_order"}const U2={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,schedulingStrategy:"first_eligible",sessionCleanupOnNodeRemove:"preserve"};function jl(e){return{...U2,...(e==null?void 0:e.policy)||{}}}function G2(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 q2({selectedMesh:e,error:t,onDismissError:n,onBack:a,onDelete:r,displayedMeshStatus:o,graphLoading:i,graphError:c,onRefreshGraph:d,savingPolicy:p,onUpdatePolicy:u,coordinatorPromptDraft:m,onCoordinatorPromptDraftChange:f,savingCoordinatorPrompt:g,onSaveCoordinatorPrompt:k,daemons:h,coordinatorDaemonId:x,onCoordinatorDaemonIdChange:S,coordinatorCliType:b,isHostNodeAttached:w,selectedHostNode:C,hostPinned:v,hostLabel:y,hostOnline:j,hostRebindDaemonId:N,onHostRebindDaemonIdChange:T,settingMeshHost:A,onSetMeshHost:I,activeDaemon:D,activeDaemonId:M,meshQueue:E,userName:P,availableCliProviders:B,savingNodeSlotsId:R,onUpdateNodeSlots:W,savingNodeCapabilitiesId:_,onUpdateNodeCapabilities:H,nodeSystemPromptDrafts:L,onNodeSystemPromptDraftChange:F,savingNodeSystemPromptId:$,onSaveNodeSystemPrompt:K,selectedNodeId:z,onSelectNode:ne,showAddNode:ie,onShowAddNode:Ce,onCancelAddNode:me,nodeWorkspace:O,onNodeWorkspaceChange:Y,nodeProviderPriority:X,onNodeProviderPriorityChange:Q,nodeDaemonId:ve,onNodeDaemonIdChange:he,nodeCustomPath:Z,onNodeCustomPathChange:fe,nodePickerWorkspaces:V,nodePickerProviders:q,nodeOnboardingPlan:ee,nodePlanLoading:pe,attachableDaemons:le,onAddNode:se,onRemoveNode:te,availableCliAgents:ue,features:ye,sendCommand:Me}){const{t:re}=ke("common"),ce=jl(e),Ae=e.nodes||[],be=l.useMemo(()=>zL(Ae,h),[Ae,h]),we=Ae.some(et=>{var Le;const J=Number((Le=et.policy)==null?void 0:Le.schedulingPriority);return Number.isFinite(J)&&J!==0}),_e=!ce.schedulingStrategy,U=l.useMemo(()=>Ae.some(et=>{var J;return Array.isArray((J=et.policy)==null?void 0:J.slots)&&et.policy.slots.length>0}),[Ae]),Ne=_e&&(U||Ae.length>=2)?"smart":null,[Ie,We]=l.useState(!1),Xe=!!M&&!!e.id;return s.jsxs(Qa,{icon:s.jsx(cs,{}),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:a,children:re("repoMesh.detail.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(HL,{size:13}),re(i?"repoMesh.detail.probing":"repoMesh.detail.refresh")]}),s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>r(e.id),children:re("repoMesh.detail.delete")})]}),children:[t&&s.jsx(Mt,{variant:"error",onDismiss:n,className:"mb-4",children:t}),(()=>{var rt;const et=s.jsxs(s.Fragment,{children:[ye.meshHostDaemonSection&&s.jsx($2,{daemons:h,coordinatorDaemonId:x,onCoordinatorDaemonIdChange:S,isHostNodeAttached:w,selectedHostNode:C,hostPinned:v,hostLabel:y,hostOnline:j,hostRebindDaemonId:N,onHostRebindDaemonIdChange:G=>{T(G),d()},settingMeshHost:A,onSetMeshHost:I}),s.jsxs(xt,{title:re("repoMesh.detail.observabilityTitle"),description:re("repoMesh.detail.observabilityDescription"),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:()=>We(!0),disabled:!Xe,title:re(Xe?"repoMesh.detail.observabilityOpenTitle":"repoMesh.detail.observabilityDisabledTitle"),children:[s.jsx(cs,{size:14}),re("repoMesh.detail.observabilityOpen")]}),s.jsx("span",{className:"text-[12px] text-text-muted",children:re("repoMesh.detail.observabilityHint")})]})]}),s.jsx(u2,{nodes:Ae,meshQueue:E,activeDaemon:D,daemons:h,selectedMeshId:e.id,userName:P,features:{addNodeDaemonPicker:ye.addNodeDaemonPicker,nodeInstruction:ye.nodeInstruction},coordinatorDaemonId:x,availableCliProviders:B,savingNodeSlotsId:R,onUpdateNodeSlots:W,savingNodeCapabilitiesId:_,onUpdateNodeCapabilities:H,nodeSystemPromptDrafts:L,onNodeSystemPromptDraftChange:F,savingNodeSystemPromptId:$,onSaveNodeSystemPrompt:K,selectedNodeId:z,onSelectNode:ne,showAddNode:ie,onShowAddNode:Ce,onCancelAddNode:me,nodeWorkspace:O,onNodeWorkspaceChange:Y,nodeProviderPriority:X,onNodeProviderPriorityChange:Q,nodeDaemonId:ve,onNodeDaemonIdChange:he,nodeCustomPath:Z,onNodeCustomPathChange:fe,nodePickerWorkspaces:V,nodePickerProviders:q,nodeOnboardingPlan:ee,nodePlanLoading:pe,attachableDaemons:le,onAddNode:se,onRemoveNode:te})]}),J=s.jsxs(s.Fragment,{children:[s.jsxs(xt,{title:re("repoMesh.detail.schedulingTitle"),description:re("repoMesh.detail.schedulingDescription"),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:re("repoMesh.detail.distribution")}),s.jsx("div",{className:"flex flex-col gap-2",children:B2.map(G=>{const de=O2(ce.schedulingStrategy,{priorityConfigured:we})===G.value;return s.jsxs("label",{className:`flex items-start gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${de?"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:G.value,checked:de,disabled:p,onChange:()=>u({schedulingStrategy:W2(G.value)})}),s.jsxs("span",{className:"min-w-0",children:[s.jsxs("span",{className:"flex items-center gap-2 text-sm text-text-primary",children:[re(G.labelKey),Ne===G.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:re("repoMesh.detail.recommended")})]}),s.jsx("span",{className:"block text-[12px] text-text-muted",children:re(G.descriptionKey)})]})]},G.value)})})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:re("repoMesh.detail.saving")})]}),s.jsx(xt,{title:re("repoMesh.detail.visibilityTitle"),description:re("repoMesh.detail.visibilityDescription"),children:s.jsx(Tt,{label:re("repoMesh.detail.visibilityLabel"),hint:re("repoMesh.detail.visibilityHint"),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:ce.spawnedSessionVisibility==="visible"?"visible":"hidden",onChange:G=>u({spawnedSessionVisibility:G.target.value==="visible"?"visible":"hidden"}),disabled:p,children:[s.jsx("option",{value:"hidden",children:re("repoMesh.detail.visibilityHidden")}),s.jsx("option",{value:"visible",children:re("repoMesh.detail.visibilityVisible")})]})})}),o&&s.jsx(xt,{title:re("repoMesh.detail.magiTitle"),description:re("repoMesh.detail.magiDescription"),children:s.jsx(b2,{status:o,daemonId:M,sendDaemonCommand:Me,availableProviders:B})}),s.jsx(xt,{children:s.jsx(w2,{quotaRouting:ce.quotaRouting??null,saving:p,error:t,onSave:G=>u({quotaRouting:G})})}),s.jsx(_2,{hostDaemonId:x,hostOnline:j,hostWorkspace:(C==null?void 0:C.workspace)||"",meshProviders:be.providers,unreportedNodeCount:be.unreportedNodeCount,machineAutoApproveEnabled:ce.delegatedWorkerAutoApprove!==!1,machineDangerousAllowed:ce.delegatedWorkerDangerousModeAllow===!0,onUpdatePolicy:u,savingPolicy:p,sendCommand:Me})]}),Le=s.jsx(s.Fragment,{children:ye.coordinatorPrompt&&s.jsx(xt,{title:re("repoMesh.detail.coordinatorPromptTitle"),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:re("repoMesh.detail.advanced")}),description:re("repoMesh.detail.coordinatorPromptDescription"),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:re("repoMesh.detail.thisMesh")}),s.jsx("p",{className:"text-[12px] text-text-muted mb-3",children:re("repoMesh.detail.thisMeshHint",{name:e.name})}),s.jsx(S2,{daemonId:M,meshId:e.id,cliType:b,sendCommand:Me,defaultOpen:!0}),s.jsxs(Tt,{label:re("repoMesh.detail.overrideLabel"),hint:re("repoMesh.detail.overrideHint"),className:"mt-3",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:G=>f({...m,override:G.target.value}),disabled:g,placeholder:re("repoMesh.detail.overridePlaceholder")}),s.jsx(C2,{daemonId:M,meshId:e.id,cliType:b,sendCommand:Me,disabled:g,hasContent:!!m.override.trim(),onApply:G=>f({...m,override:G})})]}),s.jsx(Tt,{label:re("repoMesh.detail.appendLabel"),hint:re("repoMesh.detail.appendHint"),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:G=>f({...m,append:G.target.value}),disabled:g,placeholder:re("repoMesh.detail.appendPlaceholder")})}),s.jsxs("details",{className:"mt-2 text-[12px] text-text-muted",children:[s.jsx("summary",{className:"cursor-pointer select-none",children:re("repoMesh.detail.availablePlaceholders")}),s.jsx("p",{className:"mt-1",children:re("repoMesh.detail.placeholdersIntro")}),s.jsx("div",{className:"mt-2 overflow-x-auto",children:s.jsx("table",{className:"w-full text-left border-collapse",children:s.jsx("tbody",{children:j2.map(G=>s.jsxs("tr",{className:"border-t border-border-subtle/60 align-top",children:[s.jsx("td",{className:"py-1 pr-3 font-mono whitespace-nowrap text-text-secondary",children:`{{${G.token}}}`}),s.jsx("td",{className:"py-1 pr-3",children:G.description}),s.jsx("td",{className:"py-1 font-mono text-text-muted/80",children:G.example})]},G.token))})})})]}),s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:k,disabled:g,children:re(g?"repoMesh.detail.saving":"repoMesh.detail.saveCoordinatorPrompt")}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>f({override:"",append:""}),disabled:g,title:re("repoMesh.detail.clearTitle"),children:re("repoMesh.detail.clear")})]})]})})}),$e=s.jsxs(s.Fragment,{children:[s.jsx(I2,{status:o,daemonId:M,meshId:e.id,sendCommand:Me}),s.jsxs(xt,{title:re("repoMesh.detail.safetyTitle"),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:re("repoMesh.detail.advanced")}),description:re("repoMesh.detail.safetyDescription"),children:[s.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:[{label:re("repoMesh.detail.checkpointBefore"),key:"requirePreTaskCheckpoint",opts:[["no","No"],["yes","Yes"]],val:G=>G?"yes":"no",parse:G=>G==="yes"},{label:re("repoMesh.detail.checkpointAfter"),key:"requirePostTaskCheckpoint",opts:[["yes","Yes"],["no","No"]],val:G=>G?"yes":"no",parse:G=>G==="yes"},{label:re("repoMesh.detail.pushApproval"),key:"requireApprovalForPush",opts:[["required",re("repoMesh.detail.requireApprovalBeforePush")],["not_required",re("repoMesh.detail.doNotRequireApproval")]],val:G=>G?"required":"not_required",parse:G=>G==="required"},{label:re("repoMesh.detail.uncommittedChanges"),key:"dirtyWorkspaceBehavior",opts:[["warn",re("repoMesh.detail.warnAndContinue")],["block",re("repoMesh.detail.blockTask")],["checkpoint_then_continue",re("repoMesh.detail.checkpointThenContinue")]],val:G=>G||"warn",parse:G=>G},{label:re("repoMesh.detail.autoPublishSubmodule"),key:"allowAutoPublishSubmoduleMainCommits",opts:[["disabled",re("repoMesh.detail.requireExplicitApproval")],["enabled",re("repoMesh.detail.allowRefineryPublish")]],val:G=>G?"enabled":"disabled",parse:G=>G==="enabled"}].map(({label:G,key:oe,opts:de,val:xe,parse:Se})=>s.jsx(Tt,{label:G,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:xe(ce[oe]),onChange:Pe=>u({[oe]:Se(Pe.target.value)}),disabled:p,children:de.map(([Pe,He])=>s.jsx("option",{value:Pe,children:He},Pe))})},oe))}),(()=>{const G=ce.autoFastForward&&typeof ce.autoFastForward=="object"?ce.autoFastForward:{},oe=G.enabled!==!1,de=G.remoteNodes===!0,xe=G.mode==="continuous"?"continuous":"idle",Se=Pe=>u({autoFastForward:{...G,...Pe}});return s.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[s.jsx(Tt,{label:re("repoMesh.detail.autoFastForward"),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:oe?"enabled":"disabled",onChange:Pe=>Se({enabled:Pe.target.value==="enabled"}),disabled:p,children:[s.jsx("option",{value:"enabled",children:re("repoMesh.detail.ffEnabled")}),s.jsx("option",{value:"disabled",children:re("repoMesh.detail.ffDisabled")})]})}),s.jsx(Tt,{label:re("repoMesh.detail.includeRemoteNodes"),hint:re("repoMesh.detail.includeRemoteNodesHint"),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:de?"yes":"no",onChange:Pe=>Se({remoteNodes:Pe.target.value==="yes"}),disabled:p||!oe,children:[s.jsx("option",{value:"no",children:re("repoMesh.detail.remoteNo")}),s.jsx("option",{value:"yes",children:re("repoMesh.detail.remoteYes")})]})}),s.jsx(Tt,{label:re("repoMesh.detail.detectionMode"),hint:re("repoMesh.detail.detectionModeHint"),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:xe,onChange:Pe=>Se({mode:Pe.target.value==="continuous"?"continuous":"idle"}),disabled:p||!oe||!de,children:[s.jsx("option",{value:"idle",children:re("repoMesh.detail.idleEdgeOnly")}),s.jsx("option",{value:"continuous",children:re("repoMesh.detail.continuousScan")})]})})]})})(),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(Tt,{label:re("repoMesh.detail.sessionCleanupLabel"),hint:re("repoMesh.detail.sessionCleanupHint"),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:ce.sessionCleanupOnNodeRemove||"preserve",onChange:G=>u({sessionCleanupOnNodeRemove:G.target.value}),disabled:p,children:Ri.map(G=>s.jsx("option",{value:G.value,children:G.label},G.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((rt=Ri.find(G=>G.value===ce.sessionCleanupOnNodeRemove))==null?void 0:rt.description)||Ri[0].description})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:re("repoMesh.detail.saving")})]})]}),at=[{key:"nodes",label:re("repoMesh.detail.tabNodes"),content:et},{key:"scheduling",label:re("repoMesh.detail.tabScheduling"),content:J},{key:"prompts",label:re("repoMesh.detail.tabPrompts"),content:s.jsxs(s.Fragment,{children:[Le,ye.hermesMcpConfig&&s.jsx(F2,{meshId:e.id,availableCliAgents:ue}),ye.meshHostDaemonSection&&s.jsxs(Mt,{variant:"info",className:"mt-4",children:[s.jsx("strong",{children:re("repoMesh.detail.mcpMode")})," ",s.jsxs("code",{className:"bg-bg-secondary px-1 rounded text-xs",children:["adhdev mcp --repo-mesh ",e.id]})," ",re("repoMesh.detail.mcpDescription")]})]})},{key:"advanced",label:re("repoMesh.detail.tabAdvanced"),content:$e}];return s.jsxs(s.Fragment,{children:[s.jsx(g1,{tabs:at,ariaLabel:re("repoMesh.detail.tabsAriaLabel"),className:"flex flex-col gap-4"}),Ie&&Xe&&s.jsx(Kf,{activeConv:G2({meshId:e.id,daemonId:M,meshName:e.name}),sendDaemonCommand:Me,onClose:()=>We(!1)})]})})()]})}const va=new Map;async function rg(e){var r,o,i,c,d,p,u,m,f,g,k;const{sendCommand:t,unwrapResult:n}=e,a={meshCreated:!1,meshId:"",error:null,warning:null,plan:null};try{const h=e.reusablePlan??n(await t(e.targetDaemonId,"plan_mesh_onboarding",{workspace:e.workspace||void 0,operation:"auto",meshInventory:e.meshInventory}));if(a.plan=h,(h==null?void 0:h.success)===!1)return{...a,error:`${h.code||"onboarding_blocked"}: ${h.error}${h.action?` ${h.action}`:""}`};if(((r=h==null?void 0:h.plan)==null?void 0:r.kind)!=="create_mesh_and_onboard")return{...a,error:((o=h==null?void 0:h.plan)==null?void 0:o.summary)||"A compatible mesh already exists; add this workspace to it instead of creating a duplicate mesh."};const x={name:e.name.trim()};(e.repoRemoteUrl||(d=(c=(i=h==null?void 0:h.discovery)==null?void 0:i.origin)==null?void 0:c.urls)!=null&&d[0])&&(x.repoRemoteUrl=e.repoRemoteUrl||h.discovery.origin.urls[0]),(e.repoIdentity||(p=h==null?void 0:h.discovery)!=null&&p.repoIdentity)&&(x.repoIdentity=e.repoIdentity||h.discovery.repoIdentity),(u=h==null?void 0:h.discovery)!=null&&u.defaultBranch&&(x.defaultBranch=h.discovery.defaultBranch);const S=await t(e.targetDaemonId,"create_mesh",x),b=n(S);if((b==null?void 0:b.success)===!1)return{...a,error:b.error||"Create failed"};const w=typeof((m=b==null?void 0:b.mesh)==null?void 0:m.id)=="string"?b.mesh.id:"",C={...a,meshCreated:!0,meshId:w};if(!w||!e.attachWorkspace||!e.workspace)return C;try{const v=await t(e.targetDaemonId,"add_mesh_node",{meshId:w,daemonId:e.targetDaemonId,machineId:e.machineId,workspace:((f=h==null?void 0:h.discovery)==null?void 0:f.repoRoot)||e.workspace,repoRoot:(g=h==null?void 0:h.discovery)==null?void 0:g.repoRoot,isLocalWorktree:((k=h==null?void 0:h.discovery)==null?void 0:k.isLinkedWorktree)===!0,role:"host",providerPriority:e.providerPriority}),y=n(v);return(y==null?void 0:y.success)===!1?{...C,warning:tp(y.error||"add_mesh_node failed")}:C}catch(v){return{...C,warning:tp((v==null?void 0:v.message)||"add_mesh_node failed")}}}catch(h){return{...a,error:(h==null?void 0:h.message)||"Create failed"}}}function tp(e){return`Mesh created, but attaching the workspace failed: ${e}. Add the workspace from the mesh's node list.`}function sp(e,t){return e===t?!0:e.length!==t.length?!1:JSON.stringify(e)===JSON.stringify(t)}function og({daemons:e,primaryDaemonId:t,sendCommand:n,unwrapResult:a,normalizeMesh:r,features:o,loadDaemonMetadata:i}){const c=e.map(me=>me.id).filter(Boolean).sort().join(","),[d,p]=l.useState(()=>va.get(c)??[]),[u,m]=l.useState(null),[f,g]=l.useState(()=>!va.has(c)),[k,h]=l.useState(null),[x,S]=l.useState(!1),[b,w]=l.useState(!1),[C,v]=l.useState(null),[y,j]=l.useState(""),[N,T]=l.useState(""),[A,I]=l.useState(""),[D,M]=l.useState(""),[E,P]=l.useState(""),[B,R]=l.useState(null),[W,_]=l.useState(!1),H=o.createDaemonPicker?D:t,L=l.useMemo(()=>e.find(me=>me.id===H),[e,H]),F=(L==null?void 0:L.workspaces)||[],$=l.useMemo(()=>ln((L==null?void 0:L.availableProviders)||[]),[L]);l.useEffect(()=>{!i||!H||!L||!(!L.workspaces||!L.availableProviders)||Promise.resolve(i(H,{minFreshMs:3e4})).catch(()=>{})},[i,H,L]),l.useEffect(()=>{if(!x||!H||!E){R(null);return}let me=!1;return _(!0),n(H,"plan_mesh_onboarding",{workspace:E,operation:"auto",meshInventory:d}).then(O=>{if(me)return;const Y=a(O);R(Y),Y!=null&&Y.success&&(T(X=>{var Q;return X||((Q=Y.discovery)==null?void 0:Q.repoIdentity)||""}),I(X=>{var Q,ve,he,Z,fe,V;return X||((he=(ve=(Q=Y.discovery)==null?void 0:Q.origin)==null?void 0:ve.urls)==null?void 0:he[0])||((V=(fe=(Z=Y.discovery)==null?void 0:Z.upstream)==null?void 0:fe.urls)==null?void 0:V[0])||""}),j(X=>{var Q,ve;return X||`${String(((Q=Y.discovery)==null?void 0:Q.repoIdentity)||((ve=Y.discovery)==null?void 0:ve.repoRoot)||"").split(/[\\/]/).filter(Boolean).pop()||"repo"}-mesh`}))}).catch(O=>{me||R({success:!1,error:(O==null?void 0:O.message)||"Git discovery failed"})}).finally(()=>{me||_(!1)}),()=>{me=!0}},[x,H,E,d,n,a]);const K=l.useMemo(()=>e.map(me=>me.id).filter(Boolean).sort().join(","),[e]),z=l.useCallback(async(me=!1)=>{const O=me||va.has(K);g(Y=>O?Y:!0);try{if(o.createDaemonPicker){const Y=await Promise.allSettled(e.map(async ve=>{if(!ve.id)return[];const he=await n(ve.id,"list_meshes",{}),Z=a(he);if((Z==null?void 0:Z.success)===!1)throw new Error(Z.error||"Failed to load meshes");return(Array.isArray(Z==null?void 0:Z.meshes)?Z.meshes:[]).map(fe=>r(fe,ve.id)).filter(fe=>fe.id)})),X=new Map;for(const ve of Y)if(ve.status==="fulfilled")for(const he of ve.value)X.has(he.id)||X.set(he.id,he);const Q=Array.from(X.values());p(ve=>sp(ve,Q)?ve:Q),va.set(K,Q),h(null)}else{if(!t)return;const Y=await n(t,"list_meshes");if(Y!=null&&Y.success){const X=(Y.meshes||[]).map(Q=>r(Q,t));p(Q=>sp(Q,X)?Q:X),va.set(K,X),h(null)}else h((Y==null?void 0:Y.error)||"Failed to load meshes")}}catch(Y){h((Y==null?void 0:Y.message)||"Failed to load meshes")}finally{g(!1)}},[K,t,n,a,r,o.createDaemonPicker]);async function ne(){const me=o.createDaemonPicker?D:t;if(!me||!y.trim())return;const O=A.trim(),Y=N.trim(),X=E.trim();if(!(!X&&!O&&!Y)&&!b){w(!0),v(null);try{const Q=await rg({targetDaemonId:me,name:y,repoRemoteUrl:O,repoIdentity:Y,workspace:X,attachWorkspace:!!X,machineId:L==null?void 0:L.machineId,providerPriority:Pn($),meshInventory:d,sendCommand:n,unwrapResult:a,reusablePlan:!W&&B?B:void 0});if(Q.plan!==null&&R(Q.plan),Q.warning&&v(Q.warning),!Q.meshCreated){h(Q.error||"Create failed");return}S(!1),j(""),T(""),I(""),P(""),await z(),Q.meshId&&m(Q.meshId)}finally{w(!1)}}}async function ie(me){var Y;if(!confirm("Delete this mesh? This cannot be undone."))return;const O=((Y=d.find(X=>X.id===me))==null?void 0:Y.__sourceDaemonId)||t;try{const X=await n(O,"delete_mesh",{meshId:me}),Q=a(X);if((Q==null?void 0:Q.success)===!1)throw new Error(Q.error||"Failed to delete");u===me&&m(null),await z()}catch(X){h((X==null?void 0:X.message)||"Delete failed")}}function Ce(){S(!1),j(""),T(""),I(""),P(""),R(null),v(null)}return{meshes:d,setMeshes:p,selectedMeshId:u,setSelectedMeshId:m,loading:f,error:k,setError:h,showCreate:x,setShowCreate:S,creating:b,createWarning:C,setCreateWarning:v,createName:y,setCreateName:j,createRepoIdentity:N,setCreateRepoIdentity:T,createRepoRemoteUrl:A,setCreateRepoRemoteUrl:I,newMeshDaemonId:D,setNewMeshDaemonId:M,newMeshWorkspace:E,setNewMeshWorkspace:P,createPickerWorkspaces:F,createPickerProviders:$,createOnboardingPlan:B,createPlanLoading:W,loadMeshes:z,handleCreate:ne,handleDelete:ie,cancelCreate:Ce}}function z2({selectedMesh:e,selectedMeshId:t,primaryDaemonId:n,activeDaemonId:a,daemons:r,sendCommand:o,unwrapResult:i,loadLiveMesh:c,resolveCommandTarget:d,launchCoordinator:p,features:u,loadMeshes:m,loadQueue:f,queueSection:g,setError:k}){const[h,x]=l.useState(null),[S,b]=l.useState(!1),[w,C]=l.useState(""),[v,y]=l.useState([]),[j,N]=l.useState(""),[T,A]=l.useState(!1),[I,D]=l.useState(null),[M,E]=l.useState(!1),[P,B]=l.useState(""),[R,W]=l.useState(!1),[_,H]=l.useState(!1),[L,F]=l.useState(null),[$,K]=l.useState(!1),[z,ne]=l.useState({override:"",append:""}),[ie,Ce]=l.useState(!1),[me,O]=l.useState({}),[Y,X]=l.useState(null),Q=l.useMemo(()=>r.find(ce=>ce.id===j),[r,j]),ve=(Q==null?void 0:Q.workspaces)||[],he=l.useMemo(()=>ln((Q==null?void 0:Q.availableProviders)||[]),[Q]);l.useEffect(()=>{if(!S||!t||!w.trim()){D(null);return}const ce=u.addNodeDaemonPicker?j:(e==null?void 0:e.__sourceDaemonId)||n;if(!ce)return;let Ae=!1;return E(!0),o(ce,"plan_mesh_onboarding",{workspace:w.trim(),meshId:t,inlineMesh:e,operation:"add_existing"}).then(be=>{Ae||D(i(be))}).catch(be=>{Ae||D({success:!1,error:(be==null?void 0:be.message)||"Git discovery failed"})}).finally(()=>{Ae||E(!1)}),()=>{Ae=!0}},[S,t,e,w,j,n,u.addNodeDaemonPicker,o,i]);async function Z(){var be,we,_e;const ce=(e==null?void 0:e.__sourceDaemonId)||n;if(!t||!ce)return;const Ae=w.trim();if(Ae)try{const U=u.addNodeDaemonPicker?j:ce,Ne=await o(U,"plan_mesh_onboarding",{workspace:Ae,meshId:t,inlineMesh:e,operation:"add_existing"}),Ie=i(Ne);if(D(Ie),(Ie==null?void 0:Ie.success)===!1)throw new Error(`${Ie.code||"onboarding_blocked"}: ${Ie.error}${Ie.action?` ${Ie.action}`:""}`);const We={meshId:t,workspace:((be=Ie==null?void 0:Ie.discovery)==null?void 0:be.repoRoot)||Ae,repoRoot:(we=Ie==null?void 0:Ie.discovery)==null?void 0:we.repoRoot,isLocalWorktree:((_e=Ie==null?void 0:Ie.discovery)==null?void 0:_e.isLinkedWorktree)===!0};u.addNodeDaemonPicker&&j&&(We.daemonId=j,We.machineId=Q==null?void 0:Q.machineId),We.providerPriority=Va(v);const Xe=await o(ce,"add_mesh_node",We),et=i(Xe);if((et==null?void 0:et.success)===!1)throw new Error(et.error||"Add node failed");b(!1),C(""),y([]),N(""),A(!1),await m(),g||await f(t)}catch(U){k((U==null?void 0:U.message)||"Add node failed")}}async function fe(ce){var _e;if(!e)return;const Ae=jl(e),be=((_e=[{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(U=>U.value===Ae.sessionCleanupOnNodeRemove))==null?void 0:_e.label)||"Preserve history and runtimes";if(!confirm(`Remove this node?
|
|
120
120
|
|
|
121
|
-
Node removal cleanup policy: ${be}`))return;const we=e.__sourceDaemonId||n;try{const U=await o(we,"remove_mesh_node",{meshId:e.id,nodeId:ce}),Ne=i(U);if((Ne==null?void 0:Ne.success)===!1)throw new Error(Ne.error||"Remove failed");h===ce&&x(null),await m(),g||await f(t)}catch(U){k((U==null?void 0:U.message)||"Remove node failed")}}async function V(ce){if(!e)return;const Ae={...jl(e),...ce},be=e.__sourceDaemonId||n;try{K(!0),k(null);const we=await o(be,"update_mesh",{meshId:e.id,policy:Ae}),_e=i(we);if((_e==null?void 0:_e.success)===!1)throw new Error(_e.error||"Policy update failed");await m()}catch(we){k((we==null?void 0:we.message)||"Policy update failed")}finally{K(!1)}}const[q,ee]=l.useState(null);async function pe(ce,Ae){if(!t)return;const be=(e==null?void 0:e.__sourceDaemonId)||n;try{ee(ce.id),k(null);const we=await o(be,"update_mesh_node",{meshId:t,nodeId:ce.id,policy:{slots:Ae}}),_e=i(we);if((_e==null?void 0:_e.success)===!1){k(_e.error||"Node slots update failed");return}await m()}catch(we){k((we==null?void 0:we.message)||"Node slots update failed")}finally{ee(null)}}const[le,se]=l.useState(null);async function te(ce,Ae){if(!t)return;const be=(e==null?void 0:e.__sourceDaemonId)||n,we=Ae.map(_e=>_e.trim()).filter(Boolean);try{se(ce.id),k(null);const _e=await o(be,"update_mesh_node",{meshId:t,nodeId:ce.id,capabilities:we}),U=i(_e);if((U==null?void 0:U.success)===!1){k(U.error||"Node tag update failed");return}await m()}catch(_e){k((_e==null?void 0:_e.message)||"Node tag update failed")}finally{se(null)}}async function ue(){if(!n||!t)return;const Ae={...(e==null?void 0:e.coordinator)||{}};z.override.trim()?Ae.systemPromptOverride=z.override:delete Ae.systemPromptOverride,z.append.trim()?Ae.systemPromptAppend=z.append:delete Ae.systemPromptAppend,delete Ae.systemPromptSuffix;try{Ce(!0),k(null);const be=await o(n,"update_mesh",{meshId:t,coordinator:Ae}),we=i(be);if((we==null?void 0:we.success)===!1){k(we.error||"Coordinator prompt save failed");return}await m()}catch(be){k((be==null?void 0:be.message)||"Coordinator prompt save failed")}finally{Ce(!1)}}async function ye(ce){if(!n||!t)return;const Ae=(me[ce.id]||"").trim();try{X(ce.id),k(null);const be=await o(n,"update_mesh_node",{meshId:t,nodeId:ce.id,systemPrompt:Ae}),we=i(be);if((we==null?void 0:we.success)===!1){k(we.error||"Node instruction save failed");return}await m()}catch(be){k((be==null?void 0:be.message)||"Node instruction save failed")}finally{X(null)}}async function Me(ce){if(!(!e||!ce)){k(null),F(null);try{H(!0);const Ae=(e.nodes||[]).find(_e=>Zs(String(_e.daemon_id||_e.daemonId||""),ce)),be=await o(ce,"set_mesh_host",{meshId:e.id,hostDaemonId:ce,...Ae!=null&&Ae.id?{hostNodeId:Ae.id}:{}}),we=i(be);if((we==null?void 0:we.success)===!1){k(we.error||"Setting the mesh host failed");return}await m()}catch(Ae){k((Ae==null?void 0:Ae.message)||"Setting the mesh host failed")}finally{H(!1)}}}async function re(){if(e){k(null),F(null);try{W(!0);const ce=c?await c(a,e.id,e):null,Ae=d(a,e.id,e,e.nodes||[],ce);if("error"in Ae)throw new Error(Ae.error);const be=await p(Ae.targetDaemonId,{meshId:e.id,inlineMesh:Ae.inlineMesh,coordinatorNodeId:Ae.coordinatorNodeId,cliType:P.trim()||void 0});F(be.message)}catch(ce){k((ce==null?void 0:ce.message)||"Coordinator launch failed")}finally{W(!1)}}}return{selectedNodeId:h,setSelectedNodeId:x,showAddNode:S,setShowAddNode:b,nodeWorkspace:w,setNodeWorkspace:C,nodeProviderPriority:v,setNodeProviderPriority:y,nodeDaemonId:j,setNodeDaemonId:N,nodeCustomPath:T,setNodeCustomPath:A,nodePickerWorkspaces:ve,nodePickerProviders:he,nodeOnboardingPlan:I,nodePlanLoading:M,coordinatorCliType:P,setCoordinatorCliType:B,launchingCoordinator:R,launchResult:L,settingMeshHost:_,savingPolicy:$,coordinatorPromptDraft:z,setCoordinatorPromptDraft:ne,savingCoordinatorPrompt:ie,nodeSystemPromptDrafts:me,setNodeSystemPromptDrafts:O,savingNodeSystemPromptId:Y,savingNodeSlotsId:q,savingNodeCapabilitiesId:le,handleAddNode:Z,handleRemoveNode:fe,handleUpdatePolicy:V,handleUpdateNodeSlots:pe,handleUpdateNodeCapabilities:te,handleSaveCoordinatorPrompt:ue,handleSaveNodeSystemPrompt:ye,handleLaunchCoordinator:re,handleSetMeshHost:Me}}function K2(e){const t=e.filter(a=>a.status==="pending"||a.status==="assigned"),n=e.filter(a=>a.status==="completed"||a.status==="failed"||a.status==="cancelled");return{active:t.length,historical:n.length,activeCounts:{pending:t.filter(a=>a.status==="pending").length,assigned:t.filter(a=>a.status==="assigned").length},historicalCounts:{completed:n.filter(a=>a.status==="completed").length,failed:n.filter(a=>a.status==="failed").length},counts:{pending:e.filter(a=>a.status==="pending").length,assigned:e.filter(a=>a.status==="assigned").length,completed:e.filter(a=>a.status==="completed").length,failed:e.filter(a=>a.status==="failed").length},staleAssignedCount:e.filter(a=>a.staleAssigned).length,recent:e.slice(0,20)}}function V2({primaryDaemonId:e,activeDaemonId:t,sendCommand:n,unwrapResult:a,loadLiveMesh:r,resolveCommandTarget:o}){const[i,c]=l.useState([]),[d,p]=l.useState(null),[u,m]=l.useState(!1),[f,g]=l.useState(null),k=l.useCallback(async x=>{if(!e||!x){c([]);return}try{const S=await n(e,"get_mesh_queue",{meshId:x});c(S!=null&&S.success?Array.isArray(S.queue)?S.queue:[]:[])}catch{c([])}},[e,n]);async function h(x){var S,b;if(x){m(!0),g(null);try{const w=r?await r(t,x.id,x):null,C=o(t,x.id,x,x.nodes||[],w);if("error"in C)throw new Error(C.error);const v=await n(C.targetDaemonId,"get_mesh_queue",{meshId:x.id}),y=a(v);if((y==null?void 0:y.success)===!1)throw new Error(y.error||"Queue load failed");const j=Array.isArray(((S=y==null?void 0:y.result)==null?void 0:S.rows)??(y==null?void 0:y.rows)??(y==null?void 0:y.queue))?((b=y==null?void 0:y.result)==null?void 0:b.rows)??(y==null?void 0:y.rows)??(y==null?void 0:y.queue):[];p(K2(j))}catch(w){g((w==null?void 0:w.message)||"Queue load failed")}finally{m(!1)}}}return{meshQueue:i,setMeshQueue:c,queueSummary:d,queueLoading:u,queueError:f,loadQueue:k,handleLoadQueue:h}}function Y2(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}const ig=new Map;function lg(e){return e?ig.get(e)??null:null}function Q2(e,t){!e||!t||ig.set(e,t)}function J2({selectedMeshId:e,loadMeshStatus:t,extractStatus:n,normalizeNode:a,gateIncompleteGraph:r}){const[o,i]=l.useState(()=>lg(e)),[c,d]=l.useState(!1),[p,u]=l.useState(null),[m,f]=l.useState("idle"),[g,k]=l.useState(!1),h=l.useRef(!1);async function x(S,b=e,w=!1){if(!(!S||!b))try{d(!w&&o===null),f(w?"settling":"first_paint"),u(null);const C=await t(S,b,{refresh:w,retryProfile:w?"settled":"interactive"});k(Y2(C));const v=n(C),y=a&&v?{...v,nodes:(v.nodes??[]).map(j=>a(j,v.meshId??b,""))}:v;if(y){if(r&&!w&&o!==null&&!fM(Cf(y))){f("settling"),h.current||(h.current=!0,Promise.resolve().then(()=>x(S,b,!0)).finally(()=>{h.current=!1}));return}i(y),Q2(b,y),f("settled")}else i(null),u("mesh_status returned an unexpected payload."),f("idle")}catch(C){o||i(null),u((C==null?void 0:C.message)||"Failed to load mesh graph"),f("idle")}finally{d(!1)}}return{meshGraphStatus:o,setMeshGraphStatus:i,graphLoading:c,graphError:p,setGraphError:u,graphProvenance:m,graphBootstrapFallback:g,loadGraph:x}}function np(e){return!e||e.hostSynthesized?{hostDaemonId:"",hostNodeId:""}:{hostDaemonId:String(e.hostDaemonId||""),hostNodeId:String(e.hostNodeId||"")}}function X2(e,t,n,a,r){if(!e.length)return"";const o=String(r||"");if(o){const d=e.find(p=>Zs(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=>Zs(p.id,c));if(d)return d.id}return""}function Z2(e){var r;if(!e)return"null";const t=[...e.nodes??[]].map(o=>{var i,c,d,p,u,m;return[o.nodeId,o.health,((i=o.git)==null?void 0:i.branch)??"",((c=o.git)==null?void 0:c.headCommit)??"",(d=o.git)!=null&&d.dirty?"1":"0",((p=o.git)==null?void 0:p.ahead)??0,((u=o.git)==null?void 0:u.behind)??0,(m=o.git)!=null&&m.hasConflicts?"1":"0",[...o.activeSessions??[]].sort().join(",")].join("|")}).sort().join(";"),n=(r=e.queue)==null?void 0:r.summary,a=n?[n.pending,n.assigned,n.completed,n.failed,n.cancelled].join(","):"";return`${t}::${a}`}const eR=4,tR=3e4;function sR(){return{lastFingerprint:null,stableTicks:0,backedOff:!1}}function Nl(e){e.stableTicks=0,e.backedOff=!1}function nR(e,t){const n=Z2(t);return e.lastFingerprint===null?(e.lastFingerprint=n,e.backedOff):n!==e.lastFingerprint?(e.lastFingerprint=n,Nl(e),!1):(e.stableTicks+=1,e.stableTicks>=eR&&(e.backedOff=!0),e.backedOff)}function aR(e,t){return e.backedOff?Math.max(t,tR):t}const rR=7e3,oR=45e3;function iR(){const e=EL(),{sendCommand:t,sendData:n,daemons:a,userName:r,loadMeshStatus:o,launchCoordinator:i,loadLiveMesh:c,extractStatus:d,unwrapResult:p,normalizeMesh:u,normalizeNode:m,resolveCommandTarget:f,features:g,gateIncompleteGraph:k}=e,h=ca(),x=a[0],S=(x==null?void 0:x.id)||"",b=l.useMemo(()=>((x==null?void 0:x.availableProviders)||[]).filter(lt=>lt.category==="cli").map(lt=>({id:lt.type||lt.id,name:lt.displayName||lt.name||lt.type,meshCoordinator:lt.meshCoordinator})),[x]),w=l.useMemo(()=>ln((x==null?void 0:x.availableProviders)||[]),[x]),{meshes:C,selectedMeshId:v,setSelectedMeshId:y,loading:j,error:N,setError:T,showCreate:A,setShowCreate:I,createName:D,setCreateName:M,createRepoIdentity:E,setCreateRepoIdentity:P,createRepoRemoteUrl:B,setCreateRepoRemoteUrl:R,newMeshDaemonId:W,setNewMeshDaemonId:_,newMeshWorkspace:H,setNewMeshWorkspace:L,createPickerWorkspaces:F,createOnboardingPlan:$,createPlanLoading:K,creating:z,createWarning:ne,setCreateWarning:ie,loadMeshes:Ce,handleCreate:me,handleDelete:O,cancelCreate:Y}=og({daemons:a,primaryDaemonId:S,sendCommand:t,unwrapResult:p,normalizeMesh:u,features:g,loadDaemonMetadata:h}),X=C.find(Oe=>Oe.id===v)||null,{meshGraphStatus:Q,setMeshGraphStatus:ve,graphLoading:he,graphError:Z,setGraphError:fe,loadGraph:V}=J2({selectedMeshId:v,loadMeshStatus:o,extractStatus:d,normalizeNode:m,gateIncompleteGraph:k}),[q,ee]=l.useState(""),[pe,le]=l.useState(""),se=g.meshHostDaemonSection?q:S,{meshQueue:te,loadQueue:ue}=V2({primaryDaemonId:S,activeDaemonId:se,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:f}),{selectedNodeId:ye,setSelectedNodeId:Me,showAddNode:re,setShowAddNode:ce,nodeWorkspace:Ae,setNodeWorkspace:be,nodeProviderPriority:we,setNodeProviderPriority:_e,nodeDaemonId:U,setNodeDaemonId:Ne,nodeCustomPath:Ie,setNodeCustomPath:We,nodePickerWorkspaces:Xe,nodePickerProviders:et,nodeOnboardingPlan:J,nodePlanLoading:Le,coordinatorCliType:$e,savingPolicy:at,coordinatorPromptDraft:rt,setCoordinatorPromptDraft:G,savingCoordinatorPrompt:oe,nodeSystemPromptDrafts:de,setNodeSystemPromptDrafts:xe,savingNodeSystemPromptId:Se,savingNodeSlotsId:Pe,savingNodeCapabilitiesId:He,handleAddNode:Ee,handleRemoveNode:Je,handleUpdatePolicy:st,handleUpdateNodeSlots:Ze,handleUpdateNodeCapabilities:Ue,handleSaveCoordinatorPrompt:Qe,handleSaveNodeSystemPrompt:nt,settingMeshHost:Be,handleSetMeshHost:ge}=z2({selectedMesh:X,selectedMeshId:v,primaryDaemonId:S,activeDaemonId:se,daemons:a,availableCliProviders:w,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:f,launchCoordinator:i,features:{addNodeDaemonPicker:g.addNodeDaemonPicker},loadMeshes:Ce,loadQueue:ue,queueSection:g.queueSection,setError:T}),je=l.useMemo(()=>a.find(Oe=>Oe.id===se)||x,[a,se,x]),Te=l.useMemo(()=>new Set(((X==null?void 0:X.nodes)||[]).map(Oe=>String(Oe.daemon_id||Oe.daemonId||""))),[X]),Fe=l.useMemo(()=>a.filter(Oe=>Oe.id&&!Te.has(Oe.id)&&!Xp(Oe)),[a,Te]),Ge=(X==null?void 0:X.nodes)||[],dt=l.useMemo(()=>Ge.find(Oe=>Zs(String(Oe.daemon_id||Oe.daemonId||""),q)),[Ge,q]),Ve=g.meshHostDaemonSection?!!dt:!0,ut=l.useMemo(()=>{if(!g.meshHostDaemonSection||!X)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const Oe=X.meshHost,lt=Q!=null&&Q.meshId&&String(Q.meshId)===String(X.id??"")?Q.meshHost:void 0,es=lt!=null&<.hostDaemonId?lt:Oe??lt,ns=np(es),js=ns.hostDaemonId,Ys=Ge.find(Fs=>Fs.role==="host"),cn=ns.hostNodeId||String((Ys==null?void 0:Ys.id)||""),ae=cn?Ge.find(Fs=>String(Fs.id)===cn):void 0,Ke=String((ae==null?void 0:ae.daemon_id)||(ae==null?void 0:ae.daemonId)||""),qe=js||Ke;if(!qe)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const Nt=a.find(Fs=>js&&Zs(Fs.id,js))||(Ke?a.find(Fs=>Zs(Fs.id,Ke)):void 0);if(Nt)return{pinned:!0,daemonId:Nt.id,label:lR(Nt),online:!0,hostNode:ae};const dn=String((ae==null?void 0:ae.machineLabel)||"")||String((ae==null?void 0:ae.workspace)||"")||qe;return{pinned:!0,daemonId:qe,label:dn,online:!1,hostNode:ae}},[X,Ge,a,Q,g.meshHostDaemonSection]),zt=ut.daemonId,Et=ut.online,ps=ut.pinned?ut.hostNode:dt,Zt=l.useMemo(()=>!g.meshHostDaemonSection||!ut.pinned?"":!Et&&pe&&a.some(Oe=>Oe.id===pe)?pe:zt,[g.meshHostDaemonSection,ut.pinned,Et,pe,a,zt]),_s=l.useMemo(()=>Q?[...new Set((Q.nodes??[]).map(Oe=>String(Oe.daemonId||Oe.daemon_id||"")).filter(Boolean))]:[],[Q]),Re=zf({status:Q,daemonId:se||null,extraDaemonIds:_s,meshId:v,sendData:n});l.useEffect(()=>{const Oe=(X==null?void 0:X.coordinator)||{};G({override:typeof Oe.systemPromptOverride=="string"?Oe.systemPromptOverride:"",append:typeof Oe.systemPromptAppend=="string"?Oe.systemPromptAppend:typeof Oe.systemPromptSuffix=="string"?Oe.systemPromptSuffix:""}),xe(Object.fromEntries(((X==null?void 0:X.nodes)||[]).map(lt=>[lt.id,typeof lt.systemPrompt=="string"?lt.systemPrompt:""])))},[X]),l.useEffect(()=>{const Oe=g.addNodeDaemonPicker?Pn(et):Pn(w);re&&we.length===0&&Oe.length>0&&_e(Oe)},[re,w,et,we.length,g.addNodeDaemonPicker]),l.useEffect(()=>{const Oe=new Set(((X==null?void 0:X.nodes)||[]).map(lt=>lt.id));ye&&!Oe.has(ye)&&Me(null)},[X,ye]);const tt=l.useMemo(()=>{if(!(!(Q!=null&&Q.meshId)||String(Q.meshId)!==String((X==null?void 0:X.id)??"")))return np(Q.meshHost).hostDaemonId||void 0},[Q,X]),It=l.useMemo(()=>X2(a,Ge,se,S,tt),[a,Ge,se,S,tt]);l.useEffect(()=>{if(!g.meshHostDaemonSection)return;if(!a.length&&!ut.pinned){ee("");return}const Oe=ut.pinned?Zt:It;Oe&&!Zs(Oe,q)&&ee(Oe)},[a,q,ut.pinned,Zt,It,g.meshHostDaemonSection]),l.useEffect(()=>{pe&&(Et||!a.some(Oe=>Oe.id===pe))&&le("")},[Et,pe,a]),l.useEffect(()=>{if(g.createDaemonPicker){if(!a.length){_("");return}(!W||!a.some(Oe=>Oe.id===W))&&_(a[0].id)}},[a,W,g.createDaemonPicker]),l.useEffect(()=>{var Oe;if(!g.createDaemonPicker||!W){L("");return}if(!F.length){L("");return}F.some(lt=>lt.path===H)||L(((Oe=F[0])==null?void 0:Oe.path)||"")},[W,H,F,g.createDaemonPicker]);const pt=l.useRef(null),Yt=l.useRef(sR()),_t=g.meshStatePushRefresh?oR:rR,[Qt,Cs]=l.useState(_t);l.useEffect(()=>{if(!v)return;const Oe=pt.current!==v;if(pt.current=v,Oe){Nl(Yt.current),Cs(_t);const lt=lg(v);ve(lt),fe(null),V(se,v,lt!==null)}else fe(null),V(se,v,!0)},[v,se]);const Hs=l.useRef(V);Hs.current=V;const ms=l.useRef(!1),ss=l.useRef(()=>{});ss.current=()=>{ms.current||!v||!se||(ms.current=!0,Promise.resolve(Hs.current(se,v,!0)).finally(()=>{ms.current=!1}))},l.useEffect(()=>{nR(Yt.current,Q),Cs(aR(Yt.current,_t))},[Q,_t]),RL({daemonIds:l.useMemo(()=>[se,..._s].filter(Boolean),[se,_s]),meshId:v,sendData:n,onRevisionAdvance:()=>{typeof document<"u"&&document.visibilityState!=="visible"||ss.current()}}),l.useEffect(()=>{if(!v||!se||typeof document>"u")return;let Oe=null;const lt=()=>{document.visibilityState==="visible"&&ss.current()},es=()=>{Oe===null&&(Oe=setInterval(lt,Qt))},ns=()=>{Oe!==null&&(clearInterval(Oe),Oe=null)},js=()=>{document.visibilityState==="visible"?es():ns()};return document.visibilityState==="visible"&&es(),document.addEventListener("visibilitychange",js),()=>{ns(),document.removeEventListener("visibilitychange",js)}},[v,se,Qt]),l.useEffect(()=>{g.queueSection||ue(v)},[v,g.queueSection]);const Vs=l.useMemo(()=>a.map(Oe=>Oe.id).filter(Boolean).sort().join(","),[a]),$s=l.useRef(!1);return l.useEffect(()=>{Ce($s.current),$s.current=!0},[Vs]),S?X?s.jsx(q2,{selectedMesh:X,error:N,onDismissError:()=>T(null),onBack:()=>{y(null),ve(null)},onDelete:O,displayedMeshStatus:Re,graphLoading:he,graphError:Z,onRefreshGraph:()=>{Nl(Yt.current),V(se,v,!0)},savingPolicy:at,onUpdatePolicy:st,coordinatorPromptDraft:rt,onCoordinatorPromptDraftChange:G,savingCoordinatorPrompt:oe,onSaveCoordinatorPrompt:Qe,daemons:a,coordinatorDaemonId:q,onCoordinatorDaemonIdChange:ee,coordinatorCliType:$e,isHostNodeAttached:Ve,selectedHostNode:ps,hostPinned:ut.pinned,hostLabel:ut.label,hostOnline:Et,hostRebindDaemonId:pe,onHostRebindDaemonIdChange:Oe=>le(Oe),settingMeshHost:Be,onSetMeshHost:ge,activeDaemon:je,activeDaemonId:se,meshQueue:te,userName:r,availableCliProviders:w,savingNodeSlotsId:Pe,onUpdateNodeSlots:Ze,savingNodeCapabilitiesId:He,onUpdateNodeCapabilities:Ue,nodeSystemPromptDrafts:de,onNodeSystemPromptDraftChange:(Oe,lt)=>xe(es=>({...es,[Oe]:lt})),savingNodeSystemPromptId:Se,onSaveNodeSystemPrompt:nt,selectedNodeId:ye,onSelectNode:Me,showAddNode:re,onShowAddNode:()=>ce(!0),onCancelAddNode:()=>ce(!1),nodeWorkspace:Ae,onNodeWorkspaceChange:be,nodeProviderPriority:we,onNodeProviderPriorityChange:_e,nodeDaemonId:U,onNodeDaemonIdChange:Ne,nodeCustomPath:Ie,onNodeCustomPathChange:We,nodePickerWorkspaces:Xe,nodePickerProviders:et,nodeOnboardingPlan:J,nodePlanLoading:Le,attachableDaemons:Fe,onAddNode:Ee,onRemoveNode:Je,availableCliAgents:b,features:{coordinatorPrompt:g.coordinatorPrompt,meshHostDaemonSection:g.meshHostDaemonSection,hermesMcpConfig:g.hermesMcpConfig,addNodeDaemonPicker:g.addNodeDaemonPicker,nodeInstruction:g.nodeInstruction},sendCommand:t}):s.jsx(UL,{meshes:C,loading:j,error:N,onDismissError:()=>T(null),daemons:a,features:{createDaemonPicker:g.createDaemonPicker,maxMeshes:g.maxMeshes},showCreate:A,onToggleCreate:()=>I(!A),createName:D,onCreateNameChange:M,createRepoIdentity:E,onCreateRepoIdentityChange:P,createRepoRemoteUrl:B,onCreateRepoRemoteUrlChange:R,newMeshDaemonId:W,onNewMeshDaemonIdChange:_,newMeshWorkspace:H,onNewMeshWorkspaceChange:L,createPickerWorkspaces:F,createOnboardingPlan:$,createPlanLoading:K,creating:z,createWarning:ne,onDismissCreateWarning:()=>ie(null),onSelectMesh:y,onCreate:me,onCancelCreate:Y}):s.jsx(Qa,{icon:s.jsx(cs,{}),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 lR(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function cR({children:e}){const{sendCommand:t,sendData:n}=St(),{ides:a}=Ss(),r=l.useMemo(()=>a.filter(i=>i.daemonMode||i.type==="adhdev-daemon").map(i=>i),[a]),o=l.useMemo(()=>({sendCommand:t,sendData:n,daemons:r,userName:void 0,loadMeshStatus:async(i,c)=>t(i,"mesh_status",{meshId:c}),launchCoordinator:async(i,c)=>{var f;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)||((f=u==null?void 0:u.session)==null?void 0:f.id)||(u==null?void 0:u.targetSessionId);return{sessionId:m,message:m?`Coordinator launched (${m})`:"Coordinator launch command sent"}},loadLiveMesh:void 0,extractStatus:Vl,unwrapResult:i=>i,normalizeMesh:(i,c)=>i,normalizeNode:(i,c,d)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:Zf}),[t,n,r]);return s.jsx(eg.Provider,{value:o,children:e})}function dR(e){const{daemons:t,features:n,meshes:a,meshesLoading:r,selectedMeshId:o,onSelectMesh:i,createMode:c,onCreateModeChange:d,createName:p,onCreateNameChange:u,createDaemonId:m,onCreateDaemonIdChange:f,createWorkspace:g,onCreateWorkspaceChange:k,createPickerWorkspaces:h,createPlan:x,createPlanLoading:S,creating:b,createWarning:w,onCreate:C,createRepoRemoteUrl:v,onCreateRepoRemoteUrlChange:y,createRepoIdentity:j,onCreateRepoIdentityChange:N,createManualOpen:T,onCreateManualOpenChange:A,nodes:I,attachableDaemons:D,attachDaemonId:M,onAttachDaemonIdChange:E,attachWorkspace:P,onAttachWorkspaceChange:B,attachPickerWorkspaces:R,attachPlan:W,attachPlanLoading:_,attaching:H,onAttach:L,renderInstallOnboarding:F,nodeLabel:$,daemonLabel:K}=e,{t:z}=ke("common");if(t.length===0)return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:z("setupWizard.machines.title")}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-text-muted",children:z("setupWizard.machines.noMachinesDescription")})]}),F?F():s.jsx("p",{className:"text-[11px] text-text-muted",children:z("setupWizard.machines.noMachinesFallback")})]});const ne=H||_||(W==null?void 0:W.success)===!1||!P.trim()||n.addNodeDaemonPicker&&!M;return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:z("setupWizard.machines.title")}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-text-muted",children:z("setupWizard.machines.description")})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[a.map(ie=>{const Ce=!c&&o===ie.id;return s.jsx("button",{type:"button",onClick:()=>{d(!1),i(ie.id)},className:`flex items-center gap-2 rounded-lg border px-3 py-2 text-left transition-colors ${Ce?"border-accent-primary/60 bg-accent-primary/10":"border-border-subtle bg-bg-secondary/60 hover:border-border-default"}`,children:s.jsxs("span",{className:"min-w-0",children:[s.jsx("span",{className:"block truncate text-sm text-text-primary",children:ie.name}),s.jsxs("span",{className:"block truncate text-[11px] text-text-muted",children:[ie.repoIdentity||ie.repoRemoteUrl||""," · ",z("setupWizard.machines.nodeCount",{count:(ie.nodes||[]).length})]})]})},ie.id)}),s.jsx("button",{type:"button",onClick:()=>d(!0),className:`flex items-center gap-2 rounded-lg border px-3 py-2 text-left transition-colors ${c?"border-accent-primary/60 bg-accent-primary/10":"border-dashed border-border-subtle bg-bg-secondary/40 hover:border-border-default"}`,children:s.jsxs("span",{className:"text-sm text-text-primary",children:["+ ",z("setupWizard.machines.createNew")]})}),r&&a.length===0&&s.jsx("p",{className:"text-[11px] text-text-muted",children:z("setupWizard.machines.loadingMeshes")})]}),c&&s.jsx(ng,{variant:"wizard",showDaemonPicker:n.createDaemonPicker,daemons:t,daemonLabel:K,name:p,onNameChange:u,daemonId:m,onDaemonIdChange:f,workspace:g,onWorkspaceChange:k,workspaces:h,plan:x,planLoading:S,repoRemoteUrl:v,onRepoRemoteUrlChange:y,repoIdentity:j,onRepoIdentityChange:N,manualOpen:T,onManualOpenChange:A,creating:b,warning:w,onCreate:C}),!c&&o&&s.jsxs("div",{className:"flex flex-col gap-2.5 rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2.5",children:[I.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5",children:I.map(ie=>s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] text-text-secondary",children:$(ie)},ie.id))}),s.jsx("span",{className:"text-[11px] font-medium text-text-secondary",children:z("setupWizard.machines.attachTitle")}),n.addNodeDaemonPicker&&(D.length>0?s.jsx("div",{className:"flex flex-wrap gap-1.5",children:D.map(ie=>{const Ce=M===ie.id;return s.jsx("button",{type:"button",onClick:()=>E(ie.id),className:`rounded-full border px-2.5 py-1 text-[11px] transition-colors ${Ce?"border-accent-primary/60 bg-accent-primary/10 text-text-primary":"border-border-subtle bg-bg-secondary text-text-secondary hover:border-border-default"}`,children:K(ie)},ie.id)})}):s.jsx("p",{className:"text-[11px] text-text-muted",children:z("setupWizard.machines.allMachinesAttached")})),(!n.addNodeDaemonPicker||M)&&s.jsxs(s.Fragment,{children:[s.jsx(yl,{workspaces:R,value:P,onChange:B}),s.jsx(sg,{plan:W,loading:_}),s.jsx("div",{className:"flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:L,disabled:ne,children:z(H?"setupWizard.machines.attaching":"setupWizard.machines.addMachine")})})]})]})]})}function uR(e){var t;return e.machineNickname||e.nickname||e.hostname||((t=e.user)==null?void 0:t.name)||e.id}function pR(e){const t=e;return t.machine_label||t.machineLabel||t.hostname||String(e.workspace||"").split(/[\\/]/).filter(Boolean).pop()||e.id}function mR({daemons:e,features:t,sendCommand:n,unwrapResult:a,normalizeMesh:r,loadDaemonMetadata:o,initialMeshId:i,onClose:c,renderInstallOnboarding:d}){var Ae,be;const{t:p}=ke("common"),u=((Ae=e[0])==null?void 0:Ae.id)||"",{meshes:m,loading:f,error:g,setError:k,loadMeshes:h,selectedMeshId:x,setSelectedMeshId:S}=og({daemons:e,primaryDaemonId:u,sendCommand:n,unwrapResult:a,normalizeMesh:r,features:{createDaemonPicker:t.createDaemonPicker,addNodeDaemonPicker:t.addNodeDaemonPicker},loadDaemonMetadata:o});l.useEffect(()=>{h()},[h]);const b=l.useRef(m);b.current=m;const w=l.useMemo(()=>m.map(we=>we.id).sort().join(","),[m]),C=l.useRef(n);C.current=n;const v=l.useRef(a);v.current=a,l.useEffect(()=>{x||m.length===0||(i&&m.some(we=>we.id===i)?S(i):m.length===1&&S(m[0].id))},[m,x,i,S]);const y=l.useMemo(()=>m.find(we=>we.id===x)??null,[m,x]),j=l.useMemo(()=>(y==null?void 0:y.nodes)||[],[y]),N=l.useCallback(we=>(we==null?void 0:we.__sourceDaemonId)||u,[u]),[T,A]=l.useState(!1),[I,D]=l.useState(""),[M,E]=l.useState(""),[P,B]=l.useState(""),[R,W]=l.useState(null),[_,H]=l.useState(!1),[L,F]=l.useState(!1),[$,K]=l.useState(null),[z,ne]=l.useState(""),[ie,Ce]=l.useState(""),[me,O]=l.useState(!1),Y=t.createDaemonPicker&&M||u,X=l.useMemo(()=>e.find(we=>we.id===Y),[e,Y]),Q=(X==null?void 0:X.workspaces)||[];l.useEffect(()=>{if(!T||!Y||!P.trim()){W(null),H(!1);return}let we=!1;const _e=setTimeout(()=>{we||(H(!0),C.current(Y,"plan_mesh_onboarding",{workspace:P.trim(),operation:"auto",meshInventory:b.current}).then(U=>{if(we)return;const Ne=v.current(U);W(Ne),Ne!=null&&Ne.success&&(D(Ie=>{var We,Xe;return Ie||`${String(((We=Ne.discovery)==null?void 0:We.repoIdentity)||((Xe=Ne.discovery)==null?void 0:Xe.repoRoot)||"").split(/[\\/]/).filter(Boolean).pop()||"repo"}-mesh`}),Ce(Ie=>{var We;return Ie||((We=Ne.discovery)==null?void 0:We.repoIdentity)||""}),ne(Ie=>{var We,Xe,et,J,Le,$e;return Ie||((et=(Xe=(We=Ne.discovery)==null?void 0:We.origin)==null?void 0:Xe.urls)==null?void 0:et[0])||(($e=(Le=(J=Ne.discovery)==null?void 0:J.upstream)==null?void 0:Le.urls)==null?void 0:$e[0])||""}))}).catch(U=>{we||W({success:!1,error:(U==null?void 0:U.message)||"Git discovery failed"})}).finally(()=>{we||H(!1)}))},300);return()=>{we=!0,clearTimeout(_e)}},[T,Y,P,w]);const ve=l.useCallback(async()=>{const we=Y,_e=P.trim(),U=z.trim(),Ne=ie.trim();if(!(!we||!I.trim()||L)&&!(!_e&&!U&&!Ne)){F(!0),K(null),k(null);try{const Ie=await rg({targetDaemonId:we,name:I,repoRemoteUrl:U,repoIdentity:Ne,workspace:_e,attachWorkspace:!!_e,machineId:X==null?void 0:X.machineId,providerPriority:Pn(ln((X==null?void 0:X.availableProviders)||[])),meshInventory:m,sendCommand:n,unwrapResult:a});if(Ie.warning&&K(Ie.warning),!Ie.meshCreated){k(Ie.error||p("setupWizard.machines.createFailed"));return}await h(!0),Ie.meshId&&S(Ie.meshId),A(!1)}finally{F(!1)}}},[Y,I,P,z,ie,L,X,m,n,a,h,S,k,p]),[he,Z]=l.useState(""),[fe,V]=l.useState(""),[q,ee]=l.useState(null),[pe,le]=l.useState(!1),[se,te]=l.useState(!1),ue=l.useMemo(()=>{if(!t.addNodeDaemonPicker)return[];const we=new Set(j.map(_e=>String(_e.daemon_id||_e.daemonId||"")));return e.filter(_e=>_e.id&&!we.has(_e.id)&&!Xp(_e))},[t.addNodeDaemonPicker,j,e]),ye=l.useMemo(()=>e.find(we=>we.id===he),[e,he]),Me=t.addNodeDaemonPicker?(ye==null?void 0:ye.workspaces)||[]:((be=e.find(we=>we.id===u))==null?void 0:be.workspaces)||[];l.useEffect(()=>{if(T||!x||!fe.trim()){ee(null);return}const we=t.addNodeDaemonPicker?he:N(y);if(!we)return;let _e=!1;return le(!0),n(we,"plan_mesh_onboarding",{workspace:fe.trim(),meshId:x,inlineMesh:y,operation:"add_existing"}).then(U=>{_e||ee(a(U))}).catch(U=>{_e||ee({success:!1,error:(U==null?void 0:U.message)||"Git discovery failed"})}).finally(()=>{_e||le(!1)}),()=>{_e=!0}},[T,x,y,fe,he,t.addNodeDaemonPicker,N,n,a]);const re=l.useCallback(async()=>{var U,Ne,Ie,We;const we=N(y);if(!x||!we||se)return;const _e=fe.trim();if(_e){te(!0),k(null);try{const Xe=t.addNodeDaemonPicker?he:we,et=await n(Xe,"plan_mesh_onboarding",{workspace:_e,meshId:x,inlineMesh:y,operation:"add_existing"}),J=a(et);if(ee(J),(J==null?void 0:J.success)===!1)throw new Error(`${J.code||"onboarding_blocked"}: ${J.error}${J.action?` ${J.action}`:""}`);const Le={meshId:x,workspace:((U=J==null?void 0:J.discovery)==null?void 0:U.repoRoot)||_e,repoRoot:(Ne=J==null?void 0:J.discovery)==null?void 0:Ne.repoRoot,isLocalWorktree:((Ie=J==null?void 0:J.discovery)==null?void 0:Ie.isLinkedWorktree)===!0};t.addNodeDaemonPicker&&he&&(Le.daemonId=he,Le.machineId=ye==null?void 0:ye.machineId),Le.providerPriority=Pn(ln(((We=t.addNodeDaemonPicker?ye:e[0])==null?void 0:We.availableProviders)||[]));const $e=await n(we,"add_mesh_node",Le),at=a($e);if((at==null?void 0:at.success)===!1)throw new Error(at.error||"Add node failed");V(""),ee(null),await h(!0)}catch(Xe){k((Xe==null?void 0:Xe.message)||"Add node failed")}finally{te(!1)}}},[y,x,fe,he,ye,se,t.addNodeDaemonPicker,N,e,n,a,h,k]),ce=!T&&!!y&&j.length>0;return s.jsxs("div",{className:"mx-auto flex w-full max-w-2xl flex-col gap-4 p-4",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-base font-semibold text-text-primary",children:p("setupWizard.title")}),s.jsx("p",{className:"mt-1.5 text-[11px] text-text-muted",children:p("setupWizard.machines.description")})]}),g&&s.jsx("p",{className:"text-[11px] text-red-400",children:g}),s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary p-4",children:s.jsx(dR,{daemons:e,features:t,meshes:m,meshesLoading:f,selectedMeshId:x,onSelectMesh:we=>{S(we),V(""),Z("")},createMode:T,onCreateModeChange:A,createName:I,onCreateNameChange:D,createDaemonId:M,onCreateDaemonIdChange:E,createWorkspace:P,onCreateWorkspaceChange:B,createPickerWorkspaces:Q,createPlan:R,createPlanLoading:_,creating:L,createWarning:$,onCreate:ve,createRepoRemoteUrl:z,onCreateRepoRemoteUrlChange:ne,createRepoIdentity:ie,onCreateRepoIdentityChange:Ce,createManualOpen:me,onCreateManualOpenChange:O,nodes:j,attachableDaemons:ue,attachDaemonId:he,onAttachDaemonIdChange:we=>{Z(we),V("")},attachWorkspace:fe,onAttachWorkspaceChange:V,attachPickerWorkspaces:Me,attachPlan:q,attachPlanLoading:pe,attaching:se,onAttach:re,renderInstallOnboarding:d,nodeLabel:pR,daemonLabel:uR})}),s.jsx("div",{className:"flex items-center gap-2",children:s.jsx("div",{className:"ml-auto flex items-center gap-2",children:s.jsx("button",{type:"button",className:ce?"btn btn-primary btn-sm":"btn btn-secondary btn-sm",onClick:c,children:p(ce?"setupWizard.continueToMesh":"setupWizard.close")})})})]})}function Tc(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function hR(e){if(typeof window>"u")return e;const t=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),n=Tc();return n&&!t.searchParams.has("token")&&t.searchParams.set("token",n),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function Ts(e,t){return await fetch(hR(e),{credentials:"same-origin",...t})}function cg(){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 fR{constructor(){it(this,"adapters",new Map);it(this,"states",new Map);it(this,"runtimeListeners",new Map);it(this,"screenshotCallbacks",new Map);it(this,"statusCallbacks",new Set);it(this,"stateChangeCallbacks",new Set);it(this,"ptyInputSender",null)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const n of this.adapters.keys())if(n.startsWith("standalone"))return n}return null}register(t,n){this.adapters.set(t,n),this.states.set(t,n.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,n){this.states.set(t,n);const a=this.resolveDaemonId(t)||t;this.stateChangeCallbacks.forEach(r=>r(a,n))}onStateChange(t){return this.stateChangeCallbacks.add(t),()=>{this.stateChangeCallbacks.delete(t)}}retryConnection(t){}get(t){const n=this.resolveDaemonId(t);return n?this.adapters.get(n):void 0}getState(t){const n=this.resolveDaemonId(t);return n&&this.states.get(n)||"disconnected"}registerPtyInputSender(t){this.ptyInputSender=t}sendData(t,n){return!1}sendPtyInput(t,n,a){return this.ptyInputSender?this.ptyInputSender(t,n,a):!1}onScreenshot(t,n){return this.screenshotCallbacks.set(t,n),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,n){this.screenshotCallbacks.forEach(a=>a(t,n))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,n){this.statusCallbacks.forEach(a=>a(t,n))}emitRuntimeSnapshot(t,n,a=0,r=!1,o,i){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:a,text:n,truncated:r,cols:o,rows:i})}emitSessionOutput(t,n,a){!t||typeof n!="string"||!n||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof a=="number"?{seq:a}:{},data:n})}onRuntimeEvent(t,n){const a=this.runtimeListeners.get(t)||new Set;return a.add(n),this.runtimeListeners.set(t,a),()=>{const r=this.runtimeListeners.get(t);r&&(r.delete(n),r.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,n,a){if(!n)return{success:!1,error:"sessionId is required"};const r=new URL(`/api/v1/runtime/${encodeURIComponent(n)}/snapshot`,window.location.origin);typeof(a==null?void 0:a.sinceSeq)=="number"&&r.searchParams.set("sinceSeq",String(a.sinceSeq));const o=await Ts(`${r.pathname}${r.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(n,{type:"runtime_snapshot",sessionId:n,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:!!(a!=null&&a.force)}),{success:!0}}emitRuntimeEvent(t,n){var a;(a=this.runtimeListeners.get(t))==null||a.forEach(r=>r(n))}}const As=new fR;function gR(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,n=Tc();return n?`${t}?token=${encodeURIComponent(n)}`:t}const Sr=gR(),ap=3e3,bR=3e4;let gs=null,xR=0;const io=new Map;let gn=null,Ia=null;function rp(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function ya(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function vR(e){return e==="connected"?"connected":e}async function La(e,t,n){const a=ph(e,n||{}),r=gs;if(r&&r.readyState===WebSocket.OPEN){const o=`req_${++xR}_${Date.now()}`;return new Promise((i,c)=>{const d=setTimeout(()=>{io.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);io.set(o,{resolve:p=>{clearTimeout(d),i(p)},reject:p=>{clearTimeout(d),c(p)}}),r.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:a.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function Al(e,t){const n=gs;if(!n||n.readyState!==WebSocket.OPEN||!t||t.type!=="subscribe"&&t.type!=="unsubscribe")return!1;try{return n.send(JSON.stringify(t)),!0}catch{return!1}}function dg(e,t,n){const a=gs;if(!a||a.readyState!==WebSocket.OPEN)return!1;const r=ph(e,{sessionId:t,targetSessionId:t,data:n});try{return a.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:r.payload}})),!0}catch{return!1}}As.registerPtyInputSender(dg);class yR{constructor(t){it(this,"daemonId");it(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(gs==null?void 0:gs.readyState)===WebSocket.OPEN}get connectionState(){return(gs==null?void 0:gs.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,n){return La(this.daemonId,t,n)}async sendInput(t,n){return La(this.daemonId,"cdp_remote_action",{action:t,params:n,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,gn&&(clearInterval(gn),gn=null);const n=async()=>{if(this.hasCommandChannel)try{const a=await La(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(a!=null&&a.success&&(a!=null&&a.base64)){const r=await fetch(`data:image/jpeg;base64,${a.base64}`).then(o=>o.blob());As.emitScreenshot(this.daemonId,r)}}catch{}};n(),gn=setInterval(n,2e3)}stopScreenshots(t){gn&&(clearInterval(gn),gn=null)}}let rs=null;function wR(e){return(!rs||rs.daemonId!==e)&&(rs=new yR(e)),rs}function kR({children:e}){const t=l.useRef(Ra()),n=Ra();t.current=n;const{setUserName:a}=Ss(),r=l.useRef(a);r.current=a;const o=l.useRef(null),i=l.useRef(null),[,c]=l.useState("disconnected"),d=l.useCallback((h,x)=>{c(h),Ia==null||Ia(h,x)},[]),p=l.useRef(null),u=l.useRef(),m=l.useRef(ap),f=l.useRef(!0),g=l.useRef(!1),k=l.useRef("initial_connect");return l.useEffect(()=>{f.current=!0,g.current=!1;function h(){var b,w;if(!f.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 ${Sr}...`),ya("connect_attempt",{url:Sr,reason:k.current,delayMs:m.current});let S;try{S=new WebSocket(Sr)}catch(C){console.error("[Standalone WS] Failed to create WebSocket:",C),x();return}p.current=S,S.onopen=()=>{if(!f.current){S.close();return}d("connected"),m.current=ap,ya("open",{url:Sr,reason:k.current}),ys.resubscribeAll({sendData:Al}),console.log("[Standalone WS] Connected")},gs=S,S.onmessage=C=>{var v,y;try{const j=JSON.parse(C.data);if((j.type==="command_result"||j.type==="error")&&j.requestId){const N=io.get(j.requestId);N&&(io.delete(j.requestId),j.type==="error"?N.reject(new Error(((v=j.data)==null?void 0:v.message)||"Command failed")):N.resolve(j.data));return}if(j.type==="session_output"){const N=j.sessionId||j.cliId||j.cliType;N&&As.emitSessionOutput(N,typeof j.data=="string"?j.data:"",typeof j.seq=="number"?j.seq:void 0);return}if(j.type==="runtime_snapshot"){As.emitRuntimeSnapshot(j.sessionId,typeof j.text=="string"?j.text:"",typeof j.seq=="number"?j.seq:0,!!j.truncated,typeof j.cols=="number"?j.cols:void 0,typeof j.rows=="number"?j.rows:void 0);return}if(j.type==="topic_update"){const N=j.update;N&&ys.publish(N);return}if(j.type==="status"||j.type==="initial_state"){const N=j.data;if(!N)return;const{injectEntries:T,markLoaded:A,getIdes:I}=t.current,D=N.instanceId||"standalone",M=I().find(B=>B.id===D),E=wR(D);As.register(D,E),As.setState(D,"connected"),d("connected",D),As.emitStatus(D,N);const P=Wr(N,{daemonId:D,existingDaemon:M,existingEntries:I()});rp("ws_status",{type:j.type,daemonId:D,sessions:(N.sessions||[]).map(B=>({id:B.id,parentId:B.parentId,providerType:B.providerType,kind:B.kind,transport:B.transport,unread:B.unread,inboxBucket:B.inboxBucket,lastSeenAt:B.lastSeenAt,lastUpdated:B.lastUpdated,title:B.title})),recentLaunches:(N.recentLaunches||[]).map(B=>({id:B.id,providerType:B.providerType,kind:B.kind,workspace:B.workspace,lastLaunchedAt:B.lastLaunchedAt}))}),rp("entries",{daemonId:D,entries:P.filter(B=>B.type!=="adhdev-daemon").map(B=>({id:B.id,type:B.type,unread:B.unread,inboxBucket:B.inboxBucket,lastSeenAt:B.lastSeenAt,lastUpdated:B.lastUpdated,sessionId:B.sessionId}))}),P.length>0&&T(P,{authoritativeDaemonIds:[D]}),A(),i.current!==D&&((y=o.current)==null||y.call(o),i.current=D,o.current=ys.subscribe({sendData:Al},D,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${D}`,params:{includeSessions:!0}},B=>{if(B.topic!=="daemon.metadata")return;const R=t.current.getIdes(),W=R.find(H=>H.id===D),_=Wr(B.status,{daemonId:D,existingDaemon:W,existingEntries:R,timestamp:B.timestamp});_.length>0&&t.current.injectEntries(_,{authoritativeDaemonIds:[D]}),B.userName&&r.current&&r.current(B.userName)}))}}catch(j){console.error("[Standalone WS] Parse error:",j)}},S.onclose=C=>{f.current&&(rs==null||rs.stopScreenshots(),rs&&As.setState(rs.daemonId,"disconnected"),d("disconnected"),p.current=null,k.current=`close:${C.code}${C.wasClean?":clean":":unclean"}`,ya("close",{code:C.code,reason:C.reason||"",wasClean:C.wasClean}),x())},S.onerror=C=>{g.current||!f.current||(k.current="error",ya("error",{message:C instanceof Event?"event":String(C),readyState:S.readyState}),console.warn("[Standalone WS] Error, will reconnect:",C))}}function x(){if(!f.current)return;clearTimeout(u.current);const S=m.current;console.log(`[Standalone WS] Reconnecting in ${S}ms...`),ya("schedule_reconnect",{reason:k.current,delayMs:S}),u.current=setTimeout(()=>{m.current=Math.min(m.current*1.5,bR),h()},S)}return h(),()=>{var S;f.current=!1,g.current=!0,(S=o.current)==null||S.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,gs=null),rs&&(rs.stopScreenshots(),As.unregister(rs.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function SR({children:e}){const[t,n]=l.useState("disconnected"),[a,r]=l.useState(null);l.useEffect(()=>(Ia=(i,c)=>{n(i),c&&r(c)},()=>{Ia=null}),[]);const o=l.useMemo(()=>{const i=t==="connected",c=vR(t),d={};return a&&(d[a]=c),d.standalone=c,{wsStatus:t,isConnected:i,connectionStates:d,usesP2P:!1}},[t,a]);return s.jsx(Zg,{connectionOverrides:o,children:s.jsx(kR,{children:e})})}const ug="adhdev_standalone_font_preferences",Nn={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Lo=[{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"}],Wa=[{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"}],CR=new Set(Lo.map(e=>e.id)),jR=new Set(Wa.map(e=>e.id));function Ms(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Rr("chat",t.chat),code:Rr("code",t.code),terminal:Rr("terminal",t.terminal)}}function Rr(e,t){const n=Nn[e],a=t&&typeof t=="object"&&!Array.isArray(t)?t:{},r=typeof a.preset=="string"?a.preset.trim():"",o=typeof a.customFamily=="string"?a.customFamily.trim():"";return(e==="chat"?CR:jR).has(r)?r==="custom"?o?{preset:"custom",customFamily:o}:n:{preset:r}:n}function Er(e,t){var r;const n=Rr(e,t);if(n.preset==="custom"&&n.customFamily)return n.customFamily;const a=e==="chat"?Lo:Wa;return((r=a.find(o=>o.id===n.preset))==null?void 0:r.family)||a[0].family}function NR(e){const t=Ms(e),n=Er("chat",t.chat),a=Er("code",t.code),r=Er("terminal",t.terminal);return{"--chat-font-family":n,"--chat-code-font-family":a,"--chat-terminal-font-family":r,"--chat-tool-font-family":r}}function xn(e,t=document.documentElement){const n=Ms(e),a=NR(n);t.setAttribute("data-standalone-fonts","custom");for(const[r,o]of Object.entries(a))t.style.setProperty(r,o);return n}function Tl(e){const t=Ms(e);try{localStorage.setItem(ug,JSON.stringify(t))}catch{}return t}function AR(){try{const e=localStorage.getItem(ug);if(e)return Ms(JSON.parse(e))}catch{}return Nn}function TR(){return xn(AR())}function wa(e,t){var a;const n=e==="chat"?Lo:Wa;return((a=n.find(r=>r.id===t))==null?void 0:a.label)||n[0].label}function MR({children:e}){const t=oa(),n=Pl(),{t:a}=ke("common"),r=l.useMemo(()=>[{id:"dashboard",path:"/dashboard",icon:s.jsx(kp,{}),label:a("nav.dashboard"),active:n.pathname.startsWith("/dashboard"),onSelect:()=>t("/dashboard")},{id:"machine",path:"/machines",icon:s.jsx(sn,{}),label:a("nav.machines"),active:n.pathname.startsWith("/machines"),onSelect:()=>t("/machines")},{id:"mesh",path:"/mesh",icon:s.jsx(cs,{}),label:a("nav.mesh"),active:n.pathname.startsWith("/mesh")||n.pathname.startsWith("/setup"),onSelect:()=>t("/mesh")},{id:"settings",path:"/settings",icon:s.jsx(Oa,{}),label:a("nav.settings"),active:n.pathname.startsWith("/settings"),onSelect:()=>t("/settings")}],[n.pathname,t,a]),o=l.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:a("nav.docs")}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(Sp,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:a("nav.docs")},{id:"about",label:a("nav.about"),icon:s.jsx(co,{}),active:n.pathname==="/about",onSelect:()=>t("/about"),title:a("nav.about")}],[n.pathname,t,a]);return s.jsx(l1,{brand:({collapsed:i})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&s.jsx("span",{children:"ADHDev"})]}),navItems:r,footerItems:o,footerInfo:({collapsed:i})=>i?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","1.0.53"]}),footerActions:({collapsed:i,toggleCollapsed:c})=>s.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:c,title:a(i?"standalone.layout.expandSidebar":"standalone.layout.collapseSidebar"),children:[s.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&s.jsx("span",{className:"text-xs",children:a("standalone.layout.collapse")})]}),children:e})}function PR(){const e=oa(),{sendCommand:t}=St(),{ides:n}=Ss(),a=l.useMemo(()=>n.filter(r=>r.daemonMode||r.type==="adhdev-daemon").map(r=>r),[n]);return s.jsx(mR,{daemons:a,features:Zf,sendCommand:t,unwrapResult:r=>r,normalizeMesh:r=>r,onClose:()=>e("/mesh")})}const DR=[{icon:s.jsx(sn,{size:16}),key:"localFirst"},{icon:s.jsx(Ds,{size:16}),key:"chatRelay"},{icon:s.jsx(El,{size:16}),key:"screenshots"},{icon:s.jsx(us,{size:16}),key:"remoteControl"},{icon:s.jsx(Ea,{size:16}),key:"multiIde"},{icon:s.jsx(Sp,{size:16}),key:"cliAcp"}],IR=[{icon:s.jsx(mo,{size:16}),key:"anywhere"},{icon:s.jsx(kp,{size:16}),key:"p2pStream"},{icon:s.jsx(ia,{size:16}),key:"mobileNotifications"},{icon:s.jsx(cb,{size:16}),key:"restApi"},{icon:s.jsx(ub,{size:16}),key:"enterpriseControls"}],LR=[{key:"chatRelay",selfhost:!0,cloud:!0},{key:"screenshots",selfhost:!0,cloud:!0},{key:"remoteControl",selfhost:!0,cloud:!0},{key:"multiIde",selfhost:!0,cloud:!0},{key:"extensionCli",selfhost:!0,cloud:!0},{key:"anyNetwork",selfhost:!1,cloud:!0},{key:"webrtc",selfhost:!1,cloud:!0},{key:"mobilePush",selfhost:!1,cloud:!0},{key:"restApi",selfhost:!1,cloud:!0},{key:"multiMachineDashboards",selfhost:!1,cloud:!0},{key:"ssoRbacAuditLogs",selfhost:!1,cloud:!0}];function RR(){const{t:e}=ke("common");return s.jsxs(Qa,{icon:s.jsx(co,{className:"text-text-primary"}),title:e("standalone.about.title"),subtitle:e("standalone.about.subtitle"),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","1.0.53"]}),children:[s.jsx(xt,{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:e("standalone.about.selfHostedEdition")}),s.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:e("standalone.about.headline")}),s.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:e("standalone.about.description")})]}),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:e("standalone.about.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:e("standalone.about.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:e("standalone.about.tryCloud")})]})]})}),s.jsx(xt,{title:e("standalone.about.includedSection"),description:e("standalone.about.includedDescription"),children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:DR.map(t=>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:t.icon}),e("standalone.about.features."+t.key+".title")]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e("standalone.about.features."+t.key+".desc")})]},t.key))})}),s.jsx(xt,{title:e("standalone.about.inventorySection"),description:e("standalone.about.inventoryDescription"),children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:mh.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:fh.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:hh.map(t=>`${t.icon} ${t.name}`)}].map(t=>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:t.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:t.items.map(n=>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:n},n))})]},t.label))})}),s.jsx(xt,{title:e("standalone.about.cloudExtrasSection"),description:e("standalone.about.cloudExtrasDescription"),children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:IR.map(t=>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:t.icon}),e("standalone.about.extras."+t.key+".title")]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e("standalone.about.extras."+t.key+".desc")})]},t.key))})}),s.jsx(xt,{title:e("standalone.about.comparisonSection"),description:e("standalone.about.comparisonDescription"),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:e("standalone.about.featureHeader")}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:e("standalone.about.selfhostHeader")}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:e("standalone.about.cloudHeader")})]})}),s.jsx("tbody",{children:LR.map((t,n)=>s.jsxs("tr",{className:n%2===0?"bg-bg-glass":"bg-transparent",children:[s.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e("standalone.about.comparison."+t.key)}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:t.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:"✓"})})]},t.key))})]})})}),s.jsx(Ja,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:e("standalone.about.cloudOptional"),description:e("standalone.about.cloudOptionalDescription"),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:e("standalone.about.compareCloud")}),s.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[s.jsx(yb,{size:14,className:"mr-1"}),e("standalone.about.discord")]})]})})]})}function Ei(e,t,n){return{...e,[t]:n}}function _i({surface:e,title:t,description:n,value:a,options:r,onChange:o}){const{t:i}=ke("common");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:n})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(p1,{value:a.preset,onChange:c=>{const d=c.target.value;o(d==="custom"?{preset:"custom",customFamily:a.customFamily||""}:{preset:d})},children:r.map(c=>s.jsx("option",{value:c.id,children:c.label},c.id))}),a.preset==="custom"&&s.jsx(xs,{type:"text",className:"font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:a.customFamily||"",onChange:c=>o({preset:"custom",customFamily:c.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:i("standalone.fonts.resolvedStack")})," ",s.jsx("span",{className:"font-mono break-all",children:Er(e,a)})]})]})]})}function ER({value:e,savedValue:t,saving:n=!1,error:a,notice:r,onChange:o,onSave:i,onResetToSaved:c,onResetToDefaults:d}){const{t:p}=ke("common"),u=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:p("standalone.fonts.fontOverridesNotice")}),a&&s.jsx(Mt,{variant:"error",children:a}),r&&s.jsx(Mt,{variant:"success",children:r}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(_i,{surface:"chat",title:p("standalone.fonts.chat"),description:p("standalone.fonts.chatDescription"),value:e.chat,options:Lo,onChange:m=>o(Ei(e,"chat",m))}),s.jsx(_i,{surface:"code",title:p("standalone.fonts.code"),description:p("standalone.fonts.codeDescription"),value:e.code,options:Wa,onChange:m=>o(Ei(e,"code",m))}),s.jsx(_i,{surface:"terminal",title:p("standalone.fonts.terminal"),description:p("standalone.fonts.terminalDescription"),value:e.terminal,options:Wa,onChange:m=>o(Ei(e,"terminal",m))})]}),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:p("standalone.fonts.livePreview")}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",wa("chat",e.chat.preset)," · Code: ",wa("code",e.code.preset)," · Terminal: ",wa("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[p("standalone.fonts.defaults")," ",wa("chat",Nn.chat.preset)," / ",wa("code",Nn.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(Us,{type:"button",variant:"primary",size:"sm",onClick:i,disabled:n||!u,children:p(n?"standalone.fonts.saving":"standalone.fonts.saveFontSettings")}),s.jsx(Us,{type:"button",variant:"secondary",size:"sm",onClick:c,disabled:n||!u,children:p("standalone.fonts.revertToSaved")}),s.jsx(Us,{type:"button",variant:"secondary",size:"sm",onClick:d,disabled:n,children:p("standalone.fonts.resetToDefaults")})]})]})}function _R(){const{t:e}=ke("common"),{ides:t}=Ss(),n=t.find(O=>O.type==="adhdev-daemon"),a=(n==null?void 0:n.detectedIdes)||[],{sendCommand:r}=St(),{userName:o}=Ss(),[i,c]=l.useState(o||""),[d,p]=l.useState(null),[u,m]=l.useState(null),[f,g]=l.useState(Nn),[k,h]=l.useState(!1),[x,S]=l.useState(""),[b,w]=l.useState(""),[C,v]=l.useState("127.0.0.1"),[y,j]=l.useState(""),[N,T]=l.useState(""),[A,I]=l.useState(""),[D,M]=l.useState(""),[E,P]=l.useState(""),[B,R]=l.useState(!1),W=async()=>{const Y=await(await Ts("/auth/session")).json();p(Y)},_=async()=>{const Y=await(await Ts("/api/v1/standalone/preferences")).json();m(Y),v(Y.standaloneBindHost);const X=Ms(Y.standaloneFontPreferences);g(X),xn(X),Tl(X)};l.useEffect(()=>{o!==void 0&&c(o)},[o]),l.useEffect(()=>{Promise.all([W(),_()]).catch(O=>{M(O instanceof Error?O.message:String(O))})},[]),l.useEffect(()=>{xn(f)},[f]);const H=O=>{const Y=O.target.value.trim();n!=null&&n.id&&Y!==o&&r(n.id,"set_user_name",{userName:Y}).catch(console.error)},[L,F]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),$=O=>{F(O);try{localStorage.setItem("adhdev_sound",O?"1":"0")}catch{}},K=async()=>{S(""),w(""),h(!0);try{const O=Ms(f),Y=await Ts("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:O})}),X=await Y.json();if(!Y.ok)throw new Error((X==null?void 0:X.error)||"Failed to save standalone font preferences");const Q=Ms(X.standaloneFontPreferences);m(X),g(Q),xn(Q),Tl(Q),w(e("standalone.settings.fontsSaved"))}catch(O){S(O instanceof Error?O.message:String(O))}finally{h(!1)}},z=()=>{const O=Ms(u==null?void 0:u.standaloneFontPreferences);S(""),w(""),g(O),xn(O)},ne=()=>{S(""),w(""),g(Nn),xn(Nn)},ie=async()=>{M(""),P(""),R(!0);try{const O=await Ts("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:C})}),Y=await O.json();if(!O.ok)throw new Error((Y==null?void 0:Y.error)||"Failed to save standalone network preference");m(Y),v(Y.standaloneBindHost),P(Y.standaloneBindHost==="0.0.0.0"?e("standalone.settings.networkSavedAll"):e("standalone.settings.networkSavedLocal"))}catch(O){M(O instanceof Error?O.message:String(O))}finally{R(!1)}},Ce=async()=>{if(M(""),P(""),N.trim().length<4){M(e("standalone.settings.passwordTooShort"));return}if(N!==A){M(e("standalone.settings.passwordMismatch"));return}R(!0);try{const O=await Ts("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,newPassword:N})}),Y=await O.json();if(!O.ok)throw new Error((Y==null?void 0:Y.error)||"Failed to save password");p(Y),await _(),j(""),T(""),I(""),P(d!=null&&d.hasPasswordAuth?e("standalone.settings.passwordUpdated"):e("standalone.settings.passwordEnabled")),cg()}catch(O){M(O instanceof Error?O.message:String(O))}finally{R(!1)}},me=async()=>{M(""),P(""),R(!0);try{const O=await Ts("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,clear:!0})}),Y=await O.json();if(!O.ok)throw new Error((Y==null?void 0:Y.error)||"Failed to clear password");p(Y),await _(),j(""),T(""),I(""),P(e("standalone.settings.passwordDisabled"))}catch(O){M(O instanceof Error?O.message:String(O))}finally{R(!1)}};return s.jsxs(Qa,{icon:s.jsx(Oa,{className:"text-text-primary"}),title:e("standalone.settings.title"),subtitle:e("standalone.settings.subtitle"),widthClassName:"max-w-5xl",children:[s.jsx(Mt,{variant:"info",children:e("standalone.settings.infoNotice")}),(d==null?void 0:d.publicHostWarning)&&s.jsx(Mt,{variant:"warning",children:e("standalone.settings.publicHostWarning")}),s.jsx(xt,{title:e("standalone.settings.daemonSection"),description:e("standalone.settings.daemonDescription"),children:s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.versionLabel")}),s.jsxs("span",{className:"font-mono text-xs text-text-primary",children:["v","1.0.53"]})]}),s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.statusLabel")}),s.jsx("span",{className:`text-xs font-medium ${n?"text-green-400":"text-yellow-400"}`,children:e(n?"standalone.settings.statusRunning":"standalone.settings.statusNotConnected")})]}),s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.currentBindLabel")}),s.jsx("span",{className:"font-mono text-xs text-text-primary",children:(u==null?void 0:u.currentBindHost)||(d==null?void 0:d.boundHost)||"127.0.0.1"})]}),s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.defaultBindLabel")}),s.jsx("span",{className:"font-mono text-xs text-text-primary",children:(u==null?void 0:u.standaloneBindHost)||"127.0.0.1"})]}),s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.authLabel")}),s.jsx("span",{className:"text-xs text-text-primary",children:d!=null&&d.hasPasswordAuth?e("standalone.settings.authPassword"):d!=null&&d.hasTokenAuth?e("standalone.settings.authToken"):e("standalone.settings.authNone")})]})]})}),s.jsx(xt,{title:e("standalone.settings.networkSection"),description:e("standalone.settings.networkDescription"),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:e("standalone.settings.networkHint")}),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:C==="127.0.0.1",onChange:()=>v("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:e("standalone.settings.localhostLabel")}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:e("standalone.settings.localhostHint")})]})]}),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:C==="0.0.0.0",onChange:()=>v("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:e("standalone.settings.allInterfacesLabel")}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:e("standalone.settings.allInterfacesHint")})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx(Us,{type:"button",variant:"primary",size:"sm",onClick:()=>{ie()},disabled:B,children:e(B?"standalone.settings.saving":"standalone.settings.saveNetworkMode")}),s.jsx("span",{className:"text-xs text-text-muted",children:e("standalone.settings.networkRestartHint",{host:(u==null?void 0:u.currentBindHost)||(d==null?void 0:d.boundHost)||"127.0.0.1"})})]})]})}),s.jsx(xt,{title:e("standalone.settings.securitySection"),description:e("standalone.settings.securityDescription"),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:d!=null&&d.hasPasswordAuth?e("standalone.settings.passwordSet"):e("standalone.settings.passwordNotSet")}),D&&s.jsx(Mt,{variant:"error",children:D}),E&&s.jsx(Mt,{variant:"success",children:E}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx(xs,{type:"password",placeholder:d!=null&&d.hasPasswordAuth?e("standalone.settings.currentPasswordPlaceholder"):e("standalone.settings.currentPasswordFirstTimePlaceholder"),value:y,onChange:O=>j(O.target.value)}),s.jsx(xs,{type:"password",placeholder:d!=null&&d.hasPasswordAuth?e("standalone.settings.newPasswordPlaceholder"):e("standalone.settings.newPasswordFirstTimePlaceholder"),value:N,onChange:O=>T(O.target.value)}),s.jsx(xs,{type:"password",className:"md:col-span-2",placeholder:e("standalone.settings.confirmPasswordPlaceholder"),value:A,onChange:O=>I(O.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Us,{type:"button",variant:"primary",size:"sm",onClick:()=>{Ce()},disabled:B,children:B?e("standalone.settings.saving"):d!=null&&d.hasPasswordAuth?e("standalone.settings.updatePassword"):e("standalone.settings.enablePassword")}),(d==null?void 0:d.hasPasswordAuth)&&s.jsx(Us,{type:"button",variant:"danger",size:"sm",onClick:()=>{me()},disabled:B,children:e("standalone.settings.disablePassword")})]})]})}),s.jsx(xt,{title:e("standalone.settings.detectedIdesSection"),description:e("standalone.settings.detectedIdesDescription"),children:a.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:e("standalone.settings.noIdesDetected")}):s.jsx("div",{className:"flex flex-col gap-2",children:a.map(O=>s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${O.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium text-text-primary",children:O.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:O.type})]},O.type))})}),s.jsx(xt,{title:e("standalone.settings.machineSection"),description:e("standalone.settings.machineDescription"),children:s.jsx(k1,{ides:t,emptyMessage:e("standalone.settings.daemonNotConnected")})}),s.jsx(xt,{title:e("standalone.settings.appearanceSection"),description:e("standalone.settings.appearanceDescription"),children:s.jsx(B1,{themeDescription:e("standalone.settings.themeDescription"),mobileDescription:e("standalone.settings.mobileDescription"),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:e("standalone.settings.fontsLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:e("standalone.settings.fontsDescription")}),s.jsx(ER,{value:f,savedValue:Ms(u==null?void 0:u.standaloneFontPreferences),saving:k,error:x,notice:b,onChange:g,onSave:()=>{K()},onResetToSaved:z,onResetToDefaults:ne})]})})}),s.jsx(xt,{title:e("standalone.settings.notificationsSection"),description:e("standalone.settings.notificationsDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(b1,{}),s.jsx(bn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(vb,{size:15})," ",e("standalone.settings.soundEffectsLabel")]}),description:e("standalone.settings.soundEffectsDescription"),checked:L,onChange:$})]})}),s.jsx(xt,{title:e("standalone.settings.profileSection"),description:e("standalone.settings.profileDescription"),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(lb,{size:16,className:"text-text-secondary"})," ",e("standalone.settings.displayNameLabel")]}),s.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:e("standalone.settings.displayNameHint")})]}),s.jsx(xs,{type:"text",className:"w-48 text-right",placeholder:e("standalone.settings.displayNamePlaceholder"),value:i,onChange:O=>c(O.target.value),onBlur:H,onKeyDown:O=>{O.key==="Enter"&&O.currentTarget.blur()}})]})})})]})}const HR=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],ja="adhdev_onboarding_done",$R=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],FR={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function BR({onDone:e}){const{t}=ke("common"),[n,a]=l.useState([]),[r,o]=l.useState(new Set(HR)),[i,c]=l.useState(!0),[d,p]=l.useState(null),[u,m]=l.useState(!1),[f,g]=l.useState(null),[k,h]=l.useState("all");l.useEffect(()=>{let y=!1;return fetch("https://api.adhf.dev/api/v1/registry/providers?sort=popular&limit=100").then(async N=>{if(!N.ok)throw new Error(`HTTP ${N.status}`);const T=await N.text();try{return JSON.parse(T)}catch{throw new Error(`unexpected non-JSON response (${N.headers.get("content-type")??"unknown content type"})`)}}).then(N=>{y||a(N.providers??[])}).catch(N=>{y||p(N instanceof Error?N.message:String(N))}).finally(()=>{y||c(!1)}),()=>{y=!0}},[]);const x=n.filter(y=>k==="all"||y.category===k),S=["cli","ide","extension","acp"].map(y=>({category:y,items:x.filter(j=>j.category===y)})).filter(y=>y.items.length>0),b=l.useCallback(y=>{o(j=>{const N=new Set(j);return N.has(y)?N.delete(y):N.add(y),N})},[]),w=l.useCallback(async()=>{if(r.size===0){localStorage.setItem(ja,"1"),e();return}m(!0);const y=[];for(const j of r)try{const T=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:j})})).json().catch(()=>({}));y.push({type:j,ok:!!T.success,error:T.error})}catch(N){y.push({type:j,ok:!1,error:N instanceof Error?N.message:String(N)})}g(y),m(!1),y.every(j=>j.ok)&&localStorage.setItem(ja,"1")},[r,e]),C=l.useCallback(()=>{localStorage.setItem(ja,"1"),e()},[e]),v=l.useCallback(()=>{f&&f.every(y=>y.ok)?e():u||C()},[f,u,e,C]);return s.jsx(xm,{open:!0,onClose:v,size:"lg",contentClassName:"max-w-2xl",title:t("standalone.onboarding.title"),footer:s.jsxs("div",{className:"flex w-full items-center gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:t(r.size!==1?"standalone.onboarding.selectedCount_other":"standalone.onboarding.selectedCount_one",{count:r.size})}),s.jsxs("div",{className:"ml-auto flex gap-2",children:[s.jsx(Us,{variant:"secondary",size:"sm",onClick:C,disabled:u,children:t("standalone.onboarding.skip")}),s.jsx(Us,{variant:"primary",size:"sm",onClick:()=>{f?(localStorage.setItem(ja,"1"),e()):w()},disabled:u||!f&&r.size===0,children:u?t("standalone.onboarding.installing"):f?t("standalone.onboarding.done"):t("standalone.onboarding.installCount",{count:r.size})})]})]}),children:s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsx("div",{className:"text-[12px] text-text-muted",children:t("standalone.onboarding.intro")}),!i&&!d&&n.length>0&&s.jsx("div",{className:"flex gap-1 flex-wrap border-b border-border-subtle pb-2",children:$R.map(y=>{const j=y.key==="all"?n.length:n.filter(N=>N.category===y.key).length;return j===0&&y.key!=="all"?null:s.jsxs("button",{onClick:()=>h(y.key),className:`machine-btn text-[10px] px-2 py-0.5 ${k===y.key?"bg-accent-primary/12 border-accent-primary/40 text-accent-primary":""}`,children:[y.label," ",s.jsxs("span",{className:"opacity-60",children:["(",j,")"]})]},y.key)})}),i&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.loadingRegistry")}),!i&&d&&s.jsx(Mt,{variant:"error",children:t("standalone.onboarding.loadError",{error:d})}),!i&&!d&&x.length===0&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.noProviders")}),!i&&!d&&x.length>0&&s.jsx("div",{className:"flex flex-col gap-4",children:S.map(y=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:FR[y.category]??y.category}),s.jsx("div",{className:"grid gap-1.5",children:y.items.map(j=>{var I;const N=r.has(j.type),T=f==null?void 0:f.find(D=>D.type===j.type),A=((I=j.manifest)==null?void 0:I.details)??"";return s.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${N?"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:N,onChange:()=>b(j.type),disabled:u,className:"shrink-0"}),s.jsx(Ya,{type:j.type,label:j.displayName??j.type,size:18,className:"shrink-0"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[13px] font-medium text-text-primary truncate",children:j.displayName}),A&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:A})]}),T&&s.jsx("span",{className:`text-[10px] font-semibold ${T.ok?"text-status-online":"text-status-error"}`,children:T.ok?t("standalone.onboarding.installed"):t("standalone.onboarding.installFailed",{error:T.error??"failed"})})]},j.type)})})]},y.category))})]})})}function WR(){try{return localStorage.getItem(ja)==="1"}catch{return!1}}Jj();I1();S0();TR();const OR=vp({baseUrl:"",getToken:Tc});function UR({children:e}){const{t}=ke("common"),[n,a]=l.useState(null),[r,o]=l.useState(!0),[i,c]=l.useState(""),[d,p]=l.useState(""),[u,m]=l.useState(!1),f=async()=>{o(!0),p("");try{const h=await(await Ts("/auth/session")).json();a(h)}catch(k){p(k instanceof Error?k.message:String(k))}finally{o(!1)}};l.useEffect(()=>{f()},[]),l.useEffect(()=>{if(!n||n.required&&!n.authenticated)return;let k=!1;return(async()=>{try{const h=await Ts("/api/v1/standalone/preferences");if(!h.ok)return;const x=await h.json();if(k)return;const S=Ms(x.standaloneFontPreferences);xn(S),Tl(S)}catch{}})(),()=>{k=!0}},[n==null?void 0:n.authenticated,n==null?void 0:n.required]);const g=async k=>{k.preventDefault(),m(!0),p("");try{const h=await Ts("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),x=await h.json();if(!h.ok)throw new Error((x==null?void 0:x.error)||"Login failed");a(x),c(""),cg()}catch(h){p(h instanceof Error?h.message:String(h))}finally{m(!1)}};return r?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:t("standalone.auth.loading")}):n?!n.required||n.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:t("standalone.auth.signInTitle")}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:n.hasPasswordAuth?t("standalone.auth.passwordProtected"):t("standalone.auth.tokenProtected")})]}),n.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:g,children:[s.jsx(xs,{type:"password",value:i,onChange:k=>c(k.target.value),placeholder:t("standalone.auth.passwordPlaceholder"),autoFocus:!0}),s.jsx(Us,{type:"submit",variant:"primary",disabled:u||!i,className:"justify-center",children:t(u?"standalone.auth.signingIn":"standalone.auth.unlock")})]}):s.jsx(Mt,{variant:"warning",children:t("standalone.auth.noPasswordEnabled")}),d&&s.jsx(Mt,{variant:"error",children:d})]})}):s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:t("standalone.auth.loadError",{error:d||"unknown error"})})}function op(){const{t:e}=ke("common"),{ides:t,initialLoaded:n}=Ss();if(!n)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:e("standalone.machine.loading")});const a=t.find(r=>r.daemonMode||r.type==="adhdev-daemon");return a?s.jsx(Fi,{to:`/machines/${a.id}`,replace:!0}):s.jsx(Fi,{to:"/dashboard",replace:!0})}function GR(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let n=!1;if(!WR())return fetch("/api/v1/providers/installed").then(a=>a.ok?a.json():{providers:[]}).then(a=>{n||(a.providers??[]).length===0&&t(!0)}).catch(()=>{}),()=>{n=!0}},[]),e?s.jsx(BR,{onDone:()=>t(!1)}):null}function qR(){const{t:e}=ke("common"),{ides:t}=Ss(),n=l.useMemo(()=>{for(const u of t)if(u.activeInteractivePrompt)return u.instanceId??u.id;return null},[t]),{promptSession:a,hasActivePrompt:r,responseError:o,isSubmitting:i,submit:c,cancel:d,reopen:p}=jh(n);return r?s.jsxs("div",{className:"relative",children:[!a&&s.jsx("button",{type:"button",onClick:p,className:"fixed bottom-4 right-4 z-[79] btn btn-primary btn-sm shadow-lg",children:e("standalone.machine.awaitingInput")}),s.jsx(zp,{promptSession:a,isSubmitting:i,error:o,onSubmit:c,onCancel:d})]}):null}function zR(){const e=l.useMemo(()=>({sendCommand:La,sendData:Al,sendPtyInput:dg}),[]);return s.jsx(_g,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(sb,{client:OR,children:s.jsx(UR,{children:s.jsx(SR,{children:s.jsx(ab,{value:e,children:s.jsxs(Db,{sendDaemonCommand:La,children:[s.jsx(qR,{}),s.jsxs(MR,{children:[s.jsx(GR,{}),s.jsxs(Hg,{children:[s.jsx(Bs,{path:"/dashboard",element:s.jsx(yI,{})}),s.jsx(Bs,{path:"/machine",element:s.jsx(op,{})}),s.jsx(Bs,{path:"/machines/:id",element:s.jsx(LL,{})}),s.jsx(Bs,{path:"/machines",element:s.jsx(op,{})}),s.jsx(Bs,{path:"/about",element:s.jsx(RR,{})}),s.jsx(Bs,{path:"/settings",element:s.jsx(_R,{})}),s.jsx(Bs,{path:"/mesh",element:s.jsx(cR,{children:s.jsx(iR,{})})}),s.jsx(Bs,{path:"/setup",element:s.jsx(PR,{})}),s.jsx(Bs,{path:"*",element:s.jsx(Fi,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}$C({connectionManager:As});$g(document.getElementById("root")).render(s.jsx(zR,{}));
|
|
121
|
+
Node removal cleanup policy: ${be}`))return;const we=e.__sourceDaemonId||n;try{const U=await o(we,"remove_mesh_node",{meshId:e.id,nodeId:ce}),Ne=i(U);if((Ne==null?void 0:Ne.success)===!1)throw new Error(Ne.error||"Remove failed");h===ce&&x(null),await m(),g||await f(t)}catch(U){k((U==null?void 0:U.message)||"Remove node failed")}}async function V(ce){if(!e)return;const Ae={...jl(e),...ce},be=e.__sourceDaemonId||n;try{K(!0),k(null);const we=await o(be,"update_mesh",{meshId:e.id,policy:Ae}),_e=i(we);if((_e==null?void 0:_e.success)===!1)throw new Error(_e.error||"Policy update failed");await m()}catch(we){k((we==null?void 0:we.message)||"Policy update failed")}finally{K(!1)}}const[q,ee]=l.useState(null);async function pe(ce,Ae){if(!t)return;const be=(e==null?void 0:e.__sourceDaemonId)||n;try{ee(ce.id),k(null);const we=await o(be,"update_mesh_node",{meshId:t,nodeId:ce.id,policy:{slots:Ae}}),_e=i(we);if((_e==null?void 0:_e.success)===!1){k(_e.error||"Node slots update failed");return}await m()}catch(we){k((we==null?void 0:we.message)||"Node slots update failed")}finally{ee(null)}}const[le,se]=l.useState(null);async function te(ce,Ae){if(!t)return;const be=(e==null?void 0:e.__sourceDaemonId)||n,we=Ae.map(_e=>_e.trim()).filter(Boolean);try{se(ce.id),k(null);const _e=await o(be,"update_mesh_node",{meshId:t,nodeId:ce.id,capabilities:we}),U=i(_e);if((U==null?void 0:U.success)===!1){k(U.error||"Node tag update failed");return}await m()}catch(_e){k((_e==null?void 0:_e.message)||"Node tag update failed")}finally{se(null)}}async function ue(){if(!n||!t)return;const Ae={...(e==null?void 0:e.coordinator)||{}};z.override.trim()?Ae.systemPromptOverride=z.override:delete Ae.systemPromptOverride,z.append.trim()?Ae.systemPromptAppend=z.append:delete Ae.systemPromptAppend,delete Ae.systemPromptSuffix;try{Ce(!0),k(null);const be=await o(n,"update_mesh",{meshId:t,coordinator:Ae}),we=i(be);if((we==null?void 0:we.success)===!1){k(we.error||"Coordinator prompt save failed");return}await m()}catch(be){k((be==null?void 0:be.message)||"Coordinator prompt save failed")}finally{Ce(!1)}}async function ye(ce){if(!n||!t)return;const Ae=(me[ce.id]||"").trim();try{X(ce.id),k(null);const be=await o(n,"update_mesh_node",{meshId:t,nodeId:ce.id,systemPrompt:Ae}),we=i(be);if((we==null?void 0:we.success)===!1){k(we.error||"Node instruction save failed");return}await m()}catch(be){k((be==null?void 0:be.message)||"Node instruction save failed")}finally{X(null)}}async function Me(ce){if(!(!e||!ce)){k(null),F(null);try{H(!0);const Ae=(e.nodes||[]).find(_e=>Zs(String(_e.daemon_id||_e.daemonId||""),ce)),be=await o(ce,"set_mesh_host",{meshId:e.id,hostDaemonId:ce,...Ae!=null&&Ae.id?{hostNodeId:Ae.id}:{}}),we=i(be);if((we==null?void 0:we.success)===!1){k(we.error||"Setting the mesh host failed");return}await m()}catch(Ae){k((Ae==null?void 0:Ae.message)||"Setting the mesh host failed")}finally{H(!1)}}}async function re(){if(e){k(null),F(null);try{W(!0);const ce=c?await c(a,e.id,e):null,Ae=d(a,e.id,e,e.nodes||[],ce);if("error"in Ae)throw new Error(Ae.error);const be=await p(Ae.targetDaemonId,{meshId:e.id,inlineMesh:Ae.inlineMesh,coordinatorNodeId:Ae.coordinatorNodeId,cliType:P.trim()||void 0});F(be.message)}catch(ce){k((ce==null?void 0:ce.message)||"Coordinator launch failed")}finally{W(!1)}}}return{selectedNodeId:h,setSelectedNodeId:x,showAddNode:S,setShowAddNode:b,nodeWorkspace:w,setNodeWorkspace:C,nodeProviderPriority:v,setNodeProviderPriority:y,nodeDaemonId:j,setNodeDaemonId:N,nodeCustomPath:T,setNodeCustomPath:A,nodePickerWorkspaces:ve,nodePickerProviders:he,nodeOnboardingPlan:I,nodePlanLoading:M,coordinatorCliType:P,setCoordinatorCliType:B,launchingCoordinator:R,launchResult:L,settingMeshHost:_,savingPolicy:$,coordinatorPromptDraft:z,setCoordinatorPromptDraft:ne,savingCoordinatorPrompt:ie,nodeSystemPromptDrafts:me,setNodeSystemPromptDrafts:O,savingNodeSystemPromptId:Y,savingNodeSlotsId:q,savingNodeCapabilitiesId:le,handleAddNode:Z,handleRemoveNode:fe,handleUpdatePolicy:V,handleUpdateNodeSlots:pe,handleUpdateNodeCapabilities:te,handleSaveCoordinatorPrompt:ue,handleSaveNodeSystemPrompt:ye,handleLaunchCoordinator:re,handleSetMeshHost:Me}}function K2(e){const t=e.filter(a=>a.status==="pending"||a.status==="assigned"),n=e.filter(a=>a.status==="completed"||a.status==="failed"||a.status==="cancelled");return{active:t.length,historical:n.length,activeCounts:{pending:t.filter(a=>a.status==="pending").length,assigned:t.filter(a=>a.status==="assigned").length},historicalCounts:{completed:n.filter(a=>a.status==="completed").length,failed:n.filter(a=>a.status==="failed").length},counts:{pending:e.filter(a=>a.status==="pending").length,assigned:e.filter(a=>a.status==="assigned").length,completed:e.filter(a=>a.status==="completed").length,failed:e.filter(a=>a.status==="failed").length},staleAssignedCount:e.filter(a=>a.staleAssigned).length,recent:e.slice(0,20)}}function V2({primaryDaemonId:e,activeDaemonId:t,sendCommand:n,unwrapResult:a,loadLiveMesh:r,resolveCommandTarget:o}){const[i,c]=l.useState([]),[d,p]=l.useState(null),[u,m]=l.useState(!1),[f,g]=l.useState(null),k=l.useCallback(async x=>{if(!e||!x){c([]);return}try{const S=await n(e,"get_mesh_queue",{meshId:x});c(S!=null&&S.success?Array.isArray(S.queue)?S.queue:[]:[])}catch{c([])}},[e,n]);async function h(x){var S,b;if(x){m(!0),g(null);try{const w=r?await r(t,x.id,x):null,C=o(t,x.id,x,x.nodes||[],w);if("error"in C)throw new Error(C.error);const v=await n(C.targetDaemonId,"get_mesh_queue",{meshId:x.id}),y=a(v);if((y==null?void 0:y.success)===!1)throw new Error(y.error||"Queue load failed");const j=Array.isArray(((S=y==null?void 0:y.result)==null?void 0:S.rows)??(y==null?void 0:y.rows)??(y==null?void 0:y.queue))?((b=y==null?void 0:y.result)==null?void 0:b.rows)??(y==null?void 0:y.rows)??(y==null?void 0:y.queue):[];p(K2(j))}catch(w){g((w==null?void 0:w.message)||"Queue load failed")}finally{m(!1)}}}return{meshQueue:i,setMeshQueue:c,queueSummary:d,queueLoading:u,queueError:f,loadQueue:k,handleLoadQueue:h}}function Y2(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}const ig=new Map;function lg(e){return e?ig.get(e)??null:null}function Q2(e,t){!e||!t||ig.set(e,t)}function J2({selectedMeshId:e,loadMeshStatus:t,extractStatus:n,normalizeNode:a,gateIncompleteGraph:r}){const[o,i]=l.useState(()=>lg(e)),[c,d]=l.useState(!1),[p,u]=l.useState(null),[m,f]=l.useState("idle"),[g,k]=l.useState(!1),h=l.useRef(!1);async function x(S,b=e,w=!1){if(!(!S||!b))try{d(!w&&o===null),f(w?"settling":"first_paint"),u(null);const C=await t(S,b,{refresh:w,retryProfile:w?"settled":"interactive"});k(Y2(C));const v=n(C),y=a&&v?{...v,nodes:(v.nodes??[]).map(j=>a(j,v.meshId??b,""))}:v;if(y){if(r&&!w&&o!==null&&!fM(Cf(y))){f("settling"),h.current||(h.current=!0,Promise.resolve().then(()=>x(S,b,!0)).finally(()=>{h.current=!1}));return}i(y),Q2(b,y),f("settled")}else i(null),u("mesh_status returned an unexpected payload."),f("idle")}catch(C){o||i(null),u((C==null?void 0:C.message)||"Failed to load mesh graph"),f("idle")}finally{d(!1)}}return{meshGraphStatus:o,setMeshGraphStatus:i,graphLoading:c,graphError:p,setGraphError:u,graphProvenance:m,graphBootstrapFallback:g,loadGraph:x}}function np(e){return!e||e.hostSynthesized?{hostDaemonId:"",hostNodeId:""}:{hostDaemonId:String(e.hostDaemonId||""),hostNodeId:String(e.hostNodeId||"")}}function X2(e,t,n,a,r){if(!e.length)return"";const o=String(r||"");if(o){const d=e.find(p=>Zs(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=>Zs(p.id,c));if(d)return d.id}return""}function Z2(e){var r;if(!e)return"null";const t=[...e.nodes??[]].map(o=>{var i,c,d,p,u,m;return[o.nodeId,o.health,((i=o.git)==null?void 0:i.branch)??"",((c=o.git)==null?void 0:c.headCommit)??"",(d=o.git)!=null&&d.dirty?"1":"0",((p=o.git)==null?void 0:p.ahead)??0,((u=o.git)==null?void 0:u.behind)??0,(m=o.git)!=null&&m.hasConflicts?"1":"0",[...o.activeSessions??[]].sort().join(",")].join("|")}).sort().join(";"),n=(r=e.queue)==null?void 0:r.summary,a=n?[n.pending,n.assigned,n.completed,n.failed,n.cancelled].join(","):"";return`${t}::${a}`}const eR=4,tR=3e4;function sR(){return{lastFingerprint:null,stableTicks:0,backedOff:!1}}function Nl(e){e.stableTicks=0,e.backedOff=!1}function nR(e,t){const n=Z2(t);return e.lastFingerprint===null?(e.lastFingerprint=n,e.backedOff):n!==e.lastFingerprint?(e.lastFingerprint=n,Nl(e),!1):(e.stableTicks+=1,e.stableTicks>=eR&&(e.backedOff=!0),e.backedOff)}function aR(e,t){return e.backedOff?Math.max(t,tR):t}const rR=7e3,oR=45e3;function iR(){const e=EL(),{sendCommand:t,sendData:n,daemons:a,userName:r,loadMeshStatus:o,launchCoordinator:i,loadLiveMesh:c,extractStatus:d,unwrapResult:p,normalizeMesh:u,normalizeNode:m,resolveCommandTarget:f,features:g,gateIncompleteGraph:k}=e,h=ca(),x=a[0],S=(x==null?void 0:x.id)||"",b=l.useMemo(()=>((x==null?void 0:x.availableProviders)||[]).filter(lt=>lt.category==="cli").map(lt=>({id:lt.type||lt.id,name:lt.displayName||lt.name||lt.type,meshCoordinator:lt.meshCoordinator})),[x]),w=l.useMemo(()=>ln((x==null?void 0:x.availableProviders)||[]),[x]),{meshes:C,selectedMeshId:v,setSelectedMeshId:y,loading:j,error:N,setError:T,showCreate:A,setShowCreate:I,createName:D,setCreateName:M,createRepoIdentity:E,setCreateRepoIdentity:P,createRepoRemoteUrl:B,setCreateRepoRemoteUrl:R,newMeshDaemonId:W,setNewMeshDaemonId:_,newMeshWorkspace:H,setNewMeshWorkspace:L,createPickerWorkspaces:F,createOnboardingPlan:$,createPlanLoading:K,creating:z,createWarning:ne,setCreateWarning:ie,loadMeshes:Ce,handleCreate:me,handleDelete:O,cancelCreate:Y}=og({daemons:a,primaryDaemonId:S,sendCommand:t,unwrapResult:p,normalizeMesh:u,features:g,loadDaemonMetadata:h}),X=C.find(Oe=>Oe.id===v)||null,{meshGraphStatus:Q,setMeshGraphStatus:ve,graphLoading:he,graphError:Z,setGraphError:fe,loadGraph:V}=J2({selectedMeshId:v,loadMeshStatus:o,extractStatus:d,normalizeNode:m,gateIncompleteGraph:k}),[q,ee]=l.useState(""),[pe,le]=l.useState(""),se=g.meshHostDaemonSection?q:S,{meshQueue:te,loadQueue:ue}=V2({primaryDaemonId:S,activeDaemonId:se,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:f}),{selectedNodeId:ye,setSelectedNodeId:Me,showAddNode:re,setShowAddNode:ce,nodeWorkspace:Ae,setNodeWorkspace:be,nodeProviderPriority:we,setNodeProviderPriority:_e,nodeDaemonId:U,setNodeDaemonId:Ne,nodeCustomPath:Ie,setNodeCustomPath:We,nodePickerWorkspaces:Xe,nodePickerProviders:et,nodeOnboardingPlan:J,nodePlanLoading:Le,coordinatorCliType:$e,savingPolicy:at,coordinatorPromptDraft:rt,setCoordinatorPromptDraft:G,savingCoordinatorPrompt:oe,nodeSystemPromptDrafts:de,setNodeSystemPromptDrafts:xe,savingNodeSystemPromptId:Se,savingNodeSlotsId:Pe,savingNodeCapabilitiesId:He,handleAddNode:Ee,handleRemoveNode:Je,handleUpdatePolicy:st,handleUpdateNodeSlots:Ze,handleUpdateNodeCapabilities:Ue,handleSaveCoordinatorPrompt:Qe,handleSaveNodeSystemPrompt:nt,settingMeshHost:Be,handleSetMeshHost:ge}=z2({selectedMesh:X,selectedMeshId:v,primaryDaemonId:S,activeDaemonId:se,daemons:a,availableCliProviders:w,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:f,launchCoordinator:i,features:{addNodeDaemonPicker:g.addNodeDaemonPicker},loadMeshes:Ce,loadQueue:ue,queueSection:g.queueSection,setError:T}),je=l.useMemo(()=>a.find(Oe=>Oe.id===se)||x,[a,se,x]),Te=l.useMemo(()=>new Set(((X==null?void 0:X.nodes)||[]).map(Oe=>String(Oe.daemon_id||Oe.daemonId||""))),[X]),Fe=l.useMemo(()=>a.filter(Oe=>Oe.id&&!Te.has(Oe.id)&&!Xp(Oe)),[a,Te]),Ge=(X==null?void 0:X.nodes)||[],dt=l.useMemo(()=>Ge.find(Oe=>Zs(String(Oe.daemon_id||Oe.daemonId||""),q)),[Ge,q]),Ve=g.meshHostDaemonSection?!!dt:!0,ut=l.useMemo(()=>{if(!g.meshHostDaemonSection||!X)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const Oe=X.meshHost,lt=Q!=null&&Q.meshId&&String(Q.meshId)===String(X.id??"")?Q.meshHost:void 0,es=lt!=null&<.hostDaemonId?lt:Oe??lt,ns=np(es),js=ns.hostDaemonId,Ys=Ge.find(Fs=>Fs.role==="host"),cn=ns.hostNodeId||String((Ys==null?void 0:Ys.id)||""),ae=cn?Ge.find(Fs=>String(Fs.id)===cn):void 0,Ke=String((ae==null?void 0:ae.daemon_id)||(ae==null?void 0:ae.daemonId)||""),qe=js||Ke;if(!qe)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const Nt=a.find(Fs=>js&&Zs(Fs.id,js))||(Ke?a.find(Fs=>Zs(Fs.id,Ke)):void 0);if(Nt)return{pinned:!0,daemonId:Nt.id,label:lR(Nt),online:!0,hostNode:ae};const dn=String((ae==null?void 0:ae.machineLabel)||"")||String((ae==null?void 0:ae.workspace)||"")||qe;return{pinned:!0,daemonId:qe,label:dn,online:!1,hostNode:ae}},[X,Ge,a,Q,g.meshHostDaemonSection]),zt=ut.daemonId,Et=ut.online,ps=ut.pinned?ut.hostNode:dt,Zt=l.useMemo(()=>!g.meshHostDaemonSection||!ut.pinned?"":!Et&&pe&&a.some(Oe=>Oe.id===pe)?pe:zt,[g.meshHostDaemonSection,ut.pinned,Et,pe,a,zt]),_s=l.useMemo(()=>Q?[...new Set((Q.nodes??[]).map(Oe=>String(Oe.daemonId||Oe.daemon_id||"")).filter(Boolean))]:[],[Q]),Re=zf({status:Q,daemonId:se||null,extraDaemonIds:_s,meshId:v,sendData:n});l.useEffect(()=>{const Oe=(X==null?void 0:X.coordinator)||{};G({override:typeof Oe.systemPromptOverride=="string"?Oe.systemPromptOverride:"",append:typeof Oe.systemPromptAppend=="string"?Oe.systemPromptAppend:typeof Oe.systemPromptSuffix=="string"?Oe.systemPromptSuffix:""}),xe(Object.fromEntries(((X==null?void 0:X.nodes)||[]).map(lt=>[lt.id,typeof lt.systemPrompt=="string"?lt.systemPrompt:""])))},[X]),l.useEffect(()=>{const Oe=g.addNodeDaemonPicker?Pn(et):Pn(w);re&&we.length===0&&Oe.length>0&&_e(Oe)},[re,w,et,we.length,g.addNodeDaemonPicker]),l.useEffect(()=>{const Oe=new Set(((X==null?void 0:X.nodes)||[]).map(lt=>lt.id));ye&&!Oe.has(ye)&&Me(null)},[X,ye]);const tt=l.useMemo(()=>{if(!(!(Q!=null&&Q.meshId)||String(Q.meshId)!==String((X==null?void 0:X.id)??"")))return np(Q.meshHost).hostDaemonId||void 0},[Q,X]),It=l.useMemo(()=>X2(a,Ge,se,S,tt),[a,Ge,se,S,tt]);l.useEffect(()=>{if(!g.meshHostDaemonSection)return;if(!a.length&&!ut.pinned){ee("");return}const Oe=ut.pinned?Zt:It;Oe&&!Zs(Oe,q)&&ee(Oe)},[a,q,ut.pinned,Zt,It,g.meshHostDaemonSection]),l.useEffect(()=>{pe&&(Et||!a.some(Oe=>Oe.id===pe))&&le("")},[Et,pe,a]),l.useEffect(()=>{if(g.createDaemonPicker){if(!a.length){_("");return}(!W||!a.some(Oe=>Oe.id===W))&&_(a[0].id)}},[a,W,g.createDaemonPicker]),l.useEffect(()=>{var Oe;if(!g.createDaemonPicker||!W){L("");return}if(!F.length){L("");return}F.some(lt=>lt.path===H)||L(((Oe=F[0])==null?void 0:Oe.path)||"")},[W,H,F,g.createDaemonPicker]);const pt=l.useRef(null),Yt=l.useRef(sR()),_t=g.meshStatePushRefresh?oR:rR,[Qt,Cs]=l.useState(_t);l.useEffect(()=>{if(!v)return;const Oe=pt.current!==v;if(pt.current=v,Oe){Nl(Yt.current),Cs(_t);const lt=lg(v);ve(lt),fe(null),V(se,v,lt!==null)}else fe(null),V(se,v,!0)},[v,se]);const Hs=l.useRef(V);Hs.current=V;const ms=l.useRef(!1),ss=l.useRef(()=>{});ss.current=()=>{ms.current||!v||!se||(ms.current=!0,Promise.resolve(Hs.current(se,v,!0)).finally(()=>{ms.current=!1}))},l.useEffect(()=>{nR(Yt.current,Q),Cs(aR(Yt.current,_t))},[Q,_t]),RL({daemonIds:l.useMemo(()=>[se,..._s].filter(Boolean),[se,_s]),meshId:v,sendData:n,onRevisionAdvance:()=>{typeof document<"u"&&document.visibilityState!=="visible"||ss.current()}}),l.useEffect(()=>{if(!v||!se||typeof document>"u")return;let Oe=null;const lt=()=>{document.visibilityState==="visible"&&ss.current()},es=()=>{Oe===null&&(Oe=setInterval(lt,Qt))},ns=()=>{Oe!==null&&(clearInterval(Oe),Oe=null)},js=()=>{document.visibilityState==="visible"?es():ns()};return document.visibilityState==="visible"&&es(),document.addEventListener("visibilitychange",js),()=>{ns(),document.removeEventListener("visibilitychange",js)}},[v,se,Qt]),l.useEffect(()=>{g.queueSection||ue(v)},[v,g.queueSection]);const Vs=l.useMemo(()=>a.map(Oe=>Oe.id).filter(Boolean).sort().join(","),[a]),$s=l.useRef(!1);return l.useEffect(()=>{Ce($s.current),$s.current=!0},[Vs]),S?X?s.jsx(q2,{selectedMesh:X,error:N,onDismissError:()=>T(null),onBack:()=>{y(null),ve(null)},onDelete:O,displayedMeshStatus:Re,graphLoading:he,graphError:Z,onRefreshGraph:()=>{Nl(Yt.current),V(se,v,!0)},savingPolicy:at,onUpdatePolicy:st,coordinatorPromptDraft:rt,onCoordinatorPromptDraftChange:G,savingCoordinatorPrompt:oe,onSaveCoordinatorPrompt:Qe,daemons:a,coordinatorDaemonId:q,onCoordinatorDaemonIdChange:ee,coordinatorCliType:$e,isHostNodeAttached:Ve,selectedHostNode:ps,hostPinned:ut.pinned,hostLabel:ut.label,hostOnline:Et,hostRebindDaemonId:pe,onHostRebindDaemonIdChange:Oe=>le(Oe),settingMeshHost:Be,onSetMeshHost:ge,activeDaemon:je,activeDaemonId:se,meshQueue:te,userName:r,availableCliProviders:w,savingNodeSlotsId:Pe,onUpdateNodeSlots:Ze,savingNodeCapabilitiesId:He,onUpdateNodeCapabilities:Ue,nodeSystemPromptDrafts:de,onNodeSystemPromptDraftChange:(Oe,lt)=>xe(es=>({...es,[Oe]:lt})),savingNodeSystemPromptId:Se,onSaveNodeSystemPrompt:nt,selectedNodeId:ye,onSelectNode:Me,showAddNode:re,onShowAddNode:()=>ce(!0),onCancelAddNode:()=>ce(!1),nodeWorkspace:Ae,onNodeWorkspaceChange:be,nodeProviderPriority:we,onNodeProviderPriorityChange:_e,nodeDaemonId:U,onNodeDaemonIdChange:Ne,nodeCustomPath:Ie,onNodeCustomPathChange:We,nodePickerWorkspaces:Xe,nodePickerProviders:et,nodeOnboardingPlan:J,nodePlanLoading:Le,attachableDaemons:Fe,onAddNode:Ee,onRemoveNode:Je,availableCliAgents:b,features:{coordinatorPrompt:g.coordinatorPrompt,meshHostDaemonSection:g.meshHostDaemonSection,hermesMcpConfig:g.hermesMcpConfig,addNodeDaemonPicker:g.addNodeDaemonPicker,nodeInstruction:g.nodeInstruction},sendCommand:t}):s.jsx(UL,{meshes:C,loading:j,error:N,onDismissError:()=>T(null),daemons:a,features:{createDaemonPicker:g.createDaemonPicker,maxMeshes:g.maxMeshes},showCreate:A,onToggleCreate:()=>I(!A),createName:D,onCreateNameChange:M,createRepoIdentity:E,onCreateRepoIdentityChange:P,createRepoRemoteUrl:B,onCreateRepoRemoteUrlChange:R,newMeshDaemonId:W,onNewMeshDaemonIdChange:_,newMeshWorkspace:H,onNewMeshWorkspaceChange:L,createPickerWorkspaces:F,createOnboardingPlan:$,createPlanLoading:K,creating:z,createWarning:ne,onDismissCreateWarning:()=>ie(null),onSelectMesh:y,onCreate:me,onCancelCreate:Y}):s.jsx(Qa,{icon:s.jsx(cs,{}),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 lR(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function cR({children:e}){const{sendCommand:t,sendData:n}=St(),{ides:a}=Ss(),r=l.useMemo(()=>a.filter(i=>i.daemonMode||i.type==="adhdev-daemon").map(i=>i),[a]),o=l.useMemo(()=>({sendCommand:t,sendData:n,daemons:r,userName:void 0,loadMeshStatus:async(i,c)=>t(i,"mesh_status",{meshId:c}),launchCoordinator:async(i,c)=>{var f;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)||((f=u==null?void 0:u.session)==null?void 0:f.id)||(u==null?void 0:u.targetSessionId);return{sessionId:m,message:m?`Coordinator launched (${m})`:"Coordinator launch command sent"}},loadLiveMesh:void 0,extractStatus:Vl,unwrapResult:i=>i,normalizeMesh:(i,c)=>i,normalizeNode:(i,c,d)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:Zf}),[t,n,r]);return s.jsx(eg.Provider,{value:o,children:e})}function dR(e){const{daemons:t,features:n,meshes:a,meshesLoading:r,selectedMeshId:o,onSelectMesh:i,createMode:c,onCreateModeChange:d,createName:p,onCreateNameChange:u,createDaemonId:m,onCreateDaemonIdChange:f,createWorkspace:g,onCreateWorkspaceChange:k,createPickerWorkspaces:h,createPlan:x,createPlanLoading:S,creating:b,createWarning:w,onCreate:C,createRepoRemoteUrl:v,onCreateRepoRemoteUrlChange:y,createRepoIdentity:j,onCreateRepoIdentityChange:N,createManualOpen:T,onCreateManualOpenChange:A,nodes:I,attachableDaemons:D,attachDaemonId:M,onAttachDaemonIdChange:E,attachWorkspace:P,onAttachWorkspaceChange:B,attachPickerWorkspaces:R,attachPlan:W,attachPlanLoading:_,attaching:H,onAttach:L,renderInstallOnboarding:F,nodeLabel:$,daemonLabel:K}=e,{t:z}=ke("common");if(t.length===0)return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:z("setupWizard.machines.title")}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-text-muted",children:z("setupWizard.machines.noMachinesDescription")})]}),F?F():s.jsx("p",{className:"text-[11px] text-text-muted",children:z("setupWizard.machines.noMachinesFallback")})]});const ne=H||_||(W==null?void 0:W.success)===!1||!P.trim()||n.addNodeDaemonPicker&&!M;return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:z("setupWizard.machines.title")}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-text-muted",children:z("setupWizard.machines.description")})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[a.map(ie=>{const Ce=!c&&o===ie.id;return s.jsx("button",{type:"button",onClick:()=>{d(!1),i(ie.id)},className:`flex items-center gap-2 rounded-lg border px-3 py-2 text-left transition-colors ${Ce?"border-accent-primary/60 bg-accent-primary/10":"border-border-subtle bg-bg-secondary/60 hover:border-border-default"}`,children:s.jsxs("span",{className:"min-w-0",children:[s.jsx("span",{className:"block truncate text-sm text-text-primary",children:ie.name}),s.jsxs("span",{className:"block truncate text-[11px] text-text-muted",children:[ie.repoIdentity||ie.repoRemoteUrl||""," · ",z("setupWizard.machines.nodeCount",{count:(ie.nodes||[]).length})]})]})},ie.id)}),s.jsx("button",{type:"button",onClick:()=>d(!0),className:`flex items-center gap-2 rounded-lg border px-3 py-2 text-left transition-colors ${c?"border-accent-primary/60 bg-accent-primary/10":"border-dashed border-border-subtle bg-bg-secondary/40 hover:border-border-default"}`,children:s.jsxs("span",{className:"text-sm text-text-primary",children:["+ ",z("setupWizard.machines.createNew")]})}),r&&a.length===0&&s.jsx("p",{className:"text-[11px] text-text-muted",children:z("setupWizard.machines.loadingMeshes")})]}),c&&s.jsx(ng,{variant:"wizard",showDaemonPicker:n.createDaemonPicker,daemons:t,daemonLabel:K,name:p,onNameChange:u,daemonId:m,onDaemonIdChange:f,workspace:g,onWorkspaceChange:k,workspaces:h,plan:x,planLoading:S,repoRemoteUrl:v,onRepoRemoteUrlChange:y,repoIdentity:j,onRepoIdentityChange:N,manualOpen:T,onManualOpenChange:A,creating:b,warning:w,onCreate:C}),!c&&o&&s.jsxs("div",{className:"flex flex-col gap-2.5 rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2.5",children:[I.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5",children:I.map(ie=>s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] text-text-secondary",children:$(ie)},ie.id))}),s.jsx("span",{className:"text-[11px] font-medium text-text-secondary",children:z("setupWizard.machines.attachTitle")}),n.addNodeDaemonPicker&&(D.length>0?s.jsx("div",{className:"flex flex-wrap gap-1.5",children:D.map(ie=>{const Ce=M===ie.id;return s.jsx("button",{type:"button",onClick:()=>E(ie.id),className:`rounded-full border px-2.5 py-1 text-[11px] transition-colors ${Ce?"border-accent-primary/60 bg-accent-primary/10 text-text-primary":"border-border-subtle bg-bg-secondary text-text-secondary hover:border-border-default"}`,children:K(ie)},ie.id)})}):s.jsx("p",{className:"text-[11px] text-text-muted",children:z("setupWizard.machines.allMachinesAttached")})),(!n.addNodeDaemonPicker||M)&&s.jsxs(s.Fragment,{children:[s.jsx(yl,{workspaces:R,value:P,onChange:B}),s.jsx(sg,{plan:W,loading:_}),s.jsx("div",{className:"flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:L,disabled:ne,children:z(H?"setupWizard.machines.attaching":"setupWizard.machines.addMachine")})})]})]})]})}function uR(e){var t;return e.machineNickname||e.nickname||e.hostname||((t=e.user)==null?void 0:t.name)||e.id}function pR(e){const t=e;return t.machine_label||t.machineLabel||t.hostname||String(e.workspace||"").split(/[\\/]/).filter(Boolean).pop()||e.id}function mR({daemons:e,features:t,sendCommand:n,unwrapResult:a,normalizeMesh:r,loadDaemonMetadata:o,initialMeshId:i,onClose:c,renderInstallOnboarding:d}){var Ae,be;const{t:p}=ke("common"),u=((Ae=e[0])==null?void 0:Ae.id)||"",{meshes:m,loading:f,error:g,setError:k,loadMeshes:h,selectedMeshId:x,setSelectedMeshId:S}=og({daemons:e,primaryDaemonId:u,sendCommand:n,unwrapResult:a,normalizeMesh:r,features:{createDaemonPicker:t.createDaemonPicker,addNodeDaemonPicker:t.addNodeDaemonPicker},loadDaemonMetadata:o});l.useEffect(()=>{h()},[h]);const b=l.useRef(m);b.current=m;const w=l.useMemo(()=>m.map(we=>we.id).sort().join(","),[m]),C=l.useRef(n);C.current=n;const v=l.useRef(a);v.current=a,l.useEffect(()=>{x||m.length===0||(i&&m.some(we=>we.id===i)?S(i):m.length===1&&S(m[0].id))},[m,x,i,S]);const y=l.useMemo(()=>m.find(we=>we.id===x)??null,[m,x]),j=l.useMemo(()=>(y==null?void 0:y.nodes)||[],[y]),N=l.useCallback(we=>(we==null?void 0:we.__sourceDaemonId)||u,[u]),[T,A]=l.useState(!1),[I,D]=l.useState(""),[M,E]=l.useState(""),[P,B]=l.useState(""),[R,W]=l.useState(null),[_,H]=l.useState(!1),[L,F]=l.useState(!1),[$,K]=l.useState(null),[z,ne]=l.useState(""),[ie,Ce]=l.useState(""),[me,O]=l.useState(!1),Y=t.createDaemonPicker&&M||u,X=l.useMemo(()=>e.find(we=>we.id===Y),[e,Y]),Q=(X==null?void 0:X.workspaces)||[];l.useEffect(()=>{if(!T||!Y||!P.trim()){W(null),H(!1);return}let we=!1;const _e=setTimeout(()=>{we||(H(!0),C.current(Y,"plan_mesh_onboarding",{workspace:P.trim(),operation:"auto",meshInventory:b.current}).then(U=>{if(we)return;const Ne=v.current(U);W(Ne),Ne!=null&&Ne.success&&(D(Ie=>{var We,Xe;return Ie||`${String(((We=Ne.discovery)==null?void 0:We.repoIdentity)||((Xe=Ne.discovery)==null?void 0:Xe.repoRoot)||"").split(/[\\/]/).filter(Boolean).pop()||"repo"}-mesh`}),Ce(Ie=>{var We;return Ie||((We=Ne.discovery)==null?void 0:We.repoIdentity)||""}),ne(Ie=>{var We,Xe,et,J,Le,$e;return Ie||((et=(Xe=(We=Ne.discovery)==null?void 0:We.origin)==null?void 0:Xe.urls)==null?void 0:et[0])||(($e=(Le=(J=Ne.discovery)==null?void 0:J.upstream)==null?void 0:Le.urls)==null?void 0:$e[0])||""}))}).catch(U=>{we||W({success:!1,error:(U==null?void 0:U.message)||"Git discovery failed"})}).finally(()=>{we||H(!1)}))},300);return()=>{we=!0,clearTimeout(_e)}},[T,Y,P,w]);const ve=l.useCallback(async()=>{const we=Y,_e=P.trim(),U=z.trim(),Ne=ie.trim();if(!(!we||!I.trim()||L)&&!(!_e&&!U&&!Ne)){F(!0),K(null),k(null);try{const Ie=await rg({targetDaemonId:we,name:I,repoRemoteUrl:U,repoIdentity:Ne,workspace:_e,attachWorkspace:!!_e,machineId:X==null?void 0:X.machineId,providerPriority:Pn(ln((X==null?void 0:X.availableProviders)||[])),meshInventory:m,sendCommand:n,unwrapResult:a});if(Ie.warning&&K(Ie.warning),!Ie.meshCreated){k(Ie.error||p("setupWizard.machines.createFailed"));return}await h(!0),Ie.meshId&&S(Ie.meshId),A(!1)}finally{F(!1)}}},[Y,I,P,z,ie,L,X,m,n,a,h,S,k,p]),[he,Z]=l.useState(""),[fe,V]=l.useState(""),[q,ee]=l.useState(null),[pe,le]=l.useState(!1),[se,te]=l.useState(!1),ue=l.useMemo(()=>{if(!t.addNodeDaemonPicker)return[];const we=new Set(j.map(_e=>String(_e.daemon_id||_e.daemonId||"")));return e.filter(_e=>_e.id&&!we.has(_e.id)&&!Xp(_e))},[t.addNodeDaemonPicker,j,e]),ye=l.useMemo(()=>e.find(we=>we.id===he),[e,he]),Me=t.addNodeDaemonPicker?(ye==null?void 0:ye.workspaces)||[]:((be=e.find(we=>we.id===u))==null?void 0:be.workspaces)||[];l.useEffect(()=>{if(T||!x||!fe.trim()){ee(null);return}const we=t.addNodeDaemonPicker?he:N(y);if(!we)return;let _e=!1;return le(!0),n(we,"plan_mesh_onboarding",{workspace:fe.trim(),meshId:x,inlineMesh:y,operation:"add_existing"}).then(U=>{_e||ee(a(U))}).catch(U=>{_e||ee({success:!1,error:(U==null?void 0:U.message)||"Git discovery failed"})}).finally(()=>{_e||le(!1)}),()=>{_e=!0}},[T,x,y,fe,he,t.addNodeDaemonPicker,N,n,a]);const re=l.useCallback(async()=>{var U,Ne,Ie,We;const we=N(y);if(!x||!we||se)return;const _e=fe.trim();if(_e){te(!0),k(null);try{const Xe=t.addNodeDaemonPicker?he:we,et=await n(Xe,"plan_mesh_onboarding",{workspace:_e,meshId:x,inlineMesh:y,operation:"add_existing"}),J=a(et);if(ee(J),(J==null?void 0:J.success)===!1)throw new Error(`${J.code||"onboarding_blocked"}: ${J.error}${J.action?` ${J.action}`:""}`);const Le={meshId:x,workspace:((U=J==null?void 0:J.discovery)==null?void 0:U.repoRoot)||_e,repoRoot:(Ne=J==null?void 0:J.discovery)==null?void 0:Ne.repoRoot,isLocalWorktree:((Ie=J==null?void 0:J.discovery)==null?void 0:Ie.isLinkedWorktree)===!0};t.addNodeDaemonPicker&&he&&(Le.daemonId=he,Le.machineId=ye==null?void 0:ye.machineId),Le.providerPriority=Pn(ln(((We=t.addNodeDaemonPicker?ye:e[0])==null?void 0:We.availableProviders)||[]));const $e=await n(we,"add_mesh_node",Le),at=a($e);if((at==null?void 0:at.success)===!1)throw new Error(at.error||"Add node failed");V(""),ee(null),await h(!0)}catch(Xe){k((Xe==null?void 0:Xe.message)||"Add node failed")}finally{te(!1)}}},[y,x,fe,he,ye,se,t.addNodeDaemonPicker,N,e,n,a,h,k]),ce=!T&&!!y&&j.length>0;return s.jsxs("div",{className:"mx-auto flex w-full max-w-2xl flex-col gap-4 p-4",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-base font-semibold text-text-primary",children:p("setupWizard.title")}),s.jsx("p",{className:"mt-1.5 text-[11px] text-text-muted",children:p("setupWizard.machines.description")})]}),g&&s.jsx("p",{className:"text-[11px] text-red-400",children:g}),s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary p-4",children:s.jsx(dR,{daemons:e,features:t,meshes:m,meshesLoading:f,selectedMeshId:x,onSelectMesh:we=>{S(we),V(""),Z("")},createMode:T,onCreateModeChange:A,createName:I,onCreateNameChange:D,createDaemonId:M,onCreateDaemonIdChange:E,createWorkspace:P,onCreateWorkspaceChange:B,createPickerWorkspaces:Q,createPlan:R,createPlanLoading:_,creating:L,createWarning:$,onCreate:ve,createRepoRemoteUrl:z,onCreateRepoRemoteUrlChange:ne,createRepoIdentity:ie,onCreateRepoIdentityChange:Ce,createManualOpen:me,onCreateManualOpenChange:O,nodes:j,attachableDaemons:ue,attachDaemonId:he,onAttachDaemonIdChange:we=>{Z(we),V("")},attachWorkspace:fe,onAttachWorkspaceChange:V,attachPickerWorkspaces:Me,attachPlan:q,attachPlanLoading:pe,attaching:se,onAttach:re,renderInstallOnboarding:d,nodeLabel:pR,daemonLabel:uR})}),s.jsx("div",{className:"flex items-center gap-2",children:s.jsx("div",{className:"ml-auto flex items-center gap-2",children:s.jsx("button",{type:"button",className:ce?"btn btn-primary btn-sm":"btn btn-secondary btn-sm",onClick:c,children:p(ce?"setupWizard.continueToMesh":"setupWizard.close")})})})]})}function Tc(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function hR(e){if(typeof window>"u")return e;const t=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),n=Tc();return n&&!t.searchParams.has("token")&&t.searchParams.set("token",n),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function Ts(e,t){return await fetch(hR(e),{credentials:"same-origin",...t})}function cg(){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 fR{constructor(){it(this,"adapters",new Map);it(this,"states",new Map);it(this,"runtimeListeners",new Map);it(this,"screenshotCallbacks",new Map);it(this,"statusCallbacks",new Set);it(this,"stateChangeCallbacks",new Set);it(this,"ptyInputSender",null)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const n of this.adapters.keys())if(n.startsWith("standalone"))return n}return null}register(t,n){this.adapters.set(t,n),this.states.set(t,n.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,n){this.states.set(t,n);const a=this.resolveDaemonId(t)||t;this.stateChangeCallbacks.forEach(r=>r(a,n))}onStateChange(t){return this.stateChangeCallbacks.add(t),()=>{this.stateChangeCallbacks.delete(t)}}retryConnection(t){}get(t){const n=this.resolveDaemonId(t);return n?this.adapters.get(n):void 0}getState(t){const n=this.resolveDaemonId(t);return n&&this.states.get(n)||"disconnected"}registerPtyInputSender(t){this.ptyInputSender=t}sendData(t,n){return!1}sendPtyInput(t,n,a){return this.ptyInputSender?this.ptyInputSender(t,n,a):!1}onScreenshot(t,n){return this.screenshotCallbacks.set(t,n),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,n){this.screenshotCallbacks.forEach(a=>a(t,n))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,n){this.statusCallbacks.forEach(a=>a(t,n))}emitRuntimeSnapshot(t,n,a=0,r=!1,o,i){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:a,text:n,truncated:r,cols:o,rows:i})}emitSessionOutput(t,n,a){!t||typeof n!="string"||!n||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof a=="number"?{seq:a}:{},data:n})}onRuntimeEvent(t,n){const a=this.runtimeListeners.get(t)||new Set;return a.add(n),this.runtimeListeners.set(t,a),()=>{const r=this.runtimeListeners.get(t);r&&(r.delete(n),r.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,n,a){if(!n)return{success:!1,error:"sessionId is required"};const r=new URL(`/api/v1/runtime/${encodeURIComponent(n)}/snapshot`,window.location.origin);typeof(a==null?void 0:a.sinceSeq)=="number"&&r.searchParams.set("sinceSeq",String(a.sinceSeq));const o=await Ts(`${r.pathname}${r.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(n,{type:"runtime_snapshot",sessionId:n,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:!!(a!=null&&a.force)}),{success:!0}}emitRuntimeEvent(t,n){var a;(a=this.runtimeListeners.get(t))==null||a.forEach(r=>r(n))}}const As=new fR;function gR(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,n=Tc();return n?`${t}?token=${encodeURIComponent(n)}`:t}const Sr=gR(),ap=3e3,bR=3e4;let gs=null,xR=0;const io=new Map;let gn=null,Ia=null;function rp(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function ya(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function vR(e){return e==="connected"?"connected":e}async function La(e,t,n){const a=ph(e,n||{}),r=gs;if(r&&r.readyState===WebSocket.OPEN){const o=`req_${++xR}_${Date.now()}`;return new Promise((i,c)=>{const d=setTimeout(()=>{io.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);io.set(o,{resolve:p=>{clearTimeout(d),i(p)},reject:p=>{clearTimeout(d),c(p)}}),r.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:a.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function Al(e,t){const n=gs;if(!n||n.readyState!==WebSocket.OPEN||!t||t.type!=="subscribe"&&t.type!=="unsubscribe")return!1;try{return n.send(JSON.stringify(t)),!0}catch{return!1}}function dg(e,t,n){const a=gs;if(!a||a.readyState!==WebSocket.OPEN)return!1;const r=ph(e,{sessionId:t,targetSessionId:t,data:n});try{return a.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:r.payload}})),!0}catch{return!1}}As.registerPtyInputSender(dg);class yR{constructor(t){it(this,"daemonId");it(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(gs==null?void 0:gs.readyState)===WebSocket.OPEN}get connectionState(){return(gs==null?void 0:gs.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,n){return La(this.daemonId,t,n)}async sendInput(t,n){return La(this.daemonId,"cdp_remote_action",{action:t,params:n,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,gn&&(clearInterval(gn),gn=null);const n=async()=>{if(this.hasCommandChannel)try{const a=await La(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(a!=null&&a.success&&(a!=null&&a.base64)){const r=await fetch(`data:image/jpeg;base64,${a.base64}`).then(o=>o.blob());As.emitScreenshot(this.daemonId,r)}}catch{}};n(),gn=setInterval(n,2e3)}stopScreenshots(t){gn&&(clearInterval(gn),gn=null)}}let rs=null;function wR(e){return(!rs||rs.daemonId!==e)&&(rs=new yR(e)),rs}function kR({children:e}){const t=l.useRef(Ra()),n=Ra();t.current=n;const{setUserName:a}=Ss(),r=l.useRef(a);r.current=a;const o=l.useRef(null),i=l.useRef(null),[,c]=l.useState("disconnected"),d=l.useCallback((h,x)=>{c(h),Ia==null||Ia(h,x)},[]),p=l.useRef(null),u=l.useRef(),m=l.useRef(ap),f=l.useRef(!0),g=l.useRef(!1),k=l.useRef("initial_connect");return l.useEffect(()=>{f.current=!0,g.current=!1;function h(){var b,w;if(!f.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 ${Sr}...`),ya("connect_attempt",{url:Sr,reason:k.current,delayMs:m.current});let S;try{S=new WebSocket(Sr)}catch(C){console.error("[Standalone WS] Failed to create WebSocket:",C),x();return}p.current=S,S.onopen=()=>{if(!f.current){S.close();return}d("connected"),m.current=ap,ya("open",{url:Sr,reason:k.current}),ys.resubscribeAll({sendData:Al}),console.log("[Standalone WS] Connected")},gs=S,S.onmessage=C=>{var v,y;try{const j=JSON.parse(C.data);if((j.type==="command_result"||j.type==="error")&&j.requestId){const N=io.get(j.requestId);N&&(io.delete(j.requestId),j.type==="error"?N.reject(new Error(((v=j.data)==null?void 0:v.message)||"Command failed")):N.resolve(j.data));return}if(j.type==="session_output"){const N=j.sessionId||j.cliId||j.cliType;N&&As.emitSessionOutput(N,typeof j.data=="string"?j.data:"",typeof j.seq=="number"?j.seq:void 0);return}if(j.type==="runtime_snapshot"){As.emitRuntimeSnapshot(j.sessionId,typeof j.text=="string"?j.text:"",typeof j.seq=="number"?j.seq:0,!!j.truncated,typeof j.cols=="number"?j.cols:void 0,typeof j.rows=="number"?j.rows:void 0);return}if(j.type==="topic_update"){const N=j.update;N&&ys.publish(N);return}if(j.type==="status"||j.type==="initial_state"){const N=j.data;if(!N)return;const{injectEntries:T,markLoaded:A,getIdes:I}=t.current,D=N.instanceId||"standalone",M=I().find(B=>B.id===D),E=wR(D);As.register(D,E),As.setState(D,"connected"),d("connected",D),As.emitStatus(D,N);const P=Wr(N,{daemonId:D,existingDaemon:M,existingEntries:I()});rp("ws_status",{type:j.type,daemonId:D,sessions:(N.sessions||[]).map(B=>({id:B.id,parentId:B.parentId,providerType:B.providerType,kind:B.kind,transport:B.transport,unread:B.unread,inboxBucket:B.inboxBucket,lastSeenAt:B.lastSeenAt,lastUpdated:B.lastUpdated,title:B.title})),recentLaunches:(N.recentLaunches||[]).map(B=>({id:B.id,providerType:B.providerType,kind:B.kind,workspace:B.workspace,lastLaunchedAt:B.lastLaunchedAt}))}),rp("entries",{daemonId:D,entries:P.filter(B=>B.type!=="adhdev-daemon").map(B=>({id:B.id,type:B.type,unread:B.unread,inboxBucket:B.inboxBucket,lastSeenAt:B.lastSeenAt,lastUpdated:B.lastUpdated,sessionId:B.sessionId}))}),P.length>0&&T(P,{authoritativeDaemonIds:[D]}),A(),i.current!==D&&((y=o.current)==null||y.call(o),i.current=D,o.current=ys.subscribe({sendData:Al},D,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${D}`,params:{includeSessions:!0}},B=>{if(B.topic!=="daemon.metadata")return;const R=t.current.getIdes(),W=R.find(H=>H.id===D),_=Wr(B.status,{daemonId:D,existingDaemon:W,existingEntries:R,timestamp:B.timestamp});_.length>0&&t.current.injectEntries(_,{authoritativeDaemonIds:[D]}),B.userName&&r.current&&r.current(B.userName)}))}}catch(j){console.error("[Standalone WS] Parse error:",j)}},S.onclose=C=>{f.current&&(rs==null||rs.stopScreenshots(),rs&&As.setState(rs.daemonId,"disconnected"),d("disconnected"),p.current=null,k.current=`close:${C.code}${C.wasClean?":clean":":unclean"}`,ya("close",{code:C.code,reason:C.reason||"",wasClean:C.wasClean}),x())},S.onerror=C=>{g.current||!f.current||(k.current="error",ya("error",{message:C instanceof Event?"event":String(C),readyState:S.readyState}),console.warn("[Standalone WS] Error, will reconnect:",C))}}function x(){if(!f.current)return;clearTimeout(u.current);const S=m.current;console.log(`[Standalone WS] Reconnecting in ${S}ms...`),ya("schedule_reconnect",{reason:k.current,delayMs:S}),u.current=setTimeout(()=>{m.current=Math.min(m.current*1.5,bR),h()},S)}return h(),()=>{var S;f.current=!1,g.current=!0,(S=o.current)==null||S.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,gs=null),rs&&(rs.stopScreenshots(),As.unregister(rs.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function SR({children:e}){const[t,n]=l.useState("disconnected"),[a,r]=l.useState(null);l.useEffect(()=>(Ia=(i,c)=>{n(i),c&&r(c)},()=>{Ia=null}),[]);const o=l.useMemo(()=>{const i=t==="connected",c=vR(t),d={};return a&&(d[a]=c),d.standalone=c,{wsStatus:t,isConnected:i,connectionStates:d,usesP2P:!1}},[t,a]);return s.jsx(Zg,{connectionOverrides:o,children:s.jsx(kR,{children:e})})}const ug="adhdev_standalone_font_preferences",Nn={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Lo=[{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"}],Wa=[{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"}],CR=new Set(Lo.map(e=>e.id)),jR=new Set(Wa.map(e=>e.id));function Ms(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Rr("chat",t.chat),code:Rr("code",t.code),terminal:Rr("terminal",t.terminal)}}function Rr(e,t){const n=Nn[e],a=t&&typeof t=="object"&&!Array.isArray(t)?t:{},r=typeof a.preset=="string"?a.preset.trim():"",o=typeof a.customFamily=="string"?a.customFamily.trim():"";return(e==="chat"?CR:jR).has(r)?r==="custom"?o?{preset:"custom",customFamily:o}:n:{preset:r}:n}function Er(e,t){var r;const n=Rr(e,t);if(n.preset==="custom"&&n.customFamily)return n.customFamily;const a=e==="chat"?Lo:Wa;return((r=a.find(o=>o.id===n.preset))==null?void 0:r.family)||a[0].family}function NR(e){const t=Ms(e),n=Er("chat",t.chat),a=Er("code",t.code),r=Er("terminal",t.terminal);return{"--chat-font-family":n,"--chat-code-font-family":a,"--chat-terminal-font-family":r,"--chat-tool-font-family":r}}function xn(e,t=document.documentElement){const n=Ms(e),a=NR(n);t.setAttribute("data-standalone-fonts","custom");for(const[r,o]of Object.entries(a))t.style.setProperty(r,o);return n}function Tl(e){const t=Ms(e);try{localStorage.setItem(ug,JSON.stringify(t))}catch{}return t}function AR(){try{const e=localStorage.getItem(ug);if(e)return Ms(JSON.parse(e))}catch{}return Nn}function TR(){return xn(AR())}function wa(e,t){var a;const n=e==="chat"?Lo:Wa;return((a=n.find(r=>r.id===t))==null?void 0:a.label)||n[0].label}function MR({children:e}){const t=oa(),n=Pl(),{t:a}=ke("common"),r=l.useMemo(()=>[{id:"dashboard",path:"/dashboard",icon:s.jsx(kp,{}),label:a("nav.dashboard"),active:n.pathname.startsWith("/dashboard"),onSelect:()=>t("/dashboard")},{id:"machine",path:"/machines",icon:s.jsx(sn,{}),label:a("nav.machines"),active:n.pathname.startsWith("/machines"),onSelect:()=>t("/machines")},{id:"mesh",path:"/mesh",icon:s.jsx(cs,{}),label:a("nav.mesh"),active:n.pathname.startsWith("/mesh")||n.pathname.startsWith("/setup"),onSelect:()=>t("/mesh")},{id:"settings",path:"/settings",icon:s.jsx(Oa,{}),label:a("nav.settings"),active:n.pathname.startsWith("/settings"),onSelect:()=>t("/settings")}],[n.pathname,t,a]),o=l.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:a("nav.docs")}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(Sp,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:a("nav.docs")},{id:"about",label:a("nav.about"),icon:s.jsx(co,{}),active:n.pathname==="/about",onSelect:()=>t("/about"),title:a("nav.about")}],[n.pathname,t,a]);return s.jsx(l1,{brand:({collapsed:i})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&s.jsx("span",{children:"ADHDev"})]}),navItems:r,footerItems:o,footerInfo:({collapsed:i})=>i?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","1.0.55"]}),footerActions:({collapsed:i,toggleCollapsed:c})=>s.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:c,title:a(i?"standalone.layout.expandSidebar":"standalone.layout.collapseSidebar"),children:[s.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&s.jsx("span",{className:"text-xs",children:a("standalone.layout.collapse")})]}),children:e})}function PR(){const e=oa(),{sendCommand:t}=St(),{ides:n}=Ss(),a=l.useMemo(()=>n.filter(r=>r.daemonMode||r.type==="adhdev-daemon").map(r=>r),[n]);return s.jsx(mR,{daemons:a,features:Zf,sendCommand:t,unwrapResult:r=>r,normalizeMesh:r=>r,onClose:()=>e("/mesh")})}const DR=[{icon:s.jsx(sn,{size:16}),key:"localFirst"},{icon:s.jsx(Ds,{size:16}),key:"chatRelay"},{icon:s.jsx(El,{size:16}),key:"screenshots"},{icon:s.jsx(us,{size:16}),key:"remoteControl"},{icon:s.jsx(Ea,{size:16}),key:"multiIde"},{icon:s.jsx(Sp,{size:16}),key:"cliAcp"}],IR=[{icon:s.jsx(mo,{size:16}),key:"anywhere"},{icon:s.jsx(kp,{size:16}),key:"p2pStream"},{icon:s.jsx(ia,{size:16}),key:"mobileNotifications"},{icon:s.jsx(cb,{size:16}),key:"restApi"},{icon:s.jsx(ub,{size:16}),key:"enterpriseControls"}],LR=[{key:"chatRelay",selfhost:!0,cloud:!0},{key:"screenshots",selfhost:!0,cloud:!0},{key:"remoteControl",selfhost:!0,cloud:!0},{key:"multiIde",selfhost:!0,cloud:!0},{key:"extensionCli",selfhost:!0,cloud:!0},{key:"anyNetwork",selfhost:!1,cloud:!0},{key:"webrtc",selfhost:!1,cloud:!0},{key:"mobilePush",selfhost:!1,cloud:!0},{key:"restApi",selfhost:!1,cloud:!0},{key:"multiMachineDashboards",selfhost:!1,cloud:!0},{key:"ssoRbacAuditLogs",selfhost:!1,cloud:!0}];function RR(){const{t:e}=ke("common");return s.jsxs(Qa,{icon:s.jsx(co,{className:"text-text-primary"}),title:e("standalone.about.title"),subtitle:e("standalone.about.subtitle"),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","1.0.55"]}),children:[s.jsx(xt,{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:e("standalone.about.selfHostedEdition")}),s.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:e("standalone.about.headline")}),s.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:e("standalone.about.description")})]}),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:e("standalone.about.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:e("standalone.about.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:e("standalone.about.tryCloud")})]})]})}),s.jsx(xt,{title:e("standalone.about.includedSection"),description:e("standalone.about.includedDescription"),children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:DR.map(t=>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:t.icon}),e("standalone.about.features."+t.key+".title")]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e("standalone.about.features."+t.key+".desc")})]},t.key))})}),s.jsx(xt,{title:e("standalone.about.inventorySection"),description:e("standalone.about.inventoryDescription"),children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:mh.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:fh.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:hh.map(t=>`${t.icon} ${t.name}`)}].map(t=>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:t.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:t.items.map(n=>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:n},n))})]},t.label))})}),s.jsx(xt,{title:e("standalone.about.cloudExtrasSection"),description:e("standalone.about.cloudExtrasDescription"),children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:IR.map(t=>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:t.icon}),e("standalone.about.extras."+t.key+".title")]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e("standalone.about.extras."+t.key+".desc")})]},t.key))})}),s.jsx(xt,{title:e("standalone.about.comparisonSection"),description:e("standalone.about.comparisonDescription"),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:e("standalone.about.featureHeader")}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:e("standalone.about.selfhostHeader")}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:e("standalone.about.cloudHeader")})]})}),s.jsx("tbody",{children:LR.map((t,n)=>s.jsxs("tr",{className:n%2===0?"bg-bg-glass":"bg-transparent",children:[s.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e("standalone.about.comparison."+t.key)}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:t.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:"✓"})})]},t.key))})]})})}),s.jsx(Ja,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:e("standalone.about.cloudOptional"),description:e("standalone.about.cloudOptionalDescription"),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:e("standalone.about.compareCloud")}),s.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[s.jsx(yb,{size:14,className:"mr-1"}),e("standalone.about.discord")]})]})})]})}function Ei(e,t,n){return{...e,[t]:n}}function _i({surface:e,title:t,description:n,value:a,options:r,onChange:o}){const{t:i}=ke("common");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:n})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(p1,{value:a.preset,onChange:c=>{const d=c.target.value;o(d==="custom"?{preset:"custom",customFamily:a.customFamily||""}:{preset:d})},children:r.map(c=>s.jsx("option",{value:c.id,children:c.label},c.id))}),a.preset==="custom"&&s.jsx(xs,{type:"text",className:"font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:a.customFamily||"",onChange:c=>o({preset:"custom",customFamily:c.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:i("standalone.fonts.resolvedStack")})," ",s.jsx("span",{className:"font-mono break-all",children:Er(e,a)})]})]})]})}function ER({value:e,savedValue:t,saving:n=!1,error:a,notice:r,onChange:o,onSave:i,onResetToSaved:c,onResetToDefaults:d}){const{t:p}=ke("common"),u=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:p("standalone.fonts.fontOverridesNotice")}),a&&s.jsx(Mt,{variant:"error",children:a}),r&&s.jsx(Mt,{variant:"success",children:r}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(_i,{surface:"chat",title:p("standalone.fonts.chat"),description:p("standalone.fonts.chatDescription"),value:e.chat,options:Lo,onChange:m=>o(Ei(e,"chat",m))}),s.jsx(_i,{surface:"code",title:p("standalone.fonts.code"),description:p("standalone.fonts.codeDescription"),value:e.code,options:Wa,onChange:m=>o(Ei(e,"code",m))}),s.jsx(_i,{surface:"terminal",title:p("standalone.fonts.terminal"),description:p("standalone.fonts.terminalDescription"),value:e.terminal,options:Wa,onChange:m=>o(Ei(e,"terminal",m))})]}),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:p("standalone.fonts.livePreview")}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",wa("chat",e.chat.preset)," · Code: ",wa("code",e.code.preset)," · Terminal: ",wa("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[p("standalone.fonts.defaults")," ",wa("chat",Nn.chat.preset)," / ",wa("code",Nn.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(Us,{type:"button",variant:"primary",size:"sm",onClick:i,disabled:n||!u,children:p(n?"standalone.fonts.saving":"standalone.fonts.saveFontSettings")}),s.jsx(Us,{type:"button",variant:"secondary",size:"sm",onClick:c,disabled:n||!u,children:p("standalone.fonts.revertToSaved")}),s.jsx(Us,{type:"button",variant:"secondary",size:"sm",onClick:d,disabled:n,children:p("standalone.fonts.resetToDefaults")})]})]})}function _R(){const{t:e}=ke("common"),{ides:t}=Ss(),n=t.find(O=>O.type==="adhdev-daemon"),a=(n==null?void 0:n.detectedIdes)||[],{sendCommand:r}=St(),{userName:o}=Ss(),[i,c]=l.useState(o||""),[d,p]=l.useState(null),[u,m]=l.useState(null),[f,g]=l.useState(Nn),[k,h]=l.useState(!1),[x,S]=l.useState(""),[b,w]=l.useState(""),[C,v]=l.useState("127.0.0.1"),[y,j]=l.useState(""),[N,T]=l.useState(""),[A,I]=l.useState(""),[D,M]=l.useState(""),[E,P]=l.useState(""),[B,R]=l.useState(!1),W=async()=>{const Y=await(await Ts("/auth/session")).json();p(Y)},_=async()=>{const Y=await(await Ts("/api/v1/standalone/preferences")).json();m(Y),v(Y.standaloneBindHost);const X=Ms(Y.standaloneFontPreferences);g(X),xn(X),Tl(X)};l.useEffect(()=>{o!==void 0&&c(o)},[o]),l.useEffect(()=>{Promise.all([W(),_()]).catch(O=>{M(O instanceof Error?O.message:String(O))})},[]),l.useEffect(()=>{xn(f)},[f]);const H=O=>{const Y=O.target.value.trim();n!=null&&n.id&&Y!==o&&r(n.id,"set_user_name",{userName:Y}).catch(console.error)},[L,F]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),$=O=>{F(O);try{localStorage.setItem("adhdev_sound",O?"1":"0")}catch{}},K=async()=>{S(""),w(""),h(!0);try{const O=Ms(f),Y=await Ts("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:O})}),X=await Y.json();if(!Y.ok)throw new Error((X==null?void 0:X.error)||"Failed to save standalone font preferences");const Q=Ms(X.standaloneFontPreferences);m(X),g(Q),xn(Q),Tl(Q),w(e("standalone.settings.fontsSaved"))}catch(O){S(O instanceof Error?O.message:String(O))}finally{h(!1)}},z=()=>{const O=Ms(u==null?void 0:u.standaloneFontPreferences);S(""),w(""),g(O),xn(O)},ne=()=>{S(""),w(""),g(Nn),xn(Nn)},ie=async()=>{M(""),P(""),R(!0);try{const O=await Ts("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:C})}),Y=await O.json();if(!O.ok)throw new Error((Y==null?void 0:Y.error)||"Failed to save standalone network preference");m(Y),v(Y.standaloneBindHost),P(Y.standaloneBindHost==="0.0.0.0"?e("standalone.settings.networkSavedAll"):e("standalone.settings.networkSavedLocal"))}catch(O){M(O instanceof Error?O.message:String(O))}finally{R(!1)}},Ce=async()=>{if(M(""),P(""),N.trim().length<4){M(e("standalone.settings.passwordTooShort"));return}if(N!==A){M(e("standalone.settings.passwordMismatch"));return}R(!0);try{const O=await Ts("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,newPassword:N})}),Y=await O.json();if(!O.ok)throw new Error((Y==null?void 0:Y.error)||"Failed to save password");p(Y),await _(),j(""),T(""),I(""),P(d!=null&&d.hasPasswordAuth?e("standalone.settings.passwordUpdated"):e("standalone.settings.passwordEnabled")),cg()}catch(O){M(O instanceof Error?O.message:String(O))}finally{R(!1)}},me=async()=>{M(""),P(""),R(!0);try{const O=await Ts("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,clear:!0})}),Y=await O.json();if(!O.ok)throw new Error((Y==null?void 0:Y.error)||"Failed to clear password");p(Y),await _(),j(""),T(""),I(""),P(e("standalone.settings.passwordDisabled"))}catch(O){M(O instanceof Error?O.message:String(O))}finally{R(!1)}};return s.jsxs(Qa,{icon:s.jsx(Oa,{className:"text-text-primary"}),title:e("standalone.settings.title"),subtitle:e("standalone.settings.subtitle"),widthClassName:"max-w-5xl",children:[s.jsx(Mt,{variant:"info",children:e("standalone.settings.infoNotice")}),(d==null?void 0:d.publicHostWarning)&&s.jsx(Mt,{variant:"warning",children:e("standalone.settings.publicHostWarning")}),s.jsx(xt,{title:e("standalone.settings.daemonSection"),description:e("standalone.settings.daemonDescription"),children:s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.versionLabel")}),s.jsxs("span",{className:"font-mono text-xs text-text-primary",children:["v","1.0.55"]})]}),s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.statusLabel")}),s.jsx("span",{className:`text-xs font-medium ${n?"text-green-400":"text-yellow-400"}`,children:e(n?"standalone.settings.statusRunning":"standalone.settings.statusNotConnected")})]}),s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.currentBindLabel")}),s.jsx("span",{className:"font-mono text-xs text-text-primary",children:(u==null?void 0:u.currentBindHost)||(d==null?void 0:d.boundHost)||"127.0.0.1"})]}),s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.defaultBindLabel")}),s.jsx("span",{className:"font-mono text-xs text-text-primary",children:(u==null?void 0:u.standaloneBindHost)||"127.0.0.1"})]}),s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.authLabel")}),s.jsx("span",{className:"text-xs text-text-primary",children:d!=null&&d.hasPasswordAuth?e("standalone.settings.authPassword"):d!=null&&d.hasTokenAuth?e("standalone.settings.authToken"):e("standalone.settings.authNone")})]})]})}),s.jsx(xt,{title:e("standalone.settings.networkSection"),description:e("standalone.settings.networkDescription"),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:e("standalone.settings.networkHint")}),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:C==="127.0.0.1",onChange:()=>v("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:e("standalone.settings.localhostLabel")}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:e("standalone.settings.localhostHint")})]})]}),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:C==="0.0.0.0",onChange:()=>v("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:e("standalone.settings.allInterfacesLabel")}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:e("standalone.settings.allInterfacesHint")})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx(Us,{type:"button",variant:"primary",size:"sm",onClick:()=>{ie()},disabled:B,children:e(B?"standalone.settings.saving":"standalone.settings.saveNetworkMode")}),s.jsx("span",{className:"text-xs text-text-muted",children:e("standalone.settings.networkRestartHint",{host:(u==null?void 0:u.currentBindHost)||(d==null?void 0:d.boundHost)||"127.0.0.1"})})]})]})}),s.jsx(xt,{title:e("standalone.settings.securitySection"),description:e("standalone.settings.securityDescription"),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:d!=null&&d.hasPasswordAuth?e("standalone.settings.passwordSet"):e("standalone.settings.passwordNotSet")}),D&&s.jsx(Mt,{variant:"error",children:D}),E&&s.jsx(Mt,{variant:"success",children:E}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx(xs,{type:"password",placeholder:d!=null&&d.hasPasswordAuth?e("standalone.settings.currentPasswordPlaceholder"):e("standalone.settings.currentPasswordFirstTimePlaceholder"),value:y,onChange:O=>j(O.target.value)}),s.jsx(xs,{type:"password",placeholder:d!=null&&d.hasPasswordAuth?e("standalone.settings.newPasswordPlaceholder"):e("standalone.settings.newPasswordFirstTimePlaceholder"),value:N,onChange:O=>T(O.target.value)}),s.jsx(xs,{type:"password",className:"md:col-span-2",placeholder:e("standalone.settings.confirmPasswordPlaceholder"),value:A,onChange:O=>I(O.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Us,{type:"button",variant:"primary",size:"sm",onClick:()=>{Ce()},disabled:B,children:B?e("standalone.settings.saving"):d!=null&&d.hasPasswordAuth?e("standalone.settings.updatePassword"):e("standalone.settings.enablePassword")}),(d==null?void 0:d.hasPasswordAuth)&&s.jsx(Us,{type:"button",variant:"danger",size:"sm",onClick:()=>{me()},disabled:B,children:e("standalone.settings.disablePassword")})]})]})}),s.jsx(xt,{title:e("standalone.settings.detectedIdesSection"),description:e("standalone.settings.detectedIdesDescription"),children:a.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:e("standalone.settings.noIdesDetected")}):s.jsx("div",{className:"flex flex-col gap-2",children:a.map(O=>s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${O.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium text-text-primary",children:O.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:O.type})]},O.type))})}),s.jsx(xt,{title:e("standalone.settings.machineSection"),description:e("standalone.settings.machineDescription"),children:s.jsx(k1,{ides:t,emptyMessage:e("standalone.settings.daemonNotConnected")})}),s.jsx(xt,{title:e("standalone.settings.appearanceSection"),description:e("standalone.settings.appearanceDescription"),children:s.jsx(B1,{themeDescription:e("standalone.settings.themeDescription"),mobileDescription:e("standalone.settings.mobileDescription"),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:e("standalone.settings.fontsLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:e("standalone.settings.fontsDescription")}),s.jsx(ER,{value:f,savedValue:Ms(u==null?void 0:u.standaloneFontPreferences),saving:k,error:x,notice:b,onChange:g,onSave:()=>{K()},onResetToSaved:z,onResetToDefaults:ne})]})})}),s.jsx(xt,{title:e("standalone.settings.notificationsSection"),description:e("standalone.settings.notificationsDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(b1,{}),s.jsx(bn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(vb,{size:15})," ",e("standalone.settings.soundEffectsLabel")]}),description:e("standalone.settings.soundEffectsDescription"),checked:L,onChange:$})]})}),s.jsx(xt,{title:e("standalone.settings.profileSection"),description:e("standalone.settings.profileDescription"),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(lb,{size:16,className:"text-text-secondary"})," ",e("standalone.settings.displayNameLabel")]}),s.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:e("standalone.settings.displayNameHint")})]}),s.jsx(xs,{type:"text",className:"w-48 text-right",placeholder:e("standalone.settings.displayNamePlaceholder"),value:i,onChange:O=>c(O.target.value),onBlur:H,onKeyDown:O=>{O.key==="Enter"&&O.currentTarget.blur()}})]})})})]})}const HR=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],ja="adhdev_onboarding_done",$R=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],FR={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function BR({onDone:e}){const{t}=ke("common"),[n,a]=l.useState([]),[r,o]=l.useState(new Set(HR)),[i,c]=l.useState(!0),[d,p]=l.useState(null),[u,m]=l.useState(!1),[f,g]=l.useState(null),[k,h]=l.useState("all");l.useEffect(()=>{let y=!1;return fetch("https://api.adhf.dev/api/v1/registry/providers?sort=popular&limit=100").then(async N=>{if(!N.ok)throw new Error(`HTTP ${N.status}`);const T=await N.text();try{return JSON.parse(T)}catch{throw new Error(`unexpected non-JSON response (${N.headers.get("content-type")??"unknown content type"})`)}}).then(N=>{y||a(N.providers??[])}).catch(N=>{y||p(N instanceof Error?N.message:String(N))}).finally(()=>{y||c(!1)}),()=>{y=!0}},[]);const x=n.filter(y=>k==="all"||y.category===k),S=["cli","ide","extension","acp"].map(y=>({category:y,items:x.filter(j=>j.category===y)})).filter(y=>y.items.length>0),b=l.useCallback(y=>{o(j=>{const N=new Set(j);return N.has(y)?N.delete(y):N.add(y),N})},[]),w=l.useCallback(async()=>{if(r.size===0){localStorage.setItem(ja,"1"),e();return}m(!0);const y=[];for(const j of r)try{const T=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:j})})).json().catch(()=>({}));y.push({type:j,ok:!!T.success,error:T.error})}catch(N){y.push({type:j,ok:!1,error:N instanceof Error?N.message:String(N)})}g(y),m(!1),y.every(j=>j.ok)&&localStorage.setItem(ja,"1")},[r,e]),C=l.useCallback(()=>{localStorage.setItem(ja,"1"),e()},[e]),v=l.useCallback(()=>{f&&f.every(y=>y.ok)?e():u||C()},[f,u,e,C]);return s.jsx(xm,{open:!0,onClose:v,size:"lg",contentClassName:"max-w-2xl",title:t("standalone.onboarding.title"),footer:s.jsxs("div",{className:"flex w-full items-center gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:t(r.size!==1?"standalone.onboarding.selectedCount_other":"standalone.onboarding.selectedCount_one",{count:r.size})}),s.jsxs("div",{className:"ml-auto flex gap-2",children:[s.jsx(Us,{variant:"secondary",size:"sm",onClick:C,disabled:u,children:t("standalone.onboarding.skip")}),s.jsx(Us,{variant:"primary",size:"sm",onClick:()=>{f?(localStorage.setItem(ja,"1"),e()):w()},disabled:u||!f&&r.size===0,children:u?t("standalone.onboarding.installing"):f?t("standalone.onboarding.done"):t("standalone.onboarding.installCount",{count:r.size})})]})]}),children:s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsx("div",{className:"text-[12px] text-text-muted",children:t("standalone.onboarding.intro")}),!i&&!d&&n.length>0&&s.jsx("div",{className:"flex gap-1 flex-wrap border-b border-border-subtle pb-2",children:$R.map(y=>{const j=y.key==="all"?n.length:n.filter(N=>N.category===y.key).length;return j===0&&y.key!=="all"?null:s.jsxs("button",{onClick:()=>h(y.key),className:`machine-btn text-[10px] px-2 py-0.5 ${k===y.key?"bg-accent-primary/12 border-accent-primary/40 text-accent-primary":""}`,children:[y.label," ",s.jsxs("span",{className:"opacity-60",children:["(",j,")"]})]},y.key)})}),i&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.loadingRegistry")}),!i&&d&&s.jsx(Mt,{variant:"error",children:t("standalone.onboarding.loadError",{error:d})}),!i&&!d&&x.length===0&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.noProviders")}),!i&&!d&&x.length>0&&s.jsx("div",{className:"flex flex-col gap-4",children:S.map(y=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:FR[y.category]??y.category}),s.jsx("div",{className:"grid gap-1.5",children:y.items.map(j=>{var I;const N=r.has(j.type),T=f==null?void 0:f.find(D=>D.type===j.type),A=((I=j.manifest)==null?void 0:I.details)??"";return s.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${N?"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:N,onChange:()=>b(j.type),disabled:u,className:"shrink-0"}),s.jsx(Ya,{type:j.type,label:j.displayName??j.type,size:18,className:"shrink-0"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[13px] font-medium text-text-primary truncate",children:j.displayName}),A&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:A})]}),T&&s.jsx("span",{className:`text-[10px] font-semibold ${T.ok?"text-status-online":"text-status-error"}`,children:T.ok?t("standalone.onboarding.installed"):t("standalone.onboarding.installFailed",{error:T.error??"failed"})})]},j.type)})})]},y.category))})]})})}function WR(){try{return localStorage.getItem(ja)==="1"}catch{return!1}}Jj();I1();S0();TR();const OR=vp({baseUrl:"",getToken:Tc});function UR({children:e}){const{t}=ke("common"),[n,a]=l.useState(null),[r,o]=l.useState(!0),[i,c]=l.useState(""),[d,p]=l.useState(""),[u,m]=l.useState(!1),f=async()=>{o(!0),p("");try{const h=await(await Ts("/auth/session")).json();a(h)}catch(k){p(k instanceof Error?k.message:String(k))}finally{o(!1)}};l.useEffect(()=>{f()},[]),l.useEffect(()=>{if(!n||n.required&&!n.authenticated)return;let k=!1;return(async()=>{try{const h=await Ts("/api/v1/standalone/preferences");if(!h.ok)return;const x=await h.json();if(k)return;const S=Ms(x.standaloneFontPreferences);xn(S),Tl(S)}catch{}})(),()=>{k=!0}},[n==null?void 0:n.authenticated,n==null?void 0:n.required]);const g=async k=>{k.preventDefault(),m(!0),p("");try{const h=await Ts("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),x=await h.json();if(!h.ok)throw new Error((x==null?void 0:x.error)||"Login failed");a(x),c(""),cg()}catch(h){p(h instanceof Error?h.message:String(h))}finally{m(!1)}};return r?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:t("standalone.auth.loading")}):n?!n.required||n.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:t("standalone.auth.signInTitle")}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:n.hasPasswordAuth?t("standalone.auth.passwordProtected"):t("standalone.auth.tokenProtected")})]}),n.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:g,children:[s.jsx(xs,{type:"password",value:i,onChange:k=>c(k.target.value),placeholder:t("standalone.auth.passwordPlaceholder"),autoFocus:!0}),s.jsx(Us,{type:"submit",variant:"primary",disabled:u||!i,className:"justify-center",children:t(u?"standalone.auth.signingIn":"standalone.auth.unlock")})]}):s.jsx(Mt,{variant:"warning",children:t("standalone.auth.noPasswordEnabled")}),d&&s.jsx(Mt,{variant:"error",children:d})]})}):s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:t("standalone.auth.loadError",{error:d||"unknown error"})})}function op(){const{t:e}=ke("common"),{ides:t,initialLoaded:n}=Ss();if(!n)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:e("standalone.machine.loading")});const a=t.find(r=>r.daemonMode||r.type==="adhdev-daemon");return a?s.jsx(Fi,{to:`/machines/${a.id}`,replace:!0}):s.jsx(Fi,{to:"/dashboard",replace:!0})}function GR(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let n=!1;if(!WR())return fetch("/api/v1/providers/installed").then(a=>a.ok?a.json():{providers:[]}).then(a=>{n||(a.providers??[]).length===0&&t(!0)}).catch(()=>{}),()=>{n=!0}},[]),e?s.jsx(BR,{onDone:()=>t(!1)}):null}function qR(){const{t:e}=ke("common"),{ides:t}=Ss(),n=l.useMemo(()=>{for(const u of t)if(u.activeInteractivePrompt)return u.instanceId??u.id;return null},[t]),{promptSession:a,hasActivePrompt:r,responseError:o,isSubmitting:i,submit:c,cancel:d,reopen:p}=jh(n);return r?s.jsxs("div",{className:"relative",children:[!a&&s.jsx("button",{type:"button",onClick:p,className:"fixed bottom-4 right-4 z-[79] btn btn-primary btn-sm shadow-lg",children:e("standalone.machine.awaitingInput")}),s.jsx(zp,{promptSession:a,isSubmitting:i,error:o,onSubmit:c,onCancel:d})]}):null}function zR(){const e=l.useMemo(()=>({sendCommand:La,sendData:Al,sendPtyInput:dg}),[]);return s.jsx(_g,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(sb,{client:OR,children:s.jsx(UR,{children:s.jsx(SR,{children:s.jsx(ab,{value:e,children:s.jsxs(Db,{sendDaemonCommand:La,children:[s.jsx(qR,{}),s.jsxs(MR,{children:[s.jsx(GR,{}),s.jsxs(Hg,{children:[s.jsx(Bs,{path:"/dashboard",element:s.jsx(yI,{})}),s.jsx(Bs,{path:"/machine",element:s.jsx(op,{})}),s.jsx(Bs,{path:"/machines/:id",element:s.jsx(LL,{})}),s.jsx(Bs,{path:"/machines",element:s.jsx(op,{})}),s.jsx(Bs,{path:"/about",element:s.jsx(RR,{})}),s.jsx(Bs,{path:"/settings",element:s.jsx(_R,{})}),s.jsx(Bs,{path:"/mesh",element:s.jsx(cR,{children:s.jsx(iR,{})})}),s.jsx(Bs,{path:"/setup",element:s.jsx(PR,{})}),s.jsx(Bs,{path:"*",element:s.jsx(Fi,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}$C({connectionManager:As});$g(document.getElementById("root")).render(s.jsx(zR,{}));
|