@adhdev/daemon-standalone 1.0.51 → 1.0.52

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
  `),K=((fe=de[0])==null?void 0:fe.slice(0,80))||"(empty)";return s.jsxs("div",{className:"border border-border-default rounded overflow-hidden bg-surface-secondary",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2.5 py-1.5 hover:bg-bg-glass-hover transition-colors text-left",onClick:()=>ee(V),children:[s.jsx("span",{className:"text-[10px] text-text-muted w-3",children:se?"▾":"▸"}),s.jsx("span",{className:"font-mono text-accent-primary w-20 shrink-0 text-[11px]",children:V}),!se&&s.jsx("span",{className:"text-text-secondary truncate font-mono text-[11px]",children:K}),s.jsxs("span",{className:"ml-auto text-text-muted text-[10px] shrink-0",children:[de.length,"L"]})]}),se&&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,{}),U.nativeSource&&s.jsxs("div",{children:[s.jsxs($n,{children:["Status History",U.statusHistory&&U.statusHistory.length>0?` (${U.statusHistory.length})`:""]}),U.statusHistory&&U.statusHistory.length>0?s.jsx("div",{className:"space-y-px",children:[...U.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)"})]}),!U.nativeSource&&U.stateHistory&&U.stateHistory.length>0&&s.jsxs("div",{children:[s.jsxs($n,{children:["State History (",U.stateHistory.length,")"]}),s.jsx("div",{className:"space-y-px",children:[...U.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 ${nj[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((se,de)=>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 se=="string"?se:JSON.stringify(se)},de)),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=U.messages??U.committedMessages??[];if(V.length===0)return null;const q=V.filter(K=>K.role==="user").length,se=V.filter(K=>K.role==="assistant").length,de=[...V].reverse().find(K=>K.role==="assistant");return s.jsxs("div",{children:[s.jsxs($n,{children:["Transcript (",V.length," — ",q,"u / ",se,"a)"]}),de&&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 ",de.receivedAt?Hn(de.receivedAt):""]}),s.jsxs("div",{className:"text-text-secondary font-mono whitespace-pre-wrap line-clamp-4 break-all",children:[de.content.slice(0,400),de.content.length>400?"…":""]})]})]})})(),U.specPath&&s.jsx("div",{className:"text-[10px] text-text-muted font-mono truncate border-t border-border-default pt-2 mt-1",title:U.specPath,children:U.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 (",U.screen?U.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:U.screen||"(empty)"})]})]})]})]})})})}function ij({activeConv:e,clearToken:t=0,terminalRef:n,handleSendChat:a,isSendingChat:r=!1,sendFeedbackMessage:o=null,isVisible:i=!0,isInputActive:c=!0}){var $e;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),[A,T]=l.useState(!1),[L,P]=l.useState(!1),[M,_]=l.useState(!1),[D,B]=l.useState(!1),[R,O]=l.useState(!1),[H,$]=l.useState({width:0,height:0}),[I,W]=l.useState({width:0,height:0}),[F,z]=l.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[Q,ne]=l.useState(null),oe=l.useRef(null),Ce=l.useRef(null),le=l.useRef(!1),U=l.useRef(!1),J=l.useRef(i),ee=l.useRef(0),Y=l.useRef(!1),ve=l.useRef(""),pe=l.useRef(null),te=l.useRef(!1),me=l.useRef(!1),V=l.useRef(null),q=l.useRef(null),se=l.useRef(null),de=32*1024,K=()=>{var he,je,Ne,He;return((je=(he=oe.current)==null?void 0:he.ownerDocument)==null?void 0:je.defaultView)||((He=(Ne=Ce.current)==null?void 0:Ne.ownerDocument)==null?void 0:He.defaultView)||window},fe=he=>{const je=K();return{ownerWindow:je,frameId:je.requestAnimationFrame(he)}},ie=()=>{const he=V.current;if(he){try{he.ownerWindow.cancelAnimationFrame(he.frameId)}catch{}V.current=null}},ue=()=>{const he=q.current;if(he){try{he.ownerWindow.clearTimeout(he.timeoutId)}catch{}q.current=null}},ye=()=>{const he=se.current;if(he){try{he.ownerWindow.clearTimeout(he.timeoutId)}catch{}se.current=null}},Ie=()=>{i&&V.current===null&&(V.current=fe(()=>{re()}))},E=e.tabKey,Z=e.sessionId||"",we=e.daemonId||(($e=e.routeId)==null?void 0:$e.split(":")[0])||e.routeId||"",ge=Xl(e),be=u?ge?Mm:o:g,De=u&&o||null,Me=$C,We=FC,Be=.05,Xe=()=>{const he=I.width,je=I.height;if(!Number.isFinite(H.width)||H.width<=0||!Number.isFinite(H.height)||H.height<=0||!Number.isFinite(he)||he<=0||!Number.isFinite(je)||je<=0)return 1;const Ne=H.width/he,He=H.height/je;return Number(Math.min(We,Math.max(Me,Math.min(Ne,He))).toFixed(2))},at=Xe(),st=le.current&&j>at,X=Number.isFinite(I.width)&&I.width>0?Math.max(H.width,Math.round(I.width*j)):H.width,Le=Number.isFinite(I.height)&&I.height>0?Math.max(H.height,Math.round(I.height*j)):H.height,_e=()=>{fe(()=>{const he=Ce.current;he&&(he.scrollLeft=0,he.scrollTop=he.scrollHeight-he.clientHeight)})},nt=()=>{var he,je;ee.current=0,Y.current=!1,ve.current="",pe.current=null,te.current=!1,me.current=!1,le.current||(U.current=!1,N(1)),V.current!==null&&ie(),m(!1),k("Runtime terminal unavailable"),ye(),ue(),b(null),ne(null),T(!1),x(!1),C(!1),y(!1),(je=(he=n.current)==null?void 0:he.reset)==null||je.call(he)},rt=()=>{var he,je;ee.current=0,Y.current=!1,ve.current="",pe.current=null,te.current=!1,me.current=!1,V.current!==null&&ie(),m(!0),k(""),ye(),ue(),b(null),ne(null),T(!1),x(!1),C(!1),y(!1),(je=(he=n.current)==null?void 0:he.reset)==null||je.call(he)},G=()=>{me.current&&(me.current=!1,fe(()=>{var he,je;(je=(he=n.current)==null?void 0:he.scrollToTop)==null||je.call(he)}))},re=()=>{if(V.current=null,!i)return;const he=ve.current;if(!he)return;const je=he.slice(0,de);ve.current=he.slice(je.length);const Ne=n.current;if(!Ne){ve.current=je+ve.current,Ie();return}Ne.write(je,()=>{if(ve.current.length>0){Ie();return}G()})},ce=he=>{he&&(ve.current+=he,Ie())},xe=(he,je=0,Ne,He,Ue={})=>{var Ke,ut,zt,Et;const dt=!!Ue.force;!dt&&je>0&&ee.current>=je||!dt&&je===0&&Y.current||(ee.current=je,je>0&&C(!0),m(!0),k(""),typeof Ne=="number"&&typeof He=="number"&&Ne>0&&He>0&&((ut=(Ke=n.current)==null?void 0:Ke.resize)==null||ut.call(Ke,Ne,He)),ve.current="",(Et=(zt=n.current)==null?void 0:zt.reset)==null||Et.call(zt),he?ce(he):G())};l.useEffect(()=>{nt()},[Z]),l.useEffect(()=>{var je;if(!Z)return;const he=((je=Ct.onRuntimeEvent)==null?void 0:je.call(Ct,Z,Ne=>{if(!(!Ne||Ne.sessionId!==Z)){if(Ne.type==="runtime_snapshot"){if(!i){pe.current={text:Ne.text||"",seq:Ne.seq||0,cols:Ne.cols,rows:Ne.rows,force:!!Ne.force};return}xe(Ne.text||"",Ne.seq||0,Ne.cols,Ne.rows,{force:!!Ne.force});return}if(Ne.type==="session_output"){Y.current=!0,typeof Ne.seq=="number"&&(ee.current=Math.max(ee.current,Ne.seq),Ne.seq>0&&C(!0)),f.current||m(!0),f.current||k(""),typeof Ne.data=="string"&&ce(Ne.data);return}if(Ne.type==="session_cleared"){if(!i){te.current=!0,ve.current="",pe.current=null;return}rt();return}if(Ne.type==="session_io_error"){const He=typeof Ne.error=="string"&&Ne.error?Ne.error:typeof Ne.reason=="string"&&Ne.reason?Ne.reason:"unknown error";m(!1),k(`Runtime input failed: ${He}`);return}}},we))||(()=>{});return()=>{he()}},[we,Z,n,i]);const Se=async(he={})=>{var je;if(!we||!Z)return{success:!1,error:"daemonId and sessionId are required"};he.preserveStatus||k(he.loadingMessage||"Loading runtime terminal...");try{const Ne=await((je=Ct.requestRuntimeSnapshot)==null?void 0:je.call(Ct,we,Z,{sinceSeq:he.sinceSeq,force:he.force}));return Ne&&Ne.success===!1?(he.preserveStatus||(m(!1),k(`Runtime terminal unavailable: ${Ne.error}`)),Ne):Ne||{success:!0}}catch(Ne){const He=(Ne==null?void 0:Ne.message)||String(Ne);return he.preserveStatus||(m(!1),k(`Runtime terminal unavailable: ${He}`)),{success:!1,error:He}}},Ae=async he=>{var dt,Ke;const je=((dt=oe.current)==null?void 0:dt.ownerDocument)||document,Ne=je.defaultView||window,He=(Ke=Ne.navigator)==null?void 0:Ke.clipboard;if(He!=null&&He.writeText&&Ne.isSecureContext)try{return await He.writeText(he),!0}catch{}let Ue=null;try{return Ue=je.createElement("textarea"),Ue.value=he,Ue.setAttribute("readonly","true"),Ue.style.position="fixed",Ue.style.left="-9999px",Ue.style.top="0",je.body.appendChild(Ue),Ue.focus(),Ue.select(),je.execCommand("copy")}catch{return!1}finally{Ue==null||Ue.remove()}},Ee=he=>{ue(),ne(he);const je=K();q.current={ownerWindow:je,timeoutId:je.setTimeout(()=>{q.current=null,ne(Ne=>Ne===he?null:Ne)},2200)}},Re=he=>{ye(),b(he);const je=K();se.current={ownerWindow:je,timeoutId:je.setTimeout(()=>{se.current=null,b(Ne=>Ne===he?null:Ne)},2200)}},Qe=async()=>{var Ue,dt,Ke,ut;const he=((dt=(Ue=n.current)==null?void 0:Ue.getSelection)==null?void 0:dt.call(Ue))||"",je=((ut=(Ke=n.current)==null?void 0:Ke.getVisibleText)==null?void 0:ut.call(Ke))||"",Ne=he.trimEnd()||je.trimEnd();if(!Ne){Ee("Nothing to copy");return}if(!await Ae(Ne)){Ee("Copy failed");return}Ee(he.trimEnd()?"Copied selection":"Copied visible terminal")},et=he=>{if(!u||!i)return;((p==null?void 0:p(we,Z,he))??!1)||Ee("Terminal input failed")},Je=he=>{et(WC({ctrl:L,alt:M,shift:D},he)),P(!1),_(!1),B(!1)},Oe=async()=>{if(h)return;x(!0),b("Loading older terminal output..."),me.current=!0;const he=await Se({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:u});if(x(!1),(he==null?void 0:he.success)===!1){me.current=!1,b(`Older terminal output unavailable: ${he.error}`);return}y(!0),Re("Older terminal output loaded"),fe(()=>{var je;(je=n.current)==null||je.bumpResize()})};l.useEffect(()=>{var je,Ne;if(!Z)return;we&&((je=Ct.getState)==null?void 0:je.call(Ct,we))==="connected"&&Se();const he=(Ne=Ct.onStateChange)==null?void 0:Ne.call(Ct,(He,Ue)=>{He!==we||Ue!=="connected"||Se()});return()=>{he==null||he()}},[we,Z,n]),l.useEffect(()=>{t&&nt()},[t,E,n]),l.useEffect(()=>{var He,Ue;const he=oe.current,je=(Ue=(He=he==null?void 0:he.ownerDocument)==null?void 0:He.defaultView)==null?void 0:Ue.ResizeObserver;if(!he||!je)return;const Ne=new je(dt=>{const Ke=dt[0];if(!Ke)return;const{width:ut,height:zt}=Ke.contentRect;$(Et=>{const ps=Math.round(ut),Zt=Math.round(zt);return Et.width===ps&&Et.height===Zt?Et:{width:ps,height:Zt}})});return Ne.observe(he),()=>Ne.disconnect()},[]),l.useEffect(()=>{if(le.current)return;const he=Xe();!Number.isFinite(he)||he<=0||N(je=>U.current?he<je-Be?he:je:(U.current=!0,he))},[I.height,I.width,H.height,H.width]),l.useEffect(()=>{st&&_e()},[st,Le,X]),l.useEffect(()=>{var Ne;const he=J.current;if(J.current=i,!i)return;he||y(!1),te.current&&(te.current=!1,rt());const je=pe.current;je&&(pe.current=null,xe(je.text,je.seq,je.cols,je.rows,{force:!!je.force})),we&&Z&&((Ne=Ct.getState)==null?void 0:Ne.call(Ct,we))==="connected"&&Se(),ve.current&&V.current===null&&Ie(),fe(()=>{var He;(He=n.current)==null||He.bumpResize()})},[we,i,Z]),l.useEffect(()=>()=>{V.current!==null&&ie(),ue(),ye()},[]),l.useEffect(()=>{const he=He=>{var dt;const Ue=He.detail;Ue!=null&&Ue.sessionId&&Ue.sessionId!==Z||u&&((dt=n.current)==null||dt.bumpResize())},je=K(),Ne=je===window?[window]:[window,je];for(const He of Ne)He.addEventListener("adhdev:fit-cli-terminal",he);return()=>{for(const He of Ne)He.removeEventListener("adhdev:fit-cli-terminal",he)}},[u,Z,n]);const tt=u&&w&&!v&&(F.atTop||!F.canScroll)||h||!!S;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:oe,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[tt&&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:()=>{Oe()},disabled:!Z||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:[Q&&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:Q}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>O(he=>!he),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:()=>{Qe()},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:()=>T(he=>!he),disabled:!u,"aria-label":d(A?"terminal.closeControlKeys":"terminal.openControlKeys"),"aria-expanded":A,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),A&&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:()=>T(!1),"aria-label":d("terminal.closeControlKeys"),children:"×"})]}),s.jsx("div",{className:"mb-2 grid grid-cols-3 gap-1.5",children:[["Ctrl",L,P],["Alt",M,_],["Shift",D,B]].map(([he,je,Ne])=>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:()=>Ne(He=>!He),children:he},he))}),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:()=>Je("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:()=>Je("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:()=>Je("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:()=>Je("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:()=>Je("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:()=>Je("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:()=>Je("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:()=>et(""),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:()=>Je("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:()=>Je("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:()=>{le.current=!0,N(he=>{const je=Math.max(at,Number((he-.1).toFixed(2)));return je>at&&_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:()=>{le.current=!0,N(he=>{const je=Math.min(We,Number((he+.1).toFixed(2)));return je>at&&_e(),je})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:Ce,className:st?"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:X>0?`${X}px`:"100%",height:Le>0?`${Le}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:I.width>0?`${I.width}px`:"100%",height:I.height>0?`${I.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:j},children:s.jsx(Gp,{ref:n,readOnly:!u||!i,sizingMode:"measured",onViewportMetrics:W,onScrollMetrics:z,onInput:he=>{!u||(p==null||p(we,Z,he))}})})})}),!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(hm,{contextKey:e.tabKey,panelLabel:kt(e),isSending:r,isBusy:!!ge,statusMessage:be,inlineStatusMessage:De,onSend:async he=>ge?!1:a(he),isActive:c&&i,showControlsToggle:!1,animateVisibility:!1}),R&&s.jsx(oj,{activeConv:e,onClose:()=>O(!1)})]})}const lj={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=lj[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:Dt("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 cj=5e3,dj=12e3,uj=15e3;function pj(e){return e==="disconnected"||e==="reconnecting"}function mj({wsStatus:e,showReconnected:t,loginUrl:n,onReconnect:a,reconnectDelayMs:r=cj,reconnectActionDelayMs:o=dj}){const{t:i}=ke(),c=pj(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 A=setTimeout(()=>{f.current=!0,p(!0)},r);return()=>clearTimeout(A)},[r,c]),l.useEffect(()=>{if(!c){m(!1);return}if(o<=0){m(!0);return}m(!1);const A=setTimeout(()=>{m(!0)},o);return()=>clearTimeout(A)},[o,c]),l.useEffect(()=>{e!=="reconnecting"&&k(!1)},[e]),l.useEffect(()=>{if(!g)return;const A=setTimeout(()=>k(!1),uj);return()=>clearTimeout(A)},[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 th({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(Ps,{size:r})})}function hj(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 fj(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 gj(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=hj(e),r=fj(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 ${gj(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 bj({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 xj({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:A,onMarkNotificationUnread:T,onDeleteNotification:L,onOpenGitDialog:P,onOpenMeshGraph:M}){var de;const{t:_}=ke(),{ides:D,p2pStates:B={},usesP2P:R=!0}=Ss(),O=!!e&&gt(e)&&!ht(e),H=!!e&&ht(e),$=!!(e!=null&&e.daemonId)&&!!((de=e==null?void 0:e.coordinator)!=null&&de.meshId),I=c||(e?Sm(e)?"terminal":"chat":null),[W,F]=l.useState(!1),[z,Q]=l.useState(!1),ne=l.useRef(null),oe=l.useRef(null),Ce=l.useRef(null),le=D.filter(K=>K.type==="adhdev-daemon"),U=bj({wsStatus:t,isConnected:n,daemonCount:le.length,p2pStates:B,usesP2P:R}),J=_(U.titleKey),ee=U.subtitleKey?_(U.subtitleKey,U.subtitleParams):null,Y=U.tone==="connected"?"#22c55e":U.tone==="limited"?"#eab308":"#ef4444",ve=U.tone==="connected"?"0 0 4px #22c55e80":U.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",pe=l.useMemo(()=>y.filter(K=>!K.readAt),[y]),te=l.useMemo(()=>y.filter(K=>!!K.readAt),[y]),me=l.useMemo(()=>pe.slice(0,9),[pe]),V=j;l.useEffect(()=>{if(!k)return;const K=fe=>{var ie;(ie=oe.current)!=null&&ie.contains(fe.target)||h(!1)};return document.addEventListener("mousedown",K),()=>document.removeEventListener("mousedown",K)},[k,h]),l.useEffect(()=>{if(!x)return;const K=fe=>{var ie;(ie=Ce.current)!=null&&ie.contains(fe.target)||S(!1)};return document.addEventListener("mousedown",K),()=>document.removeEventListener("mousedown",K)},[x,S]),l.useEffect(()=>{if(!x&&!k)return;const K=fe=>{if(!fe.altKey)return;const ie=fe.code.match(/^Digit([1-9])$/);if(!ie)return;const ue=Number(ie[1])-1,ye=x?u[ue]:void 0,Ie=k?me[ue]:void 0;if(!(!ye&&!Ie)){if(fe.preventDefault(),fe.stopPropagation(),ye){m==null||m(ye),S(!1);return}Ie&&(N(Ie),h(!1))}};return window.addEventListener("keydown",K,!0),()=>window.removeEventListener("keydown",K,!0)},[u,x,k,me,S,h,N,m]),l.useEffect(()=>{const K=u.length;if(ne.current===null){ne.current=K;return}K>ne.current&&Q(!0),ne.current=K},[u.length]);const q=()=>Q(!1),se=K=>{if(!K)return;const fe=a.find(ie=>ie.tabKey===K);fe&&(p==null||p(fe))};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(Ps,{size:18}),s.jsx("span",{className:"header-title-desktop",children:_("dashboard.header.title")}),s.jsx("span",{className:"header-title-mobile",children:e?kt(e):_("dashboard.header.title")}),s.jsx("span",{title:J,"aria-label":J,className:"header-title-status-dot",style:{background:Y,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:Y,boxShadow:ve}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[ee&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",ee]}),b&&s.jsx("button",{type:"button",onClick:b,className:"btn btn-secondary btn-sm ml-2",title:`${_("paneGroup.newSession")}${v!=null&&v.openNewSession?` (${v.openNewSession})`:""}`,"aria-label":_("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:_("dashboard.header.guide"),"aria-label":_("dashboard.header.guideOpen"),children:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),C&&s.jsx("span",{children:_("dashboard.header.guideShort")})]}),e&&(O||H||!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)}),P&&e.git&&e.daemonId&&e.workspacePath?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:_("dashboard.header.openGitStatus"),onClick:()=>P(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"}),$&&M&&s.jsxs("button",{type:"button",onClick:()=>M(e),className:"btn btn-secondary btn-sm dashboard-header-mesh-button",title:_("dashboard.header.openMeshGraph"),children:[s.jsx(cs,{size:14}),s.jsx("span",{className:"hidden lg:inline",children:_("dashboard.header.meshGraph")})]}),(O||H)&&i&&s.jsxs(s.Fragment,{children:[O&&d&&I&&s.jsx(th,{mode:I,onChange:d,compact:!0}),s.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:_(H?"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(Pt,{size:14})})]}),!ht(e)&&s.jsx("button",{onClick:()=>r(e),className:"btn btn-secondary btn-sm",title:_("dashboard.header.chatHistory"),children:s.jsx(Rl,{size:14})}),!O&&!ht(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:_("dashboard.header.remoteControl"),children:s.jsx(us,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:oe,children:[s.jsxs("div",{className:`dashboard-header-hidden${W?" is-drop-target":""}${z?" hidden-spawn-flash":""}${(u??[]).some(_a)?" hidden-generating-spin":""}`,onAnimationEnd:q,ref:Ce,onDragEnter:K=>{K.dataTransfer.types.includes("text/tab-key")&&(K.preventDefault(),F(!0))},onDragOver:K=>{K.dataTransfer.types.includes("text/tab-key")&&(K.preventDefault(),K.dataTransfer.dropEffect="move",F(!0))},onDragLeave:K=>{K.currentTarget.contains(K.relatedTarget)||F(!1)},onDrop:K=>{const fe=K.dataTransfer.getData("text/tab-key");K.preventDefault(),F(!1),se(fe)},children:[s.jsxs("button",{type:"button",onClick:()=>S(!x),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`${_("dashboard.hidden.title")}${v!=null&&v.toggleHiddenTabs?` (${v.toggleHiddenTabs})`:""}. ${_("dashboard.hidden.dragHint")}`,children:[s.jsx(po,{size:16}),u.length>0&&s.jsx("span",{className:`dashboard-header-hidden-badge${z?" 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:_("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:_("dashboard.hidden.resetPanels")}),u.length>0&&f&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{f(),S(!1)},children:_("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:_("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(K=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{m==null||m(K),S(!1)},children:[s.jsxs("span",{className:"dashboard-header-inbox-item-title",children:[_a(K)&&s.jsx(ls,{size:12,thickness:2,color:"success",label:_("dashboard.header.generating")}),kt(K)]}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(K)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(K)+1]}):null,sa(K)]})]},K.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:_("dashboard.hidden.empty")})]})]}),s.jsxs("button",{type:"button",onClick:()=>h(!k),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:_("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:[pe.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:_("dashboard.inbox.unread")}),pe.map(K=>s.jsx(Rd,{notification:K,shortcutIndex:me.indexOf(K)>=0?me.indexOf(K)+1:void 0,onOpen:()=>N(K),onMarkRead:()=>A(K.id),onMarkUnread:()=>T(K.id),onDelete:()=>L(K.id)},K.id))]}),te.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:_("dashboard.inbox.read")}),te.map(K=>s.jsx(Rd,{notification:K,onOpen:()=>N(K),onMarkRead:()=>A(K.id),onMarkUnread:()=>T(K.id),onDelete:()=>L(K.id)},K.id))]}),y.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:_("dashboard.inbox.empty")})]})]})]})]})}function qt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function vj(e,t){return String(e||"")!==String(t||"")}function yj(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&&!lm(i.summaryMetadata).map(d=>d.toLowerCase()).join(`
53
- `).includes(r)))}function wj(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 sh(e,t={}){return wj(yj(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 nh(e,t){return typeof e=="function"?e(t??!1?"launch.resumingSavedHistory":"launch.startingFresh"):e?"Resuming saved history…":"Starting fresh…"}function kj(e){return e?e("launch.startFresh"):"Start fresh"}function Sj(e){return e?e("launch.hostedRuntimeRecoveryDescription"):"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Cj(e){return e?e("launch.openSavedHistory"):"Open saved history"}function jj(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 Nj(e){return e?e("launch.savedHistoryEmpty"):"No saved history found yet."}function Aj(e){return e?e("launch.refreshSavedHistory"):"Refresh saved history"}function Tj(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 ah(e,t){return typeof e=="function"?e("launch.resumeWith",{label:t}):`Resume saved history with ${e}?`}function rh(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 oh({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 _;const{t:h}=ke("common"),x=t.find(D=>D.id===e.routeId),S=(x==null?void 0:x.chats)||[],b=(_=x==null?void 0:x.activeChat)==null?void 0:_.id,w=gt(e)&&!ht(e),[C,v]=l.useState(()=>qt()),[y,j]=l.useState(null),N=c||C,A=String(d||"").trim(),T=D=>{if(p){p(D);return}v(D)},L=l.useMemo(()=>r.map(D=>{const B=String(D.workspace||"").trim();return D.canResume||B||!A?D:{...D,workspace:A,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[A,r]),P=l.useMemo(()=>sh(L,{textQuery:N.textQuery,workspaceQuery:N.workspaceQuery,modelQuery:N.modelQuery,resumableOnly:N.resumableOnly,sortMode:N.sortMode}),[L,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?jj(h):h("historyModal.chatHistory")}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:zC(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(Pt,{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:D=>T({...N,textQuery:D.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:D=>T({...N,workspaceQuery:D.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:D=>T({...N,modelQuery:D.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:D=>T({...N,sortMode:D.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:D=>T({...N,resumableOnly:D.target.checked})}),h("historyModal.resumeReadyOnly")]})]}),P.map(D=>{const B=e.providerSessionId===D.providerSessionId,R=B||!D.canResume||!!i,O=D.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{R||!k||j({kind:"saved",session:D})},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:D.title||h("historyModal.untitledSession")}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:D.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Ed(D.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:D.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:[D.workspace||h("historyModal.workspaceUnknown"),O?h("historyModal.selectedWorkspaceSuffix"):"",Tn(D.summaryMetadata)?` · ${Tn(D.summaryMetadata)}`:"",D.messageCount>0?` · ${h("historyModal.msgCount",{count:D.messageCount})}`:""]}),s.jsx("div",{className:"shrink-0",children:B?h("historyModal.statusActive"):D.canResume?O?h("historyModal.statusResumeSelectedWorkspace"):i===D.providerSessionId?h("historyModal.statusResuming"):h("historyModal.statusResume"):h("historyModal.statusMissingWorkspace")})]})]},D.id)})]}):S.map(D=>s.jsxs("div",{onClick:()=>{D.id!==b&&j({kind:"chat",id:D.id,title:D.title||h("historyModal.untitledSession")})},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${b===D.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===D.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:D.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:[D.id.substring(0,12),"..."]}),b===D.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:h("historyModal.statusActive")})]})]},D.id)),(w&&!o&&P.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(gb,{size:32})}),s.jsx("div",{className:"text-[13px]",children:w?r.length>0?h("historyModal.noMatchingHistory"):Nj(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:Tj(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?Aj(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 D=y;j(null),D.kind==="chat"?(f(e.routeId,D.id),u()):k&&k(D.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 ih({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(Pt,{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 Mj=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 Pj(e,t){return lh(e)||t}function lh(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 Ij(e){return lh(e)||void 0}function Lj(e){return e.sessionId||e.instanceId||e.agentType}function ch(e=[]){const t={};for(const n of e)n.type==="adhdev-daemon"&&(t[n.id]=ds(n,{fallbackId:n.id}));return t}function dh(e,t={}){var a;const n=e.daemonId||((a=e.id)==null?void 0:a.split(":")[0])||e.id;return{machineName:O0(e,t.machineNames),connectionState:t.connectionStates?t.connectionStates[n]||t.defaultConnectionState||"new":t.defaultConnectionState}}function nc(e,t={}){return Rj(e,dh(e,t))}function Rj(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=V0(e.type,{agentName:e.cliName}),d=gt(e)||ht(e)?c:Ot(e.type),p=Pj(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:Ij(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=Mj(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)":"",A=c+N,T=(x=e.activeChat)==null?void 0:x.activeModal,L=T&&Array.isArray(T.buttons)&&T.buttons.length>0,P=Y0(e.activeChat,[{status:e.status,activeModal:(S=e.activeChat)==null?void 0:S.activeModal}],e.agents||[]),M=e.activeChat||{title:"",messages:[]};let _=M.title&&String(M.title).trim()?String(M.title).trim():"";const D=(b=e.activeChat)==null?void 0:b.id,B=e.chats;if(D&&Array.isArray(B)&&B.length>0){const z=B.find(Q=>Q.id===D||Q.id&&String(Q.id)===String(D));z!=null&&z.title&&String(z.title).trim()&&(_=String(z.title).trim())}const R=(gt(e)||ht(e),e.type),O=(gt(e)||ht(e))&&ad(_,A,R)?"":_,H=M.messages||[],$=typeof D=="string"?D.trim():"",I=(gt(e)||ht(e))&&$===String(e.type||"").trim(),W=$&&!I?$:e.providerSessionId,F=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:W,nativeSessionId:v,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:gt(e)&&e.mode||"chat",agentName:A,agentType:R,status:P,title:O,messages:H,resume:e.resume,hostIdeType:!gt(e)&&!ht(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||O||(gt(e)?e.mode==="chat"?A:`Terminal${N}`:A),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:L?T.buttons:void 0,modalMessage:L?T.message:void 0,streamSource:"native",tabKey:Wo(v,e.id),machineName:a,connectionState:r,settings:e.settings,coordinator:F,messageInput:e.messageInput})}if(m&&(gt(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=Q0(v),N=Lj(v),A=`${e.id}:${N}`,T=v.title&&String(v.title).trim()||"",L=ad(T,v.agentName,v.agentType)?"":T,P=v.messages||[];if(!(v.transport==="cdp-webview"||!!v.sessionId||!!v.providerSessionId||P.length>0||y||!!L||!["idle","panel_hidden","disconnected","not_monitored"].includes(j)))continue;const _=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:L,messages:P,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:v.git||e.git,displayPrimary:o||L||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,A),machineName:a,connectionState:r,settings:v.settings,coordinator:_,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 uh(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 Ej(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 _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.thinkingLevelOptions)}function ph(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 Hj(e){var t;return e.category!=="cli"||!uh(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(!Hj(r))continue;const o=uh(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 Dn(e){return e.map(t=>t.type)}function $j(e,t){const n=Va(e),a=t.trim();return!a||n.includes(a)?n:[...n,a]}function Fj(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 Bj={"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 Wj(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 Oj(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(Ab,{size:n,className:a});const i=Bj[r],c=(i==null?void 0:i.monogram)??Oj((t==null?void 0:t.trim())||r.replace(/-cli$/,"")),d=(i==null?void 0:i.hue)??$d[Wj(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 Uj({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($j(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(Fj(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 Gj(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 mh(e,t){const n=Gj(e);return{daemonId:n.daemonId,payload:{...t,...n.targetSessionId&&!t.targetSessionId?{targetSessionId:n.targetSessionId}:{}}}}const hh=[{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:"🏄"}],fh=[{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:"◆"}],gh=[{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:"🟠"}],qj=hh,zj=fh,Kj=gh;function Vj({icon:e,title:t,subtitle:n,badge:a,actions:r,className:o}){return s.jsxs("div",{className:Dt("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(Vj,{icon:e,title:t,subtitle:n,badge:a,actions:r}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Dt("mx-auto flex w-full flex-col gap-4",o,i),children:c})})]})}const ol="adhdev:themechange";function Yj(){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"?Yj():e}function bh(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 Qj(){const e=qn(),t=zn(e);bh(t),Tr(e,t)}function Ls(){const[e,t]=l.useState(qn),[n,a]=l.useState(()=>zn(qn()));l.useEffect(()=>{bh(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 Jj({collapsed:e}){const{preference:t,cycleTheme:n}=Ls(),a=t==="dark"?s.jsx(Mp,{size:16}):t==="light"?s.jsx(Tp,{size:16}):s.jsx(Dp,{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 Xj(){const e=wt.language;return Vn(e)?e:Xp()}function Zj(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(il,{detail:{language:e}}))}function e1(){const[e,t]=l.useState(Xj);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),Zj(a)}},[]);return{language:e,setLanguage:n}}function t1({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 s1({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 n1({collapsed:e,variant:t="sidebar"}){const{language:n,setLanguage:a}=e1(),{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 P=u.current;if(!P)return;const M=P.getBoundingClientRect(),_=m.current,D=Math.max((_==null?void 0:_.offsetWidth)??0,168),B=(_==null?void 0:_.scrollHeight)??un.length*36+12;k(t1({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:D,height:B},variant:t}))},[t]),x=Math.max(0,un.findIndex(P=>P.code===n)),S=un[x]??un[0],b=r("language.label",{defaultValue:"Language"}),w=r("language.select",{defaultValue:"Select language"}),C=P=>`${f}-opt-${P}`,v=l.useCallback(()=>{d(x),i(!0)},[x]),y=l.useCallback((P=!0)=>{var M;i(!1),P&&((M=u.current)==null||M.focus())},[]),j=l.useCallback(P=>{const M=un[P];M&&a(M.code),y()},[a,y]);l.useEffect(()=>{if(!o)return;const P=D=>{var B,R;return!!((B=p.current)!=null&&B.contains(D)||(R=m.current)!=null&&R.contains(D))},M=D=>{P(D.target)||i(!1)},_=D=>{P(D.target)||i(!1)};return document.addEventListener("pointerdown",M,!0),document.addEventListener("focusin",_,!0),()=>{document.removeEventListener("pointerdown",M,!0),document.removeEventListener("focusin",_,!0)}},[o]),l.useLayoutEffect(()=>{if(!o){k(null);return}h();const P=()=>h();return window.addEventListener("resize",P),window.addEventListener("scroll",P,!0),()=>{window.removeEventListener("resize",P),window.removeEventListener("scroll",P,!0)}},[o,h]),l.useEffect(()=>{var P;o&&g&&((P=m.current)==null||P.focus())},[o,g]);const N=P=>{const M=un.length-1;switch(P.key){case"ArrowDown":P.preventDefault(),d(_=>_>=M?0:_+1);break;case"ArrowUp":P.preventDefault(),d(_=>_<=0?M:_-1);break;case"Home":P.preventDefault(),d(0);break;case"End":P.preventDefault(),d(M);break;case"Enter":case" ":P.preventDefault(),j(c);break;case"Escape":P.preventDefault(),y();break;case"Tab":i(!1);break}},A=P=>{o||(P.key==="ArrowDown"||P.key==="ArrowUp"||P.key==="Enter"||P.key===" ")&&(P.preventDefault(),v())},T=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":""}`,L=t==="landing"||!e;return s.jsxs("div",{ref:p,className:"lang-switch",children:[s.jsxs("button",{ref:u,type:"button",className:T,"aria-haspopup":"listbox","aria-expanded":o,"aria-label":`${b}: ${S.label}`,title:`${b}: ${S.label}`,onClick:()=>o?y(!1):v(),onKeyDown:A,children:[s.jsx("span",{className:"nav-icon lang-switch-icon",children:s.jsx(Pp,{size:16})}),L&&s.jsx("span",{className:"lang-switch-label text-xs",children:S.label}),L&&s.jsx(s1,{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((P,M)=>{const _=P.code===S.code,D=M===c;return s.jsxs("li",{id:C(M),role:"option","aria-selected":_,className:`lang-switch-option${D?" is-active":""}${_?" is-selected":""}`,onMouseEnter:()=>d(M),onClick:()=>j(M),children:[s.jsx("span",{className:"lang-switch-check","aria-hidden":"true",children:_?s.jsx(lo,{size:14}):null}),s.jsx("span",{className:"lang-switch-option-label",children:P.label})]},P.code)})}),document.body)]})}const a1=[],r1=[];function Qo(e,t){return e?typeof e=="function"?e(t):e:null}const o1=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(Pt,{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(Jj,{collapsed:u}),s.jsx(n1,{collapsed:u}),Qo(c,t)]})]})});function i1({children:e,brand:t,navItems:n,sidebarSections:a=a1,footerItems:r=r1,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(o1,{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 bt({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:Dt("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:Dt("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:Dt("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:Dt("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 l1={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"},c1={error:Is,warning:Is,success:Ua,info:co};function Mt({variant:e,children:t,onDismiss:n,className:a}){return s.jsxs("div",{className:Dt("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",l1[e],a),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[(()=>{const r=c1[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:Dt("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:Dt("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 d1={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:Dt("btn",d1[t],n==="sm"&&"btn-sm",r),...o})}),u1=l.forwardRef(function({options:t,children:n,className:a,...r},o){return s.jsx("select",{ref:o,className:Dt("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)))})}),p1={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"},m1={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function h1({status:e,label:t,className:n}){const a=t||e;return s.jsxs("span",{className:Dt("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",p1[e],n),children:[s.jsx("span",{className:Dt("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",m1[e])}),a]})}function f1({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:Dt(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:Dt(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?Dt("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 g1({onPrefChange:e}){const{t}=ke("common"),[n,a]=ok(),[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:()=>{um().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(bb,{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 xh(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:xh(n,t)}function Da(e,t){if(e.versionUpdateRequired===!0)return!0;const n=e.version||null;if(!n||!t||!xh(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 b1(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=b1(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 x1(e){return ac(e).channel||null}function Co(e){return!e||!ac(e).channel?null:{}}function vh(e,t={}){const n=Ca(t.targetVersion);return n?`Update to v${n}`:t.fallback||(t.required?"Update now":"Upgrade")}const yh="Cannot update: node update policy unavailable; refresh and try again";async function v1(e,t,n){var r,o,i,c,d,p;const a=Co(n);if(!a)return{state:"error",message:yh};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 y1(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 w1({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(S1,{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 k1(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),a=[...qj,...zj,...Kj].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 S1({ide:e,allIdes:t,sendDaemonCommand:n,onDisconnect:a,onRevokeToken:r}){var D,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=((D=e.machine)==null?void 0:D.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(yh);return}c("upgrading"),p(o("machine.connectedMachines.startingUpgrade"));try{const O=y1(await n(e.id,"daemon_upgrade",R));O.alreadyLatest?(c("done"),p(`Already on v${O.version||"latest"}.`)):O.upgraded||O.success?(c("done"),p(`Upgrade to v${O.version||"latest"} started. Daemon is restarting...`)):(c("error"),p(O.error||"Upgrade failed"))}catch(O){c("error"),p(Xo(O,"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")))}}},A=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")))}}},T="1.0.51",L=Qs(e,T),P=So(e,L),M=Da(e,L),_=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] ${P?"":"bg-bg-secondary"}`,style:P?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",x,!P&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[n&&P&&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${T}`,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:T})}),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(h1,{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&&_>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),_>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[w.map(R=>{const O=k1(R.type),H=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:O.name,size:13}),s.jsx("span",{children:O.name}),H!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${H?"bg-status-online":"animate-pulse"}`,style:H?void 0:{background:"var(--status-warning)"},title:o(H?"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(jb,{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 wj(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 sh(e,t={}){return wj(yj(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 nh(e,t){return typeof e=="function"?e(t??!1?"launch.resumingSavedHistory":"launch.startingFresh"):e?"Resuming saved history…":"Starting fresh…"}function kj(e){return e?e("launch.startFresh"):"Start fresh"}function Sj(e){return e?e("launch.hostedRuntimeRecoveryDescription"):"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Cj(e){return e?e("launch.openSavedHistory"):"Open saved history"}function jj(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 Nj(e){return e?e("launch.savedHistoryEmpty"):"No saved history found yet."}function Aj(e){return e?e("launch.refreshSavedHistory"):"Refresh saved history"}function Tj(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 ah(e,t){return typeof e=="function"?e("launch.resumeWith",{label:t}):`Resume saved history with ${e}?`}function rh(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 oh({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 _;const{t:h}=ke("common"),x=t.find(D=>D.id===e.routeId),S=(x==null?void 0:x.chats)||[],b=(_=x==null?void 0:x.activeChat)==null?void 0:_.id,w=gt(e)&&!ht(e),[C,v]=l.useState(()=>qt()),[y,j]=l.useState(null),N=c||C,A=String(d||"").trim(),T=D=>{if(p){p(D);return}v(D)},L=l.useMemo(()=>r.map(D=>{const B=String(D.workspace||"").trim();return D.canResume||B||!A?D:{...D,workspace:A,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[A,r]),P=l.useMemo(()=>sh(L,{textQuery:N.textQuery,workspaceQuery:N.workspaceQuery,modelQuery:N.modelQuery,resumableOnly:N.resumableOnly,sortMode:N.sortMode}),[L,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?jj(h):h("historyModal.chatHistory")}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:zC(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(Pt,{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:D=>T({...N,textQuery:D.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:D=>T({...N,workspaceQuery:D.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:D=>T({...N,modelQuery:D.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:D=>T({...N,sortMode:D.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:D=>T({...N,resumableOnly:D.target.checked})}),h("historyModal.resumeReadyOnly")]})]}),P.map(D=>{const B=e.providerSessionId===D.providerSessionId,R=B||!D.canResume||!!i,O=D.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{R||!k||j({kind:"saved",session:D})},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:D.title||h("historyModal.untitledSession")}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:D.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Ed(D.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:D.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:[D.workspace||h("historyModal.workspaceUnknown"),O?h("historyModal.selectedWorkspaceSuffix"):"",Tn(D.summaryMetadata)?` · ${Tn(D.summaryMetadata)}`:"",D.messageCount>0?` · ${h("historyModal.msgCount",{count:D.messageCount})}`:""]}),s.jsx("div",{className:"shrink-0",children:B?h("historyModal.statusActive"):D.canResume?O?h("historyModal.statusResumeSelectedWorkspace"):i===D.providerSessionId?h("historyModal.statusResuming"):h("historyModal.statusResume"):h("historyModal.statusMissingWorkspace")})]})]},D.id)})]}):S.map(D=>s.jsxs("div",{onClick:()=>{D.id!==b&&j({kind:"chat",id:D.id,title:D.title||h("historyModal.untitledSession")})},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${b===D.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===D.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:D.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:[D.id.substring(0,12),"..."]}),b===D.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:h("historyModal.statusActive")})]})]},D.id)),(w&&!o&&P.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(gb,{size:32})}),s.jsx("div",{className:"text-[13px]",children:w?r.length>0?h("historyModal.noMatchingHistory"):Nj(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:Tj(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?Aj(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 D=y;j(null),D.kind==="chat"?(f(e.routeId,D.id),u()):k&&k(D.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 ih({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(Pt,{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 Mj=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 Pj(e,t){return lh(e)||t}function lh(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 Ij(e){return lh(e)||void 0}function Lj(e){return e.sessionId||e.instanceId||e.agentType}function ch(e=[]){const t={};for(const n of e)n.type==="adhdev-daemon"&&(t[n.id]=ds(n,{fallbackId:n.id}));return t}function dh(e,t={}){var a;const n=e.daemonId||((a=e.id)==null?void 0:a.split(":")[0])||e.id;return{machineName:O0(e,t.machineNames),connectionState:t.connectionStates?t.connectionStates[n]||t.defaultConnectionState||"new":t.defaultConnectionState}}function nc(e,t={}){return Rj(e,dh(e,t))}function Rj(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=V0(e.type,{agentName:e.cliName}),d=gt(e)||ht(e)?c:Ot(e.type),p=Pj(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:Ij(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=Mj(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)":"",A=c+N,T=(x=e.activeChat)==null?void 0:x.activeModal,L=T&&Array.isArray(T.buttons)&&T.buttons.length>0,P=Y0(e.activeChat,[{status:e.status,activeModal:(S=e.activeChat)==null?void 0:S.activeModal}],e.agents||[]),M=e.activeChat||{title:"",messages:[]};let _=M.title&&String(M.title).trim()?String(M.title).trim():"";const D=(b=e.activeChat)==null?void 0:b.id,B=e.chats;if(D&&Array.isArray(B)&&B.length>0){const z=B.find(Q=>Q.id===D||Q.id&&String(Q.id)===String(D));z!=null&&z.title&&String(z.title).trim()&&(_=String(z.title).trim())}const R=(gt(e)||ht(e),e.type),O=(gt(e)||ht(e))&&ad(_,A,R)?"":_,H=M.messages||[],$=typeof D=="string"?D.trim():"",I=(gt(e)||ht(e))&&$===String(e.type||"").trim(),W=$&&!I?$:e.providerSessionId,F=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:W,nativeSessionId:v,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:gt(e)&&e.mode||"chat",agentName:A,agentType:R,status:P,title:O,messages:H,resume:e.resume,hostIdeType:!gt(e)&&!ht(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||O||(gt(e)?e.mode==="chat"?A:`Terminal${N}`:A),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:L?T.buttons:void 0,modalMessage:L?T.message:void 0,streamSource:"native",tabKey:Wo(v,e.id),machineName:a,connectionState:r,settings:e.settings,coordinator:F,messageInput:e.messageInput})}if(m&&(gt(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=Q0(v),N=Lj(v),A=`${e.id}:${N}`,T=v.title&&String(v.title).trim()||"",L=ad(T,v.agentName,v.agentType)?"":T,P=v.messages||[];if(!(v.transport==="cdp-webview"||!!v.sessionId||!!v.providerSessionId||P.length>0||y||!!L||!["idle","panel_hidden","disconnected","not_monitored"].includes(j)))continue;const _=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:L,messages:P,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:v.git||e.git,displayPrimary:o||L||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,A),machineName:a,connectionState:r,settings:v.settings,coordinator:_,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 uh(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 Ej(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 _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.thinkingLevelOptions)}function ph(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 Hj(e){var t;return e.category!=="cli"||!uh(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(!Hj(r))continue;const o=uh(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 Dn(e){return e.map(t=>t.type)}function $j(e,t){const n=Va(e),a=t.trim();return!a||n.includes(a)?n:[...n,a]}function Fj(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 Bj={"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 Wj(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 Oj(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(Ab,{size:n,className:a});const i=Bj[r],c=(i==null?void 0:i.monogram)??Oj((t==null?void 0:t.trim())||r.replace(/-cli$/,"")),d=(i==null?void 0:i.hue)??$d[Wj(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 Uj({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($j(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(Fj(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 Gj(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 mh(e,t){const n=Gj(e);return{daemonId:n.daemonId,payload:{...t,...n.targetSessionId&&!t.targetSessionId?{targetSessionId:n.targetSessionId}:{}}}}const hh=[{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:"🏄"}],fh=[{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:"◆"}],gh=[{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:"🟠"}],qj=hh,zj=fh,Kj=gh;function Vj({icon:e,title:t,subtitle:n,badge:a,actions:r,className:o}){return s.jsxs("div",{className:Dt("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(Vj,{icon:e,title:t,subtitle:n,badge:a,actions:r}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Dt("mx-auto flex w-full flex-col gap-4",o,i),children:c})})]})}const ol="adhdev:themechange";function Yj(){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"?Yj():e}function bh(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 Qj(){const e=qn(),t=zn(e);bh(t),Tr(e,t)}function Ls(){const[e,t]=l.useState(qn),[n,a]=l.useState(()=>zn(qn()));l.useEffect(()=>{bh(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 Jj({collapsed:e}){const{preference:t,cycleTheme:n}=Ls(),a=t==="dark"?s.jsx(Mp,{size:16}):t==="light"?s.jsx(Tp,{size:16}):s.jsx(Dp,{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 Xj(){const e=wt.language;return Vn(e)?e:Xp()}function Zj(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(il,{detail:{language:e}}))}function e1(){const[e,t]=l.useState(Xj);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),Zj(a)}},[]);return{language:e,setLanguage:n}}function t1({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 s1({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 n1({collapsed:e,variant:t="sidebar"}){const{language:n,setLanguage:a}=e1(),{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 P=u.current;if(!P)return;const M=P.getBoundingClientRect(),_=m.current,D=Math.max((_==null?void 0:_.offsetWidth)??0,168),B=(_==null?void 0:_.scrollHeight)??un.length*36+12;k(t1({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:D,height:B},variant:t}))},[t]),x=Math.max(0,un.findIndex(P=>P.code===n)),S=un[x]??un[0],b=r("language.label",{defaultValue:"Language"}),w=r("language.select",{defaultValue:"Select language"}),C=P=>`${f}-opt-${P}`,v=l.useCallback(()=>{d(x),i(!0)},[x]),y=l.useCallback((P=!0)=>{var M;i(!1),P&&((M=u.current)==null||M.focus())},[]),j=l.useCallback(P=>{const M=un[P];M&&a(M.code),y()},[a,y]);l.useEffect(()=>{if(!o)return;const P=D=>{var B,R;return!!((B=p.current)!=null&&B.contains(D)||(R=m.current)!=null&&R.contains(D))},M=D=>{P(D.target)||i(!1)},_=D=>{P(D.target)||i(!1)};return document.addEventListener("pointerdown",M,!0),document.addEventListener("focusin",_,!0),()=>{document.removeEventListener("pointerdown",M,!0),document.removeEventListener("focusin",_,!0)}},[o]),l.useLayoutEffect(()=>{if(!o){k(null);return}h();const P=()=>h();return window.addEventListener("resize",P),window.addEventListener("scroll",P,!0),()=>{window.removeEventListener("resize",P),window.removeEventListener("scroll",P,!0)}},[o,h]),l.useEffect(()=>{var P;o&&g&&((P=m.current)==null||P.focus())},[o,g]);const N=P=>{const M=un.length-1;switch(P.key){case"ArrowDown":P.preventDefault(),d(_=>_>=M?0:_+1);break;case"ArrowUp":P.preventDefault(),d(_=>_<=0?M:_-1);break;case"Home":P.preventDefault(),d(0);break;case"End":P.preventDefault(),d(M);break;case"Enter":case" ":P.preventDefault(),j(c);break;case"Escape":P.preventDefault(),y();break;case"Tab":i(!1);break}},A=P=>{o||(P.key==="ArrowDown"||P.key==="ArrowUp"||P.key==="Enter"||P.key===" ")&&(P.preventDefault(),v())},T=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":""}`,L=t==="landing"||!e;return s.jsxs("div",{ref:p,className:"lang-switch",children:[s.jsxs("button",{ref:u,type:"button",className:T,"aria-haspopup":"listbox","aria-expanded":o,"aria-label":`${b}: ${S.label}`,title:`${b}: ${S.label}`,onClick:()=>o?y(!1):v(),onKeyDown:A,children:[s.jsx("span",{className:"nav-icon lang-switch-icon",children:s.jsx(Pp,{size:16})}),L&&s.jsx("span",{className:"lang-switch-label text-xs",children:S.label}),L&&s.jsx(s1,{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((P,M)=>{const _=P.code===S.code,D=M===c;return s.jsxs("li",{id:C(M),role:"option","aria-selected":_,className:`lang-switch-option${D?" is-active":""}${_?" is-selected":""}`,onMouseEnter:()=>d(M),onClick:()=>j(M),children:[s.jsx("span",{className:"lang-switch-check","aria-hidden":"true",children:_?s.jsx(lo,{size:14}):null}),s.jsx("span",{className:"lang-switch-option-label",children:P.label})]},P.code)})}),document.body)]})}const a1=[],r1=[];function Qo(e,t){return e?typeof e=="function"?e(t):e:null}const o1=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(Pt,{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(Jj,{collapsed:u}),s.jsx(n1,{collapsed:u}),Qo(c,t)]})]})});function i1({children:e,brand:t,navItems:n,sidebarSections:a=a1,footerItems:r=r1,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(o1,{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 bt({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:Dt("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:Dt("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:Dt("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:Dt("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 l1={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"},c1={error:Is,warning:Is,success:Ua,info:co};function Mt({variant:e,children:t,onDismiss:n,className:a}){return s.jsxs("div",{className:Dt("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",l1[e],a),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[(()=>{const r=c1[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:Dt("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:Dt("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 d1={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:Dt("btn",d1[t],n==="sm"&&"btn-sm",r),...o})}),u1=l.forwardRef(function({options:t,children:n,className:a,...r},o){return s.jsx("select",{ref:o,className:Dt("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)))})}),p1={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"},m1={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function h1({status:e,label:t,className:n}){const a=t||e;return s.jsxs("span",{className:Dt("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",p1[e],n),children:[s.jsx("span",{className:Dt("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",m1[e])}),a]})}function f1({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:Dt(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:Dt(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?Dt("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 g1({onPrefChange:e}){const{t}=ke("common"),[n,a]=ok(),[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:()=>{um().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(bb,{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 xh(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:xh(n,t)}function Da(e,t){if(e.versionUpdateRequired===!0)return!0;const n=e.version||null;if(!n||!t||!xh(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 b1(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=b1(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 x1(e){return ac(e).channel||null}function Co(e){return!e||!ac(e).channel?null:{}}function vh(e,t={}){const n=Ca(t.targetVersion);return n?`Update to v${n}`:t.fallback||(t.required?"Update now":"Upgrade")}const yh="Cannot update: node update policy unavailable; refresh and try again";async function v1(e,t,n){var r,o,i,c,d,p;const a=Co(n);if(!a)return{state:"error",message:yh};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 y1(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 w1({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(S1,{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 k1(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),a=[...qj,...zj,...Kj].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 S1({ide:e,allIdes:t,sendDaemonCommand:n,onDisconnect:a,onRevokeToken:r}){var D,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=((D=e.machine)==null?void 0:D.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(yh);return}c("upgrading"),p(o("machine.connectedMachines.startingUpgrade"));try{const O=y1(await n(e.id,"daemon_upgrade",R));O.alreadyLatest?(c("done"),p(`Already on v${O.version||"latest"}.`)):O.upgraded||O.success?(c("done"),p(`Upgrade to v${O.version||"latest"} started. Daemon is restarting...`)):(c("error"),p(O.error||"Upgrade failed"))}catch(O){c("error"),p(Xo(O,"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")))}}},A=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")))}}},T="1.0.52",L=Qs(e,T),P=So(e,L),M=Da(e,L),_=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] ${P?"":"bg-bg-secondary"}`,style:P?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",x,!P&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[n&&P&&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${T}`,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:T})}),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(h1,{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&&_>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),_>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[w.map(R=>{const O=k1(R.type),H=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:O.name,size:13}),s.jsx("span",{children:O.name}),H!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${H?"bg-status-online":"animate-pulse"}`,style:H?void 0:{background:"var(--status-warning)"},title:o(H?"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(jb,{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:A,onCancel:()=>m(null)})]})}const C1=[{id:"dark",label:"Dark",icon:Mp},{id:"light",label:"Light",icon:Tp},{id:"system",label:"System",icon:Dp}];function j1(){const{preference:e,setPreference:t}=Ls();return s.jsx("div",{className:"flex gap-2",children:C1.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 N1(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 A1(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}=A1(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 wh(e){const t=N1(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},T1=[{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"}}}],kh="adhdev-chat-theme",Sh="adhdev-chat-theme-custom";function Mr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(kh)||"ember"}catch{return"ember"}}function bs(e){try{const t=localStorage.getItem(Sh);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(Sh,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 M1={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Pa(e,t){var r;const n=(r=M1[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",wh(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",wh(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(kh,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=Cn()?"dark":"light";Sn(bs(t))}else rc(),Pa(e,Cn()?"dark":"light")}function P1(){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(),Pa(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 I1({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 L1(){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")):Pa(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")):Pa(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(),Pa(t,a?"dark":"light"))},[t,a]),l.useEffect(()=>{i(bs(a?"dark":"light"))},[a]);const c=p=>{n(p),D1(p)},d=[...T1,{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(I1,{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 R1(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 E1(e){try{localStorage.setItem(oc,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(dl,{detail:e}))}function _1(){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(Ps,{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),E1(n?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const H1="Choose a preset or create a fully custom theme. Custom themes control the entire app — backgrounds, text, borders, and chat bubbles.",$1="Choose whether the dashboard opens like a chat app on phones or keeps the full workspace layout.";function F1({themeDescription:e=H1,mobileDescription:t=$1,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(j1,{})]}),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(L1,{})]}),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(_1,{})]})]})}const ei=new Map,zd=new Map;function B1(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 W1(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 Ch(){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)??GS,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=B1(p);if(!u)return;const m=n().find(g=>g.id===a),f=W1(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 O1(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 U1(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=O1(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 G1(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)},KS):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 q1(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function jh(e){const{sendData:t}=St(),[n,a]=l.useState({});return l.useEffect(()=>{const r=q1(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 z1(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function K1(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 V1(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 Y1({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(!z1(o))throw new Error(K1(o));return}await V1(e.sessionId,t,r)}function Nh(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(()=>vx(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=zp(k.prompt,b);d(!0),u(null);try{const C=(a==null?void 0:a[k.daemonId])==="connected"||n===!0;await Y1({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 Ah(e){return e instanceof Error?e.message:String(e||"")}function Q1(e){const t=Ah(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 J1(e){const t=Ah(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Th({conversation:e,mode:t,ides:n,sendDaemonCommand:a,setCliViewModeOverrides:r}){if(!e||!gt(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:Ds(e),mode:t})}catch(c){const d=J1(c);i&&!d&&r(p=>{const u={...p};return o===Z1(n,i)?delete u[i]:u[i]=o,u}),Q1(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 X1(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 Z1(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 eN({visibleConversations:e,clearedTabs:t,setClearedTabs:n,setActionLogs:a,isConversationMuted:r}){l.useEffect(()=>{um()},[]);const o=l.useMemo(()=>e.map(i=>({id:i.tabKey,name:Xm(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 uk(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 Mh(e){return jn(e)||e.lastUpdated||0}function Dh(e,t,n=Mh){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 tN(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!pl(e)&&!e.title.trim()}function sN(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:Dh(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=sN(r);return a?o&&tN(a)?o:a:o||n[0]||null}function nN(e){const t=e.filter(r=>r.type!=="adhdev-daemon"),n=new Set;for(const r of t){if(!Ji(r))continue;const o=rm(r);o&&n.add(o)}const a=new Map;for(const r of t){const o=W0(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,aN(u,u===r?i:r))}return Array.from(a.values())}function aN(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 rN(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?rN(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 oN(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 iN(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 lN(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 cN(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function dN(e){const t=cN(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 uN({ides:e,connectionStates:t,clearedTabs:n}){const a=l.useMemo(()=>nN(e),[e]),r=l.useMemo(()=>Yp(e),[e]),o=l.useMemo(()=>ch(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 A of a){const{connectionState:T="new",machineName:L}=dh(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),P=oN(A),M=p.current.get(A.id);if(M&&M.ide===A&&M.sourceSignature===P&&M.connectionState===T&&M.machineName===L){C.set(A.id,M),v.push(...M.conversations);continue}const _=nc(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),D={ide:A,sourceSignature:P,connectionState:T,machineName:L,conversations:_};C.set(A.id,D),v.push(..._)}p.current=C;const y=new Map,j=A=>{const T=dN(A),L=u.current.get(A.tabKey);if(L&&L.signature===T)return y.set(A.tabKey,L),L.timestamp;const P={signature:T,timestamp:Mh(A)||(L==null?void 0:L.timestamp)||0};return y.set(A.tabKey,P),P.timestamp},N=[...v].sort((A,T)=>Dh(A,T,j));return u.current=y,N},[a,t,o]),f=l.useMemo(()=>{const C=iN(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(()=>lN(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 pN({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 mN({ides:e,sendDaemonCommand:t,setToasts:n,resolveConversationByTarget:a}){l.useEffect(()=>{xt.setIdes(e)},[e]),l.useEffect(()=>{xt.setResolveAction((r,o,i)=>{t(r,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const r=xt.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=Vm.on("status_event",o=>{xt.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 hN="adhdev_dashboardLayout_v1",fN="adhdev_dashboardDockview_v1",gN="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 bN(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Ph(e){return`${hN}:${e}`}function xN(e){const t=Ph(e);return lc(t,null)}function vN(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 Ih(e){return`${fN}:${e}`}function yN(e){const t=Ih(e);return lc(t,null)}function wN(e,t){try{const n=Ih(e);if(!t){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Lh(e){return`${gN}:${e}`}function kN(e){const t=Lh(e);return lc(t,{})}function SN(e,t){try{const n=Lh(e);if(Object.keys(t).length===0){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function CN(){return{groupAssignments:[...xa.groupAssignments],focusedGroup:xa.focusedGroup,groupActiveTabIds:{...xa.groupActiveTabIds},groupTabOrders:{...xa.groupTabOrders},groupSizes:[...xa.groupSizes]}}function jN(e,t){return e?e.length===t.length&&e.every((n,a)=>n===t[a]):t.length===0}function NN(){const[e]=l.useState(()=>bN(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 A=xN(e)??CN();n(new Map(A.groupAssignments)),r(A.focusedGroup),i(A.groupActiveTabIds),d(A.groupTabOrders),u(A.groupSizes),k(!0)},[g,e]);l.useEffect(()=>{g&&vN(e,{groupAssignments:[...t.entries()],focusedGroup:a,groupActiveTabIds:o,groupTabOrders:c,groupSizes:p})},[g,e,t,a,o,c,p]),l.useEffect(()=>{const A=window.matchMedia("(max-width: 767px)"),T=L=>f(L.matches);return A.addEventListener("change",T),()=>A.removeEventListener("change",T)},[]);const x=l.useCallback(A=>{n(A)},[]),S=l.useCallback(A=>{r(A)},[]),b=l.useCallback(A=>{i(A)},[]),w=l.useCallback(A=>{d(A)},[]),C=l.useCallback(A=>{u(A)},[]),v=l.useCallback(A=>{S(A)},[S]),y=l.useCallback((A,T)=>{i(L=>(L[A]??null)===(T??null)?L:{...L,[A]:T})},[]),j=l.useCallback((A,T)=>{d(L=>{const P=L[A];return jN(P,T)?L:{...L,[A]:T}})},[]),N=l.useCallback((A,T)=>{const L=T.get(A)??0;return y(L,A),v(L),L},[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 AN(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 TN({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||AN(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 Rh({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)}),pC(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 MN(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 PN(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 IN(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 LN({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[A,T]of j)T!==v&&(T>v?N.set(A,T-1):N.set(A,T));return N}),i(y=>{if(y.length<=1)return[];const j=[...y];j.splice(v,1);const N=j.reduce((A,T)=>A+T,0);return N>0?j.map(A=>A/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,A=j.offsetWidth,T=o.length===g?[...o]:Zd(g),L=M=>{const D=(M.clientX-N)/A*100,B=[...T];B[v]=Math.max(15,T[v]+D),B[v+1]=Math.max(15,T[v+1]-D),i(B)},P=()=>{document.removeEventListener("mousemove",L),document.removeEventListener("mouseup",P),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",L),document.addEventListener("mouseup",P)},[o,g,i]),b=l.useCallback((v,y,j)=>{if(g>=4)return;const N=j==="left"?y:y+1;t(A=>{const T=cr(A,p).assignments,L=new Map;for(const P of d){const M=T.get(P.tabKey)??0,_=M>=N?M+1:M;_>0&&L.set(P.tabKey,_)}return N>0&&L.set(v,N),L}),i(A=>{const T=A.length===g?[...A]:Zd(g),L=T[y]??100/g,P=Math.max(15,L/2),M=Math.max(15,L/2),_=[...T];_[y]=P,_.splice(N,0,M);const D=_.reduce((B,R)=>B+R,0);return _.map(B=>B/D*100)}),a(A=>{const T=Xd(A,N);return T[N]=v,T}),r(A=>{const T=Xd(A,N);return T[N]=[v],T}),n(N)},[g,t,p,d,i,a,r,n]);l.useEffect(()=>{MN(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:PN(j,y,v);return j===N?j:N}),i(j=>{const N=c?[]:IN(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 RN({ides:e,sendDaemonCommand:t}){const n="1.0.51",a=l.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:So(m,Qs(m,n))).sort((m,f)=>Number(Da(f,Qs(f,n)))-Number(Da(m,Qs(m,n)))),[n,e]),r=l.useMemo(()=>a.some(m=>Da(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 Eh=80;function Dr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function EN(e){return{...e,createdAt:Dr(e.createdAt),updatedAt:Dr(e.updatedAt,e.createdAt),lastEventAt:Dr(e.lastEventAt,e.updatedAt||e.createdAt)}}function _N(e){const t=am(e);return t==="unknown:"?e.id:t}function HN(e){return[e.type,nm(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function $N(e,t=Eh){const n=new Map;for(const a of e){if(a.deletedAt)continue;const r=_N(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 FN(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=Dr(r.lastMessageAt||(o==null?void 0:o.lastUpdated)||r.lastUpdated,n),p=HN({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(EN({id:p,dedupKey:p,type:c,routeId:r.routeId,machineId:r.daemonId||r.routeId,sessionId:r.sessionId,providerSessionId:r.providerSessionId,tabKey:r.tabKey,title:jm(r),preview:CS(r),createdAt:d,updatedAt:d,lastEventAt:d}))}return $N(a)}function BN(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function WN(e){const{conversations:t,liveSessionInboxState:n,maxItems:a=Eh}=e,r=l.useMemo(()=>FN(t,n).slice(0,Math.max(0,a)),[t,n,a]),o=l.useMemo(()=>BN(r),[r]);return{notifications:r,unreadCount:o}}function ON({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 UN(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=UN(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 GN(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 qN(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=qN(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 _h(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 zN(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 Hh(e){return bo(e)||e.tabKey||e.routeId||null}function $h(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 Fh(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 KN(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function VN(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 YN(e,t,n){if(t.event!=="agent:generating_completed")return null;const a=Fh(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&&!KN(u,p))return null}return VN(t,n)}function tu(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function QN({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"||Fh(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=$h({entrySessionId:p.sessionId,entryInstanceId:p.instanceId,entryRouteId:p.id,conversations:t});u&&(i(),n(u))},[i,t,e,n,a]),l.useEffect(()=>xt.onStatusEvent(d=>{const p=o.current;if(!p)return;const u=YN(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 JN(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 XN(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 ZN({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=JN(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=XN(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 A=String((j==null?void 0:j.code)||(y==null?void 0:y.code)||""),T=zN((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:A||void 0,manualSetup:T}}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 Th({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 eA(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 tA(e,t,n=Date.now()){return!e||!eA(t)?null:{tabKey:e,nonce:n}}function sA({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=NS(h);return b?S.set("activeTab",b):S.delete("activeTab"),S},{replace:!0})},[i]),k=l.useCallback((h,x)=>{const S=tA(h,x);S&&u(S)},[]);return{activeConv:m,openDesktopConversation:g,requestScrollToBottom:k,scrollToBottomRequest:p,setDesktopActiveTab:f}}function nA(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 aA(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 rA({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=aA({tabKey:e.tabKey,historySessionId:bo(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:jn(e),liveState:u}),f=m.autoReadKey,g=nA({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 oA({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:n,ides:a,sendDaemonCommand:r,updateRouteChats:o,setToasts:i,setClearedTabs:c,setSearchParams:d}){var O;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&&gt(v)&&!ht(v),j=l.useMemo(()=>{if(!v||!y)return null;const H=v.daemonId||v.routeId||"",$=Ds(v),I=ni(v);return`${H}:${$}:${v.providerSessionId||""}:${I}`},[v,y]),N=l.useMemo(()=>!v||!y?"":ni(v),[v,y]),{isCreatingChat:A,isRefreshingHistory:T,handleSwitchSession:L,handleNewChat:P,handleRefreshHistory:M}=Rh({sendDaemonCommand:r,activeConv:v,chats:(O=a.find(H=>H.id===(v==null?void 0:v.routeId)))==null?void 0:O.chats,updateRouteChats:o,setToasts:i,setClearedTabs:c}),_=l.useCallback(()=>{m(!0)},[]),D=l.useCallback(()=>{m(!1)},[]),B=l.useCallback(async()=>{if(!(!v||!y||x)){S(!0);try{const H=v.daemonId||v.routeId,$=Ds(v),I=ni(v),W=await r(H,"list_saved_sessions",{agentType:$,providerType:$,kind:"cli",limit:50,...v.providerSessionId?{providerSessionId:v.providerSessionId}:{},...I?{workspace:I}:{}}),F=(W==null?void 0:W.result)??W;g(Array.isArray(F==null?void 0:F.sessions)?F.sessions:[])}catch(H){console.error("Refresh saved sessions failed",H),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 H=>{if(!v||!y||!H.providerSessionId||!H.workspace)return;const $=v.daemonId||v.routeId,I=Ds(v);try{w(H.providerSessionId);const W=await p($,{cliType:I,dir:H.workspace,resumeSessionId:H.providerSessionId,initialModel:cm(H.summaryMetadata,"model",{preferShortValue:!0})||void 0}),F=(W==null?void 0:W.result)??W,z=typeof(F==null?void 0:F.sessionId)=="string"?F.sessionId:typeof(F==null?void 0:F.id)=="string"?F.id:"";z&&d(Q=>{const ne=new URLSearchParams(Q);return ne.set("activeTab",z),ne},{replace:!0}),D()}catch(W){console.error("Resume saved session failed",W)}finally{w(null)}},[D,v,y,r,d]);return{historyModalOpen:u,openHistoryModal:_,closeHistoryModal:D,historyTargetConv:v,isSavedSessionHistoryTarget:y,isHistoryCreatingChat:A,isHistoryRefreshingHistory:T,handleHistorySwitchSession:L,handleHistoryNewChat:P,handleHistoryRefresh:M,savedHistorySessions:f,savedHistoryFilters:k,setSavedHistoryFilters:h,missingWorkspaceResumePath:N,isSavedHistoryLoading:x,resumingSavedHistorySessionId:b,handleRefreshSavedHistory:B,handleResumeSavedHistorySession:R}}function iA({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&&!gt(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 lA({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}=iA({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||!gt(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||!gt(N)&&!ht(N)){v();return}S(!1);try{const A=Ds(N),T=N.routeId||N.daemonId||"";await p(T,"stop_cli",{cliType:A,targetSessionId:N.sessionId,mode:j,...yo(N)})}catch(A){console.error("Stop CLI failed:",A)}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=jh(t),A=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(Qp,{activeConv:A,onModalButton:i}),A.transport!=="pty"&&A.transport!=="acp"&&A.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,A.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(ij,{activeConv:A,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:A,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:A,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 cA({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:Cm(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=jS(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=Hh(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(ub,{size:12}),s.jsxs("span",{children:[x.pending," Pending"]})]})]})}function dA({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 P,M;const j=l.useRef(null),N=gt(e)&&!t,A=N&&x==="terminal",T=!!e.daemonId&&!!((P=e.coordinator)!=null&&P.meshId||(M=e.settings)!=null&&M.meshCoordinatorFor),L=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 ${L} 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(cA,{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(th,{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(Pt,{size:14})}),T&&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:A,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 uA(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Bh(){const[e,t]=l.useState("unix"),[n,a]=l.useState("powershell"),[r,o]=l.useState(!1),i=e==="unix"?"unix":n;l.useEffect(()=>{t(uA())},[]);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 Wh({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:Ps}];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 pA({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=Jm(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",A=g?"text-text-muted opacity-80":"text-text-muted",T=!f&&!k,L=Ym(e.conversation),P="text-[color:var(--status-warning)]",M=_=>{if(!c)return;_.preventDefault(),_.stopPropagation();const D=c==null?void 0:c(e.conversation);Promise.resolve(D).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)}),L&&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:_=>{_.preventDefault(),_.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:`${P} 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:P,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:[T&&s.jsx("span",{className:`mr-0.5 text-[11px] font-medium shrink-0 ${A}`,children:Vp(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:_=>{_.preventDefault(),_.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(Ap,{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:_=>{_.preventDefault(),_.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:_=>{_.preventDefault(),_.stopPropagation(),o()},"aria-label":u("mobileInbox.stopSessionAria",{title:S}),title:u("mobileInbox.stopSessionTitle"),children:s.jsx(Pt,{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 mA({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:A}){const{t:T}=ke(),[L,P]=l.useState(null),M=w==="disconnected"||w==="reconnecting"||w==="offline"||w==="auth_failed",_=!M&&!C,D=!M&&!(v??C),B=i.length>0,R=t.length>0||n.length>0||a.length>0||r.length>0,O=T(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),H=y?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",$=y?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",I=l.useCallback(async z=>{const Q=wn(z);if(!Q)return;const ne=Array.isArray(z.messages)?z.messages:[],oe=Pm({activeConv:z,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(Q,"get_chat_debug_bundle",{...yn(z),delivery:"daemon_file",frontendSnapshot:oe}),le=Ma(Ce),U=Rm(le),J=await Lm(U);J==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),xt.showToast(Im(le,{locatorCopyStatus:J}),J==="failed"?"warning":"success")},[d,p]),W=j||I,F=l.useCallback(()=>{L&&(f==null||f(L),P(null))},[L,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 ${H}`,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:O}),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] ${$}`,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:T(w==="offline"?"mobileInbox.networkOffline":w==="auth_failed"?"mobileInbox.sessionExpired":"mobileInbox.reconnecting"),subtitle:T(w==="offline"?"mobileInbox.waitingForNetwork":w==="auth_failed"?"mobileInbox.pleaseLogInAgain":"mobileInbox.restoringConnection")}):_?s.jsx(mn,{icon:s.jsx(ls,{size:32}),title:T("mobileInbox.loading"),subtitle:T("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:T(y?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:T(y?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!y&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(Bh,{})})}):s.jsx(Fn,{children:i.map((z,Q)=>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] ${Q>0?"border-t border-border-subtle/70":""}`,onClick:()=>x(z.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(z.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:z.label}),s.jsxs("span",{className:"flex items-center gap-2 text-[11px] font-medium text-text-muted shrink-0",children:[s.jsx(su,{count:z.generatingCount,label:T("mobileInbox.generatingCount",{count:z.generatingCount})}),z.unread>0?s.jsx("span",{className:"text-accent-primary",children:T("mobileInbox.newCount",{count:z.unread})}):z.total>0?T("mobileInbox.chatCount",{count:z.total}):T("mobileInbox.idle")]})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:z.subtitle}),z.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[T("mobileInbox.chatCount",{count:z.total}),z.unread>0?T("mobileInbox.unreadSuffix",{count:z.unread}):"",z.generatingCount>0?T("mobileInbox.collapsedGeneratingSuffix",{count:z.generatingCount}):""]}):z.generatingCount>0?s.jsx("div",{className:"text-[13px] text-accent-primary mt-0.5 font-medium",children:T("mobileInbox.generatingCount",{count:z.generatingCount})}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:T("mobileInbox.noActiveChats")})]})]},z.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:T("mobileInbox.needsAttention"),className:"mb-0"}),s.jsx(Fn,{children:t.map((z,Q)=>s.jsx("div",{className:Q>0?"border-t border-border-subtle/70":"",children:s.jsx(ur,{item:z,type:"needs_attention",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>P(z.conversation):void 0,onRequestStopCli:k?()=>k(z.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:W,isMuted:N==null?void 0:N(z.conversation),onToggleMute:A?()=>A(z.conversation):void 0})},z.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:T("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),s.jsx(Fn,{children:n.map((z,Q)=>s.jsx("div",{className:Q>0?"border-t border-border-subtle/70":"",children:s.jsx(ur,{item:z,type:"task_complete",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>P(z.conversation):void 0,onRequestStopCli:k?()=>k(z.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:W,isMuted:N==null?void 0:N(z.conversation),onToggleMute:A?()=>A(z.conversation):void 0})},z.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:T("mobileInbox.workingNow"),className:"mb-0 mt-2"}),s.jsx(Fn,{children:a.map((z,Q)=>s.jsx("div",{className:Q>0?"border-t border-border-subtle/70":"",children:s.jsx(ur,{item:z,type:"working",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>P(z.conversation):void 0,onRequestStopCli:k?()=>k(z.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:W,isMuted:N==null?void 0:N(z.conversation),onToggleMute:A?()=>A(z.conversation):void 0})},z.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:T("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),r.length>0?s.jsx(Fn,{children:r.map((z,Q)=>s.jsx("div",{className:Q>0?"border-t border-border-subtle/70":"",children:s.jsx(ur,{item:z,type:"earlier",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>P(z.conversation):void 0,onRequestStopCli:k?()=>k(z.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:W,isMuted:N==null?void 0:N(z.conversation),onToggleMute:A?()=>A(z.conversation):void 0})},z.conversation.tabKey))}):R?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:T("mobileInbox.allCaughtUp")}):M?s.jsx(mn,{icon:s.jsx(ls,{size:28}),title:T("mobileInbox.connecting"),subtitle:T("mobileInbox.connectingSubtitle")}):D?s.jsx(mn,{icon:s.jsx(ls,{size:28}),title:T("mobileInbox.loading"),subtitle:T("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(Ps,{size:20})}),title:T("mobileInbox.noConversations"),subtitle:T("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":T("paneGroup.newSession"),title:T("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:T("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:T("mobileInbox.noMachinesConnected"),subtitle:T("mobileInbox.noMachinesSubtitle")})]}),e==="chats"&&o.length>0&&(()=>{const z=jx(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:T("mobileInbox.hiddenTabs")}),s.jsx(su,{count:z,label:T("mobileInbox.generatingCount",{count:z})})]}),s.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[T("mobileInbox.collapsedCount",{count:o.length}),z>0?T("mobileInbox.collapsedGeneratingSuffix",{count:z}):""]})]}),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:T("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":T("paneGroup.newSession"),title:T("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"})]})}),L&&s.jsx(pA,{conversation:L,onCancel:()=>P(null),onConfirm:F}),s.jsx(Wh,{section:e,onSectionChange:b})]})}function hA(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 Oh(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=hA(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=GN(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(Pt,{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(Pt,{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(Np,{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 Uh(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 fA(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function gA(e){return[fA(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function bA(e){return e.lastLaunchedAt?qa(e.lastLaunchedAt):""}function Gh(e){return{metaText:gA(e),updatedLabel:bA(e)}}function oi(e,t,n){return e?"ide":t>0?"cli":n>0?"acp":null}function xA({selectedMachineEntry:e,cliProviders:t,acpProviders:n,machineAction:a,onBrowseDirectory:r,onListSavedSessions:o}){var Be,Xe,at,st;const i=ca(),[c,d]=l.useState(!1),p=(((Be=e.detectedIdes)==null?void 0:Be.length)||0)>0,u=l.useMemo(()=>(e.workspaces||[]).map(X=>({id:X.id,path:X.path,label:X.label})),[e]),m=e.defaultWorkspaceId||null,[f,g]=l.useState(m||((Xe=u[0])==null?void 0:Xe.id)||""),[k,h]=l.useState(""),[x,S]=l.useState(""),[b,w]=l.useState([]),[C,v]=l.useState(!1),[y,j]=l.useState(""),[N,A]=l.useState(!1),[T,L]=l.useState(oi(p,t.length,n.length)),P=l.useRef(null),[M,_]=l.useState(null),D=l.useRef("__home__"),[B,R]=l.useState("__home__"),[O,H]=l.useState(""),[$,I]=l.useState(""),[W,F]=l.useState(""),[z,Q]=l.useState([]),[ne,oe]=l.useState(()=>qt().textQuery),[Ce,le]=l.useState(()=>qt().workspaceQuery),[U,J]=l.useState(()=>qt().modelQuery),[ee,Y]=l.useState(()=>qt().resumableOnly),[ve,pe]=l.useState(()=>qt().sortMode),[te,me]=l.useState(!1),[V,q]=l.useState(!1),se=l.useRef(null),de=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const K=f==="__custom__"?k.trim():((at=u.find(X=>X.id===f))==null?void 0:at.path)||"",fe=f==="__custom__"&&!!K&&a.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(a.message),ie=f!=="__custom__"&&((st=u.find(X=>X.id===f))==null?void 0:st.path)||"",ue=l.useMemo(()=>(e.recentLaunches||[]).map(X=>X.workspace),[e]),ye=l.useCallback(async X=>{v(!0),j("");try{const Le=await r(X);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]),Ie=l.useCallback(()=>{var Le;g("__custom__"),A(!0);const X=dc(e.platform,cc(k.trim(),ie,ue,e.defaultWorkspacePath,(Le=u.find(_e=>_e.id===m))==null?void 0:Le.path,u.map(_e=>_e.path)));ye(X)},[k,m,ye,ue,ie,e.platform,u]),E=l.useCallback(X=>{if(X!=null&&X.workspaceId){g(X.workspaceId),h("");return}if(X!=null&&X.workspacePath){g("__custom__"),h(X.workspacePath);return}g(""),h("")},[]),Z=l.useCallback(X=>{if(g(X),X==="__custom__"){Ie();return}h("")},[Ie]),we=l.useCallback(X=>{g("__custom__"),h(X)},[]),ge=l.useCallback((X,Le)=>{P.current=Le,D.current=X.selectedWorkspaceKey||"__home__",R(X.selectedWorkspaceKey||"__home__"),H(X.initialArgs||""),I(X.initialModel||""),F(""),Q([]);const _e=X.providerType?`${e.id}:${X.providerType}`:null;if(vj(de.current,_e)){const nt=qt();oe(nt.textQuery),le(nt.workspaceQuery),J(nt.modelQuery),Y(nt.resumableOnly),pe(nt.sortMode)}de.current=_e,_(X),X.providerType&&o&&(me(!0),o(X.providerType).then(nt=>Q(nt||[])).catch(nt=>console.warn("Failed to load saved sessions",nt)).finally(()=>me(!1)))},[o,e.id]),be=l.useMemo(()=>sh(z,{textQuery:ne,workspaceQuery:Ce,modelQuery:U,resumableOnly:ee,sortMode:ve}),[U,ee,z,ve,ne,Ce]);l.useEffect(()=>{W&&(be.some(X=>X.providerSessionId===W)||F(""))},[be,W]);const De=l.useCallback(()=>{P.current&&(q(!0),P.current().finally(()=>{P.current=null,q(!1),_(null)}))},[]),Me=l.useCallback(()=>{P.current=null,_(null)},[]),We=l.useCallback(X=>{D.current=X,R(X)},[]);return l.useEffect(()=>{var X;se.current!==e.id&&(se.current=e.id,g(m||((X=u[0])==null?void 0:X.id)||"__custom__"),h(""),S(""),w([]),j(""),A(!1),oe(qt().textQuery),le(qt().workspaceQuery),J(qt().modelQuery),Y(qt().resumableOnly),pe(qt().sortMode),de.current=null,L(oi(p,t.length,n.length)))},[n.length,t.length,m,p,e.id,u]),l.useEffect(()=>{var X;f!=="__custom__"&&(f&&u.some(Le=>Le.id===f)||g(m||((X=u[0])==null?void 0:X.id)||"__custom__"))},[m,f,u]),l.useEffect(()=>{T==="ide"&&p||T==="cli"&&t.length>0||T==="acp"&&n.length>0||L(oi(p,t.length,n.length))},[T,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:T,launchConfirm:M,launchConfirmWorkspaceKeyRef:D,launchConfirmWorkspaceKey:B,launchConfirmArgs:O,launchConfirmModel:$,launchConfirmResumeId:W,launchConfirmSavedSessions:z,launchConfirmTextFilter:ne,launchConfirmWorkspaceFilter:Ce,launchConfirmModelFilter:U,launchConfirmResumableOnly:ee,launchConfirmSortMode:ve,filteredLaunchConfirmSavedSessions:be,launchConfirmSessionsLoading:te,launchConfirmBusy:V,resolvedWorkspacePath:K,canCreateMissingWorkspace:fe,openBrowseDialog:Ie,loadBrowsePath:ye,handleWorkspaceChoiceChange:Z,chooseCustomWorkspacePath:we,setCustomWorkspacePath:h,setBrowseDialogOpen:A,setActiveLauncherKind:L,openLaunchConfirm:ge,handleConfirmLaunch:De,closeLaunchConfirm:Me,setWorkspaceSelectionFromOption:E,setLaunchConfirmWorkspaceKeyAndSync:We,setLaunchConfirmArgs:H,setLaunchConfirmModel:I,setLaunchConfirmResumeId:F,setLaunchConfirmTextFilter:oe,setLaunchConfirmWorkspaceFilter:le,setLaunchConfirmModelFilter:J,setLaunchConfirmResumableOnly:Y,setLaunchConfirmSortMode:pe}}function vA({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),A=t.slice(0,3),T=xA({selectedMachineEntry:e,cliProviders:a,acpProviders:r,machineAction:c,onBrowseDirectory:w,onListSavedSessions:v}),L=l.useMemo(()=>N.map(R=>{const{metaText:O,updatedLabel:H}=Gh(R);return{key:`recent-launch:${R.id}`,primary:R.label,secondary:O,updatedLabel:H,onClick:()=>{const{options:$,selectedKey:I}=Uh({machine:{workspaces:T.workspaceRows,defaultWorkspaceId:T.defaultWorkspaceId},currentWorkspacePath:R.workspace,homeLabel:y("newSession.homeDirectory"),homeDescription:y("newSession.launchWithoutWorkspace")});T.openLaunchConfirm({title:R.kind==="ide"?qr(y,"restart-ide",R.label):R.providerSessionId?ah(y,R.label):qr(y,"start-fresh",R.label),description:R.kind==="ide"?zr(y,"restart-ide"):R.providerSessionId?rh(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?nh(y,!0):Vr(y,"start-fresh"),workspaceOptions:$,selectedWorkspaceKey:I,details:[{label:"Mode",value:j(R.kind)},...R.providerType?[{label:"Provider",value:R.providerType}]:[]]},async()=>{const W=$.find(F=>F.key===T.launchConfirmWorkspaceKeyRef.current);T.setWorkspaceSelectionFromOption(W),await k({...R,workspace:(W==null?void 0:W.workspacePath)??null})})}}}),[T,k,N,y]),P=l.useMemo(()=>A.map(R=>({key:`recent-chat:${R.conversation.tabKey}`,primary:kt(R.conversation),secondary:GC(R.conversation,{timestampLabel:R.timestamp?Vp(R.timestamp):null}),unread:R.unread,onClick:()=>g(R.conversation)})),[g,A]),M=T.showAllRecent?L:L.slice(0,4),_=L.length>0,D=P.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:[D&&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:P.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))})]}),_&&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))}),L.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:()=>T.setShowAllRecent(R=>!R),children:T.showAllRecent?"Show fewer":`Show ${L.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"})]})]})]})]}),T.browseDialogOpen&&s.jsx(mc,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:T.browseCurrentPath,directories:T.browseDirectories,busy:T.browseBusy,error:T.browseError,confirmLabel:"Use this folder",onClose:()=>T.setBrowseDialogOpen(!1),onNavigate:R=>{T.loadBrowsePath(R)},onConfirm:R=>{T.chooseCustomWorkspacePath(R),T.setBrowseDialogOpen(!1)}}),T.launchConfirm&&s.jsx(jo,{title:T.launchConfirm.title,description:T.launchConfirm.description,details:T.launchConfirm.details,workspaceOptions:T.launchConfirm.workspaceOptions,selectedWorkspaceKey:T.launchConfirmWorkspaceKey,onWorkspaceChange:T.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:T.launchConfirm.providerType?rl(y,!!T.launchConfirmResumeId):T.launchConfirm.confirmLabel,busyLabel:T.launchConfirm.providerType?void 0:T.launchConfirm.busyLabel,busy:T.launchConfirmBusy,showArgsInput:T.launchConfirm.showArgsInput,argsValue:T.launchConfirmArgs,onArgsChange:T.setLaunchConfirmArgs,showModelInput:T.launchConfirm.showModelInput,modelValue:T.launchConfirmModel,onModelChange:T.setLaunchConfirmModel,historyProviderNode:T.launchConfirm.providerType&&(T.launchConfirmSessionsLoading||T.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"}),T.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:T.launchConfirmTextFilter,onChange:R=>T.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:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:T.launchConfirmWorkspaceFilter,onChange:R=>T.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:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:T.launchConfirmModelFilter,onChange:R=>T.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:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsxs("select",{value:T.launchConfirmSortMode,onChange:R=>T.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:T.launchConfirmBusy||T.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:T.launchConfirmResumableOnly,onChange:R=>T.setLaunchConfirmResumableOnly(R.target.checked),disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:T.launchConfirmResumeId,onChange:R=>T.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:T.launchConfirmBusy||T.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:kj(y)}),T.filteredLaunchConfirmSavedSessions.map(R=>s.jsxs("option",{value:R.providerSessionId,disabled:!R.canResume,children:[R.title||R.providerSessionId," ",R.canResume?"":"(workspace missing)"]},R.providerSessionId))]}),!T.launchConfirmSessionsLoading&&T.launchConfirmSavedSessions.length>0&&T.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),T.launchConfirmResumeId&&(()=>{const R=T.filteredLaunchConfirmSavedSessions.find(H=>H.providerSessionId===T.launchConfirmResumeId);if(!R)return null;const O=Oh(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:O.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:O.providerSessionId}),s.jsx("div",{className:"mt-1",children:O.metaLine}),O.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:O.updatedLabel}),O.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:O.preview})]})})()]}),onConfirm:T.handleConfirmLaunch,onCancel:T.closeLaunchConfirm}),u&&s.jsx(Wh,{section:p,onSectionChange:f})]})}const au=8e3;function yA(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 qh(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=yA(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 Pr(e){return[...e].sort((t,n)=>{const a=n.timestamp-t.timestamp;return a!==0?a:t.conversation.tabKey.localeCompare(n.conversation.tabKey)})}function wA(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:Pr(e)}function kA(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:Pr(n),unreadItems:Pr(a),workingItems:wA(r,t),completedItems:Pr(o)}}function No(e,t){if(!t)return!1;const n=e.filter(a=>a.type==="adhdev-daemon"&&zh(a)==="Connected");return n.length===0?!0:n.every(a=>a._sessionListAuthoritative===!0)}function zh(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 SA(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 CA(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=zh(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?qC(p,Um(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 jA(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 NA({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(A=>{pr("mark_read:result",{tabKey:y.tabKey,sessionId:y.sessionId,result:A})}).catch(A=>{pr("mark_read:error",{tabKey:y.tabKey,sessionId:y.sessionId,error:A instanceof Error?A.message:String(A)})})},[i,c]);return l.useEffect(()=>{var j;if(!a){jA(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 AA(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 TA(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function MA({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 v1(e,w,C);i(v.state),d(v.message)},[n,e]),h=l.useCallback(async(w,C,v,y)=>{var A,T,L;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 P={cliType:v};(A=y==null?void 0:y.workspacePath)!=null&&A.trim()?P.dir=y.workspacePath.trim():y!=null&&y.workspaceId?P.workspaceId=y.workspaceId:y!=null&&y.useHome&&(P.useHome=!0),y!=null&&y.resumeSessionId&&(P.resumeSessionId=y.resumeSessionId),(T=y==null?void 0:y.args)!=null&&T.trim()&&(P.cliArgs=y.args.trim().split(/\s+/).filter(Boolean)),(L=y==null?void 0:y.model)!=null&&L.trim()&&(P.initialModel=y.model.trim());const M=await r(w,P),_=(M==null?void 0:M.result)||M,D=(_==null?void 0:_.sessionId)||(_==null?void 0:_.id);if(M!=null&&M.success&&D){u(null),i("done"),d(`${v} launched`),t(Ba(D));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)||(_==null?void 0:_.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(P){if(TA(P)){i("loading"),d(`${v} launch requested — waiting for session…`);return}u(null),i("error"),d(P instanceof Error?P.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 P,M,_,D;if(!y||y.type==="adhdev-daemon"||AA(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 T=String(y.providerSessionId||"");if(p.resumeSessionId&&T)return T===p.resumeSessionId;if(w){const B=ru(y.workspace||y.runtimeWorkspaceLabel);return B?B===w:!1}return Number(y.lastUpdated||y._lastUpdate||y.timestamp||((D=(_=(M=(P=y.activeChat)==null?void 0:P.messages)==null?void 0:M.at)==null?void 0:_.call(M,-1))==null?void 0:D.timestamp)||0)>=p.startedAt-5e3});if(!C)return;const v=$h({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 PA(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function IA({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:A}){const[T,L]=l.useState(()=>{var Z;return((Z=e[0])==null?void 0:Z.tabKey)||null}),[P,M]=l.useState(()=>e[0]?"chat":"inbox"),[_,D]=l.useState("chats"),[B,R]=l.useState(null),[O,H]=l.useState("inbox"),$=l.useRef([]),I=oa(),W="1.0.51",F=l.useMemo(()=>e.find(Z=>Z.tabKey===T)||e[0]||null,[e,T]),z=l.useMemo(()=>F?n.find(Z=>Z.id===F.routeId):void 0,[n,F]),Q=l.useMemo(()=>!F||ht(F)||!gt(F)?null:la(F),[F]),ne=l.useMemo(()=>n.filter(Z=>Z.type==="adhdev-daemon").sort(Ul),[n]),oe=l.useMemo(()=>ne.find(Z=>Z.id===B)||null,[ne,B]),Ce=wo({sendDaemonCommand:r,activeConv:F||void 0,setActionLogs:o,isStandalone:i}),le=MA({sendDaemonCommand:r,navigate:I,ides:n,conversations:e}),U=yC(e),J=l.useMemo(()=>e.map(Z=>{const we=P==="chat"&&(F==null?void 0:F.tabKey)===Z.tabKey,ge=fo(Z,N,{hideOpenTaskCompleteUnread:!0,isOpenConversation:we}),be=jn(Z),De=Um(Z),Me=Qm(Z,De);return{conversation:Z,timestamp:be,preview:Me,unread:ge.unread,requiresAction:ge.requiresAction,isWorking:ge.isWorking,inboxBucket:ge.inboxBucket}}),[e,N,P,F,U]),{markConversationRead:ee}=NA({conversations:e,machineEntries:ne,items:J,selectedConversation:F,selectedTabKey:T,screen:P,liveSessionInboxState:N,sendDaemonCommand:r,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,setSelectedTabKey:L,setScreen:M,setSelectedMachineId:R,setSection:D,setMachineBackTarget:H,resetMachineAction:le.resetMachineAction}),Y=DA({conversations:e,selectedConversation:F,machineBackTarget:O,markConversationRead:ee,resetMachineAction:le.resetMachineAction,setSelectedTabKey:L,setScreen:M,setSelectedMachineId:R,setSection:D,setMachineBackTarget:H}),{isMuted:ve,toggleMute:pe}=qh(N,r),{attentionItems:te,unreadItems:me,workingItems:V,completedItems:q}=l.useMemo(()=>kA(J,$.current),[J]);l.useEffect(()=>{$.current=V.map(Z=>Z.conversation.tabKey)},[V]);const se=l.useMemo(()=>oe?J.filter(Z=>Ks(Z.conversation)===oe.id):[],[J,oe]),de=l.useMemo(()=>SA(oe,n),[n,oe]),K=!!oe&&So(oe,Qs(oe,W)),fe=l.useMemo(()=>(oe==null?void 0:oe.availableProviders)||[],[oe]),ie=l.useMemo(()=>fe.filter(Z=>na(Z,"cli")).map(Z=>({type:Z.type,displayName:Z.displayName||Z.type,icon:Z.icon})),[fe]),ue=l.useMemo(()=>fe.filter(Z=>na(Z,"acp")).map(Z=>({type:Z.type,displayName:Z.displayName||Z.type,icon:Z.icon})),[fe]),ye=l.useMemo(()=>CA(ne,J,t),[J,ne,t]),Ie=l.useMemo(()=>No(n,w),[n,w]),E=l.useCallback(async Z=>{oe&&await le.handleOpenRecent(oe.id,Z)},[le,oe]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:P==="chat"&&F?s.jsx(dA,{selectedConversation:F,isAcp:ht(F),isStandalone:i,selectedIdeEntry:z,actionLogs:a,userName:c,isSendingChat:Ce.isSendingChat,sendFeedbackMessage:Ce.sendFeedbackMessage,isFocusingAgent:Ce.isFocusingAgent,handleModalButton:Ce.handleModalButton,handleRelaunch:Ce.handleRelaunch,onBack:Y.backFromConversation,onOpenNativeConversation:Y.openNativeConversation,onOpenMachine:Y.openConversationMachine,onOpenHistory:k,onOpenRemote:h,onOpenMeshGraph:y,onStopCli:x,cliViewMode:Q,onSetCliViewMode:async Z=>{await Th({conversation:F,mode:Z,ides:n,sendDaemonCommand:r,setCliViewModeOverrides:A})},handleSendChat:Ce.handleSendChat,handleForceSendChat:Ce.handleForceSendChat,handleFocusAgent:Ce.handleFocusAgent}):P==="machine"&&oe?s.jsx(vA,{selectedMachineEntry:oe,selectedMachineConversations:se,selectedMachineRecentLaunches:de,cliProviders:ie,acpProviders:ue,selectedMachineNeedsUpgrade:K,appVersion:W,machineAction:le.machineAction,isStandalone:i,section:_,showBottomNav:O==="inbox",onBack:Y.backFromMachine,onSectionChange:Y.changeMachineSection,onOpenConversation:Y.openConversation,onOpenRecent:E,onOpenMachineDetails:()=>I(`/machines/${oe.id}`),onMachineUpgrade:()=>le.handleMachineUpgrade(oe.id),onLaunchDetectedIde:(Z,we)=>le.handleLaunchDetectedIde(oe.id,Z,we),onAddWorkspace:(Z,we)=>le.handleAddWorkspace(oe.id,Z,we),onBrowseDirectory:Z=>le.handleBrowseDirectory(oe.id,Z),onLaunchWorkspaceProvider:(Z,we,ge)=>le.handleLaunchWorkspaceProvider(oe.id,Z,we,ge),onListSavedSessions:Z=>le.handleListSavedSessions(oe.id,Z)}):s.jsx(mA,{section:_,attentionItems:te,unreadItems:me,workingItems:V,completedItems:q,hiddenConversations:t,machineCards:ye,getAvatarText:PA,actionLogs:a,sendDaemonCommand:r,onOpenConversation:Y.openConversation,onShowAllHidden:C,onHideConversation:v,onOpenMeshGraph:y,onStopCli:x,onOpenNewSession:j,onOpenMachine:Y.openMachine,onOpenSettings:()=>I("/settings"),onSectionChange:D,wsStatus:S,isConnected:b,initialDataLoaded:w,conversationsLoaded:Ie,isStandalone:i,isConversationMuted:ve,onToggleMuteConversation:pe})})}function ii(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function LA({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 RA(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 EA({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=RA(j,e);return N.length===j.length&&N.every((A,T)=>A===j[T])?j:N})},[e]);const h=l.useMemo(()=>{const j=p??c;if(j.length===0)return e;const N=new Map(j.map((A,T)=>[A,T]));return[...e].sort((A,T)=>{const L=N.get(A.tabKey)??999,P=N.get(T.tabKey)??999;return L-P})},[e,p,c]);l.useEffect(()=>{var N,A;if(h.length===0){o!==null&&(i(null),(N=g.current)==null||N.call(g,null));return}if(o&&h.some(T=>T.tabKey===o))return;const j=h[0].tabKey;j!==o&&(i(j),(A=g.current)==null||A.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,A)=>{d(T=>{var _;const L=T.filter(D=>D!==j),P=L.indexOf(N);if(P<0)return T;const M=A==="left"?P:P+1;return L.splice(M,0,j),(_=k.current)==null||_.call(k,L),L}),u(null)},[]),w=l.useCallback((j,N,A)=>{const L=(c.length>0?c:e.map(_=>_.tabKey)).filter(_=>_!==j),P=L.indexOf(N);if(P<0)return;const M=A==="left"?P:P+1;L.splice(M,0,j),m.current=L,u(L)},[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 T;const A=N.filter(L=>L!==j);return A.push(j),(T=k.current)==null||T.call(k,A),A})},[]);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 _A({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(Bh,{}),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 Kh="adhdev-tab-shortcuts";function Vh(){try{return JSON.parse(localStorage.getItem(Kh)||"{}")}catch{return{}}}function Yh({enabled:e=!0,sortedTabKeys:t,onFocus:n,onSelectTab:a}){const r=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>Vh()),[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(Kh,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()},HA=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=OC(t),A=UC(t),T=Ym(t),L=l.useCallback($=>{c.current=t.tabKey,x(t.tabKey),$.dataTransfer.setData("text/tab-key",t.tabKey),$.dataTransfer.effectAllowed="move"},[t.tabKey,c,x]),P=l.useCallback(()=>{c.current=null,x(null),g(),k(),h()},[c,x,g,k,h]),M=l.useCallback($=>{const I=c.current;if(!(!I||I===t.tabKey)&&$.dataTransfer.types.includes("text/tab-key")){$.preventDefault(),$.stopPropagation();const W=$.currentTarget.getBoundingClientRect(),F=$.clientX<W.left+W.width/2?"left":"right";m(I,t.tabKey,F)}},[t.tabKey,c,m]),_=l.useCallback($=>{$.preventDefault(),$.stopPropagation();const I=$.dataTransfer.getData("text/tab-key");if(I&&I!==t.tabKey){const W=$.currentTarget.getBoundingClientRect(),F=$.clientX<W.left+W.width/2?"left":"right";i.includes(I)?f(I,t.tabKey,F):S&&S(I)}k()},[t.tabKey,i,f,S,k]),D=l.useCallback($=>{$.stopPropagation(),d(),p(t.tabKey),u(t)},[t,u,d,p]),B=l.useCallback($=>{$.preventDefault(),b($.clientX,$.clientY,t.tabKey)},[t.tabKey,b]),R=l.useCallback($=>{const I=$.touches[0];w.current=setTimeout(()=>{b(I.clientX,I.clientY,t.tabKey)},600)},[t.tabKey,w,b]),O=l.useCallback(()=>{w.current&&clearTimeout(w.current)},[w]),H=["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:H,draggable:!0,onDragStart:L,onDragEnd:P,onDragOver:M,onDrop:_,onClick:D,onContextMenu:B,onTouchStart:R,onTouchEnd:O,onTouchMove:O,style:{position:"relative",cursor:"pointer",opacity:a?.4:void 0},children:[T&&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:A,"aria-label":A||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 $A({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(_=>_.tabKey),[e]);Ga("PaneGroupTabBar",{groupIndex:n,activeTabId:t,tabCount:e.length,ctxMenuTab:(w==null?void 0:w.tabKey)||null});const{isMac:N,tabShortcuts:A,shortcutListening:T,setShortcutListening:L,saveShortcuts:P}=Yh({enabled:S,sortedTabKeys:e.map(_=>_.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!w)return;const _=D=>{const B=document.querySelector("[data-pane-context-menu]");B&&B.contains(D.target)||C(null)};return window.addEventListener("mousedown",_,!0),()=>window.removeEventListener("mousedown",_,!0)},[w]),l.useEffect(()=>{const _=y.current;if(!_)return;const D=B=>{Math.abs(B.deltaY)<=Math.abs(B.deltaX)||(B.preventDefault(),_.scrollLeft+=B.deltaY)};return _.addEventListener("wheel",D,{passive:!1}),()=>_.removeEventListener("wheel",D)},[]);const M=l.useCallback((_,D,B)=>{C({x:_,y:D,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(_=>s.jsx(HA,{conv:_,isActive:t===_.tabKey,isDraggedTab:r.current===_.tabKey,isTaskCompleteUnread:a.has(_.tabKey),shortcut:S?A[_.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},_.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:_=>{_.stopPropagation(),L(w.tabKey),C(null)},children:["⌨ ",A[w.tabKey]?`Change shortcut (${A[w.tabKey]})`:"Set shortcut"]}),A[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 _={...A};delete _[w.tabKey],P(_),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&&T&&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:()=>L(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:_=>_.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 FA({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:A}){const{sendCommand:T}=St(),L=l.useRef(null),{activeTabId:P,activeConv:M,sortedConversations:_,draggingTabRef:D,selectTab:B,handleTabReorder:R,updatePreviewOrder:O,commitPreviewOrder:H,clearPreviewOrder:$,moveTabToEnd:I,setDraggingTabKey:W}=EA({conversations:e,initialActiveTabId:b,initialTabOrder:w,onActiveTabChange:S,onTabOrderChange:C}),F=wo({sendDaemonCommand:r,activeConv:M,setActionLogs:o,isStandalone:i}),{dragOver:z,dropAction:Q,resetDragState:ne,handleDragEnter:oe,handleDragOver:Ce,handleDragLeave:le,handleDrop:U}=LA({conversations:e,numGroups:g,onMoveTab:k,onReceiveTab:h,onOwnTabDrop:I,onClearPreviewOrder:$}),J=M&&!ht(M)&&la(M)==="terminal",ee=l.useMemo(()=>M?t.find(te=>te.id===M.routeId):void 0,[t,M]),Y=l.useMemo(()=>M?a.filter(te=>te.routeId===M.tabKey):[],[a,M]),ve=l.useMemo(()=>new Set(_.filter(te=>Ax(te,A,{isOpenConversation:te.tabKey===P})).map(te=>te.tabKey)),[P,A,_]);Ga("PaneGroup",{groupIndex:u,conversationCount:e.length,activeTabId:P,dragOver:z});const pe=l.useCallback(te=>{te.streamSource==="agent-stream"&&te.agentType&&T(te.routeId,Dm(),{agentType:te.agentType,...te.sessionId&&{targetSessionId:te.sessionId}}).catch(()=>{})},[T]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:m,style:{...x,outline:z?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx($A,{conversations:_,activeTabId:P,groupIndex:u,numGroups:g,unreadTabKeys:ve,draggingTabRef:D,onFocus:m,onSelectTab:B,onConversationActivated:pe,onPreviewReorder:O,onReorderTab:R,onCommitPreviewOrder:H,onClearPreviewOrder:$,onDragStateReset:ne,onDragTabKeyChange:W,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:oe,onDragOver:Ce,onDragLeave:le,onDrop:U,children:[z&&s.jsx(_A,{dropAction:Q,canSplit:!!(g<4&&k)}),M?s.jsx(pc,{activeConv:M,clearToken:n[M.tabKey]||0,isCliTerminal:!!J,ideEntry:ee,terminalRef:L,handleModalButton:F.handleModalButton,handleRelaunch:F.handleRelaunch,handleSendChat:F.handleSendChat,handleForceSendChat:F.handleForceSendChat,isSendingChat:F.isSendingChat,sendFeedbackMessage:F.sendFeedbackMessage,handleFocusAgent:F.handleFocusAgent,isFocusingAgent:F.isFocusingAgent,actionLogs:Y,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 BA({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:A,allowTabShortcuts:T=!0,liveSessionInboxState:L}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:r.map((P,M)=>{const _=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:D=>w(M-1,D),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(FA,{style:t?{flexBasis:_??`${100/n}%`,flexGrow:_?0:1,flexShrink:_?0:1}:void 0,conversations:P,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:(D,B)=>{B==="left"&&M>0?x(D,M-1):B==="right"&&M<n-1?x(D,M+1):B==="split-left"&&n<4?S(D,M,"left"):B==="split-right"&&n<4&&S(D,M,"right")},onReceiveTab:D=>x(D,M),onActiveTabChange:D=>v(M,D),initialActiveTabId:C[M],initialTabOrder:y[M],onTabOrderChange:D=>j(M,D),onHideTab:N,onOpenNewSession:A,allowTabShortcuts:T,liveSessionInboxState:L})]},M)})})}const Qh="adhdev-dashboard-action-shortcuts",WA=1200,OA=[["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 UA(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function ft(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 Jh(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:ft("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:ft("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:ft("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:ft("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:ft("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:ft("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:ft("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:ft("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:ft("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:ft("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:ft("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:ft("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:ft("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:ft("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:ft("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:ft("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:ft("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:ft("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:ft("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:ft("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:ft("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:ft("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:ft("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:ft("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:ft("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:ft("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(Jh(e).map(n=>[n.id,n.defaultShortcut]));try{const n=JSON.parse(localStorage.getItem(Qh)||"{}"),a={...t,...n};for(const[r,o]of OA)a[r]===o&&(a[r]=t[r]);return a}catch{return t}}function Xh(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function GA({enabled:e=!0,onTrigger:t}){const n=UA(),[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(Xh(h.key)),x.join("+"))},[n]),m=l.useCallback(h=>{r(h);try{localStorage.setItem(Qh,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}},WA))},[]);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(([,P])=>!!P),N=j.find(([,P])=>P===v);if(N){x.preventDefault(),f(),t(N[0]);return}if(j.some(([,P])=>P.startsWith(`${v} `))){x.preventDefault(),p.current.parts=C,g();return}const T=j.find(([,P])=>P===y);if(T){x.preventDefault(),f(),t(T[0]);return}if(j.some(([,P])=>P.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(()=>Jh(n),[n]);return{isMac:n,actionDefinitions:k,actionShortcuts:a,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:d,saveShortcuts:m}}function qA({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 Zh(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?!Zh(a):!0}function zA({previousVisibleConversationCount:e,visibleConversationCount:t,ides:n}){return t>0||e<=0?!1:Zh(n)}const ef=1e3,KA=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 VA({detachDelayMs:e=ef,stillnessThresholdPx:t=KA,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 YA(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 QA(e){return`remote:${e}`}function fs(e){return e.startsWith("remote:")}function cu(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}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 JA(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?QA(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=Zm(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 tf({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 sf=l.createContext(null);function Ao(){const e=l.useContext(sf);if(!e)throw new Error("DashboardDockviewContext missing");return e}function XA(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 ZA({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}=tf({doId:r,targetSessionId:n?Tm(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(qp,{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 eT(){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 tT(e){var b,w;XA(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=>CC(C),[]),i=l.useCallback(()=>SC(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 sT(e){e.preventDefault()}function nT({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 aT({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,nt,rt;const{theme:y}=Ls(),{sendCommand:j}=St(),N=l.useRef(null),A=l.useRef(null),T=l.useRef(null),L=l.useRef(!1),P=l.useRef(!1),M=l.useRef(!1),_=l.useRef(null),D=l.useRef([]),[B,R]=l.useState(null),[O,H]=l.useState(0),$=l.useRef(typeof window>"u"?{}:kN(v)),I=l.useMemo(()=>new Map(e.map(G=>[G.tabKey,G])),[e]),W=l.useMemo(()=>{const G=N.current;return G?G.groups.some(re=>{try{const ce=re.model.location.type;return ce!=="floating"&&ce!=="popout"?!1:re.panels.some(xe=>I.has(xe.id))}catch{return!1}}):!1},[I,O,e]),F=l.useCallback(()=>{var G;(G=N.current)==null||G.focus()},[]),z=l.useCallback((G,re)=>{h==null||h(G,re)},[h]),Q=l.useCallback(G=>{const re=document,ce=G.document;for(const Re of re.querySelectorAll('link[rel="stylesheet"]')){const Qe=ce.createElement("link");Qe.rel="stylesheet",Qe.href=Re.href,Re.crossOrigin&&(Qe.crossOrigin=Re.crossOrigin),ce.head.appendChild(Qe)}for(const Re of re.querySelectorAll("style")){const Qe=ce.createElement("style");Qe.textContent=Re.textContent,ce.head.appendChild(Qe)}const xe=[];for(const Re of re.styleSheets)try{for(const Qe of Re.cssRules)Qe instanceof CSSStyleRule&&(Qe.selectorText===":root"||Qe.selectorText==="html")&&xe.push(Qe.cssText)}catch{}if(xe.length>0){const Re=ce.createElement("style");Re.textContent=xe.join(`
64
+ The machine's IDE, workspace and provider settings are kept.`,confirmLabel:o("machine.connectedMachines.remove"),confirmColor:"red",onConfirm:A,onCancel:()=>m(null)})]})}const C1=[{id:"dark",label:"Dark",icon:Mp},{id:"light",label:"Light",icon:Tp},{id:"system",label:"System",icon:Dp}];function j1(){const{preference:e,setPreference:t}=Ls();return s.jsx("div",{className:"flex gap-2",children:C1.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 N1(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 A1(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}=A1(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 wh(e){const t=N1(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},T1=[{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"}}}],kh="adhdev-chat-theme",Sh="adhdev-chat-theme-custom";function Mr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(kh)||"ember"}catch{return"ember"}}function bs(e){try{const t=localStorage.getItem(Sh);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(Sh,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 M1={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Pa(e,t){var r;const n=(r=M1[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",wh(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",wh(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(kh,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=Cn()?"dark":"light";Sn(bs(t))}else rc(),Pa(e,Cn()?"dark":"light")}function P1(){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(),Pa(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 I1({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 L1(){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")):Pa(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")):Pa(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(),Pa(t,a?"dark":"light"))},[t,a]),l.useEffect(()=>{i(bs(a?"dark":"light"))},[a]);const c=p=>{n(p),D1(p)},d=[...T1,{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(I1,{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 R1(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 E1(e){try{localStorage.setItem(oc,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(dl,{detail:e}))}function _1(){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(Ps,{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),E1(n?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const H1="Choose a preset or create a fully custom theme. Custom themes control the entire app — backgrounds, text, borders, and chat bubbles.",$1="Choose whether the dashboard opens like a chat app on phones or keeps the full workspace layout.";function F1({themeDescription:e=H1,mobileDescription:t=$1,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(j1,{})]}),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(L1,{})]}),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(_1,{})]})]})}const ei=new Map,zd=new Map;function B1(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 W1(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 Ch(){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)??GS,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=B1(p);if(!u)return;const m=n().find(g=>g.id===a),f=W1(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 O1(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 U1(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=O1(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 G1(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)},KS):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 q1(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function jh(e){const{sendData:t}=St(),[n,a]=l.useState({});return l.useEffect(()=>{const r=q1(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 z1(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function K1(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 V1(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 Y1({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(!z1(o))throw new Error(K1(o));return}await V1(e.sessionId,t,r)}function Nh(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(()=>vx(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=zp(k.prompt,b);d(!0),u(null);try{const C=(a==null?void 0:a[k.daemonId])==="connected"||n===!0;await Y1({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 Ah(e){return e instanceof Error?e.message:String(e||"")}function Q1(e){const t=Ah(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 J1(e){const t=Ah(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Th({conversation:e,mode:t,ides:n,sendDaemonCommand:a,setCliViewModeOverrides:r}){if(!e||!gt(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:Ds(e),mode:t})}catch(c){const d=J1(c);i&&!d&&r(p=>{const u={...p};return o===Z1(n,i)?delete u[i]:u[i]=o,u}),Q1(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 X1(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 Z1(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 eN({visibleConversations:e,clearedTabs:t,setClearedTabs:n,setActionLogs:a,isConversationMuted:r}){l.useEffect(()=>{um()},[]);const o=l.useMemo(()=>e.map(i=>({id:i.tabKey,name:Xm(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 uk(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 Mh(e){return jn(e)||e.lastUpdated||0}function Dh(e,t,n=Mh){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 tN(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!pl(e)&&!e.title.trim()}function sN(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:Dh(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=sN(r);return a?o&&tN(a)?o:a:o||n[0]||null}function nN(e){const t=e.filter(r=>r.type!=="adhdev-daemon"),n=new Set;for(const r of t){if(!Ji(r))continue;const o=rm(r);o&&n.add(o)}const a=new Map;for(const r of t){const o=W0(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,aN(u,u===r?i:r))}return Array.from(a.values())}function aN(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 rN(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?rN(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 oN(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 iN(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 lN(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 cN(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function dN(e){const t=cN(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 uN({ides:e,connectionStates:t,clearedTabs:n}){const a=l.useMemo(()=>nN(e),[e]),r=l.useMemo(()=>Yp(e),[e]),o=l.useMemo(()=>ch(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 A of a){const{connectionState:T="new",machineName:L}=dh(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),P=oN(A),M=p.current.get(A.id);if(M&&M.ide===A&&M.sourceSignature===P&&M.connectionState===T&&M.machineName===L){C.set(A.id,M),v.push(...M.conversations);continue}const _=nc(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),D={ide:A,sourceSignature:P,connectionState:T,machineName:L,conversations:_};C.set(A.id,D),v.push(..._)}p.current=C;const y=new Map,j=A=>{const T=dN(A),L=u.current.get(A.tabKey);if(L&&L.signature===T)return y.set(A.tabKey,L),L.timestamp;const P={signature:T,timestamp:Mh(A)||(L==null?void 0:L.timestamp)||0};return y.set(A.tabKey,P),P.timestamp},N=[...v].sort((A,T)=>Dh(A,T,j));return u.current=y,N},[a,t,o]),f=l.useMemo(()=>{const C=iN(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(()=>lN(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 pN({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 mN({ides:e,sendDaemonCommand:t,setToasts:n,resolveConversationByTarget:a}){l.useEffect(()=>{xt.setIdes(e)},[e]),l.useEffect(()=>{xt.setResolveAction((r,o,i)=>{t(r,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const r=xt.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=Vm.on("status_event",o=>{xt.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 hN="adhdev_dashboardLayout_v1",fN="adhdev_dashboardDockview_v1",gN="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 bN(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Ph(e){return`${hN}:${e}`}function xN(e){const t=Ph(e);return lc(t,null)}function vN(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 Ih(e){return`${fN}:${e}`}function yN(e){const t=Ih(e);return lc(t,null)}function wN(e,t){try{const n=Ih(e);if(!t){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Lh(e){return`${gN}:${e}`}function kN(e){const t=Lh(e);return lc(t,{})}function SN(e,t){try{const n=Lh(e);if(Object.keys(t).length===0){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function CN(){return{groupAssignments:[...xa.groupAssignments],focusedGroup:xa.focusedGroup,groupActiveTabIds:{...xa.groupActiveTabIds},groupTabOrders:{...xa.groupTabOrders},groupSizes:[...xa.groupSizes]}}function jN(e,t){return e?e.length===t.length&&e.every((n,a)=>n===t[a]):t.length===0}function NN(){const[e]=l.useState(()=>bN(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 A=xN(e)??CN();n(new Map(A.groupAssignments)),r(A.focusedGroup),i(A.groupActiveTabIds),d(A.groupTabOrders),u(A.groupSizes),k(!0)},[g,e]);l.useEffect(()=>{g&&vN(e,{groupAssignments:[...t.entries()],focusedGroup:a,groupActiveTabIds:o,groupTabOrders:c,groupSizes:p})},[g,e,t,a,o,c,p]),l.useEffect(()=>{const A=window.matchMedia("(max-width: 767px)"),T=L=>f(L.matches);return A.addEventListener("change",T),()=>A.removeEventListener("change",T)},[]);const x=l.useCallback(A=>{n(A)},[]),S=l.useCallback(A=>{r(A)},[]),b=l.useCallback(A=>{i(A)},[]),w=l.useCallback(A=>{d(A)},[]),C=l.useCallback(A=>{u(A)},[]),v=l.useCallback(A=>{S(A)},[S]),y=l.useCallback((A,T)=>{i(L=>(L[A]??null)===(T??null)?L:{...L,[A]:T})},[]),j=l.useCallback((A,T)=>{d(L=>{const P=L[A];return jN(P,T)?L:{...L,[A]:T}})},[]),N=l.useCallback((A,T)=>{const L=T.get(A)??0;return y(L,A),v(L),L},[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 AN(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 TN({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||AN(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 Rh({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)}),pC(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 MN(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 PN(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 IN(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 LN({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[A,T]of j)T!==v&&(T>v?N.set(A,T-1):N.set(A,T));return N}),i(y=>{if(y.length<=1)return[];const j=[...y];j.splice(v,1);const N=j.reduce((A,T)=>A+T,0);return N>0?j.map(A=>A/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,A=j.offsetWidth,T=o.length===g?[...o]:Zd(g),L=M=>{const D=(M.clientX-N)/A*100,B=[...T];B[v]=Math.max(15,T[v]+D),B[v+1]=Math.max(15,T[v+1]-D),i(B)},P=()=>{document.removeEventListener("mousemove",L),document.removeEventListener("mouseup",P),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",L),document.addEventListener("mouseup",P)},[o,g,i]),b=l.useCallback((v,y,j)=>{if(g>=4)return;const N=j==="left"?y:y+1;t(A=>{const T=cr(A,p).assignments,L=new Map;for(const P of d){const M=T.get(P.tabKey)??0,_=M>=N?M+1:M;_>0&&L.set(P.tabKey,_)}return N>0&&L.set(v,N),L}),i(A=>{const T=A.length===g?[...A]:Zd(g),L=T[y]??100/g,P=Math.max(15,L/2),M=Math.max(15,L/2),_=[...T];_[y]=P,_.splice(N,0,M);const D=_.reduce((B,R)=>B+R,0);return _.map(B=>B/D*100)}),a(A=>{const T=Xd(A,N);return T[N]=v,T}),r(A=>{const T=Xd(A,N);return T[N]=[v],T}),n(N)},[g,t,p,d,i,a,r,n]);l.useEffect(()=>{MN(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:PN(j,y,v);return j===N?j:N}),i(j=>{const N=c?[]:IN(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 RN({ides:e,sendDaemonCommand:t}){const n="1.0.52",a=l.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:So(m,Qs(m,n))).sort((m,f)=>Number(Da(f,Qs(f,n)))-Number(Da(m,Qs(m,n)))),[n,e]),r=l.useMemo(()=>a.some(m=>Da(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 Eh=80;function Dr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function EN(e){return{...e,createdAt:Dr(e.createdAt),updatedAt:Dr(e.updatedAt,e.createdAt),lastEventAt:Dr(e.lastEventAt,e.updatedAt||e.createdAt)}}function _N(e){const t=am(e);return t==="unknown:"?e.id:t}function HN(e){return[e.type,nm(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function $N(e,t=Eh){const n=new Map;for(const a of e){if(a.deletedAt)continue;const r=_N(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 FN(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=Dr(r.lastMessageAt||(o==null?void 0:o.lastUpdated)||r.lastUpdated,n),p=HN({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(EN({id:p,dedupKey:p,type:c,routeId:r.routeId,machineId:r.daemonId||r.routeId,sessionId:r.sessionId,providerSessionId:r.providerSessionId,tabKey:r.tabKey,title:jm(r),preview:CS(r),createdAt:d,updatedAt:d,lastEventAt:d}))}return $N(a)}function BN(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function WN(e){const{conversations:t,liveSessionInboxState:n,maxItems:a=Eh}=e,r=l.useMemo(()=>FN(t,n).slice(0,Math.max(0,a)),[t,n,a]),o=l.useMemo(()=>BN(r),[r]);return{notifications:r,unreadCount:o}}function ON({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 UN(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=UN(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 GN(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 qN(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=qN(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 _h(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 zN(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 Hh(e){return bo(e)||e.tabKey||e.routeId||null}function $h(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 Fh(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 KN(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function VN(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 YN(e,t,n){if(t.event!=="agent:generating_completed")return null;const a=Fh(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&&!KN(u,p))return null}return VN(t,n)}function tu(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function QN({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"||Fh(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=$h({entrySessionId:p.sessionId,entryInstanceId:p.instanceId,entryRouteId:p.id,conversations:t});u&&(i(),n(u))},[i,t,e,n,a]),l.useEffect(()=>xt.onStatusEvent(d=>{const p=o.current;if(!p)return;const u=YN(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 JN(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 XN(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 ZN({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=JN(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=XN(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 A=String((j==null?void 0:j.code)||(y==null?void 0:y.code)||""),T=zN((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:A||void 0,manualSetup:T}}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 Th({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 eA(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 tA(e,t,n=Date.now()){return!e||!eA(t)?null:{tabKey:e,nonce:n}}function sA({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=NS(h);return b?S.set("activeTab",b):S.delete("activeTab"),S},{replace:!0})},[i]),k=l.useCallback((h,x)=>{const S=tA(h,x);S&&u(S)},[]);return{activeConv:m,openDesktopConversation:g,requestScrollToBottom:k,scrollToBottomRequest:p,setDesktopActiveTab:f}}function nA(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 aA(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 rA({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=aA({tabKey:e.tabKey,historySessionId:bo(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:jn(e),liveState:u}),f=m.autoReadKey,g=nA({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 oA({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:n,ides:a,sendDaemonCommand:r,updateRouteChats:o,setToasts:i,setClearedTabs:c,setSearchParams:d}){var O;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&&gt(v)&&!ht(v),j=l.useMemo(()=>{if(!v||!y)return null;const H=v.daemonId||v.routeId||"",$=Ds(v),I=ni(v);return`${H}:${$}:${v.providerSessionId||""}:${I}`},[v,y]),N=l.useMemo(()=>!v||!y?"":ni(v),[v,y]),{isCreatingChat:A,isRefreshingHistory:T,handleSwitchSession:L,handleNewChat:P,handleRefreshHistory:M}=Rh({sendDaemonCommand:r,activeConv:v,chats:(O=a.find(H=>H.id===(v==null?void 0:v.routeId)))==null?void 0:O.chats,updateRouteChats:o,setToasts:i,setClearedTabs:c}),_=l.useCallback(()=>{m(!0)},[]),D=l.useCallback(()=>{m(!1)},[]),B=l.useCallback(async()=>{if(!(!v||!y||x)){S(!0);try{const H=v.daemonId||v.routeId,$=Ds(v),I=ni(v),W=await r(H,"list_saved_sessions",{agentType:$,providerType:$,kind:"cli",limit:50,...v.providerSessionId?{providerSessionId:v.providerSessionId}:{},...I?{workspace:I}:{}}),F=(W==null?void 0:W.result)??W;g(Array.isArray(F==null?void 0:F.sessions)?F.sessions:[])}catch(H){console.error("Refresh saved sessions failed",H),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 H=>{if(!v||!y||!H.providerSessionId||!H.workspace)return;const $=v.daemonId||v.routeId,I=Ds(v);try{w(H.providerSessionId);const W=await p($,{cliType:I,dir:H.workspace,resumeSessionId:H.providerSessionId,initialModel:cm(H.summaryMetadata,"model",{preferShortValue:!0})||void 0}),F=(W==null?void 0:W.result)??W,z=typeof(F==null?void 0:F.sessionId)=="string"?F.sessionId:typeof(F==null?void 0:F.id)=="string"?F.id:"";z&&d(Q=>{const ne=new URLSearchParams(Q);return ne.set("activeTab",z),ne},{replace:!0}),D()}catch(W){console.error("Resume saved session failed",W)}finally{w(null)}},[D,v,y,r,d]);return{historyModalOpen:u,openHistoryModal:_,closeHistoryModal:D,historyTargetConv:v,isSavedSessionHistoryTarget:y,isHistoryCreatingChat:A,isHistoryRefreshingHistory:T,handleHistorySwitchSession:L,handleHistoryNewChat:P,handleHistoryRefresh:M,savedHistorySessions:f,savedHistoryFilters:k,setSavedHistoryFilters:h,missingWorkspaceResumePath:N,isSavedHistoryLoading:x,resumingSavedHistorySessionId:b,handleRefreshSavedHistory:B,handleResumeSavedHistorySession:R}}function iA({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&&!gt(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 lA({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}=iA({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||!gt(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||!gt(N)&&!ht(N)){v();return}S(!1);try{const A=Ds(N),T=N.routeId||N.daemonId||"";await p(T,"stop_cli",{cliType:A,targetSessionId:N.sessionId,mode:j,...yo(N)})}catch(A){console.error("Stop CLI failed:",A)}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=jh(t),A=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(Qp,{activeConv:A,onModalButton:i}),A.transport!=="pty"&&A.transport!=="acp"&&A.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,A.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(ij,{activeConv:A,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:A,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:A,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 cA({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:Cm(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=jS(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=Hh(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(ub,{size:12}),s.jsxs("span",{children:[x.pending," Pending"]})]})]})}function dA({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 P,M;const j=l.useRef(null),N=gt(e)&&!t,A=N&&x==="terminal",T=!!e.daemonId&&!!((P=e.coordinator)!=null&&P.meshId||(M=e.settings)!=null&&M.meshCoordinatorFor),L=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 ${L} 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(cA,{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(th,{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(Pt,{size:14})}),T&&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:A,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 uA(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Bh(){const[e,t]=l.useState("unix"),[n,a]=l.useState("powershell"),[r,o]=l.useState(!1),i=e==="unix"?"unix":n;l.useEffect(()=>{t(uA())},[]);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 Wh({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:Ps}];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 pA({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=Jm(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",A=g?"text-text-muted opacity-80":"text-text-muted",T=!f&&!k,L=Ym(e.conversation),P="text-[color:var(--status-warning)]",M=_=>{if(!c)return;_.preventDefault(),_.stopPropagation();const D=c==null?void 0:c(e.conversation);Promise.resolve(D).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)}),L&&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:_=>{_.preventDefault(),_.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:`${P} 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:P,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:[T&&s.jsx("span",{className:`mr-0.5 text-[11px] font-medium shrink-0 ${A}`,children:Vp(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:_=>{_.preventDefault(),_.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(Ap,{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:_=>{_.preventDefault(),_.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:_=>{_.preventDefault(),_.stopPropagation(),o()},"aria-label":u("mobileInbox.stopSessionAria",{title:S}),title:u("mobileInbox.stopSessionTitle"),children:s.jsx(Pt,{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 mA({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:A}){const{t:T}=ke(),[L,P]=l.useState(null),M=w==="disconnected"||w==="reconnecting"||w==="offline"||w==="auth_failed",_=!M&&!C,D=!M&&!(v??C),B=i.length>0,R=t.length>0||n.length>0||a.length>0||r.length>0,O=T(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),H=y?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",$=y?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",I=l.useCallback(async z=>{const Q=wn(z);if(!Q)return;const ne=Array.isArray(z.messages)?z.messages:[],oe=Pm({activeConv:z,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(Q,"get_chat_debug_bundle",{...yn(z),delivery:"daemon_file",frontendSnapshot:oe}),le=Ma(Ce),U=Rm(le),J=await Lm(U);J==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),xt.showToast(Im(le,{locatorCopyStatus:J}),J==="failed"?"warning":"success")},[d,p]),W=j||I,F=l.useCallback(()=>{L&&(f==null||f(L),P(null))},[L,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 ${H}`,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:O}),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] ${$}`,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:T(w==="offline"?"mobileInbox.networkOffline":w==="auth_failed"?"mobileInbox.sessionExpired":"mobileInbox.reconnecting"),subtitle:T(w==="offline"?"mobileInbox.waitingForNetwork":w==="auth_failed"?"mobileInbox.pleaseLogInAgain":"mobileInbox.restoringConnection")}):_?s.jsx(mn,{icon:s.jsx(ls,{size:32}),title:T("mobileInbox.loading"),subtitle:T("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:T(y?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:T(y?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!y&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(Bh,{})})}):s.jsx(Fn,{children:i.map((z,Q)=>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] ${Q>0?"border-t border-border-subtle/70":""}`,onClick:()=>x(z.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(z.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:z.label}),s.jsxs("span",{className:"flex items-center gap-2 text-[11px] font-medium text-text-muted shrink-0",children:[s.jsx(su,{count:z.generatingCount,label:T("mobileInbox.generatingCount",{count:z.generatingCount})}),z.unread>0?s.jsx("span",{className:"text-accent-primary",children:T("mobileInbox.newCount",{count:z.unread})}):z.total>0?T("mobileInbox.chatCount",{count:z.total}):T("mobileInbox.idle")]})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:z.subtitle}),z.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[T("mobileInbox.chatCount",{count:z.total}),z.unread>0?T("mobileInbox.unreadSuffix",{count:z.unread}):"",z.generatingCount>0?T("mobileInbox.collapsedGeneratingSuffix",{count:z.generatingCount}):""]}):z.generatingCount>0?s.jsx("div",{className:"text-[13px] text-accent-primary mt-0.5 font-medium",children:T("mobileInbox.generatingCount",{count:z.generatingCount})}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:T("mobileInbox.noActiveChats")})]})]},z.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:T("mobileInbox.needsAttention"),className:"mb-0"}),s.jsx(Fn,{children:t.map((z,Q)=>s.jsx("div",{className:Q>0?"border-t border-border-subtle/70":"",children:s.jsx(ur,{item:z,type:"needs_attention",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>P(z.conversation):void 0,onRequestStopCli:k?()=>k(z.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:W,isMuted:N==null?void 0:N(z.conversation),onToggleMute:A?()=>A(z.conversation):void 0})},z.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:T("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),s.jsx(Fn,{children:n.map((z,Q)=>s.jsx("div",{className:Q>0?"border-t border-border-subtle/70":"",children:s.jsx(ur,{item:z,type:"task_complete",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>P(z.conversation):void 0,onRequestStopCli:k?()=>k(z.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:W,isMuted:N==null?void 0:N(z.conversation),onToggleMute:A?()=>A(z.conversation):void 0})},z.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:T("mobileInbox.workingNow"),className:"mb-0 mt-2"}),s.jsx(Fn,{children:a.map((z,Q)=>s.jsx("div",{className:Q>0?"border-t border-border-subtle/70":"",children:s.jsx(ur,{item:z,type:"working",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>P(z.conversation):void 0,onRequestStopCli:k?()=>k(z.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:W,isMuted:N==null?void 0:N(z.conversation),onToggleMute:A?()=>A(z.conversation):void 0})},z.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:T("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),r.length>0?s.jsx(Fn,{children:r.map((z,Q)=>s.jsx("div",{className:Q>0?"border-t border-border-subtle/70":"",children:s.jsx(ur,{item:z,type:"earlier",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>P(z.conversation):void 0,onRequestStopCli:k?()=>k(z.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:W,isMuted:N==null?void 0:N(z.conversation),onToggleMute:A?()=>A(z.conversation):void 0})},z.conversation.tabKey))}):R?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:T("mobileInbox.allCaughtUp")}):M?s.jsx(mn,{icon:s.jsx(ls,{size:28}),title:T("mobileInbox.connecting"),subtitle:T("mobileInbox.connectingSubtitle")}):D?s.jsx(mn,{icon:s.jsx(ls,{size:28}),title:T("mobileInbox.loading"),subtitle:T("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(Ps,{size:20})}),title:T("mobileInbox.noConversations"),subtitle:T("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":T("paneGroup.newSession"),title:T("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:T("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:T("mobileInbox.noMachinesConnected"),subtitle:T("mobileInbox.noMachinesSubtitle")})]}),e==="chats"&&o.length>0&&(()=>{const z=jx(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:T("mobileInbox.hiddenTabs")}),s.jsx(su,{count:z,label:T("mobileInbox.generatingCount",{count:z})})]}),s.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[T("mobileInbox.collapsedCount",{count:o.length}),z>0?T("mobileInbox.collapsedGeneratingSuffix",{count:z}):""]})]}),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:T("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":T("paneGroup.newSession"),title:T("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"})]})}),L&&s.jsx(pA,{conversation:L,onCancel:()=>P(null),onConfirm:F}),s.jsx(Wh,{section:e,onSectionChange:b})]})}function hA(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 Oh(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=hA(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=GN(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(Pt,{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(Pt,{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(Np,{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 Uh(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 fA(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function gA(e){return[fA(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function bA(e){return e.lastLaunchedAt?qa(e.lastLaunchedAt):""}function Gh(e){return{metaText:gA(e),updatedLabel:bA(e)}}function oi(e,t,n){return e?"ide":t>0?"cli":n>0?"acp":null}function xA({selectedMachineEntry:e,cliProviders:t,acpProviders:n,machineAction:a,onBrowseDirectory:r,onListSavedSessions:o}){var Be,Xe,at,st;const i=ca(),[c,d]=l.useState(!1),p=(((Be=e.detectedIdes)==null?void 0:Be.length)||0)>0,u=l.useMemo(()=>(e.workspaces||[]).map(X=>({id:X.id,path:X.path,label:X.label})),[e]),m=e.defaultWorkspaceId||null,[f,g]=l.useState(m||((Xe=u[0])==null?void 0:Xe.id)||""),[k,h]=l.useState(""),[x,S]=l.useState(""),[b,w]=l.useState([]),[C,v]=l.useState(!1),[y,j]=l.useState(""),[N,A]=l.useState(!1),[T,L]=l.useState(oi(p,t.length,n.length)),P=l.useRef(null),[M,_]=l.useState(null),D=l.useRef("__home__"),[B,R]=l.useState("__home__"),[O,H]=l.useState(""),[$,I]=l.useState(""),[W,F]=l.useState(""),[z,Q]=l.useState([]),[ne,oe]=l.useState(()=>qt().textQuery),[Ce,le]=l.useState(()=>qt().workspaceQuery),[U,J]=l.useState(()=>qt().modelQuery),[ee,Y]=l.useState(()=>qt().resumableOnly),[ve,pe]=l.useState(()=>qt().sortMode),[te,me]=l.useState(!1),[V,q]=l.useState(!1),se=l.useRef(null),de=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const K=f==="__custom__"?k.trim():((at=u.find(X=>X.id===f))==null?void 0:at.path)||"",fe=f==="__custom__"&&!!K&&a.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(a.message),ie=f!=="__custom__"&&((st=u.find(X=>X.id===f))==null?void 0:st.path)||"",ue=l.useMemo(()=>(e.recentLaunches||[]).map(X=>X.workspace),[e]),ye=l.useCallback(async X=>{v(!0),j("");try{const Le=await r(X);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]),Ie=l.useCallback(()=>{var Le;g("__custom__"),A(!0);const X=dc(e.platform,cc(k.trim(),ie,ue,e.defaultWorkspacePath,(Le=u.find(_e=>_e.id===m))==null?void 0:Le.path,u.map(_e=>_e.path)));ye(X)},[k,m,ye,ue,ie,e.platform,u]),E=l.useCallback(X=>{if(X!=null&&X.workspaceId){g(X.workspaceId),h("");return}if(X!=null&&X.workspacePath){g("__custom__"),h(X.workspacePath);return}g(""),h("")},[]),Z=l.useCallback(X=>{if(g(X),X==="__custom__"){Ie();return}h("")},[Ie]),we=l.useCallback(X=>{g("__custom__"),h(X)},[]),ge=l.useCallback((X,Le)=>{P.current=Le,D.current=X.selectedWorkspaceKey||"__home__",R(X.selectedWorkspaceKey||"__home__"),H(X.initialArgs||""),I(X.initialModel||""),F(""),Q([]);const _e=X.providerType?`${e.id}:${X.providerType}`:null;if(vj(de.current,_e)){const nt=qt();oe(nt.textQuery),le(nt.workspaceQuery),J(nt.modelQuery),Y(nt.resumableOnly),pe(nt.sortMode)}de.current=_e,_(X),X.providerType&&o&&(me(!0),o(X.providerType).then(nt=>Q(nt||[])).catch(nt=>console.warn("Failed to load saved sessions",nt)).finally(()=>me(!1)))},[o,e.id]),be=l.useMemo(()=>sh(z,{textQuery:ne,workspaceQuery:Ce,modelQuery:U,resumableOnly:ee,sortMode:ve}),[U,ee,z,ve,ne,Ce]);l.useEffect(()=>{W&&(be.some(X=>X.providerSessionId===W)||F(""))},[be,W]);const De=l.useCallback(()=>{P.current&&(q(!0),P.current().finally(()=>{P.current=null,q(!1),_(null)}))},[]),Me=l.useCallback(()=>{P.current=null,_(null)},[]),We=l.useCallback(X=>{D.current=X,R(X)},[]);return l.useEffect(()=>{var X;se.current!==e.id&&(se.current=e.id,g(m||((X=u[0])==null?void 0:X.id)||"__custom__"),h(""),S(""),w([]),j(""),A(!1),oe(qt().textQuery),le(qt().workspaceQuery),J(qt().modelQuery),Y(qt().resumableOnly),pe(qt().sortMode),de.current=null,L(oi(p,t.length,n.length)))},[n.length,t.length,m,p,e.id,u]),l.useEffect(()=>{var X;f!=="__custom__"&&(f&&u.some(Le=>Le.id===f)||g(m||((X=u[0])==null?void 0:X.id)||"__custom__"))},[m,f,u]),l.useEffect(()=>{T==="ide"&&p||T==="cli"&&t.length>0||T==="acp"&&n.length>0||L(oi(p,t.length,n.length))},[T,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:T,launchConfirm:M,launchConfirmWorkspaceKeyRef:D,launchConfirmWorkspaceKey:B,launchConfirmArgs:O,launchConfirmModel:$,launchConfirmResumeId:W,launchConfirmSavedSessions:z,launchConfirmTextFilter:ne,launchConfirmWorkspaceFilter:Ce,launchConfirmModelFilter:U,launchConfirmResumableOnly:ee,launchConfirmSortMode:ve,filteredLaunchConfirmSavedSessions:be,launchConfirmSessionsLoading:te,launchConfirmBusy:V,resolvedWorkspacePath:K,canCreateMissingWorkspace:fe,openBrowseDialog:Ie,loadBrowsePath:ye,handleWorkspaceChoiceChange:Z,chooseCustomWorkspacePath:we,setCustomWorkspacePath:h,setBrowseDialogOpen:A,setActiveLauncherKind:L,openLaunchConfirm:ge,handleConfirmLaunch:De,closeLaunchConfirm:Me,setWorkspaceSelectionFromOption:E,setLaunchConfirmWorkspaceKeyAndSync:We,setLaunchConfirmArgs:H,setLaunchConfirmModel:I,setLaunchConfirmResumeId:F,setLaunchConfirmTextFilter:oe,setLaunchConfirmWorkspaceFilter:le,setLaunchConfirmModelFilter:J,setLaunchConfirmResumableOnly:Y,setLaunchConfirmSortMode:pe}}function vA({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),A=t.slice(0,3),T=xA({selectedMachineEntry:e,cliProviders:a,acpProviders:r,machineAction:c,onBrowseDirectory:w,onListSavedSessions:v}),L=l.useMemo(()=>N.map(R=>{const{metaText:O,updatedLabel:H}=Gh(R);return{key:`recent-launch:${R.id}`,primary:R.label,secondary:O,updatedLabel:H,onClick:()=>{const{options:$,selectedKey:I}=Uh({machine:{workspaces:T.workspaceRows,defaultWorkspaceId:T.defaultWorkspaceId},currentWorkspacePath:R.workspace,homeLabel:y("newSession.homeDirectory"),homeDescription:y("newSession.launchWithoutWorkspace")});T.openLaunchConfirm({title:R.kind==="ide"?qr(y,"restart-ide",R.label):R.providerSessionId?ah(y,R.label):qr(y,"start-fresh",R.label),description:R.kind==="ide"?zr(y,"restart-ide"):R.providerSessionId?rh(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?nh(y,!0):Vr(y,"start-fresh"),workspaceOptions:$,selectedWorkspaceKey:I,details:[{label:"Mode",value:j(R.kind)},...R.providerType?[{label:"Provider",value:R.providerType}]:[]]},async()=>{const W=$.find(F=>F.key===T.launchConfirmWorkspaceKeyRef.current);T.setWorkspaceSelectionFromOption(W),await k({...R,workspace:(W==null?void 0:W.workspacePath)??null})})}}}),[T,k,N,y]),P=l.useMemo(()=>A.map(R=>({key:`recent-chat:${R.conversation.tabKey}`,primary:kt(R.conversation),secondary:GC(R.conversation,{timestampLabel:R.timestamp?Vp(R.timestamp):null}),unread:R.unread,onClick:()=>g(R.conversation)})),[g,A]),M=T.showAllRecent?L:L.slice(0,4),_=L.length>0,D=P.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:[D&&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:P.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))})]}),_&&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))}),L.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:()=>T.setShowAllRecent(R=>!R),children:T.showAllRecent?"Show fewer":`Show ${L.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"})]})]})]})]}),T.browseDialogOpen&&s.jsx(mc,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:T.browseCurrentPath,directories:T.browseDirectories,busy:T.browseBusy,error:T.browseError,confirmLabel:"Use this folder",onClose:()=>T.setBrowseDialogOpen(!1),onNavigate:R=>{T.loadBrowsePath(R)},onConfirm:R=>{T.chooseCustomWorkspacePath(R),T.setBrowseDialogOpen(!1)}}),T.launchConfirm&&s.jsx(jo,{title:T.launchConfirm.title,description:T.launchConfirm.description,details:T.launchConfirm.details,workspaceOptions:T.launchConfirm.workspaceOptions,selectedWorkspaceKey:T.launchConfirmWorkspaceKey,onWorkspaceChange:T.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:T.launchConfirm.providerType?rl(y,!!T.launchConfirmResumeId):T.launchConfirm.confirmLabel,busyLabel:T.launchConfirm.providerType?void 0:T.launchConfirm.busyLabel,busy:T.launchConfirmBusy,showArgsInput:T.launchConfirm.showArgsInput,argsValue:T.launchConfirmArgs,onArgsChange:T.setLaunchConfirmArgs,showModelInput:T.launchConfirm.showModelInput,modelValue:T.launchConfirmModel,onModelChange:T.setLaunchConfirmModel,historyProviderNode:T.launchConfirm.providerType&&(T.launchConfirmSessionsLoading||T.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"}),T.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:T.launchConfirmTextFilter,onChange:R=>T.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:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:T.launchConfirmWorkspaceFilter,onChange:R=>T.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:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:T.launchConfirmModelFilter,onChange:R=>T.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:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsxs("select",{value:T.launchConfirmSortMode,onChange:R=>T.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:T.launchConfirmBusy||T.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:T.launchConfirmResumableOnly,onChange:R=>T.setLaunchConfirmResumableOnly(R.target.checked),disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:T.launchConfirmResumeId,onChange:R=>T.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:T.launchConfirmBusy||T.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:kj(y)}),T.filteredLaunchConfirmSavedSessions.map(R=>s.jsxs("option",{value:R.providerSessionId,disabled:!R.canResume,children:[R.title||R.providerSessionId," ",R.canResume?"":"(workspace missing)"]},R.providerSessionId))]}),!T.launchConfirmSessionsLoading&&T.launchConfirmSavedSessions.length>0&&T.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),T.launchConfirmResumeId&&(()=>{const R=T.filteredLaunchConfirmSavedSessions.find(H=>H.providerSessionId===T.launchConfirmResumeId);if(!R)return null;const O=Oh(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:O.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:O.providerSessionId}),s.jsx("div",{className:"mt-1",children:O.metaLine}),O.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:O.updatedLabel}),O.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:O.preview})]})})()]}),onConfirm:T.handleConfirmLaunch,onCancel:T.closeLaunchConfirm}),u&&s.jsx(Wh,{section:p,onSectionChange:f})]})}const au=8e3;function yA(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 qh(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=yA(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 Pr(e){return[...e].sort((t,n)=>{const a=n.timestamp-t.timestamp;return a!==0?a:t.conversation.tabKey.localeCompare(n.conversation.tabKey)})}function wA(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:Pr(e)}function kA(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:Pr(n),unreadItems:Pr(a),workingItems:wA(r,t),completedItems:Pr(o)}}function No(e,t){if(!t)return!1;const n=e.filter(a=>a.type==="adhdev-daemon"&&zh(a)==="Connected");return n.length===0?!0:n.every(a=>a._sessionListAuthoritative===!0)}function zh(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 SA(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 CA(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=zh(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?qC(p,Um(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 jA(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 NA({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(A=>{pr("mark_read:result",{tabKey:y.tabKey,sessionId:y.sessionId,result:A})}).catch(A=>{pr("mark_read:error",{tabKey:y.tabKey,sessionId:y.sessionId,error:A instanceof Error?A.message:String(A)})})},[i,c]);return l.useEffect(()=>{var j;if(!a){jA(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 AA(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 TA(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function MA({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 v1(e,w,C);i(v.state),d(v.message)},[n,e]),h=l.useCallback(async(w,C,v,y)=>{var A,T,L;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 P={cliType:v};(A=y==null?void 0:y.workspacePath)!=null&&A.trim()?P.dir=y.workspacePath.trim():y!=null&&y.workspaceId?P.workspaceId=y.workspaceId:y!=null&&y.useHome&&(P.useHome=!0),y!=null&&y.resumeSessionId&&(P.resumeSessionId=y.resumeSessionId),(T=y==null?void 0:y.args)!=null&&T.trim()&&(P.cliArgs=y.args.trim().split(/\s+/).filter(Boolean)),(L=y==null?void 0:y.model)!=null&&L.trim()&&(P.initialModel=y.model.trim());const M=await r(w,P),_=(M==null?void 0:M.result)||M,D=(_==null?void 0:_.sessionId)||(_==null?void 0:_.id);if(M!=null&&M.success&&D){u(null),i("done"),d(`${v} launched`),t(Ba(D));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)||(_==null?void 0:_.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(P){if(TA(P)){i("loading"),d(`${v} launch requested — waiting for session…`);return}u(null),i("error"),d(P instanceof Error?P.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 P,M,_,D;if(!y||y.type==="adhdev-daemon"||AA(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 T=String(y.providerSessionId||"");if(p.resumeSessionId&&T)return T===p.resumeSessionId;if(w){const B=ru(y.workspace||y.runtimeWorkspaceLabel);return B?B===w:!1}return Number(y.lastUpdated||y._lastUpdate||y.timestamp||((D=(_=(M=(P=y.activeChat)==null?void 0:P.messages)==null?void 0:M.at)==null?void 0:_.call(M,-1))==null?void 0:D.timestamp)||0)>=p.startedAt-5e3});if(!C)return;const v=$h({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 PA(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function IA({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:A}){const[T,L]=l.useState(()=>{var Z;return((Z=e[0])==null?void 0:Z.tabKey)||null}),[P,M]=l.useState(()=>e[0]?"chat":"inbox"),[_,D]=l.useState("chats"),[B,R]=l.useState(null),[O,H]=l.useState("inbox"),$=l.useRef([]),I=oa(),W="1.0.52",F=l.useMemo(()=>e.find(Z=>Z.tabKey===T)||e[0]||null,[e,T]),z=l.useMemo(()=>F?n.find(Z=>Z.id===F.routeId):void 0,[n,F]),Q=l.useMemo(()=>!F||ht(F)||!gt(F)?null:la(F),[F]),ne=l.useMemo(()=>n.filter(Z=>Z.type==="adhdev-daemon").sort(Ul),[n]),oe=l.useMemo(()=>ne.find(Z=>Z.id===B)||null,[ne,B]),Ce=wo({sendDaemonCommand:r,activeConv:F||void 0,setActionLogs:o,isStandalone:i}),le=MA({sendDaemonCommand:r,navigate:I,ides:n,conversations:e}),U=yC(e),J=l.useMemo(()=>e.map(Z=>{const we=P==="chat"&&(F==null?void 0:F.tabKey)===Z.tabKey,ge=fo(Z,N,{hideOpenTaskCompleteUnread:!0,isOpenConversation:we}),be=jn(Z),De=Um(Z),Me=Qm(Z,De);return{conversation:Z,timestamp:be,preview:Me,unread:ge.unread,requiresAction:ge.requiresAction,isWorking:ge.isWorking,inboxBucket:ge.inboxBucket}}),[e,N,P,F,U]),{markConversationRead:ee}=NA({conversations:e,machineEntries:ne,items:J,selectedConversation:F,selectedTabKey:T,screen:P,liveSessionInboxState:N,sendDaemonCommand:r,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,setSelectedTabKey:L,setScreen:M,setSelectedMachineId:R,setSection:D,setMachineBackTarget:H,resetMachineAction:le.resetMachineAction}),Y=DA({conversations:e,selectedConversation:F,machineBackTarget:O,markConversationRead:ee,resetMachineAction:le.resetMachineAction,setSelectedTabKey:L,setScreen:M,setSelectedMachineId:R,setSection:D,setMachineBackTarget:H}),{isMuted:ve,toggleMute:pe}=qh(N,r),{attentionItems:te,unreadItems:me,workingItems:V,completedItems:q}=l.useMemo(()=>kA(J,$.current),[J]);l.useEffect(()=>{$.current=V.map(Z=>Z.conversation.tabKey)},[V]);const se=l.useMemo(()=>oe?J.filter(Z=>Ks(Z.conversation)===oe.id):[],[J,oe]),de=l.useMemo(()=>SA(oe,n),[n,oe]),K=!!oe&&So(oe,Qs(oe,W)),fe=l.useMemo(()=>(oe==null?void 0:oe.availableProviders)||[],[oe]),ie=l.useMemo(()=>fe.filter(Z=>na(Z,"cli")).map(Z=>({type:Z.type,displayName:Z.displayName||Z.type,icon:Z.icon})),[fe]),ue=l.useMemo(()=>fe.filter(Z=>na(Z,"acp")).map(Z=>({type:Z.type,displayName:Z.displayName||Z.type,icon:Z.icon})),[fe]),ye=l.useMemo(()=>CA(ne,J,t),[J,ne,t]),Ie=l.useMemo(()=>No(n,w),[n,w]),E=l.useCallback(async Z=>{oe&&await le.handleOpenRecent(oe.id,Z)},[le,oe]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:P==="chat"&&F?s.jsx(dA,{selectedConversation:F,isAcp:ht(F),isStandalone:i,selectedIdeEntry:z,actionLogs:a,userName:c,isSendingChat:Ce.isSendingChat,sendFeedbackMessage:Ce.sendFeedbackMessage,isFocusingAgent:Ce.isFocusingAgent,handleModalButton:Ce.handleModalButton,handleRelaunch:Ce.handleRelaunch,onBack:Y.backFromConversation,onOpenNativeConversation:Y.openNativeConversation,onOpenMachine:Y.openConversationMachine,onOpenHistory:k,onOpenRemote:h,onOpenMeshGraph:y,onStopCli:x,cliViewMode:Q,onSetCliViewMode:async Z=>{await Th({conversation:F,mode:Z,ides:n,sendDaemonCommand:r,setCliViewModeOverrides:A})},handleSendChat:Ce.handleSendChat,handleForceSendChat:Ce.handleForceSendChat,handleFocusAgent:Ce.handleFocusAgent}):P==="machine"&&oe?s.jsx(vA,{selectedMachineEntry:oe,selectedMachineConversations:se,selectedMachineRecentLaunches:de,cliProviders:ie,acpProviders:ue,selectedMachineNeedsUpgrade:K,appVersion:W,machineAction:le.machineAction,isStandalone:i,section:_,showBottomNav:O==="inbox",onBack:Y.backFromMachine,onSectionChange:Y.changeMachineSection,onOpenConversation:Y.openConversation,onOpenRecent:E,onOpenMachineDetails:()=>I(`/machines/${oe.id}`),onMachineUpgrade:()=>le.handleMachineUpgrade(oe.id),onLaunchDetectedIde:(Z,we)=>le.handleLaunchDetectedIde(oe.id,Z,we),onAddWorkspace:(Z,we)=>le.handleAddWorkspace(oe.id,Z,we),onBrowseDirectory:Z=>le.handleBrowseDirectory(oe.id,Z),onLaunchWorkspaceProvider:(Z,we,ge)=>le.handleLaunchWorkspaceProvider(oe.id,Z,we,ge),onListSavedSessions:Z=>le.handleListSavedSessions(oe.id,Z)}):s.jsx(mA,{section:_,attentionItems:te,unreadItems:me,workingItems:V,completedItems:q,hiddenConversations:t,machineCards:ye,getAvatarText:PA,actionLogs:a,sendDaemonCommand:r,onOpenConversation:Y.openConversation,onShowAllHidden:C,onHideConversation:v,onOpenMeshGraph:y,onStopCli:x,onOpenNewSession:j,onOpenMachine:Y.openMachine,onOpenSettings:()=>I("/settings"),onSectionChange:D,wsStatus:S,isConnected:b,initialDataLoaded:w,conversationsLoaded:Ie,isStandalone:i,isConversationMuted:ve,onToggleMuteConversation:pe})})}function ii(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function LA({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 RA(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 EA({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=RA(j,e);return N.length===j.length&&N.every((A,T)=>A===j[T])?j:N})},[e]);const h=l.useMemo(()=>{const j=p??c;if(j.length===0)return e;const N=new Map(j.map((A,T)=>[A,T]));return[...e].sort((A,T)=>{const L=N.get(A.tabKey)??999,P=N.get(T.tabKey)??999;return L-P})},[e,p,c]);l.useEffect(()=>{var N,A;if(h.length===0){o!==null&&(i(null),(N=g.current)==null||N.call(g,null));return}if(o&&h.some(T=>T.tabKey===o))return;const j=h[0].tabKey;j!==o&&(i(j),(A=g.current)==null||A.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,A)=>{d(T=>{var _;const L=T.filter(D=>D!==j),P=L.indexOf(N);if(P<0)return T;const M=A==="left"?P:P+1;return L.splice(M,0,j),(_=k.current)==null||_.call(k,L),L}),u(null)},[]),w=l.useCallback((j,N,A)=>{const L=(c.length>0?c:e.map(_=>_.tabKey)).filter(_=>_!==j),P=L.indexOf(N);if(P<0)return;const M=A==="left"?P:P+1;L.splice(M,0,j),m.current=L,u(L)},[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 T;const A=N.filter(L=>L!==j);return A.push(j),(T=k.current)==null||T.call(k,A),A})},[]);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 _A({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(Bh,{}),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 Kh="adhdev-tab-shortcuts";function Vh(){try{return JSON.parse(localStorage.getItem(Kh)||"{}")}catch{return{}}}function Yh({enabled:e=!0,sortedTabKeys:t,onFocus:n,onSelectTab:a}){const r=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>Vh()),[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(Kh,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()},HA=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=OC(t),A=UC(t),T=Ym(t),L=l.useCallback($=>{c.current=t.tabKey,x(t.tabKey),$.dataTransfer.setData("text/tab-key",t.tabKey),$.dataTransfer.effectAllowed="move"},[t.tabKey,c,x]),P=l.useCallback(()=>{c.current=null,x(null),g(),k(),h()},[c,x,g,k,h]),M=l.useCallback($=>{const I=c.current;if(!(!I||I===t.tabKey)&&$.dataTransfer.types.includes("text/tab-key")){$.preventDefault(),$.stopPropagation();const W=$.currentTarget.getBoundingClientRect(),F=$.clientX<W.left+W.width/2?"left":"right";m(I,t.tabKey,F)}},[t.tabKey,c,m]),_=l.useCallback($=>{$.preventDefault(),$.stopPropagation();const I=$.dataTransfer.getData("text/tab-key");if(I&&I!==t.tabKey){const W=$.currentTarget.getBoundingClientRect(),F=$.clientX<W.left+W.width/2?"left":"right";i.includes(I)?f(I,t.tabKey,F):S&&S(I)}k()},[t.tabKey,i,f,S,k]),D=l.useCallback($=>{$.stopPropagation(),d(),p(t.tabKey),u(t)},[t,u,d,p]),B=l.useCallback($=>{$.preventDefault(),b($.clientX,$.clientY,t.tabKey)},[t.tabKey,b]),R=l.useCallback($=>{const I=$.touches[0];w.current=setTimeout(()=>{b(I.clientX,I.clientY,t.tabKey)},600)},[t.tabKey,w,b]),O=l.useCallback(()=>{w.current&&clearTimeout(w.current)},[w]),H=["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:H,draggable:!0,onDragStart:L,onDragEnd:P,onDragOver:M,onDrop:_,onClick:D,onContextMenu:B,onTouchStart:R,onTouchEnd:O,onTouchMove:O,style:{position:"relative",cursor:"pointer",opacity:a?.4:void 0},children:[T&&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:A,"aria-label":A||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 $A({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(_=>_.tabKey),[e]);Ga("PaneGroupTabBar",{groupIndex:n,activeTabId:t,tabCount:e.length,ctxMenuTab:(w==null?void 0:w.tabKey)||null});const{isMac:N,tabShortcuts:A,shortcutListening:T,setShortcutListening:L,saveShortcuts:P}=Yh({enabled:S,sortedTabKeys:e.map(_=>_.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!w)return;const _=D=>{const B=document.querySelector("[data-pane-context-menu]");B&&B.contains(D.target)||C(null)};return window.addEventListener("mousedown",_,!0),()=>window.removeEventListener("mousedown",_,!0)},[w]),l.useEffect(()=>{const _=y.current;if(!_)return;const D=B=>{Math.abs(B.deltaY)<=Math.abs(B.deltaX)||(B.preventDefault(),_.scrollLeft+=B.deltaY)};return _.addEventListener("wheel",D,{passive:!1}),()=>_.removeEventListener("wheel",D)},[]);const M=l.useCallback((_,D,B)=>{C({x:_,y:D,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(_=>s.jsx(HA,{conv:_,isActive:t===_.tabKey,isDraggedTab:r.current===_.tabKey,isTaskCompleteUnread:a.has(_.tabKey),shortcut:S?A[_.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},_.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:_=>{_.stopPropagation(),L(w.tabKey),C(null)},children:["⌨ ",A[w.tabKey]?`Change shortcut (${A[w.tabKey]})`:"Set shortcut"]}),A[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 _={...A};delete _[w.tabKey],P(_),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&&T&&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:()=>L(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:_=>_.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 FA({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:A}){const{sendCommand:T}=St(),L=l.useRef(null),{activeTabId:P,activeConv:M,sortedConversations:_,draggingTabRef:D,selectTab:B,handleTabReorder:R,updatePreviewOrder:O,commitPreviewOrder:H,clearPreviewOrder:$,moveTabToEnd:I,setDraggingTabKey:W}=EA({conversations:e,initialActiveTabId:b,initialTabOrder:w,onActiveTabChange:S,onTabOrderChange:C}),F=wo({sendDaemonCommand:r,activeConv:M,setActionLogs:o,isStandalone:i}),{dragOver:z,dropAction:Q,resetDragState:ne,handleDragEnter:oe,handleDragOver:Ce,handleDragLeave:le,handleDrop:U}=LA({conversations:e,numGroups:g,onMoveTab:k,onReceiveTab:h,onOwnTabDrop:I,onClearPreviewOrder:$}),J=M&&!ht(M)&&la(M)==="terminal",ee=l.useMemo(()=>M?t.find(te=>te.id===M.routeId):void 0,[t,M]),Y=l.useMemo(()=>M?a.filter(te=>te.routeId===M.tabKey):[],[a,M]),ve=l.useMemo(()=>new Set(_.filter(te=>Ax(te,A,{isOpenConversation:te.tabKey===P})).map(te=>te.tabKey)),[P,A,_]);Ga("PaneGroup",{groupIndex:u,conversationCount:e.length,activeTabId:P,dragOver:z});const pe=l.useCallback(te=>{te.streamSource==="agent-stream"&&te.agentType&&T(te.routeId,Dm(),{agentType:te.agentType,...te.sessionId&&{targetSessionId:te.sessionId}}).catch(()=>{})},[T]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:m,style:{...x,outline:z?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx($A,{conversations:_,activeTabId:P,groupIndex:u,numGroups:g,unreadTabKeys:ve,draggingTabRef:D,onFocus:m,onSelectTab:B,onConversationActivated:pe,onPreviewReorder:O,onReorderTab:R,onCommitPreviewOrder:H,onClearPreviewOrder:$,onDragStateReset:ne,onDragTabKeyChange:W,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:oe,onDragOver:Ce,onDragLeave:le,onDrop:U,children:[z&&s.jsx(_A,{dropAction:Q,canSplit:!!(g<4&&k)}),M?s.jsx(pc,{activeConv:M,clearToken:n[M.tabKey]||0,isCliTerminal:!!J,ideEntry:ee,terminalRef:L,handleModalButton:F.handleModalButton,handleRelaunch:F.handleRelaunch,handleSendChat:F.handleSendChat,handleForceSendChat:F.handleForceSendChat,isSendingChat:F.isSendingChat,sendFeedbackMessage:F.sendFeedbackMessage,handleFocusAgent:F.handleFocusAgent,isFocusingAgent:F.isFocusingAgent,actionLogs:Y,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 BA({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:A,allowTabShortcuts:T=!0,liveSessionInboxState:L}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:r.map((P,M)=>{const _=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:D=>w(M-1,D),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(FA,{style:t?{flexBasis:_??`${100/n}%`,flexGrow:_?0:1,flexShrink:_?0:1}:void 0,conversations:P,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:(D,B)=>{B==="left"&&M>0?x(D,M-1):B==="right"&&M<n-1?x(D,M+1):B==="split-left"&&n<4?S(D,M,"left"):B==="split-right"&&n<4&&S(D,M,"right")},onReceiveTab:D=>x(D,M),onActiveTabChange:D=>v(M,D),initialActiveTabId:C[M],initialTabOrder:y[M],onTabOrderChange:D=>j(M,D),onHideTab:N,onOpenNewSession:A,allowTabShortcuts:T,liveSessionInboxState:L})]},M)})})}const Qh="adhdev-dashboard-action-shortcuts",WA=1200,OA=[["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 UA(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function ft(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 Jh(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:ft("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:ft("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:ft("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:ft("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:ft("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:ft("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:ft("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:ft("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:ft("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:ft("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:ft("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:ft("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:ft("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:ft("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:ft("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:ft("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:ft("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:ft("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:ft("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:ft("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:ft("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:ft("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:ft("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:ft("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:ft("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:ft("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(Jh(e).map(n=>[n.id,n.defaultShortcut]));try{const n=JSON.parse(localStorage.getItem(Qh)||"{}"),a={...t,...n};for(const[r,o]of OA)a[r]===o&&(a[r]=t[r]);return a}catch{return t}}function Xh(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function GA({enabled:e=!0,onTrigger:t}){const n=UA(),[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(Xh(h.key)),x.join("+"))},[n]),m=l.useCallback(h=>{r(h);try{localStorage.setItem(Qh,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}},WA))},[]);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(([,P])=>!!P),N=j.find(([,P])=>P===v);if(N){x.preventDefault(),f(),t(N[0]);return}if(j.some(([,P])=>P.startsWith(`${v} `))){x.preventDefault(),p.current.parts=C,g();return}const T=j.find(([,P])=>P===y);if(T){x.preventDefault(),f(),t(T[0]);return}if(j.some(([,P])=>P.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(()=>Jh(n),[n]);return{isMac:n,actionDefinitions:k,actionShortcuts:a,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:d,saveShortcuts:m}}function qA({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 Zh(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?!Zh(a):!0}function zA({previousVisibleConversationCount:e,visibleConversationCount:t,ides:n}){return t>0||e<=0?!1:Zh(n)}const ef=1e3,KA=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 VA({detachDelayMs:e=ef,stillnessThresholdPx:t=KA,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 YA(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 QA(e){return`remote:${e}`}function fs(e){return e.startsWith("remote:")}function cu(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}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 JA(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?QA(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=Zm(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 tf({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 sf=l.createContext(null);function Ao(){const e=l.useContext(sf);if(!e)throw new Error("DashboardDockviewContext missing");return e}function XA(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 ZA({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}=tf({doId:r,targetSessionId:n?Tm(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(qp,{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 eT(){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 tT(e){var b,w;XA(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=>CC(C),[]),i=l.useCallback(()=>SC(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 sT(e){e.preventDefault()}function nT({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 aT({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,nt,rt;const{theme:y}=Ls(),{sendCommand:j}=St(),N=l.useRef(null),A=l.useRef(null),T=l.useRef(null),L=l.useRef(!1),P=l.useRef(!1),M=l.useRef(!1),_=l.useRef(null),D=l.useRef([]),[B,R]=l.useState(null),[O,H]=l.useState(0),$=l.useRef(typeof window>"u"?{}:kN(v)),I=l.useMemo(()=>new Map(e.map(G=>[G.tabKey,G])),[e]),W=l.useMemo(()=>{const G=N.current;return G?G.groups.some(re=>{try{const ce=re.model.location.type;return ce!=="floating"&&ce!=="popout"?!1:re.panels.some(xe=>I.has(xe.id))}catch{return!1}}):!1},[I,O,e]),F=l.useCallback(()=>{var G;(G=N.current)==null||G.focus()},[]),z=l.useCallback((G,re)=>{h==null||h(G,re)},[h]),Q=l.useCallback(G=>{const re=document,ce=G.document;for(const Re of re.querySelectorAll('link[rel="stylesheet"]')){const Qe=ce.createElement("link");Qe.rel="stylesheet",Qe.href=Re.href,Re.crossOrigin&&(Qe.crossOrigin=Re.crossOrigin),ce.head.appendChild(Qe)}for(const Re of re.querySelectorAll("style")){const Qe=ce.createElement("style");Qe.textContent=Re.textContent,ce.head.appendChild(Qe)}const xe=[];for(const Re of re.styleSheets)try{for(const Qe of Re.cssRules)Qe instanceof CSSStyleRule&&(Qe.selectorText===":root"||Qe.selectorText==="html")&&xe.push(Qe.cssText)}catch{}if(xe.length>0){const Re=ce.createElement("style");Re.textContent=xe.join(`
66
66
  `),ce.head.appendChild(Re)}const Se=re.documentElement.getAttribute("data-theme");Se&&ce.documentElement.setAttribute("data-theme",Se),ce.documentElement.style.colorScheme=Se==="light"?"light":"dark",ce.body.className=re.body.className;const Ae=re.documentElement.getAttribute("style");Ae&&ce.documentElement.setAttribute("style",Ae);const Ee=ce.getElementById("dv-popout-window");Ee instanceof HTMLElement&&(Ee.classList.add("adhdev-dockview"),di(Ee,y))},[y]),ne=l.useCallback(()=>{var re;const G=N.current;if(G)for(const ce of G.groups)try{const xe=(re=ce.element)==null?void 0:re.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 Ae=document.documentElement.getAttribute("data-theme");Ae&&xe.documentElement.setAttribute("data-theme",Ae),xe.documentElement.style.colorScheme=Ae==="light"?"light":"dark",xe.body.className=document.body.className;const Ee=document.documentElement.getAttribute("style");Ee?xe.documentElement.setAttribute("style",Ee):xe.documentElement.removeAttribute("style")}catch{}},[y]),oe=l.useCallback(G=>{const re=N.current;if(!re)return;const ce=re.getPanel(G);ce&&re.addPopoutGroup(ce,{popoutUrl:"/popout.html",onDidOpen:({window:xe})=>{Q(xe),te();const Se=I.get(G);xe.document.title=Se?`${kt(Se)} — ADHDev`:"ADHDev — Popout"}})},[I,Q]),Ce=l.useCallback(G=>{const re=N.current,ce=re==null?void 0:re.getPanel(G);if(!re||!ce)return;const xe=re.groups.filter(Se=>{var Ae;try{return((Ae=Se.element)==null?void 0:Ae.ownerDocument)===document}catch{return!0}});xe.length>0?ce.api.moveTo({group:xe[0],position:"center"}):ce.api.moveTo({position:"center"}),ce.api.setActive()},[]),le=l.useCallback(G=>{var xe;const re=N.current;if(!re)return!1;const ce=re.getPanel(G);if(!ce)return!1;try{return((xe=ce.group.element)==null?void 0:xe.ownerDocument)!==document}catch{return!1}},[]),U=l.useCallback(G=>{le(G)&&Ce(G),u(G)},[le,Ce,u]),J=l.useCallback(G=>{const re=N.current,ce=re==null?void 0:re.getPanel(G);!re||!ce||re.addFloatingGroup(ce,{width:600,height:500})},[]),ee=l.useCallback(G=>{var ce;const re=(ce=N.current)==null?void 0:ce.getPanel(G);if(!re)return!1;try{return re.group.model.location.type==="floating"}catch{return!1}},[]),Y=l.useCallback(()=>{var re,ce;const G=(ce=(re=N.current)==null?void 0:re.activePanel)==null?void 0:ce.id;return!G||fs(G)?null:I.has(G)?G:null},[I]),ve=l.useCallback(G=>{const re=N.current,ce=re==null?void 0:re.getPanel(G);if(!re||!ce)return;const xe=re.groups.filter(Se=>{try{return Se.model.location.type==="grid"}catch{return!0}});xe.length>0?ce.api.moveTo({group:xe[0],position:"center"}):ce.api.moveTo({position:"center"}),ce.api.setActive()},[]),pe=l.useCallback(()=>{var Ae;const G=N.current;if(!G)return;const ce=G.groups.filter(Ee=>{var Re;try{return((Re=Ee.element)==null?void 0:Re.ownerDocument)===document&&Ee.model.location.type==="grid"}catch{return!1}})[0]||null,xe=[...G.panels];for(const Ee of xe){const Re=(Ae=Ee.group.element)==null?void 0:Ae.ownerDocument,Qe=Ee.group.model.location.type;Re===document&&Qe==="grid"||(ce&&ce.id!==Ee.group.id?Ee.api.moveTo({group:ce,position:"center"}):Ee.api.moveTo({position:"center"}))}const Se=G.activePanel;Se&&(Se.group.model.openPanel(Se),Se.api.setActive()),ci(document)},[]),te=l.useCallback(()=>{var re,ce;const G=N.current;if(G)for(const xe of G.groups){const Se=(re=xe.element)==null?void 0:re.ownerDocument;if(!Se||Se===document)continue;const Ae=Se.getElementById("dv-popout-window");if(!(Ae instanceof HTMLElement))continue;let Ee=null,Re=Se.title||"ADHDev",Qe="Popout workspace";const et=xe.activePanel;if(et)if(Ee=et.id,fs(et.id)){const $e=((ce=et.params)==null?void 0:ce.routeId)||et.id.slice(7),he=ws([...I.values()],$e);Re=Zm(he),Qe=he!=null&&he.machineName?`Remote view · ${he.machineName}`:"Remote view"}else{const $e=I.get(et.id);Re=$e?kt($e):et.title||et.id,Qe=$e?kn($e):"Dockview panel"}Se.title=`${Re} — ADHDev`;const Je=Array.from(Se.querySelectorAll("#adhdev-popout-header"));for(const $e of Je)$e.remove();const Oe=Se.createElement("div");Oe.id="adhdev-popout-header",Se.body.appendChild(Oe),Oe.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(";")),Oe.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 I=await n(
111
111
 
112
112
  `)}function oL(e,t){return t==="issues"?e.filter(n=>n.level==="warn"||n.level==="error"):t==="info"?e.filter(n=>n.level!=="debug"):e}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({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=$I(a,o),g=WI(e,c),k=GI(t,c),h=qI(f,c),x=zI(r,c),S=oL(g,i),b=i==="all"?k:[],w=iL(h,i),C=i==="issues"?[]:x,v=KI({daemonLogs:g,daemonRawLines:k,trace:h,webEvents:x}),y=tL({daemonLogs:S,daemonRawLines:b,trace:w,webEvents:C}),j=nL(y),N=QI({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 cL(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Jf(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 dL({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:Jf(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 uL({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 pL({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:_I.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 mL({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:Jf(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: ",cL(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 hL({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 fL({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(dL,{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 gL({machineId:e,sendDaemonCommand:t}){const n=YI({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(()=>lL({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=VI({daemonLogs:m.visibleDaemonLogs,daemonRawLines:m.visibleDaemonRawLines,trace:m.visibleTraceEntries,webEvents:m.visibleWebEvents});if(!k.trim()){xt.showToast("No visible logs to copy.","info");return}try{await((h=navigator.clipboard)==null?void 0:h.writeText(k)),xt.showToast("Copied visible logs to clipboard.","success")}catch(x){xt.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=rL({events:m.diagnosticEvents,summary:m.diagnosticsSummary,sources:m.sourceStates});try{await((h=navigator.clipboard)==null?void 0:h.writeText(k)),xt.showToast("Copied diagnostic bundle to clipboard.","success")}catch(x){xt.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(uL,{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(pL,{logLevel:n.logLevel,traceCategory:n.traceCategory,onLogLevelChange:n.setLogLevel,onTraceCategoryChange:n.setTraceCategory}),s.jsx(mL,{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(hL,{patterns:m.diagnosticsSummary.repeatedPatterns}),s.jsx(fL,{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 bL(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 Xf(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 xL(e){var r;const t=[],n=[],a=[];for(const o of e||[]){const i=String((o==null?void 0:o.lifecycle)||"").trim(),c=Xf((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 vL(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 Di(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Pi(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 yL(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function wL(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 kL(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 SL({machineId:e,cliSessions:t,sendDaemonCommand:n}){const[a,r]=l.useState(""),[o,i]=l.useState(null),[c,d]=l.useState(!1),p=G1(e,{enabled:!!e,includeSessions:!0,limit:xd,intervalMs:zS}),u=p.diagnostics,m=p.loading,f=p.applyDiagnostics,g=l.useMemo(()=>bL({diagnostics:u,loading:m,refreshing:c,error:a}),[u,m,c,a]),k=l.useMemo(()=>new Map(t.map(L=>[L.sessionId||L.id,L])),[t]),h=l.useCallback(async()=>{if(e){d(!0);try{const L=await n(e,"session_host_get_diagnostics",{includeSessions:!0,limit:xd}),P=Di(L);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Could not load hosted runtime diagnostics");f(P.diagnostics||P.result||null),r("")}catch(L){const P=L instanceof Error?L.message:"Could not load hosted runtime diagnostics";r(P)}finally{d(!1)}}},[f,e,n]);l.useEffect(()=>{!e||u||m||c||h()},[u,m,e,h,c]);const x=l.useCallback(async(L,P)=>{const M=`${L}:${P.sessionId}`;if(!(L==="session_host_stop_session"&&!window.confirm(`Stop ${P.displayName}?
113
113
  This will terminate the hosted runtime.`))){i(M);try{const _=await n(e,L,{sessionId:P.sessionId}),D=Di(_);if(!(D!=null&&D.success))throw new Error((D==null?void 0:D.error)||"Session host action failed");const B=L==="session_host_resume_session"?"resumed":L==="session_host_restart_session"?"restarted":"stopped";xt.showToast(`Session host ${B}: ${P.displayName}`,"success"),await h()}catch(_){const D=_ instanceof Error?_.message:"Session host action failed";xt.showToast(D,"warning"),r(D)}finally{i(_=>_===M?null:_)}}},[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 P=await n(e,"session_host_prune_duplicate_sessions",{}),M=Di(P);if(!(M!=null&&M.success))throw new Error((M==null?void 0:M.error)||"Duplicate prune failed");const _=M.result||{},D=Array.isArray(_.prunedSessionIds)?_.prunedSessionIds.length:0,B=typeof _.duplicateGroupCount=="number"?_.duplicateGroupCount:0;xt.showToast(`Pruned ${D} duplicate runtime(s) across ${B} group(s)`,"success"),await h()}catch(P){const M=P instanceof Error?P.message:"Duplicate prune failed";xt.showToast(M,"warning"),r(M)}finally{i(P=>P==="session_host_prune_duplicate_sessions"?null:P)}}},[e,h,n]),b=l.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((L,P)=>(P.lastActivityAt||0)-(L.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)||[]}:xL(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(()=>kL(C),[C]),N=l.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),A=l.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(L=>L.level==="warn"||L.level==="error")||null,[u==null?void 0:u.recentLogs]),T=(L,P)=>{var I;const M=o===`session_host_resume_session:${L.sessionId}`,_=o===`session_host_restart_session:${L.sessionId}`,D=o===`session_host_stop_session:${L.sessionId}`,B=Xf(L.meta),R=k.get(L.sessionId),O=L.attachedClients.length===1?"1 client":`${L.attachedClients.length} clients`,H=P==="recovery"?"Recover":"Resume",$=vL(P);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:L.displayName||(R==null?void 0:R.cliName)||L.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${wL(L.lifecycle)}`,children:L.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:L.workspaceLabel||(R==null?void 0:R.runtimeWorkspaceLabel)||L.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:L.runtimeKey}),L.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",L.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((I=L.writeOwner)==null?void 0:I.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:yL(L.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(Sp,{size:11})," ",O]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",zu(L.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",$]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[P==="recovery"&&(L.lifecycle==="interrupted"||L.lifecycle==="failed"||L.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{x("session_host_resume_session",L)},children:M?`${H}ing…`:H}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{x("session_host_restart_session",L)},children:_?"Restarting…":"Restart"}),P==="live"&&(L.lifecycle==="running"||L.lifecycle==="starting"||L.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",L)},children:D?"Stopping…":"Stop"})]})]})},L.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:Sj()})]}),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:Pi(u.hostStartedAt)})]})]}),A&&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:A.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Pi(A.timestamp),A.sessionId?` · ${A.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(L=>T(L,"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(L=>T(L,"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(L=>T(L,"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(L=>{var M;const P=b.find(_=>_.sessionId===L.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:(P==null?void 0:P.displayName)||((M=k.get(L.sessionId))==null?void 0:M.cliName)||L.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[L.action,L.lifecycle?` · ${L.lifecycle}`:"",L.detail?` · ${L.detail}`:"",L.error?` · ${L.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${L.success===!1?"text-red-300":"text-text-secondary"}`,children:Pi(L.timestamp)})]},`${L.sessionId}:${L.timestamp}:${L.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 CL({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 jL(e,t){const n=x1(e),a=Qs(e,t),r=So(e,a),o=Da(e,a),i=vh(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 NL({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=jL(e,"1.0.51");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(Ps,{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(jp,{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}=Gh(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 AL({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 A=await uc(i,e,N);h(A.path),S(A.directories)}catch(A){v(A instanceof Error?A.message:"Could not load folder")}finally{w(!1)}},[e,i]),j=l.useCallback(()=>{g(!0);const N=[...n.map(T=>T.workspace),...a.map(T=>T.workspace),...r.map(T=>T.workspace)],A=dc(t.platform,cc(N,t.defaultWorkspacePath,(t.workspaces||[]).map(T=>T.path)));y(A)},[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 A=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 ${A?"border-yellow-500/30 bg-yellow-500/[0.05]":"border-border-subtle bg-bg-primary"}`,children:[s.jsx("button",{type:"button",title:A?"Default workspace — click to unset":"Set as default workspace",disabled:c,onClick:()=>void u(A?null:N.id),className:`text-base leading-none shrink-0 transition-colors ${A?"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:om(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 TL({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(AL,{machineId:t,machine:e,ideSessions:n,cliSessions:a,acpSessions:r,actions:o,sendDaemonCommand:i})]})}function ML({onNicknameSynced:e}={}){var me,V,q,se,de,K,fe,ie,ue,ye,Ie;const{t}=ke("common"),{id:n}=Eg(),a=oa(),r=Dl(),{sendCommand:o}=St(),i=ca(),c=Ch(),d=Km(),p=d.ides||[],u=d.initialLoaded??!0,m=p.find(E=>E.id===n&&E.type==="adhdev-daemon"),f=p.some(E=>E.type==="adhdev-daemon"),g=n?(me=d.connectionRetryStatuses)==null?void 0:me[n]:void 0,k=!!(g!=null&&g.blocked),[h,x]=l.useState("workspace"),[S,b]=l.useState(null),[w,C]=l.useState(null);l.useCallback((E,Z)=>{C({daemonId:E,workspace:Z})},[]);const[,v]=l.useState("ide"),y=l.useRef(null),[j,N]=l.useState(null),A=l.useRef("__home__"),[T,L]=l.useState("__home__"),[P,M]=l.useState(!1),_=l.useRef(null);l.useEffect(()=>{!n||!m||!(!m.workspaces||!m.availableProviders||!m.detectedIdes||!m.recentLaunches)||i(n,{minFreshMs:3e4}).catch(()=>{})},[i,m,n]),l.useEffect(()=>{if(!n||!m)return;let E=!1;return(async()=>{try{const Z=await o(n,"get_status_metadata"),we=Z&&typeof Z=="object"&&"result"in Z?Z.result:Z,ge=we==null?void 0:we.providerChannelStaleness;!E&&ge&&!ge.error&&b({staleTypes:Array.isArray(ge.staleTypes)?ge.staleTypes:[],newTypes:Array.isArray(ge.newTypes)?ge.newTypes:[]})}catch{}})(),()=>{E=!0}},[n,m==null?void 0:m.id,o]),l.useEffect(()=>{if(!n||!m||h!=="overview"&&h!=="providers")return;const E=m.machine;(typeof(E==null?void 0:E.cpus)!="number"||typeof(E==null?void 0:E.totalMem)!="number"||typeof(E==null?void 0:E.arch)!="string"||typeof(E==null?void 0:E.release)!="string"||h==="providers"&&!(E!=null&&E.quota))&&c(n,{minFreshMs:3e4}).catch(()=>{})},[h,c,m,n]),U1(n&&h==="overview"?[n]:[],{enabled:h==="overview",intervalMs:US});const D=()=>{if(f){a("/dashboard",{state:{mobileSection:"machines"}});return}a("/machines")},B=yI({machineId:n,registeredMachineId:(m==null?void 0:m.machineId)||null,sendDaemonCommand:o,onNicknameSynced:e,logsEndRef:_});l.useEffect(()=>xt.onToast(Z=>{d.setToasts(ge=>{if(ge.some(Me=>Me.message===Z.message&&Z.timestamp-Me.timestamp<3e3))return ge;const De={id:Z.id,message:Z.message,type:Z.type,timestamp:Z.timestamp,targetKey:Z.targetKey,actions:Z.actions};return[...ge.slice(-4),De]});const we=Z.duration||5e3;setTimeout(()=>d.setToasts(ge=>ge.filter(be=>be.id!==Z.id)),we)}),[d]);const R=(m==null?void 0:m.availableProviders)||[],O={};for(const E of R)O[E.type]=E.icon;const H=m?{id:m.id,hostname:im(m,{fallbackId:m.id}),platform:((V=m.machine)==null?void 0:V.platform)||"unknown",arch:((q=m.machine)==null?void 0:q.arch)||"",cpus:((se=m.machine)==null?void 0:se.cpus)||0,totalMem:((de=m.machine)==null?void 0:de.totalMem)||0,freeMem:(K=m.machine)==null?void 0:K.freeMem,availableMem:(fe=m.machine)==null?void 0:fe.availableMem,loadavg:(ie=m.machine)==null?void 0:ie.loadavg,uptime:(ue=m.machine)==null?void 0:ue.uptime,release:((ye=m.machine)==null?void 0:ye.release)||"",cdpConnected:!!m.cdpConnected,machineNickname:m.machineNickname||null,...(Ie=m.machine)!=null&&Ie.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,$=p.filter(E=>E.daemonId===n&&E.type!=="adhdev-daemon").filter(E=>!$a(E)&&!Jn(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,version:E.version||"",instanceId:E.instanceId||"",status:E.status,workspace:E.workspace||null,terminals:E.terminals||0,aiAgents:J0(E.aiAgents||(E.agents||[]).map(Z=>({id:Z.name,name:Z.name,status:Z.status,version:Z.version}))),activeChat:E.activeChat||null,chats:E.chats||[],childSessions:E.childSessions||[],cdpConnected:E.cdpConnected||!1,daemonId:n,lastMessageAt:E.lastMessageAt})),I=p.filter(E=>E.daemonId===n&&$a(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,cliName:E.cliName||E.type,status:E.status,workspace:E.workspace||"",activeChat:E.activeChat||null,providerSessionId:E.providerSessionId,mode:E.mode,runtimeKey:E.runtimeKey,runtimeDisplayName:E.runtimeDisplayName,runtimeWorkspaceLabel:E.runtimeWorkspaceLabel,runtimeWriteOwner:E.runtimeWriteOwner||null,runtimeAttachedClients:E.runtimeAttachedClients||[],daemonId:n,lastMessageAt:E.lastMessageAt})),W=p.filter(E=>E.daemonId===n&&Jn(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,acpName:E.cliName||E.type,status:E.status,workspace:E.workspace||"",activeChat:E.activeChat||null,providerSessionId:E.providerSessionId,daemonId:n,lastMessageAt:E.lastMessageAt})),F=m?ds(m,{fallbackId:n}):"",z="workspace",Q=r.state,ne=Q==null?void 0:Q.initialMachineTab,oe=Q==null?void 0:Q.initialWorkspaceCategory;Q==null||Q.initialWorkspaceId,Q==null||Q.initialWorkspacePath;const Ce=ne==="ides"||ne==="clis"||ne==="acps"?"workspace":ne||z,le=ne==="ides"?"ide":ne==="clis"?"cli":ne==="acps"?"acp":oe,U=[...$.map(E=>{var Z;return{id:`ide:${E.type}:${E.workspace||""}`,label:((Z=E.activeChat)==null?void 0:Z.title)||E.type,kind:"ide",providerType:E.type,subtitle:E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:E.lastMessageAt||0}}),...I.map(E=>{var Z;return{id:`cli:${E.type}:${E.workspace||""}`,label:((Z=E.activeChat)==null?void 0:Z.title)||E.cliName,kind:"cli",providerType:E.type,providerSessionId:E.providerSessionId,subtitle:E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:E.lastMessageAt||0}}),...W.map(E=>{var Z;return{id:`acp:${E.type}:${E.workspace||""}`,label:((Z=E.activeChat)==null?void 0:Z.title)||E.acpName,kind:"acp",providerType:E.type,providerSessionId:E.providerSessionId,subtitle:Tn(E.summaryMetadata)||E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:E.lastMessageAt||0}})].sort((E,Z)=>(Z.lastLaunchedAt||0)-(E.lastLaunchedAt||0)),J=((m==null?void 0:m.recentLaunches)||[]).length>0?((m==null?void 0:m.recentLaunches)||[]).map(E=>({id:E.id,label:E.title||E.providerName||E.providerType,kind:E.kind,providerType:E.providerType,providerSessionId:E.providerSessionId,subtitle:Tn(E.summaryMetadata)||E.workspace||void 0,workspace:E.workspace,summaryMetadata:E.summaryMetadata,lastLaunchedAt:E.lastLaunchedAt})):U,ee=l.useMemo(()=>{var Z;const E=((Z=d.connectionStates)==null?void 0:Z[n||""])||void 0;return p.filter(we=>we.daemonId===n&&we.type!=="adhdev-daemon").flatMap(we=>nc(we,{connectionStates:n&&E?{[n]:E}:void 0,defaultConnectionState:E})).filter(we=>!(we.transport==="pty"&&we.mode==="terminal")).sort((we,ge)=>ul(ge)-ul(we))},[p,d.connectionStates,n]),Y=l.useCallback(E=>{const Z=Hh(E);Z&&a(Ba(Z))},[a]),ve=l.useCallback(()=>{y.current&&(M(!0),y.current().finally(()=>{y.current=null,M(!1),N(null)}))},[]),pe=l.useCallback(E=>{if(!H)return;const{options:Z,selectedKey:we}=Uh({machine:H,currentWorkspacePath:E.workspace,homeLabel:t("newSession.homeDirectory"),homeDescription:t("newSession.launchWithoutWorkspace")}),ge=async()=>{v(E.kind),x("workspace")};y.current=async()=>{const be=Z.find(We=>We.key===A.current),De=(be==null?void 0:be.workspacePath)??null,Me=(be==null?void 0:be.workspaceId)??null;if(E.kind==="ide"&&E.providerType){await B.handleLaunchIde(E.providerType,De?{workspace:De}:void 0);return}if((E.kind==="cli"||E.kind==="acp")&&E.providerType){await B.runLaunchCliCore({cliType:E.providerType,dir:Me?void 0:De||"",workspaceId:Me||void 0,model:E.kind==="acp"&&cm(E.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:E.providerSessionId});return}await ge()},A.current=we,L(we),N({title:E.kind==="ide"?qr(t,"restart-ide",E.label):E.providerSessionId?ah(t,E.label):qr(t,"start-fresh",E.label),description:E.kind==="ide"?zr(t,"restart-ide"):E.providerSessionId?rh(t):zr(t,"start-fresh"),confirmLabel:E.kind==="ide"?Kr(t,"restart-ide"):E.providerSessionId?rl(t,!0):Kr(t,"start-fresh"),busyLabel:E.kind==="ide"?Vr(t,"restart-ide"):E.providerSessionId?nh(t,!0):Vr(t,"start-fresh"),workspaceOptions:Z,details:[{label:"Mode",value:E.kind.toUpperCase()},...E.providerType?[{label:"Provider",value:E.providerType}]:[]]})},[B,H]);if(l.useEffect(()=>{x(Ce)},[z,Ce,n]),l.useEffect(()=>{le&&v(le)},[le,n]),!H)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:D,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 te=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(us,{size:14})," ",t("machine.detail.tabWorkspace")]}),count:$.length+I.length+W.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(pb,{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:D,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:[B.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:B.nicknameInput,onChange:E=>B.setNicknameInput(E.target.value),onKeyDown:E=>{E.key==="Enter"&&B.handleSaveNickname(),E.key==="Escape"&&B.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:B.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:()=>B.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:()=>{B.setEditingNickname(!0),B.setNicknameInput(H.machineNickname||"")},title:t("machine.detail.clickToSetNickname"),children:F}),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:[H.platform," · ",H.arch]}),s.jsx("span",{children:t("machine.detail.coresCount",{count:H.cpus})}),(m==null?void 0:m.version)&&s.jsxs("span",{children:["v",m.version]}),H.p2p.available&&s.jsx("span",{children:t("machine.detail.p2pState",{state:H.p2p.state==="connected"?t("machine.detail.p2pConnected"):H.p2p.state})}),H.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:H.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-border-subtle",children:te.map(E=>s.jsxs("button",{onClick:()=>x(E.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${h===E.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[E.label,E.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${h===E.id?"bg-accent-primary/20 text-accent-primary":"bg-bg-glass-hover text-text-muted"}`,children:E.count})]},E.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(NL,{machineEntry:m,providers:R,recentLaunches:J,currentConversations:ee,onUpgradeDaemon:async()=>{const E=Co(m);if(E)try{await o(n,"daemon_upgrade",E)}catch{}},onOpenRecent:pe,onOpenConversation:Y}),s.jsx(TL,{machine:H,machineId:n,ideSessions:$,cliSessions:I,acpSessions:W,actions:B,sendDaemonCommand:o})]}),h==="providers"&&s.jsx(EI,{machineId:n,providers:R,sendDaemonCommand:o,quota:H.quota}),h==="overview"&&s.jsx(kI,{machine:H,ideSessions:$,cliSessions:I,acpSessions:W}),h==="session-host"&&s.jsx(SL,{machineId:n,cliSessions:I,sendDaemonCommand:o}),h==="logs"&&s.jsx(gL,{machineId:n,sendDaemonCommand:o})]})})}),B.launchPick&&H&&s.jsx(CL,{machine:H,launchPick:B.launchPick,actions:B}),j&&s.jsx(jo,{title:j.title,description:j.description,details:j.details,workspaceOptions:j.workspaceOptions,selectedWorkspaceKey:T,onWorkspaceChange:E=>{A.current=E,L(E)},confirmLabel:j.confirmLabel,busyLabel:j.busyLabel,busy:P,onConfirm:ve,onCancel:()=>{y.current=null,N(null)}}),w&&s.jsx(Qf,{daemonId:w.daemonId,workspace:w.workspace,onClose:()=>C(null)}),s.jsx(ih,{toasts:d.toasts||[],onDismiss:E=>d.setToasts(Z=>Z.filter(we=>we.id!==E)),onClickToast:E=>{E.targetKey&&a(Ba(E.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 P=await n(e,"session_host_prune_duplicate_sessions",{}),M=Di(P);if(!(M!=null&&M.success))throw new Error((M==null?void 0:M.error)||"Duplicate prune failed");const _=M.result||{},D=Array.isArray(_.prunedSessionIds)?_.prunedSessionIds.length:0,B=typeof _.duplicateGroupCount=="number"?_.duplicateGroupCount:0;xt.showToast(`Pruned ${D} duplicate runtime(s) across ${B} group(s)`,"success"),await h()}catch(P){const M=P instanceof Error?P.message:"Duplicate prune failed";xt.showToast(M,"warning"),r(M)}finally{i(P=>P==="session_host_prune_duplicate_sessions"?null:P)}}},[e,h,n]),b=l.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((L,P)=>(P.lastActivityAt||0)-(L.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)||[]}:xL(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(()=>kL(C),[C]),N=l.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),A=l.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(L=>L.level==="warn"||L.level==="error")||null,[u==null?void 0:u.recentLogs]),T=(L,P)=>{var I;const M=o===`session_host_resume_session:${L.sessionId}`,_=o===`session_host_restart_session:${L.sessionId}`,D=o===`session_host_stop_session:${L.sessionId}`,B=Xf(L.meta),R=k.get(L.sessionId),O=L.attachedClients.length===1?"1 client":`${L.attachedClients.length} clients`,H=P==="recovery"?"Recover":"Resume",$=vL(P);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:L.displayName||(R==null?void 0:R.cliName)||L.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${wL(L.lifecycle)}`,children:L.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:L.workspaceLabel||(R==null?void 0:R.runtimeWorkspaceLabel)||L.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:L.runtimeKey}),L.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",L.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((I=L.writeOwner)==null?void 0:I.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:yL(L.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(Sp,{size:11})," ",O]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",zu(L.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",$]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[P==="recovery"&&(L.lifecycle==="interrupted"||L.lifecycle==="failed"||L.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{x("session_host_resume_session",L)},children:M?`${H}ing…`:H}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{x("session_host_restart_session",L)},children:_?"Restarting…":"Restart"}),P==="live"&&(L.lifecycle==="running"||L.lifecycle==="starting"||L.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",L)},children:D?"Stopping…":"Stop"})]})]})},L.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:Sj()})]}),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:Pi(u.hostStartedAt)})]})]}),A&&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:A.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Pi(A.timestamp),A.sessionId?` · ${A.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(L=>T(L,"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(L=>T(L,"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(L=>T(L,"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(L=>{var M;const P=b.find(_=>_.sessionId===L.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:(P==null?void 0:P.displayName)||((M=k.get(L.sessionId))==null?void 0:M.cliName)||L.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[L.action,L.lifecycle?` · ${L.lifecycle}`:"",L.detail?` · ${L.detail}`:"",L.error?` · ${L.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${L.success===!1?"text-red-300":"text-text-secondary"}`,children:Pi(L.timestamp)})]},`${L.sessionId}:${L.timestamp}:${L.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 CL({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 jL(e,t){const n=x1(e),a=Qs(e,t),r=So(e,a),o=Da(e,a),i=vh(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 NL({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=jL(e,"1.0.52");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(Ps,{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(jp,{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}=Gh(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 AL({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 A=await uc(i,e,N);h(A.path),S(A.directories)}catch(A){v(A instanceof Error?A.message:"Could not load folder")}finally{w(!1)}},[e,i]),j=l.useCallback(()=>{g(!0);const N=[...n.map(T=>T.workspace),...a.map(T=>T.workspace),...r.map(T=>T.workspace)],A=dc(t.platform,cc(N,t.defaultWorkspacePath,(t.workspaces||[]).map(T=>T.path)));y(A)},[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 A=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 ${A?"border-yellow-500/30 bg-yellow-500/[0.05]":"border-border-subtle bg-bg-primary"}`,children:[s.jsx("button",{type:"button",title:A?"Default workspace — click to unset":"Set as default workspace",disabled:c,onClick:()=>void u(A?null:N.id),className:`text-base leading-none shrink-0 transition-colors ${A?"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:om(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 TL({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(AL,{machineId:t,machine:e,ideSessions:n,cliSessions:a,acpSessions:r,actions:o,sendDaemonCommand:i})]})}function ML({onNicknameSynced:e}={}){var me,V,q,se,de,K,fe,ie,ue,ye,Ie;const{t}=ke("common"),{id:n}=Eg(),a=oa(),r=Dl(),{sendCommand:o}=St(),i=ca(),c=Ch(),d=Km(),p=d.ides||[],u=d.initialLoaded??!0,m=p.find(E=>E.id===n&&E.type==="adhdev-daemon"),f=p.some(E=>E.type==="adhdev-daemon"),g=n?(me=d.connectionRetryStatuses)==null?void 0:me[n]:void 0,k=!!(g!=null&&g.blocked),[h,x]=l.useState("workspace"),[S,b]=l.useState(null),[w,C]=l.useState(null);l.useCallback((E,Z)=>{C({daemonId:E,workspace:Z})},[]);const[,v]=l.useState("ide"),y=l.useRef(null),[j,N]=l.useState(null),A=l.useRef("__home__"),[T,L]=l.useState("__home__"),[P,M]=l.useState(!1),_=l.useRef(null);l.useEffect(()=>{!n||!m||!(!m.workspaces||!m.availableProviders||!m.detectedIdes||!m.recentLaunches)||i(n,{minFreshMs:3e4}).catch(()=>{})},[i,m,n]),l.useEffect(()=>{if(!n||!m)return;let E=!1;return(async()=>{try{const Z=await o(n,"get_status_metadata"),we=Z&&typeof Z=="object"&&"result"in Z?Z.result:Z,ge=we==null?void 0:we.providerChannelStaleness;!E&&ge&&!ge.error&&b({staleTypes:Array.isArray(ge.staleTypes)?ge.staleTypes:[],newTypes:Array.isArray(ge.newTypes)?ge.newTypes:[]})}catch{}})(),()=>{E=!0}},[n,m==null?void 0:m.id,o]),l.useEffect(()=>{if(!n||!m||h!=="overview"&&h!=="providers")return;const E=m.machine;(typeof(E==null?void 0:E.cpus)!="number"||typeof(E==null?void 0:E.totalMem)!="number"||typeof(E==null?void 0:E.arch)!="string"||typeof(E==null?void 0:E.release)!="string"||h==="providers"&&!(E!=null&&E.quota))&&c(n,{minFreshMs:3e4}).catch(()=>{})},[h,c,m,n]),U1(n&&h==="overview"?[n]:[],{enabled:h==="overview",intervalMs:US});const D=()=>{if(f){a("/dashboard",{state:{mobileSection:"machines"}});return}a("/machines")},B=yI({machineId:n,registeredMachineId:(m==null?void 0:m.machineId)||null,sendDaemonCommand:o,onNicknameSynced:e,logsEndRef:_});l.useEffect(()=>xt.onToast(Z=>{d.setToasts(ge=>{if(ge.some(Me=>Me.message===Z.message&&Z.timestamp-Me.timestamp<3e3))return ge;const De={id:Z.id,message:Z.message,type:Z.type,timestamp:Z.timestamp,targetKey:Z.targetKey,actions:Z.actions};return[...ge.slice(-4),De]});const we=Z.duration||5e3;setTimeout(()=>d.setToasts(ge=>ge.filter(be=>be.id!==Z.id)),we)}),[d]);const R=(m==null?void 0:m.availableProviders)||[],O={};for(const E of R)O[E.type]=E.icon;const H=m?{id:m.id,hostname:im(m,{fallbackId:m.id}),platform:((V=m.machine)==null?void 0:V.platform)||"unknown",arch:((q=m.machine)==null?void 0:q.arch)||"",cpus:((se=m.machine)==null?void 0:se.cpus)||0,totalMem:((de=m.machine)==null?void 0:de.totalMem)||0,freeMem:(K=m.machine)==null?void 0:K.freeMem,availableMem:(fe=m.machine)==null?void 0:fe.availableMem,loadavg:(ie=m.machine)==null?void 0:ie.loadavg,uptime:(ue=m.machine)==null?void 0:ue.uptime,release:((ye=m.machine)==null?void 0:ye.release)||"",cdpConnected:!!m.cdpConnected,machineNickname:m.machineNickname||null,...(Ie=m.machine)!=null&&Ie.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,$=p.filter(E=>E.daemonId===n&&E.type!=="adhdev-daemon").filter(E=>!$a(E)&&!Jn(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,version:E.version||"",instanceId:E.instanceId||"",status:E.status,workspace:E.workspace||null,terminals:E.terminals||0,aiAgents:J0(E.aiAgents||(E.agents||[]).map(Z=>({id:Z.name,name:Z.name,status:Z.status,version:Z.version}))),activeChat:E.activeChat||null,chats:E.chats||[],childSessions:E.childSessions||[],cdpConnected:E.cdpConnected||!1,daemonId:n,lastMessageAt:E.lastMessageAt})),I=p.filter(E=>E.daemonId===n&&$a(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,cliName:E.cliName||E.type,status:E.status,workspace:E.workspace||"",activeChat:E.activeChat||null,providerSessionId:E.providerSessionId,mode:E.mode,runtimeKey:E.runtimeKey,runtimeDisplayName:E.runtimeDisplayName,runtimeWorkspaceLabel:E.runtimeWorkspaceLabel,runtimeWriteOwner:E.runtimeWriteOwner||null,runtimeAttachedClients:E.runtimeAttachedClients||[],daemonId:n,lastMessageAt:E.lastMessageAt})),W=p.filter(E=>E.daemonId===n&&Jn(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,acpName:E.cliName||E.type,status:E.status,workspace:E.workspace||"",activeChat:E.activeChat||null,providerSessionId:E.providerSessionId,daemonId:n,lastMessageAt:E.lastMessageAt})),F=m?ds(m,{fallbackId:n}):"",z="workspace",Q=r.state,ne=Q==null?void 0:Q.initialMachineTab,oe=Q==null?void 0:Q.initialWorkspaceCategory;Q==null||Q.initialWorkspaceId,Q==null||Q.initialWorkspacePath;const Ce=ne==="ides"||ne==="clis"||ne==="acps"?"workspace":ne||z,le=ne==="ides"?"ide":ne==="clis"?"cli":ne==="acps"?"acp":oe,U=[...$.map(E=>{var Z;return{id:`ide:${E.type}:${E.workspace||""}`,label:((Z=E.activeChat)==null?void 0:Z.title)||E.type,kind:"ide",providerType:E.type,subtitle:E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:E.lastMessageAt||0}}),...I.map(E=>{var Z;return{id:`cli:${E.type}:${E.workspace||""}`,label:((Z=E.activeChat)==null?void 0:Z.title)||E.cliName,kind:"cli",providerType:E.type,providerSessionId:E.providerSessionId,subtitle:E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:E.lastMessageAt||0}}),...W.map(E=>{var Z;return{id:`acp:${E.type}:${E.workspace||""}`,label:((Z=E.activeChat)==null?void 0:Z.title)||E.acpName,kind:"acp",providerType:E.type,providerSessionId:E.providerSessionId,subtitle:Tn(E.summaryMetadata)||E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:E.lastMessageAt||0}})].sort((E,Z)=>(Z.lastLaunchedAt||0)-(E.lastLaunchedAt||0)),J=((m==null?void 0:m.recentLaunches)||[]).length>0?((m==null?void 0:m.recentLaunches)||[]).map(E=>({id:E.id,label:E.title||E.providerName||E.providerType,kind:E.kind,providerType:E.providerType,providerSessionId:E.providerSessionId,subtitle:Tn(E.summaryMetadata)||E.workspace||void 0,workspace:E.workspace,summaryMetadata:E.summaryMetadata,lastLaunchedAt:E.lastLaunchedAt})):U,ee=l.useMemo(()=>{var Z;const E=((Z=d.connectionStates)==null?void 0:Z[n||""])||void 0;return p.filter(we=>we.daemonId===n&&we.type!=="adhdev-daemon").flatMap(we=>nc(we,{connectionStates:n&&E?{[n]:E}:void 0,defaultConnectionState:E})).filter(we=>!(we.transport==="pty"&&we.mode==="terminal")).sort((we,ge)=>ul(ge)-ul(we))},[p,d.connectionStates,n]),Y=l.useCallback(E=>{const Z=Hh(E);Z&&a(Ba(Z))},[a]),ve=l.useCallback(()=>{y.current&&(M(!0),y.current().finally(()=>{y.current=null,M(!1),N(null)}))},[]),pe=l.useCallback(E=>{if(!H)return;const{options:Z,selectedKey:we}=Uh({machine:H,currentWorkspacePath:E.workspace,homeLabel:t("newSession.homeDirectory"),homeDescription:t("newSession.launchWithoutWorkspace")}),ge=async()=>{v(E.kind),x("workspace")};y.current=async()=>{const be=Z.find(We=>We.key===A.current),De=(be==null?void 0:be.workspacePath)??null,Me=(be==null?void 0:be.workspaceId)??null;if(E.kind==="ide"&&E.providerType){await B.handleLaunchIde(E.providerType,De?{workspace:De}:void 0);return}if((E.kind==="cli"||E.kind==="acp")&&E.providerType){await B.runLaunchCliCore({cliType:E.providerType,dir:Me?void 0:De||"",workspaceId:Me||void 0,model:E.kind==="acp"&&cm(E.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:E.providerSessionId});return}await ge()},A.current=we,L(we),N({title:E.kind==="ide"?qr(t,"restart-ide",E.label):E.providerSessionId?ah(t,E.label):qr(t,"start-fresh",E.label),description:E.kind==="ide"?zr(t,"restart-ide"):E.providerSessionId?rh(t):zr(t,"start-fresh"),confirmLabel:E.kind==="ide"?Kr(t,"restart-ide"):E.providerSessionId?rl(t,!0):Kr(t,"start-fresh"),busyLabel:E.kind==="ide"?Vr(t,"restart-ide"):E.providerSessionId?nh(t,!0):Vr(t,"start-fresh"),workspaceOptions:Z,details:[{label:"Mode",value:E.kind.toUpperCase()},...E.providerType?[{label:"Provider",value:E.providerType}]:[]]})},[B,H]);if(l.useEffect(()=>{x(Ce)},[z,Ce,n]),l.useEffect(()=>{le&&v(le)},[le,n]),!H)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:D,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 te=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(us,{size:14})," ",t("machine.detail.tabWorkspace")]}),count:$.length+I.length+W.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(pb,{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:D,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:[B.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:B.nicknameInput,onChange:E=>B.setNicknameInput(E.target.value),onKeyDown:E=>{E.key==="Enter"&&B.handleSaveNickname(),E.key==="Escape"&&B.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:B.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:()=>B.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:()=>{B.setEditingNickname(!0),B.setNicknameInput(H.machineNickname||"")},title:t("machine.detail.clickToSetNickname"),children:F}),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:[H.platform," · ",H.arch]}),s.jsx("span",{children:t("machine.detail.coresCount",{count:H.cpus})}),(m==null?void 0:m.version)&&s.jsxs("span",{children:["v",m.version]}),H.p2p.available&&s.jsx("span",{children:t("machine.detail.p2pState",{state:H.p2p.state==="connected"?t("machine.detail.p2pConnected"):H.p2p.state})}),H.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:H.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-border-subtle",children:te.map(E=>s.jsxs("button",{onClick:()=>x(E.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${h===E.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[E.label,E.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${h===E.id?"bg-accent-primary/20 text-accent-primary":"bg-bg-glass-hover text-text-muted"}`,children:E.count})]},E.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(NL,{machineEntry:m,providers:R,recentLaunches:J,currentConversations:ee,onUpgradeDaemon:async()=>{const E=Co(m);if(E)try{await o(n,"daemon_upgrade",E)}catch{}},onOpenRecent:pe,onOpenConversation:Y}),s.jsx(TL,{machine:H,machineId:n,ideSessions:$,cliSessions:I,acpSessions:W,actions:B,sendDaemonCommand:o})]}),h==="providers"&&s.jsx(EI,{machineId:n,providers:R,sendDaemonCommand:o,quota:H.quota}),h==="overview"&&s.jsx(kI,{machine:H,ideSessions:$,cliSessions:I,acpSessions:W}),h==="session-host"&&s.jsx(SL,{machineId:n,cliSessions:I,sendDaemonCommand:o}),h==="logs"&&s.jsx(gL,{machineId:n,sendDaemonCommand:o})]})})}),B.launchPick&&H&&s.jsx(CL,{machine:H,launchPick:B.launchPick,actions:B}),j&&s.jsx(jo,{title:j.title,description:j.description,details:j.details,workspaceOptions:j.workspaceOptions,selectedWorkspaceKey:T,onWorkspaceChange:E=>{A.current=E,L(E)},confirmLabel:j.confirmLabel,busyLabel:j.busyLabel,busy:P,onConfirm:ve,onCancel:()=>{y.current=null,N(null)}}),w&&s.jsx(Qf,{daemonId:w.daemonId,workspace:w.workspace,onClose:()=>C(null)}),s.jsx(ih,{toasts:d.toasts||[],onDismiss:E=>d.setToasts(Z=>Z.filter(we=>we.id!==E)),onClickToast:E=>{E.targetKey&&a(Ba(E.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 DL({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 PL(){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 IL(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 _,D;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"),A=IL({creating:C,planLoading:g,plan:f,name:o,workspace:p,showDaemonPicker:n,daemonId:c,repoRemoteUrl:k,repoIdentity:x}),T=tg(g,250),L=b||!!k.trim()||!!x.trim(),P=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=L?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")}),P]}),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:A,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")})}):P}),s.jsx(Tt,{label:N("repoMesh.list.workspace"),hint:N("repoMesh.list.workspaceHint"),children:s.jsx(yl,{workspaces:m,value:p,onChange:u})}),(T||f)&&s.jsx(Mt,{variant:(f==null?void 0:f.success)===!1?"error":ro(f)?"warning":"info",className:"mb-4",children:T?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)?((_=f.plan)==null?void 0:_.summary)||N("setupWizard.machines.planExists"):`${((D=f.plan)==null?void 0:D.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:A,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 LL({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 RL({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 EL({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 _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:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function HL({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 $L(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function FL({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:A,onCancelCreate:T}){const{t:L}=ke("common"),P=o.maxMeshes!=null&&e.length>=o.maxMeshes,[M,_]=l.useState(!1);return s.jsxs(Qa,{icon:s.jsx(cs,{}),title:L("repoMesh.list.title"),subtitle:L("repoMesh.list.count",{count:e.length}),widthClassName:"max-w-5xl",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:c,disabled:P,title:P?L("repoMesh.list.meshLimitReached",{max:o.maxMeshes}):void 0,children:L("repoMesh.list.createMesh")}),children:[P&&s.jsx(Mt,{variant:"info",className:"mb-4",children:L("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(bt,{className:"mb-5 border-accent/40 animate-[fadeIn_0.3s_ease-out]",children:s.jsx(ng,{variant:"page",showDaemonPicker:o.createDaemonPicker,daemons:r,daemonLabel:$L,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:_,creating:v,onCreate:A,onCancel:T})}),t?s.jsx("div",{className:"text-sm text-text-muted p-4",children:L("repoMesh.list.loading")}):e.length===0?s.jsx(Ja,{icon:s.jsx(cs,{}),title:L("repoMesh.list.emptyTitle"),description:r.length>0?L("repoMesh.list.emptyWithDaemons"):L("repoMesh.list.emptyNoDaemons"),action:s.jsx("button",{className:"btn btn-primary btn-sm",disabled:!r.length,onClick:c,children:L("repoMesh.list.createFirst")})}):s.jsx("div",{className:"flex flex-col gap-2.5",children:e.map(D=>{var B;return s.jsx("button",{type:"button",onClick:()=>N(D.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:D.name})]}),s.jsxs("div",{className:"text-[12px] text-text-muted flex items-center gap-2",children:[s.jsx("span",{className:"font-mono",children:D.repoIdentity||D.repo_identity||L("repoMesh.list.noRepoIdentity")}),(D.defaultBranch||D.default_branch)&&s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(RL,{size:11}),D.defaultBranch||D.default_branch]})]})]}),s.jsxs("div",{className:"text-right text-[11px] text-text-muted shrink-0 ml-4",children:[s.jsx("div",{children:new Date(D.createdAt||D.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})}),s.jsxs("div",{className:"text-text-muted/60",children:[((B=D.nodes)==null?void 0:B.length)??D.nodeCount??0," ",L("repoMesh.list.nodesSuffix")]})]})]})},D.id)})})]})}function BL(e){const t=new Map;for(const n of e)n!=null&&n.id&&t.set(n.id,ln(n.availableProviders||[]));return t}function WL(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 OL(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 UL(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 sm(t.slots))r(o.provider);if(Array.isArray(t.providerPriority))for(const o of t.providerPriority)r(o);return a}function GL(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 UL(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 qL=["","low","medium","high"],zL={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 KL(){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 VL({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(()=>ph(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 A;if(y!==b)return v;const j=((A=p.get(w))==null?void 0:A.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,KL()]),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(Pt,{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]:qL,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:A=>m(w,{model:A.target.value==="__custom__"?" ":A.target.value}),children:[s.jsx("option",{value:"",children:r("repoMesh.slotEditor.providerDefault")}),v.map(A=>s.jsx("option",{value:A,children:A},A)),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:A=>m(w,{model:A.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:A=>m(w,{thinkingLevel:A.target.value}),children:y.map(A=>s.jsx("option",{value:A,children:A||r("repoMesh.slotEditor.thinkingDefault")},A||"_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:tm.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:zL[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 YL(e){const t=e.capabilities;return Array.isArray(t)?t.map(n=>typeof n=="string"?n.trim():"").filter(Boolean):[]}const QL=["os=","arch=","provider=","worktree=","converge="];function JL({node:e,saving:t,onSave:n}){const{t:a}=ke("common"),r=l.useMemo(()=>GL(e).filter(h=>!h.custom),[e]),o=l.useMemo(()=>YL(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"):QL.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 XL(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 ZL(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 A;const C=n2(w),v=e2(w,t),y=XL(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:T=>{(T.key==="Enter"||T.key===" ")&&(T.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(HL,{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:ZL(a.find(T=>T.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(JL,{node:w,saving:p===w.id,onSave:T=>u(w,T)}),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:T=>T.stopPropagation(),children:[s.jsx(Tt,{label:b("repoMesh.nodeList.slotsLabel"),hint:b("repoMesh.nodeList.slotsHint"),children:s.jsx(VL,{slots:Array.isArray((A=w.policy)==null?void 0:A.slots)?w.policy.slots:[],availableProviders:WL(w,i),saving:c===w.id,onSave:T=>d(w,T)})}),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:T=>{const L=T.target.value;f(w.id,L)},onClick:T=>T.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:T=>{T.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:T=>{T.stopPropagation(),S(w.id)},title:b("repoMesh.nodeList.removeNode"),children:s.jsx(EL,{size:14})})]}),s.jsxs("details",{className:"mt-3 group",onClick:T=>T.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(T=>s.jsx("li",{className:"font-mono",children:t2(T)},T.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(T=>s.jsxs("li",{className:"font-mono",children:[T.provider," / ",T.status," / ",T.id]},T.id))})]})]})]})]},w.id)})})}function e2(e,t){return t.filter(n=>n.status!=="assigned"?!1:(n.assignedNodeId||n.nodeId)===e.id)}function t2(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 s2(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:$0((o=e.policy)==null?void 0:o.slots)}function n2(e){const t=s2(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?Mf(e.id):void 0))||"Unknown"}function a2(e){return String(e.daemon_id||e.daemonId||"")}function r2(e,t){const n=new Map(t.map(o=>[o.id,o])),a=[],r=new Map;for(const o of e){const i=a2(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 o2({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 i2({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:A,nodeDaemonId:T,onNodeDaemonIdChange:L,nodeCustomPath:P,onNodeCustomPathChange:M,nodePickerWorkspaces:_,nodePickerProviders:D,nodeOnboardingPlan:B,nodePlanLoading:R,attachableDaemons:O,onAddNode:H,onRemoveNode:$}){var Ce,le,U;const{t:I}=ke("common"),W=l.useMemo(()=>BL(a),[a]),F=l.useMemo(()=>e.filter(J=>!wl(J)),[e]),z=l.useMemo(()=>i.addNodeDaemonPicker?r2(F,a):[],[i.addNodeDaemonPicker,F,a]),[Q,ne]=l.useState(null),oe=z.some(J=>J.key===Q)?Q:((Ce=z[0])==null?void 0:Ce.key)??"";return s.jsxs(bt,{title:i.addNodeDaemonPicker?I("repoMesh.nodeList.title",{count:F.length}):I("repoMesh.nodeList.titleNoCount"),description:i.addNodeDaemonPicker?I("repoMesh.nodeList.descriptionCloud"):I("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:I("repoMesh.nodeList.daemonCandidates")}),s.jsx("div",{className:"text-[12px] text-text-muted",children:I("repoMesh.nodeList.daemonCandidatesHint")})]}),s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:I("repoMesh.nodeList.available",{count:O.length})})]}),a.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:I("repoMesh.nodeList.noDaemonsAvailable")}):O.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:I("repoMesh.nodeList.allDaemonsAttached")}):s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:O.map(J=>s.jsxs("button",{type:"button",className:`text-left rounded-lg border px-3 py-2 transition-colors min-w-0 ${J.id===c?"border-accent-primary/50 bg-accent-primary/10":"border-border-subtle bg-bg-primary hover:border-border-default"}`,onClick:()=>{L(J.id),j(""),M(!1),A(Dn(ln(J.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(J)}),J.id===c&&s.jsx("span",{className:"text-[10px] text-accent-primary shrink-0",children:I("repoMesh.nodeList.selectedHost")})]}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted font-mono truncate",children:J.id}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:I("repoMesh.nodeList.workspacesDetected",{count:(J.workspaces||[]).length})})]},J.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(_L,{size:13})," ",i.addNodeDaemonPicker?I("repoMesh.nodeList.attachMachine"):I("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?I("repoMesh.nodeList.attachMachineTitle"):I("repoMesh.nodeList.addNodeTitle")}),s.jsx("button",{onClick:()=>{v(),L(""),M(!1)},className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(Pt,{size:16})})]}),i.addNodeDaemonPicker&&s.jsx(Tt,{label:I("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:T,onChange:J=>{var ee;L(J.target.value),j(""),M(!1),A(Dn(ln(((ee=a.find(Y=>Y.id===J.target.value))==null?void 0:ee.availableProviders)||[])))},children:[s.jsx("option",{value:"",children:I("repoMesh.nodeList.selectMachine")}),a.map(J=>s.jsx("option",{value:J.id,children:oo(J)},J.id))]})}),(i.addNodeDaemonPicker?T:!0)&&s.jsx(Tt,{label:I("repoMesh.nodeList.workspacePath"),children:i.addNodeDaemonPicker&&!P&&_.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex flex-col gap-1.5 mb-2",children:_.map(J=>s.jsxs("button",{type:"button",className:`text-left text-xs px-3 py-2 rounded-lg border transition-colors ${y===J.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(J.path),children:[s.jsx("span",{className:"font-medium block truncate",children:J.label||J.path.split("/").pop()}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:J.path})]},J.id||J.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:I("repoMesh.nodeList.enterCustomPath")})]}):s.jsx(s.Fragment,{children:i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[s.jsx(xs,{value:y,onChange:J=>j(J.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:J=>{J.key==="Enter"&&H()}}),_.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:I("repoMesh.nodeList.pickFromSaved")})]}):(()=>{var Y;const J=Array.isArray(n==null?void 0:n.workspaces)?n.workspaces:[],ee=`mesh-add-node-workspaces-${r||"new"}`;return s.jsxs(s.Fragment,{children:[s.jsx(xs,{value:y,onChange:ve=>j(ve.target.value),placeholder:((Y=J[0])==null?void 0:Y.path)||"/Users/dev/projects/myapp",list:J.length>0?ee:void 0,autoFocus:!0}),J.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("datalist",{id:ee,children:J.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:J.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?`${((le=B.plan)==null?void 0:le.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:I("repoMesh.nodeList.preferredTools"),hint:I("repoMesh.nodeList.preferredToolsHint"),children:s.jsx(Uj,{value:N,availableProviders:i.addNodeDaemonPicker?D:d,onChange:A})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:H,disabled:R||(B==null?void 0:B.success)===!1||!y.trim()||i.addNodeDaemonPicker&&!T,className:"btn btn-primary btn-sm",children:I("repoMesh.nodeList.add")}),s.jsx("button",{onClick:()=>{v(),L(""),M(!1)},className:"btn btn-secondary btn-sm",children:I("repoMesh.nodeList.cancel")})]})]}),F.length===0?s.jsx(Ja,{icon:s.jsx(An,{}),title:I("repoMesh.nodeList.emptyTitle"),description:I("repoMesh.nodeList.emptyDescription")}):i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[z.length>1&&s.jsx(o2,{groups:z,activeKey:oe,onChange:ne}),s.jsx(Yu,{nodes:((U=z.find(J=>J.key===oe))==null?void 0:U.nodes)||F,meshQueue:t,activeDaemon:n,daemons:a,userName:o,features:i,providersByDaemonId:W,savingNodeSlotsId:p,onUpdateNodeSlots:u,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:f,nodeSystemPromptDrafts:g,onNodeSystemPromptDraftChange:k,savingNodeSystemPromptId:h,onSaveNodeSystemPrompt:x,selectedNodeId:S,onSelectNode:b,onRemoveNode:$})]}):s.jsx(Yu,{nodes:F,meshQueue:t,activeDaemon:n,daemons:a,userName:o,features:i,providersByDaemonId:W,savingNodeSlotsId:p,onUpdateNodeSlots:u,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:f,nodeSystemPromptDrafts:g,onNodeSystemPromptDraftChange:k,savingNodeSystemPromptId:h,onSaveNodeSystemPrompt:x,selectedNodeId:S,onSelectNode:b,onRemoveNode:$})]})}const l2=["claude-cli","codex-cli","gemini-cli","hermes-cli","antigravity-cli"],c2=[{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 d2(){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 u2(e){return{nodeId:e.nodeId??"",provider:e.provider??"",model:e.model??"",n:e.n!=null?String(e.n):""}}function p2(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 m2({status:e,daemonId:t,sendDaemonCommand:n,availableProviders:a}){const{t:r}=ke(),{theme:o}=Ls(),i=l.useMemo(()=>Rs(o),[o]),c=l.useMemo(()=>ph(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(F=>({nodeId:F.nodeId,machineLabel:F.machineLabel,providers:F.providers,providerPriority:F.providerPriority,isLocalWorktree:F.isLocalWorktree,worktreeBranch:F.worktreeBranch})),[e==null?void 0:e.nodes]),w=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(F=>F.nodeId),[e==null?void 0:e.nodes]),C=l.useMemo(()=>new Set(b.filter(wl).map(F=>F.nodeId)),[b]),v=l.useMemo(()=>Object.fromEntries(b.filter(wl).map(F=>[F.nodeId,F.worktreeBranch])),[b]),y=l.useMemo(()=>Object.fromEntries(((e==null?void 0:e.nodes)??[]).map(F=>[F.nodeId,F.machineLabel||F.nodeId])),[e==null?void 0:e.nodes]),j=l.useMemo(()=>{const F={};for(const z of b)F[z.nodeId]=Qu(z);return F},[b]),N=l.useMemo(()=>{const F=[...new Set(b.flatMap(Qu).filter(Boolean))];return[...new Set([...F,...l2])].sort()},[b]),A=!!t&&!!n,T=F=>F&&typeof F=="object"&&"result"in F?F.result:F,L=e==null?void 0:e.meshId,P=l.useCallback(async()=>{if(!(!t||!n)){m(!0),g(null);try{const F=await n(t,"magi_kind_panel_list",{...L?{meshId:L}:{}}),z=T(F);if((z==null?void 0:z.success)===!1)throw new Error(z.error||r("meshGraph.magiKind.errorLoad"));p(z!=null&&z.kindPanels&&typeof z.kindPanels=="object"?z.kindPanels:{}),h({})}catch(F){g((F==null?void 0:F.message)||r("meshGraph.magiKind.errorLoad"))}finally{m(!1)}}},[t,n,L,r]);l.useEffect(()=>{P()},[P]);const M=l.useCallback(F=>{if(k[F])return k[F];const z=d[F];return z?z.map(u2):[]},[k,d]),_=(F,z)=>{h(Q=>({...Q,[F]:z}))},D=(F,z,Q)=>{const ne=M(F);_(F,ne.map((oe,Ce)=>Ce===z?{...oe,...Q}:oe))},B=F=>{_(F,[...M(F),d2()])},R=(F,z)=>{_(F,M(F).filter((Q,ne)=>ne!==z))},O=l.useCallback(async F=>{if(!t||!n)return;const z=p2(M(F));if("error"in z){const Q=z.error,ne=Q.code==="provider_required"?r("meshGraph.magiKind.errorSlotProvider",{slot:Q.slot}):Q.code==="replica_min"?r("meshGraph.magiKind.errorSlotReplica",{slot:Q.slot}):r("meshGraph.magiKind.errorNoSlot");g(`${F}: ${ne}`);return}S(F),g(null);try{const Q=await n(t,"magi_kind_panel_set",{kind:F,slots:z.slots,...L?{meshId:L}:{}}),ne=T(Q);if((ne==null?void 0:ne.success)===!1)throw new Error(ne.error||r("meshGraph.magiKind.errorSave"));await P()}catch(Q){g((Q==null?void 0:Q.message)||r("meshGraph.magiKind.errorSave"))}finally{S(null)}},[t,n,M,P,L,r]),H=l.useCallback(async F=>{if(!(!t||!n)&&confirm(r("meshGraph.magiKind.removeConfirm",{kind:F}))){S(F),g(null);try{const z=await n(t,"magi_kind_panel_remove",{kind:F,...L?{meshId:L}:{}}),Q=T(z);if((Q==null?void 0:Q.success)===!1)throw new Error(Q.error||r("meshGraph.magiKind.errorRemove"));await P()}catch(z){g((z==null?void 0:z.message)||r("meshGraph.magiKind.errorRemove"))}finally{S(null)}}},[t,n,P,L,r]),$=`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"}`,I="btn btn-primary btn-sm",W="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:W,onClick:()=>void P(),disabled:u||!A,children:r(u?"meshGraph.magiKind.loading":"meshGraph.magiKind.refresh")})})]}),!A&&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:c2.map(({kind:F,labelKey:z,hint:Q})=>{const ne=M(F),oe=!!d[F],Ce=x===F;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(z)}),s.jsx("span",{className:`font-mono text-[10px] ${i.textMuted}`,children:Q}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${oe?"border-emerald-400/30 bg-emerald-500/10 text-emerald-300":"border-slate-400/20 bg-slate-500/10 text-slate-300"}`,children:oe?r("meshGraph.magiKind.agentCount",{count:d[F].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((le,U)=>{const J=le.nodeId?j[le.nodeId]??[]:[],ee=le.nodeId&&J.length?J: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:$,value:le.nodeId,onChange:Y=>D(F,U,{nodeId:Y.target.value}),title:r("meshGraph.magiKind.machineTitle"),children:[s.jsx("option",{value:"",children:r("meshGraph.magiKind.anyMachine")}),w.map(Y=>{const ve=C.has(Y),pe=ve?r("meshGraph.magiKind.worktreeSuffix",{label:y[Y]??Y,branch:v[Y]||r("meshGraph.magiKind.worktreeUnknownBranch")}):y[Y]??Y;return s.jsx("option",{value:Y,disabled:ve,title:ve?r("meshGraph.magiKind.worktreeDisabledTitle"):void 0,children:pe},Y)}),le.nodeId&&!w.includes(le.nodeId)&&s.jsx("option",{value:le.nodeId,children:r("meshGraph.magiKind.offlineSuffix",{label:y[le.nodeId]??le.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:$,value:le.provider,onChange:Y=>D(F,U,{provider:Y.target.value}),title:r("meshGraph.magiKind.providerTitle"),children:[s.jsx("option",{value:"",children:r("meshGraph.magiKind.selectProvider")}),ee.map(Y=>s.jsx("option",{value:Y,children:Y},Y)),le.provider&&!ee.includes(le.provider)&&s.jsx("option",{value:le.provider,children:le.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 pe;const Y=(le.provider?(pe=c.get(le.provider))==null?void 0:pe.models:void 0)??[],ve=!!le.model&&Y.length>0&&!Y.includes(le.model);return Y.length>0&&!ve?s.jsxs("select",{className:$,value:Y.includes(le.model)?le.model:"",title:r("meshGraph.magiKind.modelTitle"),onChange:te=>D(F,U,{model:te.target.value==="__custom__"?" ":te.target.value}),children:[s.jsx("option",{value:"",children:r("meshGraph.magiKind.modelDefault")}),Y.map(te=>s.jsx("option",{value:te,children:te},te)),s.jsx("option",{value:"__custom__",children:r("meshGraph.magiKind.modelCustom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:$,value:le.model.trim(),placeholder:r("meshGraph.magiKind.modelDefault"),title:r("meshGraph.magiKind.modelTitle"),onChange:te=>D(F,U,{model:te.target.value})}),Y.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:()=>D(F,U,{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:`${$} sm:w-16`,value:le.n,placeholder:"1",inputMode:"numeric",title:r("meshGraph.magiKind.copiesTitle"),onChange:Y=>D(F,U,{n:Y.target.value})})]}),s.jsx("button",{type:"button",className:`${W} sm:mt-[18px] inline-flex h-8 w-8 items-center justify-center p-0`,onClick:()=>R(F,U),"aria-label":r("meshGraph.magiKind.removeAgent"),title:r("meshGraph.magiKind.removeAgent"),children:"✕"})]},U)}),s.jsx("div",{children:s.jsx("button",{type:"button",className:W,onClick:()=>B(F),disabled:!A,children:r("meshGraph.magiKind.addAgent")})})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:I,onClick:()=>void O(F),disabled:Ce||!A,children:r(Ce?"meshGraph.magiKind.saving":"meshGraph.magiKind.save")}),s.jsx("button",{type:"button",className:W,onClick:()=>void H(F),disabled:Ce||!A||!oe,title:r(oe?"meshGraph.magiKind.removeBindingTitle":"meshGraph.magiKind.removeBindingDisabledTitle"),children:r("meshGraph.magiKind.removeBinding")})]})]},F)})})]})}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 h2(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 f2="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs",g2="w-full rounded-lg border border-red-500/60 bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function b2({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=h2(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(x2(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?g2:f2,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 x2(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 v2({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 y2({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 w2=[{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)"}],k2=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function S2(e){const t=k2(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function C2(e){const t=e==null?void 0:e.missions;return Array.isArray(t)?t:[]}function j2(e){return typeof e.goal=="string"&&e.goal?{text:e.goal,truncated:!1}:{text:e.goalPreview??"",truncated:e.goalTruncated===!0}}const N2=["active","paused","completed","abandoned"];function Xu(e){return(e.status||"active").toLowerCase()}const A2=8;function T2({status:e,daemonId:t,meshId:n,sendCommand:a}){const{t:r}=ke("common"),o=l.useMemo(()=>C2(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 A={};for(const T of o){const L=Xu(T);A[L]=(A[L]||0)+1}return A},[o]),w=l.useMemo(()=>k==="all"?o:o.filter(A=>Xu(A)===k),[o,k]),C=x?w:w.slice(0,A2),v=w.length-C.length,y=!!t&&o.length>0,j=l.useCallback(async()=>{if(t){m(!0),g(null);try{const A=await a(t,"mesh_status",{meshId:n,verbose:!0}),T=S2(A),L=Array.isArray(T==null?void 0:T.missions)?T.missions:[],P={};for(const M of L)M.id&&typeof M.goal=="string"&&M.goal&&(P[M.id]=M.goal);c(M=>({...M,...P}))}catch(A){g(A instanceof Error?A.message:r("repoMesh.missions.errorFetch"))}finally{m(!1)}}},[t,n,a,r]),N=l.useCallback(A=>{p(T=>({...T,[A]:!T[A]})),!d[A]&&!i[A]&&j()},[d,i,j]);return o.length===0?null:s.jsxs(bt,{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:[N2.filter(A=>(b[A]||0)>0).map(A=>s.jsxs("button",{type:"button",onClick:()=>{h(A),S(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] capitalize transition-colors ${k===A?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:[A," ",b[A]]},A)),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(A=>{var B;const T=d[A.id]===!0,L=i[A.id],P=j2(A),M=T&&L?L:P.text,_=T&&!L&&P.truncated,D=((B=A.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:A.title,children:A.title||A.id}),A.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:A.status}),D>0&&s.jsx("span",{className:"shrink-0 text-[11px] text-text-muted",children:r("repoMesh.missions.taskCount",{count:D})})]}),M&&s.jsxs("div",{className:`mt-1.5 whitespace-pre-wrap text-[12px] leading-5 text-text-secondary ${T?"max-h-72 overflow-y-auto":"line-clamp-2"}`,children:[M,_&&s.jsx("span",{className:"text-text-muted",children:r("repoMesh.missions.goalUnavailable")})]}),(P.truncated||L)&&y&&s.jsx("button",{type:"button",className:"mt-1.5 text-[12px] text-accent-primary hover:underline disabled:opacity-50",onClick:()=>N(A.id),disabled:u,children:r(T?"repoMesh.missions.showLess":u&&!L?"repoMesh.missions.loading":"repoMesh.missions.showFullGoal")})]},A.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 M2(e){return e.modes.find(t=>t.strategy==="pty-parse-default"&&Gs(t)!=="dangerous")}function D2({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=M2(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 P2(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 I2({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(()=>P2(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,A]=l.useState(null),[T,L]=l.useState(!1),P=!!e&&t&&!!n,M=!!c&&!d,_=l.useCallback(async()=>{var H,$,I;if(P){h(!0),S(null);try{const W=await p(e,"read_mesh_json_config",{workspace:n}),F=(W==null?void 0:W.result)??W,z=((H=F==null?void 0:F.providerDefaults)==null?void 0:H.autoApproveModes)||((I=($=F==null?void 0:F.config)==null?void 0:$.providerDefaults)==null?void 0:I.autoApproveModes),Q={};if(z&&typeof z=="object")for(const[ne,oe]of Object.entries(z))typeof oe=="string"&&oe.trim()&&(Q[ne]=oe.trim());g(Q)}catch(W){S((W==null?void 0:W.message)||u("repoMesh.providerAutoApprove.loadError"))}finally{h(!1)}}},[P,e,n,p,u]);l.useEffect(()=>{_()},[_]);const D=l.useCallback((H,$)=>{j(!1),g(I=>{const W={...I};return $&&$.trim()?W[H]=$.trim():delete W[H],W})},[]),B=l.useCallback((H,$)=>{if(Gs($)==="dangerous"){A({type:H,mode:$});return}D(H,$.id)},[D]),R=l.useCallback(()=>{N&&D(N.type,N.mode.id),A(null)},[D,N]),O=l.useCallback(async()=>{if(P){w(!0),v(null),j(!1);try{const H=await p(e,"set_mesh_provider_defaults",{workspace:n,autoApproveModes:f,merge:!1,write:!0}),$=(H==null?void 0:H.result)??H;if(($==null?void 0:$.success)===!1)throw new Error(($==null?void 0:$.error)||u("repoMesh.providerAutoApprove.saveError"));j(!0),await _()}catch(H){v((H==null?void 0:H.message)||u("repoMesh.providerAutoApprove.saveError"))}finally{w(!1)}}},[P,e,n,_,f,p,u]);return s.jsxs(bt,{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:H=>c==null?void 0:c({delegatedWorkerAutoApprove:H})}),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:H=>{H?L(!0):c==null||c({delegatedWorkerDangerousModeAllow:!1})}})]})]}),P?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(H=>{const $=f[H.type],I=D2({config:H.autoApproveModes,requestedModeId:$,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:H.label}),s.jsx("button",{type:"button",className:"text-[11px] text-text-muted underline decoration-dotted hover:text-text-primary disabled:opacity-40",onClick:()=>D(H.type,void 0),disabled:!$||b,children:u("repoMesh.providerAutoApprove.repoSection.clear")})]}),s.jsx(cf,{config:H.autoApproveModes,selectedModeId:$||"",disabled:b,onSelectMode:W=>B(H.type,W)}),!$&&s.jsx("div",{className:"mt-1.5 text-[11px] text-text-muted",children:u("repoMesh.providerAutoApprove.repoSection.usesProviderDefault")}),s.jsx(L2,{effective:I,config:H.autoApproveModes})]},H.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 O(),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")}),T&&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:()=>{L(!1),c==null||c({delegatedWorkerDangerousModeAllow:!0})},onCancel:()=>L(!1)}),N&&s.jsx(df,{mode:N.mode,onConfirm:R,onCancel:()=>A(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 L2({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(lf,{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 R2({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(bt,{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(bt,{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 E2({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=_h(a==null?void 0:a.meshCoordinator,{meshId:e});return r?s.jsx(bt,{title:n("repoMesh.hermesMcp.title"),description:n("repoMesh.hermesMcp.description"),children:s.jsx(of,{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."}],_2=[{value:"smart",labelKey:"repoMesh.detail.distributionSmart",descriptionKey:"repoMesh.detail.distributionSmartDescription"},{value:"in_order",labelKey:"repoMesh.detail.distributionInOrder",descriptionKey:"repoMesh.detail.distributionInOrderDescription"}];function H2(e){return e==="smart"?"fitness":"first_eligible"}function $2(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 F2={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,schedulingStrategy:"first_eligible",sessionCleanupOnNodeRemove:"preserve"};function jl(e){return{...F2,...(e==null?void 0:e.policy)||{}}}function B2(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 W2({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:A,settingMeshHost:T,onSetMeshHost:L,activeDaemon:P,activeDaemonId:M,meshQueue:_,userName:D,availableCliProviders:B,savingNodeSlotsId:R,onUpdateNodeSlots:O,savingNodeCapabilitiesId:H,onUpdateNodeCapabilities:$,nodeSystemPromptDrafts:I,onNodeSystemPromptDraftChange:W,savingNodeSystemPromptId:F,onSaveNodeSystemPrompt:z,selectedNodeId:Q,onSelectNode:ne,showAddNode:oe,onShowAddNode:Ce,onCancelAddNode:le,nodeWorkspace:U,onNodeWorkspaceChange:J,nodeProviderPriority:ee,onNodeProviderPriorityChange:Y,nodeDaemonId:ve,onNodeDaemonIdChange:pe,nodeCustomPath:te,onNodeCustomPathChange:me,nodePickerWorkspaces:V,nodePickerProviders:q,nodeOnboardingPlan:se,nodePlanLoading:de,attachableDaemons:K,onAddNode:fe,onRemoveNode:ie,availableCliAgents:ue,features:ye,sendCommand:Ie}){const{t:E}=ke("common"),Z=jl(e),we=e.nodes||[],ge=l.useMemo(()=>OL(we,h),[we,h]),be=we.some(st=>{var Le;const X=Number((Le=st.policy)==null?void 0:Le.schedulingPriority);return Number.isFinite(X)&&X!==0}),De=!Z.schedulingStrategy,Me=l.useMemo(()=>we.some(st=>{var X;return Array.isArray((X=st.policy)==null?void 0:X.slots)&&st.policy.slots.length>0}),[we]),We=De&&(Me||we.length>=2)?"smart":null,[Be,Xe]=l.useState(!1),at=!!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:E("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(LL,{size:13}),E(i?"repoMesh.detail.probing":"repoMesh.detail.refresh")]}),s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>r(e.id),children:E("repoMesh.detail.delete")})]}),children:[t&&s.jsx(Mt,{variant:"error",onDismiss:n,className:"mb-4",children:t}),(()=>{var rt;const st=s.jsxs(s.Fragment,{children:[ye.meshHostDaemonSection&&s.jsx(R2,{daemons:h,coordinatorDaemonId:x,onCoordinatorDaemonIdChange:S,isHostNodeAttached:w,selectedHostNode:C,hostPinned:v,hostLabel:y,hostOnline:j,hostRebindDaemonId:N,onHostRebindDaemonIdChange:G=>{A(G),d()},settingMeshHost:T,onSetMeshHost:L}),s.jsxs(bt,{title:E("repoMesh.detail.observabilityTitle"),description:E("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:()=>Xe(!0),disabled:!at,title:E(at?"repoMesh.detail.observabilityOpenTitle":"repoMesh.detail.observabilityDisabledTitle"),children:[s.jsx(cs,{size:14}),E("repoMesh.detail.observabilityOpen")]}),s.jsx("span",{className:"text-[12px] text-text-muted",children:E("repoMesh.detail.observabilityHint")})]})]}),s.jsx(i2,{nodes:we,meshQueue:_,activeDaemon:P,daemons:h,selectedMeshId:e.id,userName:D,features:{addNodeDaemonPicker:ye.addNodeDaemonPicker,nodeInstruction:ye.nodeInstruction},coordinatorDaemonId:x,availableCliProviders:B,savingNodeSlotsId:R,onUpdateNodeSlots:O,savingNodeCapabilitiesId:H,onUpdateNodeCapabilities:$,nodeSystemPromptDrafts:I,onNodeSystemPromptDraftChange:W,savingNodeSystemPromptId:F,onSaveNodeSystemPrompt:z,selectedNodeId:Q,onSelectNode:ne,showAddNode:oe,onShowAddNode:Ce,onCancelAddNode:le,nodeWorkspace:U,onNodeWorkspaceChange:J,nodeProviderPriority:ee,onNodeProviderPriorityChange:Y,nodeDaemonId:ve,onNodeDaemonIdChange:pe,nodeCustomPath:te,onNodeCustomPathChange:me,nodePickerWorkspaces:V,nodePickerProviders:q,nodeOnboardingPlan:se,nodePlanLoading:de,attachableDaemons:K,onAddNode:fe,onRemoveNode:ie})]}),X=s.jsxs(s.Fragment,{children:[s.jsxs(bt,{title:E("repoMesh.detail.schedulingTitle"),description:E("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:E("repoMesh.detail.distribution")}),s.jsx("div",{className:"flex flex-col gap-2",children:_2.map(G=>{const ce=$2(Z.schedulingStrategy,{priorityConfigured:be})===G.value;return s.jsxs("label",{className:`flex items-start gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${ce?"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:ce,disabled:p,onChange:()=>u({schedulingStrategy:H2(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:[E(G.labelKey),We===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:E("repoMesh.detail.recommended")})]}),s.jsx("span",{className:"block text-[12px] text-text-muted",children:E(G.descriptionKey)})]})]},G.value)})})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:E("repoMesh.detail.saving")})]}),s.jsx(bt,{title:E("repoMesh.detail.visibilityTitle"),description:E("repoMesh.detail.visibilityDescription"),children:s.jsx(Tt,{label:E("repoMesh.detail.visibilityLabel"),hint:E("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:Z.spawnedSessionVisibility==="visible"?"visible":"hidden",onChange:G=>u({spawnedSessionVisibility:G.target.value==="visible"?"visible":"hidden"}),disabled:p,children:[s.jsx("option",{value:"hidden",children:E("repoMesh.detail.visibilityHidden")}),s.jsx("option",{value:"visible",children:E("repoMesh.detail.visibilityVisible")})]})})}),o&&s.jsx(bt,{title:E("repoMesh.detail.magiTitle"),description:E("repoMesh.detail.magiDescription"),children:s.jsx(m2,{status:o,daemonId:M,sendDaemonCommand:Ie,availableProviders:B})}),s.jsx(bt,{children:s.jsx(b2,{quotaRouting:Z.quotaRouting??null,saving:p,error:t,onSave:G=>u({quotaRouting:G})})}),s.jsx(I2,{hostDaemonId:x,hostOnline:j,hostWorkspace:(C==null?void 0:C.workspace)||"",meshProviders:ge.providers,unreportedNodeCount:ge.unreportedNodeCount,machineAutoApproveEnabled:Z.delegatedWorkerAutoApprove!==!1,machineDangerousAllowed:Z.delegatedWorkerDangerousModeAllow===!0,onUpdatePolicy:u,savingPolicy:p,sendCommand:Ie})]}),Le=s.jsx(s.Fragment,{children:ye.coordinatorPrompt&&s.jsx(bt,{title:E("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:E("repoMesh.detail.advanced")}),description:E("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:E("repoMesh.detail.thisMesh")}),s.jsx("p",{className:"text-[12px] text-text-muted mb-3",children:E("repoMesh.detail.thisMeshHint",{name:e.name})}),s.jsx(v2,{daemonId:M,meshId:e.id,cliType:b,sendCommand:Ie,defaultOpen:!0}),s.jsxs(Tt,{label:E("repoMesh.detail.overrideLabel"),hint:E("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:E("repoMesh.detail.overridePlaceholder")}),s.jsx(y2,{daemonId:M,meshId:e.id,cliType:b,sendCommand:Ie,disabled:g,hasContent:!!m.override.trim(),onApply:G=>f({...m,override:G})})]}),s.jsx(Tt,{label:E("repoMesh.detail.appendLabel"),hint:E("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:E("repoMesh.detail.appendPlaceholder")})}),s.jsxs("details",{className:"mt-2 text-[12px] text-text-muted",children:[s.jsx("summary",{className:"cursor-pointer select-none",children:E("repoMesh.detail.availablePlaceholders")}),s.jsx("p",{className:"mt-1",children:E("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:w2.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:E(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:E("repoMesh.detail.clearTitle"),children:E("repoMesh.detail.clear")})]})]})})}),_e=s.jsxs(s.Fragment,{children:[s.jsx(T2,{status:o,daemonId:M,meshId:e.id,sendCommand:Ie}),s.jsxs(bt,{title:E("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:E("repoMesh.detail.advanced")}),description:E("repoMesh.detail.safetyDescription"),children:[s.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:[{label:E("repoMesh.detail.checkpointBefore"),key:"requirePreTaskCheckpoint",opts:[["no","No"],["yes","Yes"]],val:G=>G?"yes":"no",parse:G=>G==="yes"},{label:E("repoMesh.detail.checkpointAfter"),key:"requirePostTaskCheckpoint",opts:[["yes","Yes"],["no","No"]],val:G=>G?"yes":"no",parse:G=>G==="yes"},{label:E("repoMesh.detail.pushApproval"),key:"requireApprovalForPush",opts:[["required",E("repoMesh.detail.requireApprovalBeforePush")],["not_required",E("repoMesh.detail.doNotRequireApproval")]],val:G=>G?"required":"not_required",parse:G=>G==="required"},{label:E("repoMesh.detail.destructiveGitApproval"),key:"requireApprovalForDestructiveGit",opts:[["required",E("repoMesh.detail.requireApproval")],["not_required",E("repoMesh.detail.doNotRequireApproval")]],val:G=>G?"required":"not_required",parse:G=>G==="required"},{label:E("repoMesh.detail.uncommittedChanges"),key:"dirtyWorkspaceBehavior",opts:[["warn",E("repoMesh.detail.warnAndContinue")],["block",E("repoMesh.detail.blockTask")],["checkpoint_then_continue",E("repoMesh.detail.checkpointThenContinue")]],val:G=>G||"warn",parse:G=>G},{label:E("repoMesh.detail.autoPublishSubmodule"),key:"allowAutoPublishSubmoduleMainCommits",opts:[["disabled",E("repoMesh.detail.requireExplicitApproval")],["enabled",E("repoMesh.detail.allowRefineryPublish")]],val:G=>G?"enabled":"disabled",parse:G=>G==="enabled"}].map(({label:G,key:re,opts:ce,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(Z[re]),onChange:Ae=>u({[re]:Se(Ae.target.value)}),disabled:p,children:ce.map(([Ae,Ee])=>s.jsx("option",{value:Ae,children:Ee},Ae))})},re))}),(()=>{const G=Z.autoFastForward&&typeof Z.autoFastForward=="object"?Z.autoFastForward:{},re=G.enabled!==!1,ce=G.remoteNodes===!0,xe=G.mode==="continuous"?"continuous":"idle",Se=Ae=>u({autoFastForward:{...G,...Ae}});return s.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[s.jsx(Tt,{label:E("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:re?"enabled":"disabled",onChange:Ae=>Se({enabled:Ae.target.value==="enabled"}),disabled:p,children:[s.jsx("option",{value:"enabled",children:E("repoMesh.detail.ffEnabled")}),s.jsx("option",{value:"disabled",children:E("repoMesh.detail.ffDisabled")})]})}),s.jsx(Tt,{label:E("repoMesh.detail.includeRemoteNodes"),hint:E("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:ce?"yes":"no",onChange:Ae=>Se({remoteNodes:Ae.target.value==="yes"}),disabled:p||!re,children:[s.jsx("option",{value:"no",children:E("repoMesh.detail.remoteNo")}),s.jsx("option",{value:"yes",children:E("repoMesh.detail.remoteYes")})]})}),s.jsx(Tt,{label:E("repoMesh.detail.detectionMode"),hint:E("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:Ae=>Se({mode:Ae.target.value==="continuous"?"continuous":"idle"}),disabled:p||!re||!ce,children:[s.jsx("option",{value:"idle",children:E("repoMesh.detail.idleEdgeOnly")}),s.jsx("option",{value:"continuous",children:E("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:E("repoMesh.detail.sessionCleanupLabel"),hint:E("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:Z.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===Z.sessionCleanupOnNodeRemove))==null?void 0:rt.description)||Ri[0].description})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:E("repoMesh.detail.saving")})]})]}),nt=[{key:"nodes",label:E("repoMesh.detail.tabNodes"),content:st},{key:"scheduling",label:E("repoMesh.detail.tabScheduling"),content:X},{key:"prompts",label:E("repoMesh.detail.tabPrompts"),content:s.jsxs(s.Fragment,{children:[Le,ye.hermesMcpConfig&&s.jsx(E2,{meshId:e.id,availableCliAgents:ue}),ye.meshHostDaemonSection&&s.jsxs(Mt,{variant:"info",className:"mt-4",children:[s.jsx("strong",{children:E("repoMesh.detail.mcpMode")})," ",s.jsxs("code",{className:"bg-bg-secondary px-1 rounded text-xs",children:["adhdev mcp --repo-mesh ",e.id]})," ",E("repoMesh.detail.mcpDescription")]})]})},{key:"advanced",label:E("repoMesh.detail.tabAdvanced"),content:_e}];return s.jsxs(s.Fragment,{children:[s.jsx(f1,{tabs:nt,ariaLabel:E("repoMesh.detail.tabsAriaLabel"),className:"flex flex-col gap-4"}),Be&&at&&s.jsx(Vf,{activeConv:B2({meshId:e.id,daemonId:M,meshName:e.name}),sendDaemonCommand:Ie,onClose:()=>Xe(!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(le=>le.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,A]=l.useState(""),[T,L]=l.useState(""),[P,M]=l.useState(""),[_,D]=l.useState(""),[B,R]=l.useState(null),[O,H]=l.useState(!1),$=o.createDaemonPicker?P:t,I=l.useMemo(()=>e.find(le=>le.id===$),[e,$]),W=(I==null?void 0:I.workspaces)||[],F=l.useMemo(()=>ln((I==null?void 0:I.availableProviders)||[]),[I]);l.useEffect(()=>{!i||!$||!I||!(!I.workspaces||!I.availableProviders)||Promise.resolve(i($,{minFreshMs:3e4})).catch(()=>{})},[i,$,I]),l.useEffect(()=>{if(!x||!$||!_){R(null);return}let le=!1;return H(!0),n($,"plan_mesh_onboarding",{workspace:_,operation:"auto",meshInventory:d}).then(U=>{if(le)return;const J=a(U);R(J),J!=null&&J.success&&(A(ee=>{var Y;return ee||((Y=J.discovery)==null?void 0:Y.repoIdentity)||""}),L(ee=>{var Y,ve,pe,te,me,V;return ee||((pe=(ve=(Y=J.discovery)==null?void 0:Y.origin)==null?void 0:ve.urls)==null?void 0:pe[0])||((V=(me=(te=J.discovery)==null?void 0:te.upstream)==null?void 0:me.urls)==null?void 0:V[0])||""}),j(ee=>{var Y,ve;return ee||`${String(((Y=J.discovery)==null?void 0:Y.repoIdentity)||((ve=J.discovery)==null?void 0:ve.repoRoot)||"").split(/[\\/]/).filter(Boolean).pop()||"repo"}-mesh`}))}).catch(U=>{le||R({success:!1,error:(U==null?void 0:U.message)||"Git discovery failed"})}).finally(()=>{le||H(!1)}),()=>{le=!0}},[x,$,_,d,n,a]);const z=l.useMemo(()=>e.map(le=>le.id).filter(Boolean).sort().join(","),[e]),Q=l.useCallback(async(le=!1)=>{const U=le||va.has(z);g(J=>U?J:!0);try{if(o.createDaemonPicker){const J=await Promise.allSettled(e.map(async ve=>{if(!ve.id)return[];const pe=await n(ve.id,"list_meshes",{}),te=a(pe);if((te==null?void 0:te.success)===!1)throw new Error(te.error||"Failed to load meshes");return(Array.isArray(te==null?void 0:te.meshes)?te.meshes:[]).map(me=>r(me,ve.id)).filter(me=>me.id)})),ee=new Map;for(const ve of J)if(ve.status==="fulfilled")for(const pe of ve.value)ee.has(pe.id)||ee.set(pe.id,pe);const Y=Array.from(ee.values());p(ve=>sp(ve,Y)?ve:Y),va.set(z,Y),h(null)}else{if(!t)return;const J=await n(t,"list_meshes");if(J!=null&&J.success){const ee=(J.meshes||[]).map(Y=>r(Y,t));p(Y=>sp(Y,ee)?Y:ee),va.set(z,ee),h(null)}else h((J==null?void 0:J.error)||"Failed to load meshes")}}catch(J){h((J==null?void 0:J.message)||"Failed to load meshes")}finally{g(!1)}},[z,t,n,a,r,o.createDaemonPicker]);async function ne(){const le=o.createDaemonPicker?P:t;if(!le||!y.trim())return;const U=T.trim(),J=N.trim(),ee=_.trim();if(!(!ee&&!U&&!J)&&!b){w(!0),v(null);try{const Y=await rg({targetDaemonId:le,name:y,repoRemoteUrl:U,repoIdentity:J,workspace:ee,attachWorkspace:!!ee,machineId:I==null?void 0:I.machineId,providerPriority:Dn(F),meshInventory:d,sendCommand:n,unwrapResult:a,reusablePlan:!O&&B?B:void 0});if(Y.plan!==null&&R(Y.plan),Y.warning&&v(Y.warning),!Y.meshCreated){h(Y.error||"Create failed");return}S(!1),j(""),A(""),L(""),D(""),await Q(),Y.meshId&&m(Y.meshId)}finally{w(!1)}}}async function oe(le){var J;if(!confirm("Delete this mesh? This cannot be undone."))return;const U=((J=d.find(ee=>ee.id===le))==null?void 0:J.__sourceDaemonId)||t;try{const ee=await n(U,"delete_mesh",{meshId:le}),Y=a(ee);if((Y==null?void 0:Y.success)===!1)throw new Error(Y.error||"Failed to delete");u===le&&m(null),await Q()}catch(ee){h((ee==null?void 0:ee.message)||"Delete failed")}}function Ce(){S(!1),j(""),A(""),L(""),D(""),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:A,createRepoRemoteUrl:T,setCreateRepoRemoteUrl:L,newMeshDaemonId:P,setNewMeshDaemonId:M,newMeshWorkspace:_,setNewMeshWorkspace:D,createPickerWorkspaces:W,createPickerProviders:F,createOnboardingPlan:B,createPlanLoading:O,loadMeshes:Q,handleCreate:ne,handleDelete:oe,cancelCreate:Ce}}function O2({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(""),[A,T]=l.useState(!1),[L,P]=l.useState(null),[M,_]=l.useState(!1),[D,B]=l.useState(""),[R,O]=l.useState(!1),[H,$]=l.useState(!1),[I,W]=l.useState(null),[F,z]=l.useState(!1),[Q,ne]=l.useState({override:"",append:""}),[oe,Ce]=l.useState(!1),[le,U]=l.useState({}),[J,ee]=l.useState(null),Y=l.useMemo(()=>r.find(Z=>Z.id===j),[r,j]),ve=(Y==null?void 0:Y.workspaces)||[],pe=l.useMemo(()=>ln((Y==null?void 0:Y.availableProviders)||[]),[Y]);l.useEffect(()=>{if(!S||!t||!w.trim()){P(null);return}const Z=u.addNodeDaemonPicker?j:(e==null?void 0:e.__sourceDaemonId)||n;if(!Z)return;let we=!1;return _(!0),o(Z,"plan_mesh_onboarding",{workspace:w.trim(),meshId:t,inlineMesh:e,operation:"add_existing"}).then(ge=>{we||P(i(ge))}).catch(ge=>{we||P({success:!1,error:(ge==null?void 0:ge.message)||"Git discovery failed"})}).finally(()=>{we||_(!1)}),()=>{we=!0}},[S,t,e,w,j,n,u.addNodeDaemonPicker,o,i]);async function te(){var ge,be,De;const Z=(e==null?void 0:e.__sourceDaemonId)||n;if(!t||!Z)return;const we=w.trim();if(we)try{const Me=u.addNodeDaemonPicker?j:Z,We=await o(Me,"plan_mesh_onboarding",{workspace:we,meshId:t,inlineMesh:e,operation:"add_existing"}),Be=i(We);if(P(Be),(Be==null?void 0:Be.success)===!1)throw new Error(`${Be.code||"onboarding_blocked"}: ${Be.error}${Be.action?` ${Be.action}`:""}`);const Xe={meshId:t,workspace:((ge=Be==null?void 0:Be.discovery)==null?void 0:ge.repoRoot)||we,repoRoot:(be=Be==null?void 0:Be.discovery)==null?void 0:be.repoRoot,isLocalWorktree:((De=Be==null?void 0:Be.discovery)==null?void 0:De.isLinkedWorktree)===!0};u.addNodeDaemonPicker&&j&&(Xe.daemonId=j,Xe.machineId=Y==null?void 0:Y.machineId),Xe.providerPriority=Va(v);const at=await o(Z,"add_mesh_node",Xe),st=i(at);if((st==null?void 0:st.success)===!1)throw new Error(st.error||"Add node failed");b(!1),C(""),y([]),N(""),T(!1),await m(),g||await f(t)}catch(Me){k((Me==null?void 0:Me.message)||"Add node failed")}}async function me(Z){var De;if(!e)return;const we=jl(e),ge=((De=[{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(Me=>Me.value===we.sessionCleanupOnNodeRemove))==null?void 0:De.label)||"Preserve history and runtimes";if(!confirm(`Remove this node?
120
120
 
121
- Node removal cleanup policy: ${ge}`))return;const be=e.__sourceDaemonId||n;try{const Me=await o(be,"remove_mesh_node",{meshId:e.id,nodeId:Z}),We=i(Me);if((We==null?void 0:We.success)===!1)throw new Error(We.error||"Remove failed");h===Z&&x(null),await m(),g||await f(t)}catch(Me){k((Me==null?void 0:Me.message)||"Remove node failed")}}async function V(Z){if(!e)return;const we={...jl(e),...Z},ge=e.__sourceDaemonId||n;try{z(!0),k(null);const be=await o(ge,"update_mesh",{meshId:e.id,policy:we}),De=i(be);if((De==null?void 0:De.success)===!1)throw new Error(De.error||"Policy update failed");await m()}catch(be){k((be==null?void 0:be.message)||"Policy update failed")}finally{z(!1)}}const[q,se]=l.useState(null);async function de(Z,we){if(!t)return;const ge=(e==null?void 0:e.__sourceDaemonId)||n;try{se(Z.id),k(null);const be=await o(ge,"update_mesh_node",{meshId:t,nodeId:Z.id,policy:{slots:we}}),De=i(be);if((De==null?void 0:De.success)===!1){k(De.error||"Node slots update failed");return}await m()}catch(be){k((be==null?void 0:be.message)||"Node slots update failed")}finally{se(null)}}const[K,fe]=l.useState(null);async function ie(Z,we){if(!t)return;const ge=(e==null?void 0:e.__sourceDaemonId)||n,be=we.map(De=>De.trim()).filter(Boolean);try{fe(Z.id),k(null);const De=await o(ge,"update_mesh_node",{meshId:t,nodeId:Z.id,capabilities:be}),Me=i(De);if((Me==null?void 0:Me.success)===!1){k(Me.error||"Node tag update failed");return}await m()}catch(De){k((De==null?void 0:De.message)||"Node tag update failed")}finally{fe(null)}}async function ue(){if(!n||!t)return;const we={...(e==null?void 0:e.coordinator)||{}};Q.override.trim()?we.systemPromptOverride=Q.override:delete we.systemPromptOverride,Q.append.trim()?we.systemPromptAppend=Q.append:delete we.systemPromptAppend,delete we.systemPromptSuffix;try{Ce(!0),k(null);const ge=await o(n,"update_mesh",{meshId:t,coordinator:we}),be=i(ge);if((be==null?void 0:be.success)===!1){k(be.error||"Coordinator prompt save failed");return}await m()}catch(ge){k((ge==null?void 0:ge.message)||"Coordinator prompt save failed")}finally{Ce(!1)}}async function ye(Z){if(!n||!t)return;const we=(le[Z.id]||"").trim();try{ee(Z.id),k(null);const ge=await o(n,"update_mesh_node",{meshId:t,nodeId:Z.id,systemPrompt:we}),be=i(ge);if((be==null?void 0:be.success)===!1){k(be.error||"Node instruction save failed");return}await m()}catch(ge){k((ge==null?void 0:ge.message)||"Node instruction save failed")}finally{ee(null)}}async function Ie(Z){if(!(!e||!Z)){k(null),W(null);try{$(!0);const we=(e.nodes||[]).find(De=>Zs(String(De.daemon_id||De.daemonId||""),Z)),ge=await o(Z,"set_mesh_host",{meshId:e.id,hostDaemonId:Z,...we!=null&&we.id?{hostNodeId:we.id}:{}}),be=i(ge);if((be==null?void 0:be.success)===!1){k(be.error||"Setting the mesh host failed");return}await m()}catch(we){k((we==null?void 0:we.message)||"Setting the mesh host failed")}finally{$(!1)}}}async function E(){if(e){k(null),W(null);try{O(!0);const Z=c?await c(a,e.id,e):null,we=d(a,e.id,e,e.nodes||[],Z);if("error"in we)throw new Error(we.error);const ge=await p(we.targetDaemonId,{meshId:e.id,inlineMesh:we.inlineMesh,coordinatorNodeId:we.coordinatorNodeId,cliType:D.trim()||void 0});W(ge.message)}catch(Z){k((Z==null?void 0:Z.message)||"Coordinator launch failed")}finally{O(!1)}}}return{selectedNodeId:h,setSelectedNodeId:x,showAddNode:S,setShowAddNode:b,nodeWorkspace:w,setNodeWorkspace:C,nodeProviderPriority:v,setNodeProviderPriority:y,nodeDaemonId:j,setNodeDaemonId:N,nodeCustomPath:A,setNodeCustomPath:T,nodePickerWorkspaces:ve,nodePickerProviders:pe,nodeOnboardingPlan:L,nodePlanLoading:M,coordinatorCliType:D,setCoordinatorCliType:B,launchingCoordinator:R,launchResult:I,settingMeshHost:H,savingPolicy:F,coordinatorPromptDraft:Q,setCoordinatorPromptDraft:ne,savingCoordinatorPrompt:oe,nodeSystemPromptDrafts:le,setNodeSystemPromptDrafts:U,savingNodeSystemPromptId:J,savingNodeSlotsId:q,savingNodeCapabilitiesId:K,handleAddNode:te,handleRemoveNode:me,handleUpdatePolicy:V,handleUpdateNodeSlots:de,handleUpdateNodeCapabilities:ie,handleSaveCoordinatorPrompt:ue,handleSaveNodeSystemPrompt:ye,handleLaunchCoordinator:E,handleSetMeshHost:Ie}}function U2(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 G2({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(U2(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 q2(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 z2(e,t){!e||!t||ig.set(e,t)}function K2({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(q2(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&&!hM(jf(y))){f("settling"),h.current||(h.current=!0,Promise.resolve().then(()=>x(S,b,!0)).finally(()=>{h.current=!1}));return}i(y),z2(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 V2(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 Y2(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 Q2=4,J2=3e4;function X2(){return{lastFingerprint:null,stableTicks:0,backedOff:!1}}function Nl(e){e.stableTicks=0,e.backedOff=!1}function Z2(e,t){const n=Y2(t);return e.lastFingerprint===null?(e.lastFingerprint=n,e.backedOff):n!==e.lastFingerprint?(e.lastFingerprint=n,Nl(e),!1):(e.stableTicks+=1,e.stableTicks>=Q2&&(e.backedOff=!0),e.backedOff)}function eR(e,t){return e.backedOff?Math.max(t,J2):t}const tR=7e3,sR=45e3;function nR(){const e=PL(),{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:A,showCreate:T,setShowCreate:L,createName:P,setCreateName:M,createRepoIdentity:_,setCreateRepoIdentity:D,createRepoRemoteUrl:B,setCreateRepoRemoteUrl:R,newMeshDaemonId:O,setNewMeshDaemonId:H,newMeshWorkspace:$,setNewMeshWorkspace:I,createPickerWorkspaces:W,createOnboardingPlan:F,createPlanLoading:z,creating:Q,createWarning:ne,setCreateWarning:oe,loadMeshes:Ce,handleCreate:le,handleDelete:U,cancelCreate:J}=og({daemons:a,primaryDaemonId:S,sendCommand:t,unwrapResult:p,normalizeMesh:u,features:g,loadDaemonMetadata:h}),ee=C.find(Fe=>Fe.id===v)||null,{meshGraphStatus:Y,setMeshGraphStatus:ve,graphLoading:pe,graphError:te,setGraphError:me,loadGraph:V}=K2({selectedMeshId:v,loadMeshStatus:o,extractStatus:d,normalizeNode:m,gateIncompleteGraph:k}),[q,se]=l.useState(""),[de,K]=l.useState(""),fe=g.meshHostDaemonSection?q:S,{meshQueue:ie,loadQueue:ue}=G2({primaryDaemonId:S,activeDaemonId:fe,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:f}),{selectedNodeId:ye,setSelectedNodeId:Ie,showAddNode:E,setShowAddNode:Z,nodeWorkspace:we,setNodeWorkspace:ge,nodeProviderPriority:be,setNodeProviderPriority:De,nodeDaemonId:Me,setNodeDaemonId:We,nodeCustomPath:Be,setNodeCustomPath:Xe,nodePickerWorkspaces:at,nodePickerProviders:st,nodeOnboardingPlan:X,nodePlanLoading:Le,coordinatorCliType:_e,savingPolicy:nt,coordinatorPromptDraft:rt,setCoordinatorPromptDraft:G,savingCoordinatorPrompt:re,nodeSystemPromptDrafts:ce,setNodeSystemPromptDrafts:xe,savingNodeSystemPromptId:Se,savingNodeSlotsId:Ae,savingNodeCapabilitiesId:Ee,handleAddNode:Re,handleRemoveNode:Qe,handleUpdatePolicy:et,handleUpdateNodeSlots:Je,handleUpdateNodeCapabilities:Oe,handleSaveCoordinatorPrompt:Ye,handleSaveNodeSystemPrompt:tt,settingMeshHost:$e,handleSetMeshHost:he}=O2({selectedMesh:ee,selectedMeshId:v,primaryDaemonId:S,activeDaemonId:fe,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:A}),je=l.useMemo(()=>a.find(Fe=>Fe.id===fe)||x,[a,fe,x]),Ne=l.useMemo(()=>new Set(((ee==null?void 0:ee.nodes)||[]).map(Fe=>String(Fe.daemon_id||Fe.daemonId||""))),[ee]),He=l.useMemo(()=>a.filter(Fe=>Fe.id&&!Ne.has(Fe.id)&&!Zp(Fe)),[a,Ne]),Ue=(ee==null?void 0:ee.nodes)||[],dt=l.useMemo(()=>Ue.find(Fe=>Zs(String(Fe.daemon_id||Fe.daemonId||""),q)),[Ue,q]),Ke=g.meshHostDaemonSection?!!dt:!0,ut=l.useMemo(()=>{if(!g.meshHostDaemonSection||!ee)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const Fe=ee.meshHost,lt=Y!=null&&Y.meshId&&String(Y.meshId)===String(ee.id??"")?Y.meshHost:void 0,es=lt!=null&&lt.hostDaemonId?lt:Fe??lt,ns=np(es),js=ns.hostDaemonId,Ys=Ue.find(Fs=>Fs.role==="host"),cn=ns.hostNodeId||String((Ys==null?void 0:Ys.id)||""),ae=cn?Ue.find(Fs=>String(Fs.id)===cn):void 0,ze=String((ae==null?void 0:ae.daemon_id)||(ae==null?void 0:ae.daemonId)||""),Ge=js||ze;if(!Ge)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const Nt=a.find(Fs=>js&&Zs(Fs.id,js))||(ze?a.find(Fs=>Zs(Fs.id,ze)):void 0);if(Nt)return{pinned:!0,daemonId:Nt.id,label:aR(Nt),online:!0,hostNode:ae};const dn=String((ae==null?void 0:ae.machineLabel)||"")||String((ae==null?void 0:ae.workspace)||"")||Ge;return{pinned:!0,daemonId:Ge,label:dn,online:!1,hostNode:ae}},[ee,Ue,a,Y,g.meshHostDaemonSection]),zt=ut.daemonId,Et=ut.online,ps=ut.pinned?ut.hostNode:dt,Zt=l.useMemo(()=>!g.meshHostDaemonSection||!ut.pinned?"":!Et&&de&&a.some(Fe=>Fe.id===de)?de:zt,[g.meshHostDaemonSection,ut.pinned,Et,de,a,zt]),_s=l.useMemo(()=>Y?[...new Set((Y.nodes??[]).map(Fe=>String(Fe.daemonId||Fe.daemon_id||"")).filter(Boolean))]:[],[Y]),Pe=Kf({status:Y,daemonId:fe||null,extraDaemonIds:_s,meshId:v,sendData:n});l.useEffect(()=>{const Fe=(ee==null?void 0:ee.coordinator)||{};G({override:typeof Fe.systemPromptOverride=="string"?Fe.systemPromptOverride:"",append:typeof Fe.systemPromptAppend=="string"?Fe.systemPromptAppend:typeof Fe.systemPromptSuffix=="string"?Fe.systemPromptSuffix:""}),xe(Object.fromEntries(((ee==null?void 0:ee.nodes)||[]).map(lt=>[lt.id,typeof lt.systemPrompt=="string"?lt.systemPrompt:""])))},[ee]),l.useEffect(()=>{const Fe=g.addNodeDaemonPicker?Dn(st):Dn(w);E&&be.length===0&&Fe.length>0&&De(Fe)},[E,w,st,be.length,g.addNodeDaemonPicker]),l.useEffect(()=>{const Fe=new Set(((ee==null?void 0:ee.nodes)||[]).map(lt=>lt.id));ye&&!Fe.has(ye)&&Ie(null)},[ee,ye]);const Ze=l.useMemo(()=>{if(!(!(Y!=null&&Y.meshId)||String(Y.meshId)!==String((ee==null?void 0:ee.id)??"")))return np(Y.meshHost).hostDaemonId||void 0},[Y,ee]),It=l.useMemo(()=>V2(a,Ue,fe,S,Ze),[a,Ue,fe,S,Ze]);l.useEffect(()=>{if(!g.meshHostDaemonSection)return;if(!a.length&&!ut.pinned){se("");return}const Fe=ut.pinned?Zt:It;Fe&&!Zs(Fe,q)&&se(Fe)},[a,q,ut.pinned,Zt,It,g.meshHostDaemonSection]),l.useEffect(()=>{de&&(Et||!a.some(Fe=>Fe.id===de))&&K("")},[Et,de,a]),l.useEffect(()=>{if(g.createDaemonPicker){if(!a.length){H("");return}(!O||!a.some(Fe=>Fe.id===O))&&H(a[0].id)}},[a,O,g.createDaemonPicker]),l.useEffect(()=>{var Fe;if(!g.createDaemonPicker||!O){I("");return}if(!W.length){I("");return}W.some(lt=>lt.path===$)||I(((Fe=W[0])==null?void 0:Fe.path)||"")},[O,$,W,g.createDaemonPicker]);const pt=l.useRef(null),Yt=l.useRef(X2()),_t=g.meshStatePushRefresh?sR:tR,[Qt,Cs]=l.useState(_t);l.useEffect(()=>{if(!v)return;const Fe=pt.current!==v;if(pt.current=v,Fe){Nl(Yt.current),Cs(_t);const lt=lg(v);ve(lt),me(null),V(fe,v,lt!==null)}else me(null),V(fe,v,!0)},[v,fe]);const Hs=l.useRef(V);Hs.current=V;const ms=l.useRef(!1),ss=l.useRef(()=>{});ss.current=()=>{ms.current||!v||!fe||(ms.current=!0,Promise.resolve(Hs.current(fe,v,!0)).finally(()=>{ms.current=!1}))},l.useEffect(()=>{Z2(Yt.current,Y),Cs(eR(Yt.current,_t))},[Y,_t]),DL({daemonIds:l.useMemo(()=>[fe,..._s].filter(Boolean),[fe,_s]),meshId:v,sendData:n,onRevisionAdvance:()=>{typeof document<"u"&&document.visibilityState!=="visible"||ss.current()}}),l.useEffect(()=>{if(!v||!fe||typeof document>"u")return;let Fe=null;const lt=()=>{document.visibilityState==="visible"&&ss.current()},es=()=>{Fe===null&&(Fe=setInterval(lt,Qt))},ns=()=>{Fe!==null&&(clearInterval(Fe),Fe=null)},js=()=>{document.visibilityState==="visible"?es():ns()};return document.visibilityState==="visible"&&es(),document.addEventListener("visibilitychange",js),()=>{ns(),document.removeEventListener("visibilitychange",js)}},[v,fe,Qt]),l.useEffect(()=>{g.queueSection||ue(v)},[v,g.queueSection]);const Vs=l.useMemo(()=>a.map(Fe=>Fe.id).filter(Boolean).sort().join(","),[a]),$s=l.useRef(!1);return l.useEffect(()=>{Ce($s.current),$s.current=!0},[Vs]),S?ee?s.jsx(W2,{selectedMesh:ee,error:N,onDismissError:()=>A(null),onBack:()=>{y(null),ve(null)},onDelete:U,displayedMeshStatus:Pe,graphLoading:pe,graphError:te,onRefreshGraph:()=>{Nl(Yt.current),V(fe,v,!0)},savingPolicy:nt,onUpdatePolicy:et,coordinatorPromptDraft:rt,onCoordinatorPromptDraftChange:G,savingCoordinatorPrompt:re,onSaveCoordinatorPrompt:Ye,daemons:a,coordinatorDaemonId:q,onCoordinatorDaemonIdChange:se,coordinatorCliType:_e,isHostNodeAttached:Ke,selectedHostNode:ps,hostPinned:ut.pinned,hostLabel:ut.label,hostOnline:Et,hostRebindDaemonId:de,onHostRebindDaemonIdChange:Fe=>K(Fe),settingMeshHost:$e,onSetMeshHost:he,activeDaemon:je,activeDaemonId:fe,meshQueue:ie,userName:r,availableCliProviders:w,savingNodeSlotsId:Ae,onUpdateNodeSlots:Je,savingNodeCapabilitiesId:Ee,onUpdateNodeCapabilities:Oe,nodeSystemPromptDrafts:ce,onNodeSystemPromptDraftChange:(Fe,lt)=>xe(es=>({...es,[Fe]:lt})),savingNodeSystemPromptId:Se,onSaveNodeSystemPrompt:tt,selectedNodeId:ye,onSelectNode:Ie,showAddNode:E,onShowAddNode:()=>Z(!0),onCancelAddNode:()=>Z(!1),nodeWorkspace:we,onNodeWorkspaceChange:ge,nodeProviderPriority:be,onNodeProviderPriorityChange:De,nodeDaemonId:Me,onNodeDaemonIdChange:We,nodeCustomPath:Be,onNodeCustomPathChange:Xe,nodePickerWorkspaces:at,nodePickerProviders:st,nodeOnboardingPlan:X,nodePlanLoading:Le,attachableDaemons:He,onAddNode:Re,onRemoveNode:Qe,availableCliAgents:b,features:{coordinatorPrompt:g.coordinatorPrompt,meshHostDaemonSection:g.meshHostDaemonSection,hermesMcpConfig:g.hermesMcpConfig,addNodeDaemonPicker:g.addNodeDaemonPicker,nodeInstruction:g.nodeInstruction},sendCommand:t}):s.jsx(FL,{meshes:C,loading:j,error:N,onDismissError:()=>A(null),daemons:a,features:{createDaemonPicker:g.createDaemonPicker,maxMeshes:g.maxMeshes},showCreate:T,onToggleCreate:()=>L(!T),createName:P,onCreateNameChange:M,createRepoIdentity:_,onCreateRepoIdentityChange:D,createRepoRemoteUrl:B,onCreateRepoRemoteUrlChange:R,newMeshDaemonId:O,onNewMeshDaemonIdChange:H,newMeshWorkspace:$,onNewMeshWorkspaceChange:I,createPickerWorkspaces:W,createOnboardingPlan:F,createPlanLoading:z,creating:Q,createWarning:ne,onDismissCreateWarning:()=>oe(null),onSelectMesh:y,onCreate:le,onCancelCreate:J}):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 aR(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function rR({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 oR(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:A,onCreateManualOpenChange:T,nodes:L,attachableDaemons:P,attachDaemonId:M,onAttachDaemonIdChange:_,attachWorkspace:D,onAttachWorkspaceChange:B,attachPickerWorkspaces:R,attachPlan:O,attachPlanLoading:H,attaching:$,onAttach:I,renderInstallOnboarding:W,nodeLabel:F,daemonLabel:z}=e,{t:Q}=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:Q("setupWizard.machines.title")}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-text-muted",children:Q("setupWizard.machines.noMachinesDescription")})]}),W?W():s.jsx("p",{className:"text-[11px] text-text-muted",children:Q("setupWizard.machines.noMachinesFallback")})]});const ne=$||H||(O==null?void 0:O.success)===!1||!D.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:Q("setupWizard.machines.title")}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-text-muted",children:Q("setupWizard.machines.description")})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[a.map(oe=>{const Ce=!c&&o===oe.id;return s.jsx("button",{type:"button",onClick:()=>{d(!1),i(oe.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:oe.name}),s.jsxs("span",{className:"block truncate text-[11px] text-text-muted",children:[oe.repoIdentity||oe.repoRemoteUrl||""," · ",Q("setupWizard.machines.nodeCount",{count:(oe.nodes||[]).length})]})]})},oe.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:["+ ",Q("setupWizard.machines.createNew")]})}),r&&a.length===0&&s.jsx("p",{className:"text-[11px] text-text-muted",children:Q("setupWizard.machines.loadingMeshes")})]}),c&&s.jsx(ng,{variant:"wizard",showDaemonPicker:n.createDaemonPicker,daemons:t,daemonLabel:z,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:A,onManualOpenChange:T,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:[L.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5",children:L.map(oe=>s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] text-text-secondary",children:F(oe)},oe.id))}),s.jsx("span",{className:"text-[11px] font-medium text-text-secondary",children:Q("setupWizard.machines.attachTitle")}),n.addNodeDaemonPicker&&(P.length>0?s.jsx("div",{className:"flex flex-wrap gap-1.5",children:P.map(oe=>{const Ce=M===oe.id;return s.jsx("button",{type:"button",onClick:()=>_(oe.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:z(oe)},oe.id)})}):s.jsx("p",{className:"text-[11px] text-text-muted",children:Q("setupWizard.machines.allMachinesAttached")})),(!n.addNodeDaemonPicker||M)&&s.jsxs(s.Fragment,{children:[s.jsx(yl,{workspaces:R,value:D,onChange:B}),s.jsx(sg,{plan:O,loading:H}),s.jsx("div",{className:"flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:I,disabled:ne,children:Q($?"setupWizard.machines.attaching":"setupWizard.machines.addMachine")})})]})]})]})}function iR(e){var t;return e.machineNickname||e.nickname||e.hostname||((t=e.user)==null?void 0:t.name)||e.id}function lR(e){const t=e;return t.machine_label||t.machineLabel||t.hostname||String(e.workspace||"").split(/[\\/]/).filter(Boolean).pop()||e.id}function cR({daemons:e,features:t,sendCommand:n,unwrapResult:a,normalizeMesh:r,loadDaemonMetadata:o,initialMeshId:i,onClose:c,renderInstallOnboarding:d}){var we,ge;const{t:p}=ke("common"),u=((we=e[0])==null?void 0:we.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(be=>be.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(be=>be.id===i)?S(i):m.length===1&&S(m[0].id))},[m,x,i,S]);const y=l.useMemo(()=>m.find(be=>be.id===x)??null,[m,x]),j=l.useMemo(()=>(y==null?void 0:y.nodes)||[],[y]),N=l.useCallback(be=>(be==null?void 0:be.__sourceDaemonId)||u,[u]),[A,T]=l.useState(!1),[L,P]=l.useState(""),[M,_]=l.useState(""),[D,B]=l.useState(""),[R,O]=l.useState(null),[H,$]=l.useState(!1),[I,W]=l.useState(!1),[F,z]=l.useState(null),[Q,ne]=l.useState(""),[oe,Ce]=l.useState(""),[le,U]=l.useState(!1),J=t.createDaemonPicker&&M||u,ee=l.useMemo(()=>e.find(be=>be.id===J),[e,J]),Y=(ee==null?void 0:ee.workspaces)||[];l.useEffect(()=>{if(!A||!J||!D.trim()){O(null),$(!1);return}let be=!1;const De=setTimeout(()=>{be||($(!0),C.current(J,"plan_mesh_onboarding",{workspace:D.trim(),operation:"auto",meshInventory:b.current}).then(Me=>{if(be)return;const We=v.current(Me);O(We),We!=null&&We.success&&(P(Be=>{var Xe,at;return Be||`${String(((Xe=We.discovery)==null?void 0:Xe.repoIdentity)||((at=We.discovery)==null?void 0:at.repoRoot)||"").split(/[\\/]/).filter(Boolean).pop()||"repo"}-mesh`}),Ce(Be=>{var Xe;return Be||((Xe=We.discovery)==null?void 0:Xe.repoIdentity)||""}),ne(Be=>{var Xe,at,st,X,Le,_e;return Be||((st=(at=(Xe=We.discovery)==null?void 0:Xe.origin)==null?void 0:at.urls)==null?void 0:st[0])||((_e=(Le=(X=We.discovery)==null?void 0:X.upstream)==null?void 0:Le.urls)==null?void 0:_e[0])||""}))}).catch(Me=>{be||O({success:!1,error:(Me==null?void 0:Me.message)||"Git discovery failed"})}).finally(()=>{be||$(!1)}))},300);return()=>{be=!0,clearTimeout(De)}},[A,J,D,w]);const ve=l.useCallback(async()=>{const be=J,De=D.trim(),Me=Q.trim(),We=oe.trim();if(!(!be||!L.trim()||I)&&!(!De&&!Me&&!We)){W(!0),z(null),k(null);try{const Be=await rg({targetDaemonId:be,name:L,repoRemoteUrl:Me,repoIdentity:We,workspace:De,attachWorkspace:!!De,machineId:ee==null?void 0:ee.machineId,providerPriority:Dn(ln((ee==null?void 0:ee.availableProviders)||[])),meshInventory:m,sendCommand:n,unwrapResult:a});if(Be.warning&&z(Be.warning),!Be.meshCreated){k(Be.error||p("setupWizard.machines.createFailed"));return}await h(!0),Be.meshId&&S(Be.meshId),T(!1)}finally{W(!1)}}},[J,L,D,Q,oe,I,ee,m,n,a,h,S,k,p]),[pe,te]=l.useState(""),[me,V]=l.useState(""),[q,se]=l.useState(null),[de,K]=l.useState(!1),[fe,ie]=l.useState(!1),ue=l.useMemo(()=>{if(!t.addNodeDaemonPicker)return[];const be=new Set(j.map(De=>String(De.daemon_id||De.daemonId||"")));return e.filter(De=>De.id&&!be.has(De.id)&&!Zp(De))},[t.addNodeDaemonPicker,j,e]),ye=l.useMemo(()=>e.find(be=>be.id===pe),[e,pe]),Ie=t.addNodeDaemonPicker?(ye==null?void 0:ye.workspaces)||[]:((ge=e.find(be=>be.id===u))==null?void 0:ge.workspaces)||[];l.useEffect(()=>{if(A||!x||!me.trim()){se(null);return}const be=t.addNodeDaemonPicker?pe:N(y);if(!be)return;let De=!1;return K(!0),n(be,"plan_mesh_onboarding",{workspace:me.trim(),meshId:x,inlineMesh:y,operation:"add_existing"}).then(Me=>{De||se(a(Me))}).catch(Me=>{De||se({success:!1,error:(Me==null?void 0:Me.message)||"Git discovery failed"})}).finally(()=>{De||K(!1)}),()=>{De=!0}},[A,x,y,me,pe,t.addNodeDaemonPicker,N,n,a]);const E=l.useCallback(async()=>{var Me,We,Be,Xe;const be=N(y);if(!x||!be||fe)return;const De=me.trim();if(De){ie(!0),k(null);try{const at=t.addNodeDaemonPicker?pe:be,st=await n(at,"plan_mesh_onboarding",{workspace:De,meshId:x,inlineMesh:y,operation:"add_existing"}),X=a(st);if(se(X),(X==null?void 0:X.success)===!1)throw new Error(`${X.code||"onboarding_blocked"}: ${X.error}${X.action?` ${X.action}`:""}`);const Le={meshId:x,workspace:((Me=X==null?void 0:X.discovery)==null?void 0:Me.repoRoot)||De,repoRoot:(We=X==null?void 0:X.discovery)==null?void 0:We.repoRoot,isLocalWorktree:((Be=X==null?void 0:X.discovery)==null?void 0:Be.isLinkedWorktree)===!0};t.addNodeDaemonPicker&&pe&&(Le.daemonId=pe,Le.machineId=ye==null?void 0:ye.machineId),Le.providerPriority=Dn(ln(((Xe=t.addNodeDaemonPicker?ye:e[0])==null?void 0:Xe.availableProviders)||[]));const _e=await n(be,"add_mesh_node",Le),nt=a(_e);if((nt==null?void 0:nt.success)===!1)throw new Error(nt.error||"Add node failed");V(""),se(null),await h(!0)}catch(at){k((at==null?void 0:at.message)||"Add node failed")}finally{ie(!1)}}},[y,x,me,pe,ye,fe,t.addNodeDaemonPicker,N,e,n,a,h,k]),Z=!A&&!!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(oR,{daemons:e,features:t,meshes:m,meshesLoading:f,selectedMeshId:x,onSelectMesh:be=>{S(be),V(""),te("")},createMode:A,onCreateModeChange:T,createName:L,onCreateNameChange:P,createDaemonId:M,onCreateDaemonIdChange:_,createWorkspace:D,onCreateWorkspaceChange:B,createPickerWorkspaces:Y,createPlan:R,createPlanLoading:H,creating:I,createWarning:F,onCreate:ve,createRepoRemoteUrl:Q,onCreateRepoRemoteUrlChange:ne,createRepoIdentity:oe,onCreateRepoIdentityChange:Ce,createManualOpen:le,onCreateManualOpenChange:U,nodes:j,attachableDaemons:ue,attachDaemonId:pe,onAttachDaemonIdChange:be=>{te(be),V("")},attachWorkspace:me,onAttachWorkspaceChange:V,attachPickerWorkspaces:Ie,attachPlan:q,attachPlanLoading:de,attaching:fe,onAttach:E,renderInstallOnboarding:d,nodeLabel:lR,daemonLabel:iR})}),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:Z?"btn btn-primary btn-sm":"btn btn-secondary btn-sm",onClick:c,children:p(Z?"setupWizard.continueToMesh":"setupWizard.close")})})})]})}function Tc(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function dR(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(dR(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 uR{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 uR;function pR(){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=pR(),ap=3e3,mR=3e4;let gs=null,hR=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 fR(e){return e==="connected"?"connected":e}async function La(e,t,n){const a=mh(e,n||{}),r=gs;if(r&&r.readyState===WebSocket.OPEN){const o=`req_${++hR}_${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=mh(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 gR{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 bR(e){return(!rs||rs.daemonId!==e)&&(rs=new gR(e)),rs}function xR({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:A,markLoaded:T,getIdes:L}=t.current,P=N.instanceId||"standalone",M=L().find(B=>B.id===P),_=bR(P);As.register(P,_),As.setState(P,"connected"),d("connected",P),As.emitStatus(P,N);const D=Wr(N,{daemonId:P,existingDaemon:M,existingEntries:L()});rp("ws_status",{type:j.type,daemonId:P,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:P,entries:D.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}))}),D.length>0&&A(D,{authoritativeDaemonIds:[P]}),T(),i.current!==P&&((y=o.current)==null||y.call(o),i.current=P,o.current=ys.subscribe({sendData:Al},P,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${P}`,params:{includeSessions:!0}},B=>{if(B.topic!=="daemon.metadata")return;const R=t.current.getIdes(),O=R.find($=>$.id===P),H=Wr(B.status,{daemonId:P,existingDaemon:O,existingEntries:R,timestamp:B.timestamp});H.length>0&&t.current.injectEntries(H,{authoritativeDaemonIds:[P]}),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,mR),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 vR({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=fR(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(xR,{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"}],yR=new Set(Lo.map(e=>e.id)),wR=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"?yR:wR).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 kR(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=kR(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 SR(){try{const e=localStorage.getItem(ug);if(e)return Ms(JSON.parse(e))}catch{}return Nn}function CR(){return xn(SR())}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 jR({children:e}){const t=oa(),n=Dl(),{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(Cp,{}),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(i1,{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.51"]}),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 NR(){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(cR,{daemons:a,features:Zf,sendCommand:t,unwrapResult:r=>r,normalizeMesh:r=>r,onClose:()=>e("/mesh")})}const AR=[{icon:s.jsx(sn,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Ps,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(El,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(us,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(Ea,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Cp,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],TR=[{icon:s.jsx(mo,{size:16}),title:"Access from anywhere",desc:"Reach your machines from another laptop or phone without opening local ports."},{icon:s.jsx(kp,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(ia,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(lb,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(Sp,{size:16}),title:"Team workspace",desc:"Share machines, activity views, and policies across a team workspace."},{icon:s.jsx(db,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],MR=[{feature:"Agent chat relay",selfhost:!0,cloud:!0},{feature:"Live IDE screenshots",selfhost:!0,cloud:!0},{feature:"Remote IDE control",selfhost:!0,cloud:!0},{feature:"Multi-IDE monitoring",selfhost:!0,cloud:!0},{feature:"Extension and CLI agents",selfhost:!0,cloud:!0},{feature:"Access from any network",selfhost:!1,cloud:!0},{feature:"WebRTC P2P streaming",selfhost:!1,cloud:!0},{feature:"Mobile push notifications",selfhost:!1,cloud:!0},{feature:"REST API and webhooks",selfhost:!1,cloud:!0},{feature:"Team collaboration",selfhost:!1,cloud:!0},{feature:"Multi-machine dashboards",selfhost:!1,cloud:!0},{feature:"SSO, RBAC, audit logs",selfhost:!1,cloud:!0}];function DR(){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.51"]}),children:[s.jsx(bt,{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(bt,{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:AR.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}),t.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:t.desc})]},t.title))})}),s.jsx(bt,{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:hh.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:gh.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:fh.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(bt,{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:TR.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}),t.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:t.desc})]},t.title))})}),s.jsx(bt,{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:MR.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:t.feature}),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.feature))})]})})}),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(vb,{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(u1,{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 PR({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 IR(){const{t:e}=ke("common"),{ides:t}=Ss(),n=t.find(U=>U.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,A]=l.useState(""),[T,L]=l.useState(""),[P,M]=l.useState(""),[_,D]=l.useState(""),[B,R]=l.useState(!1),O=async()=>{const J=await(await Ts("/auth/session")).json();p(J)},H=async()=>{const J=await(await Ts("/api/v1/standalone/preferences")).json();m(J),v(J.standaloneBindHost);const ee=Ms(J.standaloneFontPreferences);g(ee),xn(ee),Tl(ee)};l.useEffect(()=>{o!==void 0&&c(o)},[o]),l.useEffect(()=>{Promise.all([O(),H()]).catch(U=>{M(U instanceof Error?U.message:String(U))})},[]),l.useEffect(()=>{xn(f)},[f]);const $=U=>{const J=U.target.value.trim();n!=null&&n.id&&J!==o&&r(n.id,"set_user_name",{userName:J}).catch(console.error)},[I,W]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),F=U=>{W(U);try{localStorage.setItem("adhdev_sound",U?"1":"0")}catch{}},z=async()=>{S(""),w(""),h(!0);try{const U=Ms(f),J=await Ts("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:U})}),ee=await J.json();if(!J.ok)throw new Error((ee==null?void 0:ee.error)||"Failed to save standalone font preferences");const Y=Ms(ee.standaloneFontPreferences);m(ee),g(Y),xn(Y),Tl(Y),w(e("standalone.settings.fontsSaved"))}catch(U){S(U instanceof Error?U.message:String(U))}finally{h(!1)}},Q=()=>{const U=Ms(u==null?void 0:u.standaloneFontPreferences);S(""),w(""),g(U),xn(U)},ne=()=>{S(""),w(""),g(Nn),xn(Nn)},oe=async()=>{M(""),D(""),R(!0);try{const U=await Ts("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:C})}),J=await U.json();if(!U.ok)throw new Error((J==null?void 0:J.error)||"Failed to save standalone network preference");m(J),v(J.standaloneBindHost),D(J.standaloneBindHost==="0.0.0.0"?e("standalone.settings.networkSavedAll"):e("standalone.settings.networkSavedLocal"))}catch(U){M(U instanceof Error?U.message:String(U))}finally{R(!1)}},Ce=async()=>{if(M(""),D(""),N.trim().length<4){M(e("standalone.settings.passwordTooShort"));return}if(N!==T){M(e("standalone.settings.passwordMismatch"));return}R(!0);try{const U=await Ts("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,newPassword:N})}),J=await U.json();if(!U.ok)throw new Error((J==null?void 0:J.error)||"Failed to save password");p(J),await H(),j(""),A(""),L(""),D(d!=null&&d.hasPasswordAuth?e("standalone.settings.passwordUpdated"):e("standalone.settings.passwordEnabled")),cg()}catch(U){M(U instanceof Error?U.message:String(U))}finally{R(!1)}},le=async()=>{M(""),D(""),R(!0);try{const U=await Ts("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,clear:!0})}),J=await U.json();if(!U.ok)throw new Error((J==null?void 0:J.error)||"Failed to clear password");p(J),await H(),j(""),A(""),L(""),D(e("standalone.settings.passwordDisabled"))}catch(U){M(U instanceof Error?U.message:String(U))}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(bt,{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.51"]})]}),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(bt,{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:()=>{oe()},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(bt,{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")}),P&&s.jsx(Mt,{variant:"error",children:P}),_&&s.jsx(Mt,{variant:"success",children:_}),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:U=>j(U.target.value)}),s.jsx(xs,{type:"password",placeholder:d!=null&&d.hasPasswordAuth?e("standalone.settings.newPasswordPlaceholder"):e("standalone.settings.newPasswordFirstTimePlaceholder"),value:N,onChange:U=>A(U.target.value)}),s.jsx(xs,{type:"password",className:"md:col-span-2",placeholder:e("standalone.settings.confirmPasswordPlaceholder"),value:T,onChange:U=>L(U.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:()=>{le()},disabled:B,children:e("standalone.settings.disablePassword")})]})]})}),s.jsx(bt,{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(U=>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 ${U.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium text-text-primary",children:U.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:U.type})]},U.type))})}),s.jsx(bt,{title:e("standalone.settings.machineSection"),description:e("standalone.settings.machineDescription"),children:s.jsx(w1,{ides:t,emptyMessage:e("standalone.settings.daemonNotConnected")})}),s.jsx(bt,{title:e("standalone.settings.appearanceSection"),description:e("standalone.settings.appearanceDescription"),children:s.jsx(F1,{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(PR,{value:f,savedValue:Ms(u==null?void 0:u.standaloneFontPreferences),saving:k,error:x,notice:b,onChange:g,onSave:()=>{z()},onResetToSaved:Q,onResetToDefaults:ne})]})})}),s.jsx(bt,{title:e("standalone.settings.notificationsSection"),description:e("standalone.settings.notificationsDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(g1,{}),s.jsx(bn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(xb,{size:15})," ",e("standalone.settings.soundEffectsLabel")]}),description:e("standalone.settings.soundEffectsDescription"),checked:I,onChange:F})]})}),s.jsx(bt,{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(ib,{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:U=>c(U.target.value),onBlur:$,onKeyDown:U=>{U.key==="Enter"&&U.currentTarget.blur()}})]})})})]})}const LR=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],ja="adhdev_onboarding_done",RR=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],ER={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function _R({onDone:e}){const{t}=ke("common"),[n,a]=l.useState([]),[r,o]=l.useState(new Set(LR)),[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 A=await N.text();try{return JSON.parse(A)}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 A=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:!!A.success,error:A.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(vm,{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:RR.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:ER[y.category]??y.category}),s.jsx("div",{className:"grid gap-1.5",children:y.items.map(j=>{var L;const N=r.has(j.type),A=f==null?void 0:f.find(P=>P.type===j.type),T=((L=j.manifest)==null?void 0:L.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}),T&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:T})]}),A&&s.jsx("span",{className:`text-[10px] font-semibold ${A.ok?"text-status-online":"text-status-error"}`,children:A.ok?t("standalone.onboarding.installed"):t("standalone.onboarding.installFailed",{error:A.error??"failed"})})]},j.type)})})]},y.category))})]})})}function HR(){try{return localStorage.getItem(ja)==="1"}catch{return!1}}Qj();P1();k0();CR();const $R=vp({baseUrl:"",getToken:Tc});function FR({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 BR(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let n=!1;if(!HR())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(_R,{onDone:()=>t(!1)}):null}function WR(){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}=Nh(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(Kp,{promptSession:a,isSubmitting:i,error:o,onSubmit:c,onCancel:d})]}):null}function OR(){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:$R,children:s.jsx(FR,{children:s.jsx(vR,{children:s.jsx(ab,{value:e,children:s.jsxs(Db,{sendDaemonCommand:La,children:[s.jsx(WR,{}),s.jsxs(jR,{children:[s.jsx(BR,{}),s.jsxs(Hg,{children:[s.jsx(Bs,{path:"/dashboard",element:s.jsx(vI,{})}),s.jsx(Bs,{path:"/machine",element:s.jsx(op,{})}),s.jsx(Bs,{path:"/machines/:id",element:s.jsx(ML,{})}),s.jsx(Bs,{path:"/machines",element:s.jsx(op,{})}),s.jsx(Bs,{path:"/about",element:s.jsx(DR,{})}),s.jsx(Bs,{path:"/settings",element:s.jsx(IR,{})}),s.jsx(Bs,{path:"/mesh",element:s.jsx(rR,{children:s.jsx(nR,{})})}),s.jsx(Bs,{path:"/setup",element:s.jsx(NR,{})}),s.jsx(Bs,{path:"*",element:s.jsx(Fi,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}HC({connectionManager:As});$g(document.getElementById("root")).render(s.jsx(OR,{}));
121
+ Node removal cleanup policy: ${ge}`))return;const be=e.__sourceDaemonId||n;try{const Me=await o(be,"remove_mesh_node",{meshId:e.id,nodeId:Z}),We=i(Me);if((We==null?void 0:We.success)===!1)throw new Error(We.error||"Remove failed");h===Z&&x(null),await m(),g||await f(t)}catch(Me){k((Me==null?void 0:Me.message)||"Remove node failed")}}async function V(Z){if(!e)return;const we={...jl(e),...Z},ge=e.__sourceDaemonId||n;try{z(!0),k(null);const be=await o(ge,"update_mesh",{meshId:e.id,policy:we}),De=i(be);if((De==null?void 0:De.success)===!1)throw new Error(De.error||"Policy update failed");await m()}catch(be){k((be==null?void 0:be.message)||"Policy update failed")}finally{z(!1)}}const[q,se]=l.useState(null);async function de(Z,we){if(!t)return;const ge=(e==null?void 0:e.__sourceDaemonId)||n;try{se(Z.id),k(null);const be=await o(ge,"update_mesh_node",{meshId:t,nodeId:Z.id,policy:{slots:we}}),De=i(be);if((De==null?void 0:De.success)===!1){k(De.error||"Node slots update failed");return}await m()}catch(be){k((be==null?void 0:be.message)||"Node slots update failed")}finally{se(null)}}const[K,fe]=l.useState(null);async function ie(Z,we){if(!t)return;const ge=(e==null?void 0:e.__sourceDaemonId)||n,be=we.map(De=>De.trim()).filter(Boolean);try{fe(Z.id),k(null);const De=await o(ge,"update_mesh_node",{meshId:t,nodeId:Z.id,capabilities:be}),Me=i(De);if((Me==null?void 0:Me.success)===!1){k(Me.error||"Node tag update failed");return}await m()}catch(De){k((De==null?void 0:De.message)||"Node tag update failed")}finally{fe(null)}}async function ue(){if(!n||!t)return;const we={...(e==null?void 0:e.coordinator)||{}};Q.override.trim()?we.systemPromptOverride=Q.override:delete we.systemPromptOverride,Q.append.trim()?we.systemPromptAppend=Q.append:delete we.systemPromptAppend,delete we.systemPromptSuffix;try{Ce(!0),k(null);const ge=await o(n,"update_mesh",{meshId:t,coordinator:we}),be=i(ge);if((be==null?void 0:be.success)===!1){k(be.error||"Coordinator prompt save failed");return}await m()}catch(ge){k((ge==null?void 0:ge.message)||"Coordinator prompt save failed")}finally{Ce(!1)}}async function ye(Z){if(!n||!t)return;const we=(le[Z.id]||"").trim();try{ee(Z.id),k(null);const ge=await o(n,"update_mesh_node",{meshId:t,nodeId:Z.id,systemPrompt:we}),be=i(ge);if((be==null?void 0:be.success)===!1){k(be.error||"Node instruction save failed");return}await m()}catch(ge){k((ge==null?void 0:ge.message)||"Node instruction save failed")}finally{ee(null)}}async function Ie(Z){if(!(!e||!Z)){k(null),W(null);try{$(!0);const we=(e.nodes||[]).find(De=>Zs(String(De.daemon_id||De.daemonId||""),Z)),ge=await o(Z,"set_mesh_host",{meshId:e.id,hostDaemonId:Z,...we!=null&&we.id?{hostNodeId:we.id}:{}}),be=i(ge);if((be==null?void 0:be.success)===!1){k(be.error||"Setting the mesh host failed");return}await m()}catch(we){k((we==null?void 0:we.message)||"Setting the mesh host failed")}finally{$(!1)}}}async function E(){if(e){k(null),W(null);try{O(!0);const Z=c?await c(a,e.id,e):null,we=d(a,e.id,e,e.nodes||[],Z);if("error"in we)throw new Error(we.error);const ge=await p(we.targetDaemonId,{meshId:e.id,inlineMesh:we.inlineMesh,coordinatorNodeId:we.coordinatorNodeId,cliType:D.trim()||void 0});W(ge.message)}catch(Z){k((Z==null?void 0:Z.message)||"Coordinator launch failed")}finally{O(!1)}}}return{selectedNodeId:h,setSelectedNodeId:x,showAddNode:S,setShowAddNode:b,nodeWorkspace:w,setNodeWorkspace:C,nodeProviderPriority:v,setNodeProviderPriority:y,nodeDaemonId:j,setNodeDaemonId:N,nodeCustomPath:A,setNodeCustomPath:T,nodePickerWorkspaces:ve,nodePickerProviders:pe,nodeOnboardingPlan:L,nodePlanLoading:M,coordinatorCliType:D,setCoordinatorCliType:B,launchingCoordinator:R,launchResult:I,settingMeshHost:H,savingPolicy:F,coordinatorPromptDraft:Q,setCoordinatorPromptDraft:ne,savingCoordinatorPrompt:oe,nodeSystemPromptDrafts:le,setNodeSystemPromptDrafts:U,savingNodeSystemPromptId:J,savingNodeSlotsId:q,savingNodeCapabilitiesId:K,handleAddNode:te,handleRemoveNode:me,handleUpdatePolicy:V,handleUpdateNodeSlots:de,handleUpdateNodeCapabilities:ie,handleSaveCoordinatorPrompt:ue,handleSaveNodeSystemPrompt:ye,handleLaunchCoordinator:E,handleSetMeshHost:Ie}}function U2(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 G2({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(U2(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 q2(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 z2(e,t){!e||!t||ig.set(e,t)}function K2({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(q2(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&&!hM(jf(y))){f("settling"),h.current||(h.current=!0,Promise.resolve().then(()=>x(S,b,!0)).finally(()=>{h.current=!1}));return}i(y),z2(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 V2(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 Y2(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 Q2=4,J2=3e4;function X2(){return{lastFingerprint:null,stableTicks:0,backedOff:!1}}function Nl(e){e.stableTicks=0,e.backedOff=!1}function Z2(e,t){const n=Y2(t);return e.lastFingerprint===null?(e.lastFingerprint=n,e.backedOff):n!==e.lastFingerprint?(e.lastFingerprint=n,Nl(e),!1):(e.stableTicks+=1,e.stableTicks>=Q2&&(e.backedOff=!0),e.backedOff)}function eR(e,t){return e.backedOff?Math.max(t,J2):t}const tR=7e3,sR=45e3;function nR(){const e=PL(),{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:A,showCreate:T,setShowCreate:L,createName:P,setCreateName:M,createRepoIdentity:_,setCreateRepoIdentity:D,createRepoRemoteUrl:B,setCreateRepoRemoteUrl:R,newMeshDaemonId:O,setNewMeshDaemonId:H,newMeshWorkspace:$,setNewMeshWorkspace:I,createPickerWorkspaces:W,createOnboardingPlan:F,createPlanLoading:z,creating:Q,createWarning:ne,setCreateWarning:oe,loadMeshes:Ce,handleCreate:le,handleDelete:U,cancelCreate:J}=og({daemons:a,primaryDaemonId:S,sendCommand:t,unwrapResult:p,normalizeMesh:u,features:g,loadDaemonMetadata:h}),ee=C.find(Fe=>Fe.id===v)||null,{meshGraphStatus:Y,setMeshGraphStatus:ve,graphLoading:pe,graphError:te,setGraphError:me,loadGraph:V}=K2({selectedMeshId:v,loadMeshStatus:o,extractStatus:d,normalizeNode:m,gateIncompleteGraph:k}),[q,se]=l.useState(""),[de,K]=l.useState(""),fe=g.meshHostDaemonSection?q:S,{meshQueue:ie,loadQueue:ue}=G2({primaryDaemonId:S,activeDaemonId:fe,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:f}),{selectedNodeId:ye,setSelectedNodeId:Ie,showAddNode:E,setShowAddNode:Z,nodeWorkspace:we,setNodeWorkspace:ge,nodeProviderPriority:be,setNodeProviderPriority:De,nodeDaemonId:Me,setNodeDaemonId:We,nodeCustomPath:Be,setNodeCustomPath:Xe,nodePickerWorkspaces:at,nodePickerProviders:st,nodeOnboardingPlan:X,nodePlanLoading:Le,coordinatorCliType:_e,savingPolicy:nt,coordinatorPromptDraft:rt,setCoordinatorPromptDraft:G,savingCoordinatorPrompt:re,nodeSystemPromptDrafts:ce,setNodeSystemPromptDrafts:xe,savingNodeSystemPromptId:Se,savingNodeSlotsId:Ae,savingNodeCapabilitiesId:Ee,handleAddNode:Re,handleRemoveNode:Qe,handleUpdatePolicy:et,handleUpdateNodeSlots:Je,handleUpdateNodeCapabilities:Oe,handleSaveCoordinatorPrompt:Ye,handleSaveNodeSystemPrompt:tt,settingMeshHost:$e,handleSetMeshHost:he}=O2({selectedMesh:ee,selectedMeshId:v,primaryDaemonId:S,activeDaemonId:fe,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:A}),je=l.useMemo(()=>a.find(Fe=>Fe.id===fe)||x,[a,fe,x]),Ne=l.useMemo(()=>new Set(((ee==null?void 0:ee.nodes)||[]).map(Fe=>String(Fe.daemon_id||Fe.daemonId||""))),[ee]),He=l.useMemo(()=>a.filter(Fe=>Fe.id&&!Ne.has(Fe.id)&&!Zp(Fe)),[a,Ne]),Ue=(ee==null?void 0:ee.nodes)||[],dt=l.useMemo(()=>Ue.find(Fe=>Zs(String(Fe.daemon_id||Fe.daemonId||""),q)),[Ue,q]),Ke=g.meshHostDaemonSection?!!dt:!0,ut=l.useMemo(()=>{if(!g.meshHostDaemonSection||!ee)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const Fe=ee.meshHost,lt=Y!=null&&Y.meshId&&String(Y.meshId)===String(ee.id??"")?Y.meshHost:void 0,es=lt!=null&&lt.hostDaemonId?lt:Fe??lt,ns=np(es),js=ns.hostDaemonId,Ys=Ue.find(Fs=>Fs.role==="host"),cn=ns.hostNodeId||String((Ys==null?void 0:Ys.id)||""),ae=cn?Ue.find(Fs=>String(Fs.id)===cn):void 0,ze=String((ae==null?void 0:ae.daemon_id)||(ae==null?void 0:ae.daemonId)||""),Ge=js||ze;if(!Ge)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const Nt=a.find(Fs=>js&&Zs(Fs.id,js))||(ze?a.find(Fs=>Zs(Fs.id,ze)):void 0);if(Nt)return{pinned:!0,daemonId:Nt.id,label:aR(Nt),online:!0,hostNode:ae};const dn=String((ae==null?void 0:ae.machineLabel)||"")||String((ae==null?void 0:ae.workspace)||"")||Ge;return{pinned:!0,daemonId:Ge,label:dn,online:!1,hostNode:ae}},[ee,Ue,a,Y,g.meshHostDaemonSection]),zt=ut.daemonId,Et=ut.online,ps=ut.pinned?ut.hostNode:dt,Zt=l.useMemo(()=>!g.meshHostDaemonSection||!ut.pinned?"":!Et&&de&&a.some(Fe=>Fe.id===de)?de:zt,[g.meshHostDaemonSection,ut.pinned,Et,de,a,zt]),_s=l.useMemo(()=>Y?[...new Set((Y.nodes??[]).map(Fe=>String(Fe.daemonId||Fe.daemon_id||"")).filter(Boolean))]:[],[Y]),Pe=Kf({status:Y,daemonId:fe||null,extraDaemonIds:_s,meshId:v,sendData:n});l.useEffect(()=>{const Fe=(ee==null?void 0:ee.coordinator)||{};G({override:typeof Fe.systemPromptOverride=="string"?Fe.systemPromptOverride:"",append:typeof Fe.systemPromptAppend=="string"?Fe.systemPromptAppend:typeof Fe.systemPromptSuffix=="string"?Fe.systemPromptSuffix:""}),xe(Object.fromEntries(((ee==null?void 0:ee.nodes)||[]).map(lt=>[lt.id,typeof lt.systemPrompt=="string"?lt.systemPrompt:""])))},[ee]),l.useEffect(()=>{const Fe=g.addNodeDaemonPicker?Dn(st):Dn(w);E&&be.length===0&&Fe.length>0&&De(Fe)},[E,w,st,be.length,g.addNodeDaemonPicker]),l.useEffect(()=>{const Fe=new Set(((ee==null?void 0:ee.nodes)||[]).map(lt=>lt.id));ye&&!Fe.has(ye)&&Ie(null)},[ee,ye]);const Ze=l.useMemo(()=>{if(!(!(Y!=null&&Y.meshId)||String(Y.meshId)!==String((ee==null?void 0:ee.id)??"")))return np(Y.meshHost).hostDaemonId||void 0},[Y,ee]),It=l.useMemo(()=>V2(a,Ue,fe,S,Ze),[a,Ue,fe,S,Ze]);l.useEffect(()=>{if(!g.meshHostDaemonSection)return;if(!a.length&&!ut.pinned){se("");return}const Fe=ut.pinned?Zt:It;Fe&&!Zs(Fe,q)&&se(Fe)},[a,q,ut.pinned,Zt,It,g.meshHostDaemonSection]),l.useEffect(()=>{de&&(Et||!a.some(Fe=>Fe.id===de))&&K("")},[Et,de,a]),l.useEffect(()=>{if(g.createDaemonPicker){if(!a.length){H("");return}(!O||!a.some(Fe=>Fe.id===O))&&H(a[0].id)}},[a,O,g.createDaemonPicker]),l.useEffect(()=>{var Fe;if(!g.createDaemonPicker||!O){I("");return}if(!W.length){I("");return}W.some(lt=>lt.path===$)||I(((Fe=W[0])==null?void 0:Fe.path)||"")},[O,$,W,g.createDaemonPicker]);const pt=l.useRef(null),Yt=l.useRef(X2()),_t=g.meshStatePushRefresh?sR:tR,[Qt,Cs]=l.useState(_t);l.useEffect(()=>{if(!v)return;const Fe=pt.current!==v;if(pt.current=v,Fe){Nl(Yt.current),Cs(_t);const lt=lg(v);ve(lt),me(null),V(fe,v,lt!==null)}else me(null),V(fe,v,!0)},[v,fe]);const Hs=l.useRef(V);Hs.current=V;const ms=l.useRef(!1),ss=l.useRef(()=>{});ss.current=()=>{ms.current||!v||!fe||(ms.current=!0,Promise.resolve(Hs.current(fe,v,!0)).finally(()=>{ms.current=!1}))},l.useEffect(()=>{Z2(Yt.current,Y),Cs(eR(Yt.current,_t))},[Y,_t]),DL({daemonIds:l.useMemo(()=>[fe,..._s].filter(Boolean),[fe,_s]),meshId:v,sendData:n,onRevisionAdvance:()=>{typeof document<"u"&&document.visibilityState!=="visible"||ss.current()}}),l.useEffect(()=>{if(!v||!fe||typeof document>"u")return;let Fe=null;const lt=()=>{document.visibilityState==="visible"&&ss.current()},es=()=>{Fe===null&&(Fe=setInterval(lt,Qt))},ns=()=>{Fe!==null&&(clearInterval(Fe),Fe=null)},js=()=>{document.visibilityState==="visible"?es():ns()};return document.visibilityState==="visible"&&es(),document.addEventListener("visibilitychange",js),()=>{ns(),document.removeEventListener("visibilitychange",js)}},[v,fe,Qt]),l.useEffect(()=>{g.queueSection||ue(v)},[v,g.queueSection]);const Vs=l.useMemo(()=>a.map(Fe=>Fe.id).filter(Boolean).sort().join(","),[a]),$s=l.useRef(!1);return l.useEffect(()=>{Ce($s.current),$s.current=!0},[Vs]),S?ee?s.jsx(W2,{selectedMesh:ee,error:N,onDismissError:()=>A(null),onBack:()=>{y(null),ve(null)},onDelete:U,displayedMeshStatus:Pe,graphLoading:pe,graphError:te,onRefreshGraph:()=>{Nl(Yt.current),V(fe,v,!0)},savingPolicy:nt,onUpdatePolicy:et,coordinatorPromptDraft:rt,onCoordinatorPromptDraftChange:G,savingCoordinatorPrompt:re,onSaveCoordinatorPrompt:Ye,daemons:a,coordinatorDaemonId:q,onCoordinatorDaemonIdChange:se,coordinatorCliType:_e,isHostNodeAttached:Ke,selectedHostNode:ps,hostPinned:ut.pinned,hostLabel:ut.label,hostOnline:Et,hostRebindDaemonId:de,onHostRebindDaemonIdChange:Fe=>K(Fe),settingMeshHost:$e,onSetMeshHost:he,activeDaemon:je,activeDaemonId:fe,meshQueue:ie,userName:r,availableCliProviders:w,savingNodeSlotsId:Ae,onUpdateNodeSlots:Je,savingNodeCapabilitiesId:Ee,onUpdateNodeCapabilities:Oe,nodeSystemPromptDrafts:ce,onNodeSystemPromptDraftChange:(Fe,lt)=>xe(es=>({...es,[Fe]:lt})),savingNodeSystemPromptId:Se,onSaveNodeSystemPrompt:tt,selectedNodeId:ye,onSelectNode:Ie,showAddNode:E,onShowAddNode:()=>Z(!0),onCancelAddNode:()=>Z(!1),nodeWorkspace:we,onNodeWorkspaceChange:ge,nodeProviderPriority:be,onNodeProviderPriorityChange:De,nodeDaemonId:Me,onNodeDaemonIdChange:We,nodeCustomPath:Be,onNodeCustomPathChange:Xe,nodePickerWorkspaces:at,nodePickerProviders:st,nodeOnboardingPlan:X,nodePlanLoading:Le,attachableDaemons:He,onAddNode:Re,onRemoveNode:Qe,availableCliAgents:b,features:{coordinatorPrompt:g.coordinatorPrompt,meshHostDaemonSection:g.meshHostDaemonSection,hermesMcpConfig:g.hermesMcpConfig,addNodeDaemonPicker:g.addNodeDaemonPicker,nodeInstruction:g.nodeInstruction},sendCommand:t}):s.jsx(FL,{meshes:C,loading:j,error:N,onDismissError:()=>A(null),daemons:a,features:{createDaemonPicker:g.createDaemonPicker,maxMeshes:g.maxMeshes},showCreate:T,onToggleCreate:()=>L(!T),createName:P,onCreateNameChange:M,createRepoIdentity:_,onCreateRepoIdentityChange:D,createRepoRemoteUrl:B,onCreateRepoRemoteUrlChange:R,newMeshDaemonId:O,onNewMeshDaemonIdChange:H,newMeshWorkspace:$,onNewMeshWorkspaceChange:I,createPickerWorkspaces:W,createOnboardingPlan:F,createPlanLoading:z,creating:Q,createWarning:ne,onDismissCreateWarning:()=>oe(null),onSelectMesh:y,onCreate:le,onCancelCreate:J}):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 aR(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function rR({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 oR(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:A,onCreateManualOpenChange:T,nodes:L,attachableDaemons:P,attachDaemonId:M,onAttachDaemonIdChange:_,attachWorkspace:D,onAttachWorkspaceChange:B,attachPickerWorkspaces:R,attachPlan:O,attachPlanLoading:H,attaching:$,onAttach:I,renderInstallOnboarding:W,nodeLabel:F,daemonLabel:z}=e,{t:Q}=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:Q("setupWizard.machines.title")}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-text-muted",children:Q("setupWizard.machines.noMachinesDescription")})]}),W?W():s.jsx("p",{className:"text-[11px] text-text-muted",children:Q("setupWizard.machines.noMachinesFallback")})]});const ne=$||H||(O==null?void 0:O.success)===!1||!D.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:Q("setupWizard.machines.title")}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-text-muted",children:Q("setupWizard.machines.description")})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[a.map(oe=>{const Ce=!c&&o===oe.id;return s.jsx("button",{type:"button",onClick:()=>{d(!1),i(oe.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:oe.name}),s.jsxs("span",{className:"block truncate text-[11px] text-text-muted",children:[oe.repoIdentity||oe.repoRemoteUrl||""," · ",Q("setupWizard.machines.nodeCount",{count:(oe.nodes||[]).length})]})]})},oe.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:["+ ",Q("setupWizard.machines.createNew")]})}),r&&a.length===0&&s.jsx("p",{className:"text-[11px] text-text-muted",children:Q("setupWizard.machines.loadingMeshes")})]}),c&&s.jsx(ng,{variant:"wizard",showDaemonPicker:n.createDaemonPicker,daemons:t,daemonLabel:z,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:A,onManualOpenChange:T,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:[L.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5",children:L.map(oe=>s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] text-text-secondary",children:F(oe)},oe.id))}),s.jsx("span",{className:"text-[11px] font-medium text-text-secondary",children:Q("setupWizard.machines.attachTitle")}),n.addNodeDaemonPicker&&(P.length>0?s.jsx("div",{className:"flex flex-wrap gap-1.5",children:P.map(oe=>{const Ce=M===oe.id;return s.jsx("button",{type:"button",onClick:()=>_(oe.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:z(oe)},oe.id)})}):s.jsx("p",{className:"text-[11px] text-text-muted",children:Q("setupWizard.machines.allMachinesAttached")})),(!n.addNodeDaemonPicker||M)&&s.jsxs(s.Fragment,{children:[s.jsx(yl,{workspaces:R,value:D,onChange:B}),s.jsx(sg,{plan:O,loading:H}),s.jsx("div",{className:"flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:I,disabled:ne,children:Q($?"setupWizard.machines.attaching":"setupWizard.machines.addMachine")})})]})]})]})}function iR(e){var t;return e.machineNickname||e.nickname||e.hostname||((t=e.user)==null?void 0:t.name)||e.id}function lR(e){const t=e;return t.machine_label||t.machineLabel||t.hostname||String(e.workspace||"").split(/[\\/]/).filter(Boolean).pop()||e.id}function cR({daemons:e,features:t,sendCommand:n,unwrapResult:a,normalizeMesh:r,loadDaemonMetadata:o,initialMeshId:i,onClose:c,renderInstallOnboarding:d}){var we,ge;const{t:p}=ke("common"),u=((we=e[0])==null?void 0:we.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(be=>be.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(be=>be.id===i)?S(i):m.length===1&&S(m[0].id))},[m,x,i,S]);const y=l.useMemo(()=>m.find(be=>be.id===x)??null,[m,x]),j=l.useMemo(()=>(y==null?void 0:y.nodes)||[],[y]),N=l.useCallback(be=>(be==null?void 0:be.__sourceDaemonId)||u,[u]),[A,T]=l.useState(!1),[L,P]=l.useState(""),[M,_]=l.useState(""),[D,B]=l.useState(""),[R,O]=l.useState(null),[H,$]=l.useState(!1),[I,W]=l.useState(!1),[F,z]=l.useState(null),[Q,ne]=l.useState(""),[oe,Ce]=l.useState(""),[le,U]=l.useState(!1),J=t.createDaemonPicker&&M||u,ee=l.useMemo(()=>e.find(be=>be.id===J),[e,J]),Y=(ee==null?void 0:ee.workspaces)||[];l.useEffect(()=>{if(!A||!J||!D.trim()){O(null),$(!1);return}let be=!1;const De=setTimeout(()=>{be||($(!0),C.current(J,"plan_mesh_onboarding",{workspace:D.trim(),operation:"auto",meshInventory:b.current}).then(Me=>{if(be)return;const We=v.current(Me);O(We),We!=null&&We.success&&(P(Be=>{var Xe,at;return Be||`${String(((Xe=We.discovery)==null?void 0:Xe.repoIdentity)||((at=We.discovery)==null?void 0:at.repoRoot)||"").split(/[\\/]/).filter(Boolean).pop()||"repo"}-mesh`}),Ce(Be=>{var Xe;return Be||((Xe=We.discovery)==null?void 0:Xe.repoIdentity)||""}),ne(Be=>{var Xe,at,st,X,Le,_e;return Be||((st=(at=(Xe=We.discovery)==null?void 0:Xe.origin)==null?void 0:at.urls)==null?void 0:st[0])||((_e=(Le=(X=We.discovery)==null?void 0:X.upstream)==null?void 0:Le.urls)==null?void 0:_e[0])||""}))}).catch(Me=>{be||O({success:!1,error:(Me==null?void 0:Me.message)||"Git discovery failed"})}).finally(()=>{be||$(!1)}))},300);return()=>{be=!0,clearTimeout(De)}},[A,J,D,w]);const ve=l.useCallback(async()=>{const be=J,De=D.trim(),Me=Q.trim(),We=oe.trim();if(!(!be||!L.trim()||I)&&!(!De&&!Me&&!We)){W(!0),z(null),k(null);try{const Be=await rg({targetDaemonId:be,name:L,repoRemoteUrl:Me,repoIdentity:We,workspace:De,attachWorkspace:!!De,machineId:ee==null?void 0:ee.machineId,providerPriority:Dn(ln((ee==null?void 0:ee.availableProviders)||[])),meshInventory:m,sendCommand:n,unwrapResult:a});if(Be.warning&&z(Be.warning),!Be.meshCreated){k(Be.error||p("setupWizard.machines.createFailed"));return}await h(!0),Be.meshId&&S(Be.meshId),T(!1)}finally{W(!1)}}},[J,L,D,Q,oe,I,ee,m,n,a,h,S,k,p]),[pe,te]=l.useState(""),[me,V]=l.useState(""),[q,se]=l.useState(null),[de,K]=l.useState(!1),[fe,ie]=l.useState(!1),ue=l.useMemo(()=>{if(!t.addNodeDaemonPicker)return[];const be=new Set(j.map(De=>String(De.daemon_id||De.daemonId||"")));return e.filter(De=>De.id&&!be.has(De.id)&&!Zp(De))},[t.addNodeDaemonPicker,j,e]),ye=l.useMemo(()=>e.find(be=>be.id===pe),[e,pe]),Ie=t.addNodeDaemonPicker?(ye==null?void 0:ye.workspaces)||[]:((ge=e.find(be=>be.id===u))==null?void 0:ge.workspaces)||[];l.useEffect(()=>{if(A||!x||!me.trim()){se(null);return}const be=t.addNodeDaemonPicker?pe:N(y);if(!be)return;let De=!1;return K(!0),n(be,"plan_mesh_onboarding",{workspace:me.trim(),meshId:x,inlineMesh:y,operation:"add_existing"}).then(Me=>{De||se(a(Me))}).catch(Me=>{De||se({success:!1,error:(Me==null?void 0:Me.message)||"Git discovery failed"})}).finally(()=>{De||K(!1)}),()=>{De=!0}},[A,x,y,me,pe,t.addNodeDaemonPicker,N,n,a]);const E=l.useCallback(async()=>{var Me,We,Be,Xe;const be=N(y);if(!x||!be||fe)return;const De=me.trim();if(De){ie(!0),k(null);try{const at=t.addNodeDaemonPicker?pe:be,st=await n(at,"plan_mesh_onboarding",{workspace:De,meshId:x,inlineMesh:y,operation:"add_existing"}),X=a(st);if(se(X),(X==null?void 0:X.success)===!1)throw new Error(`${X.code||"onboarding_blocked"}: ${X.error}${X.action?` ${X.action}`:""}`);const Le={meshId:x,workspace:((Me=X==null?void 0:X.discovery)==null?void 0:Me.repoRoot)||De,repoRoot:(We=X==null?void 0:X.discovery)==null?void 0:We.repoRoot,isLocalWorktree:((Be=X==null?void 0:X.discovery)==null?void 0:Be.isLinkedWorktree)===!0};t.addNodeDaemonPicker&&pe&&(Le.daemonId=pe,Le.machineId=ye==null?void 0:ye.machineId),Le.providerPriority=Dn(ln(((Xe=t.addNodeDaemonPicker?ye:e[0])==null?void 0:Xe.availableProviders)||[]));const _e=await n(be,"add_mesh_node",Le),nt=a(_e);if((nt==null?void 0:nt.success)===!1)throw new Error(nt.error||"Add node failed");V(""),se(null),await h(!0)}catch(at){k((at==null?void 0:at.message)||"Add node failed")}finally{ie(!1)}}},[y,x,me,pe,ye,fe,t.addNodeDaemonPicker,N,e,n,a,h,k]),Z=!A&&!!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(oR,{daemons:e,features:t,meshes:m,meshesLoading:f,selectedMeshId:x,onSelectMesh:be=>{S(be),V(""),te("")},createMode:A,onCreateModeChange:T,createName:L,onCreateNameChange:P,createDaemonId:M,onCreateDaemonIdChange:_,createWorkspace:D,onCreateWorkspaceChange:B,createPickerWorkspaces:Y,createPlan:R,createPlanLoading:H,creating:I,createWarning:F,onCreate:ve,createRepoRemoteUrl:Q,onCreateRepoRemoteUrlChange:ne,createRepoIdentity:oe,onCreateRepoIdentityChange:Ce,createManualOpen:le,onCreateManualOpenChange:U,nodes:j,attachableDaemons:ue,attachDaemonId:pe,onAttachDaemonIdChange:be=>{te(be),V("")},attachWorkspace:me,onAttachWorkspaceChange:V,attachPickerWorkspaces:Ie,attachPlan:q,attachPlanLoading:de,attaching:fe,onAttach:E,renderInstallOnboarding:d,nodeLabel:lR,daemonLabel:iR})}),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:Z?"btn btn-primary btn-sm":"btn btn-secondary btn-sm",onClick:c,children:p(Z?"setupWizard.continueToMesh":"setupWizard.close")})})})]})}function Tc(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function dR(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(dR(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 uR{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 uR;function pR(){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=pR(),ap=3e3,mR=3e4;let gs=null,hR=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 fR(e){return e==="connected"?"connected":e}async function La(e,t,n){const a=mh(e,n||{}),r=gs;if(r&&r.readyState===WebSocket.OPEN){const o=`req_${++hR}_${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=mh(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 gR{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 bR(e){return(!rs||rs.daemonId!==e)&&(rs=new gR(e)),rs}function xR({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:A,markLoaded:T,getIdes:L}=t.current,P=N.instanceId||"standalone",M=L().find(B=>B.id===P),_=bR(P);As.register(P,_),As.setState(P,"connected"),d("connected",P),As.emitStatus(P,N);const D=Wr(N,{daemonId:P,existingDaemon:M,existingEntries:L()});rp("ws_status",{type:j.type,daemonId:P,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:P,entries:D.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}))}),D.length>0&&A(D,{authoritativeDaemonIds:[P]}),T(),i.current!==P&&((y=o.current)==null||y.call(o),i.current=P,o.current=ys.subscribe({sendData:Al},P,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${P}`,params:{includeSessions:!0}},B=>{if(B.topic!=="daemon.metadata")return;const R=t.current.getIdes(),O=R.find($=>$.id===P),H=Wr(B.status,{daemonId:P,existingDaemon:O,existingEntries:R,timestamp:B.timestamp});H.length>0&&t.current.injectEntries(H,{authoritativeDaemonIds:[P]}),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,mR),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 vR({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=fR(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(xR,{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"}],yR=new Set(Lo.map(e=>e.id)),wR=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"?yR:wR).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 kR(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=kR(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 SR(){try{const e=localStorage.getItem(ug);if(e)return Ms(JSON.parse(e))}catch{}return Nn}function CR(){return xn(SR())}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 jR({children:e}){const t=oa(),n=Dl(),{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(Cp,{}),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(i1,{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.52"]}),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 NR(){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(cR,{daemons:a,features:Zf,sendCommand:t,unwrapResult:r=>r,normalizeMesh:r=>r,onClose:()=>e("/mesh")})}const AR=[{icon:s.jsx(sn,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Ps,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(El,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(us,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(Ea,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Cp,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],TR=[{icon:s.jsx(mo,{size:16}),title:"Access from anywhere",desc:"Reach your machines from another laptop or phone without opening local ports."},{icon:s.jsx(kp,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(ia,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(lb,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(Sp,{size:16}),title:"Team workspace",desc:"Share machines, activity views, and policies across a team workspace."},{icon:s.jsx(db,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],MR=[{feature:"Agent chat relay",selfhost:!0,cloud:!0},{feature:"Live IDE screenshots",selfhost:!0,cloud:!0},{feature:"Remote IDE control",selfhost:!0,cloud:!0},{feature:"Multi-IDE monitoring",selfhost:!0,cloud:!0},{feature:"Extension and CLI agents",selfhost:!0,cloud:!0},{feature:"Access from any network",selfhost:!1,cloud:!0},{feature:"WebRTC P2P streaming",selfhost:!1,cloud:!0},{feature:"Mobile push notifications",selfhost:!1,cloud:!0},{feature:"REST API and webhooks",selfhost:!1,cloud:!0},{feature:"Team collaboration",selfhost:!1,cloud:!0},{feature:"Multi-machine dashboards",selfhost:!1,cloud:!0},{feature:"SSO, RBAC, audit logs",selfhost:!1,cloud:!0}];function DR(){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.52"]}),children:[s.jsx(bt,{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(bt,{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:AR.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}),t.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:t.desc})]},t.title))})}),s.jsx(bt,{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:hh.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:gh.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:fh.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(bt,{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:TR.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}),t.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:t.desc})]},t.title))})}),s.jsx(bt,{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:MR.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:t.feature}),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.feature))})]})})}),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(vb,{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(u1,{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 PR({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 IR(){const{t:e}=ke("common"),{ides:t}=Ss(),n=t.find(U=>U.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,A]=l.useState(""),[T,L]=l.useState(""),[P,M]=l.useState(""),[_,D]=l.useState(""),[B,R]=l.useState(!1),O=async()=>{const J=await(await Ts("/auth/session")).json();p(J)},H=async()=>{const J=await(await Ts("/api/v1/standalone/preferences")).json();m(J),v(J.standaloneBindHost);const ee=Ms(J.standaloneFontPreferences);g(ee),xn(ee),Tl(ee)};l.useEffect(()=>{o!==void 0&&c(o)},[o]),l.useEffect(()=>{Promise.all([O(),H()]).catch(U=>{M(U instanceof Error?U.message:String(U))})},[]),l.useEffect(()=>{xn(f)},[f]);const $=U=>{const J=U.target.value.trim();n!=null&&n.id&&J!==o&&r(n.id,"set_user_name",{userName:J}).catch(console.error)},[I,W]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),F=U=>{W(U);try{localStorage.setItem("adhdev_sound",U?"1":"0")}catch{}},z=async()=>{S(""),w(""),h(!0);try{const U=Ms(f),J=await Ts("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:U})}),ee=await J.json();if(!J.ok)throw new Error((ee==null?void 0:ee.error)||"Failed to save standalone font preferences");const Y=Ms(ee.standaloneFontPreferences);m(ee),g(Y),xn(Y),Tl(Y),w(e("standalone.settings.fontsSaved"))}catch(U){S(U instanceof Error?U.message:String(U))}finally{h(!1)}},Q=()=>{const U=Ms(u==null?void 0:u.standaloneFontPreferences);S(""),w(""),g(U),xn(U)},ne=()=>{S(""),w(""),g(Nn),xn(Nn)},oe=async()=>{M(""),D(""),R(!0);try{const U=await Ts("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:C})}),J=await U.json();if(!U.ok)throw new Error((J==null?void 0:J.error)||"Failed to save standalone network preference");m(J),v(J.standaloneBindHost),D(J.standaloneBindHost==="0.0.0.0"?e("standalone.settings.networkSavedAll"):e("standalone.settings.networkSavedLocal"))}catch(U){M(U instanceof Error?U.message:String(U))}finally{R(!1)}},Ce=async()=>{if(M(""),D(""),N.trim().length<4){M(e("standalone.settings.passwordTooShort"));return}if(N!==T){M(e("standalone.settings.passwordMismatch"));return}R(!0);try{const U=await Ts("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,newPassword:N})}),J=await U.json();if(!U.ok)throw new Error((J==null?void 0:J.error)||"Failed to save password");p(J),await H(),j(""),A(""),L(""),D(d!=null&&d.hasPasswordAuth?e("standalone.settings.passwordUpdated"):e("standalone.settings.passwordEnabled")),cg()}catch(U){M(U instanceof Error?U.message:String(U))}finally{R(!1)}},le=async()=>{M(""),D(""),R(!0);try{const U=await Ts("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,clear:!0})}),J=await U.json();if(!U.ok)throw new Error((J==null?void 0:J.error)||"Failed to clear password");p(J),await H(),j(""),A(""),L(""),D(e("standalone.settings.passwordDisabled"))}catch(U){M(U instanceof Error?U.message:String(U))}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(bt,{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.52"]})]}),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(bt,{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:()=>{oe()},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(bt,{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")}),P&&s.jsx(Mt,{variant:"error",children:P}),_&&s.jsx(Mt,{variant:"success",children:_}),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:U=>j(U.target.value)}),s.jsx(xs,{type:"password",placeholder:d!=null&&d.hasPasswordAuth?e("standalone.settings.newPasswordPlaceholder"):e("standalone.settings.newPasswordFirstTimePlaceholder"),value:N,onChange:U=>A(U.target.value)}),s.jsx(xs,{type:"password",className:"md:col-span-2",placeholder:e("standalone.settings.confirmPasswordPlaceholder"),value:T,onChange:U=>L(U.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:()=>{le()},disabled:B,children:e("standalone.settings.disablePassword")})]})]})}),s.jsx(bt,{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(U=>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 ${U.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium text-text-primary",children:U.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:U.type})]},U.type))})}),s.jsx(bt,{title:e("standalone.settings.machineSection"),description:e("standalone.settings.machineDescription"),children:s.jsx(w1,{ides:t,emptyMessage:e("standalone.settings.daemonNotConnected")})}),s.jsx(bt,{title:e("standalone.settings.appearanceSection"),description:e("standalone.settings.appearanceDescription"),children:s.jsx(F1,{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(PR,{value:f,savedValue:Ms(u==null?void 0:u.standaloneFontPreferences),saving:k,error:x,notice:b,onChange:g,onSave:()=>{z()},onResetToSaved:Q,onResetToDefaults:ne})]})})}),s.jsx(bt,{title:e("standalone.settings.notificationsSection"),description:e("standalone.settings.notificationsDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(g1,{}),s.jsx(bn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(xb,{size:15})," ",e("standalone.settings.soundEffectsLabel")]}),description:e("standalone.settings.soundEffectsDescription"),checked:I,onChange:F})]})}),s.jsx(bt,{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(ib,{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:U=>c(U.target.value),onBlur:$,onKeyDown:U=>{U.key==="Enter"&&U.currentTarget.blur()}})]})})})]})}const LR=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],ja="adhdev_onboarding_done",RR=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],ER={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function _R({onDone:e}){const{t}=ke("common"),[n,a]=l.useState([]),[r,o]=l.useState(new Set(LR)),[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 A=await N.text();try{return JSON.parse(A)}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 A=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:!!A.success,error:A.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(vm,{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:RR.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:ER[y.category]??y.category}),s.jsx("div",{className:"grid gap-1.5",children:y.items.map(j=>{var L;const N=r.has(j.type),A=f==null?void 0:f.find(P=>P.type===j.type),T=((L=j.manifest)==null?void 0:L.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}),T&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:T})]}),A&&s.jsx("span",{className:`text-[10px] font-semibold ${A.ok?"text-status-online":"text-status-error"}`,children:A.ok?t("standalone.onboarding.installed"):t("standalone.onboarding.installFailed",{error:A.error??"failed"})})]},j.type)})})]},y.category))})]})})}function HR(){try{return localStorage.getItem(ja)==="1"}catch{return!1}}Qj();P1();k0();CR();const $R=vp({baseUrl:"",getToken:Tc});function FR({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 BR(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let n=!1;if(!HR())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(_R,{onDone:()=>t(!1)}):null}function WR(){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}=Nh(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(Kp,{promptSession:a,isSubmitting:i,error:o,onSubmit:c,onCancel:d})]}):null}function OR(){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:$R,children:s.jsx(FR,{children:s.jsx(vR,{children:s.jsx(ab,{value:e,children:s.jsxs(Db,{sendDaemonCommand:La,children:[s.jsx(WR,{}),s.jsxs(jR,{children:[s.jsx(BR,{}),s.jsxs(Hg,{children:[s.jsx(Bs,{path:"/dashboard",element:s.jsx(vI,{})}),s.jsx(Bs,{path:"/machine",element:s.jsx(op,{})}),s.jsx(Bs,{path:"/machines/:id",element:s.jsx(ML,{})}),s.jsx(Bs,{path:"/machines",element:s.jsx(op,{})}),s.jsx(Bs,{path:"/about",element:s.jsx(DR,{})}),s.jsx(Bs,{path:"/settings",element:s.jsx(IR,{})}),s.jsx(Bs,{path:"/mesh",element:s.jsx(rR,{children:s.jsx(nR,{})})}),s.jsx(Bs,{path:"/setup",element:s.jsx(NR,{})}),s.jsx(Bs,{path:"*",element:s.jsx(Fi,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}HC({connectionManager:As});$g(document.getElementById("root")).render(s.jsx(OR,{}));