@adhdev/daemon-standalone 1.0.47 → 1.0.48
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=((be=me[0])==null?void 0:be.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:()=>O(Y),children:[s.jsx("span",{className:"text-[10px] text-text-muted w-3",children:te?"▾":"▸"}),s.jsx("span",{className:"font-mono text-accent-primary w-20 shrink-0 text-[11px]",children:Y}),!te&&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:[me.length,"L"]})]}),te&&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:G||"(empty)"})]},Y)})})]}),s.jsx(er,{}),z.nativeSource&&s.jsxs("div",{children:[s.jsxs(Pn,{children:["Status History",z.statusHistory&&z.statusHistory.length>0?` (${z.statusHistory.length})`:""]}),z.statusHistory&&z.statusHistory.length>0?s.jsx("div",{className:"space-y-px",children:[...z.statusHistory].reverse().slice(0,20).map((Y,G)=>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 ${Za(Y.status)}`,children:Y.status}),s.jsx("span",{className:"text-text-secondary text-[11px] shrink-0 tabular-nums",children:Mn(Y.at)}),Y.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:Y.trigger})]})},G))}):s.jsx("div",{className:"text-text-muted text-[11px] italic px-1",children:"N/A (native-source provider — no state-machine rules)"})]}),!z.nativeSource&&z.stateHistory&&z.stateHistory.length>0&&s.jsxs("div",{children:[s.jsxs(Pn,{children:["State History (",z.stateHistory.length,")"]}),s.jsx("div",{className:"space-y-px",children:[...z.stateHistory].reverse().slice(0,20).map((Y,G)=>s.jsxs("div",{className:"rounded px-2 py-1 hover:bg-bg-glass-hover transition-colors",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:`font-mono text-[11px] font-semibold px-1.5 py-0.5 rounded shrink-0 ${Za(Y.stateId)}`,children:Y.stateId}),s.jsx("span",{className:"text-text-secondary text-[11px] shrink-0 tabular-nums",children:Mn(Y.at)}),Y.durationMs>0&&s.jsxs("span",{className:"text-text-muted text-[11px]",children:["held ",s.jsx("span",{className:"text-text-secondary",children:ld(Y.durationMs)})]}),Y.reason&&s.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-mono shrink-0 ${cC[String(Y.reason)]??"text-text-secondary bg-bg-glass border border-border-default"}`,children:String(Y.reason)}),Y.debounceKind&&String(Y.debounceKind)!=="none"&&s.jsxs("span",{className:"text-text-muted text-[10px] font-mono",children:["debounce:",String(Y.debounceKind)]}),Y.matchedStateId&&String(Y.matchedStateId)!==Y.stateId&&s.jsxs("span",{className:"text-text-muted text-[10px] font-mono",children:["eval→",s.jsx("span",{className:"text-text-secondary",children:String(Y.matchedStateId)})]})]}),Y.matchedRules&&Y.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:[Y.matchedRules.slice(0,3).map((te,me)=>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 te=="string"?te:JSON.stringify(te)},me)),Y.matchedRules.length>3&&s.jsxs("span",{className:"text-[10px] text-text-muted",children:["+",Y.matchedRules.length-3," more"]})]})]},G))})]}),s.jsx(er,{}),(()=>{const Y=z.messages??z.committedMessages??[];if(Y.length===0)return null;const G=Y.filter(K=>K.role==="user").length,te=Y.filter(K=>K.role==="assistant").length,me=[...Y].reverse().find(K=>K.role==="assistant");return s.jsxs("div",{children:[s.jsxs(Pn,{children:["Transcript (",Y.length," — ",G,"u / ",te,"a)"]}),me&&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 ",me.receivedAt?Mn(me.receivedAt):""]}),s.jsxs("div",{className:"text-text-secondary font-mono whitespace-pre-wrap line-clamp-4 break-all",children:[me.content.slice(0,400),me.content.length>400?"…":""]})]})]})})(),z.specPath&&s.jsx("div",{className:"text-[10px] text-text-muted font-mono truncate border-t border-border-default pt-2 mt-1",title:z.specPath,children:z.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:()=>d(Y=>!Y),children:[s.jsx("span",{className:"text-text-muted",children:p?"▾":"▸"}),s.jsxs("span",{children:["Raw screen (",z.screen?z.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:z.screen||"(empty)"})]})]})]})]})})})}function mC({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:u}=Ce("common");ys();const{sendPtyInput:p}=vt(),[d,m]=l.useState(!1),h=l.useRef(!1);h.current=d;const[g,k]=l.useState("Runtime terminal unavailable"),[f,x]=l.useState(!1),[w,b]=l.useState(null),[N,j]=l.useState(!1),[v,y]=l.useState(!1),[C,S]=l.useState(1),[A,M]=l.useState(!1),[I,D]=l.useState(!1),[P,T]=l.useState(!1),[H,L]=l.useState(!1),[R,U]=l.useState(!1),[E,$]=l.useState({width:0,height:0}),[_,q]=l.useState({width:0,height:0}),[B,W]=l.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[V,ne]=l.useState(null),ae=l.useRef(null),he=l.useRef(null),Z=l.useRef(!1),z=l.useRef(!1),X=l.useRef(i),O=l.useRef(0),Q=l.useRef(!1),ke=l.useRef(""),Se=l.useRef(null),ve=l.useRef(!1),xe=l.useRef(!1),Y=l.useRef(null),G=l.useRef(null),te=l.useRef(null),me=32*1024,K=()=>{var fe,je,Ne,He;return((je=(fe=ae.current)==null?void 0:fe.ownerDocument)==null?void 0:je.defaultView)||((He=(Ne=he.current)==null?void 0:Ne.ownerDocument)==null?void 0:He.defaultView)||window},be=fe=>{const je=K();return{ownerWindow:je,frameId:je.requestAnimationFrame(fe)}},re=()=>{const fe=Y.current;if(fe){try{fe.ownerWindow.cancelAnimationFrame(fe.frameId)}catch{}Y.current=null}},de=()=>{const fe=G.current;if(fe){try{fe.ownerWindow.clearTimeout(fe.timeoutId)}catch{}G.current=null}},we=()=>{const fe=te.current;if(fe){try{fe.ownerWindow.clearTimeout(fe.timeoutId)}catch{}te.current=null}},Re=()=>{i&&Y.current===null&&(Y.current=be(()=>{oe()}))},F=e.tabKey,J=e.sessionId||"",ge=e.daemonId||(($e=e.routeId)==null?void 0:$e.split(":")[0])||e.routeId||"",ue=Il(e),ee=d?ue?Gp:o:g,De=d&&o||null,Le=qS,Xe=GS,ce=.05,Ee=()=>{const fe=_.width,je=_.height;if(!Number.isFinite(E.width)||E.width<=0||!Number.isFinite(E.height)||E.height<=0||!Number.isFinite(fe)||fe<=0||!Number.isFinite(je)||je<=0)return 1;const Ne=E.width/fe,He=E.height/je;return Number(Math.min(Xe,Math.max(Le,Math.min(Ne,He))).toFixed(2))},Fe=Ee(),et=Z.current&&C>Fe,Ae=Number.isFinite(_.width)&&_.width>0?Math.max(E.width,Math.round(_.width*C)):E.width,Je=Number.isFinite(_.height)&&_.height>0?Math.max(E.height,Math.round(_.height*C)):E.height,bt=()=>{be(()=>{const fe=he.current;fe&&(fe.scrollLeft=0,fe.scrollTop=fe.scrollHeight-fe.clientHeight)})},it=()=>{var fe,je;O.current=0,Q.current=!1,ke.current="",Se.current=null,ve.current=!1,xe.current=!1,Z.current||(z.current=!1,S(1)),Y.current!==null&&re(),m(!1),k("Runtime terminal unavailable"),we(),de(),b(null),ne(null),M(!1),x(!1),j(!1),y(!1),(je=(fe=n.current)==null?void 0:fe.reset)==null||je.call(fe)},yt=()=>{var fe,je;O.current=0,Q.current=!1,ke.current="",Se.current=null,ve.current=!1,xe.current=!1,Y.current!==null&&re(),m(!0),k(""),we(),de(),b(null),ne(null),M(!1),x(!1),j(!1),y(!1),(je=(fe=n.current)==null?void 0:fe.reset)==null||je.call(fe)},se=()=>{xe.current&&(xe.current=!1,be(()=>{var fe,je;(je=(fe=n.current)==null?void 0:fe.scrollToTop)==null||je.call(fe)}))},oe=()=>{if(Y.current=null,!i)return;const fe=ke.current;if(!fe)return;const je=fe.slice(0,me);ke.current=fe.slice(je.length);const Ne=n.current;if(!Ne){ke.current=je+ke.current,Re();return}Ne.write(je,()=>{if(ke.current.length>0){Re();return}se()})},pe=fe=>{fe&&(ke.current+=fe,Re())},ye=(fe,je=0,Ne,He,Qe={})=>{var Ke,St,Mt,zt;const lt=!!Qe.force;!lt&&je>0&&O.current>=je||!lt&&je===0&&Q.current||(O.current=je,je>0&&j(!0),m(!0),k(""),typeof Ne=="number"&&typeof He=="number"&&Ne>0&&He>0&&((St=(Ke=n.current)==null?void 0:Ke.resize)==null||St.call(Ke,Ne,He)),ke.current="",(zt=(Mt=n.current)==null?void 0:Mt.reset)==null||zt.call(Mt),fe?pe(fe):se())};l.useEffect(()=>{it()},[J]),l.useEffect(()=>{var je;if(!J)return;const fe=((je=jt.onRuntimeEvent)==null?void 0:je.call(jt,J,Ne=>{if(!(!Ne||Ne.sessionId!==J)){if(Ne.type==="runtime_snapshot"){if(!i){Se.current={text:Ne.text||"",seq:Ne.seq||0,cols:Ne.cols,rows:Ne.rows,force:!!Ne.force};return}ye(Ne.text||"",Ne.seq||0,Ne.cols,Ne.rows,{force:!!Ne.force});return}if(Ne.type==="session_output"){Q.current=!0,typeof Ne.seq=="number"&&(O.current=Math.max(O.current,Ne.seq),Ne.seq>0&&j(!0)),h.current||m(!0),h.current||k(""),typeof Ne.data=="string"&&pe(Ne.data);return}if(Ne.type==="session_cleared"){if(!i){ve.current=!0,ke.current="",Se.current=null;return}yt();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}}},ge))||(()=>{});return()=>{fe()}},[ge,J,n,i]);const le=async(fe={})=>{var je;if(!ge||!J)return{success:!1,error:"daemonId and sessionId are required"};fe.preserveStatus||k(fe.loadingMessage||"Loading runtime terminal...");try{const Ne=await((je=jt.requestRuntimeSnapshot)==null?void 0:je.call(jt,ge,J,{sinceSeq:fe.sinceSeq,force:fe.force}));return Ne&&Ne.success===!1?(fe.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 fe.preserveStatus||(m(!1),k(`Runtime terminal unavailable: ${He}`)),{success:!1,error:He}}},Me=async fe=>{var lt,Ke;const je=((lt=ae.current)==null?void 0:lt.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(fe),!0}catch{}let Qe=null;try{return Qe=je.createElement("textarea"),Qe.value=fe,Qe.setAttribute("readonly","true"),Qe.style.position="fixed",Qe.style.left="-9999px",Qe.style.top="0",je.body.appendChild(Qe),Qe.focus(),Qe.select(),je.execCommand("copy")}catch{return!1}finally{Qe==null||Qe.remove()}},_e=fe=>{de(),ne(fe);const je=K();G.current={ownerWindow:je,timeoutId:je.setTimeout(()=>{G.current=null,ne(Ne=>Ne===fe?null:Ne)},2200)}},Te=fe=>{we(),b(fe);const je=K();te.current={ownerWindow:je,timeoutId:je.setTimeout(()=>{te.current=null,b(Ne=>Ne===fe?null:Ne)},2200)}},Ue=async()=>{var Qe,lt,Ke,St;const fe=((lt=(Qe=n.current)==null?void 0:Qe.getSelection)==null?void 0:lt.call(Qe))||"",je=((St=(Ke=n.current)==null?void 0:Ke.getVisibleText)==null?void 0:St.call(Ke))||"",Ne=fe.trimEnd()||je.trimEnd();if(!Ne){_e("Nothing to copy");return}if(!await Me(Ne)){_e("Copy failed");return}_e(fe.trimEnd()?"Copied selection":"Copied visible terminal")},Ge=fe=>{if(!d||!i)return;((p==null?void 0:p(ge,J,fe))??!1)||_e("Terminal input failed")},Ye=fe=>{Ge(KS({ctrl:I,alt:P,shift:H},fe)),D(!1),T(!1),L(!1)},Be=async()=>{if(f)return;x(!0),b("Loading older terminal output..."),xe.current=!0;const fe=await le({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:d});if(x(!1),(fe==null?void 0:fe.success)===!1){xe.current=!1,b(`Older terminal output unavailable: ${fe.error}`);return}y(!0),Te("Older terminal output loaded"),be(()=>{var je;(je=n.current)==null||je.bumpResize()})};l.useEffect(()=>{var je,Ne;if(!J)return;ge&&((je=jt.getState)==null?void 0:je.call(jt,ge))==="connected"&&le();const fe=(Ne=jt.onStateChange)==null?void 0:Ne.call(jt,(He,Qe)=>{He!==ge||Qe!=="connected"||le()});return()=>{fe==null||fe()}},[ge,J,n]),l.useEffect(()=>{t&&it()},[t,F,n]),l.useEffect(()=>{var He,Qe;const fe=ae.current,je=(Qe=(He=fe==null?void 0:fe.ownerDocument)==null?void 0:He.defaultView)==null?void 0:Qe.ResizeObserver;if(!fe||!je)return;const Ne=new je(lt=>{const Ke=lt[0];if(!Ke)return;const{width:St,height:Mt}=Ke.contentRect;$(zt=>{const rs=Math.round(St),Ct=Math.round(Mt);return zt.width===rs&&zt.height===Ct?zt:{width:rs,height:Ct}})});return Ne.observe(fe),()=>Ne.disconnect()},[]),l.useEffect(()=>{if(Z.current)return;const fe=Ee();!Number.isFinite(fe)||fe<=0||S(je=>z.current?fe<je-ce?fe:je:(z.current=!0,fe))},[_.height,_.width,E.height,E.width]),l.useEffect(()=>{et&&bt()},[et,Je,Ae]),l.useEffect(()=>{var Ne;const fe=X.current;if(X.current=i,!i)return;fe||y(!1),ve.current&&(ve.current=!1,yt());const je=Se.current;je&&(Se.current=null,ye(je.text,je.seq,je.cols,je.rows,{force:!!je.force})),ge&&J&&((Ne=jt.getState)==null?void 0:Ne.call(jt,ge))==="connected"&&le(),ke.current&&Y.current===null&&Re(),be(()=>{var He;(He=n.current)==null||He.bumpResize()})},[ge,i,J]),l.useEffect(()=>()=>{Y.current!==null&&re(),de(),we()},[]),l.useEffect(()=>{const fe=He=>{var lt;const Qe=He.detail;Qe!=null&&Qe.sessionId&&Qe.sessionId!==J||d&&((lt=n.current)==null||lt.bumpResize())},je=K(),Ne=je===window?[window]:[window,je];for(const He of Ne)He.addEventListener("adhdev:fit-cli-terminal",fe);return()=>{for(const He of Ne)He.removeEventListener("adhdev:fit-cli-terminal",fe)}},[d,J,n]);const st=d&&N&&!v&&(B.atTop||!B.canScroll)||f||!!w;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:ae,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[st&&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:()=>{Be()},disabled:!J||f,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:u(f?"terminal.loadingOlder":"terminal.loadOlderOutput")}),w&&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:w})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[V&&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:V}),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:()=>U(fe=>!fe),title:"Spec debug — inspect current state, sections, and transition history",children:u("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:()=>{Ue()},disabled:!d,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:u("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:()=>M(fe=>!fe),disabled:!d,"aria-label":u(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":u("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:()=>M(!1),"aria-label":u("terminal.closeControlKeys"),children:"×"})]}),s.jsx("div",{className:"mb-2 grid grid-cols-3 gap-1.5",children:[["Ctrl",I,D],["Alt",P,T],["Shift",H,L]].map(([fe,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:fe},fe))}),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:()=>Ye("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:()=>Ye("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:()=>Ye("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:()=>Ye("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:()=>Ye("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:()=>Ye("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:()=>Ye("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:()=>Ge(""),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:()=>Ye("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:()=>Ye("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:()=>{Z.current=!0,S(fe=>{const je=Math.max(Fe,Number((fe-.1).toFixed(2)));return je>Fe&&bt(),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:()=>{Z.current=!0,S(fe=>{const je=Math.min(Xe,Number((fe+.1).toFixed(2)));return je>Fe&&bt(),je})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:he,className:et?"w-full h-full overflow-auto rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",children:s.jsx("div",{style:{width:Ae>0?`${Ae}px`:"100%",height:Je>0?`${Je}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:_.width>0?`${_.width}px`:"100%",height:_.height>0?`${_.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:C},children:s.jsx(ip,{ref:n,readOnly:!d||!i,sizingMode:"measured",onViewportMetrics:q,onScrollMetrics:W,onInput:fe=>{!d||(p==null||p(ge,J,fe))}})})})}),!d&&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(Tp,{contextKey:e.tabKey,panelLabel:kt(e),isSending:r,isBusy:!!ue,statusMessage:ee,inlineStatusMessage:De,onSend:async fe=>ue?!1:a(fe),isActive:c&&i,showControlsToggle:!1,animateVisibility:!1}),R&&s.jsx(pC,{activeConv:e,onClose:()=>U(!1)})]})}const hC=5e3,fC=12e3;function bC(e){return e==="disconnected"||e==="reconnecting"}function gC({wsStatus:e,showReconnected:t,loginUrl:n,onReconnect:a,reconnectDelayMs:r=hC,reconnectActionDelayMs:o=fC}){const{t:i}=Ce(),c=bC(e),[u,p]=l.useState(()=>!c||r<=0),[d,m]=l.useState(()=>!c||o<=0),h=l.useRef(!1);l.useEffect(()=>{if(!c){p(!1);return}if(h.current=!1,r<=0){h.current=!0,p(!0);return}p(!1);const y=setTimeout(()=>{h.current=!0,p(!0)},r);return()=>clearTimeout(y)},[r,c]),l.useEffect(()=>{if(!c){m(!1);return}if(o<=0){m(!0);return}m(!1);const y=setTimeout(()=>{m(!0)},o);return()=>clearTimeout(y)},[o,c]);const g=c?u:e==="offline"||e==="auth_failed",k=!!(a&&e!=="auth_failed"&&(!c||d)),f=l.useMemo(()=>!t||e!=="connected"?!1:r<=0||h.current,[r,t,e]),x=e==="auth_failed"?"red":e==="offline"?"orange":"accent",w={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))"},b={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)"},N={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",v={transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[g&&s.jsx("div",{className:j,style:v,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:w[x],border:b[x],color:N[x]},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"))]}),k&&s.jsx("button",{type:"button",className:"basis-full sm:basis-auto mx-auto sm:mx-0 sm:ml-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-[12px] font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>a==null?void 0:a(),disabled:e==="offline",children:i("connection.reconnectNow")})]})}),f&&s.jsx("div",{className:j,style:v,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 gm({mode:e,onChange:t,compact:n=!1}){const{t:a}=Ce("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(gl,{size:r}):s.jsx(Cn,{size:r})})}function xC(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 vC(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 yC(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 Hr({git:e,className:t="",compact:n=!1}){const a=xC(e),r=vC(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 ${yC(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 wC({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 cd({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function dd({notification:e,shortcutIndex:t,onOpen:n,onMarkRead:a,onMarkUnread:r,onDelete:o}){const{t:i}=Ce(),c=eo(e.updatedAt),u=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${u?"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:[u?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 kC({activeConv:e,wsStatus:t,isConnected:n,conversations:a,onOpenHistory:r,onOpenRemote:o,onStopCli:i,activeCliViewMode:c,onSetCliViewMode:u,onHideConversation:p,hiddenConversations:d=[],onShowConversation:m,onShowAllHidden:h,onResetPanelsToMain:g,inboxOpen:k,onInboxOpenChange:f,hiddenOpen:x,onHiddenOpenChange:w,onOpenNewSession:b,onOpenDashboardGuide:N,guideNudgeVisible:j=!1,actionShortcuts:v,notifications:y,notificationUnreadCount:C,onOpenNotification:S,onMarkNotificationRead:A,onMarkNotificationUnread:M,onDeleteNotification:I,onOpenGitDialog:D,onOpenMeshGraph:P}){var me;const{t:T}=Ce(),{ides:H,p2pStates:L={},usesP2P:R=!0}=ys(),U=!!e&&mt(e)&&!ut(e),E=!!e&&ut(e),$=!!(e!=null&&e.daemonId)&&!!((me=e==null?void 0:e.coordinator)!=null&&me.meshId),_=c||(e?Fp(e)?"terminal":"chat":null),[q,B]=l.useState(!1),[W,V]=l.useState(!1),ne=l.useRef(null),ae=l.useRef(null),he=l.useRef(null),Z=H.filter(K=>K.type==="adhdev-daemon"),z=wC({wsStatus:t,isConnected:n,daemonCount:Z.length,p2pStates:L,usesP2P:R}),X=T(z.titleKey),O=z.subtitleKey?T(z.subtitleKey,z.subtitleParams):null,Q=z.tone==="connected"?"#22c55e":z.tone==="limited"?"#eab308":"#ef4444",ke=z.tone==="connected"?"0 0 4px #22c55e80":z.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",Se=l.useMemo(()=>y.filter(K=>!K.readAt),[y]),ve=l.useMemo(()=>y.filter(K=>!!K.readAt),[y]),xe=l.useMemo(()=>Se.slice(0,9),[Se]),Y=C;l.useEffect(()=>{if(!k)return;const K=be=>{var re;(re=ae.current)!=null&&re.contains(be.target)||f(!1)};return document.addEventListener("mousedown",K),()=>document.removeEventListener("mousedown",K)},[k,f]),l.useEffect(()=>{if(!x)return;const K=be=>{var re;(re=he.current)!=null&&re.contains(be.target)||w(!1)};return document.addEventListener("mousedown",K),()=>document.removeEventListener("mousedown",K)},[x,w]),l.useEffect(()=>{if(!x&&!k)return;const K=be=>{if(!be.altKey)return;const re=be.code.match(/^Digit([1-9])$/);if(!re)return;const de=Number(re[1])-1,we=x?d[de]:void 0,Re=k?xe[de]:void 0;if(!(!we&&!Re)){if(be.preventDefault(),be.stopPropagation(),we){m==null||m(we),w(!1);return}Re&&(S(Re),f(!1))}};return window.addEventListener("keydown",K,!0),()=>window.removeEventListener("keydown",K,!0)},[d,x,k,xe,w,f,S,m]),l.useEffect(()=>{const K=d.length;if(ne.current===null){ne.current=K;return}K>ne.current&&V(!0),ne.current=K},[d.length]);const G=()=>V(!1),te=K=>{if(!K)return;const be=a.find(re=>re.tabKey===K);be&&(p==null||p(be))};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(Cn,{size:18}),s.jsx("span",{className:"header-title-desktop",children:T("dashboard.header.title")}),s.jsx("span",{className:"header-title-mobile",children:e?kt(e):T("dashboard.header.title")}),s.jsx("span",{title:X,"aria-label":X,className:"header-title-status-dot",style:{background:Q,boxShadow:ke}}),s.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:s.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:Q,boxShadow:ke}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[O&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",O]}),b&&s.jsx("button",{type:"button",onClick:b,className:"btn btn-secondary btn-sm ml-2",title:`${T("paneGroup.newSession")}${v!=null&&v.openNewSession?` (${v.openNewSession})`:""}`,"aria-label":T("paneGroup.newSession"),children:s.jsx(xl,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[N&&s.jsxs("button",{type:"button",onClick:N,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:T("dashboard.header.guide"),"aria-label":T("dashboard.header.guideOpen"),children:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),j&&s.jsx("span",{children:T("dashboard.header.guideShort")})]}),e&&(U||E||!ut(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:Kn(e)||kt(e),children:kt(e)}),D&&e.git&&e.daemonId&&e.workspacePath?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:T("dashboard.header.openGitStatus"),onClick:()=>D(e.daemonId,e.workspacePath),children:s.jsx(Hr,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(Hr,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),$&&P&&s.jsxs("button",{type:"button",onClick:()=>P(e),className:"btn btn-secondary btn-sm dashboard-header-mesh-button",title:T("dashboard.header.openMeshGraph"),children:[s.jsx(ns,{size:14}),s.jsx("span",{className:"hidden lg:inline",children:T("dashboard.header.meshGraph")})]}),(U||E)&&i&&s.jsxs(s.Fragment,{children:[U&&u&&_&&s.jsx(gm,{mode:_,onChange:u,compact:!0}),s.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:T(E?"dashboard.header.stopAcpSession":"dashboard.header.stopCliProcess"),style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(It,{size:14})})]}),!ut(e)&&s.jsx("button",{onClick:()=>r(e),className:"btn btn-secondary btn-sm",title:T("dashboard.header.chatHistory"),children:s.jsx(fl,{size:14})}),!U&&!ut(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:T("dashboard.header.remoteControl"),children:s.jsx(ws,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:ae,children:[s.jsxs("div",{className:`dashboard-header-hidden${q?" is-drop-target":""}${W?" hidden-spawn-flash":""}${(d??[]).some(Da)?" hidden-generating-spin":""}`,onAnimationEnd:G,ref:he,onDragEnter:K=>{K.dataTransfer.types.includes("text/tab-key")&&(K.preventDefault(),B(!0))},onDragOver:K=>{K.dataTransfer.types.includes("text/tab-key")&&(K.preventDefault(),K.dataTransfer.dropEffect="move",B(!0))},onDragLeave:K=>{K.currentTarget.contains(K.relatedTarget)||B(!1)},onDrop:K=>{const be=K.dataTransfer.getData("text/tab-key");K.preventDefault(),B(!1),te(be)},children:[s.jsxs("button",{type:"button",onClick:()=>w(!x),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`${T("dashboard.hidden.title")}${v!=null&&v.toggleHiddenTabs?` (${v.toggleHiddenTabs})`:""}. ${T("dashboard.hidden.dragHint")}`,children:[s.jsx(bl,{size:16}),d.length>0&&s.jsx("span",{className:`dashboard-header-hidden-badge${W?" hidden-badge-pop":""}`,children:d.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:T("dashboard.hidden.title")}),s.jsx(cd,{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:T("dashboard.hidden.resetPanels")}),d.length>0&&h&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{h(),w(!1)},children:T("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:T("dashboard.hidden.hideCurrentTab")}),s.jsx(cd,{value:v==null?void 0:v.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:kt(e)})]}),d.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:d.map(K=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{m==null||m(K),w(!1)},children:[s.jsxs("span",{className:"dashboard-header-inbox-item-title",children:[Da(K)&&s.jsx("span",{className:"tab-spinner dashboard-header-inbox-item-spinner","aria-label":T("dashboard.header.generating")}),kt(K)]}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[d.indexOf(K)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",d.indexOf(K)+1]}):null,Kn(K)]})]},K.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:T("dashboard.hidden.empty")})]})]}),s.jsxs("button",{type:"button",onClick:()=>f(!k),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:T("dashboard.header.activityInbox"),children:[s.jsx(Xn,{size:16}),Y>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:Y})]}),k&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[Se.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:T("dashboard.inbox.unread")}),Se.map(K=>s.jsx(dd,{notification:K,shortcutIndex:xe.indexOf(K)>=0?xe.indexOf(K)+1:void 0,onOpen:()=>S(K),onMarkRead:()=>A(K.id),onMarkUnread:()=>M(K.id),onDelete:()=>I(K.id)},K.id))]}),ve.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:T("dashboard.inbox.read")}),ve.map(K=>s.jsx(dd,{notification:K,onOpen:()=>S(K),onMarkRead:()=>A(K.id),onMarkUnread:()=>M(K.id),onDelete:()=>I(K.id)},K.id))]}),y.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:T("dashboard.inbox.empty")})]})]})]})]})}function Gt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function SC(e,t){return String(e||"")!==String(t||"")}function CC(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(u=>String(u||"").toLowerCase()).join(`
|
|
52
52
|
`).includes(n)||a&&!String(i.workspace||"").toLowerCase().includes(a)||r&&!Cp(i.summaryMetadata).map(u=>u.toLowerCase()).join(`
|
|
53
|
-
`).includes(r)))}function jC(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 xm(e,t={}){return jC(CC(e,t),t.sortMode||"recent")}function Ui(e,t){return typeof e=="function"?e(t??!1?"launch.resumeSavedHistory":"launch.startFresh"):e?"Resume saved history":"Start fresh"}function vm(e,t){return typeof e=="function"?e(t??!1?"launch.resumingSavedHistory":"launch.startingFresh"):e?"Resuming saved history…":"Starting fresh…"}function NC(e){return e?e("launch.startFresh"):"Start fresh"}function AC(e){return e?e("launch.hostedRuntimeRecoveryDescription"):"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function MC(e){return e?e("launch.openSavedHistory"):"Open saved history"}function PC(e){return e?e("launch.savedHistoryTitle"):"Saved History"}function _l(e){return e?e("launch.savedHistoryHelper"):"Use saved history when you want continuity in the same provider conversation."}function TC(e){return e?e("launch.savedHistoryEmpty"):"No saved history found yet."}function DC(e){return e?e("launch.refreshSavedHistory"):"Refresh saved history"}function IC(e){return e?e("launch.refreshingSavedHistory"):"Refreshing saved history…"}function $r(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 Fr(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 Br(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartFresh":"launch.confirmRestart"):e==="start-fresh"?"Start fresh":"Restart"}function Wr(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartingFresh":"launch.confirmRestarting"):e==="start-fresh"?"Starting fresh…":"Restarting…"}function ym(e,t){return typeof e=="function"?e("launch.resumeWith",{label:t}):`Resume saved history with ${e}?`}function wm(e){return e?e("launch.resumeReview"):"Review or change the target workspace before resuming saved history."}function ud(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 km({activeConv:e,ides:t,isCreatingChat:n,isRefreshingHistory:a,savedSessions:r=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:c,missingWorkspaceResumePath:u,onSavedHistoryFiltersChange:p,onClose:d,onNewChat:m,onSwitchSession:h,onRefreshHistory:g,onResumeSavedSession:k}){var T;const{t:f}=Ce("common"),x=t.find(H=>H.id===e.routeId),w=(x==null?void 0:x.chats)||[],b=(T=x==null?void 0:x.activeChat)==null?void 0:T.id,N=mt(e)&&!ut(e),[j,v]=l.useState(()=>Gt()),[y,C]=l.useState(null),S=c||j,A=String(u||"").trim(),M=H=>{if(p){p(H);return}v(H)},I=l.useMemo(()=>r.map(H=>{const L=String(H.workspace||"").trim();return H.canResume||L||!A?H:{...H,workspace:A,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[A,r]),D=l.useMemo(()=>xm(I,{textQuery:S.textQuery,workspaceQuery:S.workspaceQuery,modelQuery:S.modelQuery,resumableOnly:S.resumableOnly,sortMode:S.sortMode}),[I,S.modelQuery,S.resumableOnly,S.sortMode,S.textQuery,S.workspaceQuery]),P=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:d,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:N?PC(f):f("historyModal.chatHistory")}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:XS(e)}),N&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:_l(f)})]}),s.jsx("button",{onClick:d,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(It,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!N&&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:f(n?"historyModal.creating":"historyModal.startNewChat")}),N?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:S.textQuery,onChange:H=>M({...S,textQuery:H.target.value}),placeholder:f("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:S.workspaceQuery,onChange:H=>M({...S,workspaceQuery:H.target.value}),placeholder:f("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:S.modelQuery,onChange:H=>M({...S,modelQuery:H.target.value}),placeholder:f("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:S.sortMode,onChange:H=>M({...S,sortMode:H.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:f("historyModal.sortRecent")}),s.jsx("option",{value:"oldest",children:f("historyModal.sortOldest")}),s.jsx("option",{value:"messages",children:f("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:S.resumableOnly,onChange:H=>M({...S,resumableOnly:H.target.checked})}),f("historyModal.resumeReadyOnly")]})]}),D.map(H=>{const L=e.providerSessionId===H.providerSessionId,R=L||!H.canResume||!!i,U=H.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{R||!k||C({kind:"saved",session:H})},disabled:R,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${L?"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 ${L?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:H.title||f("historyModal.untitledSession")}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:H.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:ud(H.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:H.preview||f("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:[H.workspace||f("historyModal.workspaceUnknown"),U?f("historyModal.selectedWorkspaceSuffix"):"",vn(H.summaryMetadata)?` · ${vn(H.summaryMetadata)}`:"",H.messageCount>0?` · ${f("historyModal.msgCount",{count:H.messageCount})}`:""]}),s.jsx("div",{className:"shrink-0",children:L?f("historyModal.statusActive"):H.canResume?U?f("historyModal.statusResumeSelectedWorkspace"):i===H.providerSessionId?f("historyModal.statusResuming"):f("historyModal.statusResume"):f("historyModal.statusMissingWorkspace")})]})]},H.id)})]}):w.map(H=>s.jsxs("div",{onClick:()=>{H.id!==b&&C({kind:"chat",id:H.id,title:H.title||f("historyModal.untitledSession")})},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${b===H.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===H.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:H.title||f("historyModal.untitledSession")}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[H.id.substring(0,12),"..."]}),b===H.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:f("historyModal.statusActive")})]})]},H.id)),(N&&!o&&D.length===0||!N&&w.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(Ub,{size:32})}),s.jsx("div",{className:"text-[13px]",children:N?r.length>0?f("historyModal.noMatchingHistory"):TC(f):f("historyModal.noRecentChats")})]}),N&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:IC(f)})})]}),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?f("historyModal.refreshing"):s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Zr,{size:13})," ",N?DC(f):f("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:()=>C(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:f("historyModal.confirmSwitchTitle")}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:f("historyModal.confirmSwitchDescription",{target:y.kind==="chat"?y.title:y.session.title||f("historyModal.untitledSession")})}),y.kind==="saved"&&s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted font-mono truncate",children:[y.session.workspace||f("historyModal.workspaceUnknown"),y.session.lastMessageAt?` · ${ud(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 H=y;C(null),H.kind==="chat"?(h(e.routeId,H.id),d()):k&&k(H.session)},className:"btn btn-primary w-full justify-center min-h-[42px]",children:f("historyModal.confirmSwitchAction")}),s.jsx("button",{onClick:()=>C(null),className:"btn btn-secondary w-full justify-center min-h-[42px]",children:f("common.cancel")})]})]})]})]});return typeof document>"u"?P:Fs.createPortal(P,document.body)}const pd={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 Sm({toasts:e,onDismiss:t,onClickToast:n}){const{t:a}=Ce();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=pd[r.type]||pd.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(It,{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:u=>{u.stopPropagation(),i.onClick(),t(r.id)},children:i.label},c))})]})]},r.id)})})}const LC=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function RC(e){const t=e.workspace||"";if(!t)return"";const n=t.split(/[/\\]/).filter(Boolean);return n.length>0?n[n.length-1]:t}function EC(e,t){return Cm(e)||t}function Cm(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 _C(e){return Cm(e)||void 0}function HC(e){return e.sessionId||e.instanceId||e.agentType}function jm(e=[]){const t={};for(const n of e)n.type==="adhdev-daemon"&&(t[n.id]=as(n,{fallbackId:n.id}));return t}function Nm(e,t={}){var a;const n=e.daemonId||((a=e.id)==null?void 0:a.split(":")[0])||e.id;return{machineName:Vw(e,t.machineNames),connectionState:t.connectionStates?t.connectionStates[n]||t.defaultConnectionState||"new":t.defaultConnectionState}}function Hl(e,t={}){return $C(e,Nm(e,t))}function $C(e,t={}){var h,g,k,f,x,w,b,N,j;const n=[],a=t.machineName,r=t.connectionState,o=RC(e),i=e.workspace||"",c=e0(e.type,{agentName:e.cliName}),u=mt(e)||ut(e)?c:Wt(e.type),p=EC(e,u),d=Array.isArray(e.childSessions)?e.childSessions.map(v=>{var y,C,S;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||Wt(v.providerType),model:_C(v),status:v.status,title:v.title,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,messages:((C=v.activeChat)==null?void 0:C.messages)||[],activeModal:((S=v.activeChat)==null?void 0:S.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=LC(e);if(m){const v=e.sessionId||e.instanceId,y=(h=e.settings)==null?void 0:h.meshCoordinatorFor,C=((g=e.settings)==null?void 0:g.meshNodeFor)||!((k=e.settings)!=null&&k.meshCoordinatorFor)&&((f=e.settings)==null?void 0:f.launchedByCoordinator),S=y?" (Coordinator)":C?" (Mesh Node)":"",A=c+S,M=(x=e.activeChat)==null?void 0:x.activeModal,I=M&&Array.isArray(M.buttons)&&M.buttons.length>0,D=t0(e.activeChat,[{status:e.status,activeModal:(w=e.activeChat)==null?void 0:w.activeModal}],e.agents||[]),P=e.activeChat||{title:"",messages:[]};let T=P.title&&String(P.title).trim()?String(P.title).trim():"";const H=(b=e.activeChat)==null?void 0:b.id,L=e.chats;if(H&&Array.isArray(L)&&L.length>0){const W=L.find(V=>V.id===H||V.id&&String(V.id)===String(H));W!=null&&W.title&&String(W.title).trim()&&(T=String(W.title).trim())}const R=(mt(e)||ut(e),e.type),U=(mt(e)||ut(e))&&Rc(T,A,R)?"":T,E=P.messages||[],$=typeof H=="string"?H.trim():"",_=(mt(e)||ut(e))&&$===String(e.type||"").trim(),q=$&&!_?$:e.providerSessionId,B=e.coordinator||(typeof((N=e.settings)==null?void 0:N.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:v,providerSessionId:e.providerSessionId,historySessionId:q,nativeSessionId:v,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:mt(e)&&e.mode||"chat",agentName:A,agentType:R,status:D,title:U,messages:E,resume:e.resume,hostIdeType:!mt(e)&&!ut(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||U||(mt(e)?e.mode==="chat"?A:`Terminal${S}`: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:I?M.buttons:void 0,modalMessage:I?M.message:void 0,streamSource:"native",tabKey:Po(v,e.id),machineName:a,connectionState:r,settings:e.settings,coordinator:B,messageInput:e.messageInput})}if(m&&(mt(e)||ut(e)))return n;for(const v of d){const y=v.activeModal&&Array.isArray(v.activeModal.buttons)&&v.activeModal.buttons.length>0,C=s0(v),S=HC(v),A=`${e.id}:${S}`,M=v.title&&String(v.title).trim()||"",I=Rc(M,v.agentName,v.agentType)?"":M,D=v.messages||[];if(!(v.transport==="cdp-webview"||!!v.sessionId||!!v.providerSessionId||D.length>0||y||!!I||!["idle","panel_hidden","disconnected","not_monitored"].includes(C)))continue;const T=v.coordinator||(typeof((j=v.settings)==null?void 0:j.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:C,title:I,messages:D,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:v.git||e.git,displayPrimary:o||I||v.agentName||u,displaySecondary:v.model&&v.model.trim()?v.model.trim():`${u} · ${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:Po(v.sessionId||v.instanceId,A),machineName:a,connectionState:r,settings:v.settings,coordinator:T,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||u,displaySecondary:p,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:Po(e.sessionId||e.instanceId,e.id),connectionState:r,settings:e.settings,messageInput:e.messageInput}),n}function Am(e){return String(e.type||e.id||"").trim()}function Or(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()).map(t=>t.trim()):[]}function FC(e,t){const n=(t||"").trim();if(!n)return[];const a=(e||[]).find(r=>r.type===n);return Or(a==null?void 0:a.modelOptions)}function BC(e,t){const n=(t||"").trim();if(!n)return[];const a=(e||[]).find(r=>r.type===n);return Or(a==null?void 0:a.thinkingLevelOptions)}function Mm(e){const t=new Map;for(const n of e||[])n!=null&&n.type&&t.set(n.type,{models:Or(n.modelOptions),thinking:Or(n.thinkingLevelOptions)});return t}function WC(e){var t;return e.category!=="cli"||!Am(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 en(e){var a;const t=new Set,n=[];for(const r of e||[]){if(!WC(r))continue;const o=Am(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 Wa(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 wn(e){return e.map(t=>t.type)}function OC(e,t){const n=Wa(e),a=t.trim();return!a||n.includes(a)?n:[...n,a]}function UC(e,t){return Wa(e).filter(n=>n!==t)}function md(e,t,n){const a=Wa(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}function hd({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 qC({value:e,availableProviders:t,onChange:n,disabled:a=!1,saveButton:r}){const{t:o}=Ce("common"),[i,c]=l.useState(""),u=l.useMemo(()=>new Map(t.map(g=>[g.type,g])),[t]),p=l.useMemo(()=>Wa(e),[e]),d=p.filter(g=>!u.has(g)).length,m=t.filter(g=>!p.includes(g.type)),h=()=>{i&&(n(OC(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 f=u.get(g),x=!!f;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]}),(f==null?void 0:f.icon)&&s.jsx("span",{"aria-hidden":"true",children:f.icon}),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:f?`${f.label} · ${f.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(md(p,g,"up")),children:s.jsx(hd,{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(md(p,g,"down")),children:s.jsx(hd,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:a,onClick:()=>n(UC(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:h,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.",d>0?` ${d} provider${d===1?"":"s"} not detected here — kept in order, skipped until available.`:""]})]})}function GC(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 Pm(e,t){const n=GC(e);return{daemonId:n.daemonId,payload:{...t,...n.targetSessionId&&!t.targetSessionId?{targetSessionId:n.targetSessionId}:{}}}}const Tm=[{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:"🏄"}],Dm=[{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:"hermes-cli",name:"Hermes",icon:"⚕️"},{id:"kimi",name:"Kimi",icon:"🌙"},{id:"opencode",name:"OpenCode CLI",icon:"◆"}],Im=[{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:"🟠"}],zC=Tm,KC=Dm,VC=Im;function YC({icon:e,title:t,subtitle:n,badge:a,actions:r,className:o}){return s.jsxs("div",{className:Ot("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 Oa({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(YC,{icon:e,title:t,subtitle:n,badge:a,actions:r}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Ot("mx-auto flex w-full flex-col gap-4",o,i),children:c})})]})}const qi="adhdev:themechange";function QC(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function En(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function _n(e){return e==="system"?QC():e}function Lm(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function yr(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(qi,{detail:{preference:e,theme:t}}))}function JC(){const e=En(),t=_n(e);Lm(t),yr(e,t)}function tn(){const[e,t]=l.useState(En),[n,a]=l.useState(()=>_n(En()));l.useEffect(()=>{Lm(n)},[n]),l.useEffect(()=>{const i=window.matchMedia("(prefers-color-scheme: light)"),c=u=>{if(e==="system"){const p=u.matches?"light":"dark";a(p),yr("system",p)}};return i.addEventListener("change",c),()=>i.removeEventListener("change",c)},[e]),l.useEffect(()=>{const i=u=>{const p=u.detail||{},d=p.preference,m=p.theme;t(d==="dark"||d==="light"||d==="system"?d:En()),a(m==="dark"||m==="light"?m:_n(En()))},c=u=>{if(u.key!=="theme")return;const p=En(),d=_n(p);t(p),a(d)};return window.addEventListener(qi,i),window.addEventListener("storage",c),()=>{window.removeEventListener(qi,i),window.removeEventListener("storage",c)}},[]);const r=l.useCallback(i=>{const c=_n(i);t(i),a(c);try{localStorage.setItem("theme",i)}catch{}yr(i,c)},[]),o=l.useCallback(()=>{t(i=>{const c=i==="dark"?"light":i==="light"?"system":"dark",u=_n(c);a(u);try{localStorage.setItem("theme",c)}catch{}return yr(c,u),c})},[]);return{theme:n,preference:e,setPreference:r,cycleTheme:o,isDark:n==="dark"}}const fd={dark:"Dark",light:"Light",system:"System"};function XC({collapsed:e}){const{preference:t,cycleTheme:n}=tn(),a=t==="dark"?s.jsx(Gb,{size:16}):t==="light"?s.jsx(qb,{size:16}):s.jsx(zb,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:n,title:`Theme: ${fd[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:a}),!e&&s.jsx("span",{className:"text-xs",children:fd[t]})]})}const Gi="adhdev:langchange";function ZC(){const e=wt.language;return $n(e)?e:fp()}function ej(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(Gi,{detail:{language:e}}))}function tj(){const[e,t]=l.useState(ZC);l.useEffect(()=>{const a=i=>{$n(i)&&t(i)},r=i=>{const c=i.detail||{};$n(c.language)&&t(c.language)},o=i=>{if(i.key!==Pi)return;const c=i.newValue;$n(c)&&c!==wt.language&&(wt.changeLanguage(c),Ti(c))};return wt.on("languageChanged",a),window.addEventListener(Gi,r),window.addEventListener("storage",o),()=>{wt.off("languageChanged",a),window.removeEventListener(Gi,r),window.removeEventListener("storage",o)}},[]);const n=l.useCallback(a=>{if($n(a)){t(a);try{localStorage.setItem(Pi,a)}catch{}wt.changeLanguage(a),Ti(a),ej(a)}},[]);return{language:e,setLanguage:n}}function sj({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,u=a==="sidebar";let p=u;u&&i<n.height&&c>i&&(p=!1),!u&&c<n.height&&i>c&&(p=!0);const d=p?i:c,m=Math.max(80,Math.min(n.height,d));let h;p?h=e.top-r-m:h=e.bottom+r,h=bd(h,o,Math.max(o,t.height-m-o));const g=bd(e.left,o,Math.max(o,t.width-n.width-o));return{top:h,left:g,maxHeight:m}}function bd(e,t,n){return Math.min(Math.max(e,t),n)}function nj({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 aj({collapsed:e,variant:t="sidebar"}){const{language:n,setLanguage:a}=tj(),{t:r}=Ce("common"),[o,i]=l.useState(!1),[c,u]=l.useState(0),p=l.useRef(null),d=l.useRef(null),m=l.useRef(null),h=l.useId(),[g,k]=l.useState(null),f=l.useCallback(()=>{const D=d.current;if(!D)return;const P=D.getBoundingClientRect(),T=m.current,H=Math.max((T==null?void 0:T.offsetWidth)??0,168),L=(T==null?void 0:T.scrollHeight)??nn.length*36+12;k(sj({trigger:{top:P.top,left:P.left,right:P.right,bottom:P.bottom,width:P.width,height:P.height},viewport:{width:window.innerWidth,height:window.innerHeight},menu:{width:H,height:L},variant:t}))},[t]),x=Math.max(0,nn.findIndex(D=>D.code===n)),w=nn[x]??nn[0],b=r("language.label",{defaultValue:"Language"}),N=r("language.select",{defaultValue:"Select language"}),j=D=>`${h}-opt-${D}`,v=l.useCallback(()=>{u(x),i(!0)},[x]),y=l.useCallback((D=!0)=>{var P;i(!1),D&&((P=d.current)==null||P.focus())},[]),C=l.useCallback(D=>{const P=nn[D];P&&a(P.code),y()},[a,y]);l.useEffect(()=>{if(!o)return;const D=H=>{var L,R;return!!((L=p.current)!=null&&L.contains(H)||(R=m.current)!=null&&R.contains(H))},P=H=>{D(H.target)||i(!1)},T=H=>{D(H.target)||i(!1)};return document.addEventListener("pointerdown",P,!0),document.addEventListener("focusin",T,!0),()=>{document.removeEventListener("pointerdown",P,!0),document.removeEventListener("focusin",T,!0)}},[o]),l.useLayoutEffect(()=>{if(!o){k(null);return}f();const D=()=>f();return window.addEventListener("resize",D),window.addEventListener("scroll",D,!0),()=>{window.removeEventListener("resize",D),window.removeEventListener("scroll",D,!0)}},[o,f]),l.useEffect(()=>{var D;o&&g&&((D=m.current)==null||D.focus())},[o,g]);const S=D=>{const P=nn.length-1;switch(D.key){case"ArrowDown":D.preventDefault(),u(T=>T>=P?0:T+1);break;case"ArrowUp":D.preventDefault(),u(T=>T<=0?P:T-1);break;case"Home":D.preventDefault(),u(0);break;case"End":D.preventDefault(),u(P);break;case"Enter":case" ":D.preventDefault(),C(c);break;case"Escape":D.preventDefault(),y();break;case"Tab":i(!1);break}},A=D=>{o||(D.key==="ArrowDown"||D.key==="ArrowUp"||D.key==="Enter"||D.key===" ")&&(D.preventDefault(),v())},M=t==="landing"?"lang-switch-trigger lang-switch-trigger--landing":`lang-switch-trigger lang-switch-trigger--sidebar nav-item cursor-pointer${e?" justify-center py-2.5 px-0":""}`,I=t==="landing"||!e;return s.jsxs("div",{ref:p,className:"lang-switch",children:[s.jsxs("button",{ref:d,type:"button",className:M,"aria-haspopup":"listbox","aria-expanded":o,"aria-label":`${b}: ${w.label}`,title:`${b}: ${w.label}`,onClick:()=>o?y(!1):v(),onKeyDown:A,children:[s.jsx("span",{className:"nav-icon lang-switch-icon",children:s.jsx(tg,{size:16})}),I&&s.jsx("span",{className:"lang-switch-label text-xs",children:w.label}),I&&s.jsx(nj,{open:o})]}),o&&typeof document<"u"&&Fs.createPortal(s.jsx("ul",{ref:m,role:"listbox",tabIndex:-1,"aria-label":N,"aria-activedescendant":j(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:S,children:nn.map((D,P)=>{const T=D.code===w.code,H=P===c;return s.jsxs("li",{id:j(P),role:"option","aria-selected":T,className:`lang-switch-option${H?" is-active":""}${T?" is-selected":""}`,onMouseEnter:()=>u(P),onClick:()=>C(P),children:[s.jsx("span",{className:"lang-switch-check","aria-hidden":"true",children:T?s.jsx(Yu,{size:14}):null}),s.jsx("span",{className:"lang-switch-option-label",children:D.label})]},D.code)})}),document.body)]})}const rj=[],oj=[];function $o(e,t){return e?typeof e=="function"?e(t):e:null}const ij=l.memo(function({renderState:t,brand:n,navItems:a,sidebarSections:r,footerItems:o,footerInfo:i,footerActions:c,closeMobileMenu:u}){const{t:p}=Ce("common"),{collapsed:d,mobileMenuOpen:m}=t,h=k=>`nav-item${k.active?" active":""} cursor-pointer ${d?"justify-center py-2.5 px-0":""}${k.className?` ${k.className}`:""}`,g=k=>s.jsxs("div",{className:h(k),id:`nav-${k.id}`,onClick:()=>{k.onSelect(),u()},title:d?k.title??(typeof k.label=="string"?k.label:void 0):k.title,children:[s.jsx("span",{className:"nav-icon",children:k.icon}),!d&&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 ${d?"justify-center gap-0":""}`,children:$o(n,t)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":p("app.closeMenu"),onClick:u,children:s.jsx(It,{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:[!d&&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),$o(i,t),s.jsx(XC,{collapsed:d}),s.jsx(aj,{collapsed:d}),$o(c,t)]})]})});function lj({children:e,brand:t,navItems:n,sidebarSections:a=rj,footerItems:r=oj,footerInfo:o,footerActions:i,preMainContent:c,collapsedStorageKey:u="sidebar-collapsed"}){const{t:p}=Ce("common"),[d,m]=l.useState(!1),[h,g]=l.useState(()=>{try{return localStorage.getItem(u)==="1"}catch{return!1}}),k=l.useCallback(()=>m(!0),[]),f=l.useCallback(()=>m(!1),[]),x=l.useCallback(()=>{g(b=>{const N=!b;try{localStorage.setItem(u,N?"1":"0")}catch{}return N})},[u]),w=l.useMemo(()=>({collapsed:h,mobileMenuOpen:d,openMobileMenu:k,closeMobileMenu:f,toggleCollapsed:x}),[h,d,k,f,x]);return s.jsxs("div",{className:`app-layout${d?" mobile-menu-open":""}${h?" 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"})]}),d&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":p("app.closeMenu"),onClick:f,onKeyDown:b=>b.key==="Escape"&&f()}),s.jsx(ij,{renderState:w,brand:t,navItems:n,sidebarSections:a,footerItems:r,footerInfo:o,footerActions:i,closeMobileMenu:f}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function ht({title:e,icon:t,description:n,accentColor:a,className:r,collapsible:o,defaultOpen:i=!0,badge:c,children:u}){const[p,d]=l.useState(i),m=o?p:!0,h=(e||n)&&s.jsxs("div",{className:Ot("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:Ot("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:Ot("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&&h?s.jsx("button",{type:"button",className:"w-full bg-transparent border-none p-0 text-left cursor-pointer",onClick:()=>d(g=>!g),"aria-expanded":m,children:h}):h,m&&u]})}function co({icon:e,title:t,description:n,action:a,className:r}){return s.jsxs("div",{className:Ot("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 cj={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"},dj={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Dt({variant:e,children:t,onDismiss:n,className:a}){return s.jsxs("div",{className:Ot("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",cj[e],a),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:dj[e]}),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 At({label:e,hint:t,children:n,className:a}){return s.jsxs("div",{className:Ot("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 fs(e){const{className:t,...n}=e;return s.jsx("input",{...n,className:Ot("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 uj={primary:"btn-primary",secondary:"btn-secondary",warning:"btn-warning",danger:"btn-danger",ghost:"btn-ghost"},Hs=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:Ot("btn",uj[t],n==="sm"&&"btn-sm",r),...o})}),pj=l.forwardRef(function({options:t,children:n,className:a,...r},o){return s.jsx("select",{ref:o,className:Ot("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)))})}),mj={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"},hj={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function fj({status:e,label:t,className:n}){const a=t||e;return s.jsxs("span",{className:Ot("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",mj[e],n),children:[s.jsx("span",{className:Ot("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",hj[e])}),a]})}function cn({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 bj({onPrefChange:e}){const{t}=Ce("common"),[n,a]=p0(),[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,u)=>{a({[c]:u}),e==null||e(c,u)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(cn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Xn,{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(cn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ws,{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:()=>{Ap().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(cn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ep,{size:15})," ",t("notifications.completionAlertsLabel")]}),description:t("notifications.completionAlertsDesc"),checked:n.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(cn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Kb,{size:15})," ",t("notifications.approvalAlertsLabel")]}),description:t("notifications.approvalAlertsDesc"),checked:n.approvalAlert,onChange:c=>i("approvalAlert",c)}),s.jsx(cn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ta,{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 Ur(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 gd(e){var t;return((t=Ur(e))==null?void 0:t.base)??null}function Rm(e,t){const n=Ur(e),a=Ur(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 uo(e,t){const n=e.version||null;return!n||!t||e.versionMismatch===!0&&!Ur(t)?!1:Rm(n,t)}function ja(e,t){if(e.versionUpdateRequired===!0)return!0;const n=e.version||null;if(!n||!t||!Rm(n,t))return!1;const a=gd(n),r=gd(t);return!a||!r?!1:a[0]!==r[0]||a[1]!==r[1]}function Fo(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 gj(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 va(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function $l(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},n=Fo(t.channel)||Fo(e.updateChannel)||Fo(e.releaseChannel)||void 0,a=gj(t.npmTag)||(n==="preview"?"next":n==="stable"?"latest":void 0),r=va(t.targetVersion)||va(e.serverVersion)||void 0,o=va(t.minVersion)||void 0,i=va(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 $l(e).targetVersion||t}function xj(e){return $l(e).channel||null}function po(e){return!e||!$l(e).channel?null:{}}function Em(e,t={}){const n=va(t.targetVersion);return n?`Update to v${n}`:t.fallback||(t.required?"Update now":"Upgrade")}const _m="Cannot update: node update policy unavailable; refresh and try again";async function vj(e,t,n){var r,o,i,c,u,p;const a=po(n);if(!a)return{state:"error",message:_m};try{const d=await e(t,"daemon_upgrade",a);return(r=d==null?void 0:d.result)!=null&&r.alreadyLatest?{state:"done",message:`Already on v${((o=d==null?void 0:d.result)==null?void 0:o.version)||"latest"}.`}:(i=d==null?void 0:d.result)!=null&&i.upgraded||(c=d==null?void 0:d.result)!=null&&c.success?{state:"done",message:`Upgrade to v${((u=d==null?void 0:d.result)==null?void 0:u.version)||"latest"} started. Daemon is restarting…`}:{state:"error",message:((p=d==null?void 0:d.result)==null?void 0:p.error)||"Upgrade failed"}}catch(d){return{state:"error",message:d instanceof Error?d.message:"Upgrade failed"}}}function yj(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Bo(e,t){return e instanceof Error?e.message:t}function wj({ides:e,emptyMessage:t,sendDaemonCommand:n,onDisconnect:a,onRevokeToken:r}){const{t:o}=Ce("common"),i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?s.jsx(co,{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(Sj,{ide:c,allIdes:e,sendDaemonCommand:n,onDisconnect:a,onRevokeToken:r},c.id))})}function xd({title:e,message:t,confirmLabel:n,confirmColor:a,onConfirm:r,onCancel:o}){const{t:i}=Ce("common"),c=a==="red"?"bg-status-error/20 text-status-error border-status-error/40 hover:bg-status-error/30":"";return Fs.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:u=>u.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 kj(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),a=[...zC,...KC,...VC].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 Sj({ide:e,allIdes:t,sendDaemonCommand:n,onDisconnect:a,onRevokeToken:r}){var L,R;const{t:o}=Ce("common"),[i,c]=l.useState("idle"),[u,p]=l.useState(""),[d,m]=l.useState(null),[h,g]=l.useState("idle"),[k,f]=l.useState(""),x=e.version||null,w=((L=e.machine)==null?void 0:L.platform)||((R=e.system)==null?void 0:R.platform)||"",b=as(e,{fallbackId:e.id}),N=w==="win32"?"🪟":w==="darwin"?"🍎":"🐧",j=t.filter(U=>U.daemonId===e.id&&U.transport==="cdp-page"),v=t.filter(U=>U.daemonId===e.id&&U.transport==="pty"),y=t.filter(U=>U.daemonId===e.id&&U.transport==="acp"),C=e.p2p,S=async()=>{if(!n)return;const U=po(e);if(!U){c("error"),p(_m);return}c("upgrading"),p(o("machine.connectedMachines.startingUpgrade"));try{const E=yj(await n(e.id,"daemon_upgrade",U));E.alreadyLatest?(c("done"),p(`Already on v${E.version||"latest"}.`)):E.upgraded||E.success?(c("done"),p(`Upgrade to v${E.version||"latest"} started. Daemon is restarting...`)):(c("error"),p(E.error||"Upgrade failed"))}catch(E){c("error"),p(Bo(E,"Connection lost during upgrade"))}},A=async()=>{if(m(null),!!a){g("loading");try{await a(e.id),g("done"),f(o("machine.connectedMachines.machineDisconnected"))}catch(U){g("error"),f(Bo(U,o("machine.connectedMachines.failedToDisconnect")))}}},M=async()=>{if(m(null),!!r){g("loading");try{await r(e.id),g("done"),f(o("machine.connectedMachines.tokenRevoked"))}catch(U){g("error"),f(Bo(U,o("machine.connectedMachines.failedToRevokeToken")))}}},I="1.0.47",D=qs(e,I),P=uo(e,D),T=ja(e,D),H=j.length+v.length+y.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xl",children:N}),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:S,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${I}`,children:i==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," ",o("machine.connectedMachines.upgrading")]}):i==="done"?o("machine.connectedMachines.updated"):T?o("machine.connectedMachines.updateNow"):o("machine.connectedMachines.updateTo",{version:I})}),a&&s.jsx("button",{onClick:()=>m("disconnect"),disabled:h==="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:h==="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(fj,{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:[C&&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 ${C.state==="connected"?"bg-status-online":"bg-text-muted/30"} ${C.state==="connecting"||C.state==="new"?"animate-pulse":""}`,style:C.state==="connecting"||C.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",C.state==="connected"?"connected":C.state==="connecting"||C.state==="new"?o("machine.connectedMachines.connecting"):C.state||"off"]}),C.peers!==void 0&&C.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",C.peers," peer",C.peers!==1?"s":"",")"]})]}),C&&H>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),H>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[j.map(U=>{const E=kj(U.type),$=U.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:E.icon}),s.jsx("span",{children:E.name}),$!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${$?"bg-status-online":"animate-pulse"}`,style:$?void 0:{background:"var(--status-warning)"},title:o($?"machine.connectedMachines.cdpConnected":"machine.connectedMachines.cdpConnecting")})]},U.id)}),v.map(U=>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:U.cliName||"CLI"})]},U.id)),y.map(U=>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:U.cliName||"ACP"})]},U.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:o("machine.connectedMachines.noIdesConnected")})]}),(u||k)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||h==="error"?"text-status-error":i==="done"||h==="done"?"text-status-online":"text-text-muted"}`,children:k||u})]}),d==="disconnect"&&s.jsx(xd,{title:o("machine.connectedMachines.disconnectTitle"),message:`Disconnect "${b}" from ADHDev?
|
|
53
|
+
`).includes(r)))}function jC(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 xm(e,t={}){return jC(CC(e,t),t.sortMode||"recent")}function Ui(e,t){return typeof e=="function"?e(t??!1?"launch.resumeSavedHistory":"launch.startFresh"):e?"Resume saved history":"Start fresh"}function vm(e,t){return typeof e=="function"?e(t??!1?"launch.resumingSavedHistory":"launch.startingFresh"):e?"Resuming saved history…":"Starting fresh…"}function NC(e){return e?e("launch.startFresh"):"Start fresh"}function AC(e){return e?e("launch.hostedRuntimeRecoveryDescription"):"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function MC(e){return e?e("launch.openSavedHistory"):"Open saved history"}function PC(e){return e?e("launch.savedHistoryTitle"):"Saved History"}function _l(e){return e?e("launch.savedHistoryHelper"):"Use saved history when you want continuity in the same provider conversation."}function TC(e){return e?e("launch.savedHistoryEmpty"):"No saved history found yet."}function DC(e){return e?e("launch.refreshSavedHistory"):"Refresh saved history"}function IC(e){return e?e("launch.refreshingSavedHistory"):"Refreshing saved history…"}function $r(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 Fr(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 Br(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartFresh":"launch.confirmRestart"):e==="start-fresh"?"Start fresh":"Restart"}function Wr(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartingFresh":"launch.confirmRestarting"):e==="start-fresh"?"Starting fresh…":"Restarting…"}function ym(e,t){return typeof e=="function"?e("launch.resumeWith",{label:t}):`Resume saved history with ${e}?`}function wm(e){return e?e("launch.resumeReview"):"Review or change the target workspace before resuming saved history."}function ud(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 km({activeConv:e,ides:t,isCreatingChat:n,isRefreshingHistory:a,savedSessions:r=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:c,missingWorkspaceResumePath:u,onSavedHistoryFiltersChange:p,onClose:d,onNewChat:m,onSwitchSession:h,onRefreshHistory:g,onResumeSavedSession:k}){var T;const{t:f}=Ce("common"),x=t.find(H=>H.id===e.routeId),w=(x==null?void 0:x.chats)||[],b=(T=x==null?void 0:x.activeChat)==null?void 0:T.id,N=mt(e)&&!ut(e),[j,v]=l.useState(()=>Gt()),[y,C]=l.useState(null),S=c||j,A=String(u||"").trim(),M=H=>{if(p){p(H);return}v(H)},I=l.useMemo(()=>r.map(H=>{const L=String(H.workspace||"").trim();return H.canResume||L||!A?H:{...H,workspace:A,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[A,r]),D=l.useMemo(()=>xm(I,{textQuery:S.textQuery,workspaceQuery:S.workspaceQuery,modelQuery:S.modelQuery,resumableOnly:S.resumableOnly,sortMode:S.sortMode}),[I,S.modelQuery,S.resumableOnly,S.sortMode,S.textQuery,S.workspaceQuery]),P=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:d,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:N?PC(f):f("historyModal.chatHistory")}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:XS(e)}),N&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:_l(f)})]}),s.jsx("button",{onClick:d,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(It,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!N&&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:f(n?"historyModal.creating":"historyModal.startNewChat")}),N?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:S.textQuery,onChange:H=>M({...S,textQuery:H.target.value}),placeholder:f("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:S.workspaceQuery,onChange:H=>M({...S,workspaceQuery:H.target.value}),placeholder:f("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:S.modelQuery,onChange:H=>M({...S,modelQuery:H.target.value}),placeholder:f("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:S.sortMode,onChange:H=>M({...S,sortMode:H.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:f("historyModal.sortRecent")}),s.jsx("option",{value:"oldest",children:f("historyModal.sortOldest")}),s.jsx("option",{value:"messages",children:f("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:S.resumableOnly,onChange:H=>M({...S,resumableOnly:H.target.checked})}),f("historyModal.resumeReadyOnly")]})]}),D.map(H=>{const L=e.providerSessionId===H.providerSessionId,R=L||!H.canResume||!!i,U=H.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{R||!k||C({kind:"saved",session:H})},disabled:R,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${L?"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 ${L?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:H.title||f("historyModal.untitledSession")}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:H.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:ud(H.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:H.preview||f("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:[H.workspace||f("historyModal.workspaceUnknown"),U?f("historyModal.selectedWorkspaceSuffix"):"",vn(H.summaryMetadata)?` · ${vn(H.summaryMetadata)}`:"",H.messageCount>0?` · ${f("historyModal.msgCount",{count:H.messageCount})}`:""]}),s.jsx("div",{className:"shrink-0",children:L?f("historyModal.statusActive"):H.canResume?U?f("historyModal.statusResumeSelectedWorkspace"):i===H.providerSessionId?f("historyModal.statusResuming"):f("historyModal.statusResume"):f("historyModal.statusMissingWorkspace")})]})]},H.id)})]}):w.map(H=>s.jsxs("div",{onClick:()=>{H.id!==b&&C({kind:"chat",id:H.id,title:H.title||f("historyModal.untitledSession")})},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${b===H.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===H.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:H.title||f("historyModal.untitledSession")}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[H.id.substring(0,12),"..."]}),b===H.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:f("historyModal.statusActive")})]})]},H.id)),(N&&!o&&D.length===0||!N&&w.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(Ub,{size:32})}),s.jsx("div",{className:"text-[13px]",children:N?r.length>0?f("historyModal.noMatchingHistory"):TC(f):f("historyModal.noRecentChats")})]}),N&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:IC(f)})})]}),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?f("historyModal.refreshing"):s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Zr,{size:13})," ",N?DC(f):f("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:()=>C(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:f("historyModal.confirmSwitchTitle")}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:f("historyModal.confirmSwitchDescription",{target:y.kind==="chat"?y.title:y.session.title||f("historyModal.untitledSession")})}),y.kind==="saved"&&s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted font-mono truncate",children:[y.session.workspace||f("historyModal.workspaceUnknown"),y.session.lastMessageAt?` · ${ud(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 H=y;C(null),H.kind==="chat"?(h(e.routeId,H.id),d()):k&&k(H.session)},className:"btn btn-primary w-full justify-center min-h-[42px]",children:f("historyModal.confirmSwitchAction")}),s.jsx("button",{onClick:()=>C(null),className:"btn btn-secondary w-full justify-center min-h-[42px]",children:f("common.cancel")})]})]})]})]});return typeof document>"u"?P:Fs.createPortal(P,document.body)}const pd={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 Sm({toasts:e,onDismiss:t,onClickToast:n}){const{t:a}=Ce();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=pd[r.type]||pd.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(It,{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:u=>{u.stopPropagation(),i.onClick(),t(r.id)},children:i.label},c))})]})]},r.id)})})}const LC=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function RC(e){const t=e.workspace||"";if(!t)return"";const n=t.split(/[/\\]/).filter(Boolean);return n.length>0?n[n.length-1]:t}function EC(e,t){return Cm(e)||t}function Cm(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 _C(e){return Cm(e)||void 0}function HC(e){return e.sessionId||e.instanceId||e.agentType}function jm(e=[]){const t={};for(const n of e)n.type==="adhdev-daemon"&&(t[n.id]=as(n,{fallbackId:n.id}));return t}function Nm(e,t={}){var a;const n=e.daemonId||((a=e.id)==null?void 0:a.split(":")[0])||e.id;return{machineName:Vw(e,t.machineNames),connectionState:t.connectionStates?t.connectionStates[n]||t.defaultConnectionState||"new":t.defaultConnectionState}}function Hl(e,t={}){return $C(e,Nm(e,t))}function $C(e,t={}){var h,g,k,f,x,w,b,N,j;const n=[],a=t.machineName,r=t.connectionState,o=RC(e),i=e.workspace||"",c=e0(e.type,{agentName:e.cliName}),u=mt(e)||ut(e)?c:Wt(e.type),p=EC(e,u),d=Array.isArray(e.childSessions)?e.childSessions.map(v=>{var y,C,S;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||Wt(v.providerType),model:_C(v),status:v.status,title:v.title,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,messages:((C=v.activeChat)==null?void 0:C.messages)||[],activeModal:((S=v.activeChat)==null?void 0:S.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=LC(e);if(m){const v=e.sessionId||e.instanceId,y=(h=e.settings)==null?void 0:h.meshCoordinatorFor,C=((g=e.settings)==null?void 0:g.meshNodeFor)||!((k=e.settings)!=null&&k.meshCoordinatorFor)&&((f=e.settings)==null?void 0:f.launchedByCoordinator),S=y?" (Coordinator)":C?" (Mesh Node)":"",A=c+S,M=(x=e.activeChat)==null?void 0:x.activeModal,I=M&&Array.isArray(M.buttons)&&M.buttons.length>0,D=t0(e.activeChat,[{status:e.status,activeModal:(w=e.activeChat)==null?void 0:w.activeModal}],e.agents||[]),P=e.activeChat||{title:"",messages:[]};let T=P.title&&String(P.title).trim()?String(P.title).trim():"";const H=(b=e.activeChat)==null?void 0:b.id,L=e.chats;if(H&&Array.isArray(L)&&L.length>0){const W=L.find(V=>V.id===H||V.id&&String(V.id)===String(H));W!=null&&W.title&&String(W.title).trim()&&(T=String(W.title).trim())}const R=(mt(e)||ut(e),e.type),U=(mt(e)||ut(e))&&Rc(T,A,R)?"":T,E=P.messages||[],$=typeof H=="string"?H.trim():"",_=(mt(e)||ut(e))&&$===String(e.type||"").trim(),q=$&&!_?$:e.providerSessionId,B=e.coordinator||(typeof((N=e.settings)==null?void 0:N.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:v,providerSessionId:e.providerSessionId,historySessionId:q,nativeSessionId:v,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:mt(e)&&e.mode||"chat",agentName:A,agentType:R,status:D,title:U,messages:E,resume:e.resume,hostIdeType:!mt(e)&&!ut(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||U||(mt(e)?e.mode==="chat"?A:`Terminal${S}`: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:I?M.buttons:void 0,modalMessage:I?M.message:void 0,streamSource:"native",tabKey:Po(v,e.id),machineName:a,connectionState:r,settings:e.settings,coordinator:B,messageInput:e.messageInput})}if(m&&(mt(e)||ut(e)))return n;for(const v of d){const y=v.activeModal&&Array.isArray(v.activeModal.buttons)&&v.activeModal.buttons.length>0,C=s0(v),S=HC(v),A=`${e.id}:${S}`,M=v.title&&String(v.title).trim()||"",I=Rc(M,v.agentName,v.agentType)?"":M,D=v.messages||[];if(!(v.transport==="cdp-webview"||!!v.sessionId||!!v.providerSessionId||D.length>0||y||!!I||!["idle","panel_hidden","disconnected","not_monitored"].includes(C)))continue;const T=v.coordinator||(typeof((j=v.settings)==null?void 0:j.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:C,title:I,messages:D,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:v.git||e.git,displayPrimary:o||I||v.agentName||u,displaySecondary:v.model&&v.model.trim()?v.model.trim():`${u} · ${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:Po(v.sessionId||v.instanceId,A),machineName:a,connectionState:r,settings:v.settings,coordinator:T,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||u,displaySecondary:p,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:Po(e.sessionId||e.instanceId,e.id),connectionState:r,settings:e.settings,messageInput:e.messageInput}),n}function Am(e){return String(e.type||e.id||"").trim()}function Or(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()).map(t=>t.trim()):[]}function FC(e,t){const n=(t||"").trim();if(!n)return[];const a=(e||[]).find(r=>r.type===n);return Or(a==null?void 0:a.modelOptions)}function BC(e,t){const n=(t||"").trim();if(!n)return[];const a=(e||[]).find(r=>r.type===n);return Or(a==null?void 0:a.thinkingLevelOptions)}function Mm(e){const t=new Map;for(const n of e||[])n!=null&&n.type&&t.set(n.type,{models:Or(n.modelOptions),thinking:Or(n.thinkingLevelOptions)});return t}function WC(e){var t;return e.category!=="cli"||!Am(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 en(e){var a;const t=new Set,n=[];for(const r of e||[]){if(!WC(r))continue;const o=Am(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 Wa(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 wn(e){return e.map(t=>t.type)}function OC(e,t){const n=Wa(e),a=t.trim();return!a||n.includes(a)?n:[...n,a]}function UC(e,t){return Wa(e).filter(n=>n!==t)}function md(e,t,n){const a=Wa(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}function hd({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 qC({value:e,availableProviders:t,onChange:n,disabled:a=!1,saveButton:r}){const{t:o}=Ce("common"),[i,c]=l.useState(""),u=l.useMemo(()=>new Map(t.map(g=>[g.type,g])),[t]),p=l.useMemo(()=>Wa(e),[e]),d=p.filter(g=>!u.has(g)).length,m=t.filter(g=>!p.includes(g.type)),h=()=>{i&&(n(OC(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 f=u.get(g),x=!!f;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]}),(f==null?void 0:f.icon)&&s.jsx("span",{"aria-hidden":"true",children:f.icon}),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:f?`${f.label} · ${f.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(md(p,g,"up")),children:s.jsx(hd,{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(md(p,g,"down")),children:s.jsx(hd,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:a,onClick:()=>n(UC(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:h,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.",d>0?` ${d} provider${d===1?"":"s"} not detected here — kept in order, skipped until available.`:""]})]})}function GC(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 Pm(e,t){const n=GC(e);return{daemonId:n.daemonId,payload:{...t,...n.targetSessionId&&!t.targetSessionId?{targetSessionId:n.targetSessionId}:{}}}}const Tm=[{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:"🏄"}],Dm=[{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:"hermes-cli",name:"Hermes",icon:"⚕️"},{id:"kimi",name:"Kimi",icon:"🌙"},{id:"opencode",name:"OpenCode CLI",icon:"◆"}],Im=[{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:"🟠"}],zC=Tm,KC=Dm,VC=Im;function YC({icon:e,title:t,subtitle:n,badge:a,actions:r,className:o}){return s.jsxs("div",{className:Ot("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 Oa({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(YC,{icon:e,title:t,subtitle:n,badge:a,actions:r}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Ot("mx-auto flex w-full flex-col gap-4",o,i),children:c})})]})}const qi="adhdev:themechange";function QC(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function En(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function _n(e){return e==="system"?QC():e}function Lm(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function yr(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(qi,{detail:{preference:e,theme:t}}))}function JC(){const e=En(),t=_n(e);Lm(t),yr(e,t)}function tn(){const[e,t]=l.useState(En),[n,a]=l.useState(()=>_n(En()));l.useEffect(()=>{Lm(n)},[n]),l.useEffect(()=>{const i=window.matchMedia("(prefers-color-scheme: light)"),c=u=>{if(e==="system"){const p=u.matches?"light":"dark";a(p),yr("system",p)}};return i.addEventListener("change",c),()=>i.removeEventListener("change",c)},[e]),l.useEffect(()=>{const i=u=>{const p=u.detail||{},d=p.preference,m=p.theme;t(d==="dark"||d==="light"||d==="system"?d:En()),a(m==="dark"||m==="light"?m:_n(En()))},c=u=>{if(u.key!=="theme")return;const p=En(),d=_n(p);t(p),a(d)};return window.addEventListener(qi,i),window.addEventListener("storage",c),()=>{window.removeEventListener(qi,i),window.removeEventListener("storage",c)}},[]);const r=l.useCallback(i=>{const c=_n(i);t(i),a(c);try{localStorage.setItem("theme",i)}catch{}yr(i,c)},[]),o=l.useCallback(()=>{t(i=>{const c=i==="dark"?"light":i==="light"?"system":"dark",u=_n(c);a(u);try{localStorage.setItem("theme",c)}catch{}return yr(c,u),c})},[]);return{theme:n,preference:e,setPreference:r,cycleTheme:o,isDark:n==="dark"}}const fd={dark:"Dark",light:"Light",system:"System"};function XC({collapsed:e}){const{preference:t,cycleTheme:n}=tn(),a=t==="dark"?s.jsx(Gb,{size:16}):t==="light"?s.jsx(qb,{size:16}):s.jsx(zb,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:n,title:`Theme: ${fd[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:a}),!e&&s.jsx("span",{className:"text-xs",children:fd[t]})]})}const Gi="adhdev:langchange";function ZC(){const e=wt.language;return $n(e)?e:fp()}function ej(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(Gi,{detail:{language:e}}))}function tj(){const[e,t]=l.useState(ZC);l.useEffect(()=>{const a=i=>{$n(i)&&t(i)},r=i=>{const c=i.detail||{};$n(c.language)&&t(c.language)},o=i=>{if(i.key!==Pi)return;const c=i.newValue;$n(c)&&c!==wt.language&&(wt.changeLanguage(c),Ti(c))};return wt.on("languageChanged",a),window.addEventListener(Gi,r),window.addEventListener("storage",o),()=>{wt.off("languageChanged",a),window.removeEventListener(Gi,r),window.removeEventListener("storage",o)}},[]);const n=l.useCallback(a=>{if($n(a)){t(a);try{localStorage.setItem(Pi,a)}catch{}wt.changeLanguage(a),Ti(a),ej(a)}},[]);return{language:e,setLanguage:n}}function sj({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,u=a==="sidebar";let p=u;u&&i<n.height&&c>i&&(p=!1),!u&&c<n.height&&i>c&&(p=!0);const d=p?i:c,m=Math.max(80,Math.min(n.height,d));let h;p?h=e.top-r-m:h=e.bottom+r,h=bd(h,o,Math.max(o,t.height-m-o));const g=bd(e.left,o,Math.max(o,t.width-n.width-o));return{top:h,left:g,maxHeight:m}}function bd(e,t,n){return Math.min(Math.max(e,t),n)}function nj({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 aj({collapsed:e,variant:t="sidebar"}){const{language:n,setLanguage:a}=tj(),{t:r}=Ce("common"),[o,i]=l.useState(!1),[c,u]=l.useState(0),p=l.useRef(null),d=l.useRef(null),m=l.useRef(null),h=l.useId(),[g,k]=l.useState(null),f=l.useCallback(()=>{const D=d.current;if(!D)return;const P=D.getBoundingClientRect(),T=m.current,H=Math.max((T==null?void 0:T.offsetWidth)??0,168),L=(T==null?void 0:T.scrollHeight)??nn.length*36+12;k(sj({trigger:{top:P.top,left:P.left,right:P.right,bottom:P.bottom,width:P.width,height:P.height},viewport:{width:window.innerWidth,height:window.innerHeight},menu:{width:H,height:L},variant:t}))},[t]),x=Math.max(0,nn.findIndex(D=>D.code===n)),w=nn[x]??nn[0],b=r("language.label",{defaultValue:"Language"}),N=r("language.select",{defaultValue:"Select language"}),j=D=>`${h}-opt-${D}`,v=l.useCallback(()=>{u(x),i(!0)},[x]),y=l.useCallback((D=!0)=>{var P;i(!1),D&&((P=d.current)==null||P.focus())},[]),C=l.useCallback(D=>{const P=nn[D];P&&a(P.code),y()},[a,y]);l.useEffect(()=>{if(!o)return;const D=H=>{var L,R;return!!((L=p.current)!=null&&L.contains(H)||(R=m.current)!=null&&R.contains(H))},P=H=>{D(H.target)||i(!1)},T=H=>{D(H.target)||i(!1)};return document.addEventListener("pointerdown",P,!0),document.addEventListener("focusin",T,!0),()=>{document.removeEventListener("pointerdown",P,!0),document.removeEventListener("focusin",T,!0)}},[o]),l.useLayoutEffect(()=>{if(!o){k(null);return}f();const D=()=>f();return window.addEventListener("resize",D),window.addEventListener("scroll",D,!0),()=>{window.removeEventListener("resize",D),window.removeEventListener("scroll",D,!0)}},[o,f]),l.useEffect(()=>{var D;o&&g&&((D=m.current)==null||D.focus())},[o,g]);const S=D=>{const P=nn.length-1;switch(D.key){case"ArrowDown":D.preventDefault(),u(T=>T>=P?0:T+1);break;case"ArrowUp":D.preventDefault(),u(T=>T<=0?P:T-1);break;case"Home":D.preventDefault(),u(0);break;case"End":D.preventDefault(),u(P);break;case"Enter":case" ":D.preventDefault(),C(c);break;case"Escape":D.preventDefault(),y();break;case"Tab":i(!1);break}},A=D=>{o||(D.key==="ArrowDown"||D.key==="ArrowUp"||D.key==="Enter"||D.key===" ")&&(D.preventDefault(),v())},M=t==="landing"?"lang-switch-trigger lang-switch-trigger--landing":`lang-switch-trigger lang-switch-trigger--sidebar nav-item cursor-pointer${e?" justify-center py-2.5 px-0":""}`,I=t==="landing"||!e;return s.jsxs("div",{ref:p,className:"lang-switch",children:[s.jsxs("button",{ref:d,type:"button",className:M,"aria-haspopup":"listbox","aria-expanded":o,"aria-label":`${b}: ${w.label}`,title:`${b}: ${w.label}`,onClick:()=>o?y(!1):v(),onKeyDown:A,children:[s.jsx("span",{className:"nav-icon lang-switch-icon",children:s.jsx(tg,{size:16})}),I&&s.jsx("span",{className:"lang-switch-label text-xs",children:w.label}),I&&s.jsx(nj,{open:o})]}),o&&typeof document<"u"&&Fs.createPortal(s.jsx("ul",{ref:m,role:"listbox",tabIndex:-1,"aria-label":N,"aria-activedescendant":j(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:S,children:nn.map((D,P)=>{const T=D.code===w.code,H=P===c;return s.jsxs("li",{id:j(P),role:"option","aria-selected":T,className:`lang-switch-option${H?" is-active":""}${T?" is-selected":""}`,onMouseEnter:()=>u(P),onClick:()=>C(P),children:[s.jsx("span",{className:"lang-switch-check","aria-hidden":"true",children:T?s.jsx(Yu,{size:14}):null}),s.jsx("span",{className:"lang-switch-option-label",children:D.label})]},D.code)})}),document.body)]})}const rj=[],oj=[];function $o(e,t){return e?typeof e=="function"?e(t):e:null}const ij=l.memo(function({renderState:t,brand:n,navItems:a,sidebarSections:r,footerItems:o,footerInfo:i,footerActions:c,closeMobileMenu:u}){const{t:p}=Ce("common"),{collapsed:d,mobileMenuOpen:m}=t,h=k=>`nav-item${k.active?" active":""} cursor-pointer ${d?"justify-center py-2.5 px-0":""}${k.className?` ${k.className}`:""}`,g=k=>s.jsxs("div",{className:h(k),id:`nav-${k.id}`,onClick:()=>{k.onSelect(),u()},title:d?k.title??(typeof k.label=="string"?k.label:void 0):k.title,children:[s.jsx("span",{className:"nav-icon",children:k.icon}),!d&&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 ${d?"justify-center gap-0":""}`,children:$o(n,t)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":p("app.closeMenu"),onClick:u,children:s.jsx(It,{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:[!d&&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),$o(i,t),s.jsx(XC,{collapsed:d}),s.jsx(aj,{collapsed:d}),$o(c,t)]})]})});function lj({children:e,brand:t,navItems:n,sidebarSections:a=rj,footerItems:r=oj,footerInfo:o,footerActions:i,preMainContent:c,collapsedStorageKey:u="sidebar-collapsed"}){const{t:p}=Ce("common"),[d,m]=l.useState(!1),[h,g]=l.useState(()=>{try{return localStorage.getItem(u)==="1"}catch{return!1}}),k=l.useCallback(()=>m(!0),[]),f=l.useCallback(()=>m(!1),[]),x=l.useCallback(()=>{g(b=>{const N=!b;try{localStorage.setItem(u,N?"1":"0")}catch{}return N})},[u]),w=l.useMemo(()=>({collapsed:h,mobileMenuOpen:d,openMobileMenu:k,closeMobileMenu:f,toggleCollapsed:x}),[h,d,k,f,x]);return s.jsxs("div",{className:`app-layout${d?" mobile-menu-open":""}${h?" 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"})]}),d&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":p("app.closeMenu"),onClick:f,onKeyDown:b=>b.key==="Escape"&&f()}),s.jsx(ij,{renderState:w,brand:t,navItems:n,sidebarSections:a,footerItems:r,footerInfo:o,footerActions:i,closeMobileMenu:f}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function ht({title:e,icon:t,description:n,accentColor:a,className:r,collapsible:o,defaultOpen:i=!0,badge:c,children:u}){const[p,d]=l.useState(i),m=o?p:!0,h=(e||n)&&s.jsxs("div",{className:Ot("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:Ot("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:Ot("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&&h?s.jsx("button",{type:"button",className:"w-full bg-transparent border-none p-0 text-left cursor-pointer",onClick:()=>d(g=>!g),"aria-expanded":m,children:h}):h,m&&u]})}function co({icon:e,title:t,description:n,action:a,className:r}){return s.jsxs("div",{className:Ot("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 cj={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"},dj={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Dt({variant:e,children:t,onDismiss:n,className:a}){return s.jsxs("div",{className:Ot("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",cj[e],a),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:dj[e]}),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 At({label:e,hint:t,children:n,className:a}){return s.jsxs("div",{className:Ot("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 fs(e){const{className:t,...n}=e;return s.jsx("input",{...n,className:Ot("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 uj={primary:"btn-primary",secondary:"btn-secondary",warning:"btn-warning",danger:"btn-danger",ghost:"btn-ghost"},Hs=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:Ot("btn",uj[t],n==="sm"&&"btn-sm",r),...o})}),pj=l.forwardRef(function({options:t,children:n,className:a,...r},o){return s.jsx("select",{ref:o,className:Ot("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)))})}),mj={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"},hj={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function fj({status:e,label:t,className:n}){const a=t||e;return s.jsxs("span",{className:Ot("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",mj[e],n),children:[s.jsx("span",{className:Ot("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",hj[e])}),a]})}function cn({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 bj({onPrefChange:e}){const{t}=Ce("common"),[n,a]=p0(),[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,u)=>{a({[c]:u}),e==null||e(c,u)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(cn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Xn,{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(cn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ws,{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:()=>{Ap().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(cn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ep,{size:15})," ",t("notifications.completionAlertsLabel")]}),description:t("notifications.completionAlertsDesc"),checked:n.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(cn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Kb,{size:15})," ",t("notifications.approvalAlertsLabel")]}),description:t("notifications.approvalAlertsDesc"),checked:n.approvalAlert,onChange:c=>i("approvalAlert",c)}),s.jsx(cn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ta,{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 Ur(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 gd(e){var t;return((t=Ur(e))==null?void 0:t.base)??null}function Rm(e,t){const n=Ur(e),a=Ur(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 uo(e,t){const n=e.version||null;return!n||!t||e.versionMismatch===!0&&!Ur(t)?!1:Rm(n,t)}function ja(e,t){if(e.versionUpdateRequired===!0)return!0;const n=e.version||null;if(!n||!t||!Rm(n,t))return!1;const a=gd(n),r=gd(t);return!a||!r?!1:a[0]!==r[0]||a[1]!==r[1]}function Fo(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 gj(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 va(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function $l(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},n=Fo(t.channel)||Fo(e.updateChannel)||Fo(e.releaseChannel)||void 0,a=gj(t.npmTag)||(n==="preview"?"next":n==="stable"?"latest":void 0),r=va(t.targetVersion)||va(e.serverVersion)||void 0,o=va(t.minVersion)||void 0,i=va(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 $l(e).targetVersion||t}function xj(e){return $l(e).channel||null}function po(e){return!e||!$l(e).channel?null:{}}function Em(e,t={}){const n=va(t.targetVersion);return n?`Update to v${n}`:t.fallback||(t.required?"Update now":"Upgrade")}const _m="Cannot update: node update policy unavailable; refresh and try again";async function vj(e,t,n){var r,o,i,c,u,p;const a=po(n);if(!a)return{state:"error",message:_m};try{const d=await e(t,"daemon_upgrade",a);return(r=d==null?void 0:d.result)!=null&&r.alreadyLatest?{state:"done",message:`Already on v${((o=d==null?void 0:d.result)==null?void 0:o.version)||"latest"}.`}:(i=d==null?void 0:d.result)!=null&&i.upgraded||(c=d==null?void 0:d.result)!=null&&c.success?{state:"done",message:`Upgrade to v${((u=d==null?void 0:d.result)==null?void 0:u.version)||"latest"} started. Daemon is restarting…`}:{state:"error",message:((p=d==null?void 0:d.result)==null?void 0:p.error)||"Upgrade failed"}}catch(d){return{state:"error",message:d instanceof Error?d.message:"Upgrade failed"}}}function yj(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Bo(e,t){return e instanceof Error?e.message:t}function wj({ides:e,emptyMessage:t,sendDaemonCommand:n,onDisconnect:a,onRevokeToken:r}){const{t:o}=Ce("common"),i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?s.jsx(co,{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(Sj,{ide:c,allIdes:e,sendDaemonCommand:n,onDisconnect:a,onRevokeToken:r},c.id))})}function xd({title:e,message:t,confirmLabel:n,confirmColor:a,onConfirm:r,onCancel:o}){const{t:i}=Ce("common"),c=a==="red"?"bg-status-error/20 text-status-error border-status-error/40 hover:bg-status-error/30":"";return Fs.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:u=>u.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 kj(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),a=[...zC,...KC,...VC].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 Sj({ide:e,allIdes:t,sendDaemonCommand:n,onDisconnect:a,onRevokeToken:r}){var L,R;const{t:o}=Ce("common"),[i,c]=l.useState("idle"),[u,p]=l.useState(""),[d,m]=l.useState(null),[h,g]=l.useState("idle"),[k,f]=l.useState(""),x=e.version||null,w=((L=e.machine)==null?void 0:L.platform)||((R=e.system)==null?void 0:R.platform)||"",b=as(e,{fallbackId:e.id}),N=w==="win32"?"🪟":w==="darwin"?"🍎":"🐧",j=t.filter(U=>U.daemonId===e.id&&U.transport==="cdp-page"),v=t.filter(U=>U.daemonId===e.id&&U.transport==="pty"),y=t.filter(U=>U.daemonId===e.id&&U.transport==="acp"),C=e.p2p,S=async()=>{if(!n)return;const U=po(e);if(!U){c("error"),p(_m);return}c("upgrading"),p(o("machine.connectedMachines.startingUpgrade"));try{const E=yj(await n(e.id,"daemon_upgrade",U));E.alreadyLatest?(c("done"),p(`Already on v${E.version||"latest"}.`)):E.upgraded||E.success?(c("done"),p(`Upgrade to v${E.version||"latest"} started. Daemon is restarting...`)):(c("error"),p(E.error||"Upgrade failed"))}catch(E){c("error"),p(Bo(E,"Connection lost during upgrade"))}},A=async()=>{if(m(null),!!a){g("loading");try{await a(e.id),g("done"),f(o("machine.connectedMachines.machineDisconnected"))}catch(U){g("error"),f(Bo(U,o("machine.connectedMachines.failedToDisconnect")))}}},M=async()=>{if(m(null),!!r){g("loading");try{await r(e.id),g("done"),f(o("machine.connectedMachines.tokenRevoked"))}catch(U){g("error"),f(Bo(U,o("machine.connectedMachines.failedToRevokeToken")))}}},I="1.0.48",D=qs(e,I),P=uo(e,D),T=ja(e,D),H=j.length+v.length+y.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xl",children:N}),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:S,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${I}`,children:i==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," ",o("machine.connectedMachines.upgrading")]}):i==="done"?o("machine.connectedMachines.updated"):T?o("machine.connectedMachines.updateNow"):o("machine.connectedMachines.updateTo",{version:I})}),a&&s.jsx("button",{onClick:()=>m("disconnect"),disabled:h==="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:h==="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(fj,{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:[C&&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 ${C.state==="connected"?"bg-status-online":"bg-text-muted/30"} ${C.state==="connecting"||C.state==="new"?"animate-pulse":""}`,style:C.state==="connecting"||C.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",C.state==="connected"?"connected":C.state==="connecting"||C.state==="new"?o("machine.connectedMachines.connecting"):C.state||"off"]}),C.peers!==void 0&&C.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",C.peers," peer",C.peers!==1?"s":"",")"]})]}),C&&H>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),H>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[j.map(U=>{const E=kj(U.type),$=U.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:E.icon}),s.jsx("span",{children:E.name}),$!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${$?"bg-status-online":"animate-pulse"}`,style:$?void 0:{background:"var(--status-warning)"},title:o($?"machine.connectedMachines.cdpConnected":"machine.connectedMachines.cdpConnecting")})]},U.id)}),v.map(U=>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:U.cliName||"CLI"})]},U.id)),y.map(U=>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:U.cliName||"ACP"})]},U.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:o("machine.connectedMachines.noIdesConnected")})]}),(u||k)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||h==="error"?"text-status-error":i==="done"||h==="done"?"text-status-online":"text-text-muted"}`,children:k||u})]}),d==="disconnect"&&s.jsx(xd,{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:M,onCancel:()=>m(null)})]})}const Cj=["default","claude-cli","codex-cli","antigravity-cli","hermes-cli","gemini-cli"];function jj({daemonId:e,knownCliTypes:t=Cj}){const{t:n}=Ce("common"),{sendCommand:a}=vt(),[r,o]=l.useState({}),[i,c]=l.useState({}),[u,p]=l.useState(!0),[d,m]=l.useState(null),[h,g]=l.useState(null),[k,f]=l.useState(""),x=l.useCallback(async()=>{if(e){p(!0),g(null);try{const N=await a(e,"list_coordinator_prompts",{}),j=N!=null&&N.result&&typeof N.result=="object"?N.result:N;if(!(j!=null&&j.success)){g((j==null?void 0:j.error)||"Failed to load");return}const v=j.entries||{};f(j.dir||"");const y={};for(const C of t)y[C]=v[C]||{override:"",append:""};for(const C of Object.keys(v))y[C]||(y[C]=v[C]);o(y),c(JSON.parse(JSON.stringify(y)))}catch(N){g((N==null?void 0:N.message)||String(N))}finally{p(!1)}}},[a,e,t]);l.useEffect(()=>{x()},[x]);const w=l.useCallback(async(N,j)=>{var v;if(e){m(`${N}:${j}`),g(null);try{const y=((v=r[N])==null?void 0:v[j])||"",C=await a(e,"write_coordinator_prompt",{key:N,kind:j,content:y}),S=C!=null&&C.result&&typeof C.result=="object"?C.result:C;if(!(S!=null&&S.success)){g((S==null?void 0:S.error)||"Save failed");return}c(A=>({...A,[N]:{...A[N]||{override:"",append:""},[j]:y}}))}catch(y){g((y==null?void 0:y.message)||String(y))}finally{m(null)}}},[a,e,r]),b=l.useMemo(()=>(N,j)=>{var v,y;return(((v=r[N])==null?void 0:v[j])||"")!==(((y=i[N])==null?void 0:y[j])||"")},[r,i]);return e?s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{className:"text-[12px] text-text-muted",children:[s.jsxs("p",{children:["Customize the coordinator prompt this daemon's mesh coordinator sessions get. ",s.jsx("span",{className:"font-mono text-[11px]",children:k||"~/.adhdev/coordinator-prompts/"})]}),s.jsxs("p",{className:"mt-1",children:[s.jsx(wi,{i18nKey:"settings.coordinatorPrompts.overrideDesc",ns:"common",components:{strong:s.jsx("strong",{})}})," ",s.jsx(wi,{i18nKey:"settings.coordinatorPrompts.appendDesc",ns:"common",components:{strong:s.jsx("strong",{})}}),"Leave a field empty + Save to remove it (reset to default). Supports placeholders: ","{{meshName}}",", ","{{repo}}",", ","{{nodes}}",", ","{{rules}}",", etc."]})]}),h&&s.jsx("div",{className:"text-[12px] text-status-error bg-status-error/10 border border-status-error/40 rounded px-3 py-2",children:h}),u&&s.jsx("div",{className:"text-[12px] text-text-muted",children:"Loading…"}),s.jsx("div",{className:"flex flex-col gap-6",children:Object.entries(r).map(([N,j])=>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-2",children:N}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:n("settings.coordinatorPrompts.overrideLabel")}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:4,value:j.override,onChange:v=>o(y=>({...y,[N]:{...y[N],override:v.target.value}})),placeholder:"(empty — use daemon default base prompt)",disabled:d===`${N}:override`}),s.jsx("div",{className:"mt-1 mb-3 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void w(N,"override"),disabled:d===`${N}:override`||!b(N,"override"),children:d===`${N}:override`?"Saving…":b(N,"override")?"Save override":"Saved"})}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:n("settings.coordinatorPrompts.appendLabel")}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:3,value:j.append,onChange:v=>o(y=>({...y,[N]:{...y[N],append:v.target.value}})),placeholder:"(empty — nothing appended at this layer)",disabled:d===`${N}:append`}),s.jsx("div",{className:"mt-1 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void w(N,"append"),disabled:d===`${N}:append`||!b(N,"append"),children:d===`${N}:append`?"Saving…":b(N,"append")?"Save append":"Saved"})})]},N))})]}):s.jsx("div",{className:"text-[12px] text-text-muted",children:"Connect a daemon to edit coordinator prompts."})}const Nj=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Aj(){const{preference:e,setPreference:t}=tn();return s.jsx("div",{className:"flex gap-2",children:Nj.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("span",{children:n.icon}),n.label]},n.id))})}function Mj(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 Pj(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Wo(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function vd(e){const{r:t,g:n,b:a}=Pj(e);return .2126*Wo(t)+.7152*Wo(n)+.0722*Wo(a)}function yd(e,t){const n=vd(e),a=vd(t),r=Math.max(n,a),o=Math.min(n,a);return(r+.05)/(o+.05)}function Hm(e){const t=Mj(e);if(!t)return"#111827";const n="#111827",a="#ffffff";return yd(t,n)>=yd(t,a)?n:a}const zi={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},Ki={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},Tj=[{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"}}}],$m="adhdev-chat-theme",Fm="adhdev-chat-theme-custom";function wr(){if(typeof window>"u")return"ember";try{return localStorage.getItem($m)||"ember"}catch{return"ember"}}function hs(e){try{const t=localStorage.getItem(Fm);if(t){const n=JSON.parse(t);return{...e==="dark"?zi:Ki,...n[e]}}}catch{}return e==="dark"?zi:Ki}function tr(e,t){try{localStorage.setItem(Fm,JSON.stringify({dark:e,light:t}))}catch{}}function Zt(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 qr(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 Dj={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Na(e,t){var r;const n=(r=Dj[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",qr(n,24)),a.style.setProperty("--accent-on-primary",Hm(n)),a.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${n}, ${qr(n,18)})`),a.style.setProperty("--border-accent",Zt(n,.35)),a.style.setProperty("--nav-active-bg",Zt(n,.1)),a.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${n}, 0 0 12px ${Zt(n,.06)}`)}function hn(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",Zt(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Zt(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Zt(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",Zt(e.borderSubtle,.5)),t.style.setProperty("--border-default",Zt(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",qr(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Hm(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${qr(e.accentColor,40)})`),t.style.setProperty("--border-accent",Zt(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",Zt(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Zt(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 ${Zt(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 Fl(){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 Ij(e){try{localStorage.setItem($m,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=fn()?"dark":"light";hn(hs(t))}else Fl(),Na(e,fn()?"dark":"light")}function Lj(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=wr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=fn()?"dark":"light";hn(hs(t))}else Fl(),Na(e,fn()?"dark":"light")}function fn(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function qt({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 ua({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 Rj({dark:e,onColorsChange:t}){const{t:n}=Ce("common"),a=e?"dark":"light",[r,o]=l.useState(()=>hs(a));l.useEffect(()=>{o(hs(a))},[a]);const i=l.useCallback((c,u)=>{o(p=>{const d={...p,[c]:u},h=hs(a==="dark"?"light":"dark");return a==="dark"?tr(d,h):tr(h,d),hn(d),t(d),d})},[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(ua,{title:n("settings.theme.sectionAppBackground"),children:[s.jsx(qt,{label:n("settings.theme.colorBackground"),value:r.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(qt,{label:n("settings.theme.colorSurface"),value:r.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(qt,{label:n("settings.theme.colorCard"),value:r.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(ua,{title:n("settings.theme.sectionAppText"),children:[s.jsx(qt,{label:n("settings.theme.colorPrimary"),value:r.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(qt,{label:n("settings.theme.colorSecondary"),value:r.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(qt,{label:n("settings.theme.colorMuted"),value:r.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(ua,{title:n("settings.theme.sectionBordersAccent"),children:[s.jsx(qt,{label:n("settings.theme.colorBorderSubtle"),value:r.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(qt,{label:n("settings.theme.colorBorderDefault"),value:r.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(qt,{label:n("settings.theme.colorAccent"),value:r.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(ua,{title:n("settings.theme.sectionChatBubbles"),children:[s.jsx(qt,{label:n("settings.theme.colorUserBubble"),value:r.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(qt,{label:n("settings.theme.colorUserText"),value:r.userText,onChange:c=>i("userText",c)}),s.jsx(qt,{label:n("settings.theme.colorAgentBubble"),value:r.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(qt,{label:n("settings.theme.colorAgentText"),value:r.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(ua,{title:n("settings.theme.sectionChatLayout"),children:[s.jsx(qt,{label:n("settings.theme.colorChatBg"),value:r.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(qt,{label:n("settings.theme.colorSendButton"),value:r.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(qt,{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?zi:Ki,p=hs(e?"light":"dark");e?tr(c,p):tr(p,c),o(c),hn(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 Ej(){const{t:e}=Ce("common"),[t,n]=l.useState(wr),[a,r]=l.useState(!0),[o,i]=l.useState(()=>hs("dark"));l.useEffect(()=>{r(fn());const p=new MutationObserver(()=>{const h=fn();r(h);const g=wr();g==="custom"?hn(hs(h?"dark":"light")):Na(g,h?"dark":"light")});p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const d=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const h=fn();r(h);const g=wr();g==="custom"?hn(hs(h?"dark":"light")):Na(g,h?"dark":"light")};return d.addEventListener("change",m),()=>{p.disconnect(),d.removeEventListener("change",m)}},[]),l.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?hn(hs(a?"dark":"light")):(Fl(),Na(t,a?"dark":"light"))},[t,a]),l.useEffect(()=>{i(hs(a?"dark":"light"))},[a]);const c=p=>{n(p),Ij(p)},u=[...Tj,{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:u.map(p=>{const d=t===p.id,m=a?p.preview.dark:p.preview.light,h=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:d?"var(--bg-glass-hover)":"var(--bg-glass)",border:d?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:d?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:h},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:[d&&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(Rj,{dark:a,onColorsChange:p=>i(p)})]})}const Bl="adhdev_mobileDashboardMode_v1",Vi="adhdev:mobile-dashboard-mode-change";function Wl(){try{return localStorage.getItem(Bl)==="workspace"?"workspace":"chat"}catch{return"chat"}}function _j(e){if(typeof window>"u")return()=>{};const t=r=>{e(r??Wl())},n=r=>{const o=r.detail;t(o)},a=r=>{r.key&&r.key!==Bl||t()};return window.addEventListener(Vi,n),window.addEventListener("storage",a),()=>{window.removeEventListener(Vi,n),window.removeEventListener("storage",a)}}function Hj(e){try{localStorage.setItem(Bl,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Vi,{detail:e}))}function $j(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(Wl()==="chat")},[]),s.jsx(cn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Cn,{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),Hj(n?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const Fj="Choose a preset or create a fully custom theme. Custom themes control the entire app — backgrounds, text, borders, and chat bubbles.",Bj="Choose whether the dashboard opens like a chat app on phones or keeps the full workspace layout.";function Wj({themeDescription:e=Fj,mobileDescription:t=Bj,fontsSlot:n}){const{t:a}=Ce("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(Aj,{})]}),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(Ej,{})]}),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($j,{})]})]})}const Oo=new Map,wd=new Map;function Oj(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 Uj(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 Bm(){const{sendCommand:e}=vt(),{injectEntries:t,getIdes:n}=Pa();return l.useCallback(async(a,r)=>{if(!a)return;const o=(r==null?void 0:r.minFreshMs)??Qk,i=wd.get(a)||0;if(!(r!=null&&r.force)&&i>0&&Date.now()-i<o)return;const c=Oo.get(a);if(c)return c;const u=(async()=>{const p=await e(a,"get_machine_runtime_stats"),d=Oj(p);if(!d)return;const m=n().find(g=>g.id===a),h=Uj(m,a,d.machine,d.timestamp||Date.now());t([h]),wd.set(a,Date.now())})().finally(()=>{Oo.delete(a)});return Oo.set(a,u),u},[n,t,e])}function qj(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 Gj(e,t){const{sendData:n}=vt(),{injectEntries:a,getIdes:r}=Pa(),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(u=>gs.subscribe({sendData:n},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:t==null?void 0:t.intervalMs}},d=>{const m=r().find(g=>g.id===u),h=qj(m,u,d);a([h])}));return()=>{c.forEach(u=>u())}},[o,r,a,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,n])}function zj(e,t){const{sendData:n}=vt(),[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 u=gs.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 u.initialSendAccepted?c=setTimeout(()=>{i(!1)},Zk):i(!1),()=>{c&&clearTimeout(c),u()}},[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 Kj(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Wm(e){const{sendData:t}=vt(),[n,a]=l.useState({});return l.useEffect(()=>{const r=Kj(e);if(!r||!e.sessionId||!t){a({});return}const o=gs.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}),Un.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 Vj(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function Yj(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 Qj(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 Jj({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(!Vj(o))throw new Error(Yj(o));return}await Qj(e.sessionId,t,r)}function Om(e){const{ides:t,isP2PActive:n,p2pStates:a}=ys(),{sendCommand:r}=vt(),[o,i]=l.useState(null),[c,u]=l.useState(!1),[p,d]=l.useState(null),m=l.useRef(!1),h=l.useMemo(()=>Dg(t,e),[t,e]),g=!!h,k=l.useMemo(()=>h?h.prompt.promptId===o?null:h:null,[o,h]),f=l.useCallback(async b=>{if(!k||m.current)return;m.current=!0;const N=cp(k.prompt,b);u(!0),d(null);try{const j=(a==null?void 0:a[k.daemonId])==="connected"||n===!0;await Jj({promptSession:k,response:N,useP2PCommand:j,sendCommand:r}),i(k.prompt.promptId)}catch(j){throw d(j instanceof Error?j.message:String(j)),j}finally{u(!1),m.current=!1}},[n,a,k,r]),x=l.useCallback(()=>{k&&i(k.prompt.promptId)},[k]),w=l.useCallback(()=>{i(null),d(null)},[]);return{promptSession:k,hasActivePrompt:g,responseError:p,isSubmitting:c,submit:f,cancel:x,reopen:w}}function Um(e){return e instanceof Error?e.message:String(e||"")}function Xj(e){const t=Um(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 Zj(e){const t=Um(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function qm({conversation:e,mode:t,ides:n,sendDaemonCommand:a,setCliViewModeOverrides:r}){if(!e||!mt(e)||ut(e))return;const o=Zn(e);if(o===t)return;const i=e.sessionId;i&&r(c=>({...c,[i]:t}));try{await a(Bs(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Ms(e),mode:t})}catch(c){const u=Zj(c);i&&!u&&r(p=>{const d={...p};return o===t1(n,i)?delete d[i]:d[i]=o,d}),Xj(c)?console.warn(u?"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 e1(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(u=>kd(u,t)):r.childSessions,c=i!==r.childSessions;return o!==r||c?(n=!0,{...o,...c?{childSessions:i}:{}}):r});return n?a:e}function t1(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 s1({visibleConversations:e,clearedTabs:t,setClearedTabs:n,setActionLogs:a,isConversationMuted:r}){l.useEffect(()=>{Ap()},[]);const o=l.useMemo(()=>e.map(i=>({id:i.tabKey,name:hm(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 g0(o),l.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{n(u=>{const p=Date.now(),d={};for(const[m,h]of Object.entries(u))p-h<5e3&&(d[m]=h);return Object.keys(d).length===Object.keys(u).length?u:d})},5500);return()=>clearTimeout(c)},[t,n]),l.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;a(u=>{const p=u.filter(d=>d.timestamp>c).slice(-100);return p.length===u.length?u:p})},6e4);return()=>clearInterval(i)},[a]),null}function Sd(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 bn(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=Sd(t==null?void 0:t.receivedAt)||Sd(t==null?void 0:t.timestamp)||0;return Math.max(n,a)}function Yi(e,t=0){return bn(e)||e.lastUpdated||t||0}function Gm(e){return bn(e)||e.lastUpdated||0}function zm(e,t,n=Gm){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 Qi(e){var n;const t=ts(e.status,{activeModal:(n=e.modalButtons)!=null&&n.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function n1(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!Qi(e)&&!e.title.trim()}function a1(e){return e.length===0?null:[...e].sort((t,n)=>{const a=Number(Qi(n))-Number(Qi(t));if(a!==0)return a;const r=n.messages.length-t.messages.length;return r!==0?r:zm(t,n)})[0]||null}function xs(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=a1(r);return a?o&&n1(a)?o:a:o||n[0]||null}function r1(e){const t=e.filter(r=>r.type!=="adhdev-daemon"),n=new Set;for(const r of t){if(!Ei(r))continue;const o=wp(r);o&&n.add(o)}const a=new Map;for(const r of t){const o=Kw(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),u=c(i),p=c(r),d=p>u||p===u&&(r.timestamp||0)>(i.timestamp||0)?r:i;a.set(o,o1(d,d===r?i:r))}return Array.from(a.values())}function o1(e,t){const n=Ei(t),a=Ei(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,u=o==null?void 0:o.settings;return{...e,...i&&{ownerDaemonId:i},...c&&!e.ownerMachineName&&{ownerMachineName:c},...u&&!a&&{settings:{...u,...e.settings??{}}}}}function Uo(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 i1(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 Cd(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],n=t[t.length-1],a=n?i1(qn(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 l1(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||""),Cd(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||""),Cd(n.activeChat)].join(":"))].join("|")}function c1(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 d1(e,t){const n=new Map;for(const a of e){const r=t.get(a.routeId)||a;for(const o of Sa({routeId:a.routeId}))n.set(o,r);for(const o of Sa({providerSessionId:a.providerSessionId,sessionId:a.sessionId}))n.set(o,a.streamSource==="native"?r:a);for(const o of Sa({tabKey:a.tabKey}))n.set(o,a)}return n}function u1(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function p1(e){const t=u1(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=qn(t.content).slice(0,240);return`${e.messages.length}:${n}:${a}`}function m1({ides:e,connectionStates:t,clearedTabs:n}){const a=l.useMemo(()=>r1(e),[e]),r=l.useMemo(()=>pp(e),[e]),o=l.useMemo(()=>jm(e),[e]),i=l.useRef([]),c=l.useRef([]),u=l.useRef([]),p=l.useRef(new Map),d=l.useRef(new Map),m=l.useMemo(()=>{const j=new Map,v=[];for(const A of a){const{connectionState:M="new",machineName:I}=Nm(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),D=l1(A),P=p.current.get(A.id);if(P&&P.ide===A&&P.sourceSignature===D&&P.connectionState===M&&P.machineName===I){j.set(A.id,P),v.push(...P.conversations);continue}const T=Hl(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),H={ide:A,sourceSignature:D,connectionState:M,machineName:I,conversations:T};j.set(A.id,H),v.push(...T)}p.current=j;const y=new Map,C=A=>{const M=p1(A),I=d.current.get(A.tabKey);if(I&&I.signature===M)return y.set(A.tabKey,I),I.timestamp;const D={signature:M,timestamp:Gm(A)||(I==null?void 0:I.timestamp)||0};return y.set(A.tabKey,D),D.timestamp},S=[...v].sort((A,M)=>zm(A,M,C));return d.current=y,S},[a,t,o]),h=l.useMemo(()=>{const j=c1(m,n);return Uo(i.current,j)?i.current:(i.current=j,j)},[m,n]),g=l.useMemo(()=>{const j=new Map,v=Array.from(new Set(h.map(y=>y.routeId)));for(const y of v){const C=xs(h,y);C&&j.set(y,C)}return j},[h]),k=l.useMemo(()=>{const j=new Map;for(const v of h){const y=g.get(v.routeId),C=v.streamSource==="native"&&y?y:v;for(const S of Sa({providerSessionId:v.providerSessionId,sessionId:v.sessionId,tabKey:v.tabKey}))j.set(S,C)}return j},[h,g]),f=l.useMemo(()=>d1(h,g),[h,g]),x=l.useCallback(j=>{if(j)return k.get(j)},[k]),w=l.useCallback(j=>{if(j)return f.get(j)},[f]),b=l.useMemo(()=>{const j=h.filter(v=>!Js(v,r).surfaceHidden);return Uo(c.current,j)?c.current:(c.current=j,j)},[h,r]),N=l.useMemo(()=>{const j=b.map(v=>v.tabKey);return Uo(u.current,j)?u.current:(u.current=j,j)},[b]);return{chatIdes:a,conversations:h,visibleConversations:b,visibleTabKeys:N,resolveConversationBySessionId:x,resolveConversationByTarget:w}}function h1({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 u=new URLSearchParams(c);return u.delete("activeTab"),u},{replace:!0})},[a,t]);return{requestedDesktopTabKey:r,requestedMobileTabKey:o,consumeRequestedActiveTab:i}}function f1({ides:e,sendDaemonCommand:t,setToasts:n,resolveConversationByTarget:a}){l.useEffect(()=>{ft.setIdes(e)},[e]),l.useEffect(()=>{ft.setResolveAction((r,o,i)=>{t(r,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const r=ft.onToast(o=>{n(c=>c.some(p=>p.message===o.message&&o.timestamp-p.timestamp<3e3)?c:[...c.slice(-4),{id:o.id,message:o.message,type:o.type,timestamp:o.timestamp,targetKey:o.targetKey,actions:o.actions}]);const i=o.duration||5e3;setTimeout(()=>n(c=>c.filter(u=>u.id!==o.id)),i)});return()=>{r()}},[n]),l.useEffect(()=>{const r=dm.on("status_event",o=>{ft.handleRawEvent(o,"ws")});return()=>{r()}},[]),l.useEffect(()=>{var o;const r=i=>{var f;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 u=c.targetSessionId||c.targetKey||c.daemonId,p=a(u),d=(p==null?void 0:p.routeId)||c.daemonId;if(!d)return;const m=Number(c.buttonIndex),h=c.button||((f=p==null?void 0:p.modalButtons)==null?void 0:f[m])||"Approve",g=String(h).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),k=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(g);t(d,"resolve_action",{action:k?"approve":"reject",button:h,...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 b1="adhdev_dashboardLayout_v1",g1="adhdev_dashboardDockview_v1",x1="adhdev_dashboardDockviewHiddenRestore_v1",pa={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Ol(e,t){try{const n=localStorage.getItem(e);return n?JSON.parse(n):t}catch{return t}}function v1(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Km(e){return`${b1}:${e}`}function y1(e){const t=Km(e);return Ol(t,null)}function w1(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=Km(e);if(n){localStorage.removeItem(a);return}localStorage.setItem(a,JSON.stringify(t))}catch{}}function Vm(e){return`${g1}:${e}`}function k1(e){const t=Vm(e);return Ol(t,null)}function S1(e,t){try{const n=Vm(e);if(!t){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Ym(e){return`${x1}:${e}`}function C1(e){const t=Ym(e);return Ol(t,{})}function j1(e,t){try{const n=Ym(e);if(Object.keys(t).length===0){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function N1(){return{groupAssignments:[...pa.groupAssignments],focusedGroup:pa.focusedGroup,groupActiveTabIds:{...pa.groupActiveTabIds},groupTabOrders:{...pa.groupTabOrders},groupSizes:[...pa.groupSizes]}}function A1(e,t){return e?e.length===t.length&&e.every((n,a)=>n===t[a]):t.length===0}function M1(){const[e]=l.useState(()=>v1(typeof window<"u"?window.innerWidth:1280)),[t,n]=l.useState(()=>new Map),[a,r]=l.useState(0),[o,i]=l.useState({}),[c,u]=l.useState({}),[p,d]=l.useState([]),[m,h]=l.useState(()=>typeof window<"u"&&window.innerWidth<768),[g,k]=l.useState(!1),f=l.useCallback(()=>{if(g)return;const A=y1(e)??N1();n(new Map(A.groupAssignments)),r(A.focusedGroup),i(A.groupActiveTabIds),u(A.groupTabOrders),d(A.groupSizes),k(!0)},[g,e]);l.useEffect(()=>{g&&w1(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)"),M=I=>h(I.matches);return A.addEventListener("change",M),()=>A.removeEventListener("change",M)},[]);const x=l.useCallback(A=>{n(A)},[]),w=l.useCallback(A=>{r(A)},[]),b=l.useCallback(A=>{i(A)},[]),N=l.useCallback(A=>{u(A)},[]),j=l.useCallback(A=>{d(A)},[]),v=l.useCallback(A=>{w(A)},[w]),y=l.useCallback((A,M)=>{i(I=>(I[A]??null)===(M??null)?I:{...I,[A]:M})},[]),C=l.useCallback((A,M)=>{u(I=>{const D=I[A];return A1(D,M)?I:{...I,[A]:M}})},[]),S=l.useCallback((A,M)=>{const I=M.get(A)??0;return y(I,A),v(I),I},[v,y]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:x,focusedGroup:a,updateFocusedGroup:w,focusGroup:v,groupActiveTabIds:o,updateGroupActiveTabIds:b,setGroupActiveTab:y,groupTabOrders:c,updateGroupTabOrders:N,setGroupTabOrder:C,groupSizes:p,updateGroupSizes:j,isMobile:m,hasHydratedStoredLayout:g,hydrateStoredLayout:f,focusConversationTab:S}}function P1(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0],a=so(t);return typeof(n==null?void 0:n.id)=="string"&&a.includes(n.id)}function T1({urlActiveTab:e,conversations:t,resolveConversationBySessionId:n,normalizedGroupAssignments:a,hasHydratedStoredLayout:r,hydrateStoredLayout:o,focusConversationTab:i,setSearchParams:c,historyModalOpen:u,activeConv:p,isRefreshingHistory:d,ides:m,handleRefreshHistory:h}){const g=l.useRef(!1),k=l.useRef(!1),f=l.useRef(null),x=l.useRef(!1);l.useEffect(()=>{if(!e||g.current||t.length===0)return;if(!r){o();return}const w=n(e);w&&(i(w.tabKey,a),g.current=!0,k.current=!0,f.current!=null&&(window.clearTimeout(f.current),f.current=null),c(b=>{const N=new URLSearchParams(b);return N.delete("activeTab"),N},{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(f.current==null)return f.current=window.setTimeout(()=>{f.current=null,!(k.current||r)&&(o(),k.current=!0)},1500),()=>{f.current!=null&&(window.clearTimeout(f.current),f.current=null)}}},[e,t.length,r,o]),l.useEffect(()=>{if(!u){x.current=!1;return}if(!p||x.current||d)return;const w=m.find(b=>b.id===p.routeId);w&&(!w.chats||w.chats.length===0||P1(w.chats,p))&&(x.current=!0,h())},[u,p,d,m,h])}function qo(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=so(t);return typeof(n==null?void 0:n.id)=="string"&&a.includes(n.id)}function Qm({sendDaemonCommand:e,activeConv:t,chats:n,updateRouteChats:a,setToasts:r,setClearedTabs:o}){const[i,c]=l.useState(!1),[u,p]=l.useState(!1),d=l.useCallback(async k=>{try{await e("standalone","launch_ide",{ideType:k,enableCdp:!0})}catch(f){console.error("Launch failed",f)}},[e]),m=l.useCallback(async(k,f)=>{try{const x=k||(t==null?void 0:t.daemonId)||"",w=await e(x,"switch_chat",{id:f,sessionId:f,...un(t)}),b=w==null?void 0:w.result;if((w==null?void 0:w.success)===!0||b==="switched"||b==="switched-by-title")return;b===!1||b==="not_found"?Rn(r,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?Rn(r,`⚠️ Switch error: ${b}`):Rn(r,"⚠️ Session switch failed")}catch(x){console.error("Switch failed",x),Rn(r,`❌ Switch failed: ${x.message||"connection error"}`)}},[t,e,r]),h=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const k=pn(t);await e(k,"new_chat",{...un(t)}),xS(k,t.sessionId,so(t)[0]),o(f=>({...f,[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,f;if(!(!t||u)){p(!0);try{const x=pn(t),w=async()=>e(x,"list_chats",{forceExpand:!0,...un(t)});let b=await w(),N=(b==null?void 0:b.chats)||((k=b==null?void 0:b.result)==null?void 0:k.chats);qo(N,t)&&(await new Promise(j=>setTimeout(j,450)),b=await w(),N=(b==null?void 0:b.chats)||((f=b==null?void 0:b.result)==null?void 0:f.chats)),b!=null&&b.success&&Array.isArray(N)&&(a(t.routeId,N),qo(N,t)&&!qo(n,t)&&Rn(r,"⚠️ History dialog did not fully open — try once more"))}catch(x){console.error("Refresh history failed",x)}finally{p(!1)}}},[t,n,u,e,a,r]);return{isCreatingChat:i,isRefreshingHistory:u,handleLaunchIde:d,handleSwitchSession:m,handleNewChat:h,handleRefreshHistory:g}}function D1(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 I1(e,t){return e.length!==t.length?!1:e.every((n,a)=>n===t[a])}function jd(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 sr(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 u=r[c];typeof u=="number"&&u>0&&o.set(i,u)}return{assignments:o,groupCount:Math.max(1,a.length),mapping:r,usedGroups:a}}function Nd(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 L1(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 R1(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 Ad(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 Md(e){return Array(e).fill(100/e)}function E1({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:n,updateGroupActiveTabIds:a,updateGroupTabOrders:r,groupSizes:o,updateGroupSizes:i,isMobile:c,visibleConversations:u,visibleTabKeys:p}){const d=l.useRef(null),m=l.useMemo(()=>sr(e,p),[e,p]),h=m.assignments,g=l.useMemo(()=>c?1:m.groupCount,[m.groupCount,c]),k=g>1,f=l.useCallback((v,y)=>{t(C=>{const S=new Map(sr(C,p).assignments);return y===0?S.delete(v):S.set(v,y),S}),a(C=>({...C,[y]:v})),n(y)},[t,p,a,n]),x=l.useCallback(v=>{t(y=>{const C=sr(y,p).assignments,S=new Map;for(const[A,M]of C)M!==v&&(M>v?S.set(A,M-1):S.set(A,M));return S}),i(y=>{if(y.length<=1)return[];const C=[...y];C.splice(v,1);const S=C.reduce((A,M)=>A+M,0);return S>0?C.map(A=>A/S*100):[]}),n(0)},[t,p,i,n]),w=l.useCallback((v,y)=>{y.preventDefault();const C=d.current;if(!C)return;const S=y.clientX,A=C.offsetWidth,M=o.length===g?[...o]:Md(g),I=P=>{const H=(P.clientX-S)/A*100,L=[...M];L[v]=Math.max(15,M[v]+H),L[v+1]=Math.max(15,M[v+1]-H),i(L)},D=()=>{document.removeEventListener("mousemove",I),document.removeEventListener("mouseup",D),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",I),document.addEventListener("mouseup",D)},[o,g,i]),b=l.useCallback((v,y,C)=>{if(g>=4)return;const S=C==="left"?y:y+1;t(A=>{const M=sr(A,p).assignments,I=new Map;for(const D of u){const P=M.get(D.tabKey)??0,T=P>=S?P+1:P;T>0&&I.set(D.tabKey,T)}return S>0&&I.set(v,S),I}),i(A=>{const M=A.length===g?[...A]:Md(g),I=M[y]??100/g,D=Math.max(15,I/2),P=Math.max(15,I/2),T=[...M];T[y]=D,T.splice(S,0,P);const H=T.reduce((L,R)=>L+R,0);return T.map(L=>L/H*100)}),a(A=>{const M=Ad(A,S);return M[S]=v,M}),r(A=>{const M=Ad(A,S);return M[S]=[v],M}),n(S)},[g,t,p,u,i,a,r,n]);l.useEffect(()=>{D1(e,h)||t(h)},[e,h,t]),l.useEffect(()=>{const{mapping:v,usedGroups:y}=m;a(C=>{const S=Nd(C,v);return jd(C,S)?C:S}),r(C=>{const S=Nd(C,v);return jd(C,S)?C:S}),n(C=>{const S=c?0:L1(C,y,v);return C===S?C:S}),i(C=>{const S=c?[]:R1(C,y,m.groupCount);return I1(C,S)?C:S})},[m,c,a,r,n,i]);const N=l.useMemo(()=>{const v=Array.from({length:g},()=>[]);for(const y of u){const C=h.get(y.tabKey)??0,S=Math.min(C,g-1);v[S].push(y)}return v},[u,h,g]),j=l.useCallback(()=>{t(new Map),n(0)},[t,n]);return{containerRef:d,normalizedGroupAssignments:h,numGroups:g,isSplitMode:k,groupedConvs:N,moveTabToGroup:f,closeGroup:x,handleResizeStart:w,splitTabRelative:b,clearAllSplits:j}}function _1({ides:e,sendDaemonCommand:t}){const n="1.0.47",a=l.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:uo(m,qs(m,n))).sort((m,h)=>Number(ja(h,qs(h,n)))-Number(ja(m,qs(m,n)))),[n,e]),r=l.useMemo(()=>a.some(m=>ja(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),[u,p]=l.useState({}),d=l.useCallback(async m=>{var k,f;const h=e.find(x=>x.id===m);if(!h)return;p(x=>({...x,[m]:"upgrading"}));const g=po(h);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||(f=x==null?void 0:x.result)!=null&&f.success?p(w=>({...w,[m]:"done"})):p(w=>({...w,[m]:"error"}))}catch{p(x=>({...x,[m]:"error"}))}},[e,t]);return{versionMismatchDaemons:a,hasRequiredVersionDaemons:r,targetVersion:o,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:u,handleBannerUpgrade:d}}const Jm=80;function kr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function H1(e){return{...e,createdAt:kr(e.createdAt),updatedAt:kr(e.updatedAt,e.createdAt),lastEventAt:kr(e.lastEventAt,e.updatedAt||e.createdAt)}}function $1(e){const t=yp(e);return t==="unknown:"?e.id:t}function F1(e){return[e.type,vp(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function B1(e,t=Jm){const n=new Map;for(const a of e){if(a.deletedAt)continue;const r=$1(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 W1(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=to(r,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const u=kr(r.lastMessageAt||(o==null?void 0:o.lastUpdated)||r.lastUpdated,n),p=F1({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(H1({id:p,dedupKey:p,type:c,routeId:r.routeId,machineId:r.daemonId||r.routeId,sessionId:r.sessionId,providerSessionId:r.providerSessionId,tabKey:r.tabKey,title:Wp(r),preview:Tk(r),createdAt:u,updatedAt:u,lastEventAt:u}))}return B1(a)}function O1(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function U1(e){const{conversations:t,liveSessionInboxState:n,maxItems:a=Jm}=e,r=l.useMemo(()=>W1(t,n).slice(0,Math.max(0,a)),[t,n,a]),o=l.useMemo(()=>O1(r),[r]);return{notifications:r,unreadCount:o}}function q1({notifications:e,sendDaemonCommand:t}){const n=l.useCallback(o=>{const i=e.find(u=>u.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 Ul(...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 G1(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 ql(e,t=[]){if(e==="win32"){for(const n of t){if(typeof n!="string")continue;const a=G1(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 z1(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 K1(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function Gl(e,t,n){const a=await e(t,"file_list_browse",{path:n}),r=K1(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,d)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${d}`:p==="/"||p==="\\"?`${i}${d}`:`${p.replace(/[\\/]+$/,"")}${i}${d}`,u=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,d)=>p.name.localeCompare(d.name)):[];return{path:o,directories:u}}function Pd(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 Xm(e,t={}){const n=e==null?void 0:e.mcpConfig;if((n==null?void 0:n.mode)!=="manual")return null;const r=Pd(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:Pd(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"})}}function V1(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 Ea(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Zm(e){return no(e)||e.tabKey||e.routeId||null}function eh(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=xs(e.conversations,a)||e.conversations.find(i=>i.routeId===a);if(o!=null&&o.tabKey)return o.tabKey}return t||n||a||null}function Gs(e){return String(e||"").trim()}function th(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Gr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Y1(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function Q1(e,t){const n=Gs(e.providerSessionId),a=Gs(e.targetSessionId),r=t.find(o=>{const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(Gs).filter(Boolean);return!!(n&&i.includes(n)||a&&i.includes(a))});return r?r.tabKey:a||n||null}function J1(e,t,n){if(t.event!=="agent:generating_completed")return null;const a=th(t.daemonId);if(a&&a!==e.machineId)return null;const r=Gs(t.providerType);if(e.providerType&&r!==e.providerType)return null;const o=Gs(e.resumeSessionId),i=Gs(e.launchedSessionId),c=Gs(t.providerSessionId),u=Gs(t.targetSessionId);if(o&&o!==c&&o!==u||i&&i!==c&&i!==u)return null;const p=Gr(e.workspacePath);if(p){const d=Gr(t.workspaceName);if(d&&!Y1(d,p))return null}return Q1(t,n)}function Td(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function X1({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(u=>{o.current=u,r(u)},[]);return l.useEffect(()=>{if(!a)return;const u=Gr(a.workspacePath),p=e.find(m=>{var x,w,b,N;if(!m||m.type==="adhdev-daemon"||th(m.daemonId||m.id)!==a.machineId||(La(m)?"cli":Wn(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 j=String(a.launchedSessionId||"");return[m.providerSessionId,m.sessionId,m.instanceId,m.id].map(y=>String(y||"")).filter(Boolean).includes(j)}if(u){const j=Gr(m.workspace||m.runtimeWorkspaceLabel);return j?j===u:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((N=(b=(w=(x=m.activeChat)==null?void 0:x.messages)==null?void 0:w.at)==null?void 0:b.call(w,-1))==null?void 0:N.timestamp)||0)>=a.startedAt-5e3});if(!p)return;const d=eh({entrySessionId:p.sessionId,entryInstanceId:p.instanceId,entryRouteId:p.id,conversations:t});d&&(i(),n(d))},[i,t,e,n,a]),l.useEffect(()=>ft.onStatusEvent(u=>{const p=o.current;if(!p)return;const d=J1(p,u,t);d&&(i(),n(d))}),[i,t,n]),l.useEffect(()=>{if(!a)return;const u=window.setTimeout(()=>{r(p=>!p||p.startedAt!==a.startedAt?p:(o.current=null,null))},45e3);return()=>window.clearTimeout(u)},[a]),{trackPendingLaunch:c}}function Z1(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 eN(e,t,n){var i,c,u,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),(u=n==null?void 0:n.settings)!=null&&u.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 tN({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:n,activeConv:a,ides:r,setCliViewModeOverrides:o}){const i=Nl(),{launchCli:c}=Jr(),u=l.useCallback(async(x,w)=>Gl(e,x,w),[e]),p=l.useCallback(async(x,w)=>{if(!w.trim())return{ok:!1,error:"Choose a workspace path first."};try{const b=await e(x,"workspace_add",{path:w.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]),d=l.useCallback(async(x,w,b)=>{var N;try{const j={ideType:w,enableCdp:!0};(N=b==null?void 0:b.workspacePath)!=null&&N.trim()&&(j.workspace=b.workspacePath.trim());const v=await e(x,"launch_ide",j);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:w,workspacePath:(b==null?void 0:b.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(j){return{ok:!1,error:j instanceof Error?j.message:"Could not launch IDE"}}},[e,t]),m=l.useCallback(async(x,w,b,N)=>{const j=Date.now();try{const v=Z1(b,N),y=await c(x,v),C=(y==null?void 0:y.result)||y,S=(C==null?void 0:C.sessionId)||(C==null?void 0:C.id);return y!=null&&y.success&&S?(t({machineId:x,kind:w,providerType:b,workspacePath:(N==null?void 0:N.workspacePath)||null,resumeSessionId:(N==null?void 0:N.resumeSessionId)||null,launchedSessionId:S,startedAt:j}),{ok:!0}):y!=null&&y.success?(t({machineId:x,kind:w,providerType:b,workspacePath:(N==null?void 0:N.workspacePath)||null,resumeSessionId:(N==null?void 0:N.resumeSessionId)||null,startedAt:j}),{ok:!0}):{ok:!1,error:(y==null?void 0:y.error)||(C==null?void 0:C.error)||`Could not launch ${w.toUpperCase()} session`,code:(y==null?void 0:y.code)||(C==null?void 0:C.code)||void 0}}catch(v){return Td(v)?(t({machineId:x,kind:w,providerType:b,workspacePath:(N==null?void 0:N.workspacePath)||null,resumeSessionId:(N==null?void 0:N.resumeSessionId)||null,startedAt:j}),{ok:!0}):{ok:!1,error:v instanceof Error?v.message:`Could not launch ${w.toUpperCase()} session`}}},[c,e,t]),h=l.useCallback(async x=>{var w;if(i!=null&&i.listMeshes)return i.listMeshes(x);if(!x)return[];try{const b=await e(x,"list_meshes",{}),N=(b==null?void 0:b.result)??b;if((N==null?void 0:N.success)===!1)throw new Error((N==null?void 0:N.error)||"Could not load meshes");return(Array.isArray(N==null?void 0:N.meshes)?N.meshes:Array.isArray((w=N==null?void 0:N.result)==null?void 0:w.meshes)?N.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,w,b,N)=>{if(!w.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(x,w,b,N);const j=Date.now();try{const v=eN(w,b,N),y=await e(x,"launch_mesh_coordinator",v),C=(y==null?void 0:y.result)??y;if((C==null?void 0:C.success)===!1||(y==null?void 0:y.success)===!1){const A=String((C==null?void 0:C.code)||(y==null?void 0:y.code)||""),M=V1((C==null?void 0:C.meshCoordinatorSetup)||(C==null?void 0:C.manualSetup)||(y==null?void 0:y.meshCoordinatorSetup)||(y==null?void 0:y.manualSetup));return{ok:!1,error:(C==null?void 0:C.error)||(y==null?void 0:y.error)||"Could not launch mesh coordinator",code:A||void 0,manualSetup:M}}const S=(C==null?void 0:C.sessionId)||(C==null?void 0:C.id);return S?n(S):t({machineId:x,kind:"cli",providerType:(C==null?void 0:C.cliType)||b.trim()||void 0,workspacePath:(C==null?void 0:C.workspace)||null,startedAt:j}),{ok:!0}}catch(v){return Td(v)?(t({machineId:x,kind:"cli",providerType:b.trim()||void 0,startedAt:j}),{ok:!0}):{ok:!1,error:v instanceof Error?v.message:"Could not launch mesh coordinator"}}},[i,n,e,t]),k=l.useCallback(async(x,w)=>{if(!x||!w)return[];try{const b=await e(x,"list_saved_sessions",{providerType:w,kind:"cli",limit:30}),N=(b==null?void 0:b.result)??b;return Array.isArray(N==null?void 0:N.sessions)?N.sessions:[]}catch(b){return console.error("List saved sessions failed",b),[]}},[e]),f=l.useCallback(async x=>{await qm({conversation:a,mode:x,ides:r,sendDaemonCommand:e,setCliViewModeOverrides:o})},[a,r,e,o]);return{handleBrowseMachineDirectory:u,handleSaveMachineWorkspace:p,handleLaunchMachineIde:d,handleLaunchMachineProvider:m,handleListMachineMeshes:h,handleLaunchMeshCoordinator:g,handleListMachineSavedSessions:k,setActiveCliViewMode:f}}function sN(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 nN(e,t,n=Date.now()){return!e||!sN(t)?null:{tabKey:e,nonce:n}}function aN({isMobile:e,conversations:t,visibleConversations:n,groupActiveTabIds:a,focusedGroup:r,groupedConvs:o,setSearchParams:i}){const[c,u]=l.useState(null),[p,d]=l.useState(null),m=l.useMemo(()=>{var x,w;if(!e){if(c){const b=t.find(N=>N.tabKey===c);if(b)return b}return n[0]}const f=a[r];if(f){const b=t.find(N=>N.tabKey===f);if(b)return b}return((x=o[r])==null?void 0:x[0])||((w=o[0])==null?void 0:w[0])},[t,c,r,a,o,e,n]),h=l.useCallback(f=>{u(f)},[]),g=l.useCallback(f=>{u(f.tabKey),i(x=>{const w=new URLSearchParams(x),b=Ik(f);return b?w.set("activeTab",b):w.delete("activeTab"),w},{replace:!0})},[i]),k=l.useCallback((f,x)=>{const w=nN(f,x);w&&d(w)},[]);return{activeConv:m,openDesktopConversation:g,requestScrollToBottom:k,scrollToBottomRequest:p,setDesktopActiveTab:h}}function rN(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 oN(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 iN({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),u=l.useRef(null);l.useEffect(()=>{const p=()=>{i.current&&(clearTimeout(i.current),i.current=null),c.current&&(clearTimeout(c.current),c.current=null),u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null),o.current=null};if(t){p(),r.current=null;return}if(!(e!=null&&e.sessionId)){p(),r.current=null;return}const d=Js(e,n),m=oN({tabKey:e.tabKey,historySessionId:no(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:bn(e),liveState:d}),h=m.autoReadKey,g=rN({autoReadKey:h,shouldMarkSeen:m.shouldMarkSeen,completedKey:r.current,pendingKey:o.current});if(!m.shouldMarkSeen){g.shouldCancelPending&&p(),r.current=h;return}if(!g.shouldSchedule)return;g.shouldCancelPending&&p();const k=()=>{if(document.visibilityState!=="visible"||r.current===h)return;r.current=h,o.current=null,i.current=null,c.current=null,u.current&&(document.removeEventListener("visibilitychange",u.current),u.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)};u.current=x,document.addEventListener("visibilitychange",x);return}const f=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(k,800),u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null))};u.current=f,document.addEventListener("visibilitychange",f)},[e,t,n,a]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current),c.current&&clearTimeout(c.current),u.current&&document.removeEventListener("visibilitychange",u.current)},[])}function Go(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 lN({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:n,ides:a,sendDaemonCommand:r,updateRouteChats:o,setToasts:i,setClearedTabs:c,setSearchParams:u}){var U;const{launchCli:p}=Jr(),[d,m]=l.useState(!1),[h,g]=l.useState([]),[k,f]=l.useState(()=>Gt()),[x,w]=l.useState(!1),[b,N]=l.useState(null),j=l.useRef(null),v=l.useMemo(()=>n||t||e,[e,n,t]),y=!!v&&mt(v)&&!ut(v),C=l.useMemo(()=>{if(!v||!y)return null;const E=v.daemonId||v.routeId||"",$=Ms(v),_=Go(v);return`${E}:${$}:${v.providerSessionId||""}:${_}`},[v,y]),S=l.useMemo(()=>!v||!y?"":Go(v),[v,y]),{isCreatingChat:A,isRefreshingHistory:M,handleSwitchSession:I,handleNewChat:D,handleRefreshHistory:P}=Qm({sendDaemonCommand:r,activeConv:v,chats:(U=a.find(E=>E.id===(v==null?void 0:v.routeId)))==null?void 0:U.chats,updateRouteChats:o,setToasts:i,setClearedTabs:c}),T=l.useCallback(()=>{m(!0)},[]),H=l.useCallback(()=>{m(!1)},[]),L=l.useCallback(async()=>{if(!(!v||!y||x)){w(!0);try{const E=v.daemonId||v.routeId,$=Ms(v),_=Go(v),q=await r(E,"list_saved_sessions",{agentType:$,providerType:$,kind:"cli",limit:50,...v.providerSessionId?{providerSessionId:v.providerSessionId}:{},..._?{workspace:_}:{}}),B=(q==null?void 0:q.result)??q;g(Array.isArray(B==null?void 0:B.sessions)?B.sessions:[])}catch(E){console.error("Refresh saved sessions failed",E),g([])}finally{w(!1)}}},[v,x,y,r]);l.useEffect(()=>{if(!d){j.current=null;return}if(!y){j.current=null,g([]),w(!1);return}!C||x||j.current!==C&&(j.current=C,L())},[L,d,x,y,C]);const R=l.useCallback(async E=>{if(!v||!y||!E.providerSessionId||!E.workspace)return;const $=v.daemonId||v.routeId,_=Ms(v);try{N(E.providerSessionId);const q=await p($,{cliType:_,dir:E.workspace,resumeSessionId:E.providerSessionId,initialModel:jp(E.summaryMetadata,"model",{preferShortValue:!0})||void 0}),B=(q==null?void 0:q.result)??q,W=typeof(B==null?void 0:B.sessionId)=="string"?B.sessionId:typeof(B==null?void 0:B.id)=="string"?B.id:"";W&&u(V=>{const ne=new URLSearchParams(V);return ne.set("activeTab",W),ne},{replace:!0}),H()}catch(q){console.error("Resume saved session failed",q)}finally{N(null)}},[H,v,y,r,u]);return{historyModalOpen:d,openHistoryModal:T,closeHistoryModal:H,historyTargetConv:v,isSavedSessionHistoryTarget:y,isHistoryCreatingChat:A,isHistoryRefreshingHistory:M,handleHistorySwitchSession:I,handleHistoryNewChat:D,handleHistoryRefresh:P,savedHistorySessions:h,savedHistoryFilters:k,setSavedHistoryFilters:f,missingWorkspaceResumePath:S,isSavedHistoryLoading:x,resumingSavedHistorySessionId:b,handleRefreshSavedHistory:L,handleResumeSavedHistorySession:R}}function cN({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c}){const[u,p]=l.useState(null),[d,m]=l.useState(null),h=l.useMemo(()=>{if(e||!a)return null;const w=c(a);return w&&!mt(w)&&!ut(w)?w:null},[e,a,c]),g=l.useMemo(()=>{const w=u==null?void 0:u.routeId;if(!w)return null;const b=u!=null&&u.tabKey?o.find(N=>N.tabKey===u.tabKey):r?o.find(N=>N.tabKey===r):null;return(b==null?void 0:b.routeId)===w?b:xs(o,w)},[o,u,r]),k=l.useMemo(()=>{if(g)return i.find(w=>w.id===g.routeId)},[i,g]);l.useEffect(()=>{h&&(p({routeId:h.routeId,tabKey:Oc(h)}),m(h),n({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,n,h]);const f=l.useCallback(w=>{w&&(p({routeId:w.routeId,tabKey:Oc(w)}),m(w))},[]),x=l.useCallback(()=>{p(null),m(null)},[]);return{remoteDialogConv:g,remoteDialogIdeEntry:k,remoteDialogActiveConv:d,setRemoteDialogActiveConv:m,openRemoteDialog:f,closeRemoteDialog:x}}function dN({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c,activeConv:u,sendDaemonCommand:p}){const{remoteDialogConv:d,remoteDialogIdeEntry:m,remoteDialogActiveConv:h,setRemoteDialogActiveConv:g,openRemoteDialog:k,closeRemoteDialog:f}=cN({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c}),[x,w]=l.useState(!1),[b,N]=l.useState(null),j=l.useCallback(async C=>{const S=C||u;!S||!mt(S)&&!ut(S)||(N(S),w(!0))},[u]),v=l.useCallback(()=>{w(!1),N(null)},[]),y=l.useCallback(async C=>{const S=b||u;if(!S||!mt(S)&&!ut(S)){v();return}w(!1);try{const A=Ms(S),M=S.routeId||S.daemonId||"";await p(M,"stop_cli",{cliType:A,targetSessionId:S.sessionId,mode:C,...oo(S)})}catch(A){console.error("Stop CLI failed:",A)}finally{N(null)}},[u,v,b,p]);return{remoteDialogConv:d,remoteDialogIdeEntry:m,remoteDialogActiveConv:h,setRemoteDialogActiveConv:g,openRemoteDialog:k,closeRemoteDialog:f,cliStopDialogOpen:x,cliStopTargetConv:b,requestCliStop:j,cancelCliStop:v,confirmCliStop:y}}function zo(e,t=!0){return(e??!0)&&t}const zl=l.memo(function({activeConv:t,clearToken:n,isCliTerminal:a,ideEntry:r,terminalRef:o,handleModalButton:i,handleRelaunch:c,handleSendChat:u,handleForceSendChat:p,isSendingChat:d,sendFeedbackMessage:m=null,handleFocusAgent:h,isFocusingAgent:g,actionLogs:k,userName:f,scrollToBottomRequestNonce:x,isInputActive:w=!0,isVisible:b=!0}){const N=a,j=!a,v=zo(b,N),y=zo(b,j),C=zo(b),S=Wm(t),A=S.status||S.modalMessage||S.modalButtons?{...t,...S.status?{status:S.status}:{},...S.modalMessage!==void 0?{modalMessage:S.modalMessage}:{},...S.modalButtons!==void 0?{modalButtons:S.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(mp,{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(xn,{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:N?"visible":"hidden",pointerEvents:N?"auto":"none"},children:s.jsx(mC,{activeConv:A,clearToken:n,terminalRef:o,handleSendChat:u,isSendingChat:d,sendFeedbackMessage:m,isVisible:v,isInputActive:w&&v})}),s.jsx("div",{"aria-hidden":a,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:j?"visible":"hidden",pointerEvents:j?"auto":"none"},children:s.jsx(Oi,{activeConv:A,ideEntry:r,handleSendChat:u,isSendingChat:d,sendFeedbackMessage:m,handleFocusAgent:h,isFocusingAgent:g,actionLogs:k,userName:f,scrollToBottomRequestNonce:x,isInputActive:w&&y,isVisible:y})})]}):s.jsx(Oi,{activeConv:A,ideEntry:r,handleSendChat:u,handleForceSendChat:p,isSendingChat:d,sendFeedbackMessage:m,handleFocusAgent:h,isFocusingAgent:g,actionLogs:k,userName:f,scrollToBottomRequestNonce:x,isInputActive:w&&C,isVisible:C})]})},(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 uN({conversation:e,className:t="",onOpenNativeConversation:n,onOpenMachine:a,interactive:r=!0,meshOnly:o=!1}){var j,v,y;const{t:i}=Ce("common"),c=Jn(),u=Bs(e),p=o?null:Bp(e),d=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),m=!o&&e.streamSource==="agent-stream"&&!!e.agentName,h=!o&&!m&&(e.transport==="pty"||e.transport==="acp"),g=zn(e),k=Dk(e),f=(j=e.settings)==null?void 0:j.meshNodeFor,x=e.meshQueueStats,w=((v=e.coordinator)==null?void 0:v.meshId)||((y=e.settings)==null?void 0:y.meshCoordinatorFor),b=l.useCallback(()=>{if(a){a();return}u&&c("/dashboard",{state:{openMachineId:u}})},[u,c,a]),N=l.useCallback(()=>{if(n){n();return}const C=Zm(e);C&&c(Ea(C))},[e,c,n]);return!d&&!m&&!h&&!p&&!f&&!x?null:s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[d&&(r?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:N,title:k,children:[s.jsx(ws,{size:12}),s.jsx("span",{children:k})]}):s.jsxs("span",{className:"conversation-meta-chip",title:k,children:[s.jsx(ws,{size:12}),s.jsx("span",{children:k})]})),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(Ta,{size:12}),s.jsx("span",{children:g})]}),h&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(Ta,{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(Ys,{size:12}),s.jsx("span",{children:p})]}):s.jsxs("span",{className:"conversation-meta-chip",title:p,children:[s.jsx(Ys,{size:12}),s.jsx("span",{children:p})]})),f&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(Ys,{size:12}),s.jsx("span",{children:i("dashboard.metaChips.meshNode")})]}),w&&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(Hb,{size:12}),s.jsxs("span",{children:[x.pending," Pending"]})]})]})}function pN({selectedConversation:e,isAcp:t,isStandalone:n,selectedIdeEntry:a,actionLogs:r,userName:o,isSendingChat:i,sendFeedbackMessage:c=null,isFocusingAgent:u,onBack:p,onOpenNativeConversation:d,onOpenMachine:m,onOpenHistory:h,onOpenRemote:g,onOpenMeshGraph:k,onStopCli:f,cliViewMode:x,onSetCliViewMode:w,handleSendChat:b,handleForceSendChat:N,handleFocusAgent:j,handleModalButton:v,handleRelaunch:y}){var D,P;const C=l.useRef(null),S=mt(e)&&!t,A=S&&x==="terminal",M=!!e.daemonId&&!!((D=e.coordinator)!=null&&D.meshId||(P=e.settings)!=null&&P.meshCoordinatorFor),I=n?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`flex items-center justify-between gap-3 ${I} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:p,type:"button","aria-label":"Back",children:s.jsx(ml,{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(uN,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>d(e),onOpenMachine:()=>m(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[S&&x&&s.jsx(gm,{mode:x,onChange:w,compact:!0}),S&&f&&s.jsx("button",{onClick:()=>{f(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(It,{size:14})}),M&&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(ns,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>h(e),type:"button",children:s.jsx(fl,{size:14})}),!t&&!S&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",children:s.jsx(ws,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(zl,{activeConv:e,clearToken:0,isCliTerminal:A,ideEntry:a,terminalRef:C,handleModalButton:v,handleRelaunch:y,handleSendChat:b,handleForceSendChat:N,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:j,isFocusingAgent:u,actionLogs:r,userName:o})})]})}const Ko={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 mN(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function sh(){const[e,t]=l.useState("unix"),[n,a]=l.useState("powershell"),[r,o]=l.useState(!1),i=e==="unix"?"unix":n;l.useEffect(()=>{t(mN())},[]);const c=l.useCallback(()=>{navigator.clipboard.writeText(Ko[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:Ko[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:Ko[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.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 nh({section:e,onSectionChange:t}){const n=[{key:"machines",label:"Machines",icon:ws},{key:"chats",label:"Chats",icon:Cn}];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:n.map(({key:a,label:r,icon:o})=>{const i=e===a;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 ${i?"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:i?{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(a),type:"button","aria-pressed":i,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${i?"text-accent-primary":"bg-transparent text-current"}`,style:i?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:s.jsx(o,{size:15})}),s.jsx("span",{children:r})]},a)})})})}function nr({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 Tn({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 rn({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 hN({conversation:e,onCancel:t,onConfirm:n}){const{t:a}=Ce(),r=kt(e);return s.jsx(Kt,{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 ar({item:e,type:t,getAvatarText:n,onOpenConversation:a,onRequestHideConversation:r,onRequestStopCli:o,onOpenMeshGraph:i,onCollectChatDebugBundle:c,isMuted:u,onToggleMute:p}){const{t:d}=Ce(),m=t==="needs_attention"||t==="task_complete",h=t==="working",g=t==="earlier",k=t==="task_complete",{isReconnecting:f,isConnecting:x}=jn(e.conversation),w=kt(e.conversation),b=Kn(e.conversation),N=mm(e.conversation,{requiresAction:t==="needs_attention"}),j=m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":h?"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":h?"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",C=g?"text-text-muted":"text-text-secondary",S=g?"text-text-secondary opacity-80":"text-text-muted",A=g?"text-text-muted opacity-80":"text-text-muted",M=!h&&!k,I=um(e.conversation),D="text-[color:var(--status-warning)]",P=T=>{if(!c)return;T.preventDefault(),T.stopPropagation();const H=c==null?void 0:c(e.conversation);Promise.resolve(H).catch(L=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",L)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${j}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[m||h?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(w)}),I&&i&&s.jsx("button",{type:"button",className:"mobile-inbox-mesh-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:T=>{T.preventDefault(),T.stopPropagation(),i(e.conversation)},"aria-label":d("mobileInbox.openMeshGraphFor",{title:w}),title:d("mobileInbox.openLiveMeshGraph"),children:s.jsx(ns,{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:P,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:w})}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${C}`,children:[s.jsx("span",{className:"truncate",children:b}),s.jsx(Hr,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),f?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${D} animate-pulse`,children:d("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:d("mobileInbox.connectingItem")})]}):N==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:D,children:d("mobileInbox.actionNeeded")})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${S}`,children:e.preview})]}),s.jsxs("div",{className:"mobile-inbox-corner-actions absolute top-3 right-3 flex items-center gap-1.5",children:[M&&s.jsx("span",{className:`mr-0.5 text-[11px] font-medium shrink-0 ${A}`,children:up(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:d("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 ${u?"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:T=>{T.preventDefault(),T.stopPropagation(),p()},"aria-label":u?d("mobileInbox.unmute",{title:w}):d("mobileInbox.mute",{title:w}),title:d(u?"mobileInbox.mutedTitle":"mobileInbox.muteNotifications"),children:u?s.jsx(Zu,{size:13}):s.jsx(Xn,{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:T=>{T.preventDefault(),T.stopPropagation(),r()},"aria-label":d("mobileInbox.hideConversationAria",{title:w}),title:d("mobileInbox.hideConversationTitle"),children:s.jsx(bl,{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:T=>{T.preventDefault(),T.stopPropagation(),o()},"aria-label":d("mobileInbox.stopSessionAria",{title:w}),title:d("mobileInbox.stopSessionTitle"),children:s.jsx(It,{size:13})})]})]})},e.conversation.tabKey)}function rr({size:e=32}){return s.jsx("div",{className:"flex flex-col items-center gap-2.5",children:s.jsx("div",{className:"rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light",style:{width:e,height:e}})})}function Dd({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 fN({section:e,attentionItems:t,unreadItems:n,workingItems:a,completedItems:r,hiddenConversations:o,machineCards:i,getAvatarText:c,actionLogs:u,sendDaemonCommand:p,onOpenConversation:d,onShowAllHidden:m,onHideConversation:h,onOpenMeshGraph:g,onStopCli:k,onOpenNewSession:f,onOpenMachine:x,onOpenSettings:w,onSectionChange:b,wsStatus:N="connected",initialDataLoaded:j=!0,conversationsLoaded:v,isStandalone:y=!1,onCollectChatDebugBundle:C,isConversationMuted:S,onToggleMuteConversation:A}){const{t:M}=Ce(),[I,D]=l.useState(null),P=N==="disconnected"||N==="reconnecting"||N==="offline"||N==="auth_failed",T=!P&&!j,H=!P&&!(v??j),L=i.length>0,R=t.length>0||n.length>0||a.length>0||r.length>0,U=M(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),E=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))]",_=l.useCallback(async W=>{const V=pn(W);if(!V)return;const ne=Array.isArray(W.messages)?W.messages:[],ae=Kp({activeConv:W,visibleMessages:ne,actionLogs:u,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:ne.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),he=await p(V,"get_chat_debug_bundle",{...un(W),delivery:"daemon_file",frontendSnapshot:ae}),Z=Ca(he),z=Qp(Z),X=await Yp(z);X==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),ft.showToast(Vp(Z,{locatorCopyStatus:X}),X==="failed"?"warning":"success")},[u,p]),q=C||_,B=l.useCallback(()=>{I&&(h==null||h(I),D(null))},[I,h]);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 ${E}`,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:U}),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(Xn,{size:13}),s.jsx("span",{children:t.length+n.length})]}),s.jsx("button",{onClick:w,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(Xr,{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:P?s.jsx(rn,{icon:s.jsx(rr,{}),title:M(N==="offline"?"mobileInbox.networkOffline":N==="auth_failed"?"mobileInbox.sessionExpired":"mobileInbox.reconnecting"),subtitle:M(N==="offline"?"mobileInbox.waitingForNetwork":N==="auth_failed"?"mobileInbox.pleaseLogInAgain":"mobileInbox.restoringConnection")}):T?s.jsx(rn,{icon:s.jsx(rr,{}),title:M("mobileInbox.loading"),subtitle:M("mobileInbox.loadingSubtitle")}):i.length===0?s.jsx(rn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:M(y?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:M(y?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!y&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(sh,{})})}):s.jsx(Tn,{children:i.map((W,V)=>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] ${V>0?"border-t border-border-subtle/70":""}`,onClick:()=>x(W.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(W.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:W.label}),s.jsxs("span",{className:"flex items-center gap-2 text-[11px] font-medium text-text-muted shrink-0",children:[s.jsx(Dd,{count:W.generatingCount,label:M("mobileInbox.generatingCount",{count:W.generatingCount})}),W.unread>0?s.jsx("span",{className:"text-accent-primary",children:M("mobileInbox.newCount",{count:W.unread})}):W.total>0?M("mobileInbox.chatCount",{count:W.total}):M("mobileInbox.idle")]})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:W.subtitle}),W.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[M("mobileInbox.chatCount",{count:W.total}),W.unread>0?M("mobileInbox.unreadSuffix",{count:W.unread}):"",W.generatingCount>0?M("mobileInbox.collapsedGeneratingSuffix",{count:W.generatingCount}):""]}):W.generatingCount>0?s.jsx("div",{className:"text-[13px] text-accent-primary mt-0.5 font-medium",children:M("mobileInbox.generatingCount",{count:W.generatingCount})}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:M("mobileInbox.noActiveChats")})]})]},W.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(nr,{title:M("mobileInbox.needsAttention"),className:"mb-0"}),s.jsx(Tn,{children:t.map((W,V)=>s.jsx("div",{className:V>0?"border-t border-border-subtle/70":"",children:s.jsx(ar,{item:W,type:"needs_attention",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:h?()=>D(W.conversation):void 0,onRequestStopCli:k?()=>k(W.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:q,isMuted:S==null?void 0:S(W.conversation),onToggleMute:A?()=>A(W.conversation):void 0})},W.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(nr,{title:M("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),s.jsx(Tn,{children:n.map((W,V)=>s.jsx("div",{className:V>0?"border-t border-border-subtle/70":"",children:s.jsx(ar,{item:W,type:"task_complete",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:h?()=>D(W.conversation):void 0,onRequestStopCli:k?()=>k(W.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:q,isMuted:S==null?void 0:S(W.conversation),onToggleMute:A?()=>A(W.conversation):void 0})},W.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(nr,{title:M("mobileInbox.workingNow"),className:"mb-0 mt-2"}),s.jsx(Tn,{children:a.map((W,V)=>s.jsx("div",{className:V>0?"border-t border-border-subtle/70":"",children:s.jsx(ar,{item:W,type:"working",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:h?()=>D(W.conversation):void 0,onRequestStopCli:k?()=>k(W.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:q,isMuted:S==null?void 0:S(W.conversation),onToggleMute:A?()=>A(W.conversation):void 0})},W.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(nr,{title:M("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),r.length>0?s.jsx(Tn,{children:r.map((W,V)=>s.jsx("div",{className:V>0?"border-t border-border-subtle/70":"",children:s.jsx(ar,{item:W,type:"earlier",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:h?()=>D(W.conversation):void 0,onRequestStopCli:k?()=>k(W.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:q,isMuted:S==null?void 0:S(W.conversation),onToggleMute:A?()=>A(W.conversation):void 0})},W.conversation.tabKey))}):R?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:M("mobileInbox.allCaughtUp")}):P?s.jsx(rn,{icon:s.jsx(rr,{size:28}),title:M("mobileInbox.connecting"),subtitle:M("mobileInbox.connectingSubtitle")}):H?s.jsx(rn,{icon:s.jsx(rr,{size:28}),title:M("mobileInbox.loading"),subtitle:M("mobileInbox.loadingSubtitle")}):L?s.jsx(rn,{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(Cn,{size:20})}),title:M("mobileInbox.noConversations"),subtitle:M("paneGroup.newSessionDescription"),children:f&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:f,"aria-label":M("paneGroup.newSession"),title:M("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:M("paneGroup.newSession")})]})}):s.jsx(rn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:M("mobileInbox.noMachinesConnected"),subtitle:M("mobileInbox.noMachinesSubtitle")})]}),e==="chats"&&o.length>0&&(()=>{const W=Hg(o);return s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(Tn,{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:M("mobileInbox.hiddenTabs")}),s.jsx(Dd,{count:W,label:M("mobileInbox.generatingCount",{count:W})})]}),s.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[M("mobileInbox.collapsedCount",{count:o.length}),W>0?M("mobileInbox.collapsedGeneratingSuffix",{count:W}):""]})]}),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:M("mobileInbox.restoreAll")})]})})})})()]}),e==="chats"&&f&&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:f,"aria-label":M("paneGroup.newSession"),title:M("paneGroup.newSession"),children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),I&&s.jsx(hN,{conversation:I,onCancel:()=>D(null),onConfirm:B}),s.jsx(nh,{section:e,onSectionChange:b})]})}function bN(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 ah(e){const t=[e.workspace||"Workspace unknown"],n=vn(e.summaryMetadata);n&&t.push(n),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const a=bN(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:a?`Updated ${a}`:"",preview:(e.preview||"").trim()}}function Kl({title:e,description:t,currentPath:n,directories:a,busy:r=!1,error:o="",confirmLabel:i="Use this folder",onClose:c,onNavigate:u,onConfirm:p}){const[d,m]=l.useState(n),{t:h}=Ce("common");l.useEffect(()=>{m(n)},[n]);const g=z1(n),k=d.trim();return s.jsx(Kt,{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(It,{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||u(g)},disabled:!g||r,children:[s.jsx(ml,{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:h("machine.workspaceBrowse.currentFolder")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:d,onChange:f=>m(f.target.value),onKeyDown:f=>{f.key!=="Enter"||!k||r||(f.preventDefault(),u(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||u(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(f=>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:()=>u(f.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(Gn,{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:f.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:f.path})]})]},f.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 mo({title:e,description:t,details:n,workspaceOptions:a,selectedWorkspaceKey:r,onWorkspaceChange:o,confirmLabel:i,busyLabel:c,busy:u=!1,showArgsInput:p,argsValue:d,onArgsChange:m,showModelInput:h,modelValue:g,onModelChange:k,historyProviderNode:f,onConfirm:x,onCancel:w}){const{t:b}=Ce("common"),N=i??b("machine.launchConfirm.launch"),j=c??b("machine.launchConfirm.launching"),v=a==null?void 0:a.find(C=>C.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:w,"aria-label":b("machine.launchConfirm.closeAria"),children:s.jsx(It,{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:C=>o(C.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:u,children:a.map(C=>s.jsx("option",{value:C.key,children:C.label},C.key))}),(v==null?void 0:v.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:v.description})]}),f,n.map(C=>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:C.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:C.value})]},`${C.label}:${C.value}`)),h&&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:C=>k(C.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:u})]}),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:d||"",onChange:C=>m(C.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:u})]})]}),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:w,disabled:u,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:u,children:[s.jsx(Xu,{size:14}),u?j:N]})]})]})});return typeof document>"u"?y:Fs.createPortal(y,document.body)}function Id(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function rh(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 d of t.workspaces||[])c.push({key:`saved:${d.id}`,label:`${d.id===t.defaultWorkspaceId?"⭐ ":""}${Id(d.path,d.label)}`,description:d.path,workspaceId:d.id,workspacePath:d.path});const u=(n==null?void 0:n.trim())||"",p=u?(t.workspaces||[]).find(d=>d.path===u):null;if(u&&!p&&c.push({key:`custom:${u}`,label:Id(u),description:u,workspaceId:null,workspacePath:u}),a){const d=`saved:${a}`;if(c.some(m=>m.key===d))return{options:c,selectedKey:d}}return p?{options:c,selectedKey:`saved:${p.id}`}:u?{options:c,selectedKey:`custom:${u}`}:{options:c,selectedKey:"__home__"}}function gN(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function xN(e){return[gN(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function vN(e){return e.lastLaunchedAt?eo(e.lastLaunchedAt):""}function oh(e){return{metaText:xN(e),updatedLabel:vN(e)}}function Vo(e,t,n){return e?"ide":t>0?"cli":n>0?"acp":null}function yN({selectedMachineEntry:e,cliProviders:t,acpProviders:n,machineAction:a,onBrowseDirectory:r,onListSavedSessions:o}){var ce,Ee,Fe,et;const i=ea(),[c,u]=l.useState(!1),p=(((ce=e.detectedIdes)==null?void 0:ce.length)||0)>0,d=l.useMemo(()=>(e.workspaces||[]).map(Ae=>({id:Ae.id,path:Ae.path,label:Ae.label})),[e]),m=e.defaultWorkspaceId||null,[h,g]=l.useState(m||((Ee=d[0])==null?void 0:Ee.id)||""),[k,f]=l.useState(""),[x,w]=l.useState(""),[b,N]=l.useState([]),[j,v]=l.useState(!1),[y,C]=l.useState(""),[S,A]=l.useState(!1),[M,I]=l.useState(Vo(p,t.length,n.length)),D=l.useRef(null),[P,T]=l.useState(null),H=l.useRef("__home__"),[L,R]=l.useState("__home__"),[U,E]=l.useState(""),[$,_]=l.useState(""),[q,B]=l.useState(""),[W,V]=l.useState([]),[ne,ae]=l.useState(()=>Gt().textQuery),[he,Z]=l.useState(()=>Gt().workspaceQuery),[z,X]=l.useState(()=>Gt().modelQuery),[O,Q]=l.useState(()=>Gt().resumableOnly),[ke,Se]=l.useState(()=>Gt().sortMode),[ve,xe]=l.useState(!1),[Y,G]=l.useState(!1),te=l.useRef(null),me=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const K=h==="__custom__"?k.trim():((Fe=d.find(Ae=>Ae.id===h))==null?void 0:Fe.path)||"",be=h==="__custom__"&&!!K&&a.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(a.message),re=h!=="__custom__"&&((et=d.find(Ae=>Ae.id===h))==null?void 0:et.path)||"",de=l.useMemo(()=>(e.recentLaunches||[]).map(Ae=>Ae.workspace),[e]),we=l.useCallback(async Ae=>{v(!0),C("");try{const Je=await r(Ae);w(Je.path),f(Je.path),N(Je.directories)}catch(Je){C(Je instanceof Error?Je.message:"Could not load folder")}finally{v(!1)}},[r]),Re=l.useCallback(()=>{var Je;g("__custom__"),A(!0);const Ae=ql(e.platform,Ul(k.trim(),re,de,e.defaultWorkspacePath,(Je=d.find(bt=>bt.id===m))==null?void 0:Je.path,d.map(bt=>bt.path)));we(Ae)},[k,m,we,de,re,e.platform,d]),F=l.useCallback(Ae=>{if(Ae!=null&&Ae.workspaceId){g(Ae.workspaceId),f("");return}if(Ae!=null&&Ae.workspacePath){g("__custom__"),f(Ae.workspacePath);return}g(""),f("")},[]),J=l.useCallback(Ae=>{if(g(Ae),Ae==="__custom__"){Re();return}f("")},[Re]),ge=l.useCallback(Ae=>{g("__custom__"),f(Ae)},[]),ue=l.useCallback((Ae,Je)=>{D.current=Je,H.current=Ae.selectedWorkspaceKey||"__home__",R(Ae.selectedWorkspaceKey||"__home__"),E(Ae.initialArgs||""),_(Ae.initialModel||""),B(""),V([]);const bt=Ae.providerType?`${e.id}:${Ae.providerType}`:null;if(SC(me.current,bt)){const it=Gt();ae(it.textQuery),Z(it.workspaceQuery),X(it.modelQuery),Q(it.resumableOnly),Se(it.sortMode)}me.current=bt,T(Ae),Ae.providerType&&o&&(xe(!0),o(Ae.providerType).then(it=>V(it||[])).catch(it=>console.warn("Failed to load saved sessions",it)).finally(()=>xe(!1)))},[o,e.id]),ee=l.useMemo(()=>xm(W,{textQuery:ne,workspaceQuery:he,modelQuery:z,resumableOnly:O,sortMode:ke}),[z,O,W,ke,ne,he]);l.useEffect(()=>{q&&(ee.some(Ae=>Ae.providerSessionId===q)||B(""))},[ee,q]);const De=l.useCallback(()=>{D.current&&(G(!0),D.current().finally(()=>{D.current=null,G(!1),T(null)}))},[]),Le=l.useCallback(()=>{D.current=null,T(null)},[]),Xe=l.useCallback(Ae=>{H.current=Ae,R(Ae)},[]);return l.useEffect(()=>{var Ae;te.current!==e.id&&(te.current=e.id,g(m||((Ae=d[0])==null?void 0:Ae.id)||"__custom__"),f(""),w(""),N([]),C(""),A(!1),ae(Gt().textQuery),Z(Gt().workspaceQuery),X(Gt().modelQuery),Q(Gt().resumableOnly),Se(Gt().sortMode),me.current=null,I(Vo(p,t.length,n.length)))},[n.length,t.length,m,p,e.id,d]),l.useEffect(()=>{var Ae;h!=="__custom__"&&(h&&d.some(Je=>Je.id===h)||g(m||((Ae=d[0])==null?void 0:Ae.id)||"__custom__"))},[m,h,d]),l.useEffect(()=>{M==="ide"&&p||M==="cli"&&t.length>0||M==="acp"&&n.length>0||I(Vo(p,t.length,n.length))},[M,n.length,t.length,p]),{showAllRecent:c,setShowAllRecent:u,hasIdeOptions:p,workspaceRows:d,defaultWorkspaceId:m,workspaceChoice:h,customWorkspacePath:k,browseCurrentPath:x,browseDirectories:b,browseBusy:j,browseError:y,browseDialogOpen:S,activeLauncherKind:M,launchConfirm:P,launchConfirmWorkspaceKeyRef:H,launchConfirmWorkspaceKey:L,launchConfirmArgs:U,launchConfirmModel:$,launchConfirmResumeId:q,launchConfirmSavedSessions:W,launchConfirmTextFilter:ne,launchConfirmWorkspaceFilter:he,launchConfirmModelFilter:z,launchConfirmResumableOnly:O,launchConfirmSortMode:ke,filteredLaunchConfirmSavedSessions:ee,launchConfirmSessionsLoading:ve,launchConfirmBusy:Y,resolvedWorkspacePath:K,canCreateMissingWorkspace:be,openBrowseDialog:Re,loadBrowsePath:we,handleWorkspaceChoiceChange:J,chooseCustomWorkspacePath:ge,setCustomWorkspacePath:f,setBrowseDialogOpen:A,setActiveLauncherKind:I,openLaunchConfirm:ue,handleConfirmLaunch:De,closeLaunchConfirm:Le,setWorkspaceSelectionFromOption:F,setLaunchConfirmWorkspaceKeyAndSync:Xe,setLaunchConfirmArgs:E,setLaunchConfirmModel:_,setLaunchConfirmResumeId:B,setLaunchConfirmTextFilter:ae,setLaunchConfirmWorkspaceFilter:Z,setLaunchConfirmModelFilter:X,setLaunchConfirmResumableOnly:Q,setLaunchConfirmSortMode:Se}}function wN({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:n,cliProviders:a,acpProviders:r,selectedMachineNeedsUpgrade:o,appVersion:i,machineAction:c,isStandalone:u,section:p,showBottomNav:d,onBack:m,onSectionChange:h,onOpenConversation:g,onOpenRecent:k,onOpenMachineDetails:f,onMachineUpgrade:x,onLaunchDetectedIde:w,onAddWorkspace:b,onBrowseDirectory:N,onLaunchWorkspaceProvider:j,onListSavedSessions:v}){const{t:y}=Ce("common"),C=R=>R==="ide"?"IDE":R==="cli"?"CLI":"ACP",S=n.slice(0,4),A=t.slice(0,3),M=yN({selectedMachineEntry:e,cliProviders:a,acpProviders:r,machineAction:c,onBrowseDirectory:N,onListSavedSessions:v}),I=l.useMemo(()=>S.map(R=>{const{metaText:U,updatedLabel:E}=oh(R);return{key:`recent-launch:${R.id}`,primary:R.label,secondary:U,updatedLabel:E,onClick:()=>{const{options:$,selectedKey:_}=rh({machine:{workspaces:M.workspaceRows,defaultWorkspaceId:M.defaultWorkspaceId},currentWorkspacePath:R.workspace,homeLabel:y("newSession.homeDirectory"),homeDescription:y("newSession.launchWithoutWorkspace")});M.openLaunchConfirm({title:R.kind==="ide"?$r(y,"restart-ide",R.label):R.providerSessionId?ym(y,R.label):$r(y,"start-fresh",R.label),description:R.kind==="ide"?Fr(y,"restart-ide"):R.providerSessionId?wm(y):Fr(y,"start-fresh"),confirmLabel:R.kind==="ide"?Br(y,"restart-ide"):R.providerSessionId?Ui(y,!0):Br(y,"start-fresh"),busyLabel:R.kind==="ide"?Wr(y,"restart-ide"):R.providerSessionId?vm(y,!0):Wr(y,"start-fresh"),workspaceOptions:$,selectedWorkspaceKey:_,details:[{label:"Mode",value:C(R.kind)},...R.providerType?[{label:"Provider",value:R.providerType}]:[]]},async()=>{const q=$.find(B=>B.key===M.launchConfirmWorkspaceKeyRef.current);M.setWorkspaceSelectionFromOption(q),await k({...R,workspace:(q==null?void 0:q.workspacePath)??null})})}}}),[M,k,S,y]),D=l.useMemo(()=>A.map(R=>({key:`recent-chat:${R.conversation.tabKey}`,primary:kt(R.conversation),secondary:QS(R.conversation,{timestampLabel:R.timestamp?up(R.timestamp):null}),unread:R.unread,onClick:()=>g(R.conversation)})),[g,A]),P=M.showAllRecent?I:I.slice(0,4),T=I.length>0,H=D.length>0,L=u?"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 ${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:m,type:"button","aria-label":"Back",children:s.jsx(ml,{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:as(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:[H&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:D.map(R=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${R.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:R.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:R.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:R.secondary})]},R.key))})]}),T&&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:P.map(R=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:R.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:R.primary}),R.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:R.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:R.secondary})]},R.key))}),I.length>4&&s.jsx("div",{className:"flex justify-center px-4 pt-2",children:s.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>M.setShowAllRecent(R=>!R),children:M.showAllRecent?"Show fewer":`Show ${I.length-4} more`})})]}),!1,s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[o&&s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:x,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",i]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:f,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"})]})]})]})]}),M.browseDialogOpen&&s.jsx(Kl,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:M.browseCurrentPath,directories:M.browseDirectories,busy:M.browseBusy,error:M.browseError,confirmLabel:"Use this folder",onClose:()=>M.setBrowseDialogOpen(!1),onNavigate:R=>{M.loadBrowsePath(R)},onConfirm:R=>{M.chooseCustomWorkspacePath(R),M.setBrowseDialogOpen(!1)}}),M.launchConfirm&&s.jsx(mo,{title:M.launchConfirm.title,description:M.launchConfirm.description,details:M.launchConfirm.details,workspaceOptions:M.launchConfirm.workspaceOptions,selectedWorkspaceKey:M.launchConfirmWorkspaceKey,onWorkspaceChange:M.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:M.launchConfirm.providerType?Ui(y,!!M.launchConfirmResumeId):M.launchConfirm.confirmLabel,busyLabel:M.launchConfirm.providerType?void 0:M.launchConfirm.busyLabel,busy:M.launchConfirmBusy,showArgsInput:M.launchConfirm.showArgsInput,argsValue:M.launchConfirmArgs,onArgsChange:M.setLaunchConfirmArgs,showModelInput:M.launchConfirm.showModelInput,modelValue:M.launchConfirmModel,onModelChange:M.setLaunchConfirmModel,historyProviderNode:M.launchConfirm.providerType&&(M.launchConfirmSessionsLoading||M.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"}),M.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:_l(y)}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:M.launchConfirmTextFilter,onChange:R=>M.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:M.launchConfirmBusy||M.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:M.launchConfirmWorkspaceFilter,onChange:R=>M.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:M.launchConfirmBusy||M.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:M.launchConfirmModelFilter,onChange:R=>M.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:M.launchConfirmBusy||M.launchConfirmSessionsLoading}),s.jsxs("select",{value:M.launchConfirmSortMode,onChange:R=>M.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:M.launchConfirmBusy||M.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:M.launchConfirmResumableOnly,onChange:R=>M.setLaunchConfirmResumableOnly(R.target.checked),disabled:M.launchConfirmBusy||M.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:M.launchConfirmResumeId,onChange:R=>M.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:M.launchConfirmBusy||M.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:NC(y)}),M.filteredLaunchConfirmSavedSessions.map(R=>s.jsxs("option",{value:R.providerSessionId,disabled:!R.canResume,children:[R.title||R.providerSessionId," ",R.canResume?"":"(workspace missing)"]},R.providerSessionId))]}),!M.launchConfirmSessionsLoading&&M.launchConfirmSavedSessions.length>0&&M.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),M.launchConfirmResumeId&&(()=>{const R=M.filteredLaunchConfirmSavedSessions.find(E=>E.providerSessionId===M.launchConfirmResumeId);if(!R)return null;const U=ah(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:U.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:U.providerSessionId}),s.jsx("div",{className:"mt-1",children:U.metaLine}),U.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:U.updatedLabel}),U.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:U.preview})]})})()]}),onConfirm:M.handleConfirmLaunch,onCancel:M.closeLaunchConfirm}),d&&s.jsx(nh,{section:p,onSectionChange:h})]})}const Ld=8e3;function kN(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 ih(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 f=!1;for(const[x,w]of g){const b=e.get(x),N=w.muted===void 0||(b?b.muted===w.muted:!1),j=w.hidden===void 0||(b?b.surfaceHidden===w.hidden:!1),v=k-w.at>Ld;(N&&j||v)&&(g.delete(x),f=!0)}f&&o()},[e,o]),l.useEffect(()=>{if(a.current.size===0)return;const g=setInterval(()=>{const k=a.current,f=Date.now();let x=!1;for(const[w,b]of k)f-b.at>Ld&&(k.delete(w),x=!0);x&&o(),k.size===0&&clearInterval(g)},1e3);return()=>clearInterval(g)});const i=l.useCallback((g,k)=>{const f=a.current.get(g);a.current.set(g,{...f,...k,at:Date.now()}),o()},[o]),c=l.useCallback(g=>{const k=g.sessionId,f=k?a.current.get(k):void 0;return(f==null?void 0:f.muted)!==void 0?f.muted:Js(g,e).muted??!1},[e]),u=l.useCallback(g=>{const k=g.sessionId,f=k?a.current.get(k):void 0;return(f==null?void 0:f.hidden)!==void 0?f.hidden:Js(g,e).surfaceHidden??!1},[e]),p=l.useCallback((g,k)=>{const f=Bs(g),x=g.sessionId;!f||!x||(i(x,k),t(f,"set_conversation_prefs",{sessionId:x,...k,...oo(g)}).then(w=>{const b=kN(w);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(w=>{console.warn("[conversation-prefs] set_conversation_prefs failed",w),a.current.delete(x),o();const b=w instanceof Error?w.message:String(w??"the daemon is unreachable");n==null||n(`Couldn't update conversation — ${b}`)}))},[t,i,o,n]),d=l.useCallback(g=>{p(g,{muted:!c(g)})},[p,c]),m=l.useCallback((g,k)=>{p(g,{hidden:k})},[p]),h=l.useCallback(g=>{p(g,{hidden:!u(g)})},[p,u]);return{isMuted:c,isHidden:u,toggleMute:d,setHidden:m,toggleHidden:h}}function Sr(e){return[...e].sort((t,n)=>{const a=n.timestamp-t.timestamp;return a!==0?a:t.conversation.tabKey.localeCompare(n.conversation.tabKey)})}function SN(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:Sr(e)}function CN(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:Sr(n),unreadItems:Sr(a),workingItems:SN(r,t),completedItems:Sr(o)}}function ho(e,t){if(!t)return!1;const n=e.filter(a=>a.type==="adhdev-daemon"&&lh(a)==="Connected");return n.length===0?!0:n.every(a=>a._sessionListAuthoritative===!0)}function lh(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 jN(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:vn(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=La(a)?"cli":Wn(a)?"acp":"ide",o=vn(a.summaryMetadata);return{id:`${r}:${a.type}:${a.workspace||""}`,label:((i=a.activeChat)==null?void 0:i.title)||(La(a)?a.cliName||a.type:Wn(a)&&a.cliName||a.type),kind:r,providerType:a.type,providerSessionId:a.providerSessionId,subtitle:Wn(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 NN(e,t,n=[]){const a=new Map;for(const o of t){const i=Bs(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=Bs(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)||[],u=[...i].sort((f,x)=>x.timestamp-f.timestamp)[0]||null,p=(u==null?void 0:u.conversation)||null,d=_i(o),m=i.filter(f=>f.unread||f.requiresAction).length,h=i.filter(f=>Da(f.conversation)).length+c.filter(Da).length,g=lh(o),k=[o.platform||"machine",g].filter(Boolean);return{id:o.id,label:as(o,{fallbackId:o.id}),subtitle:k.join(" · "),unread:m,total:i.length,generatingCount:h,latestConversation:p,latestTimestamp:(u==null?void 0:u.timestamp)||0,fallbackActivityAt:d,preview:p?JS(p,rm(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,u=i.latestTimestamp||i.fallbackActivityAt||0;return u!==c?u-c:o.label.localeCompare(i.label)})}function AN(e){return e==="chat"}function or(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 MN({conversations:e,machineEntries:t,items:n,selectedConversation:a,selectedTabKey:r,screen:o,liveSessionInboxState:i,sendDaemonCommand:c,requestedActiveTabKey:u,onRequestedActiveTabConsumed:p,requestedMachineId:d,onRequestedMachineConsumed:m,requestedMobileSection:h,onRequestedMobileSectionConsumed:g,setSelectedTabKey:k,setScreen:f,setSelectedMachineId:x,setSection:w,setMachineBackTarget:b,resetMachineAction:N}){const j=l.useRef(null),v=l.useCallback(y=>{if(!(y!=null&&y.sessionId))return;const C=Js(y,i),S=Math.max(Date.now(),bn(y),C.lastUpdated||0);or("mark_read:start",{tabKey:y.tabKey,sessionId:y.sessionId,displayPrimary:kt(y),inboxBucket:C.inboxBucket,unread:C.unread,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,activityAt:bn(y),readAt:S}),c(Bs(y)||y.routeId,"mark_session_seen",{sessionId:y.sessionId,providerSessionId:y.providerSessionId,seenAt:S,completionMarker:C.completionMarker}).then(A=>{or("mark_read:result",{tabKey:y.tabKey,sessionId:y.sessionId,result:A})}).catch(A=>{or("mark_read:error",{tabKey:y.tabKey,sessionId:y.sessionId,error:A instanceof Error?A.message:String(A)})})},[i,c]);return l.useEffect(()=>{var C;if(!a){AN(o)&&f("inbox"),k(((C=e[0])==null?void 0:C.tabKey)||null),j.current=null;return}if(o!=="chat"){j.current=null;return}const y=`${a.tabKey}:${a.sessionId||""}`;j.current!==y&&(j.current=y,v(a))},[e,v,o,a,f,k]),l.useEffect(()=>{if(!u)return;const y=e.find(C=>C.tabKey===u);y&&(k(y.tabKey),f("chat"),p==null||p())},[e,p,u,f,k]),l.useEffect(()=>{if(!d)return;const y=t.find(C=>C.id===d);y&&(x(y.id),N(),w("machines"),b("inbox"),f("machine"),m==null||m())},[t,m,d,N,b,f,w,x]),l.useEffect(()=>{h&&(w(h),f("inbox"),g==null||g())},[g,h,f,w]),l.useEffect(()=>{const y=n.filter(C=>C.inboxBucket==="task_complete"||C.unread);y.length!==0&&or("inbox_state",{screen:o,selectedTabKey:r,items:y.map(C=>{const S=Js(C.conversation,i);return{liveState:S,tabKey:C.conversation.tabKey,sessionId:C.conversation.sessionId,displayPrimary:kt(C.conversation),serverBucket:S.inboxBucket,computedBucket:C.inboxBucket,serverUnread:S.unread,computedUnread:C.unread,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,activityAt:bn(C.conversation)}})})},[n,i,o,r]),{markConversationRead:v}}function PN(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Rd(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function TN(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function DN({sendDaemonCommand:e,navigate:t,ides:n,conversations:a}){const{launchCli:r}=Jr(),[o,i]=l.useState("idle"),[c,u]=l.useState(""),[p,d]=l.useState(null),m=l.useCallback(()=>{i("idle"),u(""),d(null)},[]),h=l.useCallback(async(N,j,v)=>{var y;try{i("loading"),u(`Launching ${j}…`);const C={ideType:j,enableCdp:!0};(y=v==null?void 0:v.workspacePath)!=null&&y.trim()&&(C.workspace=v.workspacePath.trim()),await e(N,"launch_ide",C),i("done"),u(`${j} launch requested`)}catch(C){i("error"),u(C instanceof Error?C.message:"Launch IDE failed"),console.error("Launch IDE failed",C)}},[e]),g=l.useCallback(async(N,j,v)=>{if(j.trim())try{i("loading"),u(v!=null&&v.createIfMissing?"Creating folder…":"Saving workspace…");const y=await e(N,"workspace_add",{path:j.trim(),createIfMissing:(v==null?void 0:v.createIfMissing)===!0});if(y!=null&&y.success){i("done"),u(v!=null&&v.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),u((y==null?void 0:y.error)||"Could not save workspace")}catch(y){i("error"),u(y instanceof Error?y.message:"Could not save workspace")}},[e]),k=l.useCallback(async N=>{i("loading"),u("Starting daemon upgrade…");const j=n.find(y=>y.id===N||y.daemonId===N),v=await vj(e,N,j);i(v.state),u(v.message)},[n,e]),f=l.useCallback(async(N,j,v,y)=>{var A,M,I;const C=Date.now(),S={machineId:N,kind:j,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:C};try{i("loading"),u(`Launching ${v}…`),d(S);const D={cliType:v};(A=y==null?void 0:y.workspacePath)!=null&&A.trim()?D.dir=y.workspacePath.trim():y!=null&&y.workspaceId?D.workspaceId=y.workspaceId:y!=null&&y.useHome&&(D.useHome=!0),y!=null&&y.resumeSessionId&&(D.resumeSessionId=y.resumeSessionId),(M=y==null?void 0:y.args)!=null&&M.trim()&&(D.cliArgs=y.args.trim().split(/\s+/).filter(Boolean)),(I=y==null?void 0:y.model)!=null&&I.trim()&&(D.initialModel=y.model.trim());const P=await r(N,D),T=(P==null?void 0:P.result)||P,H=(T==null?void 0:T.sessionId)||(T==null?void 0:T.id);if(P!=null&&P.success&&H){d(null),i("done"),u(`${v} launched`),t(Ea(H));return}if(P!=null&&P.success){i("loading"),u(`${v} launch requested — waiting for session…`);return}d(null),i("error"),u((P==null?void 0:P.error)||(T==null?void 0:T.error)||`Could not launch ${j.toUpperCase()} workspace`)}catch(D){if(TN(D)){i("loading"),u(`${v} launch requested — waiting for session…`);return}d(null),i("error"),u(D instanceof Error?D.message:`Could not launch ${j.toUpperCase()} workspace`)}},[t,e]),x=l.useCallback(async(N,j)=>{try{const v=await e(N,"list_saved_sessions",{providerType:j,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]),w=l.useCallback(async(N,j)=>Gl(e,N,j),[e]);l.useEffect(()=>{if(!p)return;const N=Rd(p.workspacePath),j=n.find(y=>{var D,P,T,H;if(!y||y.type==="adhdev-daemon"||PN(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 M=String(y.providerSessionId||"");if(p.resumeSessionId&&M)return M===p.resumeSessionId;if(N){const L=Rd(y.workspace||y.runtimeWorkspaceLabel);return L?L===N:!1}return Number(y.lastUpdated||y._lastUpdate||y.timestamp||((H=(T=(P=(D=y.activeChat)==null?void 0:D.messages)==null?void 0:P.at)==null?void 0:T.call(P,-1))==null?void 0:H.timestamp)||0)>=p.startedAt-5e3});if(!j)return;const v=eh({entrySessionId:j.sessionId,entryInstanceId:j.instanceId,entryRouteId:j.id,conversations:a});v&&(d(null),i("done"),u(`${p.providerType} launched`),t(Ea(v)))},[a,n,t,p]),l.useEffect(()=>{if(!p)return;const N=window.setTimeout(()=>{d(j=>!j||j.startedAt!==p.startedAt?j:(i("error"),u("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(N)},[p]);const b=l.useCallback(async(N,j)=>{var v;if(j.kind==="ide"&&j.providerType){await h(N,j.providerType,{workspacePath:j.workspace||null});return}if((j.kind==="cli"||j.kind==="acp")&&j.providerType){const y=((v=j.workspace)==null?void 0:v.trim())||"";await f(N,j.kind,j.providerType,{workspacePath:y||null,useHome:!y,resumeSessionId:j.providerSessionId||null})}},[h,f]);return{machineAction:{state:o,message:c},resetMachineAction:m,handleLaunchDetectedIde:h,handleAddWorkspace:g,handleMachineUpgrade:k,handleLaunchWorkspaceProvider:f,handleListSavedSessions:x,handleBrowseDirectory:w,handleOpenRecent:b}}function IN({conversations:e,selectedConversation:t,machineBackTarget:n,markConversationRead:a,resetMachineAction:r,setSelectedTabKey:o,setScreen:i,setSelectedMachineId:c,setSection:u,setMachineBackTarget:p}){const d=l.useCallback(w=>{o(w.tabKey),i("chat"),a(w)},[a,i,o]),m=l.useCallback(w=>{const b=e.find(N=>N.routeId===w.routeId&&N.streamSource==="native");b&&(o(b.tabKey),i("chat"),a(b))},[e,a,i,o]),h=l.useCallback(()=>{a(t),i("inbox")},[a,t,i]),g=l.useCallback((w,b="inbox")=>{c(w),r(),u("machines"),p(b),i("machine")},[r,p,i,u,c]),k=l.useCallback(w=>{const b=Bs(w);b&&g(b,"chat")},[g]),f=l.useCallback(()=>{r(),i(n)},[n,r,i]),x=l.useCallback(w=>{u(w),i("inbox")},[i,u]);return{openConversation:d,openNativeConversation:m,backFromConversation:h,openMachine:g,openConversationMachine:k,backFromMachine:f,changeMachineSection:x}}function Vn(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function LN(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function RN({conversations:e,hiddenConversations:t,ides:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,userName:c,requestedActiveTabKey:u,onRequestedActiveTabConsumed:p,requestedMachineId:d,onRequestedMachineConsumed:m,requestedMobileSection:h,onRequestedMobileSectionConsumed:g,onOpenHistory:k,onOpenRemote:f,onStopCli:x,wsStatus:w,isConnected:b,initialDataLoaded:N=!0,onShowAllHiddenConversations:j,onHideConversation:v,onOpenMeshGraph:y,onOpenNewSession:C,liveSessionInboxState:S,setCliViewModeOverrides:A}){const[M,I]=l.useState(()=>{var J;return((J=e[0])==null?void 0:J.tabKey)||null}),[D,P]=l.useState(()=>e[0]?"chat":"inbox"),[T,H]=l.useState("chats"),[L,R]=l.useState(null),[U,E]=l.useState("inbox"),$=l.useRef([]),_=Jn(),q="1.0.47",B=l.useMemo(()=>e.find(J=>J.tabKey===M)||e[0]||null,[e,M]),W=l.useMemo(()=>B?n.find(J=>J.id===B.routeId):void 0,[n,B]),V=l.useMemo(()=>!B||ut(B)||!mt(B)?null:Zn(B),[B]),ne=l.useMemo(()=>n.filter(J=>J.type==="adhdev-daemon").sort(Sl),[n]),ae=l.useMemo(()=>ne.find(J=>J.id===L)||null,[ne,L]),he=io({sendDaemonCommand:r,activeConv:B||void 0,setActionLogs:o,isStandalone:i}),Z=DN({sendDaemonCommand:r,navigate:_,ides:n,conversations:e}),z=NS(e),X=l.useMemo(()=>e.map(J=>{const ge=D==="chat"&&(B==null?void 0:B.tabKey)===J.tabKey,ue=to(J,S,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ge}),ee=bn(J),De=rm(J),Le=pm(J,De);return{conversation:J,timestamp:ee,preview:Le,unread:ue.unread,requiresAction:ue.requiresAction,isWorking:ue.isWorking,inboxBucket:ue.inboxBucket}}),[e,S,D,B,z]),{markConversationRead:O}=MN({conversations:e,machineEntries:ne,items:X,selectedConversation:B,selectedTabKey:M,screen:D,liveSessionInboxState:S,sendDaemonCommand:r,requestedActiveTabKey:u,onRequestedActiveTabConsumed:p,requestedMachineId:d,onRequestedMachineConsumed:m,requestedMobileSection:h,onRequestedMobileSectionConsumed:g,setSelectedTabKey:I,setScreen:P,setSelectedMachineId:R,setSection:H,setMachineBackTarget:E,resetMachineAction:Z.resetMachineAction}),Q=IN({conversations:e,selectedConversation:B,machineBackTarget:U,markConversationRead:O,resetMachineAction:Z.resetMachineAction,setSelectedTabKey:I,setScreen:P,setSelectedMachineId:R,setSection:H,setMachineBackTarget:E}),{isMuted:ke,toggleMute:Se}=ih(S,r),{attentionItems:ve,unreadItems:xe,workingItems:Y,completedItems:G}=l.useMemo(()=>CN(X,$.current),[X]);l.useEffect(()=>{$.current=Y.map(J=>J.conversation.tabKey)},[Y]);const te=l.useMemo(()=>ae?X.filter(J=>Bs(J.conversation)===ae.id):[],[X,ae]),me=l.useMemo(()=>jN(ae,n),[n,ae]),K=!!ae&&uo(ae,qs(ae,q)),be=l.useMemo(()=>(ae==null?void 0:ae.availableProviders)||[],[ae]),re=l.useMemo(()=>be.filter(J=>Vn(J,"cli")).map(J=>({type:J.type,displayName:J.displayName||J.type,icon:J.icon})),[be]),de=l.useMemo(()=>be.filter(J=>Vn(J,"acp")).map(J=>({type:J.type,displayName:J.displayName||J.type,icon:J.icon})),[be]),we=l.useMemo(()=>NN(ne,X,t),[X,ne,t]),Re=l.useMemo(()=>ho(n,N),[n,N]),F=l.useCallback(async J=>{ae&&await Z.handleOpenRecent(ae.id,J)},[Z,ae]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:D==="chat"&&B?s.jsx(pN,{selectedConversation:B,isAcp:ut(B),isStandalone:i,selectedIdeEntry:W,actionLogs:a,userName:c,isSendingChat:he.isSendingChat,sendFeedbackMessage:he.sendFeedbackMessage,isFocusingAgent:he.isFocusingAgent,handleModalButton:he.handleModalButton,handleRelaunch:he.handleRelaunch,onBack:Q.backFromConversation,onOpenNativeConversation:Q.openNativeConversation,onOpenMachine:Q.openConversationMachine,onOpenHistory:k,onOpenRemote:f,onOpenMeshGraph:y,onStopCli:x,cliViewMode:V,onSetCliViewMode:async J=>{await qm({conversation:B,mode:J,ides:n,sendDaemonCommand:r,setCliViewModeOverrides:A})},handleSendChat:he.handleSendChat,handleForceSendChat:he.handleForceSendChat,handleFocusAgent:he.handleFocusAgent}):D==="machine"&&ae?s.jsx(wN,{selectedMachineEntry:ae,selectedMachineConversations:te,selectedMachineRecentLaunches:me,cliProviders:re,acpProviders:de,selectedMachineNeedsUpgrade:K,appVersion:q,machineAction:Z.machineAction,isStandalone:i,section:T,showBottomNav:U==="inbox",onBack:Q.backFromMachine,onSectionChange:Q.changeMachineSection,onOpenConversation:Q.openConversation,onOpenRecent:F,onOpenMachineDetails:()=>_(`/machines/${ae.id}`),onMachineUpgrade:()=>Z.handleMachineUpgrade(ae.id),onLaunchDetectedIde:(J,ge)=>Z.handleLaunchDetectedIde(ae.id,J,ge),onAddWorkspace:(J,ge)=>Z.handleAddWorkspace(ae.id,J,ge),onBrowseDirectory:J=>Z.handleBrowseDirectory(ae.id,J),onLaunchWorkspaceProvider:(J,ge,ue)=>Z.handleLaunchWorkspaceProvider(ae.id,J,ge,ue),onListSavedSessions:J=>Z.handleListSavedSessions(ae.id,J)}):s.jsx(fN,{section:T,attentionItems:ve,unreadItems:xe,workingItems:Y,completedItems:G,hiddenConversations:t,machineCards:we,getAvatarText:LN,actionLogs:a,sendDaemonCommand:r,onOpenConversation:Q.openConversation,onShowAllHidden:j,onHideConversation:v,onOpenMeshGraph:y,onStopCli:x,onOpenNewSession:C,onOpenMachine:Q.openMachine,onOpenSettings:()=>_("/settings"),onSectionChange:H,wsStatus:w,isConnected:b,initialDataLoaded:N,conversationsLoaded:Re,isStandalone:i,isConversationMuted:ke,onToggleMuteConversation:Se})})}function Yo(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function EN({conversations:e,numGroups:t,onMoveTab:n,onReceiveTab:a,onOwnTabDrop:r,onClearPreviewOrder:o}){const i=l.useRef(0),[c,u]=l.useState(!1),[p,d]=l.useState(null),m=l.useCallback(()=>{i.current=0,u(!1),d(null)},[]);l.useEffect(()=>(window.addEventListener("dragend",m),window.addEventListener("drop",m),()=>{window.removeEventListener("dragend",m),window.removeEventListener("drop",m)}),[m]);const h=l.useCallback(x=>{x.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,u(!0))},[]),g=l.useCallback(x=>{if(!x.dataTransfer.types.includes("text/tab-key"))return;if(x.preventDefault(),!Yo(t,n)){d("merge");return}const w=x.currentTarget.getBoundingClientRect(),b=x.clientX-w.left,N=w.width/3;b<N?d("split-left"):b>N*2?d("split-right"):d("merge")},[t,n]),k=l.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,u(!1),d(null))},[]),f=l.useCallback(x=>{i.current=0,u(!1);const w=x.dataTransfer.getData("text/tab-key"),b=w?e.some(j=>j.tabKey===w):!1,N=p;if(d(null),o(),!!w){if(x.preventDefault(),N==="split-left"&&Yo(t,n)){n==null||n(w,"split-left");return}if(N==="split-right"&&Yo(t,n)){n==null||n(w,"split-right");return}if(b){r(w);return}a==null||a(w)}},[e,p,t,n,a,r,o]);return{dragOver:c,dropAction:p,resetDragState:m,handleDragEnter:h,handleDragOver:g,handleDragLeave:k,handleDrop:f}}function _N(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 HN({conversations:e,initialActiveTabId:t,initialTabOrder:n,onActiveTabChange:a,onTabOrderChange:r}){const[o,i]=l.useState(t??null),[c,u]=l.useState(n??[]),[p,d]=l.useState(null),m=l.useRef(null),h=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(()=>{u(C=>{const S=_N(C,e);return S.length===C.length&&S.every((A,M)=>A===C[M])?C:S})},[e]);const f=l.useMemo(()=>{const C=p??c;if(C.length===0)return e;const S=new Map(C.map((A,M)=>[A,M]));return[...e].sort((A,M)=>{const I=S.get(A.tabKey)??999,D=S.get(M.tabKey)??999;return I-D})},[e,p,c]);l.useEffect(()=>{var S,A;if(f.length===0){o!==null&&(i(null),(S=g.current)==null||S.call(g,null));return}if(o&&f.some(M=>M.tabKey===o))return;const C=f[0].tabKey;C!==o&&(i(C),(A=g.current)==null||A.call(g,C))},[f,o]);const x=l.useMemo(()=>f.find(C=>C.tabKey===o),[f,o]),w=l.useCallback(C=>{var S;i(C),(S=g.current)==null||S.call(g,C)},[]),b=l.useCallback((C,S,A)=>{u(M=>{var T;const I=M.filter(H=>H!==C),D=I.indexOf(S);if(D<0)return M;const P=A==="left"?D:D+1;return I.splice(P,0,C),(T=k.current)==null||T.call(k,I),I}),d(null)},[]),N=l.useCallback((C,S,A)=>{const I=(c.length>0?c:e.map(T=>T.tabKey)).filter(T=>T!==C),D=I.indexOf(S);if(D<0)return;const P=A==="left"?D:D+1;I.splice(P,0,C),m.current=I,d(I)},[c,e]),j=l.useCallback(()=>{var S;const C=m.current;C&&(u(C),(S=k.current)==null||S.call(k,C))},[]),v=l.useCallback(()=>{m.current=null,d(null)},[]),y=l.useCallback(C=>{u(S=>{var M;const A=S.filter(I=>I!==C);return A.push(C),(M=k.current)==null||M.call(k,A),A})},[]);return{activeTabId:o,activeConv:x,sortedConversations:f,previewOrderRef:m,draggingTabRef:h,selectTab:w,handleTabReorder:b,updatePreviewOrder:N,commitPreviewOrder:j,clearPreviewOrder:v,moveTabToEnd:y,setDraggingTabKey:C=>{h.current=C}}}function $N({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 Vl({conversationsCount:e,isSplitMode:t,isStandalone:n,hasRegisteredMachines:a=!1,suppressGuide:r=!1,onOpenNewSession:o,isLoading:i=!1}){const{t:c}=Ce("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("div",{className:"w-7 h-7 rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light","aria-hidden":"true"}),s.jsx("p",{className:"text-sm",children:c("paneGroup.loadingSessions")})]});const u=!n&&!a,p=a&&!!o,d=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:d}),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(xl,{size:14}),s.jsx("span",{children:c("paneGroup.newSession")})]})}),u&&s.jsx(sh,{}),u&&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 ch="adhdev-tab-shortcuts";function dh(){try{return JSON.parse(localStorage.getItem(ch)||"{}")}catch{return{}}}function uh({enabled:e=!0,sortedTabKeys:t,onFocus:n,onSelectTab:a}){const r=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>dh()),[c,u]=l.useState(null),p=l.useCallback(m=>{const h=[];return m.metaKey&&h.push(r?"⌘":"Meta"),m.ctrlKey&&h.push("Ctrl"),m.altKey&&h.push(r?"⌥":"Alt"),m.shiftKey&&h.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(m.key)?null:(h.push(m.key.length===1?m.key.toUpperCase():m.key),h.join("+"))},[r]),d=l.useCallback(m=>{i(m);try{localStorage.setItem(ch,JSON.stringify(m))}catch{}},[]);return l.useEffect(()=>{if(!e||!c)return;const m=h=>{if(h.preventDefault(),h.stopPropagation(),h.key==="Escape"){u(null);return}const g=p(h);if(!g)return;const k={...o};for(const[f,x]of Object.entries(k))x===g&&delete k[f];k[c]=g,d(k),u(null)};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[e,c,o,d,p]),l.useEffect(()=>{if(!e)return;const m=h=>{if(!(!h.ctrlKey&&!h.metaKey&&!h.altKey)){for(const[g,k]of Object.entries(o))if(t.includes(g)&&p(h)===k){h.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:u,saveShortcuts:d}}const Qo=e=>{e.preventDefault()},FN=l.memo(function({conv:t,isActive:n,isDraggedTab:a,isTaskCompleteUnread:r,shortcut:o,conversationKeys:i,draggingTabRef:c,onFocus:u,onSelectTab:p,onConversationActivated:d,onPreviewReorder:m,onReorderTab:h,onCommitPreviewOrder:g,onClearPreviewOrder:k,onDragStateReset:f,onDragTabKeyChange:x,onReceiveTab:w,onOpenContextMenu:b,longPressTimer:N,isGroupActive:j}){const v=jn(t),y=v.isGenerating?"agent-tab-generating":v.isWaiting?"agent-tab-waiting":"",C=v.isReconnecting,S=VS(t),A=YS(t),M=um(t),I=l.useCallback($=>{c.current=t.tabKey,x(t.tabKey),$.dataTransfer.setData("text/tab-key",t.tabKey),$.dataTransfer.effectAllowed="move"},[t.tabKey,c,x]),D=l.useCallback(()=>{c.current=null,x(null),g(),k(),f()},[c,x,g,k,f]),P=l.useCallback($=>{const _=c.current;if(!(!_||_===t.tabKey)&&$.dataTransfer.types.includes("text/tab-key")){$.preventDefault(),$.stopPropagation();const q=$.currentTarget.getBoundingClientRect(),B=$.clientX<q.left+q.width/2?"left":"right";m(_,t.tabKey,B)}},[t.tabKey,c,m]),T=l.useCallback($=>{$.preventDefault(),$.stopPropagation();const _=$.dataTransfer.getData("text/tab-key");if(_&&_!==t.tabKey){const q=$.currentTarget.getBoundingClientRect(),B=$.clientX<q.left+q.width/2?"left":"right";i.includes(_)?h(_,t.tabKey,B):w&&w(_)}k()},[t.tabKey,i,h,w,k]),H=l.useCallback($=>{$.stopPropagation(),u(),p(t.tabKey),d(t)},[t,d,u,p]),L=l.useCallback($=>{$.preventDefault(),b($.clientX,$.clientY,t.tabKey)},[t.tabKey,b]),R=l.useCallback($=>{const _=$.touches[0];N.current=setTimeout(()=>{b(_.clientX,_.clientY,t.tabKey)},600)},[t.tabKey,N,b]),U=l.useCallback(()=>{N.current&&clearTimeout(N.current)},[N]),E=["adhdev-dockview-tab",y,n&&"is-active",j&&"is-group-active",C&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:E,draggable:!0,onDragStart:I,onDragEnd:D,onDragOver:P,onDrop:T,onClick:H,onContextMenu:L,onTouchStart:R,onTouchEnd:U,onTouchMove:U,style:{position:"relative",cursor:"pointer",opacity:a?.4:void 0},children:[M&&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(ns,{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("div",{className:"tab-spinner"}):v.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):C?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):v.isConnecting?s.jsx("div",{className:"tab-connecting-spinner"}):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:"○"})}),S.length>0&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-role",title:A,"aria-label":A||S.join(" · "),children:S.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:[C?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:mn(t)}):v.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[mn(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:mn(t)}),s.jsx(Hr,{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 BN({conversations:e,activeTabId:t,groupIndex:n,unreadTabKeys:a,draggingTabRef:r,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:d,onClearPreviewOrder:m,onDragStateReset:h,onDragTabKeyChange:g,onReceiveTab:k,onHideTab:f,isGroupActive:x,allowTabShortcuts:w=!0}){const{t:b}=Ce("common"),[N,j]=l.useState(null),v=l.useRef(null),y=l.useRef(null),C=l.useMemo(()=>e.map(T=>T.tabKey),[e]);$a("PaneGroupTabBar",{groupIndex:n,activeTabId:t,tabCount:e.length,ctxMenuTab:(N==null?void 0:N.tabKey)||null});const{isMac:S,tabShortcuts:A,shortcutListening:M,setShortcutListening:I,saveShortcuts:D}=uh({enabled:w,sortedTabKeys:e.map(T=>T.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!N)return;const T=H=>{const L=document.querySelector("[data-pane-context-menu]");L&&L.contains(H.target)||j(null)};return window.addEventListener("mousedown",T,!0),()=>window.removeEventListener("mousedown",T,!0)},[N]),l.useEffect(()=>{const T=y.current;if(!T)return;const H=L=>{Math.abs(L.deltaY)<=Math.abs(L.deltaX)||(L.preventDefault(),T.scrollLeft+=L.deltaY)};return T.addEventListener("wheel",H,{passive:!1}),()=>T.removeEventListener("wheel",H)},[]);const P=l.useCallback((T,H,L)=>{j({x:T,y:H,tabKey:L})},[]);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(T=>s.jsx(FN,{conv:T,isActive:t===T.tabKey,isDraggedTab:r.current===T.tabKey,isTaskCompleteUnread:a.has(T.tabKey),shortcut:w?A[T.tabKey]:void 0,conversationKeys:C,draggingTabRef:r,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:d,onClearPreviewOrder:m,onDragStateReset:h,onDragTabKeyChange:g,onReceiveTab:k,onOpenContextMenu:P,longPressTimer:v,isGroupActive:x},T.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:b("paneGroup.noTabsInGroup")})]})}),N&&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:N.x,top:N.y},children:[w&&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:Qo,onClick:T=>{T.stopPropagation(),I(N.tabKey),j(null)},children:["⌨ ",A[N.tabKey]?`Change shortcut (${A[N.tabKey]})`:"Set shortcut"]}),A[N.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:Qo,onClick:()=>{const T={...A};delete T[N.tabKey],D(T),j(null)},children:"✕ Remove shortcut"})]}),f&&s.jsxs(s.Fragment,{children:[w&&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:Qo,onClick:()=>{f(N.tabKey),j(null)},children:"🚫 Hide from Dashboard"})]})]}),w&&M&&s.jsx(Kt,{children:s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:()=>I(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:T=>T.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. ",S?"⌘+1":"Ctrl+1",", ",S?"⌥+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 WN({conversations:e,ides:t,clearedTabs:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:u=!0,userName:p,groupIndex:d,onFocus:m,isSplitMode:h,numGroups:g,onMoveTab:k,onReceiveTab:f,style:x,onActiveTabChange:w,initialActiveTabId:b,initialTabOrder:N,onTabOrderChange:j,onHideTab:v,isFocused:y,allowTabShortcuts:C=!0,onOpenNewSession:S,liveSessionInboxState:A}){const{sendCommand:M}=vt(),I=l.useRef(null),{activeTabId:D,activeConv:P,sortedConversations:T,draggingTabRef:H,selectTab:L,handleTabReorder:R,updatePreviewOrder:U,commitPreviewOrder:E,clearPreviewOrder:$,moveTabToEnd:_,setDraggingTabKey:q}=HN({conversations:e,initialActiveTabId:b,initialTabOrder:N,onActiveTabChange:w,onTabOrderChange:j}),B=io({sendDaemonCommand:r,activeConv:P,setActionLogs:o,isStandalone:i}),{dragOver:W,dropAction:V,resetDragState:ne,handleDragEnter:ae,handleDragOver:he,handleDragLeave:Z,handleDrop:z}=EN({conversations:e,numGroups:g,onMoveTab:k,onReceiveTab:f,onOwnTabDrop:_,onClearPreviewOrder:$}),X=P&&!ut(P)&&Zn(P)==="terminal",O=l.useMemo(()=>P?t.find(ve=>ve.id===P.routeId):void 0,[t,P]),Q=l.useMemo(()=>P?a.filter(ve=>ve.routeId===P.tabKey):[],[a,P]),ke=l.useMemo(()=>new Set(T.filter(ve=>Fg(ve,A,{isOpenConversation:ve.tabKey===D})).map(ve=>ve.tabKey)),[D,A,T]);$a("PaneGroup",{groupIndex:d,conversationCount:e.length,activeTabId:D,dragOver:W});const Se=l.useCallback(ve=>{ve.streamSource==="agent-stream"&&ve.agentType&&M(ve.routeId,zp(),{agentType:ve.agentType,...ve.sessionId&&{targetSessionId:ve.sessionId}}).catch(()=>{})},[M]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:m,style:{...x,outline:W?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(BN,{conversations:T,activeTabId:D,groupIndex:d,numGroups:g,unreadTabKeys:ke,draggingTabRef:H,onFocus:m,onSelectTab:L,onConversationActivated:Se,onPreviewReorder:U,onReorderTab:R,onCommitPreviewOrder:E,onClearPreviewOrder:$,onDragStateReset:ne,onDragTabKeyChange:q,onMoveTab:k,onReceiveTab:f,onHideTab:v,isGroupActive:y??!1,allowTabShortcuts:C}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:ae,onDragOver:he,onDragLeave:Z,onDrop:z,children:[W&&s.jsx($N,{dropAction:V,canSplit:!!(g<4&&k)}),P?s.jsx(zl,{activeConv:P,clearToken:n[P.tabKey]||0,isCliTerminal:!!X,ideEntry:O,terminalRef:I,handleModalButton:B.handleModalButton,handleRelaunch:B.handleRelaunch,handleSendChat:B.handleSendChat,handleForceSendChat:B.handleForceSendChat,isSendingChat:B.isSendingChat,sendFeedbackMessage:B.sendFeedbackMessage,handleFocusAgent:B.handleFocusAgent,isFocusingAgent:B.isFocusingAgent,actionLogs:Q,userName:p,isInputActive:!h||!!y}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(Vl,{conversationsCount:e.length,isSplitMode:h,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:S,isLoading:!ho(t,u)})})]})]})}function ON({containerRef:e,isSplitMode:t,numGroups:n,groupSizes:a,groupedConvs:r,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:u,setActionLogs:p,isStandalone:d,hasRegisteredMachines:m,initialDataLoaded:h,userName:g,focusedGroup:k,focusGroup:f,moveTabToGroup:x,splitTabRelative:w,closeGroup:b,handleResizeStart:N,groupActiveTabIds:j,setGroupActiveTab:v,groupTabOrders:y,setGroupTabOrder:C,toggleHiddenTab:S,onOpenNewSession:A,allowTabShortcuts:M=!0,liveSessionInboxState:I}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:r.map((D,P)=>{const T=t&&a.length===n?`${a[P]}%`:void 0;return s.jsxs(_t.Fragment,{children:[t&&P>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:H=>N(P-1,H),onDoubleClick:()=>b(P),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(WN,{style:t?{flexBasis:T??`${100/n}%`,flexGrow:T?0:1,flexShrink:T?0:1}:void 0,conversations:D,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:u,setActionLogs:p,isStandalone:d,hasRegisteredMachines:m,initialDataLoaded:h,userName:g,groupIndex:P,isFocused:t&&k===P,onFocus:()=>f(P),isSplitMode:t,numGroups:n,onMoveTab:(H,L)=>{L==="left"&&P>0?x(H,P-1):L==="right"&&P<n-1?x(H,P+1):L==="split-left"&&n<4?w(H,P,"left"):L==="split-right"&&n<4&&w(H,P,"right")},onReceiveTab:H=>x(H,P),onActiveTabChange:H=>v(P,H),initialActiveTabId:j[P],initialTabOrder:y[P],onTabOrderChange:H=>C(P,H),onHideTab:S,onOpenNewSession:A,allowTabShortcuts:M,liveSessionInboxState:I})]},P)})})}const ph="adhdev-dashboard-action-shortcuts",UN=1200,qN=[["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 GN(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function pt(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 mh(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:pt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:pt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:pt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:pt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:pt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:pt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:pt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:pt("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:pt("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:pt("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:pt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:pt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:pt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:pt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:pt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:pt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:pt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:pt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:pt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:pt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:pt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:pt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:pt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:pt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:pt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:pt("toggleCliView",e)}]}function Ji(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(mh(e).map(n=>[n.id,n.defaultShortcut]));try{const n=JSON.parse(localStorage.getItem(ph)||"{}"),a={...t,...n};for(const[r,o]of qN)a[r]===o&&(a[r]=t[r]);return a}catch{return t}}function hh(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function zN({enabled:e=!0,onTrigger:t}){const n=GN(),[a,r]=l.useState(()=>zr(n)),[o,i]=l.useState(null),[c,u]=l.useState([]),p=l.useRef({parts:[],timer:null}),d=l.useCallback(f=>{const x=[];return f.metaKey&&x.push(n?"⌘":"Meta"),f.ctrlKey&&x.push("Ctrl"),f.altKey&&x.push(n?"⌥":"Alt"),f.shiftKey&&f.key.length!==1&&x.push(n?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(x.push(hh(f.key)),x.join("+"))},[n]),m=l.useCallback(f=>{r(f);try{localStorage.setItem(ph,JSON.stringify(f))}catch{}},[]);l.useEffect(()=>{const f=zr(n),x=Object.entries(a),w=Object.entries(f);x.length===w.length&&x.every(([b,N])=>f[b]===N)||m(f)},[a,n,m]);const h=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}},UN))},[]);l.useEffect(()=>{if(!o)return;const f=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){i(null),u([]);return}const w=d(x);if(!w)return;const N=!(x.metaKey||x.ctrlKey||x.altKey)&&/^[A-Z0-9]$/.test(w);if(c.length===0&&N){u([w]);return}const v=[...c,w].slice(0,2).join(" "),y={...a};for(const[C,S]of Object.entries(y))S===v&&delete y[C];y[o]=v,m(y),i(null),u([])};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[a,d,m,o,c]),l.useEffect(()=>{if(!e||o)return;const f=x=>{if(x.defaultPrevented)return;const w=d(x);if(!w)return;const b=x.metaKey||x.ctrlKey||x.altKey;if(Ji(x.target))return;const N=p.current.parts,j=b?[w]:[...N.slice(-1),w].slice(-2),v=j.join(" "),y=j[j.length-1],C=Object.entries(a).filter(([,D])=>!!D),S=C.find(([,D])=>D===v);if(S){x.preventDefault(),h(),t(S[0]);return}if(C.some(([,D])=>D.startsWith(`${v} `))){x.preventDefault(),p.current.parts=j,g();return}const M=C.find(([,D])=>D===y);if(M){x.preventDefault(),h(),t(M[0]);return}if(C.some(([,D])=>D.startsWith(`${y} `))){x.preventDefault(),p.current.parts=[y],g();return}h()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[a,g,e,d,t,h,o]),l.useEffect(()=>()=>h(),[h]);const k=l.useMemo(()=>mh(n),[n]);return{isMac:n,actionDefinitions:k,actionShortcuts:a,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:u,saveShortcuts:m}}function KN({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 fh(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function Ed({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:n,ides:a}){return!e||n>0?!1:t?!fh(a):!0}function VN({previousVisibleConversationCount:e,visibleConversationCount:t,ides:n}){return t>0||e<=0?!1:fh(n)}const bh=1e3,YN=4;function _d(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function Hd(e,t,n){return Math.abs(t.clientX-e.clientX)>n||Math.abs(t.clientY-e.clientY)>n}function QN({detachDelayMs:e=bh,stillnessThresholdPx:t=YN,onDetach:n,setTimeoutFn:a=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:r=globalThis.clearTimeout.bind(globalThis)}){let o=null,i=null,c=null,u=null,p=null,d=!1;const m=()=>{p!=null&&(r(p),p=null)},h=()=>{m(),c=null},g=()=>{m(),o=null,i=null,c=null,u=null,d=!1},k=()=>{!o||!c||!u||d||p!=null||(p=a(()=>{p=null,!(!o||!c||!u||d)&&_d(u,i)&&(Hd(c,u,t)||(d=!0,n({panelId:o,clientX:u.clientX,clientY:u.clientY})))},e))},f=w=>{if(!(!o||d)){if(!_d(w,i)){u={clientX:w.clientX,clientY:w.clientY},h();return}(!c||Hd(c,w,t))&&(m(),c={clientX:w.clientX,clientY:w.clientY}),u={clientX:w.clientX,clientY:w.clientY},k()}},x=w=>{!o||d||(w&&(u={clientX:w.clientX,clientY:w.clientY}),h())};return{startDrag:w=>{m(),o=w.panelId,i=w.selfPanelBounds??null,c=null,u={clientX:w.clientX,clientY:w.clientY},d=!1},markSelfPanel:f,markNonSelfPanel:x,markNoDropTarget:x,markDockTarget:x,endDrag:g,isDragging:()=>o!=null,hasDetached:()=>d,dispose:g}}function JN(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function Cr(e){return kt(e)||e.tabKey}function XN(e){return`remote:${e}`}function ps(e){return e.startsWith("remote:")}function $d(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Jo(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 Xo(e,t){e.classList.remove(ki.className,Si.className),e.classList.add(t==="light"?ki.className:Si.className)}function Fd(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 ZN(e,t,n){var i;const a=[t];let r;for(const c of a){let u;for(const p of c){const d=e.addPanel({id:p.tabKey,component:"conversation",title:Cr(p),params:{kind:"conversation",tabKey:p.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:r?{position:{referencePanel:r,direction:"right"},inactive:!0}:{}});u||(u=d.id)}r=u??r}return n??((i=t[0])==null?void 0:i.tabKey)??null}function Bd(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])ps(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!==Cr(r)&&o.api.setTitle(Cr(r));continue}e.addPanel({id:r.tabKey,component:"conversation",title:Cr(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 Wd(e,t,n){var u,p;const a=n?XN(n):null;for(const d of[...e.panels])ps(d.id)&&(!a||d.id!==a)&&e.removePanel(d);if(!n||!a)return;const r=xs(t,n);if(!r&&e.totalPanels===0)return;const o=e.getPanel(a),i=fm(r);if(o){o.title!==i&&o.api.setTitle(i);return}const c=(r==null?void 0:r.tabKey)??((u=e.activePanel)==null?void 0:u.id)??((p=e.panels.find(d=>!ps(d.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 gh({doId:e,targetSessionId:t,connState:n,viewMode:a}){const[r,o]=l.useState(null),[i,c]=l.useState(null);l.useEffect(()=>e?jt.onScreenshot("ide-page",(d,m)=>{if(d!==e)return;const h=new FileReader;h.onload=()=>o(h.result),h.readAsDataURL(m)}):void 0,[e]),l.useEffect(()=>{n!=="connected"&&o(null)},[n]),l.useEffect(()=>{var d;return e?((d=jt.onStatus)==null?void 0:d.call(jt,(m,h)=>{m===e&&h!=null&&h.screenshotUsage&&c(h.screenshotUsage)}))||(()=>{}):void 0},[e]),l.useEffect(()=>{o(null)},[e,t]),l.useEffect(()=>{const p=e?jt.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 u=l.useCallback(async(p,d)=>{const m=e?jt.get(e):null;return!m||n!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):m.sendInput(p,d,t)},[e,n,t]);return{connScreenshot:r,screenshotUsage:i,handleRemoteAction:u}}const xh=l.createContext(null);function fo(){const e=l.useContext(xh);if(!e)throw new Error("DashboardDockviewContext missing");return e}function eA(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 tA({params:e}){var u;const t=fo(),n=l.useMemo(()=>xs([...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)||((u=n==null?void 0:n.routeId)==null?void 0:u.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:i,handleRemoteAction:c}=gh({doId:r,targetSessionId:n?qp(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(lp,{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 sA(){const e=fo();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(Vl,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels,isLoading:!ho(e.ides,e.initialDataLoaded)})})}function nA(e){var b,N;eA(e);const t=fo(),n=l.useCallback(j=>{"button"in j&&j.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(j=>TS(j),[]),i=l.useCallback(()=>PS(r),[r]),c=l.useSyncExternalStore(o,i,i);if(e.params.kind==="remote"){const j=xs([...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":(j==null?void 0:j.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:j!=null&&j.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:j.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const u=t.conversationsByTabKey.get(e.params.tabKey);if(!u)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=((N=e.api.group.activePanel)==null?void 0:N.id)===e.api.id,d=e.api.isGroupActive,m=to(u,t.liveSessionInboxState,{isOpenConversation:p}),h=m.isReconnecting,g=m.isConnecting,k=m.isGenerating||c,f=m.isWaiting,x=m.unread,w=t.tabShortcuts[u.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${p?" is-active":""}${d?" is-group-active":""}${h?" is-reconnecting":""}`,title:kt(u),"data-tab-key":e.params.tabKey,onMouseDown:n,onTouchStart:n,onContextMenu:j=>{var v;j.preventDefault(),n(j),t.openTabContextMenu({x:j.clientX,y:j.clientY,tabKey:u.tabKey,sourceDocument:((v=j.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("div",{className:"tab-spinner"}):f?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):h?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):g?s.jsx("div",{className:"tab-connecting-spinner"}):u.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(u)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:h?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:mn(u)}):g?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:mn(u)}):s.jsx("span",{children:mn(u)})})]}),w&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:w,children:w})]})}function ir(e){return e.isActive}function Od(e){return e.isVisible}function aA(e){e.preventDefault()}function rA({params:e,api:t}){var g;const n=fo(),a=l.useRef(null),[r,o]=l.useState(()=>ir(t)),[i,c]=l.useState(()=>Od(t)),u=n.conversationsByTabKey.get(e.tabKey),p=io({sendDaemonCommand:n.sendDaemonCommand,activeConv:u,setActionLogs:n.setActionLogs,isStandalone:n.isStandalone});l.useEffect(()=>{o(ir(t)),c(Od(t));const k=[t.onDidActiveChange(f=>o(f.isActive)),t.onDidActiveGroupChange(f=>{if(!ir(t)&&!f.isActive){o(!1);return}o(ir(t))}),t.onDidVisibilityChange(f=>c(f.isVisible))];return()=>{for(const f of k)f.dispose()}},[t]);const d=l.useMemo(()=>u?n.ides.find(k=>k.id===u.routeId):void 0,[n.ides,u]),m=l.useMemo(()=>u?n.actionLogs.filter(k=>k.routeId===u.tabKey):[],[n.actionLogs,u]);if(!u)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(Vl,{conversationsCount:0,isSplitMode:!1,isStandalone:n.isStandalone,hasRegisteredMachines:n.hasRegisteredMachines,onOpenNewSession:n.onOpenNewSession,suppressGuide:n.hasDetachedConversationPanels,isLoading:!ho(n.ides,n.initialDataLoaded)})});const h=!ut(u)&&Zn(u)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(zl,{activeConv:u,clearToken:n.clearedTabs[u.tabKey]||0,isCliTerminal:h,ideEntry:d,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)===u.tabKey?n.scrollToBottomRequest.nonce:void 0,isInputActive:r,isVisible:i})})}function oA({visibleConversations:e,clearedTabs:t,ides:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:u,userName:p,toggleHiddenTab:d,actionShortcuts:m,registerActionHandlers:h,onActiveTabChange:g,onOpenNewSession:k,onRequestScrollToBottom:f,requestedActiveTabKey:x,requestedRemoteIdeId:w,onRequestedActiveTabConsumed:b,scrollToBottomRequest:N,liveSessionInboxState:j,layoutProfile:v}){var bt,it,yt;const{theme:y}=tn(),{sendCommand:C}=vt(),S=l.useRef(null),A=l.useRef(null),M=l.useRef(null),I=l.useRef(!1),D=l.useRef(!1),P=l.useRef(!1),T=l.useRef(null),H=l.useRef([]),[L,R]=l.useState(null),[U,E]=l.useState(0),$=l.useRef(typeof window>"u"?{}:C1(v)),_=l.useMemo(()=>new Map(e.map(se=>[se.tabKey,se])),[e]),q=l.useMemo(()=>{const se=S.current;return se?se.groups.some(oe=>{try{const pe=oe.model.location.type;return pe!=="floating"&&pe!=="popout"?!1:oe.panels.some(ye=>_.has(ye.id))}catch{return!1}}):!1},[_,U,e]),B=l.useCallback(()=>{var se;(se=S.current)==null||se.focus()},[]),W=l.useCallback((se,oe)=>{f==null||f(se,oe)},[f]),V=l.useCallback(se=>{const oe=document,pe=se.document;for(const Te of oe.querySelectorAll('link[rel="stylesheet"]')){const Ue=pe.createElement("link");Ue.rel="stylesheet",Ue.href=Te.href,Te.crossOrigin&&(Ue.crossOrigin=Te.crossOrigin),pe.head.appendChild(Ue)}for(const Te of oe.querySelectorAll("style")){const Ue=pe.createElement("style");Ue.textContent=Te.textContent,pe.head.appendChild(Ue)}const ye=[];for(const Te of oe.styleSheets)try{for(const Ue of Te.cssRules)Ue instanceof CSSStyleRule&&(Ue.selectorText===":root"||Ue.selectorText==="html")&&ye.push(Ue.cssText)}catch{}if(ye.length>0){const Te=pe.createElement("style");Te.textContent=ye.join(`
|
|
64
|
+
The machine's IDE, workspace and provider settings are kept.`,confirmLabel:o("machine.connectedMachines.remove"),confirmColor:"red",onConfirm:M,onCancel:()=>m(null)})]})}const Cj=["default","claude-cli","codex-cli","antigravity-cli","hermes-cli","gemini-cli"];function jj({daemonId:e,knownCliTypes:t=Cj}){const{t:n}=Ce("common"),{sendCommand:a}=vt(),[r,o]=l.useState({}),[i,c]=l.useState({}),[u,p]=l.useState(!0),[d,m]=l.useState(null),[h,g]=l.useState(null),[k,f]=l.useState(""),x=l.useCallback(async()=>{if(e){p(!0),g(null);try{const N=await a(e,"list_coordinator_prompts",{}),j=N!=null&&N.result&&typeof N.result=="object"?N.result:N;if(!(j!=null&&j.success)){g((j==null?void 0:j.error)||"Failed to load");return}const v=j.entries||{};f(j.dir||"");const y={};for(const C of t)y[C]=v[C]||{override:"",append:""};for(const C of Object.keys(v))y[C]||(y[C]=v[C]);o(y),c(JSON.parse(JSON.stringify(y)))}catch(N){g((N==null?void 0:N.message)||String(N))}finally{p(!1)}}},[a,e,t]);l.useEffect(()=>{x()},[x]);const w=l.useCallback(async(N,j)=>{var v;if(e){m(`${N}:${j}`),g(null);try{const y=((v=r[N])==null?void 0:v[j])||"",C=await a(e,"write_coordinator_prompt",{key:N,kind:j,content:y}),S=C!=null&&C.result&&typeof C.result=="object"?C.result:C;if(!(S!=null&&S.success)){g((S==null?void 0:S.error)||"Save failed");return}c(A=>({...A,[N]:{...A[N]||{override:"",append:""},[j]:y}}))}catch(y){g((y==null?void 0:y.message)||String(y))}finally{m(null)}}},[a,e,r]),b=l.useMemo(()=>(N,j)=>{var v,y;return(((v=r[N])==null?void 0:v[j])||"")!==(((y=i[N])==null?void 0:y[j])||"")},[r,i]);return e?s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{className:"text-[12px] text-text-muted",children:[s.jsxs("p",{children:["Customize the coordinator prompt this daemon's mesh coordinator sessions get. ",s.jsx("span",{className:"font-mono text-[11px]",children:k||"~/.adhdev/coordinator-prompts/"})]}),s.jsxs("p",{className:"mt-1",children:[s.jsx(wi,{i18nKey:"settings.coordinatorPrompts.overrideDesc",ns:"common",components:{strong:s.jsx("strong",{})}})," ",s.jsx(wi,{i18nKey:"settings.coordinatorPrompts.appendDesc",ns:"common",components:{strong:s.jsx("strong",{})}}),"Leave a field empty + Save to remove it (reset to default). Supports placeholders: ","{{meshName}}",", ","{{repo}}",", ","{{nodes}}",", ","{{rules}}",", etc."]})]}),h&&s.jsx("div",{className:"text-[12px] text-status-error bg-status-error/10 border border-status-error/40 rounded px-3 py-2",children:h}),u&&s.jsx("div",{className:"text-[12px] text-text-muted",children:"Loading…"}),s.jsx("div",{className:"flex flex-col gap-6",children:Object.entries(r).map(([N,j])=>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-2",children:N}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:n("settings.coordinatorPrompts.overrideLabel")}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:4,value:j.override,onChange:v=>o(y=>({...y,[N]:{...y[N],override:v.target.value}})),placeholder:"(empty — use daemon default base prompt)",disabled:d===`${N}:override`}),s.jsx("div",{className:"mt-1 mb-3 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void w(N,"override"),disabled:d===`${N}:override`||!b(N,"override"),children:d===`${N}:override`?"Saving…":b(N,"override")?"Save override":"Saved"})}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:n("settings.coordinatorPrompts.appendLabel")}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:3,value:j.append,onChange:v=>o(y=>({...y,[N]:{...y[N],append:v.target.value}})),placeholder:"(empty — nothing appended at this layer)",disabled:d===`${N}:append`}),s.jsx("div",{className:"mt-1 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void w(N,"append"),disabled:d===`${N}:append`||!b(N,"append"),children:d===`${N}:append`?"Saving…":b(N,"append")?"Save append":"Saved"})})]},N))})]}):s.jsx("div",{className:"text-[12px] text-text-muted",children:"Connect a daemon to edit coordinator prompts."})}const Nj=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Aj(){const{preference:e,setPreference:t}=tn();return s.jsx("div",{className:"flex gap-2",children:Nj.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("span",{children:n.icon}),n.label]},n.id))})}function Mj(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 Pj(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Wo(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function vd(e){const{r:t,g:n,b:a}=Pj(e);return .2126*Wo(t)+.7152*Wo(n)+.0722*Wo(a)}function yd(e,t){const n=vd(e),a=vd(t),r=Math.max(n,a),o=Math.min(n,a);return(r+.05)/(o+.05)}function Hm(e){const t=Mj(e);if(!t)return"#111827";const n="#111827",a="#ffffff";return yd(t,n)>=yd(t,a)?n:a}const zi={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},Ki={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},Tj=[{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"}}}],$m="adhdev-chat-theme",Fm="adhdev-chat-theme-custom";function wr(){if(typeof window>"u")return"ember";try{return localStorage.getItem($m)||"ember"}catch{return"ember"}}function hs(e){try{const t=localStorage.getItem(Fm);if(t){const n=JSON.parse(t);return{...e==="dark"?zi:Ki,...n[e]}}}catch{}return e==="dark"?zi:Ki}function tr(e,t){try{localStorage.setItem(Fm,JSON.stringify({dark:e,light:t}))}catch{}}function Zt(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 qr(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 Dj={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Na(e,t){var r;const n=(r=Dj[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",qr(n,24)),a.style.setProperty("--accent-on-primary",Hm(n)),a.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${n}, ${qr(n,18)})`),a.style.setProperty("--border-accent",Zt(n,.35)),a.style.setProperty("--nav-active-bg",Zt(n,.1)),a.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${n}, 0 0 12px ${Zt(n,.06)}`)}function hn(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",Zt(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Zt(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Zt(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",Zt(e.borderSubtle,.5)),t.style.setProperty("--border-default",Zt(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",qr(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Hm(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${qr(e.accentColor,40)})`),t.style.setProperty("--border-accent",Zt(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",Zt(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Zt(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 ${Zt(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 Fl(){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 Ij(e){try{localStorage.setItem($m,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=fn()?"dark":"light";hn(hs(t))}else Fl(),Na(e,fn()?"dark":"light")}function Lj(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=wr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=fn()?"dark":"light";hn(hs(t))}else Fl(),Na(e,fn()?"dark":"light")}function fn(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function qt({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 ua({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 Rj({dark:e,onColorsChange:t}){const{t:n}=Ce("common"),a=e?"dark":"light",[r,o]=l.useState(()=>hs(a));l.useEffect(()=>{o(hs(a))},[a]);const i=l.useCallback((c,u)=>{o(p=>{const d={...p,[c]:u},h=hs(a==="dark"?"light":"dark");return a==="dark"?tr(d,h):tr(h,d),hn(d),t(d),d})},[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(ua,{title:n("settings.theme.sectionAppBackground"),children:[s.jsx(qt,{label:n("settings.theme.colorBackground"),value:r.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(qt,{label:n("settings.theme.colorSurface"),value:r.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(qt,{label:n("settings.theme.colorCard"),value:r.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(ua,{title:n("settings.theme.sectionAppText"),children:[s.jsx(qt,{label:n("settings.theme.colorPrimary"),value:r.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(qt,{label:n("settings.theme.colorSecondary"),value:r.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(qt,{label:n("settings.theme.colorMuted"),value:r.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(ua,{title:n("settings.theme.sectionBordersAccent"),children:[s.jsx(qt,{label:n("settings.theme.colorBorderSubtle"),value:r.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(qt,{label:n("settings.theme.colorBorderDefault"),value:r.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(qt,{label:n("settings.theme.colorAccent"),value:r.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(ua,{title:n("settings.theme.sectionChatBubbles"),children:[s.jsx(qt,{label:n("settings.theme.colorUserBubble"),value:r.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(qt,{label:n("settings.theme.colorUserText"),value:r.userText,onChange:c=>i("userText",c)}),s.jsx(qt,{label:n("settings.theme.colorAgentBubble"),value:r.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(qt,{label:n("settings.theme.colorAgentText"),value:r.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(ua,{title:n("settings.theme.sectionChatLayout"),children:[s.jsx(qt,{label:n("settings.theme.colorChatBg"),value:r.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(qt,{label:n("settings.theme.colorSendButton"),value:r.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(qt,{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?zi:Ki,p=hs(e?"light":"dark");e?tr(c,p):tr(p,c),o(c),hn(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 Ej(){const{t:e}=Ce("common"),[t,n]=l.useState(wr),[a,r]=l.useState(!0),[o,i]=l.useState(()=>hs("dark"));l.useEffect(()=>{r(fn());const p=new MutationObserver(()=>{const h=fn();r(h);const g=wr();g==="custom"?hn(hs(h?"dark":"light")):Na(g,h?"dark":"light")});p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const d=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const h=fn();r(h);const g=wr();g==="custom"?hn(hs(h?"dark":"light")):Na(g,h?"dark":"light")};return d.addEventListener("change",m),()=>{p.disconnect(),d.removeEventListener("change",m)}},[]),l.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?hn(hs(a?"dark":"light")):(Fl(),Na(t,a?"dark":"light"))},[t,a]),l.useEffect(()=>{i(hs(a?"dark":"light"))},[a]);const c=p=>{n(p),Ij(p)},u=[...Tj,{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:u.map(p=>{const d=t===p.id,m=a?p.preview.dark:p.preview.light,h=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:d?"var(--bg-glass-hover)":"var(--bg-glass)",border:d?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:d?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:h},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:[d&&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(Rj,{dark:a,onColorsChange:p=>i(p)})]})}const Bl="adhdev_mobileDashboardMode_v1",Vi="adhdev:mobile-dashboard-mode-change";function Wl(){try{return localStorage.getItem(Bl)==="workspace"?"workspace":"chat"}catch{return"chat"}}function _j(e){if(typeof window>"u")return()=>{};const t=r=>{e(r??Wl())},n=r=>{const o=r.detail;t(o)},a=r=>{r.key&&r.key!==Bl||t()};return window.addEventListener(Vi,n),window.addEventListener("storage",a),()=>{window.removeEventListener(Vi,n),window.removeEventListener("storage",a)}}function Hj(e){try{localStorage.setItem(Bl,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Vi,{detail:e}))}function $j(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(Wl()==="chat")},[]),s.jsx(cn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Cn,{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),Hj(n?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const Fj="Choose a preset or create a fully custom theme. Custom themes control the entire app — backgrounds, text, borders, and chat bubbles.",Bj="Choose whether the dashboard opens like a chat app on phones or keeps the full workspace layout.";function Wj({themeDescription:e=Fj,mobileDescription:t=Bj,fontsSlot:n}){const{t:a}=Ce("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(Aj,{})]}),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(Ej,{})]}),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($j,{})]})]})}const Oo=new Map,wd=new Map;function Oj(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 Uj(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 Bm(){const{sendCommand:e}=vt(),{injectEntries:t,getIdes:n}=Pa();return l.useCallback(async(a,r)=>{if(!a)return;const o=(r==null?void 0:r.minFreshMs)??Qk,i=wd.get(a)||0;if(!(r!=null&&r.force)&&i>0&&Date.now()-i<o)return;const c=Oo.get(a);if(c)return c;const u=(async()=>{const p=await e(a,"get_machine_runtime_stats"),d=Oj(p);if(!d)return;const m=n().find(g=>g.id===a),h=Uj(m,a,d.machine,d.timestamp||Date.now());t([h]),wd.set(a,Date.now())})().finally(()=>{Oo.delete(a)});return Oo.set(a,u),u},[n,t,e])}function qj(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 Gj(e,t){const{sendData:n}=vt(),{injectEntries:a,getIdes:r}=Pa(),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(u=>gs.subscribe({sendData:n},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:t==null?void 0:t.intervalMs}},d=>{const m=r().find(g=>g.id===u),h=qj(m,u,d);a([h])}));return()=>{c.forEach(u=>u())}},[o,r,a,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,n])}function zj(e,t){const{sendData:n}=vt(),[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 u=gs.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 u.initialSendAccepted?c=setTimeout(()=>{i(!1)},Zk):i(!1),()=>{c&&clearTimeout(c),u()}},[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 Kj(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Wm(e){const{sendData:t}=vt(),[n,a]=l.useState({});return l.useEffect(()=>{const r=Kj(e);if(!r||!e.sessionId||!t){a({});return}const o=gs.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}),Un.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 Vj(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function Yj(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 Qj(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 Jj({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(!Vj(o))throw new Error(Yj(o));return}await Qj(e.sessionId,t,r)}function Om(e){const{ides:t,isP2PActive:n,p2pStates:a}=ys(),{sendCommand:r}=vt(),[o,i]=l.useState(null),[c,u]=l.useState(!1),[p,d]=l.useState(null),m=l.useRef(!1),h=l.useMemo(()=>Dg(t,e),[t,e]),g=!!h,k=l.useMemo(()=>h?h.prompt.promptId===o?null:h:null,[o,h]),f=l.useCallback(async b=>{if(!k||m.current)return;m.current=!0;const N=cp(k.prompt,b);u(!0),d(null);try{const j=(a==null?void 0:a[k.daemonId])==="connected"||n===!0;await Jj({promptSession:k,response:N,useP2PCommand:j,sendCommand:r}),i(k.prompt.promptId)}catch(j){throw d(j instanceof Error?j.message:String(j)),j}finally{u(!1),m.current=!1}},[n,a,k,r]),x=l.useCallback(()=>{k&&i(k.prompt.promptId)},[k]),w=l.useCallback(()=>{i(null),d(null)},[]);return{promptSession:k,hasActivePrompt:g,responseError:p,isSubmitting:c,submit:f,cancel:x,reopen:w}}function Um(e){return e instanceof Error?e.message:String(e||"")}function Xj(e){const t=Um(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 Zj(e){const t=Um(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function qm({conversation:e,mode:t,ides:n,sendDaemonCommand:a,setCliViewModeOverrides:r}){if(!e||!mt(e)||ut(e))return;const o=Zn(e);if(o===t)return;const i=e.sessionId;i&&r(c=>({...c,[i]:t}));try{await a(Bs(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Ms(e),mode:t})}catch(c){const u=Zj(c);i&&!u&&r(p=>{const d={...p};return o===t1(n,i)?delete d[i]:d[i]=o,d}),Xj(c)?console.warn(u?"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 e1(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(u=>kd(u,t)):r.childSessions,c=i!==r.childSessions;return o!==r||c?(n=!0,{...o,...c?{childSessions:i}:{}}):r});return n?a:e}function t1(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 s1({visibleConversations:e,clearedTabs:t,setClearedTabs:n,setActionLogs:a,isConversationMuted:r}){l.useEffect(()=>{Ap()},[]);const o=l.useMemo(()=>e.map(i=>({id:i.tabKey,name:hm(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 g0(o),l.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{n(u=>{const p=Date.now(),d={};for(const[m,h]of Object.entries(u))p-h<5e3&&(d[m]=h);return Object.keys(d).length===Object.keys(u).length?u:d})},5500);return()=>clearTimeout(c)},[t,n]),l.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;a(u=>{const p=u.filter(d=>d.timestamp>c).slice(-100);return p.length===u.length?u:p})},6e4);return()=>clearInterval(i)},[a]),null}function Sd(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 bn(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=Sd(t==null?void 0:t.receivedAt)||Sd(t==null?void 0:t.timestamp)||0;return Math.max(n,a)}function Yi(e,t=0){return bn(e)||e.lastUpdated||t||0}function Gm(e){return bn(e)||e.lastUpdated||0}function zm(e,t,n=Gm){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 Qi(e){var n;const t=ts(e.status,{activeModal:(n=e.modalButtons)!=null&&n.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function n1(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!Qi(e)&&!e.title.trim()}function a1(e){return e.length===0?null:[...e].sort((t,n)=>{const a=Number(Qi(n))-Number(Qi(t));if(a!==0)return a;const r=n.messages.length-t.messages.length;return r!==0?r:zm(t,n)})[0]||null}function xs(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=a1(r);return a?o&&n1(a)?o:a:o||n[0]||null}function r1(e){const t=e.filter(r=>r.type!=="adhdev-daemon"),n=new Set;for(const r of t){if(!Ei(r))continue;const o=wp(r);o&&n.add(o)}const a=new Map;for(const r of t){const o=Kw(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),u=c(i),p=c(r),d=p>u||p===u&&(r.timestamp||0)>(i.timestamp||0)?r:i;a.set(o,o1(d,d===r?i:r))}return Array.from(a.values())}function o1(e,t){const n=Ei(t),a=Ei(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,u=o==null?void 0:o.settings;return{...e,...i&&{ownerDaemonId:i},...c&&!e.ownerMachineName&&{ownerMachineName:c},...u&&!a&&{settings:{...u,...e.settings??{}}}}}function Uo(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 i1(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 Cd(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],n=t[t.length-1],a=n?i1(qn(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 l1(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||""),Cd(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||""),Cd(n.activeChat)].join(":"))].join("|")}function c1(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 d1(e,t){const n=new Map;for(const a of e){const r=t.get(a.routeId)||a;for(const o of Sa({routeId:a.routeId}))n.set(o,r);for(const o of Sa({providerSessionId:a.providerSessionId,sessionId:a.sessionId}))n.set(o,a.streamSource==="native"?r:a);for(const o of Sa({tabKey:a.tabKey}))n.set(o,a)}return n}function u1(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function p1(e){const t=u1(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=qn(t.content).slice(0,240);return`${e.messages.length}:${n}:${a}`}function m1({ides:e,connectionStates:t,clearedTabs:n}){const a=l.useMemo(()=>r1(e),[e]),r=l.useMemo(()=>pp(e),[e]),o=l.useMemo(()=>jm(e),[e]),i=l.useRef([]),c=l.useRef([]),u=l.useRef([]),p=l.useRef(new Map),d=l.useRef(new Map),m=l.useMemo(()=>{const j=new Map,v=[];for(const A of a){const{connectionState:M="new",machineName:I}=Nm(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),D=l1(A),P=p.current.get(A.id);if(P&&P.ide===A&&P.sourceSignature===D&&P.connectionState===M&&P.machineName===I){j.set(A.id,P),v.push(...P.conversations);continue}const T=Hl(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),H={ide:A,sourceSignature:D,connectionState:M,machineName:I,conversations:T};j.set(A.id,H),v.push(...T)}p.current=j;const y=new Map,C=A=>{const M=p1(A),I=d.current.get(A.tabKey);if(I&&I.signature===M)return y.set(A.tabKey,I),I.timestamp;const D={signature:M,timestamp:Gm(A)||(I==null?void 0:I.timestamp)||0};return y.set(A.tabKey,D),D.timestamp},S=[...v].sort((A,M)=>zm(A,M,C));return d.current=y,S},[a,t,o]),h=l.useMemo(()=>{const j=c1(m,n);return Uo(i.current,j)?i.current:(i.current=j,j)},[m,n]),g=l.useMemo(()=>{const j=new Map,v=Array.from(new Set(h.map(y=>y.routeId)));for(const y of v){const C=xs(h,y);C&&j.set(y,C)}return j},[h]),k=l.useMemo(()=>{const j=new Map;for(const v of h){const y=g.get(v.routeId),C=v.streamSource==="native"&&y?y:v;for(const S of Sa({providerSessionId:v.providerSessionId,sessionId:v.sessionId,tabKey:v.tabKey}))j.set(S,C)}return j},[h,g]),f=l.useMemo(()=>d1(h,g),[h,g]),x=l.useCallback(j=>{if(j)return k.get(j)},[k]),w=l.useCallback(j=>{if(j)return f.get(j)},[f]),b=l.useMemo(()=>{const j=h.filter(v=>!Js(v,r).surfaceHidden);return Uo(c.current,j)?c.current:(c.current=j,j)},[h,r]),N=l.useMemo(()=>{const j=b.map(v=>v.tabKey);return Uo(u.current,j)?u.current:(u.current=j,j)},[b]);return{chatIdes:a,conversations:h,visibleConversations:b,visibleTabKeys:N,resolveConversationBySessionId:x,resolveConversationByTarget:w}}function h1({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 u=new URLSearchParams(c);return u.delete("activeTab"),u},{replace:!0})},[a,t]);return{requestedDesktopTabKey:r,requestedMobileTabKey:o,consumeRequestedActiveTab:i}}function f1({ides:e,sendDaemonCommand:t,setToasts:n,resolveConversationByTarget:a}){l.useEffect(()=>{ft.setIdes(e)},[e]),l.useEffect(()=>{ft.setResolveAction((r,o,i)=>{t(r,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const r=ft.onToast(o=>{n(c=>c.some(p=>p.message===o.message&&o.timestamp-p.timestamp<3e3)?c:[...c.slice(-4),{id:o.id,message:o.message,type:o.type,timestamp:o.timestamp,targetKey:o.targetKey,actions:o.actions}]);const i=o.duration||5e3;setTimeout(()=>n(c=>c.filter(u=>u.id!==o.id)),i)});return()=>{r()}},[n]),l.useEffect(()=>{const r=dm.on("status_event",o=>{ft.handleRawEvent(o,"ws")});return()=>{r()}},[]),l.useEffect(()=>{var o;const r=i=>{var f;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 u=c.targetSessionId||c.targetKey||c.daemonId,p=a(u),d=(p==null?void 0:p.routeId)||c.daemonId;if(!d)return;const m=Number(c.buttonIndex),h=c.button||((f=p==null?void 0:p.modalButtons)==null?void 0:f[m])||"Approve",g=String(h).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),k=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(g);t(d,"resolve_action",{action:k?"approve":"reject",button:h,...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 b1="adhdev_dashboardLayout_v1",g1="adhdev_dashboardDockview_v1",x1="adhdev_dashboardDockviewHiddenRestore_v1",pa={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Ol(e,t){try{const n=localStorage.getItem(e);return n?JSON.parse(n):t}catch{return t}}function v1(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Km(e){return`${b1}:${e}`}function y1(e){const t=Km(e);return Ol(t,null)}function w1(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=Km(e);if(n){localStorage.removeItem(a);return}localStorage.setItem(a,JSON.stringify(t))}catch{}}function Vm(e){return`${g1}:${e}`}function k1(e){const t=Vm(e);return Ol(t,null)}function S1(e,t){try{const n=Vm(e);if(!t){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Ym(e){return`${x1}:${e}`}function C1(e){const t=Ym(e);return Ol(t,{})}function j1(e,t){try{const n=Ym(e);if(Object.keys(t).length===0){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function N1(){return{groupAssignments:[...pa.groupAssignments],focusedGroup:pa.focusedGroup,groupActiveTabIds:{...pa.groupActiveTabIds},groupTabOrders:{...pa.groupTabOrders},groupSizes:[...pa.groupSizes]}}function A1(e,t){return e?e.length===t.length&&e.every((n,a)=>n===t[a]):t.length===0}function M1(){const[e]=l.useState(()=>v1(typeof window<"u"?window.innerWidth:1280)),[t,n]=l.useState(()=>new Map),[a,r]=l.useState(0),[o,i]=l.useState({}),[c,u]=l.useState({}),[p,d]=l.useState([]),[m,h]=l.useState(()=>typeof window<"u"&&window.innerWidth<768),[g,k]=l.useState(!1),f=l.useCallback(()=>{if(g)return;const A=y1(e)??N1();n(new Map(A.groupAssignments)),r(A.focusedGroup),i(A.groupActiveTabIds),u(A.groupTabOrders),d(A.groupSizes),k(!0)},[g,e]);l.useEffect(()=>{g&&w1(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)"),M=I=>h(I.matches);return A.addEventListener("change",M),()=>A.removeEventListener("change",M)},[]);const x=l.useCallback(A=>{n(A)},[]),w=l.useCallback(A=>{r(A)},[]),b=l.useCallback(A=>{i(A)},[]),N=l.useCallback(A=>{u(A)},[]),j=l.useCallback(A=>{d(A)},[]),v=l.useCallback(A=>{w(A)},[w]),y=l.useCallback((A,M)=>{i(I=>(I[A]??null)===(M??null)?I:{...I,[A]:M})},[]),C=l.useCallback((A,M)=>{u(I=>{const D=I[A];return A1(D,M)?I:{...I,[A]:M}})},[]),S=l.useCallback((A,M)=>{const I=M.get(A)??0;return y(I,A),v(I),I},[v,y]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:x,focusedGroup:a,updateFocusedGroup:w,focusGroup:v,groupActiveTabIds:o,updateGroupActiveTabIds:b,setGroupActiveTab:y,groupTabOrders:c,updateGroupTabOrders:N,setGroupTabOrder:C,groupSizes:p,updateGroupSizes:j,isMobile:m,hasHydratedStoredLayout:g,hydrateStoredLayout:f,focusConversationTab:S}}function P1(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0],a=so(t);return typeof(n==null?void 0:n.id)=="string"&&a.includes(n.id)}function T1({urlActiveTab:e,conversations:t,resolveConversationBySessionId:n,normalizedGroupAssignments:a,hasHydratedStoredLayout:r,hydrateStoredLayout:o,focusConversationTab:i,setSearchParams:c,historyModalOpen:u,activeConv:p,isRefreshingHistory:d,ides:m,handleRefreshHistory:h}){const g=l.useRef(!1),k=l.useRef(!1),f=l.useRef(null),x=l.useRef(!1);l.useEffect(()=>{if(!e||g.current||t.length===0)return;if(!r){o();return}const w=n(e);w&&(i(w.tabKey,a),g.current=!0,k.current=!0,f.current!=null&&(window.clearTimeout(f.current),f.current=null),c(b=>{const N=new URLSearchParams(b);return N.delete("activeTab"),N},{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(f.current==null)return f.current=window.setTimeout(()=>{f.current=null,!(k.current||r)&&(o(),k.current=!0)},1500),()=>{f.current!=null&&(window.clearTimeout(f.current),f.current=null)}}},[e,t.length,r,o]),l.useEffect(()=>{if(!u){x.current=!1;return}if(!p||x.current||d)return;const w=m.find(b=>b.id===p.routeId);w&&(!w.chats||w.chats.length===0||P1(w.chats,p))&&(x.current=!0,h())},[u,p,d,m,h])}function qo(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=so(t);return typeof(n==null?void 0:n.id)=="string"&&a.includes(n.id)}function Qm({sendDaemonCommand:e,activeConv:t,chats:n,updateRouteChats:a,setToasts:r,setClearedTabs:o}){const[i,c]=l.useState(!1),[u,p]=l.useState(!1),d=l.useCallback(async k=>{try{await e("standalone","launch_ide",{ideType:k,enableCdp:!0})}catch(f){console.error("Launch failed",f)}},[e]),m=l.useCallback(async(k,f)=>{try{const x=k||(t==null?void 0:t.daemonId)||"",w=await e(x,"switch_chat",{id:f,sessionId:f,...un(t)}),b=w==null?void 0:w.result;if((w==null?void 0:w.success)===!0||b==="switched"||b==="switched-by-title")return;b===!1||b==="not_found"?Rn(r,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?Rn(r,`⚠️ Switch error: ${b}`):Rn(r,"⚠️ Session switch failed")}catch(x){console.error("Switch failed",x),Rn(r,`❌ Switch failed: ${x.message||"connection error"}`)}},[t,e,r]),h=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const k=pn(t);await e(k,"new_chat",{...un(t)}),xS(k,t.sessionId,so(t)[0]),o(f=>({...f,[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,f;if(!(!t||u)){p(!0);try{const x=pn(t),w=async()=>e(x,"list_chats",{forceExpand:!0,...un(t)});let b=await w(),N=(b==null?void 0:b.chats)||((k=b==null?void 0:b.result)==null?void 0:k.chats);qo(N,t)&&(await new Promise(j=>setTimeout(j,450)),b=await w(),N=(b==null?void 0:b.chats)||((f=b==null?void 0:b.result)==null?void 0:f.chats)),b!=null&&b.success&&Array.isArray(N)&&(a(t.routeId,N),qo(N,t)&&!qo(n,t)&&Rn(r,"⚠️ History dialog did not fully open — try once more"))}catch(x){console.error("Refresh history failed",x)}finally{p(!1)}}},[t,n,u,e,a,r]);return{isCreatingChat:i,isRefreshingHistory:u,handleLaunchIde:d,handleSwitchSession:m,handleNewChat:h,handleRefreshHistory:g}}function D1(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 I1(e,t){return e.length!==t.length?!1:e.every((n,a)=>n===t[a])}function jd(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 sr(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 u=r[c];typeof u=="number"&&u>0&&o.set(i,u)}return{assignments:o,groupCount:Math.max(1,a.length),mapping:r,usedGroups:a}}function Nd(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 L1(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 R1(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 Ad(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 Md(e){return Array(e).fill(100/e)}function E1({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:n,updateGroupActiveTabIds:a,updateGroupTabOrders:r,groupSizes:o,updateGroupSizes:i,isMobile:c,visibleConversations:u,visibleTabKeys:p}){const d=l.useRef(null),m=l.useMemo(()=>sr(e,p),[e,p]),h=m.assignments,g=l.useMemo(()=>c?1:m.groupCount,[m.groupCount,c]),k=g>1,f=l.useCallback((v,y)=>{t(C=>{const S=new Map(sr(C,p).assignments);return y===0?S.delete(v):S.set(v,y),S}),a(C=>({...C,[y]:v})),n(y)},[t,p,a,n]),x=l.useCallback(v=>{t(y=>{const C=sr(y,p).assignments,S=new Map;for(const[A,M]of C)M!==v&&(M>v?S.set(A,M-1):S.set(A,M));return S}),i(y=>{if(y.length<=1)return[];const C=[...y];C.splice(v,1);const S=C.reduce((A,M)=>A+M,0);return S>0?C.map(A=>A/S*100):[]}),n(0)},[t,p,i,n]),w=l.useCallback((v,y)=>{y.preventDefault();const C=d.current;if(!C)return;const S=y.clientX,A=C.offsetWidth,M=o.length===g?[...o]:Md(g),I=P=>{const H=(P.clientX-S)/A*100,L=[...M];L[v]=Math.max(15,M[v]+H),L[v+1]=Math.max(15,M[v+1]-H),i(L)},D=()=>{document.removeEventListener("mousemove",I),document.removeEventListener("mouseup",D),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",I),document.addEventListener("mouseup",D)},[o,g,i]),b=l.useCallback((v,y,C)=>{if(g>=4)return;const S=C==="left"?y:y+1;t(A=>{const M=sr(A,p).assignments,I=new Map;for(const D of u){const P=M.get(D.tabKey)??0,T=P>=S?P+1:P;T>0&&I.set(D.tabKey,T)}return S>0&&I.set(v,S),I}),i(A=>{const M=A.length===g?[...A]:Md(g),I=M[y]??100/g,D=Math.max(15,I/2),P=Math.max(15,I/2),T=[...M];T[y]=D,T.splice(S,0,P);const H=T.reduce((L,R)=>L+R,0);return T.map(L=>L/H*100)}),a(A=>{const M=Ad(A,S);return M[S]=v,M}),r(A=>{const M=Ad(A,S);return M[S]=[v],M}),n(S)},[g,t,p,u,i,a,r,n]);l.useEffect(()=>{D1(e,h)||t(h)},[e,h,t]),l.useEffect(()=>{const{mapping:v,usedGroups:y}=m;a(C=>{const S=Nd(C,v);return jd(C,S)?C:S}),r(C=>{const S=Nd(C,v);return jd(C,S)?C:S}),n(C=>{const S=c?0:L1(C,y,v);return C===S?C:S}),i(C=>{const S=c?[]:R1(C,y,m.groupCount);return I1(C,S)?C:S})},[m,c,a,r,n,i]);const N=l.useMemo(()=>{const v=Array.from({length:g},()=>[]);for(const y of u){const C=h.get(y.tabKey)??0,S=Math.min(C,g-1);v[S].push(y)}return v},[u,h,g]),j=l.useCallback(()=>{t(new Map),n(0)},[t,n]);return{containerRef:d,normalizedGroupAssignments:h,numGroups:g,isSplitMode:k,groupedConvs:N,moveTabToGroup:f,closeGroup:x,handleResizeStart:w,splitTabRelative:b,clearAllSplits:j}}function _1({ides:e,sendDaemonCommand:t}){const n="1.0.48",a=l.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:uo(m,qs(m,n))).sort((m,h)=>Number(ja(h,qs(h,n)))-Number(ja(m,qs(m,n)))),[n,e]),r=l.useMemo(()=>a.some(m=>ja(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),[u,p]=l.useState({}),d=l.useCallback(async m=>{var k,f;const h=e.find(x=>x.id===m);if(!h)return;p(x=>({...x,[m]:"upgrading"}));const g=po(h);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||(f=x==null?void 0:x.result)!=null&&f.success?p(w=>({...w,[m]:"done"})):p(w=>({...w,[m]:"error"}))}catch{p(x=>({...x,[m]:"error"}))}},[e,t]);return{versionMismatchDaemons:a,hasRequiredVersionDaemons:r,targetVersion:o,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:u,handleBannerUpgrade:d}}const Jm=80;function kr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function H1(e){return{...e,createdAt:kr(e.createdAt),updatedAt:kr(e.updatedAt,e.createdAt),lastEventAt:kr(e.lastEventAt,e.updatedAt||e.createdAt)}}function $1(e){const t=yp(e);return t==="unknown:"?e.id:t}function F1(e){return[e.type,vp(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function B1(e,t=Jm){const n=new Map;for(const a of e){if(a.deletedAt)continue;const r=$1(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 W1(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=to(r,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const u=kr(r.lastMessageAt||(o==null?void 0:o.lastUpdated)||r.lastUpdated,n),p=F1({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(H1({id:p,dedupKey:p,type:c,routeId:r.routeId,machineId:r.daemonId||r.routeId,sessionId:r.sessionId,providerSessionId:r.providerSessionId,tabKey:r.tabKey,title:Wp(r),preview:Tk(r),createdAt:u,updatedAt:u,lastEventAt:u}))}return B1(a)}function O1(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function U1(e){const{conversations:t,liveSessionInboxState:n,maxItems:a=Jm}=e,r=l.useMemo(()=>W1(t,n).slice(0,Math.max(0,a)),[t,n,a]),o=l.useMemo(()=>O1(r),[r]);return{notifications:r,unreadCount:o}}function q1({notifications:e,sendDaemonCommand:t}){const n=l.useCallback(o=>{const i=e.find(u=>u.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 Ul(...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 G1(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 ql(e,t=[]){if(e==="win32"){for(const n of t){if(typeof n!="string")continue;const a=G1(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 z1(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 K1(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function Gl(e,t,n){const a=await e(t,"file_list_browse",{path:n}),r=K1(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,d)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${d}`:p==="/"||p==="\\"?`${i}${d}`:`${p.replace(/[\\/]+$/,"")}${i}${d}`,u=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,d)=>p.name.localeCompare(d.name)):[];return{path:o,directories:u}}function Pd(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 Xm(e,t={}){const n=e==null?void 0:e.mcpConfig;if((n==null?void 0:n.mode)!=="manual")return null;const r=Pd(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:Pd(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"})}}function V1(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 Ea(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Zm(e){return no(e)||e.tabKey||e.routeId||null}function eh(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=xs(e.conversations,a)||e.conversations.find(i=>i.routeId===a);if(o!=null&&o.tabKey)return o.tabKey}return t||n||a||null}function Gs(e){return String(e||"").trim()}function th(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Gr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Y1(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function Q1(e,t){const n=Gs(e.providerSessionId),a=Gs(e.targetSessionId),r=t.find(o=>{const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(Gs).filter(Boolean);return!!(n&&i.includes(n)||a&&i.includes(a))});return r?r.tabKey:a||n||null}function J1(e,t,n){if(t.event!=="agent:generating_completed")return null;const a=th(t.daemonId);if(a&&a!==e.machineId)return null;const r=Gs(t.providerType);if(e.providerType&&r!==e.providerType)return null;const o=Gs(e.resumeSessionId),i=Gs(e.launchedSessionId),c=Gs(t.providerSessionId),u=Gs(t.targetSessionId);if(o&&o!==c&&o!==u||i&&i!==c&&i!==u)return null;const p=Gr(e.workspacePath);if(p){const d=Gr(t.workspaceName);if(d&&!Y1(d,p))return null}return Q1(t,n)}function Td(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function X1({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(u=>{o.current=u,r(u)},[]);return l.useEffect(()=>{if(!a)return;const u=Gr(a.workspacePath),p=e.find(m=>{var x,w,b,N;if(!m||m.type==="adhdev-daemon"||th(m.daemonId||m.id)!==a.machineId||(La(m)?"cli":Wn(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 j=String(a.launchedSessionId||"");return[m.providerSessionId,m.sessionId,m.instanceId,m.id].map(y=>String(y||"")).filter(Boolean).includes(j)}if(u){const j=Gr(m.workspace||m.runtimeWorkspaceLabel);return j?j===u:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((N=(b=(w=(x=m.activeChat)==null?void 0:x.messages)==null?void 0:w.at)==null?void 0:b.call(w,-1))==null?void 0:N.timestamp)||0)>=a.startedAt-5e3});if(!p)return;const d=eh({entrySessionId:p.sessionId,entryInstanceId:p.instanceId,entryRouteId:p.id,conversations:t});d&&(i(),n(d))},[i,t,e,n,a]),l.useEffect(()=>ft.onStatusEvent(u=>{const p=o.current;if(!p)return;const d=J1(p,u,t);d&&(i(),n(d))}),[i,t,n]),l.useEffect(()=>{if(!a)return;const u=window.setTimeout(()=>{r(p=>!p||p.startedAt!==a.startedAt?p:(o.current=null,null))},45e3);return()=>window.clearTimeout(u)},[a]),{trackPendingLaunch:c}}function Z1(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 eN(e,t,n){var i,c,u,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),(u=n==null?void 0:n.settings)!=null&&u.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 tN({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:n,activeConv:a,ides:r,setCliViewModeOverrides:o}){const i=Nl(),{launchCli:c}=Jr(),u=l.useCallback(async(x,w)=>Gl(e,x,w),[e]),p=l.useCallback(async(x,w)=>{if(!w.trim())return{ok:!1,error:"Choose a workspace path first."};try{const b=await e(x,"workspace_add",{path:w.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]),d=l.useCallback(async(x,w,b)=>{var N;try{const j={ideType:w,enableCdp:!0};(N=b==null?void 0:b.workspacePath)!=null&&N.trim()&&(j.workspace=b.workspacePath.trim());const v=await e(x,"launch_ide",j);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:w,workspacePath:(b==null?void 0:b.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(j){return{ok:!1,error:j instanceof Error?j.message:"Could not launch IDE"}}},[e,t]),m=l.useCallback(async(x,w,b,N)=>{const j=Date.now();try{const v=Z1(b,N),y=await c(x,v),C=(y==null?void 0:y.result)||y,S=(C==null?void 0:C.sessionId)||(C==null?void 0:C.id);return y!=null&&y.success&&S?(t({machineId:x,kind:w,providerType:b,workspacePath:(N==null?void 0:N.workspacePath)||null,resumeSessionId:(N==null?void 0:N.resumeSessionId)||null,launchedSessionId:S,startedAt:j}),{ok:!0}):y!=null&&y.success?(t({machineId:x,kind:w,providerType:b,workspacePath:(N==null?void 0:N.workspacePath)||null,resumeSessionId:(N==null?void 0:N.resumeSessionId)||null,startedAt:j}),{ok:!0}):{ok:!1,error:(y==null?void 0:y.error)||(C==null?void 0:C.error)||`Could not launch ${w.toUpperCase()} session`,code:(y==null?void 0:y.code)||(C==null?void 0:C.code)||void 0}}catch(v){return Td(v)?(t({machineId:x,kind:w,providerType:b,workspacePath:(N==null?void 0:N.workspacePath)||null,resumeSessionId:(N==null?void 0:N.resumeSessionId)||null,startedAt:j}),{ok:!0}):{ok:!1,error:v instanceof Error?v.message:`Could not launch ${w.toUpperCase()} session`}}},[c,e,t]),h=l.useCallback(async x=>{var w;if(i!=null&&i.listMeshes)return i.listMeshes(x);if(!x)return[];try{const b=await e(x,"list_meshes",{}),N=(b==null?void 0:b.result)??b;if((N==null?void 0:N.success)===!1)throw new Error((N==null?void 0:N.error)||"Could not load meshes");return(Array.isArray(N==null?void 0:N.meshes)?N.meshes:Array.isArray((w=N==null?void 0:N.result)==null?void 0:w.meshes)?N.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,w,b,N)=>{if(!w.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(x,w,b,N);const j=Date.now();try{const v=eN(w,b,N),y=await e(x,"launch_mesh_coordinator",v),C=(y==null?void 0:y.result)??y;if((C==null?void 0:C.success)===!1||(y==null?void 0:y.success)===!1){const A=String((C==null?void 0:C.code)||(y==null?void 0:y.code)||""),M=V1((C==null?void 0:C.meshCoordinatorSetup)||(C==null?void 0:C.manualSetup)||(y==null?void 0:y.meshCoordinatorSetup)||(y==null?void 0:y.manualSetup));return{ok:!1,error:(C==null?void 0:C.error)||(y==null?void 0:y.error)||"Could not launch mesh coordinator",code:A||void 0,manualSetup:M}}const S=(C==null?void 0:C.sessionId)||(C==null?void 0:C.id);return S?n(S):t({machineId:x,kind:"cli",providerType:(C==null?void 0:C.cliType)||b.trim()||void 0,workspacePath:(C==null?void 0:C.workspace)||null,startedAt:j}),{ok:!0}}catch(v){return Td(v)?(t({machineId:x,kind:"cli",providerType:b.trim()||void 0,startedAt:j}),{ok:!0}):{ok:!1,error:v instanceof Error?v.message:"Could not launch mesh coordinator"}}},[i,n,e,t]),k=l.useCallback(async(x,w)=>{if(!x||!w)return[];try{const b=await e(x,"list_saved_sessions",{providerType:w,kind:"cli",limit:30}),N=(b==null?void 0:b.result)??b;return Array.isArray(N==null?void 0:N.sessions)?N.sessions:[]}catch(b){return console.error("List saved sessions failed",b),[]}},[e]),f=l.useCallback(async x=>{await qm({conversation:a,mode:x,ides:r,sendDaemonCommand:e,setCliViewModeOverrides:o})},[a,r,e,o]);return{handleBrowseMachineDirectory:u,handleSaveMachineWorkspace:p,handleLaunchMachineIde:d,handleLaunchMachineProvider:m,handleListMachineMeshes:h,handleLaunchMeshCoordinator:g,handleListMachineSavedSessions:k,setActiveCliViewMode:f}}function sN(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 nN(e,t,n=Date.now()){return!e||!sN(t)?null:{tabKey:e,nonce:n}}function aN({isMobile:e,conversations:t,visibleConversations:n,groupActiveTabIds:a,focusedGroup:r,groupedConvs:o,setSearchParams:i}){const[c,u]=l.useState(null),[p,d]=l.useState(null),m=l.useMemo(()=>{var x,w;if(!e){if(c){const b=t.find(N=>N.tabKey===c);if(b)return b}return n[0]}const f=a[r];if(f){const b=t.find(N=>N.tabKey===f);if(b)return b}return((x=o[r])==null?void 0:x[0])||((w=o[0])==null?void 0:w[0])},[t,c,r,a,o,e,n]),h=l.useCallback(f=>{u(f)},[]),g=l.useCallback(f=>{u(f.tabKey),i(x=>{const w=new URLSearchParams(x),b=Ik(f);return b?w.set("activeTab",b):w.delete("activeTab"),w},{replace:!0})},[i]),k=l.useCallback((f,x)=>{const w=nN(f,x);w&&d(w)},[]);return{activeConv:m,openDesktopConversation:g,requestScrollToBottom:k,scrollToBottomRequest:p,setDesktopActiveTab:h}}function rN(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 oN(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 iN({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),u=l.useRef(null);l.useEffect(()=>{const p=()=>{i.current&&(clearTimeout(i.current),i.current=null),c.current&&(clearTimeout(c.current),c.current=null),u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null),o.current=null};if(t){p(),r.current=null;return}if(!(e!=null&&e.sessionId)){p(),r.current=null;return}const d=Js(e,n),m=oN({tabKey:e.tabKey,historySessionId:no(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:bn(e),liveState:d}),h=m.autoReadKey,g=rN({autoReadKey:h,shouldMarkSeen:m.shouldMarkSeen,completedKey:r.current,pendingKey:o.current});if(!m.shouldMarkSeen){g.shouldCancelPending&&p(),r.current=h;return}if(!g.shouldSchedule)return;g.shouldCancelPending&&p();const k=()=>{if(document.visibilityState!=="visible"||r.current===h)return;r.current=h,o.current=null,i.current=null,c.current=null,u.current&&(document.removeEventListener("visibilitychange",u.current),u.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)};u.current=x,document.addEventListener("visibilitychange",x);return}const f=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(k,800),u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null))};u.current=f,document.addEventListener("visibilitychange",f)},[e,t,n,a]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current),c.current&&clearTimeout(c.current),u.current&&document.removeEventListener("visibilitychange",u.current)},[])}function Go(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 lN({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:n,ides:a,sendDaemonCommand:r,updateRouteChats:o,setToasts:i,setClearedTabs:c,setSearchParams:u}){var U;const{launchCli:p}=Jr(),[d,m]=l.useState(!1),[h,g]=l.useState([]),[k,f]=l.useState(()=>Gt()),[x,w]=l.useState(!1),[b,N]=l.useState(null),j=l.useRef(null),v=l.useMemo(()=>n||t||e,[e,n,t]),y=!!v&&mt(v)&&!ut(v),C=l.useMemo(()=>{if(!v||!y)return null;const E=v.daemonId||v.routeId||"",$=Ms(v),_=Go(v);return`${E}:${$}:${v.providerSessionId||""}:${_}`},[v,y]),S=l.useMemo(()=>!v||!y?"":Go(v),[v,y]),{isCreatingChat:A,isRefreshingHistory:M,handleSwitchSession:I,handleNewChat:D,handleRefreshHistory:P}=Qm({sendDaemonCommand:r,activeConv:v,chats:(U=a.find(E=>E.id===(v==null?void 0:v.routeId)))==null?void 0:U.chats,updateRouteChats:o,setToasts:i,setClearedTabs:c}),T=l.useCallback(()=>{m(!0)},[]),H=l.useCallback(()=>{m(!1)},[]),L=l.useCallback(async()=>{if(!(!v||!y||x)){w(!0);try{const E=v.daemonId||v.routeId,$=Ms(v),_=Go(v),q=await r(E,"list_saved_sessions",{agentType:$,providerType:$,kind:"cli",limit:50,...v.providerSessionId?{providerSessionId:v.providerSessionId}:{},..._?{workspace:_}:{}}),B=(q==null?void 0:q.result)??q;g(Array.isArray(B==null?void 0:B.sessions)?B.sessions:[])}catch(E){console.error("Refresh saved sessions failed",E),g([])}finally{w(!1)}}},[v,x,y,r]);l.useEffect(()=>{if(!d){j.current=null;return}if(!y){j.current=null,g([]),w(!1);return}!C||x||j.current!==C&&(j.current=C,L())},[L,d,x,y,C]);const R=l.useCallback(async E=>{if(!v||!y||!E.providerSessionId||!E.workspace)return;const $=v.daemonId||v.routeId,_=Ms(v);try{N(E.providerSessionId);const q=await p($,{cliType:_,dir:E.workspace,resumeSessionId:E.providerSessionId,initialModel:jp(E.summaryMetadata,"model",{preferShortValue:!0})||void 0}),B=(q==null?void 0:q.result)??q,W=typeof(B==null?void 0:B.sessionId)=="string"?B.sessionId:typeof(B==null?void 0:B.id)=="string"?B.id:"";W&&u(V=>{const ne=new URLSearchParams(V);return ne.set("activeTab",W),ne},{replace:!0}),H()}catch(q){console.error("Resume saved session failed",q)}finally{N(null)}},[H,v,y,r,u]);return{historyModalOpen:d,openHistoryModal:T,closeHistoryModal:H,historyTargetConv:v,isSavedSessionHistoryTarget:y,isHistoryCreatingChat:A,isHistoryRefreshingHistory:M,handleHistorySwitchSession:I,handleHistoryNewChat:D,handleHistoryRefresh:P,savedHistorySessions:h,savedHistoryFilters:k,setSavedHistoryFilters:f,missingWorkspaceResumePath:S,isSavedHistoryLoading:x,resumingSavedHistorySessionId:b,handleRefreshSavedHistory:L,handleResumeSavedHistorySession:R}}function cN({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c}){const[u,p]=l.useState(null),[d,m]=l.useState(null),h=l.useMemo(()=>{if(e||!a)return null;const w=c(a);return w&&!mt(w)&&!ut(w)?w:null},[e,a,c]),g=l.useMemo(()=>{const w=u==null?void 0:u.routeId;if(!w)return null;const b=u!=null&&u.tabKey?o.find(N=>N.tabKey===u.tabKey):r?o.find(N=>N.tabKey===r):null;return(b==null?void 0:b.routeId)===w?b:xs(o,w)},[o,u,r]),k=l.useMemo(()=>{if(g)return i.find(w=>w.id===g.routeId)},[i,g]);l.useEffect(()=>{h&&(p({routeId:h.routeId,tabKey:Oc(h)}),m(h),n({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,n,h]);const f=l.useCallback(w=>{w&&(p({routeId:w.routeId,tabKey:Oc(w)}),m(w))},[]),x=l.useCallback(()=>{p(null),m(null)},[]);return{remoteDialogConv:g,remoteDialogIdeEntry:k,remoteDialogActiveConv:d,setRemoteDialogActiveConv:m,openRemoteDialog:f,closeRemoteDialog:x}}function dN({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c,activeConv:u,sendDaemonCommand:p}){const{remoteDialogConv:d,remoteDialogIdeEntry:m,remoteDialogActiveConv:h,setRemoteDialogActiveConv:g,openRemoteDialog:k,closeRemoteDialog:f}=cN({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c}),[x,w]=l.useState(!1),[b,N]=l.useState(null),j=l.useCallback(async C=>{const S=C||u;!S||!mt(S)&&!ut(S)||(N(S),w(!0))},[u]),v=l.useCallback(()=>{w(!1),N(null)},[]),y=l.useCallback(async C=>{const S=b||u;if(!S||!mt(S)&&!ut(S)){v();return}w(!1);try{const A=Ms(S),M=S.routeId||S.daemonId||"";await p(M,"stop_cli",{cliType:A,targetSessionId:S.sessionId,mode:C,...oo(S)})}catch(A){console.error("Stop CLI failed:",A)}finally{N(null)}},[u,v,b,p]);return{remoteDialogConv:d,remoteDialogIdeEntry:m,remoteDialogActiveConv:h,setRemoteDialogActiveConv:g,openRemoteDialog:k,closeRemoteDialog:f,cliStopDialogOpen:x,cliStopTargetConv:b,requestCliStop:j,cancelCliStop:v,confirmCliStop:y}}function zo(e,t=!0){return(e??!0)&&t}const zl=l.memo(function({activeConv:t,clearToken:n,isCliTerminal:a,ideEntry:r,terminalRef:o,handleModalButton:i,handleRelaunch:c,handleSendChat:u,handleForceSendChat:p,isSendingChat:d,sendFeedbackMessage:m=null,handleFocusAgent:h,isFocusingAgent:g,actionLogs:k,userName:f,scrollToBottomRequestNonce:x,isInputActive:w=!0,isVisible:b=!0}){const N=a,j=!a,v=zo(b,N),y=zo(b,j),C=zo(b),S=Wm(t),A=S.status||S.modalMessage||S.modalButtons?{...t,...S.status?{status:S.status}:{},...S.modalMessage!==void 0?{modalMessage:S.modalMessage}:{},...S.modalButtons!==void 0?{modalButtons:S.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(mp,{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(xn,{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:N?"visible":"hidden",pointerEvents:N?"auto":"none"},children:s.jsx(mC,{activeConv:A,clearToken:n,terminalRef:o,handleSendChat:u,isSendingChat:d,sendFeedbackMessage:m,isVisible:v,isInputActive:w&&v})}),s.jsx("div",{"aria-hidden":a,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:j?"visible":"hidden",pointerEvents:j?"auto":"none"},children:s.jsx(Oi,{activeConv:A,ideEntry:r,handleSendChat:u,isSendingChat:d,sendFeedbackMessage:m,handleFocusAgent:h,isFocusingAgent:g,actionLogs:k,userName:f,scrollToBottomRequestNonce:x,isInputActive:w&&y,isVisible:y})})]}):s.jsx(Oi,{activeConv:A,ideEntry:r,handleSendChat:u,handleForceSendChat:p,isSendingChat:d,sendFeedbackMessage:m,handleFocusAgent:h,isFocusingAgent:g,actionLogs:k,userName:f,scrollToBottomRequestNonce:x,isInputActive:w&&C,isVisible:C})]})},(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 uN({conversation:e,className:t="",onOpenNativeConversation:n,onOpenMachine:a,interactive:r=!0,meshOnly:o=!1}){var j,v,y;const{t:i}=Ce("common"),c=Jn(),u=Bs(e),p=o?null:Bp(e),d=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),m=!o&&e.streamSource==="agent-stream"&&!!e.agentName,h=!o&&!m&&(e.transport==="pty"||e.transport==="acp"),g=zn(e),k=Dk(e),f=(j=e.settings)==null?void 0:j.meshNodeFor,x=e.meshQueueStats,w=((v=e.coordinator)==null?void 0:v.meshId)||((y=e.settings)==null?void 0:y.meshCoordinatorFor),b=l.useCallback(()=>{if(a){a();return}u&&c("/dashboard",{state:{openMachineId:u}})},[u,c,a]),N=l.useCallback(()=>{if(n){n();return}const C=Zm(e);C&&c(Ea(C))},[e,c,n]);return!d&&!m&&!h&&!p&&!f&&!x?null:s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[d&&(r?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:N,title:k,children:[s.jsx(ws,{size:12}),s.jsx("span",{children:k})]}):s.jsxs("span",{className:"conversation-meta-chip",title:k,children:[s.jsx(ws,{size:12}),s.jsx("span",{children:k})]})),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(Ta,{size:12}),s.jsx("span",{children:g})]}),h&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(Ta,{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(Ys,{size:12}),s.jsx("span",{children:p})]}):s.jsxs("span",{className:"conversation-meta-chip",title:p,children:[s.jsx(Ys,{size:12}),s.jsx("span",{children:p})]})),f&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(Ys,{size:12}),s.jsx("span",{children:i("dashboard.metaChips.meshNode")})]}),w&&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(Hb,{size:12}),s.jsxs("span",{children:[x.pending," Pending"]})]})]})}function pN({selectedConversation:e,isAcp:t,isStandalone:n,selectedIdeEntry:a,actionLogs:r,userName:o,isSendingChat:i,sendFeedbackMessage:c=null,isFocusingAgent:u,onBack:p,onOpenNativeConversation:d,onOpenMachine:m,onOpenHistory:h,onOpenRemote:g,onOpenMeshGraph:k,onStopCli:f,cliViewMode:x,onSetCliViewMode:w,handleSendChat:b,handleForceSendChat:N,handleFocusAgent:j,handleModalButton:v,handleRelaunch:y}){var D,P;const C=l.useRef(null),S=mt(e)&&!t,A=S&&x==="terminal",M=!!e.daemonId&&!!((D=e.coordinator)!=null&&D.meshId||(P=e.settings)!=null&&P.meshCoordinatorFor),I=n?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`flex items-center justify-between gap-3 ${I} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:p,type:"button","aria-label":"Back",children:s.jsx(ml,{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(uN,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>d(e),onOpenMachine:()=>m(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[S&&x&&s.jsx(gm,{mode:x,onChange:w,compact:!0}),S&&f&&s.jsx("button",{onClick:()=>{f(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(It,{size:14})}),M&&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(ns,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>h(e),type:"button",children:s.jsx(fl,{size:14})}),!t&&!S&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",children:s.jsx(ws,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(zl,{activeConv:e,clearToken:0,isCliTerminal:A,ideEntry:a,terminalRef:C,handleModalButton:v,handleRelaunch:y,handleSendChat:b,handleForceSendChat:N,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:j,isFocusingAgent:u,actionLogs:r,userName:o})})]})}const Ko={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 mN(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function sh(){const[e,t]=l.useState("unix"),[n,a]=l.useState("powershell"),[r,o]=l.useState(!1),i=e==="unix"?"unix":n;l.useEffect(()=>{t(mN())},[]);const c=l.useCallback(()=>{navigator.clipboard.writeText(Ko[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:Ko[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:Ko[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.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 nh({section:e,onSectionChange:t}){const n=[{key:"machines",label:"Machines",icon:ws},{key:"chats",label:"Chats",icon:Cn}];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:n.map(({key:a,label:r,icon:o})=>{const i=e===a;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 ${i?"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:i?{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(a),type:"button","aria-pressed":i,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${i?"text-accent-primary":"bg-transparent text-current"}`,style:i?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:s.jsx(o,{size:15})}),s.jsx("span",{children:r})]},a)})})})}function nr({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 Tn({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 rn({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 hN({conversation:e,onCancel:t,onConfirm:n}){const{t:a}=Ce(),r=kt(e);return s.jsx(Kt,{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 ar({item:e,type:t,getAvatarText:n,onOpenConversation:a,onRequestHideConversation:r,onRequestStopCli:o,onOpenMeshGraph:i,onCollectChatDebugBundle:c,isMuted:u,onToggleMute:p}){const{t:d}=Ce(),m=t==="needs_attention"||t==="task_complete",h=t==="working",g=t==="earlier",k=t==="task_complete",{isReconnecting:f,isConnecting:x}=jn(e.conversation),w=kt(e.conversation),b=Kn(e.conversation),N=mm(e.conversation,{requiresAction:t==="needs_attention"}),j=m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":h?"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":h?"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",C=g?"text-text-muted":"text-text-secondary",S=g?"text-text-secondary opacity-80":"text-text-muted",A=g?"text-text-muted opacity-80":"text-text-muted",M=!h&&!k,I=um(e.conversation),D="text-[color:var(--status-warning)]",P=T=>{if(!c)return;T.preventDefault(),T.stopPropagation();const H=c==null?void 0:c(e.conversation);Promise.resolve(H).catch(L=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",L)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${j}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[m||h?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(w)}),I&&i&&s.jsx("button",{type:"button",className:"mobile-inbox-mesh-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:T=>{T.preventDefault(),T.stopPropagation(),i(e.conversation)},"aria-label":d("mobileInbox.openMeshGraphFor",{title:w}),title:d("mobileInbox.openLiveMeshGraph"),children:s.jsx(ns,{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:P,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:w})}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${C}`,children:[s.jsx("span",{className:"truncate",children:b}),s.jsx(Hr,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),f?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${D} animate-pulse`,children:d("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:d("mobileInbox.connectingItem")})]}):N==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:D,children:d("mobileInbox.actionNeeded")})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${S}`,children:e.preview})]}),s.jsxs("div",{className:"mobile-inbox-corner-actions absolute top-3 right-3 flex items-center gap-1.5",children:[M&&s.jsx("span",{className:`mr-0.5 text-[11px] font-medium shrink-0 ${A}`,children:up(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:d("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 ${u?"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:T=>{T.preventDefault(),T.stopPropagation(),p()},"aria-label":u?d("mobileInbox.unmute",{title:w}):d("mobileInbox.mute",{title:w}),title:d(u?"mobileInbox.mutedTitle":"mobileInbox.muteNotifications"),children:u?s.jsx(Zu,{size:13}):s.jsx(Xn,{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:T=>{T.preventDefault(),T.stopPropagation(),r()},"aria-label":d("mobileInbox.hideConversationAria",{title:w}),title:d("mobileInbox.hideConversationTitle"),children:s.jsx(bl,{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:T=>{T.preventDefault(),T.stopPropagation(),o()},"aria-label":d("mobileInbox.stopSessionAria",{title:w}),title:d("mobileInbox.stopSessionTitle"),children:s.jsx(It,{size:13})})]})]})},e.conversation.tabKey)}function rr({size:e=32}){return s.jsx("div",{className:"flex flex-col items-center gap-2.5",children:s.jsx("div",{className:"rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light",style:{width:e,height:e}})})}function Dd({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 fN({section:e,attentionItems:t,unreadItems:n,workingItems:a,completedItems:r,hiddenConversations:o,machineCards:i,getAvatarText:c,actionLogs:u,sendDaemonCommand:p,onOpenConversation:d,onShowAllHidden:m,onHideConversation:h,onOpenMeshGraph:g,onStopCli:k,onOpenNewSession:f,onOpenMachine:x,onOpenSettings:w,onSectionChange:b,wsStatus:N="connected",initialDataLoaded:j=!0,conversationsLoaded:v,isStandalone:y=!1,onCollectChatDebugBundle:C,isConversationMuted:S,onToggleMuteConversation:A}){const{t:M}=Ce(),[I,D]=l.useState(null),P=N==="disconnected"||N==="reconnecting"||N==="offline"||N==="auth_failed",T=!P&&!j,H=!P&&!(v??j),L=i.length>0,R=t.length>0||n.length>0||a.length>0||r.length>0,U=M(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),E=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))]",_=l.useCallback(async W=>{const V=pn(W);if(!V)return;const ne=Array.isArray(W.messages)?W.messages:[],ae=Kp({activeConv:W,visibleMessages:ne,actionLogs:u,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:ne.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),he=await p(V,"get_chat_debug_bundle",{...un(W),delivery:"daemon_file",frontendSnapshot:ae}),Z=Ca(he),z=Qp(Z),X=await Yp(z);X==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),ft.showToast(Vp(Z,{locatorCopyStatus:X}),X==="failed"?"warning":"success")},[u,p]),q=C||_,B=l.useCallback(()=>{I&&(h==null||h(I),D(null))},[I,h]);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 ${E}`,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:U}),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(Xn,{size:13}),s.jsx("span",{children:t.length+n.length})]}),s.jsx("button",{onClick:w,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(Xr,{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:P?s.jsx(rn,{icon:s.jsx(rr,{}),title:M(N==="offline"?"mobileInbox.networkOffline":N==="auth_failed"?"mobileInbox.sessionExpired":"mobileInbox.reconnecting"),subtitle:M(N==="offline"?"mobileInbox.waitingForNetwork":N==="auth_failed"?"mobileInbox.pleaseLogInAgain":"mobileInbox.restoringConnection")}):T?s.jsx(rn,{icon:s.jsx(rr,{}),title:M("mobileInbox.loading"),subtitle:M("mobileInbox.loadingSubtitle")}):i.length===0?s.jsx(rn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:M(y?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:M(y?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!y&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(sh,{})})}):s.jsx(Tn,{children:i.map((W,V)=>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] ${V>0?"border-t border-border-subtle/70":""}`,onClick:()=>x(W.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(W.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:W.label}),s.jsxs("span",{className:"flex items-center gap-2 text-[11px] font-medium text-text-muted shrink-0",children:[s.jsx(Dd,{count:W.generatingCount,label:M("mobileInbox.generatingCount",{count:W.generatingCount})}),W.unread>0?s.jsx("span",{className:"text-accent-primary",children:M("mobileInbox.newCount",{count:W.unread})}):W.total>0?M("mobileInbox.chatCount",{count:W.total}):M("mobileInbox.idle")]})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:W.subtitle}),W.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[M("mobileInbox.chatCount",{count:W.total}),W.unread>0?M("mobileInbox.unreadSuffix",{count:W.unread}):"",W.generatingCount>0?M("mobileInbox.collapsedGeneratingSuffix",{count:W.generatingCount}):""]}):W.generatingCount>0?s.jsx("div",{className:"text-[13px] text-accent-primary mt-0.5 font-medium",children:M("mobileInbox.generatingCount",{count:W.generatingCount})}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:M("mobileInbox.noActiveChats")})]})]},W.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(nr,{title:M("mobileInbox.needsAttention"),className:"mb-0"}),s.jsx(Tn,{children:t.map((W,V)=>s.jsx("div",{className:V>0?"border-t border-border-subtle/70":"",children:s.jsx(ar,{item:W,type:"needs_attention",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:h?()=>D(W.conversation):void 0,onRequestStopCli:k?()=>k(W.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:q,isMuted:S==null?void 0:S(W.conversation),onToggleMute:A?()=>A(W.conversation):void 0})},W.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(nr,{title:M("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),s.jsx(Tn,{children:n.map((W,V)=>s.jsx("div",{className:V>0?"border-t border-border-subtle/70":"",children:s.jsx(ar,{item:W,type:"task_complete",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:h?()=>D(W.conversation):void 0,onRequestStopCli:k?()=>k(W.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:q,isMuted:S==null?void 0:S(W.conversation),onToggleMute:A?()=>A(W.conversation):void 0})},W.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(nr,{title:M("mobileInbox.workingNow"),className:"mb-0 mt-2"}),s.jsx(Tn,{children:a.map((W,V)=>s.jsx("div",{className:V>0?"border-t border-border-subtle/70":"",children:s.jsx(ar,{item:W,type:"working",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:h?()=>D(W.conversation):void 0,onRequestStopCli:k?()=>k(W.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:q,isMuted:S==null?void 0:S(W.conversation),onToggleMute:A?()=>A(W.conversation):void 0})},W.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(nr,{title:M("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),r.length>0?s.jsx(Tn,{children:r.map((W,V)=>s.jsx("div",{className:V>0?"border-t border-border-subtle/70":"",children:s.jsx(ar,{item:W,type:"earlier",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:h?()=>D(W.conversation):void 0,onRequestStopCli:k?()=>k(W.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:q,isMuted:S==null?void 0:S(W.conversation),onToggleMute:A?()=>A(W.conversation):void 0})},W.conversation.tabKey))}):R?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:M("mobileInbox.allCaughtUp")}):P?s.jsx(rn,{icon:s.jsx(rr,{size:28}),title:M("mobileInbox.connecting"),subtitle:M("mobileInbox.connectingSubtitle")}):H?s.jsx(rn,{icon:s.jsx(rr,{size:28}),title:M("mobileInbox.loading"),subtitle:M("mobileInbox.loadingSubtitle")}):L?s.jsx(rn,{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(Cn,{size:20})}),title:M("mobileInbox.noConversations"),subtitle:M("paneGroup.newSessionDescription"),children:f&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:f,"aria-label":M("paneGroup.newSession"),title:M("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:M("paneGroup.newSession")})]})}):s.jsx(rn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:M("mobileInbox.noMachinesConnected"),subtitle:M("mobileInbox.noMachinesSubtitle")})]}),e==="chats"&&o.length>0&&(()=>{const W=Hg(o);return s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(Tn,{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:M("mobileInbox.hiddenTabs")}),s.jsx(Dd,{count:W,label:M("mobileInbox.generatingCount",{count:W})})]}),s.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[M("mobileInbox.collapsedCount",{count:o.length}),W>0?M("mobileInbox.collapsedGeneratingSuffix",{count:W}):""]})]}),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:M("mobileInbox.restoreAll")})]})})})})()]}),e==="chats"&&f&&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:f,"aria-label":M("paneGroup.newSession"),title:M("paneGroup.newSession"),children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),I&&s.jsx(hN,{conversation:I,onCancel:()=>D(null),onConfirm:B}),s.jsx(nh,{section:e,onSectionChange:b})]})}function bN(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 ah(e){const t=[e.workspace||"Workspace unknown"],n=vn(e.summaryMetadata);n&&t.push(n),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const a=bN(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:a?`Updated ${a}`:"",preview:(e.preview||"").trim()}}function Kl({title:e,description:t,currentPath:n,directories:a,busy:r=!1,error:o="",confirmLabel:i="Use this folder",onClose:c,onNavigate:u,onConfirm:p}){const[d,m]=l.useState(n),{t:h}=Ce("common");l.useEffect(()=>{m(n)},[n]);const g=z1(n),k=d.trim();return s.jsx(Kt,{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(It,{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||u(g)},disabled:!g||r,children:[s.jsx(ml,{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:h("machine.workspaceBrowse.currentFolder")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:d,onChange:f=>m(f.target.value),onKeyDown:f=>{f.key!=="Enter"||!k||r||(f.preventDefault(),u(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||u(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(f=>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:()=>u(f.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(Gn,{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:f.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:f.path})]})]},f.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 mo({title:e,description:t,details:n,workspaceOptions:a,selectedWorkspaceKey:r,onWorkspaceChange:o,confirmLabel:i,busyLabel:c,busy:u=!1,showArgsInput:p,argsValue:d,onArgsChange:m,showModelInput:h,modelValue:g,onModelChange:k,historyProviderNode:f,onConfirm:x,onCancel:w}){const{t:b}=Ce("common"),N=i??b("machine.launchConfirm.launch"),j=c??b("machine.launchConfirm.launching"),v=a==null?void 0:a.find(C=>C.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:w,"aria-label":b("machine.launchConfirm.closeAria"),children:s.jsx(It,{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:C=>o(C.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:u,children:a.map(C=>s.jsx("option",{value:C.key,children:C.label},C.key))}),(v==null?void 0:v.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:v.description})]}),f,n.map(C=>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:C.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:C.value})]},`${C.label}:${C.value}`)),h&&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:C=>k(C.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:u})]}),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:d||"",onChange:C=>m(C.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:u})]})]}),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:w,disabled:u,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:u,children:[s.jsx(Xu,{size:14}),u?j:N]})]})]})});return typeof document>"u"?y:Fs.createPortal(y,document.body)}function Id(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function rh(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 d of t.workspaces||[])c.push({key:`saved:${d.id}`,label:`${d.id===t.defaultWorkspaceId?"⭐ ":""}${Id(d.path,d.label)}`,description:d.path,workspaceId:d.id,workspacePath:d.path});const u=(n==null?void 0:n.trim())||"",p=u?(t.workspaces||[]).find(d=>d.path===u):null;if(u&&!p&&c.push({key:`custom:${u}`,label:Id(u),description:u,workspaceId:null,workspacePath:u}),a){const d=`saved:${a}`;if(c.some(m=>m.key===d))return{options:c,selectedKey:d}}return p?{options:c,selectedKey:`saved:${p.id}`}:u?{options:c,selectedKey:`custom:${u}`}:{options:c,selectedKey:"__home__"}}function gN(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function xN(e){return[gN(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function vN(e){return e.lastLaunchedAt?eo(e.lastLaunchedAt):""}function oh(e){return{metaText:xN(e),updatedLabel:vN(e)}}function Vo(e,t,n){return e?"ide":t>0?"cli":n>0?"acp":null}function yN({selectedMachineEntry:e,cliProviders:t,acpProviders:n,machineAction:a,onBrowseDirectory:r,onListSavedSessions:o}){var ce,Ee,Fe,et;const i=ea(),[c,u]=l.useState(!1),p=(((ce=e.detectedIdes)==null?void 0:ce.length)||0)>0,d=l.useMemo(()=>(e.workspaces||[]).map(Ae=>({id:Ae.id,path:Ae.path,label:Ae.label})),[e]),m=e.defaultWorkspaceId||null,[h,g]=l.useState(m||((Ee=d[0])==null?void 0:Ee.id)||""),[k,f]=l.useState(""),[x,w]=l.useState(""),[b,N]=l.useState([]),[j,v]=l.useState(!1),[y,C]=l.useState(""),[S,A]=l.useState(!1),[M,I]=l.useState(Vo(p,t.length,n.length)),D=l.useRef(null),[P,T]=l.useState(null),H=l.useRef("__home__"),[L,R]=l.useState("__home__"),[U,E]=l.useState(""),[$,_]=l.useState(""),[q,B]=l.useState(""),[W,V]=l.useState([]),[ne,ae]=l.useState(()=>Gt().textQuery),[he,Z]=l.useState(()=>Gt().workspaceQuery),[z,X]=l.useState(()=>Gt().modelQuery),[O,Q]=l.useState(()=>Gt().resumableOnly),[ke,Se]=l.useState(()=>Gt().sortMode),[ve,xe]=l.useState(!1),[Y,G]=l.useState(!1),te=l.useRef(null),me=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const K=h==="__custom__"?k.trim():((Fe=d.find(Ae=>Ae.id===h))==null?void 0:Fe.path)||"",be=h==="__custom__"&&!!K&&a.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(a.message),re=h!=="__custom__"&&((et=d.find(Ae=>Ae.id===h))==null?void 0:et.path)||"",de=l.useMemo(()=>(e.recentLaunches||[]).map(Ae=>Ae.workspace),[e]),we=l.useCallback(async Ae=>{v(!0),C("");try{const Je=await r(Ae);w(Je.path),f(Je.path),N(Je.directories)}catch(Je){C(Je instanceof Error?Je.message:"Could not load folder")}finally{v(!1)}},[r]),Re=l.useCallback(()=>{var Je;g("__custom__"),A(!0);const Ae=ql(e.platform,Ul(k.trim(),re,de,e.defaultWorkspacePath,(Je=d.find(bt=>bt.id===m))==null?void 0:Je.path,d.map(bt=>bt.path)));we(Ae)},[k,m,we,de,re,e.platform,d]),F=l.useCallback(Ae=>{if(Ae!=null&&Ae.workspaceId){g(Ae.workspaceId),f("");return}if(Ae!=null&&Ae.workspacePath){g("__custom__"),f(Ae.workspacePath);return}g(""),f("")},[]),J=l.useCallback(Ae=>{if(g(Ae),Ae==="__custom__"){Re();return}f("")},[Re]),ge=l.useCallback(Ae=>{g("__custom__"),f(Ae)},[]),ue=l.useCallback((Ae,Je)=>{D.current=Je,H.current=Ae.selectedWorkspaceKey||"__home__",R(Ae.selectedWorkspaceKey||"__home__"),E(Ae.initialArgs||""),_(Ae.initialModel||""),B(""),V([]);const bt=Ae.providerType?`${e.id}:${Ae.providerType}`:null;if(SC(me.current,bt)){const it=Gt();ae(it.textQuery),Z(it.workspaceQuery),X(it.modelQuery),Q(it.resumableOnly),Se(it.sortMode)}me.current=bt,T(Ae),Ae.providerType&&o&&(xe(!0),o(Ae.providerType).then(it=>V(it||[])).catch(it=>console.warn("Failed to load saved sessions",it)).finally(()=>xe(!1)))},[o,e.id]),ee=l.useMemo(()=>xm(W,{textQuery:ne,workspaceQuery:he,modelQuery:z,resumableOnly:O,sortMode:ke}),[z,O,W,ke,ne,he]);l.useEffect(()=>{q&&(ee.some(Ae=>Ae.providerSessionId===q)||B(""))},[ee,q]);const De=l.useCallback(()=>{D.current&&(G(!0),D.current().finally(()=>{D.current=null,G(!1),T(null)}))},[]),Le=l.useCallback(()=>{D.current=null,T(null)},[]),Xe=l.useCallback(Ae=>{H.current=Ae,R(Ae)},[]);return l.useEffect(()=>{var Ae;te.current!==e.id&&(te.current=e.id,g(m||((Ae=d[0])==null?void 0:Ae.id)||"__custom__"),f(""),w(""),N([]),C(""),A(!1),ae(Gt().textQuery),Z(Gt().workspaceQuery),X(Gt().modelQuery),Q(Gt().resumableOnly),Se(Gt().sortMode),me.current=null,I(Vo(p,t.length,n.length)))},[n.length,t.length,m,p,e.id,d]),l.useEffect(()=>{var Ae;h!=="__custom__"&&(h&&d.some(Je=>Je.id===h)||g(m||((Ae=d[0])==null?void 0:Ae.id)||"__custom__"))},[m,h,d]),l.useEffect(()=>{M==="ide"&&p||M==="cli"&&t.length>0||M==="acp"&&n.length>0||I(Vo(p,t.length,n.length))},[M,n.length,t.length,p]),{showAllRecent:c,setShowAllRecent:u,hasIdeOptions:p,workspaceRows:d,defaultWorkspaceId:m,workspaceChoice:h,customWorkspacePath:k,browseCurrentPath:x,browseDirectories:b,browseBusy:j,browseError:y,browseDialogOpen:S,activeLauncherKind:M,launchConfirm:P,launchConfirmWorkspaceKeyRef:H,launchConfirmWorkspaceKey:L,launchConfirmArgs:U,launchConfirmModel:$,launchConfirmResumeId:q,launchConfirmSavedSessions:W,launchConfirmTextFilter:ne,launchConfirmWorkspaceFilter:he,launchConfirmModelFilter:z,launchConfirmResumableOnly:O,launchConfirmSortMode:ke,filteredLaunchConfirmSavedSessions:ee,launchConfirmSessionsLoading:ve,launchConfirmBusy:Y,resolvedWorkspacePath:K,canCreateMissingWorkspace:be,openBrowseDialog:Re,loadBrowsePath:we,handleWorkspaceChoiceChange:J,chooseCustomWorkspacePath:ge,setCustomWorkspacePath:f,setBrowseDialogOpen:A,setActiveLauncherKind:I,openLaunchConfirm:ue,handleConfirmLaunch:De,closeLaunchConfirm:Le,setWorkspaceSelectionFromOption:F,setLaunchConfirmWorkspaceKeyAndSync:Xe,setLaunchConfirmArgs:E,setLaunchConfirmModel:_,setLaunchConfirmResumeId:B,setLaunchConfirmTextFilter:ae,setLaunchConfirmWorkspaceFilter:Z,setLaunchConfirmModelFilter:X,setLaunchConfirmResumableOnly:Q,setLaunchConfirmSortMode:Se}}function wN({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:n,cliProviders:a,acpProviders:r,selectedMachineNeedsUpgrade:o,appVersion:i,machineAction:c,isStandalone:u,section:p,showBottomNav:d,onBack:m,onSectionChange:h,onOpenConversation:g,onOpenRecent:k,onOpenMachineDetails:f,onMachineUpgrade:x,onLaunchDetectedIde:w,onAddWorkspace:b,onBrowseDirectory:N,onLaunchWorkspaceProvider:j,onListSavedSessions:v}){const{t:y}=Ce("common"),C=R=>R==="ide"?"IDE":R==="cli"?"CLI":"ACP",S=n.slice(0,4),A=t.slice(0,3),M=yN({selectedMachineEntry:e,cliProviders:a,acpProviders:r,machineAction:c,onBrowseDirectory:N,onListSavedSessions:v}),I=l.useMemo(()=>S.map(R=>{const{metaText:U,updatedLabel:E}=oh(R);return{key:`recent-launch:${R.id}`,primary:R.label,secondary:U,updatedLabel:E,onClick:()=>{const{options:$,selectedKey:_}=rh({machine:{workspaces:M.workspaceRows,defaultWorkspaceId:M.defaultWorkspaceId},currentWorkspacePath:R.workspace,homeLabel:y("newSession.homeDirectory"),homeDescription:y("newSession.launchWithoutWorkspace")});M.openLaunchConfirm({title:R.kind==="ide"?$r(y,"restart-ide",R.label):R.providerSessionId?ym(y,R.label):$r(y,"start-fresh",R.label),description:R.kind==="ide"?Fr(y,"restart-ide"):R.providerSessionId?wm(y):Fr(y,"start-fresh"),confirmLabel:R.kind==="ide"?Br(y,"restart-ide"):R.providerSessionId?Ui(y,!0):Br(y,"start-fresh"),busyLabel:R.kind==="ide"?Wr(y,"restart-ide"):R.providerSessionId?vm(y,!0):Wr(y,"start-fresh"),workspaceOptions:$,selectedWorkspaceKey:_,details:[{label:"Mode",value:C(R.kind)},...R.providerType?[{label:"Provider",value:R.providerType}]:[]]},async()=>{const q=$.find(B=>B.key===M.launchConfirmWorkspaceKeyRef.current);M.setWorkspaceSelectionFromOption(q),await k({...R,workspace:(q==null?void 0:q.workspacePath)??null})})}}}),[M,k,S,y]),D=l.useMemo(()=>A.map(R=>({key:`recent-chat:${R.conversation.tabKey}`,primary:kt(R.conversation),secondary:QS(R.conversation,{timestampLabel:R.timestamp?up(R.timestamp):null}),unread:R.unread,onClick:()=>g(R.conversation)})),[g,A]),P=M.showAllRecent?I:I.slice(0,4),T=I.length>0,H=D.length>0,L=u?"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 ${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:m,type:"button","aria-label":"Back",children:s.jsx(ml,{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:as(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:[H&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:D.map(R=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${R.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:R.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:R.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:R.secondary})]},R.key))})]}),T&&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:P.map(R=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:R.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:R.primary}),R.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:R.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:R.secondary})]},R.key))}),I.length>4&&s.jsx("div",{className:"flex justify-center px-4 pt-2",children:s.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>M.setShowAllRecent(R=>!R),children:M.showAllRecent?"Show fewer":`Show ${I.length-4} more`})})]}),!1,s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[o&&s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:x,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",i]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:f,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"})]})]})]})]}),M.browseDialogOpen&&s.jsx(Kl,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:M.browseCurrentPath,directories:M.browseDirectories,busy:M.browseBusy,error:M.browseError,confirmLabel:"Use this folder",onClose:()=>M.setBrowseDialogOpen(!1),onNavigate:R=>{M.loadBrowsePath(R)},onConfirm:R=>{M.chooseCustomWorkspacePath(R),M.setBrowseDialogOpen(!1)}}),M.launchConfirm&&s.jsx(mo,{title:M.launchConfirm.title,description:M.launchConfirm.description,details:M.launchConfirm.details,workspaceOptions:M.launchConfirm.workspaceOptions,selectedWorkspaceKey:M.launchConfirmWorkspaceKey,onWorkspaceChange:M.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:M.launchConfirm.providerType?Ui(y,!!M.launchConfirmResumeId):M.launchConfirm.confirmLabel,busyLabel:M.launchConfirm.providerType?void 0:M.launchConfirm.busyLabel,busy:M.launchConfirmBusy,showArgsInput:M.launchConfirm.showArgsInput,argsValue:M.launchConfirmArgs,onArgsChange:M.setLaunchConfirmArgs,showModelInput:M.launchConfirm.showModelInput,modelValue:M.launchConfirmModel,onModelChange:M.setLaunchConfirmModel,historyProviderNode:M.launchConfirm.providerType&&(M.launchConfirmSessionsLoading||M.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"}),M.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:_l(y)}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:M.launchConfirmTextFilter,onChange:R=>M.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:M.launchConfirmBusy||M.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:M.launchConfirmWorkspaceFilter,onChange:R=>M.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:M.launchConfirmBusy||M.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:M.launchConfirmModelFilter,onChange:R=>M.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:M.launchConfirmBusy||M.launchConfirmSessionsLoading}),s.jsxs("select",{value:M.launchConfirmSortMode,onChange:R=>M.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:M.launchConfirmBusy||M.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:M.launchConfirmResumableOnly,onChange:R=>M.setLaunchConfirmResumableOnly(R.target.checked),disabled:M.launchConfirmBusy||M.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:M.launchConfirmResumeId,onChange:R=>M.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:M.launchConfirmBusy||M.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:NC(y)}),M.filteredLaunchConfirmSavedSessions.map(R=>s.jsxs("option",{value:R.providerSessionId,disabled:!R.canResume,children:[R.title||R.providerSessionId," ",R.canResume?"":"(workspace missing)"]},R.providerSessionId))]}),!M.launchConfirmSessionsLoading&&M.launchConfirmSavedSessions.length>0&&M.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),M.launchConfirmResumeId&&(()=>{const R=M.filteredLaunchConfirmSavedSessions.find(E=>E.providerSessionId===M.launchConfirmResumeId);if(!R)return null;const U=ah(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:U.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:U.providerSessionId}),s.jsx("div",{className:"mt-1",children:U.metaLine}),U.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:U.updatedLabel}),U.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:U.preview})]})})()]}),onConfirm:M.handleConfirmLaunch,onCancel:M.closeLaunchConfirm}),d&&s.jsx(nh,{section:p,onSectionChange:h})]})}const Ld=8e3;function kN(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 ih(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 f=!1;for(const[x,w]of g){const b=e.get(x),N=w.muted===void 0||(b?b.muted===w.muted:!1),j=w.hidden===void 0||(b?b.surfaceHidden===w.hidden:!1),v=k-w.at>Ld;(N&&j||v)&&(g.delete(x),f=!0)}f&&o()},[e,o]),l.useEffect(()=>{if(a.current.size===0)return;const g=setInterval(()=>{const k=a.current,f=Date.now();let x=!1;for(const[w,b]of k)f-b.at>Ld&&(k.delete(w),x=!0);x&&o(),k.size===0&&clearInterval(g)},1e3);return()=>clearInterval(g)});const i=l.useCallback((g,k)=>{const f=a.current.get(g);a.current.set(g,{...f,...k,at:Date.now()}),o()},[o]),c=l.useCallback(g=>{const k=g.sessionId,f=k?a.current.get(k):void 0;return(f==null?void 0:f.muted)!==void 0?f.muted:Js(g,e).muted??!1},[e]),u=l.useCallback(g=>{const k=g.sessionId,f=k?a.current.get(k):void 0;return(f==null?void 0:f.hidden)!==void 0?f.hidden:Js(g,e).surfaceHidden??!1},[e]),p=l.useCallback((g,k)=>{const f=Bs(g),x=g.sessionId;!f||!x||(i(x,k),t(f,"set_conversation_prefs",{sessionId:x,...k,...oo(g)}).then(w=>{const b=kN(w);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(w=>{console.warn("[conversation-prefs] set_conversation_prefs failed",w),a.current.delete(x),o();const b=w instanceof Error?w.message:String(w??"the daemon is unreachable");n==null||n(`Couldn't update conversation — ${b}`)}))},[t,i,o,n]),d=l.useCallback(g=>{p(g,{muted:!c(g)})},[p,c]),m=l.useCallback((g,k)=>{p(g,{hidden:k})},[p]),h=l.useCallback(g=>{p(g,{hidden:!u(g)})},[p,u]);return{isMuted:c,isHidden:u,toggleMute:d,setHidden:m,toggleHidden:h}}function Sr(e){return[...e].sort((t,n)=>{const a=n.timestamp-t.timestamp;return a!==0?a:t.conversation.tabKey.localeCompare(n.conversation.tabKey)})}function SN(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:Sr(e)}function CN(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:Sr(n),unreadItems:Sr(a),workingItems:SN(r,t),completedItems:Sr(o)}}function ho(e,t){if(!t)return!1;const n=e.filter(a=>a.type==="adhdev-daemon"&&lh(a)==="Connected");return n.length===0?!0:n.every(a=>a._sessionListAuthoritative===!0)}function lh(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 jN(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:vn(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=La(a)?"cli":Wn(a)?"acp":"ide",o=vn(a.summaryMetadata);return{id:`${r}:${a.type}:${a.workspace||""}`,label:((i=a.activeChat)==null?void 0:i.title)||(La(a)?a.cliName||a.type:Wn(a)&&a.cliName||a.type),kind:r,providerType:a.type,providerSessionId:a.providerSessionId,subtitle:Wn(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 NN(e,t,n=[]){const a=new Map;for(const o of t){const i=Bs(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=Bs(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)||[],u=[...i].sort((f,x)=>x.timestamp-f.timestamp)[0]||null,p=(u==null?void 0:u.conversation)||null,d=_i(o),m=i.filter(f=>f.unread||f.requiresAction).length,h=i.filter(f=>Da(f.conversation)).length+c.filter(Da).length,g=lh(o),k=[o.platform||"machine",g].filter(Boolean);return{id:o.id,label:as(o,{fallbackId:o.id}),subtitle:k.join(" · "),unread:m,total:i.length,generatingCount:h,latestConversation:p,latestTimestamp:(u==null?void 0:u.timestamp)||0,fallbackActivityAt:d,preview:p?JS(p,rm(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,u=i.latestTimestamp||i.fallbackActivityAt||0;return u!==c?u-c:o.label.localeCompare(i.label)})}function AN(e){return e==="chat"}function or(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 MN({conversations:e,machineEntries:t,items:n,selectedConversation:a,selectedTabKey:r,screen:o,liveSessionInboxState:i,sendDaemonCommand:c,requestedActiveTabKey:u,onRequestedActiveTabConsumed:p,requestedMachineId:d,onRequestedMachineConsumed:m,requestedMobileSection:h,onRequestedMobileSectionConsumed:g,setSelectedTabKey:k,setScreen:f,setSelectedMachineId:x,setSection:w,setMachineBackTarget:b,resetMachineAction:N}){const j=l.useRef(null),v=l.useCallback(y=>{if(!(y!=null&&y.sessionId))return;const C=Js(y,i),S=Math.max(Date.now(),bn(y),C.lastUpdated||0);or("mark_read:start",{tabKey:y.tabKey,sessionId:y.sessionId,displayPrimary:kt(y),inboxBucket:C.inboxBucket,unread:C.unread,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,activityAt:bn(y),readAt:S}),c(Bs(y)||y.routeId,"mark_session_seen",{sessionId:y.sessionId,providerSessionId:y.providerSessionId,seenAt:S,completionMarker:C.completionMarker}).then(A=>{or("mark_read:result",{tabKey:y.tabKey,sessionId:y.sessionId,result:A})}).catch(A=>{or("mark_read:error",{tabKey:y.tabKey,sessionId:y.sessionId,error:A instanceof Error?A.message:String(A)})})},[i,c]);return l.useEffect(()=>{var C;if(!a){AN(o)&&f("inbox"),k(((C=e[0])==null?void 0:C.tabKey)||null),j.current=null;return}if(o!=="chat"){j.current=null;return}const y=`${a.tabKey}:${a.sessionId||""}`;j.current!==y&&(j.current=y,v(a))},[e,v,o,a,f,k]),l.useEffect(()=>{if(!u)return;const y=e.find(C=>C.tabKey===u);y&&(k(y.tabKey),f("chat"),p==null||p())},[e,p,u,f,k]),l.useEffect(()=>{if(!d)return;const y=t.find(C=>C.id===d);y&&(x(y.id),N(),w("machines"),b("inbox"),f("machine"),m==null||m())},[t,m,d,N,b,f,w,x]),l.useEffect(()=>{h&&(w(h),f("inbox"),g==null||g())},[g,h,f,w]),l.useEffect(()=>{const y=n.filter(C=>C.inboxBucket==="task_complete"||C.unread);y.length!==0&&or("inbox_state",{screen:o,selectedTabKey:r,items:y.map(C=>{const S=Js(C.conversation,i);return{liveState:S,tabKey:C.conversation.tabKey,sessionId:C.conversation.sessionId,displayPrimary:kt(C.conversation),serverBucket:S.inboxBucket,computedBucket:C.inboxBucket,serverUnread:S.unread,computedUnread:C.unread,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,activityAt:bn(C.conversation)}})})},[n,i,o,r]),{markConversationRead:v}}function PN(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Rd(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function TN(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function DN({sendDaemonCommand:e,navigate:t,ides:n,conversations:a}){const{launchCli:r}=Jr(),[o,i]=l.useState("idle"),[c,u]=l.useState(""),[p,d]=l.useState(null),m=l.useCallback(()=>{i("idle"),u(""),d(null)},[]),h=l.useCallback(async(N,j,v)=>{var y;try{i("loading"),u(`Launching ${j}…`);const C={ideType:j,enableCdp:!0};(y=v==null?void 0:v.workspacePath)!=null&&y.trim()&&(C.workspace=v.workspacePath.trim()),await e(N,"launch_ide",C),i("done"),u(`${j} launch requested`)}catch(C){i("error"),u(C instanceof Error?C.message:"Launch IDE failed"),console.error("Launch IDE failed",C)}},[e]),g=l.useCallback(async(N,j,v)=>{if(j.trim())try{i("loading"),u(v!=null&&v.createIfMissing?"Creating folder…":"Saving workspace…");const y=await e(N,"workspace_add",{path:j.trim(),createIfMissing:(v==null?void 0:v.createIfMissing)===!0});if(y!=null&&y.success){i("done"),u(v!=null&&v.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),u((y==null?void 0:y.error)||"Could not save workspace")}catch(y){i("error"),u(y instanceof Error?y.message:"Could not save workspace")}},[e]),k=l.useCallback(async N=>{i("loading"),u("Starting daemon upgrade…");const j=n.find(y=>y.id===N||y.daemonId===N),v=await vj(e,N,j);i(v.state),u(v.message)},[n,e]),f=l.useCallback(async(N,j,v,y)=>{var A,M,I;const C=Date.now(),S={machineId:N,kind:j,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:C};try{i("loading"),u(`Launching ${v}…`),d(S);const D={cliType:v};(A=y==null?void 0:y.workspacePath)!=null&&A.trim()?D.dir=y.workspacePath.trim():y!=null&&y.workspaceId?D.workspaceId=y.workspaceId:y!=null&&y.useHome&&(D.useHome=!0),y!=null&&y.resumeSessionId&&(D.resumeSessionId=y.resumeSessionId),(M=y==null?void 0:y.args)!=null&&M.trim()&&(D.cliArgs=y.args.trim().split(/\s+/).filter(Boolean)),(I=y==null?void 0:y.model)!=null&&I.trim()&&(D.initialModel=y.model.trim());const P=await r(N,D),T=(P==null?void 0:P.result)||P,H=(T==null?void 0:T.sessionId)||(T==null?void 0:T.id);if(P!=null&&P.success&&H){d(null),i("done"),u(`${v} launched`),t(Ea(H));return}if(P!=null&&P.success){i("loading"),u(`${v} launch requested — waiting for session…`);return}d(null),i("error"),u((P==null?void 0:P.error)||(T==null?void 0:T.error)||`Could not launch ${j.toUpperCase()} workspace`)}catch(D){if(TN(D)){i("loading"),u(`${v} launch requested — waiting for session…`);return}d(null),i("error"),u(D instanceof Error?D.message:`Could not launch ${j.toUpperCase()} workspace`)}},[t,e]),x=l.useCallback(async(N,j)=>{try{const v=await e(N,"list_saved_sessions",{providerType:j,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]),w=l.useCallback(async(N,j)=>Gl(e,N,j),[e]);l.useEffect(()=>{if(!p)return;const N=Rd(p.workspacePath),j=n.find(y=>{var D,P,T,H;if(!y||y.type==="adhdev-daemon"||PN(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 M=String(y.providerSessionId||"");if(p.resumeSessionId&&M)return M===p.resumeSessionId;if(N){const L=Rd(y.workspace||y.runtimeWorkspaceLabel);return L?L===N:!1}return Number(y.lastUpdated||y._lastUpdate||y.timestamp||((H=(T=(P=(D=y.activeChat)==null?void 0:D.messages)==null?void 0:P.at)==null?void 0:T.call(P,-1))==null?void 0:H.timestamp)||0)>=p.startedAt-5e3});if(!j)return;const v=eh({entrySessionId:j.sessionId,entryInstanceId:j.instanceId,entryRouteId:j.id,conversations:a});v&&(d(null),i("done"),u(`${p.providerType} launched`),t(Ea(v)))},[a,n,t,p]),l.useEffect(()=>{if(!p)return;const N=window.setTimeout(()=>{d(j=>!j||j.startedAt!==p.startedAt?j:(i("error"),u("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(N)},[p]);const b=l.useCallback(async(N,j)=>{var v;if(j.kind==="ide"&&j.providerType){await h(N,j.providerType,{workspacePath:j.workspace||null});return}if((j.kind==="cli"||j.kind==="acp")&&j.providerType){const y=((v=j.workspace)==null?void 0:v.trim())||"";await f(N,j.kind,j.providerType,{workspacePath:y||null,useHome:!y,resumeSessionId:j.providerSessionId||null})}},[h,f]);return{machineAction:{state:o,message:c},resetMachineAction:m,handleLaunchDetectedIde:h,handleAddWorkspace:g,handleMachineUpgrade:k,handleLaunchWorkspaceProvider:f,handleListSavedSessions:x,handleBrowseDirectory:w,handleOpenRecent:b}}function IN({conversations:e,selectedConversation:t,machineBackTarget:n,markConversationRead:a,resetMachineAction:r,setSelectedTabKey:o,setScreen:i,setSelectedMachineId:c,setSection:u,setMachineBackTarget:p}){const d=l.useCallback(w=>{o(w.tabKey),i("chat"),a(w)},[a,i,o]),m=l.useCallback(w=>{const b=e.find(N=>N.routeId===w.routeId&&N.streamSource==="native");b&&(o(b.tabKey),i("chat"),a(b))},[e,a,i,o]),h=l.useCallback(()=>{a(t),i("inbox")},[a,t,i]),g=l.useCallback((w,b="inbox")=>{c(w),r(),u("machines"),p(b),i("machine")},[r,p,i,u,c]),k=l.useCallback(w=>{const b=Bs(w);b&&g(b,"chat")},[g]),f=l.useCallback(()=>{r(),i(n)},[n,r,i]),x=l.useCallback(w=>{u(w),i("inbox")},[i,u]);return{openConversation:d,openNativeConversation:m,backFromConversation:h,openMachine:g,openConversationMachine:k,backFromMachine:f,changeMachineSection:x}}function Vn(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function LN(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function RN({conversations:e,hiddenConversations:t,ides:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,userName:c,requestedActiveTabKey:u,onRequestedActiveTabConsumed:p,requestedMachineId:d,onRequestedMachineConsumed:m,requestedMobileSection:h,onRequestedMobileSectionConsumed:g,onOpenHistory:k,onOpenRemote:f,onStopCli:x,wsStatus:w,isConnected:b,initialDataLoaded:N=!0,onShowAllHiddenConversations:j,onHideConversation:v,onOpenMeshGraph:y,onOpenNewSession:C,liveSessionInboxState:S,setCliViewModeOverrides:A}){const[M,I]=l.useState(()=>{var J;return((J=e[0])==null?void 0:J.tabKey)||null}),[D,P]=l.useState(()=>e[0]?"chat":"inbox"),[T,H]=l.useState("chats"),[L,R]=l.useState(null),[U,E]=l.useState("inbox"),$=l.useRef([]),_=Jn(),q="1.0.48",B=l.useMemo(()=>e.find(J=>J.tabKey===M)||e[0]||null,[e,M]),W=l.useMemo(()=>B?n.find(J=>J.id===B.routeId):void 0,[n,B]),V=l.useMemo(()=>!B||ut(B)||!mt(B)?null:Zn(B),[B]),ne=l.useMemo(()=>n.filter(J=>J.type==="adhdev-daemon").sort(Sl),[n]),ae=l.useMemo(()=>ne.find(J=>J.id===L)||null,[ne,L]),he=io({sendDaemonCommand:r,activeConv:B||void 0,setActionLogs:o,isStandalone:i}),Z=DN({sendDaemonCommand:r,navigate:_,ides:n,conversations:e}),z=NS(e),X=l.useMemo(()=>e.map(J=>{const ge=D==="chat"&&(B==null?void 0:B.tabKey)===J.tabKey,ue=to(J,S,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ge}),ee=bn(J),De=rm(J),Le=pm(J,De);return{conversation:J,timestamp:ee,preview:Le,unread:ue.unread,requiresAction:ue.requiresAction,isWorking:ue.isWorking,inboxBucket:ue.inboxBucket}}),[e,S,D,B,z]),{markConversationRead:O}=MN({conversations:e,machineEntries:ne,items:X,selectedConversation:B,selectedTabKey:M,screen:D,liveSessionInboxState:S,sendDaemonCommand:r,requestedActiveTabKey:u,onRequestedActiveTabConsumed:p,requestedMachineId:d,onRequestedMachineConsumed:m,requestedMobileSection:h,onRequestedMobileSectionConsumed:g,setSelectedTabKey:I,setScreen:P,setSelectedMachineId:R,setSection:H,setMachineBackTarget:E,resetMachineAction:Z.resetMachineAction}),Q=IN({conversations:e,selectedConversation:B,machineBackTarget:U,markConversationRead:O,resetMachineAction:Z.resetMachineAction,setSelectedTabKey:I,setScreen:P,setSelectedMachineId:R,setSection:H,setMachineBackTarget:E}),{isMuted:ke,toggleMute:Se}=ih(S,r),{attentionItems:ve,unreadItems:xe,workingItems:Y,completedItems:G}=l.useMemo(()=>CN(X,$.current),[X]);l.useEffect(()=>{$.current=Y.map(J=>J.conversation.tabKey)},[Y]);const te=l.useMemo(()=>ae?X.filter(J=>Bs(J.conversation)===ae.id):[],[X,ae]),me=l.useMemo(()=>jN(ae,n),[n,ae]),K=!!ae&&uo(ae,qs(ae,q)),be=l.useMemo(()=>(ae==null?void 0:ae.availableProviders)||[],[ae]),re=l.useMemo(()=>be.filter(J=>Vn(J,"cli")).map(J=>({type:J.type,displayName:J.displayName||J.type,icon:J.icon})),[be]),de=l.useMemo(()=>be.filter(J=>Vn(J,"acp")).map(J=>({type:J.type,displayName:J.displayName||J.type,icon:J.icon})),[be]),we=l.useMemo(()=>NN(ne,X,t),[X,ne,t]),Re=l.useMemo(()=>ho(n,N),[n,N]),F=l.useCallback(async J=>{ae&&await Z.handleOpenRecent(ae.id,J)},[Z,ae]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:D==="chat"&&B?s.jsx(pN,{selectedConversation:B,isAcp:ut(B),isStandalone:i,selectedIdeEntry:W,actionLogs:a,userName:c,isSendingChat:he.isSendingChat,sendFeedbackMessage:he.sendFeedbackMessage,isFocusingAgent:he.isFocusingAgent,handleModalButton:he.handleModalButton,handleRelaunch:he.handleRelaunch,onBack:Q.backFromConversation,onOpenNativeConversation:Q.openNativeConversation,onOpenMachine:Q.openConversationMachine,onOpenHistory:k,onOpenRemote:f,onOpenMeshGraph:y,onStopCli:x,cliViewMode:V,onSetCliViewMode:async J=>{await qm({conversation:B,mode:J,ides:n,sendDaemonCommand:r,setCliViewModeOverrides:A})},handleSendChat:he.handleSendChat,handleForceSendChat:he.handleForceSendChat,handleFocusAgent:he.handleFocusAgent}):D==="machine"&&ae?s.jsx(wN,{selectedMachineEntry:ae,selectedMachineConversations:te,selectedMachineRecentLaunches:me,cliProviders:re,acpProviders:de,selectedMachineNeedsUpgrade:K,appVersion:q,machineAction:Z.machineAction,isStandalone:i,section:T,showBottomNav:U==="inbox",onBack:Q.backFromMachine,onSectionChange:Q.changeMachineSection,onOpenConversation:Q.openConversation,onOpenRecent:F,onOpenMachineDetails:()=>_(`/machines/${ae.id}`),onMachineUpgrade:()=>Z.handleMachineUpgrade(ae.id),onLaunchDetectedIde:(J,ge)=>Z.handleLaunchDetectedIde(ae.id,J,ge),onAddWorkspace:(J,ge)=>Z.handleAddWorkspace(ae.id,J,ge),onBrowseDirectory:J=>Z.handleBrowseDirectory(ae.id,J),onLaunchWorkspaceProvider:(J,ge,ue)=>Z.handleLaunchWorkspaceProvider(ae.id,J,ge,ue),onListSavedSessions:J=>Z.handleListSavedSessions(ae.id,J)}):s.jsx(fN,{section:T,attentionItems:ve,unreadItems:xe,workingItems:Y,completedItems:G,hiddenConversations:t,machineCards:we,getAvatarText:LN,actionLogs:a,sendDaemonCommand:r,onOpenConversation:Q.openConversation,onShowAllHidden:j,onHideConversation:v,onOpenMeshGraph:y,onStopCli:x,onOpenNewSession:C,onOpenMachine:Q.openMachine,onOpenSettings:()=>_("/settings"),onSectionChange:H,wsStatus:w,isConnected:b,initialDataLoaded:N,conversationsLoaded:Re,isStandalone:i,isConversationMuted:ke,onToggleMuteConversation:Se})})}function Yo(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function EN({conversations:e,numGroups:t,onMoveTab:n,onReceiveTab:a,onOwnTabDrop:r,onClearPreviewOrder:o}){const i=l.useRef(0),[c,u]=l.useState(!1),[p,d]=l.useState(null),m=l.useCallback(()=>{i.current=0,u(!1),d(null)},[]);l.useEffect(()=>(window.addEventListener("dragend",m),window.addEventListener("drop",m),()=>{window.removeEventListener("dragend",m),window.removeEventListener("drop",m)}),[m]);const h=l.useCallback(x=>{x.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,u(!0))},[]),g=l.useCallback(x=>{if(!x.dataTransfer.types.includes("text/tab-key"))return;if(x.preventDefault(),!Yo(t,n)){d("merge");return}const w=x.currentTarget.getBoundingClientRect(),b=x.clientX-w.left,N=w.width/3;b<N?d("split-left"):b>N*2?d("split-right"):d("merge")},[t,n]),k=l.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,u(!1),d(null))},[]),f=l.useCallback(x=>{i.current=0,u(!1);const w=x.dataTransfer.getData("text/tab-key"),b=w?e.some(j=>j.tabKey===w):!1,N=p;if(d(null),o(),!!w){if(x.preventDefault(),N==="split-left"&&Yo(t,n)){n==null||n(w,"split-left");return}if(N==="split-right"&&Yo(t,n)){n==null||n(w,"split-right");return}if(b){r(w);return}a==null||a(w)}},[e,p,t,n,a,r,o]);return{dragOver:c,dropAction:p,resetDragState:m,handleDragEnter:h,handleDragOver:g,handleDragLeave:k,handleDrop:f}}function _N(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 HN({conversations:e,initialActiveTabId:t,initialTabOrder:n,onActiveTabChange:a,onTabOrderChange:r}){const[o,i]=l.useState(t??null),[c,u]=l.useState(n??[]),[p,d]=l.useState(null),m=l.useRef(null),h=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(()=>{u(C=>{const S=_N(C,e);return S.length===C.length&&S.every((A,M)=>A===C[M])?C:S})},[e]);const f=l.useMemo(()=>{const C=p??c;if(C.length===0)return e;const S=new Map(C.map((A,M)=>[A,M]));return[...e].sort((A,M)=>{const I=S.get(A.tabKey)??999,D=S.get(M.tabKey)??999;return I-D})},[e,p,c]);l.useEffect(()=>{var S,A;if(f.length===0){o!==null&&(i(null),(S=g.current)==null||S.call(g,null));return}if(o&&f.some(M=>M.tabKey===o))return;const C=f[0].tabKey;C!==o&&(i(C),(A=g.current)==null||A.call(g,C))},[f,o]);const x=l.useMemo(()=>f.find(C=>C.tabKey===o),[f,o]),w=l.useCallback(C=>{var S;i(C),(S=g.current)==null||S.call(g,C)},[]),b=l.useCallback((C,S,A)=>{u(M=>{var T;const I=M.filter(H=>H!==C),D=I.indexOf(S);if(D<0)return M;const P=A==="left"?D:D+1;return I.splice(P,0,C),(T=k.current)==null||T.call(k,I),I}),d(null)},[]),N=l.useCallback((C,S,A)=>{const I=(c.length>0?c:e.map(T=>T.tabKey)).filter(T=>T!==C),D=I.indexOf(S);if(D<0)return;const P=A==="left"?D:D+1;I.splice(P,0,C),m.current=I,d(I)},[c,e]),j=l.useCallback(()=>{var S;const C=m.current;C&&(u(C),(S=k.current)==null||S.call(k,C))},[]),v=l.useCallback(()=>{m.current=null,d(null)},[]),y=l.useCallback(C=>{u(S=>{var M;const A=S.filter(I=>I!==C);return A.push(C),(M=k.current)==null||M.call(k,A),A})},[]);return{activeTabId:o,activeConv:x,sortedConversations:f,previewOrderRef:m,draggingTabRef:h,selectTab:w,handleTabReorder:b,updatePreviewOrder:N,commitPreviewOrder:j,clearPreviewOrder:v,moveTabToEnd:y,setDraggingTabKey:C=>{h.current=C}}}function $N({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 Vl({conversationsCount:e,isSplitMode:t,isStandalone:n,hasRegisteredMachines:a=!1,suppressGuide:r=!1,onOpenNewSession:o,isLoading:i=!1}){const{t:c}=Ce("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("div",{className:"w-7 h-7 rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light","aria-hidden":"true"}),s.jsx("p",{className:"text-sm",children:c("paneGroup.loadingSessions")})]});const u=!n&&!a,p=a&&!!o,d=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:d}),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(xl,{size:14}),s.jsx("span",{children:c("paneGroup.newSession")})]})}),u&&s.jsx(sh,{}),u&&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 ch="adhdev-tab-shortcuts";function dh(){try{return JSON.parse(localStorage.getItem(ch)||"{}")}catch{return{}}}function uh({enabled:e=!0,sortedTabKeys:t,onFocus:n,onSelectTab:a}){const r=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>dh()),[c,u]=l.useState(null),p=l.useCallback(m=>{const h=[];return m.metaKey&&h.push(r?"⌘":"Meta"),m.ctrlKey&&h.push("Ctrl"),m.altKey&&h.push(r?"⌥":"Alt"),m.shiftKey&&h.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(m.key)?null:(h.push(m.key.length===1?m.key.toUpperCase():m.key),h.join("+"))},[r]),d=l.useCallback(m=>{i(m);try{localStorage.setItem(ch,JSON.stringify(m))}catch{}},[]);return l.useEffect(()=>{if(!e||!c)return;const m=h=>{if(h.preventDefault(),h.stopPropagation(),h.key==="Escape"){u(null);return}const g=p(h);if(!g)return;const k={...o};for(const[f,x]of Object.entries(k))x===g&&delete k[f];k[c]=g,d(k),u(null)};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[e,c,o,d,p]),l.useEffect(()=>{if(!e)return;const m=h=>{if(!(!h.ctrlKey&&!h.metaKey&&!h.altKey)){for(const[g,k]of Object.entries(o))if(t.includes(g)&&p(h)===k){h.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:u,saveShortcuts:d}}const Qo=e=>{e.preventDefault()},FN=l.memo(function({conv:t,isActive:n,isDraggedTab:a,isTaskCompleteUnread:r,shortcut:o,conversationKeys:i,draggingTabRef:c,onFocus:u,onSelectTab:p,onConversationActivated:d,onPreviewReorder:m,onReorderTab:h,onCommitPreviewOrder:g,onClearPreviewOrder:k,onDragStateReset:f,onDragTabKeyChange:x,onReceiveTab:w,onOpenContextMenu:b,longPressTimer:N,isGroupActive:j}){const v=jn(t),y=v.isGenerating?"agent-tab-generating":v.isWaiting?"agent-tab-waiting":"",C=v.isReconnecting,S=VS(t),A=YS(t),M=um(t),I=l.useCallback($=>{c.current=t.tabKey,x(t.tabKey),$.dataTransfer.setData("text/tab-key",t.tabKey),$.dataTransfer.effectAllowed="move"},[t.tabKey,c,x]),D=l.useCallback(()=>{c.current=null,x(null),g(),k(),f()},[c,x,g,k,f]),P=l.useCallback($=>{const _=c.current;if(!(!_||_===t.tabKey)&&$.dataTransfer.types.includes("text/tab-key")){$.preventDefault(),$.stopPropagation();const q=$.currentTarget.getBoundingClientRect(),B=$.clientX<q.left+q.width/2?"left":"right";m(_,t.tabKey,B)}},[t.tabKey,c,m]),T=l.useCallback($=>{$.preventDefault(),$.stopPropagation();const _=$.dataTransfer.getData("text/tab-key");if(_&&_!==t.tabKey){const q=$.currentTarget.getBoundingClientRect(),B=$.clientX<q.left+q.width/2?"left":"right";i.includes(_)?h(_,t.tabKey,B):w&&w(_)}k()},[t.tabKey,i,h,w,k]),H=l.useCallback($=>{$.stopPropagation(),u(),p(t.tabKey),d(t)},[t,d,u,p]),L=l.useCallback($=>{$.preventDefault(),b($.clientX,$.clientY,t.tabKey)},[t.tabKey,b]),R=l.useCallback($=>{const _=$.touches[0];N.current=setTimeout(()=>{b(_.clientX,_.clientY,t.tabKey)},600)},[t.tabKey,N,b]),U=l.useCallback(()=>{N.current&&clearTimeout(N.current)},[N]),E=["adhdev-dockview-tab",y,n&&"is-active",j&&"is-group-active",C&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:E,draggable:!0,onDragStart:I,onDragEnd:D,onDragOver:P,onDrop:T,onClick:H,onContextMenu:L,onTouchStart:R,onTouchEnd:U,onTouchMove:U,style:{position:"relative",cursor:"pointer",opacity:a?.4:void 0},children:[M&&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(ns,{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("div",{className:"tab-spinner"}):v.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):C?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):v.isConnecting?s.jsx("div",{className:"tab-connecting-spinner"}):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:"○"})}),S.length>0&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-role",title:A,"aria-label":A||S.join(" · "),children:S.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:[C?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:mn(t)}):v.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[mn(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:mn(t)}),s.jsx(Hr,{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 BN({conversations:e,activeTabId:t,groupIndex:n,unreadTabKeys:a,draggingTabRef:r,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:d,onClearPreviewOrder:m,onDragStateReset:h,onDragTabKeyChange:g,onReceiveTab:k,onHideTab:f,isGroupActive:x,allowTabShortcuts:w=!0}){const{t:b}=Ce("common"),[N,j]=l.useState(null),v=l.useRef(null),y=l.useRef(null),C=l.useMemo(()=>e.map(T=>T.tabKey),[e]);$a("PaneGroupTabBar",{groupIndex:n,activeTabId:t,tabCount:e.length,ctxMenuTab:(N==null?void 0:N.tabKey)||null});const{isMac:S,tabShortcuts:A,shortcutListening:M,setShortcutListening:I,saveShortcuts:D}=uh({enabled:w,sortedTabKeys:e.map(T=>T.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!N)return;const T=H=>{const L=document.querySelector("[data-pane-context-menu]");L&&L.contains(H.target)||j(null)};return window.addEventListener("mousedown",T,!0),()=>window.removeEventListener("mousedown",T,!0)},[N]),l.useEffect(()=>{const T=y.current;if(!T)return;const H=L=>{Math.abs(L.deltaY)<=Math.abs(L.deltaX)||(L.preventDefault(),T.scrollLeft+=L.deltaY)};return T.addEventListener("wheel",H,{passive:!1}),()=>T.removeEventListener("wheel",H)},[]);const P=l.useCallback((T,H,L)=>{j({x:T,y:H,tabKey:L})},[]);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(T=>s.jsx(FN,{conv:T,isActive:t===T.tabKey,isDraggedTab:r.current===T.tabKey,isTaskCompleteUnread:a.has(T.tabKey),shortcut:w?A[T.tabKey]:void 0,conversationKeys:C,draggingTabRef:r,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:d,onClearPreviewOrder:m,onDragStateReset:h,onDragTabKeyChange:g,onReceiveTab:k,onOpenContextMenu:P,longPressTimer:v,isGroupActive:x},T.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:b("paneGroup.noTabsInGroup")})]})}),N&&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:N.x,top:N.y},children:[w&&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:Qo,onClick:T=>{T.stopPropagation(),I(N.tabKey),j(null)},children:["⌨ ",A[N.tabKey]?`Change shortcut (${A[N.tabKey]})`:"Set shortcut"]}),A[N.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:Qo,onClick:()=>{const T={...A};delete T[N.tabKey],D(T),j(null)},children:"✕ Remove shortcut"})]}),f&&s.jsxs(s.Fragment,{children:[w&&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:Qo,onClick:()=>{f(N.tabKey),j(null)},children:"🚫 Hide from Dashboard"})]})]}),w&&M&&s.jsx(Kt,{children:s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:()=>I(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:T=>T.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. ",S?"⌘+1":"Ctrl+1",", ",S?"⌥+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 WN({conversations:e,ides:t,clearedTabs:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:u=!0,userName:p,groupIndex:d,onFocus:m,isSplitMode:h,numGroups:g,onMoveTab:k,onReceiveTab:f,style:x,onActiveTabChange:w,initialActiveTabId:b,initialTabOrder:N,onTabOrderChange:j,onHideTab:v,isFocused:y,allowTabShortcuts:C=!0,onOpenNewSession:S,liveSessionInboxState:A}){const{sendCommand:M}=vt(),I=l.useRef(null),{activeTabId:D,activeConv:P,sortedConversations:T,draggingTabRef:H,selectTab:L,handleTabReorder:R,updatePreviewOrder:U,commitPreviewOrder:E,clearPreviewOrder:$,moveTabToEnd:_,setDraggingTabKey:q}=HN({conversations:e,initialActiveTabId:b,initialTabOrder:N,onActiveTabChange:w,onTabOrderChange:j}),B=io({sendDaemonCommand:r,activeConv:P,setActionLogs:o,isStandalone:i}),{dragOver:W,dropAction:V,resetDragState:ne,handleDragEnter:ae,handleDragOver:he,handleDragLeave:Z,handleDrop:z}=EN({conversations:e,numGroups:g,onMoveTab:k,onReceiveTab:f,onOwnTabDrop:_,onClearPreviewOrder:$}),X=P&&!ut(P)&&Zn(P)==="terminal",O=l.useMemo(()=>P?t.find(ve=>ve.id===P.routeId):void 0,[t,P]),Q=l.useMemo(()=>P?a.filter(ve=>ve.routeId===P.tabKey):[],[a,P]),ke=l.useMemo(()=>new Set(T.filter(ve=>Fg(ve,A,{isOpenConversation:ve.tabKey===D})).map(ve=>ve.tabKey)),[D,A,T]);$a("PaneGroup",{groupIndex:d,conversationCount:e.length,activeTabId:D,dragOver:W});const Se=l.useCallback(ve=>{ve.streamSource==="agent-stream"&&ve.agentType&&M(ve.routeId,zp(),{agentType:ve.agentType,...ve.sessionId&&{targetSessionId:ve.sessionId}}).catch(()=>{})},[M]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:m,style:{...x,outline:W?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(BN,{conversations:T,activeTabId:D,groupIndex:d,numGroups:g,unreadTabKeys:ke,draggingTabRef:H,onFocus:m,onSelectTab:L,onConversationActivated:Se,onPreviewReorder:U,onReorderTab:R,onCommitPreviewOrder:E,onClearPreviewOrder:$,onDragStateReset:ne,onDragTabKeyChange:q,onMoveTab:k,onReceiveTab:f,onHideTab:v,isGroupActive:y??!1,allowTabShortcuts:C}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:ae,onDragOver:he,onDragLeave:Z,onDrop:z,children:[W&&s.jsx($N,{dropAction:V,canSplit:!!(g<4&&k)}),P?s.jsx(zl,{activeConv:P,clearToken:n[P.tabKey]||0,isCliTerminal:!!X,ideEntry:O,terminalRef:I,handleModalButton:B.handleModalButton,handleRelaunch:B.handleRelaunch,handleSendChat:B.handleSendChat,handleForceSendChat:B.handleForceSendChat,isSendingChat:B.isSendingChat,sendFeedbackMessage:B.sendFeedbackMessage,handleFocusAgent:B.handleFocusAgent,isFocusingAgent:B.isFocusingAgent,actionLogs:Q,userName:p,isInputActive:!h||!!y}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(Vl,{conversationsCount:e.length,isSplitMode:h,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:S,isLoading:!ho(t,u)})})]})]})}function ON({containerRef:e,isSplitMode:t,numGroups:n,groupSizes:a,groupedConvs:r,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:u,setActionLogs:p,isStandalone:d,hasRegisteredMachines:m,initialDataLoaded:h,userName:g,focusedGroup:k,focusGroup:f,moveTabToGroup:x,splitTabRelative:w,closeGroup:b,handleResizeStart:N,groupActiveTabIds:j,setGroupActiveTab:v,groupTabOrders:y,setGroupTabOrder:C,toggleHiddenTab:S,onOpenNewSession:A,allowTabShortcuts:M=!0,liveSessionInboxState:I}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:r.map((D,P)=>{const T=t&&a.length===n?`${a[P]}%`:void 0;return s.jsxs(_t.Fragment,{children:[t&&P>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:H=>N(P-1,H),onDoubleClick:()=>b(P),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(WN,{style:t?{flexBasis:T??`${100/n}%`,flexGrow:T?0:1,flexShrink:T?0:1}:void 0,conversations:D,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:u,setActionLogs:p,isStandalone:d,hasRegisteredMachines:m,initialDataLoaded:h,userName:g,groupIndex:P,isFocused:t&&k===P,onFocus:()=>f(P),isSplitMode:t,numGroups:n,onMoveTab:(H,L)=>{L==="left"&&P>0?x(H,P-1):L==="right"&&P<n-1?x(H,P+1):L==="split-left"&&n<4?w(H,P,"left"):L==="split-right"&&n<4&&w(H,P,"right")},onReceiveTab:H=>x(H,P),onActiveTabChange:H=>v(P,H),initialActiveTabId:j[P],initialTabOrder:y[P],onTabOrderChange:H=>C(P,H),onHideTab:S,onOpenNewSession:A,allowTabShortcuts:M,liveSessionInboxState:I})]},P)})})}const ph="adhdev-dashboard-action-shortcuts",UN=1200,qN=[["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 GN(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function pt(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 mh(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:pt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:pt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:pt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:pt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:pt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:pt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:pt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:pt("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:pt("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:pt("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:pt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:pt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:pt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:pt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:pt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:pt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:pt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:pt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:pt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:pt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:pt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:pt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:pt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:pt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:pt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:pt("toggleCliView",e)}]}function Ji(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(mh(e).map(n=>[n.id,n.defaultShortcut]));try{const n=JSON.parse(localStorage.getItem(ph)||"{}"),a={...t,...n};for(const[r,o]of qN)a[r]===o&&(a[r]=t[r]);return a}catch{return t}}function hh(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function zN({enabled:e=!0,onTrigger:t}){const n=GN(),[a,r]=l.useState(()=>zr(n)),[o,i]=l.useState(null),[c,u]=l.useState([]),p=l.useRef({parts:[],timer:null}),d=l.useCallback(f=>{const x=[];return f.metaKey&&x.push(n?"⌘":"Meta"),f.ctrlKey&&x.push("Ctrl"),f.altKey&&x.push(n?"⌥":"Alt"),f.shiftKey&&f.key.length!==1&&x.push(n?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(x.push(hh(f.key)),x.join("+"))},[n]),m=l.useCallback(f=>{r(f);try{localStorage.setItem(ph,JSON.stringify(f))}catch{}},[]);l.useEffect(()=>{const f=zr(n),x=Object.entries(a),w=Object.entries(f);x.length===w.length&&x.every(([b,N])=>f[b]===N)||m(f)},[a,n,m]);const h=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}},UN))},[]);l.useEffect(()=>{if(!o)return;const f=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){i(null),u([]);return}const w=d(x);if(!w)return;const N=!(x.metaKey||x.ctrlKey||x.altKey)&&/^[A-Z0-9]$/.test(w);if(c.length===0&&N){u([w]);return}const v=[...c,w].slice(0,2).join(" "),y={...a};for(const[C,S]of Object.entries(y))S===v&&delete y[C];y[o]=v,m(y),i(null),u([])};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[a,d,m,o,c]),l.useEffect(()=>{if(!e||o)return;const f=x=>{if(x.defaultPrevented)return;const w=d(x);if(!w)return;const b=x.metaKey||x.ctrlKey||x.altKey;if(Ji(x.target))return;const N=p.current.parts,j=b?[w]:[...N.slice(-1),w].slice(-2),v=j.join(" "),y=j[j.length-1],C=Object.entries(a).filter(([,D])=>!!D),S=C.find(([,D])=>D===v);if(S){x.preventDefault(),h(),t(S[0]);return}if(C.some(([,D])=>D.startsWith(`${v} `))){x.preventDefault(),p.current.parts=j,g();return}const M=C.find(([,D])=>D===y);if(M){x.preventDefault(),h(),t(M[0]);return}if(C.some(([,D])=>D.startsWith(`${y} `))){x.preventDefault(),p.current.parts=[y],g();return}h()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[a,g,e,d,t,h,o]),l.useEffect(()=>()=>h(),[h]);const k=l.useMemo(()=>mh(n),[n]);return{isMac:n,actionDefinitions:k,actionShortcuts:a,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:u,saveShortcuts:m}}function KN({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 fh(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function Ed({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:n,ides:a}){return!e||n>0?!1:t?!fh(a):!0}function VN({previousVisibleConversationCount:e,visibleConversationCount:t,ides:n}){return t>0||e<=0?!1:fh(n)}const bh=1e3,YN=4;function _d(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function Hd(e,t,n){return Math.abs(t.clientX-e.clientX)>n||Math.abs(t.clientY-e.clientY)>n}function QN({detachDelayMs:e=bh,stillnessThresholdPx:t=YN,onDetach:n,setTimeoutFn:a=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:r=globalThis.clearTimeout.bind(globalThis)}){let o=null,i=null,c=null,u=null,p=null,d=!1;const m=()=>{p!=null&&(r(p),p=null)},h=()=>{m(),c=null},g=()=>{m(),o=null,i=null,c=null,u=null,d=!1},k=()=>{!o||!c||!u||d||p!=null||(p=a(()=>{p=null,!(!o||!c||!u||d)&&_d(u,i)&&(Hd(c,u,t)||(d=!0,n({panelId:o,clientX:u.clientX,clientY:u.clientY})))},e))},f=w=>{if(!(!o||d)){if(!_d(w,i)){u={clientX:w.clientX,clientY:w.clientY},h();return}(!c||Hd(c,w,t))&&(m(),c={clientX:w.clientX,clientY:w.clientY}),u={clientX:w.clientX,clientY:w.clientY},k()}},x=w=>{!o||d||(w&&(u={clientX:w.clientX,clientY:w.clientY}),h())};return{startDrag:w=>{m(),o=w.panelId,i=w.selfPanelBounds??null,c=null,u={clientX:w.clientX,clientY:w.clientY},d=!1},markSelfPanel:f,markNonSelfPanel:x,markNoDropTarget:x,markDockTarget:x,endDrag:g,isDragging:()=>o!=null,hasDetached:()=>d,dispose:g}}function JN(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function Cr(e){return kt(e)||e.tabKey}function XN(e){return`remote:${e}`}function ps(e){return e.startsWith("remote:")}function $d(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Jo(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 Xo(e,t){e.classList.remove(ki.className,Si.className),e.classList.add(t==="light"?ki.className:Si.className)}function Fd(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 ZN(e,t,n){var i;const a=[t];let r;for(const c of a){let u;for(const p of c){const d=e.addPanel({id:p.tabKey,component:"conversation",title:Cr(p),params:{kind:"conversation",tabKey:p.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:r?{position:{referencePanel:r,direction:"right"},inactive:!0}:{}});u||(u=d.id)}r=u??r}return n??((i=t[0])==null?void 0:i.tabKey)??null}function Bd(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])ps(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!==Cr(r)&&o.api.setTitle(Cr(r));continue}e.addPanel({id:r.tabKey,component:"conversation",title:Cr(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 Wd(e,t,n){var u,p;const a=n?XN(n):null;for(const d of[...e.panels])ps(d.id)&&(!a||d.id!==a)&&e.removePanel(d);if(!n||!a)return;const r=xs(t,n);if(!r&&e.totalPanels===0)return;const o=e.getPanel(a),i=fm(r);if(o){o.title!==i&&o.api.setTitle(i);return}const c=(r==null?void 0:r.tabKey)??((u=e.activePanel)==null?void 0:u.id)??((p=e.panels.find(d=>!ps(d.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 gh({doId:e,targetSessionId:t,connState:n,viewMode:a}){const[r,o]=l.useState(null),[i,c]=l.useState(null);l.useEffect(()=>e?jt.onScreenshot("ide-page",(d,m)=>{if(d!==e)return;const h=new FileReader;h.onload=()=>o(h.result),h.readAsDataURL(m)}):void 0,[e]),l.useEffect(()=>{n!=="connected"&&o(null)},[n]),l.useEffect(()=>{var d;return e?((d=jt.onStatus)==null?void 0:d.call(jt,(m,h)=>{m===e&&h!=null&&h.screenshotUsage&&c(h.screenshotUsage)}))||(()=>{}):void 0},[e]),l.useEffect(()=>{o(null)},[e,t]),l.useEffect(()=>{const p=e?jt.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 u=l.useCallback(async(p,d)=>{const m=e?jt.get(e):null;return!m||n!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):m.sendInput(p,d,t)},[e,n,t]);return{connScreenshot:r,screenshotUsage:i,handleRemoteAction:u}}const xh=l.createContext(null);function fo(){const e=l.useContext(xh);if(!e)throw new Error("DashboardDockviewContext missing");return e}function eA(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 tA({params:e}){var u;const t=fo(),n=l.useMemo(()=>xs([...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)||((u=n==null?void 0:n.routeId)==null?void 0:u.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:i,handleRemoteAction:c}=gh({doId:r,targetSessionId:n?qp(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(lp,{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 sA(){const e=fo();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(Vl,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels,isLoading:!ho(e.ides,e.initialDataLoaded)})})}function nA(e){var b,N;eA(e);const t=fo(),n=l.useCallback(j=>{"button"in j&&j.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(j=>TS(j),[]),i=l.useCallback(()=>PS(r),[r]),c=l.useSyncExternalStore(o,i,i);if(e.params.kind==="remote"){const j=xs([...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":(j==null?void 0:j.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:j!=null&&j.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:j.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const u=t.conversationsByTabKey.get(e.params.tabKey);if(!u)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=((N=e.api.group.activePanel)==null?void 0:N.id)===e.api.id,d=e.api.isGroupActive,m=to(u,t.liveSessionInboxState,{isOpenConversation:p}),h=m.isReconnecting,g=m.isConnecting,k=m.isGenerating||c,f=m.isWaiting,x=m.unread,w=t.tabShortcuts[u.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${p?" is-active":""}${d?" is-group-active":""}${h?" is-reconnecting":""}`,title:kt(u),"data-tab-key":e.params.tabKey,onMouseDown:n,onTouchStart:n,onContextMenu:j=>{var v;j.preventDefault(),n(j),t.openTabContextMenu({x:j.clientX,y:j.clientY,tabKey:u.tabKey,sourceDocument:((v=j.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("div",{className:"tab-spinner"}):f?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):h?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):g?s.jsx("div",{className:"tab-connecting-spinner"}):u.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(u)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:h?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:mn(u)}):g?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:mn(u)}):s.jsx("span",{children:mn(u)})})]}),w&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:w,children:w})]})}function ir(e){return e.isActive}function Od(e){return e.isVisible}function aA(e){e.preventDefault()}function rA({params:e,api:t}){var g;const n=fo(),a=l.useRef(null),[r,o]=l.useState(()=>ir(t)),[i,c]=l.useState(()=>Od(t)),u=n.conversationsByTabKey.get(e.tabKey),p=io({sendDaemonCommand:n.sendDaemonCommand,activeConv:u,setActionLogs:n.setActionLogs,isStandalone:n.isStandalone});l.useEffect(()=>{o(ir(t)),c(Od(t));const k=[t.onDidActiveChange(f=>o(f.isActive)),t.onDidActiveGroupChange(f=>{if(!ir(t)&&!f.isActive){o(!1);return}o(ir(t))}),t.onDidVisibilityChange(f=>c(f.isVisible))];return()=>{for(const f of k)f.dispose()}},[t]);const d=l.useMemo(()=>u?n.ides.find(k=>k.id===u.routeId):void 0,[n.ides,u]),m=l.useMemo(()=>u?n.actionLogs.filter(k=>k.routeId===u.tabKey):[],[n.actionLogs,u]);if(!u)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(Vl,{conversationsCount:0,isSplitMode:!1,isStandalone:n.isStandalone,hasRegisteredMachines:n.hasRegisteredMachines,onOpenNewSession:n.onOpenNewSession,suppressGuide:n.hasDetachedConversationPanels,isLoading:!ho(n.ides,n.initialDataLoaded)})});const h=!ut(u)&&Zn(u)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(zl,{activeConv:u,clearToken:n.clearedTabs[u.tabKey]||0,isCliTerminal:h,ideEntry:d,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)===u.tabKey?n.scrollToBottomRequest.nonce:void 0,isInputActive:r,isVisible:i})})}function oA({visibleConversations:e,clearedTabs:t,ides:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:u,userName:p,toggleHiddenTab:d,actionShortcuts:m,registerActionHandlers:h,onActiveTabChange:g,onOpenNewSession:k,onRequestScrollToBottom:f,requestedActiveTabKey:x,requestedRemoteIdeId:w,onRequestedActiveTabConsumed:b,scrollToBottomRequest:N,liveSessionInboxState:j,layoutProfile:v}){var bt,it,yt;const{theme:y}=tn(),{sendCommand:C}=vt(),S=l.useRef(null),A=l.useRef(null),M=l.useRef(null),I=l.useRef(!1),D=l.useRef(!1),P=l.useRef(!1),T=l.useRef(null),H=l.useRef([]),[L,R]=l.useState(null),[U,E]=l.useState(0),$=l.useRef(typeof window>"u"?{}:C1(v)),_=l.useMemo(()=>new Map(e.map(se=>[se.tabKey,se])),[e]),q=l.useMemo(()=>{const se=S.current;return se?se.groups.some(oe=>{try{const pe=oe.model.location.type;return pe!=="floating"&&pe!=="popout"?!1:oe.panels.some(ye=>_.has(ye.id))}catch{return!1}}):!1},[_,U,e]),B=l.useCallback(()=>{var se;(se=S.current)==null||se.focus()},[]),W=l.useCallback((se,oe)=>{f==null||f(se,oe)},[f]),V=l.useCallback(se=>{const oe=document,pe=se.document;for(const Te of oe.querySelectorAll('link[rel="stylesheet"]')){const Ue=pe.createElement("link");Ue.rel="stylesheet",Ue.href=Te.href,Te.crossOrigin&&(Ue.crossOrigin=Te.crossOrigin),pe.head.appendChild(Ue)}for(const Te of oe.querySelectorAll("style")){const Ue=pe.createElement("style");Ue.textContent=Te.textContent,pe.head.appendChild(Ue)}const ye=[];for(const Te of oe.styleSheets)try{for(const Ue of Te.cssRules)Ue instanceof CSSStyleRule&&(Ue.selectorText===":root"||Ue.selectorText==="html")&&ye.push(Ue.cssText)}catch{}if(ye.length>0){const Te=pe.createElement("style");Te.textContent=ye.join(`
|
|
66
66
|
`),pe.head.appendChild(Te)}const le=oe.documentElement.getAttribute("data-theme");le&&pe.documentElement.setAttribute("data-theme",le),pe.documentElement.style.colorScheme=le==="light"?"light":"dark",pe.body.className=oe.body.className;const Me=oe.documentElement.getAttribute("style");Me&&pe.documentElement.setAttribute("style",Me);const _e=pe.getElementById("dv-popout-window");_e instanceof HTMLElement&&(_e.classList.add("adhdev-dockview"),Xo(_e,y))},[y]),ne=l.useCallback(()=>{var oe;const se=S.current;if(se)for(const pe of se.groups)try{const ye=(oe=pe.element)==null?void 0:oe.ownerDocument;if(!ye||ye===document)continue;const le=ye.getElementById("dv-popout-window");le instanceof HTMLElement&&(le.classList.add("adhdev-dockview"),Xo(le,y));const Me=document.documentElement.getAttribute("data-theme");Me&&ye.documentElement.setAttribute("data-theme",Me),ye.documentElement.style.colorScheme=Me==="light"?"light":"dark",ye.body.className=document.body.className;const _e=document.documentElement.getAttribute("style");_e?ye.documentElement.setAttribute("style",_e):ye.documentElement.removeAttribute("style")}catch{}},[y]),ae=l.useCallback(se=>{const oe=S.current;if(!oe)return;const pe=oe.getPanel(se);pe&&oe.addPopoutGroup(pe,{popoutUrl:"/popout.html",onDidOpen:({window:ye})=>{V(ye),ve();const le=_.get(se);ye.document.title=le?`${kt(le)} — ADHDev`:"ADHDev — Popout"}})},[_,V]),he=l.useCallback(se=>{const oe=S.current,pe=oe==null?void 0:oe.getPanel(se);if(!oe||!pe)return;const ye=oe.groups.filter(le=>{var Me;try{return((Me=le.element)==null?void 0:Me.ownerDocument)===document}catch{return!0}});ye.length>0?pe.api.moveTo({group:ye[0],position:"center"}):pe.api.moveTo({position:"center"}),pe.api.setActive()},[]),Z=l.useCallback(se=>{var ye;const oe=S.current;if(!oe)return!1;const pe=oe.getPanel(se);if(!pe)return!1;try{return((ye=pe.group.element)==null?void 0:ye.ownerDocument)!==document}catch{return!1}},[]),z=l.useCallback(se=>{Z(se)&&he(se),d(se)},[Z,he,d]),X=l.useCallback(se=>{const oe=S.current,pe=oe==null?void 0:oe.getPanel(se);!oe||!pe||oe.addFloatingGroup(pe,{width:600,height:500})},[]),O=l.useCallback(se=>{var pe;const oe=(pe=S.current)==null?void 0:pe.getPanel(se);if(!oe)return!1;try{return oe.group.model.location.type==="floating"}catch{return!1}},[]),Q=l.useCallback(()=>{var oe,pe;const se=(pe=(oe=S.current)==null?void 0:oe.activePanel)==null?void 0:pe.id;return!se||ps(se)?null:_.has(se)?se:null},[_]),ke=l.useCallback(se=>{const oe=S.current,pe=oe==null?void 0:oe.getPanel(se);if(!oe||!pe)return;const ye=oe.groups.filter(le=>{try{return le.model.location.type==="grid"}catch{return!0}});ye.length>0?pe.api.moveTo({group:ye[0],position:"center"}):pe.api.moveTo({position:"center"}),pe.api.setActive()},[]),Se=l.useCallback(()=>{var Me;const se=S.current;if(!se)return;const pe=se.groups.filter(_e=>{var Te;try{return((Te=_e.element)==null?void 0:Te.ownerDocument)===document&&_e.model.location.type==="grid"}catch{return!1}})[0]||null,ye=[...se.panels];for(const _e of ye){const Te=(Me=_e.group.element)==null?void 0:Me.ownerDocument,Ue=_e.group.model.location.type;Te===document&&Ue==="grid"||(pe&&pe.id!==_e.group.id?_e.api.moveTo({group:pe,position:"center"}):_e.api.moveTo({position:"center"}))}const le=se.activePanel;le&&(le.group.model.openPanel(le),le.api.setActive()),Jo(document)},[]),ve=l.useCallback(()=>{var oe,pe;const se=S.current;if(se)for(const ye of se.groups){const le=(oe=ye.element)==null?void 0:oe.ownerDocument;if(!le||le===document)continue;const Me=le.getElementById("dv-popout-window");if(!(Me instanceof HTMLElement))continue;let _e=null,Te=le.title||"ADHDev",Ue="Popout workspace";const Ge=ye.activePanel;if(Ge)if(_e=Ge.id,ps(Ge.id)){const $e=((pe=Ge.params)==null?void 0:pe.routeId)||Ge.id.slice(7),fe=xs([..._.values()],$e);Te=fm(fe),Ue=fe!=null&&fe.machineName?`Remote view · ${fe.machineName}`:"Remote view"}else{const $e=_.get(Ge.id);Te=$e?kt($e):Ge.title||Ge.id,Ue=$e?mn($e):"Dockview panel"}le.title=`${Te} — ADHDev`;const Ye=Array.from(le.querySelectorAll("#adhdev-popout-header"));for(const $e of Ye)$e.remove();const Be=le.createElement("div");Be.id="adhdev-popout-header",le.body.appendChild(Be),Be.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(";")),Be.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>
|
|
@@ -106,11 +106,11 @@ This will disconnect CDP and optionally kill the process.`))try{const _=await n(
|
|
|
106
106
|
|
|
107
107
|
`)}function RD(e,t){return t==="issues"?e.filter(n=>n.level==="warn"||n.level==="error"):t==="info"?e.filter(n=>n.level!=="debug"):e}function ED(e,t){return t==="issues"?e.filter(n=>n.level==="warn"||n.level==="error"):t==="info"?e.filter(n=>n.level!=="debug"):e}function _D({daemonLogs:e,daemonRawText:t,daemonLogKind:n,debugTrace:a,webEvents:r,traceCategory:o,quickFilter:i,searchQuery:c,daemonLoading:u,traceLoading:p,daemonFetchError:d,traceFetchError:m}){const h=pD(a,o),g=fD(e,c),k=xD(t,c),f=vD(h,c),x=yD(r,c),w=RD(g,i),b=i==="all"?k:[],N=ED(f,i),j=i==="issues"?[]:x,v=wD({daemonLogs:g,daemonRawLines:k,trace:f,webEvents:x}),y=PD({daemonLogs:w,daemonRawLines:b,trace:N,webEvents:j}),C=DD(y),S=CD({daemonLoading:u,traceLoading:p,daemonFetchError:d,traceFetchError:m,daemonLogKind:n,daemonLogsCount:g.length,daemonRawLineCount:k.length,traceCount:f.length,webEventCount:x.length});return{filteredDaemonLogs:g,filteredDaemonRawLines:k,filteredTraceEntries:f,filteredWebEvents:x,visibleDaemonLogs:w,visibleDaemonRawLines:b,visibleTraceEntries:N,visibleWebEvents:j,quickFilterCounts:v,diagnosticEvents:y,diagnosticsSummary:C,sourceStates:S}}function HD(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function lf(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function Zi(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 pi(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 $D({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Zi(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:lf(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 FD({quickFilter:e,quickFilterCounts:t,searchQuery:n,autoRefresh:a,onQuickFilterChange:r,onSearchQueryChange:o,onCopyDiagnostics:i,onCopyVisible:c,onToggleAutoRefresh:u,onRefresh:p,onClear:d}){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-violet-500/15 text-violet-300 border border-violet-500/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:u,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:d,className:"machine-btn",children:"Clear"})]})]})}function BD({logLevel:e,traceCategory:t,onLogLevelChange:n,onTraceCategoryChange:a}){return s.jsx(bs,{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-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:["Daemon ",r.toUpperCase(),"+"]},r))]}),s.jsx("div",{className:"flex flex-wrap gap-2 items-center",children:dD.map(r=>s.jsx("button",{onClick:()=>a(r.value),className:`machine-btn text-[10px] px-2 py-0.5 ${t===r.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:r.label},r.value))})]})})}function WD({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:n,searchQuery:a,lastUpdatedAt:r,autoRefresh:o,daemonFetchError:i,traceFetchError:c}){var d,m;const u=((d=e.latestIssue)==null?void 0:d.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 ${pi(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 ${pi(u)}`,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:lf(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 ${pi(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: ",HD(r)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:n.map(h=>s.jsxs("div",{children:[h.label,": ",h.status]},h.id))})]})]})}function OD({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 UD({streams:e,sectionsOpen:t,setSectionsOpen:n,diagnosticEvents:a,visibleDaemonLogs:r,visibleDaemonRawLines:o,visibleTraceEntries:i,visibleWebEvents:c,quickFilter:u,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(d=>({...d,timeline:!d.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(d=>s.jsx($D,{event:d},d.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(d=>({...d,daemon:!d.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:u==="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((d,m)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:d},`raw-${m}`)),e.daemonLogKind!=="text"&&r.map((d,m)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${Zi(d.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(d.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:d.level==="error"?"ERR":d.level==="warn"?"WRN":d.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:d.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(d=>({...d,trace:!d.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(d=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Zi(d.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(d.ts).toLocaleTimeString()}),s.jsx("span",{children:d.level.toUpperCase()}),s.jsxs("span",{children:[d.category,".",d.stage]}),d.interactionId&&s.jsxs("span",{children:["ix=",d.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Qn(d.payload,360)||"No payload"})]},d.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(d=>({...d,web:!d.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(d=>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(d.ts).toLocaleTimeString()}),s.jsx("span",{children:d.kind}),d.topic&&s.jsxs("span",{children:["topic=",d.topic]}),d.interactionId&&s.jsxs("span",{children:["ix=",d.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Qn(d.payload,360)||"No payload"})]},d.id))]})]})]})}function qD({machineId:e,sendDaemonCommand:t}){const n=SD({machineId:e,sendDaemonCommand:t}),[a,r]=l.useState("info"),[o,i]=l.useState(""),[c,u]=l.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),p=l.useRef(null),d=l.useRef(!1),m=l.useMemo(()=>_D({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=d.current?"smooth":"instant";setTimeout(()=>{var f;(f=p.current)==null||f.scrollIntoView({behavior:k}),d.current=!0},50)}},[m.diagnosticEvents.length,n.autoRefresh]);const h=l.useCallback(async()=>{var f;const k=kD({daemonLogs:m.visibleDaemonLogs,daemonRawLines:m.visibleDaemonRawLines,trace:m.visibleTraceEntries,webEvents:m.visibleWebEvents});if(!k.trim()){ft.showToast("No visible logs to copy.","info");return}try{await((f=navigator.clipboard)==null?void 0:f.writeText(k)),ft.showToast("Copied visible logs to clipboard.","success")}catch(x){ft.showToast(x instanceof Error?x.message:"Could not copy visible logs","warning")}},[m.visibleDaemonLogs,m.visibleDaemonRawLines,m.visibleTraceEntries,m.visibleWebEvents]),g=l.useCallback(async()=>{var f;const k=LD({events:m.diagnosticEvents,summary:m.diagnosticsSummary,sources:m.sourceStates});try{await((f=navigator.clipboard)==null?void 0:f.writeText(k)),ft.showToast("Copied diagnostic bundle to clipboard.","success")}catch(x){ft.showToast(x instanceof Error?x.message:"Could not copy diagnostic bundle","warning")}},[m.diagnosticEvents,m.diagnosticsSummary,m.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(FD,{quickFilter:a,quickFilterCounts:m.quickFilterCounts,searchQuery:o,autoRefresh:n.autoRefresh,onQuickFilterChange:r,onSearchQueryChange:i,onCopyDiagnostics:()=>{g()},onCopyVisible:()=>{h()},onToggleAutoRefresh:()=>n.setAutoRefresh(k=>!k),onRefresh:n.refresh,onClear:n.clear}),s.jsx(BD,{logLevel:n.logLevel,traceCategory:n.traceCategory,onLogLevelChange:n.setLogLevel,onTraceCategoryChange:n.setTraceCategory}),s.jsx(WD,{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(OD,{patterns:m.diagnosticsSummary.repeatedPatterns}),s.jsx(UD,{streams:n,sectionsOpen:c,setSectionsOpen:u,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 GD(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 cf(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 zD(e){var r;const t=[],n=[],a=[];for(const o of e||[]){const i=String((o==null?void 0:o.lifecycle)||"").trim(),c=cf((o==null?void 0:o.meta)||void 0),u=((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")&&(u||c)?n.push(o):a.push(o)}return{liveRuntimes:t,recoverySnapshots:n,inactiveRecords:a}}function KD(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 hi(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function fi(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function xu(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 VD(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function YD(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 QD(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 JD({machineId:e,cliSessions:t,sendDaemonCommand:n}){const[a,r]=l.useState(""),[o,i]=l.useState(null),[c,u]=l.useState(!1),p=zj(e,{enabled:!!e,includeSessions:!0,limit:Vc,intervalMs:Xk}),d=p.diagnostics,m=p.loading,h=p.applyDiagnostics,g=l.useMemo(()=>GD({diagnostics:d,loading:m,refreshing:c,error:a}),[d,m,c,a]),k=l.useMemo(()=>new Map(t.map(I=>[I.sessionId||I.id,I])),[t]),f=l.useCallback(async()=>{if(e){u(!0);try{const I=await n(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Vc}),D=hi(I);if(!(D!=null&&D.success))throw new Error((D==null?void 0:D.error)||"Could not load hosted runtime diagnostics");h(D.diagnostics||D.result||null),r("")}catch(I){const D=I instanceof Error?I.message:"Could not load hosted runtime diagnostics";r(D)}finally{u(!1)}}},[h,e,n]);l.useEffect(()=>{!e||d||m||c||f()},[d,m,e,f,c]);const x=l.useCallback(async(I,D)=>{const P=`${I}:${D.sessionId}`;if(!(I==="session_host_stop_session"&&!window.confirm(`Stop ${D.displayName}?
|
|
108
108
|
This will terminate the hosted runtime.`))){i(P);try{const T=await n(e,I,{sessionId:D.sessionId}),H=hi(T);if(!(H!=null&&H.success))throw new Error((H==null?void 0:H.error)||"Session host action failed");const L=I==="session_host_resume_session"?"resumed":I==="session_host_restart_session"?"restarted":"stopped";ft.showToast(`Session host ${L}: ${D.displayName}`,"success"),await f()}catch(T){const H=T instanceof Error?T.message:"Session host action failed";ft.showToast(H,"warning"),r(H)}finally{i(T=>T===P?null:T)}}},[e,f,n]),w=l.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
|
|
109
|
-
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){i("session_host_prune_duplicate_sessions");try{const D=await n(e,"session_host_prune_duplicate_sessions",{}),P=hi(D);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Duplicate prune failed");const T=P.result||{},H=Array.isArray(T.prunedSessionIds)?T.prunedSessionIds.length:0,L=typeof T.duplicateGroupCount=="number"?T.duplicateGroupCount:0;ft.showToast(`Pruned ${H} duplicate runtime(s) across ${L} group(s)`,"success"),await f()}catch(D){const P=D instanceof Error?D.message:"Duplicate prune failed";ft.showToast(P,"warning"),r(P)}finally{i(D=>D==="session_host_prune_duplicate_sessions"?null:D)}}},[e,f,n]),b=l.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((I,D)=>(D.lastActivityAt||0)-(I.lastActivityAt||0)),[d==null?void 0:d.sessions]),N=l.useMemo(()=>d!=null&&d.liveRuntimes||d!=null&&d.recoverySnapshots||d!=null&&d.inactiveRecords?{liveRuntimes:(d==null?void 0:d.liveRuntimes)||[],recoverySnapshots:(d==null?void 0:d.recoverySnapshots)||[],inactiveRecords:(d==null?void 0:d.inactiveRecords)||[]}:zD(b),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,b]),j=N.liveRuntimes,v=N.recoverySnapshots,y=N.inactiveRecords,C=l.useMemo(()=>QD(j),[j]),S=l.useMemo(()=>[...(d==null?void 0:d.recentTransitions)||[]].slice(-6).reverse(),[d==null?void 0:d.recentTransitions]),A=l.useMemo(()=>[...(d==null?void 0:d.recentLogs)||[]].reverse().find(I=>I.level==="warn"||I.level==="error")||null,[d==null?void 0:d.recentLogs]),M=(I,D)=>{var _;const P=o===`session_host_resume_session:${I.sessionId}`,T=o===`session_host_restart_session:${I.sessionId}`,H=o===`session_host_stop_session:${I.sessionId}`,L=cf(I.meta),R=k.get(I.sessionId),U=I.attachedClients.length===1?"1 client":`${I.attachedClients.length} clients`,E=D==="recovery"?"Recover":"Resume",$=KD(D);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:I.displayName||(R==null?void 0:R.cliName)||I.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${YD(I.lifecycle)}`,children:I.lifecycle}),L&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:L})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:I.workspaceLabel||(R==null?void 0:R.runtimeWorkspaceLabel)||I.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:I.runtimeKey}),I.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",I.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((_=I.writeOwner)==null?void 0:_.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:VD(I.writeOwner)}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[s.jsx(zu,{size:11})," ",U]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",xu(I.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:[D==="recovery"&&(I.lifecycle==="interrupted"||I.lifecycle==="failed"||I.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{x("session_host_resume_session",I)},children:P?`${E}ing…`:E}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{x("session_host_restart_session",I)},children:T?"Restarting…":"Restart"}),D==="live"&&(I.lifecycle==="running"||I.lifecycle==="starting"||I.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!o,onClick:()=>{x("session_host_stop_session",I)},children:H?"Stopping…":"Stop"})]})]})},I.sessionId)};return s.jsxs(bs,{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(Ys,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:AC()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[C>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{w()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${C})`}),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:()=>{f()},disabled:m||c,children:[s.jsx(Zr,{size:13}),m||c?"Refreshing…":"Refresh"]})]})]}),a&&!d&&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(xn,{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})]})]})}),d&&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:d.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:d.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:xu(d.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:fi(d.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(xn,{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:[fi(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(gl,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:mi("live")}),j.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:j.map(I=>M(I,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(Ys,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:mi("recovery")}),v.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):s.jsx("div",{className:"space-y-2",children:v.map(I=>M(I,"recovery"))})]}),y.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:mi("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:y.map(I=>M(I,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),S.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:S.map(I=>{var P;const D=b.find(T=>T.sessionId===I.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(D==null?void 0:D.displayName)||((P=k.get(I.sessionId))==null?void 0:P.cliName)||I.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[I.action,I.lifecycle?` · ${I.lifecycle}`:"",I.detail?` · ${I.detail}`:"",I.error?` · ${I.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${I.success===!1?"text-red-300":"text-text-secondary"}`,children:fi(I.timestamp)})]},`${I.sessionId}:${I.timestamp}:${I.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:d.endpoint||"unknown"}),a?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",a]}):null]})]})]})}function XD({machine:e,launchPick:t,actions:n}){const{t:a}=Ce("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(Kt,{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-violet-500/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 ZD(e,t){const n=xj(e),a=qs(e,t),r=uo(e,a),o=ja(e,a),i=Em(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 bi({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 gi({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 eI({machineEntry:e,providers:t,recentLaunches:n,currentConversations:a,onUpgradeDaemon:r,onOpenRecent:o,onOpenConversation:i}){const{t:c}=Ce("common"),u=a.slice(0,6),p=n.slice(0,4),m=ZD(e,"1.0.47");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:[u.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(bi,{icon:s.jsx(Cn,{size:13}),children:c("machine.commandCenter.currentChats")}),s.jsx(gi,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(h=>{const g=Yi(h);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(h),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 group-hover:text-accent-primary transition-colors",children:kt(h)}),g>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:eo(g)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:Kn(h)})]},h.tabKey)})})})]}),p.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(bi,{icon:s.jsx(Ju,{size:13}),children:c("machine.commandCenter.recentLaunches")}),s.jsx(gi,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:p.map(h=>{const{metaText:g,updatedLabel:k}=oh(h);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(h),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 group-hover:text-accent-primary transition-colors",children:h.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})]},h.id)})})})]}),m.visible&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(bi,{icon:s.jsx(xn,{size:13}),children:c("machine.commandCenter.daemonUpdate")}),s.jsx(gi,{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(Zr,{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 tI({machineId:e,machine:t,ideSessions:n,cliSessions:a,acpSessions:r,actions:o,sendDaemonCommand:i}){const{workspaceBusy:c,handleWorkspaceAdd:u,handleWorkspaceRemove:p,handleWorkspaceSetDefault:d}=o,{t:m}=Ce("common"),[h,g]=l.useState(!1),[k,f]=l.useState(""),[x,w]=l.useState([]),[b,N]=l.useState(!1),[j,v]=l.useState(""),y=l.useCallback(async S=>{N(!0),v("");try{const A=await Gl(i,e,S);f(A.path),w(A.directories)}catch(A){v(A instanceof Error?A.message:"Could not load folder")}finally{N(!1)}},[e,i]),C=l.useCallback(()=>{g(!0);const S=[...n.map(M=>M.workspace),...a.map(M=>M.workspace),...r.map(M=>M.workspace)],A=ql(t.platform,Ul(S,t.defaultWorkspacePath,(t.workspaces||[]).map(M=>M.path)));y(A)},[r,a,n,y,t.defaultWorkspacePath,t.platform,t.workspaces]);return s.jsxs(s.Fragment,{children:[s.jsxs(bs,{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(Gn,{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:C,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(S=>{const A=S.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 d(A?null:S.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:kp(S.path,S.label)}),s.jsx("div",{className:"font-mono text-text-muted truncate text-[10px]",title:S.path,children:S.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void p(S.id),children:m("machine.managedWorkspaces.remove")})]},S.id)})})]}),h&&s.jsx(Kl,{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:j,confirmLabel:"Add workspace",onClose:()=>g(!1),onNavigate:S=>{y(S)},onConfirm:S=>{(async()=>{if(!S)return;await u(S)&&g(!1)})()}})]})}function sI({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(tI,{machineId:t,machine:e,ideSessions:n,cliSessions:a,acpSessions:r,actions:o,sendDaemonCommand:i})]})}function nI({onNicknameSynced:e}={}){var xe,Y,G,te,me,K,be,re,de,we,Re;const{t}=Ce("common"),{id:n}=zf(),a=Jn(),r=dl(),{sendCommand:o}=vt(),i=ea(),c=Bm(),u=cm(),p=u.ides||[],d=u.initialLoaded??!0,m=p.find(F=>F.id===n&&F.type==="adhdev-daemon"),h=p.some(F=>F.type==="adhdev-daemon"),g=n?(xe=u.connectionRetryStatuses)==null?void 0:xe[n]:void 0,k=!!(g!=null&&g.blocked),[f,x]=l.useState("workspace"),[w,b]=l.useState(null),[N,j]=l.useState(null);l.useCallback((F,J)=>{j({daemonId:F,workspace:J})},[]);const[,v]=l.useState("ide"),y=l.useRef(null),[C,S]=l.useState(null),A=l.useRef("__home__"),[M,I]=l.useState("__home__"),[D,P]=l.useState(!1),T=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 F=!1;return(async()=>{try{const J=await o(n,"get_status_metadata"),ge=J&&typeof J=="object"&&"result"in J?J.result:J,ue=ge==null?void 0:ge.providerChannelStaleness;!F&&ue&&!ue.error&&b({staleTypes:Array.isArray(ue.staleTypes)?ue.staleTypes:[],newTypes:Array.isArray(ue.newTypes)?ue.newTypes:[]})}catch{}})(),()=>{F=!0}},[n,m==null?void 0:m.id,o]),l.useEffect(()=>{if(!n||!m||f!=="overview"&&f!=="providers")return;const F=m.machine;(typeof(F==null?void 0:F.cpus)!="number"||typeof(F==null?void 0:F.totalMem)!="number"||typeof(F==null?void 0:F.arch)!="string"||typeof(F==null?void 0:F.release)!="string"||f==="providers"&&!(F!=null&&F.quota))&&c(n,{minFreshMs:3e4}).catch(()=>{})},[f,c,m,n]),Gj(n&&f==="overview"?[n]:[],{enabled:f==="overview",intervalMs:Yk});const H=()=>{if(h){a("/dashboard",{state:{mobileSection:"machines"}});return}a("/machines")},L=VT({machineId:n,registeredMachineId:(m==null?void 0:m.machineId)||null,sendDaemonCommand:o,onNicknameSynced:e,logsEndRef:T});l.useEffect(()=>ft.onToast(J=>{u.setToasts(ue=>{if(ue.some(Le=>Le.message===J.message&&J.timestamp-Le.timestamp<3e3))return ue;const De={id:J.id,message:J.message,type:J.type,timestamp:J.timestamp,targetKey:J.targetKey,actions:J.actions};return[...ue.slice(-4),De]});const ge=J.duration||5e3;setTimeout(()=>u.setToasts(ue=>ue.filter(ee=>ee.id!==J.id)),ge)}),[u]);const R=(m==null?void 0:m.availableProviders)||[],U={};for(const F of R)U[F.type]=F.icon;const E=m?{id:m.id,hostname:Sp(m,{fallbackId:m.id}),platform:((Y=m.machine)==null?void 0:Y.platform)||"unknown",arch:((G=m.machine)==null?void 0:G.arch)||"",cpus:((te=m.machine)==null?void 0:te.cpus)||0,totalMem:((me=m.machine)==null?void 0:me.totalMem)||0,freeMem:(K=m.machine)==null?void 0:K.freeMem,availableMem:(be=m.machine)==null?void 0:be.availableMem,loadavg:(re=m.machine)==null?void 0:re.loadavg,uptime:(de=m.machine)==null?void 0:de.uptime,release:((we=m.machine)==null?void 0:we.release)||"",cdpConnected:!!m.cdpConnected,machineNickname:m.machineNickname||null,...(Re=m.machine)!=null&&Re.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(F=>F.daemonId===n&&F.type!=="adhdev-daemon").filter(F=>!La(F)&&!Wn(F)).map(F=>({id:F.id,sessionId:F.sessionId,type:F.type,version:F.version||"",instanceId:F.instanceId||"",status:F.status,workspace:F.workspace||null,terminals:F.terminals||0,aiAgents:n0(F.aiAgents||(F.agents||[]).map(J=>({id:J.name,name:J.name,status:J.status,version:J.version}))),activeChat:F.activeChat||null,chats:F.chats||[],childSessions:F.childSessions||[],cdpConnected:F.cdpConnected||!1,daemonId:n,lastMessageAt:F.lastMessageAt})),_=p.filter(F=>F.daemonId===n&&La(F)).map(F=>({id:F.id,sessionId:F.sessionId,type:F.type,cliName:F.cliName||F.type,status:F.status,workspace:F.workspace||"",activeChat:F.activeChat||null,providerSessionId:F.providerSessionId,mode:F.mode,runtimeKey:F.runtimeKey,runtimeDisplayName:F.runtimeDisplayName,runtimeWorkspaceLabel:F.runtimeWorkspaceLabel,runtimeWriteOwner:F.runtimeWriteOwner||null,runtimeAttachedClients:F.runtimeAttachedClients||[],daemonId:n,lastMessageAt:F.lastMessageAt})),q=p.filter(F=>F.daemonId===n&&Wn(F)).map(F=>({id:F.id,sessionId:F.sessionId,type:F.type,acpName:F.cliName||F.type,status:F.status,workspace:F.workspace||"",activeChat:F.activeChat||null,providerSessionId:F.providerSessionId,daemonId:n,lastMessageAt:F.lastMessageAt})),B=m?as(m,{fallbackId:n}):"",W="workspace",V=r.state,ne=V==null?void 0:V.initialMachineTab,ae=V==null?void 0:V.initialWorkspaceCategory;V==null||V.initialWorkspaceId,V==null||V.initialWorkspacePath;const he=ne==="ides"||ne==="clis"||ne==="acps"?"workspace":ne||W,Z=ne==="ides"?"ide":ne==="clis"?"cli":ne==="acps"?"acp":ae,z=[...$.map(F=>{var J;return{id:`ide:${F.type}:${F.workspace||""}`,label:((J=F.activeChat)==null?void 0:J.title)||F.type,kind:"ide",providerType:F.type,subtitle:F.workspace||void 0,workspace:F.workspace||void 0,lastLaunchedAt:F.lastMessageAt||0}}),..._.map(F=>{var J;return{id:`cli:${F.type}:${F.workspace||""}`,label:((J=F.activeChat)==null?void 0:J.title)||F.cliName,kind:"cli",providerType:F.type,providerSessionId:F.providerSessionId,subtitle:F.workspace||void 0,workspace:F.workspace||void 0,lastLaunchedAt:F.lastMessageAt||0}}),...q.map(F=>{var J;return{id:`acp:${F.type}:${F.workspace||""}`,label:((J=F.activeChat)==null?void 0:J.title)||F.acpName,kind:"acp",providerType:F.type,providerSessionId:F.providerSessionId,subtitle:vn(F.summaryMetadata)||F.workspace||void 0,workspace:F.workspace||void 0,lastLaunchedAt:F.lastMessageAt||0}})].sort((F,J)=>(J.lastLaunchedAt||0)-(F.lastLaunchedAt||0)),X=((m==null?void 0:m.recentLaunches)||[]).length>0?((m==null?void 0:m.recentLaunches)||[]).map(F=>({id:F.id,label:F.title||F.providerName||F.providerType,kind:F.kind,providerType:F.providerType,providerSessionId:F.providerSessionId,subtitle:vn(F.summaryMetadata)||F.workspace||void 0,workspace:F.workspace,summaryMetadata:F.summaryMetadata,lastLaunchedAt:F.lastLaunchedAt})):z,O=l.useMemo(()=>{var J;const F=((J=u.connectionStates)==null?void 0:J[n||""])||void 0;return p.filter(ge=>ge.daemonId===n&&ge.type!=="adhdev-daemon").flatMap(ge=>Hl(ge,{connectionStates:n&&F?{[n]:F}:void 0,defaultConnectionState:F})).filter(ge=>!(ge.transport==="pty"&&ge.mode==="terminal")).sort((ge,ue)=>Yi(ue)-Yi(ge))},[p,u.connectionStates,n]),Q=l.useCallback(F=>{const J=Zm(F);J&&a(Ea(J))},[a]),ke=l.useCallback(()=>{y.current&&(P(!0),y.current().finally(()=>{y.current=null,P(!1),S(null)}))},[]),Se=l.useCallback(F=>{if(!E)return;const{options:J,selectedKey:ge}=rh({machine:E,currentWorkspacePath:F.workspace,homeLabel:t("newSession.homeDirectory"),homeDescription:t("newSession.launchWithoutWorkspace")}),ue=async()=>{v(F.kind),x("workspace")};y.current=async()=>{const ee=J.find(Xe=>Xe.key===A.current),De=(ee==null?void 0:ee.workspacePath)??null,Le=(ee==null?void 0:ee.workspaceId)??null;if(F.kind==="ide"&&F.providerType){await L.handleLaunchIde(F.providerType,De?{workspace:De}:void 0);return}if((F.kind==="cli"||F.kind==="acp")&&F.providerType){await L.runLaunchCliCore({cliType:F.providerType,dir:Le?void 0:De||"",workspaceId:Le||void 0,model:F.kind==="acp"&&jp(F.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:F.providerSessionId});return}await ue()},A.current=ge,I(ge),S({title:F.kind==="ide"?$r(t,"restart-ide",F.label):F.providerSessionId?ym(t,F.label):$r(t,"start-fresh",F.label),description:F.kind==="ide"?Fr(t,"restart-ide"):F.providerSessionId?wm(t):Fr(t,"start-fresh"),confirmLabel:F.kind==="ide"?Br(t,"restart-ide"):F.providerSessionId?Ui(t,!0):Br(t,"start-fresh"),busyLabel:F.kind==="ide"?Wr(t,"restart-ide"):F.providerSessionId?vm(t,!0):Wr(t,"start-fresh"),workspaceOptions:J,details:[{label:"Mode",value:F.kind.toUpperCase()},...F.providerType?[{label:"Provider",value:F.providerType}]:[]]})},[L,E]);if(l.useEffect(()=>{x(he)},[W,he,n]),l.useEffect(()=>{Z&&v(Z)},[Z,n]),!E)return d?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:H,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 ve=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ws,{size:14})," ",t("machine.detail.tabWorkspace")]}),count:$.length+_.length+q.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ys,{size:14})," ",t("machine.detail.tabHostedRuntimes")]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Xr,{size:14})," ",t("machine.detail.tabProviders")]}),...w&&w.staleTypes.length+w.newTypes.length>0?{count:w.staleTypes.length+w.newTypes.length}:{}},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx($b,{size:14})," ",t("machine.detail.tabSystem")]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Vu,{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:H,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:[L.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:L.nicknameInput,onChange:F=>L.setNicknameInput(F.target.value),onKeyDown:F=>{F.key==="Enter"&&L.handleSaveNickname(),F.key==="Escape"&&L.setEditingNickname(!1)},placeholder:t("machine.detail.nicknamePlaceholder"),className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:L.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:()=>L.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:()=>{L.setEditingNickname(!0),L.setNicknameInput(E.machineNickname||"")},title:t("machine.detail.clickToSetNickname"),children:B}),k?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),u.retryConnection&&n&&s.jsx("button",{onClick:()=>u.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:[E.platform," · ",E.arch]}),s.jsx("span",{children:t("machine.detail.coresCount",{count:E.cpus})}),(m==null?void 0:m.version)&&s.jsxs("span",{children:["v",m.version]}),E.p2p.available&&s.jsx("span",{children:t("machine.detail.p2pState",{state:E.p2p.state==="connected"?t("machine.detail.p2pConnected"):E.p2p.state})}),E.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:E.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-border-subtle",children:ve.map(F=>s.jsxs("button",{onClick:()=>x(F.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${f===F.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[F.label,F.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${f===F.id?"bg-accent-primary/20 text-accent-primary":"bg-bg-glass-hover text-text-muted"}`,children:F.count})]},F.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:[f==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(eI,{machineEntry:m,providers:R,recentLaunches:X,currentConversations:O,onUpgradeDaemon:async()=>{const F=po(m);if(F)try{await o(n,"daemon_upgrade",F)}catch{}},onOpenRecent:Se,onOpenConversation:Q}),s.jsx(sI,{machine:E,machineId:n,ideSessions:$,cliSessions:_,acpSessions:q,actions:L,sendDaemonCommand:o})]}),f==="providers"&&s.jsx(cD,{machineId:n,providers:R,sendDaemonCommand:o,quota:E.quota}),f==="overview"&&s.jsx(QT,{machine:E,ideSessions:$,cliSessions:_,acpSessions:q}),f==="session-host"&&s.jsx(JD,{machineId:n,cliSessions:_,sendDaemonCommand:o}),f==="logs"&&s.jsx(qD,{machineId:n,sendDaemonCommand:o})]})})}),L.launchPick&&E&&s.jsx(XD,{machine:E,launchPick:L.launchPick,actions:L}),C&&s.jsx(mo,{title:C.title,description:C.description,details:C.details,workspaceOptions:C.workspaceOptions,selectedWorkspaceKey:M,onWorkspaceChange:F=>{A.current=F,I(F)},confirmLabel:C.confirmLabel,busyLabel:C.busyLabel,busy:D,onConfirm:ke,onCancel:()=>{y.current=null,S(null)}}),N&&s.jsx(of,{daemonId:N.daemonId,workspace:N.workspace,onClose:()=>j(null)}),s.jsx(Sm,{toasts:u.toasts||[],onDismiss:F=>u.setToasts(J=>J.filter(ge=>ge.id!==F)),onClickToast:F=>{F.targetKey&&a(Ea(F.targetKey))}}),s.jsx("style",{children:`
|
|
109
|
+
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){i("session_host_prune_duplicate_sessions");try{const D=await n(e,"session_host_prune_duplicate_sessions",{}),P=hi(D);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Duplicate prune failed");const T=P.result||{},H=Array.isArray(T.prunedSessionIds)?T.prunedSessionIds.length:0,L=typeof T.duplicateGroupCount=="number"?T.duplicateGroupCount:0;ft.showToast(`Pruned ${H} duplicate runtime(s) across ${L} group(s)`,"success"),await f()}catch(D){const P=D instanceof Error?D.message:"Duplicate prune failed";ft.showToast(P,"warning"),r(P)}finally{i(D=>D==="session_host_prune_duplicate_sessions"?null:D)}}},[e,f,n]),b=l.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((I,D)=>(D.lastActivityAt||0)-(I.lastActivityAt||0)),[d==null?void 0:d.sessions]),N=l.useMemo(()=>d!=null&&d.liveRuntimes||d!=null&&d.recoverySnapshots||d!=null&&d.inactiveRecords?{liveRuntimes:(d==null?void 0:d.liveRuntimes)||[],recoverySnapshots:(d==null?void 0:d.recoverySnapshots)||[],inactiveRecords:(d==null?void 0:d.inactiveRecords)||[]}:zD(b),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,b]),j=N.liveRuntimes,v=N.recoverySnapshots,y=N.inactiveRecords,C=l.useMemo(()=>QD(j),[j]),S=l.useMemo(()=>[...(d==null?void 0:d.recentTransitions)||[]].slice(-6).reverse(),[d==null?void 0:d.recentTransitions]),A=l.useMemo(()=>[...(d==null?void 0:d.recentLogs)||[]].reverse().find(I=>I.level==="warn"||I.level==="error")||null,[d==null?void 0:d.recentLogs]),M=(I,D)=>{var _;const P=o===`session_host_resume_session:${I.sessionId}`,T=o===`session_host_restart_session:${I.sessionId}`,H=o===`session_host_stop_session:${I.sessionId}`,L=cf(I.meta),R=k.get(I.sessionId),U=I.attachedClients.length===1?"1 client":`${I.attachedClients.length} clients`,E=D==="recovery"?"Recover":"Resume",$=KD(D);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:I.displayName||(R==null?void 0:R.cliName)||I.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${YD(I.lifecycle)}`,children:I.lifecycle}),L&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:L})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:I.workspaceLabel||(R==null?void 0:R.runtimeWorkspaceLabel)||I.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:I.runtimeKey}),I.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",I.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((_=I.writeOwner)==null?void 0:_.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:VD(I.writeOwner)}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[s.jsx(zu,{size:11})," ",U]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",xu(I.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:[D==="recovery"&&(I.lifecycle==="interrupted"||I.lifecycle==="failed"||I.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{x("session_host_resume_session",I)},children:P?`${E}ing…`:E}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{x("session_host_restart_session",I)},children:T?"Restarting…":"Restart"}),D==="live"&&(I.lifecycle==="running"||I.lifecycle==="starting"||I.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!o,onClick:()=>{x("session_host_stop_session",I)},children:H?"Stopping…":"Stop"})]})]})},I.sessionId)};return s.jsxs(bs,{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(Ys,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:AC()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[C>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{w()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${C})`}),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:()=>{f()},disabled:m||c,children:[s.jsx(Zr,{size:13}),m||c?"Refreshing…":"Refresh"]})]})]}),a&&!d&&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(xn,{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})]})]})}),d&&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:d.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:d.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:xu(d.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:fi(d.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(xn,{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:[fi(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(gl,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:mi("live")}),j.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:j.map(I=>M(I,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(Ys,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:mi("recovery")}),v.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):s.jsx("div",{className:"space-y-2",children:v.map(I=>M(I,"recovery"))})]}),y.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:mi("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:y.map(I=>M(I,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),S.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:S.map(I=>{var P;const D=b.find(T=>T.sessionId===I.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(D==null?void 0:D.displayName)||((P=k.get(I.sessionId))==null?void 0:P.cliName)||I.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[I.action,I.lifecycle?` · ${I.lifecycle}`:"",I.detail?` · ${I.detail}`:"",I.error?` · ${I.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${I.success===!1?"text-red-300":"text-text-secondary"}`,children:fi(I.timestamp)})]},`${I.sessionId}:${I.timestamp}:${I.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:d.endpoint||"unknown"}),a?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",a]}):null]})]})]})}function XD({machine:e,launchPick:t,actions:n}){const{t:a}=Ce("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(Kt,{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-violet-500/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 ZD(e,t){const n=xj(e),a=qs(e,t),r=uo(e,a),o=ja(e,a),i=Em(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 bi({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 gi({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 eI({machineEntry:e,providers:t,recentLaunches:n,currentConversations:a,onUpgradeDaemon:r,onOpenRecent:o,onOpenConversation:i}){const{t:c}=Ce("common"),u=a.slice(0,6),p=n.slice(0,4),m=ZD(e,"1.0.48");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:[u.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(bi,{icon:s.jsx(Cn,{size:13}),children:c("machine.commandCenter.currentChats")}),s.jsx(gi,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(h=>{const g=Yi(h);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(h),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 group-hover:text-accent-primary transition-colors",children:kt(h)}),g>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:eo(g)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:Kn(h)})]},h.tabKey)})})})]}),p.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(bi,{icon:s.jsx(Ju,{size:13}),children:c("machine.commandCenter.recentLaunches")}),s.jsx(gi,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:p.map(h=>{const{metaText:g,updatedLabel:k}=oh(h);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(h),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 group-hover:text-accent-primary transition-colors",children:h.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})]},h.id)})})})]}),m.visible&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(bi,{icon:s.jsx(xn,{size:13}),children:c("machine.commandCenter.daemonUpdate")}),s.jsx(gi,{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(Zr,{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 tI({machineId:e,machine:t,ideSessions:n,cliSessions:a,acpSessions:r,actions:o,sendDaemonCommand:i}){const{workspaceBusy:c,handleWorkspaceAdd:u,handleWorkspaceRemove:p,handleWorkspaceSetDefault:d}=o,{t:m}=Ce("common"),[h,g]=l.useState(!1),[k,f]=l.useState(""),[x,w]=l.useState([]),[b,N]=l.useState(!1),[j,v]=l.useState(""),y=l.useCallback(async S=>{N(!0),v("");try{const A=await Gl(i,e,S);f(A.path),w(A.directories)}catch(A){v(A instanceof Error?A.message:"Could not load folder")}finally{N(!1)}},[e,i]),C=l.useCallback(()=>{g(!0);const S=[...n.map(M=>M.workspace),...a.map(M=>M.workspace),...r.map(M=>M.workspace)],A=ql(t.platform,Ul(S,t.defaultWorkspacePath,(t.workspaces||[]).map(M=>M.path)));y(A)},[r,a,n,y,t.defaultWorkspacePath,t.platform,t.workspaces]);return s.jsxs(s.Fragment,{children:[s.jsxs(bs,{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(Gn,{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:C,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(S=>{const A=S.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 d(A?null:S.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:kp(S.path,S.label)}),s.jsx("div",{className:"font-mono text-text-muted truncate text-[10px]",title:S.path,children:S.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void p(S.id),children:m("machine.managedWorkspaces.remove")})]},S.id)})})]}),h&&s.jsx(Kl,{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:j,confirmLabel:"Add workspace",onClose:()=>g(!1),onNavigate:S=>{y(S)},onConfirm:S=>{(async()=>{if(!S)return;await u(S)&&g(!1)})()}})]})}function sI({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(tI,{machineId:t,machine:e,ideSessions:n,cliSessions:a,acpSessions:r,actions:o,sendDaemonCommand:i})]})}function nI({onNicknameSynced:e}={}){var xe,Y,G,te,me,K,be,re,de,we,Re;const{t}=Ce("common"),{id:n}=zf(),a=Jn(),r=dl(),{sendCommand:o}=vt(),i=ea(),c=Bm(),u=cm(),p=u.ides||[],d=u.initialLoaded??!0,m=p.find(F=>F.id===n&&F.type==="adhdev-daemon"),h=p.some(F=>F.type==="adhdev-daemon"),g=n?(xe=u.connectionRetryStatuses)==null?void 0:xe[n]:void 0,k=!!(g!=null&&g.blocked),[f,x]=l.useState("workspace"),[w,b]=l.useState(null),[N,j]=l.useState(null);l.useCallback((F,J)=>{j({daemonId:F,workspace:J})},[]);const[,v]=l.useState("ide"),y=l.useRef(null),[C,S]=l.useState(null),A=l.useRef("__home__"),[M,I]=l.useState("__home__"),[D,P]=l.useState(!1),T=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 F=!1;return(async()=>{try{const J=await o(n,"get_status_metadata"),ge=J&&typeof J=="object"&&"result"in J?J.result:J,ue=ge==null?void 0:ge.providerChannelStaleness;!F&&ue&&!ue.error&&b({staleTypes:Array.isArray(ue.staleTypes)?ue.staleTypes:[],newTypes:Array.isArray(ue.newTypes)?ue.newTypes:[]})}catch{}})(),()=>{F=!0}},[n,m==null?void 0:m.id,o]),l.useEffect(()=>{if(!n||!m||f!=="overview"&&f!=="providers")return;const F=m.machine;(typeof(F==null?void 0:F.cpus)!="number"||typeof(F==null?void 0:F.totalMem)!="number"||typeof(F==null?void 0:F.arch)!="string"||typeof(F==null?void 0:F.release)!="string"||f==="providers"&&!(F!=null&&F.quota))&&c(n,{minFreshMs:3e4}).catch(()=>{})},[f,c,m,n]),Gj(n&&f==="overview"?[n]:[],{enabled:f==="overview",intervalMs:Yk});const H=()=>{if(h){a("/dashboard",{state:{mobileSection:"machines"}});return}a("/machines")},L=VT({machineId:n,registeredMachineId:(m==null?void 0:m.machineId)||null,sendDaemonCommand:o,onNicknameSynced:e,logsEndRef:T});l.useEffect(()=>ft.onToast(J=>{u.setToasts(ue=>{if(ue.some(Le=>Le.message===J.message&&J.timestamp-Le.timestamp<3e3))return ue;const De={id:J.id,message:J.message,type:J.type,timestamp:J.timestamp,targetKey:J.targetKey,actions:J.actions};return[...ue.slice(-4),De]});const ge=J.duration||5e3;setTimeout(()=>u.setToasts(ue=>ue.filter(ee=>ee.id!==J.id)),ge)}),[u]);const R=(m==null?void 0:m.availableProviders)||[],U={};for(const F of R)U[F.type]=F.icon;const E=m?{id:m.id,hostname:Sp(m,{fallbackId:m.id}),platform:((Y=m.machine)==null?void 0:Y.platform)||"unknown",arch:((G=m.machine)==null?void 0:G.arch)||"",cpus:((te=m.machine)==null?void 0:te.cpus)||0,totalMem:((me=m.machine)==null?void 0:me.totalMem)||0,freeMem:(K=m.machine)==null?void 0:K.freeMem,availableMem:(be=m.machine)==null?void 0:be.availableMem,loadavg:(re=m.machine)==null?void 0:re.loadavg,uptime:(de=m.machine)==null?void 0:de.uptime,release:((we=m.machine)==null?void 0:we.release)||"",cdpConnected:!!m.cdpConnected,machineNickname:m.machineNickname||null,...(Re=m.machine)!=null&&Re.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(F=>F.daemonId===n&&F.type!=="adhdev-daemon").filter(F=>!La(F)&&!Wn(F)).map(F=>({id:F.id,sessionId:F.sessionId,type:F.type,version:F.version||"",instanceId:F.instanceId||"",status:F.status,workspace:F.workspace||null,terminals:F.terminals||0,aiAgents:n0(F.aiAgents||(F.agents||[]).map(J=>({id:J.name,name:J.name,status:J.status,version:J.version}))),activeChat:F.activeChat||null,chats:F.chats||[],childSessions:F.childSessions||[],cdpConnected:F.cdpConnected||!1,daemonId:n,lastMessageAt:F.lastMessageAt})),_=p.filter(F=>F.daemonId===n&&La(F)).map(F=>({id:F.id,sessionId:F.sessionId,type:F.type,cliName:F.cliName||F.type,status:F.status,workspace:F.workspace||"",activeChat:F.activeChat||null,providerSessionId:F.providerSessionId,mode:F.mode,runtimeKey:F.runtimeKey,runtimeDisplayName:F.runtimeDisplayName,runtimeWorkspaceLabel:F.runtimeWorkspaceLabel,runtimeWriteOwner:F.runtimeWriteOwner||null,runtimeAttachedClients:F.runtimeAttachedClients||[],daemonId:n,lastMessageAt:F.lastMessageAt})),q=p.filter(F=>F.daemonId===n&&Wn(F)).map(F=>({id:F.id,sessionId:F.sessionId,type:F.type,acpName:F.cliName||F.type,status:F.status,workspace:F.workspace||"",activeChat:F.activeChat||null,providerSessionId:F.providerSessionId,daemonId:n,lastMessageAt:F.lastMessageAt})),B=m?as(m,{fallbackId:n}):"",W="workspace",V=r.state,ne=V==null?void 0:V.initialMachineTab,ae=V==null?void 0:V.initialWorkspaceCategory;V==null||V.initialWorkspaceId,V==null||V.initialWorkspacePath;const he=ne==="ides"||ne==="clis"||ne==="acps"?"workspace":ne||W,Z=ne==="ides"?"ide":ne==="clis"?"cli":ne==="acps"?"acp":ae,z=[...$.map(F=>{var J;return{id:`ide:${F.type}:${F.workspace||""}`,label:((J=F.activeChat)==null?void 0:J.title)||F.type,kind:"ide",providerType:F.type,subtitle:F.workspace||void 0,workspace:F.workspace||void 0,lastLaunchedAt:F.lastMessageAt||0}}),..._.map(F=>{var J;return{id:`cli:${F.type}:${F.workspace||""}`,label:((J=F.activeChat)==null?void 0:J.title)||F.cliName,kind:"cli",providerType:F.type,providerSessionId:F.providerSessionId,subtitle:F.workspace||void 0,workspace:F.workspace||void 0,lastLaunchedAt:F.lastMessageAt||0}}),...q.map(F=>{var J;return{id:`acp:${F.type}:${F.workspace||""}`,label:((J=F.activeChat)==null?void 0:J.title)||F.acpName,kind:"acp",providerType:F.type,providerSessionId:F.providerSessionId,subtitle:vn(F.summaryMetadata)||F.workspace||void 0,workspace:F.workspace||void 0,lastLaunchedAt:F.lastMessageAt||0}})].sort((F,J)=>(J.lastLaunchedAt||0)-(F.lastLaunchedAt||0)),X=((m==null?void 0:m.recentLaunches)||[]).length>0?((m==null?void 0:m.recentLaunches)||[]).map(F=>({id:F.id,label:F.title||F.providerName||F.providerType,kind:F.kind,providerType:F.providerType,providerSessionId:F.providerSessionId,subtitle:vn(F.summaryMetadata)||F.workspace||void 0,workspace:F.workspace,summaryMetadata:F.summaryMetadata,lastLaunchedAt:F.lastLaunchedAt})):z,O=l.useMemo(()=>{var J;const F=((J=u.connectionStates)==null?void 0:J[n||""])||void 0;return p.filter(ge=>ge.daemonId===n&&ge.type!=="adhdev-daemon").flatMap(ge=>Hl(ge,{connectionStates:n&&F?{[n]:F}:void 0,defaultConnectionState:F})).filter(ge=>!(ge.transport==="pty"&&ge.mode==="terminal")).sort((ge,ue)=>Yi(ue)-Yi(ge))},[p,u.connectionStates,n]),Q=l.useCallback(F=>{const J=Zm(F);J&&a(Ea(J))},[a]),ke=l.useCallback(()=>{y.current&&(P(!0),y.current().finally(()=>{y.current=null,P(!1),S(null)}))},[]),Se=l.useCallback(F=>{if(!E)return;const{options:J,selectedKey:ge}=rh({machine:E,currentWorkspacePath:F.workspace,homeLabel:t("newSession.homeDirectory"),homeDescription:t("newSession.launchWithoutWorkspace")}),ue=async()=>{v(F.kind),x("workspace")};y.current=async()=>{const ee=J.find(Xe=>Xe.key===A.current),De=(ee==null?void 0:ee.workspacePath)??null,Le=(ee==null?void 0:ee.workspaceId)??null;if(F.kind==="ide"&&F.providerType){await L.handleLaunchIde(F.providerType,De?{workspace:De}:void 0);return}if((F.kind==="cli"||F.kind==="acp")&&F.providerType){await L.runLaunchCliCore({cliType:F.providerType,dir:Le?void 0:De||"",workspaceId:Le||void 0,model:F.kind==="acp"&&jp(F.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:F.providerSessionId});return}await ue()},A.current=ge,I(ge),S({title:F.kind==="ide"?$r(t,"restart-ide",F.label):F.providerSessionId?ym(t,F.label):$r(t,"start-fresh",F.label),description:F.kind==="ide"?Fr(t,"restart-ide"):F.providerSessionId?wm(t):Fr(t,"start-fresh"),confirmLabel:F.kind==="ide"?Br(t,"restart-ide"):F.providerSessionId?Ui(t,!0):Br(t,"start-fresh"),busyLabel:F.kind==="ide"?Wr(t,"restart-ide"):F.providerSessionId?vm(t,!0):Wr(t,"start-fresh"),workspaceOptions:J,details:[{label:"Mode",value:F.kind.toUpperCase()},...F.providerType?[{label:"Provider",value:F.providerType}]:[]]})},[L,E]);if(l.useEffect(()=>{x(he)},[W,he,n]),l.useEffect(()=>{Z&&v(Z)},[Z,n]),!E)return d?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:H,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 ve=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ws,{size:14})," ",t("machine.detail.tabWorkspace")]}),count:$.length+_.length+q.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ys,{size:14})," ",t("machine.detail.tabHostedRuntimes")]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Xr,{size:14})," ",t("machine.detail.tabProviders")]}),...w&&w.staleTypes.length+w.newTypes.length>0?{count:w.staleTypes.length+w.newTypes.length}:{}},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx($b,{size:14})," ",t("machine.detail.tabSystem")]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Vu,{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:H,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:[L.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:L.nicknameInput,onChange:F=>L.setNicknameInput(F.target.value),onKeyDown:F=>{F.key==="Enter"&&L.handleSaveNickname(),F.key==="Escape"&&L.setEditingNickname(!1)},placeholder:t("machine.detail.nicknamePlaceholder"),className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:L.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:()=>L.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:()=>{L.setEditingNickname(!0),L.setNicknameInput(E.machineNickname||"")},title:t("machine.detail.clickToSetNickname"),children:B}),k?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),u.retryConnection&&n&&s.jsx("button",{onClick:()=>u.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:[E.platform," · ",E.arch]}),s.jsx("span",{children:t("machine.detail.coresCount",{count:E.cpus})}),(m==null?void 0:m.version)&&s.jsxs("span",{children:["v",m.version]}),E.p2p.available&&s.jsx("span",{children:t("machine.detail.p2pState",{state:E.p2p.state==="connected"?t("machine.detail.p2pConnected"):E.p2p.state})}),E.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:E.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-border-subtle",children:ve.map(F=>s.jsxs("button",{onClick:()=>x(F.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${f===F.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[F.label,F.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${f===F.id?"bg-accent-primary/20 text-accent-primary":"bg-bg-glass-hover text-text-muted"}`,children:F.count})]},F.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:[f==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(eI,{machineEntry:m,providers:R,recentLaunches:X,currentConversations:O,onUpgradeDaemon:async()=>{const F=po(m);if(F)try{await o(n,"daemon_upgrade",F)}catch{}},onOpenRecent:Se,onOpenConversation:Q}),s.jsx(sI,{machine:E,machineId:n,ideSessions:$,cliSessions:_,acpSessions:q,actions:L,sendDaemonCommand:o})]}),f==="providers"&&s.jsx(cD,{machineId:n,providers:R,sendDaemonCommand:o,quota:E.quota}),f==="overview"&&s.jsx(QT,{machine:E,ideSessions:$,cliSessions:_,acpSessions:q}),f==="session-host"&&s.jsx(JD,{machineId:n,cliSessions:_,sendDaemonCommand:o}),f==="logs"&&s.jsx(qD,{machineId:n,sendDaemonCommand:o})]})})}),L.launchPick&&E&&s.jsx(XD,{machine:E,launchPick:L.launchPick,actions:L}),C&&s.jsx(mo,{title:C.title,description:C.description,details:C.details,workspaceOptions:C.workspaceOptions,selectedWorkspaceKey:M,onWorkspaceChange:F=>{A.current=F,I(F)},confirmLabel:C.confirmLabel,busyLabel:C.busyLabel,busy:D,onConfirm:ke,onCancel:()=>{y.current=null,S(null)}}),N&&s.jsx(of,{daemonId:N.daemonId,workspace:N.workspace,onClose:()=>j(null)}),s.jsx(Sm,{toasts:u.toasts||[],onDismiss:F=>u.setToasts(J=>J.filter(ge=>ge.id!==F)),onClickToast:F=>{F.targetKey&&a(Ea(F.targetKey))}}),s.jsx("style",{children:`
|
|
110
110
|
@keyframes toast-in {
|
|
111
111
|
from { opacity: 0; transform: translateX(40px); }
|
|
112
112
|
to { opacity: 1; transform: translateX(0); }
|
|
113
113
|
}
|
|
114
114
|
`})]})}function aI({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 u=c.map(p=>gs.subscribe({sendData:n},p,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${p}`,params:{includeSessions:!0}},d=>{if(d.topic!=="daemon.metadata")return;const m=d.meshStateRevisions;if(!m)return;const h=m[t]??m["*"];if(typeof h!="number")return;const g=r.current.get(p);r.current.set(p,h),g!==void 0&&h>g&&o.current()}));return()=>{for(const p of u)p()}},[i,t,n])}const df={meshHostDaemonSection:!1,createDaemonPicker:!1,addNodeDaemonPicker:!1,queueSection:!0,coordinatorPrompt:!0,nodeInstruction:!0,hermesMcpConfig:!0,reviewInbox:!0},uf=l.createContext(null);function rI(){const e=l.useContext(uf);if(!e)throw new Error("useRepoMeshContext must be used inside RepoMeshProvider");return e}const Yr="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function el({workspaces:e,value:t,onChange:n,autoFocus:a}){const{t:r}=Ce("common"),[o,i]=l.useState(!1),c=new Set(e.map(p=>p.path)),u=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:Yr,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:Yr,value:u,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 pf({plan:e,loading:t}){var r,o;const{t:n}=Ce("common");if(t)return s.jsx("p",{className:"text-[11px] text-text-muted",children:n("setupWizard.machines.planChecking")});if(!e)return null;if(e.success===!1)return s.jsxs("p",{className:"text-[11px] text-red-400",children:[e.error,e.action?` ${e.action}`:""]});const a=((r=e.discovery)==null?void 0:r.repoIdentity)||((o=e.discovery)==null?void 0:o.repoRoot)||"";return s.jsx("p",{className:"text-[11px] text-emerald-400",children:n("setupWizard.machines.planOk",{identity:a})})}function oI(e){var t;return e.creating||e.planLoading||!e.name.trim()||e.showDaemonPicker&&!e.daemonId||((t=e.plan)==null?void 0:t.success)===!1?!0:e.workspace.trim()?!1:!e.repoRemoteUrl.trim()&&!e.repoIdentity.trim()}function mf(e){var P;const{variant:t="page",showDaemonPicker:n,daemons:a,daemonLabel:r,name:o,onNameChange:i,daemonId:c,onDaemonIdChange:u,workspace:p,onWorkspaceChange:d,workspaces:m,plan:h,planLoading:g,repoRemoteUrl:k,onRepoRemoteUrlChange:f,repoIdentity:x,onRepoIdentityChange:w,manualOpen:b,onManualOpenChange:N,creating:j,warning:v,onCreate:y,onCancel:C}=e,{t:S}=Ce("common"),A=oI({creating:j,planLoading:g,plan:h,name:o,workspace:p,showDaemonPicker:n,daemonId:c,repoRemoteUrl:k,repoIdentity:x}),M=b||!!k.trim()||!!x.trim(),I=n&&a.length>0&&s.jsxs("select",{className:t==="wizard"?Yr:"input w-full",value:c,onChange:T=>u(T.target.value),children:[s.jsx("option",{value:"",children:S("setupWizard.machines.machineSelectPlaceholder")}),a.map(T=>s.jsx("option",{value:T.id,children:r(T)},T.id))]}),D=M?s.jsxs(s.Fragment,{children:[s.jsx(At,{label:S("repoMesh.list.remoteUrl"),hint:S("repoMesh.list.remoteUrlHint"),children:s.jsx(fs,{value:k,onChange:T=>f(T.target.value),placeholder:"https://github.com/user/repo"})}),s.jsx(At,{label:S("repoMesh.list.repoIdentity"),hint:S("repoMesh.list.repoIdentityHint"),children:s.jsx(fs,{value:x,onChange:T=>w(T.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:()=>N(!0),children:S("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:S("setupWizard.machines.meshName")}),s.jsx("input",{type:"text",className:Yr,value:o,onChange:T=>i(T.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:S("setupWizard.machines.machine")}),I]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:S("setupWizard.machines.workspace")}),s.jsx(el,{workspaces:m,value:p,onChange:d})]}),s.jsx(pf,{plan:h,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:S(j?"setupWizard.machines.creating":"setupWizard.machines.create")})})]}):s.jsxs(s.Fragment,{children:[s.jsx("h3",{className:"text-base font-bold mb-4",children:S("repoMesh.list.createTitle")}),n&&s.jsx(At,{label:S("repoMesh.list.createOnMachine"),hint:S("repoMesh.list.createOnMachineHint"),children:a.length===0?s.jsx("select",{className:"input w-full",disabled:!0,children:s.jsx("option",{value:"",children:S("repoMesh.list.noConnectedDaemon")})}):I}),s.jsx(At,{label:S("repoMesh.list.workspace"),hint:S("repoMesh.list.workspaceHint"),children:s.jsx(el,{workspaces:m,value:p,onChange:d})}),(g||h)&&s.jsx(Dt,{variant:(h==null?void 0:h.success)===!1?"error":"info",className:"mb-4",children:g?S("setupWizard.machines.planChecking"):h!=null&&h.success?`${((P=h.plan)==null?void 0:P.summary)||"Git repository detected."} No changes will be made until you click Create.`:`${(h==null?void 0:h.code)||"onboarding_blocked"}: ${(h==null?void 0:h.error)||"Git discovery failed"} ${(h==null?void 0:h.action)||""}`}),s.jsx(At,{label:S("repoMesh.list.name"),children:s.jsx(fs,{value:o,onChange:T=>i(T.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx("div",{className:"flex flex-col",children:D}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:y,disabled:A,children:S(j?"repoMesh.list.creating":"repoMesh.list.create")}),C&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:C,disabled:j,children:S("repoMesh.list.cancel")})]})]})}function iI({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 lI({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 cI({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 dI({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 uI({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 pI(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function mI({meshes:e,loading:t,error:n,onDismissError:a,daemons:r,features:o,showCreate:i,onToggleCreate:c,createName:u,onCreateNameChange:p,createRepoIdentity:d,onCreateRepoIdentityChange:m,createRepoRemoteUrl:h,onCreateRepoRemoteUrlChange:g,newMeshDaemonId:k,onNewMeshDaemonIdChange:f,newMeshWorkspace:x,onNewMeshWorkspaceChange:w,createPickerWorkspaces:b,createOnboardingPlan:N,createPlanLoading:j,creating:v,createWarning:y,onDismissCreateWarning:C,onSelectMesh:S,onCreate:A,onCancelCreate:M}){const{t:I}=Ce("common"),D=o.maxMeshes!=null&&e.length>=o.maxMeshes,[P,T]=l.useState(!1);return s.jsxs(Oa,{icon:s.jsx(ns,{}),title:I("repoMesh.list.title"),subtitle:I("repoMesh.list.count",{count:e.length}),widthClassName:"max-w-5xl",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:c,disabled:D,title:D?I("repoMesh.list.meshLimitReached",{max:o.maxMeshes}):void 0,children:I("repoMesh.list.createMesh")}),children:[D&&s.jsx(Dt,{variant:"info",className:"mb-4",children:I("repoMesh.list.meshLimitBanner",{max:o.maxMeshes})}),n&&s.jsx(Dt,{variant:"error",onDismiss:a,className:"mb-4",children:n}),y&&s.jsx(Dt,{variant:"warning",onDismiss:C,className:"mb-4",children:y}),i&&s.jsx(ht,{className:"mb-5 border-accent/40 animate-[fadeIn_0.3s_ease-out]",children:s.jsx(mf,{variant:"page",showDaemonPicker:o.createDaemonPicker,daemons:r,daemonLabel:pI,name:u,onNameChange:p,daemonId:k,onDaemonIdChange:f,workspace:x,onWorkspaceChange:w,workspaces:b,plan:N,planLoading:j,repoRemoteUrl:h,onRepoRemoteUrlChange:g,repoIdentity:d,onRepoIdentityChange:m,manualOpen:P,onManualOpenChange:T,creating:v,onCreate:A,onCancel:M})}),t?s.jsx("div",{className:"text-sm text-text-muted p-4",children:I("repoMesh.list.loading")}):e.length===0?s.jsx(co,{icon:s.jsx(ns,{}),title:I("repoMesh.list.emptyTitle"),description:r.length>0?I("repoMesh.list.emptyWithDaemons"):I("repoMesh.list.emptyNoDaemons"),action:s.jsx("button",{className:"btn btn-primary btn-sm",disabled:!r.length,onClick:c,children:I("repoMesh.list.createFirst")})}):s.jsx("div",{className:"flex flex-col gap-2.5",children:e.map(H=>{var L;return s.jsx("button",{type:"button",onClick:()=>S(H.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(ns,{size:16}),s.jsx("span",{className:"font-bold text-sm",children:H.name})]}),s.jsxs("div",{className:"text-[12px] text-text-muted flex items-center gap-2",children:[s.jsx("span",{className:"font-mono",children:H.repoIdentity||H.repo_identity||I("repoMesh.list.noRepoIdentity")}),(H.defaultBranch||H.default_branch)&&s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(lI,{size:11}),H.defaultBranch||H.default_branch]})]})]}),s.jsxs("div",{className:"text-right text-[11px] text-text-muted shrink-0 ml-4",children:[s.jsx("div",{children:new Date(H.createdAt||H.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})}),s.jsxs("div",{className:"text-text-muted/60",children:[((L=H.nodes)==null?void 0:L.length)??H.nodeCount??0," ",I("repoMesh.list.nodesSuffix")]})]})]})},H.id)})})]})}function hI({tabs:e,defaultTabKey:t,ariaLabel:n,className:a}){var i;const[r,o]=l.useState(t??((i=e[0])==null?void 0:i.key));return s.jsxs("div",{className:a,children:[s.jsx("div",{className:"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",role:"tablist","aria-label":n,children:e.map(c=>{const u=c.key===r;return s.jsx("button",{type:"button",role:"tab","aria-selected":u,className:Ot("flex-1 rounded-lg px-3.5 py-1.5 text-[13px] font-medium transition-colors sm:flex-none",u?"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:()=>o(c.key),children:c.label},c.key)})}),e.map(c=>s.jsx("div",{className:c.key===r?"flex flex-col gap-4":"hidden",children:c.content},c.key))]})}const fI=["","low","medium","high"],bI={easy:"Easy",medium:"Medium",difficult:"Difficult",freeform:"Freeform"};function vu(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 yu(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 gI(){return{provider:"",model:"",thinkingLevel:"",difficulty:[],capability:[],maxParallel:""}}const on="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function xI({slots:e,availableProviders:t,saving:n,onSave:a}){const{t:r}=Ce("common"),[o,i]=l.useState(()=>e.map(vu)),c=l.useMemo(()=>JSON.stringify(e),[e]);l.useEffect(()=>{i(e.map(vu))},[c]);const u=l.useMemo(()=>[...new Set(t.map(b=>b.type).filter(Boolean))],[t]),p=l.useMemo(()=>Mm(t),[t]),d=l.useMemo(()=>{const b=o.map(yu).filter(Boolean);return JSON.stringify(b)!==JSON.stringify(e)},[o,e]),m=(b,N)=>i(j=>j.map((v,y)=>y===b?{...v,...N}:v)),h=(b,N)=>i(j=>j.map((v,y)=>{var A;if(y!==b)return v;const C=((A=p.get(N))==null?void 0:A.models)??[],S=!v.model||C.length===0||C.includes(v.model);return{...v,provider:N,...S?{}:{model:""}}})),g=b=>i(N=>N.filter((j,v)=>v!==b)),k=()=>i(b=>[...b,gI()]),f=(b,N)=>i(j=>{const v=b+N;if(v<0||v>=j.length)return j;const y=[...j];return[y[b],y[v]]=[y[v],y[b]],y}),x=(b,N)=>i(j=>j.map((v,y)=>{if(y!==b)return v;const C=v.difficulty.includes(N);return{...v,difficulty:C?v.difficulty.filter(S=>S!==N):[...v.difficulty,N]}})),w=()=>a(o.map(yu).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,N)=>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:["#",N+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:N===0,onClick:()=>f(N,-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:N===o.length-1,onClick:()=>f(N,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(N),"aria-label":r("repoMesh.slotEditor.removeSlot"),children:s.jsx(It,{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")}),u.length>0?s.jsxs("select",{className:on,value:b.provider,onChange:j=>h(N,j.target.value),children:[s.jsx("option",{value:"",children:r("repoMesh.slotEditor.select")}),u.map(j=>s.jsx("option",{value:j,children:j},j)),b.provider&&!u.includes(b.provider)&&s.jsx("option",{value:b.provider,children:b.provider})]}):s.jsx("input",{className:on,value:b.provider,placeholder:"claude-cli",onChange:j=>m(N,{provider:j.target.value})})]}),(()=>{var S;const j=p.get(b.provider),v=(j==null?void 0:j.models)??[],y=(S=j==null?void 0:j.thinking)!=null&&S.length?["",...j.thinking]:fI,C=!!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&&!C?s.jsxs("select",{className:on,value:v.includes(b.model)?b.model:"",onChange:A=>m(N,{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:on,value:b.model.trim(),placeholder:b.provider?`${b.provider} model`:r("repoMesh.slotEditor.modelPlaceholder"),onChange:A=>m(N,{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(N,{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:on,value:b.thinkingLevel,onChange:A=>m(N,{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:gp.map(j=>{const v=b.difficulty.includes(j);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(N,j),children:bI[j]},j)})})]}),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:on,value:b.capability.join(", "),placeholder:"worktree, os=darwin",onChange:j=>m(N,{capability:j.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:on,value:b.maxParallel,placeholder:r("repoMesh.slotEditor.maxParallelPlaceholder"),onChange:j=>m(N,{maxParallel:j.target.value})})]})]})]},N)),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(xl,{size:13})," ",r("repoMesh.slotEditor.addSlot")]}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm ml-auto",onClick:w,disabled:!!n||!d,children:r(n?"repoMesh.slotEditor.saving":"repoMesh.slotEditor.saveSlots")})]})]})}function vI(e){const t=new Map;for(const n of e)n!=null&&n.id&&t.set(n.id,en(n.availableProviders||[]));return t}function yI(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 wI(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 u=String((c==null?void 0:c.daemon_id)||(c==null?void 0:c.daemonId)||""),p=u?n.get(u):n.size===1?[...n.values()][0]:void 0;if(!p||p.length===0){i++;continue}o++;for(const d of p){const m=String((d==null?void 0:d.type)||(d==null?void 0:d.id)||"").trim();!m||a.has(m)||(a.add(m),r.push(d))}}return r.sort((c,u)=>String((c==null?void 0:c.type)||(c==null?void 0:c.id)||"").localeCompare(String((u==null?void 0:u.type)||(u==null?void 0:u.id)||""))),{providers:r,reportedNodeCount:o,unreportedNodeCount:i}}function kI(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 xp(t.slots))r(o.provider);if(Array.isArray(t.providerPriority))for(const o of t.providerPriority)r(o);return a}function SI(e){var u,p;const t=e,n=[],a=Array.isArray(t.capabilities)?t.capabilities:[];for(const d of a){const m=typeof d=="string"?d.trim():"";m&&n.push({tag:m,custom:!0})}const r=(((u=t.userOverrides)==null?void 0:u.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 d of kI(t.policy))n.push({tag:`provider=${d}`,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(d=>c.has(d.tag)?!1:(c.add(d.tag),!0))}function CI(e){const t=e.capabilities;return Array.isArray(t)?t.map(n=>typeof n=="string"?n.trim():"").filter(Boolean):[]}const jI=["os=","arch=","provider=","worktree=","converge="];function NI({node:e,saving:t,onSave:n}){const{t:a}=Ce("common"),r=l.useMemo(()=>SI(e).filter(f=>!f.custom),[e]),o=l.useMemo(()=>CI(e),[e]),[i,c]=l.useState(o),[u,p]=l.useState(""),d=JSON.stringify(i)!==JSON.stringify(o),h=(f=>{const x=f.trim();return x?/\s/.test(x)?a("repoMesh.tagEditor.noSpaces"):jI.some(w=>x.toLowerCase().startsWith(w))?a("repoMesh.tagEditor.reservedPrefix"):i.includes(x)?a("repoMesh.tagEditor.alreadyAdded"):null:null})(u);function g(){const f=u.trim();!f||h||(c(x=>[...x,f]),p(""))}function k(f){c(x=>x.filter(w=>w!==f))}return s.jsxs("div",{className:"mt-2",onClick:f=>f.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(f=>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:f.tag},f.tag)),i.map(f=>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:[f,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(f),disabled:t,"aria-label":a("repoMesh.tagEditor.remove",{tag:f}),children:"×"})]},f))]}),s.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-2",children:[s.jsx("input",{type:"text",value:u,onChange:f=>p(f.target.value),onKeyDown:f=>{f.key==="Enter"&&(f.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||!u.trim()||!!h,children:a("repoMesh.tagEditor.add")}),d&&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")})]}),h&&s.jsx("div",{className:"mt-1 text-[11px] text-amber-400",children:h}),i.length===0&&r.length===0&&s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:a("repoMesh.tagEditor.empty")})]})}function AI(e,t){return t.filter(n=>n.status!=="assigned"?!1:(n.assignedNodeId||n.nodeId)===e.id)}function MI(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 PI(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:qw((o=e.policy)==null?void 0:o.slots)}function TI(e){const t=PI(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 tl(e){return e.isLocalWorktree===!0}function DI(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 wu(e){return e&&(e.machineNickname||e.nickname||e.hostname||(e.id?ef(e.id):void 0))||"Unknown"}function II(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 LI({nodes:e,meshQueue:t,activeDaemon:n,daemons:a,selectedMeshId:r,userName:o,features:i,coordinatorDaemonId:c,availableCliProviders:u,savingNodeSlotsId:p,onUpdateNodeSlots:d,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:h,nodeSystemPromptDrafts:g,onNodeSystemPromptDraftChange:k,savingNodeSystemPromptId:f,onSaveNodeSystemPrompt:x,selectedNodeId:w,onSelectNode:b,showAddNode:N,onShowAddNode:j,onCancelAddNode:v,nodeWorkspace:y,onNodeWorkspaceChange:C,nodeProviderPriority:S,onNodeProviderPriorityChange:A,nodeDaemonId:M,onNodeDaemonIdChange:I,nodeCustomPath:D,onNodeCustomPathChange:P,nodePickerWorkspaces:T,nodePickerProviders:H,nodeOnboardingPlan:L,nodePlanLoading:R,attachableDaemons:U,onAddNode:E,onRemoveNode:$}){var W;const{t:_}=Ce("common"),q=l.useMemo(()=>vI(a),[a]),B=l.useMemo(()=>e.filter(V=>!tl(V)),[e]);return s.jsxs(ht,{title:i.addNodeDaemonPicker?_("repoMesh.nodeList.title",{count:B.length}):_("repoMesh.nodeList.titleNoCount"),description:i.addNodeDaemonPicker?_("repoMesh.nodeList.descriptionCloud"):_("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",{children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:_("repoMesh.nodeList.daemonCandidates")}),s.jsx("div",{className:"text-[12px] text-text-muted",children:_("repoMesh.nodeList.daemonCandidatesHint")})]}),s.jsx("span",{className:"text-[11px] text-text-muted",children:_("repoMesh.nodeList.available",{count:U.length})})]}),a.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:_("repoMesh.nodeList.noDaemonsAvailable")}):U.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:_("repoMesh.nodeList.allDaemonsAttached")}):s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:U.map(V=>s.jsxs("button",{type:"button",className:`text-left rounded-lg border px-3 py-2 transition-colors ${V.id===c?"border-accent-primary/50 bg-accent-primary/10":"border-border-subtle bg-bg-primary hover:border-border-default"}`,onClick:()=>{I(V.id),C(""),P(!1),A(wn(en(V.availableProviders||[]))),j()},children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-sm font-medium truncate",children:wu(V)}),V.id===c&&s.jsx("span",{className:"text-[10px] text-accent-primary",children:_("repoMesh.nodeList.selectedHost")})]}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted font-mono truncate",children:V.id}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:_("repoMesh.nodeList.workspacesDetected",{count:(V.workspaces||[]).length})})]},V.id))})]}),!N&&s.jsxs("button",{className:"btn btn-primary btn-sm mb-4 inline-flex items-center gap-1.5",onClick:j,children:[s.jsx(dI,{size:13})," ",i.addNodeDaemonPicker?_("repoMesh.nodeList.attachMachine"):_("repoMesh.nodeList.addNode")]}),N&&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?_("repoMesh.nodeList.attachMachineTitle"):_("repoMesh.nodeList.addNodeTitle")}),s.jsx("button",{onClick:()=>{v(),I(""),P(!1)},className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(It,{size:16})})]}),i.addNodeDaemonPicker&&s.jsx(At,{label:_("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:M,onChange:V=>{var ne;I(V.target.value),C(""),P(!1),A(wn(en(((ne=a.find(ae=>ae.id===V.target.value))==null?void 0:ne.availableProviders)||[])))},children:[s.jsx("option",{value:"",children:_("repoMesh.nodeList.selectMachine")}),a.map(V=>s.jsx("option",{value:V.id,children:wu(V)},V.id))]})}),(i.addNodeDaemonPicker?M:!0)&&s.jsx(At,{label:_("repoMesh.nodeList.workspacePath"),children:i.addNodeDaemonPicker&&!D&&T.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex flex-col gap-1.5 mb-2",children:T.map(V=>s.jsxs("button",{type:"button",className:`text-left text-xs px-3 py-2 rounded-lg border transition-colors ${y===V.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:()=>C(V.path),children:[s.jsx("span",{className:"font-medium block truncate",children:V.label||V.path.split("/").pop()}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:V.path})]},V.id||V.path))}),s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{P(!0),C("")},children:_("repoMesh.nodeList.enterCustomPath")})]}):s.jsx(s.Fragment,{children:i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[s.jsx(fs,{value:y,onChange:V=>C(V.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:V=>{V.key==="Enter"&&E()}}),T.length>0&&s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0 mt-1",onClick:()=>{P(!1),C("")},children:_("repoMesh.nodeList.pickFromSaved")})]}):(()=>{var ae;const V=Array.isArray(n==null?void 0:n.workspaces)?n.workspaces:[],ne=`mesh-add-node-workspaces-${r||"new"}`;return s.jsxs(s.Fragment,{children:[s.jsx(fs,{value:y,onChange:he=>C(he.target.value),placeholder:((ae=V[0])==null?void 0:ae.path)||"/Users/dev/projects/myapp",list:V.length>0?ne:void 0,autoFocus:!0}),V.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("datalist",{id:ne,children:V.map(he=>s.jsx("option",{value:he.path,children:he.label||he.path},he.id||he.path))}),s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:V.slice(0,6).map(he=>s.jsx("button",{type:"button",onClick:()=>C(he.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:he.path,children:he.label||he.path.split("/").filter(Boolean).pop()||he.path},he.id||he.path))})]})]})})()})}),(R||L)&&s.jsx(Dt,{variant:(L==null?void 0:L.success)===!1?"error":"info",className:"mb-4",children:R?"Inspecting Git repository (read-only)…":L!=null&&L.success?`${((W=L.plan)==null?void 0:W.summary)||"Compatible Git workspace detected."} Adding remains an explicit action.`:`${(L==null?void 0:L.code)||"onboarding_blocked"}: ${(L==null?void 0:L.error)||"Git discovery failed"} ${(L==null?void 0:L.action)||""}`}),s.jsx(At,{label:_("repoMesh.nodeList.preferredTools"),hint:_("repoMesh.nodeList.preferredToolsHint"),children:s.jsx(qC,{value:S,availableProviders:i.addNodeDaemonPicker?H:u,onChange:A})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:E,disabled:R||(L==null?void 0:L.success)===!1||!y.trim()||i.addNodeDaemonPicker&&!M,className:"btn btn-primary btn-sm",children:_("repoMesh.nodeList.add")}),s.jsx("button",{onClick:()=>{v(),I(""),P(!1)},className:"btn btn-secondary btn-sm",children:_("repoMesh.nodeList.cancel")})]})]}),B.length===0?s.jsx(co,{icon:s.jsx(Gn,{}),title:_("repoMesh.nodeList.emptyTitle"),description:_("repoMesh.nodeList.emptyDescription")}):s.jsx("div",{className:"flex flex-col gap-2",children:B.map(V=>{var X;const ne=TI(V),ae=AI(V,t),he=DI(V,n),Z=w===V.id,z=V.status||V.machine_status||(ae.length>0||he.length>0?"active":"enabled");return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary transition-colors ${i.addNodeDaemonPicker?"bg-bg-glass border-border-subtle rounded-xl px-5 py-4":`cursor-pointer ${Z?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`}`,role:i.addNodeDaemonPicker?void 0:"button",tabIndex:i.addNodeDaemonPicker?void 0:0,onClick:i.addNodeDaemonPicker?void 0:()=>b(Z?null:V.id),onKeyDown:i.addNodeDaemonPicker?void 0:O=>{(O.key==="Enter"||O.key===" ")&&(O.preventDefault(),b(Z?null:V.id))},children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.addNodeDaemonPicker?s.jsx("span",{className:"font-semibold text-sm text-text-primary truncate",children:V.machine_label||V.machine_nickname||V.hostname||V.workspace}):s.jsx("span",{className:"text-sm font-medium",children:V.workspace.split("/").pop()}),i.addNodeDaemonPicker&&s.jsx(uI,{status:z}),i.addNodeDaemonPicker&&s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:_("repoMesh.nodeList.setupInventory")})]}),i.addNodeDaemonPicker&&s.jsx("div",{className:"text-[11px] text-text-muted",children:_("repoMesh.nodeList.ownerMachine",{owner:II(a.find(O=>O.id===String(V.daemon_id||"")),o),machine:V.machine_label||V.daemon_id||V.workspace})}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:V.workspace}),s.jsx(NI,{node:V,saving:m===V.id,onSave:O=>h(V,O)}),i.addNodeDaemonPicker&&s.jsx("div",{className:"mt-2 text-[11px] text-amber-300",children:_("repoMesh.nodeList.liveDetailGraphOwned")}),s.jsxs("div",{className:"mt-3 max-w-2xl",onClick:O=>O.stopPropagation(),children:[s.jsx(At,{label:_("repoMesh.nodeList.slotsLabel"),hint:_("repoMesh.nodeList.slotsHint"),children:s.jsx(xI,{slots:Array.isArray((X=V.policy)==null?void 0:X.slots)?V.policy.slots:[],availableProviders:yI(V,q),saving:p===V.id,onSave:O=>d(V,O)})}),i.nodeInstruction&&s.jsxs(At,{label:_("repoMesh.nodeList.nodeInstruction"),hint:_("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:g[V.id]??"",onChange:O=>{const Q=O.target.value;k(V.id,Q)},onClick:O=>O.stopPropagation(),disabled:f===V.id,placeholder:_("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:O=>{O.stopPropagation(),x(V)},disabled:f===V.id,children:f===V.id?_("repoMesh.nodeList.saving"):_("repoMesh.nodeList.saveInstruction")})})]})]})]}),s.jsx("button",{className:`transition-colors bg-transparent border-none cursor-pointer ${i.addNodeDaemonPicker?"btn btn-sm text-text-muted hover:text-red-400":"text-text-muted hover:text-red-400"}`,onClick:O=>{O.stopPropagation(),$(V.id)},title:_("repoMesh.nodeList.removeNode"),children:s.jsx(cI,{size:14})})]}),s.jsxs("details",{className:"mt-3 group",onClick:O=>O.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:"▸"})," ",_("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:_("repoMesh.nodeList.nodeId")})," ",s.jsx("span",{className:"font-mono break-all",children:V.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:_("repoMesh.nodeList.launchReady")})," ",s.jsx("span",{className:ne.configured?"text-green-400":"text-amber-400",children:ne.configured?_("repoMesh.nodeList.launchReadyYes"):_("repoMesh.nodeList.launchReadyNo")})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:_("repoMesh.nodeList.repoRoot")})," ",s.jsx("span",{className:"font-mono break-all",children:V.repoRoot||V.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:_("repoMesh.nodeList.activeSessionsLabel")})," ",he.length]}),i.addNodeDaemonPicker&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:_("repoMesh.nodeList.added")})," ",new Date(V.created_at||V.createdAt||Date.now()).toLocaleDateString()]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:_("repoMesh.nodeList.activeQueueAssignments")}),ae.length===0?s.jsx("div",{children:_("repoMesh.nodeList.noActiveAssignment")}):s.jsx("ul",{className:"m-0 pl-4",children:ae.map(O=>s.jsx("li",{className:"font-mono",children:MI(O)},O.id))})]}),he.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:_("repoMesh.nodeList.activeSessions")}),s.jsx("ul",{className:"m-0 pl-4",children:he.map(O=>s.jsxs("li",{className:"font-mono",children:[O.provider," / ",O.status," / ",O.id]},O.id))})]})]})]})]},V.id)})})]})}const RI=["claude-cli","codex-cli","gemini-cli","hermes-cli","antigravity-cli"],EI=[{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 _I(){return{nodeId:"",provider:"",model:"",n:""}}function ku(e){var t;return(t=e.providers)!=null&&t.length?e.providers.filter(Boolean):(e.providerPriority??[]).filter(Boolean)}function HI(e){return{nodeId:e.nodeId??"",provider:e.provider??"",model:e.model??"",n:e.n!=null?String(e.n):""}}function $I(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 u;if(c){const p=Number(c);if(!Number.isFinite(p)||p<1)return{error:{code:"replica_min",slot:n+1}};u=Math.floor(p)}t.push({provider:r,...o?{nodeId:o}:{},...i?{model:i}:{},...u!==void 0?{n:u}:{}})}return t.length===0?{error:{code:"no_slot"}}:{slots:t}}function FI({status:e,daemonId:t,sendDaemonCommand:n,availableProviders:a}){const{t:r}=Ce(),{theme:o}=tn(),i=l.useMemo(()=>sn(o),[o]),c=l.useMemo(()=>Mm(a),[a]),[u,p]=l.useState({}),[d,m]=l.useState(!1),[h,g]=l.useState(null),[k,f]=l.useState({}),[x,w]=l.useState(null),b=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(B=>({nodeId:B.nodeId,machineLabel:B.machineLabel,providers:B.providers,providerPriority:B.providerPriority,isLocalWorktree:B.isLocalWorktree,worktreeBranch:B.worktreeBranch})),[e==null?void 0:e.nodes]),N=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(B=>B.nodeId),[e==null?void 0:e.nodes]),j=l.useMemo(()=>new Set(b.filter(tl).map(B=>B.nodeId)),[b]),v=l.useMemo(()=>Object.fromEntries(b.filter(tl).map(B=>[B.nodeId,B.worktreeBranch])),[b]),y=l.useMemo(()=>Object.fromEntries(((e==null?void 0:e.nodes)??[]).map(B=>[B.nodeId,B.machineLabel||B.nodeId])),[e==null?void 0:e.nodes]),C=l.useMemo(()=>{const B={};for(const W of b)B[W.nodeId]=ku(W);return B},[b]),S=l.useMemo(()=>{const B=[...new Set(b.flatMap(ku).filter(Boolean))];return[...new Set([...B,...RI])].sort()},[b]),A=!!t&&!!n,M=B=>B&&typeof B=="object"&&"result"in B?B.result:B,I=e==null?void 0:e.meshId,D=l.useCallback(async()=>{if(!(!t||!n)){m(!0),g(null);try{const B=await n(t,"magi_kind_panel_list",{...I?{meshId:I}:{}}),W=M(B);if((W==null?void 0:W.success)===!1)throw new Error(W.error||r("meshGraph.magiKind.errorLoad"));p(W!=null&&W.kindPanels&&typeof W.kindPanels=="object"?W.kindPanels:{}),f({})}catch(B){g((B==null?void 0:B.message)||r("meshGraph.magiKind.errorLoad"))}finally{m(!1)}}},[t,n,I,r]);l.useEffect(()=>{D()},[D]);const P=l.useCallback(B=>{if(k[B])return k[B];const W=u[B];return W?W.map(HI):[]},[k,u]),T=(B,W)=>{f(V=>({...V,[B]:W}))},H=(B,W,V)=>{const ne=P(B);T(B,ne.map((ae,he)=>he===W?{...ae,...V}:ae))},L=B=>{T(B,[...P(B),_I()])},R=(B,W)=>{T(B,P(B).filter((V,ne)=>ne!==W))},U=l.useCallback(async B=>{if(!t||!n)return;const W=$I(P(B));if("error"in W){const V=W.error,ne=V.code==="provider_required"?r("meshGraph.magiKind.errorSlotProvider",{slot:V.slot}):V.code==="replica_min"?r("meshGraph.magiKind.errorSlotReplica",{slot:V.slot}):r("meshGraph.magiKind.errorNoSlot");g(`${B}: ${ne}`);return}w(B),g(null);try{const V=await n(t,"magi_kind_panel_set",{kind:B,slots:W.slots,...I?{meshId:I}:{}}),ne=M(V);if((ne==null?void 0:ne.success)===!1)throw new Error(ne.error||r("meshGraph.magiKind.errorSave"));await D()}catch(V){g((V==null?void 0:V.message)||r("meshGraph.magiKind.errorSave"))}finally{w(null)}},[t,n,P,D,I,r]),E=l.useCallback(async B=>{if(!(!t||!n)&&confirm(r("meshGraph.magiKind.removeConfirm",{kind:B}))){w(B),g(null);try{const W=await n(t,"magi_kind_panel_remove",{kind:B,...I?{meshId:I}:{}}),V=M(W);if((V==null?void 0:V.success)===!1)throw new Error(V.error||r("meshGraph.magiKind.errorRemove"));await D()}catch(W){g((W==null?void 0:W.message)||r("meshGraph.magiKind.errorRemove"))}finally{w(null)}}},[t,n,D,I,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"}`,_="btn btn-primary btn-sm",q="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:q,onClick:()=>void D(),disabled:d||!A,children:r(d?"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")}),h&&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:h}),s.jsx("div",{className:"flex flex-col gap-3",children:EI.map(({kind:B,labelKey:W,hint:V})=>{const ne=P(B),ae=!!u[B],he=x===B;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(W)}),s.jsx("span",{className:`font-mono text-[10px] ${i.textMuted}`,children:V}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${ae?"border-emerald-400/30 bg-emerald-500/10 text-emerald-300":"border-slate-400/20 bg-slate-500/10 text-slate-300"}`,children:ae?r("meshGraph.magiKind.agentCount",{count:u[B].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((Z,z)=>{const X=Z.nodeId?C[Z.nodeId]??[]:[],O=Z.nodeId&&X.length?X:S;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:Z.nodeId,onChange:Q=>H(B,z,{nodeId:Q.target.value}),title:r("meshGraph.magiKind.machineTitle"),children:[s.jsx("option",{value:"",children:r("meshGraph.magiKind.anyMachine")}),N.map(Q=>{const ke=j.has(Q),Se=ke?r("meshGraph.magiKind.worktreeSuffix",{label:y[Q]??Q,branch:v[Q]||r("meshGraph.magiKind.worktreeUnknownBranch")}):y[Q]??Q;return s.jsx("option",{value:Q,disabled:ke,title:ke?r("meshGraph.magiKind.worktreeDisabledTitle"):void 0,children:Se},Q)}),Z.nodeId&&!N.includes(Z.nodeId)&&s.jsx("option",{value:Z.nodeId,children:r("meshGraph.magiKind.offlineSuffix",{label:y[Z.nodeId]??Z.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:Z.provider,onChange:Q=>H(B,z,{provider:Q.target.value}),title:r("meshGraph.magiKind.providerTitle"),children:[s.jsx("option",{value:"",children:r("meshGraph.magiKind.selectProvider")}),O.map(Q=>s.jsx("option",{value:Q,children:Q},Q)),Z.provider&&!O.includes(Z.provider)&&s.jsx("option",{value:Z.provider,children:Z.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 Se;const Q=(Z.provider?(Se=c.get(Z.provider))==null?void 0:Se.models:void 0)??[],ke=!!Z.model&&Q.length>0&&!Q.includes(Z.model);return Q.length>0&&!ke?s.jsxs("select",{className:$,value:Q.includes(Z.model)?Z.model:"",title:r("meshGraph.magiKind.modelTitle"),onChange:ve=>H(B,z,{model:ve.target.value==="__custom__"?" ":ve.target.value}),children:[s.jsx("option",{value:"",children:r("meshGraph.magiKind.modelDefault")}),Q.map(ve=>s.jsx("option",{value:ve,children:ve},ve)),s.jsx("option",{value:"__custom__",children:r("meshGraph.magiKind.modelCustom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:$,value:Z.model.trim(),placeholder:r("meshGraph.magiKind.modelDefault"),title:r("meshGraph.magiKind.modelTitle"),onChange:ve=>H(B,z,{model:ve.target.value})}),Q.length>0&&s.jsx("button",{type:"button",className:`self-start bg-transparent border-none cursor-pointer p-0 text-[10px] ${i.textSecondary} hover:underline`,onClick:()=>H(B,z,{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:Z.n,placeholder:"1",inputMode:"numeric",title:r("meshGraph.magiKind.copiesTitle"),onChange:Q=>H(B,z,{n:Q.target.value})})]}),s.jsx("button",{type:"button",className:`${q} sm:mt-[18px] inline-flex h-8 w-8 items-center justify-center p-0`,onClick:()=>R(B,z),"aria-label":r("meshGraph.magiKind.removeAgent"),title:r("meshGraph.magiKind.removeAgent"),children:"✕"})]},z)}),s.jsx("div",{children:s.jsx("button",{type:"button",className:q,onClick:()=>L(B),disabled:!A,children:r("meshGraph.magiKind.addAgent")})})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:_,onClick:()=>void U(B),disabled:he||!A,children:r(he?"meshGraph.magiKind.saving":"meshGraph.magiKind.save")}),s.jsx("button",{type:"button",className:q,onClick:()=>void E(B),disabled:he||!A||!ae,title:r(ae?"meshGraph.magiKind.removeBindingTitle":"meshGraph.magiKind.removeBindingDisabledTitle"),children:r("meshGraph.magiKind.removeBinding")})]})]},B)})})]})}const Dn={sessionMinRemainingPercent:10,weeklyMinRemainingPercent:15,sessionResetImminentMinutes:5,staleAfterMinutes:30,spreadBonusMax:30,sessionAxisWeeklyHeadroomPercent:40},sl=60*1e3;function Su(e){return e===void 0||!Number.isFinite(e)?"":String(e/sl)}function nl(e){const t=e??{};return{sessionMinRemainingPercent:t.sessionMinRemainingPercent!==void 0?String(t.sessionMinRemainingPercent):"",weeklyMinRemainingPercent:t.weeklyMinRemainingPercent!==void 0?String(t.weeklyMinRemainingPercent):"",sessionResetImminentMinutes:Su(t.sessionResetImminentMs),staleAfterMinutes:Su(t.staleAfterMs),spreadBonusMax:t.spreadBonusMax!==void 0?String(t.spreadBonusMax):"",sessionAxisWeeklyHeadroomPercent:t.sessionAxisWeeklyHeadroomPercent!==void 0?String(t.sessionAxisWeeklyHeadroomPercent):""}}function BI(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 al(e){const t={},n=p=>{const d=p.trim();if(!d)return;const m=Number(d);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*sl);const i=n(e.staleAfterMinutes);i!==void 0&&(t.staleAfterMs=i*sl);const c=n(e.spreadBonusMax);c!==void 0&&(t.spreadBonusMax=c);const u=n(e.sessionAxisWeeklyHeadroomPercent);return u!==void 0&&(t.sessionAxisWeeklyHeadroomPercent=u),t}const WI="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs",OI="w-full rounded-lg border border-red-500/60 bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function UI({quotaRouting:e,saving:t,error:n,onSave:a}){const{t:r}=Ce("common"),[o,i]=l.useState(()=>nl(e)),c=l.useCallback((k,f)=>{i(x=>({...x,[k]:f}))},[]),u=l.useMemo(()=>{const k={};for(const f of Object.keys(o)){const x=BI(f,o[f]);x&&(k[f]=x)}return k},[o]),p=Object.keys(u).length>0,d=l.useMemo(()=>JSON.stringify(al(o))!==JSON.stringify(qI(e)),[o,e]),m=l.useCallback(()=>{p||a(al(o))},[o,p,a]),h=l.useCallback(()=>{i(nl(null))},[]),g=[{key:"sessionMinRemainingPercent",label:r("setupWizard.quotaPolicy.sessionMin"),hint:r("setupWizard.quotaPolicy.sessionMinHint"),placeholder:Dn.sessionMinRemainingPercent,unit:"%"},{key:"weeklyMinRemainingPercent",label:r("setupWizard.quotaPolicy.weeklyMin"),hint:r("setupWizard.quotaPolicy.weeklyMinHint"),placeholder:Dn.weeklyMinRemainingPercent,unit:"%"},{key:"sessionResetImminentMinutes",label:r("setupWizard.quotaPolicy.resetImminent"),hint:r("setupWizard.quotaPolicy.resetImminentHint"),placeholder:Dn.sessionResetImminentMinutes,unit:r("setupWizard.quotaPolicy.minutes")},{key:"staleAfterMinutes",label:r("setupWizard.quotaPolicy.staleAfter"),hint:r("setupWizard.quotaPolicy.staleAfterHint"),placeholder:Dn.staleAfterMinutes,unit:r("setupWizard.quotaPolicy.minutes")},{key:"spreadBonusMax",label:r("setupWizard.quotaPolicy.spreadBonus"),hint:r("setupWizard.quotaPolicy.spreadBonusHint"),placeholder:Dn.spreadBonusMax,unit:""},{key:"sessionAxisWeeklyHeadroomPercent",label:r("setupWizard.quotaPolicy.sessionAxisWeeklyHeadroom"),hint:r("setupWizard.quotaPolicy.sessionAxisWeeklyHeadroomHint"),placeholder:Dn.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 f=u[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:f?OI:WI,value:o[k.key],placeholder:String(k.placeholder),onChange:x=>c(k.key,x.target.value)}),s.jsx("span",{className:`text-[10px] leading-snug ${f?"text-red-400":"text-text-muted"}`,children:f?r(`setupWizard.quotaPolicy.errors.${f}`):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:h,children:r("setupWizard.quotaPolicy.useDefaults")}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm ml-auto",onClick:m,disabled:!!t||p||!d,children:r(t?"setupWizard.quotaPolicy.saving":"setupWizard.quotaPolicy.save")})]})]})}function qI(e){return al(nl(e))}function GI({daemonId:e,meshId:t,cliType:n,sendCommand:a}){const{t:r}=Ce(),[o,i]=l.useState(!1),[c,u]=l.useState(!1),[p,d]=l.useState(null),[m,h]=l.useState(null),[g,k]=l.useState(null),f=l.useCallback(async()=>{if(!e||!t){d(r("repoMesh.promptPreview.connectPrompt"));return}u(!0),d(null);try{const w=await a(e,"coordinator_prompt_preview",{meshId:t,cliType:n}),b=w!=null&&w.result&&typeof w.result=="object"?w.result:w;if(!(b!=null&&b.success)){d((b==null?void 0:b.error)||r("repoMesh.promptPreview.errorRender"));return}h(typeof b.prompt=="string"?b.prompt:""),k(typeof b.bytes=="number"?b.bytes:null)}catch(w){d((w==null?void 0:w.message)||String(w))}finally{u(!1)}},[e,t,n,a,r]),x=l.useCallback(()=>{const w=!o;i(w),w&&m===null&&!c&&f()},[o,m,c,f]);return s.jsxs("div",{className:"mt-2",children:[s.jsxs("button",{type:"button",onClick:x,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 ${o?"rotate-90":""}`,"aria-hidden":!0,children:"▸"}),r(o?"repoMesh.promptPreview.hide":"repoMesh.promptPreview.view"),s.jsxs("span",{className:"text-text-muted",children:["(",n,")"]})]}),o&&s.jsxs("div",{className:"mt-2",children:[c&&s.jsx("div",{className:"text-[12px] text-text-muted",children:r("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:r("repoMesh.promptPreview.retry")})]}),!c&&!p&&m!==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:r("repoMesh.promptPreview.info")}),g!==null&&s.jsxs("span",{children:[(g/1024).toFixed(1)," KB"]})]}),s.jsx("textarea",{readOnly:!0,value:m,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:w=>w.currentTarget.select()})]})]})]})}const zI=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function KI(e){const t=zI(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function VI(e){const t=e==null?void 0:e.missions;return Array.isArray(t)?t:[]}function YI(e){return typeof e.goal=="string"&&e.goal?{text:e.goal,truncated:!1}:{text:e.goalPreview??"",truncated:e.goalTruncated===!0}}const QI=["active","paused","completed","abandoned"];function Cu(e){return(e.status||"active").toLowerCase()}const JI=8;function XI({status:e,daemonId:t,meshId:n,sendCommand:a}){const{t:r}=Ce("common"),o=l.useMemo(()=>VI(e),[e]),[i,c]=l.useState({}),[u,p]=l.useState({}),[d,m]=l.useState(!1),[h,g]=l.useState(null),[k,f]=l.useState("active"),[x,w]=l.useState(!1),b=l.useMemo(()=>{const A={};for(const M of o){const I=Cu(M);A[I]=(A[I]||0)+1}return A},[o]),N=l.useMemo(()=>k==="all"?o:o.filter(A=>Cu(A)===k),[o,k]),j=x?N:N.slice(0,JI),v=N.length-j.length,y=!!t&&o.length>0,C=l.useCallback(async()=>{if(t){m(!0),g(null);try{const A=await a(t,"mesh_status",{meshId:n,verbose:!0}),M=KI(A),I=Array.isArray(M==null?void 0:M.missions)?M.missions:[],D={};for(const P of I)P.id&&typeof P.goal=="string"&&P.goal&&(D[P.id]=P.goal);c(P=>({...P,...D}))}catch(A){g(A instanceof Error?A.message:r("repoMesh.missions.errorFetch"))}finally{m(!1)}}},[t,n,a,r]),S=l.useCallback(A=>{p(M=>({...M,[A]:!M[A]})),!u[A]&&!i[A]&&C()},[u,i,C]);return o.length===0?null:s.jsxs(ht,{title:r("repoMesh.missions.title"),description:r("repoMesh.missions.description"),children:[h&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400",children:h}),s.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-1.5",children:[QI.filter(A=>(b[A]||0)>0).map(A=>s.jsxs("button",{type:"button",onClick:()=>{f(A),w(!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:()=>{f("all"),w(!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]})]}),N.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:j.map(A=>{var L;const M=u[A.id]===!0,I=i[A.id],D=YI(A),P=M&&I?I:D.text,T=M&&!I&&D.truncated,H=((L=A.tasks)==null?void 0:L.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}),H>0&&s.jsx("span",{className:"shrink-0 text-[11px] text-text-muted",children:r("repoMesh.missions.taskCount",{count:H})})]}),P&&s.jsxs("div",{className:`mt-1.5 whitespace-pre-wrap text-[12px] leading-5 text-text-secondary ${M?"max-h-72 overflow-y-auto":"line-clamp-2"}`,children:[P,T&&s.jsx("span",{className:"text-text-muted",children:r("repoMesh.missions.goalUnavailable")})]}),(D.truncated||I)&&y&&s.jsx("button",{type:"button",className:"mt-1.5 text-[12px] text-accent-primary hover:underline disabled:opacity-50",onClick:()=>S(A.id),disabled:d,children:r(M?"repoMesh.missions.showLess":d&&!I?"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:()=>w(!0),children:r("repoMesh.missions.showMore",{count:v})})]})}function ju(e,t){if(t)return e.modes.find(n=>n.id===t)}function ZI(e){return e.modes.find(t=>t.strategy==="pty-parse-default"&&$s(t)!=="dangerous")}function eL({config:e,requestedModeId:t,machineAutoApproveEnabled:n,machineDangerousAllowed:a}){const r=ju(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=ju(e,i),u=!!i&&!c,p=c??r;if(!p||p.strategy==="post-boot-command")return{status:"none",requestedModeId:i,providerDefaultModeId:o,requestedModeUnknown:u,downgraded:!1};if($s(p)==="dangerous"&&!a){const d=ZI(e);return{status:d?"downgraded":"none",requestedModeId:i,providerDefaultModeId:o,effectiveMode:d,requestedModeUnknown:u,downgraded:!0}}return{status:u?"invalid_fallback":"requested",requestedModeId:i,providerDefaultModeId:o,effectiveMode:p,requestedModeUnknown:u,downgraded:!1}}function tL(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 sL({hostDaemonId:e,hostOnline:t,hostWorkspace:n,meshProviders:a,unreportedNodeCount:r=0,machineAutoApproveEnabled:o,machineDangerousAllowed:i,onUpdatePolicy:c,savingPolicy:u,sendCommand:p}){const{t:d}=Ce("common"),m=l.useMemo(()=>tL(a),[a]),[h,g]=l.useState({}),[k,f]=l.useState(!1),[x,w]=l.useState(null),[b,N]=l.useState(!1),[j,v]=l.useState(null),[y,C]=l.useState(!1),[S,A]=l.useState(null),[M,I]=l.useState(!1),D=!!e&&t&&!!n,P=!!c&&!u,T=l.useCallback(async()=>{var E,$,_;if(D){f(!0),w(null);try{const q=await p(e,"read_mesh_json_config",{workspace:n}),B=(q==null?void 0:q.result)??q,W=((E=B==null?void 0:B.providerDefaults)==null?void 0:E.autoApproveModes)||((_=($=B==null?void 0:B.config)==null?void 0:$.providerDefaults)==null?void 0:_.autoApproveModes),V={};if(W&&typeof W=="object")for(const[ne,ae]of Object.entries(W))typeof ae=="string"&&ae.trim()&&(V[ne]=ae.trim());g(V)}catch(q){w((q==null?void 0:q.message)||d("repoMesh.providerAutoApprove.loadError"))}finally{f(!1)}}},[D,e,n,p,d]);l.useEffect(()=>{T()},[T]);const H=l.useCallback((E,$)=>{C(!1),g(_=>{const q={..._};return $&&$.trim()?q[E]=$.trim():delete q[E],q})},[]),L=l.useCallback((E,$)=>{if($s($)==="dangerous"){A({type:E,mode:$});return}H(E,$.id)},[H]),R=l.useCallback(()=>{S&&H(S.type,S.mode.id),A(null)},[H,S]),U=l.useCallback(async()=>{if(D){N(!0),v(null),C(!1);try{const E=await p(e,"set_mesh_provider_defaults",{workspace:n,autoApproveModes:h,merge:!1,write:!0}),$=(E==null?void 0:E.result)??E;if(($==null?void 0:$.success)===!1)throw new Error(($==null?void 0:$.error)||d("repoMesh.providerAutoApprove.saveError"));C(!0),await T()}catch(E){v((E==null?void 0:E.message)||d("repoMesh.providerAutoApprove.saveError"))}finally{N(!1)}}},[D,e,n,T,h,p,d]);return s.jsxs(ht,{title:d("repoMesh.providerAutoApprove.title"),description:d("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:d("repoMesh.providerAutoApprove.machineSection.title")}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:d("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-bg-tertiary/40 text-text-muted"}`,children:d(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-bg-tertiary/40 text-text-muted"}`,children:d(i?"repoMesh.providerAutoApprove.machineSection.dangerousOn":"repoMesh.providerAutoApprove.machineSection.dangerousOff")})]}),s.jsxs("div",{className:"mt-3 space-y-2",children:[s.jsx(Nu,{label:d("repoMesh.providerAutoApprove.machineSection.autoApproveToggleLabel"),hint:d("repoMesh.providerAutoApprove.machineSection.autoApproveToggleHint"),checked:o,disabled:!P,onChange:E=>c==null?void 0:c({delegatedWorkerAutoApprove:E})}),s.jsx(Nu,{label:d("repoMesh.providerAutoApprove.machineSection.dangerousToggleLabel"),hint:d(o?"repoMesh.providerAutoApprove.machineSection.dangerousToggleHint":"repoMesh.providerAutoApprove.machineSection.dangerousDisabledHint"),checked:i,disabled:!P||!o,onChange:E=>{E?I(!0):c==null||c({delegatedWorkerDangerousModeAllow:!1})}})]})]}),D?k?s.jsx("div",{className:"text-[13px] text-text-muted",children:d("repoMesh.providerAutoApprove.loading")}):m.length===0?s.jsx("div",{className:"text-[13px] text-text-muted",children:r>0?d("repoMesh.providerAutoApprove.awaitingNodes",{count:r}):d("repoMesh.providerAutoApprove.noProviders")}):s.jsxs("div",{className:"space-y-6",children:[x&&s.jsx(Dt,{variant:"error",onDismiss:()=>w(null),children:x}),r>0&&s.jsx("div",{className:"text-[11px] text-text-muted",children:d("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:d("repoMesh.providerAutoApprove.repoSection.title")}),s.jsx("div",{className:"text-[11px] text-text-muted",children:d("repoMesh.providerAutoApprove.repoSection.hint")})]}),s.jsx("div",{className:"space-y-5",children:m.map(E=>{const $=h[E.type],_=eL({config:E.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:E.label}),s.jsx("button",{type:"button",className:"text-[11px] text-text-muted underline decoration-dotted hover:text-text-primary disabled:opacity-40",onClick:()=>H(E.type,void 0),disabled:!$||b,children:d("repoMesh.providerAutoApprove.repoSection.clear")})]}),s.jsx(Ch,{config:E.autoApproveModes,selectedModeId:$||"",disabled:b,onSelectMode:q=>L(E.type,q)}),!$&&s.jsx("div",{className:"mt-1.5 text-[11px] text-text-muted",children:d("repoMesh.providerAutoApprove.repoSection.usesProviderDefault")}),s.jsx(nL,{effective:_,config:E.autoApproveModes})]},E.type)})}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:d("repoMesh.providerAutoApprove.effectiveSection.title")}),s.jsx("div",{className:"text-[11px] text-text-muted",children:d("repoMesh.providerAutoApprove.effectiveSection.hint")})]}),j&&s.jsx(Dt,{variant:"error",onDismiss:()=>v(null),children:j}),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 U(),disabled:b,children:d(b?"repoMesh.providerAutoApprove.saving":"repoMesh.providerAutoApprove.save")}),y&&s.jsx("span",{className:"text-[12px] text-status-online",children:d("repoMesh.providerAutoApprove.saved")})]})]}):s.jsx("div",{className:"text-[13px] text-text-muted",children:d("repoMesh.providerAutoApprove.noHostDaemon")}),M&&s.jsx(mo,{title:d("repoMesh.providerAutoApprove.machineSection.confirmTitle"),description:d("repoMesh.providerAutoApprove.machineSection.confirmDescription"),details:[{label:d("repoMesh.providerAutoApprove.machineSection.confirmScopeLabel"),value:d("repoMesh.providerAutoApprove.machineSection.confirmScopeValue")},{label:d("repoMesh.providerAutoApprove.machineSection.confirmEffectLabel"),value:d("repoMesh.providerAutoApprove.machineSection.confirmEffectValue")}],confirmLabel:d("repoMesh.providerAutoApprove.machineSection.confirmConfirm"),onConfirm:()=>{I(!1),c==null||c({delegatedWorkerDangerousModeAllow:!0})},onCancel:()=>I(!1)}),S&&s.jsx(jh,{mode:S.mode,onConfirm:R,onCancel:()=>A(null)}),S&&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:d("repoMesh.providerAutoApprove.dangerous.sharedWarningTitle")}),s.jsx("div",{className:"mt-1 text-[12px] text-text-muted",children:d("repoMesh.providerAutoApprove.dangerous.sharedWarning")})]})})]})}function nL({effective:e,config:t}){var c,u,p;const{t:n}=Ce("common"),a=d=>{var m;return(d?(m=t.modes.find(h=>h.id===d))==null?void 0:m.label:void 0)||d||""};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:((u=e.effectiveMode)==null?void 0:u.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-bg-tertiary/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(Sh,{risk:$s(e.effectiveMode)}),s.jsx("span",{className:"min-w-0",children:r})]})}function Nu({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-bg-tertiary"}`,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 hr(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function aL({daemons:e,coordinatorDaemonId:t,onCoordinatorDaemonIdChange:n,coordinatorCliType:a,onCoordinatorCliTypeChange:r,launchingCoordinator:o,launchResult:i,isHostNodeAttached:c,selectedHostNode:u,hostPinned:p,hostLabel:d,hostOnline:m,hostRebindDaemonId:h,onHostRebindDaemonIdChange:g,onLaunchCoordinator:k,settingMeshHost:f,onSetMeshHost:x}){const{t:w}=Ce("common"),b=s.jsx(At,{label:w("repoMesh.host.coordinatorProvider"),hint:w("repoMesh.host.coordinatorProviderHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:a,onChange:y=>r(y.target.value),children:[s.jsx("option",{value:"",children:w("repoMesh.host.useNodePriority")}),s.jsx("option",{value:"claude-cli",children:"Claude Code"}),s.jsx("option",{value:"codex-cli",children:"Codex"}),s.jsx("option",{value:"gemini-cli",children:"Gemini"}),s.jsx("option",{value:"hermes-cli",children:"Hermes"})]})}),N=i&&s.jsx("div",{className:"mt-3 text-[12px] text-green-400 bg-green-500/10 border border-green-500/20 rounded-lg px-3 py-2",children:i});if(p)return s.jsxs(ht,{title:w("repoMesh.host.title"),description:w("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 ${m?"border-accent-primary/40 bg-accent-primary/10":"border-amber-500/40 bg-amber-500/10"}`,children:[s.jsx("span",{className:"text-text-muted",children:w("repoMesh.host.hostLabel")}),s.jsx("span",{className:"font-medium",children:d||w("repoMesh.host.unknown")}),s.jsxs("span",{className:m?"text-text-muted":"text-amber-400",children:["· ",w(m?"repoMesh.host.online":"repoMesh.host.offline")]})]}),(u==null?void 0:u.workspace)&&s.jsxs("span",{className:"text-[12px] text-text-muted",children:[w("repoMesh.host.hostNode")," ",s.jsx("span",{className:"font-mono text-text-secondary",children:u.workspace})]})]}),!m&&s.jsxs("div",{className:"mt-4",children:[s.jsxs(Dt,{variant:"warning",className:"mb-3",children:[s.jsx("strong",{children:w("repoMesh.host.hostOffline")})," ",w("repoMesh.host.hostOfflineText")]}),e.length>0?s.jsx(At,{label:w("repoMesh.host.reconnectToCommand"),hint:w("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:h,onChange:y=>g(y.target.value),children:[s.jsx("option",{value:"",children:w("repoMesh.host.waitForHost")}),e.map(y=>s.jsx("option",{value:y.id,children:hr(y)},y.id))]})}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:w("repoMesh.host.noDaemonsToRoute")})]}),s.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-[180px_auto] items-end",children:[b,s.jsx("button",{className:"btn btn-primary btn-sm",onClick:k,disabled:o||!t,title:t?void 0:w("repoMesh.host.noCommandTarget"),children:w(o?"repoMesh.host.launching":"repoMesh.host.launchHost")})]}),N]});const j=e.find(y=>y.id===t),v=x&&t?s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>x(t),disabled:!!f,children:w(f?"repoMesh.host.settingHost":"repoMesh.host.setHostAction")}):null;return s.jsxs(ht,{title:w("repoMesh.host.title"),description:w("repoMesh.host.descriptionUnset"),children:[s.jsxs(Dt,{variant:"info",className:"mb-4",children:[s.jsx("strong",{children:w("repoMesh.host.setHostBanner")})," ",w("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:c?s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:hr(j)}),u!=null&&u.workspace?s.jsxs(s.Fragment,{children:[" · setup node ",s.jsx("span",{className:"font-mono text-text-secondary",children:u.workspace})]}):null,". ",w("repoMesh.host.confirmSetsHost")]}):s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:hr(j)}),". ",w("repoMesh.host.attachNodeThenSetHost")]})}):s.jsx(At,{label:w("repoMesh.host.hostDaemon"),hint:w("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:y=>n(y.target.value),children:[s.jsx("option",{value:"",children:w("repoMesh.host.resolvingHost")}),e.map(y=>s.jsx("option",{value:y.id,children:hr(y)},y.id))]})}),v&&s.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[v,s.jsx("span",{className:"text-[12px] text-text-muted",children:w("repoMesh.host.setHostActionHint")})]}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-[180px_auto] items-end mt-3",children:[b,s.jsx("button",{className:`btn btn-sm ${v?"btn-secondary":"btn-primary"}`,onClick:k,disabled:!t||!c||o,title:t?c?void 0:w("repoMesh.host.attachNodeFirst"):w("repoMesh.host.pickHostFirst"),children:w(o?"repoMesh.host.launching":"repoMesh.host.launchHostSetsHost")})]})]}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:w("repoMesh.host.noDaemonsToHost")}),N]})}function rL({meshId:e,availableCliAgents:t}){const{t:n}=Ce(),a=t.find(o=>{const i=o.id.toLowerCase();return i==="hermes-cli"||i.includes("hermes")||o.name.toLowerCase().includes("hermes")}),r=Xm(a==null?void 0:a.meshCoordinator,{meshId:e});return r?s.jsx(ht,{title:n("repoMesh.hermesMcp.title"),description:n("repoMesh.hermesMcp.description"),children:s.jsx(kh,{setup:r,providerName:(a==null?void 0:a.name)||n("repoMesh.hermesMcp.fallbackProvider")})}):null}const xi=[{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."}],oL=[{value:"smart",labelKey:"repoMesh.detail.distributionSmart",descriptionKey:"repoMesh.detail.distributionSmartDescription"},{value:"in_order",labelKey:"repoMesh.detail.distributionInOrder",descriptionKey:"repoMesh.detail.distributionInOrderDescription"}];function iL(e){return e==="smart"?"fitness":"first_eligible"}function lL(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 cL={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,schedulingStrategy:"first_eligible",sessionCleanupOnNodeRemove:"preserve"};function rl(e){return{...cL,...(e==null?void 0:e.policy)||{}}}function dL(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 uL({selectedMesh:e,error:t,onDismissError:n,onBack:a,onDelete:r,displayedMeshStatus:o,graphLoading:i,graphError:c,onRefreshGraph:u,savingPolicy:p,onUpdatePolicy:d,coordinatorPromptDraft:m,onCoordinatorPromptDraftChange:h,savingCoordinatorPrompt:g,onSaveCoordinatorPrompt:k,daemons:f,coordinatorDaemonId:x,onCoordinatorDaemonIdChange:w,coordinatorCliType:b,onCoordinatorCliTypeChange:N,launchingCoordinator:j,launchResult:v,isHostNodeAttached:y,selectedHostNode:C,hostPinned:S,hostLabel:A,hostOnline:M,hostRebindDaemonId:I,onHostRebindDaemonIdChange:D,onLaunchCoordinator:P,settingMeshHost:T,onSetMeshHost:H,activeDaemon:L,activeDaemonId:R,meshQueue:U,userName:E,availableCliProviders:$,savingNodeSlotsId:_,onUpdateNodeSlots:q,savingNodeCapabilitiesId:B,onUpdateNodeCapabilities:W,nodeSystemPromptDrafts:V,onNodeSystemPromptDraftChange:ne,savingNodeSystemPromptId:ae,onSaveNodeSystemPrompt:he,selectedNodeId:Z,onSelectNode:z,showAddNode:X,onShowAddNode:O,onCancelAddNode:Q,nodeWorkspace:ke,onNodeWorkspaceChange:Se,nodeProviderPriority:ve,onNodeProviderPriorityChange:xe,nodeDaemonId:Y,onNodeDaemonIdChange:G,nodeCustomPath:te,onNodeCustomPathChange:me,nodePickerWorkspaces:K,nodePickerProviders:be,nodeOnboardingPlan:re,nodePlanLoading:de,attachableDaemons:we,onAddNode:Re,onRemoveNode:F,availableCliAgents:J,features:ge,sendCommand:ue}){const{t:ee}=Ce("common"),De=rl(e),Le=e.nodes||[],Xe=l.useMemo(()=>wI(Le,f),[Le,f]),ce=Le.some(it=>{var se;const yt=Number((se=it.policy)==null?void 0:se.schedulingPriority);return Number.isFinite(yt)&&yt!==0}),Ee=!De.schedulingStrategy,Fe=l.useMemo(()=>Le.some(it=>{var yt;return Array.isArray((yt=it.policy)==null?void 0:yt.slots)&&it.policy.slots.length>0}),[Le]),et=Ee&&(Fe||Le.length>=2)?"smart":null,[Ae,Je]=l.useState(!1),bt=!!R&&!!e.id;return s.jsxs(Oa,{icon:s.jsx(ns,{}),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:ee("repoMesh.detail.back")}),s.jsxs("button",{className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:()=>u(!0),disabled:i,children:[s.jsx(iI,{size:13}),ee(i?"repoMesh.detail.probing":"repoMesh.detail.refresh")]}),s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>r(e.id),children:ee("repoMesh.detail.delete")})]}),children:[t&&s.jsx(Dt,{variant:"error",onDismiss:n,className:"mb-4",children:t}),(()=>{var ye;const it=s.jsxs(s.Fragment,{children:[ge.meshHostDaemonSection&&s.jsx(aL,{daemons:f,coordinatorDaemonId:x,onCoordinatorDaemonIdChange:w,coordinatorCliType:b,onCoordinatorCliTypeChange:N,launchingCoordinator:j,launchResult:v,isHostNodeAttached:y,selectedHostNode:C,hostPinned:S,hostLabel:A,hostOnline:M,hostRebindDaemonId:I,onHostRebindDaemonIdChange:le=>{D(le),u()},onLaunchCoordinator:P,settingMeshHost:T,onSetMeshHost:H}),s.jsxs(ht,{title:ee("repoMesh.detail.observabilityTitle"),description:ee("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:()=>Je(!0),disabled:!bt,title:ee(bt?"repoMesh.detail.observabilityOpenTitle":"repoMesh.detail.observabilityDisabledTitle"),children:[s.jsx(ns,{size:14}),ee("repoMesh.detail.observabilityOpen")]}),s.jsx("span",{className:"text-[12px] text-text-muted",children:ee("repoMesh.detail.observabilityHint")})]})]}),s.jsx(LI,{nodes:Le,meshQueue:U,activeDaemon:L,daemons:f,selectedMeshId:e.id,userName:E,features:{addNodeDaemonPicker:ge.addNodeDaemonPicker,nodeInstruction:ge.nodeInstruction},coordinatorDaemonId:x,availableCliProviders:$,savingNodeSlotsId:_,onUpdateNodeSlots:q,savingNodeCapabilitiesId:B,onUpdateNodeCapabilities:W,nodeSystemPromptDrafts:V,onNodeSystemPromptDraftChange:ne,savingNodeSystemPromptId:ae,onSaveNodeSystemPrompt:he,selectedNodeId:Z,onSelectNode:z,showAddNode:X,onShowAddNode:O,onCancelAddNode:Q,nodeWorkspace:ke,onNodeWorkspaceChange:Se,nodeProviderPriority:ve,onNodeProviderPriorityChange:xe,nodeDaemonId:Y,onNodeDaemonIdChange:G,nodeCustomPath:te,onNodeCustomPathChange:me,nodePickerWorkspaces:K,nodePickerProviders:be,nodeOnboardingPlan:re,nodePlanLoading:de,attachableDaemons:we,onAddNode:Re,onRemoveNode:F})]}),yt=s.jsxs(s.Fragment,{children:[s.jsxs(ht,{title:ee("repoMesh.detail.schedulingTitle"),description:ee("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:ee("repoMesh.detail.distribution")}),s.jsx("div",{className:"flex flex-col gap-2",children:oL.map(le=>{const _e=lL(De.schedulingStrategy,{priorityConfigured:ce})===le.value;return s.jsxs("label",{className:`flex items-start gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${_e?"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:le.value,checked:_e,disabled:p,onChange:()=>d({schedulingStrategy:iL(le.value)})}),s.jsxs("span",{className:"min-w-0",children:[s.jsxs("span",{className:"flex items-center gap-2 text-sm text-text-primary",children:[ee(le.labelKey),et===le.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:ee("repoMesh.detail.recommended")})]}),s.jsx("span",{className:"block text-[12px] text-text-muted",children:ee(le.descriptionKey)})]})]},le.value)})})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:ee("repoMesh.detail.saving")})]}),s.jsx(ht,{title:ee("repoMesh.detail.visibilityTitle"),description:ee("repoMesh.detail.visibilityDescription"),children:s.jsx(At,{label:ee("repoMesh.detail.visibilityLabel"),hint:ee("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:De.spawnedSessionVisibility==="visible"?"visible":"hidden",onChange:le=>d({spawnedSessionVisibility:le.target.value==="visible"?"visible":"hidden"}),disabled:p,children:[s.jsx("option",{value:"hidden",children:ee("repoMesh.detail.visibilityHidden")}),s.jsx("option",{value:"visible",children:ee("repoMesh.detail.visibilityVisible")})]})})}),o&&s.jsx(ht,{title:ee("repoMesh.detail.magiTitle"),description:ee("repoMesh.detail.magiDescription"),children:s.jsx(FI,{status:o,daemonId:R,sendDaemonCommand:ue,availableProviders:$})}),s.jsx(ht,{children:s.jsx(UI,{quotaRouting:De.quotaRouting??null,saving:p,error:t,onSave:le=>d({quotaRouting:le})})}),s.jsx(sL,{hostDaemonId:x,hostOnline:M,hostWorkspace:(C==null?void 0:C.workspace)||"",meshProviders:Xe.providers,unreportedNodeCount:Xe.unreportedNodeCount,machineAutoApproveEnabled:De.delegatedWorkerAutoApprove!==!1,machineDangerousAllowed:De.delegatedWorkerDangerousModeAllow===!0,onUpdatePolicy:d,savingPolicy:p,sendCommand:ue})]}),se=s.jsx(s.Fragment,{children:ge.coordinatorPrompt&&s.jsxs(ht,{title:ee("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:ee("repoMesh.detail.advanced")}),description:ee("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:ee("repoMesh.detail.thisMesh")}),s.jsx("p",{className:"text-[12px] text-text-muted mb-3",children:ee("repoMesh.detail.thisMeshHint",{name:e.name})}),s.jsxs(At,{label:ee("repoMesh.detail.overrideLabel"),hint:ee("repoMesh.detail.overrideHint"),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:le=>h({...m,override:le.target.value}),disabled:g,placeholder:ee("repoMesh.detail.overridePlaceholder")}),s.jsx(GI,{daemonId:R,meshId:e.id,cliType:b,sendCommand:ue})]}),s.jsx(At,{label:ee("repoMesh.detail.appendLabel"),hint:ee("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:le=>h({...m,append:le.target.value}),disabled:g,placeholder:ee("repoMesh.detail.appendPlaceholder")})}),s.jsxs("details",{className:"mt-2 text-[12px] text-text-muted",children:[s.jsx("summary",{className:"cursor-pointer select-none",children:ee("repoMesh.detail.availablePlaceholders")}),s.jsx("p",{className:"mt-1 font-mono break-words",children:"{{meshName}}, {{repo}}, {{defaultBranch}}, {{cliType}}, {{nodes}}, {{policy}}, {{tools}}, {{workflow}}, {{rules}}, {{toolExposurePreflight}}"})]}),s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:k,disabled:g,children:ee(g?"repoMesh.detail.saving":"repoMesh.detail.saveCoordinatorPrompt")}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>h({override:"",append:""}),disabled:g,title:ee("repoMesh.detail.clearTitle"),children:ee("repoMesh.detail.clear")})]})]}),s.jsxs("div",{className:"mt-5 border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-1",children:ee("repoMesh.detail.userLevel")}),s.jsx("p",{className:"text-[12px] text-text-muted mb-3",children:ee("repoMesh.detail.userLevelDescription")}),s.jsx(jj,{daemonId:R||void 0})]})]})}),oe=s.jsxs(s.Fragment,{children:[s.jsx(XI,{status:o,daemonId:R,meshId:e.id,sendCommand:ue}),s.jsxs(ht,{title:ee("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:ee("repoMesh.detail.advanced")}),description:ee("repoMesh.detail.safetyDescription"),children:[s.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:[{label:ee("repoMesh.detail.checkpointBefore"),key:"requirePreTaskCheckpoint",opts:[["no","No"],["yes","Yes"]],val:le=>le?"yes":"no",parse:le=>le==="yes"},{label:ee("repoMesh.detail.checkpointAfter"),key:"requirePostTaskCheckpoint",opts:[["yes","Yes"],["no","No"]],val:le=>le?"yes":"no",parse:le=>le==="yes"},{label:ee("repoMesh.detail.pushApproval"),key:"requireApprovalForPush",opts:[["required",ee("repoMesh.detail.requireApprovalBeforePush")],["not_required",ee("repoMesh.detail.doNotRequireApproval")]],val:le=>le?"required":"not_required",parse:le=>le==="required"},{label:ee("repoMesh.detail.destructiveGitApproval"),key:"requireApprovalForDestructiveGit",opts:[["required",ee("repoMesh.detail.requireApproval")],["not_required",ee("repoMesh.detail.doNotRequireApproval")]],val:le=>le?"required":"not_required",parse:le=>le==="required"},{label:ee("repoMesh.detail.uncommittedChanges"),key:"dirtyWorkspaceBehavior",opts:[["warn",ee("repoMesh.detail.warnAndContinue")],["block",ee("repoMesh.detail.blockTask")],["checkpoint_then_continue",ee("repoMesh.detail.checkpointThenContinue")]],val:le=>le||"warn",parse:le=>le},{label:ee("repoMesh.detail.autoPublishSubmodule"),key:"allowAutoPublishSubmoduleMainCommits",opts:[["disabled",ee("repoMesh.detail.requireExplicitApproval")],["enabled",ee("repoMesh.detail.allowRefineryPublish")]],val:le=>le?"enabled":"disabled",parse:le=>le==="enabled"}].map(({label:le,key:Me,opts:_e,val:Te,parse:Ue})=>s.jsx(At,{label:le,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:Te(De[Me]),onChange:Ge=>d({[Me]:Ue(Ge.target.value)}),disabled:p,children:_e.map(([Ge,Ye])=>s.jsx("option",{value:Ge,children:Ye},Ge))})},Me))}),(()=>{const le=De.autoFastForward&&typeof De.autoFastForward=="object"?De.autoFastForward:{},Me=le.enabled!==!1,_e=le.remoteNodes===!0,Te=le.mode==="continuous"?"continuous":"idle",Ue=Ge=>d({autoFastForward:{...le,...Ge}});return s.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[s.jsx(At,{label:ee("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:Me?"enabled":"disabled",onChange:Ge=>Ue({enabled:Ge.target.value==="enabled"}),disabled:p,children:[s.jsx("option",{value:"enabled",children:ee("repoMesh.detail.ffEnabled")}),s.jsx("option",{value:"disabled",children:ee("repoMesh.detail.ffDisabled")})]})}),s.jsx(At,{label:ee("repoMesh.detail.includeRemoteNodes"),hint:ee("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:_e?"yes":"no",onChange:Ge=>Ue({remoteNodes:Ge.target.value==="yes"}),disabled:p||!Me,children:[s.jsx("option",{value:"no",children:ee("repoMesh.detail.remoteNo")}),s.jsx("option",{value:"yes",children:ee("repoMesh.detail.remoteYes")})]})}),s.jsx(At,{label:ee("repoMesh.detail.detectionMode"),hint:ee("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:Te,onChange:Ge=>Ue({mode:Ge.target.value==="continuous"?"continuous":"idle"}),disabled:p||!Me||!_e,children:[s.jsx("option",{value:"idle",children:ee("repoMesh.detail.idleEdgeOnly")}),s.jsx("option",{value:"continuous",children:ee("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(At,{label:ee("repoMesh.detail.sessionCleanupLabel"),hint:ee("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:De.sessionCleanupOnNodeRemove||"preserve",onChange:le=>d({sessionCleanupOnNodeRemove:le.target.value}),disabled:p,children:xi.map(le=>s.jsx("option",{value:le.value,children:le.label},le.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((ye=xi.find(le=>le.value===De.sessionCleanupOnNodeRemove))==null?void 0:ye.description)||xi[0].description})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:ee("repoMesh.detail.saving")})]})]}),pe=[{key:"nodes",label:ee("repoMesh.detail.tabNodes"),content:it},{key:"scheduling",label:ee("repoMesh.detail.tabScheduling"),content:yt},{key:"prompts",label:ee("repoMesh.detail.tabPrompts"),content:s.jsxs(s.Fragment,{children:[se,ge.hermesMcpConfig&&s.jsx(rL,{meshId:e.id,availableCliAgents:J}),ge.meshHostDaemonSection&&s.jsxs(Dt,{variant:"info",className:"mt-4",children:[s.jsx("strong",{children:ee("repoMesh.detail.mcpMode")})," ",s.jsxs("code",{className:"bg-bg-secondary px-1 rounded text-xs",children:["adhdev mcp --repo-mesh ",e.id]})," ",ee("repoMesh.detail.mcpDescription")]})]})},{key:"advanced",label:ee("repoMesh.detail.tabAdvanced"),content:oe}];return s.jsxs(s.Fragment,{children:[s.jsx(hI,{tabs:pe,ariaLabel:ee("repoMesh.detail.tabsAriaLabel"),className:"flex flex-col gap-4"}),Ae&&bt&&s.jsx(af,{activeConv:dL({meshId:e.id,daemonId:R,meshName:e.name}),sendDaemonCommand:ue,onClose:()=>Je(!1)})]})})()]})}const ha=new Map;async function hf(e){var r,o,i,c,u,p,d,m,h,g,k;const{sendCommand:t,unwrapResult:n}=e,a={meshCreated:!1,meshId:"",error:null,warning:null,plan:null};try{const f=await t(e.targetDaemonId,"plan_mesh_onboarding",{workspace:e.workspace||void 0,operation:"auto",meshInventory:e.meshInventory}),x=n(f);if(a.plan=x,(x==null?void 0:x.success)===!1)return{...a,error:`${x.code||"onboarding_blocked"}: ${x.error}${x.action?` ${x.action}`:""}`};if(((r=x==null?void 0:x.plan)==null?void 0:r.kind)!=="create_mesh_and_onboard")return{...a,error:((o=x==null?void 0:x.plan)==null?void 0:o.summary)||"A compatible mesh already exists; add this workspace to it instead of creating a duplicate mesh."};const w={name:e.name.trim()};(e.repoRemoteUrl||(u=(c=(i=x==null?void 0:x.discovery)==null?void 0:i.origin)==null?void 0:c.urls)!=null&&u[0])&&(w.repoRemoteUrl=e.repoRemoteUrl||x.discovery.origin.urls[0]),(e.repoIdentity||(p=x==null?void 0:x.discovery)!=null&&p.repoIdentity)&&(w.repoIdentity=e.repoIdentity||x.discovery.repoIdentity),(d=x==null?void 0:x.discovery)!=null&&d.defaultBranch&&(w.defaultBranch=x.discovery.defaultBranch);const b=await t(e.targetDaemonId,"create_mesh",w),N=n(b);if((N==null?void 0:N.success)===!1)return{...a,error:N.error||"Create failed"};const j=typeof((m=N==null?void 0:N.mesh)==null?void 0:m.id)=="string"?N.mesh.id:"",v={...a,meshCreated:!0,meshId:j};if(!j||!e.attachWorkspace||!e.workspace)return v;try{const y=await t(e.targetDaemonId,"add_mesh_node",{meshId:j,daemonId:e.targetDaemonId,machineId:e.machineId,workspace:((h=x==null?void 0:x.discovery)==null?void 0:h.repoRoot)||e.workspace,repoRoot:(g=x==null?void 0:x.discovery)==null?void 0:g.repoRoot,isLocalWorktree:((k=x==null?void 0:x.discovery)==null?void 0:k.isLinkedWorktree)===!0,role:"host",providerPriority:e.providerPriority}),C=n(y);return(C==null?void 0:C.success)===!1?{...v,warning:Au(C.error||"add_mesh_node failed")}:v}catch(y){return{...v,warning:Au((y==null?void 0:y.message)||"add_mesh_node failed")}}}catch(f){return{...a,error:(f==null?void 0:f.message)||"Create failed"}}}function Au(e){return`Mesh created, but attaching the workspace failed: ${e}. Add the workspace from the mesh's node list.`}function ff({daemons:e,primaryDaemonId:t,sendCommand:n,unwrapResult:a,normalizeMesh:r,features:o,loadDaemonMetadata:i}){const c=e.map(Z=>Z.id).filter(Boolean).sort().join(","),[u,p]=l.useState(()=>ha.get(c)??[]),[d,m]=l.useState(null),[h,g]=l.useState(()=>!ha.has(c)),[k,f]=l.useState(null),[x,w]=l.useState(!1),[b,N]=l.useState(!1),[j,v]=l.useState(null),[y,C]=l.useState(""),[S,A]=l.useState(""),[M,I]=l.useState(""),[D,P]=l.useState(""),[T,H]=l.useState(""),[L,R]=l.useState(null),[U,E]=l.useState(!1),$=o.createDaemonPicker?D:t,_=l.useMemo(()=>e.find(Z=>Z.id===$),[e,$]),q=(_==null?void 0:_.workspaces)||[],B=l.useMemo(()=>en((_==null?void 0:_.availableProviders)||[]),[_]);l.useEffect(()=>{!i||!$||!_||!(!_.workspaces||!_.availableProviders)||Promise.resolve(i($,{minFreshMs:3e4})).catch(()=>{})},[i,$,_]),l.useEffect(()=>{if(!x||!$||!T){R(null);return}let Z=!1;return E(!0),n($,"plan_mesh_onboarding",{workspace:T,operation:"auto",meshInventory:u}).then(z=>{if(Z)return;const X=a(z);R(X),X!=null&&X.success&&(A(O=>{var Q;return O||((Q=X.discovery)==null?void 0:Q.repoIdentity)||""}),I(O=>{var Q,ke,Se,ve,xe,Y;return O||((Se=(ke=(Q=X.discovery)==null?void 0:Q.origin)==null?void 0:ke.urls)==null?void 0:Se[0])||((Y=(xe=(ve=X.discovery)==null?void 0:ve.upstream)==null?void 0:xe.urls)==null?void 0:Y[0])||""}),C(O=>{var Q,ke;return O||`${String(((Q=X.discovery)==null?void 0:Q.repoIdentity)||((ke=X.discovery)==null?void 0:ke.repoRoot)||"").split(/[\\/]/).filter(Boolean).pop()||"repo"}-mesh`}))}).catch(z=>{Z||R({success:!1,error:(z==null?void 0:z.message)||"Git discovery failed"})}).finally(()=>{Z||E(!1)}),()=>{Z=!0}},[x,$,T,u,n,a]);const W=l.useMemo(()=>e.map(Z=>Z.id).filter(Boolean).sort().join(","),[e]),V=l.useCallback(async(Z=!1)=>{const z=Z||ha.has(W);g(X=>z?X:!0);try{if(o.createDaemonPicker){const X=await Promise.allSettled(e.map(async ke=>{if(!ke.id)return[];const Se=await n(ke.id,"list_meshes",{}),ve=a(Se);if((ve==null?void 0:ve.success)===!1)throw new Error(ve.error||"Failed to load meshes");return(Array.isArray(ve==null?void 0:ve.meshes)?ve.meshes:[]).map(xe=>r(xe,ke.id)).filter(xe=>xe.id)})),O=new Map;for(const ke of X)if(ke.status==="fulfilled")for(const Se of ke.value)O.has(Se.id)||O.set(Se.id,Se);const Q=Array.from(O.values());p(Q),ha.set(W,Q),f(null)}else{if(!t)return;const X=await n(t,"list_meshes");if(X!=null&&X.success){const O=(X.meshes||[]).map(Q=>r(Q,t));p(O),ha.set(W,O),f(null)}else f((X==null?void 0:X.error)||"Failed to load meshes")}}catch(X){f((X==null?void 0:X.message)||"Failed to load meshes")}finally{g(!1)}},[W,t,n,a,r,o.createDaemonPicker]);async function ne(){const Z=o.createDaemonPicker?D:t;if(!Z||!y.trim())return;const z=M.trim(),X=S.trim(),O=T.trim();if(!(!O&&!z&&!X)&&!b){N(!0),v(null);try{const Q=await hf({targetDaemonId:Z,name:y,repoRemoteUrl:z,repoIdentity:X,workspace:O,attachWorkspace:!!O,machineId:_==null?void 0:_.machineId,providerPriority:wn(B),meshInventory:u,sendCommand:n,unwrapResult:a});if(Q.plan!==null&&R(Q.plan),Q.warning&&v(Q.warning),!Q.meshCreated){f(Q.error||"Create failed");return}w(!1),C(""),A(""),I(""),H(""),await V(),Q.meshId&&m(Q.meshId)}finally{N(!1)}}}async function ae(Z){var X;if(!confirm("Delete this mesh? This cannot be undone."))return;const z=((X=u.find(O=>O.id===Z))==null?void 0:X.__sourceDaemonId)||t;try{const O=await n(z,"delete_mesh",{meshId:Z}),Q=a(O);if((Q==null?void 0:Q.success)===!1)throw new Error(Q.error||"Failed to delete");d===Z&&m(null),await V()}catch(O){f((O==null?void 0:O.message)||"Delete failed")}}function he(){w(!1),C(""),A(""),I(""),H(""),R(null),v(null)}return{meshes:u,setMeshes:p,selectedMeshId:d,setSelectedMeshId:m,loading:h,error:k,setError:f,showCreate:x,setShowCreate:w,creating:b,createWarning:j,setCreateWarning:v,createName:y,setCreateName:C,createRepoIdentity:S,setCreateRepoIdentity:A,createRepoRemoteUrl:M,setCreateRepoRemoteUrl:I,newMeshDaemonId:D,setNewMeshDaemonId:P,newMeshWorkspace:T,setNewMeshWorkspace:H,createPickerWorkspaces:q,createPickerProviders:B,createOnboardingPlan:L,createPlanLoading:U,loadMeshes:V,handleCreate:ne,handleDelete:ae,cancelCreate:he}}function pL({selectedMesh:e,selectedMeshId:t,primaryDaemonId:n,activeDaemonId:a,daemons:r,sendCommand:o,unwrapResult:i,loadLiveMesh:c,resolveCommandTarget:u,launchCoordinator:p,features:d,loadMeshes:m,loadQueue:h,queueSection:g,setError:k}){const[f,x]=l.useState(null),[w,b]=l.useState(!1),[N,j]=l.useState(""),[v,y]=l.useState([]),[C,S]=l.useState(""),[A,M]=l.useState(!1),[I,D]=l.useState(null),[P,T]=l.useState(!1),[H,L]=l.useState(""),[R,U]=l.useState(!1),[E,$]=l.useState(!1),[_,q]=l.useState(null),[B,W]=l.useState(!1),[V,ne]=l.useState({override:"",append:""}),[ae,he]=l.useState(!1),[Z,z]=l.useState({}),[X,O]=l.useState(null),Q=l.useMemo(()=>r.find(J=>J.id===C),[r,C]),ke=(Q==null?void 0:Q.workspaces)||[],Se=l.useMemo(()=>en((Q==null?void 0:Q.availableProviders)||[]),[Q]);l.useEffect(()=>{if(!w||!t||!N.trim()){D(null);return}const J=d.addNodeDaemonPicker?C:(e==null?void 0:e.__sourceDaemonId)||n;if(!J)return;let ge=!1;return T(!0),o(J,"plan_mesh_onboarding",{workspace:N.trim(),meshId:t,inlineMesh:e,operation:"add_existing"}).then(ue=>{ge||D(i(ue))}).catch(ue=>{ge||D({success:!1,error:(ue==null?void 0:ue.message)||"Git discovery failed"})}).finally(()=>{ge||T(!1)}),()=>{ge=!0}},[w,t,e,N,C,n,d.addNodeDaemonPicker,o,i]);async function ve(){var ue,ee,De;const J=(e==null?void 0:e.__sourceDaemonId)||n;if(!t||!J)return;const ge=N.trim();if(ge)try{const Le=d.addNodeDaemonPicker?C:J,Xe=await o(Le,"plan_mesh_onboarding",{workspace:ge,meshId:t,inlineMesh:e,operation:"add_existing"}),ce=i(Xe);if(D(ce),(ce==null?void 0:ce.success)===!1)throw new Error(`${ce.code||"onboarding_blocked"}: ${ce.error}${ce.action?` ${ce.action}`:""}`);const Ee={meshId:t,workspace:((ue=ce==null?void 0:ce.discovery)==null?void 0:ue.repoRoot)||ge,repoRoot:(ee=ce==null?void 0:ce.discovery)==null?void 0:ee.repoRoot,isLocalWorktree:((De=ce==null?void 0:ce.discovery)==null?void 0:De.isLinkedWorktree)===!0};d.addNodeDaemonPicker&&C&&(Ee.daemonId=C,Ee.machineId=Q==null?void 0:Q.machineId),Ee.providerPriority=Wa(v);const Fe=await o(J,"add_mesh_node",Ee),et=i(Fe);if((et==null?void 0:et.success)===!1)throw new Error(et.error||"Add node failed");b(!1),j(""),y([]),S(""),M(!1),await m(),g||await h(t)}catch(Le){k((Le==null?void 0:Le.message)||"Add node failed")}}async function xe(J){var De;if(!e)return;const ge=rl(e),ue=((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(Le=>Le.value===ge.sessionCleanupOnNodeRemove))==null?void 0:De.label)||"Preserve history and runtimes";if(!confirm(`Remove this node?
|
|
115
115
|
|
|
116
|
-
Node removal cleanup policy: ${ue}`))return;const ee=e.__sourceDaemonId||n;try{const Le=await o(ee,"remove_mesh_node",{meshId:e.id,nodeId:J}),Xe=i(Le);if((Xe==null?void 0:Xe.success)===!1)throw new Error(Xe.error||"Remove failed");f===J&&x(null),await m(),g||await h(t)}catch(Le){k((Le==null?void 0:Le.message)||"Remove node failed")}}async function Y(J){if(!e)return;const ge={...rl(e),...J},ue=e.__sourceDaemonId||n;try{W(!0),k(null);const ee=await o(ue,"update_mesh",{meshId:e.id,policy:ge}),De=i(ee);if((De==null?void 0:De.success)===!1)throw new Error(De.error||"Policy update failed");await m()}catch(ee){k((ee==null?void 0:ee.message)||"Policy update failed")}finally{W(!1)}}const[G,te]=l.useState(null);async function me(J,ge){if(!t)return;const ue=(e==null?void 0:e.__sourceDaemonId)||n;try{te(J.id),k(null);const ee=await o(ue,"update_mesh_node",{meshId:t,nodeId:J.id,policy:{slots:ge}}),De=i(ee);if((De==null?void 0:De.success)===!1){k(De.error||"Node slots update failed");return}await m()}catch(ee){k((ee==null?void 0:ee.message)||"Node slots update failed")}finally{te(null)}}const[K,be]=l.useState(null);async function re(J,ge){if(!t)return;const ue=(e==null?void 0:e.__sourceDaemonId)||n,ee=ge.map(De=>De.trim()).filter(Boolean);try{be(J.id),k(null);const De=await o(ue,"update_mesh_node",{meshId:t,nodeId:J.id,capabilities:ee}),Le=i(De);if((Le==null?void 0:Le.success)===!1){k(Le.error||"Node tag update failed");return}await m()}catch(De){k((De==null?void 0:De.message)||"Node tag update failed")}finally{be(null)}}async function de(){if(!n||!t)return;const ge={...(e==null?void 0:e.coordinator)||{}};V.override.trim()?ge.systemPromptOverride=V.override:delete ge.systemPromptOverride,V.append.trim()?ge.systemPromptAppend=V.append:delete ge.systemPromptAppend,delete ge.systemPromptSuffix;try{he(!0),k(null);const ue=await o(n,"update_mesh",{meshId:t,coordinator:ge}),ee=i(ue);if((ee==null?void 0:ee.success)===!1){k(ee.error||"Coordinator prompt save failed");return}await m()}catch(ue){k((ue==null?void 0:ue.message)||"Coordinator prompt save failed")}finally{he(!1)}}async function we(J){if(!n||!t)return;const ge=(Z[J.id]||"").trim();try{O(J.id),k(null);const ue=await o(n,"update_mesh_node",{meshId:t,nodeId:J.id,systemPrompt:ge}),ee=i(ue);if((ee==null?void 0:ee.success)===!1){k(ee.error||"Node instruction save failed");return}await m()}catch(ue){k((ue==null?void 0:ue.message)||"Node instruction save failed")}finally{O(null)}}async function Re(J){if(!(!e||!J)){k(null),q(null);try{$(!0);const ge=(e.nodes||[]).find(De=>zs(String(De.daemon_id||De.daemonId||""),J)),ue=await o(J,"set_mesh_host",{meshId:e.id,hostDaemonId:J,...ge!=null&&ge.id?{hostNodeId:ge.id}:{}}),ee=i(ue);if((ee==null?void 0:ee.success)===!1){k(ee.error||"Setting the mesh host failed");return}await m()}catch(ge){k((ge==null?void 0:ge.message)||"Setting the mesh host failed")}finally{$(!1)}}}async function F(){if(e){k(null),q(null);try{U(!0);const J=c?await c(a,e.id,e):null,ge=u(a,e.id,e,e.nodes||[],J);if("error"in ge)throw new Error(ge.error);const ue=await p(ge.targetDaemonId,{meshId:e.id,inlineMesh:ge.inlineMesh,coordinatorNodeId:ge.coordinatorNodeId,cliType:H.trim()||void 0});q(ue.message)}catch(J){k((J==null?void 0:J.message)||"Coordinator launch failed")}finally{U(!1)}}}return{selectedNodeId:f,setSelectedNodeId:x,showAddNode:w,setShowAddNode:b,nodeWorkspace:N,setNodeWorkspace:j,nodeProviderPriority:v,setNodeProviderPriority:y,nodeDaemonId:C,setNodeDaemonId:S,nodeCustomPath:A,setNodeCustomPath:M,nodePickerWorkspaces:ke,nodePickerProviders:Se,nodeOnboardingPlan:I,nodePlanLoading:P,coordinatorCliType:H,setCoordinatorCliType:L,launchingCoordinator:R,launchResult:_,settingMeshHost:E,savingPolicy:B,coordinatorPromptDraft:V,setCoordinatorPromptDraft:ne,savingCoordinatorPrompt:ae,nodeSystemPromptDrafts:Z,setNodeSystemPromptDrafts:z,savingNodeSystemPromptId:X,savingNodeSlotsId:G,savingNodeCapabilitiesId:K,handleAddNode:ve,handleRemoveNode:xe,handleUpdatePolicy:Y,handleUpdateNodeSlots:me,handleUpdateNodeCapabilities:re,handleSaveCoordinatorPrompt:de,handleSaveNodeSystemPrompt:we,handleLaunchCoordinator:F,handleSetMeshHost:Re}}function mL(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 hL({primaryDaemonId:e,activeDaemonId:t,sendCommand:n,unwrapResult:a,loadLiveMesh:r,resolveCommandTarget:o}){const[i,c]=l.useState([]),[u,p]=l.useState(null),[d,m]=l.useState(!1),[h,g]=l.useState(null),k=l.useCallback(async x=>{if(!e||!x){c([]);return}try{const w=await n(e,"get_mesh_queue",{meshId:x});c(w!=null&&w.success?Array.isArray(w.queue)?w.queue:[]:[])}catch{c([])}},[e,n]);async function f(x){var w,b;if(x){m(!0),g(null);try{const N=r?await r(t,x.id,x):null,j=o(t,x.id,x,x.nodes||[],N);if("error"in j)throw new Error(j.error);const v=await n(j.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 C=Array.isArray(((w=y==null?void 0:y.result)==null?void 0:w.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(mL(C))}catch(N){g((N==null?void 0:N.message)||"Queue load failed")}finally{m(!1)}}}return{meshQueue:i,setMeshQueue:c,queueSummary:u,queueLoading:d,queueError:h,loadQueue:k,handleLoadQueue:f}}function fL(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}const bf=new Map;function gf(e){return e?bf.get(e)??null:null}function bL(e,t){!e||!t||bf.set(e,t)}function gL({selectedMeshId:e,loadMeshStatus:t,extractStatus:n,normalizeNode:a,gateIncompleteGraph:r}){const[o,i]=l.useState(()=>gf(e)),[c,u]=l.useState(!1),[p,d]=l.useState(null),[m,h]=l.useState("idle"),[g,k]=l.useState(!1),f=l.useRef(!1);async function x(w,b=e,N=!1){if(!(!w||!b))try{u(!N&&o===null),h(N?"settling":"first_paint"),d(null);const j=await t(w,b,{refresh:N,retryProfile:N?"settled":"interactive"});k(fL(j));const v=n(j),y=a&&v?{...v,nodes:(v.nodes??[]).map(C=>a(C,v.meshId??b,""))}:v;if(y){if(r&&!N&&o!==null&&!mM(Bh(y))){h("settling"),f.current||(f.current=!0,Promise.resolve().then(()=>x(w,b,!0)).finally(()=>{f.current=!1}));return}i(y),bL(b,y),h("settled")}else i(null),d("mesh_status returned an unexpected payload."),h("idle")}catch(j){o||i(null),d((j==null?void 0:j.message)||"Failed to load mesh graph"),h("idle")}finally{u(!1)}}return{meshGraphStatus:o,setMeshGraphStatus:i,graphLoading:c,graphError:p,setGraphError:d,graphProvenance:m,graphBootstrapFallback:g,loadGraph:x}}function Mu(e){return!e||e.hostSynthesized?{hostDaemonId:"",hostNodeId:""}:{hostDaemonId:String(e.hostDaemonId||""),hostNodeId:String(e.hostNodeId||"")}}function xL(e,t,n,a,r){if(!e.length)return"";const o=String(r||"");if(o){const u=e.find(p=>zs(p.id,o));return u?u.id:o}const i=t.find(u=>u.role==="host"),c=String((i==null?void 0:i.daemon_id)||(i==null?void 0:i.daemonId)||"");if(c){const u=e.find(p=>zs(p.id,c));if(u)return u.id}return""}function vL(e){var r;if(!e)return"null";const t=[...e.nodes??[]].map(o=>{var i,c,u,p,d,m;return[o.nodeId,o.health,((i=o.git)==null?void 0:i.branch)??"",((c=o.git)==null?void 0:c.headCommit)??"",(u=o.git)!=null&&u.dirty?"1":"0",((p=o.git)==null?void 0:p.ahead)??0,((d=o.git)==null?void 0:d.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 yL=4,wL=3e4;function kL(){return{lastFingerprint:null,stableTicks:0,backedOff:!1}}function ol(e){e.stableTicks=0,e.backedOff=!1}function SL(e,t){const n=vL(t);return e.lastFingerprint===null?(e.lastFingerprint=n,e.backedOff):n!==e.lastFingerprint?(e.lastFingerprint=n,ol(e),!1):(e.stableTicks+=1,e.stableTicks>=yL&&(e.backedOff=!0),e.backedOff)}function CL(e,t){return e.backedOff?Math.max(t,wL):t}const jL=7e3,NL=45e3;function AL(){const e=rI(),{sendCommand:t,sendData:n,daemons:a,userName:r,loadMeshStatus:o,launchCoordinator:i,loadLiveMesh:c,extractStatus:u,unwrapResult:p,normalizeMesh:d,normalizeNode:m,resolveCommandTarget:h,features:g,gateIncompleteGraph:k}=e,f=ea(),x=a[0],w=(x==null?void 0:x.id)||"",b=l.useMemo(()=>((x==null?void 0:x.availableProviders)||[]).filter(ot=>ot.category==="cli").map(ot=>({id:ot.type||ot.id,name:ot.displayName||ot.name||ot.type,meshCoordinator:ot.meshCoordinator})),[x]),N=l.useMemo(()=>en((x==null?void 0:x.availableProviders)||[]),[x]),{meshes:j,selectedMeshId:v,setSelectedMeshId:y,loading:C,error:S,setError:A,showCreate:M,setShowCreate:I,createName:D,setCreateName:P,createRepoIdentity:T,setCreateRepoIdentity:H,createRepoRemoteUrl:L,setCreateRepoRemoteUrl:R,newMeshDaemonId:U,setNewMeshDaemonId:E,newMeshWorkspace:$,setNewMeshWorkspace:_,createPickerWorkspaces:q,createOnboardingPlan:B,createPlanLoading:W,creating:V,createWarning:ne,setCreateWarning:ae,loadMeshes:he,handleCreate:Z,handleDelete:z,cancelCreate:X}=ff({daemons:a,primaryDaemonId:w,sendCommand:t,unwrapResult:p,normalizeMesh:d,features:g,loadDaemonMetadata:f}),O=j.find(qe=>qe.id===v)||null,{meshGraphStatus:Q,setMeshGraphStatus:ke,graphLoading:Se,graphError:ve,setGraphError:xe,loadGraph:Y}=gL({selectedMeshId:v,loadMeshStatus:o,extractStatus:u,normalizeNode:m,gateIncompleteGraph:k}),[G,te]=l.useState(""),[me,K]=l.useState(""),be=g.meshHostDaemonSection?G:w,{meshQueue:re,loadQueue:de}=hL({primaryDaemonId:w,activeDaemonId:be,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:h}),{selectedNodeId:we,setSelectedNodeId:Re,showAddNode:F,setShowAddNode:J,nodeWorkspace:ge,setNodeWorkspace:ue,nodeProviderPriority:ee,setNodeProviderPriority:De,nodeDaemonId:Le,setNodeDaemonId:Xe,nodeCustomPath:ce,setNodeCustomPath:Ee,nodePickerWorkspaces:Fe,nodePickerProviders:et,nodeOnboardingPlan:Ae,nodePlanLoading:Je,coordinatorCliType:bt,setCoordinatorCliType:it,launchingCoordinator:yt,launchResult:se,savingPolicy:oe,coordinatorPromptDraft:pe,setCoordinatorPromptDraft:ye,savingCoordinatorPrompt:le,nodeSystemPromptDrafts:Me,setNodeSystemPromptDrafts:_e,savingNodeSystemPromptId:Te,savingNodeSlotsId:Ue,savingNodeCapabilitiesId:Ge,handleAddNode:Ye,handleRemoveNode:Be,handleUpdatePolicy:Ve,handleUpdateNodeSlots:st,handleUpdateNodeCapabilities:$e,handleSaveCoordinatorPrompt:fe,handleSaveNodeSystemPrompt:je,handleLaunchCoordinator:Ne,settingMeshHost:He,handleSetMeshHost:Qe}=pL({selectedMesh:O,selectedMeshId:v,primaryDaemonId:w,activeDaemonId:be,daemons:a,availableCliProviders:N,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:h,launchCoordinator:i,features:{addNodeDaemonPicker:g.addNodeDaemonPicker},loadMeshes:he,loadQueue:de,queueSection:g.queueSection,setError:A}),lt=l.useMemo(()=>a.find(qe=>qe.id===be)||x,[a,be,x]),Ke=l.useMemo(()=>new Set(((O==null?void 0:O.nodes)||[]).map(qe=>String(qe.daemon_id||qe.daemonId||""))),[O]),St=l.useMemo(()=>a.filter(qe=>qe.id&&!Ke.has(qe.id)),[a,Ke]),Mt=(O==null?void 0:O.nodes)||[],zt=l.useMemo(()=>Mt.find(qe=>zs(String(qe.daemon_id||qe.daemonId||""),G)),[Mt,G]),rs=g.meshHostDaemonSection?!!zt:!0,Ct=l.useMemo(()=>{if(!g.meshHostDaemonSection||!O)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const qe=O.meshHost,ot=Q!=null&&Q.meshId&&String(Q.meshId)===String(O.id??"")?Q.meshHost:void 0,ds=ot!=null&&ot.hostDaemonId?ot:qe??ot,ie=Mu(ds),We=ie.hostDaemonId,Oe=Mt.find(Ls=>Ls.role==="host"),Rt=ie.hostNodeId||String((Oe==null?void 0:Oe.id)||""),Pt=Rt?Mt.find(Ls=>String(Ls.id)===Rt):void 0,ta=String((Pt==null?void 0:Pt.daemon_id)||(Pt==null?void 0:Pt.daemonId)||""),sa=We||ta;if(!sa)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const na=a.find(Ls=>We&&zs(Ls.id,We))||(ta?a.find(Ls=>zs(Ls.id,ta)):void 0);if(na)return{pinned:!0,daemonId:na.id,label:ML(na),online:!0,hostNode:Pt};const Ga=String((Pt==null?void 0:Pt.machineLabel)||"")||String((Pt==null?void 0:Pt.workspace)||"")||sa;return{pinned:!0,daemonId:sa,label:Ga,online:!1,hostNode:Pt}},[O,Mt,a,Q,g.meshHostDaemonSection]),Ws=Ct.daemonId,Pe=Ct.online,tt=Ct.pinned?Ct.hostNode:zt,Lt=l.useMemo(()=>!g.meshHostDaemonSection||!Ct.pinned?"":!Pe&&me&&a.some(qe=>qe.id===me)?me:Ws,[g.meshHostDaemonSection,Ct.pinned,Pe,me,a,Ws]),ct=l.useMemo(()=>Q?[...new Set((Q.nodes??[]).map(qe=>String(qe.daemonId||qe.daemon_id||"")).filter(Boolean))]:[],[Q]),os=nf({status:Q,daemonId:be||null,extraDaemonIds:ct,meshId:v,sendData:n});l.useEffect(()=>{const qe=(O==null?void 0:O.coordinator)||{};ye({override:typeof qe.systemPromptOverride=="string"?qe.systemPromptOverride:"",append:typeof qe.systemPromptAppend=="string"?qe.systemPromptAppend:typeof qe.systemPromptSuffix=="string"?qe.systemPromptSuffix:""}),_e(Object.fromEntries(((O==null?void 0:O.nodes)||[]).map(ot=>[ot.id,typeof ot.systemPrompt=="string"?ot.systemPrompt:""])))},[O]),l.useEffect(()=>{const qe=g.addNodeDaemonPicker?wn(et):wn(N);F&&ee.length===0&&qe.length>0&&De(qe)},[F,N,et,ee.length,g.addNodeDaemonPicker]),l.useEffect(()=>{const qe=new Set(((O==null?void 0:O.nodes)||[]).map(ot=>ot.id));we&&!qe.has(we)&&Re(null)},[O,we]);const Ut=l.useMemo(()=>{if(!(!(Q!=null&&Q.meshId)||String(Q.meshId)!==String((O==null?void 0:O.id)??"")))return Mu(Q.meshHost).hostDaemonId||void 0},[Q,O]),Vt=l.useMemo(()=>xL(a,Mt,be,w,Ut),[a,Mt,be,w,Ut]);l.useEffect(()=>{if(!g.meshHostDaemonSection)return;if(!a.length&&!Ct.pinned){te("");return}const qe=Ct.pinned?Lt:Vt;qe&&!zs(qe,G)&&te(qe)},[a,G,Ct.pinned,Lt,Vt,g.meshHostDaemonSection]),l.useEffect(()=>{me&&(Pe||!a.some(qe=>qe.id===me))&&K("")},[Pe,me,a]),l.useEffect(()=>{if(g.createDaemonPicker){if(!a.length){E("");return}(!U||!a.some(qe=>qe.id===U))&&E(a[0].id)}},[a,U,g.createDaemonPicker]),l.useEffect(()=>{var qe;if(!g.createDaemonPicker||!U){_("");return}if(!q.length){_("");return}q.some(ot=>ot.path===$)||_(((qe=q[0])==null?void 0:qe.path)||"")},[U,$,q,g.createDaemonPicker]);const ks=l.useRef(null),is=l.useRef(kL()),Xt=g.meshStatePushRefresh?NL:jL,[ls,Ts]=l.useState(Xt);l.useEffect(()=>{if(!v)return;const qe=ks.current!==v;if(ks.current=v,qe){ol(is.current),Ts(Xt);const ot=gf(v);ke(ot),xe(null),Y(be,v,ot!==null)}else xe(null),Y(be,v,!0)},[v,be]);const Ds=l.useRef(Y);Ds.current=Y;const Ss=l.useRef(!1),cs=l.useRef(()=>{});cs.current=()=>{Ss.current||!v||!be||(Ss.current=!0,Promise.resolve(Ds.current(be,v,!0)).finally(()=>{Ss.current=!1}))},l.useEffect(()=>{SL(is.current,Q),Ts(CL(is.current,Xt))},[Q,Xt]),aI({daemonIds:l.useMemo(()=>[be,...ct].filter(Boolean),[be,ct]),meshId:v,sendData:n,onRevisionAdvance:()=>{typeof document<"u"&&document.visibilityState!=="visible"||cs.current()}}),l.useEffect(()=>{if(!v||!be||typeof document>"u")return;let qe=null;const ot=()=>{document.visibilityState==="visible"&&cs.current()},ds=()=>{qe===null&&(qe=setInterval(ot,ls))},ie=()=>{qe!==null&&(clearInterval(qe),qe=null)},We=()=>{document.visibilityState==="visible"?ds():ie()};return document.visibilityState==="visible"&&ds(),document.addEventListener("visibilitychange",We),()=>{ie(),document.removeEventListener("visibilitychange",We)}},[v,be,ls]),l.useEffect(()=>{g.queueSection||de(v)},[v,g.queueSection]);const Os=l.useMemo(()=>a.map(qe=>qe.id).filter(Boolean).sort().join(","),[a]),Is=l.useRef(!1);return l.useEffect(()=>{he(Is.current),Is.current=!0},[Os]),w?O?s.jsx(uL,{selectedMesh:O,error:S,onDismissError:()=>A(null),onBack:()=>{y(null),ke(null)},onDelete:z,displayedMeshStatus:os,graphLoading:Se,graphError:ve,onRefreshGraph:()=>{ol(is.current),Y(be,v,!0)},savingPolicy:oe,onUpdatePolicy:Ve,coordinatorPromptDraft:pe,onCoordinatorPromptDraftChange:ye,savingCoordinatorPrompt:le,onSaveCoordinatorPrompt:fe,daemons:a,coordinatorDaemonId:G,onCoordinatorDaemonIdChange:te,coordinatorCliType:bt,onCoordinatorCliTypeChange:it,launchingCoordinator:yt,launchResult:se,isHostNodeAttached:rs,selectedHostNode:tt,hostPinned:Ct.pinned,hostLabel:Ct.label,hostOnline:Pe,hostRebindDaemonId:me,onHostRebindDaemonIdChange:qe=>K(qe),onLaunchCoordinator:Ne,settingMeshHost:He,onSetMeshHost:Qe,activeDaemon:lt,activeDaemonId:be,meshQueue:re,userName:r,availableCliProviders:N,savingNodeSlotsId:Ue,onUpdateNodeSlots:st,savingNodeCapabilitiesId:Ge,onUpdateNodeCapabilities:$e,nodeSystemPromptDrafts:Me,onNodeSystemPromptDraftChange:(qe,ot)=>_e(ds=>({...ds,[qe]:ot})),savingNodeSystemPromptId:Te,onSaveNodeSystemPrompt:je,selectedNodeId:we,onSelectNode:Re,showAddNode:F,onShowAddNode:()=>J(!0),onCancelAddNode:()=>J(!1),nodeWorkspace:ge,onNodeWorkspaceChange:ue,nodeProviderPriority:ee,onNodeProviderPriorityChange:De,nodeDaemonId:Le,onNodeDaemonIdChange:Xe,nodeCustomPath:ce,onNodeCustomPathChange:Ee,nodePickerWorkspaces:Fe,nodePickerProviders:et,nodeOnboardingPlan:Ae,nodePlanLoading:Je,attachableDaemons:St,onAddNode:Ye,onRemoveNode:Be,availableCliAgents:b,features:{coordinatorPrompt:g.coordinatorPrompt,meshHostDaemonSection:g.meshHostDaemonSection,hermesMcpConfig:g.hermesMcpConfig,addNodeDaemonPicker:g.addNodeDaemonPicker,nodeInstruction:g.nodeInstruction},sendCommand:t}):s.jsx(mI,{meshes:j,loading:C,error:S,onDismissError:()=>A(null),daemons:a,features:{createDaemonPicker:g.createDaemonPicker,maxMeshes:g.maxMeshes},showCreate:M,onToggleCreate:()=>I(!M),createName:D,onCreateNameChange:P,createRepoIdentity:T,onCreateRepoIdentityChange:H,createRepoRemoteUrl:L,onCreateRepoRemoteUrlChange:R,newMeshDaemonId:U,onNewMeshDaemonIdChange:E,newMeshWorkspace:$,onNewMeshWorkspaceChange:_,createPickerWorkspaces:q,createOnboardingPlan:B,createPlanLoading:W,creating:V,createWarning:ne,onDismissCreateWarning:()=>ae(null),onSelectMesh:y,onCreate:Z,onCancelCreate:X}):s.jsx(Oa,{icon:s.jsx(ns,{}),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 ML(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function PL({children:e}){const{sendCommand:t,sendData:n}=vt(),{ides:a}=ys(),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 h;const u={meshId:c.meshId};c.cliType&&(u.cliType=c.cliType);const p=await t(i,"launch_mesh_coordinator",u),d=(p==null?void 0:p.result)??p;if((d==null?void 0:d.success)===!1)throw new Error(d.error||"Coordinator launch failed");const m=(d==null?void 0:d.sessionId)||((h=d==null?void 0:d.session)==null?void 0:h.id)||(d==null?void 0:d.targetSessionId);return{sessionId:m,message:m?`Coordinator launched (${m})`:"Coordinator launch command sent"}},loadLiveMesh:void 0,extractStatus:Ml,unwrapResult:i=>i,normalizeMesh:(i,c)=>i,normalizeNode:(i,c,u)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:df}),[t,n,r]);return s.jsx(uf.Provider,{value:o,children:e})}function TL(e){const{daemons:t,features:n,meshes:a,meshesLoading:r,selectedMeshId:o,onSelectMesh:i,createMode:c,onCreateModeChange:u,createName:p,onCreateNameChange:d,createDaemonId:m,onCreateDaemonIdChange:h,createWorkspace:g,onCreateWorkspaceChange:k,createPickerWorkspaces:f,createPlan:x,createPlanLoading:w,creating:b,createWarning:N,onCreate:j,createRepoRemoteUrl:v,onCreateRepoRemoteUrlChange:y,createRepoIdentity:C,onCreateRepoIdentityChange:S,createManualOpen:A,onCreateManualOpenChange:M,nodes:I,attachableDaemons:D,attachDaemonId:P,onAttachDaemonIdChange:T,attachWorkspace:H,onAttachWorkspaceChange:L,attachPickerWorkspaces:R,attachPlan:U,attachPlanLoading:E,attaching:$,onAttach:_,renderInstallOnboarding:q,nodeLabel:B,daemonLabel:W}=e,{t:V}=Ce("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:V("setupWizard.machines.title")}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-text-muted",children:V("setupWizard.machines.noMachinesDescription")})]}),q?q():s.jsx("p",{className:"text-[11px] text-text-muted",children:V("setupWizard.machines.noMachinesFallback")})]});const ne=$||E||(U==null?void 0:U.success)===!1||!H.trim()||n.addNodeDaemonPicker&&!P;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:V("setupWizard.machines.title")}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-text-muted",children:V("setupWizard.machines.description")})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[a.map(ae=>{const he=!c&&o===ae.id;return s.jsx("button",{type:"button",onClick:()=>{u(!1),i(ae.id)},className:`flex items-center gap-2 rounded-lg border px-3 py-2 text-left transition-colors ${he?"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:ae.name}),s.jsxs("span",{className:"block truncate text-[11px] text-text-muted",children:[ae.repoIdentity||ae.repoRemoteUrl||""," · ",V("setupWizard.machines.nodeCount",{count:(ae.nodes||[]).length})]})]})},ae.id)}),s.jsx("button",{type:"button",onClick:()=>u(!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:["+ ",V("setupWizard.machines.createNew")]})}),r&&a.length===0&&s.jsx("p",{className:"text-[11px] text-text-muted",children:V("setupWizard.machines.loadingMeshes")})]}),c&&s.jsx(mf,{variant:"wizard",showDaemonPicker:n.createDaemonPicker,daemons:t,daemonLabel:W,name:p,onNameChange:d,daemonId:m,onDaemonIdChange:h,workspace:g,onWorkspaceChange:k,workspaces:f,plan:x,planLoading:w,repoRemoteUrl:v,onRepoRemoteUrlChange:y,repoIdentity:C,onRepoIdentityChange:S,manualOpen:A,onManualOpenChange:M,creating:b,warning:N,onCreate:j}),!c&&o&&s.jsxs("div",{className:"flex flex-col gap-2.5 rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2.5",children:[I.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5",children:I.map(ae=>s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] text-text-secondary",children:B(ae)},ae.id))}),s.jsx("span",{className:"text-[11px] font-medium text-text-secondary",children:V("setupWizard.machines.attachTitle")}),n.addNodeDaemonPicker&&(D.length>0?s.jsx("div",{className:"flex flex-wrap gap-1.5",children:D.map(ae=>{const he=P===ae.id;return s.jsx("button",{type:"button",onClick:()=>T(ae.id),className:`rounded-full border px-2.5 py-1 text-[11px] transition-colors ${he?"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:W(ae)},ae.id)})}):s.jsx("p",{className:"text-[11px] text-text-muted",children:V("setupWizard.machines.allMachinesAttached")})),(!n.addNodeDaemonPicker||P)&&s.jsxs(s.Fragment,{children:[s.jsx(el,{workspaces:R,value:H,onChange:L}),s.jsx(pf,{plan:U,loading:E}),s.jsx("div",{className:"flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:_,disabled:ne,children:V($?"setupWizard.machines.attaching":"setupWizard.machines.addMachine")})})]})]})]})}function DL(e){var t;return e.machineNickname||e.nickname||e.hostname||((t=e.user)==null?void 0:t.name)||e.id}function IL(e){const t=e;return t.machine_label||t.machineLabel||t.hostname||String(e.workspace||"").split(/[\\/]/).filter(Boolean).pop()||e.id}function LL({daemons:e,features:t,sendCommand:n,unwrapResult:a,normalizeMesh:r,loadDaemonMetadata:o,initialMeshId:i,onClose:c,renderInstallOnboarding:u}){var we,Re;const{t:p}=Ce("common"),d=((we=e[0])==null?void 0:we.id)||"",{meshes:m,loading:h,error:g,setError:k,loadMeshes:f,selectedMeshId:x,setSelectedMeshId:w}=ff({daemons:e,primaryDaemonId:d,sendCommand:n,unwrapResult:a,normalizeMesh:r,features:{createDaemonPicker:t.createDaemonPicker,addNodeDaemonPicker:t.addNodeDaemonPicker},loadDaemonMetadata:o});l.useEffect(()=>{f()},[f]),l.useEffect(()=>{x||m.length===0||(i&&m.some(F=>F.id===i)?w(i):m.length===1&&w(m[0].id))},[m,x,i,w]);const b=l.useMemo(()=>m.find(F=>F.id===x)??null,[m,x]),N=l.useMemo(()=>(b==null?void 0:b.nodes)||[],[b]),j=l.useCallback(F=>(F==null?void 0:F.__sourceDaemonId)||d,[d]),[v,y]=l.useState(!1),[C,S]=l.useState(""),[A,M]=l.useState(""),[I,D]=l.useState(""),[P,T]=l.useState(null),[H,L]=l.useState(!1),[R,U]=l.useState(!1),[E,$]=l.useState(null),[_,q]=l.useState(""),[B,W]=l.useState(""),[V,ne]=l.useState(!1),ae=t.createDaemonPicker&&A||d,he=l.useMemo(()=>e.find(F=>F.id===ae),[e,ae]),Z=(he==null?void 0:he.workspaces)||[];l.useEffect(()=>{if(!v||!ae||!I.trim()){T(null);return}let F=!1;return L(!0),n(ae,"plan_mesh_onboarding",{workspace:I.trim(),operation:"auto",meshInventory:m}).then(J=>{if(F)return;const ge=a(J);T(ge),ge!=null&&ge.success&&(S(ue=>{var ee,De;return ue||`${String(((ee=ge.discovery)==null?void 0:ee.repoIdentity)||((De=ge.discovery)==null?void 0:De.repoRoot)||"").split(/[\\/]/).filter(Boolean).pop()||"repo"}-mesh`}),W(ue=>{var ee;return ue||((ee=ge.discovery)==null?void 0:ee.repoIdentity)||""}),q(ue=>{var ee,De,Le,Xe,ce,Ee;return ue||((Le=(De=(ee=ge.discovery)==null?void 0:ee.origin)==null?void 0:De.urls)==null?void 0:Le[0])||((Ee=(ce=(Xe=ge.discovery)==null?void 0:Xe.upstream)==null?void 0:ce.urls)==null?void 0:Ee[0])||""}))}).catch(J=>{F||T({success:!1,error:(J==null?void 0:J.message)||"Git discovery failed"})}).finally(()=>{F||L(!1)}),()=>{F=!0}},[v,ae,I,m,n,a]);const z=l.useCallback(async()=>{const F=ae,J=I.trim(),ge=_.trim(),ue=B.trim();if(!(!F||!C.trim()||R)&&!(!J&&!ge&&!ue)){U(!0),$(null),k(null);try{const ee=await hf({targetDaemonId:F,name:C,repoRemoteUrl:ge,repoIdentity:ue,workspace:J,attachWorkspace:!!J,machineId:he==null?void 0:he.machineId,providerPriority:wn(en((he==null?void 0:he.availableProviders)||[])),meshInventory:m,sendCommand:n,unwrapResult:a});if(ee.warning&&$(ee.warning),!ee.meshCreated){k(ee.error||p("setupWizard.machines.createFailed"));return}await f(!0),ee.meshId&&w(ee.meshId),y(!1)}finally{U(!1)}}},[ae,C,I,_,B,R,he,m,n,a,f,w,k,p]),[X,O]=l.useState(""),[Q,ke]=l.useState(""),[Se,ve]=l.useState(null),[xe,Y]=l.useState(!1),[G,te]=l.useState(!1),me=l.useMemo(()=>{if(!t.addNodeDaemonPicker)return[];const F=new Set(N.map(J=>String(J.daemon_id||J.daemonId||"")));return e.filter(J=>J.id&&!F.has(J.id))},[t.addNodeDaemonPicker,N,e]),K=l.useMemo(()=>e.find(F=>F.id===X),[e,X]),be=t.addNodeDaemonPicker?(K==null?void 0:K.workspaces)||[]:((Re=e.find(F=>F.id===d))==null?void 0:Re.workspaces)||[];l.useEffect(()=>{if(v||!x||!Q.trim()){ve(null);return}const F=t.addNodeDaemonPicker?X:j(b);if(!F)return;let J=!1;return Y(!0),n(F,"plan_mesh_onboarding",{workspace:Q.trim(),meshId:x,inlineMesh:b,operation:"add_existing"}).then(ge=>{J||ve(a(ge))}).catch(ge=>{J||ve({success:!1,error:(ge==null?void 0:ge.message)||"Git discovery failed"})}).finally(()=>{J||Y(!1)}),()=>{J=!0}},[v,x,b,Q,X,t.addNodeDaemonPicker,j,n,a]);const re=l.useCallback(async()=>{var ge,ue,ee,De;const F=j(b);if(!x||!F||G)return;const J=Q.trim();if(J){te(!0),k(null);try{const Le=t.addNodeDaemonPicker?X:F,Xe=await n(Le,"plan_mesh_onboarding",{workspace:J,meshId:x,inlineMesh:b,operation:"add_existing"}),ce=a(Xe);if(ve(ce),(ce==null?void 0:ce.success)===!1)throw new Error(`${ce.code||"onboarding_blocked"}: ${ce.error}${ce.action?` ${ce.action}`:""}`);const Ee={meshId:x,workspace:((ge=ce==null?void 0:ce.discovery)==null?void 0:ge.repoRoot)||J,repoRoot:(ue=ce==null?void 0:ce.discovery)==null?void 0:ue.repoRoot,isLocalWorktree:((ee=ce==null?void 0:ce.discovery)==null?void 0:ee.isLinkedWorktree)===!0};t.addNodeDaemonPicker&&X&&(Ee.daemonId=X,Ee.machineId=K==null?void 0:K.machineId),Ee.providerPriority=wn(en(((De=t.addNodeDaemonPicker?K:e[0])==null?void 0:De.availableProviders)||[]));const Fe=await n(F,"add_mesh_node",Ee),et=a(Fe);if((et==null?void 0:et.success)===!1)throw new Error(et.error||"Add node failed");ke(""),ve(null),await f(!0)}catch(Le){k((Le==null?void 0:Le.message)||"Add node failed")}finally{te(!1)}}},[b,x,Q,X,K,G,t.addNodeDaemonPicker,j,e,n,a,f,k]),de=!v&&!!b&&N.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(TL,{daemons:e,features:t,meshes:m,meshesLoading:h,selectedMeshId:x,onSelectMesh:F=>{w(F),ke(""),O("")},createMode:v,onCreateModeChange:y,createName:C,onCreateNameChange:S,createDaemonId:A,onCreateDaemonIdChange:M,createWorkspace:I,onCreateWorkspaceChange:D,createPickerWorkspaces:Z,createPlan:P,createPlanLoading:H,creating:R,createWarning:E,onCreate:z,createRepoRemoteUrl:_,onCreateRepoRemoteUrlChange:q,createRepoIdentity:B,onCreateRepoIdentityChange:W,createManualOpen:V,onCreateManualOpenChange:ne,nodes:N,attachableDaemons:me,attachDaemonId:X,onAttachDaemonIdChange:F=>{O(F),ke("")},attachWorkspace:Q,onAttachWorkspaceChange:ke,attachPickerWorkspaces:be,attachPlan:Se,attachPlanLoading:xe,attaching:G,onAttach:re,renderInstallOnboarding:u,nodeLabel:IL,daemonLabel:DL})}),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:de?"btn btn-primary btn-sm":"btn btn-secondary btn-sm",onClick:c,children:p(de?"setupWizard.continueToMesh":"setupWizard.close")})})})]})}function rc(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function RL(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=rc();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 Ns(e,t){return await fetch(RL(e),{credentials:"same-origin",...t})}function xf(){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 EL{constructor(){at(this,"adapters",new Map);at(this,"states",new Map);at(this,"runtimeListeners",new Map);at(this,"screenshotCallbacks",new Map);at(this,"statusCallbacks",new Set);at(this,"stateChangeCallbacks",new Set);at(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 Ns(`${r.pathname}${r.search}`);if(!o.ok){let c=`Runtime snapshot unavailable (${o.status})`;try{const u=await o.json();u!=null&&u.error&&(c=u.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 js=new EL;function _L(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,n=rc();return n?`${t}?token=${encodeURIComponent(n)}`:t}const fr=_L(),Pu=3e3,HL=3e4;let ms=null,$L=0;const Qr=new Map;let ln=null,Aa=null;function Tu(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function fa(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function FL(e){return e==="connected"?"connected":e}async function Ma(e,t,n){const a=Pm(e,n||{}),r=ms;if(r&&r.readyState===WebSocket.OPEN){const o=`req_${++$L}_${Date.now()}`;return new Promise((i,c)=>{const u=setTimeout(()=>{Qr.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);Qr.set(o,{resolve:p=>{clearTimeout(u),i(p)},reject:p=>{clearTimeout(u),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 il(e,t){const n=ms;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 vf(e,t,n){const a=ms;if(!a||a.readyState!==WebSocket.OPEN)return!1;const r=Pm(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}}js.registerPtyInputSender(vf);class BL{constructor(t){at(this,"daemonId");at(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(ms==null?void 0:ms.readyState)===WebSocket.OPEN}get connectionState(){return(ms==null?void 0:ms.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,n){return Ma(this.daemonId,t,n)}async sendInput(t,n){return Ma(this.daemonId,"cdp_remote_action",{action:t,params:n,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,ln&&(clearInterval(ln),ln=null);const n=async()=>{if(this.hasCommandChannel)try{const a=await Ma(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());js.emitScreenshot(this.daemonId,r)}}catch{}};n(),ln=setInterval(n,2e3)}stopScreenshots(t){ln&&(clearInterval(ln),ln=null)}}let es=null;function WL(e){return(!es||es.daemonId!==e)&&(es=new BL(e)),es}function OL({children:e}){const t=l.useRef(Pa()),n=Pa();t.current=n;const{setUserName:a}=ys(),r=l.useRef(a);r.current=a;const o=l.useRef(null),i=l.useRef(null),[,c]=l.useState("disconnected"),u=l.useCallback((f,x)=>{c(f),Aa==null||Aa(f,x)},[]),p=l.useRef(null),d=l.useRef(),m=l.useRef(Pu),h=l.useRef(!0),g=l.useRef(!1),k=l.useRef("initial_connect");return l.useEffect(()=>{h.current=!0,g.current=!1;function f(){var b,N;if(!h.current||((b=p.current)==null?void 0:b.readyState)===WebSocket.OPEN||((N=p.current)==null?void 0:N.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${fr}...`),fa("connect_attempt",{url:fr,reason:k.current,delayMs:m.current});let w;try{w=new WebSocket(fr)}catch(j){console.error("[Standalone WS] Failed to create WebSocket:",j),x();return}p.current=w,w.onopen=()=>{if(!h.current){w.close();return}u("connected"),m.current=Pu,fa("open",{url:fr,reason:k.current}),gs.resubscribeAll({sendData:il}),console.log("[Standalone WS] Connected")},ms=w,w.onmessage=j=>{var v,y;try{const C=JSON.parse(j.data);if((C.type==="command_result"||C.type==="error")&&C.requestId){const S=Qr.get(C.requestId);S&&(Qr.delete(C.requestId),C.type==="error"?S.reject(new Error(((v=C.data)==null?void 0:v.message)||"Command failed")):S.resolve(C.data));return}if(C.type==="session_output"){const S=C.sessionId||C.cliId||C.cliType;S&&js.emitSessionOutput(S,typeof C.data=="string"?C.data:"",typeof C.seq=="number"?C.seq:void 0);return}if(C.type==="runtime_snapshot"){js.emitRuntimeSnapshot(C.sessionId,typeof C.text=="string"?C.text:"",typeof C.seq=="number"?C.seq:0,!!C.truncated,typeof C.cols=="number"?C.cols:void 0,typeof C.rows=="number"?C.rows:void 0);return}if(C.type==="topic_update"){const S=C.update;S&&gs.publish(S);return}if(C.type==="status"||C.type==="initial_state"){const S=C.data;if(!S)return;const{injectEntries:A,markLoaded:M,getIdes:I}=t.current,D=S.instanceId||"standalone",P=I().find(L=>L.id===D),T=WL(D);js.register(D,T),js.setState(D,"connected"),u("connected",D),js.emitStatus(D,S);const H=Rr(S,{daemonId:D,existingDaemon:P,existingEntries:I()});Tu("ws_status",{type:C.type,daemonId:D,sessions:(S.sessions||[]).map(L=>({id:L.id,parentId:L.parentId,providerType:L.providerType,kind:L.kind,transport:L.transport,unread:L.unread,inboxBucket:L.inboxBucket,lastSeenAt:L.lastSeenAt,lastUpdated:L.lastUpdated,title:L.title})),recentLaunches:(S.recentLaunches||[]).map(L=>({id:L.id,providerType:L.providerType,kind:L.kind,workspace:L.workspace,lastLaunchedAt:L.lastLaunchedAt}))}),Tu("entries",{daemonId:D,entries:H.filter(L=>L.type!=="adhdev-daemon").map(L=>({id:L.id,type:L.type,unread:L.unread,inboxBucket:L.inboxBucket,lastSeenAt:L.lastSeenAt,lastUpdated:L.lastUpdated,sessionId:L.sessionId}))}),H.length>0&&A(H,{authoritativeDaemonIds:[D]}),M(),i.current!==D&&((y=o.current)==null||y.call(o),i.current=D,o.current=gs.subscribe({sendData:il},D,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${D}`,params:{includeSessions:!0}},L=>{if(L.topic!=="daemon.metadata")return;const R=t.current.getIdes(),U=R.find($=>$.id===D),E=Rr(L.status,{daemonId:D,existingDaemon:U,existingEntries:R,timestamp:L.timestamp});E.length>0&&t.current.injectEntries(E,{authoritativeDaemonIds:[D]}),L.userName&&r.current&&r.current(L.userName)}))}}catch(C){console.error("[Standalone WS] Parse error:",C)}},w.onclose=j=>{h.current&&(es==null||es.stopScreenshots(),es&&js.setState(es.daemonId,"disconnected"),u("disconnected"),p.current=null,k.current=`close:${j.code}${j.wasClean?":clean":":unclean"}`,fa("close",{code:j.code,reason:j.reason||"",wasClean:j.wasClean}),x())},w.onerror=j=>{g.current||!h.current||(k.current="error",fa("error",{message:j instanceof Event?"event":String(j),readyState:w.readyState}),console.warn("[Standalone WS] Error, will reconnect:",j))}}function x(){if(!h.current)return;clearTimeout(d.current);const w=m.current;console.log(`[Standalone WS] Reconnecting in ${w}ms...`),fa("schedule_reconnect",{reason:k.current,delayMs:w}),d.current=setTimeout(()=>{m.current=Math.min(m.current*1.5,HL),f()},w)}return f(),()=>{var w;h.current=!1,g.current=!0,(w=o.current)==null||w.call(o),o.current=null,i.current=null,clearTimeout(d.current),p.current&&(p.current.onerror=null,p.current.onclose=null,p.current.close(),p.current=null,ms=null),es&&(es.stopScreenshots(),js.unregister(es.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function UL({children:e}){const[t,n]=l.useState("disconnected"),[a,r]=l.useState(null);l.useEffect(()=>(Aa=(i,c)=>{n(i),c&&r(c)},()=>{Aa=null}),[]);const o=l.useMemo(()=>{const i=t==="connected",c=FL(t),u={};return a&&(u[a]=c),u.standalone=c,{wsStatus:t,isConnected:i,connectionStates:u,usesP2P:!1}},[t,a]);return s.jsx(db,{connectionOverrides:o,children:s.jsx(OL,{children:e})})}const yf="adhdev_standalone_font_preferences",gn={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},wo=[{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"}],Ha=[{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"}],qL=new Set(wo.map(e=>e.id)),GL=new Set(Ha.map(e=>e.id));function As(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Ar("chat",t.chat),code:Ar("code",t.code),terminal:Ar("terminal",t.terminal)}}function Ar(e,t){const n=gn[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"?qL:GL).has(r)?r==="custom"?o?{preset:"custom",customFamily:o}:n:{preset:r}:n}function Mr(e,t){var r;const n=Ar(e,t);if(n.preset==="custom"&&n.customFamily)return n.customFamily;const a=e==="chat"?wo:Ha;return((r=a.find(o=>o.id===n.preset))==null?void 0:r.family)||a[0].family}function zL(e){const t=As(e),n=Mr("chat",t.chat),a=Mr("code",t.code),r=Mr("terminal",t.terminal);return{"--chat-font-family":n,"--chat-code-font-family":a,"--chat-terminal-font-family":r,"--chat-tool-font-family":r}}function dn(e,t=document.documentElement){const n=As(e),a=zL(n);t.setAttribute("data-standalone-fonts","custom");for(const[r,o]of Object.entries(a))t.style.setProperty(r,o);return n}function ll(e){const t=As(e);try{localStorage.setItem(yf,JSON.stringify(t))}catch{}return t}function KL(){try{const e=localStorage.getItem(yf);if(e)return As(JSON.parse(e))}catch{}return gn}function VL(){return dn(KL())}function ba(e,t){var a;const n=e==="chat"?wo:Ha;return((a=n.find(r=>r.id===t))==null?void 0:a.label)||n[0].label}function YL({children:e}){const t=Jn(),n=dl(),{t:a}=Ce("common"),r=l.useMemo(()=>[{id:"dashboard",path:"/dashboard",icon:s.jsx(Gu,{}),label:a("standalone.nav.dashboard"),active:n.pathname.startsWith("/dashboard"),onSelect:()=>t("/dashboard")},{id:"machine",path:"/machines",icon:s.jsx(Ys,{}),label:"Burrow",active:n.pathname.startsWith("/machines"),onSelect:()=>t("/machines")},{id:"mesh",path:"/mesh",icon:s.jsx(ns,{}),label:"Mesh",active:n.pathname.startsWith("/mesh")||n.pathname.startsWith("/setup"),onSelect:()=>t("/mesh")},{id:"settings",path:"/settings",icon:s.jsx(Xr,{}),label:a("standalone.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("standalone.nav.docs")}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(Ku,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:a("standalone.nav.docs")},{id:"about",label:a("standalone.nav.about"),icon:s.jsx(hl,{}),active:n.pathname==="/about",onSelect:()=>t("/about"),title:a("standalone.nav.about")}],[n.pathname,t,a]);return s.jsx(lj,{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.47"]}),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 QL(){const e=Jn(),{sendCommand:t}=vt(),{ides:n}=ys(),a=l.useMemo(()=>n.filter(r=>r.daemonMode||r.type==="adhdev-daemon").map(r=>r),[n]);return s.jsx(LL,{daemons:a,features:df,sendCommand:t,unwrapResult:r=>r,normalizeMesh:r=>r,onClose:()=>e("/mesh")})}const JL=[{icon:s.jsx(Ys,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Cn,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Qu,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(ws,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(Ta,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Ku,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],XL=[{icon:s.jsx(Bb,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Gu,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Xn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Rb,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(zu,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(_b,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],ZL=[{feature:"Agent chat relay",selfhost:!0,cloud:!0},{feature:"Live IDE screenshots",selfhost:!0,cloud:!0},{feature:"Remote IDE control",selfhost:!0,cloud:!0},{feature:"Multi-IDE monitoring",selfhost:!0,cloud:!0},{feature:"Extension and CLI agents",selfhost:!0,cloud:!0},{feature:"Access from any network",selfhost:!1,cloud:!0},{feature:"WebRTC P2P streaming",selfhost:!1,cloud:!0},{feature:"Mobile push notifications",selfhost:!1,cloud:!0},{feature:"REST API and webhooks",selfhost:!1,cloud:!0},{feature:"Team collaboration",selfhost:!1,cloud:!0},{feature:"Multi-machine burrows",selfhost:!1,cloud:!0},{feature:"SSO, RBAC, audit logs",selfhost:!1,cloud:!0}];function e2(){const{t:e}=Ce("common");return s.jsxs(Oa,{icon:s.jsx(hl,{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.47"]}),children:[s.jsx(ht,{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(ht,{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:JL.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(ht,{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:Tm.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:Im.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:Dm.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(ht,{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:XL.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(ht,{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:ZL.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(co,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:e("standalone.about.cloudOptional"),description:e("standalone.about.cloudOptionalDescription"),action:s.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:e("standalone.about.compareCloud")}),s.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[s.jsx(Yb,{size:14,className:"mr-1"}),e("standalone.about.discord")]})]})})]})}function vi(e,t,n){return{...e,[t]:n}}function yi({surface:e,title:t,description:n,value:a,options:r,onChange:o}){const{t:i}=Ce("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(pj,{value:a.preset,onChange:c=>{const u=c.target.value;o(u==="custom"?{preset:"custom",customFamily:a.customFamily||""}:{preset:u})},children:r.map(c=>s.jsx("option",{value:c.id,children:c.label},c.id))}),a.preset==="custom"&&s.jsx(fs,{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:Mr(e,a)})]})]})]})}function t2({value:e,savedValue:t,saving:n=!1,error:a,notice:r,onChange:o,onSave:i,onResetToSaved:c,onResetToDefaults:u}){const{t:p}=Ce("common"),d=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(Dt,{variant:"error",children:a}),r&&s.jsx(Dt,{variant:"success",children:r}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(yi,{surface:"chat",title:p("standalone.fonts.chat"),description:p("standalone.fonts.chatDescription"),value:e.chat,options:wo,onChange:m=>o(vi(e,"chat",m))}),s.jsx(yi,{surface:"code",title:p("standalone.fonts.code"),description:p("standalone.fonts.codeDescription"),value:e.code,options:Ha,onChange:m=>o(vi(e,"code",m))}),s.jsx(yi,{surface:"terminal",title:p("standalone.fonts.terminal"),description:p("standalone.fonts.terminalDescription"),value:e.terminal,options:Ha,onChange:m=>o(vi(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: ",ba("chat",e.chat.preset)," · Code: ",ba("code",e.code.preset)," · Terminal: ",ba("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[p("standalone.fonts.defaults")," ",ba("chat",gn.chat.preset)," / ",ba("code",gn.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(Hs,{type:"button",variant:"primary",size:"sm",onClick:i,disabled:n||!d,children:p(n?"standalone.fonts.saving":"standalone.fonts.saveFontSettings")}),s.jsx(Hs,{type:"button",variant:"secondary",size:"sm",onClick:c,disabled:n||!d,children:p("standalone.fonts.revertToSaved")}),s.jsx(Hs,{type:"button",variant:"secondary",size:"sm",onClick:u,disabled:n,children:p("standalone.fonts.resetToDefaults")})]})]})}function s2(){const{t:e}=Ce("common"),{ides:t}=ys(),n=t.find(z=>z.type==="adhdev-daemon"),a=(n==null?void 0:n.detectedIdes)||[],{sendCommand:r}=vt(),{userName:o}=ys(),[i,c]=l.useState(o||""),[u,p]=l.useState(null),[d,m]=l.useState(null),[h,g]=l.useState(gn),[k,f]=l.useState(!1),[x,w]=l.useState(""),[b,N]=l.useState(""),[j,v]=l.useState("127.0.0.1"),[y,C]=l.useState(""),[S,A]=l.useState(""),[M,I]=l.useState(""),[D,P]=l.useState(""),[T,H]=l.useState(""),[L,R]=l.useState(!1),U=async()=>{const X=await(await Ns("/auth/session")).json();p(X)},E=async()=>{const X=await(await Ns("/api/v1/standalone/preferences")).json();m(X),v(X.standaloneBindHost);const O=As(X.standaloneFontPreferences);g(O),dn(O),ll(O)};l.useEffect(()=>{o!==void 0&&c(o)},[o]),l.useEffect(()=>{Promise.all([U(),E()]).catch(z=>{P(z instanceof Error?z.message:String(z))})},[]),l.useEffect(()=>{dn(h)},[h]);const $=z=>{const X=z.target.value.trim();n!=null&&n.id&&X!==o&&r(n.id,"set_user_name",{userName:X}).catch(console.error)},[_,q]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),B=z=>{q(z);try{localStorage.setItem("adhdev_sound",z?"1":"0")}catch{}},W=async()=>{w(""),N(""),f(!0);try{const z=As(h),X=await Ns("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:z})}),O=await X.json();if(!X.ok)throw new Error((O==null?void 0:O.error)||"Failed to save standalone font preferences");const Q=As(O.standaloneFontPreferences);m(O),g(Q),dn(Q),ll(Q),N(e("standalone.settings.fontsSaved"))}catch(z){w(z instanceof Error?z.message:String(z))}finally{f(!1)}},V=()=>{const z=As(d==null?void 0:d.standaloneFontPreferences);w(""),N(""),g(z),dn(z)},ne=()=>{w(""),N(""),g(gn),dn(gn)},ae=async()=>{P(""),H(""),R(!0);try{const z=await Ns("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:j})}),X=await z.json();if(!z.ok)throw new Error((X==null?void 0:X.error)||"Failed to save standalone network preference");m(X),v(X.standaloneBindHost),H(X.standaloneBindHost==="0.0.0.0"?e("standalone.settings.networkSavedAll"):e("standalone.settings.networkSavedLocal"))}catch(z){P(z instanceof Error?z.message:String(z))}finally{R(!1)}},he=async()=>{if(P(""),H(""),S.trim().length<4){P(e("standalone.settings.passwordTooShort"));return}if(S!==M){P(e("standalone.settings.passwordMismatch"));return}R(!0);try{const z=await Ns("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,newPassword:S})}),X=await z.json();if(!z.ok)throw new Error((X==null?void 0:X.error)||"Failed to save password");p(X),await E(),C(""),A(""),I(""),H(u!=null&&u.hasPasswordAuth?e("standalone.settings.passwordUpdated"):e("standalone.settings.passwordEnabled")),xf()}catch(z){P(z instanceof Error?z.message:String(z))}finally{R(!1)}},Z=async()=>{P(""),H(""),R(!0);try{const z=await Ns("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,clear:!0})}),X=await z.json();if(!z.ok)throw new Error((X==null?void 0:X.error)||"Failed to clear password");p(X),await E(),C(""),A(""),I(""),H(e("standalone.settings.passwordDisabled"))}catch(z){P(z instanceof Error?z.message:String(z))}finally{R(!1)}};return s.jsxs(Oa,{icon:s.jsx(Xr,{className:"text-text-primary"}),title:e("standalone.settings.title"),subtitle:e("standalone.settings.subtitle"),widthClassName:"max-w-5xl",children:[s.jsx(Dt,{variant:"info",children:e("standalone.settings.infoNotice")}),(u==null?void 0:u.publicHostWarning)&&s.jsx(Dt,{variant:"warning",children:e("standalone.settings.publicHostWarning")}),s.jsx(ht,{title:e("standalone.settings.daemonSection"),description:e("standalone.settings.daemonDescription"),children:s.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.versionLabel")}),s.jsxs("span",{className:"font-mono text-xs",children:["v","1.0.47"]}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.statusLabel")}),s.jsx("span",{className:n?"text-green-400":"text-yellow-400",children:e(n?"standalone.settings.statusRunning":"standalone.settings.statusNotConnected")}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.currentBindLabel")}),s.jsx("span",{className:"font-mono text-xs",children:(d==null?void 0:d.currentBindHost)||(u==null?void 0:u.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.defaultBindLabel")}),s.jsx("span",{className:"font-mono text-xs",children:(d==null?void 0:d.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.authLabel")}),s.jsx("span",{className:"text-xs",children:u!=null&&u.hasPasswordAuth?e("standalone.settings.authPassword"):u!=null&&u.hasTokenAuth?e("standalone.settings.authToken"):e("standalone.settings.authNone")})]})}),s.jsx(ht,{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:j==="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:j==="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(Hs,{type:"button",variant:"primary",size:"sm",onClick:()=>{ae()},disabled:L,children:e(L?"standalone.settings.saving":"standalone.settings.saveNetworkMode")}),s.jsx("span",{className:"text-xs text-text-muted",children:e("standalone.settings.networkRestartHint",{host:(d==null?void 0:d.currentBindHost)||(u==null?void 0:u.boundHost)||"127.0.0.1"})})]})]})}),s.jsx(ht,{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:u!=null&&u.hasPasswordAuth?e("standalone.settings.passwordSet"):e("standalone.settings.passwordNotSet")}),D&&s.jsx(Dt,{variant:"error",children:D}),T&&s.jsx(Dt,{variant:"success",children:T}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx(fs,{type:"password",placeholder:u!=null&&u.hasPasswordAuth?e("standalone.settings.currentPasswordPlaceholder"):e("standalone.settings.currentPasswordFirstTimePlaceholder"),value:y,onChange:z=>C(z.target.value)}),s.jsx(fs,{type:"password",placeholder:u!=null&&u.hasPasswordAuth?e("standalone.settings.newPasswordPlaceholder"):e("standalone.settings.newPasswordFirstTimePlaceholder"),value:S,onChange:z=>A(z.target.value)}),s.jsx(fs,{type:"password",className:"md:col-span-2",placeholder:e("standalone.settings.confirmPasswordPlaceholder"),value:M,onChange:z=>I(z.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Hs,{type:"button",variant:"primary",size:"sm",onClick:()=>{he()},disabled:L,children:L?e("standalone.settings.saving"):u!=null&&u.hasPasswordAuth?e("standalone.settings.updatePassword"):e("standalone.settings.enablePassword")}),(u==null?void 0:u.hasPasswordAuth)&&s.jsx(Hs,{type:"button",variant:"danger",size:"sm",onClick:()=>{Z()},disabled:L,children:e("standalone.settings.disablePassword")})]})]})}),s.jsx(ht,{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-1.5",children:a.map(z=>s.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${z.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:z.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:z.type})]},z.type))})}),s.jsx(ht,{title:e("standalone.settings.machineSection"),description:e("standalone.settings.machineDescription"),children:s.jsx(wj,{ides:t,emptyMessage:e("standalone.settings.daemonNotConnected")})}),s.jsx(ht,{title:e("standalone.settings.appearanceSection"),description:e("standalone.settings.appearanceDescription"),children:s.jsx(Wj,{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(t2,{value:h,savedValue:As(d==null?void 0:d.standaloneFontPreferences),saving:k,error:x,notice:b,onChange:g,onSave:()=>{W()},onResetToSaved:V,onResetToDefaults:ne})]})})}),s.jsx(ht,{title:e("standalone.settings.notificationsSection"),description:e("standalone.settings.notificationsDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(bj,{}),s.jsx(cn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Vb,{size:15})," ",e("standalone.settings.soundEffectsLabel")]}),description:e("standalone.settings.soundEffectsDescription"),checked:_,onChange:B})]})}),s.jsx(ht,{title:e("standalone.settings.profileSection"),description:e("standalone.settings.profileDescription"),children:s.jsx("div",{className:"flex flex-col gap-3",children:s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[s.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[s.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[s.jsx(Lb,{size:16,className:"text-text-secondary"})," ",e("standalone.settings.displayNameLabel")]}),s.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:e("standalone.settings.displayNameHint")})]}),s.jsx(fs,{type:"text",className:"w-48 text-right",placeholder:e("standalone.settings.displayNamePlaceholder"),value:i,onChange:z=>c(z.target.value),onBlur:$,onKeyDown:z=>{z.key==="Enter"&&z.currentTarget.blur()}})]})})})]})}const n2=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],ya="adhdev_onboarding_done",a2=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],r2={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function o2({onDone:e}){const{t}=Ce("common"),[n,a]=l.useState([]),[r,o]=l.useState(new Set(n2)),[i,c]=l.useState(!0),[u,p]=l.useState(null),[d,m]=l.useState(!1),[h,g]=l.useState(null),[k,f]=l.useState("all");l.useEffect(()=>{let y=!1;const C=window.location.hostname==="localhost"?"/registry":"https://api.adhf.dev/api/v1/registry";return fetch(`${C}/providers?sort=popular&limit=100`).then(S=>{if(!S.ok)throw new Error(`HTTP ${S.status}`);return S.json()}).then(S=>{y||a(S.providers??[])}).catch(S=>{y||p(S instanceof Error?S.message:String(S))}).finally(()=>{y||c(!1)}),()=>{y=!0}},[]);const x=n.filter(y=>k==="all"||y.category===k),w=["cli","ide","extension","acp"].map(y=>({category:y,items:x.filter(C=>C.category===y)})).filter(y=>y.items.length>0),b=l.useCallback(y=>{o(C=>{const S=new Set(C);return S.has(y)?S.delete(y):S.add(y),S})},[]),N=l.useCallback(async()=>{if(r.size===0){localStorage.setItem(ya,"1"),e();return}m(!0);const y=[];for(const C of r)try{const A=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:C})})).json().catch(()=>({}));y.push({type:C,ok:!!A.success,error:A.error})}catch(S){y.push({type:C,ok:!1,error:S instanceof Error?S.message:String(S)})}g(y),m(!1),y.every(C=>C.ok)&&localStorage.setItem(ya,"1")},[r,e]),j=l.useCallback(()=>{localStorage.setItem(ya,"1"),e()},[e]),v=l.useCallback(()=>{h&&h.every(y=>y.ok)?e():d||j()},[h,d,e,j]);return s.jsx(Ep,{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(Hs,{variant:"secondary",size:"sm",onClick:j,disabled:d,children:t("standalone.onboarding.skip")}),s.jsx(Hs,{variant:"primary",size:"sm",onClick:()=>{h?(localStorage.setItem(ya,"1"),e()):N()},disabled:d||!h&&r.size===0,children:d?t("standalone.onboarding.installing"):h?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&&!u&&n.length>0&&s.jsx("div",{className:"flex gap-1 flex-wrap border-b border-border-subtle pb-2",children:a2.map(y=>{const C=y.key==="all"?n.length:n.filter(S=>S.category===y.key).length;return C===0&&y.key!=="all"?null:s.jsxs("button",{onClick:()=>f(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:["(",C,")"]})]},y.key)})}),i&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.loadingRegistry")}),!i&&u&&s.jsx(Dt,{variant:"error",children:t("standalone.onboarding.loadError",{error:u})}),!i&&!u&&x.length===0&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.noProviders")}),!i&&!u&&x.length>0&&s.jsx("div",{className:"flex flex-col gap-4",children:w.map(y=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:r2[y.category]??y.category}),s.jsx("div",{className:"grid gap-1.5",children:y.items.map(C=>{var D,P;const S=r.has(C.type),A=h==null?void 0:h.find(T=>T.type===C.type),M=((D=C.manifest)==null?void 0:D.icon)??"📦",I=((P=C.manifest)==null?void 0:P.details)??"";return s.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${S?"bg-accent-primary/[0.06] border-accent-primary/30":"bg-bg-glass border-border-subtle hover:bg-bg-glass-hover"}`,children:[s.jsx("input",{type:"checkbox",checked:S,onChange:()=>b(C.type),disabled:d,className:"shrink-0"}),s.jsx("span",{className:"text-base shrink-0",children:M}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[13px] font-medium text-text-primary truncate",children:C.displayName}),I&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:I})]}),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"})})]},C.type)})})]},y.category))})]})})}function i2(){try{return localStorage.getItem(ya)==="1"}catch{return!1}}JC();Lj();Pw();VL();const l2=$u({baseUrl:"",getToken:rc});function c2({children:e}){const{t}=Ce("common"),[n,a]=l.useState(null),[r,o]=l.useState(!0),[i,c]=l.useState(""),[u,p]=l.useState(""),[d,m]=l.useState(!1),h=async()=>{o(!0),p("");try{const f=await(await Ns("/auth/session")).json();a(f)}catch(k){p(k instanceof Error?k.message:String(k))}finally{o(!1)}};l.useEffect(()=>{h()},[]),l.useEffect(()=>{if(!n||n.required&&!n.authenticated)return;let k=!1;return(async()=>{try{const f=await Ns("/api/v1/standalone/preferences");if(!f.ok)return;const x=await f.json();if(k)return;const w=As(x.standaloneFontPreferences);dn(w),ll(w)}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 f=await Ns("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),x=await f.json();if(!f.ok)throw new Error((x==null?void 0:x.error)||"Login failed");a(x),c(""),xf()}catch(f){p(f instanceof Error?f.message:String(f))}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(fs,{type:"password",value:i,onChange:k=>c(k.target.value),placeholder:t("standalone.auth.passwordPlaceholder"),autoFocus:!0}),s.jsx(Hs,{type:"submit",variant:"primary",disabled:d||!i,className:"justify-center",children:t(d?"standalone.auth.signingIn":"standalone.auth.unlock")})]}):s.jsx(Dt,{variant:"warning",children:t("standalone.auth.noPasswordEnabled")}),u&&s.jsx(Dt,{variant:"error",children:u})]})}):s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:t("standalone.auth.loadError",{error:u||"unknown error"})})}function Du(){const{t:e}=Ce("common"),{ides:t,initialLoaded:n}=ys();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(Ci,{to:`/machines/${a.id}`,replace:!0}):s.jsx(Ci,{to:"/dashboard",replace:!0})}function d2(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let n=!1;if(!i2())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(o2,{onDone:()=>t(!1)}):null}function u2(){const{t:e}=Ce("common"),{ides:t}=ys(),n=l.useMemo(()=>{for(const d of t)if(d.activeInteractivePrompt)return d.instanceId??d.id;return null},[t]),{promptSession:a,hasActivePrompt:r,responseError:o,isSubmitting:i,submit:c,cancel:u,reopen:p}=Om(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(dp,{promptSession:a,isSubmitting:i,error:o,onSubmit:c,onCancel:u})]}):null}function p2(){const e=l.useMemo(()=>({sendCommand:Ma,sendData:il,sendPtyInput:vf}),[]);return s.jsx(Kf,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(mb,{client:l2,children:s.jsx(c2,{children:s.jsx(UL,{children:s.jsx(fb,{value:e,children:s.jsxs(vb,{sendDaemonCommand:Ma,children:[s.jsx(u2,{}),s.jsxs(YL,{children:[s.jsx(d2,{}),s.jsxs(Vf,{children:[s.jsx(Rs,{path:"/dashboard",element:s.jsx(KT,{})}),s.jsx(Rs,{path:"/machine",element:s.jsx(Du,{})}),s.jsx(Rs,{path:"/machines/:id",element:s.jsx(nI,{})}),s.jsx(Rs,{path:"/machines",element:s.jsx(Du,{})}),s.jsx(Rs,{path:"/about",element:s.jsx(e2,{})}),s.jsx(Rs,{path:"/settings",element:s.jsx(s2,{})}),s.jsx(Rs,{path:"/mesh",element:s.jsx(PL,{children:s.jsx(AL,{})})}),s.jsx(Rs,{path:"/setup",element:s.jsx(QL,{})}),s.jsx(Rs,{path:"*",element:s.jsx(Ci,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}US({connectionManager:js});Yf(document.getElementById("root")).render(s.jsx(p2,{}));
|
|
116
|
+
Node removal cleanup policy: ${ue}`))return;const ee=e.__sourceDaemonId||n;try{const Le=await o(ee,"remove_mesh_node",{meshId:e.id,nodeId:J}),Xe=i(Le);if((Xe==null?void 0:Xe.success)===!1)throw new Error(Xe.error||"Remove failed");f===J&&x(null),await m(),g||await h(t)}catch(Le){k((Le==null?void 0:Le.message)||"Remove node failed")}}async function Y(J){if(!e)return;const ge={...rl(e),...J},ue=e.__sourceDaemonId||n;try{W(!0),k(null);const ee=await o(ue,"update_mesh",{meshId:e.id,policy:ge}),De=i(ee);if((De==null?void 0:De.success)===!1)throw new Error(De.error||"Policy update failed");await m()}catch(ee){k((ee==null?void 0:ee.message)||"Policy update failed")}finally{W(!1)}}const[G,te]=l.useState(null);async function me(J,ge){if(!t)return;const ue=(e==null?void 0:e.__sourceDaemonId)||n;try{te(J.id),k(null);const ee=await o(ue,"update_mesh_node",{meshId:t,nodeId:J.id,policy:{slots:ge}}),De=i(ee);if((De==null?void 0:De.success)===!1){k(De.error||"Node slots update failed");return}await m()}catch(ee){k((ee==null?void 0:ee.message)||"Node slots update failed")}finally{te(null)}}const[K,be]=l.useState(null);async function re(J,ge){if(!t)return;const ue=(e==null?void 0:e.__sourceDaemonId)||n,ee=ge.map(De=>De.trim()).filter(Boolean);try{be(J.id),k(null);const De=await o(ue,"update_mesh_node",{meshId:t,nodeId:J.id,capabilities:ee}),Le=i(De);if((Le==null?void 0:Le.success)===!1){k(Le.error||"Node tag update failed");return}await m()}catch(De){k((De==null?void 0:De.message)||"Node tag update failed")}finally{be(null)}}async function de(){if(!n||!t)return;const ge={...(e==null?void 0:e.coordinator)||{}};V.override.trim()?ge.systemPromptOverride=V.override:delete ge.systemPromptOverride,V.append.trim()?ge.systemPromptAppend=V.append:delete ge.systemPromptAppend,delete ge.systemPromptSuffix;try{he(!0),k(null);const ue=await o(n,"update_mesh",{meshId:t,coordinator:ge}),ee=i(ue);if((ee==null?void 0:ee.success)===!1){k(ee.error||"Coordinator prompt save failed");return}await m()}catch(ue){k((ue==null?void 0:ue.message)||"Coordinator prompt save failed")}finally{he(!1)}}async function we(J){if(!n||!t)return;const ge=(Z[J.id]||"").trim();try{O(J.id),k(null);const ue=await o(n,"update_mesh_node",{meshId:t,nodeId:J.id,systemPrompt:ge}),ee=i(ue);if((ee==null?void 0:ee.success)===!1){k(ee.error||"Node instruction save failed");return}await m()}catch(ue){k((ue==null?void 0:ue.message)||"Node instruction save failed")}finally{O(null)}}async function Re(J){if(!(!e||!J)){k(null),q(null);try{$(!0);const ge=(e.nodes||[]).find(De=>zs(String(De.daemon_id||De.daemonId||""),J)),ue=await o(J,"set_mesh_host",{meshId:e.id,hostDaemonId:J,...ge!=null&&ge.id?{hostNodeId:ge.id}:{}}),ee=i(ue);if((ee==null?void 0:ee.success)===!1){k(ee.error||"Setting the mesh host failed");return}await m()}catch(ge){k((ge==null?void 0:ge.message)||"Setting the mesh host failed")}finally{$(!1)}}}async function F(){if(e){k(null),q(null);try{U(!0);const J=c?await c(a,e.id,e):null,ge=u(a,e.id,e,e.nodes||[],J);if("error"in ge)throw new Error(ge.error);const ue=await p(ge.targetDaemonId,{meshId:e.id,inlineMesh:ge.inlineMesh,coordinatorNodeId:ge.coordinatorNodeId,cliType:H.trim()||void 0});q(ue.message)}catch(J){k((J==null?void 0:J.message)||"Coordinator launch failed")}finally{U(!1)}}}return{selectedNodeId:f,setSelectedNodeId:x,showAddNode:w,setShowAddNode:b,nodeWorkspace:N,setNodeWorkspace:j,nodeProviderPriority:v,setNodeProviderPriority:y,nodeDaemonId:C,setNodeDaemonId:S,nodeCustomPath:A,setNodeCustomPath:M,nodePickerWorkspaces:ke,nodePickerProviders:Se,nodeOnboardingPlan:I,nodePlanLoading:P,coordinatorCliType:H,setCoordinatorCliType:L,launchingCoordinator:R,launchResult:_,settingMeshHost:E,savingPolicy:B,coordinatorPromptDraft:V,setCoordinatorPromptDraft:ne,savingCoordinatorPrompt:ae,nodeSystemPromptDrafts:Z,setNodeSystemPromptDrafts:z,savingNodeSystemPromptId:X,savingNodeSlotsId:G,savingNodeCapabilitiesId:K,handleAddNode:ve,handleRemoveNode:xe,handleUpdatePolicy:Y,handleUpdateNodeSlots:me,handleUpdateNodeCapabilities:re,handleSaveCoordinatorPrompt:de,handleSaveNodeSystemPrompt:we,handleLaunchCoordinator:F,handleSetMeshHost:Re}}function mL(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 hL({primaryDaemonId:e,activeDaemonId:t,sendCommand:n,unwrapResult:a,loadLiveMesh:r,resolveCommandTarget:o}){const[i,c]=l.useState([]),[u,p]=l.useState(null),[d,m]=l.useState(!1),[h,g]=l.useState(null),k=l.useCallback(async x=>{if(!e||!x){c([]);return}try{const w=await n(e,"get_mesh_queue",{meshId:x});c(w!=null&&w.success?Array.isArray(w.queue)?w.queue:[]:[])}catch{c([])}},[e,n]);async function f(x){var w,b;if(x){m(!0),g(null);try{const N=r?await r(t,x.id,x):null,j=o(t,x.id,x,x.nodes||[],N);if("error"in j)throw new Error(j.error);const v=await n(j.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 C=Array.isArray(((w=y==null?void 0:y.result)==null?void 0:w.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(mL(C))}catch(N){g((N==null?void 0:N.message)||"Queue load failed")}finally{m(!1)}}}return{meshQueue:i,setMeshQueue:c,queueSummary:u,queueLoading:d,queueError:h,loadQueue:k,handleLoadQueue:f}}function fL(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}const bf=new Map;function gf(e){return e?bf.get(e)??null:null}function bL(e,t){!e||!t||bf.set(e,t)}function gL({selectedMeshId:e,loadMeshStatus:t,extractStatus:n,normalizeNode:a,gateIncompleteGraph:r}){const[o,i]=l.useState(()=>gf(e)),[c,u]=l.useState(!1),[p,d]=l.useState(null),[m,h]=l.useState("idle"),[g,k]=l.useState(!1),f=l.useRef(!1);async function x(w,b=e,N=!1){if(!(!w||!b))try{u(!N&&o===null),h(N?"settling":"first_paint"),d(null);const j=await t(w,b,{refresh:N,retryProfile:N?"settled":"interactive"});k(fL(j));const v=n(j),y=a&&v?{...v,nodes:(v.nodes??[]).map(C=>a(C,v.meshId??b,""))}:v;if(y){if(r&&!N&&o!==null&&!mM(Bh(y))){h("settling"),f.current||(f.current=!0,Promise.resolve().then(()=>x(w,b,!0)).finally(()=>{f.current=!1}));return}i(y),bL(b,y),h("settled")}else i(null),d("mesh_status returned an unexpected payload."),h("idle")}catch(j){o||i(null),d((j==null?void 0:j.message)||"Failed to load mesh graph"),h("idle")}finally{u(!1)}}return{meshGraphStatus:o,setMeshGraphStatus:i,graphLoading:c,graphError:p,setGraphError:d,graphProvenance:m,graphBootstrapFallback:g,loadGraph:x}}function Mu(e){return!e||e.hostSynthesized?{hostDaemonId:"",hostNodeId:""}:{hostDaemonId:String(e.hostDaemonId||""),hostNodeId:String(e.hostNodeId||"")}}function xL(e,t,n,a,r){if(!e.length)return"";const o=String(r||"");if(o){const u=e.find(p=>zs(p.id,o));return u?u.id:o}const i=t.find(u=>u.role==="host"),c=String((i==null?void 0:i.daemon_id)||(i==null?void 0:i.daemonId)||"");if(c){const u=e.find(p=>zs(p.id,c));if(u)return u.id}return""}function vL(e){var r;if(!e)return"null";const t=[...e.nodes??[]].map(o=>{var i,c,u,p,d,m;return[o.nodeId,o.health,((i=o.git)==null?void 0:i.branch)??"",((c=o.git)==null?void 0:c.headCommit)??"",(u=o.git)!=null&&u.dirty?"1":"0",((p=o.git)==null?void 0:p.ahead)??0,((d=o.git)==null?void 0:d.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 yL=4,wL=3e4;function kL(){return{lastFingerprint:null,stableTicks:0,backedOff:!1}}function ol(e){e.stableTicks=0,e.backedOff=!1}function SL(e,t){const n=vL(t);return e.lastFingerprint===null?(e.lastFingerprint=n,e.backedOff):n!==e.lastFingerprint?(e.lastFingerprint=n,ol(e),!1):(e.stableTicks+=1,e.stableTicks>=yL&&(e.backedOff=!0),e.backedOff)}function CL(e,t){return e.backedOff?Math.max(t,wL):t}const jL=7e3,NL=45e3;function AL(){const e=rI(),{sendCommand:t,sendData:n,daemons:a,userName:r,loadMeshStatus:o,launchCoordinator:i,loadLiveMesh:c,extractStatus:u,unwrapResult:p,normalizeMesh:d,normalizeNode:m,resolveCommandTarget:h,features:g,gateIncompleteGraph:k}=e,f=ea(),x=a[0],w=(x==null?void 0:x.id)||"",b=l.useMemo(()=>((x==null?void 0:x.availableProviders)||[]).filter(ot=>ot.category==="cli").map(ot=>({id:ot.type||ot.id,name:ot.displayName||ot.name||ot.type,meshCoordinator:ot.meshCoordinator})),[x]),N=l.useMemo(()=>en((x==null?void 0:x.availableProviders)||[]),[x]),{meshes:j,selectedMeshId:v,setSelectedMeshId:y,loading:C,error:S,setError:A,showCreate:M,setShowCreate:I,createName:D,setCreateName:P,createRepoIdentity:T,setCreateRepoIdentity:H,createRepoRemoteUrl:L,setCreateRepoRemoteUrl:R,newMeshDaemonId:U,setNewMeshDaemonId:E,newMeshWorkspace:$,setNewMeshWorkspace:_,createPickerWorkspaces:q,createOnboardingPlan:B,createPlanLoading:W,creating:V,createWarning:ne,setCreateWarning:ae,loadMeshes:he,handleCreate:Z,handleDelete:z,cancelCreate:X}=ff({daemons:a,primaryDaemonId:w,sendCommand:t,unwrapResult:p,normalizeMesh:d,features:g,loadDaemonMetadata:f}),O=j.find(qe=>qe.id===v)||null,{meshGraphStatus:Q,setMeshGraphStatus:ke,graphLoading:Se,graphError:ve,setGraphError:xe,loadGraph:Y}=gL({selectedMeshId:v,loadMeshStatus:o,extractStatus:u,normalizeNode:m,gateIncompleteGraph:k}),[G,te]=l.useState(""),[me,K]=l.useState(""),be=g.meshHostDaemonSection?G:w,{meshQueue:re,loadQueue:de}=hL({primaryDaemonId:w,activeDaemonId:be,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:h}),{selectedNodeId:we,setSelectedNodeId:Re,showAddNode:F,setShowAddNode:J,nodeWorkspace:ge,setNodeWorkspace:ue,nodeProviderPriority:ee,setNodeProviderPriority:De,nodeDaemonId:Le,setNodeDaemonId:Xe,nodeCustomPath:ce,setNodeCustomPath:Ee,nodePickerWorkspaces:Fe,nodePickerProviders:et,nodeOnboardingPlan:Ae,nodePlanLoading:Je,coordinatorCliType:bt,setCoordinatorCliType:it,launchingCoordinator:yt,launchResult:se,savingPolicy:oe,coordinatorPromptDraft:pe,setCoordinatorPromptDraft:ye,savingCoordinatorPrompt:le,nodeSystemPromptDrafts:Me,setNodeSystemPromptDrafts:_e,savingNodeSystemPromptId:Te,savingNodeSlotsId:Ue,savingNodeCapabilitiesId:Ge,handleAddNode:Ye,handleRemoveNode:Be,handleUpdatePolicy:Ve,handleUpdateNodeSlots:st,handleUpdateNodeCapabilities:$e,handleSaveCoordinatorPrompt:fe,handleSaveNodeSystemPrompt:je,handleLaunchCoordinator:Ne,settingMeshHost:He,handleSetMeshHost:Qe}=pL({selectedMesh:O,selectedMeshId:v,primaryDaemonId:w,activeDaemonId:be,daemons:a,availableCliProviders:N,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:h,launchCoordinator:i,features:{addNodeDaemonPicker:g.addNodeDaemonPicker},loadMeshes:he,loadQueue:de,queueSection:g.queueSection,setError:A}),lt=l.useMemo(()=>a.find(qe=>qe.id===be)||x,[a,be,x]),Ke=l.useMemo(()=>new Set(((O==null?void 0:O.nodes)||[]).map(qe=>String(qe.daemon_id||qe.daemonId||""))),[O]),St=l.useMemo(()=>a.filter(qe=>qe.id&&!Ke.has(qe.id)),[a,Ke]),Mt=(O==null?void 0:O.nodes)||[],zt=l.useMemo(()=>Mt.find(qe=>zs(String(qe.daemon_id||qe.daemonId||""),G)),[Mt,G]),rs=g.meshHostDaemonSection?!!zt:!0,Ct=l.useMemo(()=>{if(!g.meshHostDaemonSection||!O)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const qe=O.meshHost,ot=Q!=null&&Q.meshId&&String(Q.meshId)===String(O.id??"")?Q.meshHost:void 0,ds=ot!=null&&ot.hostDaemonId?ot:qe??ot,ie=Mu(ds),We=ie.hostDaemonId,Oe=Mt.find(Ls=>Ls.role==="host"),Rt=ie.hostNodeId||String((Oe==null?void 0:Oe.id)||""),Pt=Rt?Mt.find(Ls=>String(Ls.id)===Rt):void 0,ta=String((Pt==null?void 0:Pt.daemon_id)||(Pt==null?void 0:Pt.daemonId)||""),sa=We||ta;if(!sa)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const na=a.find(Ls=>We&&zs(Ls.id,We))||(ta?a.find(Ls=>zs(Ls.id,ta)):void 0);if(na)return{pinned:!0,daemonId:na.id,label:ML(na),online:!0,hostNode:Pt};const Ga=String((Pt==null?void 0:Pt.machineLabel)||"")||String((Pt==null?void 0:Pt.workspace)||"")||sa;return{pinned:!0,daemonId:sa,label:Ga,online:!1,hostNode:Pt}},[O,Mt,a,Q,g.meshHostDaemonSection]),Ws=Ct.daemonId,Pe=Ct.online,tt=Ct.pinned?Ct.hostNode:zt,Lt=l.useMemo(()=>!g.meshHostDaemonSection||!Ct.pinned?"":!Pe&&me&&a.some(qe=>qe.id===me)?me:Ws,[g.meshHostDaemonSection,Ct.pinned,Pe,me,a,Ws]),ct=l.useMemo(()=>Q?[...new Set((Q.nodes??[]).map(qe=>String(qe.daemonId||qe.daemon_id||"")).filter(Boolean))]:[],[Q]),os=nf({status:Q,daemonId:be||null,extraDaemonIds:ct,meshId:v,sendData:n});l.useEffect(()=>{const qe=(O==null?void 0:O.coordinator)||{};ye({override:typeof qe.systemPromptOverride=="string"?qe.systemPromptOverride:"",append:typeof qe.systemPromptAppend=="string"?qe.systemPromptAppend:typeof qe.systemPromptSuffix=="string"?qe.systemPromptSuffix:""}),_e(Object.fromEntries(((O==null?void 0:O.nodes)||[]).map(ot=>[ot.id,typeof ot.systemPrompt=="string"?ot.systemPrompt:""])))},[O]),l.useEffect(()=>{const qe=g.addNodeDaemonPicker?wn(et):wn(N);F&&ee.length===0&&qe.length>0&&De(qe)},[F,N,et,ee.length,g.addNodeDaemonPicker]),l.useEffect(()=>{const qe=new Set(((O==null?void 0:O.nodes)||[]).map(ot=>ot.id));we&&!qe.has(we)&&Re(null)},[O,we]);const Ut=l.useMemo(()=>{if(!(!(Q!=null&&Q.meshId)||String(Q.meshId)!==String((O==null?void 0:O.id)??"")))return Mu(Q.meshHost).hostDaemonId||void 0},[Q,O]),Vt=l.useMemo(()=>xL(a,Mt,be,w,Ut),[a,Mt,be,w,Ut]);l.useEffect(()=>{if(!g.meshHostDaemonSection)return;if(!a.length&&!Ct.pinned){te("");return}const qe=Ct.pinned?Lt:Vt;qe&&!zs(qe,G)&&te(qe)},[a,G,Ct.pinned,Lt,Vt,g.meshHostDaemonSection]),l.useEffect(()=>{me&&(Pe||!a.some(qe=>qe.id===me))&&K("")},[Pe,me,a]),l.useEffect(()=>{if(g.createDaemonPicker){if(!a.length){E("");return}(!U||!a.some(qe=>qe.id===U))&&E(a[0].id)}},[a,U,g.createDaemonPicker]),l.useEffect(()=>{var qe;if(!g.createDaemonPicker||!U){_("");return}if(!q.length){_("");return}q.some(ot=>ot.path===$)||_(((qe=q[0])==null?void 0:qe.path)||"")},[U,$,q,g.createDaemonPicker]);const ks=l.useRef(null),is=l.useRef(kL()),Xt=g.meshStatePushRefresh?NL:jL,[ls,Ts]=l.useState(Xt);l.useEffect(()=>{if(!v)return;const qe=ks.current!==v;if(ks.current=v,qe){ol(is.current),Ts(Xt);const ot=gf(v);ke(ot),xe(null),Y(be,v,ot!==null)}else xe(null),Y(be,v,!0)},[v,be]);const Ds=l.useRef(Y);Ds.current=Y;const Ss=l.useRef(!1),cs=l.useRef(()=>{});cs.current=()=>{Ss.current||!v||!be||(Ss.current=!0,Promise.resolve(Ds.current(be,v,!0)).finally(()=>{Ss.current=!1}))},l.useEffect(()=>{SL(is.current,Q),Ts(CL(is.current,Xt))},[Q,Xt]),aI({daemonIds:l.useMemo(()=>[be,...ct].filter(Boolean),[be,ct]),meshId:v,sendData:n,onRevisionAdvance:()=>{typeof document<"u"&&document.visibilityState!=="visible"||cs.current()}}),l.useEffect(()=>{if(!v||!be||typeof document>"u")return;let qe=null;const ot=()=>{document.visibilityState==="visible"&&cs.current()},ds=()=>{qe===null&&(qe=setInterval(ot,ls))},ie=()=>{qe!==null&&(clearInterval(qe),qe=null)},We=()=>{document.visibilityState==="visible"?ds():ie()};return document.visibilityState==="visible"&&ds(),document.addEventListener("visibilitychange",We),()=>{ie(),document.removeEventListener("visibilitychange",We)}},[v,be,ls]),l.useEffect(()=>{g.queueSection||de(v)},[v,g.queueSection]);const Os=l.useMemo(()=>a.map(qe=>qe.id).filter(Boolean).sort().join(","),[a]),Is=l.useRef(!1);return l.useEffect(()=>{he(Is.current),Is.current=!0},[Os]),w?O?s.jsx(uL,{selectedMesh:O,error:S,onDismissError:()=>A(null),onBack:()=>{y(null),ke(null)},onDelete:z,displayedMeshStatus:os,graphLoading:Se,graphError:ve,onRefreshGraph:()=>{ol(is.current),Y(be,v,!0)},savingPolicy:oe,onUpdatePolicy:Ve,coordinatorPromptDraft:pe,onCoordinatorPromptDraftChange:ye,savingCoordinatorPrompt:le,onSaveCoordinatorPrompt:fe,daemons:a,coordinatorDaemonId:G,onCoordinatorDaemonIdChange:te,coordinatorCliType:bt,onCoordinatorCliTypeChange:it,launchingCoordinator:yt,launchResult:se,isHostNodeAttached:rs,selectedHostNode:tt,hostPinned:Ct.pinned,hostLabel:Ct.label,hostOnline:Pe,hostRebindDaemonId:me,onHostRebindDaemonIdChange:qe=>K(qe),onLaunchCoordinator:Ne,settingMeshHost:He,onSetMeshHost:Qe,activeDaemon:lt,activeDaemonId:be,meshQueue:re,userName:r,availableCliProviders:N,savingNodeSlotsId:Ue,onUpdateNodeSlots:st,savingNodeCapabilitiesId:Ge,onUpdateNodeCapabilities:$e,nodeSystemPromptDrafts:Me,onNodeSystemPromptDraftChange:(qe,ot)=>_e(ds=>({...ds,[qe]:ot})),savingNodeSystemPromptId:Te,onSaveNodeSystemPrompt:je,selectedNodeId:we,onSelectNode:Re,showAddNode:F,onShowAddNode:()=>J(!0),onCancelAddNode:()=>J(!1),nodeWorkspace:ge,onNodeWorkspaceChange:ue,nodeProviderPriority:ee,onNodeProviderPriorityChange:De,nodeDaemonId:Le,onNodeDaemonIdChange:Xe,nodeCustomPath:ce,onNodeCustomPathChange:Ee,nodePickerWorkspaces:Fe,nodePickerProviders:et,nodeOnboardingPlan:Ae,nodePlanLoading:Je,attachableDaemons:St,onAddNode:Ye,onRemoveNode:Be,availableCliAgents:b,features:{coordinatorPrompt:g.coordinatorPrompt,meshHostDaemonSection:g.meshHostDaemonSection,hermesMcpConfig:g.hermesMcpConfig,addNodeDaemonPicker:g.addNodeDaemonPicker,nodeInstruction:g.nodeInstruction},sendCommand:t}):s.jsx(mI,{meshes:j,loading:C,error:S,onDismissError:()=>A(null),daemons:a,features:{createDaemonPicker:g.createDaemonPicker,maxMeshes:g.maxMeshes},showCreate:M,onToggleCreate:()=>I(!M),createName:D,onCreateNameChange:P,createRepoIdentity:T,onCreateRepoIdentityChange:H,createRepoRemoteUrl:L,onCreateRepoRemoteUrlChange:R,newMeshDaemonId:U,onNewMeshDaemonIdChange:E,newMeshWorkspace:$,onNewMeshWorkspaceChange:_,createPickerWorkspaces:q,createOnboardingPlan:B,createPlanLoading:W,creating:V,createWarning:ne,onDismissCreateWarning:()=>ae(null),onSelectMesh:y,onCreate:Z,onCancelCreate:X}):s.jsx(Oa,{icon:s.jsx(ns,{}),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 ML(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function PL({children:e}){const{sendCommand:t,sendData:n}=vt(),{ides:a}=ys(),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 h;const u={meshId:c.meshId};c.cliType&&(u.cliType=c.cliType);const p=await t(i,"launch_mesh_coordinator",u),d=(p==null?void 0:p.result)??p;if((d==null?void 0:d.success)===!1)throw new Error(d.error||"Coordinator launch failed");const m=(d==null?void 0:d.sessionId)||((h=d==null?void 0:d.session)==null?void 0:h.id)||(d==null?void 0:d.targetSessionId);return{sessionId:m,message:m?`Coordinator launched (${m})`:"Coordinator launch command sent"}},loadLiveMesh:void 0,extractStatus:Ml,unwrapResult:i=>i,normalizeMesh:(i,c)=>i,normalizeNode:(i,c,u)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:df}),[t,n,r]);return s.jsx(uf.Provider,{value:o,children:e})}function TL(e){const{daemons:t,features:n,meshes:a,meshesLoading:r,selectedMeshId:o,onSelectMesh:i,createMode:c,onCreateModeChange:u,createName:p,onCreateNameChange:d,createDaemonId:m,onCreateDaemonIdChange:h,createWorkspace:g,onCreateWorkspaceChange:k,createPickerWorkspaces:f,createPlan:x,createPlanLoading:w,creating:b,createWarning:N,onCreate:j,createRepoRemoteUrl:v,onCreateRepoRemoteUrlChange:y,createRepoIdentity:C,onCreateRepoIdentityChange:S,createManualOpen:A,onCreateManualOpenChange:M,nodes:I,attachableDaemons:D,attachDaemonId:P,onAttachDaemonIdChange:T,attachWorkspace:H,onAttachWorkspaceChange:L,attachPickerWorkspaces:R,attachPlan:U,attachPlanLoading:E,attaching:$,onAttach:_,renderInstallOnboarding:q,nodeLabel:B,daemonLabel:W}=e,{t:V}=Ce("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:V("setupWizard.machines.title")}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-text-muted",children:V("setupWizard.machines.noMachinesDescription")})]}),q?q():s.jsx("p",{className:"text-[11px] text-text-muted",children:V("setupWizard.machines.noMachinesFallback")})]});const ne=$||E||(U==null?void 0:U.success)===!1||!H.trim()||n.addNodeDaemonPicker&&!P;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:V("setupWizard.machines.title")}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-text-muted",children:V("setupWizard.machines.description")})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[a.map(ae=>{const he=!c&&o===ae.id;return s.jsx("button",{type:"button",onClick:()=>{u(!1),i(ae.id)},className:`flex items-center gap-2 rounded-lg border px-3 py-2 text-left transition-colors ${he?"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:ae.name}),s.jsxs("span",{className:"block truncate text-[11px] text-text-muted",children:[ae.repoIdentity||ae.repoRemoteUrl||""," · ",V("setupWizard.machines.nodeCount",{count:(ae.nodes||[]).length})]})]})},ae.id)}),s.jsx("button",{type:"button",onClick:()=>u(!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:["+ ",V("setupWizard.machines.createNew")]})}),r&&a.length===0&&s.jsx("p",{className:"text-[11px] text-text-muted",children:V("setupWizard.machines.loadingMeshes")})]}),c&&s.jsx(mf,{variant:"wizard",showDaemonPicker:n.createDaemonPicker,daemons:t,daemonLabel:W,name:p,onNameChange:d,daemonId:m,onDaemonIdChange:h,workspace:g,onWorkspaceChange:k,workspaces:f,plan:x,planLoading:w,repoRemoteUrl:v,onRepoRemoteUrlChange:y,repoIdentity:C,onRepoIdentityChange:S,manualOpen:A,onManualOpenChange:M,creating:b,warning:N,onCreate:j}),!c&&o&&s.jsxs("div",{className:"flex flex-col gap-2.5 rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2.5",children:[I.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5",children:I.map(ae=>s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] text-text-secondary",children:B(ae)},ae.id))}),s.jsx("span",{className:"text-[11px] font-medium text-text-secondary",children:V("setupWizard.machines.attachTitle")}),n.addNodeDaemonPicker&&(D.length>0?s.jsx("div",{className:"flex flex-wrap gap-1.5",children:D.map(ae=>{const he=P===ae.id;return s.jsx("button",{type:"button",onClick:()=>T(ae.id),className:`rounded-full border px-2.5 py-1 text-[11px] transition-colors ${he?"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:W(ae)},ae.id)})}):s.jsx("p",{className:"text-[11px] text-text-muted",children:V("setupWizard.machines.allMachinesAttached")})),(!n.addNodeDaemonPicker||P)&&s.jsxs(s.Fragment,{children:[s.jsx(el,{workspaces:R,value:H,onChange:L}),s.jsx(pf,{plan:U,loading:E}),s.jsx("div",{className:"flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:_,disabled:ne,children:V($?"setupWizard.machines.attaching":"setupWizard.machines.addMachine")})})]})]})]})}function DL(e){var t;return e.machineNickname||e.nickname||e.hostname||((t=e.user)==null?void 0:t.name)||e.id}function IL(e){const t=e;return t.machine_label||t.machineLabel||t.hostname||String(e.workspace||"").split(/[\\/]/).filter(Boolean).pop()||e.id}function LL({daemons:e,features:t,sendCommand:n,unwrapResult:a,normalizeMesh:r,loadDaemonMetadata:o,initialMeshId:i,onClose:c,renderInstallOnboarding:u}){var we,Re;const{t:p}=Ce("common"),d=((we=e[0])==null?void 0:we.id)||"",{meshes:m,loading:h,error:g,setError:k,loadMeshes:f,selectedMeshId:x,setSelectedMeshId:w}=ff({daemons:e,primaryDaemonId:d,sendCommand:n,unwrapResult:a,normalizeMesh:r,features:{createDaemonPicker:t.createDaemonPicker,addNodeDaemonPicker:t.addNodeDaemonPicker},loadDaemonMetadata:o});l.useEffect(()=>{f()},[f]),l.useEffect(()=>{x||m.length===0||(i&&m.some(F=>F.id===i)?w(i):m.length===1&&w(m[0].id))},[m,x,i,w]);const b=l.useMemo(()=>m.find(F=>F.id===x)??null,[m,x]),N=l.useMemo(()=>(b==null?void 0:b.nodes)||[],[b]),j=l.useCallback(F=>(F==null?void 0:F.__sourceDaemonId)||d,[d]),[v,y]=l.useState(!1),[C,S]=l.useState(""),[A,M]=l.useState(""),[I,D]=l.useState(""),[P,T]=l.useState(null),[H,L]=l.useState(!1),[R,U]=l.useState(!1),[E,$]=l.useState(null),[_,q]=l.useState(""),[B,W]=l.useState(""),[V,ne]=l.useState(!1),ae=t.createDaemonPicker&&A||d,he=l.useMemo(()=>e.find(F=>F.id===ae),[e,ae]),Z=(he==null?void 0:he.workspaces)||[];l.useEffect(()=>{if(!v||!ae||!I.trim()){T(null);return}let F=!1;return L(!0),n(ae,"plan_mesh_onboarding",{workspace:I.trim(),operation:"auto",meshInventory:m}).then(J=>{if(F)return;const ge=a(J);T(ge),ge!=null&&ge.success&&(S(ue=>{var ee,De;return ue||`${String(((ee=ge.discovery)==null?void 0:ee.repoIdentity)||((De=ge.discovery)==null?void 0:De.repoRoot)||"").split(/[\\/]/).filter(Boolean).pop()||"repo"}-mesh`}),W(ue=>{var ee;return ue||((ee=ge.discovery)==null?void 0:ee.repoIdentity)||""}),q(ue=>{var ee,De,Le,Xe,ce,Ee;return ue||((Le=(De=(ee=ge.discovery)==null?void 0:ee.origin)==null?void 0:De.urls)==null?void 0:Le[0])||((Ee=(ce=(Xe=ge.discovery)==null?void 0:Xe.upstream)==null?void 0:ce.urls)==null?void 0:Ee[0])||""}))}).catch(J=>{F||T({success:!1,error:(J==null?void 0:J.message)||"Git discovery failed"})}).finally(()=>{F||L(!1)}),()=>{F=!0}},[v,ae,I,m,n,a]);const z=l.useCallback(async()=>{const F=ae,J=I.trim(),ge=_.trim(),ue=B.trim();if(!(!F||!C.trim()||R)&&!(!J&&!ge&&!ue)){U(!0),$(null),k(null);try{const ee=await hf({targetDaemonId:F,name:C,repoRemoteUrl:ge,repoIdentity:ue,workspace:J,attachWorkspace:!!J,machineId:he==null?void 0:he.machineId,providerPriority:wn(en((he==null?void 0:he.availableProviders)||[])),meshInventory:m,sendCommand:n,unwrapResult:a});if(ee.warning&&$(ee.warning),!ee.meshCreated){k(ee.error||p("setupWizard.machines.createFailed"));return}await f(!0),ee.meshId&&w(ee.meshId),y(!1)}finally{U(!1)}}},[ae,C,I,_,B,R,he,m,n,a,f,w,k,p]),[X,O]=l.useState(""),[Q,ke]=l.useState(""),[Se,ve]=l.useState(null),[xe,Y]=l.useState(!1),[G,te]=l.useState(!1),me=l.useMemo(()=>{if(!t.addNodeDaemonPicker)return[];const F=new Set(N.map(J=>String(J.daemon_id||J.daemonId||"")));return e.filter(J=>J.id&&!F.has(J.id))},[t.addNodeDaemonPicker,N,e]),K=l.useMemo(()=>e.find(F=>F.id===X),[e,X]),be=t.addNodeDaemonPicker?(K==null?void 0:K.workspaces)||[]:((Re=e.find(F=>F.id===d))==null?void 0:Re.workspaces)||[];l.useEffect(()=>{if(v||!x||!Q.trim()){ve(null);return}const F=t.addNodeDaemonPicker?X:j(b);if(!F)return;let J=!1;return Y(!0),n(F,"plan_mesh_onboarding",{workspace:Q.trim(),meshId:x,inlineMesh:b,operation:"add_existing"}).then(ge=>{J||ve(a(ge))}).catch(ge=>{J||ve({success:!1,error:(ge==null?void 0:ge.message)||"Git discovery failed"})}).finally(()=>{J||Y(!1)}),()=>{J=!0}},[v,x,b,Q,X,t.addNodeDaemonPicker,j,n,a]);const re=l.useCallback(async()=>{var ge,ue,ee,De;const F=j(b);if(!x||!F||G)return;const J=Q.trim();if(J){te(!0),k(null);try{const Le=t.addNodeDaemonPicker?X:F,Xe=await n(Le,"plan_mesh_onboarding",{workspace:J,meshId:x,inlineMesh:b,operation:"add_existing"}),ce=a(Xe);if(ve(ce),(ce==null?void 0:ce.success)===!1)throw new Error(`${ce.code||"onboarding_blocked"}: ${ce.error}${ce.action?` ${ce.action}`:""}`);const Ee={meshId:x,workspace:((ge=ce==null?void 0:ce.discovery)==null?void 0:ge.repoRoot)||J,repoRoot:(ue=ce==null?void 0:ce.discovery)==null?void 0:ue.repoRoot,isLocalWorktree:((ee=ce==null?void 0:ce.discovery)==null?void 0:ee.isLinkedWorktree)===!0};t.addNodeDaemonPicker&&X&&(Ee.daemonId=X,Ee.machineId=K==null?void 0:K.machineId),Ee.providerPriority=wn(en(((De=t.addNodeDaemonPicker?K:e[0])==null?void 0:De.availableProviders)||[]));const Fe=await n(F,"add_mesh_node",Ee),et=a(Fe);if((et==null?void 0:et.success)===!1)throw new Error(et.error||"Add node failed");ke(""),ve(null),await f(!0)}catch(Le){k((Le==null?void 0:Le.message)||"Add node failed")}finally{te(!1)}}},[b,x,Q,X,K,G,t.addNodeDaemonPicker,j,e,n,a,f,k]),de=!v&&!!b&&N.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(TL,{daemons:e,features:t,meshes:m,meshesLoading:h,selectedMeshId:x,onSelectMesh:F=>{w(F),ke(""),O("")},createMode:v,onCreateModeChange:y,createName:C,onCreateNameChange:S,createDaemonId:A,onCreateDaemonIdChange:M,createWorkspace:I,onCreateWorkspaceChange:D,createPickerWorkspaces:Z,createPlan:P,createPlanLoading:H,creating:R,createWarning:E,onCreate:z,createRepoRemoteUrl:_,onCreateRepoRemoteUrlChange:q,createRepoIdentity:B,onCreateRepoIdentityChange:W,createManualOpen:V,onCreateManualOpenChange:ne,nodes:N,attachableDaemons:me,attachDaemonId:X,onAttachDaemonIdChange:F=>{O(F),ke("")},attachWorkspace:Q,onAttachWorkspaceChange:ke,attachPickerWorkspaces:be,attachPlan:Se,attachPlanLoading:xe,attaching:G,onAttach:re,renderInstallOnboarding:u,nodeLabel:IL,daemonLabel:DL})}),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:de?"btn btn-primary btn-sm":"btn btn-secondary btn-sm",onClick:c,children:p(de?"setupWizard.continueToMesh":"setupWizard.close")})})})]})}function rc(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function RL(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=rc();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 Ns(e,t){return await fetch(RL(e),{credentials:"same-origin",...t})}function xf(){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 EL{constructor(){at(this,"adapters",new Map);at(this,"states",new Map);at(this,"runtimeListeners",new Map);at(this,"screenshotCallbacks",new Map);at(this,"statusCallbacks",new Set);at(this,"stateChangeCallbacks",new Set);at(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 Ns(`${r.pathname}${r.search}`);if(!o.ok){let c=`Runtime snapshot unavailable (${o.status})`;try{const u=await o.json();u!=null&&u.error&&(c=u.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 js=new EL;function _L(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,n=rc();return n?`${t}?token=${encodeURIComponent(n)}`:t}const fr=_L(),Pu=3e3,HL=3e4;let ms=null,$L=0;const Qr=new Map;let ln=null,Aa=null;function Tu(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function fa(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function FL(e){return e==="connected"?"connected":e}async function Ma(e,t,n){const a=Pm(e,n||{}),r=ms;if(r&&r.readyState===WebSocket.OPEN){const o=`req_${++$L}_${Date.now()}`;return new Promise((i,c)=>{const u=setTimeout(()=>{Qr.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);Qr.set(o,{resolve:p=>{clearTimeout(u),i(p)},reject:p=>{clearTimeout(u),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 il(e,t){const n=ms;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 vf(e,t,n){const a=ms;if(!a||a.readyState!==WebSocket.OPEN)return!1;const r=Pm(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}}js.registerPtyInputSender(vf);class BL{constructor(t){at(this,"daemonId");at(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(ms==null?void 0:ms.readyState)===WebSocket.OPEN}get connectionState(){return(ms==null?void 0:ms.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,n){return Ma(this.daemonId,t,n)}async sendInput(t,n){return Ma(this.daemonId,"cdp_remote_action",{action:t,params:n,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,ln&&(clearInterval(ln),ln=null);const n=async()=>{if(this.hasCommandChannel)try{const a=await Ma(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());js.emitScreenshot(this.daemonId,r)}}catch{}};n(),ln=setInterval(n,2e3)}stopScreenshots(t){ln&&(clearInterval(ln),ln=null)}}let es=null;function WL(e){return(!es||es.daemonId!==e)&&(es=new BL(e)),es}function OL({children:e}){const t=l.useRef(Pa()),n=Pa();t.current=n;const{setUserName:a}=ys(),r=l.useRef(a);r.current=a;const o=l.useRef(null),i=l.useRef(null),[,c]=l.useState("disconnected"),u=l.useCallback((f,x)=>{c(f),Aa==null||Aa(f,x)},[]),p=l.useRef(null),d=l.useRef(),m=l.useRef(Pu),h=l.useRef(!0),g=l.useRef(!1),k=l.useRef("initial_connect");return l.useEffect(()=>{h.current=!0,g.current=!1;function f(){var b,N;if(!h.current||((b=p.current)==null?void 0:b.readyState)===WebSocket.OPEN||((N=p.current)==null?void 0:N.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${fr}...`),fa("connect_attempt",{url:fr,reason:k.current,delayMs:m.current});let w;try{w=new WebSocket(fr)}catch(j){console.error("[Standalone WS] Failed to create WebSocket:",j),x();return}p.current=w,w.onopen=()=>{if(!h.current){w.close();return}u("connected"),m.current=Pu,fa("open",{url:fr,reason:k.current}),gs.resubscribeAll({sendData:il}),console.log("[Standalone WS] Connected")},ms=w,w.onmessage=j=>{var v,y;try{const C=JSON.parse(j.data);if((C.type==="command_result"||C.type==="error")&&C.requestId){const S=Qr.get(C.requestId);S&&(Qr.delete(C.requestId),C.type==="error"?S.reject(new Error(((v=C.data)==null?void 0:v.message)||"Command failed")):S.resolve(C.data));return}if(C.type==="session_output"){const S=C.sessionId||C.cliId||C.cliType;S&&js.emitSessionOutput(S,typeof C.data=="string"?C.data:"",typeof C.seq=="number"?C.seq:void 0);return}if(C.type==="runtime_snapshot"){js.emitRuntimeSnapshot(C.sessionId,typeof C.text=="string"?C.text:"",typeof C.seq=="number"?C.seq:0,!!C.truncated,typeof C.cols=="number"?C.cols:void 0,typeof C.rows=="number"?C.rows:void 0);return}if(C.type==="topic_update"){const S=C.update;S&&gs.publish(S);return}if(C.type==="status"||C.type==="initial_state"){const S=C.data;if(!S)return;const{injectEntries:A,markLoaded:M,getIdes:I}=t.current,D=S.instanceId||"standalone",P=I().find(L=>L.id===D),T=WL(D);js.register(D,T),js.setState(D,"connected"),u("connected",D),js.emitStatus(D,S);const H=Rr(S,{daemonId:D,existingDaemon:P,existingEntries:I()});Tu("ws_status",{type:C.type,daemonId:D,sessions:(S.sessions||[]).map(L=>({id:L.id,parentId:L.parentId,providerType:L.providerType,kind:L.kind,transport:L.transport,unread:L.unread,inboxBucket:L.inboxBucket,lastSeenAt:L.lastSeenAt,lastUpdated:L.lastUpdated,title:L.title})),recentLaunches:(S.recentLaunches||[]).map(L=>({id:L.id,providerType:L.providerType,kind:L.kind,workspace:L.workspace,lastLaunchedAt:L.lastLaunchedAt}))}),Tu("entries",{daemonId:D,entries:H.filter(L=>L.type!=="adhdev-daemon").map(L=>({id:L.id,type:L.type,unread:L.unread,inboxBucket:L.inboxBucket,lastSeenAt:L.lastSeenAt,lastUpdated:L.lastUpdated,sessionId:L.sessionId}))}),H.length>0&&A(H,{authoritativeDaemonIds:[D]}),M(),i.current!==D&&((y=o.current)==null||y.call(o),i.current=D,o.current=gs.subscribe({sendData:il},D,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${D}`,params:{includeSessions:!0}},L=>{if(L.topic!=="daemon.metadata")return;const R=t.current.getIdes(),U=R.find($=>$.id===D),E=Rr(L.status,{daemonId:D,existingDaemon:U,existingEntries:R,timestamp:L.timestamp});E.length>0&&t.current.injectEntries(E,{authoritativeDaemonIds:[D]}),L.userName&&r.current&&r.current(L.userName)}))}}catch(C){console.error("[Standalone WS] Parse error:",C)}},w.onclose=j=>{h.current&&(es==null||es.stopScreenshots(),es&&js.setState(es.daemonId,"disconnected"),u("disconnected"),p.current=null,k.current=`close:${j.code}${j.wasClean?":clean":":unclean"}`,fa("close",{code:j.code,reason:j.reason||"",wasClean:j.wasClean}),x())},w.onerror=j=>{g.current||!h.current||(k.current="error",fa("error",{message:j instanceof Event?"event":String(j),readyState:w.readyState}),console.warn("[Standalone WS] Error, will reconnect:",j))}}function x(){if(!h.current)return;clearTimeout(d.current);const w=m.current;console.log(`[Standalone WS] Reconnecting in ${w}ms...`),fa("schedule_reconnect",{reason:k.current,delayMs:w}),d.current=setTimeout(()=>{m.current=Math.min(m.current*1.5,HL),f()},w)}return f(),()=>{var w;h.current=!1,g.current=!0,(w=o.current)==null||w.call(o),o.current=null,i.current=null,clearTimeout(d.current),p.current&&(p.current.onerror=null,p.current.onclose=null,p.current.close(),p.current=null,ms=null),es&&(es.stopScreenshots(),js.unregister(es.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function UL({children:e}){const[t,n]=l.useState("disconnected"),[a,r]=l.useState(null);l.useEffect(()=>(Aa=(i,c)=>{n(i),c&&r(c)},()=>{Aa=null}),[]);const o=l.useMemo(()=>{const i=t==="connected",c=FL(t),u={};return a&&(u[a]=c),u.standalone=c,{wsStatus:t,isConnected:i,connectionStates:u,usesP2P:!1}},[t,a]);return s.jsx(db,{connectionOverrides:o,children:s.jsx(OL,{children:e})})}const yf="adhdev_standalone_font_preferences",gn={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},wo=[{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"}],Ha=[{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"}],qL=new Set(wo.map(e=>e.id)),GL=new Set(Ha.map(e=>e.id));function As(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Ar("chat",t.chat),code:Ar("code",t.code),terminal:Ar("terminal",t.terminal)}}function Ar(e,t){const n=gn[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"?qL:GL).has(r)?r==="custom"?o?{preset:"custom",customFamily:o}:n:{preset:r}:n}function Mr(e,t){var r;const n=Ar(e,t);if(n.preset==="custom"&&n.customFamily)return n.customFamily;const a=e==="chat"?wo:Ha;return((r=a.find(o=>o.id===n.preset))==null?void 0:r.family)||a[0].family}function zL(e){const t=As(e),n=Mr("chat",t.chat),a=Mr("code",t.code),r=Mr("terminal",t.terminal);return{"--chat-font-family":n,"--chat-code-font-family":a,"--chat-terminal-font-family":r,"--chat-tool-font-family":r}}function dn(e,t=document.documentElement){const n=As(e),a=zL(n);t.setAttribute("data-standalone-fonts","custom");for(const[r,o]of Object.entries(a))t.style.setProperty(r,o);return n}function ll(e){const t=As(e);try{localStorage.setItem(yf,JSON.stringify(t))}catch{}return t}function KL(){try{const e=localStorage.getItem(yf);if(e)return As(JSON.parse(e))}catch{}return gn}function VL(){return dn(KL())}function ba(e,t){var a;const n=e==="chat"?wo:Ha;return((a=n.find(r=>r.id===t))==null?void 0:a.label)||n[0].label}function YL({children:e}){const t=Jn(),n=dl(),{t:a}=Ce("common"),r=l.useMemo(()=>[{id:"dashboard",path:"/dashboard",icon:s.jsx(Gu,{}),label:a("standalone.nav.dashboard"),active:n.pathname.startsWith("/dashboard"),onSelect:()=>t("/dashboard")},{id:"machine",path:"/machines",icon:s.jsx(Ys,{}),label:"Burrow",active:n.pathname.startsWith("/machines"),onSelect:()=>t("/machines")},{id:"mesh",path:"/mesh",icon:s.jsx(ns,{}),label:"Mesh",active:n.pathname.startsWith("/mesh")||n.pathname.startsWith("/setup"),onSelect:()=>t("/mesh")},{id:"settings",path:"/settings",icon:s.jsx(Xr,{}),label:a("standalone.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("standalone.nav.docs")}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(Ku,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:a("standalone.nav.docs")},{id:"about",label:a("standalone.nav.about"),icon:s.jsx(hl,{}),active:n.pathname==="/about",onSelect:()=>t("/about"),title:a("standalone.nav.about")}],[n.pathname,t,a]);return s.jsx(lj,{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.48"]}),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 QL(){const e=Jn(),{sendCommand:t}=vt(),{ides:n}=ys(),a=l.useMemo(()=>n.filter(r=>r.daemonMode||r.type==="adhdev-daemon").map(r=>r),[n]);return s.jsx(LL,{daemons:a,features:df,sendCommand:t,unwrapResult:r=>r,normalizeMesh:r=>r,onClose:()=>e("/mesh")})}const JL=[{icon:s.jsx(Ys,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Cn,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Qu,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(ws,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(Ta,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Ku,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],XL=[{icon:s.jsx(Bb,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Gu,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Xn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Rb,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(zu,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(_b,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],ZL=[{feature:"Agent chat relay",selfhost:!0,cloud:!0},{feature:"Live IDE screenshots",selfhost:!0,cloud:!0},{feature:"Remote IDE control",selfhost:!0,cloud:!0},{feature:"Multi-IDE monitoring",selfhost:!0,cloud:!0},{feature:"Extension and CLI agents",selfhost:!0,cloud:!0},{feature:"Access from any network",selfhost:!1,cloud:!0},{feature:"WebRTC P2P streaming",selfhost:!1,cloud:!0},{feature:"Mobile push notifications",selfhost:!1,cloud:!0},{feature:"REST API and webhooks",selfhost:!1,cloud:!0},{feature:"Team collaboration",selfhost:!1,cloud:!0},{feature:"Multi-machine burrows",selfhost:!1,cloud:!0},{feature:"SSO, RBAC, audit logs",selfhost:!1,cloud:!0}];function e2(){const{t:e}=Ce("common");return s.jsxs(Oa,{icon:s.jsx(hl,{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.48"]}),children:[s.jsx(ht,{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(ht,{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:JL.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(ht,{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:Tm.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:Im.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:Dm.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(ht,{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:XL.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(ht,{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:ZL.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(co,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:e("standalone.about.cloudOptional"),description:e("standalone.about.cloudOptionalDescription"),action:s.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:e("standalone.about.compareCloud")}),s.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[s.jsx(Yb,{size:14,className:"mr-1"}),e("standalone.about.discord")]})]})})]})}function vi(e,t,n){return{...e,[t]:n}}function yi({surface:e,title:t,description:n,value:a,options:r,onChange:o}){const{t:i}=Ce("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(pj,{value:a.preset,onChange:c=>{const u=c.target.value;o(u==="custom"?{preset:"custom",customFamily:a.customFamily||""}:{preset:u})},children:r.map(c=>s.jsx("option",{value:c.id,children:c.label},c.id))}),a.preset==="custom"&&s.jsx(fs,{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:Mr(e,a)})]})]})]})}function t2({value:e,savedValue:t,saving:n=!1,error:a,notice:r,onChange:o,onSave:i,onResetToSaved:c,onResetToDefaults:u}){const{t:p}=Ce("common"),d=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(Dt,{variant:"error",children:a}),r&&s.jsx(Dt,{variant:"success",children:r}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(yi,{surface:"chat",title:p("standalone.fonts.chat"),description:p("standalone.fonts.chatDescription"),value:e.chat,options:wo,onChange:m=>o(vi(e,"chat",m))}),s.jsx(yi,{surface:"code",title:p("standalone.fonts.code"),description:p("standalone.fonts.codeDescription"),value:e.code,options:Ha,onChange:m=>o(vi(e,"code",m))}),s.jsx(yi,{surface:"terminal",title:p("standalone.fonts.terminal"),description:p("standalone.fonts.terminalDescription"),value:e.terminal,options:Ha,onChange:m=>o(vi(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: ",ba("chat",e.chat.preset)," · Code: ",ba("code",e.code.preset)," · Terminal: ",ba("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[p("standalone.fonts.defaults")," ",ba("chat",gn.chat.preset)," / ",ba("code",gn.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(Hs,{type:"button",variant:"primary",size:"sm",onClick:i,disabled:n||!d,children:p(n?"standalone.fonts.saving":"standalone.fonts.saveFontSettings")}),s.jsx(Hs,{type:"button",variant:"secondary",size:"sm",onClick:c,disabled:n||!d,children:p("standalone.fonts.revertToSaved")}),s.jsx(Hs,{type:"button",variant:"secondary",size:"sm",onClick:u,disabled:n,children:p("standalone.fonts.resetToDefaults")})]})]})}function s2(){const{t:e}=Ce("common"),{ides:t}=ys(),n=t.find(z=>z.type==="adhdev-daemon"),a=(n==null?void 0:n.detectedIdes)||[],{sendCommand:r}=vt(),{userName:o}=ys(),[i,c]=l.useState(o||""),[u,p]=l.useState(null),[d,m]=l.useState(null),[h,g]=l.useState(gn),[k,f]=l.useState(!1),[x,w]=l.useState(""),[b,N]=l.useState(""),[j,v]=l.useState("127.0.0.1"),[y,C]=l.useState(""),[S,A]=l.useState(""),[M,I]=l.useState(""),[D,P]=l.useState(""),[T,H]=l.useState(""),[L,R]=l.useState(!1),U=async()=>{const X=await(await Ns("/auth/session")).json();p(X)},E=async()=>{const X=await(await Ns("/api/v1/standalone/preferences")).json();m(X),v(X.standaloneBindHost);const O=As(X.standaloneFontPreferences);g(O),dn(O),ll(O)};l.useEffect(()=>{o!==void 0&&c(o)},[o]),l.useEffect(()=>{Promise.all([U(),E()]).catch(z=>{P(z instanceof Error?z.message:String(z))})},[]),l.useEffect(()=>{dn(h)},[h]);const $=z=>{const X=z.target.value.trim();n!=null&&n.id&&X!==o&&r(n.id,"set_user_name",{userName:X}).catch(console.error)},[_,q]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),B=z=>{q(z);try{localStorage.setItem("adhdev_sound",z?"1":"0")}catch{}},W=async()=>{w(""),N(""),f(!0);try{const z=As(h),X=await Ns("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:z})}),O=await X.json();if(!X.ok)throw new Error((O==null?void 0:O.error)||"Failed to save standalone font preferences");const Q=As(O.standaloneFontPreferences);m(O),g(Q),dn(Q),ll(Q),N(e("standalone.settings.fontsSaved"))}catch(z){w(z instanceof Error?z.message:String(z))}finally{f(!1)}},V=()=>{const z=As(d==null?void 0:d.standaloneFontPreferences);w(""),N(""),g(z),dn(z)},ne=()=>{w(""),N(""),g(gn),dn(gn)},ae=async()=>{P(""),H(""),R(!0);try{const z=await Ns("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:j})}),X=await z.json();if(!z.ok)throw new Error((X==null?void 0:X.error)||"Failed to save standalone network preference");m(X),v(X.standaloneBindHost),H(X.standaloneBindHost==="0.0.0.0"?e("standalone.settings.networkSavedAll"):e("standalone.settings.networkSavedLocal"))}catch(z){P(z instanceof Error?z.message:String(z))}finally{R(!1)}},he=async()=>{if(P(""),H(""),S.trim().length<4){P(e("standalone.settings.passwordTooShort"));return}if(S!==M){P(e("standalone.settings.passwordMismatch"));return}R(!0);try{const z=await Ns("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,newPassword:S})}),X=await z.json();if(!z.ok)throw new Error((X==null?void 0:X.error)||"Failed to save password");p(X),await E(),C(""),A(""),I(""),H(u!=null&&u.hasPasswordAuth?e("standalone.settings.passwordUpdated"):e("standalone.settings.passwordEnabled")),xf()}catch(z){P(z instanceof Error?z.message:String(z))}finally{R(!1)}},Z=async()=>{P(""),H(""),R(!0);try{const z=await Ns("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,clear:!0})}),X=await z.json();if(!z.ok)throw new Error((X==null?void 0:X.error)||"Failed to clear password");p(X),await E(),C(""),A(""),I(""),H(e("standalone.settings.passwordDisabled"))}catch(z){P(z instanceof Error?z.message:String(z))}finally{R(!1)}};return s.jsxs(Oa,{icon:s.jsx(Xr,{className:"text-text-primary"}),title:e("standalone.settings.title"),subtitle:e("standalone.settings.subtitle"),widthClassName:"max-w-5xl",children:[s.jsx(Dt,{variant:"info",children:e("standalone.settings.infoNotice")}),(u==null?void 0:u.publicHostWarning)&&s.jsx(Dt,{variant:"warning",children:e("standalone.settings.publicHostWarning")}),s.jsx(ht,{title:e("standalone.settings.daemonSection"),description:e("standalone.settings.daemonDescription"),children:s.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.versionLabel")}),s.jsxs("span",{className:"font-mono text-xs",children:["v","1.0.48"]}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.statusLabel")}),s.jsx("span",{className:n?"text-green-400":"text-yellow-400",children:e(n?"standalone.settings.statusRunning":"standalone.settings.statusNotConnected")}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.currentBindLabel")}),s.jsx("span",{className:"font-mono text-xs",children:(d==null?void 0:d.currentBindHost)||(u==null?void 0:u.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.defaultBindLabel")}),s.jsx("span",{className:"font-mono text-xs",children:(d==null?void 0:d.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.authLabel")}),s.jsx("span",{className:"text-xs",children:u!=null&&u.hasPasswordAuth?e("standalone.settings.authPassword"):u!=null&&u.hasTokenAuth?e("standalone.settings.authToken"):e("standalone.settings.authNone")})]})}),s.jsx(ht,{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:j==="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:j==="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(Hs,{type:"button",variant:"primary",size:"sm",onClick:()=>{ae()},disabled:L,children:e(L?"standalone.settings.saving":"standalone.settings.saveNetworkMode")}),s.jsx("span",{className:"text-xs text-text-muted",children:e("standalone.settings.networkRestartHint",{host:(d==null?void 0:d.currentBindHost)||(u==null?void 0:u.boundHost)||"127.0.0.1"})})]})]})}),s.jsx(ht,{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:u!=null&&u.hasPasswordAuth?e("standalone.settings.passwordSet"):e("standalone.settings.passwordNotSet")}),D&&s.jsx(Dt,{variant:"error",children:D}),T&&s.jsx(Dt,{variant:"success",children:T}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx(fs,{type:"password",placeholder:u!=null&&u.hasPasswordAuth?e("standalone.settings.currentPasswordPlaceholder"):e("standalone.settings.currentPasswordFirstTimePlaceholder"),value:y,onChange:z=>C(z.target.value)}),s.jsx(fs,{type:"password",placeholder:u!=null&&u.hasPasswordAuth?e("standalone.settings.newPasswordPlaceholder"):e("standalone.settings.newPasswordFirstTimePlaceholder"),value:S,onChange:z=>A(z.target.value)}),s.jsx(fs,{type:"password",className:"md:col-span-2",placeholder:e("standalone.settings.confirmPasswordPlaceholder"),value:M,onChange:z=>I(z.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Hs,{type:"button",variant:"primary",size:"sm",onClick:()=>{he()},disabled:L,children:L?e("standalone.settings.saving"):u!=null&&u.hasPasswordAuth?e("standalone.settings.updatePassword"):e("standalone.settings.enablePassword")}),(u==null?void 0:u.hasPasswordAuth)&&s.jsx(Hs,{type:"button",variant:"danger",size:"sm",onClick:()=>{Z()},disabled:L,children:e("standalone.settings.disablePassword")})]})]})}),s.jsx(ht,{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-1.5",children:a.map(z=>s.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${z.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:z.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:z.type})]},z.type))})}),s.jsx(ht,{title:e("standalone.settings.machineSection"),description:e("standalone.settings.machineDescription"),children:s.jsx(wj,{ides:t,emptyMessage:e("standalone.settings.daemonNotConnected")})}),s.jsx(ht,{title:e("standalone.settings.appearanceSection"),description:e("standalone.settings.appearanceDescription"),children:s.jsx(Wj,{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(t2,{value:h,savedValue:As(d==null?void 0:d.standaloneFontPreferences),saving:k,error:x,notice:b,onChange:g,onSave:()=>{W()},onResetToSaved:V,onResetToDefaults:ne})]})})}),s.jsx(ht,{title:e("standalone.settings.notificationsSection"),description:e("standalone.settings.notificationsDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(bj,{}),s.jsx(cn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Vb,{size:15})," ",e("standalone.settings.soundEffectsLabel")]}),description:e("standalone.settings.soundEffectsDescription"),checked:_,onChange:B})]})}),s.jsx(ht,{title:e("standalone.settings.profileSection"),description:e("standalone.settings.profileDescription"),children:s.jsx("div",{className:"flex flex-col gap-3",children:s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[s.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[s.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[s.jsx(Lb,{size:16,className:"text-text-secondary"})," ",e("standalone.settings.displayNameLabel")]}),s.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:e("standalone.settings.displayNameHint")})]}),s.jsx(fs,{type:"text",className:"w-48 text-right",placeholder:e("standalone.settings.displayNamePlaceholder"),value:i,onChange:z=>c(z.target.value),onBlur:$,onKeyDown:z=>{z.key==="Enter"&&z.currentTarget.blur()}})]})})})]})}const n2=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],ya="adhdev_onboarding_done",a2=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],r2={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function o2({onDone:e}){const{t}=Ce("common"),[n,a]=l.useState([]),[r,o]=l.useState(new Set(n2)),[i,c]=l.useState(!0),[u,p]=l.useState(null),[d,m]=l.useState(!1),[h,g]=l.useState(null),[k,f]=l.useState("all");l.useEffect(()=>{let y=!1;const C=window.location.hostname==="localhost"?"/registry":"https://api.adhf.dev/api/v1/registry";return fetch(`${C}/providers?sort=popular&limit=100`).then(S=>{if(!S.ok)throw new Error(`HTTP ${S.status}`);return S.json()}).then(S=>{y||a(S.providers??[])}).catch(S=>{y||p(S instanceof Error?S.message:String(S))}).finally(()=>{y||c(!1)}),()=>{y=!0}},[]);const x=n.filter(y=>k==="all"||y.category===k),w=["cli","ide","extension","acp"].map(y=>({category:y,items:x.filter(C=>C.category===y)})).filter(y=>y.items.length>0),b=l.useCallback(y=>{o(C=>{const S=new Set(C);return S.has(y)?S.delete(y):S.add(y),S})},[]),N=l.useCallback(async()=>{if(r.size===0){localStorage.setItem(ya,"1"),e();return}m(!0);const y=[];for(const C of r)try{const A=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:C})})).json().catch(()=>({}));y.push({type:C,ok:!!A.success,error:A.error})}catch(S){y.push({type:C,ok:!1,error:S instanceof Error?S.message:String(S)})}g(y),m(!1),y.every(C=>C.ok)&&localStorage.setItem(ya,"1")},[r,e]),j=l.useCallback(()=>{localStorage.setItem(ya,"1"),e()},[e]),v=l.useCallback(()=>{h&&h.every(y=>y.ok)?e():d||j()},[h,d,e,j]);return s.jsx(Ep,{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(Hs,{variant:"secondary",size:"sm",onClick:j,disabled:d,children:t("standalone.onboarding.skip")}),s.jsx(Hs,{variant:"primary",size:"sm",onClick:()=>{h?(localStorage.setItem(ya,"1"),e()):N()},disabled:d||!h&&r.size===0,children:d?t("standalone.onboarding.installing"):h?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&&!u&&n.length>0&&s.jsx("div",{className:"flex gap-1 flex-wrap border-b border-border-subtle pb-2",children:a2.map(y=>{const C=y.key==="all"?n.length:n.filter(S=>S.category===y.key).length;return C===0&&y.key!=="all"?null:s.jsxs("button",{onClick:()=>f(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:["(",C,")"]})]},y.key)})}),i&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.loadingRegistry")}),!i&&u&&s.jsx(Dt,{variant:"error",children:t("standalone.onboarding.loadError",{error:u})}),!i&&!u&&x.length===0&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.noProviders")}),!i&&!u&&x.length>0&&s.jsx("div",{className:"flex flex-col gap-4",children:w.map(y=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:r2[y.category]??y.category}),s.jsx("div",{className:"grid gap-1.5",children:y.items.map(C=>{var D,P;const S=r.has(C.type),A=h==null?void 0:h.find(T=>T.type===C.type),M=((D=C.manifest)==null?void 0:D.icon)??"📦",I=((P=C.manifest)==null?void 0:P.details)??"";return s.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${S?"bg-accent-primary/[0.06] border-accent-primary/30":"bg-bg-glass border-border-subtle hover:bg-bg-glass-hover"}`,children:[s.jsx("input",{type:"checkbox",checked:S,onChange:()=>b(C.type),disabled:d,className:"shrink-0"}),s.jsx("span",{className:"text-base shrink-0",children:M}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[13px] font-medium text-text-primary truncate",children:C.displayName}),I&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:I})]}),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"})})]},C.type)})})]},y.category))})]})})}function i2(){try{return localStorage.getItem(ya)==="1"}catch{return!1}}JC();Lj();Pw();VL();const l2=$u({baseUrl:"",getToken:rc});function c2({children:e}){const{t}=Ce("common"),[n,a]=l.useState(null),[r,o]=l.useState(!0),[i,c]=l.useState(""),[u,p]=l.useState(""),[d,m]=l.useState(!1),h=async()=>{o(!0),p("");try{const f=await(await Ns("/auth/session")).json();a(f)}catch(k){p(k instanceof Error?k.message:String(k))}finally{o(!1)}};l.useEffect(()=>{h()},[]),l.useEffect(()=>{if(!n||n.required&&!n.authenticated)return;let k=!1;return(async()=>{try{const f=await Ns("/api/v1/standalone/preferences");if(!f.ok)return;const x=await f.json();if(k)return;const w=As(x.standaloneFontPreferences);dn(w),ll(w)}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 f=await Ns("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),x=await f.json();if(!f.ok)throw new Error((x==null?void 0:x.error)||"Login failed");a(x),c(""),xf()}catch(f){p(f instanceof Error?f.message:String(f))}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(fs,{type:"password",value:i,onChange:k=>c(k.target.value),placeholder:t("standalone.auth.passwordPlaceholder"),autoFocus:!0}),s.jsx(Hs,{type:"submit",variant:"primary",disabled:d||!i,className:"justify-center",children:t(d?"standalone.auth.signingIn":"standalone.auth.unlock")})]}):s.jsx(Dt,{variant:"warning",children:t("standalone.auth.noPasswordEnabled")}),u&&s.jsx(Dt,{variant:"error",children:u})]})}):s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:t("standalone.auth.loadError",{error:u||"unknown error"})})}function Du(){const{t:e}=Ce("common"),{ides:t,initialLoaded:n}=ys();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(Ci,{to:`/machines/${a.id}`,replace:!0}):s.jsx(Ci,{to:"/dashboard",replace:!0})}function d2(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let n=!1;if(!i2())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(o2,{onDone:()=>t(!1)}):null}function u2(){const{t:e}=Ce("common"),{ides:t}=ys(),n=l.useMemo(()=>{for(const d of t)if(d.activeInteractivePrompt)return d.instanceId??d.id;return null},[t]),{promptSession:a,hasActivePrompt:r,responseError:o,isSubmitting:i,submit:c,cancel:u,reopen:p}=Om(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(dp,{promptSession:a,isSubmitting:i,error:o,onSubmit:c,onCancel:u})]}):null}function p2(){const e=l.useMemo(()=>({sendCommand:Ma,sendData:il,sendPtyInput:vf}),[]);return s.jsx(Kf,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(mb,{client:l2,children:s.jsx(c2,{children:s.jsx(UL,{children:s.jsx(fb,{value:e,children:s.jsxs(vb,{sendDaemonCommand:Ma,children:[s.jsx(u2,{}),s.jsxs(YL,{children:[s.jsx(d2,{}),s.jsxs(Vf,{children:[s.jsx(Rs,{path:"/dashboard",element:s.jsx(KT,{})}),s.jsx(Rs,{path:"/machine",element:s.jsx(Du,{})}),s.jsx(Rs,{path:"/machines/:id",element:s.jsx(nI,{})}),s.jsx(Rs,{path:"/machines",element:s.jsx(Du,{})}),s.jsx(Rs,{path:"/about",element:s.jsx(e2,{})}),s.jsx(Rs,{path:"/settings",element:s.jsx(s2,{})}),s.jsx(Rs,{path:"/mesh",element:s.jsx(PL,{children:s.jsx(AL,{})})}),s.jsx(Rs,{path:"/setup",element:s.jsx(QL,{})}),s.jsx(Rs,{path:"*",element:s.jsx(Ci,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}US({connectionManager:js});Yf(document.getElementById("root")).render(s.jsx(p2,{}));
|