@adhdev/daemon-standalone 1.0.24 → 1.0.26
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.
- package/dist/index.js +13 -12
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/public/assets/{index-CZHeDW5I.js → index-DLNB3eih.js} +5 -5
- package/public/index.html +1 -1
- package/vendor/mcp-server/index.js +1 -1
- package/vendor/mcp-server/index.js.map +1 -1
- package/vendor/mcp-server/package.json +1 -1
|
@@ -55,7 +55,7 @@ ${JSON.stringify(t,null,2)}
|
|
|
55
55
|
`),ue=((Pe=K[0])==null?void 0:Pe.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:()=>Y(q),children:[s.jsx("span",{className:"text-[10px] text-text-muted w-3",children:X?"▾":"▸"}),s.jsx("span",{className:"font-mono text-accent-primary w-20 shrink-0 text-[11px]",children:q}),!X&&s.jsx("span",{className:"text-text-secondary truncate font-mono text-[11px]",children:ue}),s.jsxs("span",{className:"ml-auto text-text-muted text-[10px] shrink-0",children:[K.length,"L"]})]}),X&&s.jsx("pre",{className:"px-3 pb-2.5 pt-1 font-mono text-[11px] text-text-secondary whitespace-pre-wrap break-all bg-bg-secondary max-h-40 overflow-y-auto border-t border-border-default",children:W||"(empty)"})]},q)})})]}),s.jsx(Br,{}),B.nativeSource&&s.jsxs("div",{children:[s.jsx(fn,{children:"State History"}),s.jsx("div",{className:"text-text-muted text-[11px] italic px-1",children:"N/A (native-source provider — no state-machine rules)"})]}),!B.nativeSource&&B.stateHistory&&B.stateHistory.length>0&&s.jsxs("div",{children:[s.jsxs(fn,{children:["State History (",B.stateHistory.length,")"]}),s.jsx("div",{className:"space-y-px",children:[...B.stateHistory].reverse().slice(0,20).map((q,W)=>s.jsxs("div",{className:"rounded px-2 py-1 hover:bg-bg-glass-hover transition-colors",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:`font-mono text-[11px] font-semibold px-1.5 py-0.5 rounded shrink-0 ${go(q.stateId)}`,children:q.stateId}),s.jsx("span",{className:"text-text-secondary text-[11px] shrink-0 tabular-nums",children:Yn(q.at)}),q.durationMs>0&&s.jsxs("span",{className:"text-text-muted text-[11px]",children:["held ",s.jsx("span",{className:"text-text-secondary",children:Ec(q.durationMs)})]}),q.reason&&s.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-mono shrink-0 ${Xk[String(q.reason)]??"text-text-secondary bg-bg-glass border border-border-default"}`,children:String(q.reason)}),q.debounceKind&&String(q.debounceKind)!=="none"&&s.jsxs("span",{className:"text-text-muted text-[10px] font-mono",children:["debounce:",String(q.debounceKind)]}),q.matchedStateId&&String(q.matchedStateId)!==q.stateId&&s.jsxs("span",{className:"text-text-muted text-[10px] font-mono",children:["eval→",s.jsx("span",{className:"text-text-secondary",children:String(q.matchedStateId)})]})]}),q.matchedRules&&q.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:[q.matchedRules.slice(0,3).map((X,K)=>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 X=="string"?X:JSON.stringify(X)},K)),q.matchedRules.length>3&&s.jsxs("span",{className:"text-[10px] text-text-muted",children:["+",q.matchedRules.length-3," more"]})]})]},W))})]}),s.jsx(Br,{}),(()=>{const q=B.messages??B.committedMessages??[];if(q.length===0)return null;const W=q.filter(ue=>ue.role==="user").length,X=q.filter(ue=>ue.role==="assistant").length,K=[...q].reverse().find(ue=>ue.role==="assistant");return s.jsxs("div",{children:[s.jsxs(fn,{children:["Transcript (",q.length," — ",W,"u / ",X,"a)"]}),K&&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 ",K.receivedAt?Yn(K.receivedAt):""]}),s.jsxs("div",{className:"text-text-secondary font-mono whitespace-pre-wrap line-clamp-4 break-all",children:[K.content.slice(0,400),K.content.length>400?"…":""]})]})]})})(),B.specPath&&s.jsx("div",{className:"text-[10px] text-text-muted font-mono truncate border-t border-border-default pt-2 mt-1",title:B.specPath,children:B.specPath}),s.jsxs("div",{children:[s.jsxs("button",{type:"button",className:"text-[11px] text-text-secondary hover:text-text-primary transition-colors flex items-center gap-1.5",onClick:()=>u(q=>!q),children:[s.jsx("span",{className:"text-text-muted",children:p?"▾":"▸"}),s.jsxs("span",{children:["Raw screen (",B.screen?B.screen.split(`
|
|
56
56
|
`).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:B.screen||"(empty)"})]})]})]})]})})}function sS({activeConv:e,clearToken:t=0,terminalRef:n,handleSendChat:r,isSendingChat:a=!1,sendFeedbackMessage:o=null,isVisible:i=!0,isInputActive:c=!0}){var $e;const{t:d}=Ce("common");js();const{sendPtyInput:p}=wt(),[u,m]=l.useState(!1),f=l.useRef(!1);f.current=u;const[g,k]=l.useState("Runtime terminal unavailable"),[h,v]=l.useState(!1),[w,b]=l.useState(null),[j,C]=l.useState(!1),[y,x]=l.useState(!1),[N,S]=l.useState(1),[A,T]=l.useState(!1),[I,D]=l.useState(!1),[P,_]=l.useState(!1),[G,H]=l.useState(!1),[L,O]=l.useState(!1),[E,M]=l.useState({width:0,height:0}),[$,R]=l.useState({width:0,height:0}),[z,Q]=l.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[ne,J]=l.useState(null),Z=l.useRef(null),de=l.useRef(null),te=l.useRef(!1),B=l.useRef(!1),ie=l.useRef(i),Y=l.useRef(0),le=l.useRef(!1),Ne=l.useRef(""),we=l.useRef(null),Se=l.useRef(!1),me=l.useRef(!1),q=l.useRef(null),W=l.useRef(null),X=l.useRef(null),K=32*1024,ue=()=>{var ae,ye,ke,Re;return((ye=(ae=Z.current)==null?void 0:ae.ownerDocument)==null?void 0:ye.defaultView)||((Re=(ke=de.current)==null?void 0:ke.ownerDocument)==null?void 0:Re.defaultView)||window},Pe=ae=>{const ye=ue();return{ownerWindow:ye,frameId:ye.requestAnimationFrame(ae)}},ce=()=>{const ae=q.current;if(ae){try{ae.ownerWindow.cancelAnimationFrame(ae.frameId)}catch{}q.current=null}},F=()=>{const ae=W.current;if(ae){try{ae.ownerWindow.clearTimeout(ae.timeoutId)}catch{}W.current=null}},pe=()=>{const ae=X.current;if(ae){try{ae.ownerWindow.clearTimeout(ae.timeoutId)}catch{}X.current=null}},xe=()=>{i&&q.current===null&&(q.current=Pe(()=>{ee()}))},U=e.tabKey,be=e.sessionId||"",je=e.daemonId||(($e=e.routeId)==null?void 0:$e.split(":")[0])||e.routeId||"",ge=sl(e),Ie=u?ge?ip:o:g,et=u&&o||null,Ze=Lk,rt=Rk,he=.05,Ee=()=>{const ae=$.width,ye=$.height;if(!Number.isFinite(E.width)||E.width<=0||!Number.isFinite(E.height)||E.height<=0||!Number.isFinite(ae)||ae<=0||!Number.isFinite(ye)||ye<=0)return 1;const ke=E.width/ae,Re=E.height/ye;return Number(Math.min(rt,Math.max(Ze,Math.min(ke,Re))).toFixed(2))},Be=Ee(),at=te.current&&N>Be,oe=Number.isFinite($.width)&&$.width>0?Math.max(E.width,Math.round($.width*N)):E.width,He=Number.isFinite($.height)&&$.height>0?Math.max(E.height,Math.round($.height*N)):E.height,lt=()=>{Pe(()=>{const ae=de.current;ae&&(ae.scrollLeft=0,ae.scrollTop=ae.scrollHeight-ae.clientHeight)})},ut=()=>{var ae,ye;Y.current=0,le.current=!1,Ne.current="",we.current=null,Se.current=!1,me.current=!1,te.current||(B.current=!1,S(1)),q.current!==null&&ce(),m(!1),k("Runtime terminal unavailable"),pe(),F(),b(null),J(null),T(!1),v(!1),C(!1),x(!1),(ye=(ae=n.current)==null?void 0:ae.reset)==null||ye.call(ae)},St=()=>{var ae,ye;Y.current=0,le.current=!1,Ne.current="",we.current=null,Se.current=!1,me.current=!1,q.current!==null&&ce(),m(!0),k(""),pe(),F(),b(null),J(null),T(!1),v(!1),C(!1),x(!1),(ye=(ae=n.current)==null?void 0:ae.reset)==null||ye.call(ae)},V=()=>{me.current&&(me.current=!1,Pe(()=>{var ae,ye;(ye=(ae=n.current)==null?void 0:ae.scrollToTop)==null||ye.call(ae)}))},ee=()=>{if(q.current=null,!i)return;const ae=Ne.current;if(!ae)return;const ye=ae.slice(0,K);Ne.current=ae.slice(ye.length);const ke=n.current;if(!ke){Ne.current=ye+Ne.current,xe();return}ke.write(ye,()=>{if(Ne.current.length>0){xe();return}V()})},re=ae=>{ae&&(Ne.current+=ae,xe())},fe=(ae,ye=0,ke,Re,Ge={})=>{var Oe,bt,qt,Gt;const ot=!!Ge.force;!ot&&ye>0&&Y.current>=ye||!ot&&ye===0&&le.current||(Y.current=ye,ye>0&&C(!0),m(!0),k(""),typeof ke=="number"&&typeof Re=="number"&&ke>0&&Re>0&&((bt=(Oe=n.current)==null?void 0:Oe.resize)==null||bt.call(Oe,ke,Re)),Ne.current="",(Gt=(qt=n.current)==null?void 0:qt.reset)==null||Gt.call(qt),ae?re(ae):V())};l.useEffect(()=>{ut()},[be]),l.useEffect(()=>{var ye;if(!be)return;const ae=((ye=Ct.onRuntimeEvent)==null?void 0:ye.call(Ct,be,ke=>{if(!(!ke||ke.sessionId!==be)){if(ke.type==="runtime_snapshot"){if(!i){we.current={text:ke.text||"",seq:ke.seq||0,cols:ke.cols,rows:ke.rows,force:!!ke.force};return}fe(ke.text||"",ke.seq||0,ke.cols,ke.rows,{force:!!ke.force});return}if(ke.type==="session_output"){le.current=!0,typeof ke.seq=="number"&&(Y.current=Math.max(Y.current,ke.seq),ke.seq>0&&C(!0)),f.current||m(!0),f.current||k(""),typeof ke.data=="string"&&re(ke.data);return}if(ke.type==="session_cleared"){if(!i){Se.current=!0,Ne.current="",we.current=null;return}St();return}if(ke.type==="session_io_error"){const Re=typeof ke.error=="string"&&ke.error?ke.error:typeof ke.reason=="string"&&ke.reason?ke.reason:"unknown error";m(!1),k(`Runtime input failed: ${Re}`);return}}},je))||(()=>{});return()=>{ae()}},[je,be,n,i]);const ve=async(ae={})=>{var ye;if(!je||!be)return{success:!1,error:"daemonId and sessionId are required"};ae.preserveStatus||k(ae.loadingMessage||"Loading runtime terminal...");try{const ke=await((ye=Ct.requestRuntimeSnapshot)==null?void 0:ye.call(Ct,je,be,{sinceSeq:ae.sinceSeq,force:ae.force}));return ke&&ke.success===!1?(ae.preserveStatus||(m(!1),k(`Runtime terminal unavailable: ${ke.error}`)),ke):ke||{success:!0}}catch(ke){const Re=(ke==null?void 0:ke.message)||String(ke);return ae.preserveStatus||(m(!1),k(`Runtime terminal unavailable: ${Re}`)),{success:!1,error:Re}}},De=async ae=>{var ot,Oe;const ye=((ot=Z.current)==null?void 0:ot.ownerDocument)||document,ke=ye.defaultView||window,Re=(Oe=ke.navigator)==null?void 0:Oe.clipboard;if(Re!=null&&Re.writeText&&ke.isSecureContext)try{return await Re.writeText(ae),!0}catch{}let Ge=null;try{return Ge=ye.createElement("textarea"),Ge.value=ae,Ge.setAttribute("readonly","true"),Ge.style.position="fixed",Ge.style.left="-9999px",Ge.style.top="0",ye.body.appendChild(Ge),Ge.focus(),Ge.select(),ye.execCommand("copy")}catch{return!1}finally{Ge==null||Ge.remove()}},_e=ae=>{F(),J(ae);const ye=ue();W.current={ownerWindow:ye,timeoutId:ye.setTimeout(()=>{W.current=null,J(ke=>ke===ae?null:ke)},2200)}},Te=ae=>{pe(),b(ae);const ye=ue();X.current={ownerWindow:ye,timeoutId:ye.setTimeout(()=>{X.current=null,b(ke=>ke===ae?null:ke)},2200)}},qe=async()=>{var Ge,ot,Oe,bt;const ae=((ot=(Ge=n.current)==null?void 0:Ge.getSelection)==null?void 0:ot.call(Ge))||"",ye=((bt=(Oe=n.current)==null?void 0:Oe.getVisibleText)==null?void 0:bt.call(Oe))||"",ke=ae.trimEnd()||ye.trimEnd();if(!ke){_e("Nothing to copy");return}if(!await De(ke)){_e("Copy failed");return}_e(ae.trimEnd()?"Copied selection":"Copied visible terminal")},Xe=ae=>{if(!u||!i)return;((p==null?void 0:p(je,be,ae))??!1)||_e("Terminal input failed")},Ve=ae=>{Xe(_k({ctrl:I,alt:P,shift:G},ae)),D(!1),_(!1),H(!1)},Fe=async()=>{if(h)return;v(!0),b("Loading older terminal output..."),me.current=!0;const ae=await ve({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:u});if(v(!1),(ae==null?void 0:ae.success)===!1){me.current=!1,b(`Older terminal output unavailable: ${ae.error}`);return}x(!0),Te("Older terminal output loaded"),Pe(()=>{var ye;(ye=n.current)==null||ye.bumpResize()})};l.useEffect(()=>{var ye,ke;if(!be)return;je&&((ye=Ct.getState)==null?void 0:ye.call(Ct,je))==="connected"&&ve();const ae=(ke=Ct.onStateChange)==null?void 0:ke.call(Ct,(Re,Ge)=>{Re!==je||Ge!=="connected"||ve()});return()=>{ae==null||ae()}},[je,be,n]),l.useEffect(()=>{t&&ut()},[t,U,n]),l.useEffect(()=>{var Re,Ge;const ae=Z.current,ye=(Ge=(Re=ae==null?void 0:ae.ownerDocument)==null?void 0:Re.defaultView)==null?void 0:Ge.ResizeObserver;if(!ae||!ye)return;const ke=new ye(ot=>{const Oe=ot[0];if(!Oe)return;const{width:bt,height:qt}=Oe.contentRect;M(Gt=>{const Zt=Math.round(bt),Jt=Math.round(qt);return Gt.width===Zt&&Gt.height===Jt?Gt:{width:Zt,height:Jt}})});return ke.observe(ae),()=>ke.disconnect()},[]),l.useEffect(()=>{if(te.current)return;const ae=Ee();!Number.isFinite(ae)||ae<=0||S(ye=>B.current?ae<ye-he?ae:ye:(B.current=!0,ae))},[$.height,$.width,E.height,E.width]),l.useEffect(()=>{at&<()},[at,He,oe]),l.useEffect(()=>{var ke;const ae=ie.current;if(ie.current=i,!i)return;ae||x(!1),Se.current&&(Se.current=!1,St());const ye=we.current;ye&&(we.current=null,fe(ye.text,ye.seq,ye.cols,ye.rows,{force:!!ye.force})),je&&be&&((ke=Ct.getState)==null?void 0:ke.call(Ct,je))==="connected"&&ve(),Ne.current&&q.current===null&&xe(),Pe(()=>{var Re;(Re=n.current)==null||Re.bumpResize()})},[je,i,be]),l.useEffect(()=>()=>{q.current!==null&&ce(),F(),pe()},[]),l.useEffect(()=>{const ae=Re=>{var ot;const Ge=Re.detail;Ge!=null&&Ge.sessionId&&Ge.sessionId!==be||u&&((ot=n.current)==null||ot.bumpResize())},ye=ue(),ke=ye===window?[window]:[window,ye];for(const Re of ke)Re.addEventListener("adhdev:fit-cli-terminal",ae);return()=>{for(const Re of ke)Re.removeEventListener("adhdev:fit-cli-terminal",ae)}},[u,be,n]);const Qe=u&&j&&!y&&(z.atTop||!z.canScroll)||h||!!w;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:Z,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[Qe&&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:()=>{Fe()},disabled:!be||h,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:d(h?"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:[ne&&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:ne}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>O(ae=>!ae),title:"Spec debug — inspect current state, sections, and transition history",children:d("terminal.debug")}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{qe()},disabled:!u,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:d("terminal.copy")}),s.jsxs("div",{className:"relative",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>T(ae=>!ae),disabled:!u,"aria-label":d(A?"terminal.closeControlKeys":"terminal.openControlKeys"),"aria-expanded":A,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),A&&s.jsxs("div",{id:"terminal-control-keys-popover",role:"dialog","aria-label":d("terminal.openControlKeys"),className:"absolute right-0 top-10 w-72 rounded-2xl border border-white/10 bg-[#0b0d12]/95 p-3 text-white/85 shadow-2xl shadow-black/40 backdrop-blur-md",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Terminal keys"}),s.jsx("button",{type:"button",className:"rounded-full px-2 py-0.5 text-[11px] text-white/55 transition-colors hover:bg-white/10 hover:text-white/85",onClick:()=>T(!1),"aria-label":d("terminal.closeControlKeys"),children:"×"})]}),s.jsx("div",{className:"mb-2 grid grid-cols-3 gap-1.5",children:[["Ctrl",I,D],["Alt",P,_],["Shift",G,H]].map(([ae,ye,ke])=>s.jsx("button",{type:"button","aria-pressed":ye,className:`h-9 rounded-lg border text-[12px] font-semibold transition-colors ${ye?"border-sky-400/50 bg-sky-400/25 text-white":"border-white/10 bg-white/[0.06] hover:bg-white/[0.12]"}`,onClick:()=>ke(Re=>!Re),children:ae},ae))}),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:()=>Ve("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:()=>Ve("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:()=>Ve("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:()=>Ve("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:()=>Ve("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:()=>Ve("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:()=>Ve("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:()=>Xe(""),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:()=>Ve("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:()=>Ve("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:()=>{te.current=!0,S(ae=>{const ye=Math.max(Be,Number((ae-.1).toFixed(2)));return ye>Be&<(),ye})},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:()=>{te.current=!0,S(ae=>{const ye=Math.min(rt,Number((ae+.1).toFixed(2)));return ye>Be&<(),ye})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:de,className:at?"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:oe>0?`${oe}px`:"100%",height:He>0?`${He}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:N},children:s.jsx(Au,{ref:n,readOnly:!u||!i,sizingMode:"measured",onViewportMetrics:R,onScrollMetrics:Q,onInput:ae=>{!u||(p==null||p(je,be,ae))}})})})}),!u&&s.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:g})]}),s.jsx(Ku,{contextKey:e.tabKey,panelLabel:yt(e),isSending:a,isBusy:!!ge,statusMessage:Ie,inlineStatusMessage:et,onSend:async ae=>ge?!1:r(ae),isActive:c&&i,showControlsToggle:!1,animateVisibility:!1}),L&&s.jsx(tS,{activeConv:e,onClose:()=>O(!1)})]})}const nS=5e3,rS=12e3;function aS(e){return e==="disconnected"||e==="reconnecting"}function oS({wsStatus:e,showReconnected:t,loginUrl:n,onReconnect:r,reconnectDelayMs:a=nS,reconnectActionDelayMs:o=rS}){const{t:i}=Ce(),c=aS(e),[d,p]=l.useState(()=>!c||a<=0),[u,m]=l.useState(()=>!c||o<=0),f=l.useRef(!1);l.useEffect(()=>{if(!c){p(!1);return}if(f.current=!1,a<=0){f.current=!0,p(!0);return}p(!1);const x=setTimeout(()=>{f.current=!0,p(!0)},a);return()=>clearTimeout(x)},[a,c]),l.useEffect(()=>{if(!c){m(!1);return}if(o<=0){m(!0);return}m(!1);const x=setTimeout(()=>{m(!0)},o);return()=>clearTimeout(x)},[o,c]);const g=c?d:e==="offline"||e==="auth_failed",k=!!(r&&e!=="auth_failed"&&(!c||u)),h=l.useMemo(()=>!t||e!=="connected"?!1:a<=0||f.current,[a,t,e]),v=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)"},j={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},C="fixed left-1/2 top-4 z-[var(--z-toast)] flex items-center justify-center pointer-events-none",y={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[g&&s.jsx("div",{className:C,style:y,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[v],border:b[v],color:j[v]},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:()=>r==null?void 0:r(),disabled:e==="offline",children:i("connection.reconnectNow")})]})}),h&&s.jsx("div",{className:C,style:y,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 Lp({mode:e,onChange:t,compact:n=!1}){const{t:r}=Ce("common"),a=n?14:15;return s.jsx("button",{type:"button",onClick:()=>t(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:r(e==="chat"?"cliView.switchToTerminal":"cliView.switchToChat"),children:e==="chat"?s.jsx(Ui,{size:a}):s.jsx(un,{size:a})})}function iS(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 lS(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 cS(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 ka({git:e,className:t="",compact:n=!1}){const r=iS(e),a=lS(e);if(!r||!a)return null;const o=[e!=null&&e.branch?`Branch: ${e.branch}`:null,e!=null&&e.changedFiles?`Changed files: ${e.changedFiles}`:null,e!=null&&e.ahead?`Ahead: ${e.ahead}`:null,e!=null&&e.behind?`Behind: ${e.behind}`:null,e!=null&&e.hasConflicts?"Conflicts detected":null,e!=null&&e.error?`Git error: ${e.error}`:null].filter(Boolean);return s.jsxs("span",{className:`inline-flex min-w-0 max-w-[12rem] items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-semibold leading-none ${cS(a)} ${t}`.trim(),title:o.join(" · ")||r,"data-git-tone":a,children:[s.jsx("span",{"aria-hidden":"true",children:"⑂"}),s.jsx("span",{className:"truncate",children:r})]})}function dS({wsStatus:e,isConnected:t,daemonCount:n,p2pStates:r={}}){if(e!=="connected")return{tone:"disconnected",titleKey:"connection.disconnected",subtitleKey:null};const a=Object.values(r),o=a.filter(c=>c==="connected").length,i=a.filter(c=>c==="connecting"||c==="new"||c==="checking").length;return n>0&&i>0&&o===0?{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:"connection.connectingToMachine"}:t?{tone:"connected",titleKey:"connection.connected",subtitleKey:null}:{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:null}}function _c({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function $c({notification:e,shortcutIndex:t,onOpen:n,onMarkRead:r,onMarkUnread:a,onDelete:o}){const{t:i}=Ce(),c=$a(e.updatedAt),d=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${d?"is-attention":""}`.trim(),children:[s.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:n,children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[t?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",t]}):null,[e.type==="needs_attention"?i("notification.actionNeeded"):i("notification.taskComplete"),c].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[d?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:p=>{p.stopPropagation(),r()},children:i("notification.markRead")}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:p=>{p.stopPropagation(),a()},children:i("notification.markUnread")}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:p=>{p.stopPropagation(),o()},children:i("notification.delete")})]})]})}function uS({activeConv:e,wsStatus:t,isConnected:n,conversations:r,onOpenHistory:a,onOpenRemote:o,onStopCli:i,activeCliViewMode:c,onSetCliViewMode:d,onHideConversation:p,hiddenConversations:u=[],onShowConversation:m,onShowAllHidden:f,onResetPanelsToMain:g,inboxOpen:k,onInboxOpenChange:h,hiddenOpen:v,onHiddenOpenChange:w,onOpenNewSession:b,onOpenDashboardGuide:j,guideNudgeVisible:C=!1,actionShortcuts:y,notifications:x,notificationUnreadCount:N,onOpenNotification:S,onMarkNotificationRead:A,onMarkNotificationUnread:T,onDeleteNotification:I,onOpenGitDialog:D,onOpenMeshGraph:P}){var X;const{t:_}=Ce(),{ides:G,p2pStates:H={}}=js(),L=!!e&&mt(e)&&!dt(e),O=!!e&&dt(e),E=!!(e!=null&&e.daemonId)&&!!((X=e==null?void 0:e.coordinator)!=null&&X.meshId),M=c||(e?tp(e)?"terminal":"chat":null),[$,R]=l.useState(!1),[z,Q]=l.useState(!1),ne=l.useRef(null),J=l.useRef(null),Z=l.useRef(null),de=G.filter(K=>K.type==="adhdev-daemon"),te=dS({wsStatus:t,isConnected:n,daemonCount:de.length,p2pStates:H}),B=_(te.titleKey),ie=te.subtitleKey?_(te.subtitleKey):null,Y=te.tone==="connected"?"#22c55e":te.tone==="limited"?"#eab308":"#ef4444",le=te.tone==="connected"?"0 0 4px #22c55e80":te.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",Ne=l.useMemo(()=>x.filter(K=>!K.readAt),[x]),we=l.useMemo(()=>x.filter(K=>!!K.readAt),[x]),Se=l.useMemo(()=>Ne.slice(0,9),[Ne]),me=N;l.useEffect(()=>{if(!k)return;const K=ue=>{var Pe;(Pe=J.current)!=null&&Pe.contains(ue.target)||h(!1)};return document.addEventListener("mousedown",K),()=>document.removeEventListener("mousedown",K)},[k,h]),l.useEffect(()=>{if(!v)return;const K=ue=>{var Pe;(Pe=Z.current)!=null&&Pe.contains(ue.target)||w(!1)};return document.addEventListener("mousedown",K),()=>document.removeEventListener("mousedown",K)},[v,w]),l.useEffect(()=>{if(!v&&!k)return;const K=ue=>{if(!ue.altKey)return;const Pe=ue.code.match(/^Digit([1-9])$/);if(!Pe)return;const ce=Number(Pe[1])-1,F=v?u[ce]:void 0,pe=k?Se[ce]:void 0;if(!(!F&&!pe)){if(ue.preventDefault(),ue.stopPropagation(),F){m==null||m(F),w(!1);return}pe&&(S(pe),h(!1))}};return window.addEventListener("keydown",K,!0),()=>window.removeEventListener("keydown",K,!0)},[u,v,k,Se,w,h,S,m]),l.useEffect(()=>{const K=u.length;if(ne.current===null){ne.current=K;return}K>ne.current&&Q(!0),ne.current=K},[u.length]);const q=()=>Q(!1),W=K=>{if(!K)return;const ue=r.find(Pe=>Pe.tabKey===K);ue&&(p==null||p(ue))};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(un,{size:18}),s.jsx("span",{className:"header-title-desktop",children:_("dashboard.header.title")}),s.jsx("span",{className:"header-title-mobile",children:e?yt(e):_("dashboard.header.title")}),s.jsx("span",{title:B,"aria-label":B,className:"header-title-status-dot",style:{background:Y,boxShadow:le}}),s.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:s.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:Y,boxShadow:le}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[ie&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",ie]}),b&&s.jsx("button",{type:"button",onClick:b,className:"btn btn-secondary btn-sm ml-2",title:`${_("paneGroup.newSession")}${y!=null&&y.openNewSession?` (${y.openNewSession})`:""}`,"aria-label":_("paneGroup.newSession"),children:s.jsx(Gi,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[j&&s.jsxs("button",{type:"button",onClick:j,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:_("dashboard.header.guide"),"aria-label":_("dashboard.header.guideOpen"),children:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),C&&s.jsx("span",{children:_("dashboard.header.guideShort")})]}),e&&(L||O||!dt(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:In(e)||yt(e),children:yt(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:_("dashboard.header.openGitStatus"),onClick:()=>D(e.daemonId,e.workspacePath),children:s.jsx(ka,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(ka,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),E&&P&&s.jsxs("button",{type:"button",onClick:()=>P(e),className:"btn btn-secondary btn-sm dashboard-header-mesh-button",title:_("dashboard.header.openMeshGraph"),children:[s.jsx(rs,{size:14}),s.jsx("span",{className:"hidden lg:inline",children:_("dashboard.header.meshGraph")})]}),(L||O)&&i&&s.jsxs(s.Fragment,{children:[L&&d&&M&&s.jsx(Lp,{mode:M,onChange:d,compact:!0}),s.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:_(O?"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(Tt,{size:14})})]}),!dt(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:_("dashboard.header.chatHistory"),children:s.jsx(Oi,{size:14})}),!L&&!dt(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:_("dashboard.header.remoteControl"),children:s.jsx(gs,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:J,children:[s.jsxs("div",{className:`dashboard-header-hidden${$?" is-drop-target":""}${z?" hidden-spawn-flash":""}${(u??[]).some(gr)?" hidden-generating-spin":""}`,onAnimationEnd:q,ref:Z,onDragEnter:K=>{K.dataTransfer.types.includes("text/tab-key")&&(K.preventDefault(),R(!0))},onDragOver:K=>{K.dataTransfer.types.includes("text/tab-key")&&(K.preventDefault(),K.dataTransfer.dropEffect="move",R(!0))},onDragLeave:K=>{K.currentTarget.contains(K.relatedTarget)||R(!1)},onDrop:K=>{const ue=K.dataTransfer.getData("text/tab-key");K.preventDefault(),R(!1),W(ue)},children:[s.jsxs("button",{type:"button",onClick:()=>w(!v),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`${_("dashboard.hidden.title")}${y!=null&&y.toggleHiddenTabs?` (${y.toggleHiddenTabs})`:""}. ${_("dashboard.hidden.dragHint")}`,children:[s.jsx(Wi,{size:16}),u.length>0&&s.jsx("span",{className:`dashboard-header-hidden-badge${z?" hidden-badge-pop":""}`,children:u.length})]}),v&&s.jsxs("div",{className:"dashboard-header-hidden-popover",children:[s.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:_("dashboard.hidden.title")}),s.jsx(_c,{value:y==null?void 0:y.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[g&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:g,children:_("dashboard.hidden.resetPanels")}),u.length>0&&f&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{f(),w(!1)},children:_("dashboard.hidden.restoreAll")})]})]}),e&&p&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>p(e),children:[s.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[s.jsx("span",{className:"dashboard-header-hidden-current-label",children:_("dashboard.hidden.hideCurrentTab")}),s.jsx(_c,{value:y==null?void 0:y.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:yt(e)})]}),u.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(K=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{m==null||m(K),w(!1)},children:[s.jsxs("span",{className:"dashboard-header-inbox-item-title",children:[gr(K)&&s.jsx("span",{className:"tab-spinner dashboard-header-inbox-item-spinner","aria-label":_("dashboard.header.generating")}),yt(K)]}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(K)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(K)+1]}):null,In(K)]})]},K.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:_("dashboard.hidden.empty")})]})]}),s.jsxs("button",{type:"button",onClick:()=>h(!k),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:_("dashboard.header.activityInbox"),children:[s.jsx(Hn,{size:16}),me>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:me})]}),k&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[Ne.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:_("dashboard.inbox.unread")}),Ne.map(K=>s.jsx($c,{notification:K,shortcutIndex:Se.indexOf(K)>=0?Se.indexOf(K)+1:void 0,onOpen:()=>S(K),onMarkRead:()=>A(K.id),onMarkUnread:()=>T(K.id),onDelete:()=>I(K.id)},K.id))]}),we.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:_("dashboard.inbox.read")}),we.map(K=>s.jsx($c,{notification:K,onOpen:()=>S(K),onMarkRead:()=>A(K.id),onMarkUnread:()=>T(K.id),onDelete:()=>I(K.id)},K.id))]}),x.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:_("dashboard.inbox.empty")})]})]})]})]})}function Wt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function pS(e,t){return String(e||"")!==String(t||"")}function mS(e,t={}){const n=String(t.textQuery||"").trim().toLowerCase(),r=String(t.workspaceQuery||"").trim().toLowerCase(),a=String(t.modelQuery||"").trim().toLowerCase(),o=!!t.resumableOnly;return!n&&!r&&!a&&!o?e:e.filter(i=>!(o&&!i.canResume||n&&![i.title,i.preview].map(d=>String(d||"").toLowerCase()).join(`
|
|
57
57
|
`).includes(n)||r&&!String(i.workspace||"").toLowerCase().includes(r)||a&&!Ou(i.summaryMetadata).map(d=>d.toLowerCase()).join(`
|
|
58
|
-
`).includes(a)))}function hS(e,t="recent"){const n=e.slice();return n.sort((r,a)=>{if(t==="oldest")return(Number(r.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(t==="messages"){const o=(Number(a.messageCount)||0)-(Number(r.messageCount)||0);if(o!==0)return o}return(Number(a.lastMessageAt)||0)-(Number(r.lastMessageAt)||0)}),n}function Rp(e,t={}){return hS(mS(e,t),t.sortMode||"recent")}function vi(e,t){return typeof e=="function"?e(t??!1?"launch.resumeSavedHistory":"launch.startFresh"):e?"Resume saved history":"Start fresh"}function Ep(e,t){return typeof e=="function"?e(t??!1?"launch.resumingSavedHistory":"launch.startingFresh"):e?"Resuming saved history…":"Starting fresh…"}function fS(e){return e?e("launch.startFresh"):"Start fresh"}function bS(e){return e?e("launch.hostedRuntimeRecoveryDescription"):"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function gS(e){return e?e("launch.openSavedHistory"):"Open saved history"}function xS(e){return e?e("launch.savedHistoryTitle"):"Saved History"}function ol(e){return e?e("launch.savedHistoryHelper"):"Use saved history when you want continuity in the same provider conversation."}function vS(e){return e?e("launch.savedHistoryEmpty"):"No saved history found yet."}function yS(e){return e?e("launch.refreshSavedHistory"):"Refresh saved history"}function wS(e){return e?e("launch.refreshingSavedHistory"):"Refreshing saved history…"}function Sa(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 r=e,a=t;return r==="start-fresh"?`Start fresh with ${a}?`:`Restart ${a}?`}function Ca(e,t){if(typeof e=="function"){const r=t;return e(r==="start-fresh"?"launch.startFreshReview":r==="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 ja(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartFresh":"launch.confirmRestart"):e==="start-fresh"?"Start fresh":"Restart"}function Na(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartingFresh":"launch.confirmRestarting"):e==="start-fresh"?"Starting fresh…":"Restarting…"}function _p(e,t){return typeof e=="function"?e("launch.resumeWith",{label:t}):`Resume saved history with ${e}?`}function $p(e){return e?e("launch.resumeReview"):"Review or change the target workspace before resuming saved history."}function kS(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 Hp({activeConv:e,ides:t,isCreatingChat:n,isRefreshingHistory:r,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:c,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:p,onClose:u,onNewChat:m,onSwitchSession:f,onRefreshHistory:g,onResumeSavedSession:k}){var D;const{t:h}=Ce("common"),v=t.find(P=>P.id===e.routeId),w=(v==null?void 0:v.chats)||[],b=(D=v==null?void 0:v.activeChat)==null?void 0:D.id,j=mt(e)&&!dt(e),[C,y]=l.useState(()=>Wt()),x=c||C,N=String(d||"").trim(),S=P=>{if(p){p(P);return}y(P)},A=l.useMemo(()=>a.map(P=>{const _=String(P.workspace||"").trim();return P.canResume||_||!N?P:{...P,workspace:N,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[N,a]),T=l.useMemo(()=>Rp(A,{textQuery:x.textQuery,workspaceQuery:x.workspaceQuery,modelQuery:x.modelQuery,resumableOnly:x.resumableOnly,sortMode:x.sortMode}),[A,x.modelQuery,x.resumableOnly,x.sortMode,x.textQuery,x.workspaceQuery]),I=s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:u,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:j?xS(h):h("historyModal.chatHistory")}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Ok(e)}),j&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:ol(h)})]}),s.jsx("button",{onClick:u,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(Tt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!j&&s.jsx("button",{onClick:m,disabled:n,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:h(n?"historyModal.creating":"historyModal.startNewChat")}),j?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:x.textQuery,onChange:P=>S({...x,textQuery:P.target.value}),placeholder:h("historyModal.searchPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:x.workspaceQuery,onChange:P=>S({...x,workspaceQuery:P.target.value}),placeholder:h("historyModal.filterWorkspace"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:x.modelQuery,onChange:P=>S({...x,modelQuery:P.target.value}),placeholder:h("historyModal.filterModel"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsxs("select",{value:x.sortMode,onChange:P=>S({...x,sortMode:P.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:h("historyModal.sortRecent")}),s.jsx("option",{value:"oldest",children:h("historyModal.sortOldest")}),s.jsx("option",{value:"messages",children:h("historyModal.sortMessages")})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:x.resumableOnly,onChange:P=>S({...x,resumableOnly:P.target.checked})}),h("historyModal.resumeReadyOnly")]})]}),T.map(P=>{const _=e.providerSessionId===P.providerSessionId,G=_||!P.canResume||!!i,H=P.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{G||!k||k(P)},disabled:G,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${_?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${G?"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 ${_?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:P.title||h("historyModal.untitledSession")}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:P.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:kS(P.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:P.preview||h("historyModal.noSavedPreview")}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[P.workspace||h("historyModal.workspaceUnknown"),H?h("historyModal.selectedWorkspaceSuffix"):"",ln(P.summaryMetadata)?` · ${ln(P.summaryMetadata)}`:"",P.messageCount>0?` · ${h("historyModal.msgCount",{count:P.messageCount})}`:""]}),s.jsx("div",{className:"shrink-0",children:_?h("historyModal.statusActive"):P.canResume?H?h("historyModal.statusResumeSelectedWorkspace"):i===P.providerSessionId?h("historyModal.statusResuming"):h("historyModal.statusResume"):h("historyModal.statusMissingWorkspace")})]})]},P.id)})]}):w.map(P=>s.jsxs("div",{onClick:()=>{f(e.routeId,P.id),u()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${b===P.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[s.jsx("div",{className:`font-bold text-sm mb-1 ${b===P.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:P.title||h("historyModal.untitledSession")}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[P.id.substring(0,12),"..."]}),b===P.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:h("historyModal.statusActive")})]})]},P.id)),(j&&!o&&T.length===0||!j&&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(tb,{size:32})}),s.jsx("div",{className:"text-[13px]",children:j?a.length>0?h("historyModal.noMatchingHistory"):vS(h):h("historyModal.noRecentChats")})]}),j&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:wS(h)})})]}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:s.jsx("button",{onClick:g,disabled:r||o,className:"btn btn-secondary btn-sm rounded-[10px]",children:r||o?h("historyModal.refreshing"):s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(_a,{size:13})," ",j?yS(h):h("historyModal.refreshHistory")]})})})]})]});return typeof document>"u"?I:an.createPortal(I,document.body)}const Hc={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 Fp({toasts:e,onDismiss:t,onClickToast:n}){const{t:r}=Ce();return s.jsx("div",{className:"fixed right-4 z-[var(--z-toast)] flex flex-col gap-2 pointer-events-none",style:{top:"calc(env(safe-area-inset-top, 0px) + 16px)"},children:e.map(a=>{const o=Hc[a.type]||Hc.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=a.actions)!=null&&i.length||n&&n(a)},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(a.id)},"aria-label":r("toast.dismiss"),children:s.jsx(Tt,{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:r(o.labelKey)})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:a.message}),a.actions&&a.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:a.actions.map((i,c)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:i.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:d=>{d.stopPropagation(),i.onClick(),t(a.id)},children:i.label},c))})]})]},a.id)})})}const SS=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function CS(e){const t=e.workspace||"";if(!t)return"";const n=t.split(/[/\\]/).filter(Boolean);return n.length>0?n[n.length-1]:t}function jS(e,t){return Bp(e)||t}function Bp(e){var a,o,i;const t=(o=(a=e.summaryMetadata)==null?void 0:a.items)==null?void 0:o.find(c=>(c==null?void 0:c.id)==="model"),n=((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim();if(n)return n;const r=(i=e.controlValues)==null?void 0:i.model;return typeof r=="string"&&r.trim()?r.trim():""}function NS(e){return Bp(e)||void 0}function AS(e){return e.sessionId||e.instanceId||e.agentType}function Op(e=[]){const t={};for(const n of e)n.type==="adhdev-daemon"&&(t[n.id]=as(n,{fallbackId:n.id}));return t}function Wp(e,t={}){var r;const n=e.daemonId||((r=e.id)==null?void 0:r.split(":")[0])||e.id;return{machineName:Gy(e,t.machineNames),connectionState:t.connectionStates?t.connectionStates[n]||t.defaultConnectionState||"new":t.defaultConnectionState}}function il(e,t={}){return TS(e,Wp(e,t))}function TS(e,t={}){var f,g,k,h,v,w,b,j,C;const n=[],r=t.machineName,a=t.connectionState,o=CS(e),i=e.workspace||"",c=Jy(e.type,{agentName:e.cliName}),d=mt(e)||dt(e)?c:Ht(e.type),p=jS(e,d),u=Array.isArray(e.childSessions)?e.childSessions.map(y=>{var x,N,S;return{sessionId:y.id,instanceId:y.id,providerSessionId:y.providerSessionId,activeChatId:(x=y.activeChat)==null?void 0:x.id,transport:y.transport,sessionCapabilities:y.capabilities,agentType:y.providerType,agentName:y.providerName||Ht(y.providerType),model:NS(y),status:y.status,title:y.title,lastMessagePreview:y.lastMessagePreview,lastMessageRole:y.lastMessageRole,lastMessageAt:y.lastMessageAt,lastMessageHash:y.lastMessageHash,messages:((N=y.activeChat)==null?void 0:N.messages)||[],activeModal:((S=y.activeChat)==null?void 0:S.activeModal)||void 0,unread:y.unread,lastSeenAt:y.lastSeenAt,lastUpdated:y.lastUpdated,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,surfaceHidden:y.surfaceHidden,muted:y.muted,git:y.git,settings:y.settings,coordinator:y.coordinator,messageInput:y.messageInput}}):[],m=SS(e);if(m){const y=e.sessionId||e.instanceId,x=(f=e.settings)==null?void 0:f.meshCoordinatorFor,N=((g=e.settings)==null?void 0:g.meshNodeFor)||!((k=e.settings)!=null&&k.meshCoordinatorFor)&&((h=e.settings)==null?void 0:h.launchedByCoordinator),S=x?" (Coordinator)":N?" (Mesh Node)":"",A=c+S,T=(v=e.activeChat)==null?void 0:v.activeModal,I=T&&Array.isArray(T.buttons)&&T.buttons.length>0,D=Qy(e.activeChat,[{status:e.status,activeModal:(w=e.activeChat)==null?void 0:w.activeModal}],e.agents||[]),P=e.activeChat||{title:"",messages:[]};let _=P.title&&String(P.title).trim()?String(P.title).trim():"";const G=(b=e.activeChat)==null?void 0:b.id,H=e.chats;if(G&&Array.isArray(H)&&H.length>0){const Q=H.find(ne=>ne.id===G||ne.id&&String(ne.id)===String(G));Q!=null&&Q.title&&String(Q.title).trim()&&(_=String(Q.title).trim())}const L=(mt(e)||dt(e),e.type),O=(mt(e)||dt(e))&&ic(_,A,L)?"":_,E=P.messages||[],M=typeof G=="string"?G.trim():"",$=(mt(e)||dt(e))&&M===String(e.type||"").trim(),R=M&&!$?M:e.providerSessionId,z=e.coordinator||(typeof((j=e.settings)==null?void 0:j.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:y,providerSessionId:e.providerSessionId,historySessionId:R,nativeSessionId:y,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:mt(e)&&e.mode||"chat",agentName:A,agentType:L,status:D,title:O,messages:E,resume:e.resume,hostIdeType:!mt(e)&&!dt(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||O||(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?T.buttons:void 0,modalMessage:I?T.message:void 0,streamSource:"native",tabKey:lo(y,e.id),machineName:r,connectionState:a,settings:e.settings,coordinator:z,messageInput:e.messageInput})}if(m&&(mt(e)||dt(e)))return n;for(const y of u){const x=y.activeModal&&Array.isArray(y.activeModal.buttons)&&y.activeModal.buttons.length>0,N=Xy(y),S=AS(y),A=`${e.id}:${S}`,T=y.title&&String(y.title).trim()||"",I=ic(T,y.agentName,y.agentType)?"":T,D=y.messages||[];if(!(y.transport==="cdp-webview"||!!y.sessionId||!!y.providerSessionId||D.length>0||x||!!I||!["idle","panel_hidden","disconnected","not_monitored"].includes(N)))continue;const _=y.coordinator||(typeof((C=y.settings)==null?void 0:C.meshCoordinatorFor)=="string"&&y.settings.meshCoordinatorFor?{meshId:y.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:y.sessionId||y.instanceId,providerSessionId:y.providerSessionId,historySessionId:y.activeChatId||y.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:y.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:y.sessionCapabilities,mode:"chat",agentName:y.agentName,agentType:y.agentType,status:N,title:I,messages:D,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:y.git||e.git,displayPrimary:o||I||y.agentName||d,displaySecondary:y.model&&y.model.trim()?y.model.trim():`${d} · ${y.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:y.lastMessagePreview,lastMessageRole:y.lastMessageRole,lastMessageAt:y.lastMessageAt,lastMessageHash:y.lastMessageHash,lastUpdated:y.lastUpdated||e.lastUpdated,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,modalButtons:x?y.activeModal.buttons:void 0,modalMessage:x?y.activeModal.message:void 0,streamSource:"agent-stream",tabKey:lo(y.sessionId||y.instanceId,A),machineName:r,connectionState:a,settings:y.settings,coordinator:_,messageInput:y.messageInput})}return n.length===0&&n.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:c,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||d,displaySecondary:p,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:lo(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings,messageInput:e.messageInput}),n}function Up(e){return String(e.type||e.id||"").trim()}function Aa(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()).map(t=>t.trim()):[]}function MS(e,t){const n=(t||"").trim();if(!n)return[];const r=(e||[]).find(a=>a.type===n);return Aa(r==null?void 0:r.modelOptions)}function PS(e,t){const n=(t||"").trim();if(!n)return[];const r=(e||[]).find(a=>a.type===n);return Aa(r==null?void 0:r.thinkingLevelOptions)}function Gp(e){const t=new Map;for(const n of e||[])n!=null&&n.type&&t.set(n.type,{models:Aa(n.modelOptions),thinking:Aa(n.thinkingLevelOptions)});return t}function DS(e){var t;return e.category!=="cli"||!Up(e)||e.enabled===!1?!1:e.machineStatus?e.machineStatus==="detected":((t=e.lastDetection)==null?void 0:t.ok)===!0||e.installed===!0||!!e.detectedPath}function Ln(e){var r;const t=new Set,n=[];for(const a of e||[]){if(!DS(a))continue;const o=Up(a);if(!o||t.has(o))continue;t.add(o);const i=String(a.displayName||a.name||o),c=a.detectedPath||((r=a.lastDetection)==null?void 0:r.path)||null;n.push({type:o,label:i,icon:a.icon,statusLabel:c?`Detected at ${c}`:"Detected on this machine",detectedPath:c,...Array.isArray(a.modelOptions)&&a.modelOptions.length?{modelOptions:a.modelOptions}:{},...Array.isArray(a.thinkingLevelOptions)&&a.thinkingLevelOptions.length?{thinkingLevelOptions:a.thinkingLevelOptions}:{}})}return n}function Rn(e){const t=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],n=new Set,r=[];for(const a of t){const o=typeof a=="string"?a.trim():"";!o||n.has(o)||(n.add(o),r.push(o))}return r}function yr(e){return e.map(t=>t.type)}function IS(e,t){const n=Rn(e),r=t.trim();return!r||n.includes(r)?n:[...n,r]}function LS(e,t){return Rn(e).filter(n=>n!==t)}function Fc(e,t,n){const r=Rn(e),a=r.indexOf(t);if(a<0)return r;const o=r.filter(c=>c!==t);if(n==="top")return[t,...o];if(n==="bottom")return[...o,t];const i=n==="up"?Math.max(0,a-1):Math.min(o.length,a+1);return o.splice(i,0,t),o}function Bc({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 RS({value:e,availableProviders:t,onChange:n,disabled:r=!1,saveButton:a}){const{t:o}=Ce("common"),[i,c]=l.useState(""),d=l.useMemo(()=>new Map(t.map(g=>[g.type,g])),[t]),p=l.useMemo(()=>Rn(e),[e]),u=p.filter(g=>!d.has(g)).length,m=t.filter(g=>!p.includes(g.type)),f=()=>{i&&(n(IS(p,i)),c(""))};return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[s.jsx("div",{className:"flex flex-col gap-2",children:p.length===0?s.jsx("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:"No provider priority configured. Launches without an explicit CLI provider will fail closed."}):p.map((g,k)=>{const h=d.get(g),v=!!h;return s.jsxs("div",{className:`flex flex-col gap-2 rounded-md border border-border-subtle px-3 py-2 sm:flex-row sm:items-center sm:justify-between ${v?"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]}),(h==null?void 0:h.icon)&&s.jsx("span",{"aria-hidden":"true",children:h.icon}),s.jsx("span",{className:`font-mono text-[12px] ${v?"text-text-primary":"text-text-muted"}`,children:g}),v?s.jsx("span",{className:"rounded border border-green-500/20 bg-green-500/10 px-1.5 py-px text-[9px] font-semibold text-green-400",children:o("settings.providerPriority.available")}):s.jsx("span",{className:"rounded border border-amber-500/25 bg-amber-500/10 px-1.5 py-px text-[9px] font-semibold text-amber-400",children:o("settings.providerPriority.notOnMachine")})]}),s.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:h?`${h.label} · ${h.statusLabel}`:"Kept in order; skipped at launch until detected here."})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move up",disabled:r||k===0,title:"Move up",onClick:()=>n(Fc(p,g,"up")),children:s.jsx(Bc,{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:r||k===p.length-1,title:"Move down",onClick:()=>n(Fc(p,g,"down")),children:s.jsx(Bc,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:r,onClick:()=>n(LS(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:r||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:r||!i,onClick:f,children:o("settings.providerPriority.addProvider")}),a]}),s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:["Launches use this order, top to bottom.",u>0?` ${u} provider${u===1?"":"s"} not detected here — kept in order, skipped until available.`:""]})]})}function ES(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 qp(e,t){const n=ES(e);return{daemonId:n.daemonId,payload:{...t,...n.targetSessionId&&!t.targetSessionId?{targetSessionId:n.targetSessionId}:{}}}}const zp=[{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:"🏄"}],Kp=[{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:"◆"}],Vp=[{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:"🟠"}],_S=zp,$S=Kp,HS=Vp;function FS({icon:e,title:t,subtitle:n,badge:r,actions:a,className:o}){return s.jsxs("div",{className:Ut("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,r&&s.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[r.count!==void 0?r.count:""," ",r.text]})]}),n&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:n})]}),a&&s.jsx("div",{className:"flex gap-2",children:a})]})}function Tr({icon:e,title:t,subtitle:n,badge:r,actions:a,widthClassName:o="max-w-6xl",contentClassName:i,children:c}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(FS,{icon:e,title:t,subtitle:n,badge:r,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Ut("mx-auto flex w-full flex-col gap-4",o,i),children:c})})]})}const yi="adhdev:themechange";function BS(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function yn(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function wn(e){return e==="system"?BS():e}function Yp(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function aa(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(yi,{detail:{preference:e,theme:t}}))}function OS(){const e=yn(),t=wn(e);Yp(t),aa(e,t)}function Ws(){const[e,t]=l.useState(yn),[n,r]=l.useState(()=>wn(yn()));l.useEffect(()=>{Yp(n)},[n]),l.useEffect(()=>{const i=window.matchMedia("(prefers-color-scheme: light)"),c=d=>{if(e==="system"){const p=d.matches?"light":"dark";r(p),aa("system",p)}};return i.addEventListener("change",c),()=>i.removeEventListener("change",c)},[e]),l.useEffect(()=>{const i=d=>{const p=d.detail||{},u=p.preference,m=p.theme;t(u==="dark"||u==="light"||u==="system"?u:yn()),r(m==="dark"||m==="light"?m:wn(yn()))},c=d=>{if(d.key!=="theme")return;const p=yn(),u=wn(p);t(p),r(u)};return window.addEventListener(yi,i),window.addEventListener("storage",c),()=>{window.removeEventListener(yi,i),window.removeEventListener("storage",c)}},[]);const a=l.useCallback(i=>{const c=wn(i);t(i),r(c);try{localStorage.setItem("theme",i)}catch{}aa(i,c)},[]),o=l.useCallback(()=>{t(i=>{const c=i==="dark"?"light":i==="light"?"system":"dark",d=wn(c);r(d);try{localStorage.setItem("theme",c)}catch{}return aa(c,d),c})},[]);return{theme:n,preference:e,setPreference:a,cycleTheme:o,isDark:n==="dark"}}const Oc={dark:"Dark",light:"Light",system:"System"};function WS({collapsed:e}){const{preference:t,cycleTheme:n}=Ws(),r=t==="dark"?s.jsx(nb,{size:16}):t==="light"?s.jsx(sb,{size:16}):s.jsx(rb,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:n,title:`Theme: ${Oc[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:r}),!e&&s.jsx("span",{className:"text-xs",children:Oc[t]})]})}const wi="adhdev:langchange";function US(){const e=kt.language;return Cn(e)?e:Eu()}function GS(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(wi,{detail:{language:e}}))}function qS(){const[e,t]=l.useState(US);l.useEffect(()=>{const r=i=>{Cn(i)&&t(i)},a=i=>{const c=i.detail||{};Cn(c.language)&&t(c.language)},o=i=>{if(i.key!==oi)return;const c=i.newValue;Cn(c)&&c!==kt.language&&(kt.changeLanguage(c),ii(c))};return kt.on("languageChanged",r),window.addEventListener(wi,a),window.addEventListener("storage",o),()=>{kt.off("languageChanged",r),window.removeEventListener(wi,a),window.removeEventListener("storage",o)}},[]);const n=l.useCallback(r=>{if(Cn(r)){t(r);try{localStorage.setItem(oi,r)}catch{}kt.changeLanguage(r),ii(r),GS(r)}},[]);return{language:e,setLanguage:n}}function zS({trigger:e,viewport:t,menu:n,variant:r,gap:a=6,margin:o=8}){const i=e.top-o,c=t.height-e.bottom-o,d=r==="sidebar";let p=d;d&&i<n.height&&c>i&&(p=!1),!d&&c<n.height&&i>c&&(p=!0);const u=p?i:c,m=Math.max(80,Math.min(n.height,u));let f;p?f=e.top-a-m:f=e.bottom+a,f=Wc(f,o,Math.max(o,t.height-m-o));const g=Wc(e.left,o,Math.max(o,t.width-n.width-o));return{top:f,left:g,maxHeight:m}}function Wc(e,t,n){return Math.min(Math.max(e,t),n)}function KS({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 VS({collapsed:e,variant:t="sidebar"}){const{language:n,setLanguage:r}=qS(),{t:a}=Ce("common"),[o,i]=l.useState(!1),[c,d]=l.useState(0),p=l.useRef(null),u=l.useRef(null),m=l.useRef(null),f=l.useId(),[g,k]=l.useState(null),h=l.useCallback(()=>{const D=u.current;if(!D)return;const P=D.getBoundingClientRect(),_=m.current,G=Math.max((_==null?void 0:_.offsetWidth)??0,168),H=(_==null?void 0:_.scrollHeight)??qs.length*36+12;k(zS({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:G,height:H},variant:t}))},[t]),v=Math.max(0,qs.findIndex(D=>D.code===n)),w=qs[v]??qs[0],b=a("language.label",{defaultValue:"Language"}),j=a("language.select",{defaultValue:"Select language"}),C=D=>`${f}-opt-${D}`,y=l.useCallback(()=>{d(v),i(!0)},[v]),x=l.useCallback((D=!0)=>{var P;i(!1),D&&((P=u.current)==null||P.focus())},[]),N=l.useCallback(D=>{const P=qs[D];P&&r(P.code),x()},[r,x]);l.useEffect(()=>{if(!o)return;const D=G=>{var H,L;return!!((H=p.current)!=null&&H.contains(G)||(L=m.current)!=null&&L.contains(G))},P=G=>{D(G.target)||i(!1)},_=G=>{D(G.target)||i(!1)};return document.addEventListener("pointerdown",P,!0),document.addEventListener("focusin",_,!0),()=>{document.removeEventListener("pointerdown",P,!0),document.removeEventListener("focusin",_,!0)}},[o]),l.useLayoutEffect(()=>{if(!o){k(null);return}h();const D=()=>h();return window.addEventListener("resize",D),window.addEventListener("scroll",D,!0),()=>{window.removeEventListener("resize",D),window.removeEventListener("scroll",D,!0)}},[o,h]),l.useEffect(()=>{var D;o&&g&&((D=m.current)==null||D.focus())},[o,g]);const S=D=>{const P=qs.length-1;switch(D.key){case"ArrowDown":D.preventDefault(),d(_=>_>=P?0:_+1);break;case"ArrowUp":D.preventDefault(),d(_=>_<=0?P:_-1);break;case"Home":D.preventDefault(),d(0);break;case"End":D.preventDefault(),d(P);break;case"Enter":case" ":D.preventDefault(),N(c);break;case"Escape":D.preventDefault(),x();break;case"Tab":i(!1);break}},A=D=>{o||(D.key==="ArrowDown"||D.key==="ArrowUp"||D.key==="Enter"||D.key===" ")&&(D.preventDefault(),y())},T=t==="landing"?"lang-switch-trigger lang-switch-trigger--landing":`lang-switch-trigger lang-switch-trigger--sidebar nav-item cursor-pointer${e?" justify-center py-2.5 px-0":""}`,I=t==="landing"||!e;return s.jsxs("div",{ref:p,className:"lang-switch",children:[s.jsxs("button",{ref:u,type:"button",className:T,"aria-haspopup":"listbox","aria-expanded":o,"aria-label":`${b}: ${w.label}`,title:`${b}: ${w.label}`,onClick:()=>o?x(!1):y(),onKeyDown:A,children:[s.jsx("span",{className:"nav-icon lang-switch-icon",children:s.jsx(mb,{size:16})}),I&&s.jsx("span",{className:"lang-switch-label text-xs",children:w.label}),I&&s.jsx(KS,{open:o})]}),o&&typeof document<"u"&&an.createPortal(s.jsx("ul",{ref:m,role:"listbox",tabIndex:-1,"aria-label":j,"aria-activedescendant":C(c),className:`lang-switch-menu lang-switch-menu--${t}`,style:{position:"fixed",top:(g==null?void 0:g.top)??0,left:(g==null?void 0:g.left)??0,maxHeight:g==null?void 0:g.maxHeight,overflowY:"auto",visibility:g?"visible":"hidden"},onKeyDown:S,children:qs.map((D,P)=>{const _=D.code===w.code,G=P===c;return s.jsxs("li",{id:C(P),role:"option","aria-selected":_,className:`lang-switch-option${G?" is-active":""}${_?" is-selected":""}`,onMouseEnter:()=>d(P),onClick:()=>N(P),children:[s.jsx("span",{className:"lang-switch-check","aria-hidden":"true",children:_?s.jsx(fu,{size:14}):null}),s.jsx("span",{className:"lang-switch-option-label",children:D.label})]},D.code)})}),document.body)]})}const YS=[],JS=[];function xo(e,t){return e?typeof e=="function"?e(t):e:null}const QS=l.memo(function({renderState:t,brand:n,navItems:r,sidebarSections:a,footerItems:o,footerInfo:i,footerActions:c,closeMobileMenu:d}){const{t:p}=Ce("common"),{collapsed:u,mobileMenuOpen:m}=t,f=k=>`nav-item${k.active?" active":""} cursor-pointer ${u?"justify-center py-2.5 px-0":""}${k.className?` ${k.className}`:""}`,g=k=>s.jsxs("div",{className:f(k),id:`nav-${k.id}`,onClick:()=>{k.onSelect(),d()},title:u?k.title??(typeof k.label=="string"?k.label:void 0):k.title,children:[s.jsx("span",{className:"nav-icon",children:k.icon}),!u&&k.label]},k.id);return s.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${u?"justify-center gap-0":""}`,children:xo(n,t)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":p("app.closeMenu"),onClick:d,children:s.jsx(Tt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(g)}),a.map(k=>s.jsxs("div",{className:k.className??"border-t border-border-subtle pt-2 mt-2",children:[!u&&k.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:k.title}):null,k.items.map(g)]},k.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[o.map(g),xo(i,t),s.jsx(WS,{collapsed:u}),s.jsx(VS,{collapsed:u}),xo(c,t)]})]})});function XS({children:e,brand:t,navItems:n,sidebarSections:r=YS,footerItems:a=JS,footerInfo:o,footerActions:i,preMainContent:c,collapsedStorageKey:d="sidebar-collapsed"}){const{t:p}=Ce("common"),[u,m]=l.useState(!1),[f,g]=l.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),k=l.useCallback(()=>m(!0),[]),h=l.useCallback(()=>m(!1),[]),v=l.useCallback(()=>{g(b=>{const j=!b;try{localStorage.setItem(d,j?"1":"0")}catch{}return j})},[d]),w=l.useMemo(()=>({collapsed:f,mobileMenuOpen:u,openMobileMenu:k,closeMobileMenu:h,toggleCollapsed:v}),[f,u,k,h,v]);return s.jsxs("div",{className:`app-layout${u?" mobile-menu-open":""}${f?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":p("app.openMenu"),onClick:k,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),u&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":p("app.closeMenu"),onClick:h,onKeyDown:b=>b.key==="Escape"&&h()}),s.jsx(QS,{renderState:w,brand:t,navItems:n,sidebarSections:r,footerItems:a,footerInfo:o,footerActions:i,closeMobileMenu:h}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function ft({title:e,icon:t,description:n,accentColor:r,className:a,collapsible:o,defaultOpen:i=!0,badge:c,children:d}){const[p,u]=l.useState(i),m=o?p:!0,f=(e||n)&&s.jsxs("div",{className:Ut("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:Ut("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:Ut("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",r&&"border-l-[3px]",a),style:r?{borderLeftColor:r}:void 0,children:[o&&f?s.jsx("button",{type:"button",className:"w-full bg-transparent border-none p-0 text-left cursor-pointer",onClick:()=>u(g=>!g),"aria-expanded":m,children:f}):f,m&&d]})}function za({icon:e,title:t,description:n,action:r,className:a}){return s.jsxs("div",{className:Ut("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[s.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),s.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:t}),s.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:n}),r]})}const ZS={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"},eC={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Ft({variant:e,children:t,onDismiss:n,className:r}){return s.jsxs("div",{className:Ut("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",ZS[e],r),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:eC[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 Nt({label:e,hint:t,children:n,className:r}){return s.jsxs("div",{className:Ut("mb-5",r),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 ms(e){const{className:t,...n}=e;return s.jsx("input",{...n,className:Ut("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 tC={primary:"btn-primary",secondary:"btn-secondary",warning:"btn-warning",danger:"btn-danger",ghost:"btn-ghost"},Ts=l.forwardRef(function({variant:t="secondary",size:n="md",type:r,className:a,...o},i){return s.jsx("button",{ref:i,type:r??"button",className:Ut("btn",tC[t],n==="sm"&&"btn-sm",a),...o})}),sC=l.forwardRef(function({options:t,children:n,className:r,...a},o){return s.jsx("select",{ref:o,className:Ut("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",r),...a,children:n??(t==null?void 0:t.map(i=>s.jsx("option",{value:i.value,disabled:i.disabled,children:i.label},i.value)))})}),nC={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"},rC={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function aC({status:e,label:t,className:n}){const r=t||e;return s.jsxs("span",{className:Ut("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",nC[e],n),children:[s.jsx("span",{className:Ut("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",rC[e])}),r]})}function Ys({label:e,description:t,checked:n,disabled:r,onChange:a,extra:o}){return s.jsxs("div",{className:`flex justify-between items-center ${r?"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":r,disabled:r,onClick:()=>a(!n),className:`relative inline-flex items-center ${r?"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 oC({onPrefChange:e}){const{t}=Ce("common"),[n,r]=lw(),[a,o]=l.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);l.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){o("unsupported");return}o(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,d)=>{r({[c]:d}),e==null||e(c,d)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Ys,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Hn,{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(Ys,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(gs,{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")}),a==="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:()=>{Gu().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")})]}),a==="denied"&&s.jsx("div",{className:"text-[11px] text-status-warning",children:t("notifications.permissionDenied")}),a==="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(Ys,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(yu,{size:15})," ",t("notifications.completionAlertsLabel")]}),description:t("notifications.completionAlertsDesc"),checked:n.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(Ys,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ab,{size:15})," ",t("notifications.approvalAlertsLabel")]}),description:t("notifications.approvalAlertsDesc"),checked:n.approvalAlert,onChange:c=>i("approvalAlert",c)}),s.jsx(Ys,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(br,{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 ki(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/);if(!t)return null;const n=t[4]??null;let r=null;if(n){const a=n.match(/(?:^|\.)(\d+)$/);r=a?Number(a[1]):null}return{base:[Number(t[1]),Number(t[2]),Number(t[3])],prereleaseNumber:r,isPrerelease:n!==null}}function Ta(e){var t;return((t=ki(e))==null?void 0:t.base)??null}function iC(e,t){const n=Ta(e),r=Ta(t);if(!n||!r)return e.localeCompare(t);for(let a=0;a<3;a+=1){if(n[a]<r[a])return-1;if(n[a]>r[a])return 1}return 0}function lC(e,t){const n=ki(e),r=ki(t);if(!n||!r)return e!==t;for(let a=0;a<3;a+=1){if(n.base[a]<r.base[a])return!0;if(n.base[a]>r.base[a])return!1}return n.isPrerelease&&r.isPrerelease?n.prereleaseNumber===null||r.prereleaseNumber===null?!1:n.prereleaseNumber<r.prereleaseNumber:!1}function ll(e,t){const n=e.version||null;return e.versionMismatch===!0?!0:!n||!t?!1:lC(n,t)}function ur(e,t){if(e.versionUpdateRequired===!0)return!0;const n=e.version||null;if(!n||!t||n===t||iC(n,t)>=0)return!1;const r=Ta(n),a=Ta(t);return!r||!a?!1:r[0]!==a[0]||r[1]!==a[1]}function cC(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function vo(e,t){return e instanceof Error?e.message:t}function dC({ides:e,emptyMessage:t,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:a}){const{t:o}=Ce("common"),i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?s.jsx(za,{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(pC,{ide:c,allIdes:e,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:a},c.id))})}function Uc({title:e,message:t,confirmLabel:n,confirmColor:r,onConfirm:a,onCancel:o}){const{t:i}=Ce("common"),c=r==="red"?"bg-status-error/20 text-status-error border-status-error/40 hover:bg-status-error/30":"";return an.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:"var(--z-modal)"},onClick:o,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:d=>d.stopPropagation(),children:[s.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),s.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:t}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.jsx("button",{onClick:o,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:i("common.cancel")}),s.jsx("button",{onClick:a,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,style:r==="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 uC(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),r=[..._S,...$S,...HS].find(a=>a.id===t||t.includes(a.id)||a.id.includes(t));return r?{icon:r.icon,name:r.name}:{icon:"📝",name:e}}function pC({ide:e,allIdes:t,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:a}){var G,H;const{t:o}=Ce("common"),[i,c]=l.useState("idle"),[d,p]=l.useState(""),[u,m]=l.useState(null),[f,g]=l.useState("idle"),[k,h]=l.useState(""),v=e.version||null,w=((G=e.machine)==null?void 0:G.platform)||((H=e.system)==null?void 0:H.platform)||"",b=as(e,{fallbackId:e.id}),j=w==="win32"?"🪟":w==="darwin"?"🍎":"🐧",C=t.filter(L=>L.daemonId===e.id&&L.transport==="cdp-page"),y=t.filter(L=>L.daemonId===e.id&&L.transport==="pty"),x=t.filter(L=>L.daemonId===e.id&&L.transport==="acp"),N=e.p2p,S=async()=>{if(n){c("upgrading"),p(o("machine.connectedMachines.startingUpgrade"));try{const L=cC(await n(e.id,"daemon_upgrade",{}));L.alreadyLatest?(c("done"),p(`Already on v${L.version||"latest"}.`)):L.upgraded||L.success?(c("done"),p(`Upgrade to v${L.version||"latest"} started. Daemon is restarting...`)):(c("error"),p(L.error||"Upgrade failed"))}catch(L){c("error"),p(vo(L,"Connection lost during upgrade"))}}},A=async()=>{if(m(null),!!r){g("loading");try{await r(e.id),g("done"),h(o("machine.connectedMachines.machineDisconnected"))}catch(L){g("error"),h(vo(L,o("machine.connectedMachines.failedToDisconnect")))}}},T=async()=>{if(m(null),!!a){g("loading");try{await a(e.id),g("done"),h(o("machine.connectedMachines.tokenRevoked"))}catch(L){g("error"),h(vo(L,o("machine.connectedMachines.failedToRevokeToken")))}}},I="1.0.24",D=ll(e,I),P=ur(e,I),_=C.length+y.length+x.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:j}),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),"…"]}),v&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${D?"":"bg-bg-secondary"}`,style:D?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",v,!D&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[n&&D&&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"):P?o("machine.connectedMachines.updateNow"):o("machine.connectedMachines.updateTo",{version:I})}),r&&s.jsx("button",{onClick:()=>m("disconnect"),disabled:f==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:o("machine.connectedMachines.disconnect")}),a&&s.jsx("button",{onClick:()=>m("revoke"),disabled:f==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:o("machine.connectedMachines.remove")}),s.jsx(aC,{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:[N&&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 ${N.state==="connected"?"bg-status-online":"bg-text-muted/30"} ${N.state==="connecting"||N.state==="new"?"animate-pulse":""}`,style:N.state==="connecting"||N.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",N.state==="connected"?"connected":N.state==="connecting"||N.state==="new"?o("machine.connectedMachines.connecting"):N.state||"off"]}),N.peers!==void 0&&N.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",N.peers," peer",N.peers!==1?"s":"",")"]})]}),N&&_>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),_>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[C.map(L=>{const O=uC(L.type),E=L.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:O.icon}),s.jsx("span",{children:O.name}),E!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${E?"bg-status-online":"animate-pulse"}`,style:E?void 0:{background:"var(--status-warning)"},title:o(E?"machine.connectedMachines.cdpConnected":"machine.connectedMachines.cdpConnecting")})]},L.id)}),y.map(L=>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:L.cliName||"CLI"})]},L.id)),x.map(L=>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:L.cliName||"ACP"})]},L.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:o("machine.connectedMachines.noIdesConnected")})]}),(d||k)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||f==="error"?"text-status-error":i==="done"||f==="done"?"text-status-online":"text-text-muted"}`,children:k||d})]}),u==="disconnect"&&s.jsx(Uc,{title:o("machine.connectedMachines.disconnectTitle"),message:`Disconnect "${b}" from ADHDev?
|
|
58
|
+
`).includes(a)))}function hS(e,t="recent"){const n=e.slice();return n.sort((r,a)=>{if(t==="oldest")return(Number(r.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(t==="messages"){const o=(Number(a.messageCount)||0)-(Number(r.messageCount)||0);if(o!==0)return o}return(Number(a.lastMessageAt)||0)-(Number(r.lastMessageAt)||0)}),n}function Rp(e,t={}){return hS(mS(e,t),t.sortMode||"recent")}function vi(e,t){return typeof e=="function"?e(t??!1?"launch.resumeSavedHistory":"launch.startFresh"):e?"Resume saved history":"Start fresh"}function Ep(e,t){return typeof e=="function"?e(t??!1?"launch.resumingSavedHistory":"launch.startingFresh"):e?"Resuming saved history…":"Starting fresh…"}function fS(e){return e?e("launch.startFresh"):"Start fresh"}function bS(e){return e?e("launch.hostedRuntimeRecoveryDescription"):"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function gS(e){return e?e("launch.openSavedHistory"):"Open saved history"}function xS(e){return e?e("launch.savedHistoryTitle"):"Saved History"}function ol(e){return e?e("launch.savedHistoryHelper"):"Use saved history when you want continuity in the same provider conversation."}function vS(e){return e?e("launch.savedHistoryEmpty"):"No saved history found yet."}function yS(e){return e?e("launch.refreshSavedHistory"):"Refresh saved history"}function wS(e){return e?e("launch.refreshingSavedHistory"):"Refreshing saved history…"}function Sa(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 r=e,a=t;return r==="start-fresh"?`Start fresh with ${a}?`:`Restart ${a}?`}function Ca(e,t){if(typeof e=="function"){const r=t;return e(r==="start-fresh"?"launch.startFreshReview":r==="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 ja(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartFresh":"launch.confirmRestart"):e==="start-fresh"?"Start fresh":"Restart"}function Na(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartingFresh":"launch.confirmRestarting"):e==="start-fresh"?"Starting fresh…":"Restarting…"}function _p(e,t){return typeof e=="function"?e("launch.resumeWith",{label:t}):`Resume saved history with ${e}?`}function $p(e){return e?e("launch.resumeReview"):"Review or change the target workspace before resuming saved history."}function kS(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 Hp({activeConv:e,ides:t,isCreatingChat:n,isRefreshingHistory:r,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:c,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:p,onClose:u,onNewChat:m,onSwitchSession:f,onRefreshHistory:g,onResumeSavedSession:k}){var D;const{t:h}=Ce("common"),v=t.find(P=>P.id===e.routeId),w=(v==null?void 0:v.chats)||[],b=(D=v==null?void 0:v.activeChat)==null?void 0:D.id,j=mt(e)&&!dt(e),[C,y]=l.useState(()=>Wt()),x=c||C,N=String(d||"").trim(),S=P=>{if(p){p(P);return}y(P)},A=l.useMemo(()=>a.map(P=>{const _=String(P.workspace||"").trim();return P.canResume||_||!N?P:{...P,workspace:N,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[N,a]),T=l.useMemo(()=>Rp(A,{textQuery:x.textQuery,workspaceQuery:x.workspaceQuery,modelQuery:x.modelQuery,resumableOnly:x.resumableOnly,sortMode:x.sortMode}),[A,x.modelQuery,x.resumableOnly,x.sortMode,x.textQuery,x.workspaceQuery]),I=s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:u,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:j?xS(h):h("historyModal.chatHistory")}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Ok(e)}),j&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:ol(h)})]}),s.jsx("button",{onClick:u,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(Tt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!j&&s.jsx("button",{onClick:m,disabled:n,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:h(n?"historyModal.creating":"historyModal.startNewChat")}),j?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:x.textQuery,onChange:P=>S({...x,textQuery:P.target.value}),placeholder:h("historyModal.searchPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:x.workspaceQuery,onChange:P=>S({...x,workspaceQuery:P.target.value}),placeholder:h("historyModal.filterWorkspace"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:x.modelQuery,onChange:P=>S({...x,modelQuery:P.target.value}),placeholder:h("historyModal.filterModel"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsxs("select",{value:x.sortMode,onChange:P=>S({...x,sortMode:P.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:h("historyModal.sortRecent")}),s.jsx("option",{value:"oldest",children:h("historyModal.sortOldest")}),s.jsx("option",{value:"messages",children:h("historyModal.sortMessages")})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:x.resumableOnly,onChange:P=>S({...x,resumableOnly:P.target.checked})}),h("historyModal.resumeReadyOnly")]})]}),T.map(P=>{const _=e.providerSessionId===P.providerSessionId,G=_||!P.canResume||!!i,H=P.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{G||!k||k(P)},disabled:G,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${_?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${G?"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 ${_?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:P.title||h("historyModal.untitledSession")}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:P.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:kS(P.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:P.preview||h("historyModal.noSavedPreview")}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[P.workspace||h("historyModal.workspaceUnknown"),H?h("historyModal.selectedWorkspaceSuffix"):"",ln(P.summaryMetadata)?` · ${ln(P.summaryMetadata)}`:"",P.messageCount>0?` · ${h("historyModal.msgCount",{count:P.messageCount})}`:""]}),s.jsx("div",{className:"shrink-0",children:_?h("historyModal.statusActive"):P.canResume?H?h("historyModal.statusResumeSelectedWorkspace"):i===P.providerSessionId?h("historyModal.statusResuming"):h("historyModal.statusResume"):h("historyModal.statusMissingWorkspace")})]})]},P.id)})]}):w.map(P=>s.jsxs("div",{onClick:()=>{f(e.routeId,P.id),u()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${b===P.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[s.jsx("div",{className:`font-bold text-sm mb-1 ${b===P.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:P.title||h("historyModal.untitledSession")}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[P.id.substring(0,12),"..."]}),b===P.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:h("historyModal.statusActive")})]})]},P.id)),(j&&!o&&T.length===0||!j&&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(tb,{size:32})}),s.jsx("div",{className:"text-[13px]",children:j?a.length>0?h("historyModal.noMatchingHistory"):vS(h):h("historyModal.noRecentChats")})]}),j&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:wS(h)})})]}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:s.jsx("button",{onClick:g,disabled:r||o,className:"btn btn-secondary btn-sm rounded-[10px]",children:r||o?h("historyModal.refreshing"):s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(_a,{size:13})," ",j?yS(h):h("historyModal.refreshHistory")]})})})]})]});return typeof document>"u"?I:an.createPortal(I,document.body)}const Hc={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 Fp({toasts:e,onDismiss:t,onClickToast:n}){const{t:r}=Ce();return s.jsx("div",{className:"fixed right-4 z-[var(--z-toast)] flex flex-col gap-2 pointer-events-none",style:{top:"calc(env(safe-area-inset-top, 0px) + 16px)"},children:e.map(a=>{const o=Hc[a.type]||Hc.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=a.actions)!=null&&i.length||n&&n(a)},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(a.id)},"aria-label":r("toast.dismiss"),children:s.jsx(Tt,{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:r(o.labelKey)})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:a.message}),a.actions&&a.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:a.actions.map((i,c)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:i.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:d=>{d.stopPropagation(),i.onClick(),t(a.id)},children:i.label},c))})]})]},a.id)})})}const SS=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function CS(e){const t=e.workspace||"";if(!t)return"";const n=t.split(/[/\\]/).filter(Boolean);return n.length>0?n[n.length-1]:t}function jS(e,t){return Bp(e)||t}function Bp(e){var a,o,i;const t=(o=(a=e.summaryMetadata)==null?void 0:a.items)==null?void 0:o.find(c=>(c==null?void 0:c.id)==="model"),n=((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim();if(n)return n;const r=(i=e.controlValues)==null?void 0:i.model;return typeof r=="string"&&r.trim()?r.trim():""}function NS(e){return Bp(e)||void 0}function AS(e){return e.sessionId||e.instanceId||e.agentType}function Op(e=[]){const t={};for(const n of e)n.type==="adhdev-daemon"&&(t[n.id]=as(n,{fallbackId:n.id}));return t}function Wp(e,t={}){var r;const n=e.daemonId||((r=e.id)==null?void 0:r.split(":")[0])||e.id;return{machineName:Gy(e,t.machineNames),connectionState:t.connectionStates?t.connectionStates[n]||t.defaultConnectionState||"new":t.defaultConnectionState}}function il(e,t={}){return TS(e,Wp(e,t))}function TS(e,t={}){var f,g,k,h,v,w,b,j,C;const n=[],r=t.machineName,a=t.connectionState,o=CS(e),i=e.workspace||"",c=Jy(e.type,{agentName:e.cliName}),d=mt(e)||dt(e)?c:Ht(e.type),p=jS(e,d),u=Array.isArray(e.childSessions)?e.childSessions.map(y=>{var x,N,S;return{sessionId:y.id,instanceId:y.id,providerSessionId:y.providerSessionId,activeChatId:(x=y.activeChat)==null?void 0:x.id,transport:y.transport,sessionCapabilities:y.capabilities,agentType:y.providerType,agentName:y.providerName||Ht(y.providerType),model:NS(y),status:y.status,title:y.title,lastMessagePreview:y.lastMessagePreview,lastMessageRole:y.lastMessageRole,lastMessageAt:y.lastMessageAt,lastMessageHash:y.lastMessageHash,messages:((N=y.activeChat)==null?void 0:N.messages)||[],activeModal:((S=y.activeChat)==null?void 0:S.activeModal)||void 0,unread:y.unread,lastSeenAt:y.lastSeenAt,lastUpdated:y.lastUpdated,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,surfaceHidden:y.surfaceHidden,muted:y.muted,git:y.git,settings:y.settings,coordinator:y.coordinator,messageInput:y.messageInput}}):[],m=SS(e);if(m){const y=e.sessionId||e.instanceId,x=(f=e.settings)==null?void 0:f.meshCoordinatorFor,N=((g=e.settings)==null?void 0:g.meshNodeFor)||!((k=e.settings)!=null&&k.meshCoordinatorFor)&&((h=e.settings)==null?void 0:h.launchedByCoordinator),S=x?" (Coordinator)":N?" (Mesh Node)":"",A=c+S,T=(v=e.activeChat)==null?void 0:v.activeModal,I=T&&Array.isArray(T.buttons)&&T.buttons.length>0,D=Qy(e.activeChat,[{status:e.status,activeModal:(w=e.activeChat)==null?void 0:w.activeModal}],e.agents||[]),P=e.activeChat||{title:"",messages:[]};let _=P.title&&String(P.title).trim()?String(P.title).trim():"";const G=(b=e.activeChat)==null?void 0:b.id,H=e.chats;if(G&&Array.isArray(H)&&H.length>0){const Q=H.find(ne=>ne.id===G||ne.id&&String(ne.id)===String(G));Q!=null&&Q.title&&String(Q.title).trim()&&(_=String(Q.title).trim())}const L=(mt(e)||dt(e),e.type),O=(mt(e)||dt(e))&&ic(_,A,L)?"":_,E=P.messages||[],M=typeof G=="string"?G.trim():"",$=(mt(e)||dt(e))&&M===String(e.type||"").trim(),R=M&&!$?M:e.providerSessionId,z=e.coordinator||(typeof((j=e.settings)==null?void 0:j.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:y,providerSessionId:e.providerSessionId,historySessionId:R,nativeSessionId:y,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:mt(e)&&e.mode||"chat",agentName:A,agentType:L,status:D,title:O,messages:E,resume:e.resume,hostIdeType:!mt(e)&&!dt(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||O||(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?T.buttons:void 0,modalMessage:I?T.message:void 0,streamSource:"native",tabKey:lo(y,e.id),machineName:r,connectionState:a,settings:e.settings,coordinator:z,messageInput:e.messageInput})}if(m&&(mt(e)||dt(e)))return n;for(const y of u){const x=y.activeModal&&Array.isArray(y.activeModal.buttons)&&y.activeModal.buttons.length>0,N=Xy(y),S=AS(y),A=`${e.id}:${S}`,T=y.title&&String(y.title).trim()||"",I=ic(T,y.agentName,y.agentType)?"":T,D=y.messages||[];if(!(y.transport==="cdp-webview"||!!y.sessionId||!!y.providerSessionId||D.length>0||x||!!I||!["idle","panel_hidden","disconnected","not_monitored"].includes(N)))continue;const _=y.coordinator||(typeof((C=y.settings)==null?void 0:C.meshCoordinatorFor)=="string"&&y.settings.meshCoordinatorFor?{meshId:y.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:y.sessionId||y.instanceId,providerSessionId:y.providerSessionId,historySessionId:y.activeChatId||y.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:y.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:y.sessionCapabilities,mode:"chat",agentName:y.agentName,agentType:y.agentType,status:N,title:I,messages:D,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:y.git||e.git,displayPrimary:o||I||y.agentName||d,displaySecondary:y.model&&y.model.trim()?y.model.trim():`${d} · ${y.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:y.lastMessagePreview,lastMessageRole:y.lastMessageRole,lastMessageAt:y.lastMessageAt,lastMessageHash:y.lastMessageHash,lastUpdated:y.lastUpdated||e.lastUpdated,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,modalButtons:x?y.activeModal.buttons:void 0,modalMessage:x?y.activeModal.message:void 0,streamSource:"agent-stream",tabKey:lo(y.sessionId||y.instanceId,A),machineName:r,connectionState:a,settings:y.settings,coordinator:_,messageInput:y.messageInput})}return n.length===0&&n.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:c,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||d,displaySecondary:p,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:lo(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings,messageInput:e.messageInput}),n}function Up(e){return String(e.type||e.id||"").trim()}function Aa(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()).map(t=>t.trim()):[]}function MS(e,t){const n=(t||"").trim();if(!n)return[];const r=(e||[]).find(a=>a.type===n);return Aa(r==null?void 0:r.modelOptions)}function PS(e,t){const n=(t||"").trim();if(!n)return[];const r=(e||[]).find(a=>a.type===n);return Aa(r==null?void 0:r.thinkingLevelOptions)}function Gp(e){const t=new Map;for(const n of e||[])n!=null&&n.type&&t.set(n.type,{models:Aa(n.modelOptions),thinking:Aa(n.thinkingLevelOptions)});return t}function DS(e){var t;return e.category!=="cli"||!Up(e)||e.enabled===!1?!1:e.machineStatus?e.machineStatus==="detected":((t=e.lastDetection)==null?void 0:t.ok)===!0||e.installed===!0||!!e.detectedPath}function Ln(e){var r;const t=new Set,n=[];for(const a of e||[]){if(!DS(a))continue;const o=Up(a);if(!o||t.has(o))continue;t.add(o);const i=String(a.displayName||a.name||o),c=a.detectedPath||((r=a.lastDetection)==null?void 0:r.path)||null;n.push({type:o,label:i,icon:a.icon,statusLabel:c?`Detected at ${c}`:"Detected on this machine",detectedPath:c,...Array.isArray(a.modelOptions)&&a.modelOptions.length?{modelOptions:a.modelOptions}:{},...Array.isArray(a.thinkingLevelOptions)&&a.thinkingLevelOptions.length?{thinkingLevelOptions:a.thinkingLevelOptions}:{}})}return n}function Rn(e){const t=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],n=new Set,r=[];for(const a of t){const o=typeof a=="string"?a.trim():"";!o||n.has(o)||(n.add(o),r.push(o))}return r}function yr(e){return e.map(t=>t.type)}function IS(e,t){const n=Rn(e),r=t.trim();return!r||n.includes(r)?n:[...n,r]}function LS(e,t){return Rn(e).filter(n=>n!==t)}function Fc(e,t,n){const r=Rn(e),a=r.indexOf(t);if(a<0)return r;const o=r.filter(c=>c!==t);if(n==="top")return[t,...o];if(n==="bottom")return[...o,t];const i=n==="up"?Math.max(0,a-1):Math.min(o.length,a+1);return o.splice(i,0,t),o}function Bc({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 RS({value:e,availableProviders:t,onChange:n,disabled:r=!1,saveButton:a}){const{t:o}=Ce("common"),[i,c]=l.useState(""),d=l.useMemo(()=>new Map(t.map(g=>[g.type,g])),[t]),p=l.useMemo(()=>Rn(e),[e]),u=p.filter(g=>!d.has(g)).length,m=t.filter(g=>!p.includes(g.type)),f=()=>{i&&(n(IS(p,i)),c(""))};return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[s.jsx("div",{className:"flex flex-col gap-2",children:p.length===0?s.jsx("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:"No provider priority configured. Launches without an explicit CLI provider will fail closed."}):p.map((g,k)=>{const h=d.get(g),v=!!h;return s.jsxs("div",{className:`flex flex-col gap-2 rounded-md border border-border-subtle px-3 py-2 sm:flex-row sm:items-center sm:justify-between ${v?"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]}),(h==null?void 0:h.icon)&&s.jsx("span",{"aria-hidden":"true",children:h.icon}),s.jsx("span",{className:`font-mono text-[12px] ${v?"text-text-primary":"text-text-muted"}`,children:g}),v?s.jsx("span",{className:"rounded border border-green-500/20 bg-green-500/10 px-1.5 py-px text-[9px] font-semibold text-green-400",children:o("settings.providerPriority.available")}):s.jsx("span",{className:"rounded border border-amber-500/25 bg-amber-500/10 px-1.5 py-px text-[9px] font-semibold text-amber-400",children:o("settings.providerPriority.notOnMachine")})]}),s.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:h?`${h.label} · ${h.statusLabel}`:"Kept in order; skipped at launch until detected here."})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move up",disabled:r||k===0,title:"Move up",onClick:()=>n(Fc(p,g,"up")),children:s.jsx(Bc,{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:r||k===p.length-1,title:"Move down",onClick:()=>n(Fc(p,g,"down")),children:s.jsx(Bc,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:r,onClick:()=>n(LS(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:r||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:r||!i,onClick:f,children:o("settings.providerPriority.addProvider")}),a]}),s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:["Launches use this order, top to bottom.",u>0?` ${u} provider${u===1?"":"s"} not detected here — kept in order, skipped until available.`:""]})]})}function ES(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 qp(e,t){const n=ES(e);return{daemonId:n.daemonId,payload:{...t,...n.targetSessionId&&!t.targetSessionId?{targetSessionId:n.targetSessionId}:{}}}}const zp=[{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:"🏄"}],Kp=[{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:"◆"}],Vp=[{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:"🟠"}],_S=zp,$S=Kp,HS=Vp;function FS({icon:e,title:t,subtitle:n,badge:r,actions:a,className:o}){return s.jsxs("div",{className:Ut("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,r&&s.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[r.count!==void 0?r.count:""," ",r.text]})]}),n&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:n})]}),a&&s.jsx("div",{className:"flex gap-2",children:a})]})}function Tr({icon:e,title:t,subtitle:n,badge:r,actions:a,widthClassName:o="max-w-6xl",contentClassName:i,children:c}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(FS,{icon:e,title:t,subtitle:n,badge:r,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Ut("mx-auto flex w-full flex-col gap-4",o,i),children:c})})]})}const yi="adhdev:themechange";function BS(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function yn(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function wn(e){return e==="system"?BS():e}function Yp(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function aa(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(yi,{detail:{preference:e,theme:t}}))}function OS(){const e=yn(),t=wn(e);Yp(t),aa(e,t)}function Ws(){const[e,t]=l.useState(yn),[n,r]=l.useState(()=>wn(yn()));l.useEffect(()=>{Yp(n)},[n]),l.useEffect(()=>{const i=window.matchMedia("(prefers-color-scheme: light)"),c=d=>{if(e==="system"){const p=d.matches?"light":"dark";r(p),aa("system",p)}};return i.addEventListener("change",c),()=>i.removeEventListener("change",c)},[e]),l.useEffect(()=>{const i=d=>{const p=d.detail||{},u=p.preference,m=p.theme;t(u==="dark"||u==="light"||u==="system"?u:yn()),r(m==="dark"||m==="light"?m:wn(yn()))},c=d=>{if(d.key!=="theme")return;const p=yn(),u=wn(p);t(p),r(u)};return window.addEventListener(yi,i),window.addEventListener("storage",c),()=>{window.removeEventListener(yi,i),window.removeEventListener("storage",c)}},[]);const a=l.useCallback(i=>{const c=wn(i);t(i),r(c);try{localStorage.setItem("theme",i)}catch{}aa(i,c)},[]),o=l.useCallback(()=>{t(i=>{const c=i==="dark"?"light":i==="light"?"system":"dark",d=wn(c);r(d);try{localStorage.setItem("theme",c)}catch{}return aa(c,d),c})},[]);return{theme:n,preference:e,setPreference:a,cycleTheme:o,isDark:n==="dark"}}const Oc={dark:"Dark",light:"Light",system:"System"};function WS({collapsed:e}){const{preference:t,cycleTheme:n}=Ws(),r=t==="dark"?s.jsx(nb,{size:16}):t==="light"?s.jsx(sb,{size:16}):s.jsx(rb,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:n,title:`Theme: ${Oc[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:r}),!e&&s.jsx("span",{className:"text-xs",children:Oc[t]})]})}const wi="adhdev:langchange";function US(){const e=kt.language;return Cn(e)?e:Eu()}function GS(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(wi,{detail:{language:e}}))}function qS(){const[e,t]=l.useState(US);l.useEffect(()=>{const r=i=>{Cn(i)&&t(i)},a=i=>{const c=i.detail||{};Cn(c.language)&&t(c.language)},o=i=>{if(i.key!==oi)return;const c=i.newValue;Cn(c)&&c!==kt.language&&(kt.changeLanguage(c),ii(c))};return kt.on("languageChanged",r),window.addEventListener(wi,a),window.addEventListener("storage",o),()=>{kt.off("languageChanged",r),window.removeEventListener(wi,a),window.removeEventListener("storage",o)}},[]);const n=l.useCallback(r=>{if(Cn(r)){t(r);try{localStorage.setItem(oi,r)}catch{}kt.changeLanguage(r),ii(r),GS(r)}},[]);return{language:e,setLanguage:n}}function zS({trigger:e,viewport:t,menu:n,variant:r,gap:a=6,margin:o=8}){const i=e.top-o,c=t.height-e.bottom-o,d=r==="sidebar";let p=d;d&&i<n.height&&c>i&&(p=!1),!d&&c<n.height&&i>c&&(p=!0);const u=p?i:c,m=Math.max(80,Math.min(n.height,u));let f;p?f=e.top-a-m:f=e.bottom+a,f=Wc(f,o,Math.max(o,t.height-m-o));const g=Wc(e.left,o,Math.max(o,t.width-n.width-o));return{top:f,left:g,maxHeight:m}}function Wc(e,t,n){return Math.min(Math.max(e,t),n)}function KS({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 VS({collapsed:e,variant:t="sidebar"}){const{language:n,setLanguage:r}=qS(),{t:a}=Ce("common"),[o,i]=l.useState(!1),[c,d]=l.useState(0),p=l.useRef(null),u=l.useRef(null),m=l.useRef(null),f=l.useId(),[g,k]=l.useState(null),h=l.useCallback(()=>{const D=u.current;if(!D)return;const P=D.getBoundingClientRect(),_=m.current,G=Math.max((_==null?void 0:_.offsetWidth)??0,168),H=(_==null?void 0:_.scrollHeight)??qs.length*36+12;k(zS({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:G,height:H},variant:t}))},[t]),v=Math.max(0,qs.findIndex(D=>D.code===n)),w=qs[v]??qs[0],b=a("language.label",{defaultValue:"Language"}),j=a("language.select",{defaultValue:"Select language"}),C=D=>`${f}-opt-${D}`,y=l.useCallback(()=>{d(v),i(!0)},[v]),x=l.useCallback((D=!0)=>{var P;i(!1),D&&((P=u.current)==null||P.focus())},[]),N=l.useCallback(D=>{const P=qs[D];P&&r(P.code),x()},[r,x]);l.useEffect(()=>{if(!o)return;const D=G=>{var H,L;return!!((H=p.current)!=null&&H.contains(G)||(L=m.current)!=null&&L.contains(G))},P=G=>{D(G.target)||i(!1)},_=G=>{D(G.target)||i(!1)};return document.addEventListener("pointerdown",P,!0),document.addEventListener("focusin",_,!0),()=>{document.removeEventListener("pointerdown",P,!0),document.removeEventListener("focusin",_,!0)}},[o]),l.useLayoutEffect(()=>{if(!o){k(null);return}h();const D=()=>h();return window.addEventListener("resize",D),window.addEventListener("scroll",D,!0),()=>{window.removeEventListener("resize",D),window.removeEventListener("scroll",D,!0)}},[o,h]),l.useEffect(()=>{var D;o&&g&&((D=m.current)==null||D.focus())},[o,g]);const S=D=>{const P=qs.length-1;switch(D.key){case"ArrowDown":D.preventDefault(),d(_=>_>=P?0:_+1);break;case"ArrowUp":D.preventDefault(),d(_=>_<=0?P:_-1);break;case"Home":D.preventDefault(),d(0);break;case"End":D.preventDefault(),d(P);break;case"Enter":case" ":D.preventDefault(),N(c);break;case"Escape":D.preventDefault(),x();break;case"Tab":i(!1);break}},A=D=>{o||(D.key==="ArrowDown"||D.key==="ArrowUp"||D.key==="Enter"||D.key===" ")&&(D.preventDefault(),y())},T=t==="landing"?"lang-switch-trigger lang-switch-trigger--landing":`lang-switch-trigger lang-switch-trigger--sidebar nav-item cursor-pointer${e?" justify-center py-2.5 px-0":""}`,I=t==="landing"||!e;return s.jsxs("div",{ref:p,className:"lang-switch",children:[s.jsxs("button",{ref:u,type:"button",className:T,"aria-haspopup":"listbox","aria-expanded":o,"aria-label":`${b}: ${w.label}`,title:`${b}: ${w.label}`,onClick:()=>o?x(!1):y(),onKeyDown:A,children:[s.jsx("span",{className:"nav-icon lang-switch-icon",children:s.jsx(mb,{size:16})}),I&&s.jsx("span",{className:"lang-switch-label text-xs",children:w.label}),I&&s.jsx(KS,{open:o})]}),o&&typeof document<"u"&&an.createPortal(s.jsx("ul",{ref:m,role:"listbox",tabIndex:-1,"aria-label":j,"aria-activedescendant":C(c),className:`lang-switch-menu lang-switch-menu--${t}`,style:{position:"fixed",top:(g==null?void 0:g.top)??0,left:(g==null?void 0:g.left)??0,maxHeight:g==null?void 0:g.maxHeight,overflowY:"auto",visibility:g?"visible":"hidden"},onKeyDown:S,children:qs.map((D,P)=>{const _=D.code===w.code,G=P===c;return s.jsxs("li",{id:C(P),role:"option","aria-selected":_,className:`lang-switch-option${G?" is-active":""}${_?" is-selected":""}`,onMouseEnter:()=>d(P),onClick:()=>N(P),children:[s.jsx("span",{className:"lang-switch-check","aria-hidden":"true",children:_?s.jsx(fu,{size:14}):null}),s.jsx("span",{className:"lang-switch-option-label",children:D.label})]},D.code)})}),document.body)]})}const YS=[],JS=[];function xo(e,t){return e?typeof e=="function"?e(t):e:null}const QS=l.memo(function({renderState:t,brand:n,navItems:r,sidebarSections:a,footerItems:o,footerInfo:i,footerActions:c,closeMobileMenu:d}){const{t:p}=Ce("common"),{collapsed:u,mobileMenuOpen:m}=t,f=k=>`nav-item${k.active?" active":""} cursor-pointer ${u?"justify-center py-2.5 px-0":""}${k.className?` ${k.className}`:""}`,g=k=>s.jsxs("div",{className:f(k),id:`nav-${k.id}`,onClick:()=>{k.onSelect(),d()},title:u?k.title??(typeof k.label=="string"?k.label:void 0):k.title,children:[s.jsx("span",{className:"nav-icon",children:k.icon}),!u&&k.label]},k.id);return s.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${u?"justify-center gap-0":""}`,children:xo(n,t)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":p("app.closeMenu"),onClick:d,children:s.jsx(Tt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(g)}),a.map(k=>s.jsxs("div",{className:k.className??"border-t border-border-subtle pt-2 mt-2",children:[!u&&k.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:k.title}):null,k.items.map(g)]},k.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[o.map(g),xo(i,t),s.jsx(WS,{collapsed:u}),s.jsx(VS,{collapsed:u}),xo(c,t)]})]})});function XS({children:e,brand:t,navItems:n,sidebarSections:r=YS,footerItems:a=JS,footerInfo:o,footerActions:i,preMainContent:c,collapsedStorageKey:d="sidebar-collapsed"}){const{t:p}=Ce("common"),[u,m]=l.useState(!1),[f,g]=l.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),k=l.useCallback(()=>m(!0),[]),h=l.useCallback(()=>m(!1),[]),v=l.useCallback(()=>{g(b=>{const j=!b;try{localStorage.setItem(d,j?"1":"0")}catch{}return j})},[d]),w=l.useMemo(()=>({collapsed:f,mobileMenuOpen:u,openMobileMenu:k,closeMobileMenu:h,toggleCollapsed:v}),[f,u,k,h,v]);return s.jsxs("div",{className:`app-layout${u?" mobile-menu-open":""}${f?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":p("app.openMenu"),onClick:k,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),u&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":p("app.closeMenu"),onClick:h,onKeyDown:b=>b.key==="Escape"&&h()}),s.jsx(QS,{renderState:w,brand:t,navItems:n,sidebarSections:r,footerItems:a,footerInfo:o,footerActions:i,closeMobileMenu:h}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function ft({title:e,icon:t,description:n,accentColor:r,className:a,collapsible:o,defaultOpen:i=!0,badge:c,children:d}){const[p,u]=l.useState(i),m=o?p:!0,f=(e||n)&&s.jsxs("div",{className:Ut("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:Ut("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:Ut("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",r&&"border-l-[3px]",a),style:r?{borderLeftColor:r}:void 0,children:[o&&f?s.jsx("button",{type:"button",className:"w-full bg-transparent border-none p-0 text-left cursor-pointer",onClick:()=>u(g=>!g),"aria-expanded":m,children:f}):f,m&&d]})}function za({icon:e,title:t,description:n,action:r,className:a}){return s.jsxs("div",{className:Ut("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[s.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),s.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:t}),s.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:n}),r]})}const ZS={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"},eC={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Ft({variant:e,children:t,onDismiss:n,className:r}){return s.jsxs("div",{className:Ut("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",ZS[e],r),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:eC[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 Nt({label:e,hint:t,children:n,className:r}){return s.jsxs("div",{className:Ut("mb-5",r),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 ms(e){const{className:t,...n}=e;return s.jsx("input",{...n,className:Ut("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 tC={primary:"btn-primary",secondary:"btn-secondary",warning:"btn-warning",danger:"btn-danger",ghost:"btn-ghost"},Ts=l.forwardRef(function({variant:t="secondary",size:n="md",type:r,className:a,...o},i){return s.jsx("button",{ref:i,type:r??"button",className:Ut("btn",tC[t],n==="sm"&&"btn-sm",a),...o})}),sC=l.forwardRef(function({options:t,children:n,className:r,...a},o){return s.jsx("select",{ref:o,className:Ut("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",r),...a,children:n??(t==null?void 0:t.map(i=>s.jsx("option",{value:i.value,disabled:i.disabled,children:i.label},i.value)))})}),nC={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"},rC={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function aC({status:e,label:t,className:n}){const r=t||e;return s.jsxs("span",{className:Ut("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",nC[e],n),children:[s.jsx("span",{className:Ut("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",rC[e])}),r]})}function Ys({label:e,description:t,checked:n,disabled:r,onChange:a,extra:o}){return s.jsxs("div",{className:`flex justify-between items-center ${r?"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":r,disabled:r,onClick:()=>a(!n),className:`relative inline-flex items-center ${r?"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 oC({onPrefChange:e}){const{t}=Ce("common"),[n,r]=lw(),[a,o]=l.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);l.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){o("unsupported");return}o(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,d)=>{r({[c]:d}),e==null||e(c,d)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Ys,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Hn,{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(Ys,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(gs,{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")}),a==="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:()=>{Gu().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")})]}),a==="denied"&&s.jsx("div",{className:"text-[11px] text-status-warning",children:t("notifications.permissionDenied")}),a==="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(Ys,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(yu,{size:15})," ",t("notifications.completionAlertsLabel")]}),description:t("notifications.completionAlertsDesc"),checked:n.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(Ys,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ab,{size:15})," ",t("notifications.approvalAlertsLabel")]}),description:t("notifications.approvalAlertsDesc"),checked:n.approvalAlert,onChange:c=>i("approvalAlert",c)}),s.jsx(Ys,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(br,{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 ki(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/);if(!t)return null;const n=t[4]??null;let r=null;if(n){const a=n.match(/(?:^|\.)(\d+)$/);r=a?Number(a[1]):null}return{base:[Number(t[1]),Number(t[2]),Number(t[3])],prereleaseNumber:r,isPrerelease:n!==null}}function Ta(e){var t;return((t=ki(e))==null?void 0:t.base)??null}function iC(e,t){const n=Ta(e),r=Ta(t);if(!n||!r)return e.localeCompare(t);for(let a=0;a<3;a+=1){if(n[a]<r[a])return-1;if(n[a]>r[a])return 1}return 0}function lC(e,t){const n=ki(e),r=ki(t);if(!n||!r)return e!==t;for(let a=0;a<3;a+=1){if(n.base[a]<r.base[a])return!0;if(n.base[a]>r.base[a])return!1}return n.isPrerelease&&r.isPrerelease?n.prereleaseNumber===null||r.prereleaseNumber===null?!1:n.prereleaseNumber<r.prereleaseNumber:!1}function ll(e,t){const n=e.version||null;return e.versionMismatch===!0?!0:!n||!t?!1:lC(n,t)}function ur(e,t){if(e.versionUpdateRequired===!0)return!0;const n=e.version||null;if(!n||!t||n===t||iC(n,t)>=0)return!1;const r=Ta(n),a=Ta(t);return!r||!a?!1:r[0]!==a[0]||r[1]!==a[1]}function cC(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function vo(e,t){return e instanceof Error?e.message:t}function dC({ides:e,emptyMessage:t,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:a}){const{t:o}=Ce("common"),i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?s.jsx(za,{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(pC,{ide:c,allIdes:e,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:a},c.id))})}function Uc({title:e,message:t,confirmLabel:n,confirmColor:r,onConfirm:a,onCancel:o}){const{t:i}=Ce("common"),c=r==="red"?"bg-status-error/20 text-status-error border-status-error/40 hover:bg-status-error/30":"";return an.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:"var(--z-modal)"},onClick:o,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:d=>d.stopPropagation(),children:[s.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),s.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:t}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.jsx("button",{onClick:o,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:i("common.cancel")}),s.jsx("button",{onClick:a,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,style:r==="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 uC(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),r=[..._S,...$S,...HS].find(a=>a.id===t||t.includes(a.id)||a.id.includes(t));return r?{icon:r.icon,name:r.name}:{icon:"📝",name:e}}function pC({ide:e,allIdes:t,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:a}){var G,H;const{t:o}=Ce("common"),[i,c]=l.useState("idle"),[d,p]=l.useState(""),[u,m]=l.useState(null),[f,g]=l.useState("idle"),[k,h]=l.useState(""),v=e.version||null,w=((G=e.machine)==null?void 0:G.platform)||((H=e.system)==null?void 0:H.platform)||"",b=as(e,{fallbackId:e.id}),j=w==="win32"?"🪟":w==="darwin"?"🍎":"🐧",C=t.filter(L=>L.daemonId===e.id&&L.transport==="cdp-page"),y=t.filter(L=>L.daemonId===e.id&&L.transport==="pty"),x=t.filter(L=>L.daemonId===e.id&&L.transport==="acp"),N=e.p2p,S=async()=>{if(n){c("upgrading"),p(o("machine.connectedMachines.startingUpgrade"));try{const L=cC(await n(e.id,"daemon_upgrade",{}));L.alreadyLatest?(c("done"),p(`Already on v${L.version||"latest"}.`)):L.upgraded||L.success?(c("done"),p(`Upgrade to v${L.version||"latest"} started. Daemon is restarting...`)):(c("error"),p(L.error||"Upgrade failed"))}catch(L){c("error"),p(vo(L,"Connection lost during upgrade"))}}},A=async()=>{if(m(null),!!r){g("loading");try{await r(e.id),g("done"),h(o("machine.connectedMachines.machineDisconnected"))}catch(L){g("error"),h(vo(L,o("machine.connectedMachines.failedToDisconnect")))}}},T=async()=>{if(m(null),!!a){g("loading");try{await a(e.id),g("done"),h(o("machine.connectedMachines.tokenRevoked"))}catch(L){g("error"),h(vo(L,o("machine.connectedMachines.failedToRevokeToken")))}}},I="1.0.26",D=ll(e,I),P=ur(e,I),_=C.length+y.length+x.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:j}),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),"…"]}),v&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${D?"":"bg-bg-secondary"}`,style:D?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",v,!D&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[n&&D&&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"):P?o("machine.connectedMachines.updateNow"):o("machine.connectedMachines.updateTo",{version:I})}),r&&s.jsx("button",{onClick:()=>m("disconnect"),disabled:f==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:o("machine.connectedMachines.disconnect")}),a&&s.jsx("button",{onClick:()=>m("revoke"),disabled:f==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:o("machine.connectedMachines.remove")}),s.jsx(aC,{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:[N&&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 ${N.state==="connected"?"bg-status-online":"bg-text-muted/30"} ${N.state==="connecting"||N.state==="new"?"animate-pulse":""}`,style:N.state==="connecting"||N.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",N.state==="connected"?"connected":N.state==="connecting"||N.state==="new"?o("machine.connectedMachines.connecting"):N.state||"off"]}),N.peers!==void 0&&N.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",N.peers," peer",N.peers!==1?"s":"",")"]})]}),N&&_>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),_>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[C.map(L=>{const O=uC(L.type),E=L.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:O.icon}),s.jsx("span",{children:O.name}),E!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${E?"bg-status-online":"animate-pulse"}`,style:E?void 0:{background:"var(--status-warning)"},title:o(E?"machine.connectedMachines.cdpConnected":"machine.connectedMachines.cdpConnecting")})]},L.id)}),y.map(L=>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:L.cliName||"CLI"})]},L.id)),x.map(L=>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:L.cliName||"ACP"})]},L.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:o("machine.connectedMachines.noIdesConnected")})]}),(d||k)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||f==="error"?"text-status-error":i==="done"||f==="done"?"text-status-online":"text-text-muted"}`,children:k||d})]}),u==="disconnect"&&s.jsx(Uc,{title:o("machine.connectedMachines.disconnectTitle"),message:`Disconnect "${b}" from ADHDev?
|
|
59
59
|
|
|
60
60
|
This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
|
|
61
61
|
|
|
@@ -66,8 +66,8 @@ This will:
|
|
|
66
66
|
• Delete the machine registration
|
|
67
67
|
• Require restarting ADHDev on that machine
|
|
68
68
|
|
|
69
|
-
Use this if you want to permanently remove a machine.`,confirmLabel:o("machine.connectedMachines.remove"),confirmColor:"red",onConfirm:T,onCancel:()=>m(null)})]})}const mC=["default","claude-cli","codex-cli","antigravity-cli","hermes-cli","gemini-cli"];function hC({daemonId:e,knownCliTypes:t=mC}){const{t:n}=Ce("common"),{sendCommand:r}=wt(),[a,o]=l.useState({}),[i,c]=l.useState({}),[d,p]=l.useState(!0),[u,m]=l.useState(null),[f,g]=l.useState(null),[k,h]=l.useState(""),v=l.useCallback(async()=>{if(e){p(!0),g(null);try{const j=await r(e,"list_coordinator_prompts",{}),C=j!=null&&j.result&&typeof j.result=="object"?j.result:j;if(!(C!=null&&C.success)){g((C==null?void 0:C.error)||"Failed to load");return}const y=C.entries||{};h(C.dir||"");const x={};for(const N of t)x[N]=y[N]||{override:"",append:""};for(const N of Object.keys(y))x[N]||(x[N]=y[N]);o(x),c(JSON.parse(JSON.stringify(x)))}catch(j){g((j==null?void 0:j.message)||String(j))}finally{p(!1)}}},[r,e,t]);l.useEffect(()=>{v()},[v]);const w=l.useCallback(async(j,C)=>{var y;if(e){m(`${j}:${C}`),g(null);try{const x=((y=a[j])==null?void 0:y[C])||"",N=await r(e,"write_coordinator_prompt",{key:j,kind:C,content:x}),S=N!=null&&N.result&&typeof N.result=="object"?N.result:N;if(!(S!=null&&S.success)){g((S==null?void 0:S.error)||"Save failed");return}c(A=>({...A,[j]:{...A[j]||{override:"",append:""},[C]:x}}))}catch(x){g((x==null?void 0:x.message)||String(x))}finally{m(null)}}},[r,e,a]),b=l.useMemo(()=>(j,C)=>{var y,x;return(((y=a[j])==null?void 0:y[C])||"")!==(((x=i[j])==null?void 0:x[C])||"")},[a,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(Xo,{i18nKey:"settings.coordinatorPrompts.overrideDesc",ns:"common",components:{strong:s.jsx("strong",{})}})," ",s.jsx(Xo,{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."]})]}),f&&s.jsx("div",{className:"text-[12px] text-status-error bg-status-error/10 border border-status-error/40 rounded px-3 py-2",children:f}),d&&s.jsx("div",{className:"text-[12px] text-text-muted",children:"Loading…"}),s.jsx("div",{className:"flex flex-col gap-6",children:Object.entries(a).map(([j,C])=>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:j}),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:C.override,onChange:y=>o(x=>({...x,[j]:{...x[j],override:y.target.value}})),placeholder:"(empty — use daemon default base prompt)",disabled:u===`${j}: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(j,"override"),disabled:u===`${j}:override`||!b(j,"override"),children:u===`${j}:override`?"Saving…":b(j,"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:C.append,onChange:y=>o(x=>({...x,[j]:{...x[j],append:y.target.value}})),placeholder:"(empty — nothing appended at this layer)",disabled:u===`${j}: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(j,"append"),disabled:u===`${j}:append`||!b(j,"append"),children:u===`${j}:append`?"Saving…":b(j,"append")?"Save append":"Saved"})})]},j))})]}):s.jsx("div",{className:"text-[12px] text-text-muted",children:"Connect a daemon to edit coordinator prompts."})}const fC=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function bC(){const{preference:e,setPreference:t}=Ws();return s.jsx("div",{className:"flex gap-2",children:fC.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 gC(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 xC(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function yo(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Gc(e){const{r:t,g:n,b:r}=xC(e);return .2126*yo(t)+.7152*yo(n)+.0722*yo(r)}function qc(e,t){const n=Gc(e),r=Gc(t),a=Math.max(n,r),o=Math.min(n,r);return(a+.05)/(o+.05)}function Jp(e){const t=gC(e);if(!t)return"#111827";const n="#111827",r="#ffffff";return qc(t,n)>=qc(t,r)?n:r}const Si={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},Ci={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},vC=[{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"}}}],Qp="adhdev-chat-theme",Xp="adhdev-chat-theme-custom";function oa(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Qp)||"ember"}catch{return"ember"}}function ps(e){try{const t=localStorage.getItem(Xp);if(t){const n=JSON.parse(t);return{...e==="dark"?Si:Ci,...n[e]}}}catch{}return e==="dark"?Si:Ci}function Or(e,t){try{localStorage.setItem(Xp,JSON.stringify({dark:e,light:t}))}catch{}}function ts(e,t){const n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),a=parseInt(e.slice(5,7),16);return`rgba(${n}, ${r}, ${a}, ${t})`}function Ma(e,t){const n=Math.min(255,parseInt(e.slice(1,3),16)+t),r=Math.min(255,parseInt(e.slice(3,5),16)+t),a=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${n.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const yC={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function pr(e,t){var a;const n=(a=yC[e])==null?void 0:a[t];if(!n)return;const r=document.documentElement;r.style.setProperty("--accent-primary",n),r.style.setProperty("--accent-primary-light",Ma(n,24)),r.style.setProperty("--accent-on-primary",Jp(n)),r.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${n}, ${Ma(n,18)})`),r.style.setProperty("--border-accent",ts(n,.35)),r.style.setProperty("--nav-active-bg",ts(n,.1)),r.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${n}, 0 0 12px ${ts(n,.06)}`)}function tn(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",ts(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",ts(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",ts(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",ts(e.borderSubtle,.5)),t.style.setProperty("--border-default",ts(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",Ma(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Jp(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Ma(e.accentColor,40)})`),t.style.setProperty("--border-accent",ts(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",ts(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${ts(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 ${ts(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 cl(){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 wC(e){try{localStorage.setItem(Qp,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=sn()?"dark":"light";tn(ps(t))}else cl(),pr(e,sn()?"dark":"light")}function kC(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=oa();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=sn()?"dark":"light";tn(ps(t))}else cl(),pr(e,sn()?"dark":"light")}function sn(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Ot({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:r=>n(r.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:r=>{/^#[0-9a-fA-F]{0,6}$/.test(r.target.value)&&n(r.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 Jn({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 SC({dark:e,onColorsChange:t}){const{t:n}=Ce("common"),r=e?"dark":"light",[a,o]=l.useState(()=>ps(r));l.useEffect(()=>{o(ps(r))},[r]);const i=l.useCallback((c,d)=>{o(p=>{const u={...p,[c]:d},f=ps(r==="dark"?"light":"dark");return r==="dark"?Or(u,f):Or(f,u),tn(u),t(u),u})},[r,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(Jn,{title:n("settings.theme.sectionAppBackground"),children:[s.jsx(Ot,{label:n("settings.theme.colorBackground"),value:a.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(Ot,{label:n("settings.theme.colorSurface"),value:a.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(Ot,{label:n("settings.theme.colorCard"),value:a.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(Jn,{title:n("settings.theme.sectionAppText"),children:[s.jsx(Ot,{label:n("settings.theme.colorPrimary"),value:a.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(Ot,{label:n("settings.theme.colorSecondary"),value:a.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(Ot,{label:n("settings.theme.colorMuted"),value:a.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(Jn,{title:n("settings.theme.sectionBordersAccent"),children:[s.jsx(Ot,{label:n("settings.theme.colorBorderSubtle"),value:a.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(Ot,{label:n("settings.theme.colorBorderDefault"),value:a.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(Ot,{label:n("settings.theme.colorAccent"),value:a.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(Jn,{title:n("settings.theme.sectionChatBubbles"),children:[s.jsx(Ot,{label:n("settings.theme.colorUserBubble"),value:a.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(Ot,{label:n("settings.theme.colorUserText"),value:a.userText,onChange:c=>i("userText",c)}),s.jsx(Ot,{label:n("settings.theme.colorAgentBubble"),value:a.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(Ot,{label:n("settings.theme.colorAgentText"),value:a.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(Jn,{title:n("settings.theme.sectionChatLayout"),children:[s.jsx(Ot,{label:n("settings.theme.colorChatBg"),value:a.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(Ot,{label:n("settings.theme.colorSendButton"),value:a.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(Ot,{label:n("settings.theme.colorInputBorder"),value:a.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:a.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:[a.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const c=e?Si:Ci,p=ps(e?"light":"dark");e?Or(c,p):Or(p,c),o(c),tn(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 CC(){const{t:e}=Ce("common"),[t,n]=l.useState(oa),[r,a]=l.useState(!0),[o,i]=l.useState(()=>ps("dark"));l.useEffect(()=>{a(sn());const p=new MutationObserver(()=>{const f=sn();a(f);const g=oa();g==="custom"?tn(ps(f?"dark":"light")):pr(g,f?"dark":"light")});p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const u=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const f=sn();a(f);const g=oa();g==="custom"?tn(ps(f?"dark":"light")):pr(g,f?"dark":"light")};return u.addEventListener("change",m),()=>{p.disconnect(),u.removeEventListener("change",m)}},[]),l.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?tn(ps(r?"dark":"light")):(cl(),pr(t,r?"dark":"light"))},[t,r]),l.useEffect(()=>{i(ps(r?"dark":"light"))},[r]);const c=p=>{n(p),wC(p)},d=[...vC,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText},light:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:d.map(p=>{const u=t===p.id,m=r?p.preview.dark:p.preview.light,f=p.id==="honey"||p.id==="ember"?"#1a1a1a":p.id==="custom"?o.userText:"#fff";return s.jsxs("button",{onClick:()=>c(p.id),className:"text-left rounded-xl p-3 transition-all",style:{background:u?"var(--bg-glass-hover)":"var(--bg-glass)",border:u?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:u?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:m.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:e("settings.theme.helloHelp")}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.userBubble,color:f},children:e("settings.theme.fixBug")}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:e("settings.theme.onIt")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[u&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:p.id==="custom"?e("settings.theme.customLabel"):p.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:p.description})]})]})]},p.id)})}),t==="custom"&&s.jsx(SC,{dark:r,onColorsChange:p=>i(p)})]})}const dl="adhdev_mobileDashboardMode_v1",ji="adhdev:mobile-dashboard-mode-change";function ul(){try{return localStorage.getItem(dl)==="workspace"?"workspace":"chat"}catch{return"chat"}}function jC(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??ul())},n=a=>{const o=a.detail;t(o)},r=a=>{a.key&&a.key!==dl||t()};return window.addEventListener(ji,n),window.addEventListener("storage",r),()=>{window.removeEventListener(ji,n),window.removeEventListener("storage",r)}}function NC(e){try{localStorage.setItem(dl,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(ji,{detail:e}))}function AC(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(ul()==="chat")},[]),s.jsx(Ys,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(un,{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),NC(n?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const TC="Choose a preset or create a fully custom theme. Custom themes control the entire app — backgrounds, text, borders, and chat bubbles.",MC="Choose whether the dashboard opens like a chat app on phones or keeps the full workspace layout.";function PC({themeDescription:e=TC,mobileDescription:t=MC,fontsSlot:n}){const{t:r}=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:r("settings.appearance.modeLabel")}),s.jsx(bC,{})]}),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:r("settings.appearance.themeLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:e}),s.jsx(CC,{})]}),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:r("settings.appearance.mobileLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:t}),s.jsx(AC,{})]})]})}const wo=new Map,zc=new Map;function DC(e){if(!e||typeof e!="object")return null;const t=e,n=t.result&&typeof t.result=="object"?t.result:t,r=n.machine;return!r||typeof r!="object"?null:{machine:r,timestamp:typeof n.timestamp=="number"?n.timestamp:void 0}}function IC(e,t,n,r){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:r,platform:n.platform,machine:n}}function Zp(){const{sendCommand:e}=wt(),{injectEntries:t,getIdes:n}=fr();return l.useCallback(async(r,a)=>{if(!r)return;const o=(a==null?void 0:a.minFreshMs)??F0,i=zc.get(r)||0;if(!(a!=null&&a.force)&&i>0&&Date.now()-i<o)return;const c=wo.get(r);if(c)return c;const d=(async()=>{const p=await e(r,"get_machine_runtime_stats"),u=DC(p);if(!u)return;const m=n().find(g=>g.id===r),f=IC(m,r,u.machine,u.timestamp||Date.now());t([f]),zc.set(r,Date.now())})().finally(()=>{wo.delete(r)});return wo.set(r,d),d},[n,t,e])}function LC(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 RC(e,t){const{sendData:n}=wt(),{injectEntries:r,getIdes:a}=fr(),o=Array.from(new Set(e.filter(Boolean))).join("|");l.useEffect(()=>{if(!(t!=null&&t.enabled)||!n)return;const i=o?o.split("|"):[];if(i.length===0)return;const c=i.map(d=>hs.subscribe({sendData:n},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const m=a().find(g=>g.id===d),f=LC(m,d,u);r([f])}));return()=>{c.forEach(d=>d())}},[o,a,r,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,n])}function EC(e,t){const{sendData:n}=wt(),[r,a]=l.useState(null),[o,i]=l.useState(!1);return l.useEffect(()=>{if(!e){a(null),i(!1);return}if(!(t!=null&&t.enabled)||!n){i(!1);return}a(null),i(!0);let c=null;const d=hs.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),a(p.diagnostics),i(!1)});return d.initialSendAccepted?c=setTimeout(()=>{i(!1)},W0):i(!1),()=>{c&&clearTimeout(c),d()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,n]),{diagnostics:r,loading:o,applyDiagnostics:a}}function _C(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function em(e){const{sendData:t}=wt(),[n,r]=l.useState({});return l.useEffect(()=>{const a=_C(e);if(!a||!e.sessionId||!t){r({});return}const o=hs.subscribe({sendData:t},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},i=>{r({status:i.status,modalMessage:i.modalMessage,modalButtons:i.modalButtons}),Tn.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||r({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,t]),n}function $C(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function HC(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 FC(e,t,n){const r=await n(`/api/v1/sessions/${encodeURIComponent(e)}/interactive-prompt/resolve`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let a=`HTTP ${r.status}`;try{const o=await r.json();typeof(o==null?void 0:o.error)=="string"&&(a=o.error)}catch{}throw new Error(a)}}async function BC({promptSession:e,response:t,useP2PCommand:n,sendCommand:r,fetchImpl:a=fetch}){if(n){const o=await r(e.routeId,"interactive_prompt_response",{targetSessionId:e.sessionId,sessionId:e.sessionId,response:t});if(!$C(o))throw new Error(HC(o));return}await FC(e.sessionId,t,a)}function tm(e){const{ides:t,isP2PActive:n,p2pStates:r}=js(),{sendCommand:a}=wt(),[o,i]=l.useState(null),[c,d]=l.useState(!1),[p,u]=l.useState(null),m=l.useRef(!1),f=l.useMemo(()=>Ub(t,e),[t,e]),g=!!f,k=l.useMemo(()=>f?f.prompt.promptId===o?null:f:null,[o,f]),h=l.useCallback(async b=>{if(!k||m.current)return;m.current=!0;const j=Mu(k.prompt,b);d(!0),u(null);try{const C=(r==null?void 0:r[k.daemonId])==="connected"||n===!0;await BC({promptSession:k,response:j,useP2PCommand:C,sendCommand:a}),i(k.prompt.promptId)}catch(C){throw u(C instanceof Error?C.message:String(C)),C}finally{d(!1),m.current=!1}},[n,r,k,a]),v=l.useCallback(()=>{k&&i(k.prompt.promptId)},[k]),w=l.useCallback(()=>{i(null),u(null)},[]);return{promptSession:k,hasActivePrompt:g,responseError:p,isSubmitting:c,submit:h,cancel:v,reopen:w}}function sm(e){return e instanceof Error?e.message:String(e||"")}function OC(e){const t=sm(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 WC(e){const t=sm(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function nm({conversation:e,mode:t,ides:n,sendDaemonCommand:r,setCliViewModeOverrides:a}){if(!e||!mt(e)||dt(e))return;const o=Fn(e);if(o===t)return;const i=e.sessionId;i&&a(c=>({...c,[i]:t}));try{await r(Ds(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Cs(e),mode:t})}catch(c){const d=WC(c);i&&!d&&a(p=>{const u={...p};return o===GC(n,i)?delete u[i]:u[i]=o,u}),OC(c)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",c instanceof Error?c.message:String(c)):console.error("Failed to switch CLI view mode:",c)}}function Kc(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 r=t[n];return!r||e.mode===r?e:{...e,mode:r}}function UC(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let n=!1;const r=e.map(a=>{const o=Kc(a,t),i=Array.isArray(a.childSessions)?a.childSessions.map(d=>Kc(d,t)):a.childSessions,c=i!==a.childSessions;return o!==a||c?(n=!0,{...o,...c?{childSessions:i}:{}}):a});return n?r:e}function GC(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 r of n.childSessions||[])if(r.id===t&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal"}return null}function qC({visibleConversations:e,clearedTabs:t,setClearedTabs:n,setActionLogs:r,isConversationMuted:a}){l.useEffect(()=>{Gu()},[]);const o=l.useMemo(()=>e.map(i=>({id:i.tabKey,name:Pp(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:a?a(i):!1})),[e,a]);return pw(o),l.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{n(d=>{const p=Date.now(),u={};for(const[m,f]of Object.entries(d))p-f<5e3&&(u[m]=f);return Object.keys(u).length===Object.keys(d).length?d:u})},5500);return()=>clearTimeout(c)},[t,n]),l.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;r(d=>{const p=d.filter(u=>u.timestamp>c).slice(-100);return p.length===d.length?d:p})},6e4);return()=>clearInterval(i)},[r]),null}function Vc(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 nn(e){const t=[...e.messages].reverse().find(a=>!(a!=null&&a._localId))||e.messages[e.messages.length-1],n=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,r=Vc(t==null?void 0:t.receivedAt)||Vc(t==null?void 0:t.timestamp)||0;return Math.max(n,r)}function Ni(e,t=0){return nn(e)||e.lastUpdated||t||0}function rm(e){return nn(e)||e.lastUpdated||0}function am(e,t,n=rm){const r=n(t)-n(e);if(r!==0)return r;const a=(e.machineName||"").localeCompare(t.machineName||"");if(a!==0)return a;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 Ai(e){var n;const t=ns(e.status,{activeModal:(n=e.modalButtons)!=null&&n.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function zC(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!Ai(e)&&!e.title.trim()}function KC(e){return e.length===0?null:[...e].sort((t,n)=>{const r=Number(Ai(n))-Number(Ai(t));if(r!==0)return r;const a=n.messages.length-t.messages.length;return a!==0?a:am(t,n)})[0]||null}function fs(e,t){const n=e.filter(i=>i.routeId===t);if(n.length===0)return null;const r=n.find(i=>i.streamSource==="native")||null,a=n.filter(i=>i.streamSource==="agent-stream"),o=KC(a);return r?o&&zC(r)?o:r:o||n[0]||null}function VC(e){const t=e.filter(a=>a.type!=="adhdev-daemon"),n=new Set;for(const a of t){if(!ui(a))continue;const o=Hu(a);o&&n.add(o)}const r=new Map;for(const a of t){const o=Uy(a,n),i=r.get(o);if(!i){r.set(o,a);continue}const c=m=>(m.workspace?1:0)+(m.activeChat?1:0)+(m.lastMessagePreview?1:0),d=c(i),p=c(a),u=p>d||p===d&&(a.timestamp||0)>(i.timestamp||0)?a:i;r.set(o,YC(u,u===a?i:a))}return Array.from(r.values())}function YC(e,t){const n=ui(t),r=ui(e);if(!n&&!r)return e;const a=r?n?void 0:t:e,o=r?e:n?t:void 0,i=a&&String(a.daemonId||"").trim()||String(e.ownerDaemonId||"").trim()||String(t.ownerDaemonId||"").trim()||void 0,c=String(e.ownerMachineName||"").trim()||String(t.ownerMachineName||"").trim()||void 0,d=o==null?void 0:o.settings;return{...e,...i&&{ownerDaemonId:i},...c&&!e.ownerMachineName&&{ownerMachineName:c},...d&&!r&&{settings:{...d,...e.settings??{}}}}}function ko(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 JC(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 Yc(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],n=t[t.length-1],r=n?JC(Mn(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)??""),r].join(":")}function QC(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||""),Yc(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||""),Yc(n.activeChat)].join(":"))].join("|")}function XC(e,t){const n=Date.now();return e.map(r=>{const a=t[r.tabKey];return a&&n-a<5e3?{...r,messages:[],title:""}:r})}function ZC(e,t){const n=new Map;for(const r of e){const a=t.get(r.routeId)||r;for(const o of lr({routeId:r.routeId}))n.set(o,a);for(const o of lr({providerSessionId:r.providerSessionId,sessionId:r.sessionId}))n.set(o,r.streamSource==="native"?a:r);for(const o of lr({tabKey:r.tabKey}))n.set(o,r)}return n}function ej(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function tj(e){const t=ej(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||""),r=Mn(t.content).slice(0,240);return`${e.messages.length}:${n}:${r}`}function sj({ides:e,connectionStates:t,clearedTabs:n}){const r=l.useMemo(()=>VC(e),[e]),a=l.useMemo(()=>Iu(e),[e]),o=l.useMemo(()=>Op(e),[e]),i=l.useRef([]),c=l.useRef([]),d=l.useRef([]),p=l.useRef(new Map),u=l.useRef(new Map),m=l.useMemo(()=>{const C=new Map,y=[];for(const A of r){const{connectionState:T="new",machineName:I}=Wp(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),D=QC(A),P=p.current.get(A.id);if(P&&P.ide===A&&P.sourceSignature===D&&P.connectionState===T&&P.machineName===I){C.set(A.id,P),y.push(...P.conversations);continue}const _=il(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),G={ide:A,sourceSignature:D,connectionState:T,machineName:I,conversations:_};C.set(A.id,G),y.push(..._)}p.current=C;const x=new Map,N=A=>{const T=tj(A),I=u.current.get(A.tabKey);if(I&&I.signature===T)return x.set(A.tabKey,I),I.timestamp;const D={signature:T,timestamp:rm(A)||(I==null?void 0:I.timestamp)||0};return x.set(A.tabKey,D),D.timestamp},S=[...y].sort((A,T)=>am(A,T,N));return u.current=x,S},[r,t,o]),f=l.useMemo(()=>{const C=XC(m,n);return ko(i.current,C)?i.current:(i.current=C,C)},[m,n]),g=l.useMemo(()=>{const C=new Map,y=Array.from(new Set(f.map(x=>x.routeId)));for(const x of y){const N=fs(f,x);N&&C.set(x,N)}return C},[f]),k=l.useMemo(()=>{const C=new Map;for(const y of f){const x=g.get(y.routeId),N=y.streamSource==="native"&&x?x:y;for(const S of lr({providerSessionId:y.providerSessionId,sessionId:y.sessionId,tabKey:y.tabKey}))C.set(S,N)}return C},[f,g]),h=l.useMemo(()=>ZC(f,g),[f,g]),v=l.useCallback(C=>{if(C)return k.get(C)},[k]),w=l.useCallback(C=>{if(C)return h.get(C)},[h]),b=l.useMemo(()=>{const C=f.filter(y=>!Os(y,a).surfaceHidden);return ko(c.current,C)?c.current:(c.current=C,C)},[f,a]),j=l.useMemo(()=>{const C=b.map(y=>y.tabKey);return ko(d.current,C)?d.current:(d.current=C,C)},[b]);return{chatIdes:r,conversations:f,visibleConversations:b,visibleTabKeys:j,resolveConversationBySessionId:v,resolveConversationByTarget:w}}function nj({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:n,setSearchParams:r}){const a=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&&r(c=>{const d=new URLSearchParams(c);return d.delete("activeTab"),d},{replace:!0})},[r,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:o,consumeRequestedActiveTab:i}}function rj({ides:e,sendDaemonCommand:t,setToasts:n,resolveConversationByTarget:r}){l.useEffect(()=>{ht.setIdes(e)},[e]),l.useEffect(()=>{ht.setResolveAction((a,o,i)=>{t(a,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const a=ht.onToast(o=>{n(c=>c.some(p=>p.message===o.message&&o.timestamp-p.timestamp<3e3)?c:[...c.slice(-4),{id:o.id,message:o.message,type:o.type,timestamp:o.timestamp,targetKey:o.targetKey,actions:o.actions}]);const i=o.duration||5e3;setTimeout(()=>n(c=>c.filter(d=>d.id!==o.id)),i)});return()=>{a()}},[n]),l.useEffect(()=>{const a=Np.on("status_event",o=>{ht.handleRawEvent(o,"ws")});return()=>{a()}},[]),l.useEffect(()=>{var o;const a=i=>{var h;const c=i.data;if((c==null?void 0:c.type)!=="notification_action"||typeof c.action!="string"||!c.action.startsWith("approval_")||!(c.daemonId||c.targetSessionId||c.targetKey))return;const d=c.targetSessionId||c.targetKey||c.daemonId,p=r(d),u=(p==null?void 0:p.routeId)||c.daemonId;if(!u)return;const m=Number(c.buttonIndex),f=c.button||((h=p==null?void 0:p.modalButtons)==null?void 0:h[m])||"Approve",g=String(f).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),k=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(g);t(u,"resolve_action",{action:k?"approve":"reject",button:f,...Number.isFinite(m)&&{buttonIndex:m},...(p==null?void 0:p.sessionId)&&{targetSessionId:p.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(v=>console.error("[SW Action] approval failed:",v))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",a),()=>{var i;return(i=navigator.serviceWorker)==null?void 0:i.removeEventListener("message",a)}},[r,t])}const aj="adhdev_dashboardLayout_v1",oj="adhdev_dashboardDockview_v1",ij="adhdev_dashboardDockviewHiddenRestore_v1",Qn={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function pl(e,t){try{const n=localStorage.getItem(e);return n?JSON.parse(n):t}catch{return t}}function lj(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function om(e){return`${aj}:${e}`}function cj(e){const t=om(e);return pl(t,null)}function dj(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,r=om(e);if(n){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function im(e){return`${oj}:${e}`}function uj(e){const t=im(e);return pl(t,null)}function pj(e,t){try{const n=im(e);if(!t){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function lm(e){return`${ij}:${e}`}function mj(e){const t=lm(e);return pl(t,{})}function hj(e,t){try{const n=lm(e);if(Object.keys(t).length===0){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function fj(){return{groupAssignments:[...Qn.groupAssignments],focusedGroup:Qn.focusedGroup,groupActiveTabIds:{...Qn.groupActiveTabIds},groupTabOrders:{...Qn.groupTabOrders},groupSizes:[...Qn.groupSizes]}}function bj(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):t.length===0}function gj(){const[e]=l.useState(()=>lj(typeof window<"u"?window.innerWidth:1280)),[t,n]=l.useState(()=>new Map),[r,a]=l.useState(0),[o,i]=l.useState({}),[c,d]=l.useState({}),[p,u]=l.useState([]),[m,f]=l.useState(()=>typeof window<"u"&&window.innerWidth<768),[g,k]=l.useState(!1),h=l.useCallback(()=>{if(g)return;const A=cj(e)??fj();n(new Map(A.groupAssignments)),a(A.focusedGroup),i(A.groupActiveTabIds),d(A.groupTabOrders),u(A.groupSizes),k(!0)},[g,e]);l.useEffect(()=>{g&&dj(e,{groupAssignments:[...t.entries()],focusedGroup:r,groupActiveTabIds:o,groupTabOrders:c,groupSizes:p})},[g,e,t,r,o,c,p]),l.useEffect(()=>{const A=window.matchMedia("(max-width: 767px)"),T=I=>f(I.matches);return A.addEventListener("change",T),()=>A.removeEventListener("change",T)},[]);const v=l.useCallback(A=>{n(A)},[]),w=l.useCallback(A=>{a(A)},[]),b=l.useCallback(A=>{i(A)},[]),j=l.useCallback(A=>{d(A)},[]),C=l.useCallback(A=>{u(A)},[]),y=l.useCallback(A=>{w(A)},[w]),x=l.useCallback((A,T)=>{i(I=>(I[A]??null)===(T??null)?I:{...I,[A]:T})},[]),N=l.useCallback((A,T)=>{d(I=>{const D=I[A];return bj(D,T)?I:{...I,[A]:T}})},[]),S=l.useCallback((A,T)=>{const I=T.get(A)??0;return x(I,A),y(I),I},[y,x]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:v,focusedGroup:r,updateFocusedGroup:w,focusGroup:y,groupActiveTabIds:o,updateGroupActiveTabIds:b,setGroupActiveTab:x,groupTabOrders:c,updateGroupTabOrders:j,setGroupTabOrder:N,groupSizes:p,updateGroupSizes:C,isMobile:m,hasHydratedStoredLayout:g,hydrateStoredLayout:h,focusConversationTab:S}}function xj(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0],r=Fa(t);return typeof(n==null?void 0:n.id)=="string"&&r.includes(n.id)}function vj({urlActiveTab:e,conversations:t,resolveConversationBySessionId:n,normalizedGroupAssignments:r,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:i,setSearchParams:c,historyModalOpen:d,activeConv:p,isRefreshingHistory:u,ides:m,handleRefreshHistory:f}){const g=l.useRef(!1),k=l.useRef(!1),h=l.useRef(null),v=l.useRef(!1);l.useEffect(()=>{if(!e||g.current||t.length===0)return;if(!a){o();return}const w=n(e);w&&(i(w.tabKey,r),g.current=!0,k.current=!0,h.current!=null&&(window.clearTimeout(h.current),h.current=null),c(b=>{const j=new URLSearchParams(b);return j.delete("activeTab"),j},{replace:!0}))},[e,t,n,r,a,o,i,c]),l.useEffect(()=>{if(!(k.current||a)&&t.length!==0){if(!e){o(),k.current=!0;return}if(g.current){k.current=!0;return}if(h.current==null)return h.current=window.setTimeout(()=>{h.current=null,!(k.current||a)&&(o(),k.current=!0)},1500),()=>{h.current!=null&&(window.clearTimeout(h.current),h.current=null)}}},[e,t.length,a,o]),l.useEffect(()=>{if(!d){v.current=!1;return}if(!p||v.current||u)return;const w=m.find(b=>b.id===p.routeId);w&&(!w.chats||w.chats.length===0||xj(w.chats,p))&&(v.current=!0,f())},[d,p,u,m,f])}function So(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 r=Fa(t);return typeof(n==null?void 0:n.id)=="string"&&r.includes(n.id)}function cm({sendDaemonCommand:e,activeConv:t,chats:n,updateRouteChats:r,setToasts:a,setClearedTabs:o}){const[i,c]=l.useState(!1),[d,p]=l.useState(!1),u=l.useCallback(async k=>{try{await e("standalone","launch_ide",{ideType:k,enableCdp:!0})}catch(h){console.error("Launch failed",h)}},[e]),m=l.useCallback(async(k,h)=>{try{const v=k||(t==null?void 0:t.daemonId)||"",w=await e(v,"switch_chat",{id:h,sessionId:h,...Xs(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"?vn(a,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?vn(a,`⚠️ Switch error: ${b}`):vn(a,"⚠️ Session switch failed")}catch(v){console.error("Switch failed",v),vn(a,`❌ Switch failed: ${v.message||"connection error"}`)}},[t,e,a]),f=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const k=Zs(t);await e(k,"new_chat",{...Xs(t)}),ik(k,t.sessionId,Fa(t)[0]),o(h=>({...h,[t.tabKey]:Date.now()}))}catch(k){console.error("New chat failed",k)}finally{c(!1)}}},[t,i,e,o]),g=l.useCallback(async()=>{var k,h;if(!(!t||d)){p(!0);try{const v=Zs(t),w=async()=>e(v,"list_chats",{forceExpand:!0,...Xs(t)});let b=await w(),j=(b==null?void 0:b.chats)||((k=b==null?void 0:b.result)==null?void 0:k.chats);So(j,t)&&(await new Promise(C=>setTimeout(C,450)),b=await w(),j=(b==null?void 0:b.chats)||((h=b==null?void 0:b.result)==null?void 0:h.chats)),b!=null&&b.success&&Array.isArray(j)&&(r(t.routeId,j),So(j,t)&&!So(n,t)&&vn(a,"⚠️ History dialog did not fully open — try once more"))}catch(v){console.error("Refresh history failed",v)}finally{p(!1)}}},[t,n,d,e,r,a]);return{isCreatingChat:i,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:m,handleNewChat:f,handleRefreshHistory:g}}function yj(e,t){if(e.size!==t.size)return!1;for(const[n,r]of e)if(t.get(n)!==r)return!1;return!0}function wj(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function Jc(e,t){const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(a=>t[Number(a)]===e[Number(a)])}function Wr(e,t){const n=new Set(t),r=t.length>0?[0]:[];for(const[i,c]of e)!n.has(i)||c<=0||r.includes(c)||r.push(c);r.sort((i,c)=>i-c);const a={};r.forEach((i,c)=>{a[i]=c}),r.length===0&&(a[0]=0);const o=new Map;for(const[i,c]of e){if(!n.has(i)||c<=0)continue;const d=a[c];typeof d=="number"&&d>0&&o.set(i,d)}return{assignments:o,groupCount:Math.max(1,r.length),mapping:a,usedGroups:r}}function Qc(e,t){const n={};for(const[r,a]of Object.entries(e)){const o=t[Number(r)];typeof o=="number"&&(n[o]=a)}return n}function kj(e,t,n){if(t.length===0)return 0;if(typeof n[e]=="number")return n[e];const r=[...t].reverse().find(a=>a<e)??t[0];return n[r]??0}function Sj(e,t,n){if(t.length<=1)return[];const r=t.map(i=>e[i]).filter(i=>Number.isFinite(i)),a=r.length===t.length?r:Array(n).fill(100/n),o=a.reduce((i,c)=>i+c,0);return o>0?a.map(i=>i/o*100):Array(n).fill(100/n)}function Xc(e,t){const n={};for(const[r,a]of Object.entries(e)){const o=Number(r);n[o>=t?o+1:o]=a}return n}function Zc(e){return Array(e).fill(100/e)}function Cj({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:n,updateGroupActiveTabIds:r,updateGroupTabOrders:a,groupSizes:o,updateGroupSizes:i,isMobile:c,visibleConversations:d,visibleTabKeys:p}){const u=l.useRef(null),m=l.useMemo(()=>Wr(e,p),[e,p]),f=m.assignments,g=l.useMemo(()=>c?1:m.groupCount,[m.groupCount,c]),k=g>1,h=l.useCallback((y,x)=>{t(N=>{const S=new Map(Wr(N,p).assignments);return x===0?S.delete(y):S.set(y,x),S}),r(N=>({...N,[x]:y})),n(x)},[t,p,r,n]),v=l.useCallback(y=>{t(x=>{const N=Wr(x,p).assignments,S=new Map;for(const[A,T]of N)T!==y&&(T>y?S.set(A,T-1):S.set(A,T));return S}),i(x=>{if(x.length<=1)return[];const N=[...x];N.splice(y,1);const S=N.reduce((A,T)=>A+T,0);return S>0?N.map(A=>A/S*100):[]}),n(0)},[t,p,i,n]),w=l.useCallback((y,x)=>{x.preventDefault();const N=u.current;if(!N)return;const S=x.clientX,A=N.offsetWidth,T=o.length===g?[...o]:Zc(g),I=P=>{const G=(P.clientX-S)/A*100,H=[...T];H[y]=Math.max(15,T[y]+G),H[y+1]=Math.max(15,T[y+1]-G),i(H)},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((y,x,N)=>{if(g>=4)return;const S=N==="left"?x:x+1;t(A=>{const T=Wr(A,p).assignments,I=new Map;for(const D of d){const P=T.get(D.tabKey)??0,_=P>=S?P+1:P;_>0&&I.set(D.tabKey,_)}return S>0&&I.set(y,S),I}),i(A=>{const T=A.length===g?[...A]:Zc(g),I=T[x]??100/g,D=Math.max(15,I/2),P=Math.max(15,I/2),_=[...T];_[x]=D,_.splice(S,0,P);const G=_.reduce((H,L)=>H+L,0);return _.map(H=>H/G*100)}),r(A=>{const T=Xc(A,S);return T[S]=y,T}),a(A=>{const T=Xc(A,S);return T[S]=[y],T}),n(S)},[g,t,p,d,i,r,a,n]);l.useEffect(()=>{yj(e,f)||t(f)},[e,f,t]),l.useEffect(()=>{const{mapping:y,usedGroups:x}=m;r(N=>{const S=Qc(N,y);return Jc(N,S)?N:S}),a(N=>{const S=Qc(N,y);return Jc(N,S)?N:S}),n(N=>{const S=c?0:kj(N,x,y);return N===S?N:S}),i(N=>{const S=c?[]:Sj(N,x,m.groupCount);return wj(N,S)?N:S})},[m,c,r,a,n,i]);const j=l.useMemo(()=>{const y=Array.from({length:g},()=>[]);for(const x of d){const N=f.get(x.tabKey)??0,S=Math.min(N,g-1);y[S].push(x)}return y},[d,f,g]),C=l.useCallback(()=>{t(new Map),n(0)},[t,n]);return{containerRef:u,normalizedGroupAssignments:f,numGroups:g,isSplitMode:k,groupedConvs:j,moveTabToGroup:h,closeGroup:v,handleResizeStart:w,splitTabRelative:b,clearAllSplits:C}}function Co(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 jj(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 Ur(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function ml(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},n=Co(t.channel)||Co(e.updateChannel)||Co(e.releaseChannel)||void 0,r=jj(t.npmTag)||(n==="preview"?"next":n==="stable"?"latest":void 0),a=Ur(t.targetVersion)||Ur(e.serverVersion)||void 0,o=Ur(t.minVersion)||void 0,i=Ur(t.updateCommand)||(n?`adhdev update --channel ${n}`:void 0);return{...n?{channel:n}:{},...r?{npmTag:r}:{},...a?{targetVersion:a}:{},...o?{minVersion:o}:{},...i?{updateCommand:i}:{}}}function kn(e,t=null){return ml(e).targetVersion||t}function dm(e){return ml(e).channel||null}function um(e){const t=ml(e);return{...t.channel?{channel:t.channel}:{},...t.npmTag?{npmTag:t.npmTag}:{},...t.targetVersion?{targetVersion:t.targetVersion}:{},...Object.keys(t).length>0?{updatePolicy:t}:{}}}function Nj({ides:e,sendDaemonCommand:t}){const n="1.0.24",r=l.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:ll(m,kn(m,n))).sort((m,f)=>Number(ur(f,kn(f,n)))-Number(ur(m,kn(m,n)))),[n,e]),a=l.useMemo(()=>r.some(m=>ur(m,kn(m,n))),[n,r]),o=l.useMemo(()=>r.map(m=>kn(m,n)).find(m=>typeof m=="string"&&m.trim().length>0)||n,[n,r]),[i,c]=l.useState(!1),[d,p]=l.useState({}),u=l.useCallback(async m=>{var g,k;const f=e.find(h=>h.id===m);if(f){p(h=>({...h,[m]:"upgrading"}));try{const h=await t(m,"daemon_upgrade",um(f));(g=h==null?void 0:h.result)!=null&&g.upgraded||(k=h==null?void 0:h.result)!=null&&k.success?p(v=>({...v,[m]:"done"})):p(v=>({...v,[m]:"error"}))}catch{p(h=>({...h,[m]:"error"}))}}},[e,t]);return{versionMismatchDaemons:r,hasRequiredVersionDaemons:a,targetVersion:o,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:u}}const pm=80;function ia(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function Aj(e){return{...e,createdAt:ia(e.createdAt),updatedAt:ia(e.updatedAt,e.createdAt),lastEventAt:ia(e.lastEventAt,e.updatedAt||e.createdAt)}}function Tj(e){const t=$u(e);return t==="unknown:"?e.id:t}function Mj(e){return[e.type,_u(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Pj(e,t=pm){const n=new Map;for(const r of e){if(r.deletedAt)continue;const a=Tj(r),o=n.get(a);if(!o){n.set(a,r);continue}(r.updatedAt>o.updatedAt||r.updatedAt===o.updatedAt&&r.createdAt>o.createdAt)&&n.set(a,r)}return Array.from(n.values()).sort((r,a)=>{const o=a.updatedAt-r.updatedAt;return o!==0?o:a.createdAt-r.createdAt}).slice(0,Math.max(0,t))}function Dj(e,t){const n=Date.now(),r=[];for(const a of e){const o=a.sessionId?t.get(a.sessionId):void 0;if(o!=null&&o.surfaceHidden||o!=null&&o.muted)continue;const i=Ha(a,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const d=ia(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,n),p=Mj({type:c,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,lastMessageHash:a.lastMessageHash,lastMessageAt:a.lastMessageAt,lastUpdated:(o==null?void 0:o.lastUpdated)||a.lastUpdated});r.push(Aj({id:p,dedupKey:p,type:c,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:np(a),preview:v0(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return Pj(r)}function Ij(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function Lj(e){const{conversations:t,liveSessionInboxState:n,maxItems:r=pm}=e,a=l.useMemo(()=>Dj(t,n).slice(0,Math.max(0,r)),[t,n,r]),o=l.useMemo(()=>Ij(a),[a]);return{notifications:a,unreadCount:o}}function Rj({notifications:e,sendDaemonCommand:t}){const n=l.useCallback(o=>{const i=e.find(d=>d.id===o),c=Math.max(Date.now(),(i==null?void 0:i.updatedAt)||0);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_session_seen",{sessionId:i.sessionId,seenAt:c}).catch(()=>{})},[e,t]),r=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]),a=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:r,handleDeleteDashboardNotification:a}}function hl(...e){const t=new Set,n=[],r=a=>{const o=typeof a=="string"?a.trim():"";if(!o)return;const i=o.toLowerCase();t.has(i)||(t.add(i),n.push(o))};for(const a of e){if(Array.isArray(a)){for(const o of a)r(o);continue}r(a)}return n}function Ej(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 r=n[1].toUpperCase(),a=(n[2]||"").replace(/[\\/]+/g,"\\");return a?`${r}:\\${a}`:`${r}:\\`}return null}function fl(e,t=[]){if(e==="win32"){for(const n of t){if(typeof n!="string")continue;const r=Ej(n);if(r)return r}return"C:\\"}for(const n of t){const r=typeof n=="string"?n.trim():"";if(r)return r}return"~"}function _j(e){const t=e.replace(/[\\/]+$/,"");if(!t||t==="/"||/^[A-Za-z]:$/.test(t))return null;const n=t.includes("\\")?"\\":"/",r=t.split(/[\\/]/);return/^[A-Za-z]:$/.test(r[0]||"")?r.length<=2?`${r[0]}\\`:r.slice(0,-1).join("\\"):r.length<=2?n:r.slice(0,-1).join(n)||n}function $j(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function bl(e,t,n){const r=await e(t,"file_list_browse",{path:n}),a=$j(r);if(!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||(r==null?void 0:r.error)||"Could not browse folder");const o=typeof(a==null?void 0:a.path)=="string"?a.path:n,i=o.includes("\\")?"\\":"/",c=(p,u)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${u}`:p==="/"||p==="\\"?`${i}${u}`:`${p.replace(/[\\/]+$/,"")}${i}${u}`,d=Array.isArray(a==null?void 0:a.files)?a.files.filter(p=>(p==null?void 0:p.type)==="directory"&&typeof(p==null?void 0:p.name)=="string").map(p=>({name:p.name,path:typeof(p==null?void 0:p.path)=="string"&&p.path.trim()?p.path:c(o,p.name)})).sort((p,u)=>p.name.localeCompare(u.name)):[];return{path:o,directories:d}}function ed(e,t){const n=t.meshId||"",r={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,(a,o)=>r[o]||"")}function mm(e,t={}){const n=e==null?void 0:e.mcpConfig;if((n==null?void 0:n.mode)!=="manual")return null;const a=ed(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"}).trim();return!a.includes(`
|
|
70
|
-
`)&&!a.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:ed(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"})}}function Hj(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.instructions=="string"?t.instructions:"",r=typeof t.template=="string"?t.template:"";return!n&&!r?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:r}}function wr(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function hm(e){return Ba(e)||e.tabKey||e.routeId||null}function fm(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"",n=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"",r=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"",a=e.conversations.find(o=>{if(r&&o.routeId!==r)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)||r&&o.routeId===r)});if(a!=null&&a.tabKey)return a.tabKey;if(r){const o=fs(e.conversations,r)||e.conversations.find(i=>i.routeId===r);if(o!=null&&o.tabKey)return o.tabKey}return t||n||r||null}function _s(e){return String(e||"").trim()}function bm(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Pa(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Fj(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function Bj(e,t){const n=_s(e.providerSessionId),r=_s(e.targetSessionId),a=t.find(o=>{const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(_s).filter(Boolean);return!!(n&&i.includes(n)||r&&i.includes(r))});return a?a.tabKey:r||n||null}function Oj(e,t,n){if(t.event!=="agent:generating_completed")return null;const r=bm(t.daemonId);if(r&&r!==e.machineId)return null;const a=_s(t.providerType);if(e.providerType&&a!==e.providerType)return null;const o=_s(e.resumeSessionId),i=_s(e.launchedSessionId),c=_s(t.providerSessionId),d=_s(t.targetSessionId);if(o&&o!==c&&o!==d||i&&i!==c&&i!==d)return null;const p=Pa(e.workspacePath);if(p){const u=Pa(t.workspaceName);if(u&&!Fj(u,p))return null}return Bj(t,n)}function td(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Wj({ides:e,conversations:t,onOpenSession:n}){const[r,a]=l.useState(null),o=l.useRef(null),i=l.useCallback(()=>{o.current=null,a(null)},[]),c=l.useCallback(d=>{o.current=d,a(d)},[]);return l.useEffect(()=>{if(!r)return;const d=Pa(r.workspacePath),p=e.find(m=>{var v,w,b,j;if(!m||m.type==="adhdev-daemon"||bm(m.daemonId||m.id)!==r.machineId||(xr(m)?"cli":Nn(m)?"acp":"ide")!==r.kind)return!1;const k=String(m.agentType||m.type||"");if(r.providerType&&k!==r.providerType)return!1;if(r.resumeSessionId)return String(m.providerSessionId||"")===r.resumeSessionId;if(r.launchedSessionId){const C=String(r.launchedSessionId||"");return[m.providerSessionId,m.sessionId,m.instanceId,m.id].map(x=>String(x||"")).filter(Boolean).includes(C)}if(d){const C=Pa(m.workspace||m.runtimeWorkspaceLabel);return C?C===d:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((j=(b=(w=(v=m.activeChat)==null?void 0:v.messages)==null?void 0:w.at)==null?void 0:b.call(w,-1))==null?void 0:j.timestamp)||0)>=r.startedAt-5e3});if(!p)return;const u=fm({entrySessionId:p.sessionId,entryInstanceId:p.instanceId,entryRouteId:p.id,conversations:t});u&&(i(),n(u))},[i,t,e,n,r]),l.useEffect(()=>ht.onStatusEvent(d=>{const p=o.current;if(!p)return;const u=Oj(p,d,t);u&&(i(),n(u))}),[i,t,n]),l.useEffect(()=>{if(!r)return;const d=window.setTimeout(()=>{a(p=>!p||p.startedAt!==r.startedAt?p:(o.current=null,null))},45e3);return()=>window.clearTimeout(d)},[r]),{trackPendingLaunch:c}}function Uj(e,t){var r,a,o,i;const n={cliType:e};return(r=t==null?void 0:t.workspacePath)!=null&&r.trim()?n.dir=t.workspacePath.trim():t!=null&&t.workspaceId?n.workspaceId=t.workspaceId:t!=null&&t.useHome&&(n.useHome=!0),(a=t==null?void 0:t.resumeSessionId)!=null&&a.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 Gj({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:n,activeConv:r,ides:a,setCliViewModeOverrides:o}){const i=Xi(),{launchCli:c}=Ra(),d=l.useCallback(async(v,w)=>bl(e,v,w),[e]),p=l.useCallback(async(v,w)=>{if(!w.trim())return{ok:!1,error:"Choose a workspace path first."};try{const b=await e(v,"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]),u=l.useCallback(async(v,w,b)=>{var j;try{const C={ideType:w,enableCdp:!0};(j=b==null?void 0:b.workspacePath)!=null&&j.trim()&&(C.workspace=b.workspacePath.trim());const y=await e(v,"launch_ide",C);return!(y!=null&&y.success)&&(y==null?void 0:y.success)!==void 0?{ok:!1,error:(y==null?void 0:y.error)||"Could not launch IDE"}:(t({machineId:v,kind:"ide",providerType:w,workspacePath:(b==null?void 0:b.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(C){return{ok:!1,error:C instanceof Error?C.message:"Could not launch IDE"}}},[e,t]),m=l.useCallback(async(v,w,b,j)=>{const C=Date.now();try{const y=Uj(b,j),x=await c(v,y),N=(x==null?void 0:x.result)||x,S=(N==null?void 0:N.sessionId)||(N==null?void 0:N.id);return x!=null&&x.success&&S?(t({machineId:v,kind:w,providerType:b,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,launchedSessionId:S,startedAt:C}),{ok:!0}):x!=null&&x.success?(t({machineId:v,kind:w,providerType:b,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:(x==null?void 0:x.error)||(N==null?void 0:N.error)||`Could not launch ${w.toUpperCase()} session`,code:(x==null?void 0:x.code)||(N==null?void 0:N.code)||void 0}}catch(y){return td(y)?(t({machineId:v,kind:w,providerType:b,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:y instanceof Error?y.message:`Could not launch ${w.toUpperCase()} session`}}},[c,e,t]),f=l.useCallback(async v=>{var w;if(i!=null&&i.listMeshes)return i.listMeshes(v);if(!v)return[];try{const b=await e(v,"list_meshes",{}),j=(b==null?void 0:b.result)??b;if((j==null?void 0:j.success)===!1)throw new Error((j==null?void 0:j.error)||"Could not load meshes");return(Array.isArray(j==null?void 0:j.meshes)?j.meshes:Array.isArray((w=j==null?void 0:j.result)==null?void 0:w.meshes)?j.result.meshes:[]).map(y=>{var x;return{id:String((y==null?void 0:y.id)||""),name:String((y==null?void 0:y.name)||(y==null?void 0:y.id)||"Untitled mesh"),repoIdentity:(y==null?void 0:y.repoIdentity)||(y==null?void 0:y.repo_identity)||null,workspace:Array.isArray(y==null?void 0:y.nodes)&&y.nodes.length>0?String(((x=y.nodes[0])==null?void 0:x.workspace)||""):null,nodesCount:Array.isArray(y==null?void 0:y.nodes)?y.nodes.length:void 0,status:(y==null?void 0:y.status)||null}}).filter(y=>y.id)}catch(b){throw console.error("List meshes failed",b),b}},[i,e]),g=l.useCallback(async(v,w,b,j)=>{var y,x;if(!w.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(v,w,b,j);const C=Date.now();try{const N={meshId:w.trim()};b.trim()&&(N.cliType=b.trim());const S=(y=j==null?void 0:j.initialModel)==null?void 0:y.trim(),A=(x=j==null?void 0:j.initialThinkingLevel)==null?void 0:x.trim();S&&(N.initialModel=S),A&&(N.initialThinkingLevel=A);const T=await e(v,"launch_mesh_coordinator",N),I=(T==null?void 0:T.result)??T;if((I==null?void 0:I.success)===!1||(T==null?void 0:T.success)===!1){const P=String((I==null?void 0:I.code)||(T==null?void 0:T.code)||""),_=Hj((I==null?void 0:I.meshCoordinatorSetup)||(I==null?void 0:I.manualSetup)||(T==null?void 0:T.meshCoordinatorSetup)||(T==null?void 0:T.manualSetup));return{ok:!1,error:(I==null?void 0:I.error)||(T==null?void 0:T.error)||"Could not launch mesh coordinator",code:P||void 0,manualSetup:_}}const D=(I==null?void 0:I.sessionId)||(I==null?void 0:I.id);return D?n(D):t({machineId:v,kind:"cli",providerType:(I==null?void 0:I.cliType)||b.trim()||void 0,workspacePath:(I==null?void 0:I.workspace)||null,startedAt:C}),{ok:!0}}catch(N){return td(N)?(t({machineId:v,kind:"cli",providerType:b.trim()||void 0,startedAt:C}),{ok:!0}):{ok:!1,error:N instanceof Error?N.message:"Could not launch mesh coordinator"}}},[i,n,e,t]),k=l.useCallback(async(v,w)=>{if(!v||!w)return[];try{const b=await e(v,"list_saved_sessions",{providerType:w,kind:"cli",limit:30}),j=(b==null?void 0:b.result)??b;return Array.isArray(j==null?void 0:j.sessions)?j.sessions:[]}catch(b){return console.error("List saved sessions failed",b),[]}},[e]),h=l.useCallback(async v=>{await nm({conversation:r,mode:v,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[r,a,e,o]);return{handleBrowseMachineDirectory:d,handleSaveMachineWorkspace:p,handleLaunchMachineIde:u,handleLaunchMachineProvider:m,handleListMachineMeshes:f,handleLaunchMeshCoordinator:g,handleListMachineSavedSessions:k,setActiveCliViewMode:h}}function qj(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 zj(e,t,n=Date.now()){return!e||!qj(t)?null:{tabKey:e,nonce:n}}function Kj({isMobile:e,conversations:t,visibleConversations:n,groupActiveTabIds:r,focusedGroup:a,groupedConvs:o,setSearchParams:i}){const[c,d]=l.useState(null),[p,u]=l.useState(null),m=l.useMemo(()=>{var v,w;if(!e){if(c){const b=t.find(j=>j.tabKey===c);if(b)return b}return n[0]}const h=r[a];if(h){const b=t.find(j=>j.tabKey===h);if(b)return b}return((v=o[a])==null?void 0:v[0])||((w=o[0])==null?void 0:w[0])},[t,c,a,r,o,e,n]),f=l.useCallback(h=>{d(h)},[]),g=l.useCallback(h=>{d(h.tabKey),i(v=>{const w=new URLSearchParams(v),b=w0(h);return b?w.set("activeTab",b):w.delete("activeTab"),w},{replace:!0})},[i]),k=l.useCallback((h,v)=>{const w=zj(h,v);w&&u(w)},[]);return{activeConv:m,openDesktopConversation:g,requestScrollToBottom:k,scrollToBottomRequest:p,setDesktopActiveTab:f}}function Vj(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 Yj(e){const t=String(e.liveState.completionMarker||""),n=String(e.liveState.seenCompletionMarker||""),r=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,o=[e.tabKey,e.historySessionId||"",t,n,r,a?"1":"0"].join(":");return{shouldMarkSeen:!!(r==="task_complete"&&a&&(!t||t!==n)),autoReadKey:o,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function Jj({activeConv:e,isMobile:t,liveSessionInboxState:n,sendDaemonCommand:r}){const a=l.useRef(null),o=l.useRef(null),i=l.useRef(null),c=l.useRef(null),d=l.useRef(null);l.useEffect(()=>{const p=()=>{i.current&&(clearTimeout(i.current),i.current=null),c.current&&(clearTimeout(c.current),c.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),o.current=null};if(t){p(),a.current=null;return}if(!(e!=null&&e.sessionId)){p(),a.current=null;return}const u=Os(e,n),m=Yj({tabKey:e.tabKey,historySessionId:Ba(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:nn(e),liveState:u}),f=m.autoReadKey,g=Vj({autoReadKey:f,shouldMarkSeen:m.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!m.shouldMarkSeen){g.shouldCancelPending&&p(),a.current=f;return}if(!g.shouldSchedule)return;g.shouldCancelPending&&p();const k=()=>{if(document.visibilityState!=="visible"||a.current===f)return;a.current=f,o.current=null,i.current=null,c.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const v=m.readAt;r(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:v,completionMarker:m.completionMarker}).catch(()=>{})};if(o.current=g.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(k,1500);const v=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};d.current=v,document.addEventListener("visibilitychange",v);return}const h=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(k,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=h,document.addEventListener("visibilitychange",h)},[e,t,n,r]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current),c.current&&clearTimeout(c.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function jo(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 Qj({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:n,ides:r,sendDaemonCommand:a,updateRouteChats:o,setToasts:i,setClearedTabs:c,setSearchParams:d}){var O;const{launchCli:p}=Ra(),[u,m]=l.useState(!1),[f,g]=l.useState([]),[k,h]=l.useState(()=>Wt()),[v,w]=l.useState(!1),[b,j]=l.useState(null),C=l.useRef(null),y=l.useMemo(()=>n||t||e,[e,n,t]),x=!!y&&mt(y)&&!dt(y),N=l.useMemo(()=>{if(!y||!x)return null;const E=y.daemonId||y.routeId||"",M=Cs(y),$=jo(y);return`${E}:${M}:${y.providerSessionId||""}:${$}`},[y,x]),S=l.useMemo(()=>!y||!x?"":jo(y),[y,x]),{isCreatingChat:A,isRefreshingHistory:T,handleSwitchSession:I,handleNewChat:D,handleRefreshHistory:P}=cm({sendDaemonCommand:a,activeConv:y,chats:(O=r.find(E=>E.id===(y==null?void 0:y.routeId)))==null?void 0:O.chats,updateRouteChats:o,setToasts:i,setClearedTabs:c}),_=l.useCallback(()=>{m(!0)},[]),G=l.useCallback(()=>{m(!1)},[]),H=l.useCallback(async()=>{if(!(!y||!x||v)){w(!0);try{const E=y.daemonId||y.routeId,M=Cs(y),$=jo(y),R=await a(E,"list_saved_sessions",{agentType:M,providerType:M,kind:"cli",limit:50,...y.providerSessionId?{providerSessionId:y.providerSessionId}:{},...$?{workspace:$}:{}}),z=(R==null?void 0:R.result)??R;g(Array.isArray(z==null?void 0:z.sessions)?z.sessions:[])}catch(E){console.error("Refresh saved sessions failed",E),g([])}finally{w(!1)}}},[y,v,x,a]);l.useEffect(()=>{if(!u){C.current=null;return}if(!x){C.current=null,g([]),w(!1);return}!N||v||C.current!==N&&(C.current=N,H())},[H,u,v,x,N]);const L=l.useCallback(async E=>{if(!y||!x||!E.providerSessionId||!E.workspace)return;const M=y.daemonId||y.routeId,$=Cs(y);try{j(E.providerSessionId);const R=await p(M,{cliType:$,dir:E.workspace,resumeSessionId:E.providerSessionId,initialModel:Wu(E.summaryMetadata,"model",{preferShortValue:!0})||void 0}),z=(R==null?void 0:R.result)??R,Q=typeof(z==null?void 0:z.sessionId)=="string"?z.sessionId:typeof(z==null?void 0:z.id)=="string"?z.id:"";Q&&d(ne=>{const J=new URLSearchParams(ne);return J.set("activeTab",Q),J},{replace:!0}),G()}catch(R){console.error("Resume saved session failed",R)}finally{j(null)}},[G,y,x,a,d]);return{historyModalOpen:u,openHistoryModal:_,closeHistoryModal:G,historyTargetConv:y,isSavedSessionHistoryTarget:x,isHistoryCreatingChat:A,isHistoryRefreshingHistory:T,handleHistorySwitchSession:I,handleHistoryNewChat:D,handleHistoryRefresh:P,savedHistorySessions:f,savedHistoryFilters:k,setSavedHistoryFilters:h,missingWorkspaceResumePath:S,isSavedHistoryLoading:v,resumingSavedHistorySessionId:b,handleRefreshSavedHistory:H,handleResumeSavedHistorySession:L}}function Xj({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}){const[d,p]=l.useState(null),[u,m]=l.useState(null),f=l.useMemo(()=>{if(e||!r)return null;const w=c(r);return w&&!mt(w)&&!dt(w)?w:null},[e,r,c]),g=l.useMemo(()=>{const w=d==null?void 0:d.routeId;if(!w)return null;const b=d!=null&&d.tabKey?o.find(j=>j.tabKey===d.tabKey):a?o.find(j=>j.tabKey===a):null;return(b==null?void 0:b.routeId)===w?b:fs(o,w)},[o,d,a]),k=l.useMemo(()=>{if(g)return i.find(w=>w.id===g.routeId)},[i,g]);l.useEffect(()=>{f&&(p({routeId:f.routeId,tabKey:fc(f)}),m(f),n({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,n,f]);const h=l.useCallback(w=>{w&&(p({routeId:w.routeId,tabKey:fc(w)}),m(w))},[]),v=l.useCallback(()=>{p(null),m(null)},[]);return{remoteDialogConv:g,remoteDialogIdeEntry:k,remoteDialogActiveConv:u,setRemoteDialogActiveConv:m,openRemoteDialog:h,closeRemoteDialog:v}}function Zj({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c,activeConv:d,sendDaemonCommand:p}){const{remoteDialogConv:u,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:g,openRemoteDialog:k,closeRemoteDialog:h}=Xj({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}),[v,w]=l.useState(!1),[b,j]=l.useState(null),C=l.useCallback(async N=>{const S=N||d;!S||!mt(S)&&!dt(S)||(j(S),w(!0))},[d]),y=l.useCallback(()=>{w(!1),j(null)},[]),x=l.useCallback(async N=>{const S=b||d;if(!S||!mt(S)&&!dt(S)){y();return}w(!1);try{const A=Cs(S),T=S.routeId||S.daemonId||"";await p(T,"stop_cli",{cliType:A,targetSessionId:S.sessionId,mode:N,...Ua(S)})}catch(A){console.error("Stop CLI failed:",A)}finally{j(null)}},[d,y,b,p]);return{remoteDialogConv:u,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:g,openRemoteDialog:k,closeRemoteDialog:h,cliStopDialogOpen:v,cliStopTargetConv:b,requestCliStop:C,cancelCliStop:y,confirmCliStop:x}}function No(e,t=!0){return(e??!0)&&t}const gl=l.memo(function({activeConv:t,clearToken:n,isCliTerminal:r,ideEntry:a,terminalRef:o,handleModalButton:i,handleRelaunch:c,handleSendChat:d,handleForceSendChat:p,isSendingChat:u,sendFeedbackMessage:m=null,handleFocusAgent:f,isFocusingAgent:g,actionLogs:k,userName:h,scrollToBottomRequestNonce:v,isInputActive:w=!0,isVisible:b=!0}){const j=r,C=!r,y=No(b,j),x=No(b,C),N=No(b),S=em(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(Lu,{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(on,{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":!r,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:j?"visible":"hidden",pointerEvents:j?"auto":"none"},children:s.jsx(sS,{activeConv:A,clearToken:n,terminalRef:o,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:m,isVisible:y,isInputActive:w&&y})}),s.jsx("div",{"aria-hidden":r,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:C?"visible":"hidden",pointerEvents:C?"auto":"none"},children:s.jsx(xi,{activeConv:A,ideEntry:a,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:k,userName:h,scrollToBottomRequestNonce:v,isInputActive:w&&x,isVisible:x})})]}):s.jsx(xi,{activeConv:A,ideEntry:a,handleSendChat:d,handleForceSendChat:p,isSendingChat:u,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:k,userName:h,scrollToBottomRequestNonce:v,isInputActive:w&&N,isVisible:N})]})},(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 e1({conversation:e,className:t="",onOpenNativeConversation:n,onOpenMachine:r,interactive:a=!0,meshOnly:o=!1}){var C,y,x;const{t:i}=Ce("common"),c=Cr(),d=Ds(e),p=o?null:sp(e),u=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),m=!o&&e.streamSource==="agent-stream"&&!!e.agentName,f=!o&&!m&&(e.transport==="pty"||e.transport==="acp"),g=Dn(e),k=y0(e),h=(C=e.settings)==null?void 0:C.meshNodeFor,v=e.meshQueueStats,w=((y=e.coordinator)==null?void 0:y.meshId)||((x=e.settings)==null?void 0:x.meshCoordinatorFor),b=l.useCallback(()=>{if(r){r();return}d&&c("/dashboard",{state:{openMachineId:d}})},[d,c,r]),j=l.useCallback(()=>{if(n){n();return}const N=hm(e);N&&c(wr(N))},[e,c,n]);return!u&&!m&&!f&&!p&&!h&&!v?null:s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[u&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:j,title:k,children:[s.jsx(gs,{size:12}),s.jsx("span",{children:k})]}):s.jsxs("span",{className:"conversation-meta-chip",title:k,children:[s.jsx(gs,{size:12}),s.jsx("span",{children:k})]})),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(br,{size:12}),s.jsx("span",{children:g})]}),f&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(br,{size:12}),s.jsx("span",{children:g})]}),p&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:b,title:p,children:[s.jsx(Fs,{size:12}),s.jsx("span",{children:p})]}):s.jsxs("span",{className:"conversation-meta-chip",title:p,children:[s.jsx(Fs,{size:12}),s.jsx("span",{children:p})]})),h&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(Fs,{size:12}),s.jsx("span",{children:i("dashboard.metaChips.meshNode")})]}),w&&v&&s.jsxs("span",{className:`conversation-meta-chip ${v.pending>0?"is-active":""}`,style:v.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${v.pending} pending, ${v.assigned} assigned, ${v.completed} completed, ${v.failed} failed`,children:[s.jsx(Yf,{size:12}),s.jsxs("span",{children:[v.pending," Pending"]})]})]})}function t1({selectedConversation:e,isAcp:t,isStandalone:n,selectedIdeEntry:r,actionLogs:a,userName:o,isSendingChat:i,sendFeedbackMessage:c=null,isFocusingAgent:d,onBack:p,onOpenNativeConversation:u,onOpenMachine:m,onOpenHistory:f,onOpenRemote:g,onOpenMeshGraph:k,onStopCli:h,cliViewMode:v,onSetCliViewMode:w,handleSendChat:b,handleForceSendChat:j,handleFocusAgent:C,handleModalButton:y,handleRelaunch:x}){var D,P;const N=l.useRef(null),S=mt(e)&&!t,A=S&&v==="terminal",T=!!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(Fi,{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:yt(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(e1,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>m(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[S&&v&&s.jsx(Lp,{mode:v,onChange:w,compact:!0}),S&&h&&s.jsx("button",{onClick:()=>{h(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(Tt,{size:14})}),T&&k&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>k(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(rs,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",children:s.jsx(Oi,{size:14})}),!t&&!S&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",children:s.jsx(gs,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(gl,{activeConv:e,clearToken:0,isCliTerminal:A,ideEntry:r,terminalRef:N,handleModalButton:y,handleRelaunch:x,handleSendChat:b,handleForceSendChat:j,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:C,isFocusingAgent:d,actionLogs:a,userName:o})})]})}const Ao={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 s1(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function gm(){const[e,t]=l.useState("unix"),[n,r]=l.useState("powershell"),[a,o]=l.useState(!1),i=e==="unix"?"unix":n;l.useEffect(()=>{t(s1())},[]);const c=l.useCallback(()=>{navigator.clipboard.writeText(Ao[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:()=>r("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:()=>r("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:Ao[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:Ao[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:a?"✓":"📋"})]}),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 xm({section:e,onSectionChange:t}){const n=[{key:"machines",label:"Machines",icon:gs},{key:"chats",label:"Chats",icon:un}];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:r,label:a,icon:o})=>{const i=e===r;return s.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${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(r),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:a})]},r)})})})}function Gr({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 bn({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 Xn({icon:e,title:t,subtitle:n,children:r}){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}),r]})}function n1({conversation:e,onCancel:t,onConfirm:n}){const{t:r}=Ce(),a=yt(e);return 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:r("mobileInbox.hideTitle",{title:a})}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:r("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:r("mobileInbox.hide")}),s.jsx("button",{onClick:t,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:r("common.cancel")})]})]})]})}function qr({item:e,type:t,getAvatarText:n,onOpenConversation:r,onRequestHideConversation:a,onRequestStopCli:o,onOpenMeshGraph:i,onCollectChatDebugBundle:c,isMuted:d,onToggleMute:p}){const{t:u}=Ce(),m=t==="needs_attention"||t==="task_complete",f=t==="working",g=t==="earlier",k=t==="task_complete",{isReconnecting:h,isConnecting:v}=pn(e.conversation),w=yt(e.conversation),b=In(e.conversation),j=Mp(e.conversation,{requiresAction:t==="needs_attention"}),C=m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":f?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":g?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",y=m?"bg-accent-primary shadow-glow":f?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":g?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",x=g?"text-text-secondary":"text-text-primary",N=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",T=!f&&!k,I=Ap(e.conversation),D="text-[color:var(--status-warning)]",P=_=>{if(!c)return;_.preventDefault(),_.stopPropagation();const G=c==null?void 0:c(e.conversation);Promise.resolve(G).catch(H=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",H)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${C}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[m||f?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${y}`,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:_=>{_.preventDefault(),_.stopPropagation(),i(e.conversation)},"aria-label":u("mobileInbox.openMeshGraphFor",{title:w}),title:u("mobileInbox.openLiveMeshGraph"),children:s.jsx(rs,{size:13})})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>r(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 ${x}`,children:w})}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${N}`,children:[s.jsx("span",{className:"truncate",children:b}),s.jsx(ka,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),h?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${D} animate-pulse`,children:u("mobileInbox.reconnectingItem")})]}):v?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:u("mobileInbox.connectingItem")})]}):j==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:D,children:u("mobileInbox.actionNeeded")})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${S}`,children:e.preview})]}),s.jsxs("div",{className:"mobile-inbox-corner-actions absolute top-3 right-3 flex items-center gap-1.5",children:[T&&s.jsx("span",{className:`mr-0.5 text-[11px] font-medium shrink-0 ${A}`,children:Du(e.timestamp)}),k&&s.jsx("span",{className:"rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:u("mobileInbox.done")}),p&&s.jsx("button",{type:"button",className:`mobile-inbox-mute-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border transition-colors ${d?"border-amber-500/60 bg-amber-500 text-white hover:bg-amber-600":"border-border-subtle bg-bg-primary/70 text-text-muted hover:border-border-default hover:text-text-primary"}`,onClick:_=>{_.preventDefault(),_.stopPropagation(),p()},"aria-label":d?u("mobileInbox.unmute",{title:w}):u("mobileInbox.mute",{title:w}),title:u(d?"mobileInbox.mutedTitle":"mobileInbox.muteNotifications"),children:d?s.jsx(vu,{size:13}):s.jsx(Hn,{size:13})}),a&&s.jsx("button",{type:"button",className:"mobile-inbox-hide-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:_=>{_.preventDefault(),_.stopPropagation(),a()},"aria-label":u("mobileInbox.hideConversationAria",{title:w}),title:u("mobileInbox.hideConversationTitle"),children:s.jsx(Wi,{size:13})}),o&&s.jsx("button",{type:"button",className:"mobile-inbox-stop-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-status-error/30 bg-bg-primary/70 text-status-error transition-colors hover:border-status-error/60 hover:bg-status-error/10",onClick:_=>{_.preventDefault(),_.stopPropagation(),o()},"aria-label":u("mobileInbox.stopSessionAria",{title:w}),title:u("mobileInbox.stopSessionTitle"),children:s.jsx(Tt,{size:13})})]})]})},e.conversation.tabKey)}function sd({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 nd({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 r1({section:e,attentionItems:t,unreadItems:n,workingItems:r,completedItems:a,hiddenConversations:o,machineCards:i,getAvatarText:c,actionLogs:d,sendDaemonCommand:p,onOpenConversation:u,onShowAllHidden:m,onHideConversation:f,onOpenMeshGraph:g,onStopCli:k,onOpenNewSession:h,onOpenMachine:v,onOpenSettings:w,onSectionChange:b,wsStatus:j="connected",isStandalone:C=!1,onCollectChatDebugBundle:y,isConversationMuted:x,onToggleMuteConversation:N}){const{t:S}=Ce(),[A,T]=l.useState(null),I=j==="disconnected"||j==="reconnecting"||j==="offline"||j==="auth_failed",D=i.length>0,P=t.length>0||n.length>0||r.length>0||a.length>0,_=S(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),G=C?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",H=C?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",L=l.useCallback(async M=>{const $=Zs(M);if(!$)return;const R=Array.isArray(M.messages)?M.messages:[],z=cp({activeConv:M,visibleMessages:R,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:R.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),Q=await p($,"get_chat_debug_bundle",{...Xs(M),delivery:"daemon_file",frontendSnapshot:z}),ne=dr(Q),J=pp(ne),Z=await up(J);Z==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),ht.showToast(dp(ne,{locatorCopyStatus:Z}),Z==="failed"?"warning":"success")},[d,p]),O=y||L,E=l.useCallback(()=>{A&&(f==null||f(A),T(null))},[A,f]);return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${G}`,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:_}),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(Hn,{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(Ea,{size:18})})]})]})}),s.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${H}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:I?s.jsx(Xn,{icon:s.jsx(sd,{}),title:S(j==="offline"?"mobileInbox.networkOffline":j==="auth_failed"?"mobileInbox.sessionExpired":"mobileInbox.reconnecting"),subtitle:S(j==="offline"?"mobileInbox.waitingForNetwork":j==="auth_failed"?"mobileInbox.pleaseLogInAgain":"mobileInbox.restoringConnection")}):i.length===0?s.jsx(Xn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:S(C?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:S(C?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!C&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(gm,{})})}):s.jsx(bn,{children:i.map((M,$)=>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] ${$>0?"border-t border-border-subtle/70":""}`,onClick:()=>v(M.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(M.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:M.label}),s.jsxs("span",{className:"flex items-center gap-2 text-[11px] font-medium text-text-muted shrink-0",children:[s.jsx(nd,{count:M.generatingCount,label:S("mobileInbox.generatingCount",{count:M.generatingCount})}),M.unread>0?s.jsx("span",{className:"text-accent-primary",children:S("mobileInbox.newCount",{count:M.unread})}):M.total>0?S("mobileInbox.chatCount",{count:M.total}):S("mobileInbox.idle")]})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:M.subtitle}),M.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[S("mobileInbox.chatCount",{count:M.total}),M.unread>0?S("mobileInbox.unreadSuffix",{count:M.unread}):"",M.generatingCount>0?S("mobileInbox.collapsedGeneratingSuffix",{count:M.generatingCount}):""]}):M.generatingCount>0?s.jsx("div",{className:"text-[13px] text-accent-primary mt-0.5 font-medium",children:S("mobileInbox.generatingCount",{count:M.generatingCount})}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:S("mobileInbox.noActiveChats")})]})]},M.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(Gr,{title:S("mobileInbox.needsAttention"),className:"mb-0"}),s.jsx(bn,{children:t.map((M,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(qr,{item:M,type:"needs_attention",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>T(M.conversation):void 0,onRequestStopCli:k?()=>k(M.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:O,isMuted:x==null?void 0:x(M.conversation),onToggleMute:N?()=>N(M.conversation):void 0})},M.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(Gr,{title:S("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),s.jsx(bn,{children:n.map((M,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(qr,{item:M,type:"task_complete",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>T(M.conversation):void 0,onRequestStopCli:k?()=>k(M.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:O,isMuted:x==null?void 0:x(M.conversation),onToggleMute:N?()=>N(M.conversation):void 0})},M.conversation.tabKey))})]}),e==="chats"&&r.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(Gr,{title:S("mobileInbox.workingNow"),className:"mb-0 mt-2"}),s.jsx(bn,{children:r.map((M,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(qr,{item:M,type:"working",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>T(M.conversation):void 0,onRequestStopCli:k?()=>k(M.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:O,isMuted:x==null?void 0:x(M.conversation),onToggleMute:N?()=>N(M.conversation):void 0})},M.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&s.jsx(Gr,{title:S("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(bn,{children:a.map((M,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(qr,{item:M,type:"earlier",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>T(M.conversation):void 0,onRequestStopCli:k?()=>k(M.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:O,isMuted:x==null?void 0:x(M.conversation),onToggleMute:N?()=>N(M.conversation):void 0})},M.conversation.tabKey))}):P?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:S("mobileInbox.allCaughtUp")}):I?s.jsx(Xn,{icon:s.jsx(sd,{size:28}),title:S("mobileInbox.connecting"),subtitle:S("mobileInbox.connectingSubtitle")}):D?s.jsx(Xn,{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(un,{size:20})}),title:S("mobileInbox.noConversations"),subtitle:S("paneGroup.newSessionDescription"),children:h&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:h,"aria-label":S("paneGroup.newSession"),title:S("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:S("paneGroup.newSession")})]})}):s.jsx(Xn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:S("mobileInbox.noMachinesConnected"),subtitle:S("mobileInbox.noMachinesSubtitle")})]}),e==="chats"&&o.length>0&&(()=>{const M=Kb(o);return s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(bn,{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:S("mobileInbox.hiddenTabs")}),s.jsx(nd,{count:M,label:S("mobileInbox.generatingCount",{count:M})})]}),s.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[S("mobileInbox.collapsedCount",{count:o.length}),M>0?S("mobileInbox.collapsedGeneratingSuffix",{count:M}):""]})]}),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:S("mobileInbox.restoreAll")})]})})})})()]}),e==="chats"&&h&&P&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:h,"aria-label":S("paneGroup.newSession"),title:S("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"})]})}),A&&s.jsx(n1,{conversation:A,onCancel:()=>T(null),onConfirm:E}),s.jsx(xm,{section:e,onSectionChange:b})]})}function a1(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 vm(e){const t=[e.workspace||"Workspace unknown"],n=ln(e.summaryMetadata);n&&t.push(n),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const r=a1(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:r?`Updated ${r}`:"",preview:(e.preview||"").trim()}}function xl({title:e,description:t,currentPath:n,directories:r,busy:a=!1,error:o="",confirmLabel:i="Use this folder",onClose:c,onNavigate:d,onConfirm:p}){const[u,m]=l.useState(n),{t:f}=Ce("common");l.useEffect(()=>{m(n)},[n]);const g=_j(n),k=u.trim();return 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(Tt,{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||a||d(g)},disabled:!g||a,children:[s.jsx(Fi,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:f("machine.workspaceBrowse.currentFolder")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:u,onChange:h=>m(h.target.value),onKeyDown:h=>{h.key!=="Enter"||!k||a||(h.preventDefault(),d(k))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!k||a||d(k)},disabled:!k||a,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?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}):r.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:r.map(h=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>d(h.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Pn,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:h.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:h.path})]})]},h.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:c,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>p(k||n),disabled:!k&&!n||a,children:i})]})]})})}function vl({title:e,description:t,details:n,workspaceOptions:r,selectedWorkspaceKey:a,onWorkspaceChange:o,confirmLabel:i,busyLabel:c,busy:d=!1,showArgsInput:p,argsValue:u,onArgsChange:m,showModelInput:f,modelValue:g,onModelChange:k,historyProviderNode:h,onConfirm:v,onCancel:w}){const{t:b}=Ce("common"),j=i??b("machine.launchConfirm.launch"),C=c??b("machine.launchConfirm.launching"),y=r==null?void 0:r.find(x=>x.key===a);return 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(Tt,{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:[r&&r.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:a||"",onChange:x=>o(x.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:d,children:r.map(x=>s.jsx("option",{value:x.key,children:x.label},x.key))}),(y==null?void 0:y.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:y.description})]}),h,n.map(x=>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:x.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:x.value})]},`${x.label}:${x.value}`)),f&&k&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.languageModel")}),s.jsx("input",{type:"text",value:g||"",onChange:x=>k(x.target.value),placeholder:b("machine.launchConfirm.autoDetect"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]}),p&&m&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.cliArgs")}),s.jsx("input",{type:"text",value:u||"",onChange:x=>m(x.target.value),placeholder:b("machine.launchConfirm.cliArgsPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:w,disabled:d,children:b("machine.launchConfirm.cancel")}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:v,disabled:d,children:[s.jsx(xu,{size:14}),d?C:j]})]})]})})}function rd(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function ym(e){const{machine:t,currentWorkspacePath:n,currentWorkspaceId:r,includeHome:a=!0,homeLabel:o="Home directory",homeDescription:i="Launch without a workspace"}=e,c=[];a&&c.push({key:"__home__",label:o,description:i,workspaceId:null,workspacePath:null});for(const u of t.workspaces||[])c.push({key:`saved:${u.id}`,label:`${u.id===t.defaultWorkspaceId?"⭐ ":""}${rd(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const d=(n==null?void 0:n.trim())||"",p=d?(t.workspaces||[]).find(u=>u.path===d):null;if(d&&!p&&c.push({key:`custom:${d}`,label:rd(d),description:d,workspaceId:null,workspacePath:d}),r){const u=`saved:${r}`;if(c.some(m=>m.key===u))return{options:c,selectedKey:u}}return p?{options:c,selectedKey:`saved:${p.id}`}:d?{options:c,selectedKey:`custom:${d}`}:{options:c,selectedKey:"__home__"}}function o1(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function i1(e){return[o1(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function l1(e){return e.lastLaunchedAt?$a(e.lastLaunchedAt):""}function wm(e){return{metaText:i1(e),updatedLabel:l1(e)}}function To(e,t,n){return e?"ide":t>0?"cli":n>0?"acp":null}function c1({selectedMachineEntry:e,cliProviders:t,acpProviders:n,machineAction:r,onBrowseDirectory:a,onListSavedSessions:o}){var he,Ee,Be,at;const i=Bn(),[c,d]=l.useState(!1),p=(((he=e.detectedIdes)==null?void 0:he.length)||0)>0,u=l.useMemo(()=>(e.workspaces||[]).map(oe=>({id:oe.id,path:oe.path,label:oe.label})),[e]),m=e.defaultWorkspaceId||null,[f,g]=l.useState(m||((Ee=u[0])==null?void 0:Ee.id)||""),[k,h]=l.useState(""),[v,w]=l.useState(""),[b,j]=l.useState([]),[C,y]=l.useState(!1),[x,N]=l.useState(""),[S,A]=l.useState(!1),[T,I]=l.useState(To(p,t.length,n.length)),D=l.useRef(null),[P,_]=l.useState(null),G=l.useRef("__home__"),[H,L]=l.useState("__home__"),[O,E]=l.useState(""),[M,$]=l.useState(""),[R,z]=l.useState(""),[Q,ne]=l.useState([]),[J,Z]=l.useState(()=>Wt().textQuery),[de,te]=l.useState(()=>Wt().workspaceQuery),[B,ie]=l.useState(()=>Wt().modelQuery),[Y,le]=l.useState(()=>Wt().resumableOnly),[Ne,we]=l.useState(()=>Wt().sortMode),[Se,me]=l.useState(!1),[q,W]=l.useState(!1),X=l.useRef(null),K=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const ue=f==="__custom__"?k.trim():((Be=u.find(oe=>oe.id===f))==null?void 0:Be.path)||"",Pe=f==="__custom__"&&!!ue&&r.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(r.message),ce=f!=="__custom__"&&((at=u.find(oe=>oe.id===f))==null?void 0:at.path)||"",F=l.useMemo(()=>(e.recentLaunches||[]).map(oe=>oe.workspace),[e]),pe=l.useCallback(async oe=>{y(!0),N("");try{const He=await a(oe);w(He.path),h(He.path),j(He.directories)}catch(He){N(He instanceof Error?He.message:"Could not load folder")}finally{y(!1)}},[a]),xe=l.useCallback(()=>{var He;g("__custom__"),A(!0);const oe=fl(e.platform,hl(k.trim(),ce,F,e.defaultWorkspacePath,(He=u.find(lt=>lt.id===m))==null?void 0:He.path,u.map(lt=>lt.path)));pe(oe)},[k,m,pe,F,ce,e.platform,u]),U=l.useCallback(oe=>{if(oe!=null&&oe.workspaceId){g(oe.workspaceId),h("");return}if(oe!=null&&oe.workspacePath){g("__custom__"),h(oe.workspacePath);return}g(""),h("")},[]),be=l.useCallback(oe=>{if(g(oe),oe==="__custom__"){xe();return}h("")},[xe]),je=l.useCallback(oe=>{g("__custom__"),h(oe)},[]),ge=l.useCallback((oe,He)=>{D.current=He,G.current=oe.selectedWorkspaceKey||"__home__",L(oe.selectedWorkspaceKey||"__home__"),E(oe.initialArgs||""),$(oe.initialModel||""),z(""),ne([]);const lt=oe.providerType?`${e.id}:${oe.providerType}`:null;if(pS(K.current,lt)){const ut=Wt();Z(ut.textQuery),te(ut.workspaceQuery),ie(ut.modelQuery),le(ut.resumableOnly),we(ut.sortMode)}K.current=lt,_(oe),oe.providerType&&o&&(me(!0),o(oe.providerType).then(ut=>ne(ut||[])).catch(ut=>console.warn("Failed to load saved sessions",ut)).finally(()=>me(!1)))},[o,e.id]),Ie=l.useMemo(()=>Rp(Q,{textQuery:J,workspaceQuery:de,modelQuery:B,resumableOnly:Y,sortMode:Ne}),[B,Y,Q,Ne,J,de]);l.useEffect(()=>{R&&(Ie.some(oe=>oe.providerSessionId===R)||z(""))},[Ie,R]);const et=l.useCallback(()=>{D.current&&(W(!0),D.current().finally(()=>{D.current=null,W(!1),_(null)}))},[]),Ze=l.useCallback(()=>{D.current=null,_(null)},[]),rt=l.useCallback(oe=>{G.current=oe,L(oe)},[]);return l.useEffect(()=>{var oe;X.current!==e.id&&(X.current=e.id,g(m||((oe=u[0])==null?void 0:oe.id)||"__custom__"),h(""),w(""),j([]),N(""),A(!1),Z(Wt().textQuery),te(Wt().workspaceQuery),ie(Wt().modelQuery),le(Wt().resumableOnly),we(Wt().sortMode),K.current=null,I(To(p,t.length,n.length)))},[n.length,t.length,m,p,e.id,u]),l.useEffect(()=>{var oe;f!=="__custom__"&&(f&&u.some(He=>He.id===f)||g(m||((oe=u[0])==null?void 0:oe.id)||"__custom__"))},[m,f,u]),l.useEffect(()=>{T==="ide"&&p||T==="cli"&&t.length>0||T==="acp"&&n.length>0||I(To(p,t.length,n.length))},[T,n.length,t.length,p]),{showAllRecent:c,setShowAllRecent:d,hasIdeOptions:p,workspaceRows:u,defaultWorkspaceId:m,workspaceChoice:f,customWorkspacePath:k,browseCurrentPath:v,browseDirectories:b,browseBusy:C,browseError:x,browseDialogOpen:S,activeLauncherKind:T,launchConfirm:P,launchConfirmWorkspaceKeyRef:G,launchConfirmWorkspaceKey:H,launchConfirmArgs:O,launchConfirmModel:M,launchConfirmResumeId:R,launchConfirmSavedSessions:Q,launchConfirmTextFilter:J,launchConfirmWorkspaceFilter:de,launchConfirmModelFilter:B,launchConfirmResumableOnly:Y,launchConfirmSortMode:Ne,filteredLaunchConfirmSavedSessions:Ie,launchConfirmSessionsLoading:Se,launchConfirmBusy:q,resolvedWorkspacePath:ue,canCreateMissingWorkspace:Pe,openBrowseDialog:xe,loadBrowsePath:pe,handleWorkspaceChoiceChange:be,chooseCustomWorkspacePath:je,setCustomWorkspacePath:h,setBrowseDialogOpen:A,setActiveLauncherKind:I,openLaunchConfirm:ge,handleConfirmLaunch:et,closeLaunchConfirm:Ze,setWorkspaceSelectionFromOption:U,setLaunchConfirmWorkspaceKeyAndSync:rt,setLaunchConfirmArgs:E,setLaunchConfirmModel:$,setLaunchConfirmResumeId:z,setLaunchConfirmTextFilter:Z,setLaunchConfirmWorkspaceFilter:te,setLaunchConfirmModelFilter:ie,setLaunchConfirmResumableOnly:le,setLaunchConfirmSortMode:we}}function d1({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:n,cliProviders:r,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:i,machineAction:c,isStandalone:d,section:p,showBottomNav:u,onBack:m,onSectionChange:f,onOpenConversation:g,onOpenRecent:k,onOpenMachineDetails:h,onMachineUpgrade:v,onLaunchDetectedIde:w,onAddWorkspace:b,onBrowseDirectory:j,onLaunchWorkspaceProvider:C,onListSavedSessions:y}){const{t:x}=Ce("common"),N=L=>L==="ide"?"IDE":L==="cli"?"CLI":"ACP",S=n.slice(0,4),A=t.slice(0,3),T=c1({selectedMachineEntry:e,cliProviders:r,acpProviders:a,machineAction:c,onBrowseDirectory:j,onListSavedSessions:y}),I=l.useMemo(()=>S.map(L=>{const{metaText:O,updatedLabel:E}=wm(L);return{key:`recent-launch:${L.id}`,primary:L.label,secondary:O,updatedLabel:E,onClick:()=>{const{options:M,selectedKey:$}=ym({machine:{workspaces:T.workspaceRows,defaultWorkspaceId:T.defaultWorkspaceId},currentWorkspacePath:L.workspace,homeLabel:x("newSession.homeDirectory"),homeDescription:x("newSession.launchWithoutWorkspace")});T.openLaunchConfirm({title:L.kind==="ide"?Sa(x,"restart-ide",L.label):L.providerSessionId?_p(x,L.label):Sa(x,"start-fresh",L.label),description:L.kind==="ide"?Ca(x,"restart-ide"):L.providerSessionId?$p(x):Ca(x,"start-fresh"),confirmLabel:L.kind==="ide"?ja(x,"restart-ide"):L.providerSessionId?vi(x,!0):ja(x,"start-fresh"),busyLabel:L.kind==="ide"?Na(x,"restart-ide"):L.providerSessionId?Ep(x,!0):Na(x,"start-fresh"),workspaceOptions:M,selectedWorkspaceKey:$,details:[{label:"Mode",value:N(L.kind)},...L.providerType?[{label:"Provider",value:L.providerType}]:[]]},async()=>{const R=M.find(z=>z.key===T.launchConfirmWorkspaceKeyRef.current);T.setWorkspaceSelectionFromOption(R),await k({...L,workspace:(R==null?void 0:R.workspacePath)??null})})}}}),[T,k,S,x]),D=l.useMemo(()=>A.map(L=>({key:`recent-chat:${L.conversation.tabKey}`,primary:yt(L.conversation),secondary:Fk(L.conversation,{timestampLabel:L.timestamp?Du(L.timestamp):null}),unread:L.unread,onClick:()=>g(L.conversation)})),[g,A]),P=T.showAllRecent?I:I.slice(0,4),_=I.length>0,G=D.length>0,H=d?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${H} 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(Fi,{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:[G&&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(L=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${L.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:L.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:L.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:L.secondary})]},L.key))})]}),_&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:P.map(L=>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:L.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:L.primary}),L.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:L.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:L.secondary})]},L.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:()=>T.setShowAllRecent(L=>!L),children:T.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:v,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",i]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:h,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),T.browseDialogOpen&&s.jsx(xl,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:T.browseCurrentPath,directories:T.browseDirectories,busy:T.browseBusy,error:T.browseError,confirmLabel:"Use this folder",onClose:()=>T.setBrowseDialogOpen(!1),onNavigate:L=>{T.loadBrowsePath(L)},onConfirm:L=>{T.chooseCustomWorkspacePath(L),T.setBrowseDialogOpen(!1)}}),T.launchConfirm&&s.jsx(vl,{title:T.launchConfirm.title,description:T.launchConfirm.description,details:T.launchConfirm.details,workspaceOptions:T.launchConfirm.workspaceOptions,selectedWorkspaceKey:T.launchConfirmWorkspaceKey,onWorkspaceChange:T.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:T.launchConfirm.providerType?vi(x,!!T.launchConfirmResumeId):T.launchConfirm.confirmLabel,busyLabel:T.launchConfirm.providerType?void 0:T.launchConfirm.busyLabel,busy:T.launchConfirmBusy,showArgsInput:T.launchConfirm.showArgsInput,argsValue:T.launchConfirmArgs,onArgsChange:T.setLaunchConfirmArgs,showModelInput:T.launchConfirm.showModelInput,modelValue:T.launchConfirmModel,onModelChange:T.setLaunchConfirmModel,historyProviderNode:T.launchConfirm.providerType&&(T.launchConfirmSessionsLoading||T.launchConfirmSavedSessions.length>0)&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),T.launchConfirmSessionsLoading&&s.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:ol(x)}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:T.launchConfirmTextFilter,onChange:L=>T.setLaunchConfirmTextFilter(L.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:T.launchConfirmWorkspaceFilter,onChange:L=>T.setLaunchConfirmWorkspaceFilter(L.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:T.launchConfirmModelFilter,onChange:L=>T.setLaunchConfirmModelFilter(L.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsxs("select",{value:T.launchConfirmSortMode,onChange:L=>T.setLaunchConfirmSortMode(L.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:T.launchConfirmResumableOnly,onChange:L=>T.setLaunchConfirmResumableOnly(L.target.checked),disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:T.launchConfirmResumeId,onChange:L=>T.setLaunchConfirmResumeId(L.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:fS(x)}),T.filteredLaunchConfirmSavedSessions.map(L=>s.jsxs("option",{value:L.providerSessionId,disabled:!L.canResume,children:[L.title||L.providerSessionId," ",L.canResume?"":"(workspace missing)"]},L.providerSessionId))]}),!T.launchConfirmSessionsLoading&&T.launchConfirmSavedSessions.length>0&&T.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),T.launchConfirmResumeId&&(()=>{const L=T.filteredLaunchConfirmSavedSessions.find(E=>E.providerSessionId===T.launchConfirmResumeId);if(!L)return null;const O=vm(L);return s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:O.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:O.providerSessionId}),s.jsx("div",{className:"mt-1",children:O.metaLine}),O.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:O.updatedLabel}),O.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:O.preview})]})})()]}),onConfirm:T.handleConfirmLaunch,onCancel:T.closeLaunchConfirm}),u&&s.jsx(xm,{section:p,onSectionChange:f})]})}const ad=8e3;function u1(e){const t=e&&typeof e=="object"&&"result"in e?e.result:e,n=t&&typeof t=="object",r=n&&t.success===!1,a=n&&t.mirrorStale===!0;return!r&&!a?{confirmed:!0}:{confirmed:!1,reason:r&&typeof t.error=="string"?t.error:a?"the coordinator did not confirm the change":"command was rejected"}}function km(e,t,n){const r=l.useRef(new Map),[,a]=l.useState(0),o=l.useCallback(()=>a(g=>g+1),[]);l.useEffect(()=>{const g=r.current;if(g.size===0)return;const k=Date.now();let h=!1;for(const[v,w]of g){const b=e.get(v),j=w.muted===void 0||(b?b.muted===w.muted:!1),C=w.hidden===void 0||(b?b.surfaceHidden===w.hidden:!1),y=k-w.at>ad;(j&&C||y)&&(g.delete(v),h=!0)}h&&o()},[e,o]),l.useEffect(()=>{if(r.current.size===0)return;const g=setInterval(()=>{const k=r.current,h=Date.now();let v=!1;for(const[w,b]of k)h-b.at>ad&&(k.delete(w),v=!0);v&&o(),k.size===0&&clearInterval(g)},1e3);return()=>clearInterval(g)});const i=l.useCallback((g,k)=>{const h=r.current.get(g);r.current.set(g,{...h,...k,at:Date.now()}),o()},[o]),c=l.useCallback(g=>{const k=g.sessionId,h=k?r.current.get(k):void 0;return(h==null?void 0:h.muted)!==void 0?h.muted:Os(g,e).muted??!1},[e]),d=l.useCallback(g=>{const k=g.sessionId,h=k?r.current.get(k):void 0;return(h==null?void 0:h.hidden)!==void 0?h.hidden:Os(g,e).surfaceHidden??!1},[e]),p=l.useCallback((g,k)=>{const h=Ds(g),v=g.sessionId;!h||!v||(i(v,k),t(h,"set_conversation_prefs",{sessionId:v,...k,...Ua(g)}).then(w=>{const b=u1(w);b.confirmed||(console.warn("[conversation-prefs] set_conversation_prefs not confirmed",b.reason),r.current.delete(v),o(),n==null||n(`Couldn't update conversation — ${b.reason}`))}).catch(w=>{console.warn("[conversation-prefs] set_conversation_prefs failed",w),r.current.delete(v),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]),u=l.useCallback(g=>{p(g,{muted:!c(g)})},[p,c]),m=l.useCallback((g,k)=>{p(g,{hidden:k})},[p]),f=l.useCallback(g=>{p(g,{hidden:!d(g)})},[p,d]);return{isMuted:c,isHidden:d,toggleMute:u,setHidden:m,toggleHidden:f}}function la(e){return[...e].sort((t,n)=>{const r=n.timestamp-t.timestamp;return r!==0?r:t.conversation.tabKey.localeCompare(n.conversation.tabKey)})}function p1(e,t=[]){const n=new Map(e.map(a=>[a.conversation.tabKey,a])),r=t.map(a=>n.get(a)).filter(a=>!!a);return r.length===e.length?r:la(e)}function m1(e,t=[]){const n=e.filter(i=>i.requiresAction),r=e.filter(i=>i.unread&&!i.requiresAction),a=e.filter(i=>!i.unread&&!i.requiresAction&&i.isWorking),o=e.filter(i=>!i.unread&&!i.requiresAction&&!i.isWorking);return{attentionItems:la(n),unreadItems:la(r),workingItems:p1(a,t),completedItems:la(o)}}function h1(e){var r,a,o;const t=((r=e.p2p)==null?void 0:r.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":!(!!((a=e.p2p)!=null&&a.available)||!!((o=e.p2p)!=null&&o.state))&&e.status&&e.status!=="offline"?"Connected":"Offline"}function f1(e,t){if(!e)return[];const n=e.recentLaunches||[];return n.length>0?n.map(r=>({id:r.id,label:r.title||r.providerName||r.providerType,kind:r.kind,providerType:r.providerType,providerSessionId:r.providerSessionId,subtitle:ln(r.summaryMetadata)||r.workspace||void 0,workspace:r.workspace,summaryMetadata:r.summaryMetadata})):t.filter(r=>r.type!=="adhdev-daemon"&&r.daemonId===e.id).map(r=>{var i;const a=xr(r)?"cli":Nn(r)?"acp":"ide",o=ln(r.summaryMetadata);return{id:`${a}:${r.type}:${r.workspace||""}`,label:((i=r.activeChat)==null?void 0:i.title)||(xr(r)?r.cliName||r.type:Nn(r)&&r.cliName||r.type),kind:a,providerType:r.type,providerSessionId:r.providerSessionId,subtitle:Nn(r)?o||r.workspace||void 0:r.workspace||void 0,workspace:r.workspace||void 0,timestamp:r.lastMessageAt||0}}).sort((r,a)=>a.timestamp-r.timestamp).map(({timestamp:r,...a})=>a)}function b1(e,t,n=[]){const r=new Map;for(const o of t){const i=Ds(o.conversation),c=r.get(i);c?c.push(o):r.set(i,[o])}const a=new Map;for(const o of n){const i=Ds(o),c=a.get(i);c?c.push(o):a.set(i,[o])}return e.map(o=>{const i=r.get(o.id)||[],c=a.get(o.id)||[],d=[...i].sort((h,v)=>v.timestamp-h.timestamp)[0]||null,p=(d==null?void 0:d.conversation)||null,u=pi(o),m=i.filter(h=>h.unread||h.requiresAction).length,f=i.filter(h=>gr(h.conversation)).length+c.filter(gr).length,g=h1(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:f,latestConversation:p,latestTimestamp:(d==null?void 0:d.timestamp)||0,fallbackActivityAt:u,preview:p?Bk(p,wp(p)):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((o,i)=>{const c=o.latestTimestamp||o.fallbackActivityAt||0,d=i.latestTimestamp||i.fallbackActivityAt||0;return d!==c?d-c:o.label.localeCompare(i.label)})}function g1(e){return e==="chat"}function zr(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 x1({conversations:e,machineEntries:t,items:n,selectedConversation:r,selectedTabKey:a,screen:o,liveSessionInboxState:i,sendDaemonCommand:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,setSelectedTabKey:k,setScreen:h,setSelectedMachineId:v,setSection:w,setMachineBackTarget:b,resetMachineAction:j}){const C=l.useRef(null),y=l.useCallback(x=>{if(!(x!=null&&x.sessionId))return;const N=Os(x,i),S=Math.max(Date.now(),nn(x),N.lastUpdated||0);zr("mark_read:start",{tabKey:x.tabKey,sessionId:x.sessionId,displayPrimary:yt(x),inboxBucket:N.inboxBucket,unread:N.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:nn(x),readAt:S}),c(Ds(x)||x.routeId,"mark_session_seen",{sessionId:x.sessionId,providerSessionId:x.providerSessionId,seenAt:S,completionMarker:N.completionMarker}).then(A=>{zr("mark_read:result",{tabKey:x.tabKey,sessionId:x.sessionId,result:A})}).catch(A=>{zr("mark_read:error",{tabKey:x.tabKey,sessionId:x.sessionId,error:A instanceof Error?A.message:String(A)})})},[i,c]);return l.useEffect(()=>{var N;if(!r){g1(o)&&h("inbox"),k(((N=e[0])==null?void 0:N.tabKey)||null),C.current=null;return}if(o!=="chat"){C.current=null;return}const x=`${r.tabKey}:${r.sessionId||""}`;C.current!==x&&(C.current=x,y(r))},[e,y,o,r,h,k]),l.useEffect(()=>{if(!d)return;const x=e.find(N=>N.tabKey===d);x&&(k(x.tabKey),h("chat"),p==null||p())},[e,p,d,h,k]),l.useEffect(()=>{if(!u)return;const x=t.find(N=>N.id===u);x&&(v(x.id),j(),w("machines"),b("inbox"),h("machine"),m==null||m())},[t,m,u,j,b,h,w,v]),l.useEffect(()=>{f&&(w(f),h("inbox"),g==null||g())},[g,f,h,w]),l.useEffect(()=>{const x=n.filter(N=>N.inboxBucket==="task_complete"||N.unread);x.length!==0&&zr("inbox_state",{screen:o,selectedTabKey:a,items:x.map(N=>{const S=Os(N.conversation,i);return{liveState:S,tabKey:N.conversation.tabKey,sessionId:N.conversation.sessionId,displayPrimary:yt(N.conversation),serverBucket:S.inboxBucket,computedBucket:N.inboxBucket,serverUnread:S.unread,computedUnread:N.unread,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,activityAt:nn(N.conversation)}})})},[n,i,o,a]),{markConversationRead:y}}function v1(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function od(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function y1(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function w1({sendDaemonCommand:e,navigate:t,ides:n,conversations:r}){const{launchCli:a}=Ra(),[o,i]=l.useState("idle"),[c,d]=l.useState(""),[p,u]=l.useState(null),m=l.useCallback(()=>{i("idle"),d(""),u(null)},[]),f=l.useCallback(async(j,C,y)=>{var x;try{i("loading"),d(`Launching ${C}…`);const N={ideType:C,enableCdp:!0};(x=y==null?void 0:y.workspacePath)!=null&&x.trim()&&(N.workspace=y.workspacePath.trim()),await e(j,"launch_ide",N),i("done"),d(`${C} launch requested`)}catch(N){i("error"),d(N instanceof Error?N.message:"Launch IDE failed"),console.error("Launch IDE failed",N)}},[e]),g=l.useCallback(async(j,C,y)=>{if(C.trim())try{i("loading"),d(y!=null&&y.createIfMissing?"Creating folder…":"Saving workspace…");const x=await e(j,"workspace_add",{path:C.trim(),createIfMissing:(y==null?void 0:y.createIfMissing)===!0});if(x!=null&&x.success){i("done"),d(y!=null&&y.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),d((x==null?void 0:x.error)||"Could not save workspace")}catch(x){i("error"),d(x instanceof Error?x.message:"Could not save workspace")}},[e]),k=l.useCallback(async j=>{var C,y,x,N,S,A;try{i("loading"),d("Starting daemon upgrade…");const T=await e(j,"daemon_upgrade",{});if((C=T==null?void 0:T.result)!=null&&C.alreadyLatest){i("done"),d(`Already on v${((y=T==null?void 0:T.result)==null?void 0:y.version)||"latest"}.`);return}if((x=T==null?void 0:T.result)!=null&&x.upgraded||(N=T==null?void 0:T.result)!=null&&N.success){i("done"),d(`Upgrade to v${((S=T==null?void 0:T.result)==null?void 0:S.version)||"latest"} started. Daemon is restarting…`);return}i("error"),d(((A=T==null?void 0:T.result)==null?void 0:A.error)||"Upgrade failed")}catch(T){i("error"),d(T instanceof Error?T.message:"Upgrade failed")}},[e]),h=l.useCallback(async(j,C,y,x)=>{var A,T,I;const N=Date.now(),S={machineId:j,kind:C,providerType:y,workspaceId:(x==null?void 0:x.workspaceId)||null,workspacePath:(x==null?void 0:x.workspacePath)||null,resumeSessionId:(x==null?void 0:x.resumeSessionId)||null,startedAt:N};try{i("loading"),d(`Launching ${y}…`),u(S);const D={cliType:y};(A=x==null?void 0:x.workspacePath)!=null&&A.trim()?D.dir=x.workspacePath.trim():x!=null&&x.workspaceId?D.workspaceId=x.workspaceId:x!=null&&x.useHome&&(D.useHome=!0),x!=null&&x.resumeSessionId&&(D.resumeSessionId=x.resumeSessionId),(T=x==null?void 0:x.args)!=null&&T.trim()&&(D.cliArgs=x.args.trim().split(/\s+/).filter(Boolean)),(I=x==null?void 0:x.model)!=null&&I.trim()&&(D.initialModel=x.model.trim());const P=await a(j,D),_=(P==null?void 0:P.result)||P,G=(_==null?void 0:_.sessionId)||(_==null?void 0:_.id);if(P!=null&&P.success&&G){u(null),i("done"),d(`${y} launched`),t(wr(G));return}if(P!=null&&P.success){i("loading"),d(`${y} launch requested — waiting for session…`);return}u(null),i("error"),d((P==null?void 0:P.error)||(_==null?void 0:_.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(D){if(y1(D)){i("loading"),d(`${y} launch requested — waiting for session…`);return}u(null),i("error"),d(D instanceof Error?D.message:`Could not launch ${C.toUpperCase()} workspace`)}},[t,e]),v=l.useCallback(async(j,C)=>{try{const y=await e(j,"list_saved_sessions",{providerType:C,kind:"cli",limit:30}),x=(y==null?void 0:y.result)??y;return Array.isArray(x==null?void 0:x.sessions)?x.sessions:[]}catch(y){return console.error("Failed to list saved sessions on mobile:",y),[]}},[e]),w=l.useCallback(async(j,C)=>bl(e,j,C),[e]);l.useEffect(()=>{if(!p)return;const j=od(p.workspacePath),C=n.find(x=>{var D,P,_,G;if(!x||x.type==="adhdev-daemon"||v1(x.daemonId||x.id)!==p.machineId||(x.transport==="acp"?"acp":x.transport==="pty"?"cli":null)!==p.kind||String(x.agentType||x.type||"")!==p.providerType)return!1;const T=String(x.providerSessionId||"");if(p.resumeSessionId&&T)return T===p.resumeSessionId;if(j){const H=od(x.workspace||x.runtimeWorkspaceLabel);return H?H===j:!1}return Number(x.lastUpdated||x._lastUpdate||x.timestamp||((G=(_=(P=(D=x.activeChat)==null?void 0:D.messages)==null?void 0:P.at)==null?void 0:_.call(P,-1))==null?void 0:G.timestamp)||0)>=p.startedAt-5e3});if(!C)return;const y=fm({entrySessionId:C.sessionId,entryInstanceId:C.instanceId,entryRouteId:C.id,conversations:r});y&&(u(null),i("done"),d(`${p.providerType} launched`),t(wr(y)))},[r,n,t,p]),l.useEffect(()=>{if(!p)return;const j=window.setTimeout(()=>{u(C=>!C||C.startedAt!==p.startedAt?C:(i("error"),d("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(j)},[p]);const b=l.useCallback(async(j,C)=>{var y;if(C.kind==="ide"&&C.providerType){await f(j,C.providerType,{workspacePath:C.workspace||null});return}if((C.kind==="cli"||C.kind==="acp")&&C.providerType){const x=((y=C.workspace)==null?void 0:y.trim())||"";await h(j,C.kind,C.providerType,{workspacePath:x||null,useHome:!x,resumeSessionId:C.providerSessionId||null})}},[f,h]);return{machineAction:{state:o,message:c},resetMachineAction:m,handleLaunchDetectedIde:f,handleAddWorkspace:g,handleMachineUpgrade:k,handleLaunchWorkspaceProvider:h,handleListSavedSessions:v,handleBrowseDirectory:w,handleOpenRecent:b}}function k1({conversations:e,selectedConversation:t,machineBackTarget:n,markConversationRead:r,resetMachineAction:a,setSelectedTabKey:o,setScreen:i,setSelectedMachineId:c,setSection:d,setMachineBackTarget:p}){const u=l.useCallback(w=>{o(w.tabKey),i("chat"),r(w)},[r,i,o]),m=l.useCallback(w=>{const b=e.find(j=>j.routeId===w.routeId&&j.streamSource==="native");b&&(o(b.tabKey),i("chat"),r(b))},[e,r,i,o]),f=l.useCallback(()=>{r(t),i("inbox")},[r,t,i]),g=l.useCallback((w,b="inbox")=>{c(w),a(),d("machines"),p(b),i("machine")},[a,p,i,d,c]),k=l.useCallback(w=>{const b=Ds(w);b&&g(b,"chat")},[g]),h=l.useCallback(()=>{a(),i(n)},[n,a,i]),v=l.useCallback(w=>{d(w),i("inbox")},[i,d]);return{openConversation:u,openNativeConversation:m,backFromConversation:f,openMachine:g,openConversationMachine:k,backFromMachine:h,changeMachineSection:v}}function En(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function S1(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function C1({conversations:e,hiddenConversations:t,ides:n,actionLogs:r,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,userName:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,onOpenHistory:k,onOpenRemote:h,onStopCli:v,wsStatus:w,isConnected:b,onShowAllHiddenConversations:j,onHideConversation:C,onOpenMeshGraph:y,onOpenNewSession:x,liveSessionInboxState:N,setCliViewModeOverrides:S}){const[A,T]=l.useState(()=>{var U;return((U=e[0])==null?void 0:U.tabKey)||null}),[I,D]=l.useState(()=>e[0]?"chat":"inbox"),[P,_]=l.useState("chats"),[G,H]=l.useState(null),[L,O]=l.useState("inbox"),E=l.useRef([]),M=Cr(),$="1.0.24",R=l.useMemo(()=>e.find(U=>U.tabKey===A)||e[0]||null,[e,A]),z=l.useMemo(()=>R?n.find(U=>U.id===R.routeId):void 0,[n,R]),Q=l.useMemo(()=>!R||dt(R)||!mt(R)?null:Fn(R),[R]),ne=l.useMemo(()=>n.filter(U=>U.type==="adhdev-daemon").sort(Yi),[n]),J=l.useMemo(()=>ne.find(U=>U.id===G)||null,[ne,G]),Z=Ga({sendDaemonCommand:a,activeConv:R||void 0,setActionLogs:o,isStandalone:i}),de=w1({sendDaemonCommand:a,navigate:M,ides:n,conversations:e}),te=fk(e),B=l.useMemo(()=>e.map(U=>{const be=I==="chat"&&(R==null?void 0:R.tabKey)===U.tabKey,je=Ha(U,N,{hideOpenTaskCompleteUnread:!0,isOpenConversation:be}),ge=nn(U),Ie=wp(U),et=Tp(U,Ie);return{conversation:U,timestamp:ge,preview:et,unread:je.unread,requiresAction:je.requiresAction,isWorking:je.isWorking,inboxBucket:je.inboxBucket}}),[e,N,I,R,te]),{markConversationRead:ie}=x1({conversations:e,machineEntries:ne,items:B,selectedConversation:R,selectedTabKey:A,screen:I,liveSessionInboxState:N,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,setSelectedTabKey:T,setScreen:D,setSelectedMachineId:H,setSection:_,setMachineBackTarget:O,resetMachineAction:de.resetMachineAction}),Y=k1({conversations:e,selectedConversation:R,machineBackTarget:L,markConversationRead:ie,resetMachineAction:de.resetMachineAction,setSelectedTabKey:T,setScreen:D,setSelectedMachineId:H,setSection:_,setMachineBackTarget:O}),{isMuted:le,toggleMute:Ne}=km(N,a),{attentionItems:we,unreadItems:Se,workingItems:me,completedItems:q}=l.useMemo(()=>m1(B,E.current),[B]);l.useEffect(()=>{E.current=me.map(U=>U.conversation.tabKey)},[me]);const W=l.useMemo(()=>J?B.filter(U=>Ds(U.conversation)===J.id):[],[B,J]),X=l.useMemo(()=>f1(J,n),[n,J]),K=(J==null?void 0:J.version)||null,ue=!!J&&!!K&&!0&&K!==$,Pe=l.useMemo(()=>(J==null?void 0:J.availableProviders)||[],[J]),ce=l.useMemo(()=>Pe.filter(U=>En(U,"cli")).map(U=>({type:U.type,displayName:U.displayName||U.type,icon:U.icon})),[Pe]),F=l.useMemo(()=>Pe.filter(U=>En(U,"acp")).map(U=>({type:U.type,displayName:U.displayName||U.type,icon:U.icon})),[Pe]),pe=l.useMemo(()=>b1(ne,B,t),[B,ne,t]),xe=l.useCallback(async U=>{J&&await de.handleOpenRecent(J.id,U)},[de,J]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:I==="chat"&&R?s.jsx(t1,{selectedConversation:R,isAcp:dt(R),isStandalone:i,selectedIdeEntry:z,actionLogs:r,userName:c,isSendingChat:Z.isSendingChat,sendFeedbackMessage:Z.sendFeedbackMessage,isFocusingAgent:Z.isFocusingAgent,handleModalButton:Z.handleModalButton,handleRelaunch:Z.handleRelaunch,onBack:Y.backFromConversation,onOpenNativeConversation:Y.openNativeConversation,onOpenMachine:Y.openConversationMachine,onOpenHistory:k,onOpenRemote:h,onOpenMeshGraph:y,onStopCli:v,cliViewMode:Q,onSetCliViewMode:async U=>{await nm({conversation:R,mode:U,ides:n,sendDaemonCommand:a,setCliViewModeOverrides:S})},handleSendChat:Z.handleSendChat,handleForceSendChat:Z.handleForceSendChat,handleFocusAgent:Z.handleFocusAgent}):I==="machine"&&J?s.jsx(d1,{selectedMachineEntry:J,selectedMachineConversations:W,selectedMachineRecentLaunches:X,cliProviders:ce,acpProviders:F,selectedMachineNeedsUpgrade:ue,appVersion:$,machineAction:de.machineAction,isStandalone:i,section:P,showBottomNav:L==="inbox",onBack:Y.backFromMachine,onSectionChange:Y.changeMachineSection,onOpenConversation:Y.openConversation,onOpenRecent:xe,onOpenMachineDetails:()=>M(`/machines/${J.id}`),onMachineUpgrade:()=>de.handleMachineUpgrade(J.id),onLaunchDetectedIde:(U,be)=>de.handleLaunchDetectedIde(J.id,U,be),onAddWorkspace:(U,be)=>de.handleAddWorkspace(J.id,U,be),onBrowseDirectory:U=>de.handleBrowseDirectory(J.id,U),onLaunchWorkspaceProvider:(U,be,je)=>de.handleLaunchWorkspaceProvider(J.id,U,be,je),onListSavedSessions:U=>de.handleListSavedSessions(J.id,U)}):s.jsx(r1,{section:P,attentionItems:we,unreadItems:Se,workingItems:me,completedItems:q,hiddenConversations:t,machineCards:pe,getAvatarText:S1,actionLogs:r,sendDaemonCommand:a,onOpenConversation:Y.openConversation,onShowAllHidden:j,onHideConversation:C,onOpenMeshGraph:y,onStopCli:v,onOpenNewSession:x,onOpenMachine:Y.openMachine,onOpenSettings:()=>M("/settings"),onSectionChange:_,wsStatus:w,isConnected:b,isStandalone:i,isConversationMuted:le,onToggleMuteConversation:Ne})})}function Mo(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function j1({conversations:e,numGroups:t,onMoveTab:n,onReceiveTab:r,onOwnTabDrop:a,onClearPreviewOrder:o}){const i=l.useRef(0),[c,d]=l.useState(!1),[p,u]=l.useState(null),m=l.useCallback(()=>{i.current=0,d(!1),u(null)},[]);l.useEffect(()=>(window.addEventListener("dragend",m),window.addEventListener("drop",m),()=>{window.removeEventListener("dragend",m),window.removeEventListener("drop",m)}),[m]);const f=l.useCallback(v=>{v.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,d(!0))},[]),g=l.useCallback(v=>{if(!v.dataTransfer.types.includes("text/tab-key"))return;if(v.preventDefault(),!Mo(t,n)){u("merge");return}const w=v.currentTarget.getBoundingClientRect(),b=v.clientX-w.left,j=w.width/3;b<j?u("split-left"):b>j*2?u("split-right"):u("merge")},[t,n]),k=l.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,d(!1),u(null))},[]),h=l.useCallback(v=>{i.current=0,d(!1);const w=v.dataTransfer.getData("text/tab-key"),b=w?e.some(C=>C.tabKey===w):!1,j=p;if(u(null),o(),!!w){if(v.preventDefault(),j==="split-left"&&Mo(t,n)){n==null||n(w,"split-left");return}if(j==="split-right"&&Mo(t,n)){n==null||n(w,"split-right");return}if(b){a(w);return}r==null||r(w)}},[e,p,t,n,r,a,o]);return{dragOver:c,dropAction:p,resetDragState:m,handleDragEnter:f,handleDragOver:g,handleDragLeave:k,handleDrop:h}}function N1(e,t){const n=new Set(t.map(o=>o.tabKey)),r=e.filter(o=>n.has(o)),a=t.filter(o=>!e.includes(o.tabKey)).map(o=>o.tabKey);return[...r,...a]}function A1({conversations:e,initialActiveTabId:t,initialTabOrder:n,onActiveTabChange:r,onTabOrderChange:a}){const[o,i]=l.useState(t??null),[c,d]=l.useState(n??[]),[p,u]=l.useState(null),m=l.useRef(null),f=l.useRef(null),g=l.useRef(r),k=l.useRef(a);l.useEffect(()=>{g.current=r},[r]),l.useEffect(()=>{k.current=a},[a]),l.useEffect(()=>{t&&t!==o&&i(t)},[t,o]),l.useEffect(()=>{d(N=>{const S=N1(N,e);return S.length===N.length&&S.every((A,T)=>A===N[T])?N:S})},[e]);const h=l.useMemo(()=>{const N=p??c;if(N.length===0)return e;const S=new Map(N.map((A,T)=>[A,T]));return[...e].sort((A,T)=>{const I=S.get(A.tabKey)??999,D=S.get(T.tabKey)??999;return I-D})},[e,p,c]);l.useEffect(()=>{var S,A;if(h.length===0){o!==null&&(i(null),(S=g.current)==null||S.call(g,null));return}if(o&&h.some(T=>T.tabKey===o))return;const N=h[0].tabKey;N!==o&&(i(N),(A=g.current)==null||A.call(g,N))},[h,o]);const v=l.useMemo(()=>h.find(N=>N.tabKey===o),[h,o]),w=l.useCallback(N=>{var S;i(N),(S=g.current)==null||S.call(g,N)},[]),b=l.useCallback((N,S,A)=>{d(T=>{var _;const I=T.filter(G=>G!==N),D=I.indexOf(S);if(D<0)return T;const P=A==="left"?D:D+1;return I.splice(P,0,N),(_=k.current)==null||_.call(k,I),I}),u(null)},[]),j=l.useCallback((N,S,A)=>{const I=(c.length>0?c:e.map(_=>_.tabKey)).filter(_=>_!==N),D=I.indexOf(S);if(D<0)return;const P=A==="left"?D:D+1;I.splice(P,0,N),m.current=I,u(I)},[c,e]),C=l.useCallback(()=>{var S;const N=m.current;N&&(d(N),(S=k.current)==null||S.call(k,N))},[]),y=l.useCallback(()=>{m.current=null,u(null)},[]),x=l.useCallback(N=>{d(S=>{var T;const A=S.filter(I=>I!==N);return A.push(N),(T=k.current)==null||T.call(k,A),A})},[]);return{activeTabId:o,activeConv:v,sortedConversations:h,previewOrderRef:m,draggingTabRef:f,selectTab:w,handleTabReorder:b,updatePreviewOrder:j,commitPreviewOrder:C,clearPreviewOrder:y,moveTabToEnd:x,setDraggingTabKey:N=>{f.current=N}}}function T1({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 yl({conversationsCount:e,isSplitMode:t,isStandalone:n,hasRegisteredMachines:r=!1,suppressGuide:a=!1,onOpenNewSession:o}){const{t:i}=Ce("common");if(a)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const c=!n&&!r,d=r&&!!o,p=i(r?"paneGroup.noConversations":n?"paneGroup.waitingForDaemon":"paneGroup.connectYourMachines"),u=i(r?"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:p}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:u}),d&&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:i("paneGroup.newSession"),"aria-label":i("paneGroup.newSession"),children:[s.jsx(Gi,{size:14}),s.jsx("span",{children:i("paneGroup.newSession")})]})}),c&&s.jsx(gm,{}),c&&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 Sm="adhdev-tab-shortcuts";function Cm(){try{return JSON.parse(localStorage.getItem(Sm)||"{}")}catch{return{}}}function jm({enabled:e=!0,sortedTabKeys:t,onFocus:n,onSelectTab:r}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>Cm()),[c,d]=l.useState(null),p=l.useCallback(m=>{const f=[];return m.metaKey&&f.push(a?"⌘":"Meta"),m.ctrlKey&&f.push("Ctrl"),m.altKey&&f.push(a?"⌥":"Alt"),m.shiftKey&&f.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(m.key)?null:(f.push(m.key.length===1?m.key.toUpperCase():m.key),f.join("+"))},[a]),u=l.useCallback(m=>{i(m);try{localStorage.setItem(Sm,JSON.stringify(m))}catch{}},[]);return l.useEffect(()=>{if(!e||!c)return;const m=f=>{if(f.preventDefault(),f.stopPropagation(),f.key==="Escape"){d(null);return}const g=p(f);if(!g)return;const k={...o};for(const[h,v]of Object.entries(k))v===g&&delete k[h];k[c]=g,u(k),d(null)};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[e,c,o,u,p]),l.useEffect(()=>{if(!e)return;const m=f=>{if(!(!f.ctrlKey&&!f.metaKey&&!f.altKey)){for(const[g,k]of Object.entries(o))if(t.includes(g)&&p(f)===k){f.preventDefault(),n(),r(g);return}}};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[e,o,t,n,r,p]),{isMac:a,tabShortcuts:o,shortcutListening:c,setShortcutListening:d,saveShortcuts:u}}const Po=e=>{e.preventDefault()},M1=l.memo(function({conv:t,isActive:n,isDraggedTab:r,isTaskCompleteUnread:a,shortcut:o,conversationKeys:i,draggingTabRef:c,onFocus:d,onSelectTab:p,onConversationActivated:u,onPreviewReorder:m,onReorderTab:f,onCommitPreviewOrder:g,onClearPreviewOrder:k,onDragStateReset:h,onDragTabKeyChange:v,onReceiveTab:w,onOpenContextMenu:b,longPressTimer:j,isGroupActive:C}){const y=pn(t),x=y.isGenerating?"agent-tab-generating":y.isWaiting?"agent-tab-waiting":"",N=y.isReconnecting,S=$k(t),A=Hk(t),T=Ap(t),I=l.useCallback(M=>{c.current=t.tabKey,v(t.tabKey),M.dataTransfer.setData("text/tab-key",t.tabKey),M.dataTransfer.effectAllowed="move"},[t.tabKey,c,v]),D=l.useCallback(()=>{c.current=null,v(null),g(),k(),h()},[c,v,g,k,h]),P=l.useCallback(M=>{const $=c.current;if(!(!$||$===t.tabKey)&&M.dataTransfer.types.includes("text/tab-key")){M.preventDefault(),M.stopPropagation();const R=M.currentTarget.getBoundingClientRect(),z=M.clientX<R.left+R.width/2?"left":"right";m($,t.tabKey,z)}},[t.tabKey,c,m]),_=l.useCallback(M=>{M.preventDefault(),M.stopPropagation();const $=M.dataTransfer.getData("text/tab-key");if($&&$!==t.tabKey){const R=M.currentTarget.getBoundingClientRect(),z=M.clientX<R.left+R.width/2?"left":"right";i.includes($)?f($,t.tabKey,z):w&&w($)}k()},[t.tabKey,i,f,w,k]),G=l.useCallback(M=>{M.stopPropagation(),d(),p(t.tabKey),u(t)},[t,u,d,p]),H=l.useCallback(M=>{M.preventDefault(),b(M.clientX,M.clientY,t.tabKey)},[t.tabKey,b]),L=l.useCallback(M=>{const $=M.touches[0];j.current=setTimeout(()=>{b($.clientX,$.clientY,t.tabKey)},600)},[t.tabKey,j,b]),O=l.useCallback(()=>{j.current&&clearTimeout(j.current)},[j]),E=["adhdev-dockview-tab",x,n&&"is-active",C&&"is-group-active",N&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:E,draggable:!0,onDragStart:I,onDragEnd:D,onDragOver:P,onDrop:_,onClick:G,onContextMenu:H,onTouchStart:L,onTouchEnd:O,onTouchMove:O,style:{position:"relative",cursor:"pointer",opacity:r?.4:void 0},children:[T&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-badge pointer-events-none absolute top-0.5 right-0.5 text-text-muted",title:"Mesh chat","aria-label":"Mesh chat",children:s.jsx(rs,{size:11})}),a&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:y.isGenerating?s.jsx("div",{className:"tab-spinner"}):y.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):N?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):y.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:yt(t),children:yt(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[N?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:en(t)}):y.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[en(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:en(t)}),s.jsx(ka,{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 P1({conversations:e,activeTabId:t,groupIndex:n,unreadTabKeys:r,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:m,onDragStateReset:f,onDragTabKeyChange:g,onReceiveTab:k,onHideTab:h,isGroupActive:v,allowTabShortcuts:w=!0}){const{t:b}=Ce("common"),[j,C]=l.useState(null),y=l.useRef(null),x=l.useRef(null),N=l.useMemo(()=>e.map(_=>_.tabKey),[e]);jr("PaneGroupTabBar",{groupIndex:n,activeTabId:t,tabCount:e.length,ctxMenuTab:(j==null?void 0:j.tabKey)||null});const{isMac:S,tabShortcuts:A,shortcutListening:T,setShortcutListening:I,saveShortcuts:D}=jm({enabled:w,sortedTabKeys:e.map(_=>_.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!j)return;const _=G=>{const H=document.querySelector("[data-pane-context-menu]");H&&H.contains(G.target)||C(null)};return window.addEventListener("mousedown",_,!0),()=>window.removeEventListener("mousedown",_,!0)},[j]),l.useEffect(()=>{const _=x.current;if(!_)return;const G=H=>{Math.abs(H.deltaY)<=Math.abs(H.deltaX)||(H.preventDefault(),_.scrollLeft+=H.deltaY)};return _.addEventListener("wheel",G,{passive:!1}),()=>_.removeEventListener("wheel",G)},[]);const P=l.useCallback((_,G,H)=>{C({x:_,y:G,tabKey:H})},[]);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:x,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(_=>s.jsx(M1,{conv:_,isActive:t===_.tabKey,isDraggedTab:a.current===_.tabKey,isTaskCompleteUnread:r.has(_.tabKey),shortcut:w?A[_.tabKey]:void 0,conversationKeys:N,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:m,onDragStateReset:f,onDragTabKeyChange:g,onReceiveTab:k,onOpenContextMenu:P,longPressTimer:y,isGroupActive:v},_.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:b("paneGroup.noTabsInGroup")})]})}),j&&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:j.x,top:j.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:Po,onClick:_=>{_.stopPropagation(),I(j.tabKey),C(null)},children:["⌨ ",A[j.tabKey]?`Change shortcut (${A[j.tabKey]})`:"Set shortcut"]}),A[j.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:Po,onClick:()=>{const _={...A};delete _[j.tabKey],D(_),C(null)},children:"✕ Remove shortcut"})]}),h&&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:Po,onClick:()=>{h(j.tabKey),C(null)},children:"🚫 Hide from Dashboard"})]})]}),w&&T&&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:_=>_.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 D1({conversations:e,ides:t,clearedTabs:n,actionLogs:r,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,userName:d,groupIndex:p,onFocus:u,isSplitMode:m,numGroups:f,onMoveTab:g,onReceiveTab:k,style:h,onActiveTabChange:v,initialActiveTabId:w,initialTabOrder:b,onTabOrderChange:j,onHideTab:C,isFocused:y,allowTabShortcuts:x=!0,onOpenNewSession:N,liveSessionInboxState:S}){const{sendCommand:A}=wt(),T=l.useRef(null),{activeTabId:I,activeConv:D,sortedConversations:P,draggingTabRef:_,selectTab:G,handleTabReorder:H,updatePreviewOrder:L,commitPreviewOrder:O,clearPreviewOrder:E,moveTabToEnd:M,setDraggingTabKey:$}=A1({conversations:e,initialActiveTabId:w,initialTabOrder:b,onActiveTabChange:v,onTabOrderChange:j}),R=Ga({sendDaemonCommand:a,activeConv:D,setActionLogs:o,isStandalone:i}),{dragOver:z,dropAction:Q,resetDragState:ne,handleDragEnter:J,handleDragOver:Z,handleDragLeave:de,handleDrop:te}=j1({conversations:e,numGroups:f,onMoveTab:g,onReceiveTab:k,onOwnTabDrop:M,onClearPreviewOrder:E}),B=D&&!dt(D)&&Fn(D)==="terminal",ie=l.useMemo(()=>D?t.find(we=>we.id===D.routeId):void 0,[t,D]),Y=l.useMemo(()=>D?r.filter(we=>we.routeId===D.tabKey):[],[r,D]),le=l.useMemo(()=>new Set(P.filter(we=>Vb(we,S,{isOpenConversation:we.tabKey===I})).map(we=>we.tabKey)),[I,S,P]);jr("PaneGroup",{groupIndex:p,conversationCount:e.length,activeTabId:I,dragOver:z});const Ne=l.useCallback(we=>{we.streamSource==="agent-stream"&&we.agentType&&A(we.routeId,lp(),{agentType:we.agentType,...we.sessionId&&{targetSessionId:we.sessionId}}).catch(()=>{})},[A]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:u,style:{...h,outline:z?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(P1,{conversations:P,activeTabId:I,groupIndex:p,numGroups:f,unreadTabKeys:le,draggingTabRef:_,onFocus:u,onSelectTab:G,onConversationActivated:Ne,onPreviewReorder:L,onReorderTab:H,onCommitPreviewOrder:O,onClearPreviewOrder:E,onDragStateReset:ne,onDragTabKeyChange:$,onMoveTab:g,onReceiveTab:k,onHideTab:C,isGroupActive:y??!1,allowTabShortcuts:x}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:J,onDragOver:Z,onDragLeave:de,onDrop:te,children:[z&&s.jsx(T1,{dropAction:Q,canSplit:!!(f<4&&g)}),D?s.jsx(gl,{activeConv:D,clearToken:n[D.tabKey]||0,isCliTerminal:!!B,ideEntry:ie,terminalRef:T,handleModalButton:R.handleModalButton,handleRelaunch:R.handleRelaunch,handleSendChat:R.handleSendChat,handleForceSendChat:R.handleForceSendChat,isSendingChat:R.isSendingChat,sendFeedbackMessage:R.sendFeedbackMessage,handleFocusAgent:R.handleFocusAgent,isFocusingAgent:R.isFocusingAgent,actionLogs:Y,userName:d,isInputActive:!m||!!y}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(yl,{conversationsCount:e.length,isSplitMode:m,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:N})})]})]})}function I1({containerRef:e,isSplitMode:t,numGroups:n,groupSizes:r,groupedConvs:a,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:p,isStandalone:u,hasRegisteredMachines:m,userName:f,focusedGroup:g,focusGroup:k,moveTabToGroup:h,splitTabRelative:v,closeGroup:w,handleResizeStart:b,groupActiveTabIds:j,setGroupActiveTab:C,groupTabOrders:y,setGroupTabOrder:x,toggleHiddenTab:N,onOpenNewSession:S,allowTabShortcuts:A=!0,liveSessionInboxState:T}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((I,D)=>{const P=t&&r.length===n?`${r[D]}%`:void 0;return s.jsxs(Lt.Fragment,{children:[t&&D>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:_=>b(D-1,_),onDoubleClick:()=>w(D),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(D1,{style:t?{flexBasis:P??`${100/n}%`,flexGrow:P?0:1,flexShrink:P?0:1}:void 0,conversations:I,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:p,isStandalone:u,hasRegisteredMachines:m,userName:f,groupIndex:D,isFocused:t&&g===D,onFocus:()=>k(D),isSplitMode:t,numGroups:n,onMoveTab:(_,G)=>{G==="left"&&D>0?h(_,D-1):G==="right"&&D<n-1?h(_,D+1):G==="split-left"&&n<4?v(_,D,"left"):G==="split-right"&&n<4&&v(_,D,"right")},onReceiveTab:_=>h(_,D),onActiveTabChange:_=>C(D,_),initialActiveTabId:j[D],initialTabOrder:y[D],onTabOrderChange:_=>x(D,_),onHideTab:N,onOpenNewSession:S,allowTabShortcuts:A,liveSessionInboxState:T})]},D)})})}const Nm="adhdev-dashboard-action-shortcuts",L1=1200,R1=[["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 E1(){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 Am(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 Ti(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function Da(e){const t=Object.fromEntries(Am(e).map(n=>[n.id,n.defaultShortcut]));try{const n=JSON.parse(localStorage.getItem(Nm)||"{}"),r={...t,...n};for(const[a,o]of R1)r[a]===o&&(r[a]=t[a]);return r}catch{return t}}function Tm(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function _1({enabled:e=!0,onTrigger:t}){const n=E1(),[r,a]=l.useState(()=>Da(n)),[o,i]=l.useState(null),[c,d]=l.useState([]),p=l.useRef({parts:[],timer:null}),u=l.useCallback(h=>{const v=[];return h.metaKey&&v.push(n?"⌘":"Meta"),h.ctrlKey&&v.push("Ctrl"),h.altKey&&v.push(n?"⌥":"Alt"),h.shiftKey&&h.key.length!==1&&v.push(n?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(v.push(Tm(h.key)),v.join("+"))},[n]),m=l.useCallback(h=>{a(h);try{localStorage.setItem(Nm,JSON.stringify(h))}catch{}},[]);l.useEffect(()=>{const h=Da(n),v=Object.entries(r),w=Object.entries(h);v.length===w.length&&v.every(([b,j])=>h[b]===j)||m(h)},[r,n,m]);const f=l.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),g=l.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},L1))},[]);l.useEffect(()=>{if(!o)return;const h=v=>{if(v.preventDefault(),v.stopPropagation(),v.key==="Escape"){i(null),d([]);return}const w=u(v);if(!w)return;const j=!(v.metaKey||v.ctrlKey||v.altKey)&&/^[A-Z0-9]$/.test(w);if(c.length===0&&j){d([w]);return}const y=[...c,w].slice(0,2).join(" "),x={...r};for(const[N,S]of Object.entries(x))S===y&&delete x[N];x[o]=y,m(x),i(null),d([])};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[r,u,m,o,c]),l.useEffect(()=>{if(!e||o)return;const h=v=>{if(v.defaultPrevented)return;const w=u(v);if(!w)return;const b=v.metaKey||v.ctrlKey||v.altKey;if(Ti(v.target))return;const j=p.current.parts,C=b?[w]:[...j.slice(-1),w].slice(-2),y=C.join(" "),x=C[C.length-1],N=Object.entries(r).filter(([,D])=>!!D),S=N.find(([,D])=>D===y);if(S){v.preventDefault(),f(),t(S[0]);return}if(N.some(([,D])=>D.startsWith(`${y} `))){v.preventDefault(),p.current.parts=C,g();return}const T=N.find(([,D])=>D===x);if(T){v.preventDefault(),f(),t(T[0]);return}if(N.some(([,D])=>D.startsWith(`${x} `))){v.preventDefault(),p.current.parts=[x],g();return}f()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[r,g,e,u,t,f,o]),l.useEffect(()=>()=>f(),[f]);const k=l.useMemo(()=>Am(n),[n]);return{isMac:n,actionDefinitions:k,actionShortcuts:r,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:d,saveShortcuts:m}}function $1({isTabInPopout:e,isTabFloating:t,tabShortcut:n,actionShortcuts:r}){const a=[];return e?(t&&a.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:r.dockActiveTab}),a.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:r.dockActiveTab})):t?a.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:r.dockActiveTab}):a.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:r.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:r.popoutActiveTab}),a.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:n?`Change shortcut (${n})`:"Set shortcut",shortcut:r.setActiveTabShortcut}),n&&a.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),a.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:r.hideCurrentTab,tone:"muted"}),a}function Mm(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function id({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:n,ides:r}){return!e||n>0?!1:t?!Mm(r):!0}function H1({previousVisibleConversationCount:e,visibleConversationCount:t,ides:n}){return t>0||e<=0?!1:Mm(n)}const Pm=1e3,F1=4;function ld(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function cd(e,t,n){return Math.abs(t.clientX-e.clientX)>n||Math.abs(t.clientY-e.clientY)>n}function B1({detachDelayMs:e=Pm,stillnessThresholdPx:t=F1,onDetach:n,setTimeoutFn:r=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let o=null,i=null,c=null,d=null,p=null,u=!1;const m=()=>{p!=null&&(a(p),p=null)},f=()=>{m(),c=null},g=()=>{m(),o=null,i=null,c=null,d=null,u=!1},k=()=>{!o||!c||!d||u||p!=null||(p=r(()=>{p=null,!(!o||!c||!d||u)&&ld(d,i)&&(cd(c,d,t)||(u=!0,n({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},h=w=>{if(!(!o||u)){if(!ld(w,i)){d={clientX:w.clientX,clientY:w.clientY},f();return}(!c||cd(c,w,t))&&(m(),c={clientX:w.clientX,clientY:w.clientY}),d={clientX:w.clientX,clientY:w.clientY},k()}},v=w=>{!o||u||(w&&(d={clientX:w.clientX,clientY:w.clientY}),f())};return{startDrag:w=>{m(),o=w.panelId,i=w.selfPanelBounds??null,c=null,d={clientX:w.clientX,clientY:w.clientY},u=!1},markSelfPanel:h,markNonSelfPanel:v,markNoDropTarget:v,markDockTarget:v,endDrag:g,isDragging:()=>o!=null,hasDetached:()=>u,dispose:g}}function O1(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function ca(e){return yt(e)||e.tabKey}function W1(e){return`remote:${e}`}function cs(e){return e.startsWith("remote:")}function dd(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Do(e){var r;const t=e==null?void 0:e.defaultView;if(!t)return;const n=a=>{if(a)try{a.focus({preventScroll:!0})}catch{try{a.focus()}catch{}}};try{t.focus(),n(e==null?void 0:e.body),n(e==null?void 0:e.documentElement),(r=t.requestAnimationFrame)==null||r.call(t,()=>{try{t.focus(),n(e==null?void 0:e.body)}catch{}})}catch{}}function Io(e,t){e.classList.remove(Zo.className,ei.className),e.classList.add(t==="light"?Zo.className:ei.className)}function ud(e){return e?Array.from(new Set(e.groups.map(t=>{var n,r;return(r=(n=t.element)==null?void 0:n.ownerDocument)==null?void 0:r.defaultView}).filter(t=>!!t&&t!==window))):[]}function U1(e,t,n){var i;const r=[t];let a;for(const c of r){let d;for(const p of c){const u=e.addPanel({id:p.tabKey,component:"conversation",title:ca(p),params:{kind:"conversation",tabKey:p.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});d||(d=u.id)}a=d??a}return n??((i=t[0])==null?void 0:i.tabKey)??null}function pd(e,t){const n=new Set(t.map(a=>a.tabKey)),r=new Map;for(const a of t)r.set(a.tabKey,(r.get(a.tabKey)||0)+1);for(const a of[...e.panels])cs(a.id)||n.has(a.id)||e.removePanel(a);for(const a of t){const o=e.getPanel(a.tabKey);if(o){(r.get(a.tabKey)||0)>1&&console.warn("[dashboard-conversations] Dockview panel already exists for duplicate tabKey",{tabKey:a.tabKey,daemonId:a.daemonId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,panelId:o.id}),o.update({params:{tabKey:a.tabKey}}),o.title!==ca(a)&&o.api.setTitle(ca(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:ca(a),params:{kind:"conversation",tabKey:a.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 md(e,t,n){var d,p;const r=n?W1(n):null;for(const u of[...e.panels])cs(u.id)&&(!r||u.id!==r)&&e.removePanel(u);if(!n||!r)return;const a=fs(t,n);if(!a&&e.totalPanels===0)return;const o=e.getPanel(r),i=Dp(a);if(o){o.title!==i&&o.api.setTitle(i);return}const c=(a==null?void 0:a.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((p=e.panels.find(u=>!cs(u.id)))==null?void 0:p.id);e.addPanel({id:r,component:"remote",title:i,params:{kind:"remote",routeId:n},...c?{position:{referencePanel:c,direction:"right"},inactive:!0}:{}})}function Dm({doId:e,targetSessionId:t,connState:n,viewMode:r}){const[a,o]=l.useState(null),[i,c]=l.useState(null);l.useEffect(()=>e?Ct.onScreenshot("ide-page",(u,m)=>{if(u!==e)return;const f=new FileReader;f.onload=()=>o(f.result),f.readAsDataURL(m)}):void 0,[e]),l.useEffect(()=>{n!=="connected"&&o(null)},[n]),l.useEffect(()=>{var u;return e?((u=Ct.onStatus)==null?void 0:u.call(Ct,(m,f)=>{m===e&&f!=null&&f.screenshotUsage&&c(f.screenshotUsage)}))||(()=>{}):void 0},[e]),l.useEffect(()=>{o(null)},[e,t]),l.useEffect(()=>{const p=e?Ct.get(e):null;if(!(!p||n!=="connected"))return r!=="chat"&&t?p.startScreenshots(t):p.stopScreenshots(t),()=>{p.stopScreenshots(t)}},[r,n,t,e]);const d=l.useCallback(async(p,u)=>{const m=e?Ct.get(e):null;return!m||n!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):m.sendInput(p,u,t)},[e,n,t]);return{connScreenshot:a,screenshotUsage:i,handleRemoteAction:d}}const Im=l.createContext(null);function Ka(){const e=l.useContext(Im);if(!e)throw new Error("DashboardDockviewContext missing");return e}function G1(e){const[,t]=l.useState(0);l.useEffect(()=>{const n=()=>t(a=>a+1),r=[e.api.onDidActiveGroupChange(n),e.api.onDidTitleChange(n),e.api.onDidGroupChange(n),e.containerApi.onDidActivePanelChange(n)];return()=>{for(const a of r)a.dispose()}},[e.api,e.containerApi])}function q1({params:e}){var d;const t=Ka(),n=l.useMemo(()=>fs([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),r=l.useMemo(()=>t.ides.find(p=>p.id===e.routeId),[t.ides,e.routeId]),a=(n==null?void 0:n.daemonId)||((d=n==null?void 0:n.routeId)==null?void 0:d.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:i,handleRemoteAction:c}=Dm({doId:a,targetSessionId:n?op(n):(r==null?void 0:r.sessionId)||(r==null?void 0:r.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(Tu,{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 z1(){const e=Ka();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(yl,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function K1(e){var b,j;G1(e);const t=Ka(),n=l.useCallback(C=>{"button"in C&&C.button!==0||e.api.setActive()},[e.api]),r=e.params.kind==="remote"?void 0:t.conversationsByTabKey.get(e.params.tabKey),a=r==null?void 0:r.sessionId,o=l.useCallback(C=>vk(C),[]),i=l.useCallback(()=>xk(a),[a]),c=l.useSyncExternalStore(o,i,i);if(e.params.kind==="remote"){const C=fs([...t.conversationsByTabKey.values()],e.params.routeId),y=((b=e.api.group.activePanel)==null?void 0:b.id)===e.api.id,x=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${y?" is-active":""}${x?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(C==null?void 0:C.tabKey)||"",onMouseDown:n,onTouchStart:n,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:C!=null&&C.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:C.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const d=t.conversationsByTabKey.get(e.params.tabKey);if(!d)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const p=((j=e.api.group.activePanel)==null?void 0:j.id)===e.api.id,u=e.api.isGroupActive,m=Ha(d,t.liveSessionInboxState,{isOpenConversation:p}),f=m.isReconnecting,g=m.isConnecting,k=m.isGenerating||c,h=m.isWaiting,v=m.unread,w=t.tabShortcuts[d.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${p?" is-active":""}${u?" is-group-active":""}${f?" is-reconnecting":""}`,title:yt(d),"data-tab-key":e.params.tabKey,onMouseDown:n,onTouchStart:n,onContextMenu:C=>{var y;C.preventDefault(),n(C),t.openTabContextMenu({x:C.clientX,y:C.clientY,tabKey:d.tabKey,sourceDocument:((y=C.target)==null?void 0:y.ownerDocument)??document})},children:[v&&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"}):h?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):f?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):g?s.jsx("div",{className:"tab-connecting-spinner"}):d.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:yt(d)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:f?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:en(d)}):g?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:en(d)}):s.jsx("span",{children:en(d)})})]}),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 Kr(e){return e.isActive}function hd(e){return e.isVisible}function V1(e){e.preventDefault()}function Y1({params:e,api:t}){var g;const n=Ka(),r=l.useRef(null),[a,o]=l.useState(()=>Kr(t)),[i,c]=l.useState(()=>hd(t)),d=n.conversationsByTabKey.get(e.tabKey),p=Ga({sendDaemonCommand:n.sendDaemonCommand,activeConv:d,setActionLogs:n.setActionLogs,isStandalone:n.isStandalone});l.useEffect(()=>{o(Kr(t)),c(hd(t));const k=[t.onDidActiveChange(h=>o(h.isActive)),t.onDidActiveGroupChange(h=>{if(!Kr(t)&&!h.isActive){o(!1);return}o(Kr(t))}),t.onDidVisibilityChange(h=>c(h.isVisible))];return()=>{for(const h of k)h.dispose()}},[t]);const u=l.useMemo(()=>d?n.ides.find(k=>k.id===d.routeId):void 0,[n.ides,d]),m=l.useMemo(()=>d?n.actionLogs.filter(k=>k.routeId===d.tabKey):[],[n.actionLogs,d]);if(!d)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(yl,{conversationsCount:0,isSplitMode:!1,isStandalone:n.isStandalone,hasRegisteredMachines:n.hasRegisteredMachines,onOpenNewSession:n.onOpenNewSession,suppressGuide:n.hasDetachedConversationPanels})});const f=!dt(d)&&Fn(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(gl,{activeConv:d,clearToken:n.clearedTabs[d.tabKey]||0,isCliTerminal:f,ideEntry:u,terminalRef:r,handleModalButton:p.handleModalButton,handleRelaunch:p.handleRelaunch,handleSendChat:p.handleSendChat,handleForceSendChat:p.handleForceSendChat,isSendingChat:p.isSendingChat,handleFocusAgent:p.handleFocusAgent,isFocusingAgent:p.isFocusingAgent,actionLogs:m,userName:n.userName,scrollToBottomRequestNonce:((g=n.scrollToBottomRequest)==null?void 0:g.tabKey)===d.tabKey?n.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:i})})}function J1({visibleConversations:e,clearedTabs:t,ides:n,actionLogs:r,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:d,userName:p,toggleHiddenTab:u,actionShortcuts:m,registerActionHandlers:f,onActiveTabChange:g,onOpenNewSession:k,onRequestScrollToBottom:h,requestedActiveTabKey:v,requestedRemoteIdeId:w,onRequestedActiveTabConsumed:b,scrollToBottomRequest:j,liveSessionInboxState:C,layoutProfile:y}){var lt,ut,St;const{theme:x}=Ws(),{sendCommand:N}=wt(),S=l.useRef(null),A=l.useRef(null),T=l.useRef(null),I=l.useRef(!1),D=l.useRef(!1),P=l.useRef(!1),_=l.useRef(null),G=l.useRef([]),[H,L]=l.useState(null),[O,E]=l.useState(0),M=l.useRef(typeof window>"u"?{}:mj(y)),$=l.useMemo(()=>new Map(e.map(V=>[V.tabKey,V])),[e]),R=l.useMemo(()=>{const V=S.current;return V?V.groups.some(ee=>{try{const re=ee.model.location.type;return re!=="floating"&&re!=="popout"?!1:ee.panels.some(fe=>$.has(fe.id))}catch{return!1}}):!1},[$,O,e]),z=l.useCallback(()=>{var V;(V=S.current)==null||V.focus()},[]),Q=l.useCallback((V,ee)=>{h==null||h(V,ee)},[h]),ne=l.useCallback(V=>{const ee=document,re=V.document;for(const Te of ee.querySelectorAll('link[rel="stylesheet"]')){const qe=re.createElement("link");qe.rel="stylesheet",qe.href=Te.href,Te.crossOrigin&&(qe.crossOrigin=Te.crossOrigin),re.head.appendChild(qe)}for(const Te of ee.querySelectorAll("style")){const qe=re.createElement("style");qe.textContent=Te.textContent,re.head.appendChild(qe)}const fe=[];for(const Te of ee.styleSheets)try{for(const qe of Te.cssRules)qe instanceof CSSStyleRule&&(qe.selectorText===":root"||qe.selectorText==="html")&&fe.push(qe.cssText)}catch{}if(fe.length>0){const Te=re.createElement("style");Te.textContent=fe.join(`
|
|
69
|
+
Use this if you want to permanently remove a machine.`,confirmLabel:o("machine.connectedMachines.remove"),confirmColor:"red",onConfirm:T,onCancel:()=>m(null)})]})}const mC=["default","claude-cli","codex-cli","antigravity-cli","hermes-cli","gemini-cli"];function hC({daemonId:e,knownCliTypes:t=mC}){const{t:n}=Ce("common"),{sendCommand:r}=wt(),[a,o]=l.useState({}),[i,c]=l.useState({}),[d,p]=l.useState(!0),[u,m]=l.useState(null),[f,g]=l.useState(null),[k,h]=l.useState(""),v=l.useCallback(async()=>{if(e){p(!0),g(null);try{const j=await r(e,"list_coordinator_prompts",{}),C=j!=null&&j.result&&typeof j.result=="object"?j.result:j;if(!(C!=null&&C.success)){g((C==null?void 0:C.error)||"Failed to load");return}const y=C.entries||{};h(C.dir||"");const x={};for(const N of t)x[N]=y[N]||{override:"",append:""};for(const N of Object.keys(y))x[N]||(x[N]=y[N]);o(x),c(JSON.parse(JSON.stringify(x)))}catch(j){g((j==null?void 0:j.message)||String(j))}finally{p(!1)}}},[r,e,t]);l.useEffect(()=>{v()},[v]);const w=l.useCallback(async(j,C)=>{var y;if(e){m(`${j}:${C}`),g(null);try{const x=((y=a[j])==null?void 0:y[C])||"",N=await r(e,"write_coordinator_prompt",{key:j,kind:C,content:x}),S=N!=null&&N.result&&typeof N.result=="object"?N.result:N;if(!(S!=null&&S.success)){g((S==null?void 0:S.error)||"Save failed");return}c(A=>({...A,[j]:{...A[j]||{override:"",append:""},[C]:x}}))}catch(x){g((x==null?void 0:x.message)||String(x))}finally{m(null)}}},[r,e,a]),b=l.useMemo(()=>(j,C)=>{var y,x;return(((y=a[j])==null?void 0:y[C])||"")!==(((x=i[j])==null?void 0:x[C])||"")},[a,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(Xo,{i18nKey:"settings.coordinatorPrompts.overrideDesc",ns:"common",components:{strong:s.jsx("strong",{})}})," ",s.jsx(Xo,{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."]})]}),f&&s.jsx("div",{className:"text-[12px] text-status-error bg-status-error/10 border border-status-error/40 rounded px-3 py-2",children:f}),d&&s.jsx("div",{className:"text-[12px] text-text-muted",children:"Loading…"}),s.jsx("div",{className:"flex flex-col gap-6",children:Object.entries(a).map(([j,C])=>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:j}),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:C.override,onChange:y=>o(x=>({...x,[j]:{...x[j],override:y.target.value}})),placeholder:"(empty — use daemon default base prompt)",disabled:u===`${j}: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(j,"override"),disabled:u===`${j}:override`||!b(j,"override"),children:u===`${j}:override`?"Saving…":b(j,"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:C.append,onChange:y=>o(x=>({...x,[j]:{...x[j],append:y.target.value}})),placeholder:"(empty — nothing appended at this layer)",disabled:u===`${j}: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(j,"append"),disabled:u===`${j}:append`||!b(j,"append"),children:u===`${j}:append`?"Saving…":b(j,"append")?"Save append":"Saved"})})]},j))})]}):s.jsx("div",{className:"text-[12px] text-text-muted",children:"Connect a daemon to edit coordinator prompts."})}const fC=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function bC(){const{preference:e,setPreference:t}=Ws();return s.jsx("div",{className:"flex gap-2",children:fC.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 gC(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 xC(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function yo(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Gc(e){const{r:t,g:n,b:r}=xC(e);return .2126*yo(t)+.7152*yo(n)+.0722*yo(r)}function qc(e,t){const n=Gc(e),r=Gc(t),a=Math.max(n,r),o=Math.min(n,r);return(a+.05)/(o+.05)}function Jp(e){const t=gC(e);if(!t)return"#111827";const n="#111827",r="#ffffff";return qc(t,n)>=qc(t,r)?n:r}const Si={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},Ci={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},vC=[{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"}}}],Qp="adhdev-chat-theme",Xp="adhdev-chat-theme-custom";function oa(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Qp)||"ember"}catch{return"ember"}}function ps(e){try{const t=localStorage.getItem(Xp);if(t){const n=JSON.parse(t);return{...e==="dark"?Si:Ci,...n[e]}}}catch{}return e==="dark"?Si:Ci}function Or(e,t){try{localStorage.setItem(Xp,JSON.stringify({dark:e,light:t}))}catch{}}function ts(e,t){const n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),a=parseInt(e.slice(5,7),16);return`rgba(${n}, ${r}, ${a}, ${t})`}function Ma(e,t){const n=Math.min(255,parseInt(e.slice(1,3),16)+t),r=Math.min(255,parseInt(e.slice(3,5),16)+t),a=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${n.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const yC={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function pr(e,t){var a;const n=(a=yC[e])==null?void 0:a[t];if(!n)return;const r=document.documentElement;r.style.setProperty("--accent-primary",n),r.style.setProperty("--accent-primary-light",Ma(n,24)),r.style.setProperty("--accent-on-primary",Jp(n)),r.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${n}, ${Ma(n,18)})`),r.style.setProperty("--border-accent",ts(n,.35)),r.style.setProperty("--nav-active-bg",ts(n,.1)),r.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${n}, 0 0 12px ${ts(n,.06)}`)}function tn(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",ts(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",ts(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",ts(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",ts(e.borderSubtle,.5)),t.style.setProperty("--border-default",ts(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",Ma(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Jp(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Ma(e.accentColor,40)})`),t.style.setProperty("--border-accent",ts(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",ts(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${ts(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 ${ts(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 cl(){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 wC(e){try{localStorage.setItem(Qp,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=sn()?"dark":"light";tn(ps(t))}else cl(),pr(e,sn()?"dark":"light")}function kC(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=oa();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=sn()?"dark":"light";tn(ps(t))}else cl(),pr(e,sn()?"dark":"light")}function sn(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Ot({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:r=>n(r.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:r=>{/^#[0-9a-fA-F]{0,6}$/.test(r.target.value)&&n(r.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 Jn({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 SC({dark:e,onColorsChange:t}){const{t:n}=Ce("common"),r=e?"dark":"light",[a,o]=l.useState(()=>ps(r));l.useEffect(()=>{o(ps(r))},[r]);const i=l.useCallback((c,d)=>{o(p=>{const u={...p,[c]:d},f=ps(r==="dark"?"light":"dark");return r==="dark"?Or(u,f):Or(f,u),tn(u),t(u),u})},[r,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(Jn,{title:n("settings.theme.sectionAppBackground"),children:[s.jsx(Ot,{label:n("settings.theme.colorBackground"),value:a.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(Ot,{label:n("settings.theme.colorSurface"),value:a.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(Ot,{label:n("settings.theme.colorCard"),value:a.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(Jn,{title:n("settings.theme.sectionAppText"),children:[s.jsx(Ot,{label:n("settings.theme.colorPrimary"),value:a.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(Ot,{label:n("settings.theme.colorSecondary"),value:a.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(Ot,{label:n("settings.theme.colorMuted"),value:a.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(Jn,{title:n("settings.theme.sectionBordersAccent"),children:[s.jsx(Ot,{label:n("settings.theme.colorBorderSubtle"),value:a.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(Ot,{label:n("settings.theme.colorBorderDefault"),value:a.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(Ot,{label:n("settings.theme.colorAccent"),value:a.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(Jn,{title:n("settings.theme.sectionChatBubbles"),children:[s.jsx(Ot,{label:n("settings.theme.colorUserBubble"),value:a.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(Ot,{label:n("settings.theme.colorUserText"),value:a.userText,onChange:c=>i("userText",c)}),s.jsx(Ot,{label:n("settings.theme.colorAgentBubble"),value:a.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(Ot,{label:n("settings.theme.colorAgentText"),value:a.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(Jn,{title:n("settings.theme.sectionChatLayout"),children:[s.jsx(Ot,{label:n("settings.theme.colorChatBg"),value:a.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(Ot,{label:n("settings.theme.colorSendButton"),value:a.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(Ot,{label:n("settings.theme.colorInputBorder"),value:a.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:a.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:[a.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const c=e?Si:Ci,p=ps(e?"light":"dark");e?Or(c,p):Or(p,c),o(c),tn(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 CC(){const{t:e}=Ce("common"),[t,n]=l.useState(oa),[r,a]=l.useState(!0),[o,i]=l.useState(()=>ps("dark"));l.useEffect(()=>{a(sn());const p=new MutationObserver(()=>{const f=sn();a(f);const g=oa();g==="custom"?tn(ps(f?"dark":"light")):pr(g,f?"dark":"light")});p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const u=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const f=sn();a(f);const g=oa();g==="custom"?tn(ps(f?"dark":"light")):pr(g,f?"dark":"light")};return u.addEventListener("change",m),()=>{p.disconnect(),u.removeEventListener("change",m)}},[]),l.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?tn(ps(r?"dark":"light")):(cl(),pr(t,r?"dark":"light"))},[t,r]),l.useEffect(()=>{i(ps(r?"dark":"light"))},[r]);const c=p=>{n(p),wC(p)},d=[...vC,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText},light:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:d.map(p=>{const u=t===p.id,m=r?p.preview.dark:p.preview.light,f=p.id==="honey"||p.id==="ember"?"#1a1a1a":p.id==="custom"?o.userText:"#fff";return s.jsxs("button",{onClick:()=>c(p.id),className:"text-left rounded-xl p-3 transition-all",style:{background:u?"var(--bg-glass-hover)":"var(--bg-glass)",border:u?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:u?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:m.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:e("settings.theme.helloHelp")}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.userBubble,color:f},children:e("settings.theme.fixBug")}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:e("settings.theme.onIt")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[u&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:p.id==="custom"?e("settings.theme.customLabel"):p.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:p.description})]})]})]},p.id)})}),t==="custom"&&s.jsx(SC,{dark:r,onColorsChange:p=>i(p)})]})}const dl="adhdev_mobileDashboardMode_v1",ji="adhdev:mobile-dashboard-mode-change";function ul(){try{return localStorage.getItem(dl)==="workspace"?"workspace":"chat"}catch{return"chat"}}function jC(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??ul())},n=a=>{const o=a.detail;t(o)},r=a=>{a.key&&a.key!==dl||t()};return window.addEventListener(ji,n),window.addEventListener("storage",r),()=>{window.removeEventListener(ji,n),window.removeEventListener("storage",r)}}function NC(e){try{localStorage.setItem(dl,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(ji,{detail:e}))}function AC(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(ul()==="chat")},[]),s.jsx(Ys,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(un,{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),NC(n?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const TC="Choose a preset or create a fully custom theme. Custom themes control the entire app — backgrounds, text, borders, and chat bubbles.",MC="Choose whether the dashboard opens like a chat app on phones or keeps the full workspace layout.";function PC({themeDescription:e=TC,mobileDescription:t=MC,fontsSlot:n}){const{t:r}=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:r("settings.appearance.modeLabel")}),s.jsx(bC,{})]}),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:r("settings.appearance.themeLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:e}),s.jsx(CC,{})]}),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:r("settings.appearance.mobileLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:t}),s.jsx(AC,{})]})]})}const wo=new Map,zc=new Map;function DC(e){if(!e||typeof e!="object")return null;const t=e,n=t.result&&typeof t.result=="object"?t.result:t,r=n.machine;return!r||typeof r!="object"?null:{machine:r,timestamp:typeof n.timestamp=="number"?n.timestamp:void 0}}function IC(e,t,n,r){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:r,platform:n.platform,machine:n}}function Zp(){const{sendCommand:e}=wt(),{injectEntries:t,getIdes:n}=fr();return l.useCallback(async(r,a)=>{if(!r)return;const o=(a==null?void 0:a.minFreshMs)??F0,i=zc.get(r)||0;if(!(a!=null&&a.force)&&i>0&&Date.now()-i<o)return;const c=wo.get(r);if(c)return c;const d=(async()=>{const p=await e(r,"get_machine_runtime_stats"),u=DC(p);if(!u)return;const m=n().find(g=>g.id===r),f=IC(m,r,u.machine,u.timestamp||Date.now());t([f]),zc.set(r,Date.now())})().finally(()=>{wo.delete(r)});return wo.set(r,d),d},[n,t,e])}function LC(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 RC(e,t){const{sendData:n}=wt(),{injectEntries:r,getIdes:a}=fr(),o=Array.from(new Set(e.filter(Boolean))).join("|");l.useEffect(()=>{if(!(t!=null&&t.enabled)||!n)return;const i=o?o.split("|"):[];if(i.length===0)return;const c=i.map(d=>hs.subscribe({sendData:n},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const m=a().find(g=>g.id===d),f=LC(m,d,u);r([f])}));return()=>{c.forEach(d=>d())}},[o,a,r,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,n])}function EC(e,t){const{sendData:n}=wt(),[r,a]=l.useState(null),[o,i]=l.useState(!1);return l.useEffect(()=>{if(!e){a(null),i(!1);return}if(!(t!=null&&t.enabled)||!n){i(!1);return}a(null),i(!0);let c=null;const d=hs.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),a(p.diagnostics),i(!1)});return d.initialSendAccepted?c=setTimeout(()=>{i(!1)},W0):i(!1),()=>{c&&clearTimeout(c),d()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,n]),{diagnostics:r,loading:o,applyDiagnostics:a}}function _C(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function em(e){const{sendData:t}=wt(),[n,r]=l.useState({});return l.useEffect(()=>{const a=_C(e);if(!a||!e.sessionId||!t){r({});return}const o=hs.subscribe({sendData:t},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},i=>{r({status:i.status,modalMessage:i.modalMessage,modalButtons:i.modalButtons}),Tn.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||r({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,t]),n}function $C(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function HC(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 FC(e,t,n){const r=await n(`/api/v1/sessions/${encodeURIComponent(e)}/interactive-prompt/resolve`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let a=`HTTP ${r.status}`;try{const o=await r.json();typeof(o==null?void 0:o.error)=="string"&&(a=o.error)}catch{}throw new Error(a)}}async function BC({promptSession:e,response:t,useP2PCommand:n,sendCommand:r,fetchImpl:a=fetch}){if(n){const o=await r(e.routeId,"interactive_prompt_response",{targetSessionId:e.sessionId,sessionId:e.sessionId,response:t});if(!$C(o))throw new Error(HC(o));return}await FC(e.sessionId,t,a)}function tm(e){const{ides:t,isP2PActive:n,p2pStates:r}=js(),{sendCommand:a}=wt(),[o,i]=l.useState(null),[c,d]=l.useState(!1),[p,u]=l.useState(null),m=l.useRef(!1),f=l.useMemo(()=>Ub(t,e),[t,e]),g=!!f,k=l.useMemo(()=>f?f.prompt.promptId===o?null:f:null,[o,f]),h=l.useCallback(async b=>{if(!k||m.current)return;m.current=!0;const j=Mu(k.prompt,b);d(!0),u(null);try{const C=(r==null?void 0:r[k.daemonId])==="connected"||n===!0;await BC({promptSession:k,response:j,useP2PCommand:C,sendCommand:a}),i(k.prompt.promptId)}catch(C){throw u(C instanceof Error?C.message:String(C)),C}finally{d(!1),m.current=!1}},[n,r,k,a]),v=l.useCallback(()=>{k&&i(k.prompt.promptId)},[k]),w=l.useCallback(()=>{i(null),u(null)},[]);return{promptSession:k,hasActivePrompt:g,responseError:p,isSubmitting:c,submit:h,cancel:v,reopen:w}}function sm(e){return e instanceof Error?e.message:String(e||"")}function OC(e){const t=sm(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 WC(e){const t=sm(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function nm({conversation:e,mode:t,ides:n,sendDaemonCommand:r,setCliViewModeOverrides:a}){if(!e||!mt(e)||dt(e))return;const o=Fn(e);if(o===t)return;const i=e.sessionId;i&&a(c=>({...c,[i]:t}));try{await r(Ds(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Cs(e),mode:t})}catch(c){const d=WC(c);i&&!d&&a(p=>{const u={...p};return o===GC(n,i)?delete u[i]:u[i]=o,u}),OC(c)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",c instanceof Error?c.message:String(c)):console.error("Failed to switch CLI view mode:",c)}}function Kc(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 r=t[n];return!r||e.mode===r?e:{...e,mode:r}}function UC(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let n=!1;const r=e.map(a=>{const o=Kc(a,t),i=Array.isArray(a.childSessions)?a.childSessions.map(d=>Kc(d,t)):a.childSessions,c=i!==a.childSessions;return o!==a||c?(n=!0,{...o,...c?{childSessions:i}:{}}):a});return n?r:e}function GC(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 r of n.childSessions||[])if(r.id===t&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal"}return null}function qC({visibleConversations:e,clearedTabs:t,setClearedTabs:n,setActionLogs:r,isConversationMuted:a}){l.useEffect(()=>{Gu()},[]);const o=l.useMemo(()=>e.map(i=>({id:i.tabKey,name:Pp(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:a?a(i):!1})),[e,a]);return pw(o),l.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{n(d=>{const p=Date.now(),u={};for(const[m,f]of Object.entries(d))p-f<5e3&&(u[m]=f);return Object.keys(u).length===Object.keys(d).length?d:u})},5500);return()=>clearTimeout(c)},[t,n]),l.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;r(d=>{const p=d.filter(u=>u.timestamp>c).slice(-100);return p.length===d.length?d:p})},6e4);return()=>clearInterval(i)},[r]),null}function Vc(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 nn(e){const t=[...e.messages].reverse().find(a=>!(a!=null&&a._localId))||e.messages[e.messages.length-1],n=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,r=Vc(t==null?void 0:t.receivedAt)||Vc(t==null?void 0:t.timestamp)||0;return Math.max(n,r)}function Ni(e,t=0){return nn(e)||e.lastUpdated||t||0}function rm(e){return nn(e)||e.lastUpdated||0}function am(e,t,n=rm){const r=n(t)-n(e);if(r!==0)return r;const a=(e.machineName||"").localeCompare(t.machineName||"");if(a!==0)return a;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 Ai(e){var n;const t=ns(e.status,{activeModal:(n=e.modalButtons)!=null&&n.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function zC(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!Ai(e)&&!e.title.trim()}function KC(e){return e.length===0?null:[...e].sort((t,n)=>{const r=Number(Ai(n))-Number(Ai(t));if(r!==0)return r;const a=n.messages.length-t.messages.length;return a!==0?a:am(t,n)})[0]||null}function fs(e,t){const n=e.filter(i=>i.routeId===t);if(n.length===0)return null;const r=n.find(i=>i.streamSource==="native")||null,a=n.filter(i=>i.streamSource==="agent-stream"),o=KC(a);return r?o&&zC(r)?o:r:o||n[0]||null}function VC(e){const t=e.filter(a=>a.type!=="adhdev-daemon"),n=new Set;for(const a of t){if(!ui(a))continue;const o=Hu(a);o&&n.add(o)}const r=new Map;for(const a of t){const o=Uy(a,n),i=r.get(o);if(!i){r.set(o,a);continue}const c=m=>(m.workspace?1:0)+(m.activeChat?1:0)+(m.lastMessagePreview?1:0),d=c(i),p=c(a),u=p>d||p===d&&(a.timestamp||0)>(i.timestamp||0)?a:i;r.set(o,YC(u,u===a?i:a))}return Array.from(r.values())}function YC(e,t){const n=ui(t),r=ui(e);if(!n&&!r)return e;const a=r?n?void 0:t:e,o=r?e:n?t:void 0,i=a&&String(a.daemonId||"").trim()||String(e.ownerDaemonId||"").trim()||String(t.ownerDaemonId||"").trim()||void 0,c=String(e.ownerMachineName||"").trim()||String(t.ownerMachineName||"").trim()||void 0,d=o==null?void 0:o.settings;return{...e,...i&&{ownerDaemonId:i},...c&&!e.ownerMachineName&&{ownerMachineName:c},...d&&!r&&{settings:{...d,...e.settings??{}}}}}function ko(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 JC(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 Yc(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],n=t[t.length-1],r=n?JC(Mn(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)??""),r].join(":")}function QC(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||""),Yc(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||""),Yc(n.activeChat)].join(":"))].join("|")}function XC(e,t){const n=Date.now();return e.map(r=>{const a=t[r.tabKey];return a&&n-a<5e3?{...r,messages:[],title:""}:r})}function ZC(e,t){const n=new Map;for(const r of e){const a=t.get(r.routeId)||r;for(const o of lr({routeId:r.routeId}))n.set(o,a);for(const o of lr({providerSessionId:r.providerSessionId,sessionId:r.sessionId}))n.set(o,r.streamSource==="native"?a:r);for(const o of lr({tabKey:r.tabKey}))n.set(o,r)}return n}function ej(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function tj(e){const t=ej(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||""),r=Mn(t.content).slice(0,240);return`${e.messages.length}:${n}:${r}`}function sj({ides:e,connectionStates:t,clearedTabs:n}){const r=l.useMemo(()=>VC(e),[e]),a=l.useMemo(()=>Iu(e),[e]),o=l.useMemo(()=>Op(e),[e]),i=l.useRef([]),c=l.useRef([]),d=l.useRef([]),p=l.useRef(new Map),u=l.useRef(new Map),m=l.useMemo(()=>{const C=new Map,y=[];for(const A of r){const{connectionState:T="new",machineName:I}=Wp(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),D=QC(A),P=p.current.get(A.id);if(P&&P.ide===A&&P.sourceSignature===D&&P.connectionState===T&&P.machineName===I){C.set(A.id,P),y.push(...P.conversations);continue}const _=il(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),G={ide:A,sourceSignature:D,connectionState:T,machineName:I,conversations:_};C.set(A.id,G),y.push(..._)}p.current=C;const x=new Map,N=A=>{const T=tj(A),I=u.current.get(A.tabKey);if(I&&I.signature===T)return x.set(A.tabKey,I),I.timestamp;const D={signature:T,timestamp:rm(A)||(I==null?void 0:I.timestamp)||0};return x.set(A.tabKey,D),D.timestamp},S=[...y].sort((A,T)=>am(A,T,N));return u.current=x,S},[r,t,o]),f=l.useMemo(()=>{const C=XC(m,n);return ko(i.current,C)?i.current:(i.current=C,C)},[m,n]),g=l.useMemo(()=>{const C=new Map,y=Array.from(new Set(f.map(x=>x.routeId)));for(const x of y){const N=fs(f,x);N&&C.set(x,N)}return C},[f]),k=l.useMemo(()=>{const C=new Map;for(const y of f){const x=g.get(y.routeId),N=y.streamSource==="native"&&x?x:y;for(const S of lr({providerSessionId:y.providerSessionId,sessionId:y.sessionId,tabKey:y.tabKey}))C.set(S,N)}return C},[f,g]),h=l.useMemo(()=>ZC(f,g),[f,g]),v=l.useCallback(C=>{if(C)return k.get(C)},[k]),w=l.useCallback(C=>{if(C)return h.get(C)},[h]),b=l.useMemo(()=>{const C=f.filter(y=>!Os(y,a).surfaceHidden);return ko(c.current,C)?c.current:(c.current=C,C)},[f,a]),j=l.useMemo(()=>{const C=b.map(y=>y.tabKey);return ko(d.current,C)?d.current:(d.current=C,C)},[b]);return{chatIdes:r,conversations:f,visibleConversations:b,visibleTabKeys:j,resolveConversationBySessionId:v,resolveConversationByTarget:w}}function nj({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:n,setSearchParams:r}){const a=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&&r(c=>{const d=new URLSearchParams(c);return d.delete("activeTab"),d},{replace:!0})},[r,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:o,consumeRequestedActiveTab:i}}function rj({ides:e,sendDaemonCommand:t,setToasts:n,resolveConversationByTarget:r}){l.useEffect(()=>{ht.setIdes(e)},[e]),l.useEffect(()=>{ht.setResolveAction((a,o,i)=>{t(a,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const a=ht.onToast(o=>{n(c=>c.some(p=>p.message===o.message&&o.timestamp-p.timestamp<3e3)?c:[...c.slice(-4),{id:o.id,message:o.message,type:o.type,timestamp:o.timestamp,targetKey:o.targetKey,actions:o.actions}]);const i=o.duration||5e3;setTimeout(()=>n(c=>c.filter(d=>d.id!==o.id)),i)});return()=>{a()}},[n]),l.useEffect(()=>{const a=Np.on("status_event",o=>{ht.handleRawEvent(o,"ws")});return()=>{a()}},[]),l.useEffect(()=>{var o;const a=i=>{var h;const c=i.data;if((c==null?void 0:c.type)!=="notification_action"||typeof c.action!="string"||!c.action.startsWith("approval_")||!(c.daemonId||c.targetSessionId||c.targetKey))return;const d=c.targetSessionId||c.targetKey||c.daemonId,p=r(d),u=(p==null?void 0:p.routeId)||c.daemonId;if(!u)return;const m=Number(c.buttonIndex),f=c.button||((h=p==null?void 0:p.modalButtons)==null?void 0:h[m])||"Approve",g=String(f).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),k=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(g);t(u,"resolve_action",{action:k?"approve":"reject",button:f,...Number.isFinite(m)&&{buttonIndex:m},...(p==null?void 0:p.sessionId)&&{targetSessionId:p.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(v=>console.error("[SW Action] approval failed:",v))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",a),()=>{var i;return(i=navigator.serviceWorker)==null?void 0:i.removeEventListener("message",a)}},[r,t])}const aj="adhdev_dashboardLayout_v1",oj="adhdev_dashboardDockview_v1",ij="adhdev_dashboardDockviewHiddenRestore_v1",Qn={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function pl(e,t){try{const n=localStorage.getItem(e);return n?JSON.parse(n):t}catch{return t}}function lj(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function om(e){return`${aj}:${e}`}function cj(e){const t=om(e);return pl(t,null)}function dj(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,r=om(e);if(n){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function im(e){return`${oj}:${e}`}function uj(e){const t=im(e);return pl(t,null)}function pj(e,t){try{const n=im(e);if(!t){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function lm(e){return`${ij}:${e}`}function mj(e){const t=lm(e);return pl(t,{})}function hj(e,t){try{const n=lm(e);if(Object.keys(t).length===0){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function fj(){return{groupAssignments:[...Qn.groupAssignments],focusedGroup:Qn.focusedGroup,groupActiveTabIds:{...Qn.groupActiveTabIds},groupTabOrders:{...Qn.groupTabOrders},groupSizes:[...Qn.groupSizes]}}function bj(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):t.length===0}function gj(){const[e]=l.useState(()=>lj(typeof window<"u"?window.innerWidth:1280)),[t,n]=l.useState(()=>new Map),[r,a]=l.useState(0),[o,i]=l.useState({}),[c,d]=l.useState({}),[p,u]=l.useState([]),[m,f]=l.useState(()=>typeof window<"u"&&window.innerWidth<768),[g,k]=l.useState(!1),h=l.useCallback(()=>{if(g)return;const A=cj(e)??fj();n(new Map(A.groupAssignments)),a(A.focusedGroup),i(A.groupActiveTabIds),d(A.groupTabOrders),u(A.groupSizes),k(!0)},[g,e]);l.useEffect(()=>{g&&dj(e,{groupAssignments:[...t.entries()],focusedGroup:r,groupActiveTabIds:o,groupTabOrders:c,groupSizes:p})},[g,e,t,r,o,c,p]),l.useEffect(()=>{const A=window.matchMedia("(max-width: 767px)"),T=I=>f(I.matches);return A.addEventListener("change",T),()=>A.removeEventListener("change",T)},[]);const v=l.useCallback(A=>{n(A)},[]),w=l.useCallback(A=>{a(A)},[]),b=l.useCallback(A=>{i(A)},[]),j=l.useCallback(A=>{d(A)},[]),C=l.useCallback(A=>{u(A)},[]),y=l.useCallback(A=>{w(A)},[w]),x=l.useCallback((A,T)=>{i(I=>(I[A]??null)===(T??null)?I:{...I,[A]:T})},[]),N=l.useCallback((A,T)=>{d(I=>{const D=I[A];return bj(D,T)?I:{...I,[A]:T}})},[]),S=l.useCallback((A,T)=>{const I=T.get(A)??0;return x(I,A),y(I),I},[y,x]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:v,focusedGroup:r,updateFocusedGroup:w,focusGroup:y,groupActiveTabIds:o,updateGroupActiveTabIds:b,setGroupActiveTab:x,groupTabOrders:c,updateGroupTabOrders:j,setGroupTabOrder:N,groupSizes:p,updateGroupSizes:C,isMobile:m,hasHydratedStoredLayout:g,hydrateStoredLayout:h,focusConversationTab:S}}function xj(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0],r=Fa(t);return typeof(n==null?void 0:n.id)=="string"&&r.includes(n.id)}function vj({urlActiveTab:e,conversations:t,resolveConversationBySessionId:n,normalizedGroupAssignments:r,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:i,setSearchParams:c,historyModalOpen:d,activeConv:p,isRefreshingHistory:u,ides:m,handleRefreshHistory:f}){const g=l.useRef(!1),k=l.useRef(!1),h=l.useRef(null),v=l.useRef(!1);l.useEffect(()=>{if(!e||g.current||t.length===0)return;if(!a){o();return}const w=n(e);w&&(i(w.tabKey,r),g.current=!0,k.current=!0,h.current!=null&&(window.clearTimeout(h.current),h.current=null),c(b=>{const j=new URLSearchParams(b);return j.delete("activeTab"),j},{replace:!0}))},[e,t,n,r,a,o,i,c]),l.useEffect(()=>{if(!(k.current||a)&&t.length!==0){if(!e){o(),k.current=!0;return}if(g.current){k.current=!0;return}if(h.current==null)return h.current=window.setTimeout(()=>{h.current=null,!(k.current||a)&&(o(),k.current=!0)},1500),()=>{h.current!=null&&(window.clearTimeout(h.current),h.current=null)}}},[e,t.length,a,o]),l.useEffect(()=>{if(!d){v.current=!1;return}if(!p||v.current||u)return;const w=m.find(b=>b.id===p.routeId);w&&(!w.chats||w.chats.length===0||xj(w.chats,p))&&(v.current=!0,f())},[d,p,u,m,f])}function So(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 r=Fa(t);return typeof(n==null?void 0:n.id)=="string"&&r.includes(n.id)}function cm({sendDaemonCommand:e,activeConv:t,chats:n,updateRouteChats:r,setToasts:a,setClearedTabs:o}){const[i,c]=l.useState(!1),[d,p]=l.useState(!1),u=l.useCallback(async k=>{try{await e("standalone","launch_ide",{ideType:k,enableCdp:!0})}catch(h){console.error("Launch failed",h)}},[e]),m=l.useCallback(async(k,h)=>{try{const v=k||(t==null?void 0:t.daemonId)||"",w=await e(v,"switch_chat",{id:h,sessionId:h,...Xs(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"?vn(a,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?vn(a,`⚠️ Switch error: ${b}`):vn(a,"⚠️ Session switch failed")}catch(v){console.error("Switch failed",v),vn(a,`❌ Switch failed: ${v.message||"connection error"}`)}},[t,e,a]),f=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const k=Zs(t);await e(k,"new_chat",{...Xs(t)}),ik(k,t.sessionId,Fa(t)[0]),o(h=>({...h,[t.tabKey]:Date.now()}))}catch(k){console.error("New chat failed",k)}finally{c(!1)}}},[t,i,e,o]),g=l.useCallback(async()=>{var k,h;if(!(!t||d)){p(!0);try{const v=Zs(t),w=async()=>e(v,"list_chats",{forceExpand:!0,...Xs(t)});let b=await w(),j=(b==null?void 0:b.chats)||((k=b==null?void 0:b.result)==null?void 0:k.chats);So(j,t)&&(await new Promise(C=>setTimeout(C,450)),b=await w(),j=(b==null?void 0:b.chats)||((h=b==null?void 0:b.result)==null?void 0:h.chats)),b!=null&&b.success&&Array.isArray(j)&&(r(t.routeId,j),So(j,t)&&!So(n,t)&&vn(a,"⚠️ History dialog did not fully open — try once more"))}catch(v){console.error("Refresh history failed",v)}finally{p(!1)}}},[t,n,d,e,r,a]);return{isCreatingChat:i,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:m,handleNewChat:f,handleRefreshHistory:g}}function yj(e,t){if(e.size!==t.size)return!1;for(const[n,r]of e)if(t.get(n)!==r)return!1;return!0}function wj(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function Jc(e,t){const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(a=>t[Number(a)]===e[Number(a)])}function Wr(e,t){const n=new Set(t),r=t.length>0?[0]:[];for(const[i,c]of e)!n.has(i)||c<=0||r.includes(c)||r.push(c);r.sort((i,c)=>i-c);const a={};r.forEach((i,c)=>{a[i]=c}),r.length===0&&(a[0]=0);const o=new Map;for(const[i,c]of e){if(!n.has(i)||c<=0)continue;const d=a[c];typeof d=="number"&&d>0&&o.set(i,d)}return{assignments:o,groupCount:Math.max(1,r.length),mapping:a,usedGroups:r}}function Qc(e,t){const n={};for(const[r,a]of Object.entries(e)){const o=t[Number(r)];typeof o=="number"&&(n[o]=a)}return n}function kj(e,t,n){if(t.length===0)return 0;if(typeof n[e]=="number")return n[e];const r=[...t].reverse().find(a=>a<e)??t[0];return n[r]??0}function Sj(e,t,n){if(t.length<=1)return[];const r=t.map(i=>e[i]).filter(i=>Number.isFinite(i)),a=r.length===t.length?r:Array(n).fill(100/n),o=a.reduce((i,c)=>i+c,0);return o>0?a.map(i=>i/o*100):Array(n).fill(100/n)}function Xc(e,t){const n={};for(const[r,a]of Object.entries(e)){const o=Number(r);n[o>=t?o+1:o]=a}return n}function Zc(e){return Array(e).fill(100/e)}function Cj({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:n,updateGroupActiveTabIds:r,updateGroupTabOrders:a,groupSizes:o,updateGroupSizes:i,isMobile:c,visibleConversations:d,visibleTabKeys:p}){const u=l.useRef(null),m=l.useMemo(()=>Wr(e,p),[e,p]),f=m.assignments,g=l.useMemo(()=>c?1:m.groupCount,[m.groupCount,c]),k=g>1,h=l.useCallback((y,x)=>{t(N=>{const S=new Map(Wr(N,p).assignments);return x===0?S.delete(y):S.set(y,x),S}),r(N=>({...N,[x]:y})),n(x)},[t,p,r,n]),v=l.useCallback(y=>{t(x=>{const N=Wr(x,p).assignments,S=new Map;for(const[A,T]of N)T!==y&&(T>y?S.set(A,T-1):S.set(A,T));return S}),i(x=>{if(x.length<=1)return[];const N=[...x];N.splice(y,1);const S=N.reduce((A,T)=>A+T,0);return S>0?N.map(A=>A/S*100):[]}),n(0)},[t,p,i,n]),w=l.useCallback((y,x)=>{x.preventDefault();const N=u.current;if(!N)return;const S=x.clientX,A=N.offsetWidth,T=o.length===g?[...o]:Zc(g),I=P=>{const G=(P.clientX-S)/A*100,H=[...T];H[y]=Math.max(15,T[y]+G),H[y+1]=Math.max(15,T[y+1]-G),i(H)},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((y,x,N)=>{if(g>=4)return;const S=N==="left"?x:x+1;t(A=>{const T=Wr(A,p).assignments,I=new Map;for(const D of d){const P=T.get(D.tabKey)??0,_=P>=S?P+1:P;_>0&&I.set(D.tabKey,_)}return S>0&&I.set(y,S),I}),i(A=>{const T=A.length===g?[...A]:Zc(g),I=T[x]??100/g,D=Math.max(15,I/2),P=Math.max(15,I/2),_=[...T];_[x]=D,_.splice(S,0,P);const G=_.reduce((H,L)=>H+L,0);return _.map(H=>H/G*100)}),r(A=>{const T=Xc(A,S);return T[S]=y,T}),a(A=>{const T=Xc(A,S);return T[S]=[y],T}),n(S)},[g,t,p,d,i,r,a,n]);l.useEffect(()=>{yj(e,f)||t(f)},[e,f,t]),l.useEffect(()=>{const{mapping:y,usedGroups:x}=m;r(N=>{const S=Qc(N,y);return Jc(N,S)?N:S}),a(N=>{const S=Qc(N,y);return Jc(N,S)?N:S}),n(N=>{const S=c?0:kj(N,x,y);return N===S?N:S}),i(N=>{const S=c?[]:Sj(N,x,m.groupCount);return wj(N,S)?N:S})},[m,c,r,a,n,i]);const j=l.useMemo(()=>{const y=Array.from({length:g},()=>[]);for(const x of d){const N=f.get(x.tabKey)??0,S=Math.min(N,g-1);y[S].push(x)}return y},[d,f,g]),C=l.useCallback(()=>{t(new Map),n(0)},[t,n]);return{containerRef:u,normalizedGroupAssignments:f,numGroups:g,isSplitMode:k,groupedConvs:j,moveTabToGroup:h,closeGroup:v,handleResizeStart:w,splitTabRelative:b,clearAllSplits:C}}function Co(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 jj(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 Ur(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function ml(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},n=Co(t.channel)||Co(e.updateChannel)||Co(e.releaseChannel)||void 0,r=jj(t.npmTag)||(n==="preview"?"next":n==="stable"?"latest":void 0),a=Ur(t.targetVersion)||Ur(e.serverVersion)||void 0,o=Ur(t.minVersion)||void 0,i=Ur(t.updateCommand)||(n?`adhdev update --channel ${n}`:void 0);return{...n?{channel:n}:{},...r?{npmTag:r}:{},...a?{targetVersion:a}:{},...o?{minVersion:o}:{},...i?{updateCommand:i}:{}}}function kn(e,t=null){return ml(e).targetVersion||t}function dm(e){return ml(e).channel||null}function um(e){const t=ml(e);return{...t.channel?{channel:t.channel}:{},...t.npmTag?{npmTag:t.npmTag}:{},...t.targetVersion?{targetVersion:t.targetVersion}:{},...Object.keys(t).length>0?{updatePolicy:t}:{}}}function Nj({ides:e,sendDaemonCommand:t}){const n="1.0.26",r=l.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:ll(m,kn(m,n))).sort((m,f)=>Number(ur(f,kn(f,n)))-Number(ur(m,kn(m,n)))),[n,e]),a=l.useMemo(()=>r.some(m=>ur(m,kn(m,n))),[n,r]),o=l.useMemo(()=>r.map(m=>kn(m,n)).find(m=>typeof m=="string"&&m.trim().length>0)||n,[n,r]),[i,c]=l.useState(!1),[d,p]=l.useState({}),u=l.useCallback(async m=>{var g,k;const f=e.find(h=>h.id===m);if(f){p(h=>({...h,[m]:"upgrading"}));try{const h=await t(m,"daemon_upgrade",um(f));(g=h==null?void 0:h.result)!=null&&g.upgraded||(k=h==null?void 0:h.result)!=null&&k.success?p(v=>({...v,[m]:"done"})):p(v=>({...v,[m]:"error"}))}catch{p(h=>({...h,[m]:"error"}))}}},[e,t]);return{versionMismatchDaemons:r,hasRequiredVersionDaemons:a,targetVersion:o,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:u}}const pm=80;function ia(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function Aj(e){return{...e,createdAt:ia(e.createdAt),updatedAt:ia(e.updatedAt,e.createdAt),lastEventAt:ia(e.lastEventAt,e.updatedAt||e.createdAt)}}function Tj(e){const t=$u(e);return t==="unknown:"?e.id:t}function Mj(e){return[e.type,_u(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Pj(e,t=pm){const n=new Map;for(const r of e){if(r.deletedAt)continue;const a=Tj(r),o=n.get(a);if(!o){n.set(a,r);continue}(r.updatedAt>o.updatedAt||r.updatedAt===o.updatedAt&&r.createdAt>o.createdAt)&&n.set(a,r)}return Array.from(n.values()).sort((r,a)=>{const o=a.updatedAt-r.updatedAt;return o!==0?o:a.createdAt-r.createdAt}).slice(0,Math.max(0,t))}function Dj(e,t){const n=Date.now(),r=[];for(const a of e){const o=a.sessionId?t.get(a.sessionId):void 0;if(o!=null&&o.surfaceHidden||o!=null&&o.muted)continue;const i=Ha(a,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const d=ia(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,n),p=Mj({type:c,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,lastMessageHash:a.lastMessageHash,lastMessageAt:a.lastMessageAt,lastUpdated:(o==null?void 0:o.lastUpdated)||a.lastUpdated});r.push(Aj({id:p,dedupKey:p,type:c,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:np(a),preview:v0(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return Pj(r)}function Ij(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function Lj(e){const{conversations:t,liveSessionInboxState:n,maxItems:r=pm}=e,a=l.useMemo(()=>Dj(t,n).slice(0,Math.max(0,r)),[t,n,r]),o=l.useMemo(()=>Ij(a),[a]);return{notifications:a,unreadCount:o}}function Rj({notifications:e,sendDaemonCommand:t}){const n=l.useCallback(o=>{const i=e.find(d=>d.id===o),c=Math.max(Date.now(),(i==null?void 0:i.updatedAt)||0);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_session_seen",{sessionId:i.sessionId,seenAt:c}).catch(()=>{})},[e,t]),r=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]),a=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:r,handleDeleteDashboardNotification:a}}function hl(...e){const t=new Set,n=[],r=a=>{const o=typeof a=="string"?a.trim():"";if(!o)return;const i=o.toLowerCase();t.has(i)||(t.add(i),n.push(o))};for(const a of e){if(Array.isArray(a)){for(const o of a)r(o);continue}r(a)}return n}function Ej(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 r=n[1].toUpperCase(),a=(n[2]||"").replace(/[\\/]+/g,"\\");return a?`${r}:\\${a}`:`${r}:\\`}return null}function fl(e,t=[]){if(e==="win32"){for(const n of t){if(typeof n!="string")continue;const r=Ej(n);if(r)return r}return"C:\\"}for(const n of t){const r=typeof n=="string"?n.trim():"";if(r)return r}return"~"}function _j(e){const t=e.replace(/[\\/]+$/,"");if(!t||t==="/"||/^[A-Za-z]:$/.test(t))return null;const n=t.includes("\\")?"\\":"/",r=t.split(/[\\/]/);return/^[A-Za-z]:$/.test(r[0]||"")?r.length<=2?`${r[0]}\\`:r.slice(0,-1).join("\\"):r.length<=2?n:r.slice(0,-1).join(n)||n}function $j(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function bl(e,t,n){const r=await e(t,"file_list_browse",{path:n}),a=$j(r);if(!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||(r==null?void 0:r.error)||"Could not browse folder");const o=typeof(a==null?void 0:a.path)=="string"?a.path:n,i=o.includes("\\")?"\\":"/",c=(p,u)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${u}`:p==="/"||p==="\\"?`${i}${u}`:`${p.replace(/[\\/]+$/,"")}${i}${u}`,d=Array.isArray(a==null?void 0:a.files)?a.files.filter(p=>(p==null?void 0:p.type)==="directory"&&typeof(p==null?void 0:p.name)=="string").map(p=>({name:p.name,path:typeof(p==null?void 0:p.path)=="string"&&p.path.trim()?p.path:c(o,p.name)})).sort((p,u)=>p.name.localeCompare(u.name)):[];return{path:o,directories:d}}function ed(e,t){const n=t.meshId||"",r={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,(a,o)=>r[o]||"")}function mm(e,t={}){const n=e==null?void 0:e.mcpConfig;if((n==null?void 0:n.mode)!=="manual")return null;const a=ed(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"}).trim();return!a.includes(`
|
|
70
|
+
`)&&!a.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:ed(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"})}}function Hj(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.instructions=="string"?t.instructions:"",r=typeof t.template=="string"?t.template:"";return!n&&!r?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:r}}function wr(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function hm(e){return Ba(e)||e.tabKey||e.routeId||null}function fm(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"",n=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"",r=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"",a=e.conversations.find(o=>{if(r&&o.routeId!==r)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)||r&&o.routeId===r)});if(a!=null&&a.tabKey)return a.tabKey;if(r){const o=fs(e.conversations,r)||e.conversations.find(i=>i.routeId===r);if(o!=null&&o.tabKey)return o.tabKey}return t||n||r||null}function _s(e){return String(e||"").trim()}function bm(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Pa(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Fj(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function Bj(e,t){const n=_s(e.providerSessionId),r=_s(e.targetSessionId),a=t.find(o=>{const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(_s).filter(Boolean);return!!(n&&i.includes(n)||r&&i.includes(r))});return a?a.tabKey:r||n||null}function Oj(e,t,n){if(t.event!=="agent:generating_completed")return null;const r=bm(t.daemonId);if(r&&r!==e.machineId)return null;const a=_s(t.providerType);if(e.providerType&&a!==e.providerType)return null;const o=_s(e.resumeSessionId),i=_s(e.launchedSessionId),c=_s(t.providerSessionId),d=_s(t.targetSessionId);if(o&&o!==c&&o!==d||i&&i!==c&&i!==d)return null;const p=Pa(e.workspacePath);if(p){const u=Pa(t.workspaceName);if(u&&!Fj(u,p))return null}return Bj(t,n)}function td(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Wj({ides:e,conversations:t,onOpenSession:n}){const[r,a]=l.useState(null),o=l.useRef(null),i=l.useCallback(()=>{o.current=null,a(null)},[]),c=l.useCallback(d=>{o.current=d,a(d)},[]);return l.useEffect(()=>{if(!r)return;const d=Pa(r.workspacePath),p=e.find(m=>{var v,w,b,j;if(!m||m.type==="adhdev-daemon"||bm(m.daemonId||m.id)!==r.machineId||(xr(m)?"cli":Nn(m)?"acp":"ide")!==r.kind)return!1;const k=String(m.agentType||m.type||"");if(r.providerType&&k!==r.providerType)return!1;if(r.resumeSessionId)return String(m.providerSessionId||"")===r.resumeSessionId;if(r.launchedSessionId){const C=String(r.launchedSessionId||"");return[m.providerSessionId,m.sessionId,m.instanceId,m.id].map(x=>String(x||"")).filter(Boolean).includes(C)}if(d){const C=Pa(m.workspace||m.runtimeWorkspaceLabel);return C?C===d:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((j=(b=(w=(v=m.activeChat)==null?void 0:v.messages)==null?void 0:w.at)==null?void 0:b.call(w,-1))==null?void 0:j.timestamp)||0)>=r.startedAt-5e3});if(!p)return;const u=fm({entrySessionId:p.sessionId,entryInstanceId:p.instanceId,entryRouteId:p.id,conversations:t});u&&(i(),n(u))},[i,t,e,n,r]),l.useEffect(()=>ht.onStatusEvent(d=>{const p=o.current;if(!p)return;const u=Oj(p,d,t);u&&(i(),n(u))}),[i,t,n]),l.useEffect(()=>{if(!r)return;const d=window.setTimeout(()=>{a(p=>!p||p.startedAt!==r.startedAt?p:(o.current=null,null))},45e3);return()=>window.clearTimeout(d)},[r]),{trackPendingLaunch:c}}function Uj(e,t){var r,a,o,i;const n={cliType:e};return(r=t==null?void 0:t.workspacePath)!=null&&r.trim()?n.dir=t.workspacePath.trim():t!=null&&t.workspaceId?n.workspaceId=t.workspaceId:t!=null&&t.useHome&&(n.useHome=!0),(a=t==null?void 0:t.resumeSessionId)!=null&&a.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 Gj({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:n,activeConv:r,ides:a,setCliViewModeOverrides:o}){const i=Xi(),{launchCli:c}=Ra(),d=l.useCallback(async(v,w)=>bl(e,v,w),[e]),p=l.useCallback(async(v,w)=>{if(!w.trim())return{ok:!1,error:"Choose a workspace path first."};try{const b=await e(v,"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]),u=l.useCallback(async(v,w,b)=>{var j;try{const C={ideType:w,enableCdp:!0};(j=b==null?void 0:b.workspacePath)!=null&&j.trim()&&(C.workspace=b.workspacePath.trim());const y=await e(v,"launch_ide",C);return!(y!=null&&y.success)&&(y==null?void 0:y.success)!==void 0?{ok:!1,error:(y==null?void 0:y.error)||"Could not launch IDE"}:(t({machineId:v,kind:"ide",providerType:w,workspacePath:(b==null?void 0:b.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(C){return{ok:!1,error:C instanceof Error?C.message:"Could not launch IDE"}}},[e,t]),m=l.useCallback(async(v,w,b,j)=>{const C=Date.now();try{const y=Uj(b,j),x=await c(v,y),N=(x==null?void 0:x.result)||x,S=(N==null?void 0:N.sessionId)||(N==null?void 0:N.id);return x!=null&&x.success&&S?(t({machineId:v,kind:w,providerType:b,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,launchedSessionId:S,startedAt:C}),{ok:!0}):x!=null&&x.success?(t({machineId:v,kind:w,providerType:b,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:(x==null?void 0:x.error)||(N==null?void 0:N.error)||`Could not launch ${w.toUpperCase()} session`,code:(x==null?void 0:x.code)||(N==null?void 0:N.code)||void 0}}catch(y){return td(y)?(t({machineId:v,kind:w,providerType:b,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:y instanceof Error?y.message:`Could not launch ${w.toUpperCase()} session`}}},[c,e,t]),f=l.useCallback(async v=>{var w;if(i!=null&&i.listMeshes)return i.listMeshes(v);if(!v)return[];try{const b=await e(v,"list_meshes",{}),j=(b==null?void 0:b.result)??b;if((j==null?void 0:j.success)===!1)throw new Error((j==null?void 0:j.error)||"Could not load meshes");return(Array.isArray(j==null?void 0:j.meshes)?j.meshes:Array.isArray((w=j==null?void 0:j.result)==null?void 0:w.meshes)?j.result.meshes:[]).map(y=>{var x;return{id:String((y==null?void 0:y.id)||""),name:String((y==null?void 0:y.name)||(y==null?void 0:y.id)||"Untitled mesh"),repoIdentity:(y==null?void 0:y.repoIdentity)||(y==null?void 0:y.repo_identity)||null,workspace:Array.isArray(y==null?void 0:y.nodes)&&y.nodes.length>0?String(((x=y.nodes[0])==null?void 0:x.workspace)||""):null,nodesCount:Array.isArray(y==null?void 0:y.nodes)?y.nodes.length:void 0,status:(y==null?void 0:y.status)||null}}).filter(y=>y.id)}catch(b){throw console.error("List meshes failed",b),b}},[i,e]),g=l.useCallback(async(v,w,b,j)=>{var y,x;if(!w.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(v,w,b,j);const C=Date.now();try{const N={meshId:w.trim()};b.trim()&&(N.cliType=b.trim());const S=(y=j==null?void 0:j.initialModel)==null?void 0:y.trim(),A=(x=j==null?void 0:j.initialThinkingLevel)==null?void 0:x.trim();S&&(N.initialModel=S),A&&(N.initialThinkingLevel=A);const T=await e(v,"launch_mesh_coordinator",N),I=(T==null?void 0:T.result)??T;if((I==null?void 0:I.success)===!1||(T==null?void 0:T.success)===!1){const P=String((I==null?void 0:I.code)||(T==null?void 0:T.code)||""),_=Hj((I==null?void 0:I.meshCoordinatorSetup)||(I==null?void 0:I.manualSetup)||(T==null?void 0:T.meshCoordinatorSetup)||(T==null?void 0:T.manualSetup));return{ok:!1,error:(I==null?void 0:I.error)||(T==null?void 0:T.error)||"Could not launch mesh coordinator",code:P||void 0,manualSetup:_}}const D=(I==null?void 0:I.sessionId)||(I==null?void 0:I.id);return D?n(D):t({machineId:v,kind:"cli",providerType:(I==null?void 0:I.cliType)||b.trim()||void 0,workspacePath:(I==null?void 0:I.workspace)||null,startedAt:C}),{ok:!0}}catch(N){return td(N)?(t({machineId:v,kind:"cli",providerType:b.trim()||void 0,startedAt:C}),{ok:!0}):{ok:!1,error:N instanceof Error?N.message:"Could not launch mesh coordinator"}}},[i,n,e,t]),k=l.useCallback(async(v,w)=>{if(!v||!w)return[];try{const b=await e(v,"list_saved_sessions",{providerType:w,kind:"cli",limit:30}),j=(b==null?void 0:b.result)??b;return Array.isArray(j==null?void 0:j.sessions)?j.sessions:[]}catch(b){return console.error("List saved sessions failed",b),[]}},[e]),h=l.useCallback(async v=>{await nm({conversation:r,mode:v,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[r,a,e,o]);return{handleBrowseMachineDirectory:d,handleSaveMachineWorkspace:p,handleLaunchMachineIde:u,handleLaunchMachineProvider:m,handleListMachineMeshes:f,handleLaunchMeshCoordinator:g,handleListMachineSavedSessions:k,setActiveCliViewMode:h}}function qj(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 zj(e,t,n=Date.now()){return!e||!qj(t)?null:{tabKey:e,nonce:n}}function Kj({isMobile:e,conversations:t,visibleConversations:n,groupActiveTabIds:r,focusedGroup:a,groupedConvs:o,setSearchParams:i}){const[c,d]=l.useState(null),[p,u]=l.useState(null),m=l.useMemo(()=>{var v,w;if(!e){if(c){const b=t.find(j=>j.tabKey===c);if(b)return b}return n[0]}const h=r[a];if(h){const b=t.find(j=>j.tabKey===h);if(b)return b}return((v=o[a])==null?void 0:v[0])||((w=o[0])==null?void 0:w[0])},[t,c,a,r,o,e,n]),f=l.useCallback(h=>{d(h)},[]),g=l.useCallback(h=>{d(h.tabKey),i(v=>{const w=new URLSearchParams(v),b=w0(h);return b?w.set("activeTab",b):w.delete("activeTab"),w},{replace:!0})},[i]),k=l.useCallback((h,v)=>{const w=zj(h,v);w&&u(w)},[]);return{activeConv:m,openDesktopConversation:g,requestScrollToBottom:k,scrollToBottomRequest:p,setDesktopActiveTab:f}}function Vj(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 Yj(e){const t=String(e.liveState.completionMarker||""),n=String(e.liveState.seenCompletionMarker||""),r=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,o=[e.tabKey,e.historySessionId||"",t,n,r,a?"1":"0"].join(":");return{shouldMarkSeen:!!(r==="task_complete"&&a&&(!t||t!==n)),autoReadKey:o,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function Jj({activeConv:e,isMobile:t,liveSessionInboxState:n,sendDaemonCommand:r}){const a=l.useRef(null),o=l.useRef(null),i=l.useRef(null),c=l.useRef(null),d=l.useRef(null);l.useEffect(()=>{const p=()=>{i.current&&(clearTimeout(i.current),i.current=null),c.current&&(clearTimeout(c.current),c.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),o.current=null};if(t){p(),a.current=null;return}if(!(e!=null&&e.sessionId)){p(),a.current=null;return}const u=Os(e,n),m=Yj({tabKey:e.tabKey,historySessionId:Ba(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:nn(e),liveState:u}),f=m.autoReadKey,g=Vj({autoReadKey:f,shouldMarkSeen:m.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!m.shouldMarkSeen){g.shouldCancelPending&&p(),a.current=f;return}if(!g.shouldSchedule)return;g.shouldCancelPending&&p();const k=()=>{if(document.visibilityState!=="visible"||a.current===f)return;a.current=f,o.current=null,i.current=null,c.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const v=m.readAt;r(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:v,completionMarker:m.completionMarker}).catch(()=>{})};if(o.current=g.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(k,1500);const v=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};d.current=v,document.addEventListener("visibilitychange",v);return}const h=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(k,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=h,document.addEventListener("visibilitychange",h)},[e,t,n,r]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current),c.current&&clearTimeout(c.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function jo(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 Qj({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:n,ides:r,sendDaemonCommand:a,updateRouteChats:o,setToasts:i,setClearedTabs:c,setSearchParams:d}){var O;const{launchCli:p}=Ra(),[u,m]=l.useState(!1),[f,g]=l.useState([]),[k,h]=l.useState(()=>Wt()),[v,w]=l.useState(!1),[b,j]=l.useState(null),C=l.useRef(null),y=l.useMemo(()=>n||t||e,[e,n,t]),x=!!y&&mt(y)&&!dt(y),N=l.useMemo(()=>{if(!y||!x)return null;const E=y.daemonId||y.routeId||"",M=Cs(y),$=jo(y);return`${E}:${M}:${y.providerSessionId||""}:${$}`},[y,x]),S=l.useMemo(()=>!y||!x?"":jo(y),[y,x]),{isCreatingChat:A,isRefreshingHistory:T,handleSwitchSession:I,handleNewChat:D,handleRefreshHistory:P}=cm({sendDaemonCommand:a,activeConv:y,chats:(O=r.find(E=>E.id===(y==null?void 0:y.routeId)))==null?void 0:O.chats,updateRouteChats:o,setToasts:i,setClearedTabs:c}),_=l.useCallback(()=>{m(!0)},[]),G=l.useCallback(()=>{m(!1)},[]),H=l.useCallback(async()=>{if(!(!y||!x||v)){w(!0);try{const E=y.daemonId||y.routeId,M=Cs(y),$=jo(y),R=await a(E,"list_saved_sessions",{agentType:M,providerType:M,kind:"cli",limit:50,...y.providerSessionId?{providerSessionId:y.providerSessionId}:{},...$?{workspace:$}:{}}),z=(R==null?void 0:R.result)??R;g(Array.isArray(z==null?void 0:z.sessions)?z.sessions:[])}catch(E){console.error("Refresh saved sessions failed",E),g([])}finally{w(!1)}}},[y,v,x,a]);l.useEffect(()=>{if(!u){C.current=null;return}if(!x){C.current=null,g([]),w(!1);return}!N||v||C.current!==N&&(C.current=N,H())},[H,u,v,x,N]);const L=l.useCallback(async E=>{if(!y||!x||!E.providerSessionId||!E.workspace)return;const M=y.daemonId||y.routeId,$=Cs(y);try{j(E.providerSessionId);const R=await p(M,{cliType:$,dir:E.workspace,resumeSessionId:E.providerSessionId,initialModel:Wu(E.summaryMetadata,"model",{preferShortValue:!0})||void 0}),z=(R==null?void 0:R.result)??R,Q=typeof(z==null?void 0:z.sessionId)=="string"?z.sessionId:typeof(z==null?void 0:z.id)=="string"?z.id:"";Q&&d(ne=>{const J=new URLSearchParams(ne);return J.set("activeTab",Q),J},{replace:!0}),G()}catch(R){console.error("Resume saved session failed",R)}finally{j(null)}},[G,y,x,a,d]);return{historyModalOpen:u,openHistoryModal:_,closeHistoryModal:G,historyTargetConv:y,isSavedSessionHistoryTarget:x,isHistoryCreatingChat:A,isHistoryRefreshingHistory:T,handleHistorySwitchSession:I,handleHistoryNewChat:D,handleHistoryRefresh:P,savedHistorySessions:f,savedHistoryFilters:k,setSavedHistoryFilters:h,missingWorkspaceResumePath:S,isSavedHistoryLoading:v,resumingSavedHistorySessionId:b,handleRefreshSavedHistory:H,handleResumeSavedHistorySession:L}}function Xj({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}){const[d,p]=l.useState(null),[u,m]=l.useState(null),f=l.useMemo(()=>{if(e||!r)return null;const w=c(r);return w&&!mt(w)&&!dt(w)?w:null},[e,r,c]),g=l.useMemo(()=>{const w=d==null?void 0:d.routeId;if(!w)return null;const b=d!=null&&d.tabKey?o.find(j=>j.tabKey===d.tabKey):a?o.find(j=>j.tabKey===a):null;return(b==null?void 0:b.routeId)===w?b:fs(o,w)},[o,d,a]),k=l.useMemo(()=>{if(g)return i.find(w=>w.id===g.routeId)},[i,g]);l.useEffect(()=>{f&&(p({routeId:f.routeId,tabKey:fc(f)}),m(f),n({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,n,f]);const h=l.useCallback(w=>{w&&(p({routeId:w.routeId,tabKey:fc(w)}),m(w))},[]),v=l.useCallback(()=>{p(null),m(null)},[]);return{remoteDialogConv:g,remoteDialogIdeEntry:k,remoteDialogActiveConv:u,setRemoteDialogActiveConv:m,openRemoteDialog:h,closeRemoteDialog:v}}function Zj({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c,activeConv:d,sendDaemonCommand:p}){const{remoteDialogConv:u,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:g,openRemoteDialog:k,closeRemoteDialog:h}=Xj({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}),[v,w]=l.useState(!1),[b,j]=l.useState(null),C=l.useCallback(async N=>{const S=N||d;!S||!mt(S)&&!dt(S)||(j(S),w(!0))},[d]),y=l.useCallback(()=>{w(!1),j(null)},[]),x=l.useCallback(async N=>{const S=b||d;if(!S||!mt(S)&&!dt(S)){y();return}w(!1);try{const A=Cs(S),T=S.routeId||S.daemonId||"";await p(T,"stop_cli",{cliType:A,targetSessionId:S.sessionId,mode:N,...Ua(S)})}catch(A){console.error("Stop CLI failed:",A)}finally{j(null)}},[d,y,b,p]);return{remoteDialogConv:u,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:g,openRemoteDialog:k,closeRemoteDialog:h,cliStopDialogOpen:v,cliStopTargetConv:b,requestCliStop:C,cancelCliStop:y,confirmCliStop:x}}function No(e,t=!0){return(e??!0)&&t}const gl=l.memo(function({activeConv:t,clearToken:n,isCliTerminal:r,ideEntry:a,terminalRef:o,handleModalButton:i,handleRelaunch:c,handleSendChat:d,handleForceSendChat:p,isSendingChat:u,sendFeedbackMessage:m=null,handleFocusAgent:f,isFocusingAgent:g,actionLogs:k,userName:h,scrollToBottomRequestNonce:v,isInputActive:w=!0,isVisible:b=!0}){const j=r,C=!r,y=No(b,j),x=No(b,C),N=No(b),S=em(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(Lu,{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(on,{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":!r,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:j?"visible":"hidden",pointerEvents:j?"auto":"none"},children:s.jsx(sS,{activeConv:A,clearToken:n,terminalRef:o,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:m,isVisible:y,isInputActive:w&&y})}),s.jsx("div",{"aria-hidden":r,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:C?"visible":"hidden",pointerEvents:C?"auto":"none"},children:s.jsx(xi,{activeConv:A,ideEntry:a,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:k,userName:h,scrollToBottomRequestNonce:v,isInputActive:w&&x,isVisible:x})})]}):s.jsx(xi,{activeConv:A,ideEntry:a,handleSendChat:d,handleForceSendChat:p,isSendingChat:u,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:k,userName:h,scrollToBottomRequestNonce:v,isInputActive:w&&N,isVisible:N})]})},(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 e1({conversation:e,className:t="",onOpenNativeConversation:n,onOpenMachine:r,interactive:a=!0,meshOnly:o=!1}){var C,y,x;const{t:i}=Ce("common"),c=Cr(),d=Ds(e),p=o?null:sp(e),u=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),m=!o&&e.streamSource==="agent-stream"&&!!e.agentName,f=!o&&!m&&(e.transport==="pty"||e.transport==="acp"),g=Dn(e),k=y0(e),h=(C=e.settings)==null?void 0:C.meshNodeFor,v=e.meshQueueStats,w=((y=e.coordinator)==null?void 0:y.meshId)||((x=e.settings)==null?void 0:x.meshCoordinatorFor),b=l.useCallback(()=>{if(r){r();return}d&&c("/dashboard",{state:{openMachineId:d}})},[d,c,r]),j=l.useCallback(()=>{if(n){n();return}const N=hm(e);N&&c(wr(N))},[e,c,n]);return!u&&!m&&!f&&!p&&!h&&!v?null:s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[u&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:j,title:k,children:[s.jsx(gs,{size:12}),s.jsx("span",{children:k})]}):s.jsxs("span",{className:"conversation-meta-chip",title:k,children:[s.jsx(gs,{size:12}),s.jsx("span",{children:k})]})),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(br,{size:12}),s.jsx("span",{children:g})]}),f&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(br,{size:12}),s.jsx("span",{children:g})]}),p&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:b,title:p,children:[s.jsx(Fs,{size:12}),s.jsx("span",{children:p})]}):s.jsxs("span",{className:"conversation-meta-chip",title:p,children:[s.jsx(Fs,{size:12}),s.jsx("span",{children:p})]})),h&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(Fs,{size:12}),s.jsx("span",{children:i("dashboard.metaChips.meshNode")})]}),w&&v&&s.jsxs("span",{className:`conversation-meta-chip ${v.pending>0?"is-active":""}`,style:v.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${v.pending} pending, ${v.assigned} assigned, ${v.completed} completed, ${v.failed} failed`,children:[s.jsx(Yf,{size:12}),s.jsxs("span",{children:[v.pending," Pending"]})]})]})}function t1({selectedConversation:e,isAcp:t,isStandalone:n,selectedIdeEntry:r,actionLogs:a,userName:o,isSendingChat:i,sendFeedbackMessage:c=null,isFocusingAgent:d,onBack:p,onOpenNativeConversation:u,onOpenMachine:m,onOpenHistory:f,onOpenRemote:g,onOpenMeshGraph:k,onStopCli:h,cliViewMode:v,onSetCliViewMode:w,handleSendChat:b,handleForceSendChat:j,handleFocusAgent:C,handleModalButton:y,handleRelaunch:x}){var D,P;const N=l.useRef(null),S=mt(e)&&!t,A=S&&v==="terminal",T=!!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(Fi,{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:yt(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(e1,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>m(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[S&&v&&s.jsx(Lp,{mode:v,onChange:w,compact:!0}),S&&h&&s.jsx("button",{onClick:()=>{h(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(Tt,{size:14})}),T&&k&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>k(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(rs,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",children:s.jsx(Oi,{size:14})}),!t&&!S&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",children:s.jsx(gs,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(gl,{activeConv:e,clearToken:0,isCliTerminal:A,ideEntry:r,terminalRef:N,handleModalButton:y,handleRelaunch:x,handleSendChat:b,handleForceSendChat:j,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:C,isFocusingAgent:d,actionLogs:a,userName:o})})]})}const Ao={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 s1(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function gm(){const[e,t]=l.useState("unix"),[n,r]=l.useState("powershell"),[a,o]=l.useState(!1),i=e==="unix"?"unix":n;l.useEffect(()=>{t(s1())},[]);const c=l.useCallback(()=>{navigator.clipboard.writeText(Ao[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:()=>r("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:()=>r("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:Ao[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:Ao[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:a?"✓":"📋"})]}),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 xm({section:e,onSectionChange:t}){const n=[{key:"machines",label:"Machines",icon:gs},{key:"chats",label:"Chats",icon:un}];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:r,label:a,icon:o})=>{const i=e===r;return s.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${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(r),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:a})]},r)})})})}function Gr({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 bn({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 Xn({icon:e,title:t,subtitle:n,children:r}){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}),r]})}function n1({conversation:e,onCancel:t,onConfirm:n}){const{t:r}=Ce(),a=yt(e);return 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:r("mobileInbox.hideTitle",{title:a})}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:r("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:r("mobileInbox.hide")}),s.jsx("button",{onClick:t,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:r("common.cancel")})]})]})]})}function qr({item:e,type:t,getAvatarText:n,onOpenConversation:r,onRequestHideConversation:a,onRequestStopCli:o,onOpenMeshGraph:i,onCollectChatDebugBundle:c,isMuted:d,onToggleMute:p}){const{t:u}=Ce(),m=t==="needs_attention"||t==="task_complete",f=t==="working",g=t==="earlier",k=t==="task_complete",{isReconnecting:h,isConnecting:v}=pn(e.conversation),w=yt(e.conversation),b=In(e.conversation),j=Mp(e.conversation,{requiresAction:t==="needs_attention"}),C=m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":f?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":g?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",y=m?"bg-accent-primary shadow-glow":f?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":g?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",x=g?"text-text-secondary":"text-text-primary",N=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",T=!f&&!k,I=Ap(e.conversation),D="text-[color:var(--status-warning)]",P=_=>{if(!c)return;_.preventDefault(),_.stopPropagation();const G=c==null?void 0:c(e.conversation);Promise.resolve(G).catch(H=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",H)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${C}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[m||f?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${y}`,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:_=>{_.preventDefault(),_.stopPropagation(),i(e.conversation)},"aria-label":u("mobileInbox.openMeshGraphFor",{title:w}),title:u("mobileInbox.openLiveMeshGraph"),children:s.jsx(rs,{size:13})})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>r(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 ${x}`,children:w})}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${N}`,children:[s.jsx("span",{className:"truncate",children:b}),s.jsx(ka,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),h?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${D} animate-pulse`,children:u("mobileInbox.reconnectingItem")})]}):v?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:u("mobileInbox.connectingItem")})]}):j==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:D,children:u("mobileInbox.actionNeeded")})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${S}`,children:e.preview})]}),s.jsxs("div",{className:"mobile-inbox-corner-actions absolute top-3 right-3 flex items-center gap-1.5",children:[T&&s.jsx("span",{className:`mr-0.5 text-[11px] font-medium shrink-0 ${A}`,children:Du(e.timestamp)}),k&&s.jsx("span",{className:"rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:u("mobileInbox.done")}),p&&s.jsx("button",{type:"button",className:`mobile-inbox-mute-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border transition-colors ${d?"border-amber-500/60 bg-amber-500 text-white hover:bg-amber-600":"border-border-subtle bg-bg-primary/70 text-text-muted hover:border-border-default hover:text-text-primary"}`,onClick:_=>{_.preventDefault(),_.stopPropagation(),p()},"aria-label":d?u("mobileInbox.unmute",{title:w}):u("mobileInbox.mute",{title:w}),title:u(d?"mobileInbox.mutedTitle":"mobileInbox.muteNotifications"),children:d?s.jsx(vu,{size:13}):s.jsx(Hn,{size:13})}),a&&s.jsx("button",{type:"button",className:"mobile-inbox-hide-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:_=>{_.preventDefault(),_.stopPropagation(),a()},"aria-label":u("mobileInbox.hideConversationAria",{title:w}),title:u("mobileInbox.hideConversationTitle"),children:s.jsx(Wi,{size:13})}),o&&s.jsx("button",{type:"button",className:"mobile-inbox-stop-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-status-error/30 bg-bg-primary/70 text-status-error transition-colors hover:border-status-error/60 hover:bg-status-error/10",onClick:_=>{_.preventDefault(),_.stopPropagation(),o()},"aria-label":u("mobileInbox.stopSessionAria",{title:w}),title:u("mobileInbox.stopSessionTitle"),children:s.jsx(Tt,{size:13})})]})]})},e.conversation.tabKey)}function sd({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 nd({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 r1({section:e,attentionItems:t,unreadItems:n,workingItems:r,completedItems:a,hiddenConversations:o,machineCards:i,getAvatarText:c,actionLogs:d,sendDaemonCommand:p,onOpenConversation:u,onShowAllHidden:m,onHideConversation:f,onOpenMeshGraph:g,onStopCli:k,onOpenNewSession:h,onOpenMachine:v,onOpenSettings:w,onSectionChange:b,wsStatus:j="connected",isStandalone:C=!1,onCollectChatDebugBundle:y,isConversationMuted:x,onToggleMuteConversation:N}){const{t:S}=Ce(),[A,T]=l.useState(null),I=j==="disconnected"||j==="reconnecting"||j==="offline"||j==="auth_failed",D=i.length>0,P=t.length>0||n.length>0||r.length>0||a.length>0,_=S(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),G=C?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",H=C?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",L=l.useCallback(async M=>{const $=Zs(M);if(!$)return;const R=Array.isArray(M.messages)?M.messages:[],z=cp({activeConv:M,visibleMessages:R,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:R.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),Q=await p($,"get_chat_debug_bundle",{...Xs(M),delivery:"daemon_file",frontendSnapshot:z}),ne=dr(Q),J=pp(ne),Z=await up(J);Z==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),ht.showToast(dp(ne,{locatorCopyStatus:Z}),Z==="failed"?"warning":"success")},[d,p]),O=y||L,E=l.useCallback(()=>{A&&(f==null||f(A),T(null))},[A,f]);return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${G}`,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:_}),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(Hn,{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(Ea,{size:18})})]})]})}),s.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${H}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:I?s.jsx(Xn,{icon:s.jsx(sd,{}),title:S(j==="offline"?"mobileInbox.networkOffline":j==="auth_failed"?"mobileInbox.sessionExpired":"mobileInbox.reconnecting"),subtitle:S(j==="offline"?"mobileInbox.waitingForNetwork":j==="auth_failed"?"mobileInbox.pleaseLogInAgain":"mobileInbox.restoringConnection")}):i.length===0?s.jsx(Xn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:S(C?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:S(C?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!C&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(gm,{})})}):s.jsx(bn,{children:i.map((M,$)=>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] ${$>0?"border-t border-border-subtle/70":""}`,onClick:()=>v(M.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(M.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:M.label}),s.jsxs("span",{className:"flex items-center gap-2 text-[11px] font-medium text-text-muted shrink-0",children:[s.jsx(nd,{count:M.generatingCount,label:S("mobileInbox.generatingCount",{count:M.generatingCount})}),M.unread>0?s.jsx("span",{className:"text-accent-primary",children:S("mobileInbox.newCount",{count:M.unread})}):M.total>0?S("mobileInbox.chatCount",{count:M.total}):S("mobileInbox.idle")]})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:M.subtitle}),M.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[S("mobileInbox.chatCount",{count:M.total}),M.unread>0?S("mobileInbox.unreadSuffix",{count:M.unread}):"",M.generatingCount>0?S("mobileInbox.collapsedGeneratingSuffix",{count:M.generatingCount}):""]}):M.generatingCount>0?s.jsx("div",{className:"text-[13px] text-accent-primary mt-0.5 font-medium",children:S("mobileInbox.generatingCount",{count:M.generatingCount})}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:S("mobileInbox.noActiveChats")})]})]},M.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(Gr,{title:S("mobileInbox.needsAttention"),className:"mb-0"}),s.jsx(bn,{children:t.map((M,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(qr,{item:M,type:"needs_attention",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>T(M.conversation):void 0,onRequestStopCli:k?()=>k(M.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:O,isMuted:x==null?void 0:x(M.conversation),onToggleMute:N?()=>N(M.conversation):void 0})},M.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(Gr,{title:S("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),s.jsx(bn,{children:n.map((M,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(qr,{item:M,type:"task_complete",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>T(M.conversation):void 0,onRequestStopCli:k?()=>k(M.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:O,isMuted:x==null?void 0:x(M.conversation),onToggleMute:N?()=>N(M.conversation):void 0})},M.conversation.tabKey))})]}),e==="chats"&&r.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(Gr,{title:S("mobileInbox.workingNow"),className:"mb-0 mt-2"}),s.jsx(bn,{children:r.map((M,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(qr,{item:M,type:"working",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>T(M.conversation):void 0,onRequestStopCli:k?()=>k(M.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:O,isMuted:x==null?void 0:x(M.conversation),onToggleMute:N?()=>N(M.conversation):void 0})},M.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&s.jsx(Gr,{title:S("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(bn,{children:a.map((M,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(qr,{item:M,type:"earlier",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>T(M.conversation):void 0,onRequestStopCli:k?()=>k(M.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:O,isMuted:x==null?void 0:x(M.conversation),onToggleMute:N?()=>N(M.conversation):void 0})},M.conversation.tabKey))}):P?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:S("mobileInbox.allCaughtUp")}):I?s.jsx(Xn,{icon:s.jsx(sd,{size:28}),title:S("mobileInbox.connecting"),subtitle:S("mobileInbox.connectingSubtitle")}):D?s.jsx(Xn,{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(un,{size:20})}),title:S("mobileInbox.noConversations"),subtitle:S("paneGroup.newSessionDescription"),children:h&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:h,"aria-label":S("paneGroup.newSession"),title:S("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:S("paneGroup.newSession")})]})}):s.jsx(Xn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:S("mobileInbox.noMachinesConnected"),subtitle:S("mobileInbox.noMachinesSubtitle")})]}),e==="chats"&&o.length>0&&(()=>{const M=Kb(o);return s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(bn,{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:S("mobileInbox.hiddenTabs")}),s.jsx(nd,{count:M,label:S("mobileInbox.generatingCount",{count:M})})]}),s.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[S("mobileInbox.collapsedCount",{count:o.length}),M>0?S("mobileInbox.collapsedGeneratingSuffix",{count:M}):""]})]}),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:S("mobileInbox.restoreAll")})]})})})})()]}),e==="chats"&&h&&P&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:h,"aria-label":S("paneGroup.newSession"),title:S("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"})]})}),A&&s.jsx(n1,{conversation:A,onCancel:()=>T(null),onConfirm:E}),s.jsx(xm,{section:e,onSectionChange:b})]})}function a1(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 vm(e){const t=[e.workspace||"Workspace unknown"],n=ln(e.summaryMetadata);n&&t.push(n),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const r=a1(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:r?`Updated ${r}`:"",preview:(e.preview||"").trim()}}function xl({title:e,description:t,currentPath:n,directories:r,busy:a=!1,error:o="",confirmLabel:i="Use this folder",onClose:c,onNavigate:d,onConfirm:p}){const[u,m]=l.useState(n),{t:f}=Ce("common");l.useEffect(()=>{m(n)},[n]);const g=_j(n),k=u.trim();return 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(Tt,{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||a||d(g)},disabled:!g||a,children:[s.jsx(Fi,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:f("machine.workspaceBrowse.currentFolder")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:u,onChange:h=>m(h.target.value),onKeyDown:h=>{h.key!=="Enter"||!k||a||(h.preventDefault(),d(k))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!k||a||d(k)},disabled:!k||a,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?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}):r.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:r.map(h=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>d(h.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Pn,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:h.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:h.path})]})]},h.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:c,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>p(k||n),disabled:!k&&!n||a,children:i})]})]})})}function vl({title:e,description:t,details:n,workspaceOptions:r,selectedWorkspaceKey:a,onWorkspaceChange:o,confirmLabel:i,busyLabel:c,busy:d=!1,showArgsInput:p,argsValue:u,onArgsChange:m,showModelInput:f,modelValue:g,onModelChange:k,historyProviderNode:h,onConfirm:v,onCancel:w}){const{t:b}=Ce("common"),j=i??b("machine.launchConfirm.launch"),C=c??b("machine.launchConfirm.launching"),y=r==null?void 0:r.find(x=>x.key===a);return 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(Tt,{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:[r&&r.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:a||"",onChange:x=>o(x.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:d,children:r.map(x=>s.jsx("option",{value:x.key,children:x.label},x.key))}),(y==null?void 0:y.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:y.description})]}),h,n.map(x=>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:x.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:x.value})]},`${x.label}:${x.value}`)),f&&k&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.languageModel")}),s.jsx("input",{type:"text",value:g||"",onChange:x=>k(x.target.value),placeholder:b("machine.launchConfirm.autoDetect"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]}),p&&m&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.cliArgs")}),s.jsx("input",{type:"text",value:u||"",onChange:x=>m(x.target.value),placeholder:b("machine.launchConfirm.cliArgsPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:w,disabled:d,children:b("machine.launchConfirm.cancel")}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:v,disabled:d,children:[s.jsx(xu,{size:14}),d?C:j]})]})]})})}function rd(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function ym(e){const{machine:t,currentWorkspacePath:n,currentWorkspaceId:r,includeHome:a=!0,homeLabel:o="Home directory",homeDescription:i="Launch without a workspace"}=e,c=[];a&&c.push({key:"__home__",label:o,description:i,workspaceId:null,workspacePath:null});for(const u of t.workspaces||[])c.push({key:`saved:${u.id}`,label:`${u.id===t.defaultWorkspaceId?"⭐ ":""}${rd(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const d=(n==null?void 0:n.trim())||"",p=d?(t.workspaces||[]).find(u=>u.path===d):null;if(d&&!p&&c.push({key:`custom:${d}`,label:rd(d),description:d,workspaceId:null,workspacePath:d}),r){const u=`saved:${r}`;if(c.some(m=>m.key===u))return{options:c,selectedKey:u}}return p?{options:c,selectedKey:`saved:${p.id}`}:d?{options:c,selectedKey:`custom:${d}`}:{options:c,selectedKey:"__home__"}}function o1(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function i1(e){return[o1(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function l1(e){return e.lastLaunchedAt?$a(e.lastLaunchedAt):""}function wm(e){return{metaText:i1(e),updatedLabel:l1(e)}}function To(e,t,n){return e?"ide":t>0?"cli":n>0?"acp":null}function c1({selectedMachineEntry:e,cliProviders:t,acpProviders:n,machineAction:r,onBrowseDirectory:a,onListSavedSessions:o}){var he,Ee,Be,at;const i=Bn(),[c,d]=l.useState(!1),p=(((he=e.detectedIdes)==null?void 0:he.length)||0)>0,u=l.useMemo(()=>(e.workspaces||[]).map(oe=>({id:oe.id,path:oe.path,label:oe.label})),[e]),m=e.defaultWorkspaceId||null,[f,g]=l.useState(m||((Ee=u[0])==null?void 0:Ee.id)||""),[k,h]=l.useState(""),[v,w]=l.useState(""),[b,j]=l.useState([]),[C,y]=l.useState(!1),[x,N]=l.useState(""),[S,A]=l.useState(!1),[T,I]=l.useState(To(p,t.length,n.length)),D=l.useRef(null),[P,_]=l.useState(null),G=l.useRef("__home__"),[H,L]=l.useState("__home__"),[O,E]=l.useState(""),[M,$]=l.useState(""),[R,z]=l.useState(""),[Q,ne]=l.useState([]),[J,Z]=l.useState(()=>Wt().textQuery),[de,te]=l.useState(()=>Wt().workspaceQuery),[B,ie]=l.useState(()=>Wt().modelQuery),[Y,le]=l.useState(()=>Wt().resumableOnly),[Ne,we]=l.useState(()=>Wt().sortMode),[Se,me]=l.useState(!1),[q,W]=l.useState(!1),X=l.useRef(null),K=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const ue=f==="__custom__"?k.trim():((Be=u.find(oe=>oe.id===f))==null?void 0:Be.path)||"",Pe=f==="__custom__"&&!!ue&&r.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(r.message),ce=f!=="__custom__"&&((at=u.find(oe=>oe.id===f))==null?void 0:at.path)||"",F=l.useMemo(()=>(e.recentLaunches||[]).map(oe=>oe.workspace),[e]),pe=l.useCallback(async oe=>{y(!0),N("");try{const He=await a(oe);w(He.path),h(He.path),j(He.directories)}catch(He){N(He instanceof Error?He.message:"Could not load folder")}finally{y(!1)}},[a]),xe=l.useCallback(()=>{var He;g("__custom__"),A(!0);const oe=fl(e.platform,hl(k.trim(),ce,F,e.defaultWorkspacePath,(He=u.find(lt=>lt.id===m))==null?void 0:He.path,u.map(lt=>lt.path)));pe(oe)},[k,m,pe,F,ce,e.platform,u]),U=l.useCallback(oe=>{if(oe!=null&&oe.workspaceId){g(oe.workspaceId),h("");return}if(oe!=null&&oe.workspacePath){g("__custom__"),h(oe.workspacePath);return}g(""),h("")},[]),be=l.useCallback(oe=>{if(g(oe),oe==="__custom__"){xe();return}h("")},[xe]),je=l.useCallback(oe=>{g("__custom__"),h(oe)},[]),ge=l.useCallback((oe,He)=>{D.current=He,G.current=oe.selectedWorkspaceKey||"__home__",L(oe.selectedWorkspaceKey||"__home__"),E(oe.initialArgs||""),$(oe.initialModel||""),z(""),ne([]);const lt=oe.providerType?`${e.id}:${oe.providerType}`:null;if(pS(K.current,lt)){const ut=Wt();Z(ut.textQuery),te(ut.workspaceQuery),ie(ut.modelQuery),le(ut.resumableOnly),we(ut.sortMode)}K.current=lt,_(oe),oe.providerType&&o&&(me(!0),o(oe.providerType).then(ut=>ne(ut||[])).catch(ut=>console.warn("Failed to load saved sessions",ut)).finally(()=>me(!1)))},[o,e.id]),Ie=l.useMemo(()=>Rp(Q,{textQuery:J,workspaceQuery:de,modelQuery:B,resumableOnly:Y,sortMode:Ne}),[B,Y,Q,Ne,J,de]);l.useEffect(()=>{R&&(Ie.some(oe=>oe.providerSessionId===R)||z(""))},[Ie,R]);const et=l.useCallback(()=>{D.current&&(W(!0),D.current().finally(()=>{D.current=null,W(!1),_(null)}))},[]),Ze=l.useCallback(()=>{D.current=null,_(null)},[]),rt=l.useCallback(oe=>{G.current=oe,L(oe)},[]);return l.useEffect(()=>{var oe;X.current!==e.id&&(X.current=e.id,g(m||((oe=u[0])==null?void 0:oe.id)||"__custom__"),h(""),w(""),j([]),N(""),A(!1),Z(Wt().textQuery),te(Wt().workspaceQuery),ie(Wt().modelQuery),le(Wt().resumableOnly),we(Wt().sortMode),K.current=null,I(To(p,t.length,n.length)))},[n.length,t.length,m,p,e.id,u]),l.useEffect(()=>{var oe;f!=="__custom__"&&(f&&u.some(He=>He.id===f)||g(m||((oe=u[0])==null?void 0:oe.id)||"__custom__"))},[m,f,u]),l.useEffect(()=>{T==="ide"&&p||T==="cli"&&t.length>0||T==="acp"&&n.length>0||I(To(p,t.length,n.length))},[T,n.length,t.length,p]),{showAllRecent:c,setShowAllRecent:d,hasIdeOptions:p,workspaceRows:u,defaultWorkspaceId:m,workspaceChoice:f,customWorkspacePath:k,browseCurrentPath:v,browseDirectories:b,browseBusy:C,browseError:x,browseDialogOpen:S,activeLauncherKind:T,launchConfirm:P,launchConfirmWorkspaceKeyRef:G,launchConfirmWorkspaceKey:H,launchConfirmArgs:O,launchConfirmModel:M,launchConfirmResumeId:R,launchConfirmSavedSessions:Q,launchConfirmTextFilter:J,launchConfirmWorkspaceFilter:de,launchConfirmModelFilter:B,launchConfirmResumableOnly:Y,launchConfirmSortMode:Ne,filteredLaunchConfirmSavedSessions:Ie,launchConfirmSessionsLoading:Se,launchConfirmBusy:q,resolvedWorkspacePath:ue,canCreateMissingWorkspace:Pe,openBrowseDialog:xe,loadBrowsePath:pe,handleWorkspaceChoiceChange:be,chooseCustomWorkspacePath:je,setCustomWorkspacePath:h,setBrowseDialogOpen:A,setActiveLauncherKind:I,openLaunchConfirm:ge,handleConfirmLaunch:et,closeLaunchConfirm:Ze,setWorkspaceSelectionFromOption:U,setLaunchConfirmWorkspaceKeyAndSync:rt,setLaunchConfirmArgs:E,setLaunchConfirmModel:$,setLaunchConfirmResumeId:z,setLaunchConfirmTextFilter:Z,setLaunchConfirmWorkspaceFilter:te,setLaunchConfirmModelFilter:ie,setLaunchConfirmResumableOnly:le,setLaunchConfirmSortMode:we}}function d1({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:n,cliProviders:r,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:i,machineAction:c,isStandalone:d,section:p,showBottomNav:u,onBack:m,onSectionChange:f,onOpenConversation:g,onOpenRecent:k,onOpenMachineDetails:h,onMachineUpgrade:v,onLaunchDetectedIde:w,onAddWorkspace:b,onBrowseDirectory:j,onLaunchWorkspaceProvider:C,onListSavedSessions:y}){const{t:x}=Ce("common"),N=L=>L==="ide"?"IDE":L==="cli"?"CLI":"ACP",S=n.slice(0,4),A=t.slice(0,3),T=c1({selectedMachineEntry:e,cliProviders:r,acpProviders:a,machineAction:c,onBrowseDirectory:j,onListSavedSessions:y}),I=l.useMemo(()=>S.map(L=>{const{metaText:O,updatedLabel:E}=wm(L);return{key:`recent-launch:${L.id}`,primary:L.label,secondary:O,updatedLabel:E,onClick:()=>{const{options:M,selectedKey:$}=ym({machine:{workspaces:T.workspaceRows,defaultWorkspaceId:T.defaultWorkspaceId},currentWorkspacePath:L.workspace,homeLabel:x("newSession.homeDirectory"),homeDescription:x("newSession.launchWithoutWorkspace")});T.openLaunchConfirm({title:L.kind==="ide"?Sa(x,"restart-ide",L.label):L.providerSessionId?_p(x,L.label):Sa(x,"start-fresh",L.label),description:L.kind==="ide"?Ca(x,"restart-ide"):L.providerSessionId?$p(x):Ca(x,"start-fresh"),confirmLabel:L.kind==="ide"?ja(x,"restart-ide"):L.providerSessionId?vi(x,!0):ja(x,"start-fresh"),busyLabel:L.kind==="ide"?Na(x,"restart-ide"):L.providerSessionId?Ep(x,!0):Na(x,"start-fresh"),workspaceOptions:M,selectedWorkspaceKey:$,details:[{label:"Mode",value:N(L.kind)},...L.providerType?[{label:"Provider",value:L.providerType}]:[]]},async()=>{const R=M.find(z=>z.key===T.launchConfirmWorkspaceKeyRef.current);T.setWorkspaceSelectionFromOption(R),await k({...L,workspace:(R==null?void 0:R.workspacePath)??null})})}}}),[T,k,S,x]),D=l.useMemo(()=>A.map(L=>({key:`recent-chat:${L.conversation.tabKey}`,primary:yt(L.conversation),secondary:Fk(L.conversation,{timestampLabel:L.timestamp?Du(L.timestamp):null}),unread:L.unread,onClick:()=>g(L.conversation)})),[g,A]),P=T.showAllRecent?I:I.slice(0,4),_=I.length>0,G=D.length>0,H=d?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${H} 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(Fi,{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:[G&&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(L=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${L.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:L.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:L.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:L.secondary})]},L.key))})]}),_&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:P.map(L=>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:L.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:L.primary}),L.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:L.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:L.secondary})]},L.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:()=>T.setShowAllRecent(L=>!L),children:T.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:v,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",i]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:h,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),T.browseDialogOpen&&s.jsx(xl,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:T.browseCurrentPath,directories:T.browseDirectories,busy:T.browseBusy,error:T.browseError,confirmLabel:"Use this folder",onClose:()=>T.setBrowseDialogOpen(!1),onNavigate:L=>{T.loadBrowsePath(L)},onConfirm:L=>{T.chooseCustomWorkspacePath(L),T.setBrowseDialogOpen(!1)}}),T.launchConfirm&&s.jsx(vl,{title:T.launchConfirm.title,description:T.launchConfirm.description,details:T.launchConfirm.details,workspaceOptions:T.launchConfirm.workspaceOptions,selectedWorkspaceKey:T.launchConfirmWorkspaceKey,onWorkspaceChange:T.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:T.launchConfirm.providerType?vi(x,!!T.launchConfirmResumeId):T.launchConfirm.confirmLabel,busyLabel:T.launchConfirm.providerType?void 0:T.launchConfirm.busyLabel,busy:T.launchConfirmBusy,showArgsInput:T.launchConfirm.showArgsInput,argsValue:T.launchConfirmArgs,onArgsChange:T.setLaunchConfirmArgs,showModelInput:T.launchConfirm.showModelInput,modelValue:T.launchConfirmModel,onModelChange:T.setLaunchConfirmModel,historyProviderNode:T.launchConfirm.providerType&&(T.launchConfirmSessionsLoading||T.launchConfirmSavedSessions.length>0)&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),T.launchConfirmSessionsLoading&&s.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:ol(x)}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:T.launchConfirmTextFilter,onChange:L=>T.setLaunchConfirmTextFilter(L.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:T.launchConfirmWorkspaceFilter,onChange:L=>T.setLaunchConfirmWorkspaceFilter(L.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:T.launchConfirmModelFilter,onChange:L=>T.setLaunchConfirmModelFilter(L.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsxs("select",{value:T.launchConfirmSortMode,onChange:L=>T.setLaunchConfirmSortMode(L.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:T.launchConfirmResumableOnly,onChange:L=>T.setLaunchConfirmResumableOnly(L.target.checked),disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:T.launchConfirmResumeId,onChange:L=>T.setLaunchConfirmResumeId(L.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:fS(x)}),T.filteredLaunchConfirmSavedSessions.map(L=>s.jsxs("option",{value:L.providerSessionId,disabled:!L.canResume,children:[L.title||L.providerSessionId," ",L.canResume?"":"(workspace missing)"]},L.providerSessionId))]}),!T.launchConfirmSessionsLoading&&T.launchConfirmSavedSessions.length>0&&T.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),T.launchConfirmResumeId&&(()=>{const L=T.filteredLaunchConfirmSavedSessions.find(E=>E.providerSessionId===T.launchConfirmResumeId);if(!L)return null;const O=vm(L);return s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:O.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:O.providerSessionId}),s.jsx("div",{className:"mt-1",children:O.metaLine}),O.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:O.updatedLabel}),O.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:O.preview})]})})()]}),onConfirm:T.handleConfirmLaunch,onCancel:T.closeLaunchConfirm}),u&&s.jsx(xm,{section:p,onSectionChange:f})]})}const ad=8e3;function u1(e){const t=e&&typeof e=="object"&&"result"in e?e.result:e,n=t&&typeof t=="object",r=n&&t.success===!1,a=n&&t.mirrorStale===!0;return!r&&!a?{confirmed:!0}:{confirmed:!1,reason:r&&typeof t.error=="string"?t.error:a?"the coordinator did not confirm the change":"command was rejected"}}function km(e,t,n){const r=l.useRef(new Map),[,a]=l.useState(0),o=l.useCallback(()=>a(g=>g+1),[]);l.useEffect(()=>{const g=r.current;if(g.size===0)return;const k=Date.now();let h=!1;for(const[v,w]of g){const b=e.get(v),j=w.muted===void 0||(b?b.muted===w.muted:!1),C=w.hidden===void 0||(b?b.surfaceHidden===w.hidden:!1),y=k-w.at>ad;(j&&C||y)&&(g.delete(v),h=!0)}h&&o()},[e,o]),l.useEffect(()=>{if(r.current.size===0)return;const g=setInterval(()=>{const k=r.current,h=Date.now();let v=!1;for(const[w,b]of k)h-b.at>ad&&(k.delete(w),v=!0);v&&o(),k.size===0&&clearInterval(g)},1e3);return()=>clearInterval(g)});const i=l.useCallback((g,k)=>{const h=r.current.get(g);r.current.set(g,{...h,...k,at:Date.now()}),o()},[o]),c=l.useCallback(g=>{const k=g.sessionId,h=k?r.current.get(k):void 0;return(h==null?void 0:h.muted)!==void 0?h.muted:Os(g,e).muted??!1},[e]),d=l.useCallback(g=>{const k=g.sessionId,h=k?r.current.get(k):void 0;return(h==null?void 0:h.hidden)!==void 0?h.hidden:Os(g,e).surfaceHidden??!1},[e]),p=l.useCallback((g,k)=>{const h=Ds(g),v=g.sessionId;!h||!v||(i(v,k),t(h,"set_conversation_prefs",{sessionId:v,...k,...Ua(g)}).then(w=>{const b=u1(w);b.confirmed||(console.warn("[conversation-prefs] set_conversation_prefs not confirmed",b.reason),r.current.delete(v),o(),n==null||n(`Couldn't update conversation — ${b.reason}`))}).catch(w=>{console.warn("[conversation-prefs] set_conversation_prefs failed",w),r.current.delete(v),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]),u=l.useCallback(g=>{p(g,{muted:!c(g)})},[p,c]),m=l.useCallback((g,k)=>{p(g,{hidden:k})},[p]),f=l.useCallback(g=>{p(g,{hidden:!d(g)})},[p,d]);return{isMuted:c,isHidden:d,toggleMute:u,setHidden:m,toggleHidden:f}}function la(e){return[...e].sort((t,n)=>{const r=n.timestamp-t.timestamp;return r!==0?r:t.conversation.tabKey.localeCompare(n.conversation.tabKey)})}function p1(e,t=[]){const n=new Map(e.map(a=>[a.conversation.tabKey,a])),r=t.map(a=>n.get(a)).filter(a=>!!a);return r.length===e.length?r:la(e)}function m1(e,t=[]){const n=e.filter(i=>i.requiresAction),r=e.filter(i=>i.unread&&!i.requiresAction),a=e.filter(i=>!i.unread&&!i.requiresAction&&i.isWorking),o=e.filter(i=>!i.unread&&!i.requiresAction&&!i.isWorking);return{attentionItems:la(n),unreadItems:la(r),workingItems:p1(a,t),completedItems:la(o)}}function h1(e){var r,a,o;const t=((r=e.p2p)==null?void 0:r.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":!(!!((a=e.p2p)!=null&&a.available)||!!((o=e.p2p)!=null&&o.state))&&e.status&&e.status!=="offline"?"Connected":"Offline"}function f1(e,t){if(!e)return[];const n=e.recentLaunches||[];return n.length>0?n.map(r=>({id:r.id,label:r.title||r.providerName||r.providerType,kind:r.kind,providerType:r.providerType,providerSessionId:r.providerSessionId,subtitle:ln(r.summaryMetadata)||r.workspace||void 0,workspace:r.workspace,summaryMetadata:r.summaryMetadata})):t.filter(r=>r.type!=="adhdev-daemon"&&r.daemonId===e.id).map(r=>{var i;const a=xr(r)?"cli":Nn(r)?"acp":"ide",o=ln(r.summaryMetadata);return{id:`${a}:${r.type}:${r.workspace||""}`,label:((i=r.activeChat)==null?void 0:i.title)||(xr(r)?r.cliName||r.type:Nn(r)&&r.cliName||r.type),kind:a,providerType:r.type,providerSessionId:r.providerSessionId,subtitle:Nn(r)?o||r.workspace||void 0:r.workspace||void 0,workspace:r.workspace||void 0,timestamp:r.lastMessageAt||0}}).sort((r,a)=>a.timestamp-r.timestamp).map(({timestamp:r,...a})=>a)}function b1(e,t,n=[]){const r=new Map;for(const o of t){const i=Ds(o.conversation),c=r.get(i);c?c.push(o):r.set(i,[o])}const a=new Map;for(const o of n){const i=Ds(o),c=a.get(i);c?c.push(o):a.set(i,[o])}return e.map(o=>{const i=r.get(o.id)||[],c=a.get(o.id)||[],d=[...i].sort((h,v)=>v.timestamp-h.timestamp)[0]||null,p=(d==null?void 0:d.conversation)||null,u=pi(o),m=i.filter(h=>h.unread||h.requiresAction).length,f=i.filter(h=>gr(h.conversation)).length+c.filter(gr).length,g=h1(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:f,latestConversation:p,latestTimestamp:(d==null?void 0:d.timestamp)||0,fallbackActivityAt:u,preview:p?Bk(p,wp(p)):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((o,i)=>{const c=o.latestTimestamp||o.fallbackActivityAt||0,d=i.latestTimestamp||i.fallbackActivityAt||0;return d!==c?d-c:o.label.localeCompare(i.label)})}function g1(e){return e==="chat"}function zr(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 x1({conversations:e,machineEntries:t,items:n,selectedConversation:r,selectedTabKey:a,screen:o,liveSessionInboxState:i,sendDaemonCommand:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,setSelectedTabKey:k,setScreen:h,setSelectedMachineId:v,setSection:w,setMachineBackTarget:b,resetMachineAction:j}){const C=l.useRef(null),y=l.useCallback(x=>{if(!(x!=null&&x.sessionId))return;const N=Os(x,i),S=Math.max(Date.now(),nn(x),N.lastUpdated||0);zr("mark_read:start",{tabKey:x.tabKey,sessionId:x.sessionId,displayPrimary:yt(x),inboxBucket:N.inboxBucket,unread:N.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:nn(x),readAt:S}),c(Ds(x)||x.routeId,"mark_session_seen",{sessionId:x.sessionId,providerSessionId:x.providerSessionId,seenAt:S,completionMarker:N.completionMarker}).then(A=>{zr("mark_read:result",{tabKey:x.tabKey,sessionId:x.sessionId,result:A})}).catch(A=>{zr("mark_read:error",{tabKey:x.tabKey,sessionId:x.sessionId,error:A instanceof Error?A.message:String(A)})})},[i,c]);return l.useEffect(()=>{var N;if(!r){g1(o)&&h("inbox"),k(((N=e[0])==null?void 0:N.tabKey)||null),C.current=null;return}if(o!=="chat"){C.current=null;return}const x=`${r.tabKey}:${r.sessionId||""}`;C.current!==x&&(C.current=x,y(r))},[e,y,o,r,h,k]),l.useEffect(()=>{if(!d)return;const x=e.find(N=>N.tabKey===d);x&&(k(x.tabKey),h("chat"),p==null||p())},[e,p,d,h,k]),l.useEffect(()=>{if(!u)return;const x=t.find(N=>N.id===u);x&&(v(x.id),j(),w("machines"),b("inbox"),h("machine"),m==null||m())},[t,m,u,j,b,h,w,v]),l.useEffect(()=>{f&&(w(f),h("inbox"),g==null||g())},[g,f,h,w]),l.useEffect(()=>{const x=n.filter(N=>N.inboxBucket==="task_complete"||N.unread);x.length!==0&&zr("inbox_state",{screen:o,selectedTabKey:a,items:x.map(N=>{const S=Os(N.conversation,i);return{liveState:S,tabKey:N.conversation.tabKey,sessionId:N.conversation.sessionId,displayPrimary:yt(N.conversation),serverBucket:S.inboxBucket,computedBucket:N.inboxBucket,serverUnread:S.unread,computedUnread:N.unread,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,activityAt:nn(N.conversation)}})})},[n,i,o,a]),{markConversationRead:y}}function v1(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function od(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function y1(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function w1({sendDaemonCommand:e,navigate:t,ides:n,conversations:r}){const{launchCli:a}=Ra(),[o,i]=l.useState("idle"),[c,d]=l.useState(""),[p,u]=l.useState(null),m=l.useCallback(()=>{i("idle"),d(""),u(null)},[]),f=l.useCallback(async(j,C,y)=>{var x;try{i("loading"),d(`Launching ${C}…`);const N={ideType:C,enableCdp:!0};(x=y==null?void 0:y.workspacePath)!=null&&x.trim()&&(N.workspace=y.workspacePath.trim()),await e(j,"launch_ide",N),i("done"),d(`${C} launch requested`)}catch(N){i("error"),d(N instanceof Error?N.message:"Launch IDE failed"),console.error("Launch IDE failed",N)}},[e]),g=l.useCallback(async(j,C,y)=>{if(C.trim())try{i("loading"),d(y!=null&&y.createIfMissing?"Creating folder…":"Saving workspace…");const x=await e(j,"workspace_add",{path:C.trim(),createIfMissing:(y==null?void 0:y.createIfMissing)===!0});if(x!=null&&x.success){i("done"),d(y!=null&&y.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),d((x==null?void 0:x.error)||"Could not save workspace")}catch(x){i("error"),d(x instanceof Error?x.message:"Could not save workspace")}},[e]),k=l.useCallback(async j=>{var C,y,x,N,S,A;try{i("loading"),d("Starting daemon upgrade…");const T=await e(j,"daemon_upgrade",{});if((C=T==null?void 0:T.result)!=null&&C.alreadyLatest){i("done"),d(`Already on v${((y=T==null?void 0:T.result)==null?void 0:y.version)||"latest"}.`);return}if((x=T==null?void 0:T.result)!=null&&x.upgraded||(N=T==null?void 0:T.result)!=null&&N.success){i("done"),d(`Upgrade to v${((S=T==null?void 0:T.result)==null?void 0:S.version)||"latest"} started. Daemon is restarting…`);return}i("error"),d(((A=T==null?void 0:T.result)==null?void 0:A.error)||"Upgrade failed")}catch(T){i("error"),d(T instanceof Error?T.message:"Upgrade failed")}},[e]),h=l.useCallback(async(j,C,y,x)=>{var A,T,I;const N=Date.now(),S={machineId:j,kind:C,providerType:y,workspaceId:(x==null?void 0:x.workspaceId)||null,workspacePath:(x==null?void 0:x.workspacePath)||null,resumeSessionId:(x==null?void 0:x.resumeSessionId)||null,startedAt:N};try{i("loading"),d(`Launching ${y}…`),u(S);const D={cliType:y};(A=x==null?void 0:x.workspacePath)!=null&&A.trim()?D.dir=x.workspacePath.trim():x!=null&&x.workspaceId?D.workspaceId=x.workspaceId:x!=null&&x.useHome&&(D.useHome=!0),x!=null&&x.resumeSessionId&&(D.resumeSessionId=x.resumeSessionId),(T=x==null?void 0:x.args)!=null&&T.trim()&&(D.cliArgs=x.args.trim().split(/\s+/).filter(Boolean)),(I=x==null?void 0:x.model)!=null&&I.trim()&&(D.initialModel=x.model.trim());const P=await a(j,D),_=(P==null?void 0:P.result)||P,G=(_==null?void 0:_.sessionId)||(_==null?void 0:_.id);if(P!=null&&P.success&&G){u(null),i("done"),d(`${y} launched`),t(wr(G));return}if(P!=null&&P.success){i("loading"),d(`${y} launch requested — waiting for session…`);return}u(null),i("error"),d((P==null?void 0:P.error)||(_==null?void 0:_.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(D){if(y1(D)){i("loading"),d(`${y} launch requested — waiting for session…`);return}u(null),i("error"),d(D instanceof Error?D.message:`Could not launch ${C.toUpperCase()} workspace`)}},[t,e]),v=l.useCallback(async(j,C)=>{try{const y=await e(j,"list_saved_sessions",{providerType:C,kind:"cli",limit:30}),x=(y==null?void 0:y.result)??y;return Array.isArray(x==null?void 0:x.sessions)?x.sessions:[]}catch(y){return console.error("Failed to list saved sessions on mobile:",y),[]}},[e]),w=l.useCallback(async(j,C)=>bl(e,j,C),[e]);l.useEffect(()=>{if(!p)return;const j=od(p.workspacePath),C=n.find(x=>{var D,P,_,G;if(!x||x.type==="adhdev-daemon"||v1(x.daemonId||x.id)!==p.machineId||(x.transport==="acp"?"acp":x.transport==="pty"?"cli":null)!==p.kind||String(x.agentType||x.type||"")!==p.providerType)return!1;const T=String(x.providerSessionId||"");if(p.resumeSessionId&&T)return T===p.resumeSessionId;if(j){const H=od(x.workspace||x.runtimeWorkspaceLabel);return H?H===j:!1}return Number(x.lastUpdated||x._lastUpdate||x.timestamp||((G=(_=(P=(D=x.activeChat)==null?void 0:D.messages)==null?void 0:P.at)==null?void 0:_.call(P,-1))==null?void 0:G.timestamp)||0)>=p.startedAt-5e3});if(!C)return;const y=fm({entrySessionId:C.sessionId,entryInstanceId:C.instanceId,entryRouteId:C.id,conversations:r});y&&(u(null),i("done"),d(`${p.providerType} launched`),t(wr(y)))},[r,n,t,p]),l.useEffect(()=>{if(!p)return;const j=window.setTimeout(()=>{u(C=>!C||C.startedAt!==p.startedAt?C:(i("error"),d("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(j)},[p]);const b=l.useCallback(async(j,C)=>{var y;if(C.kind==="ide"&&C.providerType){await f(j,C.providerType,{workspacePath:C.workspace||null});return}if((C.kind==="cli"||C.kind==="acp")&&C.providerType){const x=((y=C.workspace)==null?void 0:y.trim())||"";await h(j,C.kind,C.providerType,{workspacePath:x||null,useHome:!x,resumeSessionId:C.providerSessionId||null})}},[f,h]);return{machineAction:{state:o,message:c},resetMachineAction:m,handleLaunchDetectedIde:f,handleAddWorkspace:g,handleMachineUpgrade:k,handleLaunchWorkspaceProvider:h,handleListSavedSessions:v,handleBrowseDirectory:w,handleOpenRecent:b}}function k1({conversations:e,selectedConversation:t,machineBackTarget:n,markConversationRead:r,resetMachineAction:a,setSelectedTabKey:o,setScreen:i,setSelectedMachineId:c,setSection:d,setMachineBackTarget:p}){const u=l.useCallback(w=>{o(w.tabKey),i("chat"),r(w)},[r,i,o]),m=l.useCallback(w=>{const b=e.find(j=>j.routeId===w.routeId&&j.streamSource==="native");b&&(o(b.tabKey),i("chat"),r(b))},[e,r,i,o]),f=l.useCallback(()=>{r(t),i("inbox")},[r,t,i]),g=l.useCallback((w,b="inbox")=>{c(w),a(),d("machines"),p(b),i("machine")},[a,p,i,d,c]),k=l.useCallback(w=>{const b=Ds(w);b&&g(b,"chat")},[g]),h=l.useCallback(()=>{a(),i(n)},[n,a,i]),v=l.useCallback(w=>{d(w),i("inbox")},[i,d]);return{openConversation:u,openNativeConversation:m,backFromConversation:f,openMachine:g,openConversationMachine:k,backFromMachine:h,changeMachineSection:v}}function En(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function S1(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function C1({conversations:e,hiddenConversations:t,ides:n,actionLogs:r,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,userName:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,onOpenHistory:k,onOpenRemote:h,onStopCli:v,wsStatus:w,isConnected:b,onShowAllHiddenConversations:j,onHideConversation:C,onOpenMeshGraph:y,onOpenNewSession:x,liveSessionInboxState:N,setCliViewModeOverrides:S}){const[A,T]=l.useState(()=>{var U;return((U=e[0])==null?void 0:U.tabKey)||null}),[I,D]=l.useState(()=>e[0]?"chat":"inbox"),[P,_]=l.useState("chats"),[G,H]=l.useState(null),[L,O]=l.useState("inbox"),E=l.useRef([]),M=Cr(),$="1.0.26",R=l.useMemo(()=>e.find(U=>U.tabKey===A)||e[0]||null,[e,A]),z=l.useMemo(()=>R?n.find(U=>U.id===R.routeId):void 0,[n,R]),Q=l.useMemo(()=>!R||dt(R)||!mt(R)?null:Fn(R),[R]),ne=l.useMemo(()=>n.filter(U=>U.type==="adhdev-daemon").sort(Yi),[n]),J=l.useMemo(()=>ne.find(U=>U.id===G)||null,[ne,G]),Z=Ga({sendDaemonCommand:a,activeConv:R||void 0,setActionLogs:o,isStandalone:i}),de=w1({sendDaemonCommand:a,navigate:M,ides:n,conversations:e}),te=fk(e),B=l.useMemo(()=>e.map(U=>{const be=I==="chat"&&(R==null?void 0:R.tabKey)===U.tabKey,je=Ha(U,N,{hideOpenTaskCompleteUnread:!0,isOpenConversation:be}),ge=nn(U),Ie=wp(U),et=Tp(U,Ie);return{conversation:U,timestamp:ge,preview:et,unread:je.unread,requiresAction:je.requiresAction,isWorking:je.isWorking,inboxBucket:je.inboxBucket}}),[e,N,I,R,te]),{markConversationRead:ie}=x1({conversations:e,machineEntries:ne,items:B,selectedConversation:R,selectedTabKey:A,screen:I,liveSessionInboxState:N,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,setSelectedTabKey:T,setScreen:D,setSelectedMachineId:H,setSection:_,setMachineBackTarget:O,resetMachineAction:de.resetMachineAction}),Y=k1({conversations:e,selectedConversation:R,machineBackTarget:L,markConversationRead:ie,resetMachineAction:de.resetMachineAction,setSelectedTabKey:T,setScreen:D,setSelectedMachineId:H,setSection:_,setMachineBackTarget:O}),{isMuted:le,toggleMute:Ne}=km(N,a),{attentionItems:we,unreadItems:Se,workingItems:me,completedItems:q}=l.useMemo(()=>m1(B,E.current),[B]);l.useEffect(()=>{E.current=me.map(U=>U.conversation.tabKey)},[me]);const W=l.useMemo(()=>J?B.filter(U=>Ds(U.conversation)===J.id):[],[B,J]),X=l.useMemo(()=>f1(J,n),[n,J]),K=(J==null?void 0:J.version)||null,ue=!!J&&!!K&&!0&&K!==$,Pe=l.useMemo(()=>(J==null?void 0:J.availableProviders)||[],[J]),ce=l.useMemo(()=>Pe.filter(U=>En(U,"cli")).map(U=>({type:U.type,displayName:U.displayName||U.type,icon:U.icon})),[Pe]),F=l.useMemo(()=>Pe.filter(U=>En(U,"acp")).map(U=>({type:U.type,displayName:U.displayName||U.type,icon:U.icon})),[Pe]),pe=l.useMemo(()=>b1(ne,B,t),[B,ne,t]),xe=l.useCallback(async U=>{J&&await de.handleOpenRecent(J.id,U)},[de,J]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:I==="chat"&&R?s.jsx(t1,{selectedConversation:R,isAcp:dt(R),isStandalone:i,selectedIdeEntry:z,actionLogs:r,userName:c,isSendingChat:Z.isSendingChat,sendFeedbackMessage:Z.sendFeedbackMessage,isFocusingAgent:Z.isFocusingAgent,handleModalButton:Z.handleModalButton,handleRelaunch:Z.handleRelaunch,onBack:Y.backFromConversation,onOpenNativeConversation:Y.openNativeConversation,onOpenMachine:Y.openConversationMachine,onOpenHistory:k,onOpenRemote:h,onOpenMeshGraph:y,onStopCli:v,cliViewMode:Q,onSetCliViewMode:async U=>{await nm({conversation:R,mode:U,ides:n,sendDaemonCommand:a,setCliViewModeOverrides:S})},handleSendChat:Z.handleSendChat,handleForceSendChat:Z.handleForceSendChat,handleFocusAgent:Z.handleFocusAgent}):I==="machine"&&J?s.jsx(d1,{selectedMachineEntry:J,selectedMachineConversations:W,selectedMachineRecentLaunches:X,cliProviders:ce,acpProviders:F,selectedMachineNeedsUpgrade:ue,appVersion:$,machineAction:de.machineAction,isStandalone:i,section:P,showBottomNav:L==="inbox",onBack:Y.backFromMachine,onSectionChange:Y.changeMachineSection,onOpenConversation:Y.openConversation,onOpenRecent:xe,onOpenMachineDetails:()=>M(`/machines/${J.id}`),onMachineUpgrade:()=>de.handleMachineUpgrade(J.id),onLaunchDetectedIde:(U,be)=>de.handleLaunchDetectedIde(J.id,U,be),onAddWorkspace:(U,be)=>de.handleAddWorkspace(J.id,U,be),onBrowseDirectory:U=>de.handleBrowseDirectory(J.id,U),onLaunchWorkspaceProvider:(U,be,je)=>de.handleLaunchWorkspaceProvider(J.id,U,be,je),onListSavedSessions:U=>de.handleListSavedSessions(J.id,U)}):s.jsx(r1,{section:P,attentionItems:we,unreadItems:Se,workingItems:me,completedItems:q,hiddenConversations:t,machineCards:pe,getAvatarText:S1,actionLogs:r,sendDaemonCommand:a,onOpenConversation:Y.openConversation,onShowAllHidden:j,onHideConversation:C,onOpenMeshGraph:y,onStopCli:v,onOpenNewSession:x,onOpenMachine:Y.openMachine,onOpenSettings:()=>M("/settings"),onSectionChange:_,wsStatus:w,isConnected:b,isStandalone:i,isConversationMuted:le,onToggleMuteConversation:Ne})})}function Mo(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function j1({conversations:e,numGroups:t,onMoveTab:n,onReceiveTab:r,onOwnTabDrop:a,onClearPreviewOrder:o}){const i=l.useRef(0),[c,d]=l.useState(!1),[p,u]=l.useState(null),m=l.useCallback(()=>{i.current=0,d(!1),u(null)},[]);l.useEffect(()=>(window.addEventListener("dragend",m),window.addEventListener("drop",m),()=>{window.removeEventListener("dragend",m),window.removeEventListener("drop",m)}),[m]);const f=l.useCallback(v=>{v.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,d(!0))},[]),g=l.useCallback(v=>{if(!v.dataTransfer.types.includes("text/tab-key"))return;if(v.preventDefault(),!Mo(t,n)){u("merge");return}const w=v.currentTarget.getBoundingClientRect(),b=v.clientX-w.left,j=w.width/3;b<j?u("split-left"):b>j*2?u("split-right"):u("merge")},[t,n]),k=l.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,d(!1),u(null))},[]),h=l.useCallback(v=>{i.current=0,d(!1);const w=v.dataTransfer.getData("text/tab-key"),b=w?e.some(C=>C.tabKey===w):!1,j=p;if(u(null),o(),!!w){if(v.preventDefault(),j==="split-left"&&Mo(t,n)){n==null||n(w,"split-left");return}if(j==="split-right"&&Mo(t,n)){n==null||n(w,"split-right");return}if(b){a(w);return}r==null||r(w)}},[e,p,t,n,r,a,o]);return{dragOver:c,dropAction:p,resetDragState:m,handleDragEnter:f,handleDragOver:g,handleDragLeave:k,handleDrop:h}}function N1(e,t){const n=new Set(t.map(o=>o.tabKey)),r=e.filter(o=>n.has(o)),a=t.filter(o=>!e.includes(o.tabKey)).map(o=>o.tabKey);return[...r,...a]}function A1({conversations:e,initialActiveTabId:t,initialTabOrder:n,onActiveTabChange:r,onTabOrderChange:a}){const[o,i]=l.useState(t??null),[c,d]=l.useState(n??[]),[p,u]=l.useState(null),m=l.useRef(null),f=l.useRef(null),g=l.useRef(r),k=l.useRef(a);l.useEffect(()=>{g.current=r},[r]),l.useEffect(()=>{k.current=a},[a]),l.useEffect(()=>{t&&t!==o&&i(t)},[t,o]),l.useEffect(()=>{d(N=>{const S=N1(N,e);return S.length===N.length&&S.every((A,T)=>A===N[T])?N:S})},[e]);const h=l.useMemo(()=>{const N=p??c;if(N.length===0)return e;const S=new Map(N.map((A,T)=>[A,T]));return[...e].sort((A,T)=>{const I=S.get(A.tabKey)??999,D=S.get(T.tabKey)??999;return I-D})},[e,p,c]);l.useEffect(()=>{var S,A;if(h.length===0){o!==null&&(i(null),(S=g.current)==null||S.call(g,null));return}if(o&&h.some(T=>T.tabKey===o))return;const N=h[0].tabKey;N!==o&&(i(N),(A=g.current)==null||A.call(g,N))},[h,o]);const v=l.useMemo(()=>h.find(N=>N.tabKey===o),[h,o]),w=l.useCallback(N=>{var S;i(N),(S=g.current)==null||S.call(g,N)},[]),b=l.useCallback((N,S,A)=>{d(T=>{var _;const I=T.filter(G=>G!==N),D=I.indexOf(S);if(D<0)return T;const P=A==="left"?D:D+1;return I.splice(P,0,N),(_=k.current)==null||_.call(k,I),I}),u(null)},[]),j=l.useCallback((N,S,A)=>{const I=(c.length>0?c:e.map(_=>_.tabKey)).filter(_=>_!==N),D=I.indexOf(S);if(D<0)return;const P=A==="left"?D:D+1;I.splice(P,0,N),m.current=I,u(I)},[c,e]),C=l.useCallback(()=>{var S;const N=m.current;N&&(d(N),(S=k.current)==null||S.call(k,N))},[]),y=l.useCallback(()=>{m.current=null,u(null)},[]),x=l.useCallback(N=>{d(S=>{var T;const A=S.filter(I=>I!==N);return A.push(N),(T=k.current)==null||T.call(k,A),A})},[]);return{activeTabId:o,activeConv:v,sortedConversations:h,previewOrderRef:m,draggingTabRef:f,selectTab:w,handleTabReorder:b,updatePreviewOrder:j,commitPreviewOrder:C,clearPreviewOrder:y,moveTabToEnd:x,setDraggingTabKey:N=>{f.current=N}}}function T1({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 yl({conversationsCount:e,isSplitMode:t,isStandalone:n,hasRegisteredMachines:r=!1,suppressGuide:a=!1,onOpenNewSession:o}){const{t:i}=Ce("common");if(a)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const c=!n&&!r,d=r&&!!o,p=i(r?"paneGroup.noConversations":n?"paneGroup.waitingForDaemon":"paneGroup.connectYourMachines"),u=i(r?"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:p}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:u}),d&&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:i("paneGroup.newSession"),"aria-label":i("paneGroup.newSession"),children:[s.jsx(Gi,{size:14}),s.jsx("span",{children:i("paneGroup.newSession")})]})}),c&&s.jsx(gm,{}),c&&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 Sm="adhdev-tab-shortcuts";function Cm(){try{return JSON.parse(localStorage.getItem(Sm)||"{}")}catch{return{}}}function jm({enabled:e=!0,sortedTabKeys:t,onFocus:n,onSelectTab:r}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>Cm()),[c,d]=l.useState(null),p=l.useCallback(m=>{const f=[];return m.metaKey&&f.push(a?"⌘":"Meta"),m.ctrlKey&&f.push("Ctrl"),m.altKey&&f.push(a?"⌥":"Alt"),m.shiftKey&&f.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(m.key)?null:(f.push(m.key.length===1?m.key.toUpperCase():m.key),f.join("+"))},[a]),u=l.useCallback(m=>{i(m);try{localStorage.setItem(Sm,JSON.stringify(m))}catch{}},[]);return l.useEffect(()=>{if(!e||!c)return;const m=f=>{if(f.preventDefault(),f.stopPropagation(),f.key==="Escape"){d(null);return}const g=p(f);if(!g)return;const k={...o};for(const[h,v]of Object.entries(k))v===g&&delete k[h];k[c]=g,u(k),d(null)};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[e,c,o,u,p]),l.useEffect(()=>{if(!e)return;const m=f=>{if(!(!f.ctrlKey&&!f.metaKey&&!f.altKey)){for(const[g,k]of Object.entries(o))if(t.includes(g)&&p(f)===k){f.preventDefault(),n(),r(g);return}}};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[e,o,t,n,r,p]),{isMac:a,tabShortcuts:o,shortcutListening:c,setShortcutListening:d,saveShortcuts:u}}const Po=e=>{e.preventDefault()},M1=l.memo(function({conv:t,isActive:n,isDraggedTab:r,isTaskCompleteUnread:a,shortcut:o,conversationKeys:i,draggingTabRef:c,onFocus:d,onSelectTab:p,onConversationActivated:u,onPreviewReorder:m,onReorderTab:f,onCommitPreviewOrder:g,onClearPreviewOrder:k,onDragStateReset:h,onDragTabKeyChange:v,onReceiveTab:w,onOpenContextMenu:b,longPressTimer:j,isGroupActive:C}){const y=pn(t),x=y.isGenerating?"agent-tab-generating":y.isWaiting?"agent-tab-waiting":"",N=y.isReconnecting,S=$k(t),A=Hk(t),T=Ap(t),I=l.useCallback(M=>{c.current=t.tabKey,v(t.tabKey),M.dataTransfer.setData("text/tab-key",t.tabKey),M.dataTransfer.effectAllowed="move"},[t.tabKey,c,v]),D=l.useCallback(()=>{c.current=null,v(null),g(),k(),h()},[c,v,g,k,h]),P=l.useCallback(M=>{const $=c.current;if(!(!$||$===t.tabKey)&&M.dataTransfer.types.includes("text/tab-key")){M.preventDefault(),M.stopPropagation();const R=M.currentTarget.getBoundingClientRect(),z=M.clientX<R.left+R.width/2?"left":"right";m($,t.tabKey,z)}},[t.tabKey,c,m]),_=l.useCallback(M=>{M.preventDefault(),M.stopPropagation();const $=M.dataTransfer.getData("text/tab-key");if($&&$!==t.tabKey){const R=M.currentTarget.getBoundingClientRect(),z=M.clientX<R.left+R.width/2?"left":"right";i.includes($)?f($,t.tabKey,z):w&&w($)}k()},[t.tabKey,i,f,w,k]),G=l.useCallback(M=>{M.stopPropagation(),d(),p(t.tabKey),u(t)},[t,u,d,p]),H=l.useCallback(M=>{M.preventDefault(),b(M.clientX,M.clientY,t.tabKey)},[t.tabKey,b]),L=l.useCallback(M=>{const $=M.touches[0];j.current=setTimeout(()=>{b($.clientX,$.clientY,t.tabKey)},600)},[t.tabKey,j,b]),O=l.useCallback(()=>{j.current&&clearTimeout(j.current)},[j]),E=["adhdev-dockview-tab",x,n&&"is-active",C&&"is-group-active",N&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:E,draggable:!0,onDragStart:I,onDragEnd:D,onDragOver:P,onDrop:_,onClick:G,onContextMenu:H,onTouchStart:L,onTouchEnd:O,onTouchMove:O,style:{position:"relative",cursor:"pointer",opacity:r?.4:void 0},children:[T&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-badge pointer-events-none absolute top-0.5 right-0.5 text-text-muted",title:"Mesh chat","aria-label":"Mesh chat",children:s.jsx(rs,{size:11})}),a&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:y.isGenerating?s.jsx("div",{className:"tab-spinner"}):y.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):N?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):y.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:yt(t),children:yt(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[N?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:en(t)}):y.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[en(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:en(t)}),s.jsx(ka,{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 P1({conversations:e,activeTabId:t,groupIndex:n,unreadTabKeys:r,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:m,onDragStateReset:f,onDragTabKeyChange:g,onReceiveTab:k,onHideTab:h,isGroupActive:v,allowTabShortcuts:w=!0}){const{t:b}=Ce("common"),[j,C]=l.useState(null),y=l.useRef(null),x=l.useRef(null),N=l.useMemo(()=>e.map(_=>_.tabKey),[e]);jr("PaneGroupTabBar",{groupIndex:n,activeTabId:t,tabCount:e.length,ctxMenuTab:(j==null?void 0:j.tabKey)||null});const{isMac:S,tabShortcuts:A,shortcutListening:T,setShortcutListening:I,saveShortcuts:D}=jm({enabled:w,sortedTabKeys:e.map(_=>_.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!j)return;const _=G=>{const H=document.querySelector("[data-pane-context-menu]");H&&H.contains(G.target)||C(null)};return window.addEventListener("mousedown",_,!0),()=>window.removeEventListener("mousedown",_,!0)},[j]),l.useEffect(()=>{const _=x.current;if(!_)return;const G=H=>{Math.abs(H.deltaY)<=Math.abs(H.deltaX)||(H.preventDefault(),_.scrollLeft+=H.deltaY)};return _.addEventListener("wheel",G,{passive:!1}),()=>_.removeEventListener("wheel",G)},[]);const P=l.useCallback((_,G,H)=>{C({x:_,y:G,tabKey:H})},[]);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:x,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(_=>s.jsx(M1,{conv:_,isActive:t===_.tabKey,isDraggedTab:a.current===_.tabKey,isTaskCompleteUnread:r.has(_.tabKey),shortcut:w?A[_.tabKey]:void 0,conversationKeys:N,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:m,onDragStateReset:f,onDragTabKeyChange:g,onReceiveTab:k,onOpenContextMenu:P,longPressTimer:y,isGroupActive:v},_.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:b("paneGroup.noTabsInGroup")})]})}),j&&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:j.x,top:j.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:Po,onClick:_=>{_.stopPropagation(),I(j.tabKey),C(null)},children:["⌨ ",A[j.tabKey]?`Change shortcut (${A[j.tabKey]})`:"Set shortcut"]}),A[j.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:Po,onClick:()=>{const _={...A};delete _[j.tabKey],D(_),C(null)},children:"✕ Remove shortcut"})]}),h&&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:Po,onClick:()=>{h(j.tabKey),C(null)},children:"🚫 Hide from Dashboard"})]})]}),w&&T&&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:_=>_.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 D1({conversations:e,ides:t,clearedTabs:n,actionLogs:r,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,userName:d,groupIndex:p,onFocus:u,isSplitMode:m,numGroups:f,onMoveTab:g,onReceiveTab:k,style:h,onActiveTabChange:v,initialActiveTabId:w,initialTabOrder:b,onTabOrderChange:j,onHideTab:C,isFocused:y,allowTabShortcuts:x=!0,onOpenNewSession:N,liveSessionInboxState:S}){const{sendCommand:A}=wt(),T=l.useRef(null),{activeTabId:I,activeConv:D,sortedConversations:P,draggingTabRef:_,selectTab:G,handleTabReorder:H,updatePreviewOrder:L,commitPreviewOrder:O,clearPreviewOrder:E,moveTabToEnd:M,setDraggingTabKey:$}=A1({conversations:e,initialActiveTabId:w,initialTabOrder:b,onActiveTabChange:v,onTabOrderChange:j}),R=Ga({sendDaemonCommand:a,activeConv:D,setActionLogs:o,isStandalone:i}),{dragOver:z,dropAction:Q,resetDragState:ne,handleDragEnter:J,handleDragOver:Z,handleDragLeave:de,handleDrop:te}=j1({conversations:e,numGroups:f,onMoveTab:g,onReceiveTab:k,onOwnTabDrop:M,onClearPreviewOrder:E}),B=D&&!dt(D)&&Fn(D)==="terminal",ie=l.useMemo(()=>D?t.find(we=>we.id===D.routeId):void 0,[t,D]),Y=l.useMemo(()=>D?r.filter(we=>we.routeId===D.tabKey):[],[r,D]),le=l.useMemo(()=>new Set(P.filter(we=>Vb(we,S,{isOpenConversation:we.tabKey===I})).map(we=>we.tabKey)),[I,S,P]);jr("PaneGroup",{groupIndex:p,conversationCount:e.length,activeTabId:I,dragOver:z});const Ne=l.useCallback(we=>{we.streamSource==="agent-stream"&&we.agentType&&A(we.routeId,lp(),{agentType:we.agentType,...we.sessionId&&{targetSessionId:we.sessionId}}).catch(()=>{})},[A]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:u,style:{...h,outline:z?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(P1,{conversations:P,activeTabId:I,groupIndex:p,numGroups:f,unreadTabKeys:le,draggingTabRef:_,onFocus:u,onSelectTab:G,onConversationActivated:Ne,onPreviewReorder:L,onReorderTab:H,onCommitPreviewOrder:O,onClearPreviewOrder:E,onDragStateReset:ne,onDragTabKeyChange:$,onMoveTab:g,onReceiveTab:k,onHideTab:C,isGroupActive:y??!1,allowTabShortcuts:x}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:J,onDragOver:Z,onDragLeave:de,onDrop:te,children:[z&&s.jsx(T1,{dropAction:Q,canSplit:!!(f<4&&g)}),D?s.jsx(gl,{activeConv:D,clearToken:n[D.tabKey]||0,isCliTerminal:!!B,ideEntry:ie,terminalRef:T,handleModalButton:R.handleModalButton,handleRelaunch:R.handleRelaunch,handleSendChat:R.handleSendChat,handleForceSendChat:R.handleForceSendChat,isSendingChat:R.isSendingChat,sendFeedbackMessage:R.sendFeedbackMessage,handleFocusAgent:R.handleFocusAgent,isFocusingAgent:R.isFocusingAgent,actionLogs:Y,userName:d,isInputActive:!m||!!y}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(yl,{conversationsCount:e.length,isSplitMode:m,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:N})})]})]})}function I1({containerRef:e,isSplitMode:t,numGroups:n,groupSizes:r,groupedConvs:a,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:p,isStandalone:u,hasRegisteredMachines:m,userName:f,focusedGroup:g,focusGroup:k,moveTabToGroup:h,splitTabRelative:v,closeGroup:w,handleResizeStart:b,groupActiveTabIds:j,setGroupActiveTab:C,groupTabOrders:y,setGroupTabOrder:x,toggleHiddenTab:N,onOpenNewSession:S,allowTabShortcuts:A=!0,liveSessionInboxState:T}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((I,D)=>{const P=t&&r.length===n?`${r[D]}%`:void 0;return s.jsxs(Lt.Fragment,{children:[t&&D>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:_=>b(D-1,_),onDoubleClick:()=>w(D),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(D1,{style:t?{flexBasis:P??`${100/n}%`,flexGrow:P?0:1,flexShrink:P?0:1}:void 0,conversations:I,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:p,isStandalone:u,hasRegisteredMachines:m,userName:f,groupIndex:D,isFocused:t&&g===D,onFocus:()=>k(D),isSplitMode:t,numGroups:n,onMoveTab:(_,G)=>{G==="left"&&D>0?h(_,D-1):G==="right"&&D<n-1?h(_,D+1):G==="split-left"&&n<4?v(_,D,"left"):G==="split-right"&&n<4&&v(_,D,"right")},onReceiveTab:_=>h(_,D),onActiveTabChange:_=>C(D,_),initialActiveTabId:j[D],initialTabOrder:y[D],onTabOrderChange:_=>x(D,_),onHideTab:N,onOpenNewSession:S,allowTabShortcuts:A,liveSessionInboxState:T})]},D)})})}const Nm="adhdev-dashboard-action-shortcuts",L1=1200,R1=[["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 E1(){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 Am(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 Ti(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function Da(e){const t=Object.fromEntries(Am(e).map(n=>[n.id,n.defaultShortcut]));try{const n=JSON.parse(localStorage.getItem(Nm)||"{}"),r={...t,...n};for(const[a,o]of R1)r[a]===o&&(r[a]=t[a]);return r}catch{return t}}function Tm(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function _1({enabled:e=!0,onTrigger:t}){const n=E1(),[r,a]=l.useState(()=>Da(n)),[o,i]=l.useState(null),[c,d]=l.useState([]),p=l.useRef({parts:[],timer:null}),u=l.useCallback(h=>{const v=[];return h.metaKey&&v.push(n?"⌘":"Meta"),h.ctrlKey&&v.push("Ctrl"),h.altKey&&v.push(n?"⌥":"Alt"),h.shiftKey&&h.key.length!==1&&v.push(n?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(v.push(Tm(h.key)),v.join("+"))},[n]),m=l.useCallback(h=>{a(h);try{localStorage.setItem(Nm,JSON.stringify(h))}catch{}},[]);l.useEffect(()=>{const h=Da(n),v=Object.entries(r),w=Object.entries(h);v.length===w.length&&v.every(([b,j])=>h[b]===j)||m(h)},[r,n,m]);const f=l.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),g=l.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},L1))},[]);l.useEffect(()=>{if(!o)return;const h=v=>{if(v.preventDefault(),v.stopPropagation(),v.key==="Escape"){i(null),d([]);return}const w=u(v);if(!w)return;const j=!(v.metaKey||v.ctrlKey||v.altKey)&&/^[A-Z0-9]$/.test(w);if(c.length===0&&j){d([w]);return}const y=[...c,w].slice(0,2).join(" "),x={...r};for(const[N,S]of Object.entries(x))S===y&&delete x[N];x[o]=y,m(x),i(null),d([])};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[r,u,m,o,c]),l.useEffect(()=>{if(!e||o)return;const h=v=>{if(v.defaultPrevented)return;const w=u(v);if(!w)return;const b=v.metaKey||v.ctrlKey||v.altKey;if(Ti(v.target))return;const j=p.current.parts,C=b?[w]:[...j.slice(-1),w].slice(-2),y=C.join(" "),x=C[C.length-1],N=Object.entries(r).filter(([,D])=>!!D),S=N.find(([,D])=>D===y);if(S){v.preventDefault(),f(),t(S[0]);return}if(N.some(([,D])=>D.startsWith(`${y} `))){v.preventDefault(),p.current.parts=C,g();return}const T=N.find(([,D])=>D===x);if(T){v.preventDefault(),f(),t(T[0]);return}if(N.some(([,D])=>D.startsWith(`${x} `))){v.preventDefault(),p.current.parts=[x],g();return}f()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[r,g,e,u,t,f,o]),l.useEffect(()=>()=>f(),[f]);const k=l.useMemo(()=>Am(n),[n]);return{isMac:n,actionDefinitions:k,actionShortcuts:r,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:d,saveShortcuts:m}}function $1({isTabInPopout:e,isTabFloating:t,tabShortcut:n,actionShortcuts:r}){const a=[];return e?(t&&a.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:r.dockActiveTab}),a.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:r.dockActiveTab})):t?a.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:r.dockActiveTab}):a.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:r.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:r.popoutActiveTab}),a.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:n?`Change shortcut (${n})`:"Set shortcut",shortcut:r.setActiveTabShortcut}),n&&a.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),a.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:r.hideCurrentTab,tone:"muted"}),a}function Mm(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function id({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:n,ides:r}){return!e||n>0?!1:t?!Mm(r):!0}function H1({previousVisibleConversationCount:e,visibleConversationCount:t,ides:n}){return t>0||e<=0?!1:Mm(n)}const Pm=1e3,F1=4;function ld(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function cd(e,t,n){return Math.abs(t.clientX-e.clientX)>n||Math.abs(t.clientY-e.clientY)>n}function B1({detachDelayMs:e=Pm,stillnessThresholdPx:t=F1,onDetach:n,setTimeoutFn:r=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let o=null,i=null,c=null,d=null,p=null,u=!1;const m=()=>{p!=null&&(a(p),p=null)},f=()=>{m(),c=null},g=()=>{m(),o=null,i=null,c=null,d=null,u=!1},k=()=>{!o||!c||!d||u||p!=null||(p=r(()=>{p=null,!(!o||!c||!d||u)&&ld(d,i)&&(cd(c,d,t)||(u=!0,n({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},h=w=>{if(!(!o||u)){if(!ld(w,i)){d={clientX:w.clientX,clientY:w.clientY},f();return}(!c||cd(c,w,t))&&(m(),c={clientX:w.clientX,clientY:w.clientY}),d={clientX:w.clientX,clientY:w.clientY},k()}},v=w=>{!o||u||(w&&(d={clientX:w.clientX,clientY:w.clientY}),f())};return{startDrag:w=>{m(),o=w.panelId,i=w.selfPanelBounds??null,c=null,d={clientX:w.clientX,clientY:w.clientY},u=!1},markSelfPanel:h,markNonSelfPanel:v,markNoDropTarget:v,markDockTarget:v,endDrag:g,isDragging:()=>o!=null,hasDetached:()=>u,dispose:g}}function O1(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function ca(e){return yt(e)||e.tabKey}function W1(e){return`remote:${e}`}function cs(e){return e.startsWith("remote:")}function dd(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Do(e){var r;const t=e==null?void 0:e.defaultView;if(!t)return;const n=a=>{if(a)try{a.focus({preventScroll:!0})}catch{try{a.focus()}catch{}}};try{t.focus(),n(e==null?void 0:e.body),n(e==null?void 0:e.documentElement),(r=t.requestAnimationFrame)==null||r.call(t,()=>{try{t.focus(),n(e==null?void 0:e.body)}catch{}})}catch{}}function Io(e,t){e.classList.remove(Zo.className,ei.className),e.classList.add(t==="light"?Zo.className:ei.className)}function ud(e){return e?Array.from(new Set(e.groups.map(t=>{var n,r;return(r=(n=t.element)==null?void 0:n.ownerDocument)==null?void 0:r.defaultView}).filter(t=>!!t&&t!==window))):[]}function U1(e,t,n){var i;const r=[t];let a;for(const c of r){let d;for(const p of c){const u=e.addPanel({id:p.tabKey,component:"conversation",title:ca(p),params:{kind:"conversation",tabKey:p.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});d||(d=u.id)}a=d??a}return n??((i=t[0])==null?void 0:i.tabKey)??null}function pd(e,t){const n=new Set(t.map(a=>a.tabKey)),r=new Map;for(const a of t)r.set(a.tabKey,(r.get(a.tabKey)||0)+1);for(const a of[...e.panels])cs(a.id)||n.has(a.id)||e.removePanel(a);for(const a of t){const o=e.getPanel(a.tabKey);if(o){(r.get(a.tabKey)||0)>1&&console.warn("[dashboard-conversations] Dockview panel already exists for duplicate tabKey",{tabKey:a.tabKey,daemonId:a.daemonId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,panelId:o.id}),o.update({params:{tabKey:a.tabKey}}),o.title!==ca(a)&&o.api.setTitle(ca(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:ca(a),params:{kind:"conversation",tabKey:a.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 md(e,t,n){var d,p;const r=n?W1(n):null;for(const u of[...e.panels])cs(u.id)&&(!r||u.id!==r)&&e.removePanel(u);if(!n||!r)return;const a=fs(t,n);if(!a&&e.totalPanels===0)return;const o=e.getPanel(r),i=Dp(a);if(o){o.title!==i&&o.api.setTitle(i);return}const c=(a==null?void 0:a.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((p=e.panels.find(u=>!cs(u.id)))==null?void 0:p.id);e.addPanel({id:r,component:"remote",title:i,params:{kind:"remote",routeId:n},...c?{position:{referencePanel:c,direction:"right"},inactive:!0}:{}})}function Dm({doId:e,targetSessionId:t,connState:n,viewMode:r}){const[a,o]=l.useState(null),[i,c]=l.useState(null);l.useEffect(()=>e?Ct.onScreenshot("ide-page",(u,m)=>{if(u!==e)return;const f=new FileReader;f.onload=()=>o(f.result),f.readAsDataURL(m)}):void 0,[e]),l.useEffect(()=>{n!=="connected"&&o(null)},[n]),l.useEffect(()=>{var u;return e?((u=Ct.onStatus)==null?void 0:u.call(Ct,(m,f)=>{m===e&&f!=null&&f.screenshotUsage&&c(f.screenshotUsage)}))||(()=>{}):void 0},[e]),l.useEffect(()=>{o(null)},[e,t]),l.useEffect(()=>{const p=e?Ct.get(e):null;if(!(!p||n!=="connected"))return r!=="chat"&&t?p.startScreenshots(t):p.stopScreenshots(t),()=>{p.stopScreenshots(t)}},[r,n,t,e]);const d=l.useCallback(async(p,u)=>{const m=e?Ct.get(e):null;return!m||n!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):m.sendInput(p,u,t)},[e,n,t]);return{connScreenshot:a,screenshotUsage:i,handleRemoteAction:d}}const Im=l.createContext(null);function Ka(){const e=l.useContext(Im);if(!e)throw new Error("DashboardDockviewContext missing");return e}function G1(e){const[,t]=l.useState(0);l.useEffect(()=>{const n=()=>t(a=>a+1),r=[e.api.onDidActiveGroupChange(n),e.api.onDidTitleChange(n),e.api.onDidGroupChange(n),e.containerApi.onDidActivePanelChange(n)];return()=>{for(const a of r)a.dispose()}},[e.api,e.containerApi])}function q1({params:e}){var d;const t=Ka(),n=l.useMemo(()=>fs([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),r=l.useMemo(()=>t.ides.find(p=>p.id===e.routeId),[t.ides,e.routeId]),a=(n==null?void 0:n.daemonId)||((d=n==null?void 0:n.routeId)==null?void 0:d.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:i,handleRemoteAction:c}=Dm({doId:a,targetSessionId:n?op(n):(r==null?void 0:r.sessionId)||(r==null?void 0:r.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(Tu,{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 z1(){const e=Ka();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(yl,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function K1(e){var b,j;G1(e);const t=Ka(),n=l.useCallback(C=>{"button"in C&&C.button!==0||e.api.setActive()},[e.api]),r=e.params.kind==="remote"?void 0:t.conversationsByTabKey.get(e.params.tabKey),a=r==null?void 0:r.sessionId,o=l.useCallback(C=>vk(C),[]),i=l.useCallback(()=>xk(a),[a]),c=l.useSyncExternalStore(o,i,i);if(e.params.kind==="remote"){const C=fs([...t.conversationsByTabKey.values()],e.params.routeId),y=((b=e.api.group.activePanel)==null?void 0:b.id)===e.api.id,x=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${y?" is-active":""}${x?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(C==null?void 0:C.tabKey)||"",onMouseDown:n,onTouchStart:n,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:C!=null&&C.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:C.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const d=t.conversationsByTabKey.get(e.params.tabKey);if(!d)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const p=((j=e.api.group.activePanel)==null?void 0:j.id)===e.api.id,u=e.api.isGroupActive,m=Ha(d,t.liveSessionInboxState,{isOpenConversation:p}),f=m.isReconnecting,g=m.isConnecting,k=m.isGenerating||c,h=m.isWaiting,v=m.unread,w=t.tabShortcuts[d.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${p?" is-active":""}${u?" is-group-active":""}${f?" is-reconnecting":""}`,title:yt(d),"data-tab-key":e.params.tabKey,onMouseDown:n,onTouchStart:n,onContextMenu:C=>{var y;C.preventDefault(),n(C),t.openTabContextMenu({x:C.clientX,y:C.clientY,tabKey:d.tabKey,sourceDocument:((y=C.target)==null?void 0:y.ownerDocument)??document})},children:[v&&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"}):h?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):f?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):g?s.jsx("div",{className:"tab-connecting-spinner"}):d.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:yt(d)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:f?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:en(d)}):g?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:en(d)}):s.jsx("span",{children:en(d)})})]}),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 Kr(e){return e.isActive}function hd(e){return e.isVisible}function V1(e){e.preventDefault()}function Y1({params:e,api:t}){var g;const n=Ka(),r=l.useRef(null),[a,o]=l.useState(()=>Kr(t)),[i,c]=l.useState(()=>hd(t)),d=n.conversationsByTabKey.get(e.tabKey),p=Ga({sendDaemonCommand:n.sendDaemonCommand,activeConv:d,setActionLogs:n.setActionLogs,isStandalone:n.isStandalone});l.useEffect(()=>{o(Kr(t)),c(hd(t));const k=[t.onDidActiveChange(h=>o(h.isActive)),t.onDidActiveGroupChange(h=>{if(!Kr(t)&&!h.isActive){o(!1);return}o(Kr(t))}),t.onDidVisibilityChange(h=>c(h.isVisible))];return()=>{for(const h of k)h.dispose()}},[t]);const u=l.useMemo(()=>d?n.ides.find(k=>k.id===d.routeId):void 0,[n.ides,d]),m=l.useMemo(()=>d?n.actionLogs.filter(k=>k.routeId===d.tabKey):[],[n.actionLogs,d]);if(!d)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(yl,{conversationsCount:0,isSplitMode:!1,isStandalone:n.isStandalone,hasRegisteredMachines:n.hasRegisteredMachines,onOpenNewSession:n.onOpenNewSession,suppressGuide:n.hasDetachedConversationPanels})});const f=!dt(d)&&Fn(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(gl,{activeConv:d,clearToken:n.clearedTabs[d.tabKey]||0,isCliTerminal:f,ideEntry:u,terminalRef:r,handleModalButton:p.handleModalButton,handleRelaunch:p.handleRelaunch,handleSendChat:p.handleSendChat,handleForceSendChat:p.handleForceSendChat,isSendingChat:p.isSendingChat,handleFocusAgent:p.handleFocusAgent,isFocusingAgent:p.isFocusingAgent,actionLogs:m,userName:n.userName,scrollToBottomRequestNonce:((g=n.scrollToBottomRequest)==null?void 0:g.tabKey)===d.tabKey?n.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:i})})}function J1({visibleConversations:e,clearedTabs:t,ides:n,actionLogs:r,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:d,userName:p,toggleHiddenTab:u,actionShortcuts:m,registerActionHandlers:f,onActiveTabChange:g,onOpenNewSession:k,onRequestScrollToBottom:h,requestedActiveTabKey:v,requestedRemoteIdeId:w,onRequestedActiveTabConsumed:b,scrollToBottomRequest:j,liveSessionInboxState:C,layoutProfile:y}){var lt,ut,St;const{theme:x}=Ws(),{sendCommand:N}=wt(),S=l.useRef(null),A=l.useRef(null),T=l.useRef(null),I=l.useRef(!1),D=l.useRef(!1),P=l.useRef(!1),_=l.useRef(null),G=l.useRef([]),[H,L]=l.useState(null),[O,E]=l.useState(0),M=l.useRef(typeof window>"u"?{}:mj(y)),$=l.useMemo(()=>new Map(e.map(V=>[V.tabKey,V])),[e]),R=l.useMemo(()=>{const V=S.current;return V?V.groups.some(ee=>{try{const re=ee.model.location.type;return re!=="floating"&&re!=="popout"?!1:ee.panels.some(fe=>$.has(fe.id))}catch{return!1}}):!1},[$,O,e]),z=l.useCallback(()=>{var V;(V=S.current)==null||V.focus()},[]),Q=l.useCallback((V,ee)=>{h==null||h(V,ee)},[h]),ne=l.useCallback(V=>{const ee=document,re=V.document;for(const Te of ee.querySelectorAll('link[rel="stylesheet"]')){const qe=re.createElement("link");qe.rel="stylesheet",qe.href=Te.href,Te.crossOrigin&&(qe.crossOrigin=Te.crossOrigin),re.head.appendChild(qe)}for(const Te of ee.querySelectorAll("style")){const qe=re.createElement("style");qe.textContent=Te.textContent,re.head.appendChild(qe)}const fe=[];for(const Te of ee.styleSheets)try{for(const qe of Te.cssRules)qe instanceof CSSStyleRule&&(qe.selectorText===":root"||qe.selectorText==="html")&&fe.push(qe.cssText)}catch{}if(fe.length>0){const Te=re.createElement("style");Te.textContent=fe.join(`
|
|
71
71
|
`),re.head.appendChild(Te)}const ve=ee.documentElement.getAttribute("data-theme");ve&&re.documentElement.setAttribute("data-theme",ve),re.documentElement.style.colorScheme=ve==="light"?"light":"dark",re.body.className=ee.body.className;const De=ee.documentElement.getAttribute("style");De&&re.documentElement.setAttribute("style",De);const _e=re.getElementById("dv-popout-window");_e instanceof HTMLElement&&(_e.classList.add("adhdev-dockview"),Io(_e,x))},[x]),J=l.useCallback(()=>{var ee;const V=S.current;if(V)for(const re of V.groups)try{const fe=(ee=re.element)==null?void 0:ee.ownerDocument;if(!fe||fe===document)continue;const ve=fe.getElementById("dv-popout-window");ve instanceof HTMLElement&&(ve.classList.add("adhdev-dockview"),Io(ve,x));const De=document.documentElement.getAttribute("data-theme");De&&fe.documentElement.setAttribute("data-theme",De),fe.documentElement.style.colorScheme=De==="light"?"light":"dark",fe.body.className=document.body.className;const _e=document.documentElement.getAttribute("style");_e?fe.documentElement.setAttribute("style",_e):fe.documentElement.removeAttribute("style")}catch{}},[x]),Z=l.useCallback(V=>{const ee=S.current;if(!ee)return;const re=ee.getPanel(V);re&&ee.addPopoutGroup(re,{popoutUrl:"/popout.html",onDidOpen:({window:fe})=>{ne(fe),Se();const ve=$.get(V);fe.document.title=ve?`${yt(ve)} — ADHDev`:"ADHDev — Popout"}})},[$,ne]),de=l.useCallback(V=>{const ee=S.current,re=ee==null?void 0:ee.getPanel(V);if(!ee||!re)return;const fe=ee.groups.filter(ve=>{var De;try{return((De=ve.element)==null?void 0:De.ownerDocument)===document}catch{return!0}});fe.length>0?re.api.moveTo({group:fe[0],position:"center"}):re.api.moveTo({position:"center"}),re.api.setActive()},[]),te=l.useCallback(V=>{var fe;const ee=S.current;if(!ee)return!1;const re=ee.getPanel(V);if(!re)return!1;try{return((fe=re.group.element)==null?void 0:fe.ownerDocument)!==document}catch{return!1}},[]),B=l.useCallback(V=>{te(V)&&de(V),u(V)},[te,de,u]),ie=l.useCallback(V=>{const ee=S.current,re=ee==null?void 0:ee.getPanel(V);!ee||!re||ee.addFloatingGroup(re,{width:600,height:500})},[]),Y=l.useCallback(V=>{var re;const ee=(re=S.current)==null?void 0:re.getPanel(V);if(!ee)return!1;try{return ee.group.model.location.type==="floating"}catch{return!1}},[]),le=l.useCallback(()=>{var ee,re;const V=(re=(ee=S.current)==null?void 0:ee.activePanel)==null?void 0:re.id;return!V||cs(V)?null:$.has(V)?V:null},[$]),Ne=l.useCallback(V=>{const ee=S.current,re=ee==null?void 0:ee.getPanel(V);if(!ee||!re)return;const fe=ee.groups.filter(ve=>{try{return ve.model.location.type==="grid"}catch{return!0}});fe.length>0?re.api.moveTo({group:fe[0],position:"center"}):re.api.moveTo({position:"center"}),re.api.setActive()},[]),we=l.useCallback(()=>{var De;const V=S.current;if(!V)return;const re=V.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,fe=[...V.panels];for(const _e of fe){const Te=(De=_e.group.element)==null?void 0:De.ownerDocument,qe=_e.group.model.location.type;Te===document&&qe==="grid"||(re&&re.id!==_e.group.id?_e.api.moveTo({group:re,position:"center"}):_e.api.moveTo({position:"center"}))}const ve=V.activePanel;ve&&(ve.group.model.openPanel(ve),ve.api.setActive()),Do(document)},[]),Se=l.useCallback(()=>{var ee,re;const V=S.current;if(V)for(const fe of V.groups){const ve=(ee=fe.element)==null?void 0:ee.ownerDocument;if(!ve||ve===document)continue;const De=ve.getElementById("dv-popout-window");if(!(De instanceof HTMLElement))continue;let _e=null,Te=ve.title||"ADHDev",qe="Popout workspace";const Xe=fe.activePanel;if(Xe)if(_e=Xe.id,cs(Xe.id)){const $e=((re=Xe.params)==null?void 0:re.routeId)||Xe.id.slice(7),ae=fs([...$.values()],$e);Te=Dp(ae),qe=ae!=null&&ae.machineName?`Remote view · ${ae.machineName}`:"Remote view"}else{const $e=$.get(Xe.id);Te=$e?yt($e):Xe.title||Xe.id,qe=$e?en($e):"Dockview panel"}ve.title=`${Te} — ADHDev`;const Ve=Array.from(ve.querySelectorAll("#adhdev-popout-header"));for(const $e of Ve)$e.remove();const Fe=ve.createElement("div");Fe.id="adhdev-popout-header",ve.body.appendChild(Fe),Fe.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(";")),Fe.innerHTML=`
|
|
72
72
|
<div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
|
|
73
73
|
<div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
|
|
@@ -111,11 +111,11 @@ This will disconnect CDP and optionally kill the process.`))try{const $=await n(
|
|
|
111
111
|
|
|
112
112
|
`)}function mP(e,t){return t==="issues"?e.filter(n=>n.level==="warn"||n.level==="error"):t==="info"?e.filter(n=>n.level!=="debug"):e}function hP(e,t){return t==="issues"?e.filter(n=>n.level==="warn"||n.level==="error"):t==="info"?e.filter(n=>n.level!=="debug"):e}function fP({daemonLogs:e,daemonRawText:t,daemonLogKind:n,debugTrace:r,webEvents:a,traceCategory:o,quickFilter:i,searchQuery:c,daemonLoading:d,traceLoading:p,daemonFetchError:u,traceFetchError:m}){const f=qM(r,o),g=VM(e,c),k=QM(t,c),h=XM(f,c),v=ZM(a,c),w=mP(g,i),b=i==="all"?k:[],j=hP(h,i),C=i==="issues"?[]:v,y=eP({daemonLogs:g,daemonRawLines:k,trace:h,webEvents:v}),x=lP({daemonLogs:w,daemonRawLines:b,trace:j,webEvents:C}),N=dP(x),S=nP({daemonLoading:d,traceLoading:p,daemonFetchError:u,traceFetchError:m,daemonLogKind:n,daemonLogsCount:g.length,daemonRawLineCount:k.length,traceCount:h.length,webEventCount:v.length});return{filteredDaemonLogs:g,filteredDaemonRawLines:k,filteredTraceEntries:h,filteredWebEvents:v,visibleDaemonLogs:w,visibleDaemonRawLines:b,visibleTraceEntries:j,visibleWebEvents:C,quickFilterCounts:y,diagnosticEvents:x,diagnosticsSummary:N,sourceStates:S}}function bP(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function yh(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function Di(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 Uo(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 Pl(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function gP({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Di(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:yh(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:Pl(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 xP({quickFilter:e,quickFilterCounts:t,searchQuery:n,autoRefresh:r,onQuickFilterChange:a,onSearchQueryChange:o,onCopyDiagnostics:i,onCopyVisible:c,onToggleAutoRefresh:d,onRefresh:p,onClear:u}){return s.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"View"}),s.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${t.info})`},{id:"issues",label:`Issues (${t.issues})`},{id:"all",label:`All (${t.all})`}].map(m=>s.jsx("button",{type:"button",onClick:()=>a(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:d,className:`machine-btn ${r?"text-green-500 border-green-500/30":""}`,children:r?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:p,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:u,className:"machine-btn",children:"Clear"})]})]})}function vP({logLevel:e,traceCategory:t,onLogLevelChange:n,onTraceCategoryChange:r}){return s.jsx(Ps,{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(a=>s.jsxs("button",{onClick:()=>n(a),className:`machine-btn text-[10px] px-2 py-0.5 ${e===a?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:["Daemon ",a.toUpperCase(),"+"]},a))]}),s.jsx("div",{className:"flex flex-wrap gap-2 items-center",children:UM.map(a=>s.jsx("button",{onClick:()=>r(a.value),className:`machine-btn text-[10px] px-2 py-0.5 ${t===a.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:a.label},a.value))})]})})}function yP({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:n,searchQuery:r,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:i,traceFetchError:c}){var u,m;const d=((u=e.latestIssue)==null?void 0:u.severity)==="error"?"danger":((m=e.latestIssue)==null?void 0:m.severity)==="warn"?"warning":"good",p=i||c?"danger":o?"good":"neutral";return s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${Uo(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:r.trim()?`Filtered by “${r.trim()}”`:"Daemon, trace, and browser signals merged by time"})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${Uo(d)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Latest issue"}),e.latestIssue?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[Pl(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:yh(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 ${Uo(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: ",bP(a)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:n.map(f=>s.jsxs("div",{children:[f.label,": ",f.status]},f.id))})]})]})}function wP({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()," · ",Pl(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function kP({streams:e,sectionsOpen:t,setSectionsOpen:n,diagnosticEvents:r,visibleDaemonLogs:a,visibleDaemonRawLines:o,visibleTraceEntries:i,visibleWebEvents:c,quickFilter:d,searchQuery:p}){return s.jsxs("div",{className:"grid gap-3",children:[s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>n(u=>({...u,timeline:!u.timeline})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Unified timeline"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[r.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)&&r.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&r.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&&r.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),r.map(u=>s.jsx(gP,{event:u},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>n(u=>({...u,daemon:!u.daemon})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · daemon logs"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:e.daemonLogKind==="text"?`${o.length} visible raw line(s) from file fallback`:`${a.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&&a.length===0&&o.length===0&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),e.daemonLogKind==="text"&&o.length===0&&e.daemonRawText&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:d==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),e.daemonLogKind==="structured"&&a.length===0&&e.daemonLogs.length>0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),e.daemonLogKind==="text"&&o.map((u,m)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:u},`raw-${m}`)),e.daemonLogKind!=="text"&&a.map((u,m)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${Di(u.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(u.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:u.level==="error"?"ERR":u.level==="warn"?"WRN":u.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:u.message})]},`log-${m}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>n(u=>({...u,trace:!u.trace})),children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Raw source · daemon trace",e.traceCategory==="session_host"?" · session_host only":""]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[i.length," visible trace event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.trace?"Hide":"Show"})]}),t.trace&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.traceLoading&&i.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&i.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&i.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:p.trim()?"No trace entries match the current search.":e.traceCategory==="session_host"?"No session_host trace entries yet. This filter uses get_debug_trace(category=session_host).":"No trace entries yet. Run daemon with --dev or --trace."}),i.map(u=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Di(u.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),s.jsx("span",{children:u.level.toUpperCase()}),s.jsxs("span",{children:[u.category,".",u.stage]}),u.interactionId&&s.jsxs("span",{children:["ix=",u.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:$n(u.payload,360)||"No payload"})]},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>n(u=>({...u,web:!u.web})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · browser debug events"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[c.length," visible browser event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.web?"Hide":"Show"})]}),t.web&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[c.length===0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:p.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),c.map(u=>s.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),s.jsx("span",{children:u.kind}),u.topic&&s.jsxs("span",{children:["topic=",u.topic]}),u.interactionId&&s.jsxs("span",{children:["ix=",u.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:$n(u.payload,360)||"No payload"})]},u.id))]})]})]})}function SP({machineId:e,sendDaemonCommand:t}){const n=sP({machineId:e,sendDaemonCommand:t}),[r,a]=l.useState("info"),[o,i]=l.useState(""),[c,d]=l.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),p=l.useRef(null),u=l.useRef(!1),m=l.useMemo(()=>fP({daemonLogs:n.daemonLogs,daemonRawText:n.daemonRawText,daemonLogKind:n.daemonLogKind,debugTrace:n.debugTrace,webEvents:n.webEvents,traceCategory:n.traceCategory,quickFilter:r,searchQuery:o,daemonLoading:n.daemonLoading,traceLoading:n.traceLoading,daemonFetchError:n.daemonFetchError,traceFetchError:n.traceFetchError}),[r,o,n.daemonFetchError,n.daemonLoading,n.daemonLogKind,n.daemonLogs,n.daemonRawText,n.debugTrace,n.traceCategory,n.traceFetchError,n.traceLoading,n.webEvents]);l.useEffect(()=>{if(n.autoRefresh&&m.diagnosticEvents.length>0){const k=u.current?"smooth":"instant";setTimeout(()=>{var h;(h=p.current)==null||h.scrollIntoView({behavior:k}),u.current=!0},50)}},[m.diagnosticEvents.length,n.autoRefresh]);const f=l.useCallback(async()=>{var h;const k=tP({daemonLogs:m.visibleDaemonLogs,daemonRawLines:m.visibleDaemonRawLines,trace:m.visibleTraceEntries,webEvents:m.visibleWebEvents});if(!k.trim()){ht.showToast("No visible logs to copy.","info");return}try{await((h=navigator.clipboard)==null?void 0:h.writeText(k)),ht.showToast("Copied visible logs to clipboard.","success")}catch(v){ht.showToast(v instanceof Error?v.message:"Could not copy visible logs","warning")}},[m.visibleDaemonLogs,m.visibleDaemonRawLines,m.visibleTraceEntries,m.visibleWebEvents]),g=l.useCallback(async()=>{var h;const k=pP({events:m.diagnosticEvents,summary:m.diagnosticsSummary,sources:m.sourceStates});try{await((h=navigator.clipboard)==null?void 0:h.writeText(k)),ht.showToast("Copied diagnostic bundle to clipboard.","success")}catch(v){ht.showToast(v instanceof Error?v.message:"Could not copy diagnostic bundle","warning")}},[m.diagnosticEvents,m.diagnosticsSummary,m.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(xP,{quickFilter:r,quickFilterCounts:m.quickFilterCounts,searchQuery:o,autoRefresh:n.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:i,onCopyDiagnostics:()=>{g()},onCopyVisible:()=>{f()},onToggleAutoRefresh:()=>n.setAutoRefresh(k=>!k),onRefresh:n.refresh,onClear:n.clear}),s.jsx(vP,{logLevel:n.logLevel,traceCategory:n.traceCategory,onLogLevelChange:n.setLogLevel,onTraceCategoryChange:n.setTraceCategory}),s.jsx(yP,{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(wP,{patterns:m.diagnosticsSummary.repeatedPatterns}),s.jsx(kP,{streams:n,sectionsOpen:c,setSectionsOpen:d,diagnosticEvents:m.diagnosticEvents,visibleDaemonLogs:m.visibleDaemonLogs,visibleDaemonRawLines:m.visibleDaemonRawLines,visibleTraceEntries:m.visibleTraceEntries,visibleWebEvents:m.visibleWebEvents,quickFilter:r,searchQuery:o}),s.jsx("div",{ref:p})]})}function CP(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 wh(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 jP(e){var a;const t=[],n=[],r=[];for(const o of e||[]){const i=String((o==null?void 0:o.lifecycle)||"").trim(),c=wh((o==null?void 0:o.meta)||void 0),d=((a=o==null?void 0:o.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(i)?t.push(o):(i==="stopped"||i==="failed")&&(d||c)?n.push(o):r.push(o)}return{liveRuntimes:t,recoverySnapshots:n,inactiveRecords:r}}function NP(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Go(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 qo(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function zo(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Wd(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 r=Math.round(n/60);if(r<60)return`${r}m ago`;const a=Math.round(r/60);return a<48?`${a}h ago`:`${Math.round(a/24)}d ago`}function AP(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function TP(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 MP(e){var n;const t=new Map;for(const r of e){if(!["starting","running","stopping","interrupted"].includes(r.lifecycle))continue;const a=typeof((n=r.meta)==null?void 0:n.providerSessionId)=="string"?String(r.meta.providerSessionId).trim():"";if(!a)continue;const o=`${r.providerType}::${r.workspace}::${a}`;t.set(o,(t.get(o)||0)+1)}return Array.from(t.values()).filter(r=>r>1).length}function PP({machineId:e,cliSessions:t,sendDaemonCommand:n}){const[r,a]=l.useState(""),[o,i]=l.useState(null),[c,d]=l.useState(!1),p=EC(e,{enabled:!!e,includeSessions:!0,limit:wc,intervalMs:O0}),u=p.diagnostics,m=p.loading,f=p.applyDiagnostics,g=l.useMemo(()=>CP({diagnostics:u,loading:m,refreshing:c,error:r}),[u,m,c,r]),k=l.useMemo(()=>new Map(t.map(I=>[I.sessionId||I.id,I])),[t]),h=l.useCallback(async()=>{if(e){d(!0);try{const I=await n(e,"session_host_get_diagnostics",{includeSessions:!0,limit:wc}),D=qo(I);if(!(D!=null&&D.success))throw new Error((D==null?void 0:D.error)||"Could not load hosted runtime diagnostics");f(D.diagnostics||D.result||null),a("")}catch(I){const D=I instanceof Error?I.message:"Could not load hosted runtime diagnostics";a(D)}finally{d(!1)}}},[f,e,n]);l.useEffect(()=>{!e||u||m||c||h()},[u,m,e,h,c]);const v=l.useCallback(async(I,D)=>{const P=`${I}:${D.sessionId}`;if(!(I==="session_host_stop_session"&&!window.confirm(`Stop ${D.displayName}?
|
|
113
113
|
This will terminate the hosted runtime.`))){i(P);try{const _=await n(e,I,{sessionId:D.sessionId}),G=qo(_);if(!(G!=null&&G.success))throw new Error((G==null?void 0:G.error)||"Session host action failed");const H=I==="session_host_resume_session"?"resumed":I==="session_host_restart_session"?"restarted":"stopped";ht.showToast(`Session host ${H}: ${D.displayName}`,"success"),await h()}catch(_){const G=_ instanceof Error?_.message:"Session host action failed";ht.showToast(G,"warning"),a(G)}finally{i(_=>_===P?null:_)}}},[e,h,n]),w=l.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
|
|
114
|
-
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){i("session_host_prune_duplicate_sessions");try{const D=await n(e,"session_host_prune_duplicate_sessions",{}),P=qo(D);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Duplicate prune failed");const _=P.result||{},G=Array.isArray(_.prunedSessionIds)?_.prunedSessionIds.length:0,H=typeof _.duplicateGroupCount=="number"?_.duplicateGroupCount:0;ht.showToast(`Pruned ${G} duplicate runtime(s) across ${H} group(s)`,"success"),await h()}catch(D){const P=D instanceof Error?D.message:"Duplicate prune failed";ht.showToast(P,"warning"),a(P)}finally{i(D=>D==="session_host_prune_duplicate_sessions"?null:D)}}},[e,h,n]),b=l.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((I,D)=>(D.lastActivityAt||0)-(I.lastActivityAt||0)),[u==null?void 0:u.sessions]),j=l.useMemo(()=>u!=null&&u.liveRuntimes||u!=null&&u.recoverySnapshots||u!=null&&u.inactiveRecords?{liveRuntimes:(u==null?void 0:u.liveRuntimes)||[],recoverySnapshots:(u==null?void 0:u.recoverySnapshots)||[],inactiveRecords:(u==null?void 0:u.inactiveRecords)||[]}:jP(b),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,b]),C=j.liveRuntimes,y=j.recoverySnapshots,x=j.inactiveRecords,N=l.useMemo(()=>MP(C),[C]),S=l.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),A=l.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(I=>I.level==="warn"||I.level==="error")||null,[u==null?void 0:u.recentLogs]),T=(I,D)=>{var $;const P=o===`session_host_resume_session:${I.sessionId}`,_=o===`session_host_restart_session:${I.sessionId}`,G=o===`session_host_stop_session:${I.sessionId}`,H=wh(I.meta),L=k.get(I.sessionId),O=I.attachedClients.length===1?"1 client":`${I.attachedClients.length} clients`,E=D==="recovery"?"Recover":"Resume",M=NP(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||(L==null?void 0:L.cliName)||I.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${TP(I.lifecycle)}`,children:I.lifecycle}),H&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:H})]}),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||(L==null?void 0:L.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:AP(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(pu,{size:11})," ",O]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",Wd(I.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",M]})]})]}),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:()=>{v("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:()=>{v("session_host_restart_session",I)},children:_?"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:()=>{v("session_host_stop_session",I)},children:G?"Stopping…":"Stop"})]})]})},I.sessionId)};return s.jsxs(Ps,{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(Fs,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:bS()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[N>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 (${N})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${g.toneClass}`,children:g.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{h()},disabled:m||c,children:[s.jsx(_a,{size:13}),m||c?"Refreshing…":"Refresh"]})]})]}),r&&!u&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(on,{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:r})]})]})}),u&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:y.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:Wd(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:zo(u.hostStartedAt)})]})]}),A&&s.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[s.jsx(on,{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:[zo(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(Ui,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Go("live")}),C.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):s.jsx("div",{className:"space-y-2",children:C.map(I=>T(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(Fs,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Go("recovery")}),y.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:y.map(I=>T(I,"recovery"))})]}),x.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:Go("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:x.map(I=>T(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(_=>_.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:zo(I.timestamp)})]},`${I.sessionId}:${I.timestamp}:${I.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:u.endpoint||"unknown"}),r?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",r]}):null]})]})]})}function DP({machine:e,launchPick:t,actions:n}){const{t:r}=Ce("common"),{runLaunchCliCore:a,setLaunchPick:o}=n;return 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",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",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),a({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),a({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:r("newSession.defaultWorkspace")}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{o(null),a({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:r("newSession.homeDirectory")}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>o(null),children:"Cancel"})]})]})})}function IP(e,t){const n=dm(e),r=kn(e,t),a=ll(e,r),o=ur(e,r),i=n==="preview"?"Update to preview":"Update daemon";return a?{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:r,channel:n,required:o,tone:"warn"}:n==="preview"?{visible:!0,showButton:!1,title:r?"Preview daemon is up to date":"Preview update status unknown",description:r?"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:r,channel:n,required:!1,tone:r?"good":"info"}:{visible:!1,showButton:!1,title:"",description:"",buttonLabel:i,targetVersion:r,channel:n,required:!1,tone:"info"}}function Ko({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 Vo({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 LP({machineEntry:e,providers:t,recentLaunches:n,currentConversations:r,onUpgradeDaemon:a,onOpenRecent:o,onOpenConversation:i}){const{t:c}=Ce("common"),d=r.slice(0,6),p=n.slice(0,4),m=IP(e,"1.0.24");return s.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ko,{icon:s.jsx(un,{size:13}),children:c("machine.commandCenter.currentChats")}),s.jsx(Vo,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(f=>{const g=Ni(f);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>i(f),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:yt(f)}),g>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:$a(g)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:In(f)})]},f.tabKey)})})})]}),p.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ko,{icon:s.jsx(gu,{size:13}),children:c("machine.commandCenter.recentLaunches")}),s.jsx(Vo,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:p.map(f=>{const{metaText:g,updatedLabel:k}=wm(f);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>o(f),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:f.label}),k&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:k})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:g})]},f.id)})})})]}),m.visible&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ko,{icon:s.jsx(on,{size:13}),children:c("machine.commandCenter.daemonUpdate")}),s.jsx(Vo,{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:a,children:[s.jsx(_a,{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 RP({machineId:e,machine:t,ideSessions:n,cliSessions:r,acpSessions:a,actions:o,sendDaemonCommand:i}){const{workspaceBusy:c,handleWorkspaceAdd:d,handleWorkspaceRemove:p,handleWorkspaceSetDefault:u}=o,{t:m}=Ce("common"),[f,g]=l.useState(!1),[k,h]=l.useState(""),[v,w]=l.useState([]),[b,j]=l.useState(!1),[C,y]=l.useState(""),x=l.useCallback(async S=>{j(!0),y("");try{const A=await bl(i,e,S);h(A.path),w(A.directories)}catch(A){y(A instanceof Error?A.message:"Could not load folder")}finally{j(!1)}},[e,i]),N=l.useCallback(()=>{g(!0);const S=[...n.map(T=>T.workspace),...r.map(T=>T.workspace),...a.map(T=>T.workspace)],A=fl(t.platform,hl(S,t.defaultWorkspacePath,(t.workspaces||[]).map(T=>T.path)));x(A)},[a,r,n,x,t.defaultWorkspacePath,t.platform,t.workspaces]);return s.jsxs(s.Fragment,{children:[s.jsxs(Ps,{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(Pn,{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:N,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 u(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:Fu(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)})})]}),f&&s.jsx(xl,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:k,directories:v,busy:b,error:C,confirmLabel:"Add workspace",onClose:()=>g(!1),onNavigate:S=>{x(S)},onConfirm:S=>{(async()=>{if(!S)return;await d(S)&&g(!1)})()}})]})}function EP({machine:e,machineId:t,ideSessions:n,cliSessions:r,acpSessions:a,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(RP,{machineId:t,machine:e,ideSessions:n,cliSessions:r,acpSessions:a,actions:o,sendDaemonCommand:i})]})}function _P({onNicknameSynced:e}={}){var we,Se,me,q,W,X,K,ue,Pe,ce;const{t}=Ce("common"),{id:n}=nf(),r=Cr(),a=_i(),{sendCommand:o}=wt(),i=Bn(),c=Zp(),d=jp(),p=d.ides||[],u=d.initialLoaded??!0,m=p.find(F=>F.id===n&&F.type==="adhdev-daemon"),f=p.some(F=>F.type==="adhdev-daemon"),g=n?(we=d.connectionRetryStatuses)==null?void 0:we[n]:void 0,k=!!(g!=null&&g.blocked),[h,v]=l.useState("workspace"),[w,b]=l.useState(null);l.useCallback((F,pe)=>{b({daemonId:F,workspace:pe})},[]);const[,j]=l.useState("ide"),C=l.useRef(null),[y,x]=l.useState(null),N=l.useRef("__home__"),[S,A]=l.useState("__home__"),[T,I]=l.useState(!1),D=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||h!=="overview")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")&&c(n,{minFreshMs:3e4}).catch(()=>{})},[h,c,m,n]),RC(n&&h==="overview"?[n]:[],{enabled:h==="overview",intervalMs:H0});const P=()=>{if(f){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},_=MM({machineId:n,registeredMachineId:(m==null?void 0:m.machineId)||null,sendDaemonCommand:o,onNicknameSynced:e,logsEndRef:D});l.useEffect(()=>ht.onToast(pe=>{d.setToasts(U=>{if(U.some(ge=>ge.message===pe.message&&pe.timestamp-ge.timestamp<3e3))return U;const je={id:pe.id,message:pe.message,type:pe.type,timestamp:pe.timestamp,targetKey:pe.targetKey,actions:pe.actions};return[...U.slice(-4),je]});const xe=pe.duration||5e3;setTimeout(()=>d.setToasts(U=>U.filter(be=>be.id!==pe.id)),xe)}),[d]);const G=(m==null?void 0:m.availableProviders)||[],H={};for(const F of G)H[F.type]=F.icon;const L=m?{id:m.id,hostname:Bu(m,{fallbackId:m.id}),platform:((Se=m.machine)==null?void 0:Se.platform)||"unknown",arch:((me=m.machine)==null?void 0:me.arch)||"",cpus:((q=m.machine)==null?void 0:q.cpus)||0,totalMem:((W=m.machine)==null?void 0:W.totalMem)||0,freeMem:(X=m.machine)==null?void 0:X.freeMem,availableMem:(K=m.machine)==null?void 0:K.availableMem,loadavg:(ue=m.machine)==null?void 0:ue.loadavg,uptime:(Pe=m.machine)==null?void 0:Pe.uptime,release:((ce=m.machine)==null?void 0:ce.release)||"",cdpConnected:!!m.cdpConnected,machineNickname:m.machineNickname||null,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,O=p.filter(F=>F.daemonId===n&&F.type!=="adhdev-daemon").filter(F=>!xr(F)&&!Nn(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:Zy(F.aiAgents||(F.agents||[]).map(pe=>({id:pe.name,name:pe.name,status:pe.status,version:pe.version}))),activeChat:F.activeChat||null,chats:F.chats||[],childSessions:F.childSessions||[],cdpConnected:F.cdpConnected||!1,daemonId:n,lastMessageAt:F.lastMessageAt})),E=p.filter(F=>F.daemonId===n&&xr(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})),M=p.filter(F=>F.daemonId===n&&Nn(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})),$=m?as(m,{fallbackId:n}):"",R="workspace",z=a.state,Q=z==null?void 0:z.initialMachineTab,ne=z==null?void 0:z.initialWorkspaceCategory;z==null||z.initialWorkspaceId,z==null||z.initialWorkspacePath;const J=Q==="ides"||Q==="clis"||Q==="acps"?"workspace":Q||R,Z=Q==="ides"?"ide":Q==="clis"?"cli":Q==="acps"?"acp":ne,de=[...O.map(F=>{var pe;return{id:`ide:${F.type}:${F.workspace||""}`,label:((pe=F.activeChat)==null?void 0:pe.title)||F.type,kind:"ide",providerType:F.type,subtitle:F.workspace||void 0,workspace:F.workspace||void 0,lastLaunchedAt:F.lastMessageAt||0}}),...E.map(F=>{var pe;return{id:`cli:${F.type}:${F.workspace||""}`,label:((pe=F.activeChat)==null?void 0:pe.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}}),...M.map(F=>{var pe;return{id:`acp:${F.type}:${F.workspace||""}`,label:((pe=F.activeChat)==null?void 0:pe.title)||F.acpName,kind:"acp",providerType:F.type,providerSessionId:F.providerSessionId,subtitle:ln(F.summaryMetadata)||F.workspace||void 0,workspace:F.workspace||void 0,lastLaunchedAt:F.lastMessageAt||0}})].sort((F,pe)=>(pe.lastLaunchedAt||0)-(F.lastLaunchedAt||0)),te=((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:ln(F.summaryMetadata)||F.workspace||void 0,workspace:F.workspace,summaryMetadata:F.summaryMetadata,lastLaunchedAt:F.lastLaunchedAt})):de,B=l.useMemo(()=>{var pe;const F=((pe=d.connectionStates)==null?void 0:pe[n||""])||void 0;return p.filter(xe=>xe.daemonId===n&&xe.type!=="adhdev-daemon").flatMap(xe=>il(xe,{connectionStates:n&&F?{[n]:F}:void 0,defaultConnectionState:F})).filter(xe=>!(xe.transport==="pty"&&xe.mode==="terminal")).sort((xe,U)=>Ni(U)-Ni(xe))},[p,d.connectionStates,n]),ie=l.useCallback(F=>{const pe=hm(F);pe&&r(wr(pe))},[r]),Y=l.useCallback(()=>{C.current&&(I(!0),C.current().finally(()=>{C.current=null,I(!1),x(null)}))},[]),le=l.useCallback(F=>{if(!L)return;const{options:pe,selectedKey:xe}=ym({machine:L,currentWorkspacePath:F.workspace,homeLabel:t("newSession.homeDirectory"),homeDescription:t("newSession.launchWithoutWorkspace")}),U=async()=>{j(F.kind),v("workspace")};C.current=async()=>{const be=pe.find(Ie=>Ie.key===N.current),je=(be==null?void 0:be.workspacePath)??null,ge=(be==null?void 0:be.workspaceId)??null;if(F.kind==="ide"&&F.providerType){await _.handleLaunchIde(F.providerType,je?{workspace:je}:void 0);return}if((F.kind==="cli"||F.kind==="acp")&&F.providerType){await _.runLaunchCliCore({cliType:F.providerType,dir:ge?void 0:je||"",workspaceId:ge||void 0,model:F.kind==="acp"&&Wu(F.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:F.providerSessionId});return}await U()},N.current=xe,A(xe),x({title:F.kind==="ide"?Sa(t,"restart-ide",F.label):F.providerSessionId?_p(t,F.label):Sa(t,"start-fresh",F.label),description:F.kind==="ide"?Ca(t,"restart-ide"):F.providerSessionId?$p(t):Ca(t,"start-fresh"),confirmLabel:F.kind==="ide"?ja(t,"restart-ide"):F.providerSessionId?vi(t,!0):ja(t,"start-fresh"),busyLabel:F.kind==="ide"?Na(t,"restart-ide"):F.providerSessionId?Ep(t,!0):Na(t,"start-fresh"),workspaceOptions:pe,details:[{label:"Mode",value:F.kind.toUpperCase()},...F.providerType?[{label:"Provider",value:F.providerType}]:[]]})},[_,L]);if(l.useEffect(()=>{v(J)},[R,J,n]),l.useEffect(()=>{Z&&j(Z)},[Z,n]),!L)return u?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:t("machine.detail.notFound")}),s.jsx("p",{className:"mt-3",children:t("machine.detail.offlineHint")}),s.jsx("button",{onClick:P,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 Ne=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(gs,{size:14})," ",t("machine.detail.tabWorkspace")]}),count:O.length+E.length+M.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Fs,{size:14})," ",t("machine.detail.tabHostedRuntimes")]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ea,{size:14})," ",t("machine.detail.tabProviders")]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Jf,{size:14})," ",t("machine.detail.tabSystem")]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(hu,{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-[#ffffff0a]",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:P,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] 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:[_.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:_.nicknameInput,onChange:F=>_.setNicknameInput(F.target.value),onKeyDown:F=>{F.key==="Enter"&&_.handleSaveNickname(),F.key==="Escape"&&_.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:_.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:()=>_.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] 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:()=>{_.setEditingNickname(!0),_.setNicknameInput(L.machineNickname||"")},title:t("machine.detail.clickToSetNickname"),children:$}),k?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),d.retryConnection&&n&&s.jsx("button",{onClick:()=>d.retryConnection(n),className:"px-2.5 py-0.5 rounded text-[11px] font-semibold bg-red-500/10 border border-red-500/20 text-red-400 hover:bg-red-500/20 transition-colors",children:t("machine.detail.reconnect")})]}):s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[s.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[L.platform," · ",L.arch]}),s.jsx("span",{children:t("machine.detail.coresCount",{count:L.cpus})}),(m==null?void 0:m.version)&&s.jsxs("span",{children:["v",m.version]}),L.p2p.available&&s.jsx("span",{children:t("machine.detail.p2pState",{state:L.p2p.state==="connected"?t("machine.detail.p2pConnected"):L.p2p.state})}),L.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:L.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:Ne.map(F=>s.jsxs("button",{onClick:()=>v(F.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${h===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 ${h===F.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] 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:[h==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(LP,{machineEntry:m,providers:G,recentLaunches:te,currentConversations:B,onUpgradeDaemon:async()=>{try{await o(n,"daemon_upgrade",um(m))}catch{}},onOpenRecent:le,onOpenConversation:ie}),s.jsx(EP,{machine:L,machineId:n,ideSessions:O,cliSessions:E,acpSessions:M,actions:_,sendDaemonCommand:o})]}),h==="providers"&&s.jsx(WM,{machineId:n,providers:G,sendDaemonCommand:o}),h==="overview"&&s.jsx(PM,{machine:L,ideSessions:O,cliSessions:E,acpSessions:M}),h==="session-host"&&s.jsx(PP,{machineId:n,cliSessions:E,sendDaemonCommand:o}),h==="logs"&&s.jsx(SP,{machineId:n,sendDaemonCommand:o})]})})}),_.launchPick&&L&&s.jsx(DP,{machine:L,launchPick:_.launchPick,actions:_}),y&&s.jsx(vl,{title:y.title,description:y.description,details:y.details,workspaceOptions:y.workspaceOptions,selectedWorkspaceKey:S,onWorkspaceChange:F=>{N.current=F,A(F)},confirmLabel:y.confirmLabel,busyLabel:y.busyLabel,busy:T,onConfirm:Y,onCancel:()=>{C.current=null,x(null)}}),w&&s.jsx(vh,{daemonId:w.daemonId,workspace:w.workspace,onClose:()=>b(null)}),s.jsx(Fp,{toasts:d.toasts||[],onDismiss:F=>d.setToasts(pe=>pe.filter(xe=>xe.id!==F)),onClickToast:F=>{F.targetKey&&r(wr(F.targetKey))}}),s.jsx("style",{children:`
|
|
114
|
+
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){i("session_host_prune_duplicate_sessions");try{const D=await n(e,"session_host_prune_duplicate_sessions",{}),P=qo(D);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Duplicate prune failed");const _=P.result||{},G=Array.isArray(_.prunedSessionIds)?_.prunedSessionIds.length:0,H=typeof _.duplicateGroupCount=="number"?_.duplicateGroupCount:0;ht.showToast(`Pruned ${G} duplicate runtime(s) across ${H} group(s)`,"success"),await h()}catch(D){const P=D instanceof Error?D.message:"Duplicate prune failed";ht.showToast(P,"warning"),a(P)}finally{i(D=>D==="session_host_prune_duplicate_sessions"?null:D)}}},[e,h,n]),b=l.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((I,D)=>(D.lastActivityAt||0)-(I.lastActivityAt||0)),[u==null?void 0:u.sessions]),j=l.useMemo(()=>u!=null&&u.liveRuntimes||u!=null&&u.recoverySnapshots||u!=null&&u.inactiveRecords?{liveRuntimes:(u==null?void 0:u.liveRuntimes)||[],recoverySnapshots:(u==null?void 0:u.recoverySnapshots)||[],inactiveRecords:(u==null?void 0:u.inactiveRecords)||[]}:jP(b),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,b]),C=j.liveRuntimes,y=j.recoverySnapshots,x=j.inactiveRecords,N=l.useMemo(()=>MP(C),[C]),S=l.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),A=l.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(I=>I.level==="warn"||I.level==="error")||null,[u==null?void 0:u.recentLogs]),T=(I,D)=>{var $;const P=o===`session_host_resume_session:${I.sessionId}`,_=o===`session_host_restart_session:${I.sessionId}`,G=o===`session_host_stop_session:${I.sessionId}`,H=wh(I.meta),L=k.get(I.sessionId),O=I.attachedClients.length===1?"1 client":`${I.attachedClients.length} clients`,E=D==="recovery"?"Recover":"Resume",M=NP(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||(L==null?void 0:L.cliName)||I.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${TP(I.lifecycle)}`,children:I.lifecycle}),H&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:H})]}),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||(L==null?void 0:L.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:AP(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(pu,{size:11})," ",O]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",Wd(I.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",M]})]})]}),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:()=>{v("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:()=>{v("session_host_restart_session",I)},children:_?"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:()=>{v("session_host_stop_session",I)},children:G?"Stopping…":"Stop"})]})]})},I.sessionId)};return s.jsxs(Ps,{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(Fs,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:bS()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[N>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 (${N})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${g.toneClass}`,children:g.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{h()},disabled:m||c,children:[s.jsx(_a,{size:13}),m||c?"Refreshing…":"Refresh"]})]})]}),r&&!u&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(on,{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:r})]})]})}),u&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:y.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:Wd(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:zo(u.hostStartedAt)})]})]}),A&&s.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[s.jsx(on,{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:[zo(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(Ui,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Go("live")}),C.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):s.jsx("div",{className:"space-y-2",children:C.map(I=>T(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(Fs,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Go("recovery")}),y.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:y.map(I=>T(I,"recovery"))})]}),x.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:Go("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:x.map(I=>T(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(_=>_.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:zo(I.timestamp)})]},`${I.sessionId}:${I.timestamp}:${I.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:u.endpoint||"unknown"}),r?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",r]}):null]})]})]})}function DP({machine:e,launchPick:t,actions:n}){const{t:r}=Ce("common"),{runLaunchCliCore:a,setLaunchPick:o}=n;return 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",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",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),a({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),a({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:r("newSession.defaultWorkspace")}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{o(null),a({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:r("newSession.homeDirectory")}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>o(null),children:"Cancel"})]})]})})}function IP(e,t){const n=dm(e),r=kn(e,t),a=ll(e,r),o=ur(e,r),i=n==="preview"?"Update to preview":"Update daemon";return a?{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:r,channel:n,required:o,tone:"warn"}:n==="preview"?{visible:!0,showButton:!1,title:r?"Preview daemon is up to date":"Preview update status unknown",description:r?"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:r,channel:n,required:!1,tone:r?"good":"info"}:{visible:!1,showButton:!1,title:"",description:"",buttonLabel:i,targetVersion:r,channel:n,required:!1,tone:"info"}}function Ko({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 Vo({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 LP({machineEntry:e,providers:t,recentLaunches:n,currentConversations:r,onUpgradeDaemon:a,onOpenRecent:o,onOpenConversation:i}){const{t:c}=Ce("common"),d=r.slice(0,6),p=n.slice(0,4),m=IP(e,"1.0.26");return s.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ko,{icon:s.jsx(un,{size:13}),children:c("machine.commandCenter.currentChats")}),s.jsx(Vo,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(f=>{const g=Ni(f);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>i(f),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:yt(f)}),g>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:$a(g)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:In(f)})]},f.tabKey)})})})]}),p.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ko,{icon:s.jsx(gu,{size:13}),children:c("machine.commandCenter.recentLaunches")}),s.jsx(Vo,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:p.map(f=>{const{metaText:g,updatedLabel:k}=wm(f);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>o(f),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:f.label}),k&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:k})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:g})]},f.id)})})})]}),m.visible&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ko,{icon:s.jsx(on,{size:13}),children:c("machine.commandCenter.daemonUpdate")}),s.jsx(Vo,{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:a,children:[s.jsx(_a,{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 RP({machineId:e,machine:t,ideSessions:n,cliSessions:r,acpSessions:a,actions:o,sendDaemonCommand:i}){const{workspaceBusy:c,handleWorkspaceAdd:d,handleWorkspaceRemove:p,handleWorkspaceSetDefault:u}=o,{t:m}=Ce("common"),[f,g]=l.useState(!1),[k,h]=l.useState(""),[v,w]=l.useState([]),[b,j]=l.useState(!1),[C,y]=l.useState(""),x=l.useCallback(async S=>{j(!0),y("");try{const A=await bl(i,e,S);h(A.path),w(A.directories)}catch(A){y(A instanceof Error?A.message:"Could not load folder")}finally{j(!1)}},[e,i]),N=l.useCallback(()=>{g(!0);const S=[...n.map(T=>T.workspace),...r.map(T=>T.workspace),...a.map(T=>T.workspace)],A=fl(t.platform,hl(S,t.defaultWorkspacePath,(t.workspaces||[]).map(T=>T.path)));x(A)},[a,r,n,x,t.defaultWorkspacePath,t.platform,t.workspaces]);return s.jsxs(s.Fragment,{children:[s.jsxs(Ps,{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(Pn,{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:N,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 u(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:Fu(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)})})]}),f&&s.jsx(xl,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:k,directories:v,busy:b,error:C,confirmLabel:"Add workspace",onClose:()=>g(!1),onNavigate:S=>{x(S)},onConfirm:S=>{(async()=>{if(!S)return;await d(S)&&g(!1)})()}})]})}function EP({machine:e,machineId:t,ideSessions:n,cliSessions:r,acpSessions:a,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(RP,{machineId:t,machine:e,ideSessions:n,cliSessions:r,acpSessions:a,actions:o,sendDaemonCommand:i})]})}function _P({onNicknameSynced:e}={}){var we,Se,me,q,W,X,K,ue,Pe,ce;const{t}=Ce("common"),{id:n}=nf(),r=Cr(),a=_i(),{sendCommand:o}=wt(),i=Bn(),c=Zp(),d=jp(),p=d.ides||[],u=d.initialLoaded??!0,m=p.find(F=>F.id===n&&F.type==="adhdev-daemon"),f=p.some(F=>F.type==="adhdev-daemon"),g=n?(we=d.connectionRetryStatuses)==null?void 0:we[n]:void 0,k=!!(g!=null&&g.blocked),[h,v]=l.useState("workspace"),[w,b]=l.useState(null);l.useCallback((F,pe)=>{b({daemonId:F,workspace:pe})},[]);const[,j]=l.useState("ide"),C=l.useRef(null),[y,x]=l.useState(null),N=l.useRef("__home__"),[S,A]=l.useState("__home__"),[T,I]=l.useState(!1),D=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||h!=="overview")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")&&c(n,{minFreshMs:3e4}).catch(()=>{})},[h,c,m,n]),RC(n&&h==="overview"?[n]:[],{enabled:h==="overview",intervalMs:H0});const P=()=>{if(f){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},_=MM({machineId:n,registeredMachineId:(m==null?void 0:m.machineId)||null,sendDaemonCommand:o,onNicknameSynced:e,logsEndRef:D});l.useEffect(()=>ht.onToast(pe=>{d.setToasts(U=>{if(U.some(ge=>ge.message===pe.message&&pe.timestamp-ge.timestamp<3e3))return U;const je={id:pe.id,message:pe.message,type:pe.type,timestamp:pe.timestamp,targetKey:pe.targetKey,actions:pe.actions};return[...U.slice(-4),je]});const xe=pe.duration||5e3;setTimeout(()=>d.setToasts(U=>U.filter(be=>be.id!==pe.id)),xe)}),[d]);const G=(m==null?void 0:m.availableProviders)||[],H={};for(const F of G)H[F.type]=F.icon;const L=m?{id:m.id,hostname:Bu(m,{fallbackId:m.id}),platform:((Se=m.machine)==null?void 0:Se.platform)||"unknown",arch:((me=m.machine)==null?void 0:me.arch)||"",cpus:((q=m.machine)==null?void 0:q.cpus)||0,totalMem:((W=m.machine)==null?void 0:W.totalMem)||0,freeMem:(X=m.machine)==null?void 0:X.freeMem,availableMem:(K=m.machine)==null?void 0:K.availableMem,loadavg:(ue=m.machine)==null?void 0:ue.loadavg,uptime:(Pe=m.machine)==null?void 0:Pe.uptime,release:((ce=m.machine)==null?void 0:ce.release)||"",cdpConnected:!!m.cdpConnected,machineNickname:m.machineNickname||null,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,O=p.filter(F=>F.daemonId===n&&F.type!=="adhdev-daemon").filter(F=>!xr(F)&&!Nn(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:Zy(F.aiAgents||(F.agents||[]).map(pe=>({id:pe.name,name:pe.name,status:pe.status,version:pe.version}))),activeChat:F.activeChat||null,chats:F.chats||[],childSessions:F.childSessions||[],cdpConnected:F.cdpConnected||!1,daemonId:n,lastMessageAt:F.lastMessageAt})),E=p.filter(F=>F.daemonId===n&&xr(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})),M=p.filter(F=>F.daemonId===n&&Nn(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})),$=m?as(m,{fallbackId:n}):"",R="workspace",z=a.state,Q=z==null?void 0:z.initialMachineTab,ne=z==null?void 0:z.initialWorkspaceCategory;z==null||z.initialWorkspaceId,z==null||z.initialWorkspacePath;const J=Q==="ides"||Q==="clis"||Q==="acps"?"workspace":Q||R,Z=Q==="ides"?"ide":Q==="clis"?"cli":Q==="acps"?"acp":ne,de=[...O.map(F=>{var pe;return{id:`ide:${F.type}:${F.workspace||""}`,label:((pe=F.activeChat)==null?void 0:pe.title)||F.type,kind:"ide",providerType:F.type,subtitle:F.workspace||void 0,workspace:F.workspace||void 0,lastLaunchedAt:F.lastMessageAt||0}}),...E.map(F=>{var pe;return{id:`cli:${F.type}:${F.workspace||""}`,label:((pe=F.activeChat)==null?void 0:pe.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}}),...M.map(F=>{var pe;return{id:`acp:${F.type}:${F.workspace||""}`,label:((pe=F.activeChat)==null?void 0:pe.title)||F.acpName,kind:"acp",providerType:F.type,providerSessionId:F.providerSessionId,subtitle:ln(F.summaryMetadata)||F.workspace||void 0,workspace:F.workspace||void 0,lastLaunchedAt:F.lastMessageAt||0}})].sort((F,pe)=>(pe.lastLaunchedAt||0)-(F.lastLaunchedAt||0)),te=((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:ln(F.summaryMetadata)||F.workspace||void 0,workspace:F.workspace,summaryMetadata:F.summaryMetadata,lastLaunchedAt:F.lastLaunchedAt})):de,B=l.useMemo(()=>{var pe;const F=((pe=d.connectionStates)==null?void 0:pe[n||""])||void 0;return p.filter(xe=>xe.daemonId===n&&xe.type!=="adhdev-daemon").flatMap(xe=>il(xe,{connectionStates:n&&F?{[n]:F}:void 0,defaultConnectionState:F})).filter(xe=>!(xe.transport==="pty"&&xe.mode==="terminal")).sort((xe,U)=>Ni(U)-Ni(xe))},[p,d.connectionStates,n]),ie=l.useCallback(F=>{const pe=hm(F);pe&&r(wr(pe))},[r]),Y=l.useCallback(()=>{C.current&&(I(!0),C.current().finally(()=>{C.current=null,I(!1),x(null)}))},[]),le=l.useCallback(F=>{if(!L)return;const{options:pe,selectedKey:xe}=ym({machine:L,currentWorkspacePath:F.workspace,homeLabel:t("newSession.homeDirectory"),homeDescription:t("newSession.launchWithoutWorkspace")}),U=async()=>{j(F.kind),v("workspace")};C.current=async()=>{const be=pe.find(Ie=>Ie.key===N.current),je=(be==null?void 0:be.workspacePath)??null,ge=(be==null?void 0:be.workspaceId)??null;if(F.kind==="ide"&&F.providerType){await _.handleLaunchIde(F.providerType,je?{workspace:je}:void 0);return}if((F.kind==="cli"||F.kind==="acp")&&F.providerType){await _.runLaunchCliCore({cliType:F.providerType,dir:ge?void 0:je||"",workspaceId:ge||void 0,model:F.kind==="acp"&&Wu(F.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:F.providerSessionId});return}await U()},N.current=xe,A(xe),x({title:F.kind==="ide"?Sa(t,"restart-ide",F.label):F.providerSessionId?_p(t,F.label):Sa(t,"start-fresh",F.label),description:F.kind==="ide"?Ca(t,"restart-ide"):F.providerSessionId?$p(t):Ca(t,"start-fresh"),confirmLabel:F.kind==="ide"?ja(t,"restart-ide"):F.providerSessionId?vi(t,!0):ja(t,"start-fresh"),busyLabel:F.kind==="ide"?Na(t,"restart-ide"):F.providerSessionId?Ep(t,!0):Na(t,"start-fresh"),workspaceOptions:pe,details:[{label:"Mode",value:F.kind.toUpperCase()},...F.providerType?[{label:"Provider",value:F.providerType}]:[]]})},[_,L]);if(l.useEffect(()=>{v(J)},[R,J,n]),l.useEffect(()=>{Z&&j(Z)},[Z,n]),!L)return u?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:t("machine.detail.notFound")}),s.jsx("p",{className:"mt-3",children:t("machine.detail.offlineHint")}),s.jsx("button",{onClick:P,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 Ne=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(gs,{size:14})," ",t("machine.detail.tabWorkspace")]}),count:O.length+E.length+M.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Fs,{size:14})," ",t("machine.detail.tabHostedRuntimes")]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ea,{size:14})," ",t("machine.detail.tabProviders")]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Jf,{size:14})," ",t("machine.detail.tabSystem")]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(hu,{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-[#ffffff0a]",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:P,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] 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:[_.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:_.nicknameInput,onChange:F=>_.setNicknameInput(F.target.value),onKeyDown:F=>{F.key==="Enter"&&_.handleSaveNickname(),F.key==="Escape"&&_.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:_.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:()=>_.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] 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:()=>{_.setEditingNickname(!0),_.setNicknameInput(L.machineNickname||"")},title:t("machine.detail.clickToSetNickname"),children:$}),k?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),d.retryConnection&&n&&s.jsx("button",{onClick:()=>d.retryConnection(n),className:"px-2.5 py-0.5 rounded text-[11px] font-semibold bg-red-500/10 border border-red-500/20 text-red-400 hover:bg-red-500/20 transition-colors",children:t("machine.detail.reconnect")})]}):s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[s.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[L.platform," · ",L.arch]}),s.jsx("span",{children:t("machine.detail.coresCount",{count:L.cpus})}),(m==null?void 0:m.version)&&s.jsxs("span",{children:["v",m.version]}),L.p2p.available&&s.jsx("span",{children:t("machine.detail.p2pState",{state:L.p2p.state==="connected"?t("machine.detail.p2pConnected"):L.p2p.state})}),L.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:L.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:Ne.map(F=>s.jsxs("button",{onClick:()=>v(F.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${h===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 ${h===F.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] 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:[h==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(LP,{machineEntry:m,providers:G,recentLaunches:te,currentConversations:B,onUpgradeDaemon:async()=>{try{await o(n,"daemon_upgrade",um(m))}catch{}},onOpenRecent:le,onOpenConversation:ie}),s.jsx(EP,{machine:L,machineId:n,ideSessions:O,cliSessions:E,acpSessions:M,actions:_,sendDaemonCommand:o})]}),h==="providers"&&s.jsx(WM,{machineId:n,providers:G,sendDaemonCommand:o}),h==="overview"&&s.jsx(PM,{machine:L,ideSessions:O,cliSessions:E,acpSessions:M}),h==="session-host"&&s.jsx(PP,{machineId:n,cliSessions:E,sendDaemonCommand:o}),h==="logs"&&s.jsx(SP,{machineId:n,sendDaemonCommand:o})]})})}),_.launchPick&&L&&s.jsx(DP,{machine:L,launchPick:_.launchPick,actions:_}),y&&s.jsx(vl,{title:y.title,description:y.description,details:y.details,workspaceOptions:y.workspaceOptions,selectedWorkspaceKey:S,onWorkspaceChange:F=>{N.current=F,A(F)},confirmLabel:y.confirmLabel,busyLabel:y.busyLabel,busy:T,onConfirm:Y,onCancel:()=>{C.current=null,x(null)}}),w&&s.jsx(vh,{daemonId:w.daemonId,workspace:w.workspace,onClose:()=>b(null)}),s.jsx(Fp,{toasts:d.toasts||[],onDismiss:F=>d.setToasts(pe=>pe.filter(xe=>xe.id!==F)),onClickToast:F=>{F.targetKey&&r(wr(F.targetKey))}}),s.jsx("style",{children:`
|
|
115
115
|
@keyframes toast-in {
|
|
116
116
|
from { opacity: 0; transform: translateX(40px); }
|
|
117
117
|
to { opacity: 1; transform: translateX(0); }
|
|
118
118
|
}
|
|
119
119
|
`})]})}function $P({daemonIds:e,meshId:t,sendData:n,onRevisionAdvance:r}){const a=l.useRef(new Map),o=l.useRef(r);o.current=r;const i=[...new Set(e.filter(Boolean))].sort().join(",");l.useEffect(()=>{a.current=new Map},[i,t]),l.useEffect(()=>{if(!t||!n)return;const c=[...new Set(e.filter(Boolean))];if(c.length===0)return;const d=c.map(p=>hs.subscribe({sendData:n},p,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${p}`,params:{includeSessions:!0}},u=>{if(u.topic!=="daemon.metadata")return;const m=u.meshStateRevisions;if(!m)return;const f=m[t]??m["*"];if(typeof f!="number")return;const g=a.current.get(p);a.current.set(p,f),g!==void 0&&f>g&&o.current()}));return()=>{for(const p of d)p()}},[i,t,n])}const HP={meshHostDaemonSection:!1,createDaemonPicker:!1,addNodeDaemonPicker:!1,queueSection:!0,coordinatorPrompt:!0,nodeInstruction:!0,hermesMcpConfig:!0,reviewInbox:!0},kh=l.createContext(null);function FP(){const e=l.useContext(kh);if(!e)throw new Error("useRepoMeshContext must be used inside RepoMeshProvider");return e}function BP({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 OP({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 WP({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 UP({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 GP({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 qP(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function zP({meshes:e,loading:t,error:n,onDismissError:r,daemons:a,features:o,showCreate:i,onToggleCreate:c,createName:d,onCreateNameChange:p,createRepoIdentity:u,onCreateRepoIdentityChange:m,createRepoRemoteUrl:f,onCreateRepoRemoteUrlChange:g,newMeshDaemonId:k,onNewMeshDaemonIdChange:h,newMeshWorkspace:v,onNewMeshWorkspaceChange:w,createPickerWorkspaces:b,onSelectMesh:j,onCreate:C,onCancelCreate:y}){const{t:x}=Ce("common"),N=o.maxMeshes!=null&&e.length>=o.maxMeshes,[S,A]=l.useState(!1),T=S||!!u.trim();return s.jsxs(Tr,{icon:s.jsx(rs,{}),title:x("repoMesh.list.title"),subtitle:x("repoMesh.list.count",{count:e.length}),widthClassName:"max-w-5xl",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:c,disabled:N,title:N?x("repoMesh.list.meshLimitReached",{max:o.maxMeshes}):void 0,children:x("repoMesh.list.createMesh")}),children:[N&&s.jsx(Ft,{variant:"info",className:"mb-4",children:x("repoMesh.list.meshLimitBanner",{max:o.maxMeshes})}),n&&s.jsx(Ft,{variant:"error",onDismiss:r,className:"mb-4",children:n}),i&&s.jsxs(ft,{className:"mb-5 border-accent/40 animate-[fadeIn_0.3s_ease-out]",children:[s.jsx("h3",{className:"text-base font-bold mb-4",children:x("repoMesh.list.createTitle")}),o.createDaemonPicker&&s.jsx(Nt,{label:x("repoMesh.list.createOnMachine"),hint:x("repoMesh.list.createOnMachineHint"),children:s.jsx("select",{className:"input w-full",value:k,onChange:I=>h(I.target.value),disabled:!a.length,children:a.length===0?s.jsx("option",{value:"",children:x("repoMesh.list.noConnectedDaemon")}):a.map(I=>s.jsx("option",{value:I.id,children:qP(I)},I.id))})}),o.createDaemonPicker&&s.jsx(Nt,{label:x("repoMesh.list.workspace"),hint:x("repoMesh.list.workspaceHint"),children:s.jsx("select",{className:"input w-full",value:v,onChange:I=>w(I.target.value),disabled:!k||!b.length,children:k?b.length===0?s.jsx("option",{value:"",children:x("repoMesh.list.noRegisteredWorkspaces")}):b.map(I=>s.jsx("option",{value:I.path,children:I.label?`${I.label} · ${I.path}`:I.path},I.id||I.path)):s.jsx("option",{value:"",children:x("repoMesh.list.selectMachineFirst")})})}),s.jsx(Nt,{label:x("repoMesh.list.name"),children:s.jsx(ms,{value:d,onChange:I=>p(I.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(Nt,{label:x("repoMesh.list.remoteUrl"),hint:x("repoMesh.list.remoteUrlHint"),children:s.jsx(ms,{value:f,onChange:I=>g(I.target.value),placeholder:"https://github.com/user/repo"})}),T?s.jsx(Nt,{label:x("repoMesh.list.repoIdentity"),hint:x("repoMesh.list.repoIdentityHint"),children:s.jsx(ms,{value:u,onChange:I=>m(I.target.value),placeholder:"github.com/user/repo"})}):s.jsx("button",{type:"button",className:"text-xs text-text-muted hover:text-text-primary underline underline-offset-2 mb-5",onClick:()=>A(!0),children:x("repoMesh.list.advancedIdentityToggle")}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:C,disabled:!d.trim()||!f.trim()&&!u.trim()||o.createDaemonPicker&&(!k||!v),children:x("repoMesh.list.create")}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:y,children:x("repoMesh.list.cancel")})]})]}),t?s.jsx("div",{className:"text-sm text-text-muted p-4",children:x("repoMesh.list.loading")}):e.length===0?s.jsx(za,{icon:s.jsx(rs,{}),title:x("repoMesh.list.emptyTitle"),description:a.length>0?x("repoMesh.list.emptyWithDaemons"):x("repoMesh.list.emptyNoDaemons"),action:s.jsx("button",{className:"btn btn-primary btn-sm",disabled:!a.length,onClick:c,children:x("repoMesh.list.createFirst")})}):s.jsx("div",{className:"flex flex-col gap-2.5",children:e.map(I=>{var D;return s.jsx("button",{type:"button",onClick:()=>j(I.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(rs,{size:16}),s.jsx("span",{className:"font-bold text-sm",children:I.name})]}),s.jsxs("div",{className:"text-[12px] text-text-muted flex items-center gap-2",children:[s.jsx("span",{className:"font-mono",children:I.repoIdentity||I.repo_identity||x("repoMesh.list.noRepoIdentity")}),(I.defaultBranch||I.default_branch)&&s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(OP,{size:11}),I.defaultBranch||I.default_branch]})]})]}),s.jsxs("div",{className:"text-right text-[11px] text-text-muted shrink-0 ml-4",children:[s.jsx("div",{children:new Date(I.createdAt||I.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})}),s.jsxs("div",{className:"text-text-muted/60",children:[((D=I.nodes)==null?void 0:D.length)??I.nodeCount??0," ",x("repoMesh.list.nodesSuffix")]})]})]})},I.id)})})]})}const KP=["claude-cli","codex-cli","gemini-cli","hermes-cli","antigravity-cli"],VP=[{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 YP(){return{nodeId:"",provider:"",model:"",n:""}}function Ud(e){var t;return(t=e.providers)!=null&&t.length?e.providers.filter(Boolean):(e.providerPriority??[]).filter(Boolean)}function JP(e){return{nodeId:e.nodeId??"",provider:e.provider??"",model:e.model??"",n:e.n!=null?String(e.n):""}}function QP(e){const t=[];for(let n=0;n<e.length;n++){const r=e[n],a=r.provider.trim();if(!a)return{error:{code:"provider_required",slot:n+1}};const o=r.nodeId.trim(),i=r.model.trim(),c=r.n.trim();let d;if(c){const p=Number(c);if(!Number.isFinite(p)||p<1)return{error:{code:"replica_min",slot:n+1}};d=Math.floor(p)}t.push({provider:a,...o?{nodeId:o}:{},...i?{model:i}:{},...d!==void 0?{n:d}:{}})}return t.length===0?{error:{code:"no_slot"}}:{slots:t}}function XP({status:e,daemonId:t,sendDaemonCommand:n,availableProviders:r}){const{t:a}=Ce(),{theme:o}=Ws(),i=l.useMemo(()=>Us(o),[o]),c=l.useMemo(()=>Gp(r),[r]),[d,p]=l.useState({}),[u,m]=l.useState(!1),[f,g]=l.useState(null),[k,h]=l.useState({}),[v,w]=l.useState(null),b=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(M=>({nodeId:M.nodeId,machineLabel:M.machineLabel,providers:M.providers,providerPriority:M.providerPriority})),[e==null?void 0:e.nodes]),j=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(M=>M.nodeId),[e==null?void 0:e.nodes]),C=l.useMemo(()=>Object.fromEntries(((e==null?void 0:e.nodes)??[]).map(M=>[M.nodeId,M.machineLabel||M.nodeId])),[e==null?void 0:e.nodes]),y=l.useMemo(()=>{const M={};for(const $ of b)M[$.nodeId]=Ud($);return M},[b]),x=l.useMemo(()=>{const M=[...new Set(b.flatMap(Ud).filter(Boolean))];return[...new Set([...M,...KP])].sort()},[b]),N=!!t&&!!n,S=M=>M&&typeof M=="object"&&"result"in M?M.result:M,A=l.useCallback(async()=>{if(!(!t||!n)){m(!0),g(null);try{const M=await n(t,"magi_kind_panel_list",{}),$=S(M);if(($==null?void 0:$.success)===!1)throw new Error($.error||a("meshGraph.magiKind.errorLoad"));p($!=null&&$.kindPanels&&typeof $.kindPanels=="object"?$.kindPanels:{}),h({})}catch(M){g((M==null?void 0:M.message)||a("meshGraph.magiKind.errorLoad"))}finally{m(!1)}}},[t,n,a]);l.useEffect(()=>{A()},[A]);const T=l.useCallback(M=>{if(k[M])return k[M];const $=d[M];return $?$.map(JP):[]},[k,d]),I=(M,$)=>{h(R=>({...R,[M]:$}))},D=(M,$,R)=>{const z=T(M);I(M,z.map((Q,ne)=>ne===$?{...Q,...R}:Q))},P=M=>{I(M,[...T(M),YP()])},_=(M,$)=>{I(M,T(M).filter((R,z)=>z!==$))},G=l.useCallback(async M=>{if(!t||!n)return;const $=QP(T(M));if("error"in $){const R=$.error,z=R.code==="provider_required"?a("meshGraph.magiKind.errorSlotProvider",{slot:R.slot}):R.code==="replica_min"?a("meshGraph.magiKind.errorSlotReplica",{slot:R.slot}):a("meshGraph.magiKind.errorNoSlot");g(`${M}: ${z}`);return}w(M),g(null);try{const R=await n(t,"magi_kind_panel_set",{kind:M,slots:$.slots}),z=S(R);if((z==null?void 0:z.success)===!1)throw new Error(z.error||a("meshGraph.magiKind.errorSave"));await A()}catch(R){g((R==null?void 0:R.message)||a("meshGraph.magiKind.errorSave"))}finally{w(null)}},[t,n,T,A,a]),H=l.useCallback(async M=>{if(!(!t||!n)&&confirm(a("meshGraph.magiKind.removeConfirm",{kind:M}))){w(M),g(null);try{const $=await n(t,"magi_kind_panel_remove",{kind:M}),R=S($);if((R==null?void 0:R.success)===!1)throw new Error(R.error||a("meshGraph.magiKind.errorRemove"));await A()}catch($){g(($==null?void 0:$.message)||a("meshGraph.magiKind.errorRemove"))}finally{w(null)}}},[t,n,A,a]),L=`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"}`,O="btn btn-primary btn-sm",E="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:a("meshGraph.magiKind.intro")}),s.jsx("div",{className:"ml-auto flex items-center gap-2",children:s.jsx("button",{type:"button",className:E,onClick:()=>void A(),disabled:u||!N,children:a(u?"meshGraph.magiKind.loading":"meshGraph.magiKind.refresh")})})]}),!N&&s.jsx("div",{className:`rounded-xl border p-3 text-[12px] ${i.textSecondary} ${i.isDark?"border-white/10":"border-slate-200"}`,children:a("meshGraph.magiKind.connectPrompt")}),f&&s.jsx("div",{className:"rounded-xl border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-[12px] text-rose-300",children:f}),s.jsx("div",{className:"flex flex-col gap-3",children:VP.map(({kind:M,labelKey:$,hint:R})=>{const z=T(M),Q=!!d[M],ne=v===M;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:a($)}),s.jsx("span",{className:`font-mono text-[10px] ${i.textMuted}`,children:R}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${Q?"border-emerald-400/30 bg-emerald-500/10 text-emerald-300":"border-slate-400/20 bg-slate-500/10 text-slate-300"}`,children:Q?a("meshGraph.magiKind.agentCount",{count:d[M].length}):a("meshGraph.magiKind.off")})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[z.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:a("meshGraph.magiKind.noAgents")}),z.map((J,Z)=>{const de=J.nodeId?y[J.nodeId]??[]:[],te=J.nodeId&&de.length?de:x;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:a("meshGraph.magiKind.machine")}),s.jsxs("select",{className:L,value:J.nodeId,onChange:B=>D(M,Z,{nodeId:B.target.value}),title:a("meshGraph.magiKind.machineTitle"),children:[s.jsx("option",{value:"",children:a("meshGraph.magiKind.anyMachine")}),j.map(B=>s.jsx("option",{value:B,children:C[B]??B},B)),J.nodeId&&!j.includes(J.nodeId)&&s.jsx("option",{value:J.nodeId,children:a("meshGraph.magiKind.offlineSuffix",{label:C[J.nodeId]??J.nodeId})})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsxs("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:[a("meshGraph.magiKind.provider")," *"]}),s.jsxs("select",{className:L,value:J.provider,onChange:B=>D(M,Z,{provider:B.target.value}),title:a("meshGraph.magiKind.providerTitle"),children:[s.jsx("option",{value:"",children:a("meshGraph.magiKind.selectProvider")}),te.map(B=>s.jsx("option",{value:B,children:B},B)),J.provider&&!te.includes(J.provider)&&s.jsx("option",{value:J.provider,children:J.provider})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:a("meshGraph.magiKind.model")}),(()=>{var Y;const B=(J.provider?(Y=c.get(J.provider))==null?void 0:Y.models:void 0)??[],ie=!!J.model&&B.length>0&&!B.includes(J.model);return B.length>0&&!ie?s.jsxs("select",{className:L,value:B.includes(J.model)?J.model:"",title:a("meshGraph.magiKind.modelTitle"),onChange:le=>D(M,Z,{model:le.target.value==="__custom__"?" ":le.target.value}),children:[s.jsx("option",{value:"",children:a("meshGraph.magiKind.modelDefault")}),B.map(le=>s.jsx("option",{value:le,children:le},le)),s.jsx("option",{value:"__custom__",children:a("meshGraph.magiKind.modelCustom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:L,value:J.model.trim(),placeholder:a("meshGraph.magiKind.modelDefault"),title:a("meshGraph.magiKind.modelTitle"),onChange:le=>D(M,Z,{model:le.target.value})}),B.length>0&&s.jsx("button",{type:"button",className:`self-start bg-transparent border-none cursor-pointer p-0 text-[10px] ${i.textSecondary} hover:underline`,onClick:()=>D(M,Z,{model:""}),children:a("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:a("meshGraph.magiKind.copies")}),s.jsx("input",{className:`${L} sm:w-16`,value:J.n,placeholder:"1",inputMode:"numeric",title:a("meshGraph.magiKind.copiesTitle"),onChange:B=>D(M,Z,{n:B.target.value})})]}),s.jsx("button",{type:"button",className:`${E} sm:mt-[18px] inline-flex h-8 w-8 items-center justify-center p-0`,onClick:()=>_(M,Z),"aria-label":a("meshGraph.magiKind.removeAgent"),title:a("meshGraph.magiKind.removeAgent"),children:"✕"})]},Z)}),s.jsx("div",{children:s.jsx("button",{type:"button",className:E,onClick:()=>P(M),disabled:!N,children:a("meshGraph.magiKind.addAgent")})})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:O,onClick:()=>void G(M),disabled:ne||!N,children:a(ne?"meshGraph.magiKind.saving":"meshGraph.magiKind.save")}),s.jsx("button",{type:"button",className:E,onClick:()=>void H(M),disabled:ne||!N||!Q,title:a(Q?"meshGraph.magiKind.removeBindingTitle":"meshGraph.magiKind.removeBindingDisabledTitle"),children:a("meshGraph.magiKind.removeBinding")})]})]},M)})})]})}function ZP({daemonId:e,meshId:t,cliType:n,sendCommand:r}){const{t:a}=Ce(),[o,i]=l.useState(!1),[c,d]=l.useState(!1),[p,u]=l.useState(null),[m,f]=l.useState(null),[g,k]=l.useState(null),h=l.useCallback(async()=>{if(!e||!t){u(a("repoMesh.promptPreview.connectPrompt"));return}d(!0),u(null);try{const w=await r(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)){u((b==null?void 0:b.error)||a("repoMesh.promptPreview.errorRender"));return}f(typeof b.prompt=="string"?b.prompt:""),k(typeof b.bytes=="number"?b.bytes:null)}catch(w){u((w==null?void 0:w.message)||String(w))}finally{d(!1)}},[e,t,n,r,a]),v=l.useCallback(()=>{const w=!o;i(w),w&&m===null&&!c&&h()},[o,m,c,h]);return s.jsxs("div",{className:"mt-2",children:[s.jsxs("button",{type:"button",onClick:v,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:"▸"}),a(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:a("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 h(),className:"ml-2 underline bg-transparent border-none cursor-pointer text-amber-300",children:a("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:a("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 eD=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function tD(e){const t=eD(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function sD(e){const t=e==null?void 0:e.missions;return Array.isArray(t)?t:[]}function nD(e){return typeof e.goal=="string"&&e.goal?{text:e.goal,truncated:!1}:{text:e.goalPreview??"",truncated:e.goalTruncated===!0}}const rD=["active","paused","completed","abandoned"];function Gd(e){return(e.status||"active").toLowerCase()}const aD=8;function oD({status:e,daemonId:t,meshId:n,sendCommand:r}){const{t:a}=Ce("common"),o=l.useMemo(()=>sD(e),[e]),[i,c]=l.useState({}),[d,p]=l.useState({}),[u,m]=l.useState(!1),[f,g]=l.useState(null),[k,h]=l.useState("active"),[v,w]=l.useState(!1),b=l.useMemo(()=>{const A={};for(const T of o){const I=Gd(T);A[I]=(A[I]||0)+1}return A},[o]),j=l.useMemo(()=>k==="all"?o:o.filter(A=>Gd(A)===k),[o,k]),C=v?j:j.slice(0,aD),y=j.length-C.length,x=!!t&&o.length>0,N=l.useCallback(async()=>{if(t){m(!0),g(null);try{const A=await r(t,"mesh_status",{meshId:n,verbose:!0}),T=tD(A),I=Array.isArray(T==null?void 0:T.missions)?T.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:a("repoMesh.missions.errorFetch"))}finally{m(!1)}}},[t,n,r,a]),S=l.useCallback(A=>{p(T=>({...T,[A]:!T[A]})),!d[A]&&!i[A]&&N()},[d,i,N]);return o.length===0?null:s.jsxs(ft,{title:a("repoMesh.missions.title"),description:a("repoMesh.missions.description"),children:[f&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400",children:f}),s.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-1.5",children:[rD.filter(A=>(b[A]||0)>0).map(A=>s.jsxs("button",{type:"button",onClick:()=>{h(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:()=>{h("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]})]}),j.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:a("repoMesh.missions.empty",{status:k})}),s.jsx("div",{className:"flex flex-col gap-2",children:C.map(A=>{var H;const T=d[A.id]===!0,I=i[A.id],D=nD(A),P=T&&I?I:D.text,_=T&&!I&&D.truncated,G=((H=A.tasks)==null?void 0:H.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}),G>0&&s.jsx("span",{className:"shrink-0 text-[11px] text-text-muted",children:a("repoMesh.missions.taskCount",{count:G})})]}),P&&s.jsxs("div",{className:`mt-1.5 whitespace-pre-wrap text-[12px] leading-5 text-text-secondary ${T?"max-h-72 overflow-y-auto":"line-clamp-2"}`,children:[P,_&&s.jsx("span",{className:"text-text-muted",children:a("repoMesh.missions.goalUnavailable")})]}),(D.truncated||I)&&x&&s.jsx("button",{type:"button",className:"mt-1.5 text-[12px] text-accent-primary hover:underline disabled:opacity-50",onClick:()=>S(A.id),disabled:u,children:a(T?"repoMesh.missions.showLess":u&&!I?"repoMesh.missions.loading":"repoMesh.missions.showFullGoal")})]},A.id)})}),y>0&&s.jsx("button",{type:"button",className:"mt-2 text-[12px] text-accent-primary hover:underline",onClick:()=>w(!0),children:a("repoMesh.missions.showMore",{count:y})})]})}function qd(e,t){if(t)return e.modes.find(n=>n.id===t)}function iD(e){return e.modes.find(t=>t.strategy==="pty-parse-default"&&Ms(t)!=="dangerous")}function lD({config:e,requestedModeId:t,machineAutoApproveEnabled:n,machineDangerousAllowed:r}){const a=qd(e,e.default),o=a==null?void 0:a.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=qd(e,i),d=!!i&&!c,p=c??a;if(!p||p.strategy==="post-boot-command")return{status:"none",requestedModeId:i,providerDefaultModeId:o,requestedModeUnknown:d,downgraded:!1};if(Ms(p)==="dangerous"&&!r){const u=iD(e);return{status:u?"downgraded":"none",requestedModeId:i,providerDefaultModeId:o,effectiveMode:u,requestedModeUnknown:d,downgraded:!0}}return{status:d?"invalid_fallback":"requested",requestedModeId:i,providerDefaultModeId:o,effectiveMode:p,requestedModeUnknown:d,downgraded:!1}}function cD(e){const t=[];for(const n of e||[]){if(!n||n.category!=="cli")continue;const r=n.autoApproveModes;if(!r||!Array.isArray(r.modes)||r.modes.length===0)continue;const a=String(n.type||n.id||"").trim();a&&t.push({type:a,label:String(n.displayName||n.name||a),autoApproveModes:r})}return t}function dD({hostDaemonId:e,hostOnline:t,hostWorkspace:n,hostProviders:r,machineAutoApproveEnabled:a,machineDangerousAllowed:o,sendCommand:i}){const{t:c}=Ce("common"),d=l.useMemo(()=>cD(r),[r]),[p,u]=l.useState({}),[m,f]=l.useState(!1),[g,k]=l.useState(null),[h,v]=l.useState(!1),[w,b]=l.useState(null),[j,C]=l.useState(!1),[y,x]=l.useState(null),N=!!e&&t&&!!n,S=l.useCallback(async()=>{var P,_,G;if(N){f(!0),k(null);try{const H=await i(e,"read_mesh_json_config",{workspace:n}),L=(H==null?void 0:H.result)??H,O=((P=L==null?void 0:L.providerDefaults)==null?void 0:P.autoApproveModes)||((G=(_=L==null?void 0:L.config)==null?void 0:_.providerDefaults)==null?void 0:G.autoApproveModes),E={};if(O&&typeof O=="object")for(const[M,$]of Object.entries(O))typeof $=="string"&&$.trim()&&(E[M]=$.trim());u(E)}catch(H){k((H==null?void 0:H.message)||c("repoMesh.providerAutoApprove.loadError"))}finally{f(!1)}}},[N,e,n,i,c]);l.useEffect(()=>{S()},[S]);const A=l.useCallback((P,_)=>{C(!1),u(G=>{const H={...G};return _&&_.trim()?H[P]=_.trim():delete H[P],H})},[]),T=l.useCallback((P,_)=>{if(Ms(_)==="dangerous"){x({type:P,mode:_});return}A(P,_.id)},[A]),I=l.useCallback(()=>{y&&A(y.type,y.mode.id),x(null)},[A,y]),D=l.useCallback(async()=>{if(N){v(!0),b(null),C(!1);try{const P=await i(e,"set_mesh_provider_defaults",{workspace:n,autoApproveModes:p,merge:!1,write:!0}),_=(P==null?void 0:P.result)??P;if((_==null?void 0:_.success)===!1)throw new Error((_==null?void 0:_.error)||c("repoMesh.providerAutoApprove.saveError"));C(!0),await S()}catch(P){b((P==null?void 0:P.message)||c("repoMesh.providerAutoApprove.saveError"))}finally{v(!1)}}},[N,e,n,S,p,i,c]);return s.jsxs(ft,{title:c("repoMesh.providerAutoApprove.title"),description:c("repoMesh.providerAutoApprove.subtitle"),collapsible:!0,defaultOpen:!1,children:[N?m?s.jsx("div",{className:"text-[13px] text-text-muted",children:c("repoMesh.providerAutoApprove.loading")}):d.length===0?s.jsx("div",{className:"text-[13px] text-text-muted",children:c("repoMesh.providerAutoApprove.noProviders")}):s.jsxs("div",{className:"space-y-6",children:[g&&s.jsx(Ft,{variant:"error",onDismiss:()=>k(null),children:g}),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:c("repoMesh.providerAutoApprove.machineSection.title")}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:c("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 ${a?"border-status-online/25 bg-status-online/10 text-status-online":"border-border-subtle bg-bg-tertiary/40 text-text-muted"}`,children:c(a?"repoMesh.providerAutoApprove.machineSection.autoApproveOn":"repoMesh.providerAutoApprove.machineSection.autoApproveOff")}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 font-semibold ${o?"border-status-error/30 bg-status-error/10 text-status-error":"border-border-subtle bg-bg-tertiary/40 text-text-muted"}`,children:c(o?"repoMesh.providerAutoApprove.machineSection.dangerousOn":"repoMesh.providerAutoApprove.machineSection.dangerousOff")})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:c("repoMesh.providerAutoApprove.machineSection.editHint")})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:c("repoMesh.providerAutoApprove.repoSection.title")}),s.jsx("div",{className:"text-[11px] text-text-muted",children:c("repoMesh.providerAutoApprove.repoSection.hint")})]}),s.jsx("div",{className:"space-y-5",children:d.map(P=>{const _=p[P.type],G=lD({config:P.autoApproveModes,requestedModeId:_,machineAutoApproveEnabled:a,machineDangerousAllowed:o});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:P.label}),s.jsx("button",{type:"button",className:"text-[11px] text-text-muted underline decoration-dotted hover:text-text-primary disabled:opacity-40",onClick:()=>A(P.type,void 0),disabled:!_||h,children:c("repoMesh.providerAutoApprove.repoSection.clear")})]}),s.jsx(Hm,{config:P.autoApproveModes,selectedModeId:_||"",disabled:h,onSelectMode:H=>T(P.type,H)}),!_&&s.jsx("div",{className:"mt-1.5 text-[11px] text-text-muted",children:c("repoMesh.providerAutoApprove.repoSection.usesProviderDefault")}),s.jsx(uD,{effective:G,config:P.autoApproveModes})]},P.type)})}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:c("repoMesh.providerAutoApprove.effectiveSection.title")}),s.jsx("div",{className:"text-[11px] text-text-muted",children:c("repoMesh.providerAutoApprove.effectiveSection.hint")})]}),w&&s.jsx(Ft,{variant:"error",onDismiss:()=>b(null),children:w}),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 D(),disabled:h,children:c(h?"repoMesh.providerAutoApprove.saving":"repoMesh.providerAutoApprove.save")}),j&&s.jsx("span",{className:"text-[12px] text-status-online",children:c("repoMesh.providerAutoApprove.saved")})]})]}):s.jsx("div",{className:"text-[13px] text-text-muted",children:c("repoMesh.providerAutoApprove.noHostDaemon")}),y&&s.jsx(Fm,{mode:y.mode,onConfirm:I,onCancel:()=>x(null)}),y&&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:c("repoMesh.providerAutoApprove.dangerous.sharedWarningTitle")}),s.jsx("div",{className:"mt-1 text-[12px] text-text-muted",children:c("repoMesh.providerAutoApprove.dangerous.sharedWarning")})]})})]})}function uD({effective:e,config:t}){var c,d,p;const{t:n}=Ce("common"),r=u=>{var m;return(u?(m=t.modes.find(f=>f.id===u))==null?void 0:m.label:void 0)||u||""};let a,o="ok";switch(e.status){case"requested":a=n("repoMesh.providerAutoApprove.effectiveSection.statusRequested",{mode:((c=e.effectiveMode)==null?void 0:c.label)||""});break;case"invalid_fallback":a=n("repoMesh.providerAutoApprove.effectiveSection.statusInvalidFallback",{mode:((d=e.effectiveMode)==null?void 0:d.label)||""}),o="warn";break;case"downgraded":a=n("repoMesh.providerAutoApprove.effectiveSection.statusDowngraded",{requested:r(e.requestedModeId)||r(e.providerDefaultModeId),mode:((p=e.effectiveMode)==null?void 0:p.label)||""}),o="warn";break;case"disabled":a=n("repoMesh.providerAutoApprove.effectiveSection.statusDisabled"),o="muted";break;default:a=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($m,{risk:Ms(e.effectiveMode)}),s.jsx("span",{className:"min-w-0",children:a})]})}const pD=["","low","medium","high"],mD={easy:"Easy",medium:"Medium",difficult:"Difficult",freeform:"Freeform"};function zd(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 Kd(e){const t=e.provider.trim();if(!t)return null;const n=e.model.trim(),r=e.thinkingLevel.trim()||void 0,a=Number(e.maxParallel),o=Number.isFinite(a)&&a>0?Math.floor(a):void 0;return{provider:t,...n?{model:n}:{},...r?{thinkingLevel:r}:{},...e.difficulty.length?{difficulty:e.difficulty}:{},...e.capability.length?{capability:e.capability}:{},...o!==void 0?{maxParallel:o}:{}}}function hD(){return{provider:"",model:"",thinkingLevel:"",difficulty:[],capability:[],maxParallel:""}}const Ks="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function fD({slots:e,availableProviders:t,saving:n,onSave:r}){const{t:a}=Ce("common"),[o,i]=l.useState(()=>e.map(zd)),c=l.useMemo(()=>JSON.stringify(e),[e]);l.useEffect(()=>{i(e.map(zd))},[c]);const d=l.useMemo(()=>[...new Set(t.map(b=>b.type).filter(Boolean))],[t]),p=l.useMemo(()=>Gp(t),[t]),u=l.useMemo(()=>{const b=o.map(Kd).filter(Boolean);return JSON.stringify(b)!==JSON.stringify(e)},[o,e]),m=(b,j)=>i(C=>C.map((y,x)=>x===b?{...y,...j}:y)),f=(b,j)=>i(C=>C.map((y,x)=>{var A;if(x!==b)return y;const N=((A=p.get(j))==null?void 0:A.models)??[],S=!y.model||N.length===0||N.includes(y.model);return{...y,provider:j,...S?{}:{model:""}}})),g=b=>i(j=>j.filter((C,y)=>y!==b)),k=()=>i(b=>[...b,hD()]),h=(b,j)=>i(C=>{const y=b+j;if(y<0||y>=C.length)return C;const x=[...C];return[x[b],x[y]]=[x[y],x[b]],x}),v=(b,j)=>i(C=>C.map((y,x)=>{if(x!==b)return y;const N=y.difficulty.includes(j);return{...y,difficulty:N?y.difficulty.filter(S=>S!==j):[...y.difficulty,j]}})),w=()=>r(o.map(Kd).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:a("repoMesh.slotEditor.empty")}),o.map((b,j)=>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:["#",j+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:j===0,onClick:()=>h(j,-1),title:a("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:j===o.length-1,onClick:()=>h(j,1),title:a("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(j),"aria-label":a("repoMesh.slotEditor.removeSlot"),children:s.jsx(Tt,{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:a("repoMesh.slotEditor.provider")}),d.length>0?s.jsxs("select",{className:Ks,value:b.provider,onChange:C=>f(j,C.target.value),children:[s.jsx("option",{value:"",children:a("repoMesh.slotEditor.select")}),d.map(C=>s.jsx("option",{value:C,children:C},C)),b.provider&&!d.includes(b.provider)&&s.jsx("option",{value:b.provider,children:b.provider})]}):s.jsx("input",{className:Ks,value:b.provider,placeholder:"claude-cli",onChange:C=>m(j,{provider:C.target.value})})]}),(()=>{var S;const C=p.get(b.provider),y=(C==null?void 0:C.models)??[],x=(S=C==null?void 0:C.thinking)!=null&&S.length?["",...C.thinking]:pD,N=!!b.model&&y.length>0&&!y.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:a("repoMesh.slotEditor.model")}),y.length>0&&!N?s.jsxs("select",{className:Ks,value:y.includes(b.model)?b.model:"",onChange:A=>m(j,{model:A.target.value==="__custom__"?" ":A.target.value}),children:[s.jsx("option",{value:"",children:a("repoMesh.slotEditor.providerDefault")}),y.map(A=>s.jsx("option",{value:A,children:A},A)),s.jsx("option",{value:"__custom__",children:a("repoMesh.slotEditor.custom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:Ks,value:b.model.trim(),placeholder:b.provider?`${b.provider} model`:a("repoMesh.slotEditor.modelPlaceholder"),onChange:A=>m(j,{model:A.target.value})}),y.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(j,{model:""}),children:a("repoMesh.slotEditor.backToModelList")})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:a("repoMesh.slotEditor.thinking")}),s.jsx("select",{className:Ks,value:b.thinkingLevel,onChange:A=>m(j,{thinkingLevel:A.target.value}),children:x.map(A=>s.jsx("option",{value:A,children:A||a("repoMesh.slotEditor.thinkingDefault")},A||"_default"))})]})]})})()]}),s.jsxs("div",{className:"mt-2",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:a("repoMesh.slotEditor.difficulty")}),s.jsx("div",{className:"mt-1 flex flex-wrap gap-1.5",children:By.map(C=>{const y=b.difficulty.includes(C);return s.jsx("button",{type:"button",className:`rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors ${y?"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:()=>v(j,C),children:mD[C]},C)})})]}),s.jsxs("div",{className:"mt-2 grid grid-cols-1 sm:grid-cols-2 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:a("repoMesh.slotEditor.capabilityTags")}),s.jsx("input",{className:Ks,value:b.capability.join(", "),placeholder:"worktree, os=darwin",onChange:C=>m(j,{capability:C.target.value.split(",").map(y=>y.trim()).filter(Boolean)})})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:a("repoMesh.slotEditor.maxParallel")}),s.jsx("input",{type:"number",inputMode:"numeric",min:1,className:Ks,value:b.maxParallel,placeholder:a("repoMesh.slotEditor.maxParallelPlaceholder"),onChange:C=>m(j,{maxParallel:C.target.value})})]})]})]},j)),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(Gi,{size:13})," ",a("repoMesh.slotEditor.addSlot")]}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm ml-auto",onClick:w,disabled:!!n||!u,children:a(n?"repoMesh.slotEditor.saving":"repoMesh.slotEditor.saveSlots")})]})]})}function bD(e){const t=new Map;for(const n of e)n!=null&&n.id&&t.set(n.id,Ln(n.availableProviders||[]));return t}function gD(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 xD(e){var d,p,u;const t=e,n=[],r=Array.isArray(t.capabilities)?t.capabilities:[];for(const m of r){const f=typeof m=="string"?m.trim():"";f&&n.push({tag:f,custom:!0})}const a=(((d=t.userOverrides)==null?void 0:d.platform)||t.reportedPlatform||"").toString().trim(),o=(((p=t.userOverrides)==null?void 0:p.arch)||t.reportedArch||"").toString().trim();a&&n.push({tag:`os=${a}`,custom:!1}),o&&n.push({tag:`arch=${o}`,custom:!1});const i=Array.isArray((u=t.policy)==null?void 0:u.providerPriority)?String(t.policy.providerPriority[0]||"").trim():"";i&&n.push({tag:`provider=${i}`,custom:!1});const c=typeof t.worktreeBranch=="string"?t.worktreeBranch.trim():"";return t.isLocalWorktree===!0&&c&&n.push({tag:`worktree=${c}`,custom:!1}),n}function vD(e){const t=e.capabilities;return Array.isArray(t)?t.map(n=>typeof n=="string"?n.trim():"").filter(Boolean):[]}const yD=["os=","arch=","provider=","worktree=","converge="];function wD({node:e,saving:t,onSave:n}){const{t:r}=Ce("common"),a=l.useMemo(()=>xD(e).filter(h=>!h.custom),[e]),o=l.useMemo(()=>vD(e),[e]),[i,c]=l.useState(o),[d,p]=l.useState(""),u=JSON.stringify(i)!==JSON.stringify(o),f=(h=>{const v=h.trim();return v?/\s/.test(v)?r("repoMesh.tagEditor.noSpaces"):yD.some(w=>v.toLowerCase().startsWith(w))?r("repoMesh.tagEditor.reservedPrefix"):i.includes(v)?r("repoMesh.tagEditor.alreadyAdded"):null:null})(d);function g(){const h=d.trim();!h||f||(c(v=>[...v,h]),p(""))}function k(h){c(v=>v.filter(w=>w!==h))}return s.jsxs("div",{className:"mt-2",onClick:h=>h.stopPropagation(),children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wide text-text-muted mr-1",children:r("repoMesh.tagEditor.routingTags")}),a.map(h=>s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-1.5 py-0.5 font-mono text-[10px] text-text-muted",title:r("repoMesh.tagEditor.autoDerivedTitle"),children:h.tag},h.tag)),i.map(h=>s.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 font-mono text-[10px] text-accent-primary",title:r("repoMesh.tagEditor.customTagTitle"),children:[h,s.jsx("button",{type:"button",className:"text-accent-primary/70 hover:text-accent-primary bg-transparent border-none cursor-pointer p-0 leading-none",onClick:()=>k(h),disabled:t,"aria-label":r("repoMesh.tagEditor.remove",{tag:h}),children:"×"})]},h))]}),s.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-2",children:[s.jsx("input",{type:"text",value:d,onChange:h=>p(h.target.value),onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),g())},placeholder:r("repoMesh.tagEditor.addPlaceholder"),disabled:t,className:"min-w-[12rem] flex-1 px-2 py-1 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-primary"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:g,disabled:t||!d.trim()||!!f,children:r("repoMesh.tagEditor.add")}),u&&s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>n(i),disabled:t,children:r(t?"repoMesh.tagEditor.saving":"repoMesh.tagEditor.saveTags")})]}),f&&s.jsx("div",{className:"mt-1 text-[11px] text-amber-400",children:f}),i.length===0&&a.length===0&&s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:r("repoMesh.tagEditor.empty")})]})}function kD(e,t){return t.filter(n=>n.status!=="assigned"?!1:(n.assignedNodeId||n.nodeId)===e.id)}function SD(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 CD(e){var r;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>n.has(a)?!1:(n.add(a),!0))}function jD(e){const t=CD(e);return t.length?{configured:!0,label:t.join(" → ")}:{configured:!1,label:"not configured",launchBlockedMessage:"No provider detected on this node — task launch is blocked until a provider is selected or installed. (Empty capability slots alone do not block launch; this means no provider was found.)"}}function ND(e){return e.isLocalWorktree===!0}function AD(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(a=>{var o;return((o=a==null?void 0:a.settings)==null?void 0:o.meshNodeId)===e.id||(a==null?void 0:a.workspace)===e.workspace}).map(a=>{var o;return{id:a.sessionId||a.id||a.instanceId||"unknown",provider:a.providerType||a.cliType||a.acpType||a.type||"unknown",status:a.status||((o=a.activeChat)==null?void 0:o.status)||"unknown"}})}function Vd(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function TD(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 MD({nodes:e,meshQueue:t,activeDaemon:n,daemons:r,selectedMeshId:a,userName:o,features:i,coordinatorDaemonId:c,availableCliProviders:d,savingNodeSlotsId:p,onUpdateNodeSlots:u,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:f,nodeSystemPromptDrafts:g,onNodeSystemPromptDraftChange:k,savingNodeSystemPromptId:h,onSaveNodeSystemPrompt:v,selectedNodeId:w,onSelectNode:b,showAddNode:j,onShowAddNode:C,onCancelAddNode:y,nodeWorkspace:x,onNodeWorkspaceChange:N,nodeProviderPriority:S,onNodeProviderPriorityChange:A,nodeDaemonId:T,onNodeDaemonIdChange:I,nodeCustomPath:D,onNodeCustomPathChange:P,nodePickerWorkspaces:_,nodePickerProviders:G,attachableDaemons:H,onAddNode:L,onRemoveNode:O}){const{t:E}=Ce("common"),M=l.useMemo(()=>bD(r),[r]),$=l.useMemo(()=>e.filter(R=>!ND(R)),[e]);return s.jsxs(ft,{title:i.addNodeDaemonPicker?E("repoMesh.nodeList.title",{count:$.length}):E("repoMesh.nodeList.titleNoCount"),description:i.addNodeDaemonPicker?E("repoMesh.nodeList.descriptionCloud"):E("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:E("repoMesh.nodeList.daemonCandidates")}),s.jsx("div",{className:"text-[12px] text-text-muted",children:E("repoMesh.nodeList.daemonCandidatesHint")})]}),s.jsx("span",{className:"text-[11px] text-text-muted",children:E("repoMesh.nodeList.available",{count:H.length})})]}),r.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:E("repoMesh.nodeList.noDaemonsAvailable")}):H.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:E("repoMesh.nodeList.allDaemonsAttached")}):s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:H.map(R=>s.jsxs("button",{type:"button",className:`text-left rounded-lg border px-3 py-2 transition-colors ${R.id===c?"border-accent-primary/50 bg-accent-primary/10":"border-border-subtle bg-bg-primary hover:border-border-default"}`,onClick:()=>{I(R.id),N(""),P(!1),A(yr(Ln(R.availableProviders||[]))),C()},children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-sm font-medium truncate",children:Vd(R)}),R.id===c&&s.jsx("span",{className:"text-[10px] text-accent-primary",children:E("repoMesh.nodeList.selectedHost")})]}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted font-mono truncate",children:R.id}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:E("repoMesh.nodeList.workspacesDetected",{count:(R.workspaces||[]).length})})]},R.id))})]}),!j&&s.jsxs("button",{className:"btn btn-primary btn-sm mb-4 inline-flex items-center gap-1.5",onClick:C,children:[s.jsx(UP,{size:13})," ",i.addNodeDaemonPicker?E("repoMesh.nodeList.attachMachine"):E("repoMesh.nodeList.addNode")]}),j&&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?E("repoMesh.nodeList.attachMachineTitle"):E("repoMesh.nodeList.addNodeTitle")}),s.jsx("button",{onClick:()=>{y(),I(""),P(!1)},className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(Tt,{size:16})})]}),i.addNodeDaemonPicker&&s.jsx(Nt,{label:E("repoMesh.nodeList.machine"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:T,onChange:R=>{var z;I(R.target.value),N(""),P(!1),A(yr(Ln(((z=r.find(Q=>Q.id===R.target.value))==null?void 0:z.availableProviders)||[])))},children:[s.jsx("option",{value:"",children:E("repoMesh.nodeList.selectMachine")}),r.map(R=>s.jsx("option",{value:R.id,children:Vd(R)},R.id))]})}),(i.addNodeDaemonPicker?T:!0)&&s.jsx(Nt,{label:E("repoMesh.nodeList.workspacePath"),children:i.addNodeDaemonPicker&&!D&&_.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex flex-col gap-1.5 mb-2",children:_.map(R=>s.jsxs("button",{type:"button",className:`text-left text-xs px-3 py-2 rounded-lg border transition-colors ${x===R.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:()=>N(R.path),children:[s.jsx("span",{className:"font-medium block truncate",children:R.label||R.path.split("/").pop()}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:R.path})]},R.id||R.path))}),s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{P(!0),N("")},children:E("repoMesh.nodeList.enterCustomPath")})]}):s.jsx(s.Fragment,{children:i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[s.jsx(ms,{value:x,onChange:R=>N(R.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:R=>{R.key==="Enter"&&L()}}),_.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),N("")},children:E("repoMesh.nodeList.pickFromSaved")})]}):(()=>{var Q;const R=Array.isArray(n==null?void 0:n.workspaces)?n.workspaces:[],z=`mesh-add-node-workspaces-${a||"new"}`;return s.jsxs(s.Fragment,{children:[s.jsx(ms,{value:x,onChange:ne=>N(ne.target.value),placeholder:((Q=R[0])==null?void 0:Q.path)||"/Users/dev/projects/myapp",list:R.length>0?z:void 0,autoFocus:!0}),R.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("datalist",{id:z,children:R.map(ne=>s.jsx("option",{value:ne.path,children:ne.label||ne.path},ne.id||ne.path))}),s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:R.slice(0,6).map(ne=>s.jsx("button",{type:"button",onClick:()=>N(ne.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:ne.path,children:ne.label||ne.path.split("/").filter(Boolean).pop()||ne.path},ne.id||ne.path))})]})]})})()})}),s.jsx(Nt,{label:E("repoMesh.nodeList.preferredTools"),hint:E("repoMesh.nodeList.preferredToolsHint"),children:s.jsx(RS,{value:S,availableProviders:i.addNodeDaemonPicker?G:d,onChange:A})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:L,disabled:!x.trim()||i.addNodeDaemonPicker&&!T,className:"btn btn-primary btn-sm",children:E("repoMesh.nodeList.add")}),s.jsx("button",{onClick:()=>{y(),I(""),P(!1)},className:"btn btn-secondary btn-sm",children:E("repoMesh.nodeList.cancel")})]})]}),i.addNodeDaemonPicker&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-300 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:E("repoMesh.nodeList.setupInventoryWarning")}),$.length===0?s.jsx(za,{icon:s.jsx(Pn,{}),title:E("repoMesh.nodeList.emptyTitle"),description:E("repoMesh.nodeList.emptyDescription")}):s.jsx("div",{className:"flex flex-col gap-2",children:$.map(R=>{var de;const z=jD(R),Q=kD(R,t),ne=AD(R,n),J=w===R.id,Z=R.status||R.machine_status||(Q.length>0||ne.length>0?"active":"enabled");return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary transition-colors ${i.addNodeDaemonPicker?"bg-bg-glass border-border-subtle rounded-xl px-5 py-4":`cursor-pointer ${J?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`}`,role:i.addNodeDaemonPicker?void 0:"button",tabIndex:i.addNodeDaemonPicker?void 0:0,onClick:i.addNodeDaemonPicker?void 0:()=>b(J?null:R.id),onKeyDown:i.addNodeDaemonPicker?void 0:te=>{(te.key==="Enter"||te.key===" ")&&(te.preventDefault(),b(J?null:R.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:R.machine_label||R.machine_nickname||R.hostname||R.workspace}):s.jsx("span",{className:"text-sm font-medium",children:R.workspace.split("/").pop()}),i.addNodeDaemonPicker&&s.jsx(GP,{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:E("repoMesh.nodeList.setupInventory")})]}),i.addNodeDaemonPicker&&s.jsx("div",{className:"text-[11px] text-text-muted",children:E("repoMesh.nodeList.ownerMachine",{owner:TD(r.find(te=>te.id===String(R.daemon_id||"")),o),machine:R.machine_label||R.daemon_id||R.workspace})}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:R.workspace}),s.jsx(wD,{node:R,saving:m===R.id,onSave:te=>f(R,te)}),i.addNodeDaemonPicker&&s.jsx("div",{className:"mt-2 text-[11px] text-amber-300",children:E("repoMesh.nodeList.liveDetailGraphOwned")}),s.jsxs("div",{className:"mt-3 max-w-2xl",onClick:te=>te.stopPropagation(),children:[s.jsx(Nt,{label:E("repoMesh.nodeList.slotsLabel"),hint:E("repoMesh.nodeList.slotsHint"),children:s.jsx(fD,{slots:Array.isArray((de=R.policy)==null?void 0:de.slots)?R.policy.slots:[],availableProviders:gD(R,M),saving:p===R.id,onSave:te=>u(R,te)})}),i.nodeInstruction&&s.jsxs(Nt,{label:E("repoMesh.nodeList.nodeInstruction"),hint:E("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[R.id]??"",onChange:te=>{const B=te.target.value;k(R.id,B)},onClick:te=>te.stopPropagation(),disabled:h===R.id,placeholder:E("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:te=>{te.stopPropagation(),v(R)},disabled:h===R.id,children:h===R.id?E("repoMesh.nodeList.saving"):E("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:te=>{te.stopPropagation(),O(R.id)},title:E("repoMesh.nodeList.removeNode"),children:s.jsx(WP,{size:14})})]}),s.jsxs("details",{className:"mt-3 group",onClick:te=>te.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:"▸"})," ",E("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:E("repoMesh.nodeList.nodeId")})," ",s.jsx("span",{className:"font-mono break-all",children:R.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:E("repoMesh.nodeList.launchReady")})," ",s.jsx("span",{className:z.configured?"text-green-400":"text-amber-400",children:z.configured?E("repoMesh.nodeList.launchReadyYes"):E("repoMesh.nodeList.launchReadyNo")})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:E("repoMesh.nodeList.repoRoot")})," ",s.jsx("span",{className:"font-mono break-all",children:R.repoRoot||R.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:E("repoMesh.nodeList.activeSessionsLabel")})," ",ne.length]}),i.addNodeDaemonPicker&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:E("repoMesh.nodeList.added")})," ",new Date(R.created_at||R.createdAt||Date.now()).toLocaleDateString()]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:E("repoMesh.nodeList.activeQueueAssignments")}),Q.length===0?s.jsx("div",{children:E("repoMesh.nodeList.noActiveAssignment")}):s.jsx("ul",{className:"m-0 pl-4",children:Q.map(te=>s.jsx("li",{className:"font-mono",children:SD(te)},te.id))})]}),ne.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:E("repoMesh.nodeList.activeSessions")}),s.jsx("ul",{className:"m-0 pl-4",children:ne.map(te=>s.jsxs("li",{className:"font-mono",children:[te.provider," / ",te.status," / ",te.id]},te.id))})]})]})]})]},R.id)})})]})}function Zr(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function PD({daemons:e,coordinatorDaemonId:t,onCoordinatorDaemonIdChange:n,coordinatorCliType:r,onCoordinatorCliTypeChange:a,launchingCoordinator:o,launchResult:i,isHostNodeAttached:c,selectedHostNode:d,hostPinned:p,hostLabel:u,hostOnline:m,hostRebindDaemonId:f,onHostRebindDaemonIdChange:g,onLaunchCoordinator:k}){const{t:h}=Ce("common"),v=s.jsx(Nt,{label:h("repoMesh.host.coordinatorProvider"),hint:h("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:r,onChange:j=>a(j.target.value),children:[s.jsx("option",{value:"",children:h("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"})]})}),w=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(ft,{title:h("repoMesh.host.title"),description:h("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:h("repoMesh.host.hostLabel")}),s.jsx("span",{className:"font-medium",children:u||h("repoMesh.host.unknown")}),s.jsxs("span",{className:m?"text-text-muted":"text-amber-400",children:["· ",h(m?"repoMesh.host.online":"repoMesh.host.offline")]})]}),(d==null?void 0:d.workspace)&&s.jsxs("span",{className:"text-[12px] text-text-muted",children:[h("repoMesh.host.hostNode")," ",s.jsx("span",{className:"font-mono text-text-secondary",children:d.workspace})]})]}),!m&&s.jsxs("div",{className:"mt-4",children:[s.jsxs(Ft,{variant:"warning",className:"mb-3",children:[s.jsx("strong",{children:h("repoMesh.host.hostOffline")})," ",h("repoMesh.host.hostOfflineText")]}),e.length>0?s.jsx(Nt,{label:h("repoMesh.host.reconnectToCommand"),hint:h("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:f,onChange:j=>g(j.target.value),children:[s.jsx("option",{value:"",children:h("repoMesh.host.waitForHost")}),e.map(j=>s.jsx("option",{value:j.id,children:Zr(j)},j.id))]})}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:h("repoMesh.host.noDaemonsToRoute")})]}),s.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-[180px_auto] items-end",children:[v,s.jsx("button",{className:"btn btn-primary btn-sm",onClick:k,disabled:o||!t,title:t?void 0:h("repoMesh.host.noCommandTarget"),children:h(o?"repoMesh.host.launching":"repoMesh.host.launchHost")})]}),w]});const b=e.find(j=>j.id===t);return s.jsxs(ft,{title:h("repoMesh.host.title"),description:h("repoMesh.host.descriptionUnset"),children:[s.jsxs(Ft,{variant:"info",className:"mb-4",children:[s.jsx("strong",{children:h("repoMesh.host.setHostBanner")})," ",h("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:Zr(b)}),d!=null&&d.workspace?s.jsxs(s.Fragment,{children:[" · setup node ",s.jsx("span",{className:"font-mono text-text-secondary",children:d.workspace})]}):null,". Launching sets this daemon as the mesh host."]}):s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:Zr(b)}),". Attach one of its workspaces as a node first, then launch to set the host."]})}):s.jsx(Nt,{label:h("repoMesh.host.hostDaemon"),hint:h("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:j=>n(j.target.value),children:[s.jsx("option",{value:"",children:h("repoMesh.host.resolvingHost")}),e.map(j=>s.jsx("option",{value:j.id,children:Zr(j)},j.id))]})}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-[180px_auto] items-end mt-3",children:[v,s.jsx("button",{className:"btn btn-primary btn-sm",onClick:k,disabled:!t||!c||o,title:t?c?void 0:h("repoMesh.host.attachNodeFirst"):h("repoMesh.host.pickHostFirst"),children:h(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:h("repoMesh.host.noDaemonsToHost")}),w]})}function DD({meshId:e,availableCliAgents:t}){const{t:n}=Ce(),r=t.find(o=>{const i=o.id.toLowerCase();return i==="hermes-cli"||i.includes("hermes")||o.name.toLowerCase().includes("hermes")}),a=mm(r==null?void 0:r.meshCoordinator,{meshId:e});return a?s.jsx(ft,{title:n("repoMesh.hermesMcp.title"),description:n("repoMesh.hermesMcp.description"),children:s.jsx(_m,{setup:a,providerName:(r==null?void 0:r.name)||n("repoMesh.hermesMcp.fallbackProvider")})}):null}const Yo=[{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."}],ID=[{value:"smart",label:"Smart",description:"Match each task to the node whose capability slot best fits it (task difficulty + capability tags), then load-spread among ties. Auto-enabled when any node has capability slots."},{value:"spread",label:"Spread",description:"Distribute work evenly across eligible nodes (prefers the least-loaded, rotating ties fairly). Set a per-node priority below to bias the order."},{value:"in_order",label:"In order",description:"Assign to nodes in the order they were added — the first eligible node takes the work. No load-spreading."}];function LD(e){return e==="smart"?"fitness":e==="spread"?"least_loaded":"first_eligible"}function RD(e,t){const n=e||"first_eligible";return n==="fitness"?"smart":n==="first_eligible"?"in_order":n==="priority_only"?t!=null&&t.priorityConfigured?"spread":"in_order":n==="least_loaded"||n==="round_robin"?"spread":"in_order"}const ED={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,schedulingStrategy:"first_eligible",sessionCleanupOnNodeRemove:"preserve"};function Ii(e){return{...ED,...(e==null?void 0:e.policy)||{}}}function _D(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 $D({selectedMesh:e,error:t,onDismissError:n,onBack:r,onDelete:a,displayedMeshStatus:o,graphLoading:i,graphError:c,onRefreshGraph:d,savingPolicy:p,onUpdatePolicy:u,coordinatorPromptDraft:m,onCoordinatorPromptDraftChange:f,savingCoordinatorPrompt:g,onSaveCoordinatorPrompt:k,daemons:h,coordinatorDaemonId:v,onCoordinatorDaemonIdChange:w,coordinatorCliType:b,onCoordinatorCliTypeChange:j,launchingCoordinator:C,launchResult:y,isHostNodeAttached:x,selectedHostNode:N,hostPinned:S,hostLabel:A,hostOnline:T,hostRebindDaemonId:I,onHostRebindDaemonIdChange:D,onLaunchCoordinator:P,activeDaemon:_,activeDaemonId:G,meshQueue:H,userName:L,availableCliProviders:O,savingNodeSlotsId:E,onUpdateNodeSlots:M,savingNodeCapabilitiesId:$,onUpdateNodeCapabilities:R,nodeSystemPromptDrafts:z,onNodeSystemPromptDraftChange:Q,savingNodeSystemPromptId:ne,onSaveNodeSystemPrompt:J,selectedNodeId:Z,onSelectNode:de,showAddNode:te,onShowAddNode:B,onCancelAddNode:ie,nodeWorkspace:Y,onNodeWorkspaceChange:le,nodeProviderPriority:Ne,onNodeProviderPriorityChange:we,nodeDaemonId:Se,onNodeDaemonIdChange:me,nodeCustomPath:q,onNodeCustomPathChange:W,nodePickerWorkspaces:X,nodePickerProviders:K,attachableDaemons:ue,onAddNode:Pe,onRemoveNode:ce,availableCliAgents:F,features:pe,sendCommand:xe}){var Be,at;const{t:U}=Ce("common"),be=Ii(e),je=e.nodes||[],ge=je.some(oe=>{var lt;const He=Number((lt=oe.policy)==null?void 0:lt.schedulingPriority);return Number.isFinite(He)&&He!==0}),Ie=!be.schedulingStrategy,et=l.useMemo(()=>je.some(oe=>{var He;return Array.isArray((He=oe.policy)==null?void 0:He.slots)&&oe.policy.slots.length>0}),[je]),Ze=Ie?et?"smart":je.length>=2?"spread":null:null,[rt,he]=l.useState(!1),Ee=!!G&&!!e.id;return s.jsxs(Tr,{icon:s.jsx(rs,{}),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:r,children:U("repoMesh.detail.back")}),s.jsxs("button",{className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:()=>d(!0),disabled:i,children:[s.jsx(BP,{size:13}),U(i?"repoMesh.detail.probing":"repoMesh.detail.refresh")]}),s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>a(e.id),children:U("repoMesh.detail.delete")})]}),children:[t&&s.jsx(Ft,{variant:"error",onDismiss:n,className:"mb-4",children:t}),pe.meshHostDaemonSection&&s.jsx(PD,{daemons:h,coordinatorDaemonId:v,onCoordinatorDaemonIdChange:w,coordinatorCliType:b,onCoordinatorCliTypeChange:j,launchingCoordinator:C,launchResult:y,isHostNodeAttached:x,selectedHostNode:N,hostPinned:S,hostLabel:A,hostOnline:T,hostRebindDaemonId:I,onHostRebindDaemonIdChange:oe=>{D(oe),d()},onLaunchCoordinator:P}),s.jsxs(ft,{title:U("repoMesh.detail.observabilityTitle"),description:U("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:()=>he(!0),disabled:!Ee,title:U(Ee?"repoMesh.detail.observabilityOpenTitle":"repoMesh.detail.observabilityDisabledTitle"),children:[s.jsx(rs,{size:14}),U("repoMesh.detail.observabilityOpen")]}),s.jsx("span",{className:"text-[12px] text-text-muted",children:U("repoMesh.detail.observabilityHint")})]})]}),s.jsx(MD,{nodes:je,meshQueue:H,activeDaemon:_,daemons:h,selectedMeshId:e.id,userName:L,features:{addNodeDaemonPicker:pe.addNodeDaemonPicker,nodeInstruction:pe.nodeInstruction},coordinatorDaemonId:v,availableCliProviders:O,savingNodeSlotsId:E,onUpdateNodeSlots:M,savingNodeCapabilitiesId:$,onUpdateNodeCapabilities:R,nodeSystemPromptDrafts:z,onNodeSystemPromptDraftChange:Q,savingNodeSystemPromptId:ne,onSaveNodeSystemPrompt:J,selectedNodeId:Z,onSelectNode:de,showAddNode:te,onShowAddNode:B,onCancelAddNode:ie,nodeWorkspace:Y,onNodeWorkspaceChange:le,nodeProviderPriority:Ne,onNodeProviderPriorityChange:we,nodeDaemonId:Se,onNodeDaemonIdChange:me,nodeCustomPath:q,onNodeCustomPathChange:W,nodePickerWorkspaces:X,nodePickerProviders:K,attachableDaemons:ue,onAddNode:Pe,onRemoveNode:ce}),s.jsxs(ft,{title:U("repoMesh.detail.schedulingTitle"),description:U("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:U("repoMesh.detail.distribution")}),s.jsx("div",{className:"flex flex-col gap-2",children:ID.map(oe=>{const lt=RD(be.schedulingStrategy,{priorityConfigured:ge})===oe.value;return s.jsxs("label",{className:`flex items-start gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${lt?"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:oe.value,checked:lt,disabled:p,onChange:()=>u({schedulingStrategy:LD(oe.value)})}),s.jsxs("span",{className:"min-w-0",children:[s.jsxs("span",{className:"flex items-center gap-2 text-sm text-text-primary",children:[oe.label,Ze===oe.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:U("repoMesh.detail.recommended")})]}),s.jsx("span",{className:"block text-[12px] text-text-muted",children:oe.description})]})]},oe.value)})})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:U("repoMesh.detail.saving")})]}),s.jsx(ft,{title:U("repoMesh.detail.visibilityTitle"),description:U("repoMesh.detail.visibilityDescription"),children:s.jsx(Nt,{label:U("repoMesh.detail.visibilityLabel"),hint:U("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:be.spawnedSessionVisibility==="visible"?"visible":"hidden",onChange:oe=>u({spawnedSessionVisibility:oe.target.value==="visible"?"visible":"hidden"}),disabled:p,children:[s.jsx("option",{value:"hidden",children:U("repoMesh.detail.visibilityHidden")}),s.jsx("option",{value:"visible",children:U("repoMesh.detail.visibilityVisible")})]})})}),o&&s.jsx(ft,{title:U("repoMesh.detail.magiTitle"),description:U("repoMesh.detail.magiDescription"),children:s.jsx(XP,{status:o,daemonId:G,sendDaemonCommand:xe,availableProviders:O})}),s.jsx(dD,{hostDaemonId:v,hostOnline:T,hostWorkspace:(N==null?void 0:N.workspace)||"",hostProviders:((Be=h.find(oe=>oe.id===v))==null?void 0:Be.availableProviders)||[],machineAutoApproveEnabled:be.delegatedWorkerAutoApprove!==!1,machineDangerousAllowed:be.delegatedWorkerDangerousModeAllow===!0,sendCommand:xe}),s.jsx(oD,{status:o,daemonId:G,meshId:e.id,sendCommand:xe}),pe.coordinatorPrompt&&s.jsxs(ft,{title:U("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:U("repoMesh.detail.advanced")}),description:U("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:U("repoMesh.detail.thisMesh")}),s.jsx("p",{className:"text-[12px] text-text-muted mb-3",children:U("repoMesh.detail.thisMeshHint",{name:e.name})}),s.jsxs(Nt,{label:U("repoMesh.detail.overrideLabel"),hint:U("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:oe=>f({...m,override:oe.target.value}),disabled:g,placeholder:U("repoMesh.detail.overridePlaceholder")}),s.jsx(ZP,{daemonId:G,meshId:e.id,cliType:b,sendCommand:xe})]}),s.jsx(Nt,{label:U("repoMesh.detail.appendLabel"),hint:U("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:oe=>f({...m,append:oe.target.value}),disabled:g,placeholder:U("repoMesh.detail.appendPlaceholder")})}),s.jsxs("details",{className:"mt-2 text-[12px] text-text-muted",children:[s.jsx("summary",{className:"cursor-pointer select-none",children:U("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:U(g?"repoMesh.detail.saving":"repoMesh.detail.saveCoordinatorPrompt")}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>f({override:"",append:""}),disabled:g,title:U("repoMesh.detail.clearTitle"),children:U("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:U("repoMesh.detail.userLevel")}),s.jsx("p",{className:"text-[12px] text-text-muted mb-3",children:U("repoMesh.detail.userLevelDescription")}),s.jsx(hC,{daemonId:G||void 0})]})]}),s.jsxs(ft,{title:U("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:U("repoMesh.detail.advanced")}),description:U("repoMesh.detail.safetyDescription"),children:[s.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:[{label:U("repoMesh.detail.checkpointBefore"),key:"requirePreTaskCheckpoint",opts:[["no","No"],["yes","Yes"]],val:oe=>oe?"yes":"no",parse:oe=>oe==="yes"},{label:U("repoMesh.detail.checkpointAfter"),key:"requirePostTaskCheckpoint",opts:[["yes","Yes"],["no","No"]],val:oe=>oe?"yes":"no",parse:oe=>oe==="yes"},{label:U("repoMesh.detail.pushApproval"),key:"requireApprovalForPush",opts:[["required",U("repoMesh.detail.requireApprovalBeforePush")],["not_required",U("repoMesh.detail.doNotRequireApproval")]],val:oe=>oe?"required":"not_required",parse:oe=>oe==="required"},{label:U("repoMesh.detail.destructiveGitApproval"),key:"requireApprovalForDestructiveGit",opts:[["required",U("repoMesh.detail.requireApproval")],["not_required",U("repoMesh.detail.doNotRequireApproval")]],val:oe=>oe?"required":"not_required",parse:oe=>oe==="required"},{label:U("repoMesh.detail.uncommittedChanges"),key:"dirtyWorkspaceBehavior",opts:[["warn",U("repoMesh.detail.warnAndContinue")],["block",U("repoMesh.detail.blockTask")],["checkpoint_then_continue",U("repoMesh.detail.checkpointThenContinue")]],val:oe=>oe||"warn",parse:oe=>oe},{label:U("repoMesh.detail.autoPublishSubmodule"),key:"allowAutoPublishSubmoduleMainCommits",opts:[["disabled",U("repoMesh.detail.requireExplicitApproval")],["enabled",U("repoMesh.detail.allowRefineryPublish")]],val:oe=>oe?"enabled":"disabled",parse:oe=>oe==="enabled"}].map(({label:oe,key:He,opts:lt,val:ut,parse:St})=>s.jsx(Nt,{label:oe,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:ut(be[He]),onChange:V=>u({[He]:St(V.target.value)}),disabled:p,children:lt.map(([V,ee])=>s.jsx("option",{value:V,children:ee},V))})},He))}),(()=>{const oe=be.autoFastForward&&typeof be.autoFastForward=="object"?be.autoFastForward:{},He=oe.enabled!==!1,lt=oe.remoteNodes===!0,ut=oe.mode==="continuous"?"continuous":"idle",St=V=>u({autoFastForward:{...oe,...V}});return s.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[s.jsx(Nt,{label:U("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:He?"enabled":"disabled",onChange:V=>St({enabled:V.target.value==="enabled"}),disabled:p,children:[s.jsx("option",{value:"enabled",children:U("repoMesh.detail.ffEnabled")}),s.jsx("option",{value:"disabled",children:U("repoMesh.detail.ffDisabled")})]})}),s.jsx(Nt,{label:U("repoMesh.detail.includeRemoteNodes"),hint:U("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:lt?"yes":"no",onChange:V=>St({remoteNodes:V.target.value==="yes"}),disabled:p||!He,children:[s.jsx("option",{value:"no",children:U("repoMesh.detail.remoteNo")}),s.jsx("option",{value:"yes",children:U("repoMesh.detail.remoteYes")})]})}),s.jsx(Nt,{label:U("repoMesh.detail.detectionMode"),hint:U("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:ut,onChange:V=>St({mode:V.target.value==="continuous"?"continuous":"idle"}),disabled:p||!He||!lt,children:[s.jsx("option",{value:"idle",children:U("repoMesh.detail.idleEdgeOnly")}),s.jsx("option",{value:"continuous",children:U("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(Nt,{label:U("repoMesh.detail.sessionCleanupLabel"),hint:U("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:be.sessionCleanupOnNodeRemove||"preserve",onChange:oe=>u({sessionCleanupOnNodeRemove:oe.target.value}),disabled:p,children:Yo.map(oe=>s.jsx("option",{value:oe.value,children:oe.label},oe.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((at=Yo.find(oe=>oe.value===be.sessionCleanupOnNodeRemove))==null?void 0:at.description)||Yo[0].description})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:U("repoMesh.detail.saving")})]}),pe.hermesMcpConfig&&s.jsx(DD,{meshId:e.id,availableCliAgents:F}),pe.meshHostDaemonSection&&s.jsxs(Ft,{variant:"info",className:"mt-4",children:[s.jsx("strong",{children:"MCP Mode:"})," ",s.jsxs("code",{className:"bg-bg-secondary px-1 rounded text-xs",children:["adhdev mcp --repo-mesh ",e.id]})," · The mesh MCP server can be used directly from your CLI agent."]}),rt&&Ee&&s.jsx(gh,{activeConv:_D({meshId:e.id,daemonId:G,meshName:e.name}),sendDaemonCommand:xe,onClose:()=>he(!1)})]})}const er=new Map;function HD({daemons:e,primaryDaemonId:t,sendCommand:n,unwrapResult:r,normalizeMesh:a,features:o,loadDaemonMetadata:i}){const c=e.map(M=>M.id).filter(Boolean).sort().join(","),[d,p]=l.useState(()=>er.get(c)??[]),[u,m]=l.useState(null),[f,g]=l.useState(()=>!er.has(c)),[k,h]=l.useState(null),[v,w]=l.useState(!1),[b,j]=l.useState(""),[C,y]=l.useState(""),[x,N]=l.useState(""),[S,A]=l.useState(""),[T,I]=l.useState(""),D=l.useMemo(()=>e.find(M=>M.id===S),[e,S]),P=(D==null?void 0:D.workspaces)||[],_=l.useMemo(()=>Ln((D==null?void 0:D.availableProviders)||[]),[D]);l.useEffect(()=>{!o.createDaemonPicker||!i||!S||!D||!(!D.workspaces||!D.availableProviders)||Promise.resolve(i(S,{minFreshMs:3e4})).catch(()=>{})},[o.createDaemonPicker,i,S,D]);const G=l.useMemo(()=>e.map(M=>M.id).filter(Boolean).sort().join(","),[e]),H=l.useCallback(async(M=!1)=>{const $=M||er.has(G);g(R=>$?R:!0);try{if(o.createDaemonPicker){const R=await Promise.allSettled(e.map(async ne=>{if(!ne.id)return[];const J=await n(ne.id,"list_meshes",{}),Z=r(J);if((Z==null?void 0:Z.success)===!1)throw new Error(Z.error||"Failed to load meshes");return(Array.isArray(Z==null?void 0:Z.meshes)?Z.meshes:[]).map(de=>a(de,ne.id)).filter(de=>de.id)})),z=new Map;for(const ne of R)if(ne.status==="fulfilled")for(const J of ne.value)z.has(J.id)||z.set(J.id,J);const Q=Array.from(z.values());p(Q),er.set(G,Q),h(null)}else{if(!t)return;const R=await n(t,"list_meshes");if(R!=null&&R.success){const z=(R.meshes||[]).map(Q=>a(Q,t));p(z),er.set(G,z),h(null)}else h((R==null?void 0:R.error)||"Failed to load meshes")}}catch(R){h((R==null?void 0:R.message)||"Failed to load meshes")}finally{g(!1)}},[G,t,n,r,a,o.createDaemonPicker]);async function L(){var z,Q;const M=o.createDaemonPicker?S:t;if(!M||!b.trim())return;const $=x.trim(),R=C.trim();if(!(!$&&!R))try{const ne={name:b.trim()};$&&(ne.repoRemoteUrl=$),R&&(ne.repoIdentity=R);const J=await n(M,"create_mesh",ne),Z=r(J);if((Z==null?void 0:Z.success)===!1)throw new Error(Z.error||"Create failed");const de=typeof((z=Z==null?void 0:Z.mesh)==null?void 0:z.id)=="string"?Z.mesh.id:"";if(de&&o.createDaemonPicker&&T){const te=await n(M,"add_mesh_node",{meshId:de,daemonId:M,machineId:D==null?void 0:D.machineId,workspace:T,role:"host",providerPriority:yr(_)}),B=r(te);if((B==null?void 0:B.success)===!1)throw new Error(B.error||"Mesh created but failed to attach workspace")}w(!1),j(""),y(""),N(""),I(""),await H(),(Q=Z==null?void 0:Z.mesh)!=null&&Q.id&&m(Z.mesh.id)}catch(ne){h((ne==null?void 0:ne.message)||"Create failed")}}async function O(M){var R;if(!confirm("Delete this mesh? This cannot be undone."))return;const $=((R=d.find(z=>z.id===M))==null?void 0:R.__sourceDaemonId)||t;try{const z=await n($,"delete_mesh",{meshId:M}),Q=r(z);if((Q==null?void 0:Q.success)===!1)throw new Error(Q.error||"Failed to delete");u===M&&m(null),await H()}catch(z){h((z==null?void 0:z.message)||"Delete failed")}}function E(){w(!1),j(""),y(""),N("")}return{meshes:d,setMeshes:p,selectedMeshId:u,setSelectedMeshId:m,loading:f,error:k,setError:h,showCreate:v,setShowCreate:w,createName:b,setCreateName:j,createRepoIdentity:C,setCreateRepoIdentity:y,createRepoRemoteUrl:x,setCreateRepoRemoteUrl:N,newMeshDaemonId:S,setNewMeshDaemonId:A,newMeshWorkspace:T,setNewMeshWorkspace:I,createPickerWorkspaces:P,createPickerProviders:_,loadMeshes:H,handleCreate:L,handleDelete:O,cancelCreate:E}}function FD({selectedMesh:e,selectedMeshId:t,primaryDaemonId:n,activeDaemonId:r,daemons:a,sendCommand:o,unwrapResult:i,loadLiveMesh:c,resolveCommandTarget:d,launchCoordinator:p,features:u,loadMeshes:m,loadQueue:f,queueSection:g,setError:k}){const[h,v]=l.useState({}),[w,b]=l.useState(null),[j,C]=l.useState(null),[y,x]=l.useState(!1),[N,S]=l.useState(""),[A,T]=l.useState([]),[I,D]=l.useState(""),[P,_]=l.useState(!1),[G,H]=l.useState(""),[L,O]=l.useState(!1),[E,M]=l.useState(null),[$,R]=l.useState(!1),[z,Q]=l.useState({override:"",append:""}),[ne,J]=l.useState(!1),[Z,de]=l.useState({}),[te,B]=l.useState(null),ie=l.useMemo(()=>a.find(xe=>xe.id===I),[a,I]),Y=(ie==null?void 0:ie.workspaces)||[],le=l.useMemo(()=>Ln((ie==null?void 0:ie.availableProviders)||[]),[ie]);async function Ne(){const xe=(e==null?void 0:e.__sourceDaemonId)||n;if(!t||!xe)return;const U=N.trim();if(U)try{const be={meshId:t,workspace:U};u.addNodeDaemonPicker&&I&&(be.daemonId=I,be.machineId=ie==null?void 0:ie.machineId),be.providerPriority=Rn(A);const je=await o(xe,"add_mesh_node",be),ge=i(je);if((ge==null?void 0:ge.success)===!1)throw new Error(ge.error||"Add node failed");x(!1),S(""),T([]),D(""),_(!1),await m(),g||await f(t)}catch(be){k((be==null?void 0:be.message)||"Add node failed")}}async function we(xe){var ge;if(!e)return;const U=Ii(e),be=((ge=[{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(Ie=>Ie.value===U.sessionCleanupOnNodeRemove))==null?void 0:ge.label)||"Preserve history and runtimes";if(!confirm(`Remove this node?
|
|
120
120
|
|
|
121
|
-
Node removal cleanup policy: ${be}`))return;const je=e.__sourceDaemonId||n;try{const Ie=await o(je,"remove_mesh_node",{meshId:e.id,nodeId:xe}),et=i(Ie);if((et==null?void 0:et.success)===!1)throw new Error(et.error||"Remove failed");j===xe&&C(null),await m(),g||await f(t)}catch(Ie){k((Ie==null?void 0:Ie.message)||"Remove node failed")}}async function Se(xe){if(!e)return;const U={...Ii(e),...xe},be=e.__sourceDaemonId||n;try{R(!0),k(null);const je=await o(be,"update_mesh",{meshId:e.id,policy:U}),ge=i(je);if((ge==null?void 0:ge.success)===!1)throw new Error(ge.error||"Policy update failed");await m()}catch(je){k((je==null?void 0:je.message)||"Policy update failed")}finally{R(!1)}}async function me(xe){if(!t)return;const U=(e==null?void 0:e.__sourceDaemonId)||n,be=h[xe.id]||BD(xe),je=Rn(be),ge={...xe.policy||{}};delete ge.provider_priority,je.length?ge.providerPriority=je:delete ge.providerPriority;try{b(xe.id),k(null);const Ie=await o(U,"update_mesh_node",{meshId:t,nodeId:xe.id,policy:ge,providerPriority:je}),et=i(Ie);if((et==null?void 0:et.success)===!1){k(et.error||"Node policy update failed");return}await m()}catch(Ie){k((Ie==null?void 0:Ie.message)||"Node policy update failed")}finally{b(null)}}const[q,W]=l.useState(null);async function X(xe,U){if(!t)return;const be=(e==null?void 0:e.__sourceDaemonId)||n;try{W(xe.id),k(null);const je=await o(be,"update_mesh_node",{meshId:t,nodeId:xe.id,policy:{slots:U}}),ge=i(je);if((ge==null?void 0:ge.success)===!1){k(ge.error||"Node slots update failed");return}await m()}catch(je){k((je==null?void 0:je.message)||"Node slots update failed")}finally{W(null)}}const[K,ue]=l.useState(null);async function Pe(xe,U){if(!t)return;const be=(e==null?void 0:e.__sourceDaemonId)||n,je=U.map(ge=>ge.trim()).filter(Boolean);try{ue(xe.id),k(null);const ge=await o(be,"update_mesh_node",{meshId:t,nodeId:xe.id,capabilities:je}),Ie=i(ge);if((Ie==null?void 0:Ie.success)===!1){k(Ie.error||"Node tag update failed");return}await m()}catch(ge){k((ge==null?void 0:ge.message)||"Node tag update failed")}finally{ue(null)}}async function ce(){if(!n||!t)return;const U={...(e==null?void 0:e.coordinator)||{}};z.override.trim()?U.systemPromptOverride=z.override:delete U.systemPromptOverride,z.append.trim()?U.systemPromptAppend=z.append:delete U.systemPromptAppend,delete U.systemPromptSuffix;try{J(!0),k(null);const be=await o(n,"update_mesh",{meshId:t,coordinator:U}),je=i(be);if((je==null?void 0:je.success)===!1){k(je.error||"Coordinator prompt save failed");return}await m()}catch(be){k((be==null?void 0:be.message)||"Coordinator prompt save failed")}finally{J(!1)}}async function F(xe){if(!n||!t)return;const U=(Z[xe.id]||"").trim();try{B(xe.id),k(null);const be=await o(n,"update_mesh_node",{meshId:t,nodeId:xe.id,systemPrompt:U}),je=i(be);if((je==null?void 0:je.success)===!1){k(je.error||"Node instruction save failed");return}await m()}catch(be){k((be==null?void 0:be.message)||"Node instruction save failed")}finally{B(null)}}async function pe(){if(e){k(null),M(null);try{O(!0);const xe=c?await c(r,e.id,e):null,U=d(r,e.id,e,e.nodes||[],xe);if("error"in U)throw new Error(U.error);const be=await p(U.targetDaemonId,{meshId:e.id,inlineMesh:U.inlineMesh,coordinatorNodeId:U.coordinatorNodeId,cliType:G.trim()||void 0});M(be.message)}catch(xe){k((xe==null?void 0:xe.message)||"Coordinator launch failed")}finally{O(!1)}}}return{nodeProviderPriorityDrafts:h,setNodeProviderPriorityDrafts:v,savingNodePolicyId:w,selectedNodeId:j,setSelectedNodeId:C,showAddNode:y,setShowAddNode:x,nodeWorkspace:N,setNodeWorkspace:S,nodeProviderPriority:A,setNodeProviderPriority:T,nodeDaemonId:I,setNodeDaemonId:D,nodeCustomPath:P,setNodeCustomPath:_,nodePickerWorkspaces:Y,nodePickerProviders:le,coordinatorCliType:G,setCoordinatorCliType:H,launchingCoordinator:L,launchResult:E,savingPolicy:$,coordinatorPromptDraft:z,setCoordinatorPromptDraft:Q,savingCoordinatorPrompt:ne,nodeSystemPromptDrafts:Z,setNodeSystemPromptDrafts:de,savingNodeSystemPromptId:te,savingNodeSlotsId:q,savingNodeCapabilitiesId:K,handleAddNode:Ne,handleRemoveNode:we,handleUpdatePolicy:Se,handleUpdateNodeProviderPriority:me,handleUpdateNodeSlots:X,handleUpdateNodeCapabilities:Pe,handleSaveCoordinatorPrompt:ce,handleSaveNodeSystemPrompt:F,handleLaunchCoordinator:pe}}function BD(e){var r;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>n.has(a)?!1:(n.add(a),!0))}function OD(e){const t=e.filter(r=>r.status==="pending"||r.status==="assigned"),n=e.filter(r=>r.status==="completed"||r.status==="failed"||r.status==="cancelled");return{active:t.length,historical:n.length,activeCounts:{pending:t.filter(r=>r.status==="pending").length,assigned:t.filter(r=>r.status==="assigned").length},historicalCounts:{completed:n.filter(r=>r.status==="completed").length,failed:n.filter(r=>r.status==="failed").length},counts:{pending:e.filter(r=>r.status==="pending").length,assigned:e.filter(r=>r.status==="assigned").length,completed:e.filter(r=>r.status==="completed").length,failed:e.filter(r=>r.status==="failed").length},staleAssignedCount:e.filter(r=>r.staleAssigned).length,recent:e.slice(0,20)}}function WD({primaryDaemonId:e,activeDaemonId:t,sendCommand:n,unwrapResult:r,loadLiveMesh:a,resolveCommandTarget:o}){const[i,c]=l.useState([]),[d,p]=l.useState(null),[u,m]=l.useState(!1),[f,g]=l.useState(null),k=l.useCallback(async v=>{if(!e||!v){c([]);return}try{const w=await n(e,"get_mesh_queue",{meshId:v});c(w!=null&&w.success?Array.isArray(w.queue)?w.queue:[]:[])}catch{c([])}},[e,n]);async function h(v){var w,b;if(v){m(!0),g(null);try{const j=a?await a(t,v.id,v):null,C=o(t,v.id,v,v.nodes||[],j);if("error"in C)throw new Error(C.error);const y=await n(C.targetDaemonId,"get_mesh_queue",{meshId:v.id}),x=r(y);if((x==null?void 0:x.success)===!1)throw new Error(x.error||"Queue load failed");const N=Array.isArray(((w=x==null?void 0:x.result)==null?void 0:w.rows)??(x==null?void 0:x.rows)??(x==null?void 0:x.queue))?((b=x==null?void 0:x.result)==null?void 0:b.rows)??(x==null?void 0:x.rows)??(x==null?void 0:x.queue):[];p(OD(N))}catch(j){g((j==null?void 0:j.message)||"Queue load failed")}finally{m(!1)}}}return{meshQueue:i,setMeshQueue:c,queueSummary:d,queueLoading:u,queueError:f,loadQueue:k,handleLoadQueue:h}}function UD(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}const Sh=new Map;function Ch(e){return e?Sh.get(e)??null:null}function GD(e,t){!e||!t||Sh.set(e,t)}function qD({selectedMeshId:e,loadMeshStatus:t,extractStatus:n,normalizeNode:r,gateIncompleteGraph:a}){const[o,i]=l.useState(()=>Ch(e)),[c,d]=l.useState(!1),[p,u]=l.useState(null),[m,f]=l.useState("idle"),[g,k]=l.useState(!1),h=l.useRef(!1);async function v(w,b=e,j=!1){if(!(!w||!b))try{d(!j&&o===null),f(j?"settling":"first_paint"),u(null);const C=await t(w,b,{refresh:j,retryProfile:j?"settled":"interactive"});k(UD(C));const y=n(C),x=r&&y?{...y,nodes:(y.nodes??[]).map(N=>r(N,y.meshId??b,""))}:y;if(x){if(a&&!j&&o!==null&&!nA(eh(x))){f("settling"),h.current||(h.current=!0,Promise.resolve().then(()=>v(w,b,!0)).finally(()=>{h.current=!1}));return}i(x),GD(b,x),f("settled")}else i(null),u("mesh_status returned an unexpected payload."),f("idle")}catch(C){o||i(null),u((C==null?void 0:C.message)||"Failed to load mesh graph"),f("idle")}finally{d(!1)}}return{meshGraphStatus:o,setMeshGraphStatus:i,graphLoading:c,graphError:p,setGraphError:u,graphProvenance:m,graphBootstrapFallback:g,loadGraph:v}}function zD(e,t,n,r,a){if(!e.length)return"";const o=String(a||"");if(o){const d=e.find(p=>Qs(p.id,o));return d?d.id:o}const i=t.find(d=>d.role==="host"),c=String((i==null?void 0:i.daemon_id)||(i==null?void 0:i.daemonId)||"");if(c){const d=e.find(p=>Qs(p.id,c));if(d)return d.id}return""}const KD=7e3,VD=45e3;function YD(){const e=FP(),{sendCommand:t,sendData:n,daemons:r,userName:a,loadMeshStatus:o,launchCoordinator:i,loadLiveMesh:c,extractStatus:d,unwrapResult:p,normalizeMesh:u,normalizeNode:m,resolveCommandTarget:f,features:g,gateIncompleteGraph:k}=e,h=Bn(),v=r[0],w=(v==null?void 0:v.id)||"",b=l.useMemo(()=>((v==null?void 0:v.availableProviders)||[]).filter(tt=>tt.category==="cli").map(tt=>({id:tt.type||tt.id,name:tt.displayName||tt.name||tt.type,meshCoordinator:tt.meshCoordinator})),[v]),j=l.useMemo(()=>Ln((v==null?void 0:v.availableProviders)||[]),[v]),{meshes:C,selectedMeshId:y,setSelectedMeshId:x,loading:N,error:S,setError:A,showCreate:T,setShowCreate:I,createName:D,setCreateName:P,createRepoIdentity:_,setCreateRepoIdentity:G,createRepoRemoteUrl:H,setCreateRepoRemoteUrl:L,newMeshDaemonId:O,setNewMeshDaemonId:E,newMeshWorkspace:M,setNewMeshWorkspace:$,createPickerWorkspaces:R,loadMeshes:z,handleCreate:Q,handleDelete:ne,cancelCreate:J}=HD({daemons:r,primaryDaemonId:w,sendCommand:t,unwrapResult:p,normalizeMesh:u,features:g,loadDaemonMetadata:h}),Z=C.find(Le=>Le.id===y)||null,{meshGraphStatus:de,setMeshGraphStatus:te,graphLoading:B,graphError:ie,setGraphError:Y,loadGraph:le}=qD({selectedMeshId:y,loadMeshStatus:o,extractStatus:d,normalizeNode:m,gateIncompleteGraph:k}),[Ne,we]=l.useState(""),[Se,me]=l.useState(""),q=g.meshHostDaemonSection&&Ne||w,{meshQueue:W,loadQueue:X}=WD({primaryDaemonId:w,activeDaemonId:q,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:f}),{setNodeProviderPriorityDrafts:K,selectedNodeId:ue,setSelectedNodeId:Pe,showAddNode:ce,setShowAddNode:F,nodeWorkspace:pe,setNodeWorkspace:xe,nodeProviderPriority:U,setNodeProviderPriority:be,nodeDaemonId:je,setNodeDaemonId:ge,nodeCustomPath:Ie,setNodeCustomPath:et,nodePickerWorkspaces:Ze,nodePickerProviders:rt,coordinatorCliType:he,setCoordinatorCliType:Ee,launchingCoordinator:Be,launchResult:at,savingPolicy:oe,coordinatorPromptDraft:He,setCoordinatorPromptDraft:lt,savingCoordinatorPrompt:ut,nodeSystemPromptDrafts:St,setNodeSystemPromptDrafts:V,savingNodeSystemPromptId:ee,savingNodeSlotsId:re,savingNodeCapabilitiesId:fe,handleAddNode:ve,handleRemoveNode:De,handleUpdatePolicy:_e,handleUpdateNodeSlots:Te,handleUpdateNodeCapabilities:qe,handleSaveCoordinatorPrompt:Xe,handleSaveNodeSystemPrompt:Ve,handleLaunchCoordinator:Fe}=FD({selectedMesh:Z,selectedMeshId:y,primaryDaemonId:w,activeDaemonId:q,daemons:r,availableCliProviders:j,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:f,launchCoordinator:i,features:{addNodeDaemonPicker:g.addNodeDaemonPicker},loadMeshes:z,loadQueue:X,queueSection:g.queueSection,setError:A}),Ue=l.useMemo(()=>r.find(Le=>Le.id===q)||v,[r,q,v]),Qe=l.useMemo(()=>new Set(((Z==null?void 0:Z.nodes)||[]).map(Le=>String(Le.daemon_id||Le.daemonId||""))),[Z]),$e=l.useMemo(()=>r.filter(Le=>Le.id&&!Qe.has(Le.id)),[r,Qe]),ae=(Z==null?void 0:Z.nodes)||[],ye=l.useMemo(()=>ae.find(Le=>Qs(String(Le.daemon_id||Le.daemonId||""),Ne)),[ae,Ne]),ke=g.meshHostDaemonSection?!!ye:!0,Re=l.useMemo(()=>{if(!g.meshHostDaemonSection||!Z)return{pinned:!1,daemonId:"",label:"",online:!1};const Le=Z.meshHost,tt=de!=null&&de.meshId&&String(de.meshId)===String(Z.id??"")?de.meshHost:void 0,Pt=tt!=null&&tt.hostDaemonId?tt:Le??tt,Qt=String((Pt==null?void 0:Pt.hostDaemonId)||""),zt=ae.find(Kt=>Kt.role==="host"),os=String((Pt==null?void 0:Pt.hostNodeId)||(zt==null?void 0:zt.id)||""),Dt=os?ae.find(Kt=>String(Kt.id)===os):void 0,xs=String((Dt==null?void 0:Dt.daemon_id)||(Dt==null?void 0:Dt.daemonId)||""),vs=Qt||xs;if(!vs)return{pinned:!1,daemonId:"",label:"",online:!1};const is=r.find(Kt=>Qt&&Qs(Kt.id,Qt))||(xs?r.find(Kt=>Qs(Kt.id,xs)):void 0);if(is)return{pinned:!0,daemonId:is.id,label:JD(is),online:!0};const Ls=String((Dt==null?void 0:Dt.machineLabel)||"")||String((Dt==null?void 0:Dt.workspace)||"")||vs;return{pinned:!0,daemonId:vs,label:Ls,online:!1}},[Z,ae,r,de,g.meshHostDaemonSection]),Ge=Re.daemonId,ot=Re.online,Oe=l.useMemo(()=>!g.meshHostDaemonSection||!Re.pinned?"":!ot&&Se&&r.some(Le=>Le.id===Se)?Se:Ge,[g.meshHostDaemonSection,Re.pinned,ot,Se,r,Ge]),bt=l.useMemo(()=>de?[...new Set((de.nodes??[]).map(Le=>String(Le.daemonId||Le.daemon_id||"")).filter(Boolean))]:[],[de]),qt=bh({status:de,daemonId:q||null,extraDaemonIds:bt,meshId:y,sendData:n});l.useEffect(()=>{K(Object.fromEntries(((Z==null?void 0:Z.nodes)||[]).map(Le=>[Le.id,QD(Le)])))},[Z]),l.useEffect(()=>{const Le=(Z==null?void 0:Z.coordinator)||{};lt({override:typeof Le.systemPromptOverride=="string"?Le.systemPromptOverride:"",append:typeof Le.systemPromptAppend=="string"?Le.systemPromptAppend:typeof Le.systemPromptSuffix=="string"?Le.systemPromptSuffix:""}),V(Object.fromEntries(((Z==null?void 0:Z.nodes)||[]).map(tt=>[tt.id,typeof tt.systemPrompt=="string"?tt.systemPrompt:""])))},[Z]),l.useEffect(()=>{const Le=g.addNodeDaemonPicker?yr(rt):yr(j);ce&&U.length===0&&Le.length>0&&be(Le)},[ce,j,rt,U.length,g.addNodeDaemonPicker]),l.useEffect(()=>{const Le=new Set(((Z==null?void 0:Z.nodes)||[]).map(tt=>tt.id));ue&&!Le.has(ue)&&Pe(null)},[Z,ue]);const Gt=l.useMemo(()=>{var Le;if(!(!(de!=null&&de.meshId)||String(de.meshId)!==String((Z==null?void 0:Z.id)??"")))return(Le=de.meshHost)==null?void 0:Le.hostDaemonId},[de,Z]),Zt=l.useMemo(()=>zD(r,ae,q,w,Gt),[r,ae,q,w,Gt]);l.useEffect(()=>{if(!g.meshHostDaemonSection)return;if(!r.length&&!Re.pinned){we("");return}const Le=Re.pinned?Oe:Zt;Le&&!Qs(Le,Ne)&&we(Le)},[r,Ne,Re.pinned,Oe,Zt,g.meshHostDaemonSection]),l.useEffect(()=>{Se&&(ot||!r.some(Le=>Le.id===Se))&&me("")},[ot,Se,r]),l.useEffect(()=>{if(g.createDaemonPicker){if(!r.length){E("");return}(!O||!r.some(Le=>Le.id===O))&&E(r[0].id)}},[r,O,g.createDaemonPicker]),l.useEffect(()=>{var Le;if(!g.createDaemonPicker||!O){$("");return}if(!R.length){$("");return}R.some(tt=>tt.path===M)||$(((Le=R[0])==null?void 0:Le.path)||"")},[O,M,R,g.createDaemonPicker]);const Jt=l.useRef(null);l.useEffect(()=>{if(!y)return;const Le=Jt.current!==y;if(Jt.current=y,Le){const tt=Ch(y);te(tt),Y(null),le(q,y,tt!==null)}else Y(null),le(q,y,!0)},[y,q]);const Is=l.useRef(le);Is.current=le;const Ae=l.useRef(!1),Ye=l.useRef(()=>{});Ye.current=()=>{Ae.current||!y||!q||(Ae.current=!0,Promise.resolve(Is.current(q,y,!0)).finally(()=>{Ae.current=!1}))};const Mt=g.meshStatePushRefresh?VD:KD;$P({daemonIds:l.useMemo(()=>[q,...bt].filter(Boolean),[q,bt]),meshId:y,sendData:n,onRevisionAdvance:()=>{typeof document<"u"&&document.visibilityState!=="visible"||Ye.current()}}),l.useEffect(()=>{if(!y||!q||typeof document>"u")return;let Le=null;const tt=()=>{document.visibilityState==="visible"&&Ye.current()},Pt=()=>{Le===null&&(Le=setInterval(tt,Mt))},Qt=()=>{Le!==null&&(clearInterval(Le),Le=null)},zt=()=>{document.visibilityState==="visible"?Pt():Qt()};return document.visibilityState==="visible"&&Pt(),document.addEventListener("visibilitychange",zt),()=>{Qt(),document.removeEventListener("visibilitychange",zt)}},[y,q,Mt]),l.useEffect(()=>{g.queueSection||X(y)},[y,g.queueSection]);const ct=l.useMemo(()=>r.map(Le=>Le.id).filter(Boolean).sort().join(","),[r]),es=l.useRef(!1);return l.useEffect(()=>{z(es.current),es.current=!0},[ct]),w?Z?s.jsx($D,{selectedMesh:Z,error:S,onDismissError:()=>A(null),onBack:()=>{x(null),te(null)},onDelete:ne,displayedMeshStatus:qt,graphLoading:B,graphError:ie,onRefreshGraph:()=>le(q,y,!0),savingPolicy:oe,onUpdatePolicy:_e,coordinatorPromptDraft:He,onCoordinatorPromptDraftChange:lt,savingCoordinatorPrompt:ut,onSaveCoordinatorPrompt:Xe,daemons:r,coordinatorDaemonId:Ne,onCoordinatorDaemonIdChange:we,coordinatorCliType:he,onCoordinatorCliTypeChange:Ee,launchingCoordinator:Be,launchResult:at,isHostNodeAttached:ke,selectedHostNode:ye,hostPinned:Re.pinned,hostLabel:Re.label,hostOnline:ot,hostRebindDaemonId:Se,onHostRebindDaemonIdChange:Le=>me(Le),onLaunchCoordinator:Fe,activeDaemon:Ue,activeDaemonId:q,meshQueue:W,userName:a,availableCliProviders:j,savingNodeSlotsId:re,onUpdateNodeSlots:Te,savingNodeCapabilitiesId:fe,onUpdateNodeCapabilities:qe,nodeSystemPromptDrafts:St,onNodeSystemPromptDraftChange:(Le,tt)=>V(Pt=>({...Pt,[Le]:tt})),savingNodeSystemPromptId:ee,onSaveNodeSystemPrompt:Ve,selectedNodeId:ue,onSelectNode:Pe,showAddNode:ce,onShowAddNode:()=>F(!0),onCancelAddNode:()=>F(!1),nodeWorkspace:pe,onNodeWorkspaceChange:xe,nodeProviderPriority:U,onNodeProviderPriorityChange:be,nodeDaemonId:je,onNodeDaemonIdChange:ge,nodeCustomPath:Ie,onNodeCustomPathChange:et,nodePickerWorkspaces:Ze,nodePickerProviders:rt,attachableDaemons:$e,onAddNode:ve,onRemoveNode:De,availableCliAgents:b,features:{coordinatorPrompt:g.coordinatorPrompt,meshHostDaemonSection:g.meshHostDaemonSection,hermesMcpConfig:g.hermesMcpConfig,addNodeDaemonPicker:g.addNodeDaemonPicker,nodeInstruction:g.nodeInstruction},sendCommand:t}):s.jsx(zP,{meshes:C,loading:N,error:S,onDismissError:()=>A(null),daemons:r,features:{createDaemonPicker:g.createDaemonPicker,maxMeshes:g.maxMeshes},showCreate:T,onToggleCreate:()=>I(!T),createName:D,onCreateNameChange:P,createRepoIdentity:_,onCreateRepoIdentityChange:G,createRepoRemoteUrl:H,onCreateRepoRemoteUrlChange:L,newMeshDaemonId:O,onNewMeshDaemonIdChange:E,newMeshWorkspace:M,onNewMeshWorkspaceChange:$,createPickerWorkspaces:R,onSelectMesh:x,onCreate:Q,onCancelCreate:J}):s.jsx(Tr,{icon:s.jsx(rs,{}),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 JD(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function QD(e){var r;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>n.has(a)?!1:(n.add(a),!0))}function XD({children:e}){const{sendCommand:t,sendData:n}=wt(),{ides:r}=js(),a=l.useMemo(()=>r.filter(i=>i.daemonMode||i.type==="adhdev-daemon").map(i=>i),[r]),o=l.useMemo(()=>({sendCommand:t,sendData:n,daemons:a,userName:void 0,loadMeshStatus:async(i,c)=>t(i,"mesh_status",{meshId:c}),launchCoordinator:async(i,c)=>{var f;const d={meshId:c.meshId};c.cliType&&(d.cliType=c.cliType);const p=await t(i,"launch_mesh_coordinator",d),u=(p==null?void 0:p.result)??p;if((u==null?void 0:u.success)===!1)throw new Error(u.error||"Coordinator launch failed");const m=(u==null?void 0:u.sessionId)||((f=u==null?void 0:u.session)==null?void 0:f.id)||(u==null?void 0:u.targetSessionId);return{sessionId:m,message:m?`Coordinator launched (${m})`:"Coordinator launch command sent"}},loadLiveMesh:void 0,extractStatus:el,unwrapResult:i=>i,normalizeMesh:(i,c)=>i,normalizeNode:(i,c,d)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:HP}),[t,n,a]);return s.jsx(kh.Provider,{value:o,children:e})}function Dl(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function ZD(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=Dl();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 ks(e,t){return await fetch(ZD(e),{credentials:"same-origin",...t})}function jh(){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 eI{constructor(){st(this,"adapters",new Map);st(this,"states",new Map);st(this,"runtimeListeners",new Map);st(this,"screenshotCallbacks",new Map);st(this,"statusCallbacks",new Set);st(this,"stateChangeCallbacks",new Set);st(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 r=this.resolveDaemonId(t)||t;this.stateChangeCallbacks.forEach(a=>a(r,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,r){return this.ptyInputSender?this.ptyInputSender(t,n,r):!1}onScreenshot(t,n){return this.screenshotCallbacks.set(t,n),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,n){this.screenshotCallbacks.forEach(r=>r(t,n))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,n){this.statusCallbacks.forEach(r=>r(t,n))}emitRuntimeSnapshot(t,n,r=0,a=!1,o,i){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:r,text:n,truncated:a,cols:o,rows:i})}emitSessionOutput(t,n,r){!t||typeof n!="string"||!n||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof r=="number"?{seq:r}:{},data:n})}onRuntimeEvent(t,n){const r=this.runtimeListeners.get(t)||new Set;return r.add(n),this.runtimeListeners.set(t,r),()=>{const a=this.runtimeListeners.get(t);a&&(a.delete(n),a.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,n,r){if(!n)return{success:!1,error:"sessionId is required"};const a=new URL(`/api/v1/runtime/${encodeURIComponent(n)}/snapshot`,window.location.origin);typeof(r==null?void 0:r.sinceSeq)=="number"&&a.searchParams.set("sinceSeq",String(r.sinceSeq));const o=await ks(`${a.pathname}${a.search}`);if(!o.ok){let c=`Runtime snapshot unavailable (${o.status})`;try{const d=await o.json();d!=null&&d.error&&(c=d.error)}catch{}return{success:!1,error:c}}const i=await o.json();return this.emitRuntimeEvent(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:!!(r!=null&&r.force)}),{success:!0}}emitRuntimeEvent(t,n){var r;(r=this.runtimeListeners.get(t))==null||r.forEach(a=>a(n))}}const ws=new eI;function tI(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,n=Dl();return n?`${t}?token=${encodeURIComponent(n)}`:t}const ea=tI(),Yd=3e3,sI=3e4;let ds=null,nI=0;const La=new Map;let Vs=null,mr=null;function Jd(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function tr(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function rI(e){return e==="connected"?"connected":e}async function hr(e,t,n){const r=qp(e,n||{}),a=ds;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++nI}_${Date.now()}`;return new Promise((i,c)=>{const d=setTimeout(()=>{La.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);La.set(o,{resolve:p=>{clearTimeout(d),i(p)},reject:p=>{clearTimeout(d),c(p)}}),a.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:r.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function Li(e,t){const n=ds;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 Nh(e,t,n){const r=ds;if(!r||r.readyState!==WebSocket.OPEN)return!1;const a=qp(e,{sessionId:t,targetSessionId:t,data:n});try{return r.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:a.payload}})),!0}catch{return!1}}ws.registerPtyInputSender(Nh);class aI{constructor(t){st(this,"daemonId");st(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(ds==null?void 0:ds.readyState)===WebSocket.OPEN}get connectionState(){return(ds==null?void 0:ds.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,n){return hr(this.daemonId,t,n)}async sendInput(t,n){return hr(this.daemonId,"cdp_remote_action",{action:t,params:n,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,Vs&&(clearInterval(Vs),Vs=null);const n=async()=>{if(this.hasCommandChannel)try{const r=await hr(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(r!=null&&r.success&&(r!=null&&r.base64)){const a=await fetch(`data:image/jpeg;base64,${r.base64}`).then(o=>o.blob());ws.emitScreenshot(this.daemonId,a)}}catch{}};n(),Vs=setInterval(n,2e3)}stopScreenshots(t){Vs&&(clearInterval(Vs),Vs=null)}}let ss=null;function oI(e){return(!ss||ss.daemonId!==e)&&(ss=new aI(e)),ss}function iI({children:e}){const t=l.useRef(fr()),n=fr();t.current=n;const{setUserName:r}=js(),a=l.useRef(r);a.current=r;const o=l.useRef(null),i=l.useRef(null),[,c]=l.useState("disconnected"),d=l.useCallback((h,v)=>{c(h),mr==null||mr(h,v)},[]),p=l.useRef(null),u=l.useRef(),m=l.useRef(Yd),f=l.useRef(!0),g=l.useRef(!1),k=l.useRef("initial_connect");return l.useEffect(()=>{f.current=!0,g.current=!1;function h(){var b,j;if(!f.current||((b=p.current)==null?void 0:b.readyState)===WebSocket.OPEN||((j=p.current)==null?void 0:j.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${ea}...`),tr("connect_attempt",{url:ea,reason:k.current,delayMs:m.current});let w;try{w=new WebSocket(ea)}catch(C){console.error("[Standalone WS] Failed to create WebSocket:",C),v();return}p.current=w,w.onopen=()=>{if(!f.current){w.close();return}d("connected"),m.current=Yd,tr("open",{url:ea,reason:k.current}),hs.resubscribeAll({sendData:Li}),console.log("[Standalone WS] Connected")},ds=w,w.onmessage=C=>{var y,x;try{const N=JSON.parse(C.data);if((N.type==="command_result"||N.type==="error")&&N.requestId){const S=La.get(N.requestId);S&&(La.delete(N.requestId),N.type==="error"?S.reject(new Error(((y=N.data)==null?void 0:y.message)||"Command failed")):S.resolve(N.data));return}if(N.type==="session_output"){const S=N.sessionId||N.cliId||N.cliType;S&&ws.emitSessionOutput(S,typeof N.data=="string"?N.data:"",typeof N.seq=="number"?N.seq:void 0);return}if(N.type==="runtime_snapshot"){ws.emitRuntimeSnapshot(N.sessionId,typeof N.text=="string"?N.text:"",typeof N.seq=="number"?N.seq:0,!!N.truncated,typeof N.cols=="number"?N.cols:void 0,typeof N.rows=="number"?N.rows:void 0);return}if(N.type==="topic_update"){const S=N.update;S&&hs.publish(S);return}if(N.type==="status"||N.type==="initial_state"){const S=N.data;if(!S)return;const{injectEntries:A,markLoaded:T,getIdes:I}=t.current,D=S.instanceId||"standalone",P=I().find(H=>H.id===D),_=oI(D);ws.register(D,_),ws.setState(D,"connected"),d("connected",D),ws.emitStatus(D,S);const G=va(S,{daemonId:D,existingDaemon:P,existingEntries:I()});Jd("ws_status",{type:N.type,daemonId:D,sessions:(S.sessions||[]).map(H=>({id:H.id,parentId:H.parentId,providerType:H.providerType,kind:H.kind,transport:H.transport,unread:H.unread,inboxBucket:H.inboxBucket,lastSeenAt:H.lastSeenAt,lastUpdated:H.lastUpdated,title:H.title})),recentLaunches:(S.recentLaunches||[]).map(H=>({id:H.id,providerType:H.providerType,kind:H.kind,workspace:H.workspace,lastLaunchedAt:H.lastLaunchedAt}))}),Jd("entries",{daemonId:D,entries:G.filter(H=>H.type!=="adhdev-daemon").map(H=>({id:H.id,type:H.type,unread:H.unread,inboxBucket:H.inboxBucket,lastSeenAt:H.lastSeenAt,lastUpdated:H.lastUpdated,sessionId:H.sessionId}))}),G.length>0&&A(G,{authoritativeDaemonIds:[D]}),T(),i.current!==D&&((x=o.current)==null||x.call(o),i.current=D,o.current=hs.subscribe({sendData:Li},D,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${D}`,params:{includeSessions:!0}},H=>{if(H.topic!=="daemon.metadata")return;const L=t.current.getIdes(),O=L.find(M=>M.id===D),E=va(H.status,{daemonId:D,existingDaemon:O,existingEntries:L,timestamp:H.timestamp});E.length>0&&t.current.injectEntries(E,{authoritativeDaemonIds:[D]}),H.userName&&a.current&&a.current(H.userName)}))}}catch(N){console.error("[Standalone WS] Parse error:",N)}},w.onclose=C=>{f.current&&(ss==null||ss.stopScreenshots(),ss&&ws.setState(ss.daemonId,"disconnected"),d("disconnected"),p.current=null,k.current=`close:${C.code}${C.wasClean?":clean":":unclean"}`,tr("close",{code:C.code,reason:C.reason||"",wasClean:C.wasClean}),v())},w.onerror=C=>{g.current||!f.current||(k.current="error",tr("error",{message:C instanceof Event?"event":String(C),readyState:w.readyState}),console.warn("[Standalone WS] Error, will reconnect:",C))}}function v(){if(!f.current)return;clearTimeout(u.current);const w=m.current;console.log(`[Standalone WS] Reconnecting in ${w}ms...`),tr("schedule_reconnect",{reason:k.current,delayMs:w}),u.current=setTimeout(()=>{m.current=Math.min(m.current*1.5,sI),h()},w)}return h(),()=>{var w;f.current=!1,g.current=!0,(w=o.current)==null||w.call(o),o.current=null,i.current=null,clearTimeout(u.current),p.current&&(p.current.onerror=null,p.current.onclose=null,p.current.close(),p.current=null,ds=null),ss&&(ss.stopScreenshots(),ws.unregister(ss.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function lI({children:e}){const[t,n]=l.useState("disconnected"),[r,a]=l.useState(null);l.useEffect(()=>(mr=(i,c)=>{n(i),c&&a(c)},()=>{mr=null}),[]);const o=l.useMemo(()=>{const i=t==="connected",c=rI(t),d={};return r&&(d[r]=c),d.standalone=c,{wsStatus:t,isConnected:i,connectionStates:d}},[t,r]);return s.jsx(kf,{connectionOverrides:o,children:s.jsx(iI,{children:e})})}const Ah="adhdev_standalone_font_preferences",rn={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Za=[{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"}],Sr=[{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"}],cI=new Set(Za.map(e=>e.id)),dI=new Set(Sr.map(e=>e.id));function Ss(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:pa("chat",t.chat),code:pa("code",t.code),terminal:pa("terminal",t.terminal)}}function pa(e,t){const n=rn[e],r=t&&typeof t=="object"&&!Array.isArray(t)?t:{},a=typeof r.preset=="string"?r.preset.trim():"",o=typeof r.customFamily=="string"?r.customFamily.trim():"";return(e==="chat"?cI:dI).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:n:{preset:a}:n}function ma(e,t){var a;const n=pa(e,t);if(n.preset==="custom"&&n.customFamily)return n.customFamily;const r=e==="chat"?Za:Sr;return((a=r.find(o=>o.id===n.preset))==null?void 0:a.family)||r[0].family}function uI(e){const t=Ss(e),n=ma("chat",t.chat),r=ma("code",t.code),a=ma("terminal",t.terminal);return{"--chat-font-family":n,"--chat-code-font-family":r,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function Js(e,t=document.documentElement){const n=Ss(e),r=uI(n);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(r))t.style.setProperty(a,o);return n}function Ri(e){const t=Ss(e);try{localStorage.setItem(Ah,JSON.stringify(t))}catch{}return t}function pI(){try{const e=localStorage.getItem(Ah);if(e)return Ss(JSON.parse(e))}catch{}return rn}function mI(){return Js(pI())}function sr(e,t){var r;const n=e==="chat"?Za:Sr;return((r=n.find(a=>a.id===t))==null?void 0:r.label)||n[0].label}function hI({children:e}){const t=Cr(),n=_i(),{t:r}=Ce("common"),a=l.useMemo(()=>[{id:"dashboard",path:"/dashboard",icon:s.jsx(uu,{}),label:r("standalone.nav.dashboard"),active:n.pathname.startsWith("/dashboard"),onSelect:()=>t("/dashboard")},{id:"machine",path:"/machines",icon:s.jsx(Fs,{}),label:"Burrow",active:n.pathname.startsWith("/machines"),onSelect:()=>t("/machines")},{id:"mesh",path:"/mesh",icon:s.jsx(rs,{}),label:"Mesh",active:n.pathname.startsWith("/mesh"),onSelect:()=>t("/mesh")},{id:"settings",path:"/settings",icon:s.jsx(Ea,{}),label:r("standalone.nav.settings"),active:n.pathname.startsWith("/settings"),onSelect:()=>t("/settings")}],[n.pathname,t,r]),o=l.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:r("standalone.nav.docs")}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(mu,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:r("standalone.nav.docs")},{id:"about",label:r("standalone.nav.about"),icon:s.jsx(Bi,{}),active:n.pathname==="/about",onSelect:()=>t("/about"),title:r("standalone.nav.about")}],[n.pathname,t,r]);return s.jsx(XS,{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:a,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.24"]}),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:r(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:r("standalone.layout.collapse")})]}),children:e})}const fI=[{icon:s.jsx(Fs,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(un,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(bu,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(gs,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(br,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(mu,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],bI=[{icon:s.jsx(Xf,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(uu,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Hn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(zf,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(pu,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Vf,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],gI=[{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 xI(){const{t:e}=Ce("common");return s.jsxs(Tr,{icon:s.jsx(Bi,{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.24"]}),children:[s.jsx(ft,{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(ft,{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:fI.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(ft,{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:zp.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:Vp.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:Kp.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(ft,{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:bI.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(ft,{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:gI.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(za,{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(ib,{size:14,className:"mr-1"}),e("standalone.about.discord")]})]})})]})}function Jo(e,t,n){return{...e,[t]:n}}function Qo({surface:e,title:t,description:n,value:r,options:a,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(sC,{value:r.preset,onChange:c=>{const d=c.target.value;o(d==="custom"?{preset:"custom",customFamily:r.customFamily||""}:{preset:d})},children:a.map(c=>s.jsx("option",{value:c.id,children:c.label},c.id))}),r.preset==="custom"&&s.jsx(ms,{type:"text",className:"font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:r.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:ma(e,r)})]})]})]})}function vI({value:e,savedValue:t,saving:n=!1,error:r,notice:a,onChange:o,onSave:i,onResetToSaved:c,onResetToDefaults:d}){const{t:p}=Ce("common"),u=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:p("standalone.fonts.fontOverridesNotice")}),r&&s.jsx(Ft,{variant:"error",children:r}),a&&s.jsx(Ft,{variant:"success",children:a}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(Qo,{surface:"chat",title:p("standalone.fonts.chat"),description:p("standalone.fonts.chatDescription"),value:e.chat,options:Za,onChange:m=>o(Jo(e,"chat",m))}),s.jsx(Qo,{surface:"code",title:p("standalone.fonts.code"),description:p("standalone.fonts.codeDescription"),value:e.code,options:Sr,onChange:m=>o(Jo(e,"code",m))}),s.jsx(Qo,{surface:"terminal",title:p("standalone.fonts.terminal"),description:p("standalone.fonts.terminalDescription"),value:e.terminal,options:Sr,onChange:m=>o(Jo(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: ",sr("chat",e.chat.preset)," · Code: ",sr("code",e.code.preset)," · Terminal: ",sr("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[p("standalone.fonts.defaults")," ",sr("chat",rn.chat.preset)," / ",sr("code",rn.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(Ts,{type:"button",variant:"primary",size:"sm",onClick:i,disabled:n||!u,children:p(n?"standalone.fonts.saving":"standalone.fonts.saveFontSettings")}),s.jsx(Ts,{type:"button",variant:"secondary",size:"sm",onClick:c,disabled:n||!u,children:p("standalone.fonts.revertToSaved")}),s.jsx(Ts,{type:"button",variant:"secondary",size:"sm",onClick:d,disabled:n,children:p("standalone.fonts.resetToDefaults")})]})]})}function yI(){const{t:e}=Ce("common"),{ides:t}=js(),n=t.find(B=>B.type==="adhdev-daemon"),r=(n==null?void 0:n.detectedIdes)||[],{sendCommand:a}=wt(),{userName:o}=js(),[i,c]=l.useState(o||""),[d,p]=l.useState(null),[u,m]=l.useState(null),[f,g]=l.useState(rn),[k,h]=l.useState(!1),[v,w]=l.useState(""),[b,j]=l.useState(""),[C,y]=l.useState("127.0.0.1"),[x,N]=l.useState(""),[S,A]=l.useState(""),[T,I]=l.useState(""),[D,P]=l.useState(""),[_,G]=l.useState(""),[H,L]=l.useState(!1),O=async()=>{const ie=await(await ks("/auth/session")).json();p(ie)},E=async()=>{const ie=await(await ks("/api/v1/standalone/preferences")).json();m(ie),y(ie.standaloneBindHost);const Y=Ss(ie.standaloneFontPreferences);g(Y),Js(Y),Ri(Y)};l.useEffect(()=>{o!==void 0&&c(o)},[o]),l.useEffect(()=>{Promise.all([O(),E()]).catch(B=>{P(B instanceof Error?B.message:String(B))})},[]),l.useEffect(()=>{Js(f)},[f]);const M=B=>{const ie=B.target.value.trim();n!=null&&n.id&&ie!==o&&a(n.id,"set_user_name",{userName:ie}).catch(console.error)},[$,R]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),z=B=>{R(B);try{localStorage.setItem("adhdev_sound",B?"1":"0")}catch{}},Q=async()=>{w(""),j(""),h(!0);try{const B=Ss(f),ie=await ks("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:B})}),Y=await ie.json();if(!ie.ok)throw new Error((Y==null?void 0:Y.error)||"Failed to save standalone font preferences");const le=Ss(Y.standaloneFontPreferences);m(Y),g(le),Js(le),Ri(le),j(e("standalone.settings.fontsSaved"))}catch(B){w(B instanceof Error?B.message:String(B))}finally{h(!1)}},ne=()=>{const B=Ss(u==null?void 0:u.standaloneFontPreferences);w(""),j(""),g(B),Js(B)},J=()=>{w(""),j(""),g(rn),Js(rn)},Z=async()=>{P(""),G(""),L(!0);try{const B=await ks("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:C})}),ie=await B.json();if(!B.ok)throw new Error((ie==null?void 0:ie.error)||"Failed to save standalone network preference");m(ie),y(ie.standaloneBindHost),G(ie.standaloneBindHost==="0.0.0.0"?e("standalone.settings.networkSavedAll"):e("standalone.settings.networkSavedLocal"))}catch(B){P(B instanceof Error?B.message:String(B))}finally{L(!1)}},de=async()=>{if(P(""),G(""),S.trim().length<4){P(e("standalone.settings.passwordTooShort"));return}if(S!==T){P(e("standalone.settings.passwordMismatch"));return}L(!0);try{const B=await ks("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:x,newPassword:S})}),ie=await B.json();if(!B.ok)throw new Error((ie==null?void 0:ie.error)||"Failed to save password");p(ie),await E(),N(""),A(""),I(""),G(d!=null&&d.hasPasswordAuth?e("standalone.settings.passwordUpdated"):e("standalone.settings.passwordEnabled")),jh()}catch(B){P(B instanceof Error?B.message:String(B))}finally{L(!1)}},te=async()=>{P(""),G(""),L(!0);try{const B=await ks("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:x,clear:!0})}),ie=await B.json();if(!B.ok)throw new Error((ie==null?void 0:ie.error)||"Failed to clear password");p(ie),await E(),N(""),A(""),I(""),G(e("standalone.settings.passwordDisabled"))}catch(B){P(B instanceof Error?B.message:String(B))}finally{L(!1)}};return s.jsxs(Tr,{icon:s.jsx(Ea,{className:"text-text-primary"}),title:e("standalone.settings.title"),subtitle:e("standalone.settings.subtitle"),widthClassName:"max-w-5xl",children:[s.jsx(Ft,{variant:"info",children:e("standalone.settings.infoNotice")}),(d==null?void 0:d.publicHostWarning)&&s.jsx(Ft,{variant:"warning",children:e("standalone.settings.publicHostWarning")}),s.jsx(ft,{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.24"]}),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:(u==null?void 0:u.currentBindHost)||(d==null?void 0:d.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:(u==null?void 0:u.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.authLabel")}),s.jsx("span",{className:"text-xs",children:d!=null&&d.hasPasswordAuth?e("standalone.settings.authPassword"):d!=null&&d.hasTokenAuth?e("standalone.settings.authToken"):e("standalone.settings.authNone")})]})}),s.jsx(ft,{title:e("standalone.settings.networkSection"),description:e("standalone.settings.networkDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:e("standalone.settings.networkHint")}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:C==="127.0.0.1",onChange:()=>y("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:e("standalone.settings.localhostLabel")}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:e("standalone.settings.localhostHint")})]})]}),s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:C==="0.0.0.0",onChange:()=>y("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(Ts,{type:"button",variant:"primary",size:"sm",onClick:()=>{Z()},disabled:H,children:e(H?"standalone.settings.saving":"standalone.settings.saveNetworkMode")}),s.jsx("span",{className:"text-xs text-text-muted",children:e("standalone.settings.networkRestartHint",{host:(u==null?void 0:u.currentBindHost)||(d==null?void 0:d.boundHost)||"127.0.0.1"})})]})]})}),s.jsx(ft,{title:e("standalone.settings.securitySection"),description:e("standalone.settings.securityDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:d!=null&&d.hasPasswordAuth?e("standalone.settings.passwordSet"):e("standalone.settings.passwordNotSet")}),D&&s.jsx(Ft,{variant:"error",children:D}),_&&s.jsx(Ft,{variant:"success",children:_}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx(ms,{type:"password",placeholder:d!=null&&d.hasPasswordAuth?e("standalone.settings.currentPasswordPlaceholder"):e("standalone.settings.currentPasswordFirstTimePlaceholder"),value:x,onChange:B=>N(B.target.value)}),s.jsx(ms,{type:"password",placeholder:d!=null&&d.hasPasswordAuth?e("standalone.settings.newPasswordPlaceholder"):e("standalone.settings.newPasswordFirstTimePlaceholder"),value:S,onChange:B=>A(B.target.value)}),s.jsx(ms,{type:"password",className:"md:col-span-2",placeholder:e("standalone.settings.confirmPasswordPlaceholder"),value:T,onChange:B=>I(B.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ts,{type:"button",variant:"primary",size:"sm",onClick:()=>{de()},disabled:H,children:H?e("standalone.settings.saving"):d!=null&&d.hasPasswordAuth?e("standalone.settings.updatePassword"):e("standalone.settings.enablePassword")}),(d==null?void 0:d.hasPasswordAuth)&&s.jsx(Ts,{type:"button",variant:"danger",size:"sm",onClick:()=>{te()},disabled:H,children:e("standalone.settings.disablePassword")})]})]})}),s.jsx(ft,{title:e("standalone.settings.detectedIdesSection"),description:e("standalone.settings.detectedIdesDescription"),children:r.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:r.map(B=>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 ${B.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:B.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:B.type})]},B.type))})}),s.jsx(ft,{title:e("standalone.settings.machineSection"),description:e("standalone.settings.machineDescription"),children:s.jsx(dC,{ides:t,emptyMessage:e("standalone.settings.daemonNotConnected")})}),s.jsx(ft,{title:e("standalone.settings.appearanceSection"),description:e("standalone.settings.appearanceDescription"),children:s.jsx(PC,{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(vI,{value:f,savedValue:Ss(u==null?void 0:u.standaloneFontPreferences),saving:k,error:v,notice:b,onChange:g,onSave:()=>{Q()},onResetToSaved:ne,onResetToDefaults:J})]})})}),s.jsx(ft,{title:e("standalone.settings.notificationsSection"),description:e("standalone.settings.notificationsDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(oC,{}),s.jsx(Ys,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ob,{size:15})," ",e("standalone.settings.soundEffectsLabel")]}),description:e("standalone.settings.soundEffectsDescription"),checked:$,onChange:z})]})}),s.jsx(ft,{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(qf,{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(ms,{type:"text",className:"w-48 text-right",placeholder:e("standalone.settings.displayNamePlaceholder"),value:i,onChange:B=>c(B.target.value),onBlur:M,onKeyDown:B=>{B.key==="Enter"&&B.currentTarget.blur()}})]})})})]})}const wI=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],ar="adhdev_onboarding_done",kI=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],SI={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function CI({onDone:e}){const{t}=Ce("common"),[n,r]=l.useState([]),[a,o]=l.useState(new Set(wI)),[i,c]=l.useState(!0),[d,p]=l.useState(null),[u,m]=l.useState(!1),[f,g]=l.useState(null),[k,h]=l.useState("all");l.useEffect(()=>{let x=!1;const N=window.location.hostname==="localhost"?"/registry":"https://api.adhf.dev/api/v1/registry";return fetch(`${N}/providers?sort=popular&limit=100`).then(S=>{if(!S.ok)throw new Error(`HTTP ${S.status}`);return S.json()}).then(S=>{x||r(S.providers??[])}).catch(S=>{x||p(S instanceof Error?S.message:String(S))}).finally(()=>{x||c(!1)}),()=>{x=!0}},[]);const v=n.filter(x=>k==="all"||x.category===k),w=["cli","ide","extension","acp"].map(x=>({category:x,items:v.filter(N=>N.category===x)})).filter(x=>x.items.length>0),b=l.useCallback(x=>{o(N=>{const S=new Set(N);return S.has(x)?S.delete(x):S.add(x),S})},[]),j=l.useCallback(async()=>{if(a.size===0){localStorage.setItem(ar,"1"),e();return}m(!0);const x=[];for(const N of a)try{const A=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:N})})).json().catch(()=>({}));x.push({type:N,ok:!!A.success,error:A.error})}catch(S){x.push({type:N,ok:!1,error:S instanceof Error?S.message:String(S)})}g(x),m(!1),x.every(N=>N.ok)&&localStorage.setItem(ar,"1")},[a,e]),C=l.useCallback(()=>{localStorage.setItem(ar,"1"),e()},[e]),y=l.useCallback(()=>{f&&f.every(x=>x.ok)?e():u||C()},[f,u,e,C]);return s.jsx(Xu,{open:!0,onClose:y,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(a.size!==1?"standalone.onboarding.selectedCount_other":"standalone.onboarding.selectedCount_one",{count:a.size})}),s.jsxs("div",{className:"ml-auto flex gap-2",children:[s.jsx(Ts,{variant:"secondary",size:"sm",onClick:C,disabled:u,children:t("standalone.onboarding.skip")}),s.jsx(Ts,{variant:"primary",size:"sm",onClick:()=>{f?(localStorage.setItem(ar,"1"),e()):j()},disabled:u||!f&&a.size===0,children:u?t("standalone.onboarding.installing"):f?t("standalone.onboarding.done"):t("standalone.onboarding.installCount",{count:a.size})})]})]}),children:s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsx("div",{className:"text-[12px] text-text-muted",children:t("standalone.onboarding.intro")}),!i&&!d&&n.length>0&&s.jsx("div",{className:"flex gap-1 flex-wrap border-b border-border-subtle pb-2",children:kI.map(x=>{const N=x.key==="all"?n.length:n.filter(S=>S.category===x.key).length;return N===0&&x.key!=="all"?null:s.jsxs("button",{onClick:()=>h(x.key),className:`machine-btn text-[10px] px-2 py-0.5 ${k===x.key?"bg-accent-primary/12 border-accent-primary/40 text-accent-primary":""}`,children:[x.label," ",s.jsxs("span",{className:"opacity-60",children:["(",N,")"]})]},x.key)})}),i&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.loadingRegistry")}),!i&&d&&s.jsx(Ft,{variant:"error",children:t("standalone.onboarding.loadError",{error:d})}),!i&&!d&&v.length===0&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.noProviders")}),!i&&!d&&v.length>0&&s.jsx("div",{className:"flex flex-col gap-4",children:w.map(x=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:SI[x.category]??x.category}),s.jsx("div",{className:"grid gap-1.5",children:x.items.map(N=>{var D,P;const S=a.has(N.type),A=f==null?void 0:f.find(_=>_.type===N.type),T=((D=N.manifest)==null?void 0:D.icon)??"📦",I=((P=N.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(N.type),disabled:u,className:"shrink-0"}),s.jsx("span",{className:"text-base shrink-0",children:T}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[13px] font-medium text-text-primary truncate",children:N.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"})})]},N.type)})})]},x.category))})]})})}function jI(){try{return localStorage.getItem(ar)==="1"}catch{return!1}}OS();kC();Ty();mI();const NI=ru({baseUrl:"",getToken:Dl});function AI({children:e}){const{t}=Ce("common"),[n,r]=l.useState(null),[a,o]=l.useState(!0),[i,c]=l.useState(""),[d,p]=l.useState(""),[u,m]=l.useState(!1),f=async()=>{o(!0),p("");try{const h=await(await ks("/auth/session")).json();r(h)}catch(k){p(k instanceof Error?k.message:String(k))}finally{o(!1)}};l.useEffect(()=>{f()},[]),l.useEffect(()=>{if(!n||n.required&&!n.authenticated)return;let k=!1;return(async()=>{try{const h=await ks("/api/v1/standalone/preferences");if(!h.ok)return;const v=await h.json();if(k)return;const w=Ss(v.standaloneFontPreferences);Js(w),Ri(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 h=await ks("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),v=await h.json();if(!h.ok)throw new Error((v==null?void 0:v.error)||"Login failed");r(v),c(""),jh()}catch(h){p(h instanceof Error?h.message:String(h))}finally{m(!1)}};return a?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(ms,{type:"password",value:i,onChange:k=>c(k.target.value),placeholder:t("standalone.auth.passwordPlaceholder"),autoFocus:!0}),s.jsx(Ts,{type:"submit",variant:"primary",disabled:u||!i,className:"justify-center",children:t(u?"standalone.auth.signingIn":"standalone.auth.unlock")})]}):s.jsx(Ft,{variant:"warning",children:t("standalone.auth.noPasswordEnabled")}),d&&s.jsx(Ft,{variant:"error",children:d})]})}):s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:t("standalone.auth.loadError",{error:d||"unknown error"})})}function Qd(){const{t:e}=Ce("common"),{ides:t,initialLoaded:n}=js();if(!n)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:e("standalone.machine.loading")});const r=t.find(a=>a.daemonMode||a.type==="adhdev-daemon");return r?s.jsx(ti,{to:`/machines/${r.id}`,replace:!0}):s.jsx(ti,{to:"/dashboard",replace:!0})}function TI(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let n=!1;if(!jI())return fetch("/api/v1/providers/installed").then(r=>r.ok?r.json():{providers:[]}).then(r=>{n||(r.providers??[]).length===0&&t(!0)}).catch(()=>{}),()=>{n=!0}},[]),e?s.jsx(CI,{onDone:()=>t(!1)}):null}function MI(){const{t:e}=Ce("common"),{ides:t}=js(),n=l.useMemo(()=>{for(const u of t)if(u.activeInteractivePrompt)return u.instanceId??u.id;return null},[t]),{promptSession:r,hasActivePrompt:a,responseError:o,isSubmitting:i,submit:c,cancel:d,reopen:p}=tm(n);return a?s.jsxs("div",{className:"relative",children:[!r&&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(Pu,{promptSession:r,isSubmitting:i,error:o,onSubmit:c,onCancel:d})]}):null}function PI(){const e=l.useMemo(()=>({sendCommand:hr,sendData:Li,sendPtyInput:Nh}),[]);return s.jsx(rf,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(jf,{client:NI,children:s.jsx(AI,{children:s.jsx(lI,{children:s.jsx(Af,{value:e,children:s.jsxs(Df,{sendDaemonCommand:hr,children:[s.jsx(MI,{}),s.jsxs(hI,{children:[s.jsx(TI,{}),s.jsxs(af,{children:[s.jsx(Es,{path:"/dashboard",element:s.jsx(TM,{})}),s.jsx(Es,{path:"/machine",element:s.jsx(Qd,{})}),s.jsx(Es,{path:"/machines/:id",element:s.jsx(_P,{})}),s.jsx(Es,{path:"/machines",element:s.jsx(Qd,{})}),s.jsx(Es,{path:"/about",element:s.jsx(xI,{})}),s.jsx(Es,{path:"/settings",element:s.jsx(yI,{})}),s.jsx(Es,{path:"/mesh",element:s.jsx(XD,{children:s.jsx(YD,{})})}),s.jsx(Es,{path:"*",element:s.jsx(ti,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}Ik({connectionManager:ws});of(document.getElementById("root")).render(s.jsx(PI,{}));
|
|
121
|
+
Node removal cleanup policy: ${be}`))return;const je=e.__sourceDaemonId||n;try{const Ie=await o(je,"remove_mesh_node",{meshId:e.id,nodeId:xe}),et=i(Ie);if((et==null?void 0:et.success)===!1)throw new Error(et.error||"Remove failed");j===xe&&C(null),await m(),g||await f(t)}catch(Ie){k((Ie==null?void 0:Ie.message)||"Remove node failed")}}async function Se(xe){if(!e)return;const U={...Ii(e),...xe},be=e.__sourceDaemonId||n;try{R(!0),k(null);const je=await o(be,"update_mesh",{meshId:e.id,policy:U}),ge=i(je);if((ge==null?void 0:ge.success)===!1)throw new Error(ge.error||"Policy update failed");await m()}catch(je){k((je==null?void 0:je.message)||"Policy update failed")}finally{R(!1)}}async function me(xe){if(!t)return;const U=(e==null?void 0:e.__sourceDaemonId)||n,be=h[xe.id]||BD(xe),je=Rn(be),ge={...xe.policy||{}};delete ge.provider_priority,je.length?ge.providerPriority=je:delete ge.providerPriority;try{b(xe.id),k(null);const Ie=await o(U,"update_mesh_node",{meshId:t,nodeId:xe.id,policy:ge,providerPriority:je}),et=i(Ie);if((et==null?void 0:et.success)===!1){k(et.error||"Node policy update failed");return}await m()}catch(Ie){k((Ie==null?void 0:Ie.message)||"Node policy update failed")}finally{b(null)}}const[q,W]=l.useState(null);async function X(xe,U){if(!t)return;const be=(e==null?void 0:e.__sourceDaemonId)||n;try{W(xe.id),k(null);const je=await o(be,"update_mesh_node",{meshId:t,nodeId:xe.id,policy:{slots:U}}),ge=i(je);if((ge==null?void 0:ge.success)===!1){k(ge.error||"Node slots update failed");return}await m()}catch(je){k((je==null?void 0:je.message)||"Node slots update failed")}finally{W(null)}}const[K,ue]=l.useState(null);async function Pe(xe,U){if(!t)return;const be=(e==null?void 0:e.__sourceDaemonId)||n,je=U.map(ge=>ge.trim()).filter(Boolean);try{ue(xe.id),k(null);const ge=await o(be,"update_mesh_node",{meshId:t,nodeId:xe.id,capabilities:je}),Ie=i(ge);if((Ie==null?void 0:Ie.success)===!1){k(Ie.error||"Node tag update failed");return}await m()}catch(ge){k((ge==null?void 0:ge.message)||"Node tag update failed")}finally{ue(null)}}async function ce(){if(!n||!t)return;const U={...(e==null?void 0:e.coordinator)||{}};z.override.trim()?U.systemPromptOverride=z.override:delete U.systemPromptOverride,z.append.trim()?U.systemPromptAppend=z.append:delete U.systemPromptAppend,delete U.systemPromptSuffix;try{J(!0),k(null);const be=await o(n,"update_mesh",{meshId:t,coordinator:U}),je=i(be);if((je==null?void 0:je.success)===!1){k(je.error||"Coordinator prompt save failed");return}await m()}catch(be){k((be==null?void 0:be.message)||"Coordinator prompt save failed")}finally{J(!1)}}async function F(xe){if(!n||!t)return;const U=(Z[xe.id]||"").trim();try{B(xe.id),k(null);const be=await o(n,"update_mesh_node",{meshId:t,nodeId:xe.id,systemPrompt:U}),je=i(be);if((je==null?void 0:je.success)===!1){k(je.error||"Node instruction save failed");return}await m()}catch(be){k((be==null?void 0:be.message)||"Node instruction save failed")}finally{B(null)}}async function pe(){if(e){k(null),M(null);try{O(!0);const xe=c?await c(r,e.id,e):null,U=d(r,e.id,e,e.nodes||[],xe);if("error"in U)throw new Error(U.error);const be=await p(U.targetDaemonId,{meshId:e.id,inlineMesh:U.inlineMesh,coordinatorNodeId:U.coordinatorNodeId,cliType:G.trim()||void 0});M(be.message)}catch(xe){k((xe==null?void 0:xe.message)||"Coordinator launch failed")}finally{O(!1)}}}return{nodeProviderPriorityDrafts:h,setNodeProviderPriorityDrafts:v,savingNodePolicyId:w,selectedNodeId:j,setSelectedNodeId:C,showAddNode:y,setShowAddNode:x,nodeWorkspace:N,setNodeWorkspace:S,nodeProviderPriority:A,setNodeProviderPriority:T,nodeDaemonId:I,setNodeDaemonId:D,nodeCustomPath:P,setNodeCustomPath:_,nodePickerWorkspaces:Y,nodePickerProviders:le,coordinatorCliType:G,setCoordinatorCliType:H,launchingCoordinator:L,launchResult:E,savingPolicy:$,coordinatorPromptDraft:z,setCoordinatorPromptDraft:Q,savingCoordinatorPrompt:ne,nodeSystemPromptDrafts:Z,setNodeSystemPromptDrafts:de,savingNodeSystemPromptId:te,savingNodeSlotsId:q,savingNodeCapabilitiesId:K,handleAddNode:Ne,handleRemoveNode:we,handleUpdatePolicy:Se,handleUpdateNodeProviderPriority:me,handleUpdateNodeSlots:X,handleUpdateNodeCapabilities:Pe,handleSaveCoordinatorPrompt:ce,handleSaveNodeSystemPrompt:F,handleLaunchCoordinator:pe}}function BD(e){var r;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>n.has(a)?!1:(n.add(a),!0))}function OD(e){const t=e.filter(r=>r.status==="pending"||r.status==="assigned"),n=e.filter(r=>r.status==="completed"||r.status==="failed"||r.status==="cancelled");return{active:t.length,historical:n.length,activeCounts:{pending:t.filter(r=>r.status==="pending").length,assigned:t.filter(r=>r.status==="assigned").length},historicalCounts:{completed:n.filter(r=>r.status==="completed").length,failed:n.filter(r=>r.status==="failed").length},counts:{pending:e.filter(r=>r.status==="pending").length,assigned:e.filter(r=>r.status==="assigned").length,completed:e.filter(r=>r.status==="completed").length,failed:e.filter(r=>r.status==="failed").length},staleAssignedCount:e.filter(r=>r.staleAssigned).length,recent:e.slice(0,20)}}function WD({primaryDaemonId:e,activeDaemonId:t,sendCommand:n,unwrapResult:r,loadLiveMesh:a,resolveCommandTarget:o}){const[i,c]=l.useState([]),[d,p]=l.useState(null),[u,m]=l.useState(!1),[f,g]=l.useState(null),k=l.useCallback(async v=>{if(!e||!v){c([]);return}try{const w=await n(e,"get_mesh_queue",{meshId:v});c(w!=null&&w.success?Array.isArray(w.queue)?w.queue:[]:[])}catch{c([])}},[e,n]);async function h(v){var w,b;if(v){m(!0),g(null);try{const j=a?await a(t,v.id,v):null,C=o(t,v.id,v,v.nodes||[],j);if("error"in C)throw new Error(C.error);const y=await n(C.targetDaemonId,"get_mesh_queue",{meshId:v.id}),x=r(y);if((x==null?void 0:x.success)===!1)throw new Error(x.error||"Queue load failed");const N=Array.isArray(((w=x==null?void 0:x.result)==null?void 0:w.rows)??(x==null?void 0:x.rows)??(x==null?void 0:x.queue))?((b=x==null?void 0:x.result)==null?void 0:b.rows)??(x==null?void 0:x.rows)??(x==null?void 0:x.queue):[];p(OD(N))}catch(j){g((j==null?void 0:j.message)||"Queue load failed")}finally{m(!1)}}}return{meshQueue:i,setMeshQueue:c,queueSummary:d,queueLoading:u,queueError:f,loadQueue:k,handleLoadQueue:h}}function UD(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}const Sh=new Map;function Ch(e){return e?Sh.get(e)??null:null}function GD(e,t){!e||!t||Sh.set(e,t)}function qD({selectedMeshId:e,loadMeshStatus:t,extractStatus:n,normalizeNode:r,gateIncompleteGraph:a}){const[o,i]=l.useState(()=>Ch(e)),[c,d]=l.useState(!1),[p,u]=l.useState(null),[m,f]=l.useState("idle"),[g,k]=l.useState(!1),h=l.useRef(!1);async function v(w,b=e,j=!1){if(!(!w||!b))try{d(!j&&o===null),f(j?"settling":"first_paint"),u(null);const C=await t(w,b,{refresh:j,retryProfile:j?"settled":"interactive"});k(UD(C));const y=n(C),x=r&&y?{...y,nodes:(y.nodes??[]).map(N=>r(N,y.meshId??b,""))}:y;if(x){if(a&&!j&&o!==null&&!nA(eh(x))){f("settling"),h.current||(h.current=!0,Promise.resolve().then(()=>v(w,b,!0)).finally(()=>{h.current=!1}));return}i(x),GD(b,x),f("settled")}else i(null),u("mesh_status returned an unexpected payload."),f("idle")}catch(C){o||i(null),u((C==null?void 0:C.message)||"Failed to load mesh graph"),f("idle")}finally{d(!1)}}return{meshGraphStatus:o,setMeshGraphStatus:i,graphLoading:c,graphError:p,setGraphError:u,graphProvenance:m,graphBootstrapFallback:g,loadGraph:v}}function zD(e,t,n,r,a){if(!e.length)return"";const o=String(a||"");if(o){const d=e.find(p=>Qs(p.id,o));return d?d.id:o}const i=t.find(d=>d.role==="host"),c=String((i==null?void 0:i.daemon_id)||(i==null?void 0:i.daemonId)||"");if(c){const d=e.find(p=>Qs(p.id,c));if(d)return d.id}return""}const KD=7e3,VD=45e3;function YD(){const e=FP(),{sendCommand:t,sendData:n,daemons:r,userName:a,loadMeshStatus:o,launchCoordinator:i,loadLiveMesh:c,extractStatus:d,unwrapResult:p,normalizeMesh:u,normalizeNode:m,resolveCommandTarget:f,features:g,gateIncompleteGraph:k}=e,h=Bn(),v=r[0],w=(v==null?void 0:v.id)||"",b=l.useMemo(()=>((v==null?void 0:v.availableProviders)||[]).filter(tt=>tt.category==="cli").map(tt=>({id:tt.type||tt.id,name:tt.displayName||tt.name||tt.type,meshCoordinator:tt.meshCoordinator})),[v]),j=l.useMemo(()=>Ln((v==null?void 0:v.availableProviders)||[]),[v]),{meshes:C,selectedMeshId:y,setSelectedMeshId:x,loading:N,error:S,setError:A,showCreate:T,setShowCreate:I,createName:D,setCreateName:P,createRepoIdentity:_,setCreateRepoIdentity:G,createRepoRemoteUrl:H,setCreateRepoRemoteUrl:L,newMeshDaemonId:O,setNewMeshDaemonId:E,newMeshWorkspace:M,setNewMeshWorkspace:$,createPickerWorkspaces:R,loadMeshes:z,handleCreate:Q,handleDelete:ne,cancelCreate:J}=HD({daemons:r,primaryDaemonId:w,sendCommand:t,unwrapResult:p,normalizeMesh:u,features:g,loadDaemonMetadata:h}),Z=C.find(Le=>Le.id===y)||null,{meshGraphStatus:de,setMeshGraphStatus:te,graphLoading:B,graphError:ie,setGraphError:Y,loadGraph:le}=qD({selectedMeshId:y,loadMeshStatus:o,extractStatus:d,normalizeNode:m,gateIncompleteGraph:k}),[Ne,we]=l.useState(""),[Se,me]=l.useState(""),q=g.meshHostDaemonSection&&Ne||w,{meshQueue:W,loadQueue:X}=WD({primaryDaemonId:w,activeDaemonId:q,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:f}),{setNodeProviderPriorityDrafts:K,selectedNodeId:ue,setSelectedNodeId:Pe,showAddNode:ce,setShowAddNode:F,nodeWorkspace:pe,setNodeWorkspace:xe,nodeProviderPriority:U,setNodeProviderPriority:be,nodeDaemonId:je,setNodeDaemonId:ge,nodeCustomPath:Ie,setNodeCustomPath:et,nodePickerWorkspaces:Ze,nodePickerProviders:rt,coordinatorCliType:he,setCoordinatorCliType:Ee,launchingCoordinator:Be,launchResult:at,savingPolicy:oe,coordinatorPromptDraft:He,setCoordinatorPromptDraft:lt,savingCoordinatorPrompt:ut,nodeSystemPromptDrafts:St,setNodeSystemPromptDrafts:V,savingNodeSystemPromptId:ee,savingNodeSlotsId:re,savingNodeCapabilitiesId:fe,handleAddNode:ve,handleRemoveNode:De,handleUpdatePolicy:_e,handleUpdateNodeSlots:Te,handleUpdateNodeCapabilities:qe,handleSaveCoordinatorPrompt:Xe,handleSaveNodeSystemPrompt:Ve,handleLaunchCoordinator:Fe}=FD({selectedMesh:Z,selectedMeshId:y,primaryDaemonId:w,activeDaemonId:q,daemons:r,availableCliProviders:j,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:f,launchCoordinator:i,features:{addNodeDaemonPicker:g.addNodeDaemonPicker},loadMeshes:z,loadQueue:X,queueSection:g.queueSection,setError:A}),Ue=l.useMemo(()=>r.find(Le=>Le.id===q)||v,[r,q,v]),Qe=l.useMemo(()=>new Set(((Z==null?void 0:Z.nodes)||[]).map(Le=>String(Le.daemon_id||Le.daemonId||""))),[Z]),$e=l.useMemo(()=>r.filter(Le=>Le.id&&!Qe.has(Le.id)),[r,Qe]),ae=(Z==null?void 0:Z.nodes)||[],ye=l.useMemo(()=>ae.find(Le=>Qs(String(Le.daemon_id||Le.daemonId||""),Ne)),[ae,Ne]),ke=g.meshHostDaemonSection?!!ye:!0,Re=l.useMemo(()=>{if(!g.meshHostDaemonSection||!Z)return{pinned:!1,daemonId:"",label:"",online:!1};const Le=Z.meshHost,tt=de!=null&&de.meshId&&String(de.meshId)===String(Z.id??"")?de.meshHost:void 0,Pt=tt!=null&&tt.hostDaemonId?tt:Le??tt,Qt=String((Pt==null?void 0:Pt.hostDaemonId)||""),zt=ae.find(Kt=>Kt.role==="host"),os=String((Pt==null?void 0:Pt.hostNodeId)||(zt==null?void 0:zt.id)||""),Dt=os?ae.find(Kt=>String(Kt.id)===os):void 0,xs=String((Dt==null?void 0:Dt.daemon_id)||(Dt==null?void 0:Dt.daemonId)||""),vs=Qt||xs;if(!vs)return{pinned:!1,daemonId:"",label:"",online:!1};const is=r.find(Kt=>Qt&&Qs(Kt.id,Qt))||(xs?r.find(Kt=>Qs(Kt.id,xs)):void 0);if(is)return{pinned:!0,daemonId:is.id,label:JD(is),online:!0};const Ls=String((Dt==null?void 0:Dt.machineLabel)||"")||String((Dt==null?void 0:Dt.workspace)||"")||vs;return{pinned:!0,daemonId:vs,label:Ls,online:!1}},[Z,ae,r,de,g.meshHostDaemonSection]),Ge=Re.daemonId,ot=Re.online,Oe=l.useMemo(()=>!g.meshHostDaemonSection||!Re.pinned?"":!ot&&Se&&r.some(Le=>Le.id===Se)?Se:Ge,[g.meshHostDaemonSection,Re.pinned,ot,Se,r,Ge]),bt=l.useMemo(()=>de?[...new Set((de.nodes??[]).map(Le=>String(Le.daemonId||Le.daemon_id||"")).filter(Boolean))]:[],[de]),qt=bh({status:de,daemonId:q||null,extraDaemonIds:bt,meshId:y,sendData:n});l.useEffect(()=>{K(Object.fromEntries(((Z==null?void 0:Z.nodes)||[]).map(Le=>[Le.id,QD(Le)])))},[Z]),l.useEffect(()=>{const Le=(Z==null?void 0:Z.coordinator)||{};lt({override:typeof Le.systemPromptOverride=="string"?Le.systemPromptOverride:"",append:typeof Le.systemPromptAppend=="string"?Le.systemPromptAppend:typeof Le.systemPromptSuffix=="string"?Le.systemPromptSuffix:""}),V(Object.fromEntries(((Z==null?void 0:Z.nodes)||[]).map(tt=>[tt.id,typeof tt.systemPrompt=="string"?tt.systemPrompt:""])))},[Z]),l.useEffect(()=>{const Le=g.addNodeDaemonPicker?yr(rt):yr(j);ce&&U.length===0&&Le.length>0&&be(Le)},[ce,j,rt,U.length,g.addNodeDaemonPicker]),l.useEffect(()=>{const Le=new Set(((Z==null?void 0:Z.nodes)||[]).map(tt=>tt.id));ue&&!Le.has(ue)&&Pe(null)},[Z,ue]);const Gt=l.useMemo(()=>{var Le;if(!(!(de!=null&&de.meshId)||String(de.meshId)!==String((Z==null?void 0:Z.id)??"")))return(Le=de.meshHost)==null?void 0:Le.hostDaemonId},[de,Z]),Zt=l.useMemo(()=>zD(r,ae,q,w,Gt),[r,ae,q,w,Gt]);l.useEffect(()=>{if(!g.meshHostDaemonSection)return;if(!r.length&&!Re.pinned){we("");return}const Le=Re.pinned?Oe:Zt;Le&&!Qs(Le,Ne)&&we(Le)},[r,Ne,Re.pinned,Oe,Zt,g.meshHostDaemonSection]),l.useEffect(()=>{Se&&(ot||!r.some(Le=>Le.id===Se))&&me("")},[ot,Se,r]),l.useEffect(()=>{if(g.createDaemonPicker){if(!r.length){E("");return}(!O||!r.some(Le=>Le.id===O))&&E(r[0].id)}},[r,O,g.createDaemonPicker]),l.useEffect(()=>{var Le;if(!g.createDaemonPicker||!O){$("");return}if(!R.length){$("");return}R.some(tt=>tt.path===M)||$(((Le=R[0])==null?void 0:Le.path)||"")},[O,M,R,g.createDaemonPicker]);const Jt=l.useRef(null);l.useEffect(()=>{if(!y)return;const Le=Jt.current!==y;if(Jt.current=y,Le){const tt=Ch(y);te(tt),Y(null),le(q,y,tt!==null)}else Y(null),le(q,y,!0)},[y,q]);const Is=l.useRef(le);Is.current=le;const Ae=l.useRef(!1),Ye=l.useRef(()=>{});Ye.current=()=>{Ae.current||!y||!q||(Ae.current=!0,Promise.resolve(Is.current(q,y,!0)).finally(()=>{Ae.current=!1}))};const Mt=g.meshStatePushRefresh?VD:KD;$P({daemonIds:l.useMemo(()=>[q,...bt].filter(Boolean),[q,bt]),meshId:y,sendData:n,onRevisionAdvance:()=>{typeof document<"u"&&document.visibilityState!=="visible"||Ye.current()}}),l.useEffect(()=>{if(!y||!q||typeof document>"u")return;let Le=null;const tt=()=>{document.visibilityState==="visible"&&Ye.current()},Pt=()=>{Le===null&&(Le=setInterval(tt,Mt))},Qt=()=>{Le!==null&&(clearInterval(Le),Le=null)},zt=()=>{document.visibilityState==="visible"?Pt():Qt()};return document.visibilityState==="visible"&&Pt(),document.addEventListener("visibilitychange",zt),()=>{Qt(),document.removeEventListener("visibilitychange",zt)}},[y,q,Mt]),l.useEffect(()=>{g.queueSection||X(y)},[y,g.queueSection]);const ct=l.useMemo(()=>r.map(Le=>Le.id).filter(Boolean).sort().join(","),[r]),es=l.useRef(!1);return l.useEffect(()=>{z(es.current),es.current=!0},[ct]),w?Z?s.jsx($D,{selectedMesh:Z,error:S,onDismissError:()=>A(null),onBack:()=>{x(null),te(null)},onDelete:ne,displayedMeshStatus:qt,graphLoading:B,graphError:ie,onRefreshGraph:()=>le(q,y,!0),savingPolicy:oe,onUpdatePolicy:_e,coordinatorPromptDraft:He,onCoordinatorPromptDraftChange:lt,savingCoordinatorPrompt:ut,onSaveCoordinatorPrompt:Xe,daemons:r,coordinatorDaemonId:Ne,onCoordinatorDaemonIdChange:we,coordinatorCliType:he,onCoordinatorCliTypeChange:Ee,launchingCoordinator:Be,launchResult:at,isHostNodeAttached:ke,selectedHostNode:ye,hostPinned:Re.pinned,hostLabel:Re.label,hostOnline:ot,hostRebindDaemonId:Se,onHostRebindDaemonIdChange:Le=>me(Le),onLaunchCoordinator:Fe,activeDaemon:Ue,activeDaemonId:q,meshQueue:W,userName:a,availableCliProviders:j,savingNodeSlotsId:re,onUpdateNodeSlots:Te,savingNodeCapabilitiesId:fe,onUpdateNodeCapabilities:qe,nodeSystemPromptDrafts:St,onNodeSystemPromptDraftChange:(Le,tt)=>V(Pt=>({...Pt,[Le]:tt})),savingNodeSystemPromptId:ee,onSaveNodeSystemPrompt:Ve,selectedNodeId:ue,onSelectNode:Pe,showAddNode:ce,onShowAddNode:()=>F(!0),onCancelAddNode:()=>F(!1),nodeWorkspace:pe,onNodeWorkspaceChange:xe,nodeProviderPriority:U,onNodeProviderPriorityChange:be,nodeDaemonId:je,onNodeDaemonIdChange:ge,nodeCustomPath:Ie,onNodeCustomPathChange:et,nodePickerWorkspaces:Ze,nodePickerProviders:rt,attachableDaemons:$e,onAddNode:ve,onRemoveNode:De,availableCliAgents:b,features:{coordinatorPrompt:g.coordinatorPrompt,meshHostDaemonSection:g.meshHostDaemonSection,hermesMcpConfig:g.hermesMcpConfig,addNodeDaemonPicker:g.addNodeDaemonPicker,nodeInstruction:g.nodeInstruction},sendCommand:t}):s.jsx(zP,{meshes:C,loading:N,error:S,onDismissError:()=>A(null),daemons:r,features:{createDaemonPicker:g.createDaemonPicker,maxMeshes:g.maxMeshes},showCreate:T,onToggleCreate:()=>I(!T),createName:D,onCreateNameChange:P,createRepoIdentity:_,onCreateRepoIdentityChange:G,createRepoRemoteUrl:H,onCreateRepoRemoteUrlChange:L,newMeshDaemonId:O,onNewMeshDaemonIdChange:E,newMeshWorkspace:M,onNewMeshWorkspaceChange:$,createPickerWorkspaces:R,onSelectMesh:x,onCreate:Q,onCancelCreate:J}):s.jsx(Tr,{icon:s.jsx(rs,{}),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 JD(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function QD(e){var r;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>n.has(a)?!1:(n.add(a),!0))}function XD({children:e}){const{sendCommand:t,sendData:n}=wt(),{ides:r}=js(),a=l.useMemo(()=>r.filter(i=>i.daemonMode||i.type==="adhdev-daemon").map(i=>i),[r]),o=l.useMemo(()=>({sendCommand:t,sendData:n,daemons:a,userName:void 0,loadMeshStatus:async(i,c)=>t(i,"mesh_status",{meshId:c}),launchCoordinator:async(i,c)=>{var f;const d={meshId:c.meshId};c.cliType&&(d.cliType=c.cliType);const p=await t(i,"launch_mesh_coordinator",d),u=(p==null?void 0:p.result)??p;if((u==null?void 0:u.success)===!1)throw new Error(u.error||"Coordinator launch failed");const m=(u==null?void 0:u.sessionId)||((f=u==null?void 0:u.session)==null?void 0:f.id)||(u==null?void 0:u.targetSessionId);return{sessionId:m,message:m?`Coordinator launched (${m})`:"Coordinator launch command sent"}},loadLiveMesh:void 0,extractStatus:el,unwrapResult:i=>i,normalizeMesh:(i,c)=>i,normalizeNode:(i,c,d)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:HP}),[t,n,a]);return s.jsx(kh.Provider,{value:o,children:e})}function Dl(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function ZD(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=Dl();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 ks(e,t){return await fetch(ZD(e),{credentials:"same-origin",...t})}function jh(){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 eI{constructor(){st(this,"adapters",new Map);st(this,"states",new Map);st(this,"runtimeListeners",new Map);st(this,"screenshotCallbacks",new Map);st(this,"statusCallbacks",new Set);st(this,"stateChangeCallbacks",new Set);st(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 r=this.resolveDaemonId(t)||t;this.stateChangeCallbacks.forEach(a=>a(r,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,r){return this.ptyInputSender?this.ptyInputSender(t,n,r):!1}onScreenshot(t,n){return this.screenshotCallbacks.set(t,n),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,n){this.screenshotCallbacks.forEach(r=>r(t,n))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,n){this.statusCallbacks.forEach(r=>r(t,n))}emitRuntimeSnapshot(t,n,r=0,a=!1,o,i){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:r,text:n,truncated:a,cols:o,rows:i})}emitSessionOutput(t,n,r){!t||typeof n!="string"||!n||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof r=="number"?{seq:r}:{},data:n})}onRuntimeEvent(t,n){const r=this.runtimeListeners.get(t)||new Set;return r.add(n),this.runtimeListeners.set(t,r),()=>{const a=this.runtimeListeners.get(t);a&&(a.delete(n),a.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,n,r){if(!n)return{success:!1,error:"sessionId is required"};const a=new URL(`/api/v1/runtime/${encodeURIComponent(n)}/snapshot`,window.location.origin);typeof(r==null?void 0:r.sinceSeq)=="number"&&a.searchParams.set("sinceSeq",String(r.sinceSeq));const o=await ks(`${a.pathname}${a.search}`);if(!o.ok){let c=`Runtime snapshot unavailable (${o.status})`;try{const d=await o.json();d!=null&&d.error&&(c=d.error)}catch{}return{success:!1,error:c}}const i=await o.json();return this.emitRuntimeEvent(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:!!(r!=null&&r.force)}),{success:!0}}emitRuntimeEvent(t,n){var r;(r=this.runtimeListeners.get(t))==null||r.forEach(a=>a(n))}}const ws=new eI;function tI(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,n=Dl();return n?`${t}?token=${encodeURIComponent(n)}`:t}const ea=tI(),Yd=3e3,sI=3e4;let ds=null,nI=0;const La=new Map;let Vs=null,mr=null;function Jd(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function tr(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function rI(e){return e==="connected"?"connected":e}async function hr(e,t,n){const r=qp(e,n||{}),a=ds;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++nI}_${Date.now()}`;return new Promise((i,c)=>{const d=setTimeout(()=>{La.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);La.set(o,{resolve:p=>{clearTimeout(d),i(p)},reject:p=>{clearTimeout(d),c(p)}}),a.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:r.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function Li(e,t){const n=ds;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 Nh(e,t,n){const r=ds;if(!r||r.readyState!==WebSocket.OPEN)return!1;const a=qp(e,{sessionId:t,targetSessionId:t,data:n});try{return r.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:a.payload}})),!0}catch{return!1}}ws.registerPtyInputSender(Nh);class aI{constructor(t){st(this,"daemonId");st(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(ds==null?void 0:ds.readyState)===WebSocket.OPEN}get connectionState(){return(ds==null?void 0:ds.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,n){return hr(this.daemonId,t,n)}async sendInput(t,n){return hr(this.daemonId,"cdp_remote_action",{action:t,params:n,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,Vs&&(clearInterval(Vs),Vs=null);const n=async()=>{if(this.hasCommandChannel)try{const r=await hr(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(r!=null&&r.success&&(r!=null&&r.base64)){const a=await fetch(`data:image/jpeg;base64,${r.base64}`).then(o=>o.blob());ws.emitScreenshot(this.daemonId,a)}}catch{}};n(),Vs=setInterval(n,2e3)}stopScreenshots(t){Vs&&(clearInterval(Vs),Vs=null)}}let ss=null;function oI(e){return(!ss||ss.daemonId!==e)&&(ss=new aI(e)),ss}function iI({children:e}){const t=l.useRef(fr()),n=fr();t.current=n;const{setUserName:r}=js(),a=l.useRef(r);a.current=r;const o=l.useRef(null),i=l.useRef(null),[,c]=l.useState("disconnected"),d=l.useCallback((h,v)=>{c(h),mr==null||mr(h,v)},[]),p=l.useRef(null),u=l.useRef(),m=l.useRef(Yd),f=l.useRef(!0),g=l.useRef(!1),k=l.useRef("initial_connect");return l.useEffect(()=>{f.current=!0,g.current=!1;function h(){var b,j;if(!f.current||((b=p.current)==null?void 0:b.readyState)===WebSocket.OPEN||((j=p.current)==null?void 0:j.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${ea}...`),tr("connect_attempt",{url:ea,reason:k.current,delayMs:m.current});let w;try{w=new WebSocket(ea)}catch(C){console.error("[Standalone WS] Failed to create WebSocket:",C),v();return}p.current=w,w.onopen=()=>{if(!f.current){w.close();return}d("connected"),m.current=Yd,tr("open",{url:ea,reason:k.current}),hs.resubscribeAll({sendData:Li}),console.log("[Standalone WS] Connected")},ds=w,w.onmessage=C=>{var y,x;try{const N=JSON.parse(C.data);if((N.type==="command_result"||N.type==="error")&&N.requestId){const S=La.get(N.requestId);S&&(La.delete(N.requestId),N.type==="error"?S.reject(new Error(((y=N.data)==null?void 0:y.message)||"Command failed")):S.resolve(N.data));return}if(N.type==="session_output"){const S=N.sessionId||N.cliId||N.cliType;S&&ws.emitSessionOutput(S,typeof N.data=="string"?N.data:"",typeof N.seq=="number"?N.seq:void 0);return}if(N.type==="runtime_snapshot"){ws.emitRuntimeSnapshot(N.sessionId,typeof N.text=="string"?N.text:"",typeof N.seq=="number"?N.seq:0,!!N.truncated,typeof N.cols=="number"?N.cols:void 0,typeof N.rows=="number"?N.rows:void 0);return}if(N.type==="topic_update"){const S=N.update;S&&hs.publish(S);return}if(N.type==="status"||N.type==="initial_state"){const S=N.data;if(!S)return;const{injectEntries:A,markLoaded:T,getIdes:I}=t.current,D=S.instanceId||"standalone",P=I().find(H=>H.id===D),_=oI(D);ws.register(D,_),ws.setState(D,"connected"),d("connected",D),ws.emitStatus(D,S);const G=va(S,{daemonId:D,existingDaemon:P,existingEntries:I()});Jd("ws_status",{type:N.type,daemonId:D,sessions:(S.sessions||[]).map(H=>({id:H.id,parentId:H.parentId,providerType:H.providerType,kind:H.kind,transport:H.transport,unread:H.unread,inboxBucket:H.inboxBucket,lastSeenAt:H.lastSeenAt,lastUpdated:H.lastUpdated,title:H.title})),recentLaunches:(S.recentLaunches||[]).map(H=>({id:H.id,providerType:H.providerType,kind:H.kind,workspace:H.workspace,lastLaunchedAt:H.lastLaunchedAt}))}),Jd("entries",{daemonId:D,entries:G.filter(H=>H.type!=="adhdev-daemon").map(H=>({id:H.id,type:H.type,unread:H.unread,inboxBucket:H.inboxBucket,lastSeenAt:H.lastSeenAt,lastUpdated:H.lastUpdated,sessionId:H.sessionId}))}),G.length>0&&A(G,{authoritativeDaemonIds:[D]}),T(),i.current!==D&&((x=o.current)==null||x.call(o),i.current=D,o.current=hs.subscribe({sendData:Li},D,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${D}`,params:{includeSessions:!0}},H=>{if(H.topic!=="daemon.metadata")return;const L=t.current.getIdes(),O=L.find(M=>M.id===D),E=va(H.status,{daemonId:D,existingDaemon:O,existingEntries:L,timestamp:H.timestamp});E.length>0&&t.current.injectEntries(E,{authoritativeDaemonIds:[D]}),H.userName&&a.current&&a.current(H.userName)}))}}catch(N){console.error("[Standalone WS] Parse error:",N)}},w.onclose=C=>{f.current&&(ss==null||ss.stopScreenshots(),ss&&ws.setState(ss.daemonId,"disconnected"),d("disconnected"),p.current=null,k.current=`close:${C.code}${C.wasClean?":clean":":unclean"}`,tr("close",{code:C.code,reason:C.reason||"",wasClean:C.wasClean}),v())},w.onerror=C=>{g.current||!f.current||(k.current="error",tr("error",{message:C instanceof Event?"event":String(C),readyState:w.readyState}),console.warn("[Standalone WS] Error, will reconnect:",C))}}function v(){if(!f.current)return;clearTimeout(u.current);const w=m.current;console.log(`[Standalone WS] Reconnecting in ${w}ms...`),tr("schedule_reconnect",{reason:k.current,delayMs:w}),u.current=setTimeout(()=>{m.current=Math.min(m.current*1.5,sI),h()},w)}return h(),()=>{var w;f.current=!1,g.current=!0,(w=o.current)==null||w.call(o),o.current=null,i.current=null,clearTimeout(u.current),p.current&&(p.current.onerror=null,p.current.onclose=null,p.current.close(),p.current=null,ds=null),ss&&(ss.stopScreenshots(),ws.unregister(ss.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function lI({children:e}){const[t,n]=l.useState("disconnected"),[r,a]=l.useState(null);l.useEffect(()=>(mr=(i,c)=>{n(i),c&&a(c)},()=>{mr=null}),[]);const o=l.useMemo(()=>{const i=t==="connected",c=rI(t),d={};return r&&(d[r]=c),d.standalone=c,{wsStatus:t,isConnected:i,connectionStates:d}},[t,r]);return s.jsx(kf,{connectionOverrides:o,children:s.jsx(iI,{children:e})})}const Ah="adhdev_standalone_font_preferences",rn={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Za=[{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"}],Sr=[{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"}],cI=new Set(Za.map(e=>e.id)),dI=new Set(Sr.map(e=>e.id));function Ss(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:pa("chat",t.chat),code:pa("code",t.code),terminal:pa("terminal",t.terminal)}}function pa(e,t){const n=rn[e],r=t&&typeof t=="object"&&!Array.isArray(t)?t:{},a=typeof r.preset=="string"?r.preset.trim():"",o=typeof r.customFamily=="string"?r.customFamily.trim():"";return(e==="chat"?cI:dI).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:n:{preset:a}:n}function ma(e,t){var a;const n=pa(e,t);if(n.preset==="custom"&&n.customFamily)return n.customFamily;const r=e==="chat"?Za:Sr;return((a=r.find(o=>o.id===n.preset))==null?void 0:a.family)||r[0].family}function uI(e){const t=Ss(e),n=ma("chat",t.chat),r=ma("code",t.code),a=ma("terminal",t.terminal);return{"--chat-font-family":n,"--chat-code-font-family":r,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function Js(e,t=document.documentElement){const n=Ss(e),r=uI(n);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(r))t.style.setProperty(a,o);return n}function Ri(e){const t=Ss(e);try{localStorage.setItem(Ah,JSON.stringify(t))}catch{}return t}function pI(){try{const e=localStorage.getItem(Ah);if(e)return Ss(JSON.parse(e))}catch{}return rn}function mI(){return Js(pI())}function sr(e,t){var r;const n=e==="chat"?Za:Sr;return((r=n.find(a=>a.id===t))==null?void 0:r.label)||n[0].label}function hI({children:e}){const t=Cr(),n=_i(),{t:r}=Ce("common"),a=l.useMemo(()=>[{id:"dashboard",path:"/dashboard",icon:s.jsx(uu,{}),label:r("standalone.nav.dashboard"),active:n.pathname.startsWith("/dashboard"),onSelect:()=>t("/dashboard")},{id:"machine",path:"/machines",icon:s.jsx(Fs,{}),label:"Burrow",active:n.pathname.startsWith("/machines"),onSelect:()=>t("/machines")},{id:"mesh",path:"/mesh",icon:s.jsx(rs,{}),label:"Mesh",active:n.pathname.startsWith("/mesh"),onSelect:()=>t("/mesh")},{id:"settings",path:"/settings",icon:s.jsx(Ea,{}),label:r("standalone.nav.settings"),active:n.pathname.startsWith("/settings"),onSelect:()=>t("/settings")}],[n.pathname,t,r]),o=l.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:r("standalone.nav.docs")}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(mu,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:r("standalone.nav.docs")},{id:"about",label:r("standalone.nav.about"),icon:s.jsx(Bi,{}),active:n.pathname==="/about",onSelect:()=>t("/about"),title:r("standalone.nav.about")}],[n.pathname,t,r]);return s.jsx(XS,{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:a,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.26"]}),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:r(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:r("standalone.layout.collapse")})]}),children:e})}const fI=[{icon:s.jsx(Fs,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(un,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(bu,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(gs,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(br,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(mu,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],bI=[{icon:s.jsx(Xf,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(uu,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Hn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(zf,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(pu,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Vf,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],gI=[{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 xI(){const{t:e}=Ce("common");return s.jsxs(Tr,{icon:s.jsx(Bi,{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.26"]}),children:[s.jsx(ft,{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(ft,{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:fI.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(ft,{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:zp.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:Vp.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:Kp.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(ft,{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:bI.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(ft,{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:gI.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(za,{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(ib,{size:14,className:"mr-1"}),e("standalone.about.discord")]})]})})]})}function Jo(e,t,n){return{...e,[t]:n}}function Qo({surface:e,title:t,description:n,value:r,options:a,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(sC,{value:r.preset,onChange:c=>{const d=c.target.value;o(d==="custom"?{preset:"custom",customFamily:r.customFamily||""}:{preset:d})},children:a.map(c=>s.jsx("option",{value:c.id,children:c.label},c.id))}),r.preset==="custom"&&s.jsx(ms,{type:"text",className:"font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:r.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:ma(e,r)})]})]})]})}function vI({value:e,savedValue:t,saving:n=!1,error:r,notice:a,onChange:o,onSave:i,onResetToSaved:c,onResetToDefaults:d}){const{t:p}=Ce("common"),u=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:p("standalone.fonts.fontOverridesNotice")}),r&&s.jsx(Ft,{variant:"error",children:r}),a&&s.jsx(Ft,{variant:"success",children:a}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(Qo,{surface:"chat",title:p("standalone.fonts.chat"),description:p("standalone.fonts.chatDescription"),value:e.chat,options:Za,onChange:m=>o(Jo(e,"chat",m))}),s.jsx(Qo,{surface:"code",title:p("standalone.fonts.code"),description:p("standalone.fonts.codeDescription"),value:e.code,options:Sr,onChange:m=>o(Jo(e,"code",m))}),s.jsx(Qo,{surface:"terminal",title:p("standalone.fonts.terminal"),description:p("standalone.fonts.terminalDescription"),value:e.terminal,options:Sr,onChange:m=>o(Jo(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: ",sr("chat",e.chat.preset)," · Code: ",sr("code",e.code.preset)," · Terminal: ",sr("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[p("standalone.fonts.defaults")," ",sr("chat",rn.chat.preset)," / ",sr("code",rn.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(Ts,{type:"button",variant:"primary",size:"sm",onClick:i,disabled:n||!u,children:p(n?"standalone.fonts.saving":"standalone.fonts.saveFontSettings")}),s.jsx(Ts,{type:"button",variant:"secondary",size:"sm",onClick:c,disabled:n||!u,children:p("standalone.fonts.revertToSaved")}),s.jsx(Ts,{type:"button",variant:"secondary",size:"sm",onClick:d,disabled:n,children:p("standalone.fonts.resetToDefaults")})]})]})}function yI(){const{t:e}=Ce("common"),{ides:t}=js(),n=t.find(B=>B.type==="adhdev-daemon"),r=(n==null?void 0:n.detectedIdes)||[],{sendCommand:a}=wt(),{userName:o}=js(),[i,c]=l.useState(o||""),[d,p]=l.useState(null),[u,m]=l.useState(null),[f,g]=l.useState(rn),[k,h]=l.useState(!1),[v,w]=l.useState(""),[b,j]=l.useState(""),[C,y]=l.useState("127.0.0.1"),[x,N]=l.useState(""),[S,A]=l.useState(""),[T,I]=l.useState(""),[D,P]=l.useState(""),[_,G]=l.useState(""),[H,L]=l.useState(!1),O=async()=>{const ie=await(await ks("/auth/session")).json();p(ie)},E=async()=>{const ie=await(await ks("/api/v1/standalone/preferences")).json();m(ie),y(ie.standaloneBindHost);const Y=Ss(ie.standaloneFontPreferences);g(Y),Js(Y),Ri(Y)};l.useEffect(()=>{o!==void 0&&c(o)},[o]),l.useEffect(()=>{Promise.all([O(),E()]).catch(B=>{P(B instanceof Error?B.message:String(B))})},[]),l.useEffect(()=>{Js(f)},[f]);const M=B=>{const ie=B.target.value.trim();n!=null&&n.id&&ie!==o&&a(n.id,"set_user_name",{userName:ie}).catch(console.error)},[$,R]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),z=B=>{R(B);try{localStorage.setItem("adhdev_sound",B?"1":"0")}catch{}},Q=async()=>{w(""),j(""),h(!0);try{const B=Ss(f),ie=await ks("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:B})}),Y=await ie.json();if(!ie.ok)throw new Error((Y==null?void 0:Y.error)||"Failed to save standalone font preferences");const le=Ss(Y.standaloneFontPreferences);m(Y),g(le),Js(le),Ri(le),j(e("standalone.settings.fontsSaved"))}catch(B){w(B instanceof Error?B.message:String(B))}finally{h(!1)}},ne=()=>{const B=Ss(u==null?void 0:u.standaloneFontPreferences);w(""),j(""),g(B),Js(B)},J=()=>{w(""),j(""),g(rn),Js(rn)},Z=async()=>{P(""),G(""),L(!0);try{const B=await ks("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:C})}),ie=await B.json();if(!B.ok)throw new Error((ie==null?void 0:ie.error)||"Failed to save standalone network preference");m(ie),y(ie.standaloneBindHost),G(ie.standaloneBindHost==="0.0.0.0"?e("standalone.settings.networkSavedAll"):e("standalone.settings.networkSavedLocal"))}catch(B){P(B instanceof Error?B.message:String(B))}finally{L(!1)}},de=async()=>{if(P(""),G(""),S.trim().length<4){P(e("standalone.settings.passwordTooShort"));return}if(S!==T){P(e("standalone.settings.passwordMismatch"));return}L(!0);try{const B=await ks("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:x,newPassword:S})}),ie=await B.json();if(!B.ok)throw new Error((ie==null?void 0:ie.error)||"Failed to save password");p(ie),await E(),N(""),A(""),I(""),G(d!=null&&d.hasPasswordAuth?e("standalone.settings.passwordUpdated"):e("standalone.settings.passwordEnabled")),jh()}catch(B){P(B instanceof Error?B.message:String(B))}finally{L(!1)}},te=async()=>{P(""),G(""),L(!0);try{const B=await ks("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:x,clear:!0})}),ie=await B.json();if(!B.ok)throw new Error((ie==null?void 0:ie.error)||"Failed to clear password");p(ie),await E(),N(""),A(""),I(""),G(e("standalone.settings.passwordDisabled"))}catch(B){P(B instanceof Error?B.message:String(B))}finally{L(!1)}};return s.jsxs(Tr,{icon:s.jsx(Ea,{className:"text-text-primary"}),title:e("standalone.settings.title"),subtitle:e("standalone.settings.subtitle"),widthClassName:"max-w-5xl",children:[s.jsx(Ft,{variant:"info",children:e("standalone.settings.infoNotice")}),(d==null?void 0:d.publicHostWarning)&&s.jsx(Ft,{variant:"warning",children:e("standalone.settings.publicHostWarning")}),s.jsx(ft,{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.26"]}),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:(u==null?void 0:u.currentBindHost)||(d==null?void 0:d.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:(u==null?void 0:u.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.authLabel")}),s.jsx("span",{className:"text-xs",children:d!=null&&d.hasPasswordAuth?e("standalone.settings.authPassword"):d!=null&&d.hasTokenAuth?e("standalone.settings.authToken"):e("standalone.settings.authNone")})]})}),s.jsx(ft,{title:e("standalone.settings.networkSection"),description:e("standalone.settings.networkDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:e("standalone.settings.networkHint")}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:C==="127.0.0.1",onChange:()=>y("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:e("standalone.settings.localhostLabel")}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:e("standalone.settings.localhostHint")})]})]}),s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:C==="0.0.0.0",onChange:()=>y("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(Ts,{type:"button",variant:"primary",size:"sm",onClick:()=>{Z()},disabled:H,children:e(H?"standalone.settings.saving":"standalone.settings.saveNetworkMode")}),s.jsx("span",{className:"text-xs text-text-muted",children:e("standalone.settings.networkRestartHint",{host:(u==null?void 0:u.currentBindHost)||(d==null?void 0:d.boundHost)||"127.0.0.1"})})]})]})}),s.jsx(ft,{title:e("standalone.settings.securitySection"),description:e("standalone.settings.securityDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:d!=null&&d.hasPasswordAuth?e("standalone.settings.passwordSet"):e("standalone.settings.passwordNotSet")}),D&&s.jsx(Ft,{variant:"error",children:D}),_&&s.jsx(Ft,{variant:"success",children:_}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx(ms,{type:"password",placeholder:d!=null&&d.hasPasswordAuth?e("standalone.settings.currentPasswordPlaceholder"):e("standalone.settings.currentPasswordFirstTimePlaceholder"),value:x,onChange:B=>N(B.target.value)}),s.jsx(ms,{type:"password",placeholder:d!=null&&d.hasPasswordAuth?e("standalone.settings.newPasswordPlaceholder"):e("standalone.settings.newPasswordFirstTimePlaceholder"),value:S,onChange:B=>A(B.target.value)}),s.jsx(ms,{type:"password",className:"md:col-span-2",placeholder:e("standalone.settings.confirmPasswordPlaceholder"),value:T,onChange:B=>I(B.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ts,{type:"button",variant:"primary",size:"sm",onClick:()=>{de()},disabled:H,children:H?e("standalone.settings.saving"):d!=null&&d.hasPasswordAuth?e("standalone.settings.updatePassword"):e("standalone.settings.enablePassword")}),(d==null?void 0:d.hasPasswordAuth)&&s.jsx(Ts,{type:"button",variant:"danger",size:"sm",onClick:()=>{te()},disabled:H,children:e("standalone.settings.disablePassword")})]})]})}),s.jsx(ft,{title:e("standalone.settings.detectedIdesSection"),description:e("standalone.settings.detectedIdesDescription"),children:r.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:r.map(B=>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 ${B.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:B.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:B.type})]},B.type))})}),s.jsx(ft,{title:e("standalone.settings.machineSection"),description:e("standalone.settings.machineDescription"),children:s.jsx(dC,{ides:t,emptyMessage:e("standalone.settings.daemonNotConnected")})}),s.jsx(ft,{title:e("standalone.settings.appearanceSection"),description:e("standalone.settings.appearanceDescription"),children:s.jsx(PC,{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(vI,{value:f,savedValue:Ss(u==null?void 0:u.standaloneFontPreferences),saving:k,error:v,notice:b,onChange:g,onSave:()=>{Q()},onResetToSaved:ne,onResetToDefaults:J})]})})}),s.jsx(ft,{title:e("standalone.settings.notificationsSection"),description:e("standalone.settings.notificationsDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(oC,{}),s.jsx(Ys,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ob,{size:15})," ",e("standalone.settings.soundEffectsLabel")]}),description:e("standalone.settings.soundEffectsDescription"),checked:$,onChange:z})]})}),s.jsx(ft,{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(qf,{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(ms,{type:"text",className:"w-48 text-right",placeholder:e("standalone.settings.displayNamePlaceholder"),value:i,onChange:B=>c(B.target.value),onBlur:M,onKeyDown:B=>{B.key==="Enter"&&B.currentTarget.blur()}})]})})})]})}const wI=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],ar="adhdev_onboarding_done",kI=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],SI={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function CI({onDone:e}){const{t}=Ce("common"),[n,r]=l.useState([]),[a,o]=l.useState(new Set(wI)),[i,c]=l.useState(!0),[d,p]=l.useState(null),[u,m]=l.useState(!1),[f,g]=l.useState(null),[k,h]=l.useState("all");l.useEffect(()=>{let x=!1;const N=window.location.hostname==="localhost"?"/registry":"https://api.adhf.dev/api/v1/registry";return fetch(`${N}/providers?sort=popular&limit=100`).then(S=>{if(!S.ok)throw new Error(`HTTP ${S.status}`);return S.json()}).then(S=>{x||r(S.providers??[])}).catch(S=>{x||p(S instanceof Error?S.message:String(S))}).finally(()=>{x||c(!1)}),()=>{x=!0}},[]);const v=n.filter(x=>k==="all"||x.category===k),w=["cli","ide","extension","acp"].map(x=>({category:x,items:v.filter(N=>N.category===x)})).filter(x=>x.items.length>0),b=l.useCallback(x=>{o(N=>{const S=new Set(N);return S.has(x)?S.delete(x):S.add(x),S})},[]),j=l.useCallback(async()=>{if(a.size===0){localStorage.setItem(ar,"1"),e();return}m(!0);const x=[];for(const N of a)try{const A=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:N})})).json().catch(()=>({}));x.push({type:N,ok:!!A.success,error:A.error})}catch(S){x.push({type:N,ok:!1,error:S instanceof Error?S.message:String(S)})}g(x),m(!1),x.every(N=>N.ok)&&localStorage.setItem(ar,"1")},[a,e]),C=l.useCallback(()=>{localStorage.setItem(ar,"1"),e()},[e]),y=l.useCallback(()=>{f&&f.every(x=>x.ok)?e():u||C()},[f,u,e,C]);return s.jsx(Xu,{open:!0,onClose:y,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(a.size!==1?"standalone.onboarding.selectedCount_other":"standalone.onboarding.selectedCount_one",{count:a.size})}),s.jsxs("div",{className:"ml-auto flex gap-2",children:[s.jsx(Ts,{variant:"secondary",size:"sm",onClick:C,disabled:u,children:t("standalone.onboarding.skip")}),s.jsx(Ts,{variant:"primary",size:"sm",onClick:()=>{f?(localStorage.setItem(ar,"1"),e()):j()},disabled:u||!f&&a.size===0,children:u?t("standalone.onboarding.installing"):f?t("standalone.onboarding.done"):t("standalone.onboarding.installCount",{count:a.size})})]})]}),children:s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsx("div",{className:"text-[12px] text-text-muted",children:t("standalone.onboarding.intro")}),!i&&!d&&n.length>0&&s.jsx("div",{className:"flex gap-1 flex-wrap border-b border-border-subtle pb-2",children:kI.map(x=>{const N=x.key==="all"?n.length:n.filter(S=>S.category===x.key).length;return N===0&&x.key!=="all"?null:s.jsxs("button",{onClick:()=>h(x.key),className:`machine-btn text-[10px] px-2 py-0.5 ${k===x.key?"bg-accent-primary/12 border-accent-primary/40 text-accent-primary":""}`,children:[x.label," ",s.jsxs("span",{className:"opacity-60",children:["(",N,")"]})]},x.key)})}),i&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.loadingRegistry")}),!i&&d&&s.jsx(Ft,{variant:"error",children:t("standalone.onboarding.loadError",{error:d})}),!i&&!d&&v.length===0&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.noProviders")}),!i&&!d&&v.length>0&&s.jsx("div",{className:"flex flex-col gap-4",children:w.map(x=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:SI[x.category]??x.category}),s.jsx("div",{className:"grid gap-1.5",children:x.items.map(N=>{var D,P;const S=a.has(N.type),A=f==null?void 0:f.find(_=>_.type===N.type),T=((D=N.manifest)==null?void 0:D.icon)??"📦",I=((P=N.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(N.type),disabled:u,className:"shrink-0"}),s.jsx("span",{className:"text-base shrink-0",children:T}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[13px] font-medium text-text-primary truncate",children:N.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"})})]},N.type)})})]},x.category))})]})})}function jI(){try{return localStorage.getItem(ar)==="1"}catch{return!1}}OS();kC();Ty();mI();const NI=ru({baseUrl:"",getToken:Dl});function AI({children:e}){const{t}=Ce("common"),[n,r]=l.useState(null),[a,o]=l.useState(!0),[i,c]=l.useState(""),[d,p]=l.useState(""),[u,m]=l.useState(!1),f=async()=>{o(!0),p("");try{const h=await(await ks("/auth/session")).json();r(h)}catch(k){p(k instanceof Error?k.message:String(k))}finally{o(!1)}};l.useEffect(()=>{f()},[]),l.useEffect(()=>{if(!n||n.required&&!n.authenticated)return;let k=!1;return(async()=>{try{const h=await ks("/api/v1/standalone/preferences");if(!h.ok)return;const v=await h.json();if(k)return;const w=Ss(v.standaloneFontPreferences);Js(w),Ri(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 h=await ks("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),v=await h.json();if(!h.ok)throw new Error((v==null?void 0:v.error)||"Login failed");r(v),c(""),jh()}catch(h){p(h instanceof Error?h.message:String(h))}finally{m(!1)}};return a?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(ms,{type:"password",value:i,onChange:k=>c(k.target.value),placeholder:t("standalone.auth.passwordPlaceholder"),autoFocus:!0}),s.jsx(Ts,{type:"submit",variant:"primary",disabled:u||!i,className:"justify-center",children:t(u?"standalone.auth.signingIn":"standalone.auth.unlock")})]}):s.jsx(Ft,{variant:"warning",children:t("standalone.auth.noPasswordEnabled")}),d&&s.jsx(Ft,{variant:"error",children:d})]})}):s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:t("standalone.auth.loadError",{error:d||"unknown error"})})}function Qd(){const{t:e}=Ce("common"),{ides:t,initialLoaded:n}=js();if(!n)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:e("standalone.machine.loading")});const r=t.find(a=>a.daemonMode||a.type==="adhdev-daemon");return r?s.jsx(ti,{to:`/machines/${r.id}`,replace:!0}):s.jsx(ti,{to:"/dashboard",replace:!0})}function TI(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let n=!1;if(!jI())return fetch("/api/v1/providers/installed").then(r=>r.ok?r.json():{providers:[]}).then(r=>{n||(r.providers??[]).length===0&&t(!0)}).catch(()=>{}),()=>{n=!0}},[]),e?s.jsx(CI,{onDone:()=>t(!1)}):null}function MI(){const{t:e}=Ce("common"),{ides:t}=js(),n=l.useMemo(()=>{for(const u of t)if(u.activeInteractivePrompt)return u.instanceId??u.id;return null},[t]),{promptSession:r,hasActivePrompt:a,responseError:o,isSubmitting:i,submit:c,cancel:d,reopen:p}=tm(n);return a?s.jsxs("div",{className:"relative",children:[!r&&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(Pu,{promptSession:r,isSubmitting:i,error:o,onSubmit:c,onCancel:d})]}):null}function PI(){const e=l.useMemo(()=>({sendCommand:hr,sendData:Li,sendPtyInput:Nh}),[]);return s.jsx(rf,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(jf,{client:NI,children:s.jsx(AI,{children:s.jsx(lI,{children:s.jsx(Af,{value:e,children:s.jsxs(Df,{sendDaemonCommand:hr,children:[s.jsx(MI,{}),s.jsxs(hI,{children:[s.jsx(TI,{}),s.jsxs(af,{children:[s.jsx(Es,{path:"/dashboard",element:s.jsx(TM,{})}),s.jsx(Es,{path:"/machine",element:s.jsx(Qd,{})}),s.jsx(Es,{path:"/machines/:id",element:s.jsx(_P,{})}),s.jsx(Es,{path:"/machines",element:s.jsx(Qd,{})}),s.jsx(Es,{path:"/about",element:s.jsx(xI,{})}),s.jsx(Es,{path:"/settings",element:s.jsx(yI,{})}),s.jsx(Es,{path:"/mesh",element:s.jsx(XD,{children:s.jsx(YD,{})})}),s.jsx(Es,{path:"*",element:s.jsx(ti,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}Ik({connectionManager:ws});of(document.getElementById("root")).render(s.jsx(PI,{}));
|