@adhdev/daemon-standalone 1.0.57-rc.1 → 1.0.57
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 +19 -19
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/public/assets/{index-Dc_QNQdx.js → index-CUub692o.js} +5 -5
- package/public/index.html +1 -1
- package/vendor/mcp-server/index.js +0 -0
- package/vendor/session-host-daemon/index.js +0 -0
- package/vendor/session-host-daemon/index.mjs +0 -0
|
@@ -50,7 +50,7 @@ ${JSON.stringify(t,null,2)}
|
|
|
50
50
|
`),le=((se=pe[0])==null?void 0:se.slice(0,80))||"(empty)";return s.jsxs("div",{className:"border border-border-default rounded overflow-hidden bg-surface-secondary",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2.5 py-1.5 hover:bg-bg-glass-hover transition-colors text-left",onClick:()=>X(V),children:[s.jsx("span",{className:"text-[10px] text-text-muted w-3",children:ee?"▾":"▸"}),s.jsx("span",{className:"font-mono text-accent-primary w-20 shrink-0 text-[11px]",children:V}),!ee&&s.jsx("span",{className:"text-text-secondary truncate font-mono text-[11px]",children:le}),s.jsxs("span",{className:"ml-auto text-text-muted text-[10px] shrink-0",children:[pe.length,"L"]})]}),ee&&s.jsx("pre",{className:"px-3 pb-2.5 pt-1 font-mono text-[11px] text-text-secondary whitespace-pre-wrap break-all bg-bg-secondary max-h-40 overflow-y-auto border-t border-border-default",children:q||"(empty)"})]},V)})})]}),s.jsx(lr,{}),O.nativeSource&&s.jsxs("div",{children:[s.jsxs(Fn,{children:["Status History",O.statusHistory&&O.statusHistory.length>0?` (${O.statusHistory.length})`:""]}),O.statusHistory&&O.statusHistory.length>0?s.jsx("div",{className:"space-y-px",children:[...O.statusHistory].reverse().slice(0,20).map((V,q)=>s.jsx("div",{className:"rounded px-2 py-1 hover:bg-bg-glass-hover transition-colors",children:s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:`font-mono text-[11px] font-semibold px-1.5 py-0.5 rounded shrink-0 ${ir(V.status)}`,children:V.status}),s.jsx("span",{className:"text-text-secondary text-[11px] shrink-0 tabular-nums",children:$n(V.at)}),V.trigger&&s.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded font-mono shrink-0 text-text-secondary bg-bg-glass border border-border-default",children:V.trigger})]})},q))}):s.jsx("div",{className:"text-text-muted text-[11px] italic px-1",children:"N/A (native-source provider — no state-machine rules)"})]}),!O.nativeSource&&O.stateHistory&&O.stateHistory.length>0&&s.jsxs("div",{children:[s.jsxs(Fn,{children:["State History (",O.stateHistory.length,")"]}),s.jsx("div",{className:"space-y-px",children:[...O.stateHistory].reverse().slice(0,20).map((V,q)=>s.jsxs("div",{className:"rounded px-2 py-1 hover:bg-bg-glass-hover transition-colors",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:`font-mono text-[11px] font-semibold px-1.5 py-0.5 rounded shrink-0 ${ir(V.stateId)}`,children:V.stateId}),s.jsx("span",{className:"text-text-secondary text-[11px] shrink-0 tabular-nums",children:$n(V.at)}),V.durationMs>0&&s.jsxs("span",{className:"text-text-muted text-[11px]",children:["held ",s.jsx("span",{className:"text-text-secondary",children:$d(V.durationMs)})]}),V.reason&&s.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-mono shrink-0 ${cj[String(V.reason)]??"text-text-secondary bg-bg-glass border border-border-default"}`,children:String(V.reason)}),V.debounceKind&&String(V.debounceKind)!=="none"&&s.jsxs("span",{className:"text-text-muted text-[10px] font-mono",children:["debounce:",String(V.debounceKind)]}),V.matchedStateId&&String(V.matchedStateId)!==V.stateId&&s.jsxs("span",{className:"text-text-muted text-[10px] font-mono",children:["eval→",s.jsx("span",{className:"text-text-secondary",children:String(V.matchedStateId)})]})]}),V.matchedRules&&V.matchedRules.length>0&&s.jsxs("div",{className:"flex items-start gap-1 flex-wrap mt-0.5 ml-1 pl-1 border-l border-border-default",children:[V.matchedRules.slice(0,3).map((ee,pe)=>s.jsx("span",{className:"font-mono text-[10px] text-accent-primary bg-accent-primary/20 border border-accent px-1.5 py-0.5 rounded break-all",children:typeof ee=="string"?ee:JSON.stringify(ee)},pe)),V.matchedRules.length>3&&s.jsxs("span",{className:"text-[10px] text-text-muted",children:["+",V.matchedRules.length-3," more"]})]})]},q))})]}),s.jsx(lr,{}),(()=>{const V=O.messages??O.committedMessages??[];if(V.length===0)return null;const q=V.filter(le=>le.role==="user").length,ee=V.filter(le=>le.role==="assistant").length,pe=[...V].reverse().find(le=>le.role==="assistant");return s.jsxs("div",{children:[s.jsxs(Fn,{children:["Transcript (",V.length," — ",q,"u / ",ee,"a)"]}),pe&&s.jsxs("div",{className:"bg-surface-secondary border border-border-default rounded-md p-2.5 text-[11px]",children:[s.jsxs("div",{className:"text-text-muted mb-1 text-[10px]",children:["Last assistant ",pe.receivedAt?$n(pe.receivedAt):""]}),s.jsxs("div",{className:"text-text-secondary font-mono whitespace-pre-wrap line-clamp-4 break-all",children:[pe.content.slice(0,400),pe.content.length>400?"…":""]})]})]})})(),O.specPath&&s.jsx("div",{className:"text-[10px] text-text-muted font-mono truncate border-t border-border-default pt-2 mt-1",title:O.specPath,children:O.specPath}),s.jsxs("div",{children:[s.jsxs("button",{type:"button",className:"text-[11px] text-text-secondary hover:text-text-primary transition-colors flex items-center gap-1.5",onClick:()=>u(V=>!V),children:[s.jsx("span",{className:"text-text-muted",children:p?"▾":"▸"}),s.jsxs("span",{children:["Raw screen (",O.screen?O.screen.split(`
|
|
51
51
|
`).length:0," lines)"]})]}),p&&s.jsx("pre",{className:"mt-1.5 px-3 py-2 font-mono text-[11px] text-text-secondary whitespace-pre bg-bg-secondary rounded-md border border-border-default max-h-64 overflow-auto",children:O.screen||"(empty)"})]})]})]})]})})})}function mj({activeConv:e,clearToken:t=0,terminalRef:n,handleSendChat:a,isSendingChat:r=!1,sendFeedbackMessage:o=null,isVisible:i=!0,isInputActive:c=!0}){var Be;const{t:d}=ke("common");Ss();const{sendPtyInput:p}=St(),[u,m]=l.useState(!1),f=l.useRef(!1);f.current=u;const[g,k]=l.useState("Runtime terminal unavailable"),[h,b]=l.useState(!1),[S,x]=l.useState(null),[y,C]=l.useState(!1),[v,w]=l.useState(!1),[j,N]=l.useState(1),[A,T]=l.useState(!1),[I,P]=l.useState(!1),[M,E]=l.useState(!1),[D,W]=l.useState(!1),[R,B]=l.useState(!1),[_,H]=l.useState({width:0,height:0}),[L,F]=l.useState({width:0,height:0}),[$,K]=l.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[z,ne]=l.useState(null),ie=l.useRef(null),Ce=l.useRef(null),me=l.useRef(!1),O=l.useRef(!1),Y=l.useRef(i),X=l.useRef(0),Q=l.useRef(!1),ve=l.useRef(""),he=l.useRef(null),Z=l.useRef(!1),fe=l.useRef(!1),V=l.useRef(null),q=l.useRef(null),ee=l.useRef(null),pe=32*1024,le=()=>{var ge,je,Te,Fe;return((je=(ge=ie.current)==null?void 0:ge.ownerDocument)==null?void 0:je.defaultView)||((Fe=(Te=Ce.current)==null?void 0:Te.ownerDocument)==null?void 0:Fe.defaultView)||window},se=ge=>{const je=le();return{ownerWindow:je,frameId:je.requestAnimationFrame(ge)}},te=()=>{const ge=V.current;if(ge){try{ge.ownerWindow.cancelAnimationFrame(ge.frameId)}catch{}V.current=null}},ue=()=>{const ge=q.current;if(ge){try{ge.ownerWindow.clearTimeout(ge.timeoutId)}catch{}q.current=null}},ye=()=>{const ge=ee.current;if(ge){try{ge.ownerWindow.clearTimeout(ge.timeoutId)}catch{}ee.current=null}},Me=()=>{i&&V.current===null&&(V.current=se(()=>{oe()}))},re=e.tabKey,ce=e.sessionId||"",Ae=e.daemonId||((Be=e.routeId)==null?void 0:Be.split(":")[0])||e.routeId||"",be=sc(e),we=u?be?Rm:o:g,_e=u&&o||null,U=GC,Ne=qC,Ie=.05,We=()=>{const ge=L.width,je=L.height;if(!Number.isFinite(_.width)||_.width<=0||!Number.isFinite(_.height)||_.height<=0||!Number.isFinite(ge)||ge<=0||!Number.isFinite(je)||je<=0)return 1;const Te=_.width/ge,Fe=_.height/je;return Number(Math.min(Ne,Math.max(U,Math.min(Te,Fe))).toFixed(2))},Xe=We(),et=me.current&&j>Xe,J=Number.isFinite(L.width)&&L.width>0?Math.max(_.width,Math.round(L.width*j)):_.width,Le=Number.isFinite(L.height)&&L.height>0?Math.max(_.height,Math.round(L.height*j)):_.height,$e=()=>{se(()=>{const ge=Ce.current;ge&&(ge.scrollLeft=0,ge.scrollTop=ge.scrollHeight-ge.clientHeight)})},at=()=>{var ge,je;X.current=0,Q.current=!1,ve.current="",he.current=null,Z.current=!1,fe.current=!1,me.current||(O.current=!1,N(1)),V.current!==null&&te(),m(!1),k("Runtime terminal unavailable"),ye(),ue(),x(null),ne(null),T(!1),b(!1),C(!1),w(!1),(je=(ge=n.current)==null?void 0:ge.reset)==null||je.call(ge)},rt=()=>{var ge,je;X.current=0,Q.current=!1,ve.current="",he.current=null,Z.current=!1,fe.current=!1,V.current!==null&&te(),m(!0),k(""),ye(),ue(),x(null),ne(null),T(!1),b(!1),C(!1),w(!1),(je=(ge=n.current)==null?void 0:ge.reset)==null||je.call(ge)},G=()=>{fe.current&&(fe.current=!1,se(()=>{var ge,je;(je=(ge=n.current)==null?void 0:ge.scrollToTop)==null||je.call(ge)}))},oe=()=>{if(V.current=null,!i)return;const ge=ve.current;if(!ge)return;const je=ge.slice(0,pe);ve.current=ge.slice(je.length);const Te=n.current;if(!Te){ve.current=je+ve.current,Me();return}Te.write(je,()=>{if(ve.current.length>0){Me();return}G()})},de=ge=>{ge&&(ve.current+=ge,Me())},xe=(ge,je=0,Te,Fe,Ge={})=>{var Ve,ut,Kt,Et;const dt=!!Ge.force;!dt&&je>0&&X.current>=je||!dt&&je===0&&Q.current||(X.current=je,je>0&&C(!0),m(!0),k(""),typeof Te=="number"&&typeof Fe=="number"&&Te>0&&Fe>0&&((ut=(Ve=n.current)==null?void 0:Ve.resize)==null||ut.call(Ve,Te,Fe)),ve.current="",(Et=(Kt=n.current)==null?void 0:Kt.reset)==null||Et.call(Kt),ge?de(ge):G())};l.useEffect(()=>{at()},[ce]),l.useEffect(()=>{var je;if(!ce)return;const ge=((je=Ct.onRuntimeEvent)==null?void 0:je.call(Ct,ce,Te=>{if(!(!Te||Te.sessionId!==ce)){if(Te.type==="runtime_snapshot"){if(!i){he.current={text:Te.text||"",seq:Te.seq||0,cols:Te.cols,rows:Te.rows,force:!!Te.force};return}xe(Te.text||"",Te.seq||0,Te.cols,Te.rows,{force:!!Te.force});return}if(Te.type==="session_output"){Q.current=!0,typeof Te.seq=="number"&&(X.current=Math.max(X.current,Te.seq),Te.seq>0&&C(!0)),f.current||m(!0),f.current||k(""),typeof Te.data=="string"&&de(Te.data);return}if(Te.type==="session_cleared"){if(!i){Z.current=!0,ve.current="",he.current=null;return}rt();return}if(Te.type==="session_io_error"){const Fe=typeof Te.error=="string"&&Te.error?Te.error:typeof Te.reason=="string"&&Te.reason?Te.reason:"unknown error";m(!1),k(`Runtime input failed: ${Fe}`);return}}},Ae))||(()=>{});return()=>{ge()}},[Ae,ce,n,i]);const Se=async(ge={})=>{var je;if(!Ae||!ce)return{success:!1,error:"daemonId and sessionId are required"};ge.preserveStatus||k(ge.loadingMessage||"Loading runtime terminal...");try{const Te=await((je=Ct.requestRuntimeSnapshot)==null?void 0:je.call(Ct,Ae,ce,{sinceSeq:ge.sinceSeq,force:ge.force}));return Te&&Te.success===!1?(ge.preserveStatus||(m(!1),k(`Runtime terminal unavailable: ${Te.error}`)),Te):Te||{success:!0}}catch(Te){const Fe=(Te==null?void 0:Te.message)||String(Te);return ge.preserveStatus||(m(!1),k(`Runtime terminal unavailable: ${Fe}`)),{success:!1,error:Fe}}},Pe=async ge=>{var dt,Ve;const je=((dt=ie.current)==null?void 0:dt.ownerDocument)||document,Te=je.defaultView||window,Fe=(Ve=Te.navigator)==null?void 0:Ve.clipboard;if(Fe!=null&&Fe.writeText&&Te.isSecureContext)try{return await Fe.writeText(ge),!0}catch{}let Ge=null;try{return Ge=je.createElement("textarea"),Ge.value=ge,Ge.setAttribute("readonly","true"),Ge.style.position="fixed",Ge.style.left="-9999px",Ge.style.top="0",je.body.appendChild(Ge),Ge.focus(),Ge.select(),je.execCommand("copy")}catch{return!1}finally{Ge==null||Ge.remove()}},He=ge=>{ue(),ne(ge);const je=le();q.current={ownerWindow:je,timeoutId:je.setTimeout(()=>{q.current=null,ne(Te=>Te===ge?null:Te)},2200)}},Ee=ge=>{ye(),x(ge);const je=le();ee.current={ownerWindow:je,timeoutId:je.setTimeout(()=>{ee.current=null,x(Te=>Te===ge?null:Te)},2200)}},Je=async()=>{var Ge,dt,Ve,ut;const ge=((dt=(Ge=n.current)==null?void 0:Ge.getSelection)==null?void 0:dt.call(Ge))||"",je=((ut=(Ve=n.current)==null?void 0:Ve.getVisibleText)==null?void 0:ut.call(Ve))||"",Te=ge.trimEnd()||je.trimEnd();if(!Te){He("Nothing to copy");return}if(!await Pe(Te)){He("Copy failed");return}He(ge.trimEnd()?"Copied selection":"Copied visible terminal")},st=ge=>{if(!u||!i)return;((p==null?void 0:p(Ae,ce,ge))??!1)||He("Terminal input failed")},Ze=ge=>{st(KC({ctrl:I,alt:M,shift:D},ge)),P(!1),E(!1),W(!1)},Ue=async()=>{if(h)return;b(!0),x("Loading older terminal output..."),fe.current=!0;const ge=await Se({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:u});if(b(!1),(ge==null?void 0:ge.success)===!1){fe.current=!1,x(`Older terminal output unavailable: ${ge.error}`);return}w(!0),Ee("Older terminal output loaded"),se(()=>{var je;(je=n.current)==null||je.bumpResize()})};l.useEffect(()=>{var je,Te;if(!ce)return;Ae&&((je=Ct.getState)==null?void 0:je.call(Ct,Ae))==="connected"&&Se();const ge=(Te=Ct.onStateChange)==null?void 0:Te.call(Ct,(Fe,Ge)=>{Fe!==Ae||Ge!=="connected"||Se()});return()=>{ge==null||ge()}},[Ae,ce,n]),l.useEffect(()=>{t&&at()},[t,re,n]),l.useEffect(()=>{var Fe,Ge;const ge=ie.current,je=(Ge=(Fe=ge==null?void 0:ge.ownerDocument)==null?void 0:Fe.defaultView)==null?void 0:Ge.ResizeObserver;if(!ge||!je)return;const Te=new je(dt=>{const Ve=dt[0];if(!Ve)return;const{width:ut,height:Kt}=Ve.contentRect;H(Et=>{const ps=Math.round(ut),Zt=Math.round(Kt);return Et.width===ps&&Et.height===Zt?Et:{width:ps,height:Zt}})});return Te.observe(ge),()=>Te.disconnect()},[]),l.useEffect(()=>{if(me.current)return;const ge=We();!Number.isFinite(ge)||ge<=0||N(je=>O.current?ge<je-Ie?ge:je:(O.current=!0,ge))},[L.height,L.width,_.height,_.width]),l.useEffect(()=>{et&&$e()},[et,Le,J]),l.useEffect(()=>{var Te;const ge=Y.current;if(Y.current=i,!i)return;ge||w(!1),Z.current&&(Z.current=!1,rt());const je=he.current;je&&(he.current=null,xe(je.text,je.seq,je.cols,je.rows,{force:!!je.force})),Ae&&ce&&((Te=Ct.getState)==null?void 0:Te.call(Ct,Ae))==="connected"&&Se(),ve.current&&V.current===null&&Me(),se(()=>{var Fe;(Fe=n.current)==null||Fe.bumpResize()})},[Ae,i,ce]),l.useEffect(()=>()=>{V.current!==null&&te(),ue(),ye()},[]),l.useEffect(()=>{const ge=Fe=>{var dt;const Ge=Fe.detail;Ge!=null&&Ge.sessionId&&Ge.sessionId!==ce||u&&((dt=n.current)==null||dt.bumpResize())},je=le(),Te=je===window?[window]:[window,je];for(const Fe of Te)Fe.addEventListener("adhdev:fit-cli-terminal",ge);return()=>{for(const Fe of Te)Fe.removeEventListener("adhdev:fit-cli-terminal",ge)}},[u,ce,n]);const nt=u&&y&&!v&&($.atTop||!$.canScroll)||h||!!S;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:ie,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[nt&&s.jsxs("div",{className:"absolute left-3 top-3 z-10 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-medium text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{Ue()},disabled:!ce||h,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:d(h?"terminal.loadingOlder":"terminal.loadOlderOutput")}),S&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:S})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[z&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:z}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>B(ge=>!ge),title:"Spec debug — inspect current state, sections, and transition history",children:d("terminal.debug")}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{Je()},disabled:!u,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:d("terminal.copy")}),s.jsxs("div",{className:"relative",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>T(ge=>!ge),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,P],["Alt",M,E],["Shift",D,W]].map(([ge,je,Te])=>s.jsx("button",{type:"button","aria-pressed":je,className:`h-9 rounded-lg border text-[12px] font-semibold transition-colors ${je?"border-sky-400/50 bg-sky-400/25 text-white":"border-white/10 bg-white/[0.06] hover:bg-white/[0.12]"}`,onClick:()=>Te(Fe=>!Fe),children:ge},ge))}),s.jsx("div",{className:"my-2 h-px bg-white/10"}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ze("Escape"),children:"Esc"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ze("Tab"),children:"Tab"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ze("Enter"),children:"Enter"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ze("ArrowUp"),"aria-label":"Arrow up",children:"↑"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ze("ArrowLeft"),"aria-label":"Arrow left",children:"←"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ze("ArrowDown"),"aria-label":"Arrow down",children:"↓"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ze("ArrowRight"),"aria-label":"Arrow right",children:"→"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>st(""),title:"Send SIGINT (Ctrl-C)",children:"Ctrl-C"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ze("Space"),children:"Space"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ze("Backspace"),children:"Bksp"})]})]})]}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{me.current=!0,N(ge=>{const je=Math.max(Xe,Number((ge-.1).toFixed(2)));return je>Xe&&$e(),je})},title:"Shrink terminal viewport",children:"-"}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{me.current=!0,N(ge=>{const je=Math.min(Ne,Number((ge+.1).toFixed(2)));return je>Xe&&$e(),je})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:Ce,className:et?"w-full h-full overflow-auto rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",children:s.jsx("div",{style:{width:J>0?`${J}px`:"100%",height:Le>0?`${Le}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:L.width>0?`${L.width}px`:"100%",height:L.height>0?`${L.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:j},children:s.jsx(Yp,{ref:n,readOnly:!u||!i,sizingMode:"measured",onViewportMetrics:F,onScrollMetrics:K,onInput:ge=>{!u||(p==null||p(Ae,ce,ge))}})})})}),!u&&s.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:g})]}),s.jsx(vm,{contextKey:e.tabKey,panelLabel:kt(e),isSending:r,isBusy:!!be,statusMessage:we,inlineStatusMessage:_e,onSend:async ge=>be?!1:a(ge),isActive:c&&i,showControlsToggle:!1,animateVisibility:!1}),R&&s.jsx(pj,{activeConv:e,onClose:()=>B(!1)})]})}const hj={accent:{track:"--accent-primary",head:"--accent-primary-light"},success:{track:"--status-online",head:"--status-online"},muted:{track:"--text-muted",head:"--text-muted"}};function ls({size:e=28,thickness:t=2.5,color:n="accent",className:a,label:r}){const o=hj[n],i={width:e,height:e,border:`${t}px solid color-mix(in srgb, var(${o.track}) 20%, transparent)`,borderTopColor:`var(${o.head})`};return s.jsx("span",{className:Pt("block shrink-0 rounded-full animate-spin",a),style:i,role:r?"status":void 0,"aria-label":r,"aria-hidden":r?void 0:!0})}const fj=5e3,gj=12e3,bj=15e3;function xj(e){return e==="disconnected"||e==="reconnecting"}function vj({wsStatus:e,showReconnected:t,loginUrl:n,onReconnect:a,reconnectDelayMs:r=fj,reconnectActionDelayMs:o=gj}){const{t:i}=ke(),c=xj(e),[d,p]=l.useState(()=>!c||r<=0),[u,m]=l.useState(()=>!c||o<=0),f=l.useRef(!1),[g,k]=l.useState(!1);l.useEffect(()=>{if(!c){p(!1);return}if(f.current=!1,r<=0){f.current=!0,p(!0);return}p(!1);const A=setTimeout(()=>{f.current=!0,p(!0)},r);return()=>clearTimeout(A)},[r,c]),l.useEffect(()=>{if(!c){m(!1);return}if(o<=0){m(!0);return}m(!1);const A=setTimeout(()=>{m(!0)},o);return()=>clearTimeout(A)},[o,c]),l.useEffect(()=>{e!=="reconnecting"&&k(!1)},[e]),l.useEffect(()=>{if(!g)return;const A=setTimeout(()=>k(!1),bj);return()=>clearTimeout(A)},[g]);const h=()=>{k(!0),a==null||a()},b=c?d:e==="offline"||e==="auth_failed",S=!!(a&&e!=="auth_failed"&&(!c||u)),x=l.useMemo(()=>!t||e!=="connected"?!1:r<=0||f.current,[r,t,e]),y=e==="auth_failed"?"red":e==="offline"?"orange":"accent",C={red:"linear-gradient(90deg, rgba(239,68,68,0.12), rgba(239,68,68,0.04))",orange:"linear-gradient(90deg, rgba(255,107,53,0.12), rgba(255,107,53,0.04))",accent:"linear-gradient(90deg, color-mix(in srgb, var(--accent-primary) 18%, transparent), color-mix(in srgb, var(--accent-primary) 6%, transparent))"},v={red:"1px solid rgba(239,68,68,0.2)",orange:"1px solid rgba(255,107,53,0.2)",accent:"1px solid color-mix(in srgb, var(--accent-primary) 28%, transparent)"},w={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},j="fixed left-1/2 top-[calc(env(safe-area-inset-top,0px)+64px)] sm:top-[calc(env(safe-area-inset-top,0px)+16px)] z-[var(--z-toast)] flex items-center justify-center pointer-events-none",N={transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[b&&s.jsx("div",{className:j,style:N,children:s.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-3 py-2.5 sm:px-4 sm:py-3 text-[13px] font-semibold flex flex-wrap items-center gap-x-2.5 gap-y-2 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:C[y],border:v[y],color:w[y]},children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5 shrink-0",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),s.jsxs("span",{className:"min-w-0 text-center whitespace-nowrap",children:[e==="offline"&&i("connection.networkOffline"),e==="disconnected"&&i("connection.reconnecting"),e==="reconnecting"&&i("connection.reconnecting"),e==="auth_failed"&&(n?s.jsxs(s.Fragment,{children:[i("connection.sessionExpired")," ",s.jsx("a",{href:n,className:"text-inherit underline",children:i("connection.logInAgain")})]}):i("connection.connectionFailed"))]}),S&&s.jsxs("button",{type:"button",className:"basis-full sm:basis-auto mx-auto sm:mx-0 sm:ml-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-[12px] font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed inline-flex items-center gap-1.5",onClick:h,disabled:e==="offline"||g,children:[g&&s.jsx(ls,{size:11,thickness:2,color:"muted"}),i(g?"connection.reconnecting":"connection.reconnectNow")]})]})}),x&&s.jsx("div",{className:j,style:N,children:s.jsxs("div",{className:"pointer-events-none rounded-2xl border px-4 py-2 text-xs font-semibold flex items-center gap-2 justify-center bg-gradient-to-r from-green-500/[0.12] to-green-500/[0.04] text-green-400 border-green-500/15 shadow-[0_18px_40px_rgba(2,6,23,0.2)] backdrop-blur-xl animate-[fadeIn_0.3s_ease]",children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),i("connection.connected")]})})]})}function oh({mode:e,onChange:t,compact:n=!1}){const{t:a}=ke("common"),r=n?14:15;return s.jsx("button",{type:"button",onClick:()=>t(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:a(e==="chat"?"cliView.switchToTerminal":"cliView.switchToChat"),children:e==="chat"?s.jsx(Bl,{size:r}):s.jsx(Is,{size:r})})}function yj(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 wj(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 kj(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 qr({git:e,className:t="",compact:n=!1}){const a=yj(e),r=wj(e);if(!a||!r)return null;const o=[e!=null&&e.branch?`Branch: ${e.branch}`:null,e!=null&&e.changedFiles?`Changed files: ${e.changedFiles}`:null,e!=null&&e.ahead?`Ahead: ${e.ahead}`:null,e!=null&&e.behind?`Behind: ${e.behind}`:null,e!=null&&e.hasConflicts?"Conflicts detected":null,e!=null&&e.error?`Git error: ${e.error}`:null].filter(Boolean);return s.jsxs("span",{className:`inline-flex min-w-0 max-w-[12rem] items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-semibold leading-none ${kj(r)} ${t}`.trim(),title:o.join(" · ")||a,"data-git-tone":r,children:[s.jsx("span",{"aria-hidden":"true",children:"⑂"}),s.jsx("span",{className:"truncate",children:a})]})}function Sj({wsStatus:e,isConnected:t,daemonCount:n,p2pStates:a={},usesP2P:r=!0}){if(e!=="connected")return{tone:"disconnected",titleKey:"connection.disconnected",subtitleKey:null};if(n>0&&!r)return t?{tone:"connected",titleKey:"connection.connected",subtitleKey:null}:{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:null};const i=Object.values(a).filter(c=>c==="connected").length;return n>0?i>=n?{tone:"connected",titleKey:"connection.connected",subtitleKey:null}:{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:"connection.machinesConnectedCount",subtitleParams:{connected:i,total:n}}:t?{tone:"connected",titleKey:"connection.connected",subtitleKey:null}:{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:null}}function Fd({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Bd({notification:e,shortcutIndex:t,onOpen:n,onMarkRead:a,onMarkUnread:r,onDelete:o}){const{t:i}=ke(),c=za(e.updatedAt),d=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${d?"is-attention":""}`.trim(),children:[s.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:n,children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[t?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",t]}):null,[e.type==="needs_attention"?i("notification.actionNeeded"):i("notification.taskComplete"),c].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[d?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:p=>{p.stopPropagation(),a()},children:i("notification.markRead")}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:p=>{p.stopPropagation(),r()},children:i("notification.markUnread")}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:p=>{p.stopPropagation(),o()},children:i("notification.delete")})]})]})}function Cj({activeConv:e,wsStatus:t,isConnected:n,conversations:a,onOpenHistory:r,onOpenRemote:o,onStopCli:i,activeCliViewMode:c,onSetCliViewMode:d,onHideConversation:p,hiddenConversations:u=[],onShowConversation:m,onShowAllHidden:f,onResetPanelsToMain:g,inboxOpen:k,onInboxOpenChange:h,hiddenOpen:b,onHiddenOpenChange:S,onOpenNewSession:x,onOpenDashboardGuide:y,guideNudgeVisible:C=!1,actionShortcuts:v,notifications:w,notificationUnreadCount:j,onOpenNotification:N,onMarkNotificationRead:A,onMarkNotificationUnread:T,onDeleteNotification:I,onOpenGitDialog:P,onOpenMeshGraph:M}){var pe;const{t:E}=ke(),{ides:D,p2pStates:W={},usesP2P:R=!0}=Ss(),B=!!e&&bt(e)&&!ht(e),_=!!e&&ht(e),H=!!(e!=null&&e.daemonId)&&!!((pe=e==null?void 0:e.coordinator)!=null&&pe.meshId),L=c||(e?Tm(e)?"terminal":"chat":null),[F,$]=l.useState(!1),[K,z]=l.useState(!1),ne=l.useRef(null),ie=l.useRef(null),Ce=l.useRef(null),me=D.filter(le=>le.type==="adhdev-daemon"),O=Sj({wsStatus:t,isConnected:n,daemonCount:me.length,p2pStates:W,usesP2P:R}),Y=E(O.titleKey),X=O.subtitleKey?E(O.subtitleKey,O.subtitleParams):null,Q=O.tone==="connected"?"#22c55e":O.tone==="limited"?"#eab308":"#ef4444",ve=O.tone==="connected"?"0 0 4px #22c55e80":O.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",he=l.useMemo(()=>w.filter(le=>!le.readAt),[w]),Z=l.useMemo(()=>w.filter(le=>!!le.readAt),[w]),fe=l.useMemo(()=>he.slice(0,9),[he]),V=j;l.useEffect(()=>{if(!k)return;const le=se=>{var te;(te=ie.current)!=null&&te.contains(se.target)||h(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[k,h]),l.useEffect(()=>{if(!b)return;const le=se=>{var te;(te=Ce.current)!=null&&te.contains(se.target)||S(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[b,S]),l.useEffect(()=>{if(!b&&!k)return;const le=se=>{if(!se.altKey)return;const te=se.code.match(/^Digit([1-9])$/);if(!te)return;const ue=Number(te[1])-1,ye=b?u[ue]:void 0,Me=k?fe[ue]:void 0;if(!(!ye&&!Me)){if(se.preventDefault(),se.stopPropagation(),ye){m==null||m(ye),S(!1);return}Me&&(N(Me),h(!1))}};return window.addEventListener("keydown",le,!0),()=>window.removeEventListener("keydown",le,!0)},[u,b,k,fe,S,h,N,m]),l.useEffect(()=>{const le=u.length;if(ne.current===null){ne.current=le;return}le>ne.current&&z(!0),ne.current=le},[u.length]);const q=()=>z(!1),ee=le=>{if(!le)return;const se=a.find(te=>te.tabKey===le);se&&(p==null||p(se))};return s.jsxs("div",{className:"dashboard-header",children:[s.jsx("div",{className:"flex items-center gap-3",children:s.jsx("div",{className:"header-title-block",children:s.jsxs("div",{className:"header-title-row",children:[s.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[s.jsx(Is,{size:18}),s.jsx("span",{className:"header-title-desktop",children:E("dashboard.header.title")}),s.jsx("span",{className:"header-title-mobile",children:e?kt(e):E("dashboard.header.title")}),s.jsx("span",{title:Y,"aria-label":Y,className:"header-title-status-dot",style:{background:Q,boxShadow:ve}}),s.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:s.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:Q,boxShadow:ve}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[X&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",X]}),x&&s.jsx("button",{type:"button",onClick:x,className:"btn btn-secondary btn-sm ml-2",title:`${E("paneGroup.newSession")}${v!=null&&v.openNewSession?` (${v.openNewSession})`:""}`,"aria-label":E("paneGroup.newSession"),children:s.jsx(Wl,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[y&&s.jsxs("button",{type:"button",onClick:y,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:E("dashboard.header.guide"),"aria-label":E("dashboard.header.guideOpen"),children:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),C&&s.jsx("span",{children:E("dashboard.header.guideShort")})]}),e&&(B||_||!ht(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:na(e)||kt(e),children:kt(e)}),P&&e.git&&e.daemonId&&e.workspacePath?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:E("dashboard.header.openGitStatus"),onClick:()=>P(e.daemonId,e.workspacePath),children:s.jsx(qr,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(qr,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),H&&M&&s.jsxs("button",{type:"button",onClick:()=>M(e),className:"btn btn-secondary btn-sm dashboard-header-mesh-button",title:E("dashboard.header.openMeshGraph"),children:[s.jsx(cs,{size:14}),s.jsx("span",{className:"hidden lg:inline",children:E("dashboard.header.meshGraph")})]}),(B||_)&&i&&s.jsxs(s.Fragment,{children:[B&&d&&L&&s.jsx(oh,{mode:L,onChange:d,compact:!0}),s.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:E(_?"dashboard.header.stopAcpSession":"dashboard.header.stopCliProcess"),style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(Dt,{size:14})})]}),!ht(e)&&s.jsx("button",{onClick:()=>r(e),className:"btn btn-secondary btn-sm",title:E("dashboard.header.chatHistory"),children:s.jsx($l,{size:14})}),!B&&!ht(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:E("dashboard.header.remoteControl"),children:s.jsx(us,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:ie,children:[s.jsxs("div",{className:`dashboard-header-hidden${F?" is-drop-target":""}${K?" hidden-spawn-flash":""}${(u??[]).some(Ha)?" hidden-generating-spin":""}`,onAnimationEnd:q,ref:Ce,onDragEnter:le=>{le.dataTransfer.types.includes("text/tab-key")&&(le.preventDefault(),$(!0))},onDragOver:le=>{le.dataTransfer.types.includes("text/tab-key")&&(le.preventDefault(),le.dataTransfer.dropEffect="move",$(!0))},onDragLeave:le=>{le.currentTarget.contains(le.relatedTarget)||$(!1)},onDrop:le=>{const se=le.dataTransfer.getData("text/tab-key");le.preventDefault(),$(!1),ee(se)},children:[s.jsxs("button",{type:"button",onClick:()=>S(!b),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`${E("dashboard.hidden.title")}${v!=null&&v.toggleHiddenTabs?` (${v.toggleHiddenTabs})`:""}. ${E("dashboard.hidden.dragHint")}`,children:[s.jsx(mo,{size:16}),u.length>0&&s.jsx("span",{className:`dashboard-header-hidden-badge${K?" hidden-badge-pop":""}`,children:u.length})]}),b&&s.jsxs("div",{className:"dashboard-header-hidden-popover",children:[s.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:E("dashboard.hidden.title")}),s.jsx(Fd,{value:v==null?void 0:v.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[g&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:g,children:E("dashboard.hidden.resetPanels")}),u.length>0&&f&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{f(),S(!1)},children:E("dashboard.hidden.restoreAll")})]})]}),e&&p&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>p(e),children:[s.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[s.jsx("span",{className:"dashboard-header-hidden-current-label",children:E("dashboard.hidden.hideCurrentTab")}),s.jsx(Fd,{value:v==null?void 0:v.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:kt(e)})]}),u.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(le=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{m==null||m(le),S(!1)},children:[s.jsxs("span",{className:"dashboard-header-inbox-item-title",children:[Ha(le)&&s.jsx(ls,{size:12,thickness:2,color:"success",label:E("dashboard.header.generating")}),kt(le)]}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(le)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(le)+1]}):null,na(le)]})]},le.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:E("dashboard.hidden.empty")})]})]}),s.jsxs("button",{type:"button",onClick:()=>h(!k),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:E("dashboard.header.activityInbox"),children:[s.jsx(la,{size:16}),V>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:V})]}),k&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[he.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:E("dashboard.inbox.unread")}),he.map(le=>s.jsx(Bd,{notification:le,shortcutIndex:fe.indexOf(le)>=0?fe.indexOf(le)+1:void 0,onOpen:()=>N(le),onMarkRead:()=>A(le.id),onMarkUnread:()=>T(le.id),onDelete:()=>I(le.id)},le.id))]}),Z.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:E("dashboard.inbox.read")}),Z.map(le=>s.jsx(Bd,{notification:le,onOpen:()=>N(le),onMarkRead:()=>A(le.id),onMarkUnread:()=>T(le.id),onDelete:()=>I(le.id)},le.id))]}),w.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:E("dashboard.inbox.empty")})]})]})]})]})}function qt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function jj(e,t){return String(e||"")!==String(t||"")}function Nj(e,t={}){const n=String(t.textQuery||"").trim().toLowerCase(),a=String(t.workspaceQuery||"").trim().toLowerCase(),r=String(t.modelQuery||"").trim().toLowerCase(),o=!!t.resumableOnly;return!n&&!a&&!r&&!o?e:e.filter(i=>!(o&&!i.canResume||n&&![i.title,i.preview].map(d=>String(d||"").toLowerCase()).join(`
|
|
52
52
|
`).includes(n)||a&&!String(i.workspace||"").toLowerCase().includes(a)||r&&!mm(i.summaryMetadata).map(d=>d.toLowerCase()).join(`
|
|
53
|
-
`).includes(r)))}function Aj(e,t="recent"){const n=e.slice();return n.sort((a,r)=>{if(t==="oldest")return(Number(a.lastMessageAt)||0)-(Number(r.lastMessageAt)||0);if(t==="messages"){const o=(Number(r.messageCount)||0)-(Number(a.messageCount)||0);if(o!==0)return o}return(Number(r.lastMessageAt)||0)-(Number(a.lastMessageAt)||0)}),n}function ih(e,t={}){return Aj(Nj(e,t),t.sortMode||"recent")}function cl(e,t){return typeof e=="function"?e(t??!1?"launch.resumeSavedHistory":"launch.startFresh"):e?"Resume saved history":"Start fresh"}function lh(e,t){return typeof e=="function"?e(t??!1?"launch.resumingSavedHistory":"launch.startingFresh"):e?"Resuming saved history…":"Starting fresh…"}function Tj(e){return e?e("launch.startFresh"):"Start fresh"}function Mj(e){return e?e("launch.hostedRuntimeRecoveryDescription"):"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Pj(e){return e?e("launch.openSavedHistory"):"Open saved history"}function Dj(e){return e?e("launch.savedHistoryTitle"):"Saved History"}function oc(e){return e?e("launch.savedHistoryHelper"):"Use saved history when you want continuity in the same provider conversation."}function Ij(e){return e?e("launch.savedHistoryEmpty"):"No saved history found yet."}function Lj(e){return e?e("launch.refreshSavedHistory"):"Refresh saved history"}function Rj(e){return e?e("launch.refreshingSavedHistory"):"Refreshing saved history…"}function zr(e,t,n){if(typeof e=="function"){const o=t,i=n;return o==="start-fresh"?e("launch.startFreshWith",{label:i}):e("launch.restart",{label:i})}const a=e,r=t;return a==="start-fresh"?`Start fresh with ${r}?`:`Restart ${r}?`}function Kr(e,t){if(typeof e=="function"){const a=t;return e(a==="start-fresh"?"launch.startFreshReview":a==="restart-ide"?"launch.restartIdeReview":"launch.restartStoppedReview")}const n=e;return n==="start-fresh"?"Review the provider and target folder before starting fresh.":n==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function Vr(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartFresh":"launch.confirmRestart"):e==="start-fresh"?"Start fresh":"Restart"}function Yr(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartingFresh":"launch.confirmRestarting"):e==="start-fresh"?"Starting fresh…":"Restarting…"}function ch(e,t){return typeof e=="function"?e("launch.resumeWith",{label:t}):`Resume saved history with ${e}?`}function dh(e){return e?e("launch.resumeReview"):"Review or change the target workspace before resuming saved history."}function Wd(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 uh({activeConv:e,ides:t,isCreatingChat:n,isRefreshingHistory:a,savedSessions:r=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:c,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:p,onClose:u,onNewChat:m,onSwitchSession:f,onRefreshHistory:g,onResumeSavedSession:k}){var E;const{t:h}=ke("common"),b=t.find(D=>D.id===e.routeId),S=(b==null?void 0:b.chats)||[],x=(E=b==null?void 0:b.activeChat)==null?void 0:E.id,y=bt(e)&&!ht(e),[C,v]=l.useState(()=>qt()),[w,j]=l.useState(null),N=c||C,A=String(d||"").trim(),T=D=>{if(p){p(D);return}v(D)},I=l.useMemo(()=>r.map(D=>{const W=String(D.workspace||"").trim();return D.canResume||W||!A?D:{...D,workspace:A,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[A,r]),P=l.useMemo(()=>ih(I,{textQuery:N.textQuery,workspaceQuery:N.workspaceQuery,modelQuery:N.modelQuery,resumableOnly:N.resumableOnly,sortMode:N.sortMode}),[I,N.modelQuery,N.resumableOnly,N.sortMode,N.textQuery,N.workspaceQuery]),M=s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:u,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:y?Dj(h):h("historyModal.chatHistory")}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:XC(e)}),y&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:oc(h)})]}),s.jsx("button",{onClick:u,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(Dt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!y&&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")}),y?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[s.jsx("input",{type:"text",value:N.textQuery,onChange:D=>T({...N,textQuery:D.target.value}),placeholder:h("historyModal.searchPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:N.workspaceQuery,onChange:D=>T({...N,workspaceQuery:D.target.value}),placeholder:h("historyModal.filterWorkspace"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:N.modelQuery,onChange:D=>T({...N,modelQuery:D.target.value}),placeholder:h("historyModal.filterModel"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsxs("select",{value:N.sortMode,onChange:D=>T({...N,sortMode:D.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:h("historyModal.sortRecent")}),s.jsx("option",{value:"oldest",children:h("historyModal.sortOldest")}),s.jsx("option",{value:"messages",children:h("historyModal.sortMessages")})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:N.resumableOnly,onChange:D=>T({...N,resumableOnly:D.target.checked})}),h("historyModal.resumeReadyOnly")]})]}),P.map(D=>{const W=e.providerSessionId===D.providerSessionId,R=W||!D.canResume||!!i,B=D.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{R||!k||j({kind:"saved",session:D})},disabled:R,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${W?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${R?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${W?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:D.title||h("historyModal.untitledSession")}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:D.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Wd(D.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:D.preview||h("historyModal.noSavedPreview")}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[D.workspace||h("historyModal.workspaceUnknown"),B?h("historyModal.selectedWorkspaceSuffix"):"",Mn(D.summaryMetadata)?` · ${Mn(D.summaryMetadata)}`:"",D.messageCount>0?` · ${h("historyModal.msgCount",{count:D.messageCount})}`:""]}),s.jsx("div",{className:"shrink-0",children:W?h("historyModal.statusActive"):D.canResume?B?h("historyModal.statusResumeSelectedWorkspace"):i===D.providerSessionId?h("historyModal.statusResuming"):h("historyModal.statusResume"):h("historyModal.statusMissingWorkspace")})]})]},D.id)})]}):S.map(D=>s.jsxs("div",{onClick:()=>{D.id!==x&&j({kind:"chat",id:D.id,title:D.title||h("historyModal.untitledSession")})},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${x===D.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[s.jsx("div",{className:`font-bold text-sm mb-1 ${x===D.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:D.title||h("historyModal.untitledSession")}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[D.id.substring(0,12),"..."]}),x===D.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:h("historyModal.statusActive")})]})]},D.id)),(y&&!o&&P.length===0||!y&&S.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(Sb,{size:32})}),s.jsx("div",{className:"text-[13px]",children:y?r.length>0?h("historyModal.noMatchingHistory"):Ij(h):h("historyModal.noRecentChats")})]}),y&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:Rj(h)})})]}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:s.jsx("button",{onClick:g,disabled:a||o,className:"btn btn-secondary btn-sm rounded-[10px]",children:a||o?h("historyModal.refreshing"):s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(po,{size:13})," ",y?Lj(h):h("historyModal.refreshHistory")]})})})]}),w&&s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center p-4",children:[s.jsx("div",{onClick:()=>j(null),className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true",className:"card fade-in relative w-full sm:w-[min(92vw,420px)] max-w-[420px] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-bg-primary",children:[s.jsx("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:h("historyModal.confirmSwitchTitle")}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:h("historyModal.confirmSwitchDescription",{target:w.kind==="chat"?w.title:w.session.title||h("historyModal.untitledSession")})}),w.kind==="saved"&&s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted font-mono truncate",children:[w.session.workspace||h("historyModal.workspaceUnknown"),w.session.lastMessageAt?` · ${Wd(w.session.lastMessageAt)}`:""]})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[s.jsx("button",{onClick:()=>{const D=w;j(null),D.kind==="chat"?(f(e.routeId,D.id),u()):k&&k(D.session)},className:"btn btn-primary w-full justify-center min-h-[42px]",children:h("historyModal.confirmSwitchAction")}),s.jsx("button",{onClick:()=>j(null),className:"btn btn-secondary w-full justify-center min-h-[42px]",children:h("common.cancel")})]})]})]})]});return typeof document>"u"?M:zs.createPortal(M,document.body)}const Od={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 ph({toasts:e,onDismiss:t,onClickToast:n}){const{t:a}=ke();return s.jsx("div",{className:"fixed right-4 top-[calc(env(safe-area-inset-top,0px)+64px)] z-[var(--z-toast)] flex flex-col gap-2 pointer-events-none sm:top-[calc(env(safe-area-inset-top,0px)+16px)]",children:e.map(r=>{const o=Od[r.type]||Od.info;return s.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var i;(i=r.actions)!=null&&i.length||n&&n(r)},children:[s.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${o.accent}, color-mix(in srgb, ${o.accent} 55%, transparent))`}}),s.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:i=>{i.stopPropagation(),t(r.id)},"aria-label":a("toast.dismiss"),children:s.jsx(Dt,{size:14})}),s.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[s.jsx("div",{className:"flex items-center gap-2 pr-8",children:s.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:o.chipBg,color:o.chipText,border:`1px solid color-mix(in srgb, ${o.accent} 22%, transparent)`},children:a(o.labelKey)})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:r.message}),r.actions&&r.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:r.actions.map((i,c)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:i.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:d=>{d.stopPropagation(),i.onClick(),t(r.id)},children:i.label},c))})]})]},r.id)})})}const Ej=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function _j(e){const t=e.workspace||"";if(!t)return"";const n=t.split(/[/\\]/).filter(Boolean);return n.length>0?n[n.length-1]:t}function Hj(e,t){return mh(e)||t}function mh(e){var r,o,i;const t=(o=(r=e.summaryMetadata)==null?void 0:r.items)==null?void 0:o.find(c=>(c==null?void 0:c.id)==="model"),n=((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim();if(n)return n;const a=(i=e.controlValues)==null?void 0:i.model;return typeof a=="string"&&a.trim()?a.trim():""}function $j(e){return mh(e)||void 0}function Fj(e){return e.sessionId||e.instanceId||e.agentType}function hh(e=[]){const t={};for(const n of e)n.type==="adhdev-daemon"&&(t[n.id]=ds(n,{fallbackId:n.id}));return t}function fh(e,t={}){var a;const n=e.daemonId||((a=e.id)==null?void 0:a.split(":")[0])||e.id;return{machineName:V0(e,t.machineNames),connectionState:t.connectionStates?t.connectionStates[n]||t.defaultConnectionState||"new":t.defaultConnectionState}}function ic(e,t={}){return Bj(e,fh(e,t))}function Bj(e,t={}){var f,g,k,h,b,S,x,y,C;const n=[],a=t.machineName,r=t.connectionState,o=_j(e),i=e.workspace||"",c=ek(e.type,{agentName:e.cliName}),d=bt(e)||ht(e)?c:Ot(e.type),p=Hj(e,d),u=Array.isArray(e.childSessions)?e.childSessions.map(v=>{var w,j,N;return{sessionId:v.id,instanceId:v.id,providerSessionId:v.providerSessionId,activeChatId:(w=v.activeChat)==null?void 0:w.id,transport:v.transport,sessionCapabilities:v.capabilities,agentType:v.providerType,agentName:v.providerName||Ot(v.providerType),model:$j(v),status:v.status,title:v.title,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,messages:((j=v.activeChat)==null?void 0:j.messages)||[],activeModal:((N=v.activeChat)==null?void 0:N.activeModal)||void 0,unread:v.unread,lastSeenAt:v.lastSeenAt,lastUpdated:v.lastUpdated,inboxBucket:v.inboxBucket,completionMarker:v.completionMarker,surfaceHidden:v.surfaceHidden,muted:v.muted,git:v.git,settings:v.settings,coordinator:v.coordinator,messageInput:v.messageInput}}):[],m=Ej(e);if(m){const v=e.sessionId||e.instanceId,w=(f=e.settings)==null?void 0:f.meshCoordinatorFor,j=((g=e.settings)==null?void 0:g.meshNodeFor)||!((k=e.settings)!=null&&k.meshCoordinatorFor)&&((h=e.settings)==null?void 0:h.launchedByCoordinator),N=w?" (Coordinator)":j?" (Mesh Node)":"",A=c+N,T=(b=e.activeChat)==null?void 0:b.activeModal,I=T&&Array.isArray(T.buttons)&&T.buttons.length>0,P=tk(e.activeChat,[{status:e.status,activeModal:(S=e.activeChat)==null?void 0:S.activeModal}],e.agents||[]),M=e.activeChat||{title:"",messages:[]};let E=M.title&&String(M.title).trim()?String(M.title).trim():"";const D=(x=e.activeChat)==null?void 0:x.id,W=e.chats;if(D&&Array.isArray(W)&&W.length>0){const K=W.find(z=>z.id===D||z.id&&String(z.id)===String(D));K!=null&&K.title&&String(K.title).trim()&&(E=String(K.title).trim())}const R=(bt(e)||ht(e),e.type),B=(bt(e)||ht(e))&&cd(E,A,R)?"":E,_=M.messages||[],H=typeof D=="string"?D.trim():"",L=(bt(e)||ht(e))&&H===String(e.type||"").trim(),F=H&&!L?H:e.providerSessionId,$=e.coordinator||(typeof((y=e.settings)==null?void 0:y.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:v,providerSessionId:e.providerSessionId,historySessionId:F,nativeSessionId:v,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:bt(e)&&e.mode||"chat",agentName:A,agentType:R,status:P,title:B,messages:_,resume:e.resume,hostIdeType:!bt(e)&&!ht(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||B||(bt(e)?e.mode==="chat"?A:`Terminal${N}`:A),displaySecondary:p,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,inboxBucket:e.inboxBucket,completionMarker:e.completionMarker,modalButtons:I?T.buttons:void 0,modalMessage:I?T.message:void 0,streamSource:"native",tabKey:Uo(v,e.id),machineName:a,connectionState:r,settings:e.settings,coordinator:$,messageInput:e.messageInput})}if(m&&(bt(e)||ht(e)))return n;for(const v of u){const w=v.activeModal&&Array.isArray(v.activeModal.buttons)&&v.activeModal.buttons.length>0,j=sk(v),N=Fj(v),A=`${e.id}:${N}`,T=v.title&&String(v.title).trim()||"",I=cd(T,v.agentName,v.agentType)?"":T,P=v.messages||[];if(!(v.transport==="cdp-webview"||!!v.sessionId||!!v.providerSessionId||P.length>0||w||!!I||!["idle","panel_hidden","disconnected","not_monitored"].includes(j)))continue;const E=v.coordinator||(typeof((C=v.settings)==null?void 0:C.meshCoordinatorFor)=="string"&&v.settings.meshCoordinatorFor?{meshId:v.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:v.sessionId||v.instanceId,providerSessionId:v.providerSessionId,historySessionId:v.activeChatId||v.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:v.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:v.sessionCapabilities,mode:"chat",agentName:v.agentName,agentType:v.agentType,status:j,title:I,messages:P,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:v.git||e.git,displayPrimary:o||I||v.agentName||d,displaySecondary:v.model&&v.model.trim()?v.model.trim():`${d} · ${v.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,lastUpdated:v.lastUpdated||e.lastUpdated,inboxBucket:v.inboxBucket,completionMarker:v.completionMarker,modalButtons:w?v.activeModal.buttons:void 0,modalMessage:w?v.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Uo(v.sessionId||v.instanceId,A),machineName:a,connectionState:r,settings:v.settings,coordinator:E,messageInput:v.messageInput})}return n.length===0&&n.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:c,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||d,displaySecondary:p,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:Uo(e.sessionId||e.instanceId,e.id),connectionState:r,settings:e.settings,messageInput:e.messageInput}),n}function gh(e){return String(e.type||e.id||"").trim()}function Qr(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()).map(t=>t.trim()):[]}function Wj(e,t){const n=(t||"").trim();if(!n)return[];const a=(e||[]).find(r=>r.type===n);return Qr(a==null?void 0:a.modelOptions)}function Oj(e,t){const n=(t||"").trim();if(!n)return[];const a=(e||[]).find(r=>r.type===n);return Qr(a==null?void 0:a.thinkingLevelOptions)}function bh(e){const t=new Map;for(const n of e||[])n!=null&&n.type&&t.set(n.type,{models:Qr(n.modelOptions),thinking:Qr(n.thinkingLevelOptions)});return t}function Uj(e){var t;return e.category!=="cli"||!gh(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 cn(e){var a;const t=new Set,n=[];for(const r of e||[]){if(!Uj(r))continue;const o=gh(r);if(!o||t.has(o))continue;t.add(o);const i=String(r.displayName||r.name||o),c=r.detectedPath||((a=r.lastDetection)==null?void 0:a.path)||null;n.push({type:o,label:i,icon:r.icon,statusLabel:c?`Detected at ${c}`:"Detected on this machine",detectedPath:c,...Array.isArray(r.modelOptions)&&r.modelOptions.length?{modelOptions:r.modelOptions}:{},...Array.isArray(r.thinkingLevelOptions)&&r.thinkingLevelOptions.length?{thinkingLevelOptions:r.thinkingLevelOptions}:{}})}return n}function Ya(e){const t=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],n=new Set,a=[];for(const r of t){const o=typeof r=="string"?r.trim():"";!o||n.has(o)||(n.add(o),a.push(o))}return a}function Dn(e){return e.map(t=>t.type)}function Gj(e,t){const n=Ya(e),a=t.trim();return!a||n.includes(a)?n:[...n,a]}function qj(e,t){return Ya(e).filter(n=>n!==t)}function Ud(e,t,n){const a=Ya(e),r=a.indexOf(t);if(r<0)return a;const o=a.filter(c=>c!==t);if(n==="top")return[t,...o];if(n==="bottom")return[...o,t];const i=n==="up"?Math.max(0,r-1):Math.min(o.length,r+1);return o.splice(i,0,t),o}const zj={"claude-cli":{monogram:"CL",hue:"#D97757"},"codex-cli":{monogram:"CX",hue:"#10A37F"},"gemini-cli":{monogram:"GM",hue:"#4285F4"},"kimi-cli":{monogram:"KM",hue:"#6366F1"},"antigravity-cli":{monogram:"AG",hue:"#8B5CF6"},"cursor-cli":{monogram:"CU",hue:"#64748B"},"opencode-cli":{monogram:"OC",hue:"#CA8A04"},"hermes-cli":{monogram:"HM",hue:"#14B8A6"},"grok-cli":{monogram:"GK",hue:"#475569"},antigravity:{monogram:"AG",hue:"#8B5CF6"},cursor:{monogram:"CU",hue:"#64748B"},kiro:{monogram:"KI",hue:"#F59E0B"},pearai:{monogram:"PA",hue:"#22C55E"},trae:{monogram:"TR",hue:"#EF4444"},vscode:{monogram:"VS",hue:"#3B82F6"},vscodium:{monogram:"VC",hue:"#2DD4BF"},windsurf:{monogram:"WS",hue:"#0EA5E9"},cline:{monogram:"CN",hue:"#0284C7"},"roo-code":{monogram:"RC",hue:"#F97316"}},Gd=["#0EA5E9","#8B5CF6","#10B981","#F59E0B","#EF4444","#14B8A6","#6366F1","#EC4899","#84CC16","#F97316","#06B6D4","#A855F7"];function Kj(e){let t=0;for(let n=0;n<e.length;n+=1)t=(t<<5)-t+e.charCodeAt(n)|0;return Math.abs(t)}function Vj(e){const t=e.replace(/[-_./]+/g," ").split(/\s+/).map(n=>n.trim()).filter(Boolean);return t.length===0?"?":t.length===1?t[0].slice(0,2).toUpperCase():(t[0][0]+t[1][0]).toUpperCase()}function Qa({type:e,label:t,size:n=16,className:a}){const r=(e||"").trim().toLowerCase(),o=(t==null?void 0:t.trim())||r;if(!o)return s.jsx(Rb,{size:n,className:a});const i=zj[r],c=(i==null?void 0:i.monogram)??Vj((t==null?void 0:t.trim())||r.replace(/-cli$/,"")),d=(i==null?void 0:i.hue)??Gd[Kj(r||o)%Gd.length];return s.jsx("span",{"aria-hidden":!0,className:`inline-flex shrink-0 select-none items-center justify-center font-semibold ${a??""}`,style:{width:n,height:n,borderRadius:Math.max(4,Math.round(n*.3)),backgroundColor:`${d}21`,border:`1px solid ${d}4D`,color:d,fontSize:Math.max(7,Math.round(n*.42)),letterSpacing:"0.02em",lineHeight:1},children:c})}function qd({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 Yj({value:e,availableProviders:t,onChange:n,disabled:a=!1,saveButton:r}){const{t:o}=ke("common"),[i,c]=l.useState(""),d=l.useMemo(()=>new Map(t.map(g=>[g.type,g])),[t]),p=l.useMemo(()=>Ya(e),[e]),u=p.filter(g=>!d.has(g)).length,m=t.filter(g=>!p.includes(g.type)),f=()=>{i&&(n(Gj(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),b=!!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 ${b?"bg-bg-primary":"bg-bg-primary/40"}`,children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("span",{className:"text-[10px] font-semibold text-text-muted",children:["#",k+1]}),s.jsx(Qa,{type:g,label:h==null?void 0:h.label,size:14}),s.jsx("span",{className:`font-mono text-[12px] ${b?"text-text-primary":"text-text-muted"}`,children:g}),b?s.jsx("span",{className:"rounded border border-green-500/20 bg-green-500/10 px-1.5 py-px text-[9px] font-semibold text-green-400",children:o("settings.providerPriority.available")}):s.jsx("span",{className:"rounded border border-amber-500/25 bg-amber-500/10 px-1.5 py-px text-[9px] font-semibold text-amber-400",children:o("settings.providerPriority.notOnMachine")})]}),s.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:h?`${h.label} · ${h.statusLabel}`:"Kept in order; skipped at launch until detected here."})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move up",disabled:a||k===0,title:"Move up",onClick:()=>n(Ud(p,g,"up")),children:s.jsx(qd,{direction:"up"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move down",disabled:a||k===p.length-1,title:"Move down",onClick:()=>n(Ud(p,g,"down")),children:s.jsx(qd,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:a,onClick:()=>n(qj(p,g)),children:o("settings.providerPriority.remove")})]})]},g)})}),s.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-end",children:[s.jsxs("label",{className:"flex-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"mb-1 block font-medium text-text-primary",children:o("settings.providerPriority.addCliLabel")}),s.jsxs("select",{className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-sm text-text-primary",value:i,onChange:g=>c(g.target.value),disabled:a||m.length===0,children:[s.jsx("option",{value:"",children:m.length?"Select provider…":"No additional detected CLI providers"}),m.map(g=>s.jsxs("option",{value:g.type,children:[g.label," (",g.type,")"]},g.type))]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:a||!i,onClick:f,children:o("settings.providerPriority.addProvider")}),r]}),s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:["Launches use this order, top to bottom.",u>0?` ${u} provider${u===1?"":"s"} not detected here — kept in order, skipped until available.`:""]})]})}function Qj(e){const t=e.split(":");return t.length>=3&&(t[1]==="ide"||t[1]==="cli"||t[1]==="acp")?{daemonId:t[0],targetSessionId:t.slice(2).join(":")||void 0}:{daemonId:e}}function xh(e,t){const n=Qj(e);return{daemonId:n.daemonId,payload:{...t,...n.targetSessionId&&!t.targetSessionId?{targetSessionId:n.targetSessionId}:{}}}}const vh=[{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:"🏄"}],yh=[{id:"antigravity-cli",name:"Antigravity CLI",icon:"🪐"},{id:"claude-cli",name:"Claude Code",icon:"🟠"},{id:"codex-cli",name:"Codex CLI",icon:"📦"},{id:"cursor-cli",name:"Cursor CLI",icon:"⚡"},{id:"grok-cli",name:"Grok",icon:"🛰️"},{id:"hermes-cli",name:"Hermes",icon:"⚕️"},{id:"kimi",name:"Kimi",icon:"🌙"},{id:"opencode",name:"OpenCode CLI",icon:"◆"}],wh=[{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:"🟠"}],Jj=vh,Xj=yh,Zj=wh;function e1({icon:e,title:t,subtitle:n,badge:a,actions:r,className:o}){return s.jsxs("div",{className:Pt("dashboard-header",o),children:[s.jsxs("div",{children:[s.jsxs("h1",{className:"header-title flex items-center gap-2",children:[s.jsx("span",{className:"flex items-center text-lg",children:e})," ",t,a&&s.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[a.count!==void 0?a.count:""," ",a.text]})]}),n&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:n})]}),r&&s.jsx("div",{className:"flex gap-2",children:r})]})}function Ja({icon:e,title:t,subtitle:n,badge:a,actions:r,widthClassName:o="max-w-6xl",contentClassName:i,children:c}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(e1,{icon:e,title:t,subtitle:n,badge:a,actions:r}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Pt("mx-auto flex w-full flex-col gap-4",o,i),children:c})})]})}const dl="adhdev:themechange";function t1(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function zn(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Kn(e){return e==="system"?t1():e}function kh(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Mr(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(dl,{detail:{preference:e,theme:t}}))}function s1(){const e=zn(),t=Kn(e);kh(t),Mr(e,t)}function Rs(){const[e,t]=l.useState(zn),[n,a]=l.useState(()=>Kn(zn()));l.useEffect(()=>{kh(n)},[n]),l.useEffect(()=>{const i=window.matchMedia("(prefers-color-scheme: light)"),c=d=>{if(e==="system"){const p=d.matches?"light":"dark";a(p),Mr("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:zn()),a(m==="dark"||m==="light"?m:Kn(zn()))},c=d=>{if(d.key!=="theme")return;const p=zn(),u=Kn(p);t(p),a(u)};return window.addEventListener(dl,i),window.addEventListener("storage",c),()=>{window.removeEventListener(dl,i),window.removeEventListener("storage",c)}},[]);const r=l.useCallback(i=>{const c=Kn(i);t(i),a(c);try{localStorage.setItem("theme",i)}catch{}Mr(i,c)},[]),o=l.useCallback(()=>{t(i=>{const c=i==="dark"?"light":i==="light"?"system":"dark",d=Kn(c);a(d);try{localStorage.setItem("theme",c)}catch{}return Mr(c,d),c})},[]);return{theme:n,preference:e,setPreference:r,cycleTheme:o,isDark:n==="dark"}}const zd={dark:"Dark",light:"Light",system:"System"};function n1({collapsed:e}){const{preference:t,cycleTheme:n}=Rs(),a=t==="dark"?s.jsx(Rp,{size:16}):t==="light"?s.jsx(Lp,{size:16}):s.jsx(Ep,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:n,title:`Theme: ${zd[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:a}),!e&&s.jsx("span",{className:"text-xs",children:zd[t]})]})}const ul="adhdev:langchange";function a1(){const e=wt.language;return Yn(e)?e:nm()}function r1(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(ul,{detail:{language:e}}))}function o1(){const[e,t]=l.useState(a1);l.useEffect(()=>{const a=i=>{Yn(i)&&t(i)},r=i=>{const c=i.detail||{};Yn(c.language)&&t(c.language)},o=i=>{if(i.key!==Yi)return;const c=i.newValue;Yn(c)&&c!==wt.language&&(wt.changeLanguage(c),Qi(c))};return wt.on("languageChanged",a),window.addEventListener(ul,r),window.addEventListener("storage",o),()=>{wt.off("languageChanged",a),window.removeEventListener(ul,r),window.removeEventListener("storage",o)}},[]);const n=l.useCallback(a=>{if(Yn(a)){t(a);try{localStorage.setItem(Yi,a)}catch{}wt.changeLanguage(a),Qi(a),r1(a)}},[]);return{language:e,setLanguage:n}}function i1({trigger:e,viewport:t,menu:n,variant:a,gap:r=6,margin:o=8}){const i=e.top-o,c=t.height-e.bottom-o,d=a==="sidebar";let p=d;d&&i<n.height&&c>i&&(p=!1),!d&&c<n.height&&i>c&&(p=!0);const u=p?i:c,m=Math.max(80,Math.min(n.height,u));let f;p?f=e.top-r-m:f=e.bottom+r,f=Kd(f,o,Math.max(o,t.height-m-o));const g=Kd(e.left,o,Math.max(o,t.width-n.width-o));return{top:f,left:g,maxHeight:m}}function Kd(e,t,n){return Math.min(Math.max(e,t),n)}function l1({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 c1({collapsed:e,variant:t="sidebar"}){const{language:n,setLanguage:a}=o1(),{t:r}=ke("common"),[o,i]=l.useState(!1),[c,d]=l.useState(0),p=l.useRef(null),u=l.useRef(null),m=l.useRef(null),f=l.useId(),[g,k]=l.useState(null),h=l.useCallback(()=>{const P=u.current;if(!P)return;const M=P.getBoundingClientRect(),E=m.current,D=Math.max((E==null?void 0:E.offsetWidth)??0,168),W=(E==null?void 0:E.scrollHeight)??pn.length*36+12;k(i1({trigger:{top:M.top,left:M.left,right:M.right,bottom:M.bottom,width:M.width,height:M.height},viewport:{width:window.innerWidth,height:window.innerHeight},menu:{width:D,height:W},variant:t}))},[t]),b=Math.max(0,pn.findIndex(P=>P.code===n)),S=pn[b]??pn[0],x=r("language.label",{defaultValue:"Language"}),y=r("language.select",{defaultValue:"Select language"}),C=P=>`${f}-opt-${P}`,v=l.useCallback(()=>{d(b),i(!0)},[b]),w=l.useCallback((P=!0)=>{var M;i(!1),P&&((M=u.current)==null||M.focus())},[]),j=l.useCallback(P=>{const M=pn[P];M&&a(M.code),w()},[a,w]);l.useEffect(()=>{if(!o)return;const P=D=>{var W,R;return!!((W=p.current)!=null&&W.contains(D)||(R=m.current)!=null&&R.contains(D))},M=D=>{P(D.target)||i(!1)},E=D=>{P(D.target)||i(!1)};return document.addEventListener("pointerdown",M,!0),document.addEventListener("focusin",E,!0),()=>{document.removeEventListener("pointerdown",M,!0),document.removeEventListener("focusin",E,!0)}},[o]),l.useLayoutEffect(()=>{if(!o){k(null);return}h();const P=()=>h();return window.addEventListener("resize",P),window.addEventListener("scroll",P,!0),()=>{window.removeEventListener("resize",P),window.removeEventListener("scroll",P,!0)}},[o,h]),l.useEffect(()=>{var P;o&&g&&((P=m.current)==null||P.focus())},[o,g]);const N=P=>{const M=pn.length-1;switch(P.key){case"ArrowDown":P.preventDefault(),d(E=>E>=M?0:E+1);break;case"ArrowUp":P.preventDefault(),d(E=>E<=0?M:E-1);break;case"Home":P.preventDefault(),d(0);break;case"End":P.preventDefault(),d(M);break;case"Enter":case" ":P.preventDefault(),j(c);break;case"Escape":P.preventDefault(),w();break;case"Tab":i(!1);break}},A=P=>{o||(P.key==="ArrowDown"||P.key==="ArrowUp"||P.key==="Enter"||P.key===" ")&&(P.preventDefault(),v())},T=t==="landing"?"lang-switch-trigger lang-switch-trigger--landing":`lang-switch-trigger lang-switch-trigger--sidebar nav-item cursor-pointer${e?" justify-center py-2.5 px-0":""}`,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":`${x}: ${S.label}`,title:`${x}: ${S.label}`,onClick:()=>o?w(!1):v(),onKeyDown:A,children:[s.jsx("span",{className:"nav-icon lang-switch-icon",children:s.jsx(_p,{size:16})}),I&&s.jsx("span",{className:"lang-switch-label text-xs",children:S.label}),I&&s.jsx(l1,{open:o})]}),o&&typeof document<"u"&&zs.createPortal(s.jsx("ul",{ref:m,role:"listbox",tabIndex:-1,"aria-label":y,"aria-activedescendant":C(c),className:`lang-switch-menu lang-switch-menu--${t}`,style:{position:"fixed",top:(g==null?void 0:g.top)??0,left:(g==null?void 0:g.left)??0,maxHeight:g==null?void 0:g.maxHeight,overflowY:"auto",visibility:g?"visible":"hidden"},onKeyDown:N,children:pn.map((P,M)=>{const E=P.code===S.code,D=M===c;return s.jsxs("li",{id:C(M),role:"option","aria-selected":E,className:`lang-switch-option${D?" is-active":""}${E?" is-selected":""}`,onMouseEnter:()=>d(M),onClick:()=>j(M),children:[s.jsx("span",{className:"lang-switch-check","aria-hidden":"true",children:E?s.jsx(co,{size:14}):null}),s.jsx("span",{className:"lang-switch-option-label",children:P.label})]},P.code)})}),document.body)]})}const d1=[],u1=[];function Xo(e,t){return e?typeof e=="function"?e(t):e:null}const p1=l.memo(function({renderState:t,brand:n,navItems:a,sidebarSections:r,footerItems:o,footerInfo:i,footerActions:c,closeMobileMenu:d}){const{t:p}=ke("common"),{collapsed:u,mobileMenuOpen:m}=t,f=k=>`nav-item${k.active?" active":""} cursor-pointer ${u?"justify-center py-2.5 px-0":""}${k.className?` ${k.className}`:""}`,g=k=>s.jsxs("div",{className:f(k),id:`nav-${k.id}`,onClick:()=>{k.onSelect(),d()},title:u?k.title??(typeof k.label=="string"?k.label:void 0):k.title,children:[s.jsx("span",{className:"nav-icon",children:k.icon}),!u&&k.label]},k.id);return s.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${u?"justify-center gap-0":""}`,children:Xo(n,t)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":p("app.closeMenu"),onClick:d,children:s.jsx(Dt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:a.map(g)}),r.map(k=>s.jsxs("div",{className:k.className??"border-t border-border-subtle pt-2 mt-2",children:[!u&&k.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:k.title}):null,k.items.map(g)]},k.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[o.map(g),Xo(i,t),s.jsx(n1,{collapsed:u}),s.jsx(c1,{collapsed:u}),Xo(c,t)]})]})});function m1({children:e,brand:t,navItems:n,sidebarSections:a=d1,footerItems:r=u1,footerInfo:o,footerActions:i,preMainContent:c,collapsedStorageKey:d="sidebar-collapsed"}){const{t:p}=ke("common"),[u,m]=l.useState(!1),[f,g]=l.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),k=l.useCallback(()=>m(!0),[]),h=l.useCallback(()=>m(!1),[]),b=l.useCallback(()=>{g(x=>{const y=!x;try{localStorage.setItem(d,y?"1":"0")}catch{}return y})},[d]),S=l.useMemo(()=>({collapsed:f,mobileMenuOpen:u,openMobileMenu:k,closeMobileMenu:h,toggleCollapsed:b}),[f,u,k,h,b]);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:x=>x.key==="Escape"&&h()}),s.jsx(p1,{renderState:S,brand:t,navItems:n,sidebarSections:a,footerItems:r,footerInfo:o,footerActions:i,closeMobileMenu:h}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function xt({title:e,icon:t,description:n,accentColor:a,className:r,collapsible:o,defaultOpen:i=!0,badge:c,children:d}){const[p,u]=l.useState(i),m=o?p:!0,f=(e||n)&&s.jsxs("div",{className:Pt("flex items-start justify-between gap-3",m&&"mb-4"),children:[s.jsxs("div",{className:"min-w-0",children:[e&&s.jsxs("h3",{className:"text-base font-semibold text-text-primary flex items-center gap-1.5",children:[t&&s.jsx("span",{children:t}),s.jsx("span",{children:e}),c]}),n&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:n})]}),o&&s.jsx("span",{className:Pt("mt-0.5 shrink-0 text-text-muted transition-transform select-none",m?"rotate-90":"rotate-0"),"aria-hidden":!0,children:"▸"})]});return s.jsxs("div",{className:Pt("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",a&&"border-l-[3px]",r),style:a?{borderLeftColor:a}:void 0,children:[o&&f?s.jsx("button",{type:"button",className:"w-full bg-transparent border-none p-0 text-left cursor-pointer",onClick:()=>u(g=>!g),"aria-expanded":m,children:f}):f,m&&d]})}function Xa({icon:e,title:t,description:n,action:a,className:r}){return s.jsxs("div",{className:Pt("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",r),children:[s.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),s.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:t}),s.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:n}),a]})}const h1={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"},f1={error:Ls,warning:Ls,success:Ga,info:uo};function Mt({variant:e,children:t,onDismiss:n,className:a}){return s.jsxs("div",{className:Pt("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",h1[e],a),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[(()=>{const r=f1[e];return s.jsx(r,{size:14})})(),s.jsx("span",{children:t})]}),n&&s.jsx("button",{onClick:n,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}function Tt({label:e,hint:t,children:n,className:a}){return s.jsxs("div",{className:Pt("mb-5",a),children:[s.jsx("label",{className:"block text-xs font-semibold text-text-muted uppercase tracking-wider mb-2",children:e}),n,t&&s.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:t})]})}function xs(e){const{className:t,...n}=e;return s.jsx("input",{...n,className:Pt("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none","focus:border-accent transition-colors",t)})}const g1={primary:"btn-primary",secondary:"btn-secondary",warning:"btn-warning",danger:"btn-danger",ghost:"btn-ghost"},Gs=l.forwardRef(function({variant:t="secondary",size:n="md",type:a,className:r,...o},i){return s.jsx("button",{ref:i,type:a??"button",className:Pt("btn",g1[t],n==="sm"&&"btn-sm",r),...o})}),b1=l.forwardRef(function({options:t,children:n,className:a,...r},o){return s.jsx("select",{ref:o,className:Pt("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none cursor-pointer","focus:border-accent transition-colors",a),...r,children:n??(t==null?void 0:t.map(i=>s.jsx("option",{value:i.value,disabled:i.disabled,children:i.label},i.value)))})}),x1={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"},v1={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function y1({status:e,label:t,className:n}){const a=t||e;return s.jsxs("span",{className:Pt("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",x1[e],n),children:[s.jsx("span",{className:Pt("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",v1[e])}),a]})}function w1({tabs:e,defaultTabKey:t,activeKey:n,onTabChange:a,variant:r="pill",ariaLabel:o,className:i,tabListClassName:c,panelClassName:d,tabIdPrefix:p,unmountInactivePanels:u=!1}){var S;const[m,f]=l.useState(t??((S=e[0])==null?void 0:S.key)),g=n!==void 0,k=g?n:m,h=x=>{g||f(x),a==null||a(x)},b=r==="underline";return s.jsxs("div",{className:i,children:[s.jsx("div",{className:Pt(b?"flex shrink-0 items-center gap-1 border-b border-border-subtle px-4 md:px-6":"mb-5 inline-flex w-full flex-wrap items-center gap-1 rounded-xl border border-border-subtle bg-bg-secondary/60 p-1 sm:w-fit",c),role:"tablist","aria-label":o,children:e.map(x=>{const y=x.key===k;return s.jsxs("button",{id:p?`${p}-${x.key}`:void 0,type:"button",role:"tab","aria-selected":y,className:Pt(b?["-mb-px flex cursor-pointer items-center gap-1.5 border-b-2 px-3 py-2.5 text-[13px] font-medium transition-colors",y?"border-accent text-accent":"border-transparent text-text-muted hover:text-text-secondary"]:["flex flex-1 items-center justify-center gap-1.5 rounded-lg px-3.5 py-1.5 text-[13px] font-medium transition-colors sm:flex-none",y?"bg-bg-card text-text-primary shadow-sm border border-border-default":"text-text-muted border border-transparent hover:text-text-secondary hover:bg-white/[0.03]"]),onClick:()=>h(x.key),children:[x.icon,x.label]},x.key)})}),e.map(x=>{const y=x.key===k;return u&&!y?null:s.jsx("div",{className:y?Pt("flex flex-col gap-4",d):"hidden",children:x.content},x.key)})]})}function xn({label:e,description:t,checked:n,disabled:a,onChange:r,extra:o}){return s.jsxs("div",{className:`flex justify-between items-center ${a?"opacity-60":""}`,children:[s.jsxs("div",{className:"pr-4",children:[s.jsx("div",{className:"font-medium text-sm",children:e}),s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:t})]}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[o,s.jsxs("button",{type:"button",role:"switch","aria-checked":n,"aria-disabled":a,disabled:a,onClick:()=>r(!n),className:`relative inline-flex items-center ${a?"cursor-not-allowed":"cursor-pointer"}`,children:[s.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:n?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),s.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${n?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function k1({onPrefChange:e}){const{t}=ke("common"),[n,a]=pk(),[r,o]=l.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);l.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){o("unsupported");return}o(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,d)=>{a({[c]:d}),e==null||e(c,d)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(xn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(la,{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(xn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(us,{size:15})," ",t("notifications.browserNotificationsLabel")]}),description:t("notifications.browserNotificationsDesc"),checked:n.browserNotifications,onChange:c=>i("browserNotifications",c)}),n.globalEnabled&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:t("notifications.standaloneBackgroundInfo")}),r==="default"&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-status-warning",children:[s.jsx("span",{children:t("notifications.standalonePermissionDefault")}),s.jsx("button",{onClick:()=>{gm().then(o)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:t("notifications.allowNotifications")})]}),r==="denied"&&s.jsx("div",{className:"text-[11px] text-status-warning",children:t("notifications.permissionDenied")}),r==="unsupported"&&s.jsx("div",{className:"text-[11px] text-status-warning",children:t("notifications.standalonePermissionUnsupported")})]}),n.globalEnabled&&n.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(xn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ga,{size:15})," ",t("notifications.completionAlertsLabel")]}),description:t("notifications.completionAlertsDesc"),checked:n.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(xn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Cb,{size:15})," ",t("notifications.approvalAlertsLabel")]}),description:t("notifications.approvalAlertsDesc"),checked:n.approvalAlert,onChange:c=>i("approvalAlert",c)}),s.jsx(xn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(_a,{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 Jr(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/);if(!t)return null;const n=t[4]??null;let a=null;if(n){const r=n.match(/(?:^|\.)(\d+)$/);a=r?Number(r[1]):null}return{base:[Number(t[1]),Number(t[2]),Number(t[3])],prereleaseNumber:a,isPrerelease:n!==null}}function Vd(e){var t;return((t=Jr(e))==null?void 0:t.base)??null}function Sh(e,t){const n=Jr(e),a=Jr(t);if(!n||!a)return e!==t;for(let r=0;r<3;r+=1){if(n.base[r]<a.base[r])return!0;if(n.base[r]>a.base[r])return!1}return n.isPrerelease&&a.isPrerelease?n.prereleaseNumber===null||a.prereleaseNumber===null?!1:n.prereleaseNumber<a.prereleaseNumber:!1}function jo(e,t){const n=e.version||null;return!n||!t||e.versionMismatch===!0&&!Jr(t)?!1:Sh(n,t)}function Da(e,t){if(e.versionUpdateRequired===!0)return!0;const n=e.version||null;if(!n||!t||!Sh(n,t))return!1;const a=Vd(n),r=Vd(t);return!a||!r?!1:a[0]!==r[0]||a[1]!==r[1]}function Zo(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 S1(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 ja(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function lc(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},n=Zo(t.channel)||Zo(e.updateChannel)||Zo(e.releaseChannel)||void 0,a=S1(t.npmTag)||(n==="preview"?"next":n==="stable"?"latest":void 0),r=ja(t.targetVersion)||ja(e.serverVersion)||void 0,o=ja(t.minVersion)||void 0,i=ja(t.updateCommand)||(n?"adhdev update":void 0);return{...n?{channel:n}:{},...a?{npmTag:a}:{},...r?{targetVersion:r}:{},...o?{minVersion:o}:{},...i?{updateCommand:i}:{}}}function Js(e,t=null){return lc(e).targetVersion||t}function C1(e){return lc(e).channel||null}function No(e){return!e||!lc(e).channel?null:{}}function Ch(e,t={}){const n=ja(t.targetVersion);return n?`Update to v${n}`:t.fallback||(t.required?"Update now":"Upgrade")}const jh="Cannot update: node update policy unavailable; refresh and try again";async function j1(e,t,n){var r,o,i,c,d,p;const a=No(n);if(!a)return{state:"error",message:jh};try{const u=await e(t,"daemon_upgrade",a);return(r=u==null?void 0:u.result)!=null&&r.alreadyLatest?{state:"done",message:`Already on v${((o=u==null?void 0:u.result)==null?void 0:o.version)||"latest"}.`}:(i=u==null?void 0:u.result)!=null&&i.upgraded||(c=u==null?void 0:u.result)!=null&&c.success?{state:"done",message:`Upgrade to v${((d=u==null?void 0:u.result)==null?void 0:d.version)||"latest"} started. Daemon is restarting…`}:{state:"error",message:((p=u==null?void 0:u.result)==null?void 0:p.error)||"Upgrade failed"}}catch(u){return{state:"error",message:u instanceof Error?u.message:"Upgrade failed"}}}function N1(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function ei(e,t){return e instanceof Error?e.message:t}function A1({ides:e,emptyMessage:t,sendDaemonCommand:n,onDisconnect:a,onRevokeToken:r}){const{t:o}=ke("common"),i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?s.jsx(Xa,{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(M1,{ide:c,allIdes:e,sendDaemonCommand:n,onDisconnect:a,onRevokeToken:r},c.id))})}function Yd({title:e,message:t,confirmLabel:n,confirmColor:a,onConfirm:r,onCancel:o}){const{t:i}=ke("common"),c=a==="red"?"bg-status-error/20 text-status-error border-status-error/40 hover:bg-status-error/30":"";return zs.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:"var(--z-modal)"},onClick:o,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:d=>d.stopPropagation(),children:[s.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),s.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:t}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.jsx("button",{onClick:o,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:i("common.cancel")}),s.jsx("button",{onClick:r,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,style:a==="amber"?{background:"color-mix(in srgb, var(--status-warning) 20%, transparent)",color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"}:void 0,children:n})]})]})}),document.body)}function T1(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),a=[...Jj,...Xj,...Zj].find(r=>r.id===t||t.includes(r.id)||r.id.includes(t));return a?{icon:a.icon,name:a.name}:{icon:"",name:e}}function M1({ide:e,allIdes:t,sendDaemonCommand:n,onDisconnect:a,onRevokeToken:r}){var D,W;const{t:o}=ke("common"),[i,c]=l.useState("idle"),[d,p]=l.useState(""),[u,m]=l.useState(null),[f,g]=l.useState("idle"),[k,h]=l.useState(""),b=e.version||null,S=((D=e.machine)==null?void 0:D.platform)||((W=e.system)==null?void 0:W.platform)||"",x=ds(e,{fallbackId:e.id}),y=t.filter(R=>R.daemonId===e.id&&R.transport==="cdp-page"),C=t.filter(R=>R.daemonId===e.id&&R.transport==="pty"),v=t.filter(R=>R.daemonId===e.id&&R.transport==="acp"),w=e.p2p,j=async()=>{if(!n)return;const R=No(e);if(!R){c("error"),p(jh);return}c("upgrading"),p(o("machine.connectedMachines.startingUpgrade"));try{const B=N1(await n(e.id,"daemon_upgrade",R));B.alreadyLatest?(c("done"),p(`Already on v${B.version||"latest"}.`)):B.upgraded||B.success?(c("done"),p(`Upgrade to v${B.version||"latest"} started. Daemon is restarting...`)):(c("error"),p(B.error||"Upgrade failed"))}catch(B){c("error"),p(ei(B,"Connection lost during upgrade"))}},N=async()=>{if(m(null),!!a){g("loading");try{await a(e.id),g("done"),h(o("machine.connectedMachines.machineDisconnected"))}catch(R){g("error"),h(ei(R,o("machine.connectedMachines.failedToDisconnect")))}}},A=async()=>{if(m(null),!!r){g("loading");try{await r(e.id),g("done"),h(o("machine.connectedMachines.tokenRevoked"))}catch(R){g("error"),h(ei(R,o("machine.connectedMachines.failedToRevokeToken")))}}},T="1.0.56",I=Js(e,T),P=jo(e,I),M=Da(e,I),E=y.length+C.length+v.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-text-muted",title:S,children:s.jsx(us,{size:18})}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:x}),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),"…"]}),b&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${P?"":"bg-bg-secondary"}`,style:P?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",b,!P&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[n&&P&&s.jsx("button",{onClick:j,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${T}`,children:i==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(ls,{size:12,thickness:2})," ",o("machine.connectedMachines.upgrading")]}):i==="done"?o("machine.connectedMachines.updated"):M?o("machine.connectedMachines.updateNow"):o("machine.connectedMachines.updateTo",{version:T})}),a&&s.jsx("button",{onClick:()=>m("disconnect"),disabled:f==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:o("machine.connectedMachines.disconnect")}),r&&s.jsx("button",{onClick:()=>m("revoke"),disabled:f==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:o("machine.connectedMachines.remove")}),s.jsx(y1,{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:[w&&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 ${w.state==="connected"?"bg-status-online":"bg-text-muted/30"} ${w.state==="connecting"||w.state==="new"?"animate-pulse":""}`,style:w.state==="connecting"||w.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",w.state==="connected"?"connected":w.state==="connecting"||w.state==="new"?o("machine.connectedMachines.connecting"):w.state||"off"]}),w.peers!==void 0&&w.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",w.peers," peer",w.peers!==1?"s":"",")"]})]}),w&&E>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),E>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[y.map(R=>{const B=T1(R.type),_=R.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx(Qa,{type:R.type,label:B.name,size:13}),s.jsx("span",{children:B.name}),_!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${_?"bg-status-online":"animate-pulse"}`,style:_?void 0:{background:"var(--status-warning)"},title:o(_?"machine.connectedMachines.cdpConnected":"machine.connectedMachines.cdpConnecting")})]},R.id)}),C.map(R=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"⌨️"}),s.jsx("span",{children:R.cliName||"CLI"})]},R.id)),v.map(R=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{className:"inline-flex",children:s.jsx(Ib,{size:12})}),s.jsx("span",{children:R.cliName||"ACP"})]},R.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:o("machine.connectedMachines.noIdesConnected")})]}),(d||k)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||f==="error"?"text-status-error":i==="done"||f==="done"?"text-status-online":"text-text-muted"}`,children:k||d})]}),u==="disconnect"&&s.jsx(Yd,{title:o("machine.connectedMachines.disconnectTitle"),message:`Disconnect "${x}" from ADHDev?
|
|
53
|
+
`).includes(r)))}function Aj(e,t="recent"){const n=e.slice();return n.sort((a,r)=>{if(t==="oldest")return(Number(a.lastMessageAt)||0)-(Number(r.lastMessageAt)||0);if(t==="messages"){const o=(Number(r.messageCount)||0)-(Number(a.messageCount)||0);if(o!==0)return o}return(Number(r.lastMessageAt)||0)-(Number(a.lastMessageAt)||0)}),n}function ih(e,t={}){return Aj(Nj(e,t),t.sortMode||"recent")}function cl(e,t){return typeof e=="function"?e(t??!1?"launch.resumeSavedHistory":"launch.startFresh"):e?"Resume saved history":"Start fresh"}function lh(e,t){return typeof e=="function"?e(t??!1?"launch.resumingSavedHistory":"launch.startingFresh"):e?"Resuming saved history…":"Starting fresh…"}function Tj(e){return e?e("launch.startFresh"):"Start fresh"}function Mj(e){return e?e("launch.hostedRuntimeRecoveryDescription"):"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Pj(e){return e?e("launch.openSavedHistory"):"Open saved history"}function Dj(e){return e?e("launch.savedHistoryTitle"):"Saved History"}function oc(e){return e?e("launch.savedHistoryHelper"):"Use saved history when you want continuity in the same provider conversation."}function Ij(e){return e?e("launch.savedHistoryEmpty"):"No saved history found yet."}function Lj(e){return e?e("launch.refreshSavedHistory"):"Refresh saved history"}function Rj(e){return e?e("launch.refreshingSavedHistory"):"Refreshing saved history…"}function zr(e,t,n){if(typeof e=="function"){const o=t,i=n;return o==="start-fresh"?e("launch.startFreshWith",{label:i}):e("launch.restart",{label:i})}const a=e,r=t;return a==="start-fresh"?`Start fresh with ${r}?`:`Restart ${r}?`}function Kr(e,t){if(typeof e=="function"){const a=t;return e(a==="start-fresh"?"launch.startFreshReview":a==="restart-ide"?"launch.restartIdeReview":"launch.restartStoppedReview")}const n=e;return n==="start-fresh"?"Review the provider and target folder before starting fresh.":n==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function Vr(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartFresh":"launch.confirmRestart"):e==="start-fresh"?"Start fresh":"Restart"}function Yr(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartingFresh":"launch.confirmRestarting"):e==="start-fresh"?"Starting fresh…":"Restarting…"}function ch(e,t){return typeof e=="function"?e("launch.resumeWith",{label:t}):`Resume saved history with ${e}?`}function dh(e){return e?e("launch.resumeReview"):"Review or change the target workspace before resuming saved history."}function Wd(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 uh({activeConv:e,ides:t,isCreatingChat:n,isRefreshingHistory:a,savedSessions:r=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:c,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:p,onClose:u,onNewChat:m,onSwitchSession:f,onRefreshHistory:g,onResumeSavedSession:k}){var E;const{t:h}=ke("common"),b=t.find(D=>D.id===e.routeId),S=(b==null?void 0:b.chats)||[],x=(E=b==null?void 0:b.activeChat)==null?void 0:E.id,y=bt(e)&&!ht(e),[C,v]=l.useState(()=>qt()),[w,j]=l.useState(null),N=c||C,A=String(d||"").trim(),T=D=>{if(p){p(D);return}v(D)},I=l.useMemo(()=>r.map(D=>{const W=String(D.workspace||"").trim();return D.canResume||W||!A?D:{...D,workspace:A,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[A,r]),P=l.useMemo(()=>ih(I,{textQuery:N.textQuery,workspaceQuery:N.workspaceQuery,modelQuery:N.modelQuery,resumableOnly:N.resumableOnly,sortMode:N.sortMode}),[I,N.modelQuery,N.resumableOnly,N.sortMode,N.textQuery,N.workspaceQuery]),M=s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:u,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:y?Dj(h):h("historyModal.chatHistory")}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:XC(e)}),y&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:oc(h)})]}),s.jsx("button",{onClick:u,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(Dt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!y&&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")}),y?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[s.jsx("input",{type:"text",value:N.textQuery,onChange:D=>T({...N,textQuery:D.target.value}),placeholder:h("historyModal.searchPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:N.workspaceQuery,onChange:D=>T({...N,workspaceQuery:D.target.value}),placeholder:h("historyModal.filterWorkspace"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:N.modelQuery,onChange:D=>T({...N,modelQuery:D.target.value}),placeholder:h("historyModal.filterModel"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsxs("select",{value:N.sortMode,onChange:D=>T({...N,sortMode:D.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:h("historyModal.sortRecent")}),s.jsx("option",{value:"oldest",children:h("historyModal.sortOldest")}),s.jsx("option",{value:"messages",children:h("historyModal.sortMessages")})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:N.resumableOnly,onChange:D=>T({...N,resumableOnly:D.target.checked})}),h("historyModal.resumeReadyOnly")]})]}),P.map(D=>{const W=e.providerSessionId===D.providerSessionId,R=W||!D.canResume||!!i,B=D.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{R||!k||j({kind:"saved",session:D})},disabled:R,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${W?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${R?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${W?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:D.title||h("historyModal.untitledSession")}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:D.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Wd(D.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:D.preview||h("historyModal.noSavedPreview")}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[D.workspace||h("historyModal.workspaceUnknown"),B?h("historyModal.selectedWorkspaceSuffix"):"",Mn(D.summaryMetadata)?` · ${Mn(D.summaryMetadata)}`:"",D.messageCount>0?` · ${h("historyModal.msgCount",{count:D.messageCount})}`:""]}),s.jsx("div",{className:"shrink-0",children:W?h("historyModal.statusActive"):D.canResume?B?h("historyModal.statusResumeSelectedWorkspace"):i===D.providerSessionId?h("historyModal.statusResuming"):h("historyModal.statusResume"):h("historyModal.statusMissingWorkspace")})]})]},D.id)})]}):S.map(D=>s.jsxs("div",{onClick:()=>{D.id!==x&&j({kind:"chat",id:D.id,title:D.title||h("historyModal.untitledSession")})},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${x===D.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[s.jsx("div",{className:`font-bold text-sm mb-1 ${x===D.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:D.title||h("historyModal.untitledSession")}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[D.id.substring(0,12),"..."]}),x===D.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:h("historyModal.statusActive")})]})]},D.id)),(y&&!o&&P.length===0||!y&&S.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(Sb,{size:32})}),s.jsx("div",{className:"text-[13px]",children:y?r.length>0?h("historyModal.noMatchingHistory"):Ij(h):h("historyModal.noRecentChats")})]}),y&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:Rj(h)})})]}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:s.jsx("button",{onClick:g,disabled:a||o,className:"btn btn-secondary btn-sm rounded-[10px]",children:a||o?h("historyModal.refreshing"):s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(po,{size:13})," ",y?Lj(h):h("historyModal.refreshHistory")]})})})]}),w&&s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center p-4",children:[s.jsx("div",{onClick:()=>j(null),className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true",className:"card fade-in relative w-full sm:w-[min(92vw,420px)] max-w-[420px] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-bg-primary",children:[s.jsx("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:h("historyModal.confirmSwitchTitle")}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:h("historyModal.confirmSwitchDescription",{target:w.kind==="chat"?w.title:w.session.title||h("historyModal.untitledSession")})}),w.kind==="saved"&&s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted font-mono truncate",children:[w.session.workspace||h("historyModal.workspaceUnknown"),w.session.lastMessageAt?` · ${Wd(w.session.lastMessageAt)}`:""]})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[s.jsx("button",{onClick:()=>{const D=w;j(null),D.kind==="chat"?(f(e.routeId,D.id),u()):k&&k(D.session)},className:"btn btn-primary w-full justify-center min-h-[42px]",children:h("historyModal.confirmSwitchAction")}),s.jsx("button",{onClick:()=>j(null),className:"btn btn-secondary w-full justify-center min-h-[42px]",children:h("common.cancel")})]})]})]})]});return typeof document>"u"?M:zs.createPortal(M,document.body)}const Od={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 ph({toasts:e,onDismiss:t,onClickToast:n}){const{t:a}=ke();return s.jsx("div",{className:"fixed right-4 top-[calc(env(safe-area-inset-top,0px)+64px)] z-[var(--z-toast)] flex flex-col gap-2 pointer-events-none sm:top-[calc(env(safe-area-inset-top,0px)+16px)]",children:e.map(r=>{const o=Od[r.type]||Od.info;return s.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var i;(i=r.actions)!=null&&i.length||n&&n(r)},children:[s.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${o.accent}, color-mix(in srgb, ${o.accent} 55%, transparent))`}}),s.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:i=>{i.stopPropagation(),t(r.id)},"aria-label":a("toast.dismiss"),children:s.jsx(Dt,{size:14})}),s.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[s.jsx("div",{className:"flex items-center gap-2 pr-8",children:s.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:o.chipBg,color:o.chipText,border:`1px solid color-mix(in srgb, ${o.accent} 22%, transparent)`},children:a(o.labelKey)})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:r.message}),r.actions&&r.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:r.actions.map((i,c)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:i.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:d=>{d.stopPropagation(),i.onClick(),t(r.id)},children:i.label},c))})]})]},r.id)})})}const Ej=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function _j(e){const t=e.workspace||"";if(!t)return"";const n=t.split(/[/\\]/).filter(Boolean);return n.length>0?n[n.length-1]:t}function Hj(e,t){return mh(e)||t}function mh(e){var r,o,i;const t=(o=(r=e.summaryMetadata)==null?void 0:r.items)==null?void 0:o.find(c=>(c==null?void 0:c.id)==="model"),n=((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim();if(n)return n;const a=(i=e.controlValues)==null?void 0:i.model;return typeof a=="string"&&a.trim()?a.trim():""}function $j(e){return mh(e)||void 0}function Fj(e){return e.sessionId||e.instanceId||e.agentType}function hh(e=[]){const t={};for(const n of e)n.type==="adhdev-daemon"&&(t[n.id]=ds(n,{fallbackId:n.id}));return t}function fh(e,t={}){var a;const n=e.daemonId||((a=e.id)==null?void 0:a.split(":")[0])||e.id;return{machineName:V0(e,t.machineNames),connectionState:t.connectionStates?t.connectionStates[n]||t.defaultConnectionState||"new":t.defaultConnectionState}}function ic(e,t={}){return Bj(e,fh(e,t))}function Bj(e,t={}){var f,g,k,h,b,S,x,y,C;const n=[],a=t.machineName,r=t.connectionState,o=_j(e),i=e.workspace||"",c=ek(e.type,{agentName:e.cliName}),d=bt(e)||ht(e)?c:Ot(e.type),p=Hj(e,d),u=Array.isArray(e.childSessions)?e.childSessions.map(v=>{var w,j,N;return{sessionId:v.id,instanceId:v.id,providerSessionId:v.providerSessionId,activeChatId:(w=v.activeChat)==null?void 0:w.id,transport:v.transport,sessionCapabilities:v.capabilities,agentType:v.providerType,agentName:v.providerName||Ot(v.providerType),model:$j(v),status:v.status,title:v.title,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,messages:((j=v.activeChat)==null?void 0:j.messages)||[],activeModal:((N=v.activeChat)==null?void 0:N.activeModal)||void 0,unread:v.unread,lastSeenAt:v.lastSeenAt,lastUpdated:v.lastUpdated,inboxBucket:v.inboxBucket,completionMarker:v.completionMarker,surfaceHidden:v.surfaceHidden,muted:v.muted,git:v.git,settings:v.settings,coordinator:v.coordinator,messageInput:v.messageInput}}):[],m=Ej(e);if(m){const v=e.sessionId||e.instanceId,w=(f=e.settings)==null?void 0:f.meshCoordinatorFor,j=((g=e.settings)==null?void 0:g.meshNodeFor)||!((k=e.settings)!=null&&k.meshCoordinatorFor)&&((h=e.settings)==null?void 0:h.launchedByCoordinator),N=w?" (Coordinator)":j?" (Mesh Node)":"",A=c+N,T=(b=e.activeChat)==null?void 0:b.activeModal,I=T&&Array.isArray(T.buttons)&&T.buttons.length>0,P=tk(e.activeChat,[{status:e.status,activeModal:(S=e.activeChat)==null?void 0:S.activeModal}],e.agents||[]),M=e.activeChat||{title:"",messages:[]};let E=M.title&&String(M.title).trim()?String(M.title).trim():"";const D=(x=e.activeChat)==null?void 0:x.id,W=e.chats;if(D&&Array.isArray(W)&&W.length>0){const K=W.find(z=>z.id===D||z.id&&String(z.id)===String(D));K!=null&&K.title&&String(K.title).trim()&&(E=String(K.title).trim())}const R=(bt(e)||ht(e),e.type),B=(bt(e)||ht(e))&&cd(E,A,R)?"":E,_=M.messages||[],H=typeof D=="string"?D.trim():"",L=(bt(e)||ht(e))&&H===String(e.type||"").trim(),F=H&&!L?H:e.providerSessionId,$=e.coordinator||(typeof((y=e.settings)==null?void 0:y.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:v,providerSessionId:e.providerSessionId,historySessionId:F,nativeSessionId:v,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:bt(e)&&e.mode||"chat",agentName:A,agentType:R,status:P,title:B,messages:_,resume:e.resume,hostIdeType:!bt(e)&&!ht(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||B||(bt(e)?e.mode==="chat"?A:`Terminal${N}`:A),displaySecondary:p,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,inboxBucket:e.inboxBucket,completionMarker:e.completionMarker,modalButtons:I?T.buttons:void 0,modalMessage:I?T.message:void 0,streamSource:"native",tabKey:Uo(v,e.id),machineName:a,connectionState:r,settings:e.settings,coordinator:$,messageInput:e.messageInput})}if(m&&(bt(e)||ht(e)))return n;for(const v of u){const w=v.activeModal&&Array.isArray(v.activeModal.buttons)&&v.activeModal.buttons.length>0,j=sk(v),N=Fj(v),A=`${e.id}:${N}`,T=v.title&&String(v.title).trim()||"",I=cd(T,v.agentName,v.agentType)?"":T,P=v.messages||[];if(!(v.transport==="cdp-webview"||!!v.sessionId||!!v.providerSessionId||P.length>0||w||!!I||!["idle","panel_hidden","disconnected","not_monitored"].includes(j)))continue;const E=v.coordinator||(typeof((C=v.settings)==null?void 0:C.meshCoordinatorFor)=="string"&&v.settings.meshCoordinatorFor?{meshId:v.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:v.sessionId||v.instanceId,providerSessionId:v.providerSessionId,historySessionId:v.activeChatId||v.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:v.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:v.sessionCapabilities,mode:"chat",agentName:v.agentName,agentType:v.agentType,status:j,title:I,messages:P,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:v.git||e.git,displayPrimary:o||I||v.agentName||d,displaySecondary:v.model&&v.model.trim()?v.model.trim():`${d} · ${v.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,lastUpdated:v.lastUpdated||e.lastUpdated,inboxBucket:v.inboxBucket,completionMarker:v.completionMarker,modalButtons:w?v.activeModal.buttons:void 0,modalMessage:w?v.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Uo(v.sessionId||v.instanceId,A),machineName:a,connectionState:r,settings:v.settings,coordinator:E,messageInput:v.messageInput})}return n.length===0&&n.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:c,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||d,displaySecondary:p,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:Uo(e.sessionId||e.instanceId,e.id),connectionState:r,settings:e.settings,messageInput:e.messageInput}),n}function gh(e){return String(e.type||e.id||"").trim()}function Qr(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()).map(t=>t.trim()):[]}function Wj(e,t){const n=(t||"").trim();if(!n)return[];const a=(e||[]).find(r=>r.type===n);return Qr(a==null?void 0:a.modelOptions)}function Oj(e,t){const n=(t||"").trim();if(!n)return[];const a=(e||[]).find(r=>r.type===n);return Qr(a==null?void 0:a.thinkingLevelOptions)}function bh(e){const t=new Map;for(const n of e||[])n!=null&&n.type&&t.set(n.type,{models:Qr(n.modelOptions),thinking:Qr(n.thinkingLevelOptions)});return t}function Uj(e){var t;return e.category!=="cli"||!gh(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 cn(e){var a;const t=new Set,n=[];for(const r of e||[]){if(!Uj(r))continue;const o=gh(r);if(!o||t.has(o))continue;t.add(o);const i=String(r.displayName||r.name||o),c=r.detectedPath||((a=r.lastDetection)==null?void 0:a.path)||null;n.push({type:o,label:i,icon:r.icon,statusLabel:c?`Detected at ${c}`:"Detected on this machine",detectedPath:c,...Array.isArray(r.modelOptions)&&r.modelOptions.length?{modelOptions:r.modelOptions}:{},...Array.isArray(r.thinkingLevelOptions)&&r.thinkingLevelOptions.length?{thinkingLevelOptions:r.thinkingLevelOptions}:{}})}return n}function Ya(e){const t=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],n=new Set,a=[];for(const r of t){const o=typeof r=="string"?r.trim():"";!o||n.has(o)||(n.add(o),a.push(o))}return a}function Dn(e){return e.map(t=>t.type)}function Gj(e,t){const n=Ya(e),a=t.trim();return!a||n.includes(a)?n:[...n,a]}function qj(e,t){return Ya(e).filter(n=>n!==t)}function Ud(e,t,n){const a=Ya(e),r=a.indexOf(t);if(r<0)return a;const o=a.filter(c=>c!==t);if(n==="top")return[t,...o];if(n==="bottom")return[...o,t];const i=n==="up"?Math.max(0,r-1):Math.min(o.length,r+1);return o.splice(i,0,t),o}const zj={"claude-cli":{monogram:"CL",hue:"#D97757"},"codex-cli":{monogram:"CX",hue:"#10A37F"},"gemini-cli":{monogram:"GM",hue:"#4285F4"},"kimi-cli":{monogram:"KM",hue:"#6366F1"},"antigravity-cli":{monogram:"AG",hue:"#8B5CF6"},"cursor-cli":{monogram:"CU",hue:"#64748B"},"opencode-cli":{monogram:"OC",hue:"#CA8A04"},"hermes-cli":{monogram:"HM",hue:"#14B8A6"},"grok-cli":{monogram:"GK",hue:"#475569"},antigravity:{monogram:"AG",hue:"#8B5CF6"},cursor:{monogram:"CU",hue:"#64748B"},kiro:{monogram:"KI",hue:"#F59E0B"},pearai:{monogram:"PA",hue:"#22C55E"},trae:{monogram:"TR",hue:"#EF4444"},vscode:{monogram:"VS",hue:"#3B82F6"},vscodium:{monogram:"VC",hue:"#2DD4BF"},windsurf:{monogram:"WS",hue:"#0EA5E9"},cline:{monogram:"CN",hue:"#0284C7"},"roo-code":{monogram:"RC",hue:"#F97316"}},Gd=["#0EA5E9","#8B5CF6","#10B981","#F59E0B","#EF4444","#14B8A6","#6366F1","#EC4899","#84CC16","#F97316","#06B6D4","#A855F7"];function Kj(e){let t=0;for(let n=0;n<e.length;n+=1)t=(t<<5)-t+e.charCodeAt(n)|0;return Math.abs(t)}function Vj(e){const t=e.replace(/[-_./]+/g," ").split(/\s+/).map(n=>n.trim()).filter(Boolean);return t.length===0?"?":t.length===1?t[0].slice(0,2).toUpperCase():(t[0][0]+t[1][0]).toUpperCase()}function Qa({type:e,label:t,size:n=16,className:a}){const r=(e||"").trim().toLowerCase(),o=(t==null?void 0:t.trim())||r;if(!o)return s.jsx(Rb,{size:n,className:a});const i=zj[r],c=(i==null?void 0:i.monogram)??Vj((t==null?void 0:t.trim())||r.replace(/-cli$/,"")),d=(i==null?void 0:i.hue)??Gd[Kj(r||o)%Gd.length];return s.jsx("span",{"aria-hidden":!0,className:`inline-flex shrink-0 select-none items-center justify-center font-semibold ${a??""}`,style:{width:n,height:n,borderRadius:Math.max(4,Math.round(n*.3)),backgroundColor:`${d}21`,border:`1px solid ${d}4D`,color:d,fontSize:Math.max(7,Math.round(n*.42)),letterSpacing:"0.02em",lineHeight:1},children:c})}function qd({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 Yj({value:e,availableProviders:t,onChange:n,disabled:a=!1,saveButton:r}){const{t:o}=ke("common"),[i,c]=l.useState(""),d=l.useMemo(()=>new Map(t.map(g=>[g.type,g])),[t]),p=l.useMemo(()=>Ya(e),[e]),u=p.filter(g=>!d.has(g)).length,m=t.filter(g=>!p.includes(g.type)),f=()=>{i&&(n(Gj(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),b=!!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 ${b?"bg-bg-primary":"bg-bg-primary/40"}`,children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("span",{className:"text-[10px] font-semibold text-text-muted",children:["#",k+1]}),s.jsx(Qa,{type:g,label:h==null?void 0:h.label,size:14}),s.jsx("span",{className:`font-mono text-[12px] ${b?"text-text-primary":"text-text-muted"}`,children:g}),b?s.jsx("span",{className:"rounded border border-green-500/20 bg-green-500/10 px-1.5 py-px text-[9px] font-semibold text-green-400",children:o("settings.providerPriority.available")}):s.jsx("span",{className:"rounded border border-amber-500/25 bg-amber-500/10 px-1.5 py-px text-[9px] font-semibold text-amber-400",children:o("settings.providerPriority.notOnMachine")})]}),s.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:h?`${h.label} · ${h.statusLabel}`:"Kept in order; skipped at launch until detected here."})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move up",disabled:a||k===0,title:"Move up",onClick:()=>n(Ud(p,g,"up")),children:s.jsx(qd,{direction:"up"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move down",disabled:a||k===p.length-1,title:"Move down",onClick:()=>n(Ud(p,g,"down")),children:s.jsx(qd,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:a,onClick:()=>n(qj(p,g)),children:o("settings.providerPriority.remove")})]})]},g)})}),s.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-end",children:[s.jsxs("label",{className:"flex-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"mb-1 block font-medium text-text-primary",children:o("settings.providerPriority.addCliLabel")}),s.jsxs("select",{className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-sm text-text-primary",value:i,onChange:g=>c(g.target.value),disabled:a||m.length===0,children:[s.jsx("option",{value:"",children:m.length?"Select provider…":"No additional detected CLI providers"}),m.map(g=>s.jsxs("option",{value:g.type,children:[g.label," (",g.type,")"]},g.type))]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:a||!i,onClick:f,children:o("settings.providerPriority.addProvider")}),r]}),s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:["Launches use this order, top to bottom.",u>0?` ${u} provider${u===1?"":"s"} not detected here — kept in order, skipped until available.`:""]})]})}function Qj(e){const t=e.split(":");return t.length>=3&&(t[1]==="ide"||t[1]==="cli"||t[1]==="acp")?{daemonId:t[0],targetSessionId:t.slice(2).join(":")||void 0}:{daemonId:e}}function xh(e,t){const n=Qj(e);return{daemonId:n.daemonId,payload:{...t,...n.targetSessionId&&!t.targetSessionId?{targetSessionId:n.targetSessionId}:{}}}}const vh=[{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:"🏄"}],yh=[{id:"antigravity-cli",name:"Antigravity CLI",icon:"🪐"},{id:"claude-cli",name:"Claude Code",icon:"🟠"},{id:"codex-cli",name:"Codex CLI",icon:"📦"},{id:"cursor-cli",name:"Cursor CLI",icon:"⚡"},{id:"grok-cli",name:"Grok",icon:"🛰️"},{id:"hermes-cli",name:"Hermes",icon:"⚕️"},{id:"kimi",name:"Kimi",icon:"🌙"},{id:"opencode",name:"OpenCode CLI",icon:"◆"}],wh=[{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:"🟠"}],Jj=vh,Xj=yh,Zj=wh;function e1({icon:e,title:t,subtitle:n,badge:a,actions:r,className:o}){return s.jsxs("div",{className:Pt("dashboard-header",o),children:[s.jsxs("div",{children:[s.jsxs("h1",{className:"header-title flex items-center gap-2",children:[s.jsx("span",{className:"flex items-center text-lg",children:e})," ",t,a&&s.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[a.count!==void 0?a.count:""," ",a.text]})]}),n&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:n})]}),r&&s.jsx("div",{className:"flex gap-2",children:r})]})}function Ja({icon:e,title:t,subtitle:n,badge:a,actions:r,widthClassName:o="max-w-6xl",contentClassName:i,children:c}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(e1,{icon:e,title:t,subtitle:n,badge:a,actions:r}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Pt("mx-auto flex w-full flex-col gap-4",o,i),children:c})})]})}const dl="adhdev:themechange";function t1(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function zn(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Kn(e){return e==="system"?t1():e}function kh(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Mr(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(dl,{detail:{preference:e,theme:t}}))}function s1(){const e=zn(),t=Kn(e);kh(t),Mr(e,t)}function Rs(){const[e,t]=l.useState(zn),[n,a]=l.useState(()=>Kn(zn()));l.useEffect(()=>{kh(n)},[n]),l.useEffect(()=>{const i=window.matchMedia("(prefers-color-scheme: light)"),c=d=>{if(e==="system"){const p=d.matches?"light":"dark";a(p),Mr("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:zn()),a(m==="dark"||m==="light"?m:Kn(zn()))},c=d=>{if(d.key!=="theme")return;const p=zn(),u=Kn(p);t(p),a(u)};return window.addEventListener(dl,i),window.addEventListener("storage",c),()=>{window.removeEventListener(dl,i),window.removeEventListener("storage",c)}},[]);const r=l.useCallback(i=>{const c=Kn(i);t(i),a(c);try{localStorage.setItem("theme",i)}catch{}Mr(i,c)},[]),o=l.useCallback(()=>{t(i=>{const c=i==="dark"?"light":i==="light"?"system":"dark",d=Kn(c);a(d);try{localStorage.setItem("theme",c)}catch{}return Mr(c,d),c})},[]);return{theme:n,preference:e,setPreference:r,cycleTheme:o,isDark:n==="dark"}}const zd={dark:"Dark",light:"Light",system:"System"};function n1({collapsed:e}){const{preference:t,cycleTheme:n}=Rs(),a=t==="dark"?s.jsx(Rp,{size:16}):t==="light"?s.jsx(Lp,{size:16}):s.jsx(Ep,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:n,title:`Theme: ${zd[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:a}),!e&&s.jsx("span",{className:"text-xs",children:zd[t]})]})}const ul="adhdev:langchange";function a1(){const e=wt.language;return Yn(e)?e:nm()}function r1(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(ul,{detail:{language:e}}))}function o1(){const[e,t]=l.useState(a1);l.useEffect(()=>{const a=i=>{Yn(i)&&t(i)},r=i=>{const c=i.detail||{};Yn(c.language)&&t(c.language)},o=i=>{if(i.key!==Yi)return;const c=i.newValue;Yn(c)&&c!==wt.language&&(wt.changeLanguage(c),Qi(c))};return wt.on("languageChanged",a),window.addEventListener(ul,r),window.addEventListener("storage",o),()=>{wt.off("languageChanged",a),window.removeEventListener(ul,r),window.removeEventListener("storage",o)}},[]);const n=l.useCallback(a=>{if(Yn(a)){t(a);try{localStorage.setItem(Yi,a)}catch{}wt.changeLanguage(a),Qi(a),r1(a)}},[]);return{language:e,setLanguage:n}}function i1({trigger:e,viewport:t,menu:n,variant:a,gap:r=6,margin:o=8}){const i=e.top-o,c=t.height-e.bottom-o,d=a==="sidebar";let p=d;d&&i<n.height&&c>i&&(p=!1),!d&&c<n.height&&i>c&&(p=!0);const u=p?i:c,m=Math.max(80,Math.min(n.height,u));let f;p?f=e.top-r-m:f=e.bottom+r,f=Kd(f,o,Math.max(o,t.height-m-o));const g=Kd(e.left,o,Math.max(o,t.width-n.width-o));return{top:f,left:g,maxHeight:m}}function Kd(e,t,n){return Math.min(Math.max(e,t),n)}function l1({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 c1({collapsed:e,variant:t="sidebar"}){const{language:n,setLanguage:a}=o1(),{t:r}=ke("common"),[o,i]=l.useState(!1),[c,d]=l.useState(0),p=l.useRef(null),u=l.useRef(null),m=l.useRef(null),f=l.useId(),[g,k]=l.useState(null),h=l.useCallback(()=>{const P=u.current;if(!P)return;const M=P.getBoundingClientRect(),E=m.current,D=Math.max((E==null?void 0:E.offsetWidth)??0,168),W=(E==null?void 0:E.scrollHeight)??pn.length*36+12;k(i1({trigger:{top:M.top,left:M.left,right:M.right,bottom:M.bottom,width:M.width,height:M.height},viewport:{width:window.innerWidth,height:window.innerHeight},menu:{width:D,height:W},variant:t}))},[t]),b=Math.max(0,pn.findIndex(P=>P.code===n)),S=pn[b]??pn[0],x=r("language.label",{defaultValue:"Language"}),y=r("language.select",{defaultValue:"Select language"}),C=P=>`${f}-opt-${P}`,v=l.useCallback(()=>{d(b),i(!0)},[b]),w=l.useCallback((P=!0)=>{var M;i(!1),P&&((M=u.current)==null||M.focus())},[]),j=l.useCallback(P=>{const M=pn[P];M&&a(M.code),w()},[a,w]);l.useEffect(()=>{if(!o)return;const P=D=>{var W,R;return!!((W=p.current)!=null&&W.contains(D)||(R=m.current)!=null&&R.contains(D))},M=D=>{P(D.target)||i(!1)},E=D=>{P(D.target)||i(!1)};return document.addEventListener("pointerdown",M,!0),document.addEventListener("focusin",E,!0),()=>{document.removeEventListener("pointerdown",M,!0),document.removeEventListener("focusin",E,!0)}},[o]),l.useLayoutEffect(()=>{if(!o){k(null);return}h();const P=()=>h();return window.addEventListener("resize",P),window.addEventListener("scroll",P,!0),()=>{window.removeEventListener("resize",P),window.removeEventListener("scroll",P,!0)}},[o,h]),l.useEffect(()=>{var P;o&&g&&((P=m.current)==null||P.focus())},[o,g]);const N=P=>{const M=pn.length-1;switch(P.key){case"ArrowDown":P.preventDefault(),d(E=>E>=M?0:E+1);break;case"ArrowUp":P.preventDefault(),d(E=>E<=0?M:E-1);break;case"Home":P.preventDefault(),d(0);break;case"End":P.preventDefault(),d(M);break;case"Enter":case" ":P.preventDefault(),j(c);break;case"Escape":P.preventDefault(),w();break;case"Tab":i(!1);break}},A=P=>{o||(P.key==="ArrowDown"||P.key==="ArrowUp"||P.key==="Enter"||P.key===" ")&&(P.preventDefault(),v())},T=t==="landing"?"lang-switch-trigger lang-switch-trigger--landing":`lang-switch-trigger lang-switch-trigger--sidebar nav-item cursor-pointer${e?" justify-center py-2.5 px-0":""}`,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":`${x}: ${S.label}`,title:`${x}: ${S.label}`,onClick:()=>o?w(!1):v(),onKeyDown:A,children:[s.jsx("span",{className:"nav-icon lang-switch-icon",children:s.jsx(_p,{size:16})}),I&&s.jsx("span",{className:"lang-switch-label text-xs",children:S.label}),I&&s.jsx(l1,{open:o})]}),o&&typeof document<"u"&&zs.createPortal(s.jsx("ul",{ref:m,role:"listbox",tabIndex:-1,"aria-label":y,"aria-activedescendant":C(c),className:`lang-switch-menu lang-switch-menu--${t}`,style:{position:"fixed",top:(g==null?void 0:g.top)??0,left:(g==null?void 0:g.left)??0,maxHeight:g==null?void 0:g.maxHeight,overflowY:"auto",visibility:g?"visible":"hidden"},onKeyDown:N,children:pn.map((P,M)=>{const E=P.code===S.code,D=M===c;return s.jsxs("li",{id:C(M),role:"option","aria-selected":E,className:`lang-switch-option${D?" is-active":""}${E?" is-selected":""}`,onMouseEnter:()=>d(M),onClick:()=>j(M),children:[s.jsx("span",{className:"lang-switch-check","aria-hidden":"true",children:E?s.jsx(co,{size:14}):null}),s.jsx("span",{className:"lang-switch-option-label",children:P.label})]},P.code)})}),document.body)]})}const d1=[],u1=[];function Xo(e,t){return e?typeof e=="function"?e(t):e:null}const p1=l.memo(function({renderState:t,brand:n,navItems:a,sidebarSections:r,footerItems:o,footerInfo:i,footerActions:c,closeMobileMenu:d}){const{t:p}=ke("common"),{collapsed:u,mobileMenuOpen:m}=t,f=k=>`nav-item${k.active?" active":""} cursor-pointer ${u?"justify-center py-2.5 px-0":""}${k.className?` ${k.className}`:""}`,g=k=>s.jsxs("div",{className:f(k),id:`nav-${k.id}`,onClick:()=>{k.onSelect(),d()},title:u?k.title??(typeof k.label=="string"?k.label:void 0):k.title,children:[s.jsx("span",{className:"nav-icon",children:k.icon}),!u&&k.label]},k.id);return s.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${u?"justify-center gap-0":""}`,children:Xo(n,t)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":p("app.closeMenu"),onClick:d,children:s.jsx(Dt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:a.map(g)}),r.map(k=>s.jsxs("div",{className:k.className??"border-t border-border-subtle pt-2 mt-2",children:[!u&&k.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:k.title}):null,k.items.map(g)]},k.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[o.map(g),Xo(i,t),s.jsx(n1,{collapsed:u}),s.jsx(c1,{collapsed:u}),Xo(c,t)]})]})});function m1({children:e,brand:t,navItems:n,sidebarSections:a=d1,footerItems:r=u1,footerInfo:o,footerActions:i,preMainContent:c,collapsedStorageKey:d="sidebar-collapsed"}){const{t:p}=ke("common"),[u,m]=l.useState(!1),[f,g]=l.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),k=l.useCallback(()=>m(!0),[]),h=l.useCallback(()=>m(!1),[]),b=l.useCallback(()=>{g(x=>{const y=!x;try{localStorage.setItem(d,y?"1":"0")}catch{}return y})},[d]),S=l.useMemo(()=>({collapsed:f,mobileMenuOpen:u,openMobileMenu:k,closeMobileMenu:h,toggleCollapsed:b}),[f,u,k,h,b]);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:x=>x.key==="Escape"&&h()}),s.jsx(p1,{renderState:S,brand:t,navItems:n,sidebarSections:a,footerItems:r,footerInfo:o,footerActions:i,closeMobileMenu:h}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function xt({title:e,icon:t,description:n,accentColor:a,className:r,collapsible:o,defaultOpen:i=!0,badge:c,children:d}){const[p,u]=l.useState(i),m=o?p:!0,f=(e||n)&&s.jsxs("div",{className:Pt("flex items-start justify-between gap-3",m&&"mb-4"),children:[s.jsxs("div",{className:"min-w-0",children:[e&&s.jsxs("h3",{className:"text-base font-semibold text-text-primary flex items-center gap-1.5",children:[t&&s.jsx("span",{children:t}),s.jsx("span",{children:e}),c]}),n&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:n})]}),o&&s.jsx("span",{className:Pt("mt-0.5 shrink-0 text-text-muted transition-transform select-none",m?"rotate-90":"rotate-0"),"aria-hidden":!0,children:"▸"})]});return s.jsxs("div",{className:Pt("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",a&&"border-l-[3px]",r),style:a?{borderLeftColor:a}:void 0,children:[o&&f?s.jsx("button",{type:"button",className:"w-full bg-transparent border-none p-0 text-left cursor-pointer",onClick:()=>u(g=>!g),"aria-expanded":m,children:f}):f,m&&d]})}function Xa({icon:e,title:t,description:n,action:a,className:r}){return s.jsxs("div",{className:Pt("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",r),children:[s.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),s.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:t}),s.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:n}),a]})}const h1={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"},f1={error:Ls,warning:Ls,success:Ga,info:uo};function Mt({variant:e,children:t,onDismiss:n,className:a}){return s.jsxs("div",{className:Pt("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",h1[e],a),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[(()=>{const r=f1[e];return s.jsx(r,{size:14})})(),s.jsx("span",{children:t})]}),n&&s.jsx("button",{onClick:n,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}function Tt({label:e,hint:t,children:n,className:a}){return s.jsxs("div",{className:Pt("mb-5",a),children:[s.jsx("label",{className:"block text-xs font-semibold text-text-muted uppercase tracking-wider mb-2",children:e}),n,t&&s.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:t})]})}function xs(e){const{className:t,...n}=e;return s.jsx("input",{...n,className:Pt("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none","focus:border-accent transition-colors",t)})}const g1={primary:"btn-primary",secondary:"btn-secondary",warning:"btn-warning",danger:"btn-danger",ghost:"btn-ghost"},Gs=l.forwardRef(function({variant:t="secondary",size:n="md",type:a,className:r,...o},i){return s.jsx("button",{ref:i,type:a??"button",className:Pt("btn",g1[t],n==="sm"&&"btn-sm",r),...o})}),b1=l.forwardRef(function({options:t,children:n,className:a,...r},o){return s.jsx("select",{ref:o,className:Pt("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none cursor-pointer","focus:border-accent transition-colors",a),...r,children:n??(t==null?void 0:t.map(i=>s.jsx("option",{value:i.value,disabled:i.disabled,children:i.label},i.value)))})}),x1={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"},v1={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function y1({status:e,label:t,className:n}){const a=t||e;return s.jsxs("span",{className:Pt("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",x1[e],n),children:[s.jsx("span",{className:Pt("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",v1[e])}),a]})}function w1({tabs:e,defaultTabKey:t,activeKey:n,onTabChange:a,variant:r="pill",ariaLabel:o,className:i,tabListClassName:c,panelClassName:d,tabIdPrefix:p,unmountInactivePanels:u=!1}){var S;const[m,f]=l.useState(t??((S=e[0])==null?void 0:S.key)),g=n!==void 0,k=g?n:m,h=x=>{g||f(x),a==null||a(x)},b=r==="underline";return s.jsxs("div",{className:i,children:[s.jsx("div",{className:Pt(b?"flex shrink-0 items-center gap-1 border-b border-border-subtle px-4 md:px-6":"mb-5 inline-flex w-full flex-wrap items-center gap-1 rounded-xl border border-border-subtle bg-bg-secondary/60 p-1 sm:w-fit",c),role:"tablist","aria-label":o,children:e.map(x=>{const y=x.key===k;return s.jsxs("button",{id:p?`${p}-${x.key}`:void 0,type:"button",role:"tab","aria-selected":y,className:Pt(b?["-mb-px flex cursor-pointer items-center gap-1.5 border-b-2 px-3 py-2.5 text-[13px] font-medium transition-colors",y?"border-accent text-accent":"border-transparent text-text-muted hover:text-text-secondary"]:["flex flex-1 items-center justify-center gap-1.5 rounded-lg px-3.5 py-1.5 text-[13px] font-medium transition-colors sm:flex-none",y?"bg-bg-card text-text-primary shadow-sm border border-border-default":"text-text-muted border border-transparent hover:text-text-secondary hover:bg-white/[0.03]"]),onClick:()=>h(x.key),children:[x.icon,x.label]},x.key)})}),e.map(x=>{const y=x.key===k;return u&&!y?null:s.jsx("div",{className:y?Pt("flex flex-col gap-4",d):"hidden",children:x.content},x.key)})]})}function xn({label:e,description:t,checked:n,disabled:a,onChange:r,extra:o}){return s.jsxs("div",{className:`flex justify-between items-center ${a?"opacity-60":""}`,children:[s.jsxs("div",{className:"pr-4",children:[s.jsx("div",{className:"font-medium text-sm",children:e}),s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:t})]}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[o,s.jsxs("button",{type:"button",role:"switch","aria-checked":n,"aria-disabled":a,disabled:a,onClick:()=>r(!n),className:`relative inline-flex items-center ${a?"cursor-not-allowed":"cursor-pointer"}`,children:[s.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:n?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),s.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${n?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function k1({onPrefChange:e}){const{t}=ke("common"),[n,a]=pk(),[r,o]=l.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);l.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){o("unsupported");return}o(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,d)=>{a({[c]:d}),e==null||e(c,d)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(xn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(la,{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(xn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(us,{size:15})," ",t("notifications.browserNotificationsLabel")]}),description:t("notifications.browserNotificationsDesc"),checked:n.browserNotifications,onChange:c=>i("browserNotifications",c)}),n.globalEnabled&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:t("notifications.standaloneBackgroundInfo")}),r==="default"&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-status-warning",children:[s.jsx("span",{children:t("notifications.standalonePermissionDefault")}),s.jsx("button",{onClick:()=>{gm().then(o)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:t("notifications.allowNotifications")})]}),r==="denied"&&s.jsx("div",{className:"text-[11px] text-status-warning",children:t("notifications.permissionDenied")}),r==="unsupported"&&s.jsx("div",{className:"text-[11px] text-status-warning",children:t("notifications.standalonePermissionUnsupported")})]}),n.globalEnabled&&n.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(xn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ga,{size:15})," ",t("notifications.completionAlertsLabel")]}),description:t("notifications.completionAlertsDesc"),checked:n.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(xn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Cb,{size:15})," ",t("notifications.approvalAlertsLabel")]}),description:t("notifications.approvalAlertsDesc"),checked:n.approvalAlert,onChange:c=>i("approvalAlert",c)}),s.jsx(xn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(_a,{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 Jr(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/);if(!t)return null;const n=t[4]??null;let a=null;if(n){const r=n.match(/(?:^|\.)(\d+)$/);a=r?Number(r[1]):null}return{base:[Number(t[1]),Number(t[2]),Number(t[3])],prereleaseNumber:a,isPrerelease:n!==null}}function Vd(e){var t;return((t=Jr(e))==null?void 0:t.base)??null}function Sh(e,t){const n=Jr(e),a=Jr(t);if(!n||!a)return e!==t;for(let r=0;r<3;r+=1){if(n.base[r]<a.base[r])return!0;if(n.base[r]>a.base[r])return!1}return n.isPrerelease&&a.isPrerelease?n.prereleaseNumber===null||a.prereleaseNumber===null?!1:n.prereleaseNumber<a.prereleaseNumber:!1}function jo(e,t){const n=e.version||null;return!n||!t||e.versionMismatch===!0&&!Jr(t)?!1:Sh(n,t)}function Da(e,t){if(e.versionUpdateRequired===!0)return!0;const n=e.version||null;if(!n||!t||!Sh(n,t))return!1;const a=Vd(n),r=Vd(t);return!a||!r?!1:a[0]!==r[0]||a[1]!==r[1]}function Zo(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 S1(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 ja(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function lc(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},n=Zo(t.channel)||Zo(e.updateChannel)||Zo(e.releaseChannel)||void 0,a=S1(t.npmTag)||(n==="preview"?"next":n==="stable"?"latest":void 0),r=ja(t.targetVersion)||ja(e.serverVersion)||void 0,o=ja(t.minVersion)||void 0,i=ja(t.updateCommand)||(n?"adhdev update":void 0);return{...n?{channel:n}:{},...a?{npmTag:a}:{},...r?{targetVersion:r}:{},...o?{minVersion:o}:{},...i?{updateCommand:i}:{}}}function Js(e,t=null){return lc(e).targetVersion||t}function C1(e){return lc(e).channel||null}function No(e){return!e||!lc(e).channel?null:{}}function Ch(e,t={}){const n=ja(t.targetVersion);return n?`Update to v${n}`:t.fallback||(t.required?"Update now":"Upgrade")}const jh="Cannot update: node update policy unavailable; refresh and try again";async function j1(e,t,n){var r,o,i,c,d,p;const a=No(n);if(!a)return{state:"error",message:jh};try{const u=await e(t,"daemon_upgrade",a);return(r=u==null?void 0:u.result)!=null&&r.alreadyLatest?{state:"done",message:`Already on v${((o=u==null?void 0:u.result)==null?void 0:o.version)||"latest"}.`}:(i=u==null?void 0:u.result)!=null&&i.upgraded||(c=u==null?void 0:u.result)!=null&&c.success?{state:"done",message:`Upgrade to v${((d=u==null?void 0:u.result)==null?void 0:d.version)||"latest"} started. Daemon is restarting…`}:{state:"error",message:((p=u==null?void 0:u.result)==null?void 0:p.error)||"Upgrade failed"}}catch(u){return{state:"error",message:u instanceof Error?u.message:"Upgrade failed"}}}function N1(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function ei(e,t){return e instanceof Error?e.message:t}function A1({ides:e,emptyMessage:t,sendDaemonCommand:n,onDisconnect:a,onRevokeToken:r}){const{t:o}=ke("common"),i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?s.jsx(Xa,{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(M1,{ide:c,allIdes:e,sendDaemonCommand:n,onDisconnect:a,onRevokeToken:r},c.id))})}function Yd({title:e,message:t,confirmLabel:n,confirmColor:a,onConfirm:r,onCancel:o}){const{t:i}=ke("common"),c=a==="red"?"bg-status-error/20 text-status-error border-status-error/40 hover:bg-status-error/30":"";return zs.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:"var(--z-modal)"},onClick:o,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:d=>d.stopPropagation(),children:[s.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),s.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:t}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.jsx("button",{onClick:o,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:i("common.cancel")}),s.jsx("button",{onClick:r,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,style:a==="amber"?{background:"color-mix(in srgb, var(--status-warning) 20%, transparent)",color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"}:void 0,children:n})]})]})}),document.body)}function T1(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),a=[...Jj,...Xj,...Zj].find(r=>r.id===t||t.includes(r.id)||r.id.includes(t));return a?{icon:a.icon,name:a.name}:{icon:"",name:e}}function M1({ide:e,allIdes:t,sendDaemonCommand:n,onDisconnect:a,onRevokeToken:r}){var D,W;const{t:o}=ke("common"),[i,c]=l.useState("idle"),[d,p]=l.useState(""),[u,m]=l.useState(null),[f,g]=l.useState("idle"),[k,h]=l.useState(""),b=e.version||null,S=((D=e.machine)==null?void 0:D.platform)||((W=e.system)==null?void 0:W.platform)||"",x=ds(e,{fallbackId:e.id}),y=t.filter(R=>R.daemonId===e.id&&R.transport==="cdp-page"),C=t.filter(R=>R.daemonId===e.id&&R.transport==="pty"),v=t.filter(R=>R.daemonId===e.id&&R.transport==="acp"),w=e.p2p,j=async()=>{if(!n)return;const R=No(e);if(!R){c("error"),p(jh);return}c("upgrading"),p(o("machine.connectedMachines.startingUpgrade"));try{const B=N1(await n(e.id,"daemon_upgrade",R));B.alreadyLatest?(c("done"),p(`Already on v${B.version||"latest"}.`)):B.upgraded||B.success?(c("done"),p(`Upgrade to v${B.version||"latest"} started. Daemon is restarting...`)):(c("error"),p(B.error||"Upgrade failed"))}catch(B){c("error"),p(ei(B,"Connection lost during upgrade"))}},N=async()=>{if(m(null),!!a){g("loading");try{await a(e.id),g("done"),h(o("machine.connectedMachines.machineDisconnected"))}catch(R){g("error"),h(ei(R,o("machine.connectedMachines.failedToDisconnect")))}}},A=async()=>{if(m(null),!!r){g("loading");try{await r(e.id),g("done"),h(o("machine.connectedMachines.tokenRevoked"))}catch(R){g("error"),h(ei(R,o("machine.connectedMachines.failedToRevokeToken")))}}},T="1.0.57",I=Js(e,T),P=jo(e,I),M=Da(e,I),E=y.length+C.length+v.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-text-muted",title:S,children:s.jsx(us,{size:18})}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:x}),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),"…"]}),b&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${P?"":"bg-bg-secondary"}`,style:P?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",b,!P&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[n&&P&&s.jsx("button",{onClick:j,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${T}`,children:i==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx(ls,{size:12,thickness:2})," ",o("machine.connectedMachines.upgrading")]}):i==="done"?o("machine.connectedMachines.updated"):M?o("machine.connectedMachines.updateNow"):o("machine.connectedMachines.updateTo",{version:T})}),a&&s.jsx("button",{onClick:()=>m("disconnect"),disabled:f==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:o("machine.connectedMachines.disconnect")}),r&&s.jsx("button",{onClick:()=>m("revoke"),disabled:f==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:o("machine.connectedMachines.remove")}),s.jsx(y1,{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:[w&&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 ${w.state==="connected"?"bg-status-online":"bg-text-muted/30"} ${w.state==="connecting"||w.state==="new"?"animate-pulse":""}`,style:w.state==="connecting"||w.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",w.state==="connected"?"connected":w.state==="connecting"||w.state==="new"?o("machine.connectedMachines.connecting"):w.state||"off"]}),w.peers!==void 0&&w.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",w.peers," peer",w.peers!==1?"s":"",")"]})]}),w&&E>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),E>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[y.map(R=>{const B=T1(R.type),_=R.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx(Qa,{type:R.type,label:B.name,size:13}),s.jsx("span",{children:B.name}),_!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${_?"bg-status-online":"animate-pulse"}`,style:_?void 0:{background:"var(--status-warning)"},title:o(_?"machine.connectedMachines.cdpConnected":"machine.connectedMachines.cdpConnecting")})]},R.id)}),C.map(R=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"⌨️"}),s.jsx("span",{children:R.cliName||"CLI"})]},R.id)),v.map(R=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{className:"inline-flex",children:s.jsx(Ib,{size:12})}),s.jsx("span",{children:R.cliName||"ACP"})]},R.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:o("machine.connectedMachines.noIdesConnected")})]}),(d||k)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||f==="error"?"text-status-error":i==="done"||f==="done"?"text-status-online":"text-text-muted"}`,children:k||d})]}),u==="disconnect"&&s.jsx(Yd,{title:o("machine.connectedMachines.disconnectTitle"),message:`Disconnect "${x}" from ADHDev?
|
|
54
54
|
|
|
55
55
|
This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
|
|
56
56
|
|
|
@@ -61,8 +61,8 @@ This will:
|
|
|
61
61
|
• Delete the machine registration
|
|
62
62
|
• Require running \`adhdev setup\` again on that machine
|
|
63
63
|
|
|
64
|
-
The machine's IDE, workspace and provider settings are kept.`,confirmLabel:o("machine.connectedMachines.remove"),confirmColor:"red",onConfirm:A,onCancel:()=>m(null)})]})}const P1=[{id:"dark",label:"Dark",icon:Rp},{id:"light",label:"Light",icon:Lp},{id:"system",label:"System",icon:Ep}];function D1(){const{preference:e,setPreference:t}=Rs();return s.jsx("div",{className:"flex gap-2",children:P1.map(n=>s.jsxs("button",{onClick:()=>t(n.id),className:`px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors flex items-center gap-1.5 ${e===n.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:e===n.id?{color:"var(--accent-on-primary)"}:void 0,children:[s.jsx(n.icon,{size:14}),n.label]},n.id))})}function I1(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 L1(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function ti(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Qd(e){const{r:t,g:n,b:a}=L1(e);return .2126*ti(t)+.7152*ti(n)+.0722*ti(a)}function Jd(e,t){const n=Qd(e),a=Qd(t),r=Math.max(n,a),o=Math.min(n,a);return(r+.05)/(o+.05)}function Nh(e){const t=I1(e);if(!t)return"#111827";const n="#111827",a="#ffffff";return Jd(t,n)>=Jd(t,a)?n:a}const pl={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},ml={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},R1=[{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"}}}],Ah="adhdev-chat-theme",Th="adhdev-chat-theme-custom";function Pr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Ah)||"ember"}catch{return"ember"}}function bs(e){try{const t=localStorage.getItem(Th);if(t){const n=JSON.parse(t);return{...e==="dark"?pl:ml,...n[e]}}}catch{}return e==="dark"?pl:ml}function cr(e,t){try{localStorage.setItem(Th,JSON.stringify({dark:e,light:t}))}catch{}}function as(e,t){const n=parseInt(e.slice(1,3),16),a=parseInt(e.slice(3,5),16),r=parseInt(e.slice(5,7),16);return`rgba(${n}, ${a}, ${r}, ${t})`}function Xr(e,t){const n=Math.min(255,parseInt(e.slice(1,3),16)+t),a=Math.min(255,parseInt(e.slice(3,5),16)+t),r=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}`}const E1={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Ia(e,t){var r;const n=(r=E1[e])==null?void 0:r[t];if(!n)return;const a=document.documentElement;a.style.setProperty("--accent-primary",n),a.style.setProperty("--accent-primary-light",Xr(n,24)),a.style.setProperty("--accent-on-primary",Nh(n)),a.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${n}, ${Xr(n,18)})`),a.style.setProperty("--border-accent",as(n,.35)),a.style.setProperty("--nav-active-bg",as(n,.1)),a.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${n}, 0 0 12px ${as(n,.06)}`)}function Cn(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",as(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",as(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",as(e.borderSubtle,.25)),t.style.setProperty("--text-primary",e.textPrimary),t.style.setProperty("--text-secondary",e.textSecondary),t.style.setProperty("--text-muted",e.textMuted),t.style.setProperty("--border-subtle",as(e.borderSubtle,.5)),t.style.setProperty("--border-default",as(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",Xr(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Nh(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Xr(e.accentColor,40)})`),t.style.setProperty("--border-accent",as(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",as(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${as(e.accentColor,.06)}`),t.style.setProperty("--chat-user-bg",e.userBubble),t.style.setProperty("--chat-user-color",e.userText),t.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),t.style.setProperty("--chat-assistant-bg",e.assistantBubble),t.style.setProperty("--chat-assistant-color",e.assistantText),t.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),t.style.setProperty("--chat-assistant-border",`1px solid ${as(e.accentColor,.12)}`),t.style.setProperty("--chat-container-bg",e.containerBg),t.style.setProperty("--dashboard-pane-bg",e.containerBg),t.style.setProperty("--chat-thought-accent",e.accentColor),t.style.setProperty("--chat-tool-accent",e.accentColor),t.style.setProperty("--chat-action-color",e.accentColor),t.style.setProperty("--chat-send-bg",e.sendButton),t.style.setProperty("--chat-input-border",e.inputBorder)}function cc(){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 _1(e){try{localStorage.setItem(Ah,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=jn()?"dark":"light";Cn(bs(t))}else cc(),Ia(e,jn()?"dark":"light")}function H1(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Pr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=jn()?"dark":"light";Cn(bs(t))}else cc(),Ia(e,jn()?"dark":"light")}function jn(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Gt({label:e,value:t,onChange:n}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[s.jsx("input",{type:"color",value:t,onChange:a=>n(a.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),s.jsx("input",{type:"text",value:t,onChange:a=>{/^#[0-9a-fA-F]{0,6}$/.test(a.target.value)&&n(a.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function xa({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 $1({dark:e,onColorsChange:t}){const{t:n}=ke("common"),a=e?"dark":"light",[r,o]=l.useState(()=>bs(a));l.useEffect(()=>{o(bs(a))},[a]);const i=l.useCallback((c,d)=>{o(p=>{const u={...p,[c]:d},f=bs(a==="dark"?"light":"dark");return a==="dark"?cr(u,f):cr(f,u),Cn(u),t(u),u})},[a,t]);return s.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[s.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[n("settings.theme.customEditorTitle"),s.jsx("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:n(e?"settings.theme.darkMode":"settings.theme.lightMode")})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs(xa,{title:n("settings.theme.sectionAppBackground"),children:[s.jsx(Gt,{label:n("settings.theme.colorBackground"),value:r.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(Gt,{label:n("settings.theme.colorSurface"),value:r.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(Gt,{label:n("settings.theme.colorCard"),value:r.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(xa,{title:n("settings.theme.sectionAppText"),children:[s.jsx(Gt,{label:n("settings.theme.colorPrimary"),value:r.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(Gt,{label:n("settings.theme.colorSecondary"),value:r.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(Gt,{label:n("settings.theme.colorMuted"),value:r.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(xa,{title:n("settings.theme.sectionBordersAccent"),children:[s.jsx(Gt,{label:n("settings.theme.colorBorderSubtle"),value:r.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(Gt,{label:n("settings.theme.colorBorderDefault"),value:r.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(Gt,{label:n("settings.theme.colorAccent"),value:r.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(xa,{title:n("settings.theme.sectionChatBubbles"),children:[s.jsx(Gt,{label:n("settings.theme.colorUserBubble"),value:r.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(Gt,{label:n("settings.theme.colorUserText"),value:r.userText,onChange:c=>i("userText",c)}),s.jsx(Gt,{label:n("settings.theme.colorAgentBubble"),value:r.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(Gt,{label:n("settings.theme.colorAgentText"),value:r.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(xa,{title:n("settings.theme.sectionChatLayout"),children:[s.jsx(Gt,{label:n("settings.theme.colorChatBg"),value:r.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(Gt,{label:n("settings.theme.colorSendButton"),value:r.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(Gt,{label:n("settings.theme.colorInputBorder"),value:r.inputBorder,onChange:c=>i("inputBorder",c)}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:n("settings.theme.labelBubbleRadius")}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[s.jsx("input",{type:"range",min:4,max:24,value:r.bubbleRadius,onChange:c=>i("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),s.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[r.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const c=e?pl:ml,p=bs(e?"light":"dark");e?cr(c,p):cr(p,c),o(c),Cn(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 F1(){const{t:e}=ke("common"),[t,n]=l.useState(Pr),[a,r]=l.useState(!0),[o,i]=l.useState(()=>bs("dark"));l.useEffect(()=>{r(jn());const p=new MutationObserver(()=>{const f=jn();r(f);const g=Pr();g==="custom"?Cn(bs(f?"dark":"light")):Ia(g,f?"dark":"light")});p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const u=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const f=jn();r(f);const g=Pr();g==="custom"?Cn(bs(f?"dark":"light")):Ia(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"?Cn(bs(a?"dark":"light")):(cc(),Ia(t,a?"dark":"light"))},[t,a]),l.useEffect(()=>{i(bs(a?"dark":"light"))},[a]);const c=p=>{n(p),_1(p)},d=[...R1,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText},light:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:d.map(p=>{const u=t===p.id,m=a?p.preview.dark:p.preview.light,f=p.id==="honey"||p.id==="ember"?"#1a1a1a":p.id==="custom"?o.userText:"#fff";return s.jsxs("button",{onClick:()=>c(p.id),className:"text-left rounded-xl p-3 transition-all",style:{background:u?"var(--bg-glass-hover)":"var(--bg-glass)",border:u?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:u?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:m.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:e("settings.theme.helloHelp")}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.userBubble,color:f},children:e("settings.theme.fixBug")}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:e("settings.theme.onIt")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[u&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:p.id==="custom"?e("settings.theme.customLabel"):p.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:p.description})]})]})]},p.id)})}),t==="custom"&&s.jsx($1,{dark:a,onColorsChange:p=>i(p)})]})}const dc="adhdev_mobileDashboardMode_v1",hl="adhdev:mobile-dashboard-mode-change";function uc(){try{return localStorage.getItem(dc)==="workspace"?"workspace":"chat"}catch{return"chat"}}function B1(e){if(typeof window>"u")return()=>{};const t=r=>{e(r??uc())},n=r=>{const o=r.detail;t(o)},a=r=>{r.key&&r.key!==dc||t()};return window.addEventListener(hl,n),window.addEventListener("storage",a),()=>{window.removeEventListener(hl,n),window.removeEventListener("storage",a)}}function W1(e){try{localStorage.setItem(dc,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(hl,{detail:e}))}function O1(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(uc()==="chat")},[]),s.jsx(xn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Is,{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),W1(n?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const U1="Choose a preset or create a fully custom theme. Custom themes control the entire app — backgrounds, text, borders, and chat bubbles.",G1="Choose whether the dashboard opens like a chat app on phones or keeps the full workspace layout.";function q1({themeDescription:e=U1,mobileDescription:t=G1,fontsSlot:n}){const{t:a}=ke("common");return s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:a("settings.appearance.modeLabel")}),s.jsx(D1,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:a("settings.appearance.themeLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:e}),s.jsx(F1,{})]}),n,s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:a("settings.appearance.mobileLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:t}),s.jsx(O1,{})]})]})}const si=new Map,Xd=new Map;function z1(e){if(!e||typeof e!="object")return null;const t=e,n=t.result&&typeof t.result=="object"?t.result:t,a=n.machine;return!a||typeof a!="object"?null:{machine:a,timestamp:typeof n.timestamp=="number"?n.timestamp:void 0}}function K1(e,t,n,a){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:a,platform:n.platform,machine:n}}function Mh(){const{sendCommand:e}=St(),{injectEntries:t,getIdes:n}=Ea();return l.useCallback(async(a,r)=>{if(!a)return;const o=(r==null?void 0:r.minFreshMs)??QS,i=Xd.get(a)||0;if(!(r!=null&&r.force)&&i>0&&Date.now()-i<o)return;const c=si.get(a);if(c)return c;const d=(async()=>{const p=await e(a,"get_machine_runtime_stats"),u=z1(p);if(!u)return;const m=n().find(g=>g.id===a),f=K1(m,a,u.machine,u.timestamp||Date.now());t([f]),Xd.set(a,Date.now())})().finally(()=>{si.delete(a)});return si.set(a,d),d},[n,t,e])}function V1(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 Y1(e,t){const{sendData:n}=St(),{injectEntries:a,getIdes:r}=Ea(),o=Array.from(new Set(e.filter(Boolean))).join("|");l.useEffect(()=>{if(!(t!=null&&t.enabled)||!n)return;const i=o?o.split("|"):[];if(i.length===0)return;const c=i.map(d=>ys.subscribe({sendData:n},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const m=r().find(g=>g.id===d),f=V1(m,d,u);a([f])}));return()=>{c.forEach(d=>d())}},[o,r,a,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,n])}function Q1(e,t){const{sendData:n}=St(),[a,r]=l.useState(null),[o,i]=l.useState(!1);return l.useEffect(()=>{if(!e){r(null),i(!1);return}if(!(t!=null&&t.enabled)||!n){i(!1);return}r(null),i(!0);let c=null;const d=ys.subscribe({sendData:n},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},p=>{c&&(clearTimeout(c),c=null),r(p.diagnostics),i(!1)});return d.initialSendAccepted?c=setTimeout(()=>{i(!1)},ZS):i(!1),()=>{c&&clearTimeout(c),d()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,n]),{diagnostics:a,loading:o,applyDiagnostics:r}}function J1(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Ph(e){const{sendData:t}=St(),[n,a]=l.useState({});return l.useEffect(()=>{const r=J1(e);if(!r||!e.sessionId||!t){a({});return}const o=ys.subscribe({sendData:t},r,{type:"subscribe",topic:"session.modal",key:`daemon:${r}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},i=>{a({status:i.status,modalMessage:i.modalMessage,modalButtons:i.modalButtons}),ea.record({interactionId:i.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:i.status,modalButtonCount:Array.isArray(i.modalButtons)?i.modalButtons.length:0}})});return o.initialSendAccepted||a({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,t]),n}function X1(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function Z1(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 eN(e,t,n){const a=await n(`/api/v1/sessions/${encodeURIComponent(e)}/interactive-prompt/resolve`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(!a.ok){let r=`HTTP ${a.status}`;try{const o=await a.json();typeof(o==null?void 0:o.error)=="string"&&(r=o.error)}catch{}throw new Error(r)}}async function tN({promptSession:e,response:t,useP2PCommand:n,sendCommand:a,fetchImpl:r=fetch}){if(n){const o=await a(e.routeId,"interactive_prompt_response",{targetSessionId:e.sessionId,sessionId:e.sessionId,response:t});if(!X1(o))throw new Error(Z1(o));return}await eN(e.sessionId,t,r)}function Dh(e){const{ides:t,isP2PActive:n,p2pStates:a}=Ss(),{sendCommand:r}=St(),[o,i]=l.useState(null),[c,d]=l.useState(!1),[p,u]=l.useState(null),m=l.useRef(!1),f=l.useMemo(()=>Nx(t,e),[t,e]),g=!!f,k=l.useMemo(()=>f?f.prompt.promptId===o?null:f:null,[o,f]),h=l.useCallback(async x=>{if(!k||m.current)return;m.current=!0;const y=Jp(k.prompt,x);d(!0),u(null);try{const C=(a==null?void 0:a[k.daemonId])==="connected"||n===!0;await tN({promptSession:k,response:y,useP2PCommand:C,sendCommand:r}),i(k.prompt.promptId)}catch(C){throw u(C instanceof Error?C.message:String(C)),C}finally{d(!1),m.current=!1}},[n,a,k,r]),b=l.useCallback(()=>{k&&i(k.prompt.promptId)},[k]),S=l.useCallback(()=>{i(null),u(null)},[]);return{promptSession:k,hasActivePrompt:g,responseError:p,isSubmitting:c,submit:h,cancel:b,reopen:S}}function Ih(e){return e instanceof Error?e.message:String(e||"")}function sN(e){const t=Ih(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 nN(e){const t=Ih(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Lh({conversation:e,mode:t,ides:n,sendDaemonCommand:a,setCliViewModeOverrides:r}){if(!e||!bt(e)||ht(e))return;const o=ca(e);if(o===t)return;const i=e.sessionId;i&&r(c=>({...c,[i]:t}));try{await a(Vs(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Ds(e),mode:t})}catch(c){const d=nN(c);i&&!d&&r(p=>{const u={...p};return o===rN(n,i)?delete u[i]:u[i]=o,u}),sN(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 Zd(e,t){const n=typeof e.sessionId=="string"&&e.sessionId?e.sessionId:typeof e.id=="string"?e.id:"";if(!n||e.transport!=="pty")return e;const a=t[n];return!a||e.mode===a?e:{...e,mode:a}}function aN(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let n=!1;const a=e.map(r=>{const o=Zd(r,t),i=Array.isArray(r.childSessions)?r.childSessions.map(d=>Zd(d,t)):r.childSessions,c=i!==r.childSessions;return o!==r||c?(n=!0,{...o,...c?{childSessions:i}:{}}):r});return n?a:e}function rN(e,t){if(!t)return null;for(const n of e){if(n.sessionId===t&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal";for(const a of n.childSessions||[])if(a.id===t&&a.transport==="pty")return a.mode==="chat"?"chat":"terminal"}return null}function oN({visibleConversations:e,clearedTabs:t,setClearedTabs:n,setActionLogs:a,isConversationMuted:r}){l.useEffect(()=>{gm()},[]);const o=l.useMemo(()=>e.map(i=>({id:i.tabKey,name:nh(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null,target:{providerSessionId:i.providerSessionId,sessionId:i.sessionId,tabKey:i.tabKey,routeId:i.routeId},muted:r?r(i):!1})),[e,r]);return bk(o),l.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{n(d=>{const p=Date.now(),u={};for(const[m,f]of Object.entries(d))p-f<5e3&&(u[m]=f);return Object.keys(u).length===Object.keys(d).length?d:u})},5500);return()=>clearTimeout(c)},[t,n]),l.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;a(d=>{const p=d.filter(u=>u.timestamp>c).slice(-100);return p.length===d.length?d:p})},6e4);return()=>clearInterval(i)},[a]),null}function eu(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(r=>!(r!=null&&r._localId))||e.messages[e.messages.length-1],n=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,a=eu(t==null?void 0:t.receivedAt)||eu(t==null?void 0:t.timestamp)||0;return Math.max(n,a)}function fl(e,t=0){return Nn(e)||e.lastUpdated||t||0}function Rh(e){return Nn(e)||e.lastUpdated||0}function Eh(e,t,n=Rh){const a=n(t)-n(e);if(a!==0)return a;const r=(e.machineName||"").localeCompare(t.machineName||"");if(r!==0)return r;const o=e.displayPrimary.localeCompare(t.displayPrimary);if(o!==0)return o;const i=e.displaySecondary.localeCompare(t.displaySecondary);return i!==0?i:e.tabKey.localeCompare(t.tabKey)}function gl(e){var n;const t=os(e.status,{activeModal:(n=e.modalButtons)!=null&&n.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function iN(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!gl(e)&&!e.title.trim()}function lN(e){return e.length===0?null:[...e].sort((t,n)=>{const a=Number(gl(n))-Number(gl(t));if(a!==0)return a;const r=n.messages.length-t.messages.length;return r!==0?r:Eh(t,n)})[0]||null}function ws(e,t){const n=e.filter(i=>i.routeId===t);if(n.length===0)return null;const a=n.find(i=>i.streamSource==="native")||null,r=n.filter(i=>i.streamSource==="agent-stream"),o=lN(r);return a?o&&iN(a)?o:a:o||n[0]||null}function cN(e){const t=e.filter(r=>r.type!=="adhdev-daemon"),n=new Set;for(const r of t){if(!tl(r))continue;const o=dm(r);o&&n.add(o)}const a=new Map;for(const r of t){const o=K0(r,n),i=a.get(o);if(!i){a.set(o,r);continue}const c=m=>(m.workspace?1:0)+(m.activeChat?1:0)+(m.lastMessagePreview?1:0),d=c(i),p=c(r),u=p>d||p===d&&(r.timestamp||0)>(i.timestamp||0)?r:i;a.set(o,dN(u,u===r?i:r))}return Array.from(a.values())}function dN(e,t){const n=tl(t),a=tl(e);if(!n&&!a)return e;const r=a?n?void 0:t:e,o=a?e:n?t:void 0,i=r&&String(r.daemonId||"").trim()||String(e.ownerDaemonId||"").trim()||String(t.ownerDaemonId||"").trim()||void 0,c=String(e.ownerMachineName||"").trim()||String(t.ownerMachineName||"").trim()||void 0,d=o==null?void 0:o.settings;return{...e,...i&&{ownerDaemonId:i},...c&&!e.ownerMachineName&&{ownerMachineName:c},...d&&!a&&{settings:{...d,...e.settings??{}}}}}function ni(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 uN(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 tu(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],n=t[t.length-1],a=n?uN(ta(n.content)):"";return[e.id||"",e.title||"",e.status||"",t.length,String((n==null?void 0:n.id)||""),String((n==null?void 0:n.index)??""),String((n==null?void 0:n.receivedAt)??(n==null?void 0:n.timestamp)??""),a].join(":")}function pN(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||""),tu(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||""),tu(n.activeChat)].join(":"))].join("|")}function mN(e,t){const n=Date.now();return e.map(a=>{const r=t[a.tabKey];return r&&n-r<5e3?{...a,messages:[],title:""}:a})}function hN(e,t){const n=new Map;for(const a of e){const r=t.get(a.routeId)||a;for(const o of Ma({routeId:a.routeId}))n.set(o,r);for(const o of Ma({providerSessionId:a.providerSessionId,sessionId:a.sessionId}))n.set(o,a.streamSource==="native"?r:a);for(const o of Ma({tabKey:a.tabKey}))n.set(o,a)}return n}function fN(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function gN(e){const t=fN(e);if(!t)return`empty:${e.messages.length}`;if(t.id)return`id:${String(t.id)}`;if(t._localId)return`local:${String(t._localId)}`;const n=String(t.role||""),a=ta(t.content).slice(0,240);return`${e.messages.length}:${n}:${a}`}function bN({ides:e,connectionStates:t,clearedTabs:n}){const a=l.useMemo(()=>cN(e),[e]),r=l.useMemo(()=>em(e),[e]),o=l.useMemo(()=>hh(e),[e]),i=l.useRef([]),c=l.useRef([]),d=l.useRef([]),p=l.useRef(new Map),u=l.useRef(new Map),m=l.useMemo(()=>{const C=new Map,v=[];for(const A of a){const{connectionState:T="new",machineName:I}=fh(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),P=pN(A),M=p.current.get(A.id);if(M&&M.ide===A&&M.sourceSignature===P&&M.connectionState===T&&M.machineName===I){C.set(A.id,M),v.push(...M.conversations);continue}const E=ic(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),D={ide:A,sourceSignature:P,connectionState:T,machineName:I,conversations:E};C.set(A.id,D),v.push(...E)}p.current=C;const w=new Map,j=A=>{const T=gN(A),I=u.current.get(A.tabKey);if(I&&I.signature===T)return w.set(A.tabKey,I),I.timestamp;const P={signature:T,timestamp:Rh(A)||(I==null?void 0:I.timestamp)||0};return w.set(A.tabKey,P),P.timestamp},N=[...v].sort((A,T)=>Eh(A,T,j));return u.current=w,N},[a,t,o]),f=l.useMemo(()=>{const C=mN(m,n);return ni(i.current,C)?i.current:(i.current=C,C)},[m,n]),g=l.useMemo(()=>{const C=new Map,v=Array.from(new Set(f.map(w=>w.routeId)));for(const w of v){const j=ws(f,w);j&&C.set(w,j)}return C},[f]),k=l.useMemo(()=>{const C=new Map;for(const v of f){const w=g.get(v.routeId),j=v.streamSource==="native"&&w?w:v;for(const N of Ma({providerSessionId:v.providerSessionId,sessionId:v.sessionId,tabKey:v.tabKey}))C.set(N,j)}return C},[f,g]),h=l.useMemo(()=>hN(f,g),[f,g]),b=l.useCallback(C=>{if(C)return k.get(C)},[k]),S=l.useCallback(C=>{if(C)return h.get(C)},[h]),x=l.useMemo(()=>{const C=f.filter(v=>!rn(v,r).surfaceHidden);return ni(c.current,C)?c.current:(c.current=C,C)},[f,r]),y=l.useMemo(()=>{const C=x.map(v=>v.tabKey);return ni(d.current,C)?d.current:(d.current=C,C)},[x]);return{chatIdes:a,conversations:f,visibleConversations:x,visibleTabKeys:y,resolveConversationBySessionId:b,resolveConversationByTarget:S}}function xN({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:n,setSearchParams:a}){const r=l.useMemo(()=>{var c;return e||!t?null:((c=n(t))==null?void 0:c.tabKey)??null},[e,n,t]),o=l.useMemo(()=>{var c;return!e||!t?null:((c=n(t))==null?void 0:c.tabKey)??null},[e,n,t]),i=l.useCallback(()=>{t&&a(c=>{const d=new URLSearchParams(c);return d.delete("activeTab"),d},{replace:!0})},[a,t]);return{requestedDesktopTabKey:r,requestedMobileTabKey:o,consumeRequestedActiveTab:i}}function vN({ides:e,sendDaemonCommand:t,setToasts:n,resolveConversationByTarget:a}){l.useEffect(()=>{ft.setIdes(e)},[e]),l.useEffect(()=>{ft.setResolveAction((r,o,i)=>{t(r,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const r=ft.onToast(o=>{n(c=>c.some(p=>p.message===o.message&&o.timestamp-p.timestamp<3e3)?c:[...c.slice(-4),{id:o.id,message:o.message,type:o.type,timestamp:o.timestamp,targetKey:o.targetKey,actions:o.actions}]);const i=o.duration||5e3;setTimeout(()=>n(c=>c.filter(d=>d.id!==o.id)),i)});return()=>{r()}},[n]),l.useEffect(()=>{const r=Zm.on("status_event",o=>{ft.handleRawEvent(o,"ws")});return()=>{r()}},[]),l.useEffect(()=>{var o;const r=i=>{var h;const c=i.data;if((c==null?void 0:c.type)!=="notification_action"||typeof c.action!="string"||!c.action.startsWith("approval_")||!(c.daemonId||c.targetSessionId||c.targetKey))return;const d=c.targetSessionId||c.targetKey||c.daemonId,p=a(d),u=(p==null?void 0:p.routeId)||c.daemonId;if(!u)return;const m=Number(c.buttonIndex),f=c.button||((h=p==null?void 0:p.modalButtons)==null?void 0:h[m])||"Approve",g=String(f).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),k=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(g);t(u,"resolve_action",{action:k?"approve":"reject",button:f,...Number.isFinite(m)&&{buttonIndex:m},...(p==null?void 0:p.sessionId)&&{targetSessionId:p.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(b=>console.error("[SW Action] approval failed:",b))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",r),()=>{var i;return(i=navigator.serviceWorker)==null?void 0:i.removeEventListener("message",r)}},[a,t])}const yN="adhdev_dashboardLayout_v1",wN="adhdev_dashboardDockview_v1",kN="adhdev_dashboardDockviewHiddenRestore_v1",va={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function pc(e,t){try{const n=localStorage.getItem(e);return n?JSON.parse(n):t}catch{return t}}function SN(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function _h(e){return`${yN}:${e}`}function CN(e){const t=_h(e);return pc(t,null)}function jN(e,t){try{const n=t.groupAssignments.length===0&&t.focusedGroup===0&&Object.keys(t.groupActiveTabIds).length===0&&Object.keys(t.groupTabOrders).length===0&&t.groupSizes.length===0,a=_h(e);if(n){localStorage.removeItem(a);return}localStorage.setItem(a,JSON.stringify(t))}catch{}}function Hh(e){return`${wN}:${e}`}function NN(e){const t=Hh(e);return pc(t,null)}function AN(e,t){try{const n=Hh(e);if(!t){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function $h(e){return`${kN}:${e}`}function TN(e){const t=$h(e);return pc(t,{})}function MN(e,t){try{const n=$h(e);if(Object.keys(t).length===0){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function PN(){return{groupAssignments:[...va.groupAssignments],focusedGroup:va.focusedGroup,groupActiveTabIds:{...va.groupActiveTabIds},groupTabOrders:{...va.groupTabOrders},groupSizes:[...va.groupSizes]}}function DN(e,t){return e?e.length===t.length&&e.every((n,a)=>n===t[a]):t.length===0}function IN(){const[e]=l.useState(()=>SN(typeof window<"u"?window.innerWidth:1280)),[t,n]=l.useState(()=>new Map),[a,r]=l.useState(0),[o,i]=l.useState({}),[c,d]=l.useState({}),[p,u]=l.useState([]),[m,f]=l.useState(()=>typeof window<"u"&&window.innerWidth<768),[g,k]=l.useState(!1),h=l.useCallback(()=>{if(g)return;const A=CN(e)??PN();n(new Map(A.groupAssignments)),r(A.focusedGroup),i(A.groupActiveTabIds),d(A.groupTabOrders),u(A.groupSizes),k(!0)},[g,e]);l.useEffect(()=>{g&&jN(e,{groupAssignments:[...t.entries()],focusedGroup:a,groupActiveTabIds:o,groupTabOrders:c,groupSizes:p})},[g,e,t,a,o,c,p]),l.useEffect(()=>{const A=window.matchMedia("(max-width: 767px)"),T=I=>f(I.matches);return A.addEventListener("change",T),()=>A.removeEventListener("change",T)},[]);const b=l.useCallback(A=>{n(A)},[]),S=l.useCallback(A=>{r(A)},[]),x=l.useCallback(A=>{i(A)},[]),y=l.useCallback(A=>{d(A)},[]),C=l.useCallback(A=>{u(A)},[]),v=l.useCallback(A=>{S(A)},[S]),w=l.useCallback((A,T)=>{i(I=>(I[A]??null)===(T??null)?I:{...I,[A]:T})},[]),j=l.useCallback((A,T)=>{d(I=>{const P=I[A];return DN(P,T)?I:{...I,[A]:T}})},[]),N=l.useCallback((A,T)=>{const I=T.get(A)??0;return w(I,A),v(I),I},[v,w]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:b,focusedGroup:a,updateFocusedGroup:S,focusGroup:v,groupActiveTabIds:o,updateGroupActiveTabIds:x,setGroupActiveTab:w,groupTabOrders:c,updateGroupTabOrders:y,setGroupTabOrder:j,groupSizes:p,updateGroupSizes:C,isMobile:m,hasHydratedStoredLayout:g,hydrateStoredLayout:h,focusConversationTab:N}}function LN(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0],a=bo(t);return typeof(n==null?void 0:n.id)=="string"&&a.includes(n.id)}function RN({urlActiveTab:e,conversations:t,resolveConversationBySessionId:n,normalizedGroupAssignments:a,hasHydratedStoredLayout:r,hydrateStoredLayout:o,focusConversationTab:i,setSearchParams:c,historyModalOpen:d,activeConv:p,isRefreshingHistory:u,ides:m,handleRefreshHistory:f}){const g=l.useRef(!1),k=l.useRef(!1),h=l.useRef(null),b=l.useRef(!1);l.useEffect(()=>{if(!e||g.current||t.length===0)return;if(!r){o();return}const S=n(e);S&&(i(S.tabKey,a),g.current=!0,k.current=!0,h.current!=null&&(window.clearTimeout(h.current),h.current=null),c(x=>{const y=new URLSearchParams(x);return y.delete("activeTab"),y},{replace:!0}))},[e,t,n,a,r,o,i,c]),l.useEffect(()=>{if(!(k.current||r)&&t.length!==0){if(!e){o(),k.current=!0;return}if(g.current){k.current=!0;return}if(h.current==null)return h.current=window.setTimeout(()=>{h.current=null,!(k.current||r)&&(o(),k.current=!0)},1500),()=>{h.current!=null&&(window.clearTimeout(h.current),h.current=null)}}},[e,t.length,r,o]),l.useEffect(()=>{if(!d){b.current=!1;return}if(!p||b.current||u)return;const S=m.find(x=>x.id===p.routeId);S&&(!S.chats||S.chats.length===0||LN(S.chats,p))&&(b.current=!0,f())},[d,p,u,m,f])}function ai(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0];if((n==null?void 0:n.active)===!0)return!0;const a=bo(t);return typeof(n==null?void 0:n.id)=="string"&&a.includes(n.id)}function Fh({sendDaemonCommand:e,activeConv:t,chats:n,updateRouteChats:a,setToasts:r,setClearedTabs:o}){const[i,c]=l.useState(!1),[d,p]=l.useState(!1),u=l.useCallback(async k=>{try{await e("standalone","launch_ide",{ideType:k,enableCdp:!0})}catch(h){console.error("Launch failed",h)}},[e]),m=l.useCallback(async(k,h)=>{try{const b=k||(t==null?void 0:t.daemonId)||"",S=await e(b,"switch_chat",{id:h,sessionId:h,...wn(t)}),x=S==null?void 0:S.result;if((S==null?void 0:S.success)===!0||x==="switched"||x==="switched-by-title")return;x===!1||x==="not_found"?qn(r,"⚠️ Session tab not found — try refreshing history"):typeof x=="string"&&x.startsWith("error:")?qn(r,`⚠️ Switch error: ${x}`):qn(r,"⚠️ Session switch failed")}catch(b){console.error("Switch failed",b),qn(r,`❌ Switch failed: ${b.message||"connection error"}`)}},[t,e,r]),f=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const k=kn(t);await e(k,"new_chat",{...wn(t)}),xC(k,t.sessionId,bo(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 b=kn(t),S=async()=>e(b,"list_chats",{forceExpand:!0,...wn(t)});let x=await S(),y=(x==null?void 0:x.chats)||((k=x==null?void 0:x.result)==null?void 0:k.chats);ai(y,t)&&(await new Promise(C=>setTimeout(C,450)),x=await S(),y=(x==null?void 0:x.chats)||((h=x==null?void 0:x.result)==null?void 0:h.chats)),x!=null&&x.success&&Array.isArray(y)&&(a(t.routeId,y),ai(y,t)&&!ai(n,t)&&qn(r,"⚠️ History dialog did not fully open — try once more"))}catch(b){console.error("Refresh history failed",b)}finally{p(!1)}}},[t,n,d,e,a,r]);return{isCreatingChat:i,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:m,handleNewChat:f,handleRefreshHistory:g}}function EN(e,t){if(e.size!==t.size)return!1;for(const[n,a]of e)if(t.get(n)!==a)return!1;return!0}function _N(e,t){return e.length!==t.length?!1:e.every((n,a)=>n===t[a])}function su(e,t){const n=Object.keys(e),a=Object.keys(t);return n.length!==a.length?!1:n.every(r=>t[Number(r)]===e[Number(r)])}function dr(e,t){const n=new Set(t),a=t.length>0?[0]:[];for(const[i,c]of e)!n.has(i)||c<=0||a.includes(c)||a.push(c);a.sort((i,c)=>i-c);const r={};a.forEach((i,c)=>{r[i]=c}),a.length===0&&(r[0]=0);const o=new Map;for(const[i,c]of e){if(!n.has(i)||c<=0)continue;const d=r[c];typeof d=="number"&&d>0&&o.set(i,d)}return{assignments:o,groupCount:Math.max(1,a.length),mapping:r,usedGroups:a}}function nu(e,t){const n={};for(const[a,r]of Object.entries(e)){const o=t[Number(a)];typeof o=="number"&&(n[o]=r)}return n}function HN(e,t,n){if(t.length===0)return 0;if(typeof n[e]=="number")return n[e];const a=[...t].reverse().find(r=>r<e)??t[0];return n[a]??0}function $N(e,t,n){if(t.length<=1)return[];const a=t.map(i=>e[i]).filter(i=>Number.isFinite(i)),r=a.length===t.length?a:Array(n).fill(100/n),o=r.reduce((i,c)=>i+c,0);return o>0?r.map(i=>i/o*100):Array(n).fill(100/n)}function au(e,t){const n={};for(const[a,r]of Object.entries(e)){const o=Number(a);n[o>=t?o+1:o]=r}return n}function ru(e){return Array(e).fill(100/e)}function FN({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:n,updateGroupActiveTabIds:a,updateGroupTabOrders:r,groupSizes:o,updateGroupSizes:i,isMobile:c,visibleConversations:d,visibleTabKeys:p}){const u=l.useRef(null),m=l.useMemo(()=>dr(e,p),[e,p]),f=m.assignments,g=l.useMemo(()=>c?1:m.groupCount,[m.groupCount,c]),k=g>1,h=l.useCallback((v,w)=>{t(j=>{const N=new Map(dr(j,p).assignments);return w===0?N.delete(v):N.set(v,w),N}),a(j=>({...j,[w]:v})),n(w)},[t,p,a,n]),b=l.useCallback(v=>{t(w=>{const j=dr(w,p).assignments,N=new Map;for(const[A,T]of j)T!==v&&(T>v?N.set(A,T-1):N.set(A,T));return N}),i(w=>{if(w.length<=1)return[];const j=[...w];j.splice(v,1);const N=j.reduce((A,T)=>A+T,0);return N>0?j.map(A=>A/N*100):[]}),n(0)},[t,p,i,n]),S=l.useCallback((v,w)=>{w.preventDefault();const j=u.current;if(!j)return;const N=w.clientX,A=j.offsetWidth,T=o.length===g?[...o]:ru(g),I=M=>{const D=(M.clientX-N)/A*100,W=[...T];W[v]=Math.max(15,T[v]+D),W[v+1]=Math.max(15,T[v+1]-D),i(W)},P=()=>{document.removeEventListener("mousemove",I),document.removeEventListener("mouseup",P),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",I),document.addEventListener("mouseup",P)},[o,g,i]),x=l.useCallback((v,w,j)=>{if(g>=4)return;const N=j==="left"?w:w+1;t(A=>{const T=dr(A,p).assignments,I=new Map;for(const P of d){const M=T.get(P.tabKey)??0,E=M>=N?M+1:M;E>0&&I.set(P.tabKey,E)}return N>0&&I.set(v,N),I}),i(A=>{const T=A.length===g?[...A]:ru(g),I=T[w]??100/g,P=Math.max(15,I/2),M=Math.max(15,I/2),E=[...T];E[w]=P,E.splice(N,0,M);const D=E.reduce((W,R)=>W+R,0);return E.map(W=>W/D*100)}),a(A=>{const T=au(A,N);return T[N]=v,T}),r(A=>{const T=au(A,N);return T[N]=[v],T}),n(N)},[g,t,p,d,i,a,r,n]);l.useEffect(()=>{EN(e,f)||t(f)},[e,f,t]),l.useEffect(()=>{const{mapping:v,usedGroups:w}=m;a(j=>{const N=nu(j,v);return su(j,N)?j:N}),r(j=>{const N=nu(j,v);return su(j,N)?j:N}),n(j=>{const N=c?0:HN(j,w,v);return j===N?j:N}),i(j=>{const N=c?[]:$N(j,w,m.groupCount);return _N(j,N)?j:N})},[m,c,a,r,n,i]);const y=l.useMemo(()=>{const v=Array.from({length:g},()=>[]);for(const w of d){const j=f.get(w.tabKey)??0,N=Math.min(j,g-1);v[N].push(w)}return v},[d,f,g]),C=l.useCallback(()=>{t(new Map),n(0)},[t,n]);return{containerRef:u,normalizedGroupAssignments:f,numGroups:g,isSplitMode:k,groupedConvs:y,moveTabToGroup:h,closeGroup:b,handleResizeStart:S,splitTabRelative:x,clearAllSplits:C}}function BN({ides:e,sendDaemonCommand:t}){const n="1.0.56",a=l.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:jo(m,Js(m,n))).sort((m,f)=>Number(Da(f,Js(f,n)))-Number(Da(m,Js(m,n)))),[n,e]),r=l.useMemo(()=>a.some(m=>Da(m,Js(m,n))),[n,a]),o=l.useMemo(()=>a.map(m=>Js(m,n)).find(m=>typeof m=="string"&&m.trim().length>0)||n,[n,a]),[i,c]=l.useState(!1),[d,p]=l.useState({}),u=l.useCallback(async m=>{var k,h;const f=e.find(b=>b.id===m);if(!f)return;p(b=>({...b,[m]:"upgrading"}));const g=No(f);if(!g){p(b=>({...b,[m]:"error"}));return}try{const b=await t(m,"daemon_upgrade",g);(k=b==null?void 0:b.result)!=null&&k.upgraded||(h=b==null?void 0:b.result)!=null&&h.success?p(S=>({...S,[m]:"done"})):p(S=>({...S,[m]:"error"}))}catch{p(b=>({...b,[m]:"error"}))}},[e,t]);return{versionMismatchDaemons:a,hasRequiredVersionDaemons:r,targetVersion:o,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:u}}const Bh=80;function Dr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function WN(e){return{...e,createdAt:Dr(e.createdAt),updatedAt:Dr(e.updatedAt,e.createdAt),lastEventAt:Dr(e.lastEventAt,e.updatedAt||e.createdAt)}}function ON(e){const t=cm(e);return t==="unknown:"?e.id:t}function UN(e){return[e.type,lm(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function GN(e,t=Bh){const n=new Map;for(const a of e){if(a.deletedAt)continue;const r=ON(a),o=n.get(r);if(!o){n.set(r,a);continue}(a.updatedAt>o.updatedAt||a.updatedAt===o.updatedAt&&a.createdAt>o.createdAt)&&n.set(r,a)}return Array.from(n.values()).sort((a,r)=>{const o=r.updatedAt-a.updatedAt;return o!==0?o:r.createdAt-a.createdAt}).slice(0,Math.max(0,t))}function qN(e,t){const n=Date.now(),a=[];for(const r of e){const o=r.sessionId?t.get(r.sessionId):void 0;if(o!=null&&o.surfaceHidden||o!=null&&o.muted)continue;const i=go(r,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const d=Dr(r.lastMessageAt||(o==null?void 0:o.lastUpdated)||r.lastUpdated,n),p=UN({type:c,sessionId:r.sessionId,providerSessionId:r.providerSessionId,tabKey:r.tabKey,lastMessageHash:r.lastMessageHash,lastMessageAt:r.lastMessageAt,lastUpdated:(o==null?void 0:o.lastUpdated)||r.lastUpdated});a.push(WN({id:p,dedupKey:p,type:c,routeId:r.routeId,machineId:r.daemonId||r.routeId,sessionId:r.sessionId,providerSessionId:r.providerSessionId,tabKey:r.tabKey,title:Pm(r),preview:PS(r),createdAt:d,updatedAt:d,lastEventAt:d}))}return GN(a)}function zN(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function KN(e){const{conversations:t,liveSessionInboxState:n,maxItems:a=Bh}=e,r=l.useMemo(()=>qN(t,n).slice(0,Math.max(0,a)),[t,n,a]),o=l.useMemo(()=>zN(r),[r]);return{notifications:r,unreadCount:o}}function VN({notifications:e,sendDaemonCommand:t}){const n=l.useCallback(o=>{const i=e.find(d=>d.id===o),c=Math.max(Date.now(),(i==null?void 0:i.updatedAt)||0);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_session_seen",{sessionId:i.sessionId,seenAt:c}).catch(()=>{})},[e,t]),a=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_notification_unread",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]),r=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"delete_notification",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:n,handleMarkDashboardNotificationUnread:a,handleDeleteDashboardNotification:r}}function mc(...e){const t=new Set,n=[],a=r=>{const o=typeof r=="string"?r.trim():"";if(!o)return;const i=o.toLowerCase();t.has(i)||(t.add(i),n.push(o))};for(const r of e){if(Array.isArray(r)){for(const o of r)a(o);continue}a(r)}return n}function YN(e){const t=e.trim();if(!t)return null;if(t.startsWith("~"))return t;if(/^[A-Za-z]:$/.test(t))return`${t[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(t))return`${t[0].toUpperCase()}:${t.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(t))return`${t[0].toUpperCase()}:\\${t.slice(2).replace(/[\\/]+/g,"\\")}`;const n=t.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(n){const a=n[1].toUpperCase(),r=(n[2]||"").replace(/[\\/]+/g,"\\");return r?`${a}:\\${r}`:`${a}:\\`}return null}function hc(e,t=[]){if(e==="win32"){for(const n of t){if(typeof n!="string")continue;const a=YN(n);if(a)return a}return"C:\\"}for(const n of t){const a=typeof n=="string"?n.trim():"";if(a)return a}return"~"}function QN(e){const t=e.replace(/[\\/]+$/,"");if(!t||t==="/"||/^[A-Za-z]:$/.test(t))return null;const n=t.includes("\\")?"\\":"/",a=t.split(/[\\/]/);return/^[A-Za-z]:$/.test(a[0]||"")?a.length<=2?`${a[0]}\\`:a.slice(0,-1).join("\\"):a.length<=2?n:a.slice(0,-1).join(n)||n}function JN(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function fc(e,t,n){const a=await e(t,"file_list_browse",{path:n}),r=JN(a);if(!(r!=null&&r.success))throw new Error((r==null?void 0:r.error)||(a==null?void 0:a.error)||"Could not browse folder");const o=typeof(r==null?void 0:r.path)=="string"?r.path:n,i=o.includes("\\")?"\\":"/",c=(p,u)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${u}`:p==="/"||p==="\\"?`${i}${u}`:`${p.replace(/[\\/]+$/,"")}${i}${u}`,d=Array.isArray(r==null?void 0:r.files)?r.files.filter(p=>(p==null?void 0:p.type)==="directory"&&typeof(p==null?void 0:p.name)=="string").map(p=>({name:p.name,path:typeof(p==null?void 0:p.path)=="string"&&p.path.trim()?p.path:c(o,p.name)})).sort((p,u)=>p.name.localeCompare(u.name)):[];return{path:o,directories:d}}function ou(e,t){const n=t.meshId||"",a={meshId:n,workspace:t.workspace||"",serverName:t.serverName||"adhdev-mesh",adhdevMcpCommand:t.adhdevMcpCommand||"adhdev-mcp",adhdevMcpArgs:t.adhdevMcpArgs||`mcp --mode ipc --repo-mesh ${n}`};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand|adhdevMcpArgs)\s*\}\}/g,(r,o)=>a[o]||"")}function Wh(e,t={}){const n=e==null?void 0:e.mcpConfig;if((n==null?void 0:n.mode)!=="manual")return null;const r=ou(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"}).trim();return!r.includes(`
|
|
65
|
-
`)&&!r.startsWith("{")?null:{serverName:n.serverName||"adhdev-mesh",configFormat:n.format,configPathCommand:n.configPathCommand,requiresRestart:n.requiresRestart===!0,instructions:n.instructions||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:ou(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"})}}function XN(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.instructions=="string"?t.instructions:"",a=typeof t.template=="string"?t.template:"";return!n&&!a?null:{serverName:typeof t.serverName=="string"?t.serverName:void 0,configFormat:typeof t.configFormat=="string"?t.configFormat:void 0,configPathCommand:typeof t.configPathCommand=="string"?t.configPathCommand:void 0,requiresRestart:t.requiresRestart===!0,instructions:n||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:a}}function Wa(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Oh(e){return xo(e)||e.tabKey||e.routeId||null}function Uh(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"",n=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"",a=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"",r=e.conversations.find(o=>{if(a&&o.routeId!==a)return!1;const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey].map(c=>typeof c=="string"?c.trim():"").filter(Boolean);return!!(t&&i.includes(t)||n&&i.includes(n)||a&&o.routeId===a)});if(r!=null&&r.tabKey)return r.tabKey;if(a){const o=ws(e.conversations,a)||e.conversations.find(i=>i.routeId===a);if(o!=null&&o.tabKey)return o.tabKey}return t||n||a||null}function Xs(e){return String(e||"").trim()}function Gh(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Zr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function ZN(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function eA(e,t){const n=Xs(e.providerSessionId),a=Xs(e.targetSessionId),r=t.find(o=>{const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(Xs).filter(Boolean);return!!(n&&i.includes(n)||a&&i.includes(a))});return r?r.tabKey:a||n||null}function tA(e,t,n){if(t.event!=="agent:generating_completed")return null;const a=Gh(t.daemonId);if(a&&a!==e.machineId)return null;const r=Xs(t.providerType);if(e.providerType&&r!==e.providerType)return null;const o=Xs(e.resumeSessionId),i=Xs(e.launchedSessionId),c=Xs(t.providerSessionId),d=Xs(t.targetSessionId);if(o&&o!==c&&o!==d||i&&i!==c&&i!==d)return null;const p=Zr(e.workspacePath);if(p){const u=Zr(t.workspaceName);if(u&&!ZN(u,p))return null}return eA(t,n)}function iu(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function sA({ides:e,conversations:t,onOpenSession:n}){const[a,r]=l.useState(null),o=l.useRef(null),i=l.useCallback(()=>{o.current=null,r(null)},[]),c=l.useCallback(d=>{o.current=d,r(d)},[]);return l.useEffect(()=>{if(!a)return;const d=Zr(a.workspacePath),p=e.find(m=>{var b,S,x,y;if(!m||m.type==="adhdev-daemon"||Gh(m.daemonId||m.id)!==a.machineId||(Fa(m)?"cli":Xn(m)?"acp":"ide")!==a.kind)return!1;const k=String(m.agentType||m.type||"");if(a.providerType&&k!==a.providerType)return!1;if(a.resumeSessionId)return String(m.providerSessionId||"")===a.resumeSessionId;if(a.launchedSessionId){const C=String(a.launchedSessionId||"");return[m.providerSessionId,m.sessionId,m.instanceId,m.id].map(w=>String(w||"")).filter(Boolean).includes(C)}if(d){const C=Zr(m.workspace||m.runtimeWorkspaceLabel);return C?C===d:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((y=(x=(S=(b=m.activeChat)==null?void 0:b.messages)==null?void 0:S.at)==null?void 0:x.call(S,-1))==null?void 0:y.timestamp)||0)>=a.startedAt-5e3});if(!p)return;const u=Uh({entrySessionId:p.sessionId,entryInstanceId:p.instanceId,entryRouteId:p.id,conversations:t});u&&(i(),n(u))},[i,t,e,n,a]),l.useEffect(()=>ft.onStatusEvent(d=>{const p=o.current;if(!p)return;const u=tA(p,d,t);u&&(i(),n(u))}),[i,t,n]),l.useEffect(()=>{if(!a)return;const d=window.setTimeout(()=>{r(p=>!p||p.startedAt!==a.startedAt?p:(o.current=null,null))},45e3);return()=>window.clearTimeout(d)},[a]),{trackPendingLaunch:c}}function nA(e,t){var a,r,o,i;const n={cliType:e};return(a=t==null?void 0:t.workspacePath)!=null&&a.trim()?n.dir=t.workspacePath.trim():t!=null&&t.workspaceId?n.workspaceId=t.workspaceId:t!=null&&t.useHome&&(n.useHome=!0),(r=t==null?void 0:t.resumeSessionId)!=null&&r.trim()&&(n.resumeSessionId=t.resumeSessionId.trim()),Array.isArray(t==null?void 0:t.cliArgs)&&t.cliArgs.length>0&&(n.cliArgs=t.cliArgs),(o=t==null?void 0:t.initialModel)!=null&&o.trim()&&(n.initialModel=t.initialModel.trim()),(i=t==null?void 0:t.initialThinkingLevel)!=null&&i.trim()&&(n.initialThinkingLevel=t.initialThinkingLevel.trim()),t!=null&&t.settings&&(n.settings=t.settings),n}function aA(e,t,n){var i,c,d,p;const a={meshId:e.trim()};t.trim()&&(a.cliType=t.trim());const r=(i=n==null?void 0:n.initialModel)==null?void 0:i.trim(),o=(c=n==null?void 0:n.initialThinkingLevel)==null?void 0:c.trim();return r&&(a.initialModel=r),o&&(a.initialThinkingLevel=o),(d=n==null?void 0:n.settings)!=null&&d.autoApproveMode?a.autoApproveMode=n.settings.autoApproveMode:typeof((p=n==null?void 0:n.settings)==null?void 0:p.autoApprove)=="boolean"&&(a.autoApprove=n.settings.autoApprove),a}function rA({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:n,activeConv:a,ides:r,setCliViewModeOverrides:o}){const i=Ql(),{launchCli:c}=fo(),d=l.useCallback(async(b,S)=>fc(e,b,S),[e]),p=l.useCallback(async(b,S)=>{if(!S.trim())return{ok:!1,error:"Choose a workspace path first."};try{const x=await e(b,"workspace_add",{path:S.trim()});return x!=null&&x.success?{ok:!0}:{ok:!1,error:(x==null?void 0:x.error)||"Could not save workspace"}}catch(x){return{ok:!1,error:x instanceof Error?x.message:"Could not save workspace"}}},[e]),u=l.useCallback(async(b,S,x)=>{var y;try{const C={ideType:S,enableCdp:!0};(y=x==null?void 0:x.workspacePath)!=null&&y.trim()&&(C.workspace=x.workspacePath.trim());const v=await e(b,"launch_ide",C);return!(v!=null&&v.success)&&(v==null?void 0:v.success)!==void 0?{ok:!1,error:(v==null?void 0:v.error)||"Could not launch IDE"}:(t({machineId:b,kind:"ide",providerType:S,workspacePath:(x==null?void 0:x.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(b,S,x,y)=>{const C=Date.now();try{const v=nA(x,y),w=await c(b,v),j=(w==null?void 0:w.result)||w,N=(j==null?void 0:j.sessionId)||(j==null?void 0:j.id);return w!=null&&w.success&&N?(t({machineId:b,kind:S,providerType:x,workspacePath:(y==null?void 0:y.workspacePath)||null,resumeSessionId:(y==null?void 0:y.resumeSessionId)||null,launchedSessionId:N,startedAt:C}),{ok:!0}):w!=null&&w.success?(t({machineId:b,kind:S,providerType:x,workspacePath:(y==null?void 0:y.workspacePath)||null,resumeSessionId:(y==null?void 0:y.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:(w==null?void 0:w.error)||(j==null?void 0:j.error)||`Could not launch ${S.toUpperCase()} session`,code:(w==null?void 0:w.code)||(j==null?void 0:j.code)||void 0}}catch(v){return iu(v)?(t({machineId:b,kind:S,providerType:x,workspacePath:(y==null?void 0:y.workspacePath)||null,resumeSessionId:(y==null?void 0:y.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:v instanceof Error?v.message:`Could not launch ${S.toUpperCase()} session`}}},[c,e,t]),f=l.useCallback(async b=>{var S;if(i!=null&&i.listMeshes)return i.listMeshes(b);if(!b)return[];try{const x=await e(b,"list_meshes",{}),y=(x==null?void 0:x.result)??x;if((y==null?void 0:y.success)===!1)throw new Error((y==null?void 0:y.error)||"Could not load meshes");return(Array.isArray(y==null?void 0:y.meshes)?y.meshes:Array.isArray((S=y==null?void 0:y.result)==null?void 0:S.meshes)?y.result.meshes:[]).map(v=>{var w;return{id:String((v==null?void 0:v.id)||""),name:String((v==null?void 0:v.name)||(v==null?void 0:v.id)||"Untitled mesh"),repoIdentity:(v==null?void 0:v.repoIdentity)||(v==null?void 0:v.repo_identity)||null,workspace:Array.isArray(v==null?void 0:v.nodes)&&v.nodes.length>0?String(((w=v.nodes[0])==null?void 0:w.workspace)||""):null,nodesCount:Array.isArray(v==null?void 0:v.nodes)?v.nodes.length:void 0,status:(v==null?void 0:v.status)||null}}).filter(v=>v.id)}catch(x){throw console.error("List meshes failed",x),x}},[i,e]),g=l.useCallback(async(b,S,x,y)=>{if(!S.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(b,S,x,y);const C=Date.now();try{const v=aA(S,x,y),w=await e(b,"launch_mesh_coordinator",v),j=(w==null?void 0:w.result)??w;if((j==null?void 0:j.success)===!1||(w==null?void 0:w.success)===!1){const A=String((j==null?void 0:j.code)||(w==null?void 0:w.code)||""),T=XN((j==null?void 0:j.meshCoordinatorSetup)||(j==null?void 0:j.manualSetup)||(w==null?void 0:w.meshCoordinatorSetup)||(w==null?void 0:w.manualSetup));return{ok:!1,error:(j==null?void 0:j.error)||(w==null?void 0:w.error)||"Could not launch mesh coordinator",code:A||void 0,manualSetup:T}}const N=(j==null?void 0:j.sessionId)||(j==null?void 0:j.id);return N?n(N):t({machineId:b,kind:"cli",providerType:(j==null?void 0:j.cliType)||x.trim()||void 0,workspacePath:(j==null?void 0:j.workspace)||null,startedAt:C}),{ok:!0}}catch(v){return iu(v)?(t({machineId:b,kind:"cli",providerType:x.trim()||void 0,startedAt:C}),{ok:!0}):{ok:!1,error:v instanceof Error?v.message:"Could not launch mesh coordinator"}}},[i,n,e,t]),k=l.useCallback(async(b,S)=>{if(!b||!S)return[];try{const x=await e(b,"list_saved_sessions",{providerType:S,kind:"cli",limit:30}),y=(x==null?void 0:x.result)??x;return Array.isArray(y==null?void 0:y.sessions)?y.sessions:[]}catch(x){return console.error("List saved sessions failed",x),[]}},[e]),h=l.useCallback(async b=>{await Lh({conversation:a,mode:b,ides:r,sendDaemonCommand:e,setCliViewModeOverrides:o})},[a,r,e,o]);return{handleBrowseMachineDirectory:d,handleSaveMachineWorkspace:p,handleLaunchMachineIde:u,handleLaunchMachineProvider:m,handleListMachineMeshes:f,handleLaunchMeshCoordinator:g,handleListMachineSavedSessions:k,setActiveCliViewMode:h}}function oA(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 iA(e,t,n=Date.now()){return!e||!oA(t)?null:{tabKey:e,nonce:n}}function lA({isMobile:e,conversations:t,visibleConversations:n,groupActiveTabIds:a,focusedGroup:r,groupedConvs:o,setSearchParams:i}){const[c,d]=l.useState(null),[p,u]=l.useState(null),m=l.useMemo(()=>{var b,S;if(!e){if(c){const x=t.find(y=>y.tabKey===c);if(x)return x}return n[0]}const h=a[r];if(h){const x=t.find(y=>y.tabKey===h);if(x)return x}return((b=o[r])==null?void 0:b[0])||((S=o[0])==null?void 0:S[0])},[t,c,r,a,o,e,n]),f=l.useCallback(h=>{d(h)},[]),g=l.useCallback(h=>{d(h.tabKey),i(b=>{const S=new URLSearchParams(b),x=IS(h);return x?S.set("activeTab",x):S.delete("activeTab"),S},{replace:!0})},[i]),k=l.useCallback((h,b)=>{const S=iA(h,b);S&&u(S)},[]);return{activeConv:m,openDesktopConversation:g,requestScrollToBottom:k,scrollToBottomRequest:p,setDesktopActiveTab:f}}function cA(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 dA(e){const t=String(e.liveState.completionMarker||""),n=String(e.liveState.seenCompletionMarker||""),a=String(e.liveState.inboxBucket||"idle"),r=!!e.liveState.unread,o=[e.tabKey,e.historySessionId||"",t,n,a,r?"1":"0"].join(":");return{shouldMarkSeen:!!(a==="task_complete"&&r&&(!t||t!==n)),autoReadKey:o,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function uA({activeConv:e,isMobile:t,liveSessionInboxState:n,sendDaemonCommand:a}){const r=l.useRef(null),o=l.useRef(null),i=l.useRef(null),c=l.useRef(null),d=l.useRef(null);l.useEffect(()=>{const p=()=>{i.current&&(clearTimeout(i.current),i.current=null),c.current&&(clearTimeout(c.current),c.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),o.current=null};if(t){p(),r.current=null;return}if(!(e!=null&&e.sessionId)){p(),r.current=null;return}const u=rn(e,n),m=dA({tabKey:e.tabKey,historySessionId:xo(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:Nn(e),liveState:u}),f=m.autoReadKey,g=cA({autoReadKey:f,shouldMarkSeen:m.shouldMarkSeen,completedKey:r.current,pendingKey:o.current});if(!m.shouldMarkSeen){g.shouldCancelPending&&p(),r.current=f;return}if(!g.shouldSchedule)return;g.shouldCancelPending&&p();const k=()=>{if(document.visibilityState!=="visible"||r.current===f)return;r.current=f,o.current=null,i.current=null,c.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const b=m.readAt;a(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:b,completionMarker:m.completionMarker}).catch(()=>{})};if(o.current=g.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(k,1500);const b=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};d.current=b,document.addEventListener("visibilitychange",b);return}const h=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(k,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=h,document.addEventListener("visibilitychange",h)},[e,t,n,a]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current),c.current&&clearTimeout(c.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function ri(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 pA({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:n,ides:a,sendDaemonCommand:r,updateRouteChats:o,setToasts:i,setClearedTabs:c,setSearchParams:d}){var B;const{launchCli:p}=fo(),[u,m]=l.useState(!1),[f,g]=l.useState([]),[k,h]=l.useState(()=>qt()),[b,S]=l.useState(!1),[x,y]=l.useState(null),C=l.useRef(null),v=l.useMemo(()=>n||t||e,[e,n,t]),w=!!v&&bt(v)&&!ht(v),j=l.useMemo(()=>{if(!v||!w)return null;const _=v.daemonId||v.routeId||"",H=Ds(v),L=ri(v);return`${_}:${H}:${v.providerSessionId||""}:${L}`},[v,w]),N=l.useMemo(()=>!v||!w?"":ri(v),[v,w]),{isCreatingChat:A,isRefreshingHistory:T,handleSwitchSession:I,handleNewChat:P,handleRefreshHistory:M}=Fh({sendDaemonCommand:r,activeConv:v,chats:(B=a.find(_=>_.id===(v==null?void 0:v.routeId)))==null?void 0:B.chats,updateRouteChats:o,setToasts:i,setClearedTabs:c}),E=l.useCallback(()=>{m(!0)},[]),D=l.useCallback(()=>{m(!1)},[]),W=l.useCallback(async()=>{if(!(!v||!w||b)){S(!0);try{const _=v.daemonId||v.routeId,H=Ds(v),L=ri(v),F=await r(_,"list_saved_sessions",{agentType:H,providerType:H,kind:"cli",limit:50,...v.providerSessionId?{providerSessionId:v.providerSessionId}:{},...L?{workspace:L}:{}}),$=(F==null?void 0:F.result)??F;g(Array.isArray($==null?void 0:$.sessions)?$.sessions:[])}catch(_){console.error("Refresh saved sessions failed",_),g([])}finally{S(!1)}}},[v,b,w,r]);l.useEffect(()=>{if(!u){C.current=null;return}if(!w){C.current=null,g([]),S(!1);return}!j||b||C.current!==j&&(C.current=j,W())},[W,u,b,w,j]);const R=l.useCallback(async _=>{if(!v||!w||!_.providerSessionId||!_.workspace)return;const H=v.daemonId||v.routeId,L=Ds(v);try{y(_.providerSessionId);const F=await p(H,{cliType:L,dir:_.workspace,resumeSessionId:_.providerSessionId,initialModel:hm(_.summaryMetadata,"model",{preferShortValue:!0})||void 0}),$=(F==null?void 0:F.result)??F,K=typeof($==null?void 0:$.sessionId)=="string"?$.sessionId:typeof($==null?void 0:$.id)=="string"?$.id:"";K&&d(z=>{const ne=new URLSearchParams(z);return ne.set("activeTab",K),ne},{replace:!0}),D()}catch(F){console.error("Resume saved session failed",F)}finally{y(null)}},[D,v,w,r,d]);return{historyModalOpen:u,openHistoryModal:E,closeHistoryModal:D,historyTargetConv:v,isSavedSessionHistoryTarget:w,isHistoryCreatingChat:A,isHistoryRefreshingHistory:T,handleHistorySwitchSession:I,handleHistoryNewChat:P,handleHistoryRefresh:M,savedHistorySessions:f,savedHistoryFilters:k,setSavedHistoryFilters:h,missingWorkspaceResumePath:N,isSavedHistoryLoading:b,resumingSavedHistorySessionId:x,handleRefreshSavedHistory:W,handleResumeSavedHistorySession:R}}function mA({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c}){const[d,p]=l.useState(null),[u,m]=l.useState(null),f=l.useMemo(()=>{if(e||!a)return null;const S=c(a);return S&&!bt(S)&&!ht(S)?S:null},[e,a,c]),g=l.useMemo(()=>{const S=d==null?void 0:d.routeId;if(!S)return null;const x=d!=null&&d.tabKey?o.find(y=>y.tabKey===d.tabKey):r?o.find(y=>y.tabKey===r):null;return(x==null?void 0:x.routeId)===S?x:ws(o,S)},[o,d,r]),k=l.useMemo(()=>{if(g)return i.find(S=>S.id===g.routeId)},[i,g]);l.useEffect(()=>{f&&(p({routeId:f.routeId,tabKey:xd(f)}),m(f),n({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,n,f]);const h=l.useCallback(S=>{S&&(p({routeId:S.routeId,tabKey:xd(S)}),m(S))},[]),b=l.useCallback(()=>{p(null),m(null)},[]);return{remoteDialogConv:g,remoteDialogIdeEntry:k,remoteDialogActiveConv:u,setRemoteDialogActiveConv:m,openRemoteDialog:h,closeRemoteDialog:b}}function hA({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c,activeConv:d,sendDaemonCommand:p}){const{remoteDialogConv:u,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:g,openRemoteDialog:k,closeRemoteDialog:h}=mA({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c}),[b,S]=l.useState(!1),[x,y]=l.useState(null),C=l.useCallback(async j=>{const N=j||d;!N||!bt(N)&&!ht(N)||(y(N),S(!0))},[d]),v=l.useCallback(()=>{S(!1),y(null)},[]),w=l.useCallback(async j=>{const N=x||d;if(!N||!bt(N)&&!ht(N)){v();return}S(!1);try{const A=Ds(N),T=N.routeId||N.daemonId||"";await p(T,"stop_cli",{cliType:A,targetSessionId:N.sessionId,mode:j,...ko(N)})}catch(A){console.error("Stop CLI failed:",A)}finally{y(null)}},[d,v,x,p]);return{remoteDialogConv:u,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:g,openRemoteDialog:k,closeRemoteDialog:h,cliStopDialogOpen:b,cliStopTargetConv:x,requestCliStop:C,cancelCliStop:v,confirmCliStop:w}}function oi(e,t=!0){return(e??!0)&&t}const gc=l.memo(function({activeConv:t,clearToken:n,isCliTerminal:a,ideEntry:r,terminalRef:o,handleModalButton:i,handleRelaunch:c,handleSendChat:d,handleForceSendChat:p,isSendingChat:u,sendFeedbackMessage:m=null,handleFocusAgent:f,isFocusingAgent:g,actionLogs:k,userName:h,scrollToBottomRequestNonce:b,isInputActive:S=!0,isVisible:x=!0}){const y=a,C=!a,v=oi(x,y),w=oi(x,C),j=oi(x),N=Ph(t),A=N.status||N.modalMessage||N.modalButtons?{...t,...N.status?{status:N.status}:{},...N.modalMessage!==void 0?{modalMessage:N.modalMessage}:{},...N.modalButtons!==void 0?{modalButtons:N.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(tm,{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(Ls,{size:14})}),s.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),s.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:c,children:"Relaunch with CDP"})]})}):null,A.transport==="pty"?s.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[s.jsx("div",{"aria-hidden":!a,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:y?"visible":"hidden",pointerEvents:y?"auto":"none"},children:s.jsx(mj,{activeConv:A,clearToken:n,terminalRef:o,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:m,isVisible:v,isInputActive:S&&v})}),s.jsx("div",{"aria-hidden":a,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:C?"visible":"hidden",pointerEvents:C?"auto":"none"},children:s.jsx(ll,{activeConv:A,ideEntry:r,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:k,userName:h,scrollToBottomRequestNonce:b,isInputActive:S&&w,isVisible:w})})]}):s.jsx(ll,{activeConv:A,ideEntry:r,handleSendChat:d,handleForceSendChat:p,isSendingChat:u,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:k,userName:h,scrollToBottomRequestNonce:b,isInputActive:S&&j,isVisible:j})]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.handleModalButton===t.handleModalButton&&e.handleRelaunch===t.handleRelaunch&&e.handleSendChat===t.handleSendChat&&e.handleForceSendChat===t.handleForceSendChat&&e.isSendingChat===t.isSendingChat&&e.sendFeedbackMessage===t.sendFeedbackMessage&&e.handleFocusAgent===t.handleFocusAgent&&e.isFocusingAgent===t.isFocusingAgent&&e.actionLogs===t.actionLogs&&e.userName===t.userName&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isInputActive===t.isInputActive&&e.isVisible===t.isVisible);function fA({conversation:e,className:t="",onOpenNativeConversation:n,onOpenMachine:a,interactive:r=!0,meshOnly:o=!1}){var C,v,w;const{t:i}=ke("common"),c=ia(),d=Vs(e),p=o?null:Mm(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=sa(e),k=DS(e),h=(C=e.settings)==null?void 0:C.meshNodeFor,b=e.meshQueueStats,S=((v=e.coordinator)==null?void 0:v.meshId)||((w=e.settings)==null?void 0:w.meshCoordinatorFor),x=l.useCallback(()=>{if(a){a();return}d&&c("/dashboard",{state:{openMachineId:d}})},[d,c,a]),y=l.useCallback(()=>{if(n){n();return}const j=Oh(e);j&&c(Wa(j))},[e,c,n]);return!u&&!m&&!f&&!p&&!h&&!b?null:s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[u&&(r?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:y,title:k,children:[s.jsx(us,{size:12}),s.jsx("span",{children:k})]}):s.jsxs("span",{className:"conversation-meta-chip",title:k,children:[s.jsx(us,{size:12}),s.jsx("span",{children:k})]})),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(_a,{size:12}),s.jsx("span",{children:g})]}),f&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(_a,{size:12}),s.jsx("span",{children:g})]}),p&&(r?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:x,title:p,children:[s.jsx(nn,{size:12}),s.jsx("span",{children:p})]}):s.jsxs("span",{className:"conversation-meta-chip",title:p,children:[s.jsx(nn,{size:12}),s.jsx("span",{children:p})]})),h&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(nn,{size:12}),s.jsx("span",{children:i("dashboard.metaChips.meshNode")})]}),S&&b&&s.jsxs("span",{className:`conversation-meta-chip ${b.pending>0?"is-active":""}`,style:b.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${b.pending} pending, ${b.assigned} assigned, ${b.completed} completed, ${b.failed} failed`,children:[s.jsx(xb,{size:12}),s.jsxs("span",{children:[b.pending," Pending"]})]})]})}function gA({selectedConversation:e,isAcp:t,isStandalone:n,selectedIdeEntry:a,actionLogs:r,userName:o,isSendingChat:i,sendFeedbackMessage:c=null,isFocusingAgent:d,onBack:p,onOpenNativeConversation:u,onOpenMachine:m,onOpenHistory:f,onOpenRemote:g,onOpenMeshGraph:k,onStopCli:h,cliViewMode:b,onSetCliViewMode:S,handleSendChat:x,handleForceSendChat:y,handleFocusAgent:C,handleModalButton:v,handleRelaunch:w}){var P,M;const j=l.useRef(null),N=bt(e)&&!t,A=N&&b==="terminal",T=!!e.daemonId&&!!((P=e.coordinator)!=null&&P.meshId||(M=e.settings)!=null&&M.meshCoordinatorFor),I=n?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`flex items-center justify-between gap-3 ${I} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:p,type:"button","aria-label":"Back",children:s.jsx(_l,{size:18})}),s.jsxs("div",{className:"min-w-0 flex-1 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:kt(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(fA,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>m(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[N&&b&&s.jsx(oh,{mode:b,onChange:S,compact:!0}),N&&h&&s.jsx("button",{onClick:()=>{h(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(Dt,{size:14})}),T&&k&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>k(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(cs,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",children:s.jsx($l,{size:14})}),!t&&!N&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",children:s.jsx(us,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(gc,{activeConv:e,clearToken:0,isCliTerminal:A,ideEntry:a,terminalRef:j,handleModalButton:v,handleRelaunch:w,handleSendChat:x,handleForceSendChat:y,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:C,isFocusingAgent:d,actionLogs:r,userName:o})})]})}const ii={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 bA(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function qh(){const[e,t]=l.useState("unix"),[n,a]=l.useState("powershell"),[r,o]=l.useState(!1),i=e==="unix"?"unix":n;l.useEffect(()=>{t(bA())},[]);const c=l.useCallback(()=>{navigator.clipboard.writeText(ii[i].cmd).catch(()=>{}),o(!0),setTimeout(()=>o(!1),2e3)},[i]);return s.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("unix"),children:"macOS / Linux"}),s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("windows"),children:"Windows"})]}),e==="windows"&&s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${n==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>a("powershell"),children:"PowerShell"}),s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${n==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>a("cmd"),children:">_ CMD"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:c,title:"Click to copy",children:[s.jsx("span",{className:"text-text-muted select-none",children:ii[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:ii[i].cmd}),s.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:r?s.jsx(co,{size:12}):s.jsx(Hl,{size:12})})]}),s.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",s.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function zh({section:e,onSectionChange:t}){const{t:n}=ke("common"),a=[{key:"machines",label:n("nav.machines"),icon:us},{key:"chats",label:n("nav.chats"),icon:Is}];return s.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:s.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:a.map(({key:r,label:o,icon:i})=>{const c=e===r;return s.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${c?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>t(r),type:"button","aria-pressed":c,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${c?"text-accent-primary":"bg-transparent text-current"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:s.jsx(i,{size:15})}),s.jsx("span",{children:o})]},r)})})})}function ur({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 hn({icon:e,title:t,subtitle:n,children:a}){return s.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[s.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),s.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:t}),s.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:n}),a]})}function xA({conversation:e,onCancel:t,onConfirm:n}){const{t:a}=ke(),r=kt(e);return s.jsx(Vt,{children:s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:t,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"mobile-hide-confirm-title",className:"card fade-in mobile-compact-dialog relative w-full sm:w-[min(92vw,420px)] md:w-[92%] md:max-w-[420px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-bg-primary",children:[s.jsx("h3",{id:"mobile-hide-confirm-title",className:"m-0 text-base md:text-lg font-extrabold",children:a("mobileInbox.hideTitle",{title:r})}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:a("mobileInbox.hideDescription")})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[s.jsx("button",{onClick:n,className:"btn btn-primary w-full justify-center min-h-[42px]",children:a("mobileInbox.hide")}),s.jsx("button",{onClick:t,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:a("common.cancel")})]})]})]})})}function pr({item:e,type:t,getAvatarText:n,onOpenConversation:a,onRequestHideConversation:r,onRequestStopCli:o,onOpenMeshGraph:i,onCollectChatDebugBundle:c,isMuted:d,onToggleMute:p}){const{t:u}=ke(),m=t==="needs_attention"||t==="task_complete",f=t==="working",g=t==="earlier",k=t==="task_complete",{isReconnecting:h,isConnecting:b}=En(e.conversation),S=kt(e.conversation),x=na(e.conversation),y=sh(e.conversation,{requiresAction:t==="needs_attention"}),C=m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":f?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":g?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",v=m?"bg-accent-primary shadow-glow":f?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":g?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",w=g?"text-text-secondary":"text-text-primary",j=g?"text-text-muted":"text-text-secondary",N=g?"text-text-secondary opacity-80":"text-text-muted",A=g?"text-text-muted opacity-80":"text-text-muted",T=!f&&!k,I=eh(e.conversation),P="text-[color:var(--status-warning)]",M=E=>{if(!c)return;E.preventDefault(),E.stopPropagation();const D=c==null?void 0:c(e.conversation);Promise.resolve(D).catch(W=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",W)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${C}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[m||f?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${v}`,style:m?{color:"var(--accent-on-primary)"}:void 0,children:n(S)}),I&&i&&s.jsx("button",{type:"button",className:"mobile-inbox-mesh-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:E=>{E.preventDefault(),E.stopPropagation(),i(e.conversation)},"aria-label":u("mobileInbox.openMeshGraphFor",{title:S}),title:u("mobileInbox.openLiveMeshGraph"),children:s.jsx(cs,{size:13})})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>a(e.conversation),onContextMenu:M,type:"button",children:[s.jsx("div",{className:"flex items-center gap-2 pr-[124px]",children:s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${w}`,children:S})}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${j}`,children:[s.jsx("span",{className:"truncate",children:x}),s.jsx(qr,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),h?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${P} animate-pulse`,children:u("mobileInbox.reconnectingItem")})]}):b?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")})]}):y==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:P,children:u("mobileInbox.actionNeeded")})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${N}`,children:e.preview})]}),s.jsxs("div",{className:"mobile-inbox-corner-actions absolute top-3 right-3 flex items-center gap-1.5",children:[T&&s.jsx("span",{className:`mr-0.5 text-[11px] font-medium shrink-0 ${A}`,children:Zp(e.timestamp)}),k&&s.jsx("span",{className:"rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:u("mobileInbox.done")}),p&&s.jsx("button",{type:"button",className:`mobile-inbox-mute-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border transition-colors ${d?"border-amber-500/60 bg-amber-500 text-white hover:bg-amber-600":"border-border-subtle bg-bg-primary/70 text-text-muted hover:border-border-default hover:text-text-primary"}`,onClick:E=>{E.preventDefault(),E.stopPropagation(),p()},"aria-label":d?u("mobileInbox.unmute",{title:S}):u("mobileInbox.mute",{title:S}),title:u(d?"mobileInbox.mutedTitle":"mobileInbox.muteNotifications"),children:d?s.jsx(Ip,{size:13}):s.jsx(la,{size:13})}),r&&s.jsx("button",{type:"button",className:"mobile-inbox-hide-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:E=>{E.preventDefault(),E.stopPropagation(),r()},"aria-label":u("mobileInbox.hideConversationAria",{title:S}),title:u("mobileInbox.hideConversationTitle"),children:s.jsx(mo,{size:13})}),o&&s.jsx("button",{type:"button",className:"mobile-inbox-stop-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-status-error/30 bg-bg-primary/70 text-status-error transition-colors hover:border-status-error/60 hover:bg-status-error/10",onClick:E=>{E.preventDefault(),E.stopPropagation(),o()},"aria-label":u("mobileInbox.stopSessionAria",{title:S}),title:u("mobileInbox.stopSessionTitle"),children:s.jsx(Dt,{size:13})})]})]})},e.conversation.tabKey)}function lu({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 vA({section:e,attentionItems:t,unreadItems:n,workingItems:a,completedItems:r,hiddenConversations:o,machineCards:i,getAvatarText:c,actionLogs:d,sendDaemonCommand:p,onOpenConversation:u,onShowAllHidden:m,onHideConversation:f,onOpenMeshGraph:g,onStopCli:k,onOpenNewSession:h,onOpenMachine:b,onOpenSettings:S,onSectionChange:x,wsStatus:y="connected",initialDataLoaded:C=!0,conversationsLoaded:v,isStandalone:w=!1,onCollectChatDebugBundle:j,isConversationMuted:N,onToggleMuteConversation:A}){const{t:T}=ke(),[I,P]=l.useState(null),M=y==="disconnected"||y==="reconnecting"||y==="offline"||y==="auth_failed",E=!M&&!C,D=!M&&!(v??C),W=i.length>0,R=t.length>0||n.length>0||a.length>0||r.length>0,B=T(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),_=w?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",H=w?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",L=l.useCallback(async K=>{const z=kn(K);if(!z)return;const ne=Array.isArray(K.messages)?K.messages:[],ie=_m({activeConv:K,visibleMessages:ne,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:ne.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),Ce=await p(z,"get_chat_debug_bundle",{...wn(K),delivery:"daemon_file",frontendSnapshot:ie}),me=Pa(Ce),O=Fm(me),Y=await $m(O);Y==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),ft.showToast(Hm(me,{locatorCopyStatus:Y}),Y==="failed"?"warning":"success")},[d,p]),F=j||L,$=l.useCallback(()=>{I&&(f==null||f(I),P(null))},[I,f]);return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${_}`,children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:B}),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(la,{size:13}),s.jsx("span",{children:t.length+n.length})]}),s.jsx("button",{onClick:S,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:s.jsx(Ua,{size:18})})]})]})}),s.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${H}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:M?s.jsx(hn,{icon:s.jsx(ls,{size:32}),title:T(y==="offline"?"mobileInbox.networkOffline":y==="auth_failed"?"mobileInbox.sessionExpired":"mobileInbox.reconnecting"),subtitle:T(y==="offline"?"mobileInbox.waitingForNetwork":y==="auth_failed"?"mobileInbox.pleaseLogInAgain":"mobileInbox.restoringConnection")}):E?s.jsx(hn,{icon:s.jsx(ls,{size:32}),title:T("mobileInbox.loading"),subtitle:T("mobileInbox.loadingSubtitle")}):i.length===0?s.jsx(hn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:T(w?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:T(w?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!w&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(qh,{})})}):s.jsx(Bn,{children:i.map((K,z)=>s.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${z>0?"border-t border-border-subtle/70":""}`,onClick:()=>b(K.id),type:"button",children:[s.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:c(K.label)}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:K.label}),s.jsxs("span",{className:"flex items-center gap-2 text-[11px] font-medium text-text-muted shrink-0",children:[s.jsx(lu,{count:K.generatingCount,label:T("mobileInbox.generatingCount",{count:K.generatingCount})}),K.unread>0?s.jsx("span",{className:"text-accent-primary",children:T("mobileInbox.newCount",{count:K.unread})}):K.total>0?T("mobileInbox.chatCount",{count:K.total}):T("mobileInbox.idle")]})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:K.subtitle}),K.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[T("mobileInbox.chatCount",{count:K.total}),K.unread>0?T("mobileInbox.unreadSuffix",{count:K.unread}):"",K.generatingCount>0?T("mobileInbox.collapsedGeneratingSuffix",{count:K.generatingCount}):""]}):K.generatingCount>0?s.jsx("div",{className:"text-[13px] text-accent-primary mt-0.5 font-medium",children:T("mobileInbox.generatingCount",{count:K.generatingCount})}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:T("mobileInbox.noActiveChats")})]})]},K.id))})}),e==="chats"&&t.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(ur,{title:T("mobileInbox.needsAttention"),className:"mb-0"}),s.jsx(Bn,{children:t.map((K,z)=>s.jsx("div",{className:z>0?"border-t border-border-subtle/70":"",children:s.jsx(pr,{item:K,type:"needs_attention",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>P(K.conversation):void 0,onRequestStopCli:k?()=>k(K.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:F,isMuted:N==null?void 0:N(K.conversation),onToggleMute:A?()=>A(K.conversation):void 0})},K.conversation.tabKey))})]}),e==="chats"&&n.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(ur,{title:T("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),s.jsx(Bn,{children:n.map((K,z)=>s.jsx("div",{className:z>0?"border-t border-border-subtle/70":"",children:s.jsx(pr,{item:K,type:"task_complete",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>P(K.conversation):void 0,onRequestStopCli:k?()=>k(K.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:F,isMuted:N==null?void 0:N(K.conversation),onToggleMute:A?()=>A(K.conversation):void 0})},K.conversation.tabKey))})]}),e==="chats"&&a.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(ur,{title:T("mobileInbox.workingNow"),className:"mb-0 mt-2"}),s.jsx(Bn,{children:a.map((K,z)=>s.jsx("div",{className:z>0?"border-t border-border-subtle/70":"",children:s.jsx(pr,{item:K,type:"working",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>P(K.conversation):void 0,onRequestStopCli:k?()=>k(K.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:F,isMuted:N==null?void 0:N(K.conversation),onToggleMute:A?()=>A(K.conversation):void 0})},K.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[r.length>0&&s.jsx(ur,{title:T("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),r.length>0?s.jsx(Bn,{children:r.map((K,z)=>s.jsx("div",{className:z>0?"border-t border-border-subtle/70":"",children:s.jsx(pr,{item:K,type:"earlier",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>P(K.conversation):void 0,onRequestStopCli:k?()=>k(K.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:F,isMuted:N==null?void 0:N(K.conversation),onToggleMute:A?()=>A(K.conversation):void 0})},K.conversation.tabKey))}):R?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:T("mobileInbox.allCaughtUp")}):M?s.jsx(hn,{icon:s.jsx(ls,{size:28}),title:T("mobileInbox.connecting"),subtitle:T("mobileInbox.connectingSubtitle")}):D?s.jsx(hn,{icon:s.jsx(ls,{size:28}),title:T("mobileInbox.loading"),subtitle:T("mobileInbox.loadingSubtitle")}):W?s.jsx(hn,{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(Is,{size:20})}),title:T("mobileInbox.noConversations"),subtitle:T("paneGroup.newSessionDescription"),children:h&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:h,"aria-label":T("paneGroup.newSession"),title:T("paneGroup.newSession"),children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s.jsx("span",{children:T("paneGroup.newSession")})]})}):s.jsx(hn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:T("mobileInbox.noMachinesConnected"),subtitle:T("mobileInbox.noMachinesSubtitle")})]}),e==="chats"&&o.length>0&&(()=>{const K=Dx(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:T("mobileInbox.hiddenTabs")}),s.jsx(lu,{count:K,label:T("mobileInbox.generatingCount",{count:K})})]}),s.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[T("mobileInbox.collapsedCount",{count:o.length}),K>0?T("mobileInbox.collapsedGeneratingSuffix",{count:K}):""]})]}),s.jsx("button",{type:"button",className:"shrink-0 rounded-full border border-border-subtle bg-bg-primary/70 px-3 py-1.5 text-[12px] font-semibold text-accent-primary hover:border-border-default",onClick:m,children:T("mobileInbox.restoreAll")})]})})})})()]}),e==="chats"&&h&&R&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:h,"aria-label":T("paneGroup.newSession"),title:T("paneGroup.newSession"),children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),I&&s.jsx(xA,{conversation:I,onCancel:()=>P(null),onConfirm:$}),s.jsx(zh,{section:e,onSectionChange:x})]})}function yA(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 Kh(e){const t=[e.workspace||"Workspace unknown"],n=Mn(e.summaryMetadata);n&&t.push(n),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const a=yA(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:a?`Updated ${a}`:"",preview:(e.preview||"").trim()}}function bc({title:e,description:t,currentPath:n,directories:a,busy:r=!1,error:o="",confirmLabel:i="Use this folder",onClose:c,onNavigate:d,onConfirm:p}){const[u,m]=l.useState(n),{t:f}=ke("common");l.useEffect(()=>{m(n)},[n]);const g=QN(n),k=u.trim();return s.jsx(Vt,{children:s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:s.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:c,"aria-label":"Close folder browser",children:s.jsx(Dt,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!g||r||d(g)},disabled:!g||r,children:[s.jsx(_l,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:f("machine.workspaceBrowse.currentFolder")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:u,onChange:h=>m(h.target.value),onKeyDown:h=>{h.key!=="Enter"||!k||r||(h.preventDefault(),d(k))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!k||r||d(k)},disabled:!k||r,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:r?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):o?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:o}):a.length===0?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):s.jsx("div",{className:"p-3",children:a.map(h=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>d(h.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Tn,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:h.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:h.path})]})]},h.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:c,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>p(k||n),disabled:!k&&!n||r,children:i})]})]})})})}function Ao({title:e,description:t,details:n,workspaceOptions:a,selectedWorkspaceKey:r,onWorkspaceChange:o,confirmLabel:i,busyLabel:c,busy:d=!1,showArgsInput:p,argsValue:u,onArgsChange:m,showModelInput:f,modelValue:g,onModelChange:k,historyProviderNode:h,onConfirm:b,onCancel:S}){const{t:x}=ke("common"),y=i??x("machine.launchConfirm.launch"),C=c??x("machine.launchConfirm.launching"),v=a==null?void 0:a.find(j=>j.key===r),w=s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:S,"aria-label":x("machine.launchConfirm.closeAria"),children:s.jsx(Dt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[a&&a.length>0&&o&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:x("machine.launchConfirm.workspace")}),s.jsx("select",{value:r||"",onChange:j=>o(j.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:d,children:a.map(j=>s.jsx("option",{value:j.key,children:j.label},j.key))}),(v==null?void 0:v.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:v.description})]}),h,n.map(j=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:j.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:j.value})]},`${j.label}:${j.value}`)),f&&k&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:x("machine.launchConfirm.languageModel")}),s.jsx("input",{type:"text",value:g||"",onChange:j=>k(j.target.value),placeholder:x("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:x("machine.launchConfirm.cliArgs")}),s.jsx("input",{type:"text",value:u||"",onChange:j=>m(j.target.value),placeholder:x("machine.launchConfirm.cliArgsPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:S,disabled:d,children:x("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:b,disabled:d,children:[s.jsx(Dp,{size:14}),d?C:y]})]})]})});return typeof document>"u"?w:zs.createPortal(w,document.body)}function cu(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function Vh(e){const{machine:t,currentWorkspacePath:n,currentWorkspaceId:a,includeHome:r=!0,homeLabel:o="Home directory",homeDescription:i="Launch without a workspace"}=e,c=[];r&&c.push({key:"__home__",label:o,description:i,workspaceId:null,workspacePath:null});for(const u of t.workspaces||[])c.push({key:`saved:${u.id}`,label:`${u.id===t.defaultWorkspaceId?"⭐ ":""}${cu(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:cu(d),description:d,workspaceId:null,workspacePath:d}),a){const u=`saved:${a}`;if(c.some(m=>m.key===u))return{options:c,selectedKey:u}}return p?{options:c,selectedKey:`saved:${p.id}`}:d?{options:c,selectedKey:`custom:${d}`}:{options:c,selectedKey:"__home__"}}function wA(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function kA(e){return[wA(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function SA(e){return e.lastLaunchedAt?za(e.lastLaunchedAt):""}function Yh(e){return{metaText:kA(e),updatedLabel:SA(e)}}function li(e,t,n){return e?"ide":t>0?"cli":n>0?"acp":null}function CA({selectedMachineEntry:e,cliProviders:t,acpProviders:n,machineAction:a,onBrowseDirectory:r,onListSavedSessions:o}){var Ie,We,Xe,et;const i=da(),[c,d]=l.useState(!1),p=(((Ie=e.detectedIdes)==null?void 0:Ie.length)||0)>0,u=l.useMemo(()=>(e.workspaces||[]).map(J=>({id:J.id,path:J.path,label:J.label})),[e]),m=e.defaultWorkspaceId||null,[f,g]=l.useState(m||((We=u[0])==null?void 0:We.id)||""),[k,h]=l.useState(""),[b,S]=l.useState(""),[x,y]=l.useState([]),[C,v]=l.useState(!1),[w,j]=l.useState(""),[N,A]=l.useState(!1),[T,I]=l.useState(li(p,t.length,n.length)),P=l.useRef(null),[M,E]=l.useState(null),D=l.useRef("__home__"),[W,R]=l.useState("__home__"),[B,_]=l.useState(""),[H,L]=l.useState(""),[F,$]=l.useState(""),[K,z]=l.useState([]),[ne,ie]=l.useState(()=>qt().textQuery),[Ce,me]=l.useState(()=>qt().workspaceQuery),[O,Y]=l.useState(()=>qt().modelQuery),[X,Q]=l.useState(()=>qt().resumableOnly),[ve,he]=l.useState(()=>qt().sortMode),[Z,fe]=l.useState(!1),[V,q]=l.useState(!1),ee=l.useRef(null),pe=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const le=f==="__custom__"?k.trim():((Xe=u.find(J=>J.id===f))==null?void 0:Xe.path)||"",se=f==="__custom__"&&!!le&&a.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(a.message),te=f!=="__custom__"&&((et=u.find(J=>J.id===f))==null?void 0:et.path)||"",ue=l.useMemo(()=>(e.recentLaunches||[]).map(J=>J.workspace),[e]),ye=l.useCallback(async J=>{v(!0),j("");try{const Le=await r(J);S(Le.path),h(Le.path),y(Le.directories)}catch(Le){j(Le instanceof Error?Le.message:"Could not load folder")}finally{v(!1)}},[r]),Me=l.useCallback(()=>{var Le;g("__custom__"),A(!0);const J=hc(e.platform,mc(k.trim(),te,ue,e.defaultWorkspacePath,(Le=u.find($e=>$e.id===m))==null?void 0:Le.path,u.map($e=>$e.path)));ye(J)},[k,m,ye,ue,te,e.platform,u]),re=l.useCallback(J=>{if(J!=null&&J.workspaceId){g(J.workspaceId),h("");return}if(J!=null&&J.workspacePath){g("__custom__"),h(J.workspacePath);return}g(""),h("")},[]),ce=l.useCallback(J=>{if(g(J),J==="__custom__"){Me();return}h("")},[Me]),Ae=l.useCallback(J=>{g("__custom__"),h(J)},[]),be=l.useCallback((J,Le)=>{P.current=Le,D.current=J.selectedWorkspaceKey||"__home__",R(J.selectedWorkspaceKey||"__home__"),_(J.initialArgs||""),L(J.initialModel||""),$(""),z([]);const $e=J.providerType?`${e.id}:${J.providerType}`:null;if(jj(pe.current,$e)){const at=qt();ie(at.textQuery),me(at.workspaceQuery),Y(at.modelQuery),Q(at.resumableOnly),he(at.sortMode)}pe.current=$e,E(J),J.providerType&&o&&(fe(!0),o(J.providerType).then(at=>z(at||[])).catch(at=>console.warn("Failed to load saved sessions",at)).finally(()=>fe(!1)))},[o,e.id]),we=l.useMemo(()=>ih(K,{textQuery:ne,workspaceQuery:Ce,modelQuery:O,resumableOnly:X,sortMode:ve}),[O,X,K,ve,ne,Ce]);l.useEffect(()=>{F&&(we.some(J=>J.providerSessionId===F)||$(""))},[we,F]);const _e=l.useCallback(()=>{P.current&&(q(!0),P.current().finally(()=>{P.current=null,q(!1),E(null)}))},[]),U=l.useCallback(()=>{P.current=null,E(null)},[]),Ne=l.useCallback(J=>{D.current=J,R(J)},[]);return l.useEffect(()=>{var J;ee.current!==e.id&&(ee.current=e.id,g(m||((J=u[0])==null?void 0:J.id)||"__custom__"),h(""),S(""),y([]),j(""),A(!1),ie(qt().textQuery),me(qt().workspaceQuery),Y(qt().modelQuery),Q(qt().resumableOnly),he(qt().sortMode),pe.current=null,I(li(p,t.length,n.length)))},[n.length,t.length,m,p,e.id,u]),l.useEffect(()=>{var J;f!=="__custom__"&&(f&&u.some(Le=>Le.id===f)||g(m||((J=u[0])==null?void 0:J.id)||"__custom__"))},[m,f,u]),l.useEffect(()=>{T==="ide"&&p||T==="cli"&&t.length>0||T==="acp"&&n.length>0||I(li(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:b,browseDirectories:x,browseBusy:C,browseError:w,browseDialogOpen:N,activeLauncherKind:T,launchConfirm:M,launchConfirmWorkspaceKeyRef:D,launchConfirmWorkspaceKey:W,launchConfirmArgs:B,launchConfirmModel:H,launchConfirmResumeId:F,launchConfirmSavedSessions:K,launchConfirmTextFilter:ne,launchConfirmWorkspaceFilter:Ce,launchConfirmModelFilter:O,launchConfirmResumableOnly:X,launchConfirmSortMode:ve,filteredLaunchConfirmSavedSessions:we,launchConfirmSessionsLoading:Z,launchConfirmBusy:V,resolvedWorkspacePath:le,canCreateMissingWorkspace:se,openBrowseDialog:Me,loadBrowsePath:ye,handleWorkspaceChoiceChange:ce,chooseCustomWorkspacePath:Ae,setCustomWorkspacePath:h,setBrowseDialogOpen:A,setActiveLauncherKind:I,openLaunchConfirm:be,handleConfirmLaunch:_e,closeLaunchConfirm:U,setWorkspaceSelectionFromOption:re,setLaunchConfirmWorkspaceKeyAndSync:Ne,setLaunchConfirmArgs:_,setLaunchConfirmModel:L,setLaunchConfirmResumeId:$,setLaunchConfirmTextFilter:ie,setLaunchConfirmWorkspaceFilter:me,setLaunchConfirmModelFilter:Y,setLaunchConfirmResumableOnly:Q,setLaunchConfirmSortMode:he}}function jA({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:n,cliProviders:a,acpProviders:r,selectedMachineNeedsUpgrade:o,appVersion:i,machineAction:c,isStandalone:d,section:p,showBottomNav:u,onBack:m,onSectionChange:f,onOpenConversation:g,onOpenRecent:k,onOpenMachineDetails:h,onMachineUpgrade:b,onLaunchDetectedIde:S,onAddWorkspace:x,onBrowseDirectory:y,onLaunchWorkspaceProvider:C,onListSavedSessions:v}){const{t:w}=ke("common"),j=R=>R==="ide"?"IDE":R==="cli"?"CLI":"ACP",N=n.slice(0,4),A=t.slice(0,3),T=CA({selectedMachineEntry:e,cliProviders:a,acpProviders:r,machineAction:c,onBrowseDirectory:y,onListSavedSessions:v}),I=l.useMemo(()=>N.map(R=>{const{metaText:B,updatedLabel:_}=Yh(R);return{key:`recent-launch:${R.id}`,primary:R.label,secondary:B,updatedLabel:_,onClick:()=>{const{options:H,selectedKey:L}=Vh({machine:{workspaces:T.workspaceRows,defaultWorkspaceId:T.defaultWorkspaceId},currentWorkspacePath:R.workspace,homeLabel:w("newSession.homeDirectory"),homeDescription:w("newSession.launchWithoutWorkspace")});T.openLaunchConfirm({title:R.kind==="ide"?zr(w,"restart-ide",R.label):R.providerSessionId?ch(w,R.label):zr(w,"start-fresh",R.label),description:R.kind==="ide"?Kr(w,"restart-ide"):R.providerSessionId?dh(w):Kr(w,"start-fresh"),confirmLabel:R.kind==="ide"?Vr(w,"restart-ide"):R.providerSessionId?cl(w,!0):Vr(w,"start-fresh"),busyLabel:R.kind==="ide"?Yr(w,"restart-ide"):R.providerSessionId?lh(w,!0):Yr(w,"start-fresh"),workspaceOptions:H,selectedWorkspaceKey:L,details:[{label:"Mode",value:j(R.kind)},...R.providerType?[{label:"Provider",value:R.providerType}]:[]]},async()=>{const F=H.find($=>$.key===T.launchConfirmWorkspaceKeyRef.current);T.setWorkspaceSelectionFromOption(F),await k({...R,workspace:(F==null?void 0:F.workspacePath)??null})})}}}),[T,k,N,w]),P=l.useMemo(()=>A.map(R=>({key:`recent-chat:${R.conversation.tabKey}`,primary:kt(R.conversation),secondary:QC(R.conversation,{timestampLabel:R.timestamp?Zp(R.timestamp):null}),unread:R.unread,onClick:()=>g(R.conversation)})),[g,A]),M=T.showAllRecent?I:I.slice(0,4),E=I.length>0,D=P.length>0,W=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 ${W} 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(_l,{size:18})}),s.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:ds(e,{fallbackId:e.id})}),s.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[D&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:P.map(R=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${R.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:R.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:R.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:R.secondary})]},R.key))})]}),E&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:M.map(R=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:R.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:R.primary}),R.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:R.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:R.secondary})]},R.key))}),I.length>4&&s.jsx("div",{className:"flex justify-center px-4 pt-2",children:s.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>T.setShowAllRecent(R=>!R),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:b,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(bc,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:T.browseCurrentPath,directories:T.browseDirectories,busy:T.browseBusy,error:T.browseError,confirmLabel:"Use this folder",onClose:()=>T.setBrowseDialogOpen(!1),onNavigate:R=>{T.loadBrowsePath(R)},onConfirm:R=>{T.chooseCustomWorkspacePath(R),T.setBrowseDialogOpen(!1)}}),T.launchConfirm&&s.jsx(Ao,{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?cl(w,!!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:oc(w)}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:T.launchConfirmTextFilter,onChange:R=>T.setLaunchConfirmTextFilter(R.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:T.launchConfirmWorkspaceFilter,onChange:R=>T.setLaunchConfirmWorkspaceFilter(R.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:T.launchConfirmModelFilter,onChange:R=>T.setLaunchConfirmModelFilter(R.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsxs("select",{value:T.launchConfirmSortMode,onChange:R=>T.setLaunchConfirmSortMode(R.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:T.launchConfirmResumableOnly,onChange:R=>T.setLaunchConfirmResumableOnly(R.target.checked),disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:T.launchConfirmResumeId,onChange:R=>T.setLaunchConfirmResumeId(R.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:Tj(w)}),T.filteredLaunchConfirmSavedSessions.map(R=>s.jsxs("option",{value:R.providerSessionId,disabled:!R.canResume,children:[R.title||R.providerSessionId," ",R.canResume?"":"(workspace missing)"]},R.providerSessionId))]}),!T.launchConfirmSessionsLoading&&T.launchConfirmSavedSessions.length>0&&T.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),T.launchConfirmResumeId&&(()=>{const R=T.filteredLaunchConfirmSavedSessions.find(_=>_.providerSessionId===T.launchConfirmResumeId);if(!R)return null;const B=Kh(R);return s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:B.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:B.providerSessionId}),s.jsx("div",{className:"mt-1",children:B.metaLine}),B.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:B.updatedLabel}),B.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:B.preview})]})})()]}),onConfirm:T.handleConfirmLaunch,onCancel:T.closeLaunchConfirm}),u&&s.jsx(zh,{section:p,onSectionChange:f})]})}const du=8e3;function NA(e){const t=e&&typeof e=="object"&&"result"in e?e.result:e,n=t&&typeof t=="object",a=n&&t.success===!1,r=n&&t.mirrorStale===!0;return!a&&!r?{confirmed:!0}:{confirmed:!1,reason:a&&typeof t.error=="string"?t.error:r?"the coordinator did not confirm the change":"command was rejected"}}function Qh(e,t,n){const a=l.useRef(new Map),[,r]=l.useState(0),o=l.useCallback(()=>r(g=>g+1),[]);l.useEffect(()=>{const g=a.current;if(g.size===0)return;const k=Date.now();let h=!1;for(const[b,S]of g){const x=e.get(b),y=S.muted===void 0||(x?x.muted===S.muted:!1),C=S.hidden===void 0||(x?x.surfaceHidden===S.hidden:!1),v=k-S.at>du;(y&&C||v)&&(g.delete(b),h=!0)}h&&o()},[e,o]),l.useEffect(()=>{if(a.current.size===0)return;const g=setInterval(()=>{const k=a.current,h=Date.now();let b=!1;for(const[S,x]of k)h-x.at>du&&(k.delete(S),b=!0);b&&o(),k.size===0&&clearInterval(g)},1e3);return()=>clearInterval(g)});const i=l.useCallback((g,k)=>{const h=a.current.get(g);a.current.set(g,{...h,...k,at:Date.now()}),o()},[o]),c=l.useCallback(g=>{const k=g.sessionId,h=k?a.current.get(k):void 0;return(h==null?void 0:h.muted)!==void 0?h.muted:rn(g,e).muted??!1},[e]),d=l.useCallback(g=>{const k=g.sessionId,h=k?a.current.get(k):void 0;return(h==null?void 0:h.hidden)!==void 0?h.hidden:rn(g,e).surfaceHidden??!1},[e]),p=l.useCallback((g,k)=>{const h=Vs(g),b=g.sessionId;!h||!b||(i(b,k),t(h,"set_conversation_prefs",{sessionId:b,...k,...ko(g)}).then(S=>{const x=NA(S);x.confirmed||(console.warn("[conversation-prefs] set_conversation_prefs not confirmed",x.reason),a.current.delete(b),o(),n==null||n(`Couldn't update conversation — ${x.reason}`))}).catch(S=>{console.warn("[conversation-prefs] set_conversation_prefs failed",S),a.current.delete(b),o();const x=S instanceof Error?S.message:String(S??"the daemon is unreachable");n==null||n(`Couldn't update conversation — ${x}`)}))},[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 Ir(e){return[...e].sort((t,n)=>{const a=n.timestamp-t.timestamp;return a!==0?a:t.conversation.tabKey.localeCompare(n.conversation.tabKey)})}function AA(e,t=[]){const n=new Map(e.map(r=>[r.conversation.tabKey,r])),a=t.map(r=>n.get(r)).filter(r=>!!r);return a.length===e.length?a:Ir(e)}function TA(e,t=[]){const n=e.filter(i=>i.requiresAction),a=e.filter(i=>i.unread&&!i.requiresAction),r=e.filter(i=>!i.unread&&!i.requiresAction&&i.isWorking),o=e.filter(i=>!i.unread&&!i.requiresAction&&!i.isWorking);return{attentionItems:Ir(n),unreadItems:Ir(a),workingItems:AA(r,t),completedItems:Ir(o)}}function To(e,t){if(!t)return!1;const n=e.filter(a=>a.type==="adhdev-daemon"&&Jh(a)==="Connected");return n.length===0?!0:n.every(a=>a._sessionListAuthoritative===!0)}function Jh(e){var a,r,o;const t=((a=e.p2p)==null?void 0:a.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":!(!!((r=e.p2p)!=null&&r.available)||!!((o=e.p2p)!=null&&o.state))&&e.status&&e.status!=="offline"?"Connected":"Offline"}function MA(e,t){if(!e)return[];const n=e.recentLaunches||[];return n.length>0?n.map(a=>({id:a.id,label:a.title||a.providerName||a.providerType,kind:a.kind,providerType:a.providerType,providerSessionId:a.providerSessionId,subtitle:Mn(a.summaryMetadata)||a.workspace||void 0,workspace:a.workspace,summaryMetadata:a.summaryMetadata})):t.filter(a=>a.type!=="adhdev-daemon"&&a.daemonId===e.id).map(a=>{var i;const r=Fa(a)?"cli":Xn(a)?"acp":"ide",o=Mn(a.summaryMetadata);return{id:`${r}:${a.type}:${a.workspace||""}`,label:((i=a.activeChat)==null?void 0:i.title)||(Fa(a)?a.cliName||a.type:Xn(a)&&a.cliName||a.type),kind:r,providerType:a.type,providerSessionId:a.providerSessionId,subtitle:Xn(a)?o||a.workspace||void 0:a.workspace||void 0,workspace:a.workspace||void 0,timestamp:a.lastMessageAt||0}}).sort((a,r)=>r.timestamp-a.timestamp).map(({timestamp:a,...r})=>r)}function PA(e,t,n=[]){const a=new Map;for(const o of t){const i=Vs(o.conversation),c=a.get(i);c?c.push(o):a.set(i,[o])}const r=new Map;for(const o of n){const i=Vs(o),c=r.get(i);c?c.push(o):r.set(i,[o])}return e.map(o=>{const i=a.get(o.id)||[],c=r.get(o.id)||[],d=[...i].sort((h,b)=>b.timestamp-h.timestamp)[0]||null,p=(d==null?void 0:d.conversation)||null,u=sl(o),m=i.filter(h=>h.unread||h.requiresAction).length,f=i.filter(h=>Ha(h.conversation)).length+c.filter(Ha).length,g=Jh(o),k=[o.platform||"machine",g].filter(Boolean);return{id:o.id,label:ds(o,{fallbackId:o.id}),subtitle:k.join(" · "),unread:m,total:i.length,generatingCount:f,latestConversation:p,latestTimestamp:(d==null?void 0:d.timestamp)||0,fallbackActivityAt:u,preview:p?JC(p,Vm(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 DA(e){return e==="chat"}function mr(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 IA({conversations:e,machineEntries:t,items:n,selectedConversation:a,selectedTabKey:r,screen:o,liveSessionInboxState:i,sendDaemonCommand:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,setSelectedTabKey:k,setScreen:h,setSelectedMachineId:b,setSection:S,setMachineBackTarget:x,resetMachineAction:y}){const C=l.useRef(null),v=l.useCallback(w=>{if(!(w!=null&&w.sessionId))return;const j=rn(w,i),N=Math.max(Date.now(),Nn(w),j.lastUpdated||0);mr("mark_read:start",{tabKey:w.tabKey,sessionId:w.sessionId,displayPrimary:kt(w),inboxBucket:j.inboxBucket,unread:j.unread,lastSeenAt:j.lastSeenAt,lastUpdated:j.lastUpdated,activityAt:Nn(w),readAt:N}),c(Vs(w)||w.routeId,"mark_session_seen",{sessionId:w.sessionId,providerSessionId:w.providerSessionId,seenAt:N,completionMarker:j.completionMarker}).then(A=>{mr("mark_read:result",{tabKey:w.tabKey,sessionId:w.sessionId,result:A})}).catch(A=>{mr("mark_read:error",{tabKey:w.tabKey,sessionId:w.sessionId,error:A instanceof Error?A.message:String(A)})})},[i,c]);return l.useEffect(()=>{var j;if(!a){DA(o)&&h("inbox"),k(((j=e[0])==null?void 0:j.tabKey)||null),C.current=null;return}if(o!=="chat"){C.current=null;return}const w=`${a.tabKey}:${a.sessionId||""}`;C.current!==w&&(C.current=w,v(a))},[e,v,o,a,h,k]),l.useEffect(()=>{if(!d)return;const w=e.find(j=>j.tabKey===d);w&&(k(w.tabKey),h("chat"),p==null||p())},[e,p,d,h,k]),l.useEffect(()=>{if(!u)return;const w=t.find(j=>j.id===u);w&&(b(w.id),y(),S("machines"),x("inbox"),h("machine"),m==null||m())},[t,m,u,y,x,h,S,b]),l.useEffect(()=>{f&&(S(f),h("inbox"),g==null||g())},[g,f,h,S]),l.useEffect(()=>{const w=n.filter(j=>j.inboxBucket==="task_complete"||j.unread);w.length!==0&&mr("inbox_state",{screen:o,selectedTabKey:r,items:w.map(j=>{const N=rn(j.conversation,i);return{liveState:N,tabKey:j.conversation.tabKey,sessionId:j.conversation.sessionId,displayPrimary:kt(j.conversation),serverBucket:N.inboxBucket,computedBucket:j.inboxBucket,serverUnread:N.unread,computedUnread:j.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:Nn(j.conversation)}})})},[n,i,o,r]),{markConversationRead:v}}function LA(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function uu(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function RA(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function EA({sendDaemonCommand:e,navigate:t,ides:n,conversations:a}){const{launchCli:r}=fo(),[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(y,C,v)=>{var w;try{i("loading"),d(`Launching ${C}…`);const j={ideType:C,enableCdp:!0};(w=v==null?void 0:v.workspacePath)!=null&&w.trim()&&(j.workspace=v.workspacePath.trim()),await e(y,"launch_ide",j),i("done"),d(`${C} launch requested`)}catch(j){i("error"),d(j instanceof Error?j.message:"Launch IDE failed"),console.error("Launch IDE failed",j)}},[e]),g=l.useCallback(async(y,C,v)=>{if(C.trim())try{i("loading"),d(v!=null&&v.createIfMissing?"Creating folder…":"Saving workspace…");const w=await e(y,"workspace_add",{path:C.trim(),createIfMissing:(v==null?void 0:v.createIfMissing)===!0});if(w!=null&&w.success){i("done"),d(v!=null&&v.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),d((w==null?void 0:w.error)||"Could not save workspace")}catch(w){i("error"),d(w instanceof Error?w.message:"Could not save workspace")}},[e]),k=l.useCallback(async y=>{i("loading"),d("Starting daemon upgrade…");const C=n.find(w=>w.id===y||w.daemonId===y),v=await j1(e,y,C);i(v.state),d(v.message)},[n,e]),h=l.useCallback(async(y,C,v,w)=>{var A,T,I;const j=Date.now(),N={machineId:y,kind:C,providerType:v,workspaceId:(w==null?void 0:w.workspaceId)||null,workspacePath:(w==null?void 0:w.workspacePath)||null,resumeSessionId:(w==null?void 0:w.resumeSessionId)||null,startedAt:j};try{i("loading"),d(`Launching ${v}…`),u(N);const P={cliType:v};(A=w==null?void 0:w.workspacePath)!=null&&A.trim()?P.dir=w.workspacePath.trim():w!=null&&w.workspaceId?P.workspaceId=w.workspaceId:w!=null&&w.useHome&&(P.useHome=!0),w!=null&&w.resumeSessionId&&(P.resumeSessionId=w.resumeSessionId),(T=w==null?void 0:w.args)!=null&&T.trim()&&(P.cliArgs=w.args.trim().split(/\s+/).filter(Boolean)),(I=w==null?void 0:w.model)!=null&&I.trim()&&(P.initialModel=w.model.trim());const M=await r(y,P),E=(M==null?void 0:M.result)||M,D=(E==null?void 0:E.sessionId)||(E==null?void 0:E.id);if(M!=null&&M.success&&D){u(null),i("done"),d(`${v} launched`),t(Wa(D));return}if(M!=null&&M.success){i("loading"),d(`${v} launch requested — waiting for session…`);return}u(null),i("error"),d((M==null?void 0:M.error)||(E==null?void 0:E.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(P){if(RA(P)){i("loading"),d(`${v} launch requested — waiting for session…`);return}u(null),i("error"),d(P instanceof Error?P.message:`Could not launch ${C.toUpperCase()} workspace`)}},[t,e]),b=l.useCallback(async(y,C)=>{try{const v=await e(y,"list_saved_sessions",{providerType:C,kind:"cli",limit:30}),w=(v==null?void 0:v.result)??v;return Array.isArray(w==null?void 0:w.sessions)?w.sessions:[]}catch(v){return console.error("Failed to list saved sessions on mobile:",v),[]}},[e]),S=l.useCallback(async(y,C)=>fc(e,y,C),[e]);l.useEffect(()=>{if(!p)return;const y=uu(p.workspacePath),C=n.find(w=>{var P,M,E,D;if(!w||w.type==="adhdev-daemon"||LA(w.daemonId||w.id)!==p.machineId||(w.transport==="acp"?"acp":w.transport==="pty"?"cli":null)!==p.kind||String(w.agentType||w.type||"")!==p.providerType)return!1;const T=String(w.providerSessionId||"");if(p.resumeSessionId&&T)return T===p.resumeSessionId;if(y){const W=uu(w.workspace||w.runtimeWorkspaceLabel);return W?W===y:!1}return Number(w.lastUpdated||w._lastUpdate||w.timestamp||((D=(E=(M=(P=w.activeChat)==null?void 0:P.messages)==null?void 0:M.at)==null?void 0:E.call(M,-1))==null?void 0:D.timestamp)||0)>=p.startedAt-5e3});if(!C)return;const v=Uh({entrySessionId:C.sessionId,entryInstanceId:C.instanceId,entryRouteId:C.id,conversations:a});v&&(u(null),i("done"),d(`${p.providerType} launched`),t(Wa(v)))},[a,n,t,p]),l.useEffect(()=>{if(!p)return;const y=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(y)},[p]);const x=l.useCallback(async(y,C)=>{var v;if(C.kind==="ide"&&C.providerType){await f(y,C.providerType,{workspacePath:C.workspace||null});return}if((C.kind==="cli"||C.kind==="acp")&&C.providerType){const w=((v=C.workspace)==null?void 0:v.trim())||"";await h(y,C.kind,C.providerType,{workspacePath:w||null,useHome:!w,resumeSessionId:C.providerSessionId||null})}},[f,h]);return{machineAction:{state:o,message:c},resetMachineAction:m,handleLaunchDetectedIde:f,handleAddWorkspace:g,handleMachineUpgrade:k,handleLaunchWorkspaceProvider:h,handleListSavedSessions:b,handleBrowseDirectory:S,handleOpenRecent:x}}function _A({conversations:e,selectedConversation:t,machineBackTarget:n,markConversationRead:a,resetMachineAction:r,setSelectedTabKey:o,setScreen:i,setSelectedMachineId:c,setSection:d,setMachineBackTarget:p}){const u=l.useCallback(S=>{o(S.tabKey),i("chat"),a(S)},[a,i,o]),m=l.useCallback(S=>{const x=e.find(y=>y.routeId===S.routeId&&y.streamSource==="native");x&&(o(x.tabKey),i("chat"),a(x))},[e,a,i,o]),f=l.useCallback(()=>{a(t),i("inbox")},[a,t,i]),g=l.useCallback((S,x="inbox")=>{c(S),r(),d("machines"),p(x),i("machine")},[r,p,i,d,c]),k=l.useCallback(S=>{const x=Vs(S);x&&g(x,"chat")},[g]),h=l.useCallback(()=>{r(),i(n)},[n,r,i]),b=l.useCallback(S=>{d(S),i("inbox")},[i,d]);return{openConversation:u,openNativeConversation:m,backFromConversation:f,openMachine:g,openConversationMachine:k,backFromMachine:h,changeMachineSection:b}}function aa(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function HA(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function $A({conversations:e,hiddenConversations:t,ides:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,userName:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,onOpenHistory:k,onOpenRemote:h,onStopCli:b,wsStatus:S,isConnected:x,initialDataLoaded:y=!0,onShowAllHiddenConversations:C,onHideConversation:v,onOpenMeshGraph:w,onOpenNewSession:j,liveSessionInboxState:N,setCliViewModeOverrides:A}){const[T,I]=l.useState(()=>{var ce;return((ce=e[0])==null?void 0:ce.tabKey)||null}),[P,M]=l.useState(()=>e[0]?"chat":"inbox"),[E,D]=l.useState("chats"),[W,R]=l.useState(null),[B,_]=l.useState("inbox"),H=l.useRef([]),L=ia(),F="1.0.56",$=l.useMemo(()=>e.find(ce=>ce.tabKey===T)||e[0]||null,[e,T]),K=l.useMemo(()=>$?n.find(ce=>ce.id===$.routeId):void 0,[n,$]),z=l.useMemo(()=>!$||ht($)||!bt($)?null:ca($),[$]),ne=l.useMemo(()=>n.filter(ce=>ce.type==="adhdev-daemon").sort(Kl),[n]),ie=l.useMemo(()=>ne.find(ce=>ce.id===W)||null,[ne,W]),Ce=So({sendDaemonCommand:r,activeConv:$||void 0,setActionLogs:o,isStandalone:i}),me=EA({sendDaemonCommand:r,navigate:L,ides:n,conversations:e}),O=NC(e),Y=l.useMemo(()=>e.map(ce=>{const Ae=P==="chat"&&($==null?void 0:$.tabKey)===ce.tabKey,be=go(ce,N,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Ae}),we=Nn(ce),_e=Vm(ce),U=th(ce,_e);return{conversation:ce,timestamp:we,preview:U,unread:be.unread,requiresAction:be.requiresAction,isWorking:be.isWorking,inboxBucket:be.inboxBucket}}),[e,N,P,$,O]),{markConversationRead:X}=IA({conversations:e,machineEntries:ne,items:Y,selectedConversation:$,selectedTabKey:T,screen:P,liveSessionInboxState:N,sendDaemonCommand:r,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,setSelectedTabKey:I,setScreen:M,setSelectedMachineId:R,setSection:D,setMachineBackTarget:_,resetMachineAction:me.resetMachineAction}),Q=_A({conversations:e,selectedConversation:$,machineBackTarget:B,markConversationRead:X,resetMachineAction:me.resetMachineAction,setSelectedTabKey:I,setScreen:M,setSelectedMachineId:R,setSection:D,setMachineBackTarget:_}),{isMuted:ve,toggleMute:he}=Qh(N,r),{attentionItems:Z,unreadItems:fe,workingItems:V,completedItems:q}=l.useMemo(()=>TA(Y,H.current),[Y]);l.useEffect(()=>{H.current=V.map(ce=>ce.conversation.tabKey)},[V]);const ee=l.useMemo(()=>ie?Y.filter(ce=>Vs(ce.conversation)===ie.id):[],[Y,ie]),pe=l.useMemo(()=>MA(ie,n),[n,ie]),le=!!ie&&jo(ie,Js(ie,F)),se=l.useMemo(()=>(ie==null?void 0:ie.availableProviders)||[],[ie]),te=l.useMemo(()=>se.filter(ce=>aa(ce,"cli")).map(ce=>({type:ce.type,displayName:ce.displayName||ce.type,icon:ce.icon})),[se]),ue=l.useMemo(()=>se.filter(ce=>aa(ce,"acp")).map(ce=>({type:ce.type,displayName:ce.displayName||ce.type,icon:ce.icon})),[se]),ye=l.useMemo(()=>PA(ne,Y,t),[Y,ne,t]),Me=l.useMemo(()=>To(n,y),[n,y]),re=l.useCallback(async ce=>{ie&&await me.handleOpenRecent(ie.id,ce)},[me,ie]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:P==="chat"&&$?s.jsx(gA,{selectedConversation:$,isAcp:ht($),isStandalone:i,selectedIdeEntry:K,actionLogs:a,userName:c,isSendingChat:Ce.isSendingChat,sendFeedbackMessage:Ce.sendFeedbackMessage,isFocusingAgent:Ce.isFocusingAgent,handleModalButton:Ce.handleModalButton,handleRelaunch:Ce.handleRelaunch,onBack:Q.backFromConversation,onOpenNativeConversation:Q.openNativeConversation,onOpenMachine:Q.openConversationMachine,onOpenHistory:k,onOpenRemote:h,onOpenMeshGraph:w,onStopCli:b,cliViewMode:z,onSetCliViewMode:async ce=>{await Lh({conversation:$,mode:ce,ides:n,sendDaemonCommand:r,setCliViewModeOverrides:A})},handleSendChat:Ce.handleSendChat,handleForceSendChat:Ce.handleForceSendChat,handleFocusAgent:Ce.handleFocusAgent}):P==="machine"&&ie?s.jsx(jA,{selectedMachineEntry:ie,selectedMachineConversations:ee,selectedMachineRecentLaunches:pe,cliProviders:te,acpProviders:ue,selectedMachineNeedsUpgrade:le,appVersion:F,machineAction:me.machineAction,isStandalone:i,section:E,showBottomNav:B==="inbox",onBack:Q.backFromMachine,onSectionChange:Q.changeMachineSection,onOpenConversation:Q.openConversation,onOpenRecent:re,onOpenMachineDetails:()=>L(`/machines/${ie.id}`),onMachineUpgrade:()=>me.handleMachineUpgrade(ie.id),onLaunchDetectedIde:(ce,Ae)=>me.handleLaunchDetectedIde(ie.id,ce,Ae),onAddWorkspace:(ce,Ae)=>me.handleAddWorkspace(ie.id,ce,Ae),onBrowseDirectory:ce=>me.handleBrowseDirectory(ie.id,ce),onLaunchWorkspaceProvider:(ce,Ae,be)=>me.handleLaunchWorkspaceProvider(ie.id,ce,Ae,be),onListSavedSessions:ce=>me.handleListSavedSessions(ie.id,ce)}):s.jsx(vA,{section:E,attentionItems:Z,unreadItems:fe,workingItems:V,completedItems:q,hiddenConversations:t,machineCards:ye,getAvatarText:HA,actionLogs:a,sendDaemonCommand:r,onOpenConversation:Q.openConversation,onShowAllHidden:C,onHideConversation:v,onOpenMeshGraph:w,onStopCli:b,onOpenNewSession:j,onOpenMachine:Q.openMachine,onOpenSettings:()=>L("/settings"),onSectionChange:D,wsStatus:S,isConnected:x,initialDataLoaded:y,conversationsLoaded:Me,isStandalone:i,isConversationMuted:ve,onToggleMuteConversation:he})})}function ci(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function FA({conversations:e,numGroups:t,onMoveTab:n,onReceiveTab:a,onOwnTabDrop:r,onClearPreviewOrder:o}){const i=l.useRef(0),[c,d]=l.useState(!1),[p,u]=l.useState(null),m=l.useCallback(()=>{i.current=0,d(!1),u(null)},[]);l.useEffect(()=>(window.addEventListener("dragend",m),window.addEventListener("drop",m),()=>{window.removeEventListener("dragend",m),window.removeEventListener("drop",m)}),[m]);const f=l.useCallback(b=>{b.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,d(!0))},[]),g=l.useCallback(b=>{if(!b.dataTransfer.types.includes("text/tab-key"))return;if(b.preventDefault(),!ci(t,n)){u("merge");return}const S=b.currentTarget.getBoundingClientRect(),x=b.clientX-S.left,y=S.width/3;x<y?u("split-left"):x>y*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(b=>{i.current=0,d(!1);const S=b.dataTransfer.getData("text/tab-key"),x=S?e.some(C=>C.tabKey===S):!1,y=p;if(u(null),o(),!!S){if(b.preventDefault(),y==="split-left"&&ci(t,n)){n==null||n(S,"split-left");return}if(y==="split-right"&&ci(t,n)){n==null||n(S,"split-right");return}if(x){r(S);return}a==null||a(S)}},[e,p,t,n,a,r,o]);return{dragOver:c,dropAction:p,resetDragState:m,handleDragEnter:f,handleDragOver:g,handleDragLeave:k,handleDrop:h}}function BA(e,t){const n=new Set(t.map(o=>o.tabKey)),a=e.filter(o=>n.has(o)),r=t.filter(o=>!e.includes(o.tabKey)).map(o=>o.tabKey);return[...a,...r]}function WA({conversations:e,initialActiveTabId:t,initialTabOrder:n,onActiveTabChange:a,onTabOrderChange:r}){const[o,i]=l.useState(t??null),[c,d]=l.useState(n??[]),[p,u]=l.useState(null),m=l.useRef(null),f=l.useRef(null),g=l.useRef(a),k=l.useRef(r);l.useEffect(()=>{g.current=a},[a]),l.useEffect(()=>{k.current=r},[r]),l.useEffect(()=>{t&&t!==o&&i(t)},[t,o]),l.useEffect(()=>{d(j=>{const N=BA(j,e);return N.length===j.length&&N.every((A,T)=>A===j[T])?j:N})},[e]);const h=l.useMemo(()=>{const j=p??c;if(j.length===0)return e;const N=new Map(j.map((A,T)=>[A,T]));return[...e].sort((A,T)=>{const I=N.get(A.tabKey)??999,P=N.get(T.tabKey)??999;return I-P})},[e,p,c]);l.useEffect(()=>{var N,A;if(h.length===0){o!==null&&(i(null),(N=g.current)==null||N.call(g,null));return}if(o&&h.some(T=>T.tabKey===o))return;const j=h[0].tabKey;j!==o&&(i(j),(A=g.current)==null||A.call(g,j))},[h,o]);const b=l.useMemo(()=>h.find(j=>j.tabKey===o),[h,o]),S=l.useCallback(j=>{var N;i(j),(N=g.current)==null||N.call(g,j)},[]),x=l.useCallback((j,N,A)=>{d(T=>{var E;const I=T.filter(D=>D!==j),P=I.indexOf(N);if(P<0)return T;const M=A==="left"?P:P+1;return I.splice(M,0,j),(E=k.current)==null||E.call(k,I),I}),u(null)},[]),y=l.useCallback((j,N,A)=>{const I=(c.length>0?c:e.map(E=>E.tabKey)).filter(E=>E!==j),P=I.indexOf(N);if(P<0)return;const M=A==="left"?P:P+1;I.splice(M,0,j),m.current=I,u(I)},[c,e]),C=l.useCallback(()=>{var N;const j=m.current;j&&(d(j),(N=k.current)==null||N.call(k,j))},[]),v=l.useCallback(()=>{m.current=null,u(null)},[]),w=l.useCallback(j=>{d(N=>{var T;const A=N.filter(I=>I!==j);return A.push(j),(T=k.current)==null||T.call(k,A),A})},[]);return{activeTabId:o,activeConv:b,sortedConversations:h,previewOrderRef:m,draggingTabRef:f,selectTab:S,handleTabReorder:x,updatePreviewOrder:y,commitPreviewOrder:C,clearPreviewOrder:v,moveTabToEnd:w,setDraggingTabKey:j=>{f.current=j}}}function OA({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 xc({conversationsCount:e,isSplitMode:t,isStandalone:n,hasRegisteredMachines:a=!1,suppressGuide:r=!1,onOpenNewSession:o,isLoading:i=!1}){const{t:c}=ke("common");if(r)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});if(i)return s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center gap-3 -mt-8 text-text-muted",children:[s.jsx(ls,{}),s.jsx("p",{className:"text-sm",children:c("paneGroup.loadingSessions")})]});const d=!n&&!a,p=a&&!!o,u=c(a?"paneGroup.noConversations":n?"paneGroup.waitingForDaemon":"paneGroup.connectYourMachines"),m=c(a?"paneGroup.newSessionDescription":n?"paneGroup.daemonDescription":"paneGroup.installDescription");return e===0&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:u}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:m}),p&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:o,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:c("paneGroup.newSession"),"aria-label":c("paneGroup.newSession"),children:[s.jsx(Wl,{size:14}),s.jsx("span",{children:c("paneGroup.newSession")})]})}),d&&s.jsx(qh,{}),d&&s.jsx("div",{className:"mt-8",children:s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:"Read the documentation →"})})]})]}):s.jsx("div",{className:"text-sm text-text-muted opacity-50",children:t?"Move a tab here to view":"No active agent"})}const Xh="adhdev-tab-shortcuts";function Zh(){try{return JSON.parse(localStorage.getItem(Xh)||"{}")}catch{return{}}}function ef({enabled:e=!0,sortedTabKeys:t,onFocus:n,onSelectTab:a}){const r=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>Zh()),[c,d]=l.useState(null),p=l.useCallback(m=>{const f=[];return m.metaKey&&f.push(r?"⌘":"Meta"),m.ctrlKey&&f.push("Ctrl"),m.altKey&&f.push(r?"⌥":"Alt"),m.shiftKey&&f.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(m.key)?null:(f.push(m.key.length===1?m.key.toUpperCase():m.key),f.join("+"))},[r]),u=l.useCallback(m=>{i(m);try{localStorage.setItem(Xh,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,b]of Object.entries(k))b===g&&delete k[h];k[c]=g,u(k),d(null)};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[e,c,o,u,p]),l.useEffect(()=>{if(!e)return;const m=f=>{if(!(!f.ctrlKey&&!f.metaKey&&!f.altKey)){for(const[g,k]of Object.entries(o))if(t.includes(g)&&p(f)===k){f.preventDefault(),n(),a(g);return}}};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[e,o,t,n,a,p]),{isMac:r,tabShortcuts:o,shortcutListening:c,setShortcutListening:d,saveShortcuts:u}}const di=e=>{e.preventDefault()},UA=l.memo(function({conv:t,isActive:n,isDraggedTab:a,isTaskCompleteUnread:r,shortcut:o,conversationKeys:i,draggingTabRef:c,onFocus:d,onSelectTab:p,onConversationActivated:u,onPreviewReorder:m,onReorderTab:f,onCommitPreviewOrder:g,onClearPreviewOrder:k,onDragStateReset:h,onDragTabKeyChange:b,onReceiveTab:S,onOpenContextMenu:x,longPressTimer:y,isGroupActive:C}){const v=En(t),w=v.isGenerating?"agent-tab-generating":v.isWaiting?"agent-tab-waiting":"",j=v.isReconnecting,N=VC(t),A=YC(t),T=eh(t),I=l.useCallback(H=>{c.current=t.tabKey,b(t.tabKey),H.dataTransfer.setData("text/tab-key",t.tabKey),H.dataTransfer.effectAllowed="move"},[t.tabKey,c,b]),P=l.useCallback(()=>{c.current=null,b(null),g(),k(),h()},[c,b,g,k,h]),M=l.useCallback(H=>{const L=c.current;if(!(!L||L===t.tabKey)&&H.dataTransfer.types.includes("text/tab-key")){H.preventDefault(),H.stopPropagation();const F=H.currentTarget.getBoundingClientRect(),$=H.clientX<F.left+F.width/2?"left":"right";m(L,t.tabKey,$)}},[t.tabKey,c,m]),E=l.useCallback(H=>{H.preventDefault(),H.stopPropagation();const L=H.dataTransfer.getData("text/tab-key");if(L&&L!==t.tabKey){const F=H.currentTarget.getBoundingClientRect(),$=H.clientX<F.left+F.width/2?"left":"right";i.includes(L)?f(L,t.tabKey,$):S&&S(L)}k()},[t.tabKey,i,f,S,k]),D=l.useCallback(H=>{H.stopPropagation(),d(),p(t.tabKey),u(t)},[t,u,d,p]),W=l.useCallback(H=>{H.preventDefault(),x(H.clientX,H.clientY,t.tabKey)},[t.tabKey,x]),R=l.useCallback(H=>{const L=H.touches[0];y.current=setTimeout(()=>{x(L.clientX,L.clientY,t.tabKey)},600)},[t.tabKey,y,x]),B=l.useCallback(()=>{y.current&&clearTimeout(y.current)},[y]),_=["adhdev-dockview-tab",w,n&&"is-active",C&&"is-group-active",j&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:_,draggable:!0,onDragStart:I,onDragEnd:P,onDragOver:M,onDrop:E,onClick:D,onContextMenu:W,onTouchStart:R,onTouchEnd:B,onTouchMove:B,style:{position:"relative",cursor:"pointer",opacity:a?.4:void 0},children:[T&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-badge pointer-events-none absolute top-0.5 right-0.5 text-text-muted",title:"Mesh chat","aria-label":"Mesh chat",children:s.jsx(cs,{size:11})}),r&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:v.isGenerating?s.jsx(ls,{size:12,thickness:2,color:"success"}):v.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):j?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):v.isConnecting?s.jsx(ls,{size:12,thickness:2}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),N.length>0&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-role",title:A,"aria-label":A||N.join(" · "),children:N.join(" · ")}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:kt(t),children:kt(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[j?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:Sn(t)}):v.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[Sn(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:Sn(t)}),s.jsx(qr,{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 GA({conversations:e,activeTabId:t,groupIndex:n,unreadTabKeys:a,draggingTabRef:r,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:m,onDragStateReset:f,onDragTabKeyChange:g,onReceiveTab:k,onHideTab:h,isGroupActive:b,allowTabShortcuts:S=!0}){const{t:x}=ke("common"),[y,C]=l.useState(null),v=l.useRef(null),w=l.useRef(null),j=l.useMemo(()=>e.map(E=>E.tabKey),[e]);qa("PaneGroupTabBar",{groupIndex:n,activeTabId:t,tabCount:e.length,ctxMenuTab:(y==null?void 0:y.tabKey)||null});const{isMac:N,tabShortcuts:A,shortcutListening:T,setShortcutListening:I,saveShortcuts:P}=ef({enabled:S,sortedTabKeys:e.map(E=>E.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!y)return;const E=D=>{const W=document.querySelector("[data-pane-context-menu]");W&&W.contains(D.target)||C(null)};return window.addEventListener("mousedown",E,!0),()=>window.removeEventListener("mousedown",E,!0)},[y]),l.useEffect(()=>{const E=w.current;if(!E)return;const D=W=>{Math.abs(W.deltaY)<=Math.abs(W.deltaX)||(W.preventDefault(),E.scrollLeft+=W.deltaY)};return E.addEventListener("wheel",D,{passive:!1}),()=>E.removeEventListener("wheel",D)},[]);const M=l.useCallback((E,D,W)=>{C({x:E,y:D,tabKey:W})},[]);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:w,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(E=>s.jsx(UA,{conv:E,isActive:t===E.tabKey,isDraggedTab:r.current===E.tabKey,isTaskCompleteUnread:a.has(E.tabKey),shortcut:S?A[E.tabKey]:void 0,conversationKeys:j,draggingTabRef:r,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:m,onDragStateReset:f,onDragTabKeyChange:g,onReceiveTab:k,onOpenContextMenu:M,longPressTimer:v,isGroupActive:b},E.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:x("paneGroup.noTabsInGroup")})]})}),y&&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:y.x,top:y.y},children:[S&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:di,onClick:E=>{E.stopPropagation(),I(y.tabKey),C(null)},children:["⌨ ",A[y.tabKey]?`Change shortcut (${A[y.tabKey]})`:"Set shortcut"]}),A[y.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:di,onClick:()=>{const E={...A};delete E[y.tabKey],P(E),C(null)},children:"✕ Remove shortcut"})]}),h&&s.jsxs(s.Fragment,{children:[S&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onMouseDown:di,onClick:()=>{h(y.tabKey),C(null)},children:s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx(mo,{size:12}),"Hide from Dashboard"]})})]})]}),S&&T&&s.jsx(Vt,{children:s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:()=>I(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:E=>E.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",N?"⌘+1":"Ctrl+1",", ",N?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:x("paneGroup.pressEscToCancel")})]})})})]})}function qA({conversations:e,ides:t,clearedTabs:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:d=!0,userName:p,groupIndex:u,onFocus:m,isSplitMode:f,numGroups:g,onMoveTab:k,onReceiveTab:h,style:b,onActiveTabChange:S,initialActiveTabId:x,initialTabOrder:y,onTabOrderChange:C,onHideTab:v,isFocused:w,allowTabShortcuts:j=!0,onOpenNewSession:N,liveSessionInboxState:A}){const{sendCommand:T}=St(),I=l.useRef(null),{activeTabId:P,activeConv:M,sortedConversations:E,draggingTabRef:D,selectTab:W,handleTabReorder:R,updatePreviewOrder:B,commitPreviewOrder:_,clearPreviewOrder:H,moveTabToEnd:L,setDraggingTabKey:F}=WA({conversations:e,initialActiveTabId:x,initialTabOrder:y,onActiveTabChange:S,onTabOrderChange:C}),$=So({sendDaemonCommand:r,activeConv:M,setActionLogs:o,isStandalone:i}),{dragOver:K,dropAction:z,resetDragState:ne,handleDragEnter:ie,handleDragOver:Ce,handleDragLeave:me,handleDrop:O}=FA({conversations:e,numGroups:g,onMoveTab:k,onReceiveTab:h,onOwnTabDrop:L,onClearPreviewOrder:H}),Y=M&&!ht(M)&&ca(M)==="terminal",X=l.useMemo(()=>M?t.find(Z=>Z.id===M.routeId):void 0,[t,M]),Q=l.useMemo(()=>M?a.filter(Z=>Z.routeId===M.tabKey):[],[a,M]),ve=l.useMemo(()=>new Set(E.filter(Z=>Lx(Z,A,{isOpenConversation:Z.tabKey===P})).map(Z=>Z.tabKey)),[P,A,E]);qa("PaneGroup",{groupIndex:u,conversationCount:e.length,activeTabId:P,dragOver:K});const he=l.useCallback(Z=>{Z.streamSource==="agent-stream"&&Z.agentType&&T(Z.routeId,Em(),{agentType:Z.agentType,...Z.sessionId&&{targetSessionId:Z.sessionId}}).catch(()=>{})},[T]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:m,style:{...b,outline:K?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(GA,{conversations:E,activeTabId:P,groupIndex:u,numGroups:g,unreadTabKeys:ve,draggingTabRef:D,onFocus:m,onSelectTab:W,onConversationActivated:he,onPreviewReorder:B,onReorderTab:R,onCommitPreviewOrder:_,onClearPreviewOrder:H,onDragStateReset:ne,onDragTabKeyChange:F,onMoveTab:k,onReceiveTab:h,onHideTab:v,isGroupActive:w??!1,allowTabShortcuts:j}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:ie,onDragOver:Ce,onDragLeave:me,onDrop:O,children:[K&&s.jsx(OA,{dropAction:z,canSplit:!!(g<4&&k)}),M?s.jsx(gc,{activeConv:M,clearToken:n[M.tabKey]||0,isCliTerminal:!!Y,ideEntry:X,terminalRef:I,handleModalButton:$.handleModalButton,handleRelaunch:$.handleRelaunch,handleSendChat:$.handleSendChat,handleForceSendChat:$.handleForceSendChat,isSendingChat:$.isSendingChat,sendFeedbackMessage:$.sendFeedbackMessage,handleFocusAgent:$.handleFocusAgent,isFocusingAgent:$.isFocusingAgent,actionLogs:Q,userName:p,isInputActive:!f||!!w}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(xc,{conversationsCount:e.length,isSplitMode:f,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:N,isLoading:!To(t,d)})})]})]})}function zA({containerRef:e,isSplitMode:t,numGroups:n,groupSizes:a,groupedConvs:r,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:p,isStandalone:u,hasRegisteredMachines:m,initialDataLoaded:f,userName:g,focusedGroup:k,focusGroup:h,moveTabToGroup:b,splitTabRelative:S,closeGroup:x,handleResizeStart:y,groupActiveTabIds:C,setGroupActiveTab:v,groupTabOrders:w,setGroupTabOrder:j,toggleHiddenTab:N,onOpenNewSession:A,allowTabShortcuts:T=!0,liveSessionInboxState:I}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:r.map((P,M)=>{const E=t&&a.length===n?`${a[M]}%`:void 0;return s.jsxs(Rt.Fragment,{children:[t&&M>0&&s.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:D=>y(M-1,D),onDoubleClick:()=>x(M),title:"Drag to resize · Double-click to merge",children:s.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),s.jsx(qA,{style:t?{flexBasis:E??`${100/n}%`,flexGrow:E?0:1,flexShrink:E?0:1}:void 0,conversations:P,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:p,isStandalone:u,hasRegisteredMachines:m,initialDataLoaded:f,userName:g,groupIndex:M,isFocused:t&&k===M,onFocus:()=>h(M),isSplitMode:t,numGroups:n,onMoveTab:(D,W)=>{W==="left"&&M>0?b(D,M-1):W==="right"&&M<n-1?b(D,M+1):W==="split-left"&&n<4?S(D,M,"left"):W==="split-right"&&n<4&&S(D,M,"right")},onReceiveTab:D=>b(D,M),onActiveTabChange:D=>v(M,D),initialActiveTabId:C[M],initialTabOrder:w[M],onTabOrderChange:D=>j(M,D),onHideTab:N,onOpenNewSession:A,allowTabShortcuts:T,liveSessionInboxState:I})]},M)})})}const tf="adhdev-dashboard-action-shortcuts",KA=1200,VA=[["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 YA(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function gt(e,t){switch(e){case"openShortcutHelp":return"?";case"openNewSession":return t?"⌘+⇧+Enter":"Ctrl+Shift+Enter";case"hideCurrentTab":return t?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return t?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return t?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return t?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return t?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return t?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return t?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return t?"⌘+Ctrl+⇧+→":"Ctrl+Alt+Shift+→";case"splitActiveTabDown":return t?"⌘+Ctrl+⇧+↓":"Ctrl+Alt+Shift+↓";case"focusLeftPane":return"";case"focusRightPane":return"";case"focusUpPane":return"";case"focusDownPane":return"";case"moveActiveTabToLeftPane":return"";case"moveActiveTabToRightPane":return"";case"moveActiveTabToUpPane":return"";case"moveActiveTabToDownPane":return"";case"triggerPrimaryApprovalAction":return t?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return t?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return t?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return t?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return t?"⌘+⇧+←":"Ctrl+Shift+←";case"selectNextGroupTab":return t?"⌘+⇧+→":"Ctrl+Shift+→";case"toggleCliView":return t?"⌥+T":"Ctrl+Alt+T"}}function sf(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:gt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:gt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:gt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:gt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:gt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:gt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:gt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:gt("popoutActiveTab",e)},{id:"dockActiveTab",label:"Dock active tab",description:"Dock a floating tab back into the grid, or move a popout tab back to the main window.",defaultShortcut:gt("dockActiveTab",e)},{id:"splitActiveTabRight",label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it.",defaultShortcut:gt("splitActiveTabRight",e)},{id:"splitActiveTabDown",label:"Move active tab to new lower pane",description:"Create a pane below and move the active tab into it.",defaultShortcut:gt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:gt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:gt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:gt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:gt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:gt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:gt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:gt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:gt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:gt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:gt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:gt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:gt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:gt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:gt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:gt("toggleCliView",e)}]}function bl(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function eo(e){const t=Object.fromEntries(sf(e).map(n=>[n.id,n.defaultShortcut]));try{const n=JSON.parse(localStorage.getItem(tf)||"{}"),a={...t,...n};for(const[r,o]of VA)a[r]===o&&(a[r]=t[r]);return a}catch{return t}}function nf(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function QA({enabled:e=!0,onTrigger:t}){const n=YA(),[a,r]=l.useState(()=>eo(n)),[o,i]=l.useState(null),[c,d]=l.useState([]),p=l.useRef({parts:[],timer:null}),u=l.useCallback(h=>{const b=[];return h.metaKey&&b.push(n?"⌘":"Meta"),h.ctrlKey&&b.push("Ctrl"),h.altKey&&b.push(n?"⌥":"Alt"),h.shiftKey&&h.key.length!==1&&b.push(n?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(b.push(nf(h.key)),b.join("+"))},[n]),m=l.useCallback(h=>{r(h);try{localStorage.setItem(tf,JSON.stringify(h))}catch{}},[]);l.useEffect(()=>{const h=eo(n),b=Object.entries(a),S=Object.entries(h);b.length===S.length&&b.every(([x,y])=>h[x]===y)||m(h)},[a,n,m]);const f=l.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),g=l.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},KA))},[]);l.useEffect(()=>{if(!o)return;const h=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){i(null),d([]);return}const S=u(b);if(!S)return;const y=!(b.metaKey||b.ctrlKey||b.altKey)&&/^[A-Z0-9]$/.test(S);if(c.length===0&&y){d([S]);return}const v=[...c,S].slice(0,2).join(" "),w={...a};for(const[j,N]of Object.entries(w))N===v&&delete w[j];w[o]=v,m(w),i(null),d([])};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[a,u,m,o,c]),l.useEffect(()=>{if(!e||o)return;const h=b=>{if(b.defaultPrevented)return;const S=u(b);if(!S)return;const x=b.metaKey||b.ctrlKey||b.altKey;if(bl(b.target))return;const y=p.current.parts,C=x?[S]:[...y.slice(-1),S].slice(-2),v=C.join(" "),w=C[C.length-1],j=Object.entries(a).filter(([,P])=>!!P),N=j.find(([,P])=>P===v);if(N){b.preventDefault(),f(),t(N[0]);return}if(j.some(([,P])=>P.startsWith(`${v} `))){b.preventDefault(),p.current.parts=C,g();return}const T=j.find(([,P])=>P===w);if(T){b.preventDefault(),f(),t(T[0]);return}if(j.some(([,P])=>P.startsWith(`${w} `))){b.preventDefault(),p.current.parts=[w],g();return}f()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[a,g,e,u,t,f,o]),l.useEffect(()=>()=>f(),[f]);const k=l.useMemo(()=>sf(n),[n]);return{isMac:n,actionDefinitions:k,actionShortcuts:a,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:d,saveShortcuts:m}}function JA({isTabInPopout:e,isTabFloating:t,tabShortcut:n,actionShortcuts:a}){const r=[];return e?(t&&r.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:a.dockActiveTab}),r.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:a.dockActiveTab})):t?r.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:a.dockActiveTab}):r.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:a.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:a.popoutActiveTab}),r.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:n?`Change shortcut (${n})`:"Set shortcut",shortcut:a.setActiveTabShortcut}),n&&r.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),r.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:a.hideCurrentTab,tone:"muted"}),r}function af(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function pu({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:n,ides:a}){return!e||n>0?!1:t?!af(a):!0}function XA({previousVisibleConversationCount:e,visibleConversationCount:t,ides:n}){return t>0||e<=0?!1:af(n)}const rf=1e3,ZA=4;function mu(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function hu(e,t,n){return Math.abs(t.clientX-e.clientX)>n||Math.abs(t.clientY-e.clientY)>n}function eT({detachDelayMs:e=rf,stillnessThresholdPx:t=ZA,onDetach:n,setTimeoutFn:a=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:r=globalThis.clearTimeout.bind(globalThis)}){let o=null,i=null,c=null,d=null,p=null,u=!1;const m=()=>{p!=null&&(r(p),p=null)},f=()=>{m(),c=null},g=()=>{m(),o=null,i=null,c=null,d=null,u=!1},k=()=>{!o||!c||!d||u||p!=null||(p=a(()=>{p=null,!(!o||!c||!d||u)&&mu(d,i)&&(hu(c,d,t)||(u=!0,n({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},h=S=>{if(!(!o||u)){if(!mu(S,i)){d={clientX:S.clientX,clientY:S.clientY},f();return}(!c||hu(c,S,t))&&(m(),c={clientX:S.clientX,clientY:S.clientY}),d={clientX:S.clientX,clientY:S.clientY},k()}},b=S=>{!o||u||(S&&(d={clientX:S.clientX,clientY:S.clientY}),f())};return{startDrag:S=>{m(),o=S.panelId,i=S.selfPanelBounds??null,c=null,d={clientX:S.clientX,clientY:S.clientY},u=!1},markSelfPanel:h,markNonSelfPanel:b,markNoDropTarget:b,markDockTarget:b,endDrag:g,isDragging:()=>o!=null,hasDetached:()=>u,dispose:g}}function tT(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function Lr(e){return kt(e)||e.tabKey}function sT(e){return`remote:${e}`}function fs(e){return e.startsWith("remote:")}function fu(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function ui(e){var a;const t=e==null?void 0:e.defaultView;if(!t)return;const n=r=>{if(r)try{r.focus({preventScroll:!0})}catch{try{r.focus()}catch{}}};try{t.focus(),n(e==null?void 0:e.body),n(e==null?void 0:e.documentElement),(a=t.requestAnimationFrame)==null||a.call(t,()=>{try{t.focus(),n(e==null?void 0:e.body)}catch{}})}catch{}}function pi(e,t){e.classList.remove(Wi.className,Oi.className),e.classList.add(t==="light"?Wi.className:Oi.className)}function gu(e){return e?Array.from(new Set(e.groups.map(t=>{var n,a;return(a=(n=t.element)==null?void 0:n.ownerDocument)==null?void 0:a.defaultView}).filter(t=>!!t&&t!==window))):[]}function nT(e,t,n){var i;const a=[t];let r;for(const c of a){let d;for(const p of c){const u=e.addPanel({id:p.tabKey,component:"conversation",title:Lr(p),params:{kind:"conversation",tabKey:p.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:r?{position:{referencePanel:r,direction:"right"},inactive:!0}:{}});d||(d=u.id)}r=d??r}return n??((i=t[0])==null?void 0:i.tabKey)??null}function bu(e,t){const n=new Set(t.map(r=>r.tabKey)),a=new Map;for(const r of t)a.set(r.tabKey,(a.get(r.tabKey)||0)+1);for(const r of[...e.panels])fs(r.id)||n.has(r.id)||e.removePanel(r);for(const r of t){const o=e.getPanel(r.tabKey);if(o){(a.get(r.tabKey)||0)>1&&console.warn("[dashboard-conversations] Dockview panel already exists for duplicate tabKey",{tabKey:r.tabKey,daemonId:r.daemonId,sessionId:r.sessionId,providerSessionId:r.providerSessionId,panelId:o.id}),o.update({params:{tabKey:r.tabKey}}),o.title!==Lr(r)&&o.api.setTitle(Lr(r));continue}e.addPanel({id:r.tabKey,component:"conversation",title:Lr(r),params:{kind:"conversation",tabKey:r.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function xu(e,t,n){var d,p;const a=n?sT(n):null;for(const u of[...e.panels])fs(u.id)&&(!a||u.id!==a)&&e.removePanel(u);if(!n||!a)return;const r=ws(t,n);if(!r&&e.totalPanels===0)return;const o=e.getPanel(a),i=ah(r);if(o){o.title!==i&&o.api.setTitle(i);return}const c=(r==null?void 0:r.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((p=e.panels.find(u=>!fs(u.id)))==null?void 0:p.id);e.addPanel({id:a,component:"remote",title:i,params:{kind:"remote",routeId:n},...c?{position:{referencePanel:c,direction:"right"},inactive:!0}:{}})}function of({doId:e,targetSessionId:t,connState:n,viewMode:a}){const[r,o]=l.useState(null),[i,c]=l.useState(null);l.useEffect(()=>e?Ct.onScreenshot("ide-page",(u,m)=>{if(u!==e)return;const f=new FileReader;f.onload=()=>o(f.result),f.readAsDataURL(m)}):void 0,[e]),l.useEffect(()=>{n!=="connected"&&o(null)},[n]),l.useEffect(()=>{var u;return e?((u=Ct.onStatus)==null?void 0:u.call(Ct,(m,f)=>{m===e&&f!=null&&f.screenshotUsage&&c(f.screenshotUsage)}))||(()=>{}):void 0},[e]),l.useEffect(()=>{o(null)},[e,t]),l.useEffect(()=>{const p=e?Ct.get(e):null;if(!(!p||n!=="connected"))return a!=="chat"&&t?p.startScreenshots(t):p.stopScreenshots(t),()=>{p.stopScreenshots(t)}},[a,n,t,e]);const d=l.useCallback(async(p,u)=>{const m=e?Ct.get(e):null;return!m||n!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):m.sendInput(p,u,t)},[e,n,t]);return{connScreenshot:r,screenshotUsage:i,handleRemoteAction:d}}const lf=l.createContext(null);function Mo(){const e=l.useContext(lf);if(!e)throw new Error("DashboardDockviewContext missing");return e}function aT(e){const[,t]=l.useState(0);l.useEffect(()=>{const n=()=>t(r=>r+1),a=[e.api.onDidActiveGroupChange(n),e.api.onDidTitleChange(n),e.api.onDidGroupChange(n),e.containerApi.onDidActivePanelChange(n)];return()=>{for(const r of a)r.dispose()}},[e.api,e.containerApi])}function rT({params:e}){var d;const t=Mo(),n=l.useMemo(()=>ws([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),a=l.useMemo(()=>t.ides.find(p=>p.id===e.routeId),[t.ides,e.routeId]),r=(n==null?void 0:n.daemonId)||((d=n==null?void 0:n.routeId)==null?void 0:d.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:i,handleRemoteAction:c}=of({doId:r,targetSessionId:n?Lm(n):(a==null?void 0:a.sessionId)||(a==null?void 0:a.instanceId),connState:(n==null?void 0:n.connectionState)||"new",viewMode:"remote"});return n?s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:s.jsx(Qp,{addLog:()=>{},connState:n.connectionState||"new",connScreenshot:o,screenshotUsage:i,transportType:n.transport,onAction:c})}):s.jsx("div",{className:"h-full min-h-0 min-w-0 flex items-center justify-center text-sm text-text-muted",children:"Remote view unavailable"})}function oT(){const e=Mo();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(xc,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels,isLoading:!To(e.ides,e.initialDataLoaded)})})}function iT(e){var x,y;aT(e);const t=Mo(),n=l.useCallback(C=>{"button"in C&&C.button!==0||e.api.setActive()},[e.api]),a=e.params.kind==="remote"?void 0:t.conversationsByTabKey.get(e.params.tabKey),r=a==null?void 0:a.sessionId,o=l.useCallback(C=>PC(C),[]),i=l.useCallback(()=>MC(r),[r]),c=l.useSyncExternalStore(o,i,i);if(e.params.kind==="remote"){const C=ws([...t.conversationsByTabKey.values()],e.params.routeId),v=((x=e.api.group.activePanel)==null?void 0:x.id)===e.api.id,w=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${v?" is-active":""}${w?" 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=((y=e.api.group.activePanel)==null?void 0:y.id)===e.api.id,u=e.api.isGroupActive,m=go(d,t.liveSessionInboxState,{isOpenConversation:p}),f=m.isReconnecting,g=m.isConnecting,k=m.isGenerating||c,h=m.isWaiting,b=m.unread,S=t.tabShortcuts[d.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${p?" is-active":""}${u?" is-group-active":""}${f?" is-reconnecting":""}`,title:kt(d),"data-tab-key":e.params.tabKey,onMouseDown:n,onTouchStart:n,onContextMenu:C=>{var v;C.preventDefault(),n(C),t.openTabContextMenu({x:C.clientX,y:C.clientY,tabKey:d.tabKey,sourceDocument:((v=C.target)==null?void 0:v.ownerDocument)??document})},children:[b&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:k?s.jsx(ls,{size:12,thickness:2,color:"success"}):h?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):f?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):g?s.jsx(ls,{size:12,thickness:2}):d.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:kt(d)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:f?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Sn(d)}):g?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Sn(d)}):s.jsx("span",{children:Sn(d)})})]}),S&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:S,children:S})]})}function hr(e){return e.isActive}function vu(e){return e.isVisible}function lT(e){e.preventDefault()}function cT({params:e,api:t}){var g;const n=Mo(),a=l.useRef(null),[r,o]=l.useState(()=>hr(t)),[i,c]=l.useState(()=>vu(t)),d=n.conversationsByTabKey.get(e.tabKey),p=So({sendDaemonCommand:n.sendDaemonCommand,activeConv:d,setActionLogs:n.setActionLogs,isStandalone:n.isStandalone});l.useEffect(()=>{o(hr(t)),c(vu(t));const k=[t.onDidActiveChange(h=>o(h.isActive)),t.onDidActiveGroupChange(h=>{if(!hr(t)&&!h.isActive){o(!1);return}o(hr(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(xc,{conversationsCount:0,isSplitMode:!1,isStandalone:n.isStandalone,hasRegisteredMachines:n.hasRegisteredMachines,onOpenNewSession:n.onOpenNewSession,suppressGuide:n.hasDetachedConversationPanels,isLoading:!To(n.ides,n.initialDataLoaded)})});const f=!ht(d)&&ca(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(gc,{activeConv:d,clearToken:n.clearedTabs[d.tabKey]||0,isCliTerminal:f,ideEntry:u,terminalRef:a,handleModalButton:p.handleModalButton,handleRelaunch:p.handleRelaunch,handleSendChat:p.handleSendChat,handleForceSendChat:p.handleForceSendChat,isSendingChat:p.isSendingChat,handleFocusAgent:p.handleFocusAgent,isFocusingAgent:p.isFocusingAgent,actionLogs:m,userName:n.userName,scrollToBottomRequestNonce:((g=n.scrollToBottomRequest)==null?void 0:g.tabKey)===d.tabKey?n.scrollToBottomRequest.nonce:void 0,isInputActive:r,isVisible:i})})}function dT({visibleConversations:e,clearedTabs:t,ides:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:d,userName:p,toggleHiddenTab:u,actionShortcuts:m,registerActionHandlers:f,onActiveTabChange:g,onOpenNewSession:k,onRequestScrollToBottom:h,requestedActiveTabKey:b,requestedRemoteIdeId:S,onRequestedActiveTabConsumed:x,scrollToBottomRequest:y,liveSessionInboxState:C,layoutProfile:v}){var $e,at,rt;const{theme:w}=Rs(),{sendCommand:j}=St(),N=l.useRef(null),A=l.useRef(null),T=l.useRef(null),I=l.useRef(!1),P=l.useRef(!1),M=l.useRef(!1),E=l.useRef(null),D=l.useRef([]),[W,R]=l.useState(null),[B,_]=l.useState(0),H=l.useRef(typeof window>"u"?{}:TN(v)),L=l.useMemo(()=>new Map(e.map(G=>[G.tabKey,G])),[e]),F=l.useMemo(()=>{const G=N.current;return G?G.groups.some(oe=>{try{const de=oe.model.location.type;return de!=="floating"&&de!=="popout"?!1:oe.panels.some(xe=>L.has(xe.id))}catch{return!1}}):!1},[L,B,e]),$=l.useCallback(()=>{var G;(G=N.current)==null||G.focus()},[]),K=l.useCallback((G,oe)=>{h==null||h(G,oe)},[h]),z=l.useCallback(G=>{const oe=document,de=G.document;for(const Ee of oe.querySelectorAll('link[rel="stylesheet"]')){const Je=de.createElement("link");Je.rel="stylesheet",Je.href=Ee.href,Ee.crossOrigin&&(Je.crossOrigin=Ee.crossOrigin),de.head.appendChild(Je)}for(const Ee of oe.querySelectorAll("style")){const Je=de.createElement("style");Je.textContent=Ee.textContent,de.head.appendChild(Je)}const xe=[];for(const Ee of oe.styleSheets)try{for(const Je of Ee.cssRules)Je instanceof CSSStyleRule&&(Je.selectorText===":root"||Je.selectorText==="html")&&xe.push(Je.cssText)}catch{}if(xe.length>0){const Ee=de.createElement("style");Ee.textContent=xe.join(`
|
|
64
|
+
The machine's IDE, workspace and provider settings are kept.`,confirmLabel:o("machine.connectedMachines.remove"),confirmColor:"red",onConfirm:A,onCancel:()=>m(null)})]})}const P1=[{id:"dark",label:"Dark",icon:Rp},{id:"light",label:"Light",icon:Lp},{id:"system",label:"System",icon:Ep}];function D1(){const{preference:e,setPreference:t}=Rs();return s.jsx("div",{className:"flex gap-2",children:P1.map(n=>s.jsxs("button",{onClick:()=>t(n.id),className:`px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors flex items-center gap-1.5 ${e===n.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:e===n.id?{color:"var(--accent-on-primary)"}:void 0,children:[s.jsx(n.icon,{size:14}),n.label]},n.id))})}function I1(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 L1(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function ti(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Qd(e){const{r:t,g:n,b:a}=L1(e);return .2126*ti(t)+.7152*ti(n)+.0722*ti(a)}function Jd(e,t){const n=Qd(e),a=Qd(t),r=Math.max(n,a),o=Math.min(n,a);return(r+.05)/(o+.05)}function Nh(e){const t=I1(e);if(!t)return"#111827";const n="#111827",a="#ffffff";return Jd(t,n)>=Jd(t,a)?n:a}const pl={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},ml={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},R1=[{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"}}}],Ah="adhdev-chat-theme",Th="adhdev-chat-theme-custom";function Pr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Ah)||"ember"}catch{return"ember"}}function bs(e){try{const t=localStorage.getItem(Th);if(t){const n=JSON.parse(t);return{...e==="dark"?pl:ml,...n[e]}}}catch{}return e==="dark"?pl:ml}function cr(e,t){try{localStorage.setItem(Th,JSON.stringify({dark:e,light:t}))}catch{}}function as(e,t){const n=parseInt(e.slice(1,3),16),a=parseInt(e.slice(3,5),16),r=parseInt(e.slice(5,7),16);return`rgba(${n}, ${a}, ${r}, ${t})`}function Xr(e,t){const n=Math.min(255,parseInt(e.slice(1,3),16)+t),a=Math.min(255,parseInt(e.slice(3,5),16)+t),r=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}`}const E1={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Ia(e,t){var r;const n=(r=E1[e])==null?void 0:r[t];if(!n)return;const a=document.documentElement;a.style.setProperty("--accent-primary",n),a.style.setProperty("--accent-primary-light",Xr(n,24)),a.style.setProperty("--accent-on-primary",Nh(n)),a.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${n}, ${Xr(n,18)})`),a.style.setProperty("--border-accent",as(n,.35)),a.style.setProperty("--nav-active-bg",as(n,.1)),a.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${n}, 0 0 12px ${as(n,.06)}`)}function Cn(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",as(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",as(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",as(e.borderSubtle,.25)),t.style.setProperty("--text-primary",e.textPrimary),t.style.setProperty("--text-secondary",e.textSecondary),t.style.setProperty("--text-muted",e.textMuted),t.style.setProperty("--border-subtle",as(e.borderSubtle,.5)),t.style.setProperty("--border-default",as(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",Xr(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Nh(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Xr(e.accentColor,40)})`),t.style.setProperty("--border-accent",as(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",as(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${as(e.accentColor,.06)}`),t.style.setProperty("--chat-user-bg",e.userBubble),t.style.setProperty("--chat-user-color",e.userText),t.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),t.style.setProperty("--chat-assistant-bg",e.assistantBubble),t.style.setProperty("--chat-assistant-color",e.assistantText),t.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),t.style.setProperty("--chat-assistant-border",`1px solid ${as(e.accentColor,.12)}`),t.style.setProperty("--chat-container-bg",e.containerBg),t.style.setProperty("--dashboard-pane-bg",e.containerBg),t.style.setProperty("--chat-thought-accent",e.accentColor),t.style.setProperty("--chat-tool-accent",e.accentColor),t.style.setProperty("--chat-action-color",e.accentColor),t.style.setProperty("--chat-send-bg",e.sendButton),t.style.setProperty("--chat-input-border",e.inputBorder)}function cc(){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 _1(e){try{localStorage.setItem(Ah,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=jn()?"dark":"light";Cn(bs(t))}else cc(),Ia(e,jn()?"dark":"light")}function H1(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Pr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=jn()?"dark":"light";Cn(bs(t))}else cc(),Ia(e,jn()?"dark":"light")}function jn(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Gt({label:e,value:t,onChange:n}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[s.jsx("input",{type:"color",value:t,onChange:a=>n(a.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),s.jsx("input",{type:"text",value:t,onChange:a=>{/^#[0-9a-fA-F]{0,6}$/.test(a.target.value)&&n(a.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function xa({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 $1({dark:e,onColorsChange:t}){const{t:n}=ke("common"),a=e?"dark":"light",[r,o]=l.useState(()=>bs(a));l.useEffect(()=>{o(bs(a))},[a]);const i=l.useCallback((c,d)=>{o(p=>{const u={...p,[c]:d},f=bs(a==="dark"?"light":"dark");return a==="dark"?cr(u,f):cr(f,u),Cn(u),t(u),u})},[a,t]);return s.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[s.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[n("settings.theme.customEditorTitle"),s.jsx("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:n(e?"settings.theme.darkMode":"settings.theme.lightMode")})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs(xa,{title:n("settings.theme.sectionAppBackground"),children:[s.jsx(Gt,{label:n("settings.theme.colorBackground"),value:r.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(Gt,{label:n("settings.theme.colorSurface"),value:r.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(Gt,{label:n("settings.theme.colorCard"),value:r.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(xa,{title:n("settings.theme.sectionAppText"),children:[s.jsx(Gt,{label:n("settings.theme.colorPrimary"),value:r.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(Gt,{label:n("settings.theme.colorSecondary"),value:r.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(Gt,{label:n("settings.theme.colorMuted"),value:r.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(xa,{title:n("settings.theme.sectionBordersAccent"),children:[s.jsx(Gt,{label:n("settings.theme.colorBorderSubtle"),value:r.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(Gt,{label:n("settings.theme.colorBorderDefault"),value:r.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(Gt,{label:n("settings.theme.colorAccent"),value:r.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(xa,{title:n("settings.theme.sectionChatBubbles"),children:[s.jsx(Gt,{label:n("settings.theme.colorUserBubble"),value:r.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(Gt,{label:n("settings.theme.colorUserText"),value:r.userText,onChange:c=>i("userText",c)}),s.jsx(Gt,{label:n("settings.theme.colorAgentBubble"),value:r.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(Gt,{label:n("settings.theme.colorAgentText"),value:r.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(xa,{title:n("settings.theme.sectionChatLayout"),children:[s.jsx(Gt,{label:n("settings.theme.colorChatBg"),value:r.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(Gt,{label:n("settings.theme.colorSendButton"),value:r.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(Gt,{label:n("settings.theme.colorInputBorder"),value:r.inputBorder,onChange:c=>i("inputBorder",c)}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:n("settings.theme.labelBubbleRadius")}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[s.jsx("input",{type:"range",min:4,max:24,value:r.bubbleRadius,onChange:c=>i("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),s.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[r.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const c=e?pl:ml,p=bs(e?"light":"dark");e?cr(c,p):cr(p,c),o(c),Cn(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 F1(){const{t:e}=ke("common"),[t,n]=l.useState(Pr),[a,r]=l.useState(!0),[o,i]=l.useState(()=>bs("dark"));l.useEffect(()=>{r(jn());const p=new MutationObserver(()=>{const f=jn();r(f);const g=Pr();g==="custom"?Cn(bs(f?"dark":"light")):Ia(g,f?"dark":"light")});p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const u=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const f=jn();r(f);const g=Pr();g==="custom"?Cn(bs(f?"dark":"light")):Ia(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"?Cn(bs(a?"dark":"light")):(cc(),Ia(t,a?"dark":"light"))},[t,a]),l.useEffect(()=>{i(bs(a?"dark":"light"))},[a]);const c=p=>{n(p),_1(p)},d=[...R1,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText},light:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:d.map(p=>{const u=t===p.id,m=a?p.preview.dark:p.preview.light,f=p.id==="honey"||p.id==="ember"?"#1a1a1a":p.id==="custom"?o.userText:"#fff";return s.jsxs("button",{onClick:()=>c(p.id),className:"text-left rounded-xl p-3 transition-all",style:{background:u?"var(--bg-glass-hover)":"var(--bg-glass)",border:u?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:u?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:m.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:e("settings.theme.helloHelp")}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.userBubble,color:f},children:e("settings.theme.fixBug")}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:e("settings.theme.onIt")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[u&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:p.id==="custom"?e("settings.theme.customLabel"):p.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:p.description})]})]})]},p.id)})}),t==="custom"&&s.jsx($1,{dark:a,onColorsChange:p=>i(p)})]})}const dc="adhdev_mobileDashboardMode_v1",hl="adhdev:mobile-dashboard-mode-change";function uc(){try{return localStorage.getItem(dc)==="workspace"?"workspace":"chat"}catch{return"chat"}}function B1(e){if(typeof window>"u")return()=>{};const t=r=>{e(r??uc())},n=r=>{const o=r.detail;t(o)},a=r=>{r.key&&r.key!==dc||t()};return window.addEventListener(hl,n),window.addEventListener("storage",a),()=>{window.removeEventListener(hl,n),window.removeEventListener("storage",a)}}function W1(e){try{localStorage.setItem(dc,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(hl,{detail:e}))}function O1(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(uc()==="chat")},[]),s.jsx(xn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Is,{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),W1(n?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const U1="Choose a preset or create a fully custom theme. Custom themes control the entire app — backgrounds, text, borders, and chat bubbles.",G1="Choose whether the dashboard opens like a chat app on phones or keeps the full workspace layout.";function q1({themeDescription:e=U1,mobileDescription:t=G1,fontsSlot:n}){const{t:a}=ke("common");return s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:a("settings.appearance.modeLabel")}),s.jsx(D1,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:a("settings.appearance.themeLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:e}),s.jsx(F1,{})]}),n,s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:a("settings.appearance.mobileLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:t}),s.jsx(O1,{})]})]})}const si=new Map,Xd=new Map;function z1(e){if(!e||typeof e!="object")return null;const t=e,n=t.result&&typeof t.result=="object"?t.result:t,a=n.machine;return!a||typeof a!="object"?null:{machine:a,timestamp:typeof n.timestamp=="number"?n.timestamp:void 0}}function K1(e,t,n,a){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:a,platform:n.platform,machine:n}}function Mh(){const{sendCommand:e}=St(),{injectEntries:t,getIdes:n}=Ea();return l.useCallback(async(a,r)=>{if(!a)return;const o=(r==null?void 0:r.minFreshMs)??QS,i=Xd.get(a)||0;if(!(r!=null&&r.force)&&i>0&&Date.now()-i<o)return;const c=si.get(a);if(c)return c;const d=(async()=>{const p=await e(a,"get_machine_runtime_stats"),u=z1(p);if(!u)return;const m=n().find(g=>g.id===a),f=K1(m,a,u.machine,u.timestamp||Date.now());t([f]),Xd.set(a,Date.now())})().finally(()=>{si.delete(a)});return si.set(a,d),d},[n,t,e])}function V1(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 Y1(e,t){const{sendData:n}=St(),{injectEntries:a,getIdes:r}=Ea(),o=Array.from(new Set(e.filter(Boolean))).join("|");l.useEffect(()=>{if(!(t!=null&&t.enabled)||!n)return;const i=o?o.split("|"):[];if(i.length===0)return;const c=i.map(d=>ys.subscribe({sendData:n},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const m=r().find(g=>g.id===d),f=V1(m,d,u);a([f])}));return()=>{c.forEach(d=>d())}},[o,r,a,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,n])}function Q1(e,t){const{sendData:n}=St(),[a,r]=l.useState(null),[o,i]=l.useState(!1);return l.useEffect(()=>{if(!e){r(null),i(!1);return}if(!(t!=null&&t.enabled)||!n){i(!1);return}r(null),i(!0);let c=null;const d=ys.subscribe({sendData:n},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},p=>{c&&(clearTimeout(c),c=null),r(p.diagnostics),i(!1)});return d.initialSendAccepted?c=setTimeout(()=>{i(!1)},ZS):i(!1),()=>{c&&clearTimeout(c),d()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,n]),{diagnostics:a,loading:o,applyDiagnostics:r}}function J1(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Ph(e){const{sendData:t}=St(),[n,a]=l.useState({});return l.useEffect(()=>{const r=J1(e);if(!r||!e.sessionId||!t){a({});return}const o=ys.subscribe({sendData:t},r,{type:"subscribe",topic:"session.modal",key:`daemon:${r}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},i=>{a({status:i.status,modalMessage:i.modalMessage,modalButtons:i.modalButtons}),ea.record({interactionId:i.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:i.status,modalButtonCount:Array.isArray(i.modalButtons)?i.modalButtons.length:0}})});return o.initialSendAccepted||a({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,t]),n}function X1(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function Z1(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 eN(e,t,n){const a=await n(`/api/v1/sessions/${encodeURIComponent(e)}/interactive-prompt/resolve`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(!a.ok){let r=`HTTP ${a.status}`;try{const o=await a.json();typeof(o==null?void 0:o.error)=="string"&&(r=o.error)}catch{}throw new Error(r)}}async function tN({promptSession:e,response:t,useP2PCommand:n,sendCommand:a,fetchImpl:r=fetch}){if(n){const o=await a(e.routeId,"interactive_prompt_response",{targetSessionId:e.sessionId,sessionId:e.sessionId,response:t});if(!X1(o))throw new Error(Z1(o));return}await eN(e.sessionId,t,r)}function Dh(e){const{ides:t,isP2PActive:n,p2pStates:a}=Ss(),{sendCommand:r}=St(),[o,i]=l.useState(null),[c,d]=l.useState(!1),[p,u]=l.useState(null),m=l.useRef(!1),f=l.useMemo(()=>Nx(t,e),[t,e]),g=!!f,k=l.useMemo(()=>f?f.prompt.promptId===o?null:f:null,[o,f]),h=l.useCallback(async x=>{if(!k||m.current)return;m.current=!0;const y=Jp(k.prompt,x);d(!0),u(null);try{const C=(a==null?void 0:a[k.daemonId])==="connected"||n===!0;await tN({promptSession:k,response:y,useP2PCommand:C,sendCommand:r}),i(k.prompt.promptId)}catch(C){throw u(C instanceof Error?C.message:String(C)),C}finally{d(!1),m.current=!1}},[n,a,k,r]),b=l.useCallback(()=>{k&&i(k.prompt.promptId)},[k]),S=l.useCallback(()=>{i(null),u(null)},[]);return{promptSession:k,hasActivePrompt:g,responseError:p,isSubmitting:c,submit:h,cancel:b,reopen:S}}function Ih(e){return e instanceof Error?e.message:String(e||"")}function sN(e){const t=Ih(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 nN(e){const t=Ih(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Lh({conversation:e,mode:t,ides:n,sendDaemonCommand:a,setCliViewModeOverrides:r}){if(!e||!bt(e)||ht(e))return;const o=ca(e);if(o===t)return;const i=e.sessionId;i&&r(c=>({...c,[i]:t}));try{await a(Vs(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Ds(e),mode:t})}catch(c){const d=nN(c);i&&!d&&r(p=>{const u={...p};return o===rN(n,i)?delete u[i]:u[i]=o,u}),sN(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 Zd(e,t){const n=typeof e.sessionId=="string"&&e.sessionId?e.sessionId:typeof e.id=="string"?e.id:"";if(!n||e.transport!=="pty")return e;const a=t[n];return!a||e.mode===a?e:{...e,mode:a}}function aN(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let n=!1;const a=e.map(r=>{const o=Zd(r,t),i=Array.isArray(r.childSessions)?r.childSessions.map(d=>Zd(d,t)):r.childSessions,c=i!==r.childSessions;return o!==r||c?(n=!0,{...o,...c?{childSessions:i}:{}}):r});return n?a:e}function rN(e,t){if(!t)return null;for(const n of e){if(n.sessionId===t&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal";for(const a of n.childSessions||[])if(a.id===t&&a.transport==="pty")return a.mode==="chat"?"chat":"terminal"}return null}function oN({visibleConversations:e,clearedTabs:t,setClearedTabs:n,setActionLogs:a,isConversationMuted:r}){l.useEffect(()=>{gm()},[]);const o=l.useMemo(()=>e.map(i=>({id:i.tabKey,name:nh(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null,target:{providerSessionId:i.providerSessionId,sessionId:i.sessionId,tabKey:i.tabKey,routeId:i.routeId},muted:r?r(i):!1})),[e,r]);return bk(o),l.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{n(d=>{const p=Date.now(),u={};for(const[m,f]of Object.entries(d))p-f<5e3&&(u[m]=f);return Object.keys(u).length===Object.keys(d).length?d:u})},5500);return()=>clearTimeout(c)},[t,n]),l.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;a(d=>{const p=d.filter(u=>u.timestamp>c).slice(-100);return p.length===d.length?d:p})},6e4);return()=>clearInterval(i)},[a]),null}function eu(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(r=>!(r!=null&&r._localId))||e.messages[e.messages.length-1],n=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,a=eu(t==null?void 0:t.receivedAt)||eu(t==null?void 0:t.timestamp)||0;return Math.max(n,a)}function fl(e,t=0){return Nn(e)||e.lastUpdated||t||0}function Rh(e){return Nn(e)||e.lastUpdated||0}function Eh(e,t,n=Rh){const a=n(t)-n(e);if(a!==0)return a;const r=(e.machineName||"").localeCompare(t.machineName||"");if(r!==0)return r;const o=e.displayPrimary.localeCompare(t.displayPrimary);if(o!==0)return o;const i=e.displaySecondary.localeCompare(t.displaySecondary);return i!==0?i:e.tabKey.localeCompare(t.tabKey)}function gl(e){var n;const t=os(e.status,{activeModal:(n=e.modalButtons)!=null&&n.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function iN(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!gl(e)&&!e.title.trim()}function lN(e){return e.length===0?null:[...e].sort((t,n)=>{const a=Number(gl(n))-Number(gl(t));if(a!==0)return a;const r=n.messages.length-t.messages.length;return r!==0?r:Eh(t,n)})[0]||null}function ws(e,t){const n=e.filter(i=>i.routeId===t);if(n.length===0)return null;const a=n.find(i=>i.streamSource==="native")||null,r=n.filter(i=>i.streamSource==="agent-stream"),o=lN(r);return a?o&&iN(a)?o:a:o||n[0]||null}function cN(e){const t=e.filter(r=>r.type!=="adhdev-daemon"),n=new Set;for(const r of t){if(!tl(r))continue;const o=dm(r);o&&n.add(o)}const a=new Map;for(const r of t){const o=K0(r,n),i=a.get(o);if(!i){a.set(o,r);continue}const c=m=>(m.workspace?1:0)+(m.activeChat?1:0)+(m.lastMessagePreview?1:0),d=c(i),p=c(r),u=p>d||p===d&&(r.timestamp||0)>(i.timestamp||0)?r:i;a.set(o,dN(u,u===r?i:r))}return Array.from(a.values())}function dN(e,t){const n=tl(t),a=tl(e);if(!n&&!a)return e;const r=a?n?void 0:t:e,o=a?e:n?t:void 0,i=r&&String(r.daemonId||"").trim()||String(e.ownerDaemonId||"").trim()||String(t.ownerDaemonId||"").trim()||void 0,c=String(e.ownerMachineName||"").trim()||String(t.ownerMachineName||"").trim()||void 0,d=o==null?void 0:o.settings;return{...e,...i&&{ownerDaemonId:i},...c&&!e.ownerMachineName&&{ownerMachineName:c},...d&&!a&&{settings:{...d,...e.settings??{}}}}}function ni(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 uN(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 tu(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],n=t[t.length-1],a=n?uN(ta(n.content)):"";return[e.id||"",e.title||"",e.status||"",t.length,String((n==null?void 0:n.id)||""),String((n==null?void 0:n.index)??""),String((n==null?void 0:n.receivedAt)??(n==null?void 0:n.timestamp)??""),a].join(":")}function pN(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||""),tu(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||""),tu(n.activeChat)].join(":"))].join("|")}function mN(e,t){const n=Date.now();return e.map(a=>{const r=t[a.tabKey];return r&&n-r<5e3?{...a,messages:[],title:""}:a})}function hN(e,t){const n=new Map;for(const a of e){const r=t.get(a.routeId)||a;for(const o of Ma({routeId:a.routeId}))n.set(o,r);for(const o of Ma({providerSessionId:a.providerSessionId,sessionId:a.sessionId}))n.set(o,a.streamSource==="native"?r:a);for(const o of Ma({tabKey:a.tabKey}))n.set(o,a)}return n}function fN(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function gN(e){const t=fN(e);if(!t)return`empty:${e.messages.length}`;if(t.id)return`id:${String(t.id)}`;if(t._localId)return`local:${String(t._localId)}`;const n=String(t.role||""),a=ta(t.content).slice(0,240);return`${e.messages.length}:${n}:${a}`}function bN({ides:e,connectionStates:t,clearedTabs:n}){const a=l.useMemo(()=>cN(e),[e]),r=l.useMemo(()=>em(e),[e]),o=l.useMemo(()=>hh(e),[e]),i=l.useRef([]),c=l.useRef([]),d=l.useRef([]),p=l.useRef(new Map),u=l.useRef(new Map),m=l.useMemo(()=>{const C=new Map,v=[];for(const A of a){const{connectionState:T="new",machineName:I}=fh(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),P=pN(A),M=p.current.get(A.id);if(M&&M.ide===A&&M.sourceSignature===P&&M.connectionState===T&&M.machineName===I){C.set(A.id,M),v.push(...M.conversations);continue}const E=ic(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),D={ide:A,sourceSignature:P,connectionState:T,machineName:I,conversations:E};C.set(A.id,D),v.push(...E)}p.current=C;const w=new Map,j=A=>{const T=gN(A),I=u.current.get(A.tabKey);if(I&&I.signature===T)return w.set(A.tabKey,I),I.timestamp;const P={signature:T,timestamp:Rh(A)||(I==null?void 0:I.timestamp)||0};return w.set(A.tabKey,P),P.timestamp},N=[...v].sort((A,T)=>Eh(A,T,j));return u.current=w,N},[a,t,o]),f=l.useMemo(()=>{const C=mN(m,n);return ni(i.current,C)?i.current:(i.current=C,C)},[m,n]),g=l.useMemo(()=>{const C=new Map,v=Array.from(new Set(f.map(w=>w.routeId)));for(const w of v){const j=ws(f,w);j&&C.set(w,j)}return C},[f]),k=l.useMemo(()=>{const C=new Map;for(const v of f){const w=g.get(v.routeId),j=v.streamSource==="native"&&w?w:v;for(const N of Ma({providerSessionId:v.providerSessionId,sessionId:v.sessionId,tabKey:v.tabKey}))C.set(N,j)}return C},[f,g]),h=l.useMemo(()=>hN(f,g),[f,g]),b=l.useCallback(C=>{if(C)return k.get(C)},[k]),S=l.useCallback(C=>{if(C)return h.get(C)},[h]),x=l.useMemo(()=>{const C=f.filter(v=>!rn(v,r).surfaceHidden);return ni(c.current,C)?c.current:(c.current=C,C)},[f,r]),y=l.useMemo(()=>{const C=x.map(v=>v.tabKey);return ni(d.current,C)?d.current:(d.current=C,C)},[x]);return{chatIdes:a,conversations:f,visibleConversations:x,visibleTabKeys:y,resolveConversationBySessionId:b,resolveConversationByTarget:S}}function xN({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:n,setSearchParams:a}){const r=l.useMemo(()=>{var c;return e||!t?null:((c=n(t))==null?void 0:c.tabKey)??null},[e,n,t]),o=l.useMemo(()=>{var c;return!e||!t?null:((c=n(t))==null?void 0:c.tabKey)??null},[e,n,t]),i=l.useCallback(()=>{t&&a(c=>{const d=new URLSearchParams(c);return d.delete("activeTab"),d},{replace:!0})},[a,t]);return{requestedDesktopTabKey:r,requestedMobileTabKey:o,consumeRequestedActiveTab:i}}function vN({ides:e,sendDaemonCommand:t,setToasts:n,resolveConversationByTarget:a}){l.useEffect(()=>{ft.setIdes(e)},[e]),l.useEffect(()=>{ft.setResolveAction((r,o,i)=>{t(r,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const r=ft.onToast(o=>{n(c=>c.some(p=>p.message===o.message&&o.timestamp-p.timestamp<3e3)?c:[...c.slice(-4),{id:o.id,message:o.message,type:o.type,timestamp:o.timestamp,targetKey:o.targetKey,actions:o.actions}]);const i=o.duration||5e3;setTimeout(()=>n(c=>c.filter(d=>d.id!==o.id)),i)});return()=>{r()}},[n]),l.useEffect(()=>{const r=Zm.on("status_event",o=>{ft.handleRawEvent(o,"ws")});return()=>{r()}},[]),l.useEffect(()=>{var o;const r=i=>{var h;const c=i.data;if((c==null?void 0:c.type)!=="notification_action"||typeof c.action!="string"||!c.action.startsWith("approval_")||!(c.daemonId||c.targetSessionId||c.targetKey))return;const d=c.targetSessionId||c.targetKey||c.daemonId,p=a(d),u=(p==null?void 0:p.routeId)||c.daemonId;if(!u)return;const m=Number(c.buttonIndex),f=c.button||((h=p==null?void 0:p.modalButtons)==null?void 0:h[m])||"Approve",g=String(f).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),k=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(g);t(u,"resolve_action",{action:k?"approve":"reject",button:f,...Number.isFinite(m)&&{buttonIndex:m},...(p==null?void 0:p.sessionId)&&{targetSessionId:p.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(b=>console.error("[SW Action] approval failed:",b))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",r),()=>{var i;return(i=navigator.serviceWorker)==null?void 0:i.removeEventListener("message",r)}},[a,t])}const yN="adhdev_dashboardLayout_v1",wN="adhdev_dashboardDockview_v1",kN="adhdev_dashboardDockviewHiddenRestore_v1",va={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function pc(e,t){try{const n=localStorage.getItem(e);return n?JSON.parse(n):t}catch{return t}}function SN(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function _h(e){return`${yN}:${e}`}function CN(e){const t=_h(e);return pc(t,null)}function jN(e,t){try{const n=t.groupAssignments.length===0&&t.focusedGroup===0&&Object.keys(t.groupActiveTabIds).length===0&&Object.keys(t.groupTabOrders).length===0&&t.groupSizes.length===0,a=_h(e);if(n){localStorage.removeItem(a);return}localStorage.setItem(a,JSON.stringify(t))}catch{}}function Hh(e){return`${wN}:${e}`}function NN(e){const t=Hh(e);return pc(t,null)}function AN(e,t){try{const n=Hh(e);if(!t){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function $h(e){return`${kN}:${e}`}function TN(e){const t=$h(e);return pc(t,{})}function MN(e,t){try{const n=$h(e);if(Object.keys(t).length===0){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function PN(){return{groupAssignments:[...va.groupAssignments],focusedGroup:va.focusedGroup,groupActiveTabIds:{...va.groupActiveTabIds},groupTabOrders:{...va.groupTabOrders},groupSizes:[...va.groupSizes]}}function DN(e,t){return e?e.length===t.length&&e.every((n,a)=>n===t[a]):t.length===0}function IN(){const[e]=l.useState(()=>SN(typeof window<"u"?window.innerWidth:1280)),[t,n]=l.useState(()=>new Map),[a,r]=l.useState(0),[o,i]=l.useState({}),[c,d]=l.useState({}),[p,u]=l.useState([]),[m,f]=l.useState(()=>typeof window<"u"&&window.innerWidth<768),[g,k]=l.useState(!1),h=l.useCallback(()=>{if(g)return;const A=CN(e)??PN();n(new Map(A.groupAssignments)),r(A.focusedGroup),i(A.groupActiveTabIds),d(A.groupTabOrders),u(A.groupSizes),k(!0)},[g,e]);l.useEffect(()=>{g&&jN(e,{groupAssignments:[...t.entries()],focusedGroup:a,groupActiveTabIds:o,groupTabOrders:c,groupSizes:p})},[g,e,t,a,o,c,p]),l.useEffect(()=>{const A=window.matchMedia("(max-width: 767px)"),T=I=>f(I.matches);return A.addEventListener("change",T),()=>A.removeEventListener("change",T)},[]);const b=l.useCallback(A=>{n(A)},[]),S=l.useCallback(A=>{r(A)},[]),x=l.useCallback(A=>{i(A)},[]),y=l.useCallback(A=>{d(A)},[]),C=l.useCallback(A=>{u(A)},[]),v=l.useCallback(A=>{S(A)},[S]),w=l.useCallback((A,T)=>{i(I=>(I[A]??null)===(T??null)?I:{...I,[A]:T})},[]),j=l.useCallback((A,T)=>{d(I=>{const P=I[A];return DN(P,T)?I:{...I,[A]:T}})},[]),N=l.useCallback((A,T)=>{const I=T.get(A)??0;return w(I,A),v(I),I},[v,w]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:b,focusedGroup:a,updateFocusedGroup:S,focusGroup:v,groupActiveTabIds:o,updateGroupActiveTabIds:x,setGroupActiveTab:w,groupTabOrders:c,updateGroupTabOrders:y,setGroupTabOrder:j,groupSizes:p,updateGroupSizes:C,isMobile:m,hasHydratedStoredLayout:g,hydrateStoredLayout:h,focusConversationTab:N}}function LN(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0],a=bo(t);return typeof(n==null?void 0:n.id)=="string"&&a.includes(n.id)}function RN({urlActiveTab:e,conversations:t,resolveConversationBySessionId:n,normalizedGroupAssignments:a,hasHydratedStoredLayout:r,hydrateStoredLayout:o,focusConversationTab:i,setSearchParams:c,historyModalOpen:d,activeConv:p,isRefreshingHistory:u,ides:m,handleRefreshHistory:f}){const g=l.useRef(!1),k=l.useRef(!1),h=l.useRef(null),b=l.useRef(!1);l.useEffect(()=>{if(!e||g.current||t.length===0)return;if(!r){o();return}const S=n(e);S&&(i(S.tabKey,a),g.current=!0,k.current=!0,h.current!=null&&(window.clearTimeout(h.current),h.current=null),c(x=>{const y=new URLSearchParams(x);return y.delete("activeTab"),y},{replace:!0}))},[e,t,n,a,r,o,i,c]),l.useEffect(()=>{if(!(k.current||r)&&t.length!==0){if(!e){o(),k.current=!0;return}if(g.current){k.current=!0;return}if(h.current==null)return h.current=window.setTimeout(()=>{h.current=null,!(k.current||r)&&(o(),k.current=!0)},1500),()=>{h.current!=null&&(window.clearTimeout(h.current),h.current=null)}}},[e,t.length,r,o]),l.useEffect(()=>{if(!d){b.current=!1;return}if(!p||b.current||u)return;const S=m.find(x=>x.id===p.routeId);S&&(!S.chats||S.chats.length===0||LN(S.chats,p))&&(b.current=!0,f())},[d,p,u,m,f])}function ai(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0];if((n==null?void 0:n.active)===!0)return!0;const a=bo(t);return typeof(n==null?void 0:n.id)=="string"&&a.includes(n.id)}function Fh({sendDaemonCommand:e,activeConv:t,chats:n,updateRouteChats:a,setToasts:r,setClearedTabs:o}){const[i,c]=l.useState(!1),[d,p]=l.useState(!1),u=l.useCallback(async k=>{try{await e("standalone","launch_ide",{ideType:k,enableCdp:!0})}catch(h){console.error("Launch failed",h)}},[e]),m=l.useCallback(async(k,h)=>{try{const b=k||(t==null?void 0:t.daemonId)||"",S=await e(b,"switch_chat",{id:h,sessionId:h,...wn(t)}),x=S==null?void 0:S.result;if((S==null?void 0:S.success)===!0||x==="switched"||x==="switched-by-title")return;x===!1||x==="not_found"?qn(r,"⚠️ Session tab not found — try refreshing history"):typeof x=="string"&&x.startsWith("error:")?qn(r,`⚠️ Switch error: ${x}`):qn(r,"⚠️ Session switch failed")}catch(b){console.error("Switch failed",b),qn(r,`❌ Switch failed: ${b.message||"connection error"}`)}},[t,e,r]),f=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const k=kn(t);await e(k,"new_chat",{...wn(t)}),xC(k,t.sessionId,bo(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 b=kn(t),S=async()=>e(b,"list_chats",{forceExpand:!0,...wn(t)});let x=await S(),y=(x==null?void 0:x.chats)||((k=x==null?void 0:x.result)==null?void 0:k.chats);ai(y,t)&&(await new Promise(C=>setTimeout(C,450)),x=await S(),y=(x==null?void 0:x.chats)||((h=x==null?void 0:x.result)==null?void 0:h.chats)),x!=null&&x.success&&Array.isArray(y)&&(a(t.routeId,y),ai(y,t)&&!ai(n,t)&&qn(r,"⚠️ History dialog did not fully open — try once more"))}catch(b){console.error("Refresh history failed",b)}finally{p(!1)}}},[t,n,d,e,a,r]);return{isCreatingChat:i,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:m,handleNewChat:f,handleRefreshHistory:g}}function EN(e,t){if(e.size!==t.size)return!1;for(const[n,a]of e)if(t.get(n)!==a)return!1;return!0}function _N(e,t){return e.length!==t.length?!1:e.every((n,a)=>n===t[a])}function su(e,t){const n=Object.keys(e),a=Object.keys(t);return n.length!==a.length?!1:n.every(r=>t[Number(r)]===e[Number(r)])}function dr(e,t){const n=new Set(t),a=t.length>0?[0]:[];for(const[i,c]of e)!n.has(i)||c<=0||a.includes(c)||a.push(c);a.sort((i,c)=>i-c);const r={};a.forEach((i,c)=>{r[i]=c}),a.length===0&&(r[0]=0);const o=new Map;for(const[i,c]of e){if(!n.has(i)||c<=0)continue;const d=r[c];typeof d=="number"&&d>0&&o.set(i,d)}return{assignments:o,groupCount:Math.max(1,a.length),mapping:r,usedGroups:a}}function nu(e,t){const n={};for(const[a,r]of Object.entries(e)){const o=t[Number(a)];typeof o=="number"&&(n[o]=r)}return n}function HN(e,t,n){if(t.length===0)return 0;if(typeof n[e]=="number")return n[e];const a=[...t].reverse().find(r=>r<e)??t[0];return n[a]??0}function $N(e,t,n){if(t.length<=1)return[];const a=t.map(i=>e[i]).filter(i=>Number.isFinite(i)),r=a.length===t.length?a:Array(n).fill(100/n),o=r.reduce((i,c)=>i+c,0);return o>0?r.map(i=>i/o*100):Array(n).fill(100/n)}function au(e,t){const n={};for(const[a,r]of Object.entries(e)){const o=Number(a);n[o>=t?o+1:o]=r}return n}function ru(e){return Array(e).fill(100/e)}function FN({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:n,updateGroupActiveTabIds:a,updateGroupTabOrders:r,groupSizes:o,updateGroupSizes:i,isMobile:c,visibleConversations:d,visibleTabKeys:p}){const u=l.useRef(null),m=l.useMemo(()=>dr(e,p),[e,p]),f=m.assignments,g=l.useMemo(()=>c?1:m.groupCount,[m.groupCount,c]),k=g>1,h=l.useCallback((v,w)=>{t(j=>{const N=new Map(dr(j,p).assignments);return w===0?N.delete(v):N.set(v,w),N}),a(j=>({...j,[w]:v})),n(w)},[t,p,a,n]),b=l.useCallback(v=>{t(w=>{const j=dr(w,p).assignments,N=new Map;for(const[A,T]of j)T!==v&&(T>v?N.set(A,T-1):N.set(A,T));return N}),i(w=>{if(w.length<=1)return[];const j=[...w];j.splice(v,1);const N=j.reduce((A,T)=>A+T,0);return N>0?j.map(A=>A/N*100):[]}),n(0)},[t,p,i,n]),S=l.useCallback((v,w)=>{w.preventDefault();const j=u.current;if(!j)return;const N=w.clientX,A=j.offsetWidth,T=o.length===g?[...o]:ru(g),I=M=>{const D=(M.clientX-N)/A*100,W=[...T];W[v]=Math.max(15,T[v]+D),W[v+1]=Math.max(15,T[v+1]-D),i(W)},P=()=>{document.removeEventListener("mousemove",I),document.removeEventListener("mouseup",P),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",I),document.addEventListener("mouseup",P)},[o,g,i]),x=l.useCallback((v,w,j)=>{if(g>=4)return;const N=j==="left"?w:w+1;t(A=>{const T=dr(A,p).assignments,I=new Map;for(const P of d){const M=T.get(P.tabKey)??0,E=M>=N?M+1:M;E>0&&I.set(P.tabKey,E)}return N>0&&I.set(v,N),I}),i(A=>{const T=A.length===g?[...A]:ru(g),I=T[w]??100/g,P=Math.max(15,I/2),M=Math.max(15,I/2),E=[...T];E[w]=P,E.splice(N,0,M);const D=E.reduce((W,R)=>W+R,0);return E.map(W=>W/D*100)}),a(A=>{const T=au(A,N);return T[N]=v,T}),r(A=>{const T=au(A,N);return T[N]=[v],T}),n(N)},[g,t,p,d,i,a,r,n]);l.useEffect(()=>{EN(e,f)||t(f)},[e,f,t]),l.useEffect(()=>{const{mapping:v,usedGroups:w}=m;a(j=>{const N=nu(j,v);return su(j,N)?j:N}),r(j=>{const N=nu(j,v);return su(j,N)?j:N}),n(j=>{const N=c?0:HN(j,w,v);return j===N?j:N}),i(j=>{const N=c?[]:$N(j,w,m.groupCount);return _N(j,N)?j:N})},[m,c,a,r,n,i]);const y=l.useMemo(()=>{const v=Array.from({length:g},()=>[]);for(const w of d){const j=f.get(w.tabKey)??0,N=Math.min(j,g-1);v[N].push(w)}return v},[d,f,g]),C=l.useCallback(()=>{t(new Map),n(0)},[t,n]);return{containerRef:u,normalizedGroupAssignments:f,numGroups:g,isSplitMode:k,groupedConvs:y,moveTabToGroup:h,closeGroup:b,handleResizeStart:S,splitTabRelative:x,clearAllSplits:C}}function BN({ides:e,sendDaemonCommand:t}){const n="1.0.57",a=l.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:jo(m,Js(m,n))).sort((m,f)=>Number(Da(f,Js(f,n)))-Number(Da(m,Js(m,n)))),[n,e]),r=l.useMemo(()=>a.some(m=>Da(m,Js(m,n))),[n,a]),o=l.useMemo(()=>a.map(m=>Js(m,n)).find(m=>typeof m=="string"&&m.trim().length>0)||n,[n,a]),[i,c]=l.useState(!1),[d,p]=l.useState({}),u=l.useCallback(async m=>{var k,h;const f=e.find(b=>b.id===m);if(!f)return;p(b=>({...b,[m]:"upgrading"}));const g=No(f);if(!g){p(b=>({...b,[m]:"error"}));return}try{const b=await t(m,"daemon_upgrade",g);(k=b==null?void 0:b.result)!=null&&k.upgraded||(h=b==null?void 0:b.result)!=null&&h.success?p(S=>({...S,[m]:"done"})):p(S=>({...S,[m]:"error"}))}catch{p(b=>({...b,[m]:"error"}))}},[e,t]);return{versionMismatchDaemons:a,hasRequiredVersionDaemons:r,targetVersion:o,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:u}}const Bh=80;function Dr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function WN(e){return{...e,createdAt:Dr(e.createdAt),updatedAt:Dr(e.updatedAt,e.createdAt),lastEventAt:Dr(e.lastEventAt,e.updatedAt||e.createdAt)}}function ON(e){const t=cm(e);return t==="unknown:"?e.id:t}function UN(e){return[e.type,lm(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function GN(e,t=Bh){const n=new Map;for(const a of e){if(a.deletedAt)continue;const r=ON(a),o=n.get(r);if(!o){n.set(r,a);continue}(a.updatedAt>o.updatedAt||a.updatedAt===o.updatedAt&&a.createdAt>o.createdAt)&&n.set(r,a)}return Array.from(n.values()).sort((a,r)=>{const o=r.updatedAt-a.updatedAt;return o!==0?o:r.createdAt-a.createdAt}).slice(0,Math.max(0,t))}function qN(e,t){const n=Date.now(),a=[];for(const r of e){const o=r.sessionId?t.get(r.sessionId):void 0;if(o!=null&&o.surfaceHidden||o!=null&&o.muted)continue;const i=go(r,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const d=Dr(r.lastMessageAt||(o==null?void 0:o.lastUpdated)||r.lastUpdated,n),p=UN({type:c,sessionId:r.sessionId,providerSessionId:r.providerSessionId,tabKey:r.tabKey,lastMessageHash:r.lastMessageHash,lastMessageAt:r.lastMessageAt,lastUpdated:(o==null?void 0:o.lastUpdated)||r.lastUpdated});a.push(WN({id:p,dedupKey:p,type:c,routeId:r.routeId,machineId:r.daemonId||r.routeId,sessionId:r.sessionId,providerSessionId:r.providerSessionId,tabKey:r.tabKey,title:Pm(r),preview:PS(r),createdAt:d,updatedAt:d,lastEventAt:d}))}return GN(a)}function zN(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function KN(e){const{conversations:t,liveSessionInboxState:n,maxItems:a=Bh}=e,r=l.useMemo(()=>qN(t,n).slice(0,Math.max(0,a)),[t,n,a]),o=l.useMemo(()=>zN(r),[r]);return{notifications:r,unreadCount:o}}function VN({notifications:e,sendDaemonCommand:t}){const n=l.useCallback(o=>{const i=e.find(d=>d.id===o),c=Math.max(Date.now(),(i==null?void 0:i.updatedAt)||0);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_session_seen",{sessionId:i.sessionId,seenAt:c}).catch(()=>{})},[e,t]),a=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_notification_unread",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]),r=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"delete_notification",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:n,handleMarkDashboardNotificationUnread:a,handleDeleteDashboardNotification:r}}function mc(...e){const t=new Set,n=[],a=r=>{const o=typeof r=="string"?r.trim():"";if(!o)return;const i=o.toLowerCase();t.has(i)||(t.add(i),n.push(o))};for(const r of e){if(Array.isArray(r)){for(const o of r)a(o);continue}a(r)}return n}function YN(e){const t=e.trim();if(!t)return null;if(t.startsWith("~"))return t;if(/^[A-Za-z]:$/.test(t))return`${t[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(t))return`${t[0].toUpperCase()}:${t.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(t))return`${t[0].toUpperCase()}:\\${t.slice(2).replace(/[\\/]+/g,"\\")}`;const n=t.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(n){const a=n[1].toUpperCase(),r=(n[2]||"").replace(/[\\/]+/g,"\\");return r?`${a}:\\${r}`:`${a}:\\`}return null}function hc(e,t=[]){if(e==="win32"){for(const n of t){if(typeof n!="string")continue;const a=YN(n);if(a)return a}return"C:\\"}for(const n of t){const a=typeof n=="string"?n.trim():"";if(a)return a}return"~"}function QN(e){const t=e.replace(/[\\/]+$/,"");if(!t||t==="/"||/^[A-Za-z]:$/.test(t))return null;const n=t.includes("\\")?"\\":"/",a=t.split(/[\\/]/);return/^[A-Za-z]:$/.test(a[0]||"")?a.length<=2?`${a[0]}\\`:a.slice(0,-1).join("\\"):a.length<=2?n:a.slice(0,-1).join(n)||n}function JN(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function fc(e,t,n){const a=await e(t,"file_list_browse",{path:n}),r=JN(a);if(!(r!=null&&r.success))throw new Error((r==null?void 0:r.error)||(a==null?void 0:a.error)||"Could not browse folder");const o=typeof(r==null?void 0:r.path)=="string"?r.path:n,i=o.includes("\\")?"\\":"/",c=(p,u)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${u}`:p==="/"||p==="\\"?`${i}${u}`:`${p.replace(/[\\/]+$/,"")}${i}${u}`,d=Array.isArray(r==null?void 0:r.files)?r.files.filter(p=>(p==null?void 0:p.type)==="directory"&&typeof(p==null?void 0:p.name)=="string").map(p=>({name:p.name,path:typeof(p==null?void 0:p.path)=="string"&&p.path.trim()?p.path:c(o,p.name)})).sort((p,u)=>p.name.localeCompare(u.name)):[];return{path:o,directories:d}}function ou(e,t){const n=t.meshId||"",a={meshId:n,workspace:t.workspace||"",serverName:t.serverName||"adhdev-mesh",adhdevMcpCommand:t.adhdevMcpCommand||"adhdev-mcp",adhdevMcpArgs:t.adhdevMcpArgs||`mcp --mode ipc --repo-mesh ${n}`};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand|adhdevMcpArgs)\s*\}\}/g,(r,o)=>a[o]||"")}function Wh(e,t={}){const n=e==null?void 0:e.mcpConfig;if((n==null?void 0:n.mode)!=="manual")return null;const r=ou(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"}).trim();return!r.includes(`
|
|
65
|
+
`)&&!r.startsWith("{")?null:{serverName:n.serverName||"adhdev-mesh",configFormat:n.format,configPathCommand:n.configPathCommand,requiresRestart:n.requiresRestart===!0,instructions:n.instructions||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:ou(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"})}}function XN(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.instructions=="string"?t.instructions:"",a=typeof t.template=="string"?t.template:"";return!n&&!a?null:{serverName:typeof t.serverName=="string"?t.serverName:void 0,configFormat:typeof t.configFormat=="string"?t.configFormat:void 0,configPathCommand:typeof t.configPathCommand=="string"?t.configPathCommand:void 0,requiresRestart:t.requiresRestart===!0,instructions:n||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:a}}function Wa(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Oh(e){return xo(e)||e.tabKey||e.routeId||null}function Uh(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"",n=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"",a=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"",r=e.conversations.find(o=>{if(a&&o.routeId!==a)return!1;const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey].map(c=>typeof c=="string"?c.trim():"").filter(Boolean);return!!(t&&i.includes(t)||n&&i.includes(n)||a&&o.routeId===a)});if(r!=null&&r.tabKey)return r.tabKey;if(a){const o=ws(e.conversations,a)||e.conversations.find(i=>i.routeId===a);if(o!=null&&o.tabKey)return o.tabKey}return t||n||a||null}function Xs(e){return String(e||"").trim()}function Gh(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Zr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function ZN(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function eA(e,t){const n=Xs(e.providerSessionId),a=Xs(e.targetSessionId),r=t.find(o=>{const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(Xs).filter(Boolean);return!!(n&&i.includes(n)||a&&i.includes(a))});return r?r.tabKey:a||n||null}function tA(e,t,n){if(t.event!=="agent:generating_completed")return null;const a=Gh(t.daemonId);if(a&&a!==e.machineId)return null;const r=Xs(t.providerType);if(e.providerType&&r!==e.providerType)return null;const o=Xs(e.resumeSessionId),i=Xs(e.launchedSessionId),c=Xs(t.providerSessionId),d=Xs(t.targetSessionId);if(o&&o!==c&&o!==d||i&&i!==c&&i!==d)return null;const p=Zr(e.workspacePath);if(p){const u=Zr(t.workspaceName);if(u&&!ZN(u,p))return null}return eA(t,n)}function iu(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function sA({ides:e,conversations:t,onOpenSession:n}){const[a,r]=l.useState(null),o=l.useRef(null),i=l.useCallback(()=>{o.current=null,r(null)},[]),c=l.useCallback(d=>{o.current=d,r(d)},[]);return l.useEffect(()=>{if(!a)return;const d=Zr(a.workspacePath),p=e.find(m=>{var b,S,x,y;if(!m||m.type==="adhdev-daemon"||Gh(m.daemonId||m.id)!==a.machineId||(Fa(m)?"cli":Xn(m)?"acp":"ide")!==a.kind)return!1;const k=String(m.agentType||m.type||"");if(a.providerType&&k!==a.providerType)return!1;if(a.resumeSessionId)return String(m.providerSessionId||"")===a.resumeSessionId;if(a.launchedSessionId){const C=String(a.launchedSessionId||"");return[m.providerSessionId,m.sessionId,m.instanceId,m.id].map(w=>String(w||"")).filter(Boolean).includes(C)}if(d){const C=Zr(m.workspace||m.runtimeWorkspaceLabel);return C?C===d:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((y=(x=(S=(b=m.activeChat)==null?void 0:b.messages)==null?void 0:S.at)==null?void 0:x.call(S,-1))==null?void 0:y.timestamp)||0)>=a.startedAt-5e3});if(!p)return;const u=Uh({entrySessionId:p.sessionId,entryInstanceId:p.instanceId,entryRouteId:p.id,conversations:t});u&&(i(),n(u))},[i,t,e,n,a]),l.useEffect(()=>ft.onStatusEvent(d=>{const p=o.current;if(!p)return;const u=tA(p,d,t);u&&(i(),n(u))}),[i,t,n]),l.useEffect(()=>{if(!a)return;const d=window.setTimeout(()=>{r(p=>!p||p.startedAt!==a.startedAt?p:(o.current=null,null))},45e3);return()=>window.clearTimeout(d)},[a]),{trackPendingLaunch:c}}function nA(e,t){var a,r,o,i;const n={cliType:e};return(a=t==null?void 0:t.workspacePath)!=null&&a.trim()?n.dir=t.workspacePath.trim():t!=null&&t.workspaceId?n.workspaceId=t.workspaceId:t!=null&&t.useHome&&(n.useHome=!0),(r=t==null?void 0:t.resumeSessionId)!=null&&r.trim()&&(n.resumeSessionId=t.resumeSessionId.trim()),Array.isArray(t==null?void 0:t.cliArgs)&&t.cliArgs.length>0&&(n.cliArgs=t.cliArgs),(o=t==null?void 0:t.initialModel)!=null&&o.trim()&&(n.initialModel=t.initialModel.trim()),(i=t==null?void 0:t.initialThinkingLevel)!=null&&i.trim()&&(n.initialThinkingLevel=t.initialThinkingLevel.trim()),t!=null&&t.settings&&(n.settings=t.settings),n}function aA(e,t,n){var i,c,d,p;const a={meshId:e.trim()};t.trim()&&(a.cliType=t.trim());const r=(i=n==null?void 0:n.initialModel)==null?void 0:i.trim(),o=(c=n==null?void 0:n.initialThinkingLevel)==null?void 0:c.trim();return r&&(a.initialModel=r),o&&(a.initialThinkingLevel=o),(d=n==null?void 0:n.settings)!=null&&d.autoApproveMode?a.autoApproveMode=n.settings.autoApproveMode:typeof((p=n==null?void 0:n.settings)==null?void 0:p.autoApprove)=="boolean"&&(a.autoApprove=n.settings.autoApprove),a}function rA({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:n,activeConv:a,ides:r,setCliViewModeOverrides:o}){const i=Ql(),{launchCli:c}=fo(),d=l.useCallback(async(b,S)=>fc(e,b,S),[e]),p=l.useCallback(async(b,S)=>{if(!S.trim())return{ok:!1,error:"Choose a workspace path first."};try{const x=await e(b,"workspace_add",{path:S.trim()});return x!=null&&x.success?{ok:!0}:{ok:!1,error:(x==null?void 0:x.error)||"Could not save workspace"}}catch(x){return{ok:!1,error:x instanceof Error?x.message:"Could not save workspace"}}},[e]),u=l.useCallback(async(b,S,x)=>{var y;try{const C={ideType:S,enableCdp:!0};(y=x==null?void 0:x.workspacePath)!=null&&y.trim()&&(C.workspace=x.workspacePath.trim());const v=await e(b,"launch_ide",C);return!(v!=null&&v.success)&&(v==null?void 0:v.success)!==void 0?{ok:!1,error:(v==null?void 0:v.error)||"Could not launch IDE"}:(t({machineId:b,kind:"ide",providerType:S,workspacePath:(x==null?void 0:x.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(b,S,x,y)=>{const C=Date.now();try{const v=nA(x,y),w=await c(b,v),j=(w==null?void 0:w.result)||w,N=(j==null?void 0:j.sessionId)||(j==null?void 0:j.id);return w!=null&&w.success&&N?(t({machineId:b,kind:S,providerType:x,workspacePath:(y==null?void 0:y.workspacePath)||null,resumeSessionId:(y==null?void 0:y.resumeSessionId)||null,launchedSessionId:N,startedAt:C}),{ok:!0}):w!=null&&w.success?(t({machineId:b,kind:S,providerType:x,workspacePath:(y==null?void 0:y.workspacePath)||null,resumeSessionId:(y==null?void 0:y.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:(w==null?void 0:w.error)||(j==null?void 0:j.error)||`Could not launch ${S.toUpperCase()} session`,code:(w==null?void 0:w.code)||(j==null?void 0:j.code)||void 0}}catch(v){return iu(v)?(t({machineId:b,kind:S,providerType:x,workspacePath:(y==null?void 0:y.workspacePath)||null,resumeSessionId:(y==null?void 0:y.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:v instanceof Error?v.message:`Could not launch ${S.toUpperCase()} session`}}},[c,e,t]),f=l.useCallback(async b=>{var S;if(i!=null&&i.listMeshes)return i.listMeshes(b);if(!b)return[];try{const x=await e(b,"list_meshes",{}),y=(x==null?void 0:x.result)??x;if((y==null?void 0:y.success)===!1)throw new Error((y==null?void 0:y.error)||"Could not load meshes");return(Array.isArray(y==null?void 0:y.meshes)?y.meshes:Array.isArray((S=y==null?void 0:y.result)==null?void 0:S.meshes)?y.result.meshes:[]).map(v=>{var w;return{id:String((v==null?void 0:v.id)||""),name:String((v==null?void 0:v.name)||(v==null?void 0:v.id)||"Untitled mesh"),repoIdentity:(v==null?void 0:v.repoIdentity)||(v==null?void 0:v.repo_identity)||null,workspace:Array.isArray(v==null?void 0:v.nodes)&&v.nodes.length>0?String(((w=v.nodes[0])==null?void 0:w.workspace)||""):null,nodesCount:Array.isArray(v==null?void 0:v.nodes)?v.nodes.length:void 0,status:(v==null?void 0:v.status)||null}}).filter(v=>v.id)}catch(x){throw console.error("List meshes failed",x),x}},[i,e]),g=l.useCallback(async(b,S,x,y)=>{if(!S.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(b,S,x,y);const C=Date.now();try{const v=aA(S,x,y),w=await e(b,"launch_mesh_coordinator",v),j=(w==null?void 0:w.result)??w;if((j==null?void 0:j.success)===!1||(w==null?void 0:w.success)===!1){const A=String((j==null?void 0:j.code)||(w==null?void 0:w.code)||""),T=XN((j==null?void 0:j.meshCoordinatorSetup)||(j==null?void 0:j.manualSetup)||(w==null?void 0:w.meshCoordinatorSetup)||(w==null?void 0:w.manualSetup));return{ok:!1,error:(j==null?void 0:j.error)||(w==null?void 0:w.error)||"Could not launch mesh coordinator",code:A||void 0,manualSetup:T}}const N=(j==null?void 0:j.sessionId)||(j==null?void 0:j.id);return N?n(N):t({machineId:b,kind:"cli",providerType:(j==null?void 0:j.cliType)||x.trim()||void 0,workspacePath:(j==null?void 0:j.workspace)||null,startedAt:C}),{ok:!0}}catch(v){return iu(v)?(t({machineId:b,kind:"cli",providerType:x.trim()||void 0,startedAt:C}),{ok:!0}):{ok:!1,error:v instanceof Error?v.message:"Could not launch mesh coordinator"}}},[i,n,e,t]),k=l.useCallback(async(b,S)=>{if(!b||!S)return[];try{const x=await e(b,"list_saved_sessions",{providerType:S,kind:"cli",limit:30}),y=(x==null?void 0:x.result)??x;return Array.isArray(y==null?void 0:y.sessions)?y.sessions:[]}catch(x){return console.error("List saved sessions failed",x),[]}},[e]),h=l.useCallback(async b=>{await Lh({conversation:a,mode:b,ides:r,sendDaemonCommand:e,setCliViewModeOverrides:o})},[a,r,e,o]);return{handleBrowseMachineDirectory:d,handleSaveMachineWorkspace:p,handleLaunchMachineIde:u,handleLaunchMachineProvider:m,handleListMachineMeshes:f,handleLaunchMeshCoordinator:g,handleListMachineSavedSessions:k,setActiveCliViewMode:h}}function oA(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 iA(e,t,n=Date.now()){return!e||!oA(t)?null:{tabKey:e,nonce:n}}function lA({isMobile:e,conversations:t,visibleConversations:n,groupActiveTabIds:a,focusedGroup:r,groupedConvs:o,setSearchParams:i}){const[c,d]=l.useState(null),[p,u]=l.useState(null),m=l.useMemo(()=>{var b,S;if(!e){if(c){const x=t.find(y=>y.tabKey===c);if(x)return x}return n[0]}const h=a[r];if(h){const x=t.find(y=>y.tabKey===h);if(x)return x}return((b=o[r])==null?void 0:b[0])||((S=o[0])==null?void 0:S[0])},[t,c,r,a,o,e,n]),f=l.useCallback(h=>{d(h)},[]),g=l.useCallback(h=>{d(h.tabKey),i(b=>{const S=new URLSearchParams(b),x=IS(h);return x?S.set("activeTab",x):S.delete("activeTab"),S},{replace:!0})},[i]),k=l.useCallback((h,b)=>{const S=iA(h,b);S&&u(S)},[]);return{activeConv:m,openDesktopConversation:g,requestScrollToBottom:k,scrollToBottomRequest:p,setDesktopActiveTab:f}}function cA(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 dA(e){const t=String(e.liveState.completionMarker||""),n=String(e.liveState.seenCompletionMarker||""),a=String(e.liveState.inboxBucket||"idle"),r=!!e.liveState.unread,o=[e.tabKey,e.historySessionId||"",t,n,a,r?"1":"0"].join(":");return{shouldMarkSeen:!!(a==="task_complete"&&r&&(!t||t!==n)),autoReadKey:o,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function uA({activeConv:e,isMobile:t,liveSessionInboxState:n,sendDaemonCommand:a}){const r=l.useRef(null),o=l.useRef(null),i=l.useRef(null),c=l.useRef(null),d=l.useRef(null);l.useEffect(()=>{const p=()=>{i.current&&(clearTimeout(i.current),i.current=null),c.current&&(clearTimeout(c.current),c.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),o.current=null};if(t){p(),r.current=null;return}if(!(e!=null&&e.sessionId)){p(),r.current=null;return}const u=rn(e,n),m=dA({tabKey:e.tabKey,historySessionId:xo(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:Nn(e),liveState:u}),f=m.autoReadKey,g=cA({autoReadKey:f,shouldMarkSeen:m.shouldMarkSeen,completedKey:r.current,pendingKey:o.current});if(!m.shouldMarkSeen){g.shouldCancelPending&&p(),r.current=f;return}if(!g.shouldSchedule)return;g.shouldCancelPending&&p();const k=()=>{if(document.visibilityState!=="visible"||r.current===f)return;r.current=f,o.current=null,i.current=null,c.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const b=m.readAt;a(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:b,completionMarker:m.completionMarker}).catch(()=>{})};if(o.current=g.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(k,1500);const b=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};d.current=b,document.addEventListener("visibilitychange",b);return}const h=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(k,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=h,document.addEventListener("visibilitychange",h)},[e,t,n,a]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current),c.current&&clearTimeout(c.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function ri(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 pA({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:n,ides:a,sendDaemonCommand:r,updateRouteChats:o,setToasts:i,setClearedTabs:c,setSearchParams:d}){var B;const{launchCli:p}=fo(),[u,m]=l.useState(!1),[f,g]=l.useState([]),[k,h]=l.useState(()=>qt()),[b,S]=l.useState(!1),[x,y]=l.useState(null),C=l.useRef(null),v=l.useMemo(()=>n||t||e,[e,n,t]),w=!!v&&bt(v)&&!ht(v),j=l.useMemo(()=>{if(!v||!w)return null;const _=v.daemonId||v.routeId||"",H=Ds(v),L=ri(v);return`${_}:${H}:${v.providerSessionId||""}:${L}`},[v,w]),N=l.useMemo(()=>!v||!w?"":ri(v),[v,w]),{isCreatingChat:A,isRefreshingHistory:T,handleSwitchSession:I,handleNewChat:P,handleRefreshHistory:M}=Fh({sendDaemonCommand:r,activeConv:v,chats:(B=a.find(_=>_.id===(v==null?void 0:v.routeId)))==null?void 0:B.chats,updateRouteChats:o,setToasts:i,setClearedTabs:c}),E=l.useCallback(()=>{m(!0)},[]),D=l.useCallback(()=>{m(!1)},[]),W=l.useCallback(async()=>{if(!(!v||!w||b)){S(!0);try{const _=v.daemonId||v.routeId,H=Ds(v),L=ri(v),F=await r(_,"list_saved_sessions",{agentType:H,providerType:H,kind:"cli",limit:50,...v.providerSessionId?{providerSessionId:v.providerSessionId}:{},...L?{workspace:L}:{}}),$=(F==null?void 0:F.result)??F;g(Array.isArray($==null?void 0:$.sessions)?$.sessions:[])}catch(_){console.error("Refresh saved sessions failed",_),g([])}finally{S(!1)}}},[v,b,w,r]);l.useEffect(()=>{if(!u){C.current=null;return}if(!w){C.current=null,g([]),S(!1);return}!j||b||C.current!==j&&(C.current=j,W())},[W,u,b,w,j]);const R=l.useCallback(async _=>{if(!v||!w||!_.providerSessionId||!_.workspace)return;const H=v.daemonId||v.routeId,L=Ds(v);try{y(_.providerSessionId);const F=await p(H,{cliType:L,dir:_.workspace,resumeSessionId:_.providerSessionId,initialModel:hm(_.summaryMetadata,"model",{preferShortValue:!0})||void 0}),$=(F==null?void 0:F.result)??F,K=typeof($==null?void 0:$.sessionId)=="string"?$.sessionId:typeof($==null?void 0:$.id)=="string"?$.id:"";K&&d(z=>{const ne=new URLSearchParams(z);return ne.set("activeTab",K),ne},{replace:!0}),D()}catch(F){console.error("Resume saved session failed",F)}finally{y(null)}},[D,v,w,r,d]);return{historyModalOpen:u,openHistoryModal:E,closeHistoryModal:D,historyTargetConv:v,isSavedSessionHistoryTarget:w,isHistoryCreatingChat:A,isHistoryRefreshingHistory:T,handleHistorySwitchSession:I,handleHistoryNewChat:P,handleHistoryRefresh:M,savedHistorySessions:f,savedHistoryFilters:k,setSavedHistoryFilters:h,missingWorkspaceResumePath:N,isSavedHistoryLoading:b,resumingSavedHistorySessionId:x,handleRefreshSavedHistory:W,handleResumeSavedHistorySession:R}}function mA({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c}){const[d,p]=l.useState(null),[u,m]=l.useState(null),f=l.useMemo(()=>{if(e||!a)return null;const S=c(a);return S&&!bt(S)&&!ht(S)?S:null},[e,a,c]),g=l.useMemo(()=>{const S=d==null?void 0:d.routeId;if(!S)return null;const x=d!=null&&d.tabKey?o.find(y=>y.tabKey===d.tabKey):r?o.find(y=>y.tabKey===r):null;return(x==null?void 0:x.routeId)===S?x:ws(o,S)},[o,d,r]),k=l.useMemo(()=>{if(g)return i.find(S=>S.id===g.routeId)},[i,g]);l.useEffect(()=>{f&&(p({routeId:f.routeId,tabKey:xd(f)}),m(f),n({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,n,f]);const h=l.useCallback(S=>{S&&(p({routeId:S.routeId,tabKey:xd(S)}),m(S))},[]),b=l.useCallback(()=>{p(null),m(null)},[]);return{remoteDialogConv:g,remoteDialogIdeEntry:k,remoteDialogActiveConv:u,setRemoteDialogActiveConv:m,openRemoteDialog:h,closeRemoteDialog:b}}function hA({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c,activeConv:d,sendDaemonCommand:p}){const{remoteDialogConv:u,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:g,openRemoteDialog:k,closeRemoteDialog:h}=mA({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c}),[b,S]=l.useState(!1),[x,y]=l.useState(null),C=l.useCallback(async j=>{const N=j||d;!N||!bt(N)&&!ht(N)||(y(N),S(!0))},[d]),v=l.useCallback(()=>{S(!1),y(null)},[]),w=l.useCallback(async j=>{const N=x||d;if(!N||!bt(N)&&!ht(N)){v();return}S(!1);try{const A=Ds(N),T=N.routeId||N.daemonId||"";await p(T,"stop_cli",{cliType:A,targetSessionId:N.sessionId,mode:j,...ko(N)})}catch(A){console.error("Stop CLI failed:",A)}finally{y(null)}},[d,v,x,p]);return{remoteDialogConv:u,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:g,openRemoteDialog:k,closeRemoteDialog:h,cliStopDialogOpen:b,cliStopTargetConv:x,requestCliStop:C,cancelCliStop:v,confirmCliStop:w}}function oi(e,t=!0){return(e??!0)&&t}const gc=l.memo(function({activeConv:t,clearToken:n,isCliTerminal:a,ideEntry:r,terminalRef:o,handleModalButton:i,handleRelaunch:c,handleSendChat:d,handleForceSendChat:p,isSendingChat:u,sendFeedbackMessage:m=null,handleFocusAgent:f,isFocusingAgent:g,actionLogs:k,userName:h,scrollToBottomRequestNonce:b,isInputActive:S=!0,isVisible:x=!0}){const y=a,C=!a,v=oi(x,y),w=oi(x,C),j=oi(x),N=Ph(t),A=N.status||N.modalMessage||N.modalButtons?{...t,...N.status?{status:N.status}:{},...N.modalMessage!==void 0?{modalMessage:N.modalMessage}:{},...N.modalButtons!==void 0?{modalButtons:N.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(tm,{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(Ls,{size:14})}),s.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),s.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:c,children:"Relaunch with CDP"})]})}):null,A.transport==="pty"?s.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[s.jsx("div",{"aria-hidden":!a,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:y?"visible":"hidden",pointerEvents:y?"auto":"none"},children:s.jsx(mj,{activeConv:A,clearToken:n,terminalRef:o,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:m,isVisible:v,isInputActive:S&&v})}),s.jsx("div",{"aria-hidden":a,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:C?"visible":"hidden",pointerEvents:C?"auto":"none"},children:s.jsx(ll,{activeConv:A,ideEntry:r,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:k,userName:h,scrollToBottomRequestNonce:b,isInputActive:S&&w,isVisible:w})})]}):s.jsx(ll,{activeConv:A,ideEntry:r,handleSendChat:d,handleForceSendChat:p,isSendingChat:u,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:k,userName:h,scrollToBottomRequestNonce:b,isInputActive:S&&j,isVisible:j})]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.handleModalButton===t.handleModalButton&&e.handleRelaunch===t.handleRelaunch&&e.handleSendChat===t.handleSendChat&&e.handleForceSendChat===t.handleForceSendChat&&e.isSendingChat===t.isSendingChat&&e.sendFeedbackMessage===t.sendFeedbackMessage&&e.handleFocusAgent===t.handleFocusAgent&&e.isFocusingAgent===t.isFocusingAgent&&e.actionLogs===t.actionLogs&&e.userName===t.userName&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isInputActive===t.isInputActive&&e.isVisible===t.isVisible);function fA({conversation:e,className:t="",onOpenNativeConversation:n,onOpenMachine:a,interactive:r=!0,meshOnly:o=!1}){var C,v,w;const{t:i}=ke("common"),c=ia(),d=Vs(e),p=o?null:Mm(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=sa(e),k=DS(e),h=(C=e.settings)==null?void 0:C.meshNodeFor,b=e.meshQueueStats,S=((v=e.coordinator)==null?void 0:v.meshId)||((w=e.settings)==null?void 0:w.meshCoordinatorFor),x=l.useCallback(()=>{if(a){a();return}d&&c("/dashboard",{state:{openMachineId:d}})},[d,c,a]),y=l.useCallback(()=>{if(n){n();return}const j=Oh(e);j&&c(Wa(j))},[e,c,n]);return!u&&!m&&!f&&!p&&!h&&!b?null:s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[u&&(r?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:y,title:k,children:[s.jsx(us,{size:12}),s.jsx("span",{children:k})]}):s.jsxs("span",{className:"conversation-meta-chip",title:k,children:[s.jsx(us,{size:12}),s.jsx("span",{children:k})]})),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(_a,{size:12}),s.jsx("span",{children:g})]}),f&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(_a,{size:12}),s.jsx("span",{children:g})]}),p&&(r?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:x,title:p,children:[s.jsx(nn,{size:12}),s.jsx("span",{children:p})]}):s.jsxs("span",{className:"conversation-meta-chip",title:p,children:[s.jsx(nn,{size:12}),s.jsx("span",{children:p})]})),h&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(nn,{size:12}),s.jsx("span",{children:i("dashboard.metaChips.meshNode")})]}),S&&b&&s.jsxs("span",{className:`conversation-meta-chip ${b.pending>0?"is-active":""}`,style:b.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${b.pending} pending, ${b.assigned} assigned, ${b.completed} completed, ${b.failed} failed`,children:[s.jsx(xb,{size:12}),s.jsxs("span",{children:[b.pending," Pending"]})]})]})}function gA({selectedConversation:e,isAcp:t,isStandalone:n,selectedIdeEntry:a,actionLogs:r,userName:o,isSendingChat:i,sendFeedbackMessage:c=null,isFocusingAgent:d,onBack:p,onOpenNativeConversation:u,onOpenMachine:m,onOpenHistory:f,onOpenRemote:g,onOpenMeshGraph:k,onStopCli:h,cliViewMode:b,onSetCliViewMode:S,handleSendChat:x,handleForceSendChat:y,handleFocusAgent:C,handleModalButton:v,handleRelaunch:w}){var P,M;const j=l.useRef(null),N=bt(e)&&!t,A=N&&b==="terminal",T=!!e.daemonId&&!!((P=e.coordinator)!=null&&P.meshId||(M=e.settings)!=null&&M.meshCoordinatorFor),I=n?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`flex items-center justify-between gap-3 ${I} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:p,type:"button","aria-label":"Back",children:s.jsx(_l,{size:18})}),s.jsxs("div",{className:"min-w-0 flex-1 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:kt(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(fA,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>m(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[N&&b&&s.jsx(oh,{mode:b,onChange:S,compact:!0}),N&&h&&s.jsx("button",{onClick:()=>{h(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(Dt,{size:14})}),T&&k&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>k(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(cs,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",children:s.jsx($l,{size:14})}),!t&&!N&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",children:s.jsx(us,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(gc,{activeConv:e,clearToken:0,isCliTerminal:A,ideEntry:a,terminalRef:j,handleModalButton:v,handleRelaunch:w,handleSendChat:x,handleForceSendChat:y,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:C,isFocusingAgent:d,actionLogs:r,userName:o})})]})}const ii={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 bA(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function qh(){const[e,t]=l.useState("unix"),[n,a]=l.useState("powershell"),[r,o]=l.useState(!1),i=e==="unix"?"unix":n;l.useEffect(()=>{t(bA())},[]);const c=l.useCallback(()=>{navigator.clipboard.writeText(ii[i].cmd).catch(()=>{}),o(!0),setTimeout(()=>o(!1),2e3)},[i]);return s.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("unix"),children:"macOS / Linux"}),s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("windows"),children:"Windows"})]}),e==="windows"&&s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${n==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>a("powershell"),children:"PowerShell"}),s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${n==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>a("cmd"),children:">_ CMD"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:c,title:"Click to copy",children:[s.jsx("span",{className:"text-text-muted select-none",children:ii[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:ii[i].cmd}),s.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:r?s.jsx(co,{size:12}):s.jsx(Hl,{size:12})})]}),s.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",s.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function zh({section:e,onSectionChange:t}){const{t:n}=ke("common"),a=[{key:"machines",label:n("nav.machines"),icon:us},{key:"chats",label:n("nav.chats"),icon:Is}];return s.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:s.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:a.map(({key:r,label:o,icon:i})=>{const c=e===r;return s.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${c?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>t(r),type:"button","aria-pressed":c,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${c?"text-accent-primary":"bg-transparent text-current"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:s.jsx(i,{size:15})}),s.jsx("span",{children:o})]},r)})})})}function ur({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 hn({icon:e,title:t,subtitle:n,children:a}){return s.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[s.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),s.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:t}),s.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:n}),a]})}function xA({conversation:e,onCancel:t,onConfirm:n}){const{t:a}=ke(),r=kt(e);return s.jsx(Vt,{children:s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:t,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"mobile-hide-confirm-title",className:"card fade-in mobile-compact-dialog relative w-full sm:w-[min(92vw,420px)] md:w-[92%] md:max-w-[420px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-bg-primary",children:[s.jsx("h3",{id:"mobile-hide-confirm-title",className:"m-0 text-base md:text-lg font-extrabold",children:a("mobileInbox.hideTitle",{title:r})}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:a("mobileInbox.hideDescription")})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[s.jsx("button",{onClick:n,className:"btn btn-primary w-full justify-center min-h-[42px]",children:a("mobileInbox.hide")}),s.jsx("button",{onClick:t,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:a("common.cancel")})]})]})]})})}function pr({item:e,type:t,getAvatarText:n,onOpenConversation:a,onRequestHideConversation:r,onRequestStopCli:o,onOpenMeshGraph:i,onCollectChatDebugBundle:c,isMuted:d,onToggleMute:p}){const{t:u}=ke(),m=t==="needs_attention"||t==="task_complete",f=t==="working",g=t==="earlier",k=t==="task_complete",{isReconnecting:h,isConnecting:b}=En(e.conversation),S=kt(e.conversation),x=na(e.conversation),y=sh(e.conversation,{requiresAction:t==="needs_attention"}),C=m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":f?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":g?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",v=m?"bg-accent-primary shadow-glow":f?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":g?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",w=g?"text-text-secondary":"text-text-primary",j=g?"text-text-muted":"text-text-secondary",N=g?"text-text-secondary opacity-80":"text-text-muted",A=g?"text-text-muted opacity-80":"text-text-muted",T=!f&&!k,I=eh(e.conversation),P="text-[color:var(--status-warning)]",M=E=>{if(!c)return;E.preventDefault(),E.stopPropagation();const D=c==null?void 0:c(e.conversation);Promise.resolve(D).catch(W=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",W)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${C}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[m||f?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${v}`,style:m?{color:"var(--accent-on-primary)"}:void 0,children:n(S)}),I&&i&&s.jsx("button",{type:"button",className:"mobile-inbox-mesh-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:E=>{E.preventDefault(),E.stopPropagation(),i(e.conversation)},"aria-label":u("mobileInbox.openMeshGraphFor",{title:S}),title:u("mobileInbox.openLiveMeshGraph"),children:s.jsx(cs,{size:13})})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>a(e.conversation),onContextMenu:M,type:"button",children:[s.jsx("div",{className:"flex items-center gap-2 pr-[124px]",children:s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${w}`,children:S})}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${j}`,children:[s.jsx("span",{className:"truncate",children:x}),s.jsx(qr,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),h?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${P} animate-pulse`,children:u("mobileInbox.reconnectingItem")})]}):b?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")})]}):y==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:P,children:u("mobileInbox.actionNeeded")})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${N}`,children:e.preview})]}),s.jsxs("div",{className:"mobile-inbox-corner-actions absolute top-3 right-3 flex items-center gap-1.5",children:[T&&s.jsx("span",{className:`mr-0.5 text-[11px] font-medium shrink-0 ${A}`,children:Zp(e.timestamp)}),k&&s.jsx("span",{className:"rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:u("mobileInbox.done")}),p&&s.jsx("button",{type:"button",className:`mobile-inbox-mute-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border transition-colors ${d?"border-amber-500/60 bg-amber-500 text-white hover:bg-amber-600":"border-border-subtle bg-bg-primary/70 text-text-muted hover:border-border-default hover:text-text-primary"}`,onClick:E=>{E.preventDefault(),E.stopPropagation(),p()},"aria-label":d?u("mobileInbox.unmute",{title:S}):u("mobileInbox.mute",{title:S}),title:u(d?"mobileInbox.mutedTitle":"mobileInbox.muteNotifications"),children:d?s.jsx(Ip,{size:13}):s.jsx(la,{size:13})}),r&&s.jsx("button",{type:"button",className:"mobile-inbox-hide-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:E=>{E.preventDefault(),E.stopPropagation(),r()},"aria-label":u("mobileInbox.hideConversationAria",{title:S}),title:u("mobileInbox.hideConversationTitle"),children:s.jsx(mo,{size:13})}),o&&s.jsx("button",{type:"button",className:"mobile-inbox-stop-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-status-error/30 bg-bg-primary/70 text-status-error transition-colors hover:border-status-error/60 hover:bg-status-error/10",onClick:E=>{E.preventDefault(),E.stopPropagation(),o()},"aria-label":u("mobileInbox.stopSessionAria",{title:S}),title:u("mobileInbox.stopSessionTitle"),children:s.jsx(Dt,{size:13})})]})]})},e.conversation.tabKey)}function lu({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 vA({section:e,attentionItems:t,unreadItems:n,workingItems:a,completedItems:r,hiddenConversations:o,machineCards:i,getAvatarText:c,actionLogs:d,sendDaemonCommand:p,onOpenConversation:u,onShowAllHidden:m,onHideConversation:f,onOpenMeshGraph:g,onStopCli:k,onOpenNewSession:h,onOpenMachine:b,onOpenSettings:S,onSectionChange:x,wsStatus:y="connected",initialDataLoaded:C=!0,conversationsLoaded:v,isStandalone:w=!1,onCollectChatDebugBundle:j,isConversationMuted:N,onToggleMuteConversation:A}){const{t:T}=ke(),[I,P]=l.useState(null),M=y==="disconnected"||y==="reconnecting"||y==="offline"||y==="auth_failed",E=!M&&!C,D=!M&&!(v??C),W=i.length>0,R=t.length>0||n.length>0||a.length>0||r.length>0,B=T(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),_=w?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",H=w?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",L=l.useCallback(async K=>{const z=kn(K);if(!z)return;const ne=Array.isArray(K.messages)?K.messages:[],ie=_m({activeConv:K,visibleMessages:ne,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:ne.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),Ce=await p(z,"get_chat_debug_bundle",{...wn(K),delivery:"daemon_file",frontendSnapshot:ie}),me=Pa(Ce),O=Fm(me),Y=await $m(O);Y==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),ft.showToast(Hm(me,{locatorCopyStatus:Y}),Y==="failed"?"warning":"success")},[d,p]),F=j||L,$=l.useCallback(()=>{I&&(f==null||f(I),P(null))},[I,f]);return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${_}`,children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:B}),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(la,{size:13}),s.jsx("span",{children:t.length+n.length})]}),s.jsx("button",{onClick:S,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:s.jsx(Ua,{size:18})})]})]})}),s.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${H}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:M?s.jsx(hn,{icon:s.jsx(ls,{size:32}),title:T(y==="offline"?"mobileInbox.networkOffline":y==="auth_failed"?"mobileInbox.sessionExpired":"mobileInbox.reconnecting"),subtitle:T(y==="offline"?"mobileInbox.waitingForNetwork":y==="auth_failed"?"mobileInbox.pleaseLogInAgain":"mobileInbox.restoringConnection")}):E?s.jsx(hn,{icon:s.jsx(ls,{size:32}),title:T("mobileInbox.loading"),subtitle:T("mobileInbox.loadingSubtitle")}):i.length===0?s.jsx(hn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:T(w?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:T(w?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!w&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(qh,{})})}):s.jsx(Bn,{children:i.map((K,z)=>s.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${z>0?"border-t border-border-subtle/70":""}`,onClick:()=>b(K.id),type:"button",children:[s.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:c(K.label)}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:K.label}),s.jsxs("span",{className:"flex items-center gap-2 text-[11px] font-medium text-text-muted shrink-0",children:[s.jsx(lu,{count:K.generatingCount,label:T("mobileInbox.generatingCount",{count:K.generatingCount})}),K.unread>0?s.jsx("span",{className:"text-accent-primary",children:T("mobileInbox.newCount",{count:K.unread})}):K.total>0?T("mobileInbox.chatCount",{count:K.total}):T("mobileInbox.idle")]})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:K.subtitle}),K.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[T("mobileInbox.chatCount",{count:K.total}),K.unread>0?T("mobileInbox.unreadSuffix",{count:K.unread}):"",K.generatingCount>0?T("mobileInbox.collapsedGeneratingSuffix",{count:K.generatingCount}):""]}):K.generatingCount>0?s.jsx("div",{className:"text-[13px] text-accent-primary mt-0.5 font-medium",children:T("mobileInbox.generatingCount",{count:K.generatingCount})}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:T("mobileInbox.noActiveChats")})]})]},K.id))})}),e==="chats"&&t.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(ur,{title:T("mobileInbox.needsAttention"),className:"mb-0"}),s.jsx(Bn,{children:t.map((K,z)=>s.jsx("div",{className:z>0?"border-t border-border-subtle/70":"",children:s.jsx(pr,{item:K,type:"needs_attention",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>P(K.conversation):void 0,onRequestStopCli:k?()=>k(K.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:F,isMuted:N==null?void 0:N(K.conversation),onToggleMute:A?()=>A(K.conversation):void 0})},K.conversation.tabKey))})]}),e==="chats"&&n.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(ur,{title:T("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),s.jsx(Bn,{children:n.map((K,z)=>s.jsx("div",{className:z>0?"border-t border-border-subtle/70":"",children:s.jsx(pr,{item:K,type:"task_complete",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>P(K.conversation):void 0,onRequestStopCli:k?()=>k(K.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:F,isMuted:N==null?void 0:N(K.conversation),onToggleMute:A?()=>A(K.conversation):void 0})},K.conversation.tabKey))})]}),e==="chats"&&a.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(ur,{title:T("mobileInbox.workingNow"),className:"mb-0 mt-2"}),s.jsx(Bn,{children:a.map((K,z)=>s.jsx("div",{className:z>0?"border-t border-border-subtle/70":"",children:s.jsx(pr,{item:K,type:"working",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>P(K.conversation):void 0,onRequestStopCli:k?()=>k(K.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:F,isMuted:N==null?void 0:N(K.conversation),onToggleMute:A?()=>A(K.conversation):void 0})},K.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[r.length>0&&s.jsx(ur,{title:T("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),r.length>0?s.jsx(Bn,{children:r.map((K,z)=>s.jsx("div",{className:z>0?"border-t border-border-subtle/70":"",children:s.jsx(pr,{item:K,type:"earlier",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>P(K.conversation):void 0,onRequestStopCli:k?()=>k(K.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:F,isMuted:N==null?void 0:N(K.conversation),onToggleMute:A?()=>A(K.conversation):void 0})},K.conversation.tabKey))}):R?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:T("mobileInbox.allCaughtUp")}):M?s.jsx(hn,{icon:s.jsx(ls,{size:28}),title:T("mobileInbox.connecting"),subtitle:T("mobileInbox.connectingSubtitle")}):D?s.jsx(hn,{icon:s.jsx(ls,{size:28}),title:T("mobileInbox.loading"),subtitle:T("mobileInbox.loadingSubtitle")}):W?s.jsx(hn,{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(Is,{size:20})}),title:T("mobileInbox.noConversations"),subtitle:T("paneGroup.newSessionDescription"),children:h&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:h,"aria-label":T("paneGroup.newSession"),title:T("paneGroup.newSession"),children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s.jsx("span",{children:T("paneGroup.newSession")})]})}):s.jsx(hn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:T("mobileInbox.noMachinesConnected"),subtitle:T("mobileInbox.noMachinesSubtitle")})]}),e==="chats"&&o.length>0&&(()=>{const K=Dx(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:T("mobileInbox.hiddenTabs")}),s.jsx(lu,{count:K,label:T("mobileInbox.generatingCount",{count:K})})]}),s.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[T("mobileInbox.collapsedCount",{count:o.length}),K>0?T("mobileInbox.collapsedGeneratingSuffix",{count:K}):""]})]}),s.jsx("button",{type:"button",className:"shrink-0 rounded-full border border-border-subtle bg-bg-primary/70 px-3 py-1.5 text-[12px] font-semibold text-accent-primary hover:border-border-default",onClick:m,children:T("mobileInbox.restoreAll")})]})})})})()]}),e==="chats"&&h&&R&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:h,"aria-label":T("paneGroup.newSession"),title:T("paneGroup.newSession"),children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),I&&s.jsx(xA,{conversation:I,onCancel:()=>P(null),onConfirm:$}),s.jsx(zh,{section:e,onSectionChange:x})]})}function yA(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 Kh(e){const t=[e.workspace||"Workspace unknown"],n=Mn(e.summaryMetadata);n&&t.push(n),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const a=yA(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:a?`Updated ${a}`:"",preview:(e.preview||"").trim()}}function bc({title:e,description:t,currentPath:n,directories:a,busy:r=!1,error:o="",confirmLabel:i="Use this folder",onClose:c,onNavigate:d,onConfirm:p}){const[u,m]=l.useState(n),{t:f}=ke("common");l.useEffect(()=>{m(n)},[n]);const g=QN(n),k=u.trim();return s.jsx(Vt,{children:s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:s.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:c,"aria-label":"Close folder browser",children:s.jsx(Dt,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!g||r||d(g)},disabled:!g||r,children:[s.jsx(_l,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:f("machine.workspaceBrowse.currentFolder")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:u,onChange:h=>m(h.target.value),onKeyDown:h=>{h.key!=="Enter"||!k||r||(h.preventDefault(),d(k))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!k||r||d(k)},disabled:!k||r,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:r?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):o?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:o}):a.length===0?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):s.jsx("div",{className:"p-3",children:a.map(h=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>d(h.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Tn,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:h.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:h.path})]})]},h.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:c,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>p(k||n),disabled:!k&&!n||r,children:i})]})]})})})}function Ao({title:e,description:t,details:n,workspaceOptions:a,selectedWorkspaceKey:r,onWorkspaceChange:o,confirmLabel:i,busyLabel:c,busy:d=!1,showArgsInput:p,argsValue:u,onArgsChange:m,showModelInput:f,modelValue:g,onModelChange:k,historyProviderNode:h,onConfirm:b,onCancel:S}){const{t:x}=ke("common"),y=i??x("machine.launchConfirm.launch"),C=c??x("machine.launchConfirm.launching"),v=a==null?void 0:a.find(j=>j.key===r),w=s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:S,"aria-label":x("machine.launchConfirm.closeAria"),children:s.jsx(Dt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[a&&a.length>0&&o&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:x("machine.launchConfirm.workspace")}),s.jsx("select",{value:r||"",onChange:j=>o(j.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:d,children:a.map(j=>s.jsx("option",{value:j.key,children:j.label},j.key))}),(v==null?void 0:v.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:v.description})]}),h,n.map(j=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:j.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:j.value})]},`${j.label}:${j.value}`)),f&&k&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:x("machine.launchConfirm.languageModel")}),s.jsx("input",{type:"text",value:g||"",onChange:j=>k(j.target.value),placeholder:x("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:x("machine.launchConfirm.cliArgs")}),s.jsx("input",{type:"text",value:u||"",onChange:j=>m(j.target.value),placeholder:x("machine.launchConfirm.cliArgsPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:S,disabled:d,children:x("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:b,disabled:d,children:[s.jsx(Dp,{size:14}),d?C:y]})]})]})});return typeof document>"u"?w:zs.createPortal(w,document.body)}function cu(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function Vh(e){const{machine:t,currentWorkspacePath:n,currentWorkspaceId:a,includeHome:r=!0,homeLabel:o="Home directory",homeDescription:i="Launch without a workspace"}=e,c=[];r&&c.push({key:"__home__",label:o,description:i,workspaceId:null,workspacePath:null});for(const u of t.workspaces||[])c.push({key:`saved:${u.id}`,label:`${u.id===t.defaultWorkspaceId?"⭐ ":""}${cu(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:cu(d),description:d,workspaceId:null,workspacePath:d}),a){const u=`saved:${a}`;if(c.some(m=>m.key===u))return{options:c,selectedKey:u}}return p?{options:c,selectedKey:`saved:${p.id}`}:d?{options:c,selectedKey:`custom:${d}`}:{options:c,selectedKey:"__home__"}}function wA(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function kA(e){return[wA(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function SA(e){return e.lastLaunchedAt?za(e.lastLaunchedAt):""}function Yh(e){return{metaText:kA(e),updatedLabel:SA(e)}}function li(e,t,n){return e?"ide":t>0?"cli":n>0?"acp":null}function CA({selectedMachineEntry:e,cliProviders:t,acpProviders:n,machineAction:a,onBrowseDirectory:r,onListSavedSessions:o}){var Ie,We,Xe,et;const i=da(),[c,d]=l.useState(!1),p=(((Ie=e.detectedIdes)==null?void 0:Ie.length)||0)>0,u=l.useMemo(()=>(e.workspaces||[]).map(J=>({id:J.id,path:J.path,label:J.label})),[e]),m=e.defaultWorkspaceId||null,[f,g]=l.useState(m||((We=u[0])==null?void 0:We.id)||""),[k,h]=l.useState(""),[b,S]=l.useState(""),[x,y]=l.useState([]),[C,v]=l.useState(!1),[w,j]=l.useState(""),[N,A]=l.useState(!1),[T,I]=l.useState(li(p,t.length,n.length)),P=l.useRef(null),[M,E]=l.useState(null),D=l.useRef("__home__"),[W,R]=l.useState("__home__"),[B,_]=l.useState(""),[H,L]=l.useState(""),[F,$]=l.useState(""),[K,z]=l.useState([]),[ne,ie]=l.useState(()=>qt().textQuery),[Ce,me]=l.useState(()=>qt().workspaceQuery),[O,Y]=l.useState(()=>qt().modelQuery),[X,Q]=l.useState(()=>qt().resumableOnly),[ve,he]=l.useState(()=>qt().sortMode),[Z,fe]=l.useState(!1),[V,q]=l.useState(!1),ee=l.useRef(null),pe=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const le=f==="__custom__"?k.trim():((Xe=u.find(J=>J.id===f))==null?void 0:Xe.path)||"",se=f==="__custom__"&&!!le&&a.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(a.message),te=f!=="__custom__"&&((et=u.find(J=>J.id===f))==null?void 0:et.path)||"",ue=l.useMemo(()=>(e.recentLaunches||[]).map(J=>J.workspace),[e]),ye=l.useCallback(async J=>{v(!0),j("");try{const Le=await r(J);S(Le.path),h(Le.path),y(Le.directories)}catch(Le){j(Le instanceof Error?Le.message:"Could not load folder")}finally{v(!1)}},[r]),Me=l.useCallback(()=>{var Le;g("__custom__"),A(!0);const J=hc(e.platform,mc(k.trim(),te,ue,e.defaultWorkspacePath,(Le=u.find($e=>$e.id===m))==null?void 0:Le.path,u.map($e=>$e.path)));ye(J)},[k,m,ye,ue,te,e.platform,u]),re=l.useCallback(J=>{if(J!=null&&J.workspaceId){g(J.workspaceId),h("");return}if(J!=null&&J.workspacePath){g("__custom__"),h(J.workspacePath);return}g(""),h("")},[]),ce=l.useCallback(J=>{if(g(J),J==="__custom__"){Me();return}h("")},[Me]),Ae=l.useCallback(J=>{g("__custom__"),h(J)},[]),be=l.useCallback((J,Le)=>{P.current=Le,D.current=J.selectedWorkspaceKey||"__home__",R(J.selectedWorkspaceKey||"__home__"),_(J.initialArgs||""),L(J.initialModel||""),$(""),z([]);const $e=J.providerType?`${e.id}:${J.providerType}`:null;if(jj(pe.current,$e)){const at=qt();ie(at.textQuery),me(at.workspaceQuery),Y(at.modelQuery),Q(at.resumableOnly),he(at.sortMode)}pe.current=$e,E(J),J.providerType&&o&&(fe(!0),o(J.providerType).then(at=>z(at||[])).catch(at=>console.warn("Failed to load saved sessions",at)).finally(()=>fe(!1)))},[o,e.id]),we=l.useMemo(()=>ih(K,{textQuery:ne,workspaceQuery:Ce,modelQuery:O,resumableOnly:X,sortMode:ve}),[O,X,K,ve,ne,Ce]);l.useEffect(()=>{F&&(we.some(J=>J.providerSessionId===F)||$(""))},[we,F]);const _e=l.useCallback(()=>{P.current&&(q(!0),P.current().finally(()=>{P.current=null,q(!1),E(null)}))},[]),U=l.useCallback(()=>{P.current=null,E(null)},[]),Ne=l.useCallback(J=>{D.current=J,R(J)},[]);return l.useEffect(()=>{var J;ee.current!==e.id&&(ee.current=e.id,g(m||((J=u[0])==null?void 0:J.id)||"__custom__"),h(""),S(""),y([]),j(""),A(!1),ie(qt().textQuery),me(qt().workspaceQuery),Y(qt().modelQuery),Q(qt().resumableOnly),he(qt().sortMode),pe.current=null,I(li(p,t.length,n.length)))},[n.length,t.length,m,p,e.id,u]),l.useEffect(()=>{var J;f!=="__custom__"&&(f&&u.some(Le=>Le.id===f)||g(m||((J=u[0])==null?void 0:J.id)||"__custom__"))},[m,f,u]),l.useEffect(()=>{T==="ide"&&p||T==="cli"&&t.length>0||T==="acp"&&n.length>0||I(li(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:b,browseDirectories:x,browseBusy:C,browseError:w,browseDialogOpen:N,activeLauncherKind:T,launchConfirm:M,launchConfirmWorkspaceKeyRef:D,launchConfirmWorkspaceKey:W,launchConfirmArgs:B,launchConfirmModel:H,launchConfirmResumeId:F,launchConfirmSavedSessions:K,launchConfirmTextFilter:ne,launchConfirmWorkspaceFilter:Ce,launchConfirmModelFilter:O,launchConfirmResumableOnly:X,launchConfirmSortMode:ve,filteredLaunchConfirmSavedSessions:we,launchConfirmSessionsLoading:Z,launchConfirmBusy:V,resolvedWorkspacePath:le,canCreateMissingWorkspace:se,openBrowseDialog:Me,loadBrowsePath:ye,handleWorkspaceChoiceChange:ce,chooseCustomWorkspacePath:Ae,setCustomWorkspacePath:h,setBrowseDialogOpen:A,setActiveLauncherKind:I,openLaunchConfirm:be,handleConfirmLaunch:_e,closeLaunchConfirm:U,setWorkspaceSelectionFromOption:re,setLaunchConfirmWorkspaceKeyAndSync:Ne,setLaunchConfirmArgs:_,setLaunchConfirmModel:L,setLaunchConfirmResumeId:$,setLaunchConfirmTextFilter:ie,setLaunchConfirmWorkspaceFilter:me,setLaunchConfirmModelFilter:Y,setLaunchConfirmResumableOnly:Q,setLaunchConfirmSortMode:he}}function jA({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:n,cliProviders:a,acpProviders:r,selectedMachineNeedsUpgrade:o,appVersion:i,machineAction:c,isStandalone:d,section:p,showBottomNav:u,onBack:m,onSectionChange:f,onOpenConversation:g,onOpenRecent:k,onOpenMachineDetails:h,onMachineUpgrade:b,onLaunchDetectedIde:S,onAddWorkspace:x,onBrowseDirectory:y,onLaunchWorkspaceProvider:C,onListSavedSessions:v}){const{t:w}=ke("common"),j=R=>R==="ide"?"IDE":R==="cli"?"CLI":"ACP",N=n.slice(0,4),A=t.slice(0,3),T=CA({selectedMachineEntry:e,cliProviders:a,acpProviders:r,machineAction:c,onBrowseDirectory:y,onListSavedSessions:v}),I=l.useMemo(()=>N.map(R=>{const{metaText:B,updatedLabel:_}=Yh(R);return{key:`recent-launch:${R.id}`,primary:R.label,secondary:B,updatedLabel:_,onClick:()=>{const{options:H,selectedKey:L}=Vh({machine:{workspaces:T.workspaceRows,defaultWorkspaceId:T.defaultWorkspaceId},currentWorkspacePath:R.workspace,homeLabel:w("newSession.homeDirectory"),homeDescription:w("newSession.launchWithoutWorkspace")});T.openLaunchConfirm({title:R.kind==="ide"?zr(w,"restart-ide",R.label):R.providerSessionId?ch(w,R.label):zr(w,"start-fresh",R.label),description:R.kind==="ide"?Kr(w,"restart-ide"):R.providerSessionId?dh(w):Kr(w,"start-fresh"),confirmLabel:R.kind==="ide"?Vr(w,"restart-ide"):R.providerSessionId?cl(w,!0):Vr(w,"start-fresh"),busyLabel:R.kind==="ide"?Yr(w,"restart-ide"):R.providerSessionId?lh(w,!0):Yr(w,"start-fresh"),workspaceOptions:H,selectedWorkspaceKey:L,details:[{label:"Mode",value:j(R.kind)},...R.providerType?[{label:"Provider",value:R.providerType}]:[]]},async()=>{const F=H.find($=>$.key===T.launchConfirmWorkspaceKeyRef.current);T.setWorkspaceSelectionFromOption(F),await k({...R,workspace:(F==null?void 0:F.workspacePath)??null})})}}}),[T,k,N,w]),P=l.useMemo(()=>A.map(R=>({key:`recent-chat:${R.conversation.tabKey}`,primary:kt(R.conversation),secondary:QC(R.conversation,{timestampLabel:R.timestamp?Zp(R.timestamp):null}),unread:R.unread,onClick:()=>g(R.conversation)})),[g,A]),M=T.showAllRecent?I:I.slice(0,4),E=I.length>0,D=P.length>0,W=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 ${W} 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(_l,{size:18})}),s.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:ds(e,{fallbackId:e.id})}),s.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[D&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:P.map(R=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${R.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:R.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:R.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:R.secondary})]},R.key))})]}),E&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:M.map(R=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:R.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:R.primary}),R.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:R.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:R.secondary})]},R.key))}),I.length>4&&s.jsx("div",{className:"flex justify-center px-4 pt-2",children:s.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>T.setShowAllRecent(R=>!R),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:b,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(bc,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:T.browseCurrentPath,directories:T.browseDirectories,busy:T.browseBusy,error:T.browseError,confirmLabel:"Use this folder",onClose:()=>T.setBrowseDialogOpen(!1),onNavigate:R=>{T.loadBrowsePath(R)},onConfirm:R=>{T.chooseCustomWorkspacePath(R),T.setBrowseDialogOpen(!1)}}),T.launchConfirm&&s.jsx(Ao,{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?cl(w,!!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:oc(w)}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:T.launchConfirmTextFilter,onChange:R=>T.setLaunchConfirmTextFilter(R.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:T.launchConfirmWorkspaceFilter,onChange:R=>T.setLaunchConfirmWorkspaceFilter(R.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:T.launchConfirmModelFilter,onChange:R=>T.setLaunchConfirmModelFilter(R.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsxs("select",{value:T.launchConfirmSortMode,onChange:R=>T.setLaunchConfirmSortMode(R.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:T.launchConfirmResumableOnly,onChange:R=>T.setLaunchConfirmResumableOnly(R.target.checked),disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:T.launchConfirmResumeId,onChange:R=>T.setLaunchConfirmResumeId(R.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:Tj(w)}),T.filteredLaunchConfirmSavedSessions.map(R=>s.jsxs("option",{value:R.providerSessionId,disabled:!R.canResume,children:[R.title||R.providerSessionId," ",R.canResume?"":"(workspace missing)"]},R.providerSessionId))]}),!T.launchConfirmSessionsLoading&&T.launchConfirmSavedSessions.length>0&&T.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),T.launchConfirmResumeId&&(()=>{const R=T.filteredLaunchConfirmSavedSessions.find(_=>_.providerSessionId===T.launchConfirmResumeId);if(!R)return null;const B=Kh(R);return s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:B.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:B.providerSessionId}),s.jsx("div",{className:"mt-1",children:B.metaLine}),B.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:B.updatedLabel}),B.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:B.preview})]})})()]}),onConfirm:T.handleConfirmLaunch,onCancel:T.closeLaunchConfirm}),u&&s.jsx(zh,{section:p,onSectionChange:f})]})}const du=8e3;function NA(e){const t=e&&typeof e=="object"&&"result"in e?e.result:e,n=t&&typeof t=="object",a=n&&t.success===!1,r=n&&t.mirrorStale===!0;return!a&&!r?{confirmed:!0}:{confirmed:!1,reason:a&&typeof t.error=="string"?t.error:r?"the coordinator did not confirm the change":"command was rejected"}}function Qh(e,t,n){const a=l.useRef(new Map),[,r]=l.useState(0),o=l.useCallback(()=>r(g=>g+1),[]);l.useEffect(()=>{const g=a.current;if(g.size===0)return;const k=Date.now();let h=!1;for(const[b,S]of g){const x=e.get(b),y=S.muted===void 0||(x?x.muted===S.muted:!1),C=S.hidden===void 0||(x?x.surfaceHidden===S.hidden:!1),v=k-S.at>du;(y&&C||v)&&(g.delete(b),h=!0)}h&&o()},[e,o]),l.useEffect(()=>{if(a.current.size===0)return;const g=setInterval(()=>{const k=a.current,h=Date.now();let b=!1;for(const[S,x]of k)h-x.at>du&&(k.delete(S),b=!0);b&&o(),k.size===0&&clearInterval(g)},1e3);return()=>clearInterval(g)});const i=l.useCallback((g,k)=>{const h=a.current.get(g);a.current.set(g,{...h,...k,at:Date.now()}),o()},[o]),c=l.useCallback(g=>{const k=g.sessionId,h=k?a.current.get(k):void 0;return(h==null?void 0:h.muted)!==void 0?h.muted:rn(g,e).muted??!1},[e]),d=l.useCallback(g=>{const k=g.sessionId,h=k?a.current.get(k):void 0;return(h==null?void 0:h.hidden)!==void 0?h.hidden:rn(g,e).surfaceHidden??!1},[e]),p=l.useCallback((g,k)=>{const h=Vs(g),b=g.sessionId;!h||!b||(i(b,k),t(h,"set_conversation_prefs",{sessionId:b,...k,...ko(g)}).then(S=>{const x=NA(S);x.confirmed||(console.warn("[conversation-prefs] set_conversation_prefs not confirmed",x.reason),a.current.delete(b),o(),n==null||n(`Couldn't update conversation — ${x.reason}`))}).catch(S=>{console.warn("[conversation-prefs] set_conversation_prefs failed",S),a.current.delete(b),o();const x=S instanceof Error?S.message:String(S??"the daemon is unreachable");n==null||n(`Couldn't update conversation — ${x}`)}))},[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 Ir(e){return[...e].sort((t,n)=>{const a=n.timestamp-t.timestamp;return a!==0?a:t.conversation.tabKey.localeCompare(n.conversation.tabKey)})}function AA(e,t=[]){const n=new Map(e.map(r=>[r.conversation.tabKey,r])),a=t.map(r=>n.get(r)).filter(r=>!!r);return a.length===e.length?a:Ir(e)}function TA(e,t=[]){const n=e.filter(i=>i.requiresAction),a=e.filter(i=>i.unread&&!i.requiresAction),r=e.filter(i=>!i.unread&&!i.requiresAction&&i.isWorking),o=e.filter(i=>!i.unread&&!i.requiresAction&&!i.isWorking);return{attentionItems:Ir(n),unreadItems:Ir(a),workingItems:AA(r,t),completedItems:Ir(o)}}function To(e,t){if(!t)return!1;const n=e.filter(a=>a.type==="adhdev-daemon"&&Jh(a)==="Connected");return n.length===0?!0:n.every(a=>a._sessionListAuthoritative===!0)}function Jh(e){var a,r,o;const t=((a=e.p2p)==null?void 0:a.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":!(!!((r=e.p2p)!=null&&r.available)||!!((o=e.p2p)!=null&&o.state))&&e.status&&e.status!=="offline"?"Connected":"Offline"}function MA(e,t){if(!e)return[];const n=e.recentLaunches||[];return n.length>0?n.map(a=>({id:a.id,label:a.title||a.providerName||a.providerType,kind:a.kind,providerType:a.providerType,providerSessionId:a.providerSessionId,subtitle:Mn(a.summaryMetadata)||a.workspace||void 0,workspace:a.workspace,summaryMetadata:a.summaryMetadata})):t.filter(a=>a.type!=="adhdev-daemon"&&a.daemonId===e.id).map(a=>{var i;const r=Fa(a)?"cli":Xn(a)?"acp":"ide",o=Mn(a.summaryMetadata);return{id:`${r}:${a.type}:${a.workspace||""}`,label:((i=a.activeChat)==null?void 0:i.title)||(Fa(a)?a.cliName||a.type:Xn(a)&&a.cliName||a.type),kind:r,providerType:a.type,providerSessionId:a.providerSessionId,subtitle:Xn(a)?o||a.workspace||void 0:a.workspace||void 0,workspace:a.workspace||void 0,timestamp:a.lastMessageAt||0}}).sort((a,r)=>r.timestamp-a.timestamp).map(({timestamp:a,...r})=>r)}function PA(e,t,n=[]){const a=new Map;for(const o of t){const i=Vs(o.conversation),c=a.get(i);c?c.push(o):a.set(i,[o])}const r=new Map;for(const o of n){const i=Vs(o),c=r.get(i);c?c.push(o):r.set(i,[o])}return e.map(o=>{const i=a.get(o.id)||[],c=r.get(o.id)||[],d=[...i].sort((h,b)=>b.timestamp-h.timestamp)[0]||null,p=(d==null?void 0:d.conversation)||null,u=sl(o),m=i.filter(h=>h.unread||h.requiresAction).length,f=i.filter(h=>Ha(h.conversation)).length+c.filter(Ha).length,g=Jh(o),k=[o.platform||"machine",g].filter(Boolean);return{id:o.id,label:ds(o,{fallbackId:o.id}),subtitle:k.join(" · "),unread:m,total:i.length,generatingCount:f,latestConversation:p,latestTimestamp:(d==null?void 0:d.timestamp)||0,fallbackActivityAt:u,preview:p?JC(p,Vm(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 DA(e){return e==="chat"}function mr(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 IA({conversations:e,machineEntries:t,items:n,selectedConversation:a,selectedTabKey:r,screen:o,liveSessionInboxState:i,sendDaemonCommand:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,setSelectedTabKey:k,setScreen:h,setSelectedMachineId:b,setSection:S,setMachineBackTarget:x,resetMachineAction:y}){const C=l.useRef(null),v=l.useCallback(w=>{if(!(w!=null&&w.sessionId))return;const j=rn(w,i),N=Math.max(Date.now(),Nn(w),j.lastUpdated||0);mr("mark_read:start",{tabKey:w.tabKey,sessionId:w.sessionId,displayPrimary:kt(w),inboxBucket:j.inboxBucket,unread:j.unread,lastSeenAt:j.lastSeenAt,lastUpdated:j.lastUpdated,activityAt:Nn(w),readAt:N}),c(Vs(w)||w.routeId,"mark_session_seen",{sessionId:w.sessionId,providerSessionId:w.providerSessionId,seenAt:N,completionMarker:j.completionMarker}).then(A=>{mr("mark_read:result",{tabKey:w.tabKey,sessionId:w.sessionId,result:A})}).catch(A=>{mr("mark_read:error",{tabKey:w.tabKey,sessionId:w.sessionId,error:A instanceof Error?A.message:String(A)})})},[i,c]);return l.useEffect(()=>{var j;if(!a){DA(o)&&h("inbox"),k(((j=e[0])==null?void 0:j.tabKey)||null),C.current=null;return}if(o!=="chat"){C.current=null;return}const w=`${a.tabKey}:${a.sessionId||""}`;C.current!==w&&(C.current=w,v(a))},[e,v,o,a,h,k]),l.useEffect(()=>{if(!d)return;const w=e.find(j=>j.tabKey===d);w&&(k(w.tabKey),h("chat"),p==null||p())},[e,p,d,h,k]),l.useEffect(()=>{if(!u)return;const w=t.find(j=>j.id===u);w&&(b(w.id),y(),S("machines"),x("inbox"),h("machine"),m==null||m())},[t,m,u,y,x,h,S,b]),l.useEffect(()=>{f&&(S(f),h("inbox"),g==null||g())},[g,f,h,S]),l.useEffect(()=>{const w=n.filter(j=>j.inboxBucket==="task_complete"||j.unread);w.length!==0&&mr("inbox_state",{screen:o,selectedTabKey:r,items:w.map(j=>{const N=rn(j.conversation,i);return{liveState:N,tabKey:j.conversation.tabKey,sessionId:j.conversation.sessionId,displayPrimary:kt(j.conversation),serverBucket:N.inboxBucket,computedBucket:j.inboxBucket,serverUnread:N.unread,computedUnread:j.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:Nn(j.conversation)}})})},[n,i,o,r]),{markConversationRead:v}}function LA(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function uu(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function RA(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function EA({sendDaemonCommand:e,navigate:t,ides:n,conversations:a}){const{launchCli:r}=fo(),[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(y,C,v)=>{var w;try{i("loading"),d(`Launching ${C}…`);const j={ideType:C,enableCdp:!0};(w=v==null?void 0:v.workspacePath)!=null&&w.trim()&&(j.workspace=v.workspacePath.trim()),await e(y,"launch_ide",j),i("done"),d(`${C} launch requested`)}catch(j){i("error"),d(j instanceof Error?j.message:"Launch IDE failed"),console.error("Launch IDE failed",j)}},[e]),g=l.useCallback(async(y,C,v)=>{if(C.trim())try{i("loading"),d(v!=null&&v.createIfMissing?"Creating folder…":"Saving workspace…");const w=await e(y,"workspace_add",{path:C.trim(),createIfMissing:(v==null?void 0:v.createIfMissing)===!0});if(w!=null&&w.success){i("done"),d(v!=null&&v.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),d((w==null?void 0:w.error)||"Could not save workspace")}catch(w){i("error"),d(w instanceof Error?w.message:"Could not save workspace")}},[e]),k=l.useCallback(async y=>{i("loading"),d("Starting daemon upgrade…");const C=n.find(w=>w.id===y||w.daemonId===y),v=await j1(e,y,C);i(v.state),d(v.message)},[n,e]),h=l.useCallback(async(y,C,v,w)=>{var A,T,I;const j=Date.now(),N={machineId:y,kind:C,providerType:v,workspaceId:(w==null?void 0:w.workspaceId)||null,workspacePath:(w==null?void 0:w.workspacePath)||null,resumeSessionId:(w==null?void 0:w.resumeSessionId)||null,startedAt:j};try{i("loading"),d(`Launching ${v}…`),u(N);const P={cliType:v};(A=w==null?void 0:w.workspacePath)!=null&&A.trim()?P.dir=w.workspacePath.trim():w!=null&&w.workspaceId?P.workspaceId=w.workspaceId:w!=null&&w.useHome&&(P.useHome=!0),w!=null&&w.resumeSessionId&&(P.resumeSessionId=w.resumeSessionId),(T=w==null?void 0:w.args)!=null&&T.trim()&&(P.cliArgs=w.args.trim().split(/\s+/).filter(Boolean)),(I=w==null?void 0:w.model)!=null&&I.trim()&&(P.initialModel=w.model.trim());const M=await r(y,P),E=(M==null?void 0:M.result)||M,D=(E==null?void 0:E.sessionId)||(E==null?void 0:E.id);if(M!=null&&M.success&&D){u(null),i("done"),d(`${v} launched`),t(Wa(D));return}if(M!=null&&M.success){i("loading"),d(`${v} launch requested — waiting for session…`);return}u(null),i("error"),d((M==null?void 0:M.error)||(E==null?void 0:E.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(P){if(RA(P)){i("loading"),d(`${v} launch requested — waiting for session…`);return}u(null),i("error"),d(P instanceof Error?P.message:`Could not launch ${C.toUpperCase()} workspace`)}},[t,e]),b=l.useCallback(async(y,C)=>{try{const v=await e(y,"list_saved_sessions",{providerType:C,kind:"cli",limit:30}),w=(v==null?void 0:v.result)??v;return Array.isArray(w==null?void 0:w.sessions)?w.sessions:[]}catch(v){return console.error("Failed to list saved sessions on mobile:",v),[]}},[e]),S=l.useCallback(async(y,C)=>fc(e,y,C),[e]);l.useEffect(()=>{if(!p)return;const y=uu(p.workspacePath),C=n.find(w=>{var P,M,E,D;if(!w||w.type==="adhdev-daemon"||LA(w.daemonId||w.id)!==p.machineId||(w.transport==="acp"?"acp":w.transport==="pty"?"cli":null)!==p.kind||String(w.agentType||w.type||"")!==p.providerType)return!1;const T=String(w.providerSessionId||"");if(p.resumeSessionId&&T)return T===p.resumeSessionId;if(y){const W=uu(w.workspace||w.runtimeWorkspaceLabel);return W?W===y:!1}return Number(w.lastUpdated||w._lastUpdate||w.timestamp||((D=(E=(M=(P=w.activeChat)==null?void 0:P.messages)==null?void 0:M.at)==null?void 0:E.call(M,-1))==null?void 0:D.timestamp)||0)>=p.startedAt-5e3});if(!C)return;const v=Uh({entrySessionId:C.sessionId,entryInstanceId:C.instanceId,entryRouteId:C.id,conversations:a});v&&(u(null),i("done"),d(`${p.providerType} launched`),t(Wa(v)))},[a,n,t,p]),l.useEffect(()=>{if(!p)return;const y=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(y)},[p]);const x=l.useCallback(async(y,C)=>{var v;if(C.kind==="ide"&&C.providerType){await f(y,C.providerType,{workspacePath:C.workspace||null});return}if((C.kind==="cli"||C.kind==="acp")&&C.providerType){const w=((v=C.workspace)==null?void 0:v.trim())||"";await h(y,C.kind,C.providerType,{workspacePath:w||null,useHome:!w,resumeSessionId:C.providerSessionId||null})}},[f,h]);return{machineAction:{state:o,message:c},resetMachineAction:m,handleLaunchDetectedIde:f,handleAddWorkspace:g,handleMachineUpgrade:k,handleLaunchWorkspaceProvider:h,handleListSavedSessions:b,handleBrowseDirectory:S,handleOpenRecent:x}}function _A({conversations:e,selectedConversation:t,machineBackTarget:n,markConversationRead:a,resetMachineAction:r,setSelectedTabKey:o,setScreen:i,setSelectedMachineId:c,setSection:d,setMachineBackTarget:p}){const u=l.useCallback(S=>{o(S.tabKey),i("chat"),a(S)},[a,i,o]),m=l.useCallback(S=>{const x=e.find(y=>y.routeId===S.routeId&&y.streamSource==="native");x&&(o(x.tabKey),i("chat"),a(x))},[e,a,i,o]),f=l.useCallback(()=>{a(t),i("inbox")},[a,t,i]),g=l.useCallback((S,x="inbox")=>{c(S),r(),d("machines"),p(x),i("machine")},[r,p,i,d,c]),k=l.useCallback(S=>{const x=Vs(S);x&&g(x,"chat")},[g]),h=l.useCallback(()=>{r(),i(n)},[n,r,i]),b=l.useCallback(S=>{d(S),i("inbox")},[i,d]);return{openConversation:u,openNativeConversation:m,backFromConversation:f,openMachine:g,openConversationMachine:k,backFromMachine:h,changeMachineSection:b}}function aa(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function HA(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function $A({conversations:e,hiddenConversations:t,ides:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,userName:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,onOpenHistory:k,onOpenRemote:h,onStopCli:b,wsStatus:S,isConnected:x,initialDataLoaded:y=!0,onShowAllHiddenConversations:C,onHideConversation:v,onOpenMeshGraph:w,onOpenNewSession:j,liveSessionInboxState:N,setCliViewModeOverrides:A}){const[T,I]=l.useState(()=>{var ce;return((ce=e[0])==null?void 0:ce.tabKey)||null}),[P,M]=l.useState(()=>e[0]?"chat":"inbox"),[E,D]=l.useState("chats"),[W,R]=l.useState(null),[B,_]=l.useState("inbox"),H=l.useRef([]),L=ia(),F="1.0.57",$=l.useMemo(()=>e.find(ce=>ce.tabKey===T)||e[0]||null,[e,T]),K=l.useMemo(()=>$?n.find(ce=>ce.id===$.routeId):void 0,[n,$]),z=l.useMemo(()=>!$||ht($)||!bt($)?null:ca($),[$]),ne=l.useMemo(()=>n.filter(ce=>ce.type==="adhdev-daemon").sort(Kl),[n]),ie=l.useMemo(()=>ne.find(ce=>ce.id===W)||null,[ne,W]),Ce=So({sendDaemonCommand:r,activeConv:$||void 0,setActionLogs:o,isStandalone:i}),me=EA({sendDaemonCommand:r,navigate:L,ides:n,conversations:e}),O=NC(e),Y=l.useMemo(()=>e.map(ce=>{const Ae=P==="chat"&&($==null?void 0:$.tabKey)===ce.tabKey,be=go(ce,N,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Ae}),we=Nn(ce),_e=Vm(ce),U=th(ce,_e);return{conversation:ce,timestamp:we,preview:U,unread:be.unread,requiresAction:be.requiresAction,isWorking:be.isWorking,inboxBucket:be.inboxBucket}}),[e,N,P,$,O]),{markConversationRead:X}=IA({conversations:e,machineEntries:ne,items:Y,selectedConversation:$,selectedTabKey:T,screen:P,liveSessionInboxState:N,sendDaemonCommand:r,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,setSelectedTabKey:I,setScreen:M,setSelectedMachineId:R,setSection:D,setMachineBackTarget:_,resetMachineAction:me.resetMachineAction}),Q=_A({conversations:e,selectedConversation:$,machineBackTarget:B,markConversationRead:X,resetMachineAction:me.resetMachineAction,setSelectedTabKey:I,setScreen:M,setSelectedMachineId:R,setSection:D,setMachineBackTarget:_}),{isMuted:ve,toggleMute:he}=Qh(N,r),{attentionItems:Z,unreadItems:fe,workingItems:V,completedItems:q}=l.useMemo(()=>TA(Y,H.current),[Y]);l.useEffect(()=>{H.current=V.map(ce=>ce.conversation.tabKey)},[V]);const ee=l.useMemo(()=>ie?Y.filter(ce=>Vs(ce.conversation)===ie.id):[],[Y,ie]),pe=l.useMemo(()=>MA(ie,n),[n,ie]),le=!!ie&&jo(ie,Js(ie,F)),se=l.useMemo(()=>(ie==null?void 0:ie.availableProviders)||[],[ie]),te=l.useMemo(()=>se.filter(ce=>aa(ce,"cli")).map(ce=>({type:ce.type,displayName:ce.displayName||ce.type,icon:ce.icon})),[se]),ue=l.useMemo(()=>se.filter(ce=>aa(ce,"acp")).map(ce=>({type:ce.type,displayName:ce.displayName||ce.type,icon:ce.icon})),[se]),ye=l.useMemo(()=>PA(ne,Y,t),[Y,ne,t]),Me=l.useMemo(()=>To(n,y),[n,y]),re=l.useCallback(async ce=>{ie&&await me.handleOpenRecent(ie.id,ce)},[me,ie]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:P==="chat"&&$?s.jsx(gA,{selectedConversation:$,isAcp:ht($),isStandalone:i,selectedIdeEntry:K,actionLogs:a,userName:c,isSendingChat:Ce.isSendingChat,sendFeedbackMessage:Ce.sendFeedbackMessage,isFocusingAgent:Ce.isFocusingAgent,handleModalButton:Ce.handleModalButton,handleRelaunch:Ce.handleRelaunch,onBack:Q.backFromConversation,onOpenNativeConversation:Q.openNativeConversation,onOpenMachine:Q.openConversationMachine,onOpenHistory:k,onOpenRemote:h,onOpenMeshGraph:w,onStopCli:b,cliViewMode:z,onSetCliViewMode:async ce=>{await Lh({conversation:$,mode:ce,ides:n,sendDaemonCommand:r,setCliViewModeOverrides:A})},handleSendChat:Ce.handleSendChat,handleForceSendChat:Ce.handleForceSendChat,handleFocusAgent:Ce.handleFocusAgent}):P==="machine"&&ie?s.jsx(jA,{selectedMachineEntry:ie,selectedMachineConversations:ee,selectedMachineRecentLaunches:pe,cliProviders:te,acpProviders:ue,selectedMachineNeedsUpgrade:le,appVersion:F,machineAction:me.machineAction,isStandalone:i,section:E,showBottomNav:B==="inbox",onBack:Q.backFromMachine,onSectionChange:Q.changeMachineSection,onOpenConversation:Q.openConversation,onOpenRecent:re,onOpenMachineDetails:()=>L(`/machines/${ie.id}`),onMachineUpgrade:()=>me.handleMachineUpgrade(ie.id),onLaunchDetectedIde:(ce,Ae)=>me.handleLaunchDetectedIde(ie.id,ce,Ae),onAddWorkspace:(ce,Ae)=>me.handleAddWorkspace(ie.id,ce,Ae),onBrowseDirectory:ce=>me.handleBrowseDirectory(ie.id,ce),onLaunchWorkspaceProvider:(ce,Ae,be)=>me.handleLaunchWorkspaceProvider(ie.id,ce,Ae,be),onListSavedSessions:ce=>me.handleListSavedSessions(ie.id,ce)}):s.jsx(vA,{section:E,attentionItems:Z,unreadItems:fe,workingItems:V,completedItems:q,hiddenConversations:t,machineCards:ye,getAvatarText:HA,actionLogs:a,sendDaemonCommand:r,onOpenConversation:Q.openConversation,onShowAllHidden:C,onHideConversation:v,onOpenMeshGraph:w,onStopCli:b,onOpenNewSession:j,onOpenMachine:Q.openMachine,onOpenSettings:()=>L("/settings"),onSectionChange:D,wsStatus:S,isConnected:x,initialDataLoaded:y,conversationsLoaded:Me,isStandalone:i,isConversationMuted:ve,onToggleMuteConversation:he})})}function ci(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function FA({conversations:e,numGroups:t,onMoveTab:n,onReceiveTab:a,onOwnTabDrop:r,onClearPreviewOrder:o}){const i=l.useRef(0),[c,d]=l.useState(!1),[p,u]=l.useState(null),m=l.useCallback(()=>{i.current=0,d(!1),u(null)},[]);l.useEffect(()=>(window.addEventListener("dragend",m),window.addEventListener("drop",m),()=>{window.removeEventListener("dragend",m),window.removeEventListener("drop",m)}),[m]);const f=l.useCallback(b=>{b.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,d(!0))},[]),g=l.useCallback(b=>{if(!b.dataTransfer.types.includes("text/tab-key"))return;if(b.preventDefault(),!ci(t,n)){u("merge");return}const S=b.currentTarget.getBoundingClientRect(),x=b.clientX-S.left,y=S.width/3;x<y?u("split-left"):x>y*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(b=>{i.current=0,d(!1);const S=b.dataTransfer.getData("text/tab-key"),x=S?e.some(C=>C.tabKey===S):!1,y=p;if(u(null),o(),!!S){if(b.preventDefault(),y==="split-left"&&ci(t,n)){n==null||n(S,"split-left");return}if(y==="split-right"&&ci(t,n)){n==null||n(S,"split-right");return}if(x){r(S);return}a==null||a(S)}},[e,p,t,n,a,r,o]);return{dragOver:c,dropAction:p,resetDragState:m,handleDragEnter:f,handleDragOver:g,handleDragLeave:k,handleDrop:h}}function BA(e,t){const n=new Set(t.map(o=>o.tabKey)),a=e.filter(o=>n.has(o)),r=t.filter(o=>!e.includes(o.tabKey)).map(o=>o.tabKey);return[...a,...r]}function WA({conversations:e,initialActiveTabId:t,initialTabOrder:n,onActiveTabChange:a,onTabOrderChange:r}){const[o,i]=l.useState(t??null),[c,d]=l.useState(n??[]),[p,u]=l.useState(null),m=l.useRef(null),f=l.useRef(null),g=l.useRef(a),k=l.useRef(r);l.useEffect(()=>{g.current=a},[a]),l.useEffect(()=>{k.current=r},[r]),l.useEffect(()=>{t&&t!==o&&i(t)},[t,o]),l.useEffect(()=>{d(j=>{const N=BA(j,e);return N.length===j.length&&N.every((A,T)=>A===j[T])?j:N})},[e]);const h=l.useMemo(()=>{const j=p??c;if(j.length===0)return e;const N=new Map(j.map((A,T)=>[A,T]));return[...e].sort((A,T)=>{const I=N.get(A.tabKey)??999,P=N.get(T.tabKey)??999;return I-P})},[e,p,c]);l.useEffect(()=>{var N,A;if(h.length===0){o!==null&&(i(null),(N=g.current)==null||N.call(g,null));return}if(o&&h.some(T=>T.tabKey===o))return;const j=h[0].tabKey;j!==o&&(i(j),(A=g.current)==null||A.call(g,j))},[h,o]);const b=l.useMemo(()=>h.find(j=>j.tabKey===o),[h,o]),S=l.useCallback(j=>{var N;i(j),(N=g.current)==null||N.call(g,j)},[]),x=l.useCallback((j,N,A)=>{d(T=>{var E;const I=T.filter(D=>D!==j),P=I.indexOf(N);if(P<0)return T;const M=A==="left"?P:P+1;return I.splice(M,0,j),(E=k.current)==null||E.call(k,I),I}),u(null)},[]),y=l.useCallback((j,N,A)=>{const I=(c.length>0?c:e.map(E=>E.tabKey)).filter(E=>E!==j),P=I.indexOf(N);if(P<0)return;const M=A==="left"?P:P+1;I.splice(M,0,j),m.current=I,u(I)},[c,e]),C=l.useCallback(()=>{var N;const j=m.current;j&&(d(j),(N=k.current)==null||N.call(k,j))},[]),v=l.useCallback(()=>{m.current=null,u(null)},[]),w=l.useCallback(j=>{d(N=>{var T;const A=N.filter(I=>I!==j);return A.push(j),(T=k.current)==null||T.call(k,A),A})},[]);return{activeTabId:o,activeConv:b,sortedConversations:h,previewOrderRef:m,draggingTabRef:f,selectTab:S,handleTabReorder:x,updatePreviewOrder:y,commitPreviewOrder:C,clearPreviewOrder:v,moveTabToEnd:w,setDraggingTabKey:j=>{f.current=j}}}function OA({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 xc({conversationsCount:e,isSplitMode:t,isStandalone:n,hasRegisteredMachines:a=!1,suppressGuide:r=!1,onOpenNewSession:o,isLoading:i=!1}){const{t:c}=ke("common");if(r)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});if(i)return s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center gap-3 -mt-8 text-text-muted",children:[s.jsx(ls,{}),s.jsx("p",{className:"text-sm",children:c("paneGroup.loadingSessions")})]});const d=!n&&!a,p=a&&!!o,u=c(a?"paneGroup.noConversations":n?"paneGroup.waitingForDaemon":"paneGroup.connectYourMachines"),m=c(a?"paneGroup.newSessionDescription":n?"paneGroup.daemonDescription":"paneGroup.installDescription");return e===0&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:u}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:m}),p&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:o,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:c("paneGroup.newSession"),"aria-label":c("paneGroup.newSession"),children:[s.jsx(Wl,{size:14}),s.jsx("span",{children:c("paneGroup.newSession")})]})}),d&&s.jsx(qh,{}),d&&s.jsx("div",{className:"mt-8",children:s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:"Read the documentation →"})})]})]}):s.jsx("div",{className:"text-sm text-text-muted opacity-50",children:t?"Move a tab here to view":"No active agent"})}const Xh="adhdev-tab-shortcuts";function Zh(){try{return JSON.parse(localStorage.getItem(Xh)||"{}")}catch{return{}}}function ef({enabled:e=!0,sortedTabKeys:t,onFocus:n,onSelectTab:a}){const r=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>Zh()),[c,d]=l.useState(null),p=l.useCallback(m=>{const f=[];return m.metaKey&&f.push(r?"⌘":"Meta"),m.ctrlKey&&f.push("Ctrl"),m.altKey&&f.push(r?"⌥":"Alt"),m.shiftKey&&f.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(m.key)?null:(f.push(m.key.length===1?m.key.toUpperCase():m.key),f.join("+"))},[r]),u=l.useCallback(m=>{i(m);try{localStorage.setItem(Xh,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,b]of Object.entries(k))b===g&&delete k[h];k[c]=g,u(k),d(null)};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[e,c,o,u,p]),l.useEffect(()=>{if(!e)return;const m=f=>{if(!(!f.ctrlKey&&!f.metaKey&&!f.altKey)){for(const[g,k]of Object.entries(o))if(t.includes(g)&&p(f)===k){f.preventDefault(),n(),a(g);return}}};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[e,o,t,n,a,p]),{isMac:r,tabShortcuts:o,shortcutListening:c,setShortcutListening:d,saveShortcuts:u}}const di=e=>{e.preventDefault()},UA=l.memo(function({conv:t,isActive:n,isDraggedTab:a,isTaskCompleteUnread:r,shortcut:o,conversationKeys:i,draggingTabRef:c,onFocus:d,onSelectTab:p,onConversationActivated:u,onPreviewReorder:m,onReorderTab:f,onCommitPreviewOrder:g,onClearPreviewOrder:k,onDragStateReset:h,onDragTabKeyChange:b,onReceiveTab:S,onOpenContextMenu:x,longPressTimer:y,isGroupActive:C}){const v=En(t),w=v.isGenerating?"agent-tab-generating":v.isWaiting?"agent-tab-waiting":"",j=v.isReconnecting,N=VC(t),A=YC(t),T=eh(t),I=l.useCallback(H=>{c.current=t.tabKey,b(t.tabKey),H.dataTransfer.setData("text/tab-key",t.tabKey),H.dataTransfer.effectAllowed="move"},[t.tabKey,c,b]),P=l.useCallback(()=>{c.current=null,b(null),g(),k(),h()},[c,b,g,k,h]),M=l.useCallback(H=>{const L=c.current;if(!(!L||L===t.tabKey)&&H.dataTransfer.types.includes("text/tab-key")){H.preventDefault(),H.stopPropagation();const F=H.currentTarget.getBoundingClientRect(),$=H.clientX<F.left+F.width/2?"left":"right";m(L,t.tabKey,$)}},[t.tabKey,c,m]),E=l.useCallback(H=>{H.preventDefault(),H.stopPropagation();const L=H.dataTransfer.getData("text/tab-key");if(L&&L!==t.tabKey){const F=H.currentTarget.getBoundingClientRect(),$=H.clientX<F.left+F.width/2?"left":"right";i.includes(L)?f(L,t.tabKey,$):S&&S(L)}k()},[t.tabKey,i,f,S,k]),D=l.useCallback(H=>{H.stopPropagation(),d(),p(t.tabKey),u(t)},[t,u,d,p]),W=l.useCallback(H=>{H.preventDefault(),x(H.clientX,H.clientY,t.tabKey)},[t.tabKey,x]),R=l.useCallback(H=>{const L=H.touches[0];y.current=setTimeout(()=>{x(L.clientX,L.clientY,t.tabKey)},600)},[t.tabKey,y,x]),B=l.useCallback(()=>{y.current&&clearTimeout(y.current)},[y]),_=["adhdev-dockview-tab",w,n&&"is-active",C&&"is-group-active",j&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:_,draggable:!0,onDragStart:I,onDragEnd:P,onDragOver:M,onDrop:E,onClick:D,onContextMenu:W,onTouchStart:R,onTouchEnd:B,onTouchMove:B,style:{position:"relative",cursor:"pointer",opacity:a?.4:void 0},children:[T&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-badge pointer-events-none absolute top-0.5 right-0.5 text-text-muted",title:"Mesh chat","aria-label":"Mesh chat",children:s.jsx(cs,{size:11})}),r&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:v.isGenerating?s.jsx(ls,{size:12,thickness:2,color:"success"}):v.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):j?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):v.isConnecting?s.jsx(ls,{size:12,thickness:2}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),N.length>0&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-role",title:A,"aria-label":A||N.join(" · "),children:N.join(" · ")}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:kt(t),children:kt(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[j?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:Sn(t)}):v.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[Sn(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:Sn(t)}),s.jsx(qr,{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 GA({conversations:e,activeTabId:t,groupIndex:n,unreadTabKeys:a,draggingTabRef:r,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:m,onDragStateReset:f,onDragTabKeyChange:g,onReceiveTab:k,onHideTab:h,isGroupActive:b,allowTabShortcuts:S=!0}){const{t:x}=ke("common"),[y,C]=l.useState(null),v=l.useRef(null),w=l.useRef(null),j=l.useMemo(()=>e.map(E=>E.tabKey),[e]);qa("PaneGroupTabBar",{groupIndex:n,activeTabId:t,tabCount:e.length,ctxMenuTab:(y==null?void 0:y.tabKey)||null});const{isMac:N,tabShortcuts:A,shortcutListening:T,setShortcutListening:I,saveShortcuts:P}=ef({enabled:S,sortedTabKeys:e.map(E=>E.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!y)return;const E=D=>{const W=document.querySelector("[data-pane-context-menu]");W&&W.contains(D.target)||C(null)};return window.addEventListener("mousedown",E,!0),()=>window.removeEventListener("mousedown",E,!0)},[y]),l.useEffect(()=>{const E=w.current;if(!E)return;const D=W=>{Math.abs(W.deltaY)<=Math.abs(W.deltaX)||(W.preventDefault(),E.scrollLeft+=W.deltaY)};return E.addEventListener("wheel",D,{passive:!1}),()=>E.removeEventListener("wheel",D)},[]);const M=l.useCallback((E,D,W)=>{C({x:E,y:D,tabKey:W})},[]);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:w,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(E=>s.jsx(UA,{conv:E,isActive:t===E.tabKey,isDraggedTab:r.current===E.tabKey,isTaskCompleteUnread:a.has(E.tabKey),shortcut:S?A[E.tabKey]:void 0,conversationKeys:j,draggingTabRef:r,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:m,onDragStateReset:f,onDragTabKeyChange:g,onReceiveTab:k,onOpenContextMenu:M,longPressTimer:v,isGroupActive:b},E.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:x("paneGroup.noTabsInGroup")})]})}),y&&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:y.x,top:y.y},children:[S&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:di,onClick:E=>{E.stopPropagation(),I(y.tabKey),C(null)},children:["⌨ ",A[y.tabKey]?`Change shortcut (${A[y.tabKey]})`:"Set shortcut"]}),A[y.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:di,onClick:()=>{const E={...A};delete E[y.tabKey],P(E),C(null)},children:"✕ Remove shortcut"})]}),h&&s.jsxs(s.Fragment,{children:[S&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onMouseDown:di,onClick:()=>{h(y.tabKey),C(null)},children:s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx(mo,{size:12}),"Hide from Dashboard"]})})]})]}),S&&T&&s.jsx(Vt,{children:s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:()=>I(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:E=>E.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",N?"⌘+1":"Ctrl+1",", ",N?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:x("paneGroup.pressEscToCancel")})]})})})]})}function qA({conversations:e,ides:t,clearedTabs:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:d=!0,userName:p,groupIndex:u,onFocus:m,isSplitMode:f,numGroups:g,onMoveTab:k,onReceiveTab:h,style:b,onActiveTabChange:S,initialActiveTabId:x,initialTabOrder:y,onTabOrderChange:C,onHideTab:v,isFocused:w,allowTabShortcuts:j=!0,onOpenNewSession:N,liveSessionInboxState:A}){const{sendCommand:T}=St(),I=l.useRef(null),{activeTabId:P,activeConv:M,sortedConversations:E,draggingTabRef:D,selectTab:W,handleTabReorder:R,updatePreviewOrder:B,commitPreviewOrder:_,clearPreviewOrder:H,moveTabToEnd:L,setDraggingTabKey:F}=WA({conversations:e,initialActiveTabId:x,initialTabOrder:y,onActiveTabChange:S,onTabOrderChange:C}),$=So({sendDaemonCommand:r,activeConv:M,setActionLogs:o,isStandalone:i}),{dragOver:K,dropAction:z,resetDragState:ne,handleDragEnter:ie,handleDragOver:Ce,handleDragLeave:me,handleDrop:O}=FA({conversations:e,numGroups:g,onMoveTab:k,onReceiveTab:h,onOwnTabDrop:L,onClearPreviewOrder:H}),Y=M&&!ht(M)&&ca(M)==="terminal",X=l.useMemo(()=>M?t.find(Z=>Z.id===M.routeId):void 0,[t,M]),Q=l.useMemo(()=>M?a.filter(Z=>Z.routeId===M.tabKey):[],[a,M]),ve=l.useMemo(()=>new Set(E.filter(Z=>Lx(Z,A,{isOpenConversation:Z.tabKey===P})).map(Z=>Z.tabKey)),[P,A,E]);qa("PaneGroup",{groupIndex:u,conversationCount:e.length,activeTabId:P,dragOver:K});const he=l.useCallback(Z=>{Z.streamSource==="agent-stream"&&Z.agentType&&T(Z.routeId,Em(),{agentType:Z.agentType,...Z.sessionId&&{targetSessionId:Z.sessionId}}).catch(()=>{})},[T]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:m,style:{...b,outline:K?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(GA,{conversations:E,activeTabId:P,groupIndex:u,numGroups:g,unreadTabKeys:ve,draggingTabRef:D,onFocus:m,onSelectTab:W,onConversationActivated:he,onPreviewReorder:B,onReorderTab:R,onCommitPreviewOrder:_,onClearPreviewOrder:H,onDragStateReset:ne,onDragTabKeyChange:F,onMoveTab:k,onReceiveTab:h,onHideTab:v,isGroupActive:w??!1,allowTabShortcuts:j}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:ie,onDragOver:Ce,onDragLeave:me,onDrop:O,children:[K&&s.jsx(OA,{dropAction:z,canSplit:!!(g<4&&k)}),M?s.jsx(gc,{activeConv:M,clearToken:n[M.tabKey]||0,isCliTerminal:!!Y,ideEntry:X,terminalRef:I,handleModalButton:$.handleModalButton,handleRelaunch:$.handleRelaunch,handleSendChat:$.handleSendChat,handleForceSendChat:$.handleForceSendChat,isSendingChat:$.isSendingChat,sendFeedbackMessage:$.sendFeedbackMessage,handleFocusAgent:$.handleFocusAgent,isFocusingAgent:$.isFocusingAgent,actionLogs:Q,userName:p,isInputActive:!f||!!w}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(xc,{conversationsCount:e.length,isSplitMode:f,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:N,isLoading:!To(t,d)})})]})]})}function zA({containerRef:e,isSplitMode:t,numGroups:n,groupSizes:a,groupedConvs:r,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:p,isStandalone:u,hasRegisteredMachines:m,initialDataLoaded:f,userName:g,focusedGroup:k,focusGroup:h,moveTabToGroup:b,splitTabRelative:S,closeGroup:x,handleResizeStart:y,groupActiveTabIds:C,setGroupActiveTab:v,groupTabOrders:w,setGroupTabOrder:j,toggleHiddenTab:N,onOpenNewSession:A,allowTabShortcuts:T=!0,liveSessionInboxState:I}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:r.map((P,M)=>{const E=t&&a.length===n?`${a[M]}%`:void 0;return s.jsxs(Rt.Fragment,{children:[t&&M>0&&s.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:D=>y(M-1,D),onDoubleClick:()=>x(M),title:"Drag to resize · Double-click to merge",children:s.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),s.jsx(qA,{style:t?{flexBasis:E??`${100/n}%`,flexGrow:E?0:1,flexShrink:E?0:1}:void 0,conversations:P,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:p,isStandalone:u,hasRegisteredMachines:m,initialDataLoaded:f,userName:g,groupIndex:M,isFocused:t&&k===M,onFocus:()=>h(M),isSplitMode:t,numGroups:n,onMoveTab:(D,W)=>{W==="left"&&M>0?b(D,M-1):W==="right"&&M<n-1?b(D,M+1):W==="split-left"&&n<4?S(D,M,"left"):W==="split-right"&&n<4&&S(D,M,"right")},onReceiveTab:D=>b(D,M),onActiveTabChange:D=>v(M,D),initialActiveTabId:C[M],initialTabOrder:w[M],onTabOrderChange:D=>j(M,D),onHideTab:N,onOpenNewSession:A,allowTabShortcuts:T,liveSessionInboxState:I})]},M)})})}const tf="adhdev-dashboard-action-shortcuts",KA=1200,VA=[["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 YA(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function gt(e,t){switch(e){case"openShortcutHelp":return"?";case"openNewSession":return t?"⌘+⇧+Enter":"Ctrl+Shift+Enter";case"hideCurrentTab":return t?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return t?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return t?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return t?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return t?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return t?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return t?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return t?"⌘+Ctrl+⇧+→":"Ctrl+Alt+Shift+→";case"splitActiveTabDown":return t?"⌘+Ctrl+⇧+↓":"Ctrl+Alt+Shift+↓";case"focusLeftPane":return"";case"focusRightPane":return"";case"focusUpPane":return"";case"focusDownPane":return"";case"moveActiveTabToLeftPane":return"";case"moveActiveTabToRightPane":return"";case"moveActiveTabToUpPane":return"";case"moveActiveTabToDownPane":return"";case"triggerPrimaryApprovalAction":return t?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return t?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return t?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return t?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return t?"⌘+⇧+←":"Ctrl+Shift+←";case"selectNextGroupTab":return t?"⌘+⇧+→":"Ctrl+Shift+→";case"toggleCliView":return t?"⌥+T":"Ctrl+Alt+T"}}function sf(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:gt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:gt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:gt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:gt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:gt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:gt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:gt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:gt("popoutActiveTab",e)},{id:"dockActiveTab",label:"Dock active tab",description:"Dock a floating tab back into the grid, or move a popout tab back to the main window.",defaultShortcut:gt("dockActiveTab",e)},{id:"splitActiveTabRight",label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it.",defaultShortcut:gt("splitActiveTabRight",e)},{id:"splitActiveTabDown",label:"Move active tab to new lower pane",description:"Create a pane below and move the active tab into it.",defaultShortcut:gt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:gt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:gt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:gt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:gt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:gt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:gt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:gt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:gt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:gt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:gt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:gt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:gt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:gt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:gt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:gt("toggleCliView",e)}]}function bl(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function eo(e){const t=Object.fromEntries(sf(e).map(n=>[n.id,n.defaultShortcut]));try{const n=JSON.parse(localStorage.getItem(tf)||"{}"),a={...t,...n};for(const[r,o]of VA)a[r]===o&&(a[r]=t[r]);return a}catch{return t}}function nf(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function QA({enabled:e=!0,onTrigger:t}){const n=YA(),[a,r]=l.useState(()=>eo(n)),[o,i]=l.useState(null),[c,d]=l.useState([]),p=l.useRef({parts:[],timer:null}),u=l.useCallback(h=>{const b=[];return h.metaKey&&b.push(n?"⌘":"Meta"),h.ctrlKey&&b.push("Ctrl"),h.altKey&&b.push(n?"⌥":"Alt"),h.shiftKey&&h.key.length!==1&&b.push(n?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(b.push(nf(h.key)),b.join("+"))},[n]),m=l.useCallback(h=>{r(h);try{localStorage.setItem(tf,JSON.stringify(h))}catch{}},[]);l.useEffect(()=>{const h=eo(n),b=Object.entries(a),S=Object.entries(h);b.length===S.length&&b.every(([x,y])=>h[x]===y)||m(h)},[a,n,m]);const f=l.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),g=l.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},KA))},[]);l.useEffect(()=>{if(!o)return;const h=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){i(null),d([]);return}const S=u(b);if(!S)return;const y=!(b.metaKey||b.ctrlKey||b.altKey)&&/^[A-Z0-9]$/.test(S);if(c.length===0&&y){d([S]);return}const v=[...c,S].slice(0,2).join(" "),w={...a};for(const[j,N]of Object.entries(w))N===v&&delete w[j];w[o]=v,m(w),i(null),d([])};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[a,u,m,o,c]),l.useEffect(()=>{if(!e||o)return;const h=b=>{if(b.defaultPrevented)return;const S=u(b);if(!S)return;const x=b.metaKey||b.ctrlKey||b.altKey;if(bl(b.target))return;const y=p.current.parts,C=x?[S]:[...y.slice(-1),S].slice(-2),v=C.join(" "),w=C[C.length-1],j=Object.entries(a).filter(([,P])=>!!P),N=j.find(([,P])=>P===v);if(N){b.preventDefault(),f(),t(N[0]);return}if(j.some(([,P])=>P.startsWith(`${v} `))){b.preventDefault(),p.current.parts=C,g();return}const T=j.find(([,P])=>P===w);if(T){b.preventDefault(),f(),t(T[0]);return}if(j.some(([,P])=>P.startsWith(`${w} `))){b.preventDefault(),p.current.parts=[w],g();return}f()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[a,g,e,u,t,f,o]),l.useEffect(()=>()=>f(),[f]);const k=l.useMemo(()=>sf(n),[n]);return{isMac:n,actionDefinitions:k,actionShortcuts:a,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:d,saveShortcuts:m}}function JA({isTabInPopout:e,isTabFloating:t,tabShortcut:n,actionShortcuts:a}){const r=[];return e?(t&&r.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:a.dockActiveTab}),r.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:a.dockActiveTab})):t?r.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:a.dockActiveTab}):r.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:a.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:a.popoutActiveTab}),r.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:n?`Change shortcut (${n})`:"Set shortcut",shortcut:a.setActiveTabShortcut}),n&&r.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),r.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:a.hideCurrentTab,tone:"muted"}),r}function af(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function pu({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:n,ides:a}){return!e||n>0?!1:t?!af(a):!0}function XA({previousVisibleConversationCount:e,visibleConversationCount:t,ides:n}){return t>0||e<=0?!1:af(n)}const rf=1e3,ZA=4;function mu(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function hu(e,t,n){return Math.abs(t.clientX-e.clientX)>n||Math.abs(t.clientY-e.clientY)>n}function eT({detachDelayMs:e=rf,stillnessThresholdPx:t=ZA,onDetach:n,setTimeoutFn:a=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:r=globalThis.clearTimeout.bind(globalThis)}){let o=null,i=null,c=null,d=null,p=null,u=!1;const m=()=>{p!=null&&(r(p),p=null)},f=()=>{m(),c=null},g=()=>{m(),o=null,i=null,c=null,d=null,u=!1},k=()=>{!o||!c||!d||u||p!=null||(p=a(()=>{p=null,!(!o||!c||!d||u)&&mu(d,i)&&(hu(c,d,t)||(u=!0,n({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},h=S=>{if(!(!o||u)){if(!mu(S,i)){d={clientX:S.clientX,clientY:S.clientY},f();return}(!c||hu(c,S,t))&&(m(),c={clientX:S.clientX,clientY:S.clientY}),d={clientX:S.clientX,clientY:S.clientY},k()}},b=S=>{!o||u||(S&&(d={clientX:S.clientX,clientY:S.clientY}),f())};return{startDrag:S=>{m(),o=S.panelId,i=S.selfPanelBounds??null,c=null,d={clientX:S.clientX,clientY:S.clientY},u=!1},markSelfPanel:h,markNonSelfPanel:b,markNoDropTarget:b,markDockTarget:b,endDrag:g,isDragging:()=>o!=null,hasDetached:()=>u,dispose:g}}function tT(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function Lr(e){return kt(e)||e.tabKey}function sT(e){return`remote:${e}`}function fs(e){return e.startsWith("remote:")}function fu(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function ui(e){var a;const t=e==null?void 0:e.defaultView;if(!t)return;const n=r=>{if(r)try{r.focus({preventScroll:!0})}catch{try{r.focus()}catch{}}};try{t.focus(),n(e==null?void 0:e.body),n(e==null?void 0:e.documentElement),(a=t.requestAnimationFrame)==null||a.call(t,()=>{try{t.focus(),n(e==null?void 0:e.body)}catch{}})}catch{}}function pi(e,t){e.classList.remove(Wi.className,Oi.className),e.classList.add(t==="light"?Wi.className:Oi.className)}function gu(e){return e?Array.from(new Set(e.groups.map(t=>{var n,a;return(a=(n=t.element)==null?void 0:n.ownerDocument)==null?void 0:a.defaultView}).filter(t=>!!t&&t!==window))):[]}function nT(e,t,n){var i;const a=[t];let r;for(const c of a){let d;for(const p of c){const u=e.addPanel({id:p.tabKey,component:"conversation",title:Lr(p),params:{kind:"conversation",tabKey:p.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:r?{position:{referencePanel:r,direction:"right"},inactive:!0}:{}});d||(d=u.id)}r=d??r}return n??((i=t[0])==null?void 0:i.tabKey)??null}function bu(e,t){const n=new Set(t.map(r=>r.tabKey)),a=new Map;for(const r of t)a.set(r.tabKey,(a.get(r.tabKey)||0)+1);for(const r of[...e.panels])fs(r.id)||n.has(r.id)||e.removePanel(r);for(const r of t){const o=e.getPanel(r.tabKey);if(o){(a.get(r.tabKey)||0)>1&&console.warn("[dashboard-conversations] Dockview panel already exists for duplicate tabKey",{tabKey:r.tabKey,daemonId:r.daemonId,sessionId:r.sessionId,providerSessionId:r.providerSessionId,panelId:o.id}),o.update({params:{tabKey:r.tabKey}}),o.title!==Lr(r)&&o.api.setTitle(Lr(r));continue}e.addPanel({id:r.tabKey,component:"conversation",title:Lr(r),params:{kind:"conversation",tabKey:r.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function xu(e,t,n){var d,p;const a=n?sT(n):null;for(const u of[...e.panels])fs(u.id)&&(!a||u.id!==a)&&e.removePanel(u);if(!n||!a)return;const r=ws(t,n);if(!r&&e.totalPanels===0)return;const o=e.getPanel(a),i=ah(r);if(o){o.title!==i&&o.api.setTitle(i);return}const c=(r==null?void 0:r.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((p=e.panels.find(u=>!fs(u.id)))==null?void 0:p.id);e.addPanel({id:a,component:"remote",title:i,params:{kind:"remote",routeId:n},...c?{position:{referencePanel:c,direction:"right"},inactive:!0}:{}})}function of({doId:e,targetSessionId:t,connState:n,viewMode:a}){const[r,o]=l.useState(null),[i,c]=l.useState(null);l.useEffect(()=>e?Ct.onScreenshot("ide-page",(u,m)=>{if(u!==e)return;const f=new FileReader;f.onload=()=>o(f.result),f.readAsDataURL(m)}):void 0,[e]),l.useEffect(()=>{n!=="connected"&&o(null)},[n]),l.useEffect(()=>{var u;return e?((u=Ct.onStatus)==null?void 0:u.call(Ct,(m,f)=>{m===e&&f!=null&&f.screenshotUsage&&c(f.screenshotUsage)}))||(()=>{}):void 0},[e]),l.useEffect(()=>{o(null)},[e,t]),l.useEffect(()=>{const p=e?Ct.get(e):null;if(!(!p||n!=="connected"))return a!=="chat"&&t?p.startScreenshots(t):p.stopScreenshots(t),()=>{p.stopScreenshots(t)}},[a,n,t,e]);const d=l.useCallback(async(p,u)=>{const m=e?Ct.get(e):null;return!m||n!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):m.sendInput(p,u,t)},[e,n,t]);return{connScreenshot:r,screenshotUsage:i,handleRemoteAction:d}}const lf=l.createContext(null);function Mo(){const e=l.useContext(lf);if(!e)throw new Error("DashboardDockviewContext missing");return e}function aT(e){const[,t]=l.useState(0);l.useEffect(()=>{const n=()=>t(r=>r+1),a=[e.api.onDidActiveGroupChange(n),e.api.onDidTitleChange(n),e.api.onDidGroupChange(n),e.containerApi.onDidActivePanelChange(n)];return()=>{for(const r of a)r.dispose()}},[e.api,e.containerApi])}function rT({params:e}){var d;const t=Mo(),n=l.useMemo(()=>ws([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),a=l.useMemo(()=>t.ides.find(p=>p.id===e.routeId),[t.ides,e.routeId]),r=(n==null?void 0:n.daemonId)||((d=n==null?void 0:n.routeId)==null?void 0:d.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:i,handleRemoteAction:c}=of({doId:r,targetSessionId:n?Lm(n):(a==null?void 0:a.sessionId)||(a==null?void 0:a.instanceId),connState:(n==null?void 0:n.connectionState)||"new",viewMode:"remote"});return n?s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:s.jsx(Qp,{addLog:()=>{},connState:n.connectionState||"new",connScreenshot:o,screenshotUsage:i,transportType:n.transport,onAction:c})}):s.jsx("div",{className:"h-full min-h-0 min-w-0 flex items-center justify-center text-sm text-text-muted",children:"Remote view unavailable"})}function oT(){const e=Mo();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(xc,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels,isLoading:!To(e.ides,e.initialDataLoaded)})})}function iT(e){var x,y;aT(e);const t=Mo(),n=l.useCallback(C=>{"button"in C&&C.button!==0||e.api.setActive()},[e.api]),a=e.params.kind==="remote"?void 0:t.conversationsByTabKey.get(e.params.tabKey),r=a==null?void 0:a.sessionId,o=l.useCallback(C=>PC(C),[]),i=l.useCallback(()=>MC(r),[r]),c=l.useSyncExternalStore(o,i,i);if(e.params.kind==="remote"){const C=ws([...t.conversationsByTabKey.values()],e.params.routeId),v=((x=e.api.group.activePanel)==null?void 0:x.id)===e.api.id,w=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${v?" is-active":""}${w?" 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=((y=e.api.group.activePanel)==null?void 0:y.id)===e.api.id,u=e.api.isGroupActive,m=go(d,t.liveSessionInboxState,{isOpenConversation:p}),f=m.isReconnecting,g=m.isConnecting,k=m.isGenerating||c,h=m.isWaiting,b=m.unread,S=t.tabShortcuts[d.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${p?" is-active":""}${u?" is-group-active":""}${f?" is-reconnecting":""}`,title:kt(d),"data-tab-key":e.params.tabKey,onMouseDown:n,onTouchStart:n,onContextMenu:C=>{var v;C.preventDefault(),n(C),t.openTabContextMenu({x:C.clientX,y:C.clientY,tabKey:d.tabKey,sourceDocument:((v=C.target)==null?void 0:v.ownerDocument)??document})},children:[b&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:k?s.jsx(ls,{size:12,thickness:2,color:"success"}):h?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):f?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):g?s.jsx(ls,{size:12,thickness:2}):d.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:kt(d)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:f?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Sn(d)}):g?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Sn(d)}):s.jsx("span",{children:Sn(d)})})]}),S&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:S,children:S})]})}function hr(e){return e.isActive}function vu(e){return e.isVisible}function lT(e){e.preventDefault()}function cT({params:e,api:t}){var g;const n=Mo(),a=l.useRef(null),[r,o]=l.useState(()=>hr(t)),[i,c]=l.useState(()=>vu(t)),d=n.conversationsByTabKey.get(e.tabKey),p=So({sendDaemonCommand:n.sendDaemonCommand,activeConv:d,setActionLogs:n.setActionLogs,isStandalone:n.isStandalone});l.useEffect(()=>{o(hr(t)),c(vu(t));const k=[t.onDidActiveChange(h=>o(h.isActive)),t.onDidActiveGroupChange(h=>{if(!hr(t)&&!h.isActive){o(!1);return}o(hr(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(xc,{conversationsCount:0,isSplitMode:!1,isStandalone:n.isStandalone,hasRegisteredMachines:n.hasRegisteredMachines,onOpenNewSession:n.onOpenNewSession,suppressGuide:n.hasDetachedConversationPanels,isLoading:!To(n.ides,n.initialDataLoaded)})});const f=!ht(d)&&ca(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(gc,{activeConv:d,clearToken:n.clearedTabs[d.tabKey]||0,isCliTerminal:f,ideEntry:u,terminalRef:a,handleModalButton:p.handleModalButton,handleRelaunch:p.handleRelaunch,handleSendChat:p.handleSendChat,handleForceSendChat:p.handleForceSendChat,isSendingChat:p.isSendingChat,handleFocusAgent:p.handleFocusAgent,isFocusingAgent:p.isFocusingAgent,actionLogs:m,userName:n.userName,scrollToBottomRequestNonce:((g=n.scrollToBottomRequest)==null?void 0:g.tabKey)===d.tabKey?n.scrollToBottomRequest.nonce:void 0,isInputActive:r,isVisible:i})})}function dT({visibleConversations:e,clearedTabs:t,ides:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:d,userName:p,toggleHiddenTab:u,actionShortcuts:m,registerActionHandlers:f,onActiveTabChange:g,onOpenNewSession:k,onRequestScrollToBottom:h,requestedActiveTabKey:b,requestedRemoteIdeId:S,onRequestedActiveTabConsumed:x,scrollToBottomRequest:y,liveSessionInboxState:C,layoutProfile:v}){var $e,at,rt;const{theme:w}=Rs(),{sendCommand:j}=St(),N=l.useRef(null),A=l.useRef(null),T=l.useRef(null),I=l.useRef(!1),P=l.useRef(!1),M=l.useRef(!1),E=l.useRef(null),D=l.useRef([]),[W,R]=l.useState(null),[B,_]=l.useState(0),H=l.useRef(typeof window>"u"?{}:TN(v)),L=l.useMemo(()=>new Map(e.map(G=>[G.tabKey,G])),[e]),F=l.useMemo(()=>{const G=N.current;return G?G.groups.some(oe=>{try{const de=oe.model.location.type;return de!=="floating"&&de!=="popout"?!1:oe.panels.some(xe=>L.has(xe.id))}catch{return!1}}):!1},[L,B,e]),$=l.useCallback(()=>{var G;(G=N.current)==null||G.focus()},[]),K=l.useCallback((G,oe)=>{h==null||h(G,oe)},[h]),z=l.useCallback(G=>{const oe=document,de=G.document;for(const Ee of oe.querySelectorAll('link[rel="stylesheet"]')){const Je=de.createElement("link");Je.rel="stylesheet",Je.href=Ee.href,Ee.crossOrigin&&(Je.crossOrigin=Ee.crossOrigin),de.head.appendChild(Je)}for(const Ee of oe.querySelectorAll("style")){const Je=de.createElement("style");Je.textContent=Ee.textContent,de.head.appendChild(Je)}const xe=[];for(const Ee of oe.styleSheets)try{for(const Je of Ee.cssRules)Je instanceof CSSStyleRule&&(Je.selectorText===":root"||Je.selectorText==="html")&&xe.push(Je.cssText)}catch{}if(xe.length>0){const Ee=de.createElement("style");Ee.textContent=xe.join(`
|
|
66
66
|
`),de.head.appendChild(Ee)}const Se=oe.documentElement.getAttribute("data-theme");Se&&de.documentElement.setAttribute("data-theme",Se),de.documentElement.style.colorScheme=Se==="light"?"light":"dark",de.body.className=oe.body.className;const Pe=oe.documentElement.getAttribute("style");Pe&&de.documentElement.setAttribute("style",Pe);const He=de.getElementById("dv-popout-window");He instanceof HTMLElement&&(He.classList.add("adhdev-dockview"),pi(He,w))},[w]),ne=l.useCallback(()=>{var oe;const G=N.current;if(G)for(const de of G.groups)try{const xe=(oe=de.element)==null?void 0:oe.ownerDocument;if(!xe||xe===document)continue;const Se=xe.getElementById("dv-popout-window");Se instanceof HTMLElement&&(Se.classList.add("adhdev-dockview"),pi(Se,w));const Pe=document.documentElement.getAttribute("data-theme");Pe&&xe.documentElement.setAttribute("data-theme",Pe),xe.documentElement.style.colorScheme=Pe==="light"?"light":"dark",xe.body.className=document.body.className;const He=document.documentElement.getAttribute("style");He?xe.documentElement.setAttribute("style",He):xe.documentElement.removeAttribute("style")}catch{}},[w]),ie=l.useCallback(G=>{const oe=N.current;if(!oe)return;const de=oe.getPanel(G);de&&oe.addPopoutGroup(de,{popoutUrl:"/popout.html",onDidOpen:({window:xe})=>{z(xe),Z();const Se=L.get(G);xe.document.title=Se?`${kt(Se)} — ADHDev`:"ADHDev — Popout"}})},[L,z]),Ce=l.useCallback(G=>{const oe=N.current,de=oe==null?void 0:oe.getPanel(G);if(!oe||!de)return;const xe=oe.groups.filter(Se=>{var Pe;try{return((Pe=Se.element)==null?void 0:Pe.ownerDocument)===document}catch{return!0}});xe.length>0?de.api.moveTo({group:xe[0],position:"center"}):de.api.moveTo({position:"center"}),de.api.setActive()},[]),me=l.useCallback(G=>{var xe;const oe=N.current;if(!oe)return!1;const de=oe.getPanel(G);if(!de)return!1;try{return((xe=de.group.element)==null?void 0:xe.ownerDocument)!==document}catch{return!1}},[]),O=l.useCallback(G=>{me(G)&&Ce(G),u(G)},[me,Ce,u]),Y=l.useCallback(G=>{const oe=N.current,de=oe==null?void 0:oe.getPanel(G);!oe||!de||oe.addFloatingGroup(de,{width:600,height:500})},[]),X=l.useCallback(G=>{var de;const oe=(de=N.current)==null?void 0:de.getPanel(G);if(!oe)return!1;try{return oe.group.model.location.type==="floating"}catch{return!1}},[]),Q=l.useCallback(()=>{var oe,de;const G=(de=(oe=N.current)==null?void 0:oe.activePanel)==null?void 0:de.id;return!G||fs(G)?null:L.has(G)?G:null},[L]),ve=l.useCallback(G=>{const oe=N.current,de=oe==null?void 0:oe.getPanel(G);if(!oe||!de)return;const xe=oe.groups.filter(Se=>{try{return Se.model.location.type==="grid"}catch{return!0}});xe.length>0?de.api.moveTo({group:xe[0],position:"center"}):de.api.moveTo({position:"center"}),de.api.setActive()},[]),he=l.useCallback(()=>{var Pe;const G=N.current;if(!G)return;const de=G.groups.filter(He=>{var Ee;try{return((Ee=He.element)==null?void 0:Ee.ownerDocument)===document&&He.model.location.type==="grid"}catch{return!1}})[0]||null,xe=[...G.panels];for(const He of xe){const Ee=(Pe=He.group.element)==null?void 0:Pe.ownerDocument,Je=He.group.model.location.type;Ee===document&&Je==="grid"||(de&&de.id!==He.group.id?He.api.moveTo({group:de,position:"center"}):He.api.moveTo({position:"center"}))}const Se=G.activePanel;Se&&(Se.group.model.openPanel(Se),Se.api.setActive()),ui(document)},[]),Z=l.useCallback(()=>{var oe,de;const G=N.current;if(G)for(const xe of G.groups){const Se=(oe=xe.element)==null?void 0:oe.ownerDocument;if(!Se||Se===document)continue;const Pe=Se.getElementById("dv-popout-window");if(!(Pe instanceof HTMLElement))continue;let He=null,Ee=Se.title||"ADHDev",Je="Popout workspace";const st=xe.activePanel;if(st)if(He=st.id,fs(st.id)){const Be=((de=st.params)==null?void 0:de.routeId)||st.id.slice(7),ge=ws([...L.values()],Be);Ee=ah(ge),Je=ge!=null&&ge.machineName?`Remote view · ${ge.machineName}`:"Remote view"}else{const Be=L.get(st.id);Ee=Be?kt(Be):st.title||st.id,Je=Be?Sn(Be):"Dockview panel"}Se.title=`${Ee} — ADHDev`;const Ze=Array.from(Se.querySelectorAll("#adhdev-popout-header"));for(const Be of Ze)Be.remove();const Ue=Se.createElement("div");Ue.id="adhdev-popout-header",Se.body.appendChild(Ue),Ue.setAttribute("style",["position:absolute","top:0","left:0","right:0","height:52px","display:flex","align-items:center","justify-content:space-between","gap:12px","padding:0 14px","box-sizing:border-box","background:var(--surface-secondary)","border-bottom:1px solid var(--border-subtle)","z-index:5","backdrop-filter:blur(14px)"].join(";")),Ue.innerHTML=`
|
|
67
67
|
<div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
|
|
68
68
|
<div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
|
|
@@ -111,11 +111,11 @@ This will disconnect CDP and optionally kill the process.`))try{const L=await n(
|
|
|
111
111
|
|
|
112
112
|
`)}function fL(e,t){return t==="issues"?e.filter(n=>n.level==="warn"||n.level==="error"):t==="info"?e.filter(n=>n.level!=="debug"):e}function gL(e,t){return t==="issues"?e.filter(n=>n.level==="warn"||n.level==="error"):t==="info"?e.filter(n=>n.level!=="debug"):e}function bL({daemonLogs:e,daemonRawText:t,daemonLogKind:n,debugTrace:a,webEvents:r,traceCategory:o,quickFilter:i,searchQuery:c,daemonLoading:d,traceLoading:p,daemonFetchError:u,traceFetchError:m}){const f=KI(a,o),g=QI(e,c),k=ZI(t,c),h=eL(f,c),b=tL(r,c),S=fL(g,i),x=i==="all"?k:[],y=gL(h,i),C=i==="issues"?[]:b,v=sL({daemonLogs:g,daemonRawLines:k,trace:h,webEvents:b}),w=dL({daemonLogs:S,daemonRawLines:x,trace:y,webEvents:C}),j=pL(w),N=rL({daemonLoading:d,traceLoading:p,daemonFetchError:u,traceFetchError:m,daemonLogKind:n,daemonLogsCount:g.length,daemonRawLineCount:k.length,traceCount:h.length,webEventCount:b.length});return{filteredDaemonLogs:g,filteredDaemonRawLines:k,filteredTraceEntries:h,filteredWebEvents:b,visibleDaemonLogs:S,visibleDaemonRawLines:x,visibleTraceEntries:y,visibleWebEvents:C,quickFilterCounts:v,diagnosticEvents:w,diagnosticsSummary:j,sourceStates:N}}function xL(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function sg(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function Sl(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 Ii(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 Dc(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function vL({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Sl(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:sg(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:Dc(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 yL({quickFilter:e,quickFilterCounts:t,searchQuery:n,autoRefresh:a,onQuickFilterChange:r,onSearchQueryChange:o,onCopyDiagnostics:i,onCopyVisible:c,onToggleAutoRefresh:d,onRefresh:p,onClear:u}){return s.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"View"}),s.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${t.info})`},{id:"issues",label:`Issues (${t.issues})`},{id:"all",label:`All (${t.all})`}].map(m=>s.jsx("button",{type:"button",onClick:()=>r(m.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===m.id?"bg-accent-primary/15 text-accent-primary border border-accent-primary/30":"text-text-secondary hover:text-text-primary"}`,children:m.label},m.id))}),s.jsx("input",{value:n,onChange:m=>o(m.target.value),placeholder:"Search diagnostics…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{onClick:i,className:"machine-btn",children:"Copy diagnostics"}),s.jsx("button",{onClick:c,className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:d,className:`machine-btn ${a?"text-green-500 border-green-500/30":""}`,children:a?"Pause":"Resume"}),s.jsx("button",{onClick:p,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:u,className:"machine-btn",children:"Clear"})]})]})}function wL({logLevel:e,traceCategory:t,onLogLevelChange:n,onTraceCategoryChange:a}){return s.jsx(vs,{padding:"sm",children:s.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wider text-text-muted font-semibold",children:"Advanced source scope"}),["debug","info","warn","error"].map(r=>s.jsxs("button",{onClick:()=>n(r),className:`machine-btn text-[10px] px-2 py-0.5 ${e===r?"bg-accent-primary/15 border-accent-primary/40 text-accent-primary":""}`,children:["Daemon ",r.toUpperCase(),"+"]},r))]}),s.jsx("div",{className:"flex flex-wrap gap-2 items-center",children:qI.map(r=>s.jsx("button",{onClick:()=>a(r.value),className:`machine-btn text-[10px] px-2 py-0.5 ${t===r.value?"bg-accent-primary/15 border-accent-primary/40 text-accent-primary":""}`,children:r.label},r.value))})]})})}function kL({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:n,searchQuery:a,lastUpdatedAt:r,autoRefresh:o,daemonFetchError:i,traceFetchError:c}){var u,m;const d=((u=e.latestIssue)==null?void 0:u.severity)==="error"?"danger":((m=e.latestIssue)==null?void 0:m.severity)==="warn"?"warning":"good",p=i||c?"danger":o?"good":"neutral";return s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${Ii(e.issueCount>0?"warning":"good")}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Diagnostics timeline"}),s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[t," visible event(s) · ",e.issueCount," issue signal(s)"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:a.trim()?`Filtered by “${a.trim()}”`:"Daemon, trace, and browser signals merged by time"})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${Ii(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:[Dc(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:sg(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 ${Ii(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: ",xL(r)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:n.map(f=>s.jsxs("div",{children:[f.label,": ",f.status]},f.id))})]})]})}function SL({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()," · ",Dc(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function CL({streams:e,sectionsOpen:t,setSectionsOpen:n,diagnosticEvents:a,visibleDaemonLogs:r,visibleDaemonRawLines:o,visibleTraceEntries:i,visibleWebEvents:c,quickFilter:d,searchQuery:p}){return s.jsxs("div",{className:"grid gap-3",children:[s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>n(u=>({...u,timeline:!u.timeline})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Unified timeline"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[a.length," visible diagnostic event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.timeline?"Hide":"Show"})]}),t.timeline&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[180px] max-h-[440px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[(e.daemonLoading||e.traceLoading)&&a.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&a.length===0&&s.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&s.jsxs("div",{children:["Daemon logs: ",e.daemonFetchError]}),e.traceFetchError&&s.jsxs("div",{children:["Daemon trace: ",e.traceFetchError]})]}),!e.daemonLoading&&!e.traceLoading&&a.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),a.map(u=>s.jsx(vL,{event:u},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>n(u=>({...u,daemon:!u.daemon})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · daemon logs"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:e.daemonLogKind==="text"?`${o.length} visible raw line(s) from file fallback`:`${r.length} visible structured line(s)`})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.daemon?"Hide":"Show"})]}),t.daemon&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.daemonLoading&&r.length===0&&o.length===0&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),e.daemonLogKind==="text"&&o.length===0&&e.daemonRawText&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:d==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),e.daemonLogKind==="structured"&&r.length===0&&e.daemonLogs.length>0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),e.daemonLogKind==="text"&&o.map((u,m)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:u},`raw-${m}`)),e.daemonLogKind!=="text"&&r.map((u,m)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${Sl(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 ${Sl(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:oa(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:oa(u.payload,360)||"No payload"})]},u.id))]})]})]})}function jL({machineId:e,sendDaemonCommand:t}){const n=aL({machineId:e,sendDaemonCommand:t}),[a,r]=l.useState("info"),[o,i]=l.useState(""),[c,d]=l.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),p=l.useRef(null),u=l.useRef(!1),m=l.useMemo(()=>bL({daemonLogs:n.daemonLogs,daemonRawText:n.daemonRawText,daemonLogKind:n.daemonLogKind,debugTrace:n.debugTrace,webEvents:n.webEvents,traceCategory:n.traceCategory,quickFilter:a,searchQuery:o,daemonLoading:n.daemonLoading,traceLoading:n.traceLoading,daemonFetchError:n.daemonFetchError,traceFetchError:n.traceFetchError}),[a,o,n.daemonFetchError,n.daemonLoading,n.daemonLogKind,n.daemonLogs,n.daemonRawText,n.debugTrace,n.traceCategory,n.traceFetchError,n.traceLoading,n.webEvents]);l.useEffect(()=>{if(n.autoRefresh&&m.diagnosticEvents.length>0){const k=u.current?"smooth":"instant";setTimeout(()=>{var h;(h=p.current)==null||h.scrollIntoView({behavior:k}),u.current=!0},50)}},[m.diagnosticEvents.length,n.autoRefresh]);const f=l.useCallback(async()=>{var h;const k=nL({daemonLogs:m.visibleDaemonLogs,daemonRawLines:m.visibleDaemonRawLines,trace:m.visibleTraceEntries,webEvents:m.visibleWebEvents});if(!k.trim()){ft.showToast("No visible logs to copy.","info");return}try{await((h=navigator.clipboard)==null?void 0:h.writeText(k)),ft.showToast("Copied visible logs to clipboard.","success")}catch(b){ft.showToast(b instanceof Error?b.message:"Could not copy visible logs","warning")}},[m.visibleDaemonLogs,m.visibleDaemonRawLines,m.visibleTraceEntries,m.visibleWebEvents]),g=l.useCallback(async()=>{var h;const k=hL({events:m.diagnosticEvents,summary:m.diagnosticsSummary,sources:m.sourceStates});try{await((h=navigator.clipboard)==null?void 0:h.writeText(k)),ft.showToast("Copied diagnostic bundle to clipboard.","success")}catch(b){ft.showToast(b instanceof Error?b.message:"Could not copy diagnostic bundle","warning")}},[m.diagnosticEvents,m.diagnosticsSummary,m.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(yL,{quickFilter:a,quickFilterCounts:m.quickFilterCounts,searchQuery:o,autoRefresh:n.autoRefresh,onQuickFilterChange:r,onSearchQueryChange:i,onCopyDiagnostics:()=>{g()},onCopyVisible:()=>{f()},onToggleAutoRefresh:()=>n.setAutoRefresh(k=>!k),onRefresh:n.refresh,onClear:n.clear}),s.jsx(wL,{logLevel:n.logLevel,traceCategory:n.traceCategory,onLogLevelChange:n.setLogLevel,onTraceCategoryChange:n.setTraceCategory}),s.jsx(kL,{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(SL,{patterns:m.diagnosticsSummary.repeatedPatterns}),s.jsx(CL,{streams:n,sectionsOpen:c,setSectionsOpen:d,diagnosticEvents:m.diagnosticEvents,visibleDaemonLogs:m.visibleDaemonLogs,visibleDaemonRawLines:m.visibleDaemonRawLines,visibleTraceEntries:m.visibleTraceEntries,visibleWebEvents:m.visibleWebEvents,quickFilter:a,searchQuery:o}),s.jsx("div",{ref:p})]})}function NL(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 ng(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 AL(e){var r;const t=[],n=[],a=[];for(const o of e||[]){const i=String((o==null?void 0:o.lifecycle)||"").trim(),c=ng((o==null?void 0:o.meta)||void 0),d=((r=o==null?void 0:o.meta)==null?void 0:r.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(i)?t.push(o):(i==="stopped"||i==="failed")&&(d||c)?n.push(o):a.push(o)}return{liveRuntimes:t,recoverySnapshots:n,inactiveRecords:a}}function TL(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Li(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 Ri(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Ei(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Xu(e){if(!e)return"unknown";const t=Date.now()-e,n=Math.max(0,Math.round(t/1e3));if(n<60)return`${n}s ago`;const a=Math.round(n/60);if(a<60)return`${a}m ago`;const r=Math.round(a/60);return r<48?`${r}h ago`:`${Math.round(r/24)}d ago`}function ML(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function PL(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 DL(e){var n;const t=new Map;for(const a of e){if(!["starting","running","stopping","interrupted"].includes(a.lifecycle))continue;const r=typeof((n=a.meta)==null?void 0:n.providerSessionId)=="string"?String(a.meta.providerSessionId).trim():"";if(!r)continue;const o=`${a.providerType}::${a.workspace}::${r}`;t.set(o,(t.get(o)||0)+1)}return Array.from(t.values()).filter(a=>a>1).length}function IL({machineId:e,cliSessions:t,sendDaemonCommand:n}){const[a,r]=l.useState(""),[o,i]=l.useState(null),[c,d]=l.useState(!1),p=Q1(e,{enabled:!!e,includeSessions:!0,limit:Cd,intervalMs:XS}),u=p.diagnostics,m=p.loading,f=p.applyDiagnostics,g=l.useMemo(()=>NL({diagnostics:u,loading:m,refreshing:c,error:a}),[u,m,c,a]),k=l.useMemo(()=>new Map(t.map(I=>[I.sessionId||I.id,I])),[t]),h=l.useCallback(async()=>{if(e){d(!0);try{const I=await n(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Cd}),P=Ri(I);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Could not load hosted runtime diagnostics");f(P.diagnostics||P.result||null),r("")}catch(I){const P=I instanceof Error?I.message:"Could not load hosted runtime diagnostics";r(P)}finally{d(!1)}}},[f,e,n]);l.useEffect(()=>{!e||u||m||c||h()},[u,m,e,h,c]);const b=l.useCallback(async(I,P)=>{const M=`${I}:${P.sessionId}`;if(!(I==="session_host_stop_session"&&!window.confirm(`Stop ${P.displayName}?
|
|
113
113
|
This will terminate the hosted runtime.`))){i(M);try{const E=await n(e,I,{sessionId:P.sessionId}),D=Ri(E);if(!(D!=null&&D.success))throw new Error((D==null?void 0:D.error)||"Session host action failed");const W=I==="session_host_resume_session"?"resumed":I==="session_host_restart_session"?"restarted":"stopped";ft.showToast(`Session host ${W}: ${P.displayName}`,"success"),await h()}catch(E){const D=E instanceof Error?E.message:"Session host action failed";ft.showToast(D,"warning"),r(D)}finally{i(E=>E===M?null:E)}}},[e,h,n]),S=l.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
|
|
114
|
-
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){i("session_host_prune_duplicate_sessions");try{const P=await n(e,"session_host_prune_duplicate_sessions",{}),M=Ri(P);if(!(M!=null&&M.success))throw new Error((M==null?void 0:M.error)||"Duplicate prune failed");const E=M.result||{},D=Array.isArray(E.prunedSessionIds)?E.prunedSessionIds.length:0,W=typeof E.duplicateGroupCount=="number"?E.duplicateGroupCount:0;ft.showToast(`Pruned ${D} duplicate runtime(s) across ${W} group(s)`,"success"),await h()}catch(P){const M=P instanceof Error?P.message:"Duplicate prune failed";ft.showToast(M,"warning"),r(M)}finally{i(P=>P==="session_host_prune_duplicate_sessions"?null:P)}}},[e,h,n]),x=l.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((I,P)=>(P.lastActivityAt||0)-(I.lastActivityAt||0)),[u==null?void 0:u.sessions]),y=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)||[]}:AL(x),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,x]),C=y.liveRuntimes,v=y.recoverySnapshots,w=y.inactiveRecords,j=l.useMemo(()=>DL(C),[C]),N=l.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),A=l.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(I=>I.level==="warn"||I.level==="error")||null,[u==null?void 0:u.recentLogs]),T=(I,P)=>{var L;const M=o===`session_host_resume_session:${I.sessionId}`,E=o===`session_host_restart_session:${I.sessionId}`,D=o===`session_host_stop_session:${I.sessionId}`,W=ng(I.meta),R=k.get(I.sessionId),B=I.attachedClients.length===1?"1 client":`${I.attachedClients.length} clients`,_=P==="recovery"?"Recover":"Resume",H=TL(P);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:I.displayName||(R==null?void 0:R.cliName)||I.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${PL(I.lifecycle)}`,children:I.lifecycle}),W&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:W})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:I.workspaceLabel||(R==null?void 0:R.runtimeWorkspaceLabel)||I.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:I.runtimeKey}),I.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",I.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((L=I.writeOwner)==null?void 0:L.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:ML(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(mb,{size:11})," ",B]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",Xu(I.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",H]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[P==="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:()=>{b("session_host_resume_session",I)},children:M?`${_}ing…`:_}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{b("session_host_restart_session",I)},children:E?"Restarting…":"Restart"}),P==="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:()=>{b("session_host_stop_session",I)},children:D?"Stopping…":"Stop"})]})]})},I.sessionId)};return s.jsxs(vs,{padding:"lg",className:"mb-5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(nn,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Mj()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[j>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{S()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${j})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${g.toneClass}`,children:g.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{h()},disabled:m||c,children:[s.jsx(po,{size:13}),m||c?"Refreshing…":"Refresh"]})]})]}),a&&!u&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(Ls,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:a})]})]})}),u&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:v.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:Xu(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Ei(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(Ls,{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:[Ei(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(Bl,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Li("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(nn,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Li("recovery")}),v.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):s.jsx("div",{className:"space-y-2",children:v.map(I=>T(I,"recovery"))})]}),w.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:Li("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:w.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"}),N.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:N.map(I=>{var M;const P=x.find(E=>E.sessionId===I.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(P==null?void 0:P.displayName)||((M=k.get(I.sessionId))==null?void 0:M.cliName)||I.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[I.action,I.lifecycle?` · ${I.lifecycle}`:"",I.detail?` · ${I.detail}`:"",I.error?` · ${I.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${I.success===!1?"text-red-300":"text-text-secondary"}`,children:Ei(I.timestamp)})]},`${I.sessionId}:${I.timestamp}:${I.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:u.endpoint||"unknown"}),a?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",a]}):null]})]})]})}function LL({machine:e,launchPick:t,actions:n}){const{t:a}=ke("common"),{runLaunchCliCore:r,setLaunchPick:o}=n;return l.useEffect(()=>{const i=c=>{c.key==="Escape"&&o(null)};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[o]),s.jsx(Vt,{children:s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",onClick:()=>o(null),children:s.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",onClick:i=>i.stopPropagation(),children:[s.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),s.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),s.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?s.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(i=>s.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-accent-primary/10 transition-colors",onClick:()=>{o(null),r({cliType:t.cliType,workspaceId:i.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{o(null),r({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:a("newSession.defaultWorkspace")}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{o(null),r({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:a("newSession.homeDirectory")}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>o(null),children:"Cancel"})]})]})})})}function RL(e,t){const n=C1(e),a=Js(e,t),r=jo(e,a),o=Da(e,a),i=Ch(e,{targetVersion:a,required:o,fallback:"Update daemon"});return r?{visible:!0,showButton:!0,title:o?"Daemon update required":"Version mismatch detected",description:o?"This machine is on an incompatible daemon version. Update it before starting more sessions.":n==="preview"?"This machine can be upgraded to the current preview daemon without opening a remote shell.":"This machine is running a different daemon version than the current app. Update it before starting more sessions.",buttonLabel:i,targetVersion:a,channel:n,required:o,tone:"warn"}:n==="preview"?{visible:!0,showButton:!1,title:a?"Preview daemon is up to date":"Preview update status unknown",description:a?"This machine is already on the current preview daemon target.":"The app is connected to preview, but the server did not report a preview target version yet.",buttonLabel:i,targetVersion:a,channel:n,required:!1,tone:a?"good":"info"}:{visible:!1,showButton:!1,title:"",description:"",buttonLabel:i,targetVersion:a,channel:n,required:!1,tone:"info"}}function _i({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 Hi({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 EL({machineEntry:e,providers:t,recentLaunches:n,currentConversations:a,onUpgradeDaemon:r,onOpenRecent:o,onOpenConversation:i}){const{t:c}=ke("common"),d=a.slice(0,6),p=n.slice(0,4),m=RL(e,"1.0.56");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(_i,{icon:s.jsx(Is,{size:13}),children:c("machine.commandCenter.currentChats")}),s.jsx(Hi,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(f=>{const g=fl(f);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>i(f),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate min-w-0 group-hover:text-accent-primary transition-colors",children:kt(f)}),g>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:za(g)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:na(f)})]},f.tabKey)})})})]}),p.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(_i,{icon:s.jsx(Pp,{size:13}),children:c("machine.commandCenter.recentLaunches")}),s.jsx(Hi,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:p.map(f=>{const{metaText:g,updatedLabel:k}=Yh(f);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>o(f),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate min-w-0 group-hover:text-accent-primary transition-colors",children:f.label}),k&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:k})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:g})]},f.id)})})})]}),m.visible&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(_i,{icon:s.jsx(Ls,{size:13}),children:c("machine.commandCenter.daemonUpdate")}),s.jsx(Hi,{className:m.tone==="good"?"border-emerald-500/20 bg-emerald-500/5":m.tone==="info"?"border-sky-500/20 bg-sky-500/5":"border-amber-500/20 bg-amber-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:m.title}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[m.description,m.targetVersion&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",m.targetVersion,m.channel?` (${m.channel})`:""]})]}),m.showButton?s.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:r,children:[s.jsx(po,{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 _L({machineId:e,machine:t,ideSessions:n,cliSessions:a,acpSessions:r,actions:o,sendDaemonCommand:i}){const{workspaceBusy:c,handleWorkspaceAdd:d,handleWorkspaceRemove:p,handleWorkspaceSetDefault:u}=o,{t:m}=ke("common"),[f,g]=l.useState(!1),[k,h]=l.useState(""),[b,S]=l.useState([]),[x,y]=l.useState(!1),[C,v]=l.useState(""),w=l.useCallback(async N=>{y(!0),v("");try{const A=await fc(i,e,N);h(A.path),S(A.directories)}catch(A){v(A instanceof Error?A.message:"Could not load folder")}finally{y(!1)}},[e,i]),j=l.useCallback(()=>{g(!0);const N=[...n.map(T=>T.workspace),...a.map(T=>T.workspace),...r.map(T=>T.workspace)],A=hc(t.platform,mc(N,t.defaultWorkspacePath,(t.workspaces||[]).map(T=>T.path)));w(A)},[r,a,n,w,t.defaultWorkspacePath,t.platform,t.workspaces]);return s.jsxs(s.Fragment,{children:[s.jsxs(vs,{padding:"lg",className:"mb-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(Tn,{size:14})," Workspaces"]}),s.jsx("button",{type:"button",className:"btn bg-bg-glass hover:bg-bg-glass-hover text-text-muted hover:text-text-primary px-3 py-1 rounded transition-colors text-xs",disabled:c,onClick:j,children:"+ Add workspace"})]}),(t.workspaces||[]).length===0?s.jsxs("div",{className:"text-[11px] text-text-muted py-4 text-center",children:["No saved workspaces yet. Click ",s.jsx("span",{className:"text-text-secondary",children:"+ Add workspace"})," to pick a folder."]}):s.jsx("ul",{className:"space-y-1.5 max-h-72 overflow-y-auto",children:(t.workspaces||[]).map(N=>{const A=N.id===t.defaultWorkspaceId;return s.jsxs("li",{className:`flex items-start gap-2 text-[11px] rounded-lg border px-2.5 py-2 transition-colors ${A?"border-yellow-500/30 bg-yellow-500/[0.05]":"border-border-subtle bg-bg-primary"}`,children:[s.jsx("button",{type:"button",title:A?"Default workspace — click to unset":"Set as default workspace",disabled:c,onClick:()=>void u(A?null:N.id),className:`text-base leading-none shrink-0 transition-colors ${A?"text-yellow-400 hover:text-yellow-300":"text-text-muted/40 hover:text-yellow-400"}`,children:"★"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"font-medium text-text-primary truncate",children:um(N.path,N.label)}),s.jsx("div",{className:"font-mono text-text-muted truncate text-[10px]",title:N.path,children:N.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void p(N.id),children:m("machine.managedWorkspaces.remove")})]},N.id)})})]}),f&&s.jsx(bc,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:k,directories:b,busy:x,error:C,confirmLabel:"Add workspace",onClose:()=>g(!1),onNavigate:N=>{w(N)},onConfirm:N=>{(async()=>{if(!N)return;await d(N)&&g(!1)})()}})]})}function HL({machine:e,machineId:t,ideSessions:n,cliSessions:a,acpSessions:r,actions:o,sendDaemonCommand:i}){return s.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[s.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-border-subtle mb-4",children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspaces"}),s.jsx("div",{className:"text-sm text-text-secondary",children:'Save folders as workspaces on this machine. Use the dashboard "+" button to launch a session.'})]}),i&&s.jsx(_L,{machineId:t,machine:e,ideSessions:n,cliSessions:a,acpSessions:r,actions:o,sendDaemonCommand:i})]})}const $L="activate_provider_updates";function ag(e){if(!e||typeof e!="object")return;const t=e;return"result"in t&&t.result&&typeof t.result=="object"?t.result:t}function FL(e){var r;const t=ag(e);if(!t)return{ok:!1,error:"empty response"};if(t.success===!1)return{ok:!1,error:typeof t.error=="string"&&t.error.trim()?t.error:"sync failed"};const n=t.channelSync;if(n&&typeof n=="object"&&n.status==="error"){const o=Array.isArray(n.errors)?(r=n.errors[0])==null?void 0:r.message:void 0;return{ok:!1,error:typeof o=="string"&&o.trim()?o:"channel sync failed"}}return{ok:!0,activatedCount:Array.isArray(t.activated)?t.activated.length:0}}function BL(e){const t=[];for(const n of(e==null?void 0:e.newTypes)??[])typeof n=="string"&&n.trim()&&t.push(n.trim());return t}function WL({onNicknameSynced:e}={}){var se,te,ue,ye,Me,re,ce,Ae,be,we,_e;const{t}=ke("common"),{id:n}=Wg(),a=ia(),r=Rl(),{sendCommand:o}=St(),i=da(),c=Mh(),d=Xm(),p=d.ides||[],u=d.initialLoaded??!0,m=p.find(U=>U.id===n&&U.type==="adhdev-daemon"),f=p.some(U=>U.type==="adhdev-daemon"),g=n?(se=d.connectionRetryStatuses)==null?void 0:se[n]:void 0,k=!!(g!=null&&g.blocked),[h,b]=l.useState("workspace"),[S,x]=l.useState(null),[y,C]=l.useState(!1),[v,w]=l.useState(0),[j,N]=l.useState(null);l.useCallback((U,Ne)=>{N({daemonId:U,workspace:Ne})},[]);const[,A]=l.useState("ide"),T=l.useRef(null),[I,P]=l.useState(null),M=l.useRef("__home__"),[E,D]=l.useState("__home__"),[W,R]=l.useState(!1),B=l.useRef(null);l.useEffect(()=>{!n||!m||!(!m.workspaces||!m.availableProviders||!m.detectedIdes||!m.recentLaunches)||i(n,{minFreshMs:3e4}).catch(()=>{})},[i,m,n]);const _=l.useCallback(U=>{const Ne=ag(U),Ie=Ne==null?void 0:Ne.providerChannelStaleness;Ie&&!Ie.error&&x({staleTypes:Array.isArray(Ie.staleTypes)?Ie.staleTypes:[],newTypes:Array.isArray(Ie.newTypes)?Ie.newTypes:[]})},[]);l.useEffect(()=>{if(!n||!m)return;let U=!1;return(async()=>{try{const Ne=await o(n,"get_status_metadata");U||_(Ne)}catch{}})(),()=>{U=!0}},[_,n,m==null?void 0:m.id,o]);const H=l.useCallback(async U=>{if(U.preventDefault(),U.stopPropagation(),!(!n||y)){b("providers"),C(!0);try{const Ne=BL(S),Ie=await o(n,$L,Ne.length>0?{types:Ne}:{}),We=FL(Ie);"error"in We?ft.showToast(t("machine.detail.providerSyncFailed",{error:We.error}),"warning"):ft.showToast(We.activatedCount>0?t("machine.detail.providerSyncSuccess",{count:We.activatedCount}):t("machine.detail.providerSyncAlreadyCurrent"),"success"),w(Xe=>Xe+1);try{_(await o(n,"get_status_metadata"))}catch{}}catch(Ne){const Ie=Ne instanceof Error?Ne.message:String(Ne);ft.showToast(t("machine.detail.providerSyncFailed",{error:Ie}),"warning")}finally{C(!1)}}},[_,n,S,y,o,t]);l.useEffect(()=>{if(!n||!m||h!=="overview"&&h!=="providers")return;const U=m.machine;(typeof(U==null?void 0:U.cpus)!="number"||typeof(U==null?void 0:U.totalMem)!="number"||typeof(U==null?void 0:U.arch)!="string"||typeof(U==null?void 0:U.release)!="string"||h==="providers"&&!(U!=null&&U.quota))&&c(n,{minFreshMs:3e4}).catch(()=>{})},[h,c,m,n]),Y1(n&&h==="overview"?[n]:[],{enabled:h==="overview",intervalMs:YS});const L=()=>{if(f){a("/dashboard",{state:{mobileSection:"machines"}});return}a("/machines")},F=MI({machineId:n,registeredMachineId:(m==null?void 0:m.machineId)||null,sendDaemonCommand:o,onNicknameSynced:e,logsEndRef:B});l.useEffect(()=>ft.onToast(Ne=>{d.setToasts(We=>{if(We.some(J=>J.message===Ne.message&&Ne.timestamp-J.timestamp<3e3))return We;const et={id:Ne.id,message:Ne.message,type:Ne.type,timestamp:Ne.timestamp,targetKey:Ne.targetKey,actions:Ne.actions};return[...We.slice(-4),et]});const Ie=Ne.duration||5e3;setTimeout(()=>d.setToasts(We=>We.filter(Xe=>Xe.id!==Ne.id)),Ie)}),[d]);const $=(m==null?void 0:m.availableProviders)||[],K={};for(const U of $)K[U.type]=U.icon;const z=m?{id:m.id,hostname:pm(m,{fallbackId:m.id}),platform:((te=m.machine)==null?void 0:te.platform)||"unknown",arch:((ue=m.machine)==null?void 0:ue.arch)||"",cpus:((ye=m.machine)==null?void 0:ye.cpus)||0,totalMem:((Me=m.machine)==null?void 0:Me.totalMem)||0,freeMem:(re=m.machine)==null?void 0:re.freeMem,availableMem:(ce=m.machine)==null?void 0:ce.availableMem,loadavg:(Ae=m.machine)==null?void 0:Ae.loadavg,uptime:(be=m.machine)==null?void 0:be.uptime,release:((we=m.machine)==null?void 0:we.release)||"",cdpConnected:!!m.cdpConnected,machineNickname:m.machineNickname||null,...(_e=m.machine)!=null&&_e.quota?{quota:m.machine.quota}:{},p2p:m.p2p?{screenshotActive:!1,...m.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:m.detectedIdes||[],workspaces:m.workspaces||[],defaultWorkspaceId:m.defaultWorkspaceId??m.activeWorkspaceId??null,defaultWorkspacePath:m.defaultWorkspacePath??m.activeWorkspacePath??null}:null,ne=p.filter(U=>U.daemonId===n&&U.type!=="adhdev-daemon").filter(U=>!Fa(U)&&!Xn(U)).map(U=>({id:U.id,sessionId:U.sessionId,type:U.type,version:U.version||"",instanceId:U.instanceId||"",status:U.status,workspace:U.workspace||null,terminals:U.terminals||0,aiAgents:nk(U.aiAgents||(U.agents||[]).map(Ne=>({id:Ne.name,name:Ne.name,status:Ne.status,version:Ne.version}))),activeChat:U.activeChat||null,chats:U.chats||[],childSessions:U.childSessions||[],cdpConnected:U.cdpConnected||!1,daemonId:n,lastMessageAt:U.lastMessageAt})),ie=p.filter(U=>U.daemonId===n&&Fa(U)).map(U=>({id:U.id,sessionId:U.sessionId,type:U.type,cliName:U.cliName||U.type,status:U.status,workspace:U.workspace||"",activeChat:U.activeChat||null,providerSessionId:U.providerSessionId,mode:U.mode,runtimeKey:U.runtimeKey,runtimeDisplayName:U.runtimeDisplayName,runtimeWorkspaceLabel:U.runtimeWorkspaceLabel,runtimeWriteOwner:U.runtimeWriteOwner||null,runtimeAttachedClients:U.runtimeAttachedClients||[],daemonId:n,lastMessageAt:U.lastMessageAt})),Ce=p.filter(U=>U.daemonId===n&&Xn(U)).map(U=>({id:U.id,sessionId:U.sessionId,type:U.type,acpName:U.cliName||U.type,status:U.status,workspace:U.workspace||"",activeChat:U.activeChat||null,providerSessionId:U.providerSessionId,daemonId:n,lastMessageAt:U.lastMessageAt})),me=m?ds(m,{fallbackId:n}):"",O="workspace",Y=r.state,X=Y==null?void 0:Y.initialMachineTab,Q=Y==null?void 0:Y.initialWorkspaceCategory;Y==null||Y.initialWorkspaceId,Y==null||Y.initialWorkspacePath;const ve=X==="ides"||X==="clis"||X==="acps"?"workspace":X||O,he=X==="ides"?"ide":X==="clis"?"cli":X==="acps"?"acp":Q,Z=[...ne.map(U=>{var Ne;return{id:`ide:${U.type}:${U.workspace||""}`,label:((Ne=U.activeChat)==null?void 0:Ne.title)||U.type,kind:"ide",providerType:U.type,subtitle:U.workspace||void 0,workspace:U.workspace||void 0,lastLaunchedAt:U.lastMessageAt||0}}),...ie.map(U=>{var Ne;return{id:`cli:${U.type}:${U.workspace||""}`,label:((Ne=U.activeChat)==null?void 0:Ne.title)||U.cliName,kind:"cli",providerType:U.type,providerSessionId:U.providerSessionId,subtitle:U.workspace||void 0,workspace:U.workspace||void 0,lastLaunchedAt:U.lastMessageAt||0}}),...Ce.map(U=>{var Ne;return{id:`acp:${U.type}:${U.workspace||""}`,label:((Ne=U.activeChat)==null?void 0:Ne.title)||U.acpName,kind:"acp",providerType:U.type,providerSessionId:U.providerSessionId,subtitle:Mn(U.summaryMetadata)||U.workspace||void 0,workspace:U.workspace||void 0,lastLaunchedAt:U.lastMessageAt||0}})].sort((U,Ne)=>(Ne.lastLaunchedAt||0)-(U.lastLaunchedAt||0)),fe=((m==null?void 0:m.recentLaunches)||[]).length>0?((m==null?void 0:m.recentLaunches)||[]).map(U=>({id:U.id,label:U.title||U.providerName||U.providerType,kind:U.kind,providerType:U.providerType,providerSessionId:U.providerSessionId,subtitle:Mn(U.summaryMetadata)||U.workspace||void 0,workspace:U.workspace,summaryMetadata:U.summaryMetadata,lastLaunchedAt:U.lastLaunchedAt})):Z,V=l.useMemo(()=>{var Ne;const U=((Ne=d.connectionStates)==null?void 0:Ne[n||""])||void 0;return p.filter(Ie=>Ie.daemonId===n&&Ie.type!=="adhdev-daemon").flatMap(Ie=>ic(Ie,{connectionStates:n&&U?{[n]:U}:void 0,defaultConnectionState:U})).filter(Ie=>!(Ie.transport==="pty"&&Ie.mode==="terminal")).sort((Ie,We)=>fl(We)-fl(Ie))},[p,d.connectionStates,n]),q=l.useCallback(U=>{const Ne=Oh(U);Ne&&a(Wa(Ne))},[a]),ee=l.useCallback(()=>{T.current&&(R(!0),T.current().finally(()=>{T.current=null,R(!1),P(null)}))},[]),pe=l.useCallback(U=>{if(!z)return;const{options:Ne,selectedKey:Ie}=Vh({machine:z,currentWorkspacePath:U.workspace,homeLabel:t("newSession.homeDirectory"),homeDescription:t("newSession.launchWithoutWorkspace")}),We=async()=>{A(U.kind),b("workspace")};T.current=async()=>{const Xe=Ne.find(Le=>Le.key===M.current),et=(Xe==null?void 0:Xe.workspacePath)??null,J=(Xe==null?void 0:Xe.workspaceId)??null;if(U.kind==="ide"&&U.providerType){await F.handleLaunchIde(U.providerType,et?{workspace:et}:void 0);return}if((U.kind==="cli"||U.kind==="acp")&&U.providerType){await F.runLaunchCliCore({cliType:U.providerType,dir:J?void 0:et||"",workspaceId:J||void 0,model:U.kind==="acp"&&hm(U.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:U.providerSessionId});return}await We()},M.current=Ie,D(Ie),P({title:U.kind==="ide"?zr(t,"restart-ide",U.label):U.providerSessionId?ch(t,U.label):zr(t,"start-fresh",U.label),description:U.kind==="ide"?Kr(t,"restart-ide"):U.providerSessionId?dh(t):Kr(t,"start-fresh"),confirmLabel:U.kind==="ide"?Vr(t,"restart-ide"):U.providerSessionId?cl(t,!0):Vr(t,"start-fresh"),busyLabel:U.kind==="ide"?Yr(t,"restart-ide"):U.providerSessionId?lh(t,!0):Yr(t,"start-fresh"),workspaceOptions:Ne,details:[{label:"Mode",value:U.kind.toUpperCase()},...U.providerType?[{label:"Provider",value:U.providerType}]:[]]})},[F,z]);if(l.useEffect(()=>{b(ve)},[O,ve,n]),l.useEffect(()=>{he&&A(he)},[he,n]),!z)return u?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:t("machine.detail.notFound")}),s.jsx("p",{className:"mt-3",children:t("machine.detail.offlineHint")}),s.jsx("button",{onClick:L,className:"machine-btn-back",children:t("machine.detail.back")})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:t("machine.detail.loading")})});const le=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(us,{size:14})," ",t("machine.detail.tabWorkspace")]}),count:ne.length+ie.length+Ce.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(nn,{size:14})," ",t("machine.detail.tabHostedRuntimes")]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ua,{size:14})," ",t("machine.detail.tabProviders")]}),...S&&S.staleTypes.length+S.newTypes.length>0?{count:S.staleTypes.length+S.newTypes.length}:{}},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(vb,{size:14})," ",t("machine.detail.tabSystem")]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Hl,{size:14})," ",t("machine.detail.tabLogs")]})}];return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-border-subtle",children:[s.jsx("div",{className:"flex items-center justify-between w-full",children:s.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[s.jsx("button",{onClick:L,className:"flex items-center justify-center w-8 h-8 rounded-full bg-bg-glass hover:bg-bg-glass-hover text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[F.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:F.nicknameInput,onChange:U=>F.setNicknameInput(U.target.value),onKeyDown:U=>{U.key==="Enter"&&F.handleSaveNickname(),U.key==="Escape"&&F.setEditingNickname(!1)},placeholder:t("machine.detail.nicknamePlaceholder"),className:"px-2.5 py-1 rounded-md border border-accent/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:F.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:t("machine.detail.save")}),s.jsx("button",{onClick:()=>F.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-bg-glass text-text-muted hover:bg-bg-glass-hover hover:text-text-primary text-sm font-medium transition-colors",children:t("machine.detail.cancel")})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{F.setEditingNickname(!0),F.setNicknameInput(z.machineNickname||"")},title:t("machine.detail.clickToSetNickname"),children:me}),k?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),d.retryConnection&&n&&s.jsx("button",{onClick:()=>d.retryConnection(n),className:"px-2.5 py-0.5 rounded text-[11px] font-semibold bg-red-500/10 border border-red-500/20 text-red-400 hover:bg-red-500/20 transition-colors",children:t("machine.detail.reconnect")})]}):s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[s.jsxs("span",{className:"font-mono bg-bg-glass px-1.5 py-0.5 rounded",children:[z.platform," · ",z.arch]}),s.jsx("span",{children:t("machine.detail.coresCount",{count:z.cpus})}),(m==null?void 0:m.version)&&s.jsxs("span",{children:["v",m.version]}),z.p2p.available&&s.jsx("span",{children:t("machine.detail.p2pState",{state:z.p2p.state==="connected"?t("machine.detail.p2pConnected"):z.p2p.state})}),z.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:z.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-border-subtle",children:le.map(U=>s.jsxs("button",{onClick:()=>b(U.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${h===U.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[U.label,U.count!==void 0&&U.id==="providers"&&S?s.jsx("span",{role:"button",title:t("machine.detail.providerStaleBadgeHint"),"aria-label":t("machine.detail.providerStaleBadgeHint"),onClick:H,className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 cursor-pointer ${y?"bg-amber-500/20 text-amber-300":"bg-amber-500/15 text-amber-400 hover:bg-amber-500/30"}`,children:y?"…":U.count}):U.count!==void 0?s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${h===U.id?"bg-accent-primary/20 text-accent-primary":"bg-bg-glass-hover text-text-muted"}`,children:U.count}):null]},U.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[h==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(EL,{machineEntry:m,providers:$,recentLaunches:fe,currentConversations:V,onUpgradeDaemon:async()=>{const U=No(m);if(U)try{await o(n,"daemon_upgrade",U)}catch{}},onOpenRecent:pe,onOpenConversation:q}),s.jsx(HL,{machine:z,machineId:n,ideSessions:ne,cliSessions:ie,acpSessions:Ce,actions:F,sendDaemonCommand:o})]}),h==="providers"&&s.jsx(GI,{machineId:n,providers:$,sendDaemonCommand:o,quota:z.quota,refreshNonce:v}),h==="overview"&&s.jsx(DI,{machine:z,ideSessions:ne,cliSessions:ie,acpSessions:Ce}),h==="session-host"&&s.jsx(IL,{machineId:n,cliSessions:ie,sendDaemonCommand:o}),h==="logs"&&s.jsx(jL,{machineId:n,sendDaemonCommand:o})]})})}),F.launchPick&&z&&s.jsx(LL,{machine:z,launchPick:F.launchPick,actions:F}),I&&s.jsx(Ao,{title:I.title,description:I.description,details:I.details,workspaceOptions:I.workspaceOptions,selectedWorkspaceKey:E,onWorkspaceChange:U=>{M.current=U,D(U)},confirmLabel:I.confirmLabel,busyLabel:I.busyLabel,busy:W,onConfirm:ee,onCancel:()=>{T.current=null,P(null)}}),j&&s.jsx(tg,{daemonId:j.daemonId,workspace:j.workspace,onClose:()=>N(null)}),s.jsx(ph,{toasts:d.toasts||[],onDismiss:U=>d.setToasts(Ne=>Ne.filter(Ie=>Ie.id!==U)),onClickToast:U=>{U.targetKey&&a(Wa(U.targetKey))}}),s.jsx("style",{children:`
|
|
114
|
+
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){i("session_host_prune_duplicate_sessions");try{const P=await n(e,"session_host_prune_duplicate_sessions",{}),M=Ri(P);if(!(M!=null&&M.success))throw new Error((M==null?void 0:M.error)||"Duplicate prune failed");const E=M.result||{},D=Array.isArray(E.prunedSessionIds)?E.prunedSessionIds.length:0,W=typeof E.duplicateGroupCount=="number"?E.duplicateGroupCount:0;ft.showToast(`Pruned ${D} duplicate runtime(s) across ${W} group(s)`,"success"),await h()}catch(P){const M=P instanceof Error?P.message:"Duplicate prune failed";ft.showToast(M,"warning"),r(M)}finally{i(P=>P==="session_host_prune_duplicate_sessions"?null:P)}}},[e,h,n]),x=l.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((I,P)=>(P.lastActivityAt||0)-(I.lastActivityAt||0)),[u==null?void 0:u.sessions]),y=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)||[]}:AL(x),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,x]),C=y.liveRuntimes,v=y.recoverySnapshots,w=y.inactiveRecords,j=l.useMemo(()=>DL(C),[C]),N=l.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),A=l.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(I=>I.level==="warn"||I.level==="error")||null,[u==null?void 0:u.recentLogs]),T=(I,P)=>{var L;const M=o===`session_host_resume_session:${I.sessionId}`,E=o===`session_host_restart_session:${I.sessionId}`,D=o===`session_host_stop_session:${I.sessionId}`,W=ng(I.meta),R=k.get(I.sessionId),B=I.attachedClients.length===1?"1 client":`${I.attachedClients.length} clients`,_=P==="recovery"?"Recover":"Resume",H=TL(P);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:I.displayName||(R==null?void 0:R.cliName)||I.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${PL(I.lifecycle)}`,children:I.lifecycle}),W&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:W})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:I.workspaceLabel||(R==null?void 0:R.runtimeWorkspaceLabel)||I.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:I.runtimeKey}),I.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",I.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((L=I.writeOwner)==null?void 0:L.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:ML(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(mb,{size:11})," ",B]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",Xu(I.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",H]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[P==="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:()=>{b("session_host_resume_session",I)},children:M?`${_}ing…`:_}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{b("session_host_restart_session",I)},children:E?"Restarting…":"Restart"}),P==="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:()=>{b("session_host_stop_session",I)},children:D?"Stopping…":"Stop"})]})]})},I.sessionId)};return s.jsxs(vs,{padding:"lg",className:"mb-5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(nn,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Mj()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[j>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{S()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${j})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${g.toneClass}`,children:g.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{h()},disabled:m||c,children:[s.jsx(po,{size:13}),m||c?"Refreshing…":"Refresh"]})]})]}),a&&!u&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(Ls,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:a})]})]})}),u&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:v.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:Xu(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Ei(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(Ls,{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:[Ei(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(Bl,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Li("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(nn,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Li("recovery")}),v.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):s.jsx("div",{className:"space-y-2",children:v.map(I=>T(I,"recovery"))})]}),w.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:Li("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:w.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"}),N.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:N.map(I=>{var M;const P=x.find(E=>E.sessionId===I.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(P==null?void 0:P.displayName)||((M=k.get(I.sessionId))==null?void 0:M.cliName)||I.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[I.action,I.lifecycle?` · ${I.lifecycle}`:"",I.detail?` · ${I.detail}`:"",I.error?` · ${I.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${I.success===!1?"text-red-300":"text-text-secondary"}`,children:Ei(I.timestamp)})]},`${I.sessionId}:${I.timestamp}:${I.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:u.endpoint||"unknown"}),a?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",a]}):null]})]})]})}function LL({machine:e,launchPick:t,actions:n}){const{t:a}=ke("common"),{runLaunchCliCore:r,setLaunchPick:o}=n;return l.useEffect(()=>{const i=c=>{c.key==="Escape"&&o(null)};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[o]),s.jsx(Vt,{children:s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",onClick:()=>o(null),children:s.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",onClick:i=>i.stopPropagation(),children:[s.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),s.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),s.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?s.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(i=>s.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-accent-primary/10 transition-colors",onClick:()=>{o(null),r({cliType:t.cliType,workspaceId:i.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{o(null),r({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:a("newSession.defaultWorkspace")}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{o(null),r({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:a("newSession.homeDirectory")}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>o(null),children:"Cancel"})]})]})})})}function RL(e,t){const n=C1(e),a=Js(e,t),r=jo(e,a),o=Da(e,a),i=Ch(e,{targetVersion:a,required:o,fallback:"Update daemon"});return r?{visible:!0,showButton:!0,title:o?"Daemon update required":"Version mismatch detected",description:o?"This machine is on an incompatible daemon version. Update it before starting more sessions.":n==="preview"?"This machine can be upgraded to the current preview daemon without opening a remote shell.":"This machine is running a different daemon version than the current app. Update it before starting more sessions.",buttonLabel:i,targetVersion:a,channel:n,required:o,tone:"warn"}:n==="preview"?{visible:!0,showButton:!1,title:a?"Preview daemon is up to date":"Preview update status unknown",description:a?"This machine is already on the current preview daemon target.":"The app is connected to preview, but the server did not report a preview target version yet.",buttonLabel:i,targetVersion:a,channel:n,required:!1,tone:a?"good":"info"}:{visible:!1,showButton:!1,title:"",description:"",buttonLabel:i,targetVersion:a,channel:n,required:!1,tone:"info"}}function _i({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 Hi({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 EL({machineEntry:e,providers:t,recentLaunches:n,currentConversations:a,onUpgradeDaemon:r,onOpenRecent:o,onOpenConversation:i}){const{t:c}=ke("common"),d=a.slice(0,6),p=n.slice(0,4),m=RL(e,"1.0.57");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(_i,{icon:s.jsx(Is,{size:13}),children:c("machine.commandCenter.currentChats")}),s.jsx(Hi,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(f=>{const g=fl(f);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>i(f),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate min-w-0 group-hover:text-accent-primary transition-colors",children:kt(f)}),g>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:za(g)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:na(f)})]},f.tabKey)})})})]}),p.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(_i,{icon:s.jsx(Pp,{size:13}),children:c("machine.commandCenter.recentLaunches")}),s.jsx(Hi,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:p.map(f=>{const{metaText:g,updatedLabel:k}=Yh(f);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>o(f),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate min-w-0 group-hover:text-accent-primary transition-colors",children:f.label}),k&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:k})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:g})]},f.id)})})})]}),m.visible&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(_i,{icon:s.jsx(Ls,{size:13}),children:c("machine.commandCenter.daemonUpdate")}),s.jsx(Hi,{className:m.tone==="good"?"border-emerald-500/20 bg-emerald-500/5":m.tone==="info"?"border-sky-500/20 bg-sky-500/5":"border-amber-500/20 bg-amber-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:m.title}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[m.description,m.targetVersion&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",m.targetVersion,m.channel?` (${m.channel})`:""]})]}),m.showButton?s.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:r,children:[s.jsx(po,{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 _L({machineId:e,machine:t,ideSessions:n,cliSessions:a,acpSessions:r,actions:o,sendDaemonCommand:i}){const{workspaceBusy:c,handleWorkspaceAdd:d,handleWorkspaceRemove:p,handleWorkspaceSetDefault:u}=o,{t:m}=ke("common"),[f,g]=l.useState(!1),[k,h]=l.useState(""),[b,S]=l.useState([]),[x,y]=l.useState(!1),[C,v]=l.useState(""),w=l.useCallback(async N=>{y(!0),v("");try{const A=await fc(i,e,N);h(A.path),S(A.directories)}catch(A){v(A instanceof Error?A.message:"Could not load folder")}finally{y(!1)}},[e,i]),j=l.useCallback(()=>{g(!0);const N=[...n.map(T=>T.workspace),...a.map(T=>T.workspace),...r.map(T=>T.workspace)],A=hc(t.platform,mc(N,t.defaultWorkspacePath,(t.workspaces||[]).map(T=>T.path)));w(A)},[r,a,n,w,t.defaultWorkspacePath,t.platform,t.workspaces]);return s.jsxs(s.Fragment,{children:[s.jsxs(vs,{padding:"lg",className:"mb-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(Tn,{size:14})," Workspaces"]}),s.jsx("button",{type:"button",className:"btn bg-bg-glass hover:bg-bg-glass-hover text-text-muted hover:text-text-primary px-3 py-1 rounded transition-colors text-xs",disabled:c,onClick:j,children:"+ Add workspace"})]}),(t.workspaces||[]).length===0?s.jsxs("div",{className:"text-[11px] text-text-muted py-4 text-center",children:["No saved workspaces yet. Click ",s.jsx("span",{className:"text-text-secondary",children:"+ Add workspace"})," to pick a folder."]}):s.jsx("ul",{className:"space-y-1.5 max-h-72 overflow-y-auto",children:(t.workspaces||[]).map(N=>{const A=N.id===t.defaultWorkspaceId;return s.jsxs("li",{className:`flex items-start gap-2 text-[11px] rounded-lg border px-2.5 py-2 transition-colors ${A?"border-yellow-500/30 bg-yellow-500/[0.05]":"border-border-subtle bg-bg-primary"}`,children:[s.jsx("button",{type:"button",title:A?"Default workspace — click to unset":"Set as default workspace",disabled:c,onClick:()=>void u(A?null:N.id),className:`text-base leading-none shrink-0 transition-colors ${A?"text-yellow-400 hover:text-yellow-300":"text-text-muted/40 hover:text-yellow-400"}`,children:"★"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"font-medium text-text-primary truncate",children:um(N.path,N.label)}),s.jsx("div",{className:"font-mono text-text-muted truncate text-[10px]",title:N.path,children:N.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void p(N.id),children:m("machine.managedWorkspaces.remove")})]},N.id)})})]}),f&&s.jsx(bc,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:k,directories:b,busy:x,error:C,confirmLabel:"Add workspace",onClose:()=>g(!1),onNavigate:N=>{w(N)},onConfirm:N=>{(async()=>{if(!N)return;await d(N)&&g(!1)})()}})]})}function HL({machine:e,machineId:t,ideSessions:n,cliSessions:a,acpSessions:r,actions:o,sendDaemonCommand:i}){return s.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[s.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-border-subtle mb-4",children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspaces"}),s.jsx("div",{className:"text-sm text-text-secondary",children:'Save folders as workspaces on this machine. Use the dashboard "+" button to launch a session.'})]}),i&&s.jsx(_L,{machineId:t,machine:e,ideSessions:n,cliSessions:a,acpSessions:r,actions:o,sendDaemonCommand:i})]})}const $L="activate_provider_updates";function ag(e){if(!e||typeof e!="object")return;const t=e;return"result"in t&&t.result&&typeof t.result=="object"?t.result:t}function FL(e){var r;const t=ag(e);if(!t)return{ok:!1,error:"empty response"};if(t.success===!1)return{ok:!1,error:typeof t.error=="string"&&t.error.trim()?t.error:"sync failed"};const n=t.channelSync;if(n&&typeof n=="object"&&n.status==="error"){const o=Array.isArray(n.errors)?(r=n.errors[0])==null?void 0:r.message:void 0;return{ok:!1,error:typeof o=="string"&&o.trim()?o:"channel sync failed"}}return{ok:!0,activatedCount:Array.isArray(t.activated)?t.activated.length:0}}function BL(e){const t=[];for(const n of(e==null?void 0:e.newTypes)??[])typeof n=="string"&&n.trim()&&t.push(n.trim());return t}function WL({onNicknameSynced:e}={}){var se,te,ue,ye,Me,re,ce,Ae,be,we,_e;const{t}=ke("common"),{id:n}=Wg(),a=ia(),r=Rl(),{sendCommand:o}=St(),i=da(),c=Mh(),d=Xm(),p=d.ides||[],u=d.initialLoaded??!0,m=p.find(U=>U.id===n&&U.type==="adhdev-daemon"),f=p.some(U=>U.type==="adhdev-daemon"),g=n?(se=d.connectionRetryStatuses)==null?void 0:se[n]:void 0,k=!!(g!=null&&g.blocked),[h,b]=l.useState("workspace"),[S,x]=l.useState(null),[y,C]=l.useState(!1),[v,w]=l.useState(0),[j,N]=l.useState(null);l.useCallback((U,Ne)=>{N({daemonId:U,workspace:Ne})},[]);const[,A]=l.useState("ide"),T=l.useRef(null),[I,P]=l.useState(null),M=l.useRef("__home__"),[E,D]=l.useState("__home__"),[W,R]=l.useState(!1),B=l.useRef(null);l.useEffect(()=>{!n||!m||!(!m.workspaces||!m.availableProviders||!m.detectedIdes||!m.recentLaunches)||i(n,{minFreshMs:3e4}).catch(()=>{})},[i,m,n]);const _=l.useCallback(U=>{const Ne=ag(U),Ie=Ne==null?void 0:Ne.providerChannelStaleness;Ie&&!Ie.error&&x({staleTypes:Array.isArray(Ie.staleTypes)?Ie.staleTypes:[],newTypes:Array.isArray(Ie.newTypes)?Ie.newTypes:[]})},[]);l.useEffect(()=>{if(!n||!m)return;let U=!1;return(async()=>{try{const Ne=await o(n,"get_status_metadata");U||_(Ne)}catch{}})(),()=>{U=!0}},[_,n,m==null?void 0:m.id,o]);const H=l.useCallback(async U=>{if(U.preventDefault(),U.stopPropagation(),!(!n||y)){b("providers"),C(!0);try{const Ne=BL(S),Ie=await o(n,$L,Ne.length>0?{types:Ne}:{}),We=FL(Ie);"error"in We?ft.showToast(t("machine.detail.providerSyncFailed",{error:We.error}),"warning"):ft.showToast(We.activatedCount>0?t("machine.detail.providerSyncSuccess",{count:We.activatedCount}):t("machine.detail.providerSyncAlreadyCurrent"),"success"),w(Xe=>Xe+1);try{_(await o(n,"get_status_metadata"))}catch{}}catch(Ne){const Ie=Ne instanceof Error?Ne.message:String(Ne);ft.showToast(t("machine.detail.providerSyncFailed",{error:Ie}),"warning")}finally{C(!1)}}},[_,n,S,y,o,t]);l.useEffect(()=>{if(!n||!m||h!=="overview"&&h!=="providers")return;const U=m.machine;(typeof(U==null?void 0:U.cpus)!="number"||typeof(U==null?void 0:U.totalMem)!="number"||typeof(U==null?void 0:U.arch)!="string"||typeof(U==null?void 0:U.release)!="string"||h==="providers"&&!(U!=null&&U.quota))&&c(n,{minFreshMs:3e4}).catch(()=>{})},[h,c,m,n]),Y1(n&&h==="overview"?[n]:[],{enabled:h==="overview",intervalMs:YS});const L=()=>{if(f){a("/dashboard",{state:{mobileSection:"machines"}});return}a("/machines")},F=MI({machineId:n,registeredMachineId:(m==null?void 0:m.machineId)||null,sendDaemonCommand:o,onNicknameSynced:e,logsEndRef:B});l.useEffect(()=>ft.onToast(Ne=>{d.setToasts(We=>{if(We.some(J=>J.message===Ne.message&&Ne.timestamp-J.timestamp<3e3))return We;const et={id:Ne.id,message:Ne.message,type:Ne.type,timestamp:Ne.timestamp,targetKey:Ne.targetKey,actions:Ne.actions};return[...We.slice(-4),et]});const Ie=Ne.duration||5e3;setTimeout(()=>d.setToasts(We=>We.filter(Xe=>Xe.id!==Ne.id)),Ie)}),[d]);const $=(m==null?void 0:m.availableProviders)||[],K={};for(const U of $)K[U.type]=U.icon;const z=m?{id:m.id,hostname:pm(m,{fallbackId:m.id}),platform:((te=m.machine)==null?void 0:te.platform)||"unknown",arch:((ue=m.machine)==null?void 0:ue.arch)||"",cpus:((ye=m.machine)==null?void 0:ye.cpus)||0,totalMem:((Me=m.machine)==null?void 0:Me.totalMem)||0,freeMem:(re=m.machine)==null?void 0:re.freeMem,availableMem:(ce=m.machine)==null?void 0:ce.availableMem,loadavg:(Ae=m.machine)==null?void 0:Ae.loadavg,uptime:(be=m.machine)==null?void 0:be.uptime,release:((we=m.machine)==null?void 0:we.release)||"",cdpConnected:!!m.cdpConnected,machineNickname:m.machineNickname||null,...(_e=m.machine)!=null&&_e.quota?{quota:m.machine.quota}:{},p2p:m.p2p?{screenshotActive:!1,...m.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:m.detectedIdes||[],workspaces:m.workspaces||[],defaultWorkspaceId:m.defaultWorkspaceId??m.activeWorkspaceId??null,defaultWorkspacePath:m.defaultWorkspacePath??m.activeWorkspacePath??null}:null,ne=p.filter(U=>U.daemonId===n&&U.type!=="adhdev-daemon").filter(U=>!Fa(U)&&!Xn(U)).map(U=>({id:U.id,sessionId:U.sessionId,type:U.type,version:U.version||"",instanceId:U.instanceId||"",status:U.status,workspace:U.workspace||null,terminals:U.terminals||0,aiAgents:nk(U.aiAgents||(U.agents||[]).map(Ne=>({id:Ne.name,name:Ne.name,status:Ne.status,version:Ne.version}))),activeChat:U.activeChat||null,chats:U.chats||[],childSessions:U.childSessions||[],cdpConnected:U.cdpConnected||!1,daemonId:n,lastMessageAt:U.lastMessageAt})),ie=p.filter(U=>U.daemonId===n&&Fa(U)).map(U=>({id:U.id,sessionId:U.sessionId,type:U.type,cliName:U.cliName||U.type,status:U.status,workspace:U.workspace||"",activeChat:U.activeChat||null,providerSessionId:U.providerSessionId,mode:U.mode,runtimeKey:U.runtimeKey,runtimeDisplayName:U.runtimeDisplayName,runtimeWorkspaceLabel:U.runtimeWorkspaceLabel,runtimeWriteOwner:U.runtimeWriteOwner||null,runtimeAttachedClients:U.runtimeAttachedClients||[],daemonId:n,lastMessageAt:U.lastMessageAt})),Ce=p.filter(U=>U.daemonId===n&&Xn(U)).map(U=>({id:U.id,sessionId:U.sessionId,type:U.type,acpName:U.cliName||U.type,status:U.status,workspace:U.workspace||"",activeChat:U.activeChat||null,providerSessionId:U.providerSessionId,daemonId:n,lastMessageAt:U.lastMessageAt})),me=m?ds(m,{fallbackId:n}):"",O="workspace",Y=r.state,X=Y==null?void 0:Y.initialMachineTab,Q=Y==null?void 0:Y.initialWorkspaceCategory;Y==null||Y.initialWorkspaceId,Y==null||Y.initialWorkspacePath;const ve=X==="ides"||X==="clis"||X==="acps"?"workspace":X||O,he=X==="ides"?"ide":X==="clis"?"cli":X==="acps"?"acp":Q,Z=[...ne.map(U=>{var Ne;return{id:`ide:${U.type}:${U.workspace||""}`,label:((Ne=U.activeChat)==null?void 0:Ne.title)||U.type,kind:"ide",providerType:U.type,subtitle:U.workspace||void 0,workspace:U.workspace||void 0,lastLaunchedAt:U.lastMessageAt||0}}),...ie.map(U=>{var Ne;return{id:`cli:${U.type}:${U.workspace||""}`,label:((Ne=U.activeChat)==null?void 0:Ne.title)||U.cliName,kind:"cli",providerType:U.type,providerSessionId:U.providerSessionId,subtitle:U.workspace||void 0,workspace:U.workspace||void 0,lastLaunchedAt:U.lastMessageAt||0}}),...Ce.map(U=>{var Ne;return{id:`acp:${U.type}:${U.workspace||""}`,label:((Ne=U.activeChat)==null?void 0:Ne.title)||U.acpName,kind:"acp",providerType:U.type,providerSessionId:U.providerSessionId,subtitle:Mn(U.summaryMetadata)||U.workspace||void 0,workspace:U.workspace||void 0,lastLaunchedAt:U.lastMessageAt||0}})].sort((U,Ne)=>(Ne.lastLaunchedAt||0)-(U.lastLaunchedAt||0)),fe=((m==null?void 0:m.recentLaunches)||[]).length>0?((m==null?void 0:m.recentLaunches)||[]).map(U=>({id:U.id,label:U.title||U.providerName||U.providerType,kind:U.kind,providerType:U.providerType,providerSessionId:U.providerSessionId,subtitle:Mn(U.summaryMetadata)||U.workspace||void 0,workspace:U.workspace,summaryMetadata:U.summaryMetadata,lastLaunchedAt:U.lastLaunchedAt})):Z,V=l.useMemo(()=>{var Ne;const U=((Ne=d.connectionStates)==null?void 0:Ne[n||""])||void 0;return p.filter(Ie=>Ie.daemonId===n&&Ie.type!=="adhdev-daemon").flatMap(Ie=>ic(Ie,{connectionStates:n&&U?{[n]:U}:void 0,defaultConnectionState:U})).filter(Ie=>!(Ie.transport==="pty"&&Ie.mode==="terminal")).sort((Ie,We)=>fl(We)-fl(Ie))},[p,d.connectionStates,n]),q=l.useCallback(U=>{const Ne=Oh(U);Ne&&a(Wa(Ne))},[a]),ee=l.useCallback(()=>{T.current&&(R(!0),T.current().finally(()=>{T.current=null,R(!1),P(null)}))},[]),pe=l.useCallback(U=>{if(!z)return;const{options:Ne,selectedKey:Ie}=Vh({machine:z,currentWorkspacePath:U.workspace,homeLabel:t("newSession.homeDirectory"),homeDescription:t("newSession.launchWithoutWorkspace")}),We=async()=>{A(U.kind),b("workspace")};T.current=async()=>{const Xe=Ne.find(Le=>Le.key===M.current),et=(Xe==null?void 0:Xe.workspacePath)??null,J=(Xe==null?void 0:Xe.workspaceId)??null;if(U.kind==="ide"&&U.providerType){await F.handleLaunchIde(U.providerType,et?{workspace:et}:void 0);return}if((U.kind==="cli"||U.kind==="acp")&&U.providerType){await F.runLaunchCliCore({cliType:U.providerType,dir:J?void 0:et||"",workspaceId:J||void 0,model:U.kind==="acp"&&hm(U.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:U.providerSessionId});return}await We()},M.current=Ie,D(Ie),P({title:U.kind==="ide"?zr(t,"restart-ide",U.label):U.providerSessionId?ch(t,U.label):zr(t,"start-fresh",U.label),description:U.kind==="ide"?Kr(t,"restart-ide"):U.providerSessionId?dh(t):Kr(t,"start-fresh"),confirmLabel:U.kind==="ide"?Vr(t,"restart-ide"):U.providerSessionId?cl(t,!0):Vr(t,"start-fresh"),busyLabel:U.kind==="ide"?Yr(t,"restart-ide"):U.providerSessionId?lh(t,!0):Yr(t,"start-fresh"),workspaceOptions:Ne,details:[{label:"Mode",value:U.kind.toUpperCase()},...U.providerType?[{label:"Provider",value:U.providerType}]:[]]})},[F,z]);if(l.useEffect(()=>{b(ve)},[O,ve,n]),l.useEffect(()=>{he&&A(he)},[he,n]),!z)return u?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:t("machine.detail.notFound")}),s.jsx("p",{className:"mt-3",children:t("machine.detail.offlineHint")}),s.jsx("button",{onClick:L,className:"machine-btn-back",children:t("machine.detail.back")})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:t("machine.detail.loading")})});const le=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(us,{size:14})," ",t("machine.detail.tabWorkspace")]}),count:ne.length+ie.length+Ce.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(nn,{size:14})," ",t("machine.detail.tabHostedRuntimes")]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ua,{size:14})," ",t("machine.detail.tabProviders")]}),...S&&S.staleTypes.length+S.newTypes.length>0?{count:S.staleTypes.length+S.newTypes.length}:{}},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(vb,{size:14})," ",t("machine.detail.tabSystem")]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Hl,{size:14})," ",t("machine.detail.tabLogs")]})}];return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-border-subtle",children:[s.jsx("div",{className:"flex items-center justify-between w-full",children:s.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[s.jsx("button",{onClick:L,className:"flex items-center justify-center w-8 h-8 rounded-full bg-bg-glass hover:bg-bg-glass-hover text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[F.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:F.nicknameInput,onChange:U=>F.setNicknameInput(U.target.value),onKeyDown:U=>{U.key==="Enter"&&F.handleSaveNickname(),U.key==="Escape"&&F.setEditingNickname(!1)},placeholder:t("machine.detail.nicknamePlaceholder"),className:"px-2.5 py-1 rounded-md border border-accent/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:F.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:t("machine.detail.save")}),s.jsx("button",{onClick:()=>F.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-bg-glass text-text-muted hover:bg-bg-glass-hover hover:text-text-primary text-sm font-medium transition-colors",children:t("machine.detail.cancel")})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{F.setEditingNickname(!0),F.setNicknameInput(z.machineNickname||"")},title:t("machine.detail.clickToSetNickname"),children:me}),k?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),d.retryConnection&&n&&s.jsx("button",{onClick:()=>d.retryConnection(n),className:"px-2.5 py-0.5 rounded text-[11px] font-semibold bg-red-500/10 border border-red-500/20 text-red-400 hover:bg-red-500/20 transition-colors",children:t("machine.detail.reconnect")})]}):s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[s.jsxs("span",{className:"font-mono bg-bg-glass px-1.5 py-0.5 rounded",children:[z.platform," · ",z.arch]}),s.jsx("span",{children:t("machine.detail.coresCount",{count:z.cpus})}),(m==null?void 0:m.version)&&s.jsxs("span",{children:["v",m.version]}),z.p2p.available&&s.jsx("span",{children:t("machine.detail.p2pState",{state:z.p2p.state==="connected"?t("machine.detail.p2pConnected"):z.p2p.state})}),z.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:z.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-border-subtle",children:le.map(U=>s.jsxs("button",{onClick:()=>b(U.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${h===U.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[U.label,U.count!==void 0&&U.id==="providers"&&S?s.jsx("span",{role:"button",title:t("machine.detail.providerStaleBadgeHint"),"aria-label":t("machine.detail.providerStaleBadgeHint"),onClick:H,className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 cursor-pointer ${y?"bg-amber-500/20 text-amber-300":"bg-amber-500/15 text-amber-400 hover:bg-amber-500/30"}`,children:y?"…":U.count}):U.count!==void 0?s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${h===U.id?"bg-accent-primary/20 text-accent-primary":"bg-bg-glass-hover text-text-muted"}`,children:U.count}):null]},U.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[h==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(EL,{machineEntry:m,providers:$,recentLaunches:fe,currentConversations:V,onUpgradeDaemon:async()=>{const U=No(m);if(U)try{await o(n,"daemon_upgrade",U)}catch{}},onOpenRecent:pe,onOpenConversation:q}),s.jsx(HL,{machine:z,machineId:n,ideSessions:ne,cliSessions:ie,acpSessions:Ce,actions:F,sendDaemonCommand:o})]}),h==="providers"&&s.jsx(GI,{machineId:n,providers:$,sendDaemonCommand:o,quota:z.quota,refreshNonce:v}),h==="overview"&&s.jsx(DI,{machine:z,ideSessions:ne,cliSessions:ie,acpSessions:Ce}),h==="session-host"&&s.jsx(IL,{machineId:n,cliSessions:ie,sendDaemonCommand:o}),h==="logs"&&s.jsx(jL,{machineId:n,sendDaemonCommand:o})]})})}),F.launchPick&&z&&s.jsx(LL,{machine:z,launchPick:F.launchPick,actions:F}),I&&s.jsx(Ao,{title:I.title,description:I.description,details:I.details,workspaceOptions:I.workspaceOptions,selectedWorkspaceKey:E,onWorkspaceChange:U=>{M.current=U,D(U)},confirmLabel:I.confirmLabel,busyLabel:I.busyLabel,busy:W,onConfirm:ee,onCancel:()=>{T.current=null,P(null)}}),j&&s.jsx(tg,{daemonId:j.daemonId,workspace:j.workspace,onClose:()=>N(null)}),s.jsx(ph,{toasts:d.toasts||[],onDismiss:U=>d.setToasts(Ne=>Ne.filter(Ie=>Ie.id!==U)),onClickToast:U=>{U.targetKey&&a(Wa(U.targetKey))}}),s.jsx("style",{children:`
|
|
115
115
|
@keyframes toast-in {
|
|
116
116
|
from { opacity: 0; transform: translateX(40px); }
|
|
117
117
|
to { opacity: 1; transform: translateX(0); }
|
|
118
118
|
}
|
|
119
119
|
`})]})}function OL({daemonIds:e,meshId:t,sendData:n,onRevisionAdvance:a}){const r=l.useRef(new Map),o=l.useRef(a);o.current=a;const i=[...new Set(e.filter(Boolean))].sort().join(",");l.useEffect(()=>{r.current=new Map},[i,t]),l.useEffect(()=>{if(!t||!n)return;const c=[...new Set(e.filter(Boolean))];if(c.length===0)return;const d=c.map(p=>ys.subscribe({sendData:n},p,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${p}`,params:{includeSessions:!0}},u=>{if(u.topic!=="daemon.metadata")return;const m=u.meshStateRevisions;if(!m)return;const f=m[t]??m["*"];if(typeof f!="number")return;const g=r.current.get(p);r.current.set(p,f),g!==void 0&&f>g&&o.current()}));return()=>{for(const p of d)p()}},[i,t,n])}const rg={meshHostDaemonSection:!1,createDaemonPicker:!1,addNodeDaemonPicker:!1,queueSection:!0,coordinatorPrompt:!0,nodeInstruction:!0,hermesMcpConfig:!0,reviewInbox:!0},og=l.createContext(null);function UL(){const e=l.useContext(og);if(!e)throw new Error("useRepoMeshContext must be used inside RepoMeshProvider");return e}const ro="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function Cl({workspaces:e,value:t,onChange:n,autoFocus:a}){const{t:r}=ke("common"),[o,i]=l.useState(!1),c=new Set(e.map(p=>p.path)),d=o?"__custom":c.has(t)?t:"";return e.length===0||o?s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx("input",{type:"text",className:ro,value:t,autoFocus:a,placeholder:r("setupWizard.machines.workspacePlaceholder"),onChange:p=>n(p.target.value)}),e.length>0&&s.jsx("button",{type:"button",className:"self-start text-[10px] text-accent-primary hover:underline",onClick:()=>i(!1),children:r("setupWizard.machines.pickFromKnown")})]}):s.jsxs("select",{className:ro,value:d,onChange:p=>{p.target.value==="__custom"?(i(!0),n("")):n(p.target.value)},children:[s.jsx("option",{value:"",children:r("setupWizard.machines.workspaceSelectPlaceholder")}),e.map(p=>s.jsx("option",{value:p.path,children:p.label||p.path},p.path)),s.jsx("option",{value:"__custom",children:r("setupWizard.machines.workspaceCustom")})]})}function oo(e){var t;return!!(e!=null&&e.success)&&((t=e==null?void 0:e.plan)==null?void 0:t.kind)!==void 0&&e.plan.kind!=="create_mesh_and_onboard"}function ig(e,t){const[n,a]=l.useState(!1),r=l.useRef(null);return l.useEffect(()=>(e?r.current=setTimeout(()=>a(!0),t):a(!1),()=>{r.current&&clearTimeout(r.current)}),[e,t]),e&&n}function lg({plan:e,loading:t}){var i,c,d;const{t:n}=ke("common"),a=ig(t,250);let r=null,o="text-[11px] text-text-muted";return a?r=n("setupWizard.machines.planChecking"):(e==null?void 0:e.success)===!1?(o="text-[11px] text-red-400",r=s.jsxs(s.Fragment,{children:[e.error,e.action?` ${e.action}`:""]})):oo(e)?(o="text-[11px] text-amber-400",r=((i=e.plan)==null?void 0:i.summary)||n("setupWizard.machines.planExists")):e&&(o="text-[11px] text-emerald-400",r=n("setupWizard.machines.planOk",{identity:((c=e.discovery)==null?void 0:c.repoIdentity)||((d=e.discovery)==null?void 0:d.repoRoot)||""})),s.jsx("p",{className:`${o} min-h-[1.4em]`,children:r})}function GL(e){var t;return e.creating||e.planLoading||!e.name.trim()||e.showDaemonPicker&&!e.daemonId||((t=e.plan)==null?void 0:t.success)===!1||oo(e.plan)?!0:e.workspace.trim()?!1:!e.repoRemoteUrl.trim()&&!e.repoIdentity.trim()}function cg(e){var E,D;const{variant:t="page",showDaemonPicker:n,daemons:a,daemonLabel:r,name:o,onNameChange:i,daemonId:c,onDaemonIdChange:d,workspace:p,onWorkspaceChange:u,workspaces:m,plan:f,planLoading:g,repoRemoteUrl:k,onRepoRemoteUrlChange:h,repoIdentity:b,onRepoIdentityChange:S,manualOpen:x,onManualOpenChange:y,creating:C,warning:v,onCreate:w,onCancel:j}=e,{t:N}=ke("common"),A=GL({creating:C,planLoading:g,plan:f,name:o,workspace:p,showDaemonPicker:n,daemonId:c,repoRemoteUrl:k,repoIdentity:b}),T=ig(g,250),I=x||!!k.trim()||!!b.trim(),P=n&&a.length>0&&s.jsxs("select",{className:t==="wizard"?ro:"input w-full",value:c,onChange:W=>d(W.target.value),children:[s.jsx("option",{value:"",children:N("setupWizard.machines.machineSelectPlaceholder")}),a.map(W=>s.jsx("option",{value:W.id,children:r(W)},W.id))]}),M=I?s.jsxs(s.Fragment,{children:[s.jsx(Tt,{label:N("repoMesh.list.remoteUrl"),hint:N("repoMesh.list.remoteUrlHint"),children:s.jsx(xs,{value:k,onChange:W=>h(W.target.value),placeholder:"https://github.com/user/repo"})}),s.jsx(Tt,{label:N("repoMesh.list.repoIdentity"),hint:N("repoMesh.list.repoIdentityHint"),children:s.jsx(xs,{value:b,onChange:W=>S(W.target.value),placeholder:"github.com/user/repo"})})]}):s.jsx("button",{type:"button",className:"self-start text-xs text-text-muted hover:text-text-primary underline underline-offset-2 mb-3 bg-transparent border-none cursor-pointer p-0",onClick:()=>y(!0),children:N("repoMesh.list.advancedIdentityToggle")});return t==="wizard"?s.jsxs("div",{className:"flex flex-col gap-2.5 rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2.5",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:N("setupWizard.machines.meshName")}),s.jsx("input",{type:"text",className:ro,value:o,onChange:W=>i(W.target.value)})]}),n&&a.length>1&&s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:N("setupWizard.machines.machine")}),P]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:N("setupWizard.machines.workspace")}),s.jsx(Cl,{workspaces:m,value:p,onChange:u})]}),s.jsx(lg,{plan:f,loading:g}),v&&s.jsx("p",{className:"text-[11px] text-amber-400",children:v}),s.jsx("div",{className:"flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:w,disabled:A,children:N(C?"setupWizard.machines.creating":"setupWizard.machines.create")})})]}):s.jsxs(s.Fragment,{children:[s.jsx("h3",{className:"text-base font-bold mb-4",children:N("repoMesh.list.createTitle")}),n&&s.jsx(Tt,{label:N("repoMesh.list.createOnMachine"),hint:N("repoMesh.list.createOnMachineHint"),children:a.length===0?s.jsx("select",{className:"input w-full",disabled:!0,children:s.jsx("option",{value:"",children:N("repoMesh.list.noConnectedDaemon")})}):P}),s.jsx(Tt,{label:N("repoMesh.list.workspace"),hint:N("repoMesh.list.workspaceHint"),children:s.jsx(Cl,{workspaces:m,value:p,onChange:u})}),(T||f)&&s.jsx(Mt,{variant:(f==null?void 0:f.success)===!1?"error":oo(f)?"warning":"info",className:"mb-4",children:T?N("setupWizard.machines.planChecking"):(f==null?void 0:f.success)===!1?`${(f==null?void 0:f.code)||"onboarding_blocked"}: ${(f==null?void 0:f.error)||"Git discovery failed"} ${(f==null?void 0:f.action)||""}`:oo(f)?((E=f.plan)==null?void 0:E.summary)||N("setupWizard.machines.planExists"):`${((D=f.plan)==null?void 0:D.summary)||"Git repository detected."} No changes will be made until you click Create.`}),s.jsx(Tt,{label:N("repoMesh.list.name"),children:s.jsx(xs,{value:o,onChange:W=>i(W.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx("div",{className:"flex flex-col",children:M}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:w,disabled:A,children:N(C?"repoMesh.list.creating":"repoMesh.list.create")}),j&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:j,disabled:C,children:N("repoMesh.list.cancel")})]})]})}function qL({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 zL({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 KL({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 VL({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 YL({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 QL(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function JL({meshes:e,loading:t,error:n,onDismissError:a,daemons:r,features:o,showCreate:i,onToggleCreate:c,createName:d,onCreateNameChange:p,createRepoIdentity:u,onCreateRepoIdentityChange:m,createRepoRemoteUrl:f,onCreateRepoRemoteUrlChange:g,newMeshDaemonId:k,onNewMeshDaemonIdChange:h,newMeshWorkspace:b,onNewMeshWorkspaceChange:S,createPickerWorkspaces:x,createOnboardingPlan:y,createPlanLoading:C,creating:v,createWarning:w,onDismissCreateWarning:j,onSelectMesh:N,onCreate:A,onCancelCreate:T}){const{t:I}=ke("common"),P=o.maxMeshes!=null&&e.length>=o.maxMeshes,[M,E]=l.useState(!1);return s.jsxs(Ja,{icon:s.jsx(cs,{}),title:I("repoMesh.list.title"),subtitle:I("repoMesh.list.count",{count:e.length}),widthClassName:"max-w-5xl",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:c,disabled:P,title:P?I("repoMesh.list.meshLimitReached",{max:o.maxMeshes}):void 0,children:I("repoMesh.list.createMesh")}),children:[P&&s.jsx(Mt,{variant:"info",className:"mb-4",children:I("repoMesh.list.meshLimitBanner",{max:o.maxMeshes})}),n&&s.jsx(Mt,{variant:"error",onDismiss:a,className:"mb-4",children:n}),w&&s.jsx(Mt,{variant:"warning",onDismiss:j,className:"mb-4",children:w}),i&&s.jsx(xt,{className:"mb-5 border-accent/40 animate-[fadeIn_0.3s_ease-out]",children:s.jsx(cg,{variant:"page",showDaemonPicker:o.createDaemonPicker,daemons:r,daemonLabel:QL,name:d,onNameChange:p,daemonId:k,onDaemonIdChange:h,workspace:b,onWorkspaceChange:S,workspaces:x,plan:y,planLoading:C,repoRemoteUrl:f,onRepoRemoteUrlChange:g,repoIdentity:u,onRepoIdentityChange:m,manualOpen:M,onManualOpenChange:E,creating:v,onCreate:A,onCancel:T})}),t?s.jsx("div",{className:"text-sm text-text-muted p-4",children:I("repoMesh.list.loading")}):e.length===0?s.jsx(Xa,{icon:s.jsx(cs,{}),title:I("repoMesh.list.emptyTitle"),description:r.length>0?I("repoMesh.list.emptyWithDaemons"):I("repoMesh.list.emptyNoDaemons"),action:s.jsx("button",{className:"btn btn-primary btn-sm",disabled:!r.length,onClick:c,children:I("repoMesh.list.createFirst")})}):s.jsx("div",{className:"flex flex-col gap-2.5",children:e.map(D=>{var W;return s.jsx("button",{type:"button",onClick:()=>N(D.id),className:"w-full text-left bg-bg-glass border border-border-subtle rounded-xl px-5 py-4 transition-colors hover:border-border-default hover:bg-bg-secondary/70",children:s.jsxs("div",{className:"flex justify-between items-start",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx(cs,{size:16}),s.jsx("span",{className:"font-bold text-sm",children:D.name})]}),s.jsxs("div",{className:"text-[12px] text-text-muted flex items-center gap-2",children:[s.jsx("span",{className:"font-mono",children:D.repoIdentity||D.repo_identity||I("repoMesh.list.noRepoIdentity")}),(D.defaultBranch||D.default_branch)&&s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(zL,{size:11}),D.defaultBranch||D.default_branch]})]})]}),s.jsxs("div",{className:"text-right text-[11px] text-text-muted shrink-0 ml-4",children:[s.jsx("div",{children:new Date(D.createdAt||D.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})}),s.jsxs("div",{className:"text-text-muted/60",children:[((W=D.nodes)==null?void 0:W.length)??D.nodeCount??0," ",I("repoMesh.list.nodesSuffix")]})]})]})},D.id)})})]})}function XL(e){const t=new Map;for(const n of e)n!=null&&n.id&&t.set(n.id,cn(n.availableProviders||[]));return t}function ZL(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 e2(e,t){const n=new Map;for(const c of t)c!=null&&c.id&&n.set(c.id,Array.isArray(c.availableProviders)?c.availableProviders:[]);const a=new Set,r=[];let o=0,i=0;for(const c of Array.isArray(e)?e:[]){const d=String((c==null?void 0:c.daemon_id)||(c==null?void 0:c.daemonId)||""),p=d?n.get(d):n.size===1?[...n.values()][0]:void 0;if(!p||p.length===0){i++;continue}o++;for(const u of p){const m=String((u==null?void 0:u.type)||(u==null?void 0:u.id)||"").trim();!m||a.has(m)||(a.add(m),r.push(u))}}return r.sort((c,d)=>String((c==null?void 0:c.type)||(c==null?void 0:c.id)||"").localeCompare(String((d==null?void 0:d.type)||(d==null?void 0:d.id)||""))),{providers:r,reportedNodeCount:o,unreportedNodeCount:i}}function t2(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{},n=new Set,a=[],r=o=>{const i=typeof o=="string"?o.trim():"";!i||n.has(i)||(n.add(i),a.push(i))};for(const o of im(t.slots))r(o.provider);if(Array.isArray(t.providerPriority))for(const o of t.providerPriority)r(o);return a}function s2(e){var d,p;const t=e,n=[],a=Array.isArray(t.capabilities)?t.capabilities:[];for(const u of a){const m=typeof u=="string"?u.trim():"";m&&n.push({tag:m,custom:!0})}const r=(((d=t.userOverrides)==null?void 0:d.platform)||t.reportedPlatform||"").toString().trim(),o=(((p=t.userOverrides)==null?void 0:p.arch)||t.reportedArch||"").toString().trim();r&&n.push({tag:`os=${r}`,custom:!1}),o&&n.push({tag:`arch=${o}`,custom:!1});for(const u of t2(t.policy))n.push({tag:`provider=${u}`,custom:!1});const i=typeof t.worktreeBranch=="string"?t.worktreeBranch.trim():"";t.isLocalWorktree===!0&&i&&n.push({tag:`worktree=${i}`,custom:!1});const c=new Set;return n.filter(u=>c.has(u.tag)?!1:(c.add(u.tag),!0))}const n2=["","low","medium","high"],a2={easy:"Easy",medium:"Medium",difficult:"Difficult",freeform:"Freeform"};function Zu(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 ep(e){const t=e.provider.trim();if(!t)return null;const n=e.model.trim(),a=e.thinkingLevel.trim()||void 0,r=Number(e.maxParallel),o=Number.isFinite(r)&&r>0?Math.floor(r):void 0;return{provider:t,...n?{model:n}:{},...a?{thinkingLevel:a}:{},...e.difficulty.length?{difficulty:e.difficulty}:{},...e.capability.length?{capability:e.capability}:{},...o!==void 0?{maxParallel:o}:{}}}function r2(){return{provider:"",model:"",thinkingLevel:"",difficulty:[],capability:[],maxParallel:""}}const gn="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function o2({slots:e,availableProviders:t,saving:n,onSave:a}){const{t:r}=ke("common"),[o,i]=l.useState(()=>e.map(Zu)),c=l.useMemo(()=>JSON.stringify(e),[e]);l.useEffect(()=>{i(e.map(Zu))},[c]);const d=l.useMemo(()=>[...new Set(t.map(x=>x.type).filter(Boolean))],[t]),p=l.useMemo(()=>bh(t),[t]),u=l.useMemo(()=>{const x=o.map(ep).filter(Boolean);return JSON.stringify(x)!==JSON.stringify(e)},[o,e]),m=(x,y)=>i(C=>C.map((v,w)=>w===x?{...v,...y}:v)),f=(x,y)=>i(C=>C.map((v,w)=>{var A;if(w!==x)return v;const j=((A=p.get(y))==null?void 0:A.models)??[],N=!v.model||j.length===0||j.includes(v.model);return{...v,provider:y,...N?{}:{model:""}}})),g=x=>i(y=>y.filter((C,v)=>v!==x)),k=()=>i(x=>[...x,r2()]),h=(x,y)=>i(C=>{const v=x+y;if(v<0||v>=C.length)return C;const w=[...C];return[w[x],w[v]]=[w[v],w[x]],w}),b=(x,y)=>i(C=>C.map((v,w)=>{if(w!==x)return v;const j=v.difficulty.includes(y);return{...v,difficulty:j?v.difficulty.filter(N=>N!==y):[...v.difficulty,y]}})),S=()=>a(o.map(ep).filter(Boolean));return s.jsxs("div",{className:"flex flex-col gap-2",onClick:x=>x.stopPropagation(),children:[o.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:r("repoMesh.slotEditor.empty")}),o.map((x,y)=>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:["#",y+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:y===0,onClick:()=>h(y,-1),title:r("repoMesh.slotEditor.moveUp"),children:"↑"}),s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:y===o.length-1,onClick:()=>h(y,1),title:r("repoMesh.slotEditor.moveDown"),children:"↓"}),s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-status-error/30 text-status-error hover:bg-status-error/10",onClick:()=>g(y),"aria-label":r("repoMesh.slotEditor.removeSlot"),children:s.jsx(Dt,{size:12})})]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.provider")}),d.length>0?s.jsxs("select",{className:gn,value:x.provider,onChange:C=>f(y,C.target.value),children:[s.jsx("option",{value:"",children:r("repoMesh.slotEditor.select")}),d.map(C=>s.jsx("option",{value:C,children:C},C)),x.provider&&!d.includes(x.provider)&&s.jsx("option",{value:x.provider,children:x.provider})]}):s.jsx("input",{className:gn,value:x.provider,placeholder:"claude-cli",onChange:C=>m(y,{provider:C.target.value})})]}),(()=>{var N;const C=p.get(x.provider),v=(C==null?void 0:C.models)??[],w=(N=C==null?void 0:C.thinking)!=null&&N.length?["",...C.thinking]:n2,j=!!x.model&&v.length>0&&!v.includes(x.model);return s.jsxs(s.Fragment,{children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.model")}),v.length>0&&!j?s.jsxs("select",{className:gn,value:v.includes(x.model)?x.model:"",onChange:A=>m(y,{model:A.target.value==="__custom__"?" ":A.target.value}),children:[s.jsx("option",{value:"",children:r("repoMesh.slotEditor.providerDefault")}),v.map(A=>s.jsx("option",{value:A,children:A},A)),s.jsx("option",{value:"__custom__",children:r("repoMesh.slotEditor.custom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:gn,value:x.model.trim(),placeholder:x.provider?`${x.provider} model`:r("repoMesh.slotEditor.modelPlaceholder"),onChange:A=>m(y,{model:A.target.value})}),v.length>0&&s.jsx("button",{type:"button",className:"self-start bg-transparent border-none cursor-pointer p-0 text-[10px] text-text-muted hover:underline",onClick:()=>m(y,{model:""}),children:r("repoMesh.slotEditor.backToModelList")})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.thinking")}),s.jsx("select",{className:gn,value:x.thinkingLevel,onChange:A=>m(y,{thinkingLevel:A.target.value}),children:w.map(A=>s.jsx("option",{value:A,children:A||r("repoMesh.slotEditor.thinkingDefault")},A||"_default"))})]})]})})()]}),s.jsxs("div",{className:"mt-2",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.difficulty")}),s.jsx("div",{className:"mt-1 flex flex-wrap gap-1.5",children:om.map(C=>{const v=x.difficulty.includes(C);return s.jsx("button",{type:"button",className:`rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors ${v?"border-accent-primary/60 bg-accent-primary/15 text-accent-primary":"border-border-subtle bg-bg-primary/60 text-text-muted hover:text-text-primary"}`,onClick:()=>b(y,C),children:a2[C]},C)})})]}),s.jsxs("div",{className:"mt-2 grid grid-cols-1 sm:grid-cols-2 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.capabilityTags")}),s.jsx("input",{className:gn,value:x.capability.join(", "),placeholder:"worktree, os=darwin",onChange:C=>m(y,{capability:C.target.value.split(",").map(v=>v.trim()).filter(Boolean)})})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.maxParallel")}),s.jsx("input",{type:"number",inputMode:"numeric",min:1,className:gn,value:x.maxParallel,placeholder:r("repoMesh.slotEditor.maxParallelPlaceholder"),onChange:C=>m(y,{maxParallel:C.target.value})})]})]})]},y)),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(Wl,{size:13})," ",r("repoMesh.slotEditor.addSlot")]}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm ml-auto",onClick:S,disabled:!!n||!u,children:r(n?"repoMesh.slotEditor.saving":"repoMesh.slotEditor.saveSlots")})]})]})}function i2(e){const t=e.capabilities;return Array.isArray(t)?t.map(n=>typeof n=="string"?n.trim():"").filter(Boolean):[]}const l2=["os=","arch=","provider=","worktree=","converge="];function c2({node:e,saving:t,onSave:n}){const{t:a}=ke("common"),r=l.useMemo(()=>s2(e).filter(h=>!h.custom),[e]),o=l.useMemo(()=>i2(e),[e]),[i,c]=l.useState(o),[d,p]=l.useState(""),u=JSON.stringify(i)!==JSON.stringify(o),f=(h=>{const b=h.trim();return b?/\s/.test(b)?a("repoMesh.tagEditor.noSpaces"):l2.some(S=>b.toLowerCase().startsWith(S))?a("repoMesh.tagEditor.reservedPrefix"):i.includes(b)?a("repoMesh.tagEditor.alreadyAdded"):null:null})(d);function g(){const h=d.trim();!h||f||(c(b=>[...b,h]),p(""))}function k(h){c(b=>b.filter(S=>S!==h))}return s.jsxs("div",{className:"mt-2",onClick:h=>h.stopPropagation(),children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wide text-text-muted mr-1",children:a("repoMesh.tagEditor.routingTags")}),r.map(h=>s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-1.5 py-0.5 font-mono text-[10px] text-text-muted",title:a("repoMesh.tagEditor.autoDerivedTitle"),children:h.tag},h.tag)),i.map(h=>s.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 font-mono text-[10px] text-accent-primary",title:a("repoMesh.tagEditor.customTagTitle"),children:[h,s.jsx("button",{type:"button",className:"text-accent-primary/70 hover:text-accent-primary bg-transparent border-none cursor-pointer p-0 leading-none",onClick:()=>k(h),disabled:t,"aria-label":a("repoMesh.tagEditor.remove",{tag:h}),children:"×"})]},h))]}),s.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-2",children:[s.jsx("input",{type:"text",value:d,onChange:h=>p(h.target.value),onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),g())},placeholder:a("repoMesh.tagEditor.addPlaceholder"),disabled:t,className:"min-w-[12rem] flex-1 px-2 py-1 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-primary"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:g,disabled:t||!d.trim()||!!f,children:a("repoMesh.tagEditor.add")}),u&&s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>n(i),disabled:t,children:a(t?"repoMesh.tagEditor.saving":"repoMesh.tagEditor.saveTags")})]}),f&&s.jsx("div",{className:"mt-1 text-[11px] text-amber-400",children:f}),i.length===0&&r.length===0&&s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:a("repoMesh.tagEditor.empty")})]})}function d2(e,t){const n=t;return[...Array.isArray(n==null?void 0:n.cliSessions)?n.cliSessions:[],...Array.isArray(n==null?void 0:n.acpSessions)?n.acpSessions:[],...Array.isArray(n==null?void 0:n.sessions)?n.sessions:[]].filter(r=>{var o;return((o=r==null?void 0:r.settings)==null?void 0:o.meshNodeId)===e.id||(r==null?void 0:r.workspace)===e.workspace}).map(r=>{var o;return{id:r.sessionId||r.id||r.instanceId||"unknown",provider:r.providerType||r.cliType||r.acpType||r.type||"unknown",status:r.status||((o=r.activeChat)==null?void 0:o.status)||"unknown"}})}function u2(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 tp({nodes:e,meshQueue:t,activeDaemon:n,daemons:a,userName:r,features:o,providersByDaemonId:i,savingNodeSlotsId:c,onUpdateNodeSlots:d,savingNodeCapabilitiesId:p,onUpdateNodeCapabilities:u,nodeSystemPromptDrafts:m,onNodeSystemPromptDraftChange:f,savingNodeSystemPromptId:g,onSaveNodeSystemPrompt:k,selectedNodeId:h,onSelectNode:b,onRemoveNode:S}){const{t:x}=ke("common");return e.length===0?s.jsx(Xa,{icon:s.jsx(Tn,{}),title:x("repoMesh.nodeList.emptyTitle"),description:x("repoMesh.nodeList.emptyDescription")}):s.jsx("div",{className:"flex flex-col gap-2",children:e.map(y=>{var A;const C=f2(y),v=p2(y,t),w=d2(y,n),j=h===y.id,N=y.status||y.machine_status||(v.length>0||w.length>0?"active":"enabled");return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary transition-colors ${o.addNodeDaemonPicker?"bg-bg-glass border-border-subtle rounded-xl px-5 py-4":`cursor-pointer ${j?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`}`,role:o.addNodeDaemonPicker?void 0:"button",tabIndex:o.addNodeDaemonPicker?void 0:0,onClick:o.addNodeDaemonPicker?void 0:()=>b(j?null:y.id),onKeyDown:o.addNodeDaemonPicker?void 0:T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),b(j?null:y.id))},children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[o.addNodeDaemonPicker?s.jsx("span",{className:"font-semibold text-sm text-text-primary truncate",children:y.machine_label||y.machine_nickname||y.hostname||y.workspace}):s.jsx("span",{className:"text-sm font-medium",children:y.workspace.split("/").pop()}),o.addNodeDaemonPicker&&s.jsx(YL,{status:N}),o.addNodeDaemonPicker&&s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:x("repoMesh.nodeList.setupInventory")})]}),o.addNodeDaemonPicker&&s.jsx("div",{className:"text-[11px] text-text-muted",children:x("repoMesh.nodeList.ownerMachine",{owner:u2(a.find(T=>T.id===String(y.daemon_id||"")),r),machine:y.machine_label||y.daemon_id||y.workspace})}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:y.workspace}),s.jsx(c2,{node:y,saving:p===y.id,onSave:T=>u(y,T)}),o.addNodeDaemonPicker&&s.jsx("div",{className:"mt-2 text-[11px] text-amber-300",children:x("repoMesh.nodeList.liveDetailGraphOwned")}),s.jsxs("div",{className:"mt-3 max-w-2xl",onClick:T=>T.stopPropagation(),children:[s.jsx(Tt,{label:x("repoMesh.nodeList.slotsLabel"),hint:x("repoMesh.nodeList.slotsHint"),children:s.jsx(o2,{slots:Array.isArray((A=y.policy)==null?void 0:A.slots)?y.policy.slots:[],availableProviders:ZL(y,i),saving:c===y.id,onSave:T=>d(y,T)})}),o.nodeInstruction&&s.jsxs(Tt,{label:x("repoMesh.nodeList.nodeInstruction"),hint:x("repoMesh.nodeList.nodeInstructionHint"),children:[s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:3,value:m[y.id]??"",onChange:T=>{const I=T.target.value;f(y.id,I)},onClick:T=>T.stopPropagation(),disabled:g===y.id,placeholder:x("repoMesh.nodeList.nodeInstructionPlaceholder")}),s.jsx("div",{className:"mt-2 flex items-center gap-2",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:T=>{T.stopPropagation(),k(y)},disabled:g===y.id,children:g===y.id?x("repoMesh.nodeList.saving"):x("repoMesh.nodeList.saveInstruction")})})]})]})]}),s.jsx("button",{className:`transition-colors bg-transparent border-none cursor-pointer ${o.addNodeDaemonPicker?"btn btn-sm text-text-muted hover:text-red-400":"text-text-muted hover:text-red-400"}`,onClick:T=>{T.stopPropagation(),S(y.id)},title:x("repoMesh.nodeList.removeNode"),children:s.jsx(KL,{size:14})})]}),s.jsxs("details",{className:"mt-3 group",onClick:T=>T.stopPropagation(),children:[s.jsxs("summary",{className:"cursor-pointer select-none text-[12px] text-text-muted hover:text-text-secondary inline-flex items-center gap-1",children:[s.jsx("span",{className:"transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"})," ",x("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:x("repoMesh.nodeList.nodeId")})," ",s.jsx("span",{className:"font-mono break-all",children:y.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:x("repoMesh.nodeList.launchReady")})," ",s.jsx("span",{className:C.configured?"text-green-400":"text-amber-400",children:C.configured?x("repoMesh.nodeList.launchReadyYes"):x("repoMesh.nodeList.launchReadyNo")})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:x("repoMesh.nodeList.repoRoot")})," ",s.jsx("span",{className:"font-mono break-all",children:y.repoRoot||y.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:x("repoMesh.nodeList.activeSessionsLabel")})," ",w.length]}),o.addNodeDaemonPicker&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:x("repoMesh.nodeList.added")})," ",new Date(y.created_at||y.createdAt||Date.now()).toLocaleDateString()]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:x("repoMesh.nodeList.activeQueueAssignments")}),v.length===0?s.jsx("div",{children:x("repoMesh.nodeList.noActiveAssignment")}):s.jsx("ul",{className:"m-0 pl-4",children:v.map(T=>s.jsx("li",{className:"font-mono",children:m2(T)},T.id))})]}),w.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:x("repoMesh.nodeList.activeSessions")}),s.jsx("ul",{className:"m-0 pl-4",children:w.map(T=>s.jsxs("li",{className:"font-mono",children:[T.provider," / ",T.status," / ",T.id]},T.id))})]})]})]})]},y.id)})})}function p2(e,t){return t.filter(n=>n.status!=="assigned"?!1:(n.assignedNodeId||n.nodeId)===e.id)}function m2(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 h2(e){var r,o;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set,a=t.map(i=>typeof i=="string"?i.trim():"").filter(Boolean).filter(i=>n.has(i)?!1:(n.add(i),!0));return a.length?a:G0((o=e.policy)==null?void 0:o.slots)}function f2(e){const t=h2(e);return t.length?{configured:!0,label:t.join(" → ")}:{configured:!1,label:"not configured",launchBlockedMessage:"No provider configured on this node — task launch is blocked until a capability slot or provider priority is set."}}function jl(e){return e.isLocalWorktree===!0}function io(e){return e&&(e.machineNickname||e.nickname||e.hostname||(e.id?Rf(e.id):void 0))||"Unknown"}function g2(e){return String(e.daemon_id||e.daemonId||"")}function b2(e,t){const n=new Map(t.map(o=>[o.id,o])),a=[],r=new Map;for(const o of e){const i=g2(o);r.has(i)||(r.set(i,[]),a.push(i)),r.get(i).push(o)}return a.map(o=>{const i=r.get(o),c=o?n.get(o):void 0,d=i[0],p=o?c?io(c):(d==null?void 0:d.machine_label)||(d==null?void 0:d.machine_nickname)||(d==null?void 0:d.hostname)||o:io(c),u=(c==null?void 0:c.status)==="online",m=i.reduce((f,g)=>{var k;return f+(Array.isArray((k=g.policy)==null?void 0:k.slots)?g.policy.slots.length:0)},0);return{key:o,label:p,online:u,nodes:i,slotCount:m}})}function x2({groups:e,activeKey:t,onChange:n}){const{t:a}=ke("common");return s.jsx("div",{className:"flex items-center gap-1 px-1 border-b border-border-subtle mb-4 overflow-x-auto",role:"tablist","aria-label":a("repoMesh.nodeList.machineTabsLabel"),children:e.map(r=>{const o=r.key===t;return s.jsxs("button",{type:"button",role:"tab","aria-selected":o,onClick:()=>n(r.key),className:`flex items-center gap-2 px-3 py-2.5 text-[13px] font-medium border-b-2 -mb-px transition-colors cursor-pointer whitespace-nowrap ${o?"border-accent text-accent":"border-transparent text-text-muted hover:text-text-secondary"}`,children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${r.online?"bg-green-400":"bg-neutral-500"}`}),s.jsx("span",{className:"truncate max-w-[160px]",children:r.label}),s.jsx("span",{className:"text-[11px] text-text-muted font-normal",children:a("repoMesh.nodeList.machineTabCounts",{nodes:r.nodes.length,slots:r.slotCount})})]},r.key)})})}function v2({nodes:e,meshQueue:t,activeDaemon:n,daemons:a,selectedMeshId:r,userName:o,features:i,coordinatorDaemonId:c,availableCliProviders:d,savingNodeSlotsId:p,onUpdateNodeSlots:u,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:f,nodeSystemPromptDrafts:g,onNodeSystemPromptDraftChange:k,savingNodeSystemPromptId:h,onSaveNodeSystemPrompt:b,selectedNodeId:S,onSelectNode:x,showAddNode:y,onShowAddNode:C,onCancelAddNode:v,nodeWorkspace:w,onNodeWorkspaceChange:j,nodeProviderPriority:N,onNodeProviderPriorityChange:A,nodeDaemonId:T,onNodeDaemonIdChange:I,nodeCustomPath:P,onNodeCustomPathChange:M,nodePickerWorkspaces:E,nodePickerProviders:D,nodeOnboardingPlan:W,nodePlanLoading:R,attachableDaemons:B,onAddNode:_,onRemoveNode:H}){var Ce,me,O;const{t:L}=ke("common"),F=l.useMemo(()=>XL(a),[a]),$=l.useMemo(()=>e.filter(Y=>!jl(Y)),[e]),K=l.useMemo(()=>i.addNodeDaemonPicker?b2($,a):[],[i.addNodeDaemonPicker,$,a]),[z,ne]=l.useState(null),ie=K.some(Y=>Y.key===z)?z:((Ce=K[0])==null?void 0:Ce.key)??"";return s.jsxs(xt,{title:i.addNodeDaemonPicker?L("repoMesh.nodeList.title",{count:$.length}):L("repoMesh.nodeList.titleNoCount"),description:i.addNodeDaemonPicker?L("repoMesh.nodeList.descriptionCloud"):L("repoMesh.nodeList.descriptionStandalone"),children:[i.addNodeDaemonPicker&&s.jsxs("div",{className:"mb-4 rounded-xl border border-border-subtle bg-bg-secondary/60 p-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:L("repoMesh.nodeList.daemonCandidates")}),s.jsx("div",{className:"text-[12px] text-text-muted",children:L("repoMesh.nodeList.daemonCandidatesHint")})]}),s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:L("repoMesh.nodeList.available",{count:B.length})})]}),a.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:L("repoMesh.nodeList.noDaemonsAvailable")}):B.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:L("repoMesh.nodeList.allDaemonsAttached")}):s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:B.map(Y=>s.jsxs("button",{type:"button",className:`text-left rounded-lg border px-3 py-2 transition-colors min-w-0 ${Y.id===c?"border-accent-primary/50 bg-accent-primary/10":"border-border-subtle bg-bg-primary hover:border-border-default"}`,onClick:()=>{I(Y.id),j(""),M(!1),A(Dn(cn(Y.availableProviders||[]))),C()},children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-sm font-medium truncate min-w-0",children:io(Y)}),Y.id===c&&s.jsx("span",{className:"text-[10px] text-accent-primary shrink-0",children:L("repoMesh.nodeList.selectedHost")})]}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted font-mono truncate",children:Y.id}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:L("repoMesh.nodeList.workspacesDetected",{count:(Y.workspaces||[]).length})})]},Y.id))})]}),!y&&s.jsxs("button",{className:"btn btn-primary btn-sm mb-4 inline-flex items-center gap-1.5",onClick:C,children:[s.jsx(VL,{size:13})," ",i.addNodeDaemonPicker?L("repoMesh.nodeList.attachMachine"):L("repoMesh.nodeList.addNode")]}),y&&s.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass animate-[fadeIn_0.3s_ease-out]",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h4",{className:"text-sm font-bold",children:i.addNodeDaemonPicker?L("repoMesh.nodeList.attachMachineTitle"):L("repoMesh.nodeList.addNodeTitle")}),s.jsx("button",{onClick:()=>{v(),I(""),M(!1)},className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(Dt,{size:16})})]}),i.addNodeDaemonPicker&&s.jsx(Tt,{label:L("repoMesh.nodeList.machine"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:T,onChange:Y=>{var X;I(Y.target.value),j(""),M(!1),A(Dn(cn(((X=a.find(Q=>Q.id===Y.target.value))==null?void 0:X.availableProviders)||[])))},children:[s.jsx("option",{value:"",children:L("repoMesh.nodeList.selectMachine")}),a.map(Y=>s.jsx("option",{value:Y.id,children:io(Y)},Y.id))]})}),(i.addNodeDaemonPicker?T:!0)&&s.jsx(Tt,{label:L("repoMesh.nodeList.workspacePath"),children:i.addNodeDaemonPicker&&!P&&E.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex flex-col gap-1.5 mb-2",children:E.map(Y=>s.jsxs("button",{type:"button",className:`text-left text-xs px-3 py-2 rounded-lg border transition-colors ${w===Y.path?"border-accent-primary bg-accent-primary/10 text-text-primary":"border-border-subtle bg-bg-primary hover:bg-violet-500/10 text-text-primary"}`,onClick:()=>j(Y.path),children:[s.jsx("span",{className:"font-medium block truncate",children:Y.label||Y.path.split("/").pop()}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:Y.path})]},Y.id||Y.path))}),s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{M(!0),j("")},children:L("repoMesh.nodeList.enterCustomPath")})]}):s.jsx(s.Fragment,{children:i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[s.jsx(xs,{value:w,onChange:Y=>j(Y.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:Y=>{Y.key==="Enter"&&_()}}),E.length>0&&s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0 mt-1",onClick:()=>{M(!1),j("")},children:L("repoMesh.nodeList.pickFromSaved")})]}):(()=>{var Q;const Y=Array.isArray(n==null?void 0:n.workspaces)?n.workspaces:[],X=`mesh-add-node-workspaces-${r||"new"}`;return s.jsxs(s.Fragment,{children:[s.jsx(xs,{value:w,onChange:ve=>j(ve.target.value),placeholder:((Q=Y[0])==null?void 0:Q.path)||"/Users/dev/projects/myapp",list:Y.length>0?X:void 0,autoFocus:!0}),Y.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("datalist",{id:X,children:Y.map(ve=>s.jsx("option",{value:ve.path,children:ve.label||ve.path},ve.id||ve.path))}),s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:Y.slice(0,6).map(ve=>s.jsx("button",{type:"button",onClick:()=>j(ve.path),className:"text-[11px] px-2 py-0.5 rounded-full border border-border-subtle hover:border-accent-primary/50 text-text-muted hover:text-text-primary transition-colors bg-transparent cursor-pointer",title:ve.path,children:ve.label||ve.path.split("/").filter(Boolean).pop()||ve.path},ve.id||ve.path))})]})]})})()})}),(R||W)&&s.jsx(Mt,{variant:(W==null?void 0:W.success)===!1?"error":"info",className:"mb-4",children:R?"Inspecting Git repository (read-only)…":W!=null&&W.success?`${((me=W.plan)==null?void 0:me.summary)||"Compatible Git workspace detected."} Adding remains an explicit action.`:`${(W==null?void 0:W.code)||"onboarding_blocked"}: ${(W==null?void 0:W.error)||"Git discovery failed"} ${(W==null?void 0:W.action)||""}`}),s.jsx(Tt,{label:L("repoMesh.nodeList.preferredTools"),hint:L("repoMesh.nodeList.preferredToolsHint"),children:s.jsx(Yj,{value:N,availableProviders:i.addNodeDaemonPicker?D:d,onChange:A})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:_,disabled:R||(W==null?void 0:W.success)===!1||!w.trim()||i.addNodeDaemonPicker&&!T,className:"btn btn-primary btn-sm",children:L("repoMesh.nodeList.add")}),s.jsx("button",{onClick:()=>{v(),I(""),M(!1)},className:"btn btn-secondary btn-sm",children:L("repoMesh.nodeList.cancel")})]})]}),$.length===0?s.jsx(Xa,{icon:s.jsx(Tn,{}),title:L("repoMesh.nodeList.emptyTitle"),description:L("repoMesh.nodeList.emptyDescription")}):i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[K.length>1&&s.jsx(x2,{groups:K,activeKey:ie,onChange:ne}),s.jsx(tp,{nodes:((O=K.find(Y=>Y.key===ie))==null?void 0:O.nodes)||$,meshQueue:t,activeDaemon:n,daemons:a,userName:o,features:i,providersByDaemonId:F,savingNodeSlotsId:p,onUpdateNodeSlots:u,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:f,nodeSystemPromptDrafts:g,onNodeSystemPromptDraftChange:k,savingNodeSystemPromptId:h,onSaveNodeSystemPrompt:b,selectedNodeId:S,onSelectNode:x,onRemoveNode:H})]}):s.jsx(tp,{nodes:$,meshQueue:t,activeDaemon:n,daemons:a,userName:o,features:i,providersByDaemonId:F,savingNodeSlotsId:p,onUpdateNodeSlots:u,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:f,nodeSystemPromptDrafts:g,onNodeSystemPromptDraftChange:k,savingNodeSystemPromptId:h,onSaveNodeSystemPrompt:b,selectedNodeId:S,onSelectNode:x,onRemoveNode:H})]})}const y2=["claude-cli","codex-cli","gemini-cli","hermes-cli","antigravity-cli"],w2=[{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 k2(){return{nodeId:"",provider:"",model:"",n:""}}function sp(e){var t;return(t=e.providers)!=null&&t.length?e.providers.filter(Boolean):(e.providerPriority??[]).filter(Boolean)}function S2(e){return{nodeId:e.nodeId??"",provider:e.provider??"",model:e.model??"",n:e.n!=null?String(e.n):""}}function C2(e){const t=[];for(let n=0;n<e.length;n++){const a=e[n],r=a.provider.trim();if(!r)return{error:{code:"provider_required",slot:n+1}};const o=a.nodeId.trim(),i=a.model.trim(),c=a.n.trim();let d;if(c){const p=Number(c);if(!Number.isFinite(p)||p<1)return{error:{code:"replica_min",slot:n+1}};d=Math.floor(p)}t.push({provider:r,...o?{nodeId:o}:{},...i?{model:i}:{},...d!==void 0?{n:d}:{}})}return t.length===0?{error:{code:"no_slot"}}:{slots:t}}function j2({status:e,daemonId:t,sendDaemonCommand:n,availableProviders:a}){const{t:r}=ke(),{theme:o}=Rs(),i=l.useMemo(()=>Es(o),[o]),c=l.useMemo(()=>bh(a),[a]),[d,p]=l.useState({}),[u,m]=l.useState(!1),[f,g]=l.useState(null),[k,h]=l.useState({}),[b,S]=l.useState(null),x=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map($=>({nodeId:$.nodeId,machineLabel:$.machineLabel,providers:$.providers,providerPriority:$.providerPriority,isLocalWorktree:$.isLocalWorktree,worktreeBranch:$.worktreeBranch})),[e==null?void 0:e.nodes]),y=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map($=>$.nodeId),[e==null?void 0:e.nodes]),C=l.useMemo(()=>new Set(x.filter(jl).map($=>$.nodeId)),[x]),v=l.useMemo(()=>Object.fromEntries(x.filter(jl).map($=>[$.nodeId,$.worktreeBranch])),[x]),w=l.useMemo(()=>Object.fromEntries(((e==null?void 0:e.nodes)??[]).map($=>[$.nodeId,$.machineLabel||$.nodeId])),[e==null?void 0:e.nodes]),j=l.useMemo(()=>{const $={};for(const K of x)$[K.nodeId]=sp(K);return $},[x]),N=l.useMemo(()=>{const $=[...new Set(x.flatMap(sp).filter(Boolean))];return[...new Set([...$,...y2])].sort()},[x]),A=!!t&&!!n,T=$=>$&&typeof $=="object"&&"result"in $?$.result:$,I=e==null?void 0:e.meshId,P=l.useCallback(async()=>{if(!(!t||!n)){m(!0),g(null);try{const $=await n(t,"magi_kind_panel_list",{...I?{meshId:I}:{}}),K=T($);if((K==null?void 0:K.success)===!1)throw new Error(K.error||r("meshGraph.magiKind.errorLoad"));p(K!=null&&K.kindPanels&&typeof K.kindPanels=="object"?K.kindPanels:{}),h({})}catch($){g(($==null?void 0:$.message)||r("meshGraph.magiKind.errorLoad"))}finally{m(!1)}}},[t,n,I,r]);l.useEffect(()=>{P()},[P]);const M=l.useCallback($=>{if(k[$])return k[$];const K=d[$];return K?K.map(S2):[]},[k,d]),E=($,K)=>{h(z=>({...z,[$]:K}))},D=($,K,z)=>{const ne=M($);E($,ne.map((ie,Ce)=>Ce===K?{...ie,...z}:ie))},W=$=>{E($,[...M($),k2()])},R=($,K)=>{E($,M($).filter((z,ne)=>ne!==K))},B=l.useCallback(async $=>{if(!t||!n)return;const K=C2(M($));if("error"in K){const z=K.error,ne=z.code==="provider_required"?r("meshGraph.magiKind.errorSlotProvider",{slot:z.slot}):z.code==="replica_min"?r("meshGraph.magiKind.errorSlotReplica",{slot:z.slot}):r("meshGraph.magiKind.errorNoSlot");g(`${$}: ${ne}`);return}S($),g(null);try{const z=await n(t,"magi_kind_panel_set",{kind:$,slots:K.slots,...I?{meshId:I}:{}}),ne=T(z);if((ne==null?void 0:ne.success)===!1)throw new Error(ne.error||r("meshGraph.magiKind.errorSave"));await P()}catch(z){g((z==null?void 0:z.message)||r("meshGraph.magiKind.errorSave"))}finally{S(null)}},[t,n,M,P,I,r]),_=l.useCallback(async $=>{if(!(!t||!n)&&confirm(r("meshGraph.magiKind.removeConfirm",{kind:$}))){S($),g(null);try{const K=await n(t,"magi_kind_panel_remove",{kind:$,...I?{meshId:I}:{}}),z=T(K);if((z==null?void 0:z.success)===!1)throw new Error(z.error||r("meshGraph.magiKind.errorRemove"));await P()}catch(K){g((K==null?void 0:K.message)||r("meshGraph.magiKind.errorRemove"))}finally{S(null)}}},[t,n,P,I,r]),H=`w-full rounded-lg border px-2.5 py-1.5 text-xs ${i.isDark?"border-white/10 bg-slate-950/40 text-slate-100 placeholder:text-slate-500":"border-slate-300 bg-white text-slate-900 placeholder:text-slate-400"}`,L="btn btn-primary btn-sm",F="btn btn-secondary btn-sm";return s.jsxs("div",{className:"flex flex-col gap-3 p-1",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("p",{className:`text-[12px] ${i.textSecondary}`,children:r("meshGraph.magiKind.intro")}),s.jsx("div",{className:"ml-auto flex items-center gap-2",children:s.jsx("button",{type:"button",className:F,onClick:()=>void P(),disabled:u||!A,children:r(u?"meshGraph.magiKind.loading":"meshGraph.magiKind.refresh")})})]}),!A&&s.jsx("div",{className:`rounded-xl border p-3 text-[12px] ${i.textSecondary} ${i.isDark?"border-white/10":"border-slate-200"}`,children:r("meshGraph.magiKind.connectPrompt")}),f&&s.jsx("div",{className:"rounded-xl border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-[12px] text-rose-300",children:f}),s.jsx("div",{className:"flex flex-col gap-3",children:w2.map(({kind:$,labelKey:K,hint:z})=>{const ne=M($),ie=!!d[$],Ce=b===$;return s.jsxs("div",{className:`${i.cardClass} rounded-2xl p-4 flex flex-col gap-3`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[13px] font-semibold ${i.textPrimary}`,children:r(K)}),s.jsx("span",{className:`font-mono text-[10px] ${i.textMuted}`,children:z}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${ie?"border-emerald-400/30 bg-emerald-500/10 text-emerald-300":"border-slate-400/20 bg-slate-500/10 text-slate-300"}`,children:ie?r("meshGraph.magiKind.agentCount",{count:d[$].length}):r("meshGraph.magiKind.off")})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[ne.length===0&&s.jsx("div",{className:`rounded-xl border p-2.5 text-[11px] ${i.textSecondary} ${i.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:r("meshGraph.magiKind.noAgents")}),ne.map((me,O)=>{const Y=me.nodeId?j[me.nodeId]??[]:[],X=me.nodeId&&Y.length?Y:N;return s.jsxs("div",{className:`rounded-xl border p-2.5 grid grid-cols-1 sm:grid-cols-[1fr_1fr_1fr_auto_auto] gap-x-2 gap-y-1 items-start ${i.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:r("meshGraph.magiKind.machine")}),s.jsxs("select",{className:H,value:me.nodeId,onChange:Q=>D($,O,{nodeId:Q.target.value}),title:r("meshGraph.magiKind.machineTitle"),children:[s.jsx("option",{value:"",children:r("meshGraph.magiKind.anyMachine")}),y.map(Q=>{const ve=C.has(Q),he=ve?r("meshGraph.magiKind.worktreeSuffix",{label:w[Q]??Q,branch:v[Q]||r("meshGraph.magiKind.worktreeUnknownBranch")}):w[Q]??Q;return s.jsx("option",{value:Q,disabled:ve,title:ve?r("meshGraph.magiKind.worktreeDisabledTitle"):void 0,children:he},Q)}),me.nodeId&&!y.includes(me.nodeId)&&s.jsx("option",{value:me.nodeId,children:r("meshGraph.magiKind.offlineSuffix",{label:w[me.nodeId]??me.nodeId})})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsxs("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:[r("meshGraph.magiKind.provider")," *"]}),s.jsxs("select",{className:H,value:me.provider,onChange:Q=>D($,O,{provider:Q.target.value}),title:r("meshGraph.magiKind.providerTitle"),children:[s.jsx("option",{value:"",children:r("meshGraph.magiKind.selectProvider")}),X.map(Q=>s.jsx("option",{value:Q,children:Q},Q)),me.provider&&!X.includes(me.provider)&&s.jsx("option",{value:me.provider,children:me.provider})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:r("meshGraph.magiKind.model")}),(()=>{var he;const Q=(me.provider?(he=c.get(me.provider))==null?void 0:he.models:void 0)??[],ve=!!me.model&&Q.length>0&&!Q.includes(me.model);return Q.length>0&&!ve?s.jsxs("select",{className:H,value:Q.includes(me.model)?me.model:"",title:r("meshGraph.magiKind.modelTitle"),onChange:Z=>D($,O,{model:Z.target.value==="__custom__"?" ":Z.target.value}),children:[s.jsx("option",{value:"",children:r("meshGraph.magiKind.modelDefault")}),Q.map(Z=>s.jsx("option",{value:Z,children:Z},Z)),s.jsx("option",{value:"__custom__",children:r("meshGraph.magiKind.modelCustom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:H,value:me.model.trim(),placeholder:r("meshGraph.magiKind.modelDefault"),title:r("meshGraph.magiKind.modelTitle"),onChange:Z=>D($,O,{model:Z.target.value})}),Q.length>0&&s.jsx("button",{type:"button",className:`self-start bg-transparent border-none cursor-pointer p-0 text-[10px] ${i.textSecondary} hover:underline`,onClick:()=>D($,O,{model:""}),children:r("meshGraph.magiKind.backToModelList")})]})})()]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:r("meshGraph.magiKind.copies")}),s.jsx("input",{className:`${H} sm:w-16`,value:me.n,placeholder:"1",inputMode:"numeric",title:r("meshGraph.magiKind.copiesTitle"),onChange:Q=>D($,O,{n:Q.target.value})})]}),s.jsx("button",{type:"button",className:`${F} sm:mt-[18px] inline-flex h-8 w-8 items-center justify-center p-0`,onClick:()=>R($,O),"aria-label":r("meshGraph.magiKind.removeAgent"),title:r("meshGraph.magiKind.removeAgent"),children:"✕"})]},O)}),s.jsx("div",{children:s.jsx("button",{type:"button",className:F,onClick:()=>W($),disabled:!A,children:r("meshGraph.magiKind.addAgent")})})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:L,onClick:()=>void B($),disabled:Ce||!A,children:r(Ce?"meshGraph.magiKind.saving":"meshGraph.magiKind.save")}),s.jsx("button",{type:"button",className:F,onClick:()=>void _($),disabled:Ce||!A||!ie,title:r(ie?"meshGraph.magiKind.removeBindingTitle":"meshGraph.magiKind.removeBindingDisabledTitle"),children:r("meshGraph.magiKind.removeBinding")})]})]},$)})})]})}const On={sessionMinRemainingPercent:10,weeklyMinRemainingPercent:15,sessionResetImminentMinutes:5,staleAfterMinutes:30,spreadBonusMax:30,sessionAxisWeeklyHeadroomPercent:40},Nl=60*1e3;function np(e){return e===void 0||!Number.isFinite(e)?"":String(e/Nl)}function Al(e){const t=e??{};return{sessionMinRemainingPercent:t.sessionMinRemainingPercent!==void 0?String(t.sessionMinRemainingPercent):"",weeklyMinRemainingPercent:t.weeklyMinRemainingPercent!==void 0?String(t.weeklyMinRemainingPercent):"",sessionResetImminentMinutes:np(t.sessionResetImminentMs),staleAfterMinutes:np(t.staleAfterMs),spreadBonusMax:t.spreadBonusMax!==void 0?String(t.spreadBonusMax):"",sessionAxisWeeklyHeadroomPercent:t.sessionAxisWeeklyHeadroomPercent!==void 0?String(t.sessionAxisWeeklyHeadroomPercent):""}}function N2(e,t){const n=t.trim();if(!n)return null;const a=Number(n);if(!Number.isFinite(a))return"notANumber";const r=e==="sessionMinRemainingPercent"||e==="weeklyMinRemainingPercent"||e==="sessionAxisWeeklyHeadroomPercent";return r&&(a<0||a>100)?"percentRange":!r&&a<0?"negative":null}function Tl(e){const t={},n=p=>{const u=p.trim();if(!u)return;const m=Number(u);return Number.isFinite(m)?m:void 0},a=n(e.sessionMinRemainingPercent);a!==void 0&&(t.sessionMinRemainingPercent=a);const r=n(e.weeklyMinRemainingPercent);r!==void 0&&(t.weeklyMinRemainingPercent=r);const o=n(e.sessionResetImminentMinutes);o!==void 0&&(t.sessionResetImminentMs=o*Nl);const i=n(e.staleAfterMinutes);i!==void 0&&(t.staleAfterMs=i*Nl);const c=n(e.spreadBonusMax);c!==void 0&&(t.spreadBonusMax=c);const d=n(e.sessionAxisWeeklyHeadroomPercent);return d!==void 0&&(t.sessionAxisWeeklyHeadroomPercent=d),t}const A2="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs",T2="w-full rounded-lg border border-red-500/60 bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function M2({quotaRouting:e,saving:t,error:n,onSave:a}){const{t:r}=ke("common"),[o,i]=l.useState(()=>Al(e)),c=l.useCallback((k,h)=>{i(b=>({...b,[k]:h}))},[]),d=l.useMemo(()=>{const k={};for(const h of Object.keys(o)){const b=N2(h,o[h]);b&&(k[h]=b)}return k},[o]),p=Object.keys(d).length>0,u=l.useMemo(()=>JSON.stringify(Tl(o))!==JSON.stringify(P2(e)),[o,e]),m=l.useCallback(()=>{p||a(Tl(o))},[o,p,a]),f=l.useCallback(()=>{i(Al(null))},[]),g=[{key:"sessionMinRemainingPercent",label:r("setupWizard.quotaPolicy.sessionMin"),hint:r("setupWizard.quotaPolicy.sessionMinHint"),placeholder:On.sessionMinRemainingPercent,unit:"%"},{key:"weeklyMinRemainingPercent",label:r("setupWizard.quotaPolicy.weeklyMin"),hint:r("setupWizard.quotaPolicy.weeklyMinHint"),placeholder:On.weeklyMinRemainingPercent,unit:"%"},{key:"sessionResetImminentMinutes",label:r("setupWizard.quotaPolicy.resetImminent"),hint:r("setupWizard.quotaPolicy.resetImminentHint"),placeholder:On.sessionResetImminentMinutes,unit:r("setupWizard.quotaPolicy.minutes")},{key:"staleAfterMinutes",label:r("setupWizard.quotaPolicy.staleAfter"),hint:r("setupWizard.quotaPolicy.staleAfterHint"),placeholder:On.staleAfterMinutes,unit:r("setupWizard.quotaPolicy.minutes")},{key:"spreadBonusMax",label:r("setupWizard.quotaPolicy.spreadBonus"),hint:r("setupWizard.quotaPolicy.spreadBonusHint"),placeholder:On.spreadBonusMax,unit:""},{key:"sessionAxisWeeklyHeadroomPercent",label:r("setupWizard.quotaPolicy.sessionAxisWeeklyHeadroom"),hint:r("setupWizard.quotaPolicy.sessionAxisWeeklyHeadroomHint"),placeholder:On.sessionAxisWeeklyHeadroomPercent,unit:"%"}];return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:r("setupWizard.quotaPolicy.title")}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-text-muted",children:r("setupWizard.quotaPolicy.description")})]}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 sm:grid-cols-2",children:g.map(k=>{const h=d[k.key];return s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsxs("span",{className:"text-[11px] text-text-muted",children:[k.label,k.unit?` (${k.unit})`:""]}),s.jsx("input",{type:"number",inputMode:"decimal",className:h?T2:A2,value:o[k.key],placeholder:String(k.placeholder),onChange:b=>c(k.key,b.target.value)}),s.jsx("span",{className:`text-[10px] leading-snug ${h?"text-red-400":"text-text-muted"}`,children:h?r(`setupWizard.quotaPolicy.errors.${h}`):k.hint})]},k.key)})}),s.jsx("p",{className:"text-[10px] leading-relaxed text-text-muted",children:r("setupWizard.quotaPolicy.blankMeansDefault")}),n?s.jsx("p",{className:"text-[11px] text-red-400",children:n}):null,s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:f,children:r("setupWizard.quotaPolicy.useDefaults")}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm ml-auto",onClick:m,disabled:!!t||p||!u,children:r(t?"setupWizard.quotaPolicy.saving":"setupWizard.quotaPolicy.save")})]})]})}function P2(e){return Tl(Al(e))}function dg(e,t,n,a){const{t:r}=ke(),[o,i]=l.useState(!1),[c,d]=l.useState(null),[p,u]=l.useState(null),[m,f]=l.useState(null),g=l.useCallback(async()=>{if(!e||!t){d(r("repoMesh.promptPreview.connectPrompt"));return}i(!0),d(null);try{const k=await a(e,"coordinator_prompt_preview",{meshId:t,cliType:n}),h=k!=null&&k.result&&typeof k.result=="object"?k.result:k;if(!(h!=null&&h.success))return d((h==null?void 0:h.error)||r("repoMesh.promptPreview.errorRender")),null;const b=typeof h.prompt=="string"?h.prompt:"";return u(b),f(typeof h.bytes=="number"?h.bytes:null),b}catch(k){return d((k==null?void 0:k.message)||String(k)),null}finally{i(!1)}},[e,t,n,a,r]);return{loading:o,error:c,prompt:p,bytes:m,load:g}}function D2({daemonId:e,meshId:t,cliType:n,sendCommand:a,defaultOpen:r=!1}){const{t:o}=ke(),[i,c]=l.useState(r),{loading:d,error:p,prompt:u,bytes:m,load:f}=dg(e,t,n,a),g=l.useRef(!1);l.useEffect(()=>{i&&!g.current&&(g.current=!0,f())},[i,f]);const k=l.useCallback(()=>{c(h=>!h)},[]);return s.jsxs("div",{className:"mt-2",children:[s.jsxs("button",{type:"button",onClick:k,className:"inline-flex items-center gap-1 text-[12px] text-accent-primary bg-transparent border-none cursor-pointer p-0",children:[s.jsx("span",{className:`transition-transform ${i?"rotate-90":""}`,"aria-hidden":!0,children:"▸"}),o(i?"repoMesh.promptPreview.hide":"repoMesh.promptPreview.view"),s.jsxs("span",{className:"text-text-muted",children:["(",n,")"]})]}),i&&s.jsxs("div",{className:"mt-2",children:[d&&s.jsx("div",{className:"text-[12px] text-text-muted",children:o("repoMesh.promptPreview.rendering")}),p&&s.jsxs("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:[p,s.jsx("button",{type:"button",onClick:()=>void f(),className:"ml-2 underline bg-transparent border-none cursor-pointer text-amber-300",children:o("repoMesh.promptPreview.retry")})]}),!d&&!p&&u!==null&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between text-[11px] text-text-muted",children:[s.jsx("span",{children:o("repoMesh.promptPreview.info")}),m!==null&&s.jsxs("span",{children:[(m/1024).toFixed(1)," KB"]})]}),s.jsx("textarea",{readOnly:!0,value:u,rows:14,className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-secondary font-mono",onFocus:h=>h.currentTarget.select()})]})]})]})}function I2({daemonId:e,meshId:t,cliType:n,sendCommand:a,disabled:r,hasContent:o,onApply:i}){const{t:c}=ke(),{loading:d,load:p}=dg(e,t,n,a),u=l.useCallback(async()=>{if(o&&!window.confirm(c("repoMesh.detail.startFromDefaultConfirm")))return;const m=await p();typeof m=="string"&&i(m)},[o,p,i,c]);return s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm mt-2",onClick:()=>void u(),disabled:r||d||!e||!t,title:c("repoMesh.detail.startFromDefaultTitle"),children:c(d?"repoMesh.promptPreview.rendering":"repoMesh.detail.startFromDefault")})}const L2=[{token:"meshName",description:"This mesh's display name.",example:"my-app"},{token:"repo",description:"Repo identity (owner/repo or workspace path).",example:"vilmire/adhdev"},{token:"defaultBranch",description:"The mesh's default branch.",example:"main"},{token:"cliType",description:"The coordinator CLI type this prompt is being rendered for.",example:"claude-cli"},{token:"nodes",description:"Live node status table, or the configured node list if no live status is available.",example:"(rendered node table)"},{token:"mission",description:"Current mission section, when a mission is active. Empty otherwise.",example:"(mission summary or empty)"},{token:"recentActivity",description:"Recent mesh activity summary. Empty when none.",example:"(recent activity or empty)"},{token:"operatingNotes",description:"Accumulated operating notes for this mesh. Empty when none.",example:"(operating notes or empty)"},{token:"policy",description:"The mesh's effective policy section (safety, scheduling, etc.).",example:"(rendered policy section)"},{token:"tools",description:"The canonical MCP tools reference table.",example:"(tools table)"},{token:"workflow",description:"The standard coordinator workflow guidance section.",example:"(workflow section)"},{token:"onboarding",description:"Onboarding/reinit guidance section.",example:"(onboarding section)"},{token:"rules",description:"CLI-type-specific and policy-derived rules section.",example:"(rules section)"},{token:"toolExposurePreflight",description:"Preflight guidance for verifying tool exposure before relying on it.",example:"(preflight section)"}],R2=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function E2(e){const t=R2(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function _2(e){const t=e==null?void 0:e.missions;return Array.isArray(t)?t:[]}function H2(e){return typeof e.goal=="string"&&e.goal?{text:e.goal,truncated:!1}:{text:e.goalPreview??"",truncated:e.goalTruncated===!0}}const $2=["active","paused","completed","abandoned"];function ap(e){return(e.status||"active").toLowerCase()}const F2=8;function B2({status:e,daemonId:t,meshId:n,sendCommand:a}){const{t:r}=ke("common"),o=l.useMemo(()=>_2(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"),[b,S]=l.useState(!1),x=l.useMemo(()=>{const A={};for(const T of o){const I=ap(T);A[I]=(A[I]||0)+1}return A},[o]),y=l.useMemo(()=>k==="all"?o:o.filter(A=>ap(A)===k),[o,k]),C=b?y:y.slice(0,F2),v=y.length-C.length,w=!!t&&o.length>0,j=l.useCallback(async()=>{if(t){m(!0),g(null);try{const A=await a(t,"mesh_status",{meshId:n,verbose:!0}),T=E2(A),I=Array.isArray(T==null?void 0:T.missions)?T.missions:[],P={};for(const M of I)M.id&&typeof M.goal=="string"&&M.goal&&(P[M.id]=M.goal);c(M=>({...M,...P}))}catch(A){g(A instanceof Error?A.message:r("repoMesh.missions.errorFetch"))}finally{m(!1)}}},[t,n,a,r]),N=l.useCallback(A=>{p(T=>({...T,[A]:!T[A]})),!d[A]&&!i[A]&&j()},[d,i,j]);return o.length===0?null:s.jsxs(xt,{title:r("repoMesh.missions.title"),description:r("repoMesh.missions.description"),children:[f&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400",children:f}),s.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-1.5",children:[$2.filter(A=>(x[A]||0)>0).map(A=>s.jsxs("button",{type:"button",onClick:()=>{h(A),S(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] capitalize transition-colors ${k===A?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:[A," ",x[A]]},A)),s.jsxs("button",{type:"button",onClick:()=>{h("all"),S(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] transition-colors ${k==="all"?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:["All ",o.length]})]}),y.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:r("repoMesh.missions.empty",{status:k})}),s.jsx("div",{className:"flex flex-col gap-2",children:C.map(A=>{var W;const T=d[A.id]===!0,I=i[A.id],P=H2(A),M=T&&I?I:P.text,E=T&&!I&&P.truncated,D=((W=A.tasks)==null?void 0:W.total)??0;return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 px-3 py-2.5",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-text-primary",title:A.title,children:A.title||A.id}),A.status&&s.jsx("span",{className:"shrink-0 rounded-full border border-border-subtle px-2 py-0.5 text-[10px] uppercase tracking-wide text-text-muted",children:A.status}),D>0&&s.jsx("span",{className:"shrink-0 text-[11px] text-text-muted",children:r("repoMesh.missions.taskCount",{count:D})})]}),M&&s.jsxs("div",{className:`mt-1.5 whitespace-pre-wrap text-[12px] leading-5 text-text-secondary ${T?"max-h-72 overflow-y-auto":"line-clamp-2"}`,children:[M,E&&s.jsx("span",{className:"text-text-muted",children:r("repoMesh.missions.goalUnavailable")})]}),(P.truncated||I)&&w&&s.jsx("button",{type:"button",className:"mt-1.5 text-[12px] text-accent-primary hover:underline disabled:opacity-50",onClick:()=>N(A.id),disabled:u,children:r(T?"repoMesh.missions.showLess":u&&!I?"repoMesh.missions.loading":"repoMesh.missions.showFullGoal")})]},A.id)})}),v>0&&s.jsx("button",{type:"button",className:"mt-2 text-[12px] text-accent-primary hover:underline",onClick:()=>S(!0),children:r("repoMesh.missions.showMore",{count:v})})]})}function rp(e,t){if(t)return e.modes.find(n=>n.id===t)}function W2(e){return e.modes.find(t=>t.strategy==="pty-parse-default"&&qs(t)!=="dangerous")}function O2({config:e,requestedModeId:t,machineAutoApproveEnabled:n,machineDangerousAllowed:a}){const r=rp(e,e.default),o=r==null?void 0:r.id,i=(t==null?void 0:t.trim())||void 0;if(!n)return{status:"disabled",requestedModeId:i,providerDefaultModeId:o,requestedModeUnknown:!1,downgraded:!1};const c=rp(e,i),d=!!i&&!c,p=c??r;if(!p||p.strategy==="post-boot-command")return{status:"none",requestedModeId:i,providerDefaultModeId:o,requestedModeUnknown:d,downgraded:!1};if(qs(p)==="dangerous"&&!a){const u=W2(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 U2(e){const t=[];for(const n of e||[]){if(!n||n.category!=="cli")continue;const a=n.autoApproveModes;if(!a||!Array.isArray(a.modes)||a.modes.length===0)continue;const r=String(n.type||n.id||"").trim();r&&t.push({type:r,label:String(n.displayName||n.name||r),autoApproveModes:a})}return t}function G2({hostDaemonId:e,hostOnline:t,hostWorkspace:n,meshProviders:a,unreportedNodeCount:r=0,machineAutoApproveEnabled:o,machineDangerousAllowed:i,onUpdatePolicy:c,savingPolicy:d,sendCommand:p}){const{t:u}=ke("common"),m=l.useMemo(()=>U2(a),[a]),[f,g]=l.useState({}),[k,h]=l.useState(!1),[b,S]=l.useState(null),[x,y]=l.useState(!1),[C,v]=l.useState(null),[w,j]=l.useState(!1),[N,A]=l.useState(null),[T,I]=l.useState(!1),P=!!e&&t&&!!n,M=!!c&&!d,E=l.useCallback(async()=>{var _,H,L;if(P){h(!0),S(null);try{const F=await p(e,"read_mesh_json_config",{workspace:n}),$=(F==null?void 0:F.result)??F,K=((_=$==null?void 0:$.providerDefaults)==null?void 0:_.autoApproveModes)||((L=(H=$==null?void 0:$.config)==null?void 0:H.providerDefaults)==null?void 0:L.autoApproveModes),z={};if(K&&typeof K=="object")for(const[ne,ie]of Object.entries(K))typeof ie=="string"&&ie.trim()&&(z[ne]=ie.trim());g(z)}catch(F){S((F==null?void 0:F.message)||u("repoMesh.providerAutoApprove.loadError"))}finally{h(!1)}}},[P,e,n,p,u]);l.useEffect(()=>{E()},[E]);const D=l.useCallback((_,H)=>{j(!1),g(L=>{const F={...L};return H&&H.trim()?F[_]=H.trim():delete F[_],F})},[]),W=l.useCallback((_,H)=>{if(qs(H)==="dangerous"){A({type:_,mode:H});return}D(_,H.id)},[D]),R=l.useCallback(()=>{N&&D(N.type,N.mode.id),A(null)},[D,N]),B=l.useCallback(async()=>{if(P){y(!0),v(null),j(!1);try{const _=await p(e,"set_mesh_provider_defaults",{workspace:n,autoApproveModes:f,merge:!1,write:!0}),H=(_==null?void 0:_.result)??_;if((H==null?void 0:H.success)===!1)throw new Error((H==null?void 0:H.error)||u("repoMesh.providerAutoApprove.saveError"));j(!0),await E()}catch(_){v((_==null?void 0:_.message)||u("repoMesh.providerAutoApprove.saveError"))}finally{y(!1)}}},[P,e,n,E,f,p,u]);return s.jsxs(xt,{title:u("repoMesh.providerAutoApprove.title"),description:u("repoMesh.providerAutoApprove.subtitle"),collapsible:!0,defaultOpen:!1,children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/40 p-3.5",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:u("repoMesh.providerAutoApprove.machineSection.title")}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:u("repoMesh.providerAutoApprove.machineSection.hint")}),s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2 text-[11px]",children:[s.jsx("span",{className:`rounded-full border px-2 py-0.5 font-semibold ${o?"border-status-online/25 bg-status-online/10 text-status-online":"border-border-subtle bg-surface-secondary/40 text-text-muted"}`,children:u(o?"repoMesh.providerAutoApprove.machineSection.autoApproveOn":"repoMesh.providerAutoApprove.machineSection.autoApproveOff")}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 font-semibold ${i?"border-status-error/30 bg-status-error/10 text-status-error":"border-border-subtle bg-surface-secondary/40 text-text-muted"}`,children:u(i?"repoMesh.providerAutoApprove.machineSection.dangerousOn":"repoMesh.providerAutoApprove.machineSection.dangerousOff")})]}),s.jsxs("div",{className:"mt-3 space-y-2",children:[s.jsx(op,{label:u("repoMesh.providerAutoApprove.machineSection.autoApproveToggleLabel"),hint:u("repoMesh.providerAutoApprove.machineSection.autoApproveToggleHint"),checked:o,disabled:!M,onChange:_=>c==null?void 0:c({delegatedWorkerAutoApprove:_})}),s.jsx(op,{label:u("repoMesh.providerAutoApprove.machineSection.dangerousToggleLabel"),hint:u(o?"repoMesh.providerAutoApprove.machineSection.dangerousToggleHint":"repoMesh.providerAutoApprove.machineSection.dangerousDisabledHint"),checked:i,disabled:!M||!o,onChange:_=>{_?I(!0):c==null||c({delegatedWorkerDangerousModeAllow:!1})}})]})]}),P?k?s.jsx("div",{className:"text-[13px] text-text-muted",children:u("repoMesh.providerAutoApprove.loading")}):m.length===0?s.jsx("div",{className:"text-[13px] text-text-muted",children:r>0?u("repoMesh.providerAutoApprove.awaitingNodes",{count:r}):u("repoMesh.providerAutoApprove.noProviders")}):s.jsxs("div",{className:"space-y-6",children:[b&&s.jsx(Mt,{variant:"error",onDismiss:()=>S(null),children:b}),r>0&&s.jsx("div",{className:"text-[11px] text-text-muted",children:u("repoMesh.providerAutoApprove.partialInventory",{count:r})}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:u("repoMesh.providerAutoApprove.repoSection.title")}),s.jsx("div",{className:"text-[11px] text-text-muted",children:u("repoMesh.providerAutoApprove.repoSection.hint")})]}),s.jsx("div",{className:"space-y-5",children:m.map(_=>{const H=f[_.type],L=O2({config:_.autoApproveModes,requestedModeId:H,machineAutoApproveEnabled:o,machineDangerousAllowed:i});return s.jsxs("div",{className:"rounded-xl border border-border-subtle p-3.5",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary",children:_.label}),s.jsx("button",{type:"button",className:"text-[11px] text-text-muted underline decoration-dotted hover:text-text-primary disabled:opacity-40",onClick:()=>D(_.type,void 0),disabled:!H||x,children:u("repoMesh.providerAutoApprove.repoSection.clear")})]}),s.jsx(hf,{config:_.autoApproveModes,selectedModeId:H||"",disabled:x,onSelectMode:F=>W(_.type,F)}),!H&&s.jsx("div",{className:"mt-1.5 text-[11px] text-text-muted",children:u("repoMesh.providerAutoApprove.repoSection.usesProviderDefault")}),s.jsx(q2,{effective:L,config:_.autoApproveModes})]},_.type)})}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:u("repoMesh.providerAutoApprove.effectiveSection.title")}),s.jsx("div",{className:"text-[11px] text-text-muted",children:u("repoMesh.providerAutoApprove.effectiveSection.hint")})]}),C&&s.jsx(Mt,{variant:"error",onDismiss:()=>v(null),children:C}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("button",{type:"button",className:"rounded-lg bg-accent-primary px-4 py-2 text-sm font-semibold text-white disabled:opacity-50",onClick:()=>void B(),disabled:x,children:u(x?"repoMesh.providerAutoApprove.saving":"repoMesh.providerAutoApprove.save")}),w&&s.jsx("span",{className:"text-[12px] text-status-online",children:u("repoMesh.providerAutoApprove.saved")})]})]}):s.jsx("div",{className:"text-[13px] text-text-muted",children:u("repoMesh.providerAutoApprove.noHostDaemon")}),T&&s.jsx(Ao,{title:u("repoMesh.providerAutoApprove.machineSection.confirmTitle"),description:u("repoMesh.providerAutoApprove.machineSection.confirmDescription"),details:[{label:u("repoMesh.providerAutoApprove.machineSection.confirmScopeLabel"),value:u("repoMesh.providerAutoApprove.machineSection.confirmScopeValue")},{label:u("repoMesh.providerAutoApprove.machineSection.confirmEffectLabel"),value:u("repoMesh.providerAutoApprove.machineSection.confirmEffectValue")}],confirmLabel:u("repoMesh.providerAutoApprove.machineSection.confirmConfirm"),onConfirm:()=>{I(!1),c==null||c({delegatedWorkerDangerousModeAllow:!0})},onCancel:()=>I(!1)}),N&&s.jsx(ff,{mode:N.mode,onConfirm:R,onCancel:()=>A(null)}),N&&s.jsx("div",{className:"fixed inset-x-0 bottom-6 z-[60] mx-auto max-w-lg px-4",children:s.jsxs("div",{className:"rounded-xl border border-status-error/40 bg-bg-primary p-3.5 shadow-lg",children:[s.jsx("div",{className:"text-sm font-semibold text-status-error",children:u("repoMesh.providerAutoApprove.dangerous.sharedWarningTitle")}),s.jsx("div",{className:"mt-1 text-[12px] text-text-muted",children:u("repoMesh.providerAutoApprove.dangerous.sharedWarning")})]})})]})}function q2({effective:e,config:t}){var c,d,p;const{t:n}=ke("common"),a=u=>{var m;return(u?(m=t.modes.find(f=>f.id===u))==null?void 0:m.label:void 0)||u||""};let r,o="ok";switch(e.status){case"requested":r=n("repoMesh.providerAutoApprove.effectiveSection.statusRequested",{mode:((c=e.effectiveMode)==null?void 0:c.label)||""});break;case"invalid_fallback":r=n("repoMesh.providerAutoApprove.effectiveSection.statusInvalidFallback",{mode:((d=e.effectiveMode)==null?void 0:d.label)||""}),o="warn";break;case"downgraded":r=n("repoMesh.providerAutoApprove.effectiveSection.statusDowngraded",{requested:a(e.requestedModeId)||a(e.providerDefaultModeId),mode:((p=e.effectiveMode)==null?void 0:p.label)||""}),o="warn";break;case"disabled":r=n("repoMesh.providerAutoApprove.effectiveSection.statusDisabled"),o="muted";break;default:r=n("repoMesh.providerAutoApprove.effectiveSection.statusNone"),o="muted"}const i=o==="ok"?"border-status-online/25 bg-status-online/5 text-text-secondary":o==="warn"?"border-status-warning/30 bg-status-warning/5 text-status-warning":"border-border-subtle bg-surface-secondary/30 text-text-muted";return s.jsxs("div",{className:`mt-3 flex items-center gap-2 rounded-lg border px-3 py-2 text-[12px] ${i}`,children:[e.effectiveMode&&s.jsx(mf,{risk:qs(e.effectiveMode)}),s.jsx("span",{className:"min-w-0",children:r})]})}function op({label:e,hint:t,checked:n,disabled:a=!1,onChange:r}){return s.jsxs("button",{type:"button",role:"switch","aria-checked":n,className:"flex w-full items-center justify-between gap-3 rounded-xl border border-border-subtle bg-bg-primary/60 px-3.5 py-2.5 text-left disabled:opacity-50",onClick:()=>r(!n),disabled:a,children:[s.jsxs("span",{children:[s.jsx("span",{className:"block text-[13px] font-semibold text-text-primary",children:e}),s.jsx("span",{className:"mt-0.5 block text-[11px] text-text-muted",children:t})]}),s.jsx("span",{className:`relative h-6 w-11 shrink-0 rounded-full transition-colors ${n?"bg-accent-primary":"bg-surface-secondary"}`,children:s.jsx("span",{className:`absolute top-0.5 h-5 w-5 rounded-full bg-white shadow transition-transform ${n?"translate-x-5":"translate-x-0.5"}`})})]})}function Sr(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function z2({daemons:e,coordinatorDaemonId:t,onCoordinatorDaemonIdChange:n,isHostNodeAttached:a,selectedHostNode:r,hostPinned:o,hostLabel:i,hostOnline:c,hostRebindDaemonId:d,onHostRebindDaemonIdChange:p,settingMeshHost:u,onSetMeshHost:m}){const{t:f}=ke("common");if(o)return s.jsxs(xt,{title:f("repoMesh.host.title"),description:f("repoMesh.host.descriptionSet"),children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsxs("span",{className:`inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-[13px] text-text-primary ${c?"border-accent-primary/40 bg-accent-primary/10":"border-amber-500/40 bg-amber-500/10"}`,children:[s.jsx("span",{className:"text-text-muted",children:f("repoMesh.host.hostLabel")}),s.jsx("span",{className:"font-medium",children:i||f("repoMesh.host.unknown")}),s.jsxs("span",{className:c?"text-text-muted":"text-amber-400",children:["· ",f(c?"repoMesh.host.online":"repoMesh.host.offline")]})]}),(r==null?void 0:r.workspace)&&s.jsxs("span",{className:"text-[12px] text-text-muted",children:[f("repoMesh.host.hostNode")," ",s.jsx("span",{className:"font-mono text-text-secondary",children:r.workspace})]})]}),!c&&s.jsxs("div",{className:"mt-4",children:[s.jsxs(Mt,{variant:"warning",className:"mb-3",children:[s.jsx("strong",{children:f("repoMesh.host.hostOffline")})," ",f("repoMesh.host.hostOfflineText")]}),e.length>0?s.jsx(Tt,{label:f("repoMesh.host.reconnectToCommand"),hint:f("repoMesh.host.reconnectToCommandHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:d,onChange:h=>p(h.target.value),children:[s.jsx("option",{value:"",children:f("repoMesh.host.waitForHost")}),e.map(h=>s.jsx("option",{value:h.id,children:Sr(h)},h.id))]})}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:f("repoMesh.host.noDaemonsToRoute")})]})]});const g=e.find(h=>h.id===t),k=m&&t?s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>m(t),disabled:!!u,children:f(u?"repoMesh.host.settingHost":"repoMesh.host.setHostAction")}):null;return s.jsxs(xt,{title:f("repoMesh.host.title"),description:f("repoMesh.host.descriptionUnset"),children:[s.jsxs(Mt,{variant:"info",className:"mb-4",children:[s.jsx("strong",{children:f("repoMesh.host.setHostBanner")})," ",f("repoMesh.host.setHostBannerText")]}),e.length>0?s.jsxs(s.Fragment,{children:[t?s.jsx("div",{className:"mb-3 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:a?s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:Sr(g)}),r!=null&&r.workspace?s.jsxs(s.Fragment,{children:[" · setup node ",s.jsx("span",{className:"font-mono text-text-secondary",children:r.workspace})]}):null,". ",f("repoMesh.host.confirmSetsHost")]}):s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:Sr(g)}),". ",f("repoMesh.host.attachNodeThenSetHost")]})}):s.jsx(Tt,{label:f("repoMesh.host.hostDaemon"),hint:f("repoMesh.host.hostDaemonHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:"",onChange:h=>n(h.target.value),children:[s.jsx("option",{value:"",children:f("repoMesh.host.resolvingHost")}),e.map(h=>s.jsx("option",{value:h.id,children:Sr(h)},h.id))]})}),k&&s.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[k,s.jsx("span",{className:"text-[12px] text-text-muted",children:f("repoMesh.host.setHostActionHint")})]})]}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:f("repoMesh.host.noDaemonsToHost")})]})}function K2({meshId:e,availableCliAgents:t}){const{t:n}=ke(),a=t.find(o=>{const i=o.id.toLowerCase();return i==="hermes-cli"||i.includes("hermes")||o.name.toLowerCase().includes("hermes")}),r=Wh(a==null?void 0:a.meshCoordinator,{meshId:e});return r?s.jsx(xt,{title:n("repoMesh.hermesMcp.title"),description:n("repoMesh.hermesMcp.description"),children:s.jsx(pf,{setup:r,providerName:(a==null?void 0:a.name)||n("repoMesh.hermesMcp.fallbackProvider")})}):null}const $i=[{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."}],V2=[{value:"smart",labelKey:"repoMesh.detail.distributionSmart",descriptionKey:"repoMesh.detail.distributionSmartDescription"},{value:"in_order",labelKey:"repoMesh.detail.distributionInOrder",descriptionKey:"repoMesh.detail.distributionInOrderDescription"}];function Y2(e){return e==="smart"?"fitness":"first_eligible"}function Q2(e,t){const n=e||"first_eligible";return n==="fitness"||n==="least_loaded"||n==="round_robin"||n==="priority_only"&&t!=null&&t.priorityConfigured?"smart":"in_order"}const J2={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,schedulingStrategy:"first_eligible",sessionCleanupOnNodeRemove:"preserve"};function Ml(e){return{...J2,...(e==null?void 0:e.policy)||{}}}function X2(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 Z2({selectedMesh:e,error:t,onDismissError:n,onBack:a,onDelete:r,displayedMeshStatus:o,graphLoading:i,graphError:c,onRefreshGraph:d,savingPolicy:p,onUpdatePolicy:u,coordinatorPromptDraft:m,onCoordinatorPromptDraftChange:f,savingCoordinatorPrompt:g,onSaveCoordinatorPrompt:k,daemons:h,coordinatorDaemonId:b,onCoordinatorDaemonIdChange:S,coordinatorCliType:x,isHostNodeAttached:y,selectedHostNode:C,hostPinned:v,hostLabel:w,hostOnline:j,hostRebindDaemonId:N,onHostRebindDaemonIdChange:A,settingMeshHost:T,onSetMeshHost:I,activeDaemon:P,activeDaemonId:M,meshQueue:E,userName:D,availableCliProviders:W,savingNodeSlotsId:R,onUpdateNodeSlots:B,savingNodeCapabilitiesId:_,onUpdateNodeCapabilities:H,nodeSystemPromptDrafts:L,onNodeSystemPromptDraftChange:F,savingNodeSystemPromptId:$,onSaveNodeSystemPrompt:K,selectedNodeId:z,onSelectNode:ne,showAddNode:ie,onShowAddNode:Ce,onCancelAddNode:me,nodeWorkspace:O,onNodeWorkspaceChange:Y,nodeProviderPriority:X,onNodeProviderPriorityChange:Q,nodeDaemonId:ve,onNodeDaemonIdChange:he,nodeCustomPath:Z,onNodeCustomPathChange:fe,nodePickerWorkspaces:V,nodePickerProviders:q,nodeOnboardingPlan:ee,nodePlanLoading:pe,attachableDaemons:le,onAddNode:se,onRemoveNode:te,availableCliAgents:ue,features:ye,sendCommand:Me}){const{t:re}=ke("common"),ce=Ml(e),Ae=e.nodes||[],be=l.useMemo(()=>e2(Ae,h),[Ae,h]),we=Ae.some(et=>{var Le;const J=Number((Le=et.policy)==null?void 0:Le.schedulingPriority);return Number.isFinite(J)&&J!==0}),_e=!ce.schedulingStrategy,U=l.useMemo(()=>Ae.some(et=>{var J;return Array.isArray((J=et.policy)==null?void 0:J.slots)&&et.policy.slots.length>0}),[Ae]),Ne=_e&&(U||Ae.length>=2)?"smart":null,[Ie,We]=l.useState(!1),Xe=!!M&&!!e.id;return s.jsxs(Ja,{icon:s.jsx(cs,{}),title:e.name,subtitle:e.repoIdentity||e.repo_identity||"Repo Mesh",widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:a,children:re("repoMesh.detail.back")}),s.jsxs("button",{className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:()=>d(!0),disabled:i,children:[s.jsx(qL,{size:13}),re(i?"repoMesh.detail.probing":"repoMesh.detail.refresh")]}),s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>r(e.id),children:re("repoMesh.detail.delete")})]}),children:[t&&s.jsx(Mt,{variant:"error",onDismiss:n,className:"mb-4",children:t}),(()=>{var rt;const et=s.jsxs(s.Fragment,{children:[ye.meshHostDaemonSection&&s.jsx(z2,{daemons:h,coordinatorDaemonId:b,onCoordinatorDaemonIdChange:S,isHostNodeAttached:y,selectedHostNode:C,hostPinned:v,hostLabel:w,hostOnline:j,hostRebindDaemonId:N,onHostRebindDaemonIdChange:G=>{A(G),d()},settingMeshHost:T,onSetMeshHost:I}),s.jsxs(xt,{title:re("repoMesh.detail.observabilityTitle"),description:re("repoMesh.detail.observabilityDescription"),children:[c&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:c}),s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsxs("button",{type:"button",className:"btn btn-primary btn-sm inline-flex items-center gap-1.5",onClick:()=>We(!0),disabled:!Xe,title:re(Xe?"repoMesh.detail.observabilityOpenTitle":"repoMesh.detail.observabilityDisabledTitle"),children:[s.jsx(cs,{size:14}),re("repoMesh.detail.observabilityOpen")]}),s.jsx("span",{className:"text-[12px] text-text-muted",children:re("repoMesh.detail.observabilityHint")})]})]}),s.jsx(v2,{nodes:Ae,meshQueue:E,activeDaemon:P,daemons:h,selectedMeshId:e.id,userName:D,features:{addNodeDaemonPicker:ye.addNodeDaemonPicker,nodeInstruction:ye.nodeInstruction},coordinatorDaemonId:b,availableCliProviders:W,savingNodeSlotsId:R,onUpdateNodeSlots:B,savingNodeCapabilitiesId:_,onUpdateNodeCapabilities:H,nodeSystemPromptDrafts:L,onNodeSystemPromptDraftChange:F,savingNodeSystemPromptId:$,onSaveNodeSystemPrompt:K,selectedNodeId:z,onSelectNode:ne,showAddNode:ie,onShowAddNode:Ce,onCancelAddNode:me,nodeWorkspace:O,onNodeWorkspaceChange:Y,nodeProviderPriority:X,onNodeProviderPriorityChange:Q,nodeDaemonId:ve,onNodeDaemonIdChange:he,nodeCustomPath:Z,onNodeCustomPathChange:fe,nodePickerWorkspaces:V,nodePickerProviders:q,nodeOnboardingPlan:ee,nodePlanLoading:pe,attachableDaemons:le,onAddNode:se,onRemoveNode:te})]}),J=s.jsxs(s.Fragment,{children:[s.jsxs(xt,{title:re("repoMesh.detail.schedulingTitle"),description:re("repoMesh.detail.schedulingDescription"),children:[s.jsxs("fieldset",{className:"border-none p-0 m-0",children:[s.jsx("legend",{className:"text-[13px] font-medium text-text-secondary mb-2",children:re("repoMesh.detail.distribution")}),s.jsx("div",{className:"flex flex-col gap-2",children:V2.map(G=>{const de=Q2(ce.schedulingStrategy,{priorityConfigured:we})===G.value;return s.jsxs("label",{className:`flex items-start gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${de?"border-accent-primary/60 bg-accent-primary/10":"border-border-subtle bg-bg-secondary/60 hover:border-border-default"}`,children:[s.jsx("input",{type:"radio",name:"mesh-distribution",className:"mt-0.5 accent-[var(--accent-primary)]",value:G.value,checked:de,disabled:p,onChange:()=>u({schedulingStrategy:Y2(G.value)})}),s.jsxs("span",{className:"min-w-0",children:[s.jsxs("span",{className:"flex items-center gap-2 text-sm text-text-primary",children:[re(G.labelKey),Ne===G.value&&s.jsx("span",{className:"rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-accent-primary",children:re("repoMesh.detail.recommended")})]}),s.jsx("span",{className:"block text-[12px] text-text-muted",children:re(G.descriptionKey)})]})]},G.value)})})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:re("repoMesh.detail.saving")})]}),s.jsx(xt,{title:re("repoMesh.detail.visibilityTitle"),description:re("repoMesh.detail.visibilityDescription"),children:s.jsx(Tt,{label:re("repoMesh.detail.visibilityLabel"),hint:re("repoMesh.detail.visibilityHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ce.spawnedSessionVisibility==="visible"?"visible":"hidden",onChange:G=>u({spawnedSessionVisibility:G.target.value==="visible"?"visible":"hidden"}),disabled:p,children:[s.jsx("option",{value:"hidden",children:re("repoMesh.detail.visibilityHidden")}),s.jsx("option",{value:"visible",children:re("repoMesh.detail.visibilityVisible")})]})})}),o&&s.jsx(xt,{title:re("repoMesh.detail.magiTitle"),description:re("repoMesh.detail.magiDescription"),children:s.jsx(j2,{status:o,daemonId:M,sendDaemonCommand:Me,availableProviders:W})}),s.jsx(xt,{children:s.jsx(M2,{quotaRouting:ce.quotaRouting??null,saving:p,error:t,onSave:G=>u({quotaRouting:G})})}),s.jsx(G2,{hostDaemonId:b,hostOnline:j,hostWorkspace:(C==null?void 0:C.workspace)||"",meshProviders:be.providers,unreportedNodeCount:be.unreportedNodeCount,machineAutoApproveEnabled:ce.delegatedWorkerAutoApprove!==!1,machineDangerousAllowed:ce.delegatedWorkerDangerousModeAllow===!0,onUpdatePolicy:u,savingPolicy:p,sendCommand:Me})]}),Le=s.jsx(s.Fragment,{children:ye.coordinatorPrompt&&s.jsx(xt,{title:re("repoMesh.detail.coordinatorPromptTitle"),collapsible:!0,defaultOpen:!1,badge:s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:re("repoMesh.detail.advanced")}),description:re("repoMesh.detail.coordinatorPromptDescription"),children:s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 p-3",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-1",children:re("repoMesh.detail.thisMesh")}),s.jsx("p",{className:"text-[12px] text-text-muted mb-3",children:re("repoMesh.detail.thisMeshHint",{name:e.name})}),s.jsx(D2,{daemonId:M,meshId:e.id,cliType:x,sendCommand:Me,defaultOpen:!0}),s.jsxs(Tt,{label:re("repoMesh.detail.overrideLabel"),hint:re("repoMesh.detail.overrideHint"),className:"mt-3",children:[s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:6,value:m.override,onChange:G=>f({...m,override:G.target.value}),disabled:g,placeholder:re("repoMesh.detail.overridePlaceholder")}),s.jsx(I2,{daemonId:M,meshId:e.id,cliType:x,sendCommand:Me,disabled:g,hasContent:!!m.override.trim(),onApply:G=>f({...m,override:G})})]}),s.jsx(Tt,{label:re("repoMesh.detail.appendLabel"),hint:re("repoMesh.detail.appendHint"),children:s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:4,value:m.append,onChange:G=>f({...m,append:G.target.value}),disabled:g,placeholder:re("repoMesh.detail.appendPlaceholder")})}),s.jsxs("details",{className:"mt-2 text-[12px] text-text-muted",children:[s.jsx("summary",{className:"cursor-pointer select-none",children:re("repoMesh.detail.availablePlaceholders")}),s.jsx("p",{className:"mt-1",children:re("repoMesh.detail.placeholdersIntro")}),s.jsx("div",{className:"mt-2 overflow-x-auto",children:s.jsx("table",{className:"w-full text-left border-collapse",children:s.jsx("tbody",{children:L2.map(G=>s.jsxs("tr",{className:"border-t border-border-subtle/60 align-top",children:[s.jsx("td",{className:"py-1 pr-3 font-mono whitespace-nowrap text-text-secondary",children:`{{${G.token}}}`}),s.jsx("td",{className:"py-1 pr-3",children:G.description}),s.jsx("td",{className:"py-1 font-mono text-text-muted/80",children:G.example})]},G.token))})})})]}),s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:k,disabled:g,children:re(g?"repoMesh.detail.saving":"repoMesh.detail.saveCoordinatorPrompt")}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>f({override:"",append:""}),disabled:g,title:re("repoMesh.detail.clearTitle"),children:re("repoMesh.detail.clear")})]})]})})}),$e=s.jsxs(s.Fragment,{children:[s.jsx(B2,{status:o,daemonId:M,meshId:e.id,sendCommand:Me}),s.jsxs(xt,{title:re("repoMesh.detail.safetyTitle"),collapsible:!0,defaultOpen:!1,badge:s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:re("repoMesh.detail.advanced")}),description:re("repoMesh.detail.safetyDescription"),children:[s.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:[{label:re("repoMesh.detail.checkpointBefore"),key:"requirePreTaskCheckpoint",opts:[["no","No"],["yes","Yes"]],val:G=>G?"yes":"no",parse:G=>G==="yes"},{label:re("repoMesh.detail.checkpointAfter"),key:"requirePostTaskCheckpoint",opts:[["yes","Yes"],["no","No"]],val:G=>G?"yes":"no",parse:G=>G==="yes"},{label:re("repoMesh.detail.pushApproval"),key:"requireApprovalForPush",opts:[["required",re("repoMesh.detail.requireApprovalBeforePush")],["not_required",re("repoMesh.detail.doNotRequireApproval")]],val:G=>G?"required":"not_required",parse:G=>G==="required"},{label:re("repoMesh.detail.uncommittedChanges"),key:"dirtyWorkspaceBehavior",opts:[["warn",re("repoMesh.detail.warnAndContinue")],["block",re("repoMesh.detail.blockTask")],["checkpoint_then_continue",re("repoMesh.detail.checkpointThenContinue")]],val:G=>G||"warn",parse:G=>G},{label:re("repoMesh.detail.autoPublishSubmodule"),key:"allowAutoPublishSubmoduleMainCommits",opts:[["disabled",re("repoMesh.detail.requireExplicitApproval")],["enabled",re("repoMesh.detail.allowRefineryPublish")]],val:G=>G?"enabled":"disabled",parse:G=>G==="enabled"}].map(({label:G,key:oe,opts:de,val:xe,parse:Se})=>s.jsx(Tt,{label:G,children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:xe(ce[oe]),onChange:Pe=>u({[oe]:Se(Pe.target.value)}),disabled:p,children:de.map(([Pe,He])=>s.jsx("option",{value:Pe,children:He},Pe))})},oe))}),(()=>{const G=ce.autoFastForward&&typeof ce.autoFastForward=="object"?ce.autoFastForward:{},oe=G.enabled!==!1,de=G.remoteNodes===!0,xe=G.mode==="continuous"?"continuous":"idle",Se=Pe=>u({autoFastForward:{...G,...Pe}});return s.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[s.jsx(Tt,{label:re("repoMesh.detail.autoFastForward"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:oe?"enabled":"disabled",onChange:Pe=>Se({enabled:Pe.target.value==="enabled"}),disabled:p,children:[s.jsx("option",{value:"enabled",children:re("repoMesh.detail.ffEnabled")}),s.jsx("option",{value:"disabled",children:re("repoMesh.detail.ffDisabled")})]})}),s.jsx(Tt,{label:re("repoMesh.detail.includeRemoteNodes"),hint:re("repoMesh.detail.includeRemoteNodesHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:de?"yes":"no",onChange:Pe=>Se({remoteNodes:Pe.target.value==="yes"}),disabled:p||!oe,children:[s.jsx("option",{value:"no",children:re("repoMesh.detail.remoteNo")}),s.jsx("option",{value:"yes",children:re("repoMesh.detail.remoteYes")})]})}),s.jsx(Tt,{label:re("repoMesh.detail.detectionMode"),hint:re("repoMesh.detail.detectionModeHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:xe,onChange:Pe=>Se({mode:Pe.target.value==="continuous"?"continuous":"idle"}),disabled:p||!oe||!de,children:[s.jsx("option",{value:"idle",children:re("repoMesh.detail.idleEdgeOnly")}),s.jsx("option",{value:"continuous",children:re("repoMesh.detail.continuousScan")})]})})]})})(),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(Tt,{label:re("repoMesh.detail.sessionCleanupLabel"),hint:re("repoMesh.detail.sessionCleanupHint"),children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ce.sessionCleanupOnNodeRemove||"preserve",onChange:G=>u({sessionCleanupOnNodeRemove:G.target.value}),disabled:p,children:$i.map(G=>s.jsx("option",{value:G.value,children:G.label},G.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((rt=$i.find(G=>G.value===ce.sessionCleanupOnNodeRemove))==null?void 0:rt.description)||$i[0].description})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:re("repoMesh.detail.saving")})]})]}),at=[{key:"nodes",label:re("repoMesh.detail.tabNodes"),content:et},{key:"scheduling",label:re("repoMesh.detail.tabScheduling"),content:J},{key:"prompts",label:re("repoMesh.detail.tabPrompts"),content:s.jsxs(s.Fragment,{children:[Le,ye.hermesMcpConfig&&s.jsx(K2,{meshId:e.id,availableCliAgents:ue}),ye.meshHostDaemonSection&&s.jsxs(Mt,{variant:"info",className:"mt-4",children:[s.jsx("strong",{children:re("repoMesh.detail.mcpMode")})," ",s.jsxs("code",{className:"bg-bg-secondary px-1 rounded text-xs",children:["adhdev mcp --repo-mesh ",e.id]})," ",re("repoMesh.detail.mcpDescription")]})]})},{key:"advanced",label:re("repoMesh.detail.tabAdvanced"),content:$e}];return s.jsxs(s.Fragment,{children:[s.jsx(w1,{tabs:at,ariaLabel:re("repoMesh.detail.tabsAriaLabel"),className:"flex flex-col gap-4"}),Ie&&Xe&&s.jsx(Zf,{activeConv:X2({meshId:e.id,daemonId:M,meshName:e.name}),sendDaemonCommand:Me,onClose:()=>We(!1)})]})})()]})}const ya=new Map;async function ug(e){var r,o,i,c,d,p,u,m,f,g,k;const{sendCommand:t,unwrapResult:n}=e,a={meshCreated:!1,meshId:"",error:null,warning:null,plan:null};try{const h=e.reusablePlan??n(await t(e.targetDaemonId,"plan_mesh_onboarding",{workspace:e.workspace||void 0,operation:"auto",meshInventory:e.meshInventory}));if(a.plan=h,(h==null?void 0:h.success)===!1)return{...a,error:`${h.code||"onboarding_blocked"}: ${h.error}${h.action?` ${h.action}`:""}`};if(((r=h==null?void 0:h.plan)==null?void 0:r.kind)!=="create_mesh_and_onboard")return{...a,error:((o=h==null?void 0:h.plan)==null?void 0:o.summary)||"A compatible mesh already exists; add this workspace to it instead of creating a duplicate mesh."};const b={name:e.name.trim()};(e.repoRemoteUrl||(d=(c=(i=h==null?void 0:h.discovery)==null?void 0:i.origin)==null?void 0:c.urls)!=null&&d[0])&&(b.repoRemoteUrl=e.repoRemoteUrl||h.discovery.origin.urls[0]),(e.repoIdentity||(p=h==null?void 0:h.discovery)!=null&&p.repoIdentity)&&(b.repoIdentity=e.repoIdentity||h.discovery.repoIdentity),(u=h==null?void 0:h.discovery)!=null&&u.defaultBranch&&(b.defaultBranch=h.discovery.defaultBranch);const S=await t(e.targetDaemonId,"create_mesh",b),x=n(S);if((x==null?void 0:x.success)===!1)return{...a,error:x.error||"Create failed"};const y=typeof((m=x==null?void 0:x.mesh)==null?void 0:m.id)=="string"?x.mesh.id:"",C={...a,meshCreated:!0,meshId:y};if(!y||!e.attachWorkspace||!e.workspace)return C;try{const v=await t(e.targetDaemonId,"add_mesh_node",{meshId:y,daemonId:e.targetDaemonId,machineId:e.machineId,workspace:((f=h==null?void 0:h.discovery)==null?void 0:f.repoRoot)||e.workspace,repoRoot:(g=h==null?void 0:h.discovery)==null?void 0:g.repoRoot,isLocalWorktree:((k=h==null?void 0:h.discovery)==null?void 0:k.isLinkedWorktree)===!0,role:"host",providerPriority:e.providerPriority}),w=n(v);return(w==null?void 0:w.success)===!1?{...C,warning:ip(w.error||"add_mesh_node failed")}:C}catch(v){return{...C,warning:ip((v==null?void 0:v.message)||"add_mesh_node failed")}}}catch(h){return{...a,error:(h==null?void 0:h.message)||"Create failed"}}}function ip(e){return`Mesh created, but attaching the workspace failed: ${e}. Add the workspace from the mesh's node list.`}function lp(e,t){return e===t?!0:e.length!==t.length?!1:JSON.stringify(e)===JSON.stringify(t)}function pg({daemons:e,primaryDaemonId:t,sendCommand:n,unwrapResult:a,normalizeMesh:r,features:o,loadDaemonMetadata:i}){const c=e.map(me=>me.id).filter(Boolean).sort().join(","),[d,p]=l.useState(()=>ya.get(c)??[]),[u,m]=l.useState(null),[f,g]=l.useState(()=>!ya.has(c)),[k,h]=l.useState(null),[b,S]=l.useState(!1),[x,y]=l.useState(!1),[C,v]=l.useState(null),[w,j]=l.useState(""),[N,A]=l.useState(""),[T,I]=l.useState(""),[P,M]=l.useState(""),[E,D]=l.useState(""),[W,R]=l.useState(null),[B,_]=l.useState(!1),H=o.createDaemonPicker?P:t,L=l.useMemo(()=>e.find(me=>me.id===H),[e,H]),F=(L==null?void 0:L.workspaces)||[],$=l.useMemo(()=>cn((L==null?void 0:L.availableProviders)||[]),[L]);l.useEffect(()=>{!i||!H||!L||!(!L.workspaces||!L.availableProviders)||Promise.resolve(i(H,{minFreshMs:3e4})).catch(()=>{})},[i,H,L]),l.useEffect(()=>{if(!b||!H||!E){R(null);return}let me=!1;return _(!0),n(H,"plan_mesh_onboarding",{workspace:E,operation:"auto",meshInventory:d}).then(O=>{if(me)return;const Y=a(O);R(Y),Y!=null&&Y.success&&(A(X=>{var Q;return X||((Q=Y.discovery)==null?void 0:Q.repoIdentity)||""}),I(X=>{var Q,ve,he,Z,fe,V;return X||((he=(ve=(Q=Y.discovery)==null?void 0:Q.origin)==null?void 0:ve.urls)==null?void 0:he[0])||((V=(fe=(Z=Y.discovery)==null?void 0:Z.upstream)==null?void 0:fe.urls)==null?void 0:V[0])||""}),j(X=>{var Q,ve;return X||`${String(((Q=Y.discovery)==null?void 0:Q.repoIdentity)||((ve=Y.discovery)==null?void 0:ve.repoRoot)||"").split(/[\\/]/).filter(Boolean).pop()||"repo"}-mesh`}))}).catch(O=>{me||R({success:!1,error:(O==null?void 0:O.message)||"Git discovery failed"})}).finally(()=>{me||_(!1)}),()=>{me=!0}},[b,H,E,d,n,a]);const K=l.useMemo(()=>e.map(me=>me.id).filter(Boolean).sort().join(","),[e]),z=l.useCallback(async(me=!1)=>{const O=me||ya.has(K);g(Y=>O?Y:!0);try{if(o.createDaemonPicker){const Y=await Promise.allSettled(e.map(async ve=>{if(!ve.id)return[];const he=await n(ve.id,"list_meshes",{}),Z=a(he);if((Z==null?void 0:Z.success)===!1)throw new Error(Z.error||"Failed to load meshes");return(Array.isArray(Z==null?void 0:Z.meshes)?Z.meshes:[]).map(fe=>r(fe,ve.id)).filter(fe=>fe.id)})),X=new Map;for(const ve of Y)if(ve.status==="fulfilled")for(const he of ve.value)X.has(he.id)||X.set(he.id,he);const Q=Array.from(X.values());p(ve=>lp(ve,Q)?ve:Q),ya.set(K,Q),h(null)}else{if(!t)return;const Y=await n(t,"list_meshes");if(Y!=null&&Y.success){const X=(Y.meshes||[]).map(Q=>r(Q,t));p(Q=>lp(Q,X)?Q:X),ya.set(K,X),h(null)}else h((Y==null?void 0:Y.error)||"Failed to load meshes")}}catch(Y){h((Y==null?void 0:Y.message)||"Failed to load meshes")}finally{g(!1)}},[K,t,n,a,r,o.createDaemonPicker]);async function ne(){const me=o.createDaemonPicker?P:t;if(!me||!w.trim())return;const O=T.trim(),Y=N.trim(),X=E.trim();if(!(!X&&!O&&!Y)&&!x){y(!0),v(null);try{const Q=await ug({targetDaemonId:me,name:w,repoRemoteUrl:O,repoIdentity:Y,workspace:X,attachWorkspace:!!X,machineId:L==null?void 0:L.machineId,providerPriority:Dn($),meshInventory:d,sendCommand:n,unwrapResult:a,reusablePlan:!B&&W?W:void 0});if(Q.plan!==null&&R(Q.plan),Q.warning&&v(Q.warning),!Q.meshCreated){h(Q.error||"Create failed");return}S(!1),j(""),A(""),I(""),D(""),await z(),Q.meshId&&m(Q.meshId)}finally{y(!1)}}}async function ie(me){var Y;if(!confirm("Delete this mesh? This cannot be undone."))return;const O=((Y=d.find(X=>X.id===me))==null?void 0:Y.__sourceDaemonId)||t;try{const X=await n(O,"delete_mesh",{meshId:me}),Q=a(X);if((Q==null?void 0:Q.success)===!1)throw new Error(Q.error||"Failed to delete");u===me&&m(null),await z()}catch(X){h((X==null?void 0:X.message)||"Delete failed")}}function Ce(){S(!1),j(""),A(""),I(""),D(""),R(null),v(null)}return{meshes:d,setMeshes:p,selectedMeshId:u,setSelectedMeshId:m,loading:f,error:k,setError:h,showCreate:b,setShowCreate:S,creating:x,createWarning:C,setCreateWarning:v,createName:w,setCreateName:j,createRepoIdentity:N,setCreateRepoIdentity:A,createRepoRemoteUrl:T,setCreateRepoRemoteUrl:I,newMeshDaemonId:P,setNewMeshDaemonId:M,newMeshWorkspace:E,setNewMeshWorkspace:D,createPickerWorkspaces:F,createPickerProviders:$,createOnboardingPlan:W,createPlanLoading:B,loadMeshes:z,handleCreate:ne,handleDelete:ie,cancelCreate:Ce}}function eR({selectedMesh:e,selectedMeshId:t,primaryDaemonId:n,activeDaemonId:a,daemons:r,sendCommand:o,unwrapResult:i,loadLiveMesh:c,resolveCommandTarget:d,launchCoordinator:p,features:u,loadMeshes:m,loadQueue:f,queueSection:g,setError:k}){const[h,b]=l.useState(null),[S,x]=l.useState(!1),[y,C]=l.useState(""),[v,w]=l.useState([]),[j,N]=l.useState(""),[A,T]=l.useState(!1),[I,P]=l.useState(null),[M,E]=l.useState(!1),[D,W]=l.useState(""),[R,B]=l.useState(!1),[_,H]=l.useState(!1),[L,F]=l.useState(null),[$,K]=l.useState(!1),[z,ne]=l.useState({override:"",append:""}),[ie,Ce]=l.useState(!1),[me,O]=l.useState({}),[Y,X]=l.useState(null),Q=l.useMemo(()=>r.find(ce=>ce.id===j),[r,j]),ve=(Q==null?void 0:Q.workspaces)||[],he=l.useMemo(()=>cn((Q==null?void 0:Q.availableProviders)||[]),[Q]);l.useEffect(()=>{if(!S||!t||!y.trim()){P(null);return}const ce=u.addNodeDaemonPicker?j:(e==null?void 0:e.__sourceDaemonId)||n;if(!ce)return;let Ae=!1;return E(!0),o(ce,"plan_mesh_onboarding",{workspace:y.trim(),meshId:t,inlineMesh:e,operation:"add_existing"}).then(be=>{Ae||P(i(be))}).catch(be=>{Ae||P({success:!1,error:(be==null?void 0:be.message)||"Git discovery failed"})}).finally(()=>{Ae||E(!1)}),()=>{Ae=!0}},[S,t,e,y,j,n,u.addNodeDaemonPicker,o,i]);async function Z(){var be,we,_e;const ce=(e==null?void 0:e.__sourceDaemonId)||n;if(!t||!ce)return;const Ae=y.trim();if(Ae)try{const U=u.addNodeDaemonPicker?j:ce,Ne=await o(U,"plan_mesh_onboarding",{workspace:Ae,meshId:t,inlineMesh:e,operation:"add_existing"}),Ie=i(Ne);if(P(Ie),(Ie==null?void 0:Ie.success)===!1)throw new Error(`${Ie.code||"onboarding_blocked"}: ${Ie.error}${Ie.action?` ${Ie.action}`:""}`);const We={meshId:t,workspace:((be=Ie==null?void 0:Ie.discovery)==null?void 0:be.repoRoot)||Ae,repoRoot:(we=Ie==null?void 0:Ie.discovery)==null?void 0:we.repoRoot,isLocalWorktree:((_e=Ie==null?void 0:Ie.discovery)==null?void 0:_e.isLinkedWorktree)===!0};u.addNodeDaemonPicker&&j&&(We.daemonId=j,We.machineId=Q==null?void 0:Q.machineId),We.providerPriority=Ya(v);const Xe=await o(ce,"add_mesh_node",We),et=i(Xe);if((et==null?void 0:et.success)===!1)throw new Error(et.error||"Add node failed");x(!1),C(""),w([]),N(""),T(!1),await m(),g||await f(t)}catch(U){k((U==null?void 0:U.message)||"Add node failed")}}async function fe(ce){var _e;if(!e)return;const Ae=Ml(e),be=((_e=[{value:"preserve",label:"Preserve history and runtimes"},{value:"stop",label:"Stop live runtimes only"},{value:"delete_stopped",label:"Delete stopped sessions only"},{value:"stop_and_delete",label:"Stop and delete sessions"}].find(U=>U.value===Ae.sessionCleanupOnNodeRemove))==null?void 0:_e.label)||"Preserve history and runtimes";if(!confirm(`Remove this node?
|
|
120
120
|
|
|
121
|
-
Node removal cleanup policy: ${be}`))return;const we=e.__sourceDaemonId||n;try{const U=await o(we,"remove_mesh_node",{meshId:e.id,nodeId:ce}),Ne=i(U);if((Ne==null?void 0:Ne.success)===!1)throw new Error(Ne.error||"Remove failed");h===ce&&b(null),await m(),g||await f(t)}catch(U){k((U==null?void 0:U.message)||"Remove node failed")}}async function V(ce){if(!e)return;const Ae={...Ml(e),...ce},be=e.__sourceDaemonId||n;try{K(!0),k(null);const we=await o(be,"update_mesh",{meshId:e.id,policy:Ae}),_e=i(we);if((_e==null?void 0:_e.success)===!1)throw new Error(_e.error||"Policy update failed");await m()}catch(we){k((we==null?void 0:we.message)||"Policy update failed")}finally{K(!1)}}const[q,ee]=l.useState(null);async function pe(ce,Ae){if(!t)return;const be=(e==null?void 0:e.__sourceDaemonId)||n;try{ee(ce.id),k(null);const we=await o(be,"update_mesh_node",{meshId:t,nodeId:ce.id,policy:{slots:Ae}}),_e=i(we);if((_e==null?void 0:_e.success)===!1){k(_e.error||"Node slots update failed");return}await m()}catch(we){k((we==null?void 0:we.message)||"Node slots update failed")}finally{ee(null)}}const[le,se]=l.useState(null);async function te(ce,Ae){if(!t)return;const be=(e==null?void 0:e.__sourceDaemonId)||n,we=Ae.map(_e=>_e.trim()).filter(Boolean);try{se(ce.id),k(null);const _e=await o(be,"update_mesh_node",{meshId:t,nodeId:ce.id,capabilities:we}),U=i(_e);if((U==null?void 0:U.success)===!1){k(U.error||"Node tag update failed");return}await m()}catch(_e){k((_e==null?void 0:_e.message)||"Node tag update failed")}finally{se(null)}}async function ue(){if(!n||!t)return;const Ae={...(e==null?void 0:e.coordinator)||{}};z.override.trim()?Ae.systemPromptOverride=z.override:delete Ae.systemPromptOverride,z.append.trim()?Ae.systemPromptAppend=z.append:delete Ae.systemPromptAppend,delete Ae.systemPromptSuffix;try{Ce(!0),k(null);const be=await o(n,"update_mesh",{meshId:t,coordinator:Ae}),we=i(be);if((we==null?void 0:we.success)===!1){k(we.error||"Coordinator prompt save failed");return}await m()}catch(be){k((be==null?void 0:be.message)||"Coordinator prompt save failed")}finally{Ce(!1)}}async function ye(ce){if(!n||!t)return;const Ae=(me[ce.id]||"").trim();try{X(ce.id),k(null);const be=await o(n,"update_mesh_node",{meshId:t,nodeId:ce.id,systemPrompt:Ae}),we=i(be);if((we==null?void 0:we.success)===!1){k(we.error||"Node instruction save failed");return}await m()}catch(be){k((be==null?void 0:be.message)||"Node instruction save failed")}finally{X(null)}}async function Me(ce){if(!(!e||!ce)){k(null),F(null);try{H(!0);const Ae=(e.nodes||[]).find(_e=>en(String(_e.daemon_id||_e.daemonId||""),ce)),be=await o(ce,"set_mesh_host",{meshId:e.id,hostDaemonId:ce,...Ae!=null&&Ae.id?{hostNodeId:Ae.id}:{}}),we=i(be);if((we==null?void 0:we.success)===!1){k(we.error||"Setting the mesh host failed");return}await m()}catch(Ae){k((Ae==null?void 0:Ae.message)||"Setting the mesh host failed")}finally{H(!1)}}}async function re(){if(e){k(null),F(null);try{B(!0);const ce=c?await c(a,e.id,e):null,Ae=d(a,e.id,e,e.nodes||[],ce);if("error"in Ae)throw new Error(Ae.error);const be=await p(Ae.targetDaemonId,{meshId:e.id,inlineMesh:Ae.inlineMesh,coordinatorNodeId:Ae.coordinatorNodeId,cliType:D.trim()||void 0});F(be.message)}catch(ce){k((ce==null?void 0:ce.message)||"Coordinator launch failed")}finally{B(!1)}}}return{selectedNodeId:h,setSelectedNodeId:b,showAddNode:S,setShowAddNode:x,nodeWorkspace:y,setNodeWorkspace:C,nodeProviderPriority:v,setNodeProviderPriority:w,nodeDaemonId:j,setNodeDaemonId:N,nodeCustomPath:A,setNodeCustomPath:T,nodePickerWorkspaces:ve,nodePickerProviders:he,nodeOnboardingPlan:I,nodePlanLoading:M,coordinatorCliType:D,setCoordinatorCliType:W,launchingCoordinator:R,launchResult:L,settingMeshHost:_,savingPolicy:$,coordinatorPromptDraft:z,setCoordinatorPromptDraft:ne,savingCoordinatorPrompt:ie,nodeSystemPromptDrafts:me,setNodeSystemPromptDrafts:O,savingNodeSystemPromptId:Y,savingNodeSlotsId:q,savingNodeCapabilitiesId:le,handleAddNode:Z,handleRemoveNode:fe,handleUpdatePolicy:V,handleUpdateNodeSlots:pe,handleUpdateNodeCapabilities:te,handleSaveCoordinatorPrompt:ue,handleSaveNodeSystemPrompt:ye,handleLaunchCoordinator:re,handleSetMeshHost:Me}}function tR(e){const t=e.filter(a=>a.status==="pending"||a.status==="assigned"),n=e.filter(a=>a.status==="completed"||a.status==="failed"||a.status==="cancelled");return{active:t.length,historical:n.length,activeCounts:{pending:t.filter(a=>a.status==="pending").length,assigned:t.filter(a=>a.status==="assigned").length},historicalCounts:{completed:n.filter(a=>a.status==="completed").length,failed:n.filter(a=>a.status==="failed").length},counts:{pending:e.filter(a=>a.status==="pending").length,assigned:e.filter(a=>a.status==="assigned").length,completed:e.filter(a=>a.status==="completed").length,failed:e.filter(a=>a.status==="failed").length},staleAssignedCount:e.filter(a=>a.staleAssigned).length,recent:e.slice(0,20)}}function sR({primaryDaemonId:e,activeDaemonId:t,sendCommand:n,unwrapResult:a,loadLiveMesh:r,resolveCommandTarget:o}){const[i,c]=l.useState([]),[d,p]=l.useState(null),[u,m]=l.useState(!1),[f,g]=l.useState(null),k=l.useCallback(async b=>{if(!e||!b){c([]);return}try{const S=await n(e,"get_mesh_queue",{meshId:b});c(S!=null&&S.success?Array.isArray(S.queue)?S.queue:[]:[])}catch{c([])}},[e,n]);async function h(b){var S,x;if(b){m(!0),g(null);try{const y=r?await r(t,b.id,b):null,C=o(t,b.id,b,b.nodes||[],y);if("error"in C)throw new Error(C.error);const v=await n(C.targetDaemonId,"get_mesh_queue",{meshId:b.id}),w=a(v);if((w==null?void 0:w.success)===!1)throw new Error(w.error||"Queue load failed");const j=Array.isArray(((S=w==null?void 0:w.result)==null?void 0:S.rows)??(w==null?void 0:w.rows)??(w==null?void 0:w.queue))?((x=w==null?void 0:w.result)==null?void 0:x.rows)??(w==null?void 0:w.rows)??(w==null?void 0:w.queue):[];p(tR(j))}catch(y){g((y==null?void 0:y.message)||"Queue load failed")}finally{m(!1)}}}return{meshQueue:i,setMeshQueue:c,queueSummary:d,queueLoading:u,queueError:f,loadQueue:k,handleLoadQueue:h}}function nR(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}const mg=new Map;function hg(e){return e?mg.get(e)??null:null}function aR(e,t){!e||!t||mg.set(e,t)}function rR({selectedMeshId:e,loadMeshStatus:t,extractStatus:n,normalizeNode:a,gateIncompleteGraph:r}){const[o,i]=l.useState(()=>hg(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 b(S,x=e,y=!1){if(!(!S||!x))try{d(!y&&o===null),f(y?"settling":"first_paint"),u(null);const C=await t(S,x,{refresh:y,retryProfile:y?"settled":"interactive"});k(nR(C));const v=n(C),w=a&&v?{...v,nodes:(v.nodes??[]).map(j=>a(j,v.meshId??x,""))}:v;if(w){if(r&&!y&&o!==null&&!yM(Pf(w))){f("settling"),h.current||(h.current=!0,Promise.resolve().then(()=>b(S,x,!0)).finally(()=>{h.current=!1}));return}i(w),aR(x,w),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:b}}function cp(e){return!e||e.hostSynthesized?{hostDaemonId:"",hostNodeId:""}:{hostDaemonId:String(e.hostDaemonId||""),hostNodeId:String(e.hostNodeId||"")}}function oR(e,t,n,a,r){if(!e.length)return"";const o=String(r||"");if(o){const d=e.find(p=>en(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=>en(p.id,c));if(d)return d.id}return""}function iR(e){var r;if(!e)return"null";const t=[...e.nodes??[]].map(o=>{var i,c,d,p,u,m;return[o.nodeId,o.health,((i=o.git)==null?void 0:i.branch)??"",((c=o.git)==null?void 0:c.headCommit)??"",(d=o.git)!=null&&d.dirty?"1":"0",((p=o.git)==null?void 0:p.ahead)??0,((u=o.git)==null?void 0:u.behind)??0,(m=o.git)!=null&&m.hasConflicts?"1":"0",[...o.activeSessions??[]].sort().join(",")].join("|")}).sort().join(";"),n=(r=e.queue)==null?void 0:r.summary,a=n?[n.pending,n.assigned,n.completed,n.failed,n.cancelled].join(","):"";return`${t}::${a}`}const lR=4,cR=3e4;function dR(){return{lastFingerprint:null,stableTicks:0,backedOff:!1}}function Pl(e){e.stableTicks=0,e.backedOff=!1}function uR(e,t){const n=iR(t);return e.lastFingerprint===null?(e.lastFingerprint=n,e.backedOff):n!==e.lastFingerprint?(e.lastFingerprint=n,Pl(e),!1):(e.stableTicks+=1,e.stableTicks>=lR&&(e.backedOff=!0),e.backedOff)}function pR(e,t){return e.backedOff?Math.max(t,cR):t}const mR=7e3,hR=45e3;function fR(){const e=UL(),{sendCommand:t,sendData:n,daemons:a,userName:r,loadMeshStatus:o,launchCoordinator:i,loadLiveMesh:c,extractStatus:d,unwrapResult:p,normalizeMesh:u,normalizeNode:m,resolveCommandTarget:f,features:g,gateIncompleteGraph:k}=e,h=da(),b=a[0],S=(b==null?void 0:b.id)||"",x=l.useMemo(()=>((b==null?void 0:b.availableProviders)||[]).filter(lt=>lt.category==="cli").map(lt=>({id:lt.type||lt.id,name:lt.displayName||lt.name||lt.type,meshCoordinator:lt.meshCoordinator})),[b]),y=l.useMemo(()=>cn((b==null?void 0:b.availableProviders)||[]),[b]),{meshes:C,selectedMeshId:v,setSelectedMeshId:w,loading:j,error:N,setError:A,showCreate:T,setShowCreate:I,createName:P,setCreateName:M,createRepoIdentity:E,setCreateRepoIdentity:D,createRepoRemoteUrl:W,setCreateRepoRemoteUrl:R,newMeshDaemonId:B,setNewMeshDaemonId:_,newMeshWorkspace:H,setNewMeshWorkspace:L,createPickerWorkspaces:F,createOnboardingPlan:$,createPlanLoading:K,creating:z,createWarning:ne,setCreateWarning:ie,loadMeshes:Ce,handleCreate:me,handleDelete:O,cancelCreate:Y}=pg({daemons:a,primaryDaemonId:S,sendCommand:t,unwrapResult:p,normalizeMesh:u,features:g,loadDaemonMetadata:h}),X=C.find(Oe=>Oe.id===v)||null,{meshGraphStatus:Q,setMeshGraphStatus:ve,graphLoading:he,graphError:Z,setGraphError:fe,loadGraph:V}=rR({selectedMeshId:v,loadMeshStatus:o,extractStatus:d,normalizeNode:m,gateIncompleteGraph:k}),[q,ee]=l.useState(""),[pe,le]=l.useState(""),se=g.meshHostDaemonSection?q:S,{meshQueue:te,loadQueue:ue}=sR({primaryDaemonId:S,activeDaemonId:se,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:f}),{selectedNodeId:ye,setSelectedNodeId:Me,showAddNode:re,setShowAddNode:ce,nodeWorkspace:Ae,setNodeWorkspace:be,nodeProviderPriority:we,setNodeProviderPriority:_e,nodeDaemonId:U,setNodeDaemonId:Ne,nodeCustomPath:Ie,setNodeCustomPath:We,nodePickerWorkspaces:Xe,nodePickerProviders:et,nodeOnboardingPlan:J,nodePlanLoading:Le,coordinatorCliType:$e,savingPolicy:at,coordinatorPromptDraft:rt,setCoordinatorPromptDraft:G,savingCoordinatorPrompt:oe,nodeSystemPromptDrafts:de,setNodeSystemPromptDrafts:xe,savingNodeSystemPromptId:Se,savingNodeSlotsId:Pe,savingNodeCapabilitiesId:He,handleAddNode:Ee,handleRemoveNode:Je,handleUpdatePolicy:st,handleUpdateNodeSlots:Ze,handleUpdateNodeCapabilities:Ue,handleSaveCoordinatorPrompt:Qe,handleSaveNodeSystemPrompt:nt,settingMeshHost:Be,handleSetMeshHost:ge}=eR({selectedMesh:X,selectedMeshId:v,primaryDaemonId:S,activeDaemonId:se,daemons:a,availableCliProviders:y,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:f,launchCoordinator:i,features:{addNodeDaemonPicker:g.addNodeDaemonPicker},loadMeshes:Ce,loadQueue:ue,queueSection:g.queueSection,setError:A}),je=l.useMemo(()=>a.find(Oe=>Oe.id===se)||b,[a,se,b]),Te=l.useMemo(()=>new Set(((X==null?void 0:X.nodes)||[]).map(Oe=>String(Oe.daemon_id||Oe.daemonId||""))),[X]),Fe=l.useMemo(()=>a.filter(Oe=>Oe.id&&!Te.has(Oe.id)&&!am(Oe)),[a,Te]),Ge=(X==null?void 0:X.nodes)||[],dt=l.useMemo(()=>Ge.find(Oe=>en(String(Oe.daemon_id||Oe.daemonId||""),q)),[Ge,q]),Ve=g.meshHostDaemonSection?!!dt:!0,ut=l.useMemo(()=>{if(!g.meshHostDaemonSection||!X)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const Oe=X.meshHost,lt=Q!=null&&Q.meshId&&String(Q.meshId)===String(X.id??"")?Q.meshHost:void 0,es=lt!=null&<.hostDaemonId?lt:Oe??lt,ns=cp(es),js=ns.hostDaemonId,Qs=Ge.find(Bs=>Bs.role==="host"),dn=ns.hostNodeId||String((Qs==null?void 0:Qs.id)||""),ae=dn?Ge.find(Bs=>String(Bs.id)===dn):void 0,Ke=String((ae==null?void 0:ae.daemon_id)||(ae==null?void 0:ae.daemonId)||""),qe=js||Ke;if(!qe)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const Nt=a.find(Bs=>js&&en(Bs.id,js))||(Ke?a.find(Bs=>en(Bs.id,Ke)):void 0);if(Nt)return{pinned:!0,daemonId:Nt.id,label:gR(Nt),online:!0,hostNode:ae};const un=String((ae==null?void 0:ae.machineLabel)||"")||String((ae==null?void 0:ae.workspace)||"")||qe;return{pinned:!0,daemonId:qe,label:un,online:!1,hostNode:ae}},[X,Ge,a,Q,g.meshHostDaemonSection]),Kt=ut.daemonId,Et=ut.online,ps=ut.pinned?ut.hostNode:dt,Zt=l.useMemo(()=>!g.meshHostDaemonSection||!ut.pinned?"":!Et&&pe&&a.some(Oe=>Oe.id===pe)?pe:Kt,[g.meshHostDaemonSection,ut.pinned,Et,pe,a,Kt]),Hs=l.useMemo(()=>Q?[...new Set((Q.nodes??[]).map(Oe=>String(Oe.daemonId||Oe.daemon_id||"")).filter(Boolean))]:[],[Q]),Re=Xf({status:Q,daemonId:se||null,extraDaemonIds:Hs,meshId:v,sendData:n});l.useEffect(()=>{const Oe=(X==null?void 0:X.coordinator)||{};G({override:typeof Oe.systemPromptOverride=="string"?Oe.systemPromptOverride:"",append:typeof Oe.systemPromptAppend=="string"?Oe.systemPromptAppend:typeof Oe.systemPromptSuffix=="string"?Oe.systemPromptSuffix:""}),xe(Object.fromEntries(((X==null?void 0:X.nodes)||[]).map(lt=>[lt.id,typeof lt.systemPrompt=="string"?lt.systemPrompt:""])))},[X]),l.useEffect(()=>{const Oe=g.addNodeDaemonPicker?Dn(et):Dn(y);re&&we.length===0&&Oe.length>0&&_e(Oe)},[re,y,et,we.length,g.addNodeDaemonPicker]),l.useEffect(()=>{const Oe=new Set(((X==null?void 0:X.nodes)||[]).map(lt=>lt.id));ye&&!Oe.has(ye)&&Me(null)},[X,ye]);const tt=l.useMemo(()=>{if(!(!(Q!=null&&Q.meshId)||String(Q.meshId)!==String((X==null?void 0:X.id)??"")))return cp(Q.meshHost).hostDaemonId||void 0},[Q,X]),It=l.useMemo(()=>oR(a,Ge,se,S,tt),[a,Ge,se,S,tt]);l.useEffect(()=>{if(!g.meshHostDaemonSection)return;if(!a.length&&!ut.pinned){ee("");return}const Oe=ut.pinned?Zt:It;Oe&&!en(Oe,q)&&ee(Oe)},[a,q,ut.pinned,Zt,It,g.meshHostDaemonSection]),l.useEffect(()=>{pe&&(Et||!a.some(Oe=>Oe.id===pe))&&le("")},[Et,pe,a]),l.useEffect(()=>{if(g.createDaemonPicker){if(!a.length){_("");return}(!B||!a.some(Oe=>Oe.id===B))&&_(a[0].id)}},[a,B,g.createDaemonPicker]),l.useEffect(()=>{var Oe;if(!g.createDaemonPicker||!B){L("");return}if(!F.length){L("");return}F.some(lt=>lt.path===H)||L(((Oe=F[0])==null?void 0:Oe.path)||"")},[B,H,F,g.createDaemonPicker]);const pt=l.useRef(null),Yt=l.useRef(dR()),_t=g.meshStatePushRefresh?hR:mR,[Qt,Cs]=l.useState(_t);l.useEffect(()=>{if(!v)return;const Oe=pt.current!==v;if(pt.current=v,Oe){Pl(Yt.current),Cs(_t);const lt=hg(v);ve(lt),fe(null),V(se,v,lt!==null)}else fe(null),V(se,v,!0)},[v,se]);const $s=l.useRef(V);$s.current=V;const ms=l.useRef(!1),ss=l.useRef(()=>{});ss.current=()=>{ms.current||!v||!se||(ms.current=!0,Promise.resolve($s.current(se,v,!0)).finally(()=>{ms.current=!1}))},l.useEffect(()=>{uR(Yt.current,Q),Cs(pR(Yt.current,_t))},[Q,_t]),OL({daemonIds:l.useMemo(()=>[se,...Hs].filter(Boolean),[se,Hs]),meshId:v,sendData:n,onRevisionAdvance:()=>{typeof document<"u"&&document.visibilityState!=="visible"||ss.current()}}),l.useEffect(()=>{if(!v||!se||typeof document>"u")return;let Oe=null;const lt=()=>{document.visibilityState==="visible"&&ss.current()},es=()=>{Oe===null&&(Oe=setInterval(lt,Qt))},ns=()=>{Oe!==null&&(clearInterval(Oe),Oe=null)},js=()=>{document.visibilityState==="visible"?es():ns()};return document.visibilityState==="visible"&&es(),document.addEventListener("visibilitychange",js),()=>{ns(),document.removeEventListener("visibilitychange",js)}},[v,se,Qt]),l.useEffect(()=>{g.queueSection||ue(v)},[v,g.queueSection]);const Ys=l.useMemo(()=>a.map(Oe=>Oe.id).filter(Boolean).sort().join(","),[a]),Fs=l.useRef(!1);return l.useEffect(()=>{Ce(Fs.current),Fs.current=!0},[Ys]),S?X?s.jsx(Z2,{selectedMesh:X,error:N,onDismissError:()=>A(null),onBack:()=>{w(null),ve(null)},onDelete:O,displayedMeshStatus:Re,graphLoading:he,graphError:Z,onRefreshGraph:()=>{Pl(Yt.current),V(se,v,!0)},savingPolicy:at,onUpdatePolicy:st,coordinatorPromptDraft:rt,onCoordinatorPromptDraftChange:G,savingCoordinatorPrompt:oe,onSaveCoordinatorPrompt:Qe,daemons:a,coordinatorDaemonId:q,onCoordinatorDaemonIdChange:ee,coordinatorCliType:$e,isHostNodeAttached:Ve,selectedHostNode:ps,hostPinned:ut.pinned,hostLabel:ut.label,hostOnline:Et,hostRebindDaemonId:pe,onHostRebindDaemonIdChange:Oe=>le(Oe),settingMeshHost:Be,onSetMeshHost:ge,activeDaemon:je,activeDaemonId:se,meshQueue:te,userName:r,availableCliProviders:y,savingNodeSlotsId:Pe,onUpdateNodeSlots:Ze,savingNodeCapabilitiesId:He,onUpdateNodeCapabilities:Ue,nodeSystemPromptDrafts:de,onNodeSystemPromptDraftChange:(Oe,lt)=>xe(es=>({...es,[Oe]:lt})),savingNodeSystemPromptId:Se,onSaveNodeSystemPrompt:nt,selectedNodeId:ye,onSelectNode:Me,showAddNode:re,onShowAddNode:()=>ce(!0),onCancelAddNode:()=>ce(!1),nodeWorkspace:Ae,onNodeWorkspaceChange:be,nodeProviderPriority:we,onNodeProviderPriorityChange:_e,nodeDaemonId:U,onNodeDaemonIdChange:Ne,nodeCustomPath:Ie,onNodeCustomPathChange:We,nodePickerWorkspaces:Xe,nodePickerProviders:et,nodeOnboardingPlan:J,nodePlanLoading:Le,attachableDaemons:Fe,onAddNode:Ee,onRemoveNode:Je,availableCliAgents:x,features:{coordinatorPrompt:g.coordinatorPrompt,meshHostDaemonSection:g.meshHostDaemonSection,hermesMcpConfig:g.hermesMcpConfig,addNodeDaemonPicker:g.addNodeDaemonPicker,nodeInstruction:g.nodeInstruction},sendCommand:t}):s.jsx(JL,{meshes:C,loading:j,error:N,onDismissError:()=>A(null),daemons:a,features:{createDaemonPicker:g.createDaemonPicker,maxMeshes:g.maxMeshes},showCreate:T,onToggleCreate:()=>I(!T),createName:P,onCreateNameChange:M,createRepoIdentity:E,onCreateRepoIdentityChange:D,createRepoRemoteUrl:W,onCreateRepoRemoteUrlChange:R,newMeshDaemonId:B,onNewMeshDaemonIdChange:_,newMeshWorkspace:H,onNewMeshWorkspaceChange:L,createPickerWorkspaces:F,createOnboardingPlan:$,createPlanLoading:K,creating:z,createWarning:ne,onDismissCreateWarning:()=>ie(null),onSelectMesh:w,onCreate:me,onCancelCreate:Y}):s.jsx(Ja,{icon:s.jsx(cs,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})})}function gR(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function bR({children:e}){const{sendCommand:t,sendData:n}=St(),{ides:a}=Ss(),r=l.useMemo(()=>a.filter(i=>i.daemonMode||i.type==="adhdev-daemon").map(i=>i),[a]),o=l.useMemo(()=>({sendCommand:t,sendData:n,daemons:r,userName:void 0,loadMeshStatus:async(i,c)=>t(i,"mesh_status",{meshId:c}),launchCoordinator:async(i,c)=>{var f;const d={meshId:c.meshId};c.cliType&&(d.cliType=c.cliType);const p=await t(i,"launch_mesh_coordinator",d),u=(p==null?void 0:p.result)??p;if((u==null?void 0:u.success)===!1)throw new Error(u.error||"Coordinator launch failed");const m=(u==null?void 0:u.sessionId)||((f=u==null?void 0:u.session)==null?void 0:f.id)||(u==null?void 0:u.targetSessionId);return{sessionId:m,message:m?`Coordinator launched (${m})`:"Coordinator launch command sent"}},loadLiveMesh:void 0,extractStatus:Xl,unwrapResult:i=>i,normalizeMesh:(i,c)=>i,normalizeNode:(i,c,d)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:rg}),[t,n,r]);return s.jsx(og.Provider,{value:o,children:e})}function xR(e){const{daemons:t,features:n,meshes:a,meshesLoading:r,selectedMeshId:o,onSelectMesh:i,createMode:c,onCreateModeChange:d,createName:p,onCreateNameChange:u,createDaemonId:m,onCreateDaemonIdChange:f,createWorkspace:g,onCreateWorkspaceChange:k,createPickerWorkspaces:h,createPlan:b,createPlanLoading:S,creating:x,createWarning:y,onCreate:C,createRepoRemoteUrl:v,onCreateRepoRemoteUrlChange:w,createRepoIdentity:j,onCreateRepoIdentityChange:N,createManualOpen:A,onCreateManualOpenChange:T,nodes:I,attachableDaemons:P,attachDaemonId:M,onAttachDaemonIdChange:E,attachWorkspace:D,onAttachWorkspaceChange:W,attachPickerWorkspaces:R,attachPlan:B,attachPlanLoading:_,attaching:H,onAttach:L,renderInstallOnboarding:F,nodeLabel:$,daemonLabel:K}=e,{t:z}=ke("common");if(t.length===0)return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:z("setupWizard.machines.title")}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-text-muted",children:z("setupWizard.machines.noMachinesDescription")})]}),F?F():s.jsx("p",{className:"text-[11px] text-text-muted",children:z("setupWizard.machines.noMachinesFallback")})]});const ne=H||_||(B==null?void 0:B.success)===!1||!D.trim()||n.addNodeDaemonPicker&&!M;return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:z("setupWizard.machines.title")}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-text-muted",children:z("setupWizard.machines.description")})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[a.map(ie=>{const Ce=!c&&o===ie.id;return s.jsx("button",{type:"button",onClick:()=>{d(!1),i(ie.id)},className:`flex items-center gap-2 rounded-lg border px-3 py-2 text-left transition-colors ${Ce?"border-accent-primary/60 bg-accent-primary/10":"border-border-subtle bg-bg-secondary/60 hover:border-border-default"}`,children:s.jsxs("span",{className:"min-w-0",children:[s.jsx("span",{className:"block truncate text-sm text-text-primary",children:ie.name}),s.jsxs("span",{className:"block truncate text-[11px] text-text-muted",children:[ie.repoIdentity||ie.repoRemoteUrl||""," · ",z("setupWizard.machines.nodeCount",{count:(ie.nodes||[]).length})]})]})},ie.id)}),s.jsx("button",{type:"button",onClick:()=>d(!0),className:`flex items-center gap-2 rounded-lg border px-3 py-2 text-left transition-colors ${c?"border-accent-primary/60 bg-accent-primary/10":"border-dashed border-border-subtle bg-bg-secondary/40 hover:border-border-default"}`,children:s.jsxs("span",{className:"text-sm text-text-primary",children:["+ ",z("setupWizard.machines.createNew")]})}),r&&a.length===0&&s.jsx("p",{className:"text-[11px] text-text-muted",children:z("setupWizard.machines.loadingMeshes")})]}),c&&s.jsx(cg,{variant:"wizard",showDaemonPicker:n.createDaemonPicker,daemons:t,daemonLabel:K,name:p,onNameChange:u,daemonId:m,onDaemonIdChange:f,workspace:g,onWorkspaceChange:k,workspaces:h,plan:b,planLoading:S,repoRemoteUrl:v,onRepoRemoteUrlChange:w,repoIdentity:j,onRepoIdentityChange:N,manualOpen:A,onManualOpenChange:T,creating:x,warning:y,onCreate:C}),!c&&o&&s.jsxs("div",{className:"flex flex-col gap-2.5 rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2.5",children:[I.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5",children:I.map(ie=>s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] text-text-secondary",children:$(ie)},ie.id))}),s.jsx("span",{className:"text-[11px] font-medium text-text-secondary",children:z("setupWizard.machines.attachTitle")}),n.addNodeDaemonPicker&&(P.length>0?s.jsx("div",{className:"flex flex-wrap gap-1.5",children:P.map(ie=>{const Ce=M===ie.id;return s.jsx("button",{type:"button",onClick:()=>E(ie.id),className:`rounded-full border px-2.5 py-1 text-[11px] transition-colors ${Ce?"border-accent-primary/60 bg-accent-primary/10 text-text-primary":"border-border-subtle bg-bg-secondary text-text-secondary hover:border-border-default"}`,children:K(ie)},ie.id)})}):s.jsx("p",{className:"text-[11px] text-text-muted",children:z("setupWizard.machines.allMachinesAttached")})),(!n.addNodeDaemonPicker||M)&&s.jsxs(s.Fragment,{children:[s.jsx(Cl,{workspaces:R,value:D,onChange:W}),s.jsx(lg,{plan:B,loading:_}),s.jsx("div",{className:"flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:L,disabled:ne,children:z(H?"setupWizard.machines.attaching":"setupWizard.machines.addMachine")})})]})]})]})}function vR(e){var t;return e.machineNickname||e.nickname||e.hostname||((t=e.user)==null?void 0:t.name)||e.id}function yR(e){const t=e;return t.machine_label||t.machineLabel||t.hostname||String(e.workspace||"").split(/[\\/]/).filter(Boolean).pop()||e.id}function wR({daemons:e,features:t,sendCommand:n,unwrapResult:a,normalizeMesh:r,loadDaemonMetadata:o,initialMeshId:i,onClose:c,renderInstallOnboarding:d}){var Ae,be;const{t:p}=ke("common"),u=((Ae=e[0])==null?void 0:Ae.id)||"",{meshes:m,loading:f,error:g,setError:k,loadMeshes:h,selectedMeshId:b,setSelectedMeshId:S}=pg({daemons:e,primaryDaemonId:u,sendCommand:n,unwrapResult:a,normalizeMesh:r,features:{createDaemonPicker:t.createDaemonPicker,addNodeDaemonPicker:t.addNodeDaemonPicker},loadDaemonMetadata:o});l.useEffect(()=>{h()},[h]);const x=l.useRef(m);x.current=m;const y=l.useMemo(()=>m.map(we=>we.id).sort().join(","),[m]),C=l.useRef(n);C.current=n;const v=l.useRef(a);v.current=a,l.useEffect(()=>{b||m.length===0||(i&&m.some(we=>we.id===i)?S(i):m.length===1&&S(m[0].id))},[m,b,i,S]);const w=l.useMemo(()=>m.find(we=>we.id===b)??null,[m,b]),j=l.useMemo(()=>(w==null?void 0:w.nodes)||[],[w]),N=l.useCallback(we=>(we==null?void 0:we.__sourceDaemonId)||u,[u]),[A,T]=l.useState(!1),[I,P]=l.useState(""),[M,E]=l.useState(""),[D,W]=l.useState(""),[R,B]=l.useState(null),[_,H]=l.useState(!1),[L,F]=l.useState(!1),[$,K]=l.useState(null),[z,ne]=l.useState(""),[ie,Ce]=l.useState(""),[me,O]=l.useState(!1),Y=t.createDaemonPicker&&M||u,X=l.useMemo(()=>e.find(we=>we.id===Y),[e,Y]),Q=(X==null?void 0:X.workspaces)||[];l.useEffect(()=>{if(!A||!Y||!D.trim()){B(null),H(!1);return}let we=!1;const _e=setTimeout(()=>{we||(H(!0),C.current(Y,"plan_mesh_onboarding",{workspace:D.trim(),operation:"auto",meshInventory:x.current}).then(U=>{if(we)return;const Ne=v.current(U);B(Ne),Ne!=null&&Ne.success&&(P(Ie=>{var We,Xe;return Ie||`${String(((We=Ne.discovery)==null?void 0:We.repoIdentity)||((Xe=Ne.discovery)==null?void 0:Xe.repoRoot)||"").split(/[\\/]/).filter(Boolean).pop()||"repo"}-mesh`}),Ce(Ie=>{var We;return Ie||((We=Ne.discovery)==null?void 0:We.repoIdentity)||""}),ne(Ie=>{var We,Xe,et,J,Le,$e;return Ie||((et=(Xe=(We=Ne.discovery)==null?void 0:We.origin)==null?void 0:Xe.urls)==null?void 0:et[0])||(($e=(Le=(J=Ne.discovery)==null?void 0:J.upstream)==null?void 0:Le.urls)==null?void 0:$e[0])||""}))}).catch(U=>{we||B({success:!1,error:(U==null?void 0:U.message)||"Git discovery failed"})}).finally(()=>{we||H(!1)}))},300);return()=>{we=!0,clearTimeout(_e)}},[A,Y,D,y]);const ve=l.useCallback(async()=>{const we=Y,_e=D.trim(),U=z.trim(),Ne=ie.trim();if(!(!we||!I.trim()||L)&&!(!_e&&!U&&!Ne)){F(!0),K(null),k(null);try{const Ie=await ug({targetDaemonId:we,name:I,repoRemoteUrl:U,repoIdentity:Ne,workspace:_e,attachWorkspace:!!_e,machineId:X==null?void 0:X.machineId,providerPriority:Dn(cn((X==null?void 0:X.availableProviders)||[])),meshInventory:m,sendCommand:n,unwrapResult:a});if(Ie.warning&&K(Ie.warning),!Ie.meshCreated){k(Ie.error||p("setupWizard.machines.createFailed"));return}await h(!0),Ie.meshId&&S(Ie.meshId),T(!1)}finally{F(!1)}}},[Y,I,D,z,ie,L,X,m,n,a,h,S,k,p]),[he,Z]=l.useState(""),[fe,V]=l.useState(""),[q,ee]=l.useState(null),[pe,le]=l.useState(!1),[se,te]=l.useState(!1),ue=l.useMemo(()=>{if(!t.addNodeDaemonPicker)return[];const we=new Set(j.map(_e=>String(_e.daemon_id||_e.daemonId||"")));return e.filter(_e=>_e.id&&!we.has(_e.id)&&!am(_e))},[t.addNodeDaemonPicker,j,e]),ye=l.useMemo(()=>e.find(we=>we.id===he),[e,he]),Me=t.addNodeDaemonPicker?(ye==null?void 0:ye.workspaces)||[]:((be=e.find(we=>we.id===u))==null?void 0:be.workspaces)||[];l.useEffect(()=>{if(A||!b||!fe.trim()){ee(null);return}const we=t.addNodeDaemonPicker?he:N(w);if(!we)return;let _e=!1;return le(!0),n(we,"plan_mesh_onboarding",{workspace:fe.trim(),meshId:b,inlineMesh:w,operation:"add_existing"}).then(U=>{_e||ee(a(U))}).catch(U=>{_e||ee({success:!1,error:(U==null?void 0:U.message)||"Git discovery failed"})}).finally(()=>{_e||le(!1)}),()=>{_e=!0}},[A,b,w,fe,he,t.addNodeDaemonPicker,N,n,a]);const re=l.useCallback(async()=>{var U,Ne,Ie,We;const we=N(w);if(!b||!we||se)return;const _e=fe.trim();if(_e){te(!0),k(null);try{const Xe=t.addNodeDaemonPicker?he:we,et=await n(Xe,"plan_mesh_onboarding",{workspace:_e,meshId:b,inlineMesh:w,operation:"add_existing"}),J=a(et);if(ee(J),(J==null?void 0:J.success)===!1)throw new Error(`${J.code||"onboarding_blocked"}: ${J.error}${J.action?` ${J.action}`:""}`);const Le={meshId:b,workspace:((U=J==null?void 0:J.discovery)==null?void 0:U.repoRoot)||_e,repoRoot:(Ne=J==null?void 0:J.discovery)==null?void 0:Ne.repoRoot,isLocalWorktree:((Ie=J==null?void 0:J.discovery)==null?void 0:Ie.isLinkedWorktree)===!0};t.addNodeDaemonPicker&&he&&(Le.daemonId=he,Le.machineId=ye==null?void 0:ye.machineId),Le.providerPriority=Dn(cn(((We=t.addNodeDaemonPicker?ye:e[0])==null?void 0:We.availableProviders)||[]));const $e=await n(we,"add_mesh_node",Le),at=a($e);if((at==null?void 0:at.success)===!1)throw new Error(at.error||"Add node failed");V(""),ee(null),await h(!0)}catch(Xe){k((Xe==null?void 0:Xe.message)||"Add node failed")}finally{te(!1)}}},[w,b,fe,he,ye,se,t.addNodeDaemonPicker,N,e,n,a,h,k]),ce=!A&&!!w&&j.length>0;return s.jsxs("div",{className:"mx-auto flex w-full max-w-2xl flex-col gap-4 p-4",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-base font-semibold text-text-primary",children:p("setupWizard.title")}),s.jsx("p",{className:"mt-1.5 text-[11px] text-text-muted",children:p("setupWizard.machines.description")})]}),g&&s.jsx("p",{className:"text-[11px] text-red-400",children:g}),s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary p-4",children:s.jsx(xR,{daemons:e,features:t,meshes:m,meshesLoading:f,selectedMeshId:b,onSelectMesh:we=>{S(we),V(""),Z("")},createMode:A,onCreateModeChange:T,createName:I,onCreateNameChange:P,createDaemonId:M,onCreateDaemonIdChange:E,createWorkspace:D,onCreateWorkspaceChange:W,createPickerWorkspaces:Q,createPlan:R,createPlanLoading:_,creating:L,createWarning:$,onCreate:ve,createRepoRemoteUrl:z,onCreateRepoRemoteUrlChange:ne,createRepoIdentity:ie,onCreateRepoIdentityChange:Ce,createManualOpen:me,onCreateManualOpenChange:O,nodes:j,attachableDaemons:ue,attachDaemonId:he,onAttachDaemonIdChange:we=>{Z(we),V("")},attachWorkspace:fe,onAttachWorkspaceChange:V,attachPickerWorkspaces:Me,attachPlan:q,attachPlanLoading:pe,attaching:se,onAttach:re,renderInstallOnboarding:d,nodeLabel:yR,daemonLabel:vR})}),s.jsx("div",{className:"flex items-center gap-2",children:s.jsx("div",{className:"ml-auto flex items-center gap-2",children:s.jsx("button",{type:"button",className:ce?"btn btn-primary btn-sm":"btn btn-secondary btn-sm",onClick:c,children:p(ce?"setupWizard.continueToMesh":"setupWizard.close")})})})]})}function Ic(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function kR(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=Ic();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 Ms(e,t){return await fetch(kR(e),{credentials:"same-origin",...t})}function fg(){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 SR{constructor(){it(this,"adapters",new Map);it(this,"states",new Map);it(this,"runtimeListeners",new Map);it(this,"screenshotCallbacks",new Map);it(this,"statusCallbacks",new Set);it(this,"stateChangeCallbacks",new Set);it(this,"ptyInputSender",null)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const n of this.adapters.keys())if(n.startsWith("standalone"))return n}return null}register(t,n){this.adapters.set(t,n),this.states.set(t,n.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,n){this.states.set(t,n);const a=this.resolveDaemonId(t)||t;this.stateChangeCallbacks.forEach(r=>r(a,n))}onStateChange(t){return this.stateChangeCallbacks.add(t),()=>{this.stateChangeCallbacks.delete(t)}}retryConnection(t){}get(t){const n=this.resolveDaemonId(t);return n?this.adapters.get(n):void 0}getState(t){const n=this.resolveDaemonId(t);return n&&this.states.get(n)||"disconnected"}registerPtyInputSender(t){this.ptyInputSender=t}sendData(t,n){return!1}sendPtyInput(t,n,a){return this.ptyInputSender?this.ptyInputSender(t,n,a):!1}onScreenshot(t,n){return this.screenshotCallbacks.set(t,n),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,n){this.screenshotCallbacks.forEach(a=>a(t,n))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,n){this.statusCallbacks.forEach(a=>a(t,n))}emitRuntimeSnapshot(t,n,a=0,r=!1,o,i){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:a,text:n,truncated:r,cols:o,rows:i})}emitSessionOutput(t,n,a){!t||typeof n!="string"||!n||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof a=="number"?{seq:a}:{},data:n})}onRuntimeEvent(t,n){const a=this.runtimeListeners.get(t)||new Set;return a.add(n),this.runtimeListeners.set(t,a),()=>{const r=this.runtimeListeners.get(t);r&&(r.delete(n),r.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,n,a){if(!n)return{success:!1,error:"sessionId is required"};const r=new URL(`/api/v1/runtime/${encodeURIComponent(n)}/snapshot`,window.location.origin);typeof(a==null?void 0:a.sinceSeq)=="number"&&r.searchParams.set("sinceSeq",String(a.sinceSeq));const o=await Ms(`${r.pathname}${r.search}`);if(!o.ok){let c=`Runtime snapshot unavailable (${o.status})`;try{const d=await o.json();d!=null&&d.error&&(c=d.error)}catch{}return{success:!1,error:c}}const i=await o.json();return this.emitRuntimeEvent(n,{type:"runtime_snapshot",sessionId:n,seq:typeof i.seq=="number"?i.seq:0,text:typeof i.text=="string"?i.text:"",truncated:!!i.truncated,cols:typeof i.cols=="number"?i.cols:void 0,rows:typeof i.rows=="number"?i.rows:void 0,force:!!(a!=null&&a.force)}),{success:!0}}emitRuntimeEvent(t,n){var a;(a=this.runtimeListeners.get(t))==null||a.forEach(r=>r(n))}}const Ts=new SR;function CR(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,n=Ic();return n?`${t}?token=${encodeURIComponent(n)}`:t}const Cr=CR(),dp=3e3,jR=3e4;let gs=null,NR=0;const lo=new Map;let bn=null,La=null;function up(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function wa(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function AR(e){return e==="connected"?"connected":e}async function Ra(e,t,n){const a=xh(e,n||{}),r=gs;if(r&&r.readyState===WebSocket.OPEN){const o=`req_${++NR}_${Date.now()}`;return new Promise((i,c)=>{const d=setTimeout(()=>{lo.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);lo.set(o,{resolve:p=>{clearTimeout(d),i(p)},reject:p=>{clearTimeout(d),c(p)}}),r.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:a.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function Dl(e,t){const n=gs;if(!n||n.readyState!==WebSocket.OPEN||!t||t.type!=="subscribe"&&t.type!=="unsubscribe")return!1;try{return n.send(JSON.stringify(t)),!0}catch{return!1}}function gg(e,t,n){const a=gs;if(!a||a.readyState!==WebSocket.OPEN)return!1;const r=xh(e,{sessionId:t,targetSessionId:t,data:n});try{return a.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:r.payload}})),!0}catch{return!1}}Ts.registerPtyInputSender(gg);class TR{constructor(t){it(this,"daemonId");it(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(gs==null?void 0:gs.readyState)===WebSocket.OPEN}get connectionState(){return(gs==null?void 0:gs.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,n){return Ra(this.daemonId,t,n)}async sendInput(t,n){return Ra(this.daemonId,"cdp_remote_action",{action:t,params:n,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,bn&&(clearInterval(bn),bn=null);const n=async()=>{if(this.hasCommandChannel)try{const a=await Ra(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(a!=null&&a.success&&(a!=null&&a.base64)){const r=await fetch(`data:image/jpeg;base64,${a.base64}`).then(o=>o.blob());Ts.emitScreenshot(this.daemonId,r)}}catch{}};n(),bn=setInterval(n,2e3)}stopScreenshots(t){bn&&(clearInterval(bn),bn=null)}}let rs=null;function MR(e){return(!rs||rs.daemonId!==e)&&(rs=new TR(e)),rs}function PR({children:e}){const t=l.useRef(Ea()),n=Ea();t.current=n;const{setUserName:a}=Ss(),r=l.useRef(a);r.current=a;const o=l.useRef(null),i=l.useRef(null),[,c]=l.useState("disconnected"),d=l.useCallback((h,b)=>{c(h),La==null||La(h,b)},[]),p=l.useRef(null),u=l.useRef(),m=l.useRef(dp),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 x,y;if(!f.current||((x=p.current)==null?void 0:x.readyState)===WebSocket.OPEN||((y=p.current)==null?void 0:y.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${Cr}...`),wa("connect_attempt",{url:Cr,reason:k.current,delayMs:m.current});let S;try{S=new WebSocket(Cr)}catch(C){console.error("[Standalone WS] Failed to create WebSocket:",C),b();return}p.current=S,S.onopen=()=>{if(!f.current){S.close();return}d("connected"),m.current=dp,wa("open",{url:Cr,reason:k.current}),ys.resubscribeAll({sendData:Dl}),console.log("[Standalone WS] Connected")},gs=S,S.onmessage=C=>{var v,w;try{const j=JSON.parse(C.data);if((j.type==="command_result"||j.type==="error")&&j.requestId){const N=lo.get(j.requestId);N&&(lo.delete(j.requestId),j.type==="error"?N.reject(new Error(((v=j.data)==null?void 0:v.message)||"Command failed")):N.resolve(j.data));return}if(j.type==="session_output"){const N=j.sessionId||j.cliId||j.cliType;N&&Ts.emitSessionOutput(N,typeof j.data=="string"?j.data:"",typeof j.seq=="number"?j.seq:void 0);return}if(j.type==="runtime_snapshot"){Ts.emitRuntimeSnapshot(j.sessionId,typeof j.text=="string"?j.text:"",typeof j.seq=="number"?j.seq:0,!!j.truncated,typeof j.cols=="number"?j.cols:void 0,typeof j.rows=="number"?j.rows:void 0);return}if(j.type==="topic_update"){const N=j.update;N&&ys.publish(N);return}if(j.type==="status"||j.type==="initial_state"){const N=j.data;if(!N)return;const{injectEntries:A,markLoaded:T,getIdes:I}=t.current,P=N.instanceId||"standalone",M=I().find(W=>W.id===P),E=MR(P);Ts.register(P,E),Ts.setState(P,"connected"),d("connected",P),Ts.emitStatus(P,N);const D=Or(N,{daemonId:P,existingDaemon:M,existingEntries:I()});up("ws_status",{type:j.type,daemonId:P,sessions:(N.sessions||[]).map(W=>({id:W.id,parentId:W.parentId,providerType:W.providerType,kind:W.kind,transport:W.transport,unread:W.unread,inboxBucket:W.inboxBucket,lastSeenAt:W.lastSeenAt,lastUpdated:W.lastUpdated,title:W.title})),recentLaunches:(N.recentLaunches||[]).map(W=>({id:W.id,providerType:W.providerType,kind:W.kind,workspace:W.workspace,lastLaunchedAt:W.lastLaunchedAt}))}),up("entries",{daemonId:P,entries:D.filter(W=>W.type!=="adhdev-daemon").map(W=>({id:W.id,type:W.type,unread:W.unread,inboxBucket:W.inboxBucket,lastSeenAt:W.lastSeenAt,lastUpdated:W.lastUpdated,sessionId:W.sessionId}))}),D.length>0&&A(D,{authoritativeDaemonIds:[P]}),T(),i.current!==P&&((w=o.current)==null||w.call(o),i.current=P,o.current=ys.subscribe({sendData:Dl},P,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${P}`,params:{includeSessions:!0}},W=>{if(W.topic!=="daemon.metadata")return;const R=t.current.getIdes(),B=R.find(H=>H.id===P),_=Or(W.status,{daemonId:P,existingDaemon:B,existingEntries:R,timestamp:W.timestamp});_.length>0&&t.current.injectEntries(_,{authoritativeDaemonIds:[P]}),W.userName&&r.current&&r.current(W.userName)}))}}catch(j){console.error("[Standalone WS] Parse error:",j)}},S.onclose=C=>{f.current&&(rs==null||rs.stopScreenshots(),rs&&Ts.setState(rs.daemonId,"disconnected"),d("disconnected"),p.current=null,k.current=`close:${C.code}${C.wasClean?":clean":":unclean"}`,wa("close",{code:C.code,reason:C.reason||"",wasClean:C.wasClean}),b())},S.onerror=C=>{g.current||!f.current||(k.current="error",wa("error",{message:C instanceof Event?"event":String(C),readyState:S.readyState}),console.warn("[Standalone WS] Error, will reconnect:",C))}}function b(){if(!f.current)return;clearTimeout(u.current);const S=m.current;console.log(`[Standalone WS] Reconnecting in ${S}ms...`),wa("schedule_reconnect",{reason:k.current,delayMs:S}),u.current=setTimeout(()=>{m.current=Math.min(m.current*1.5,jR),h()},S)}return h(),()=>{var S;f.current=!1,g.current=!0,(S=o.current)==null||S.call(o),o.current=null,i.current=null,clearTimeout(u.current),p.current&&(p.current.onerror=null,p.current.onclose=null,p.current.close(),p.current=null,gs=null),rs&&(rs.stopScreenshots(),Ts.unregister(rs.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function DR({children:e}){const[t,n]=l.useState("disconnected"),[a,r]=l.useState(null);l.useEffect(()=>(La=(i,c)=>{n(i),c&&r(c)},()=>{La=null}),[]);const o=l.useMemo(()=>{const i=t==="connected",c=AR(t),d={};return a&&(d[a]=c),d.standalone=c,{wsStatus:t,isConnected:i,connectionStates:d,usesP2P:!1}},[t,a]);return s.jsx(rb,{connectionOverrides:o,children:s.jsx(PR,{children:e})})}const bg="adhdev_standalone_font_preferences",An={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Eo=[{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"}],Oa=[{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"}],IR=new Set(Eo.map(e=>e.id)),LR=new Set(Oa.map(e=>e.id));function Ps(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Er("chat",t.chat),code:Er("code",t.code),terminal:Er("terminal",t.terminal)}}function Er(e,t){const n=An[e],a=t&&typeof t=="object"&&!Array.isArray(t)?t:{},r=typeof a.preset=="string"?a.preset.trim():"",o=typeof a.customFamily=="string"?a.customFamily.trim():"";return(e==="chat"?IR:LR).has(r)?r==="custom"?o?{preset:"custom",customFamily:o}:n:{preset:r}:n}function _r(e,t){var r;const n=Er(e,t);if(n.preset==="custom"&&n.customFamily)return n.customFamily;const a=e==="chat"?Eo:Oa;return((r=a.find(o=>o.id===n.preset))==null?void 0:r.family)||a[0].family}function RR(e){const t=Ps(e),n=_r("chat",t.chat),a=_r("code",t.code),r=_r("terminal",t.terminal);return{"--chat-font-family":n,"--chat-code-font-family":a,"--chat-terminal-font-family":r,"--chat-tool-font-family":r}}function vn(e,t=document.documentElement){const n=Ps(e),a=RR(n);t.setAttribute("data-standalone-fonts","custom");for(const[r,o]of Object.entries(a))t.style.setProperty(r,o);return n}function Il(e){const t=Ps(e);try{localStorage.setItem(bg,JSON.stringify(t))}catch{}return t}function ER(){try{const e=localStorage.getItem(bg);if(e)return Ps(JSON.parse(e))}catch{}return An}function _R(){return vn(ER())}function ka(e,t){var a;const n=e==="chat"?Eo:Oa;return((a=n.find(r=>r.id===t))==null?void 0:a.label)||n[0].label}function HR({children:e}){const t=ia(),n=Rl(),{t:a}=ke("common"),r=l.useMemo(()=>[{id:"dashboard",path:"/dashboard",icon:s.jsx(Tp,{}),label:a("nav.dashboard"),active:n.pathname.startsWith("/dashboard"),onSelect:()=>t("/dashboard")},{id:"machine",path:"/machines",icon:s.jsx(nn,{}),label:a("nav.machines"),active:n.pathname.startsWith("/machines"),onSelect:()=>t("/machines")},{id:"mesh",path:"/mesh",icon:s.jsx(cs,{}),label:a("nav.mesh"),active:n.pathname.startsWith("/mesh")||n.pathname.startsWith("/setup"),onSelect:()=>t("/mesh")},{id:"settings",path:"/settings",icon:s.jsx(Ua,{}),label:a("nav.settings"),active:n.pathname.startsWith("/settings"),onSelect:()=>t("/settings")}],[n.pathname,t,a]),o=l.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:a("nav.docs")}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(Mp,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:a("nav.docs")},{id:"about",label:a("nav.about"),icon:s.jsx(uo,{}),active:n.pathname==="/about",onSelect:()=>t("/about"),title:a("nav.about")}],[n.pathname,t,a]);return s.jsx(m1,{brand:({collapsed:i})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&s.jsx("span",{children:"ADHDev"})]}),navItems:r,footerItems:o,footerInfo:({collapsed:i})=>i?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","1.0.56"]}),footerActions:({collapsed:i,toggleCollapsed:c})=>s.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:c,title:a(i?"standalone.layout.expandSidebar":"standalone.layout.collapseSidebar"),children:[s.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&s.jsx("span",{className:"text-xs",children:a("standalone.layout.collapse")})]}),children:e})}function $R(){const e=ia(),{sendCommand:t}=St(),{ides:n}=Ss(),a=l.useMemo(()=>n.filter(r=>r.daemonMode||r.type==="adhdev-daemon").map(r=>r),[n]);return s.jsx(wR,{daemons:a,features:rg,sendCommand:t,unwrapResult:r=>r,normalizeMesh:r=>r,onClose:()=>e("/mesh")})}const FR=[{icon:s.jsx(nn,{size:16}),key:"localFirst"},{icon:s.jsx(Is,{size:16}),key:"chatRelay"},{icon:s.jsx(Fl,{size:16}),key:"screenshots"},{icon:s.jsx(us,{size:16}),key:"remoteControl"},{icon:s.jsx(_a,{size:16}),key:"multiIde"},{icon:s.jsx(Mp,{size:16}),key:"cliAcp"}],BR=[{icon:s.jsx(ho,{size:16}),key:"anywhere"},{icon:s.jsx(Tp,{size:16}),key:"p2pStream"},{icon:s.jsx(la,{size:16}),key:"mobileNotifications"},{icon:s.jsx(fb,{size:16}),key:"restApi"},{icon:s.jsx(bb,{size:16}),key:"enterpriseControls"}],WR=[{key:"chatRelay",selfhost:!0,cloud:!0},{key:"screenshots",selfhost:!0,cloud:!0},{key:"remoteControl",selfhost:!0,cloud:!0},{key:"multiIde",selfhost:!0,cloud:!0},{key:"extensionCli",selfhost:!0,cloud:!0},{key:"anyNetwork",selfhost:!1,cloud:!0},{key:"webrtc",selfhost:!1,cloud:!0},{key:"mobilePush",selfhost:!1,cloud:!0},{key:"restApi",selfhost:!1,cloud:!0},{key:"multiMachineDashboards",selfhost:!1,cloud:!0},{key:"ssoRbacAuditLogs",selfhost:!1,cloud:!0}];function OR(){const{t:e}=ke("common");return s.jsxs(Ja,{icon:s.jsx(uo,{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.56"]}),children:[s.jsx(xt,{children:s.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[s.jsxs("div",{className:"max-w-2xl",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:e("standalone.about.selfHostedEdition")}),s.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:e("standalone.about.headline")}),s.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:e("standalone.about.description")})]}),s.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.docs")}),s.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.github")}),s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.tryCloud")})]})]})}),s.jsx(xt,{title:e("standalone.about.includedSection"),description:e("standalone.about.includedDescription"),children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:FR.map(t=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:t.icon}),e("standalone.about.features."+t.key+".title")]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e("standalone.about.features."+t.key+".desc")})]},t.key))})}),s.jsx(xt,{title:e("standalone.about.inventorySection"),description:e("standalone.about.inventoryDescription"),children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:vh.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:wh.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:yh.map(t=>`${t.icon} ${t.name}`)}].map(t=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[s.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:t.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:t.items.map(n=>s.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:n},n))})]},t.label))})}),s.jsx(xt,{title:e("standalone.about.cloudExtrasSection"),description:e("standalone.about.cloudExtrasDescription"),children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:BR.map(t=>s.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:t.icon}),e("standalone.about.extras."+t.key+".title")]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e("standalone.about.extras."+t.key+".desc")})]},t.key))})}),s.jsx(xt,{title:e("standalone.about.comparisonSection"),description:e("standalone.about.comparisonDescription"),children:s.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:s.jsxs("table",{className:"w-full text-[13px]",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"bg-bg-secondary",children:[s.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:e("standalone.about.featureHeader")}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:e("standalone.about.selfhostHeader")}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:e("standalone.about.cloudHeader")})]})}),s.jsx("tbody",{children:WR.map((t,n)=>s.jsxs("tr",{className:n%2===0?"bg-bg-glass":"bg-transparent",children:[s.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e("standalone.about.comparison."+t.key)}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:t.selfhost?s.jsx("span",{className:"text-emerald-500",children:"✓"}):s.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:s.jsx("span",{className:"text-emerald-500",children:"✓"})})]},t.key))})]})})}),s.jsx(Xa,{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(Nb,{size:14,className:"mr-1"}),e("standalone.about.discord")]})]})})]})}function Fi(e,t,n){return{...e,[t]:n}}function Bi({surface:e,title:t,description:n,value:a,options:r,onChange:o}){const{t:i}=ke("common");return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:n})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(b1,{value:a.preset,onChange:c=>{const d=c.target.value;o(d==="custom"?{preset:"custom",customFamily:a.customFamily||""}:{preset:d})},children:r.map(c=>s.jsx("option",{value:c.id,children:c.label},c.id))}),a.preset==="custom"&&s.jsx(xs,{type:"text",className:"font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:a.customFamily||"",onChange:c=>o({preset:"custom",customFamily:c.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:i("standalone.fonts.resolvedStack")})," ",s.jsx("span",{className:"font-mono break-all",children:_r(e,a)})]})]})]})}function UR({value:e,savedValue:t,saving:n=!1,error:a,notice:r,onChange:o,onSave:i,onResetToSaved:c,onResetToDefaults:d}){const{t:p}=ke("common"),u=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:p("standalone.fonts.fontOverridesNotice")}),a&&s.jsx(Mt,{variant:"error",children:a}),r&&s.jsx(Mt,{variant:"success",children:r}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(Bi,{surface:"chat",title:p("standalone.fonts.chat"),description:p("standalone.fonts.chatDescription"),value:e.chat,options:Eo,onChange:m=>o(Fi(e,"chat",m))}),s.jsx(Bi,{surface:"code",title:p("standalone.fonts.code"),description:p("standalone.fonts.codeDescription"),value:e.code,options:Oa,onChange:m=>o(Fi(e,"code",m))}),s.jsx(Bi,{surface:"terminal",title:p("standalone.fonts.terminal"),description:p("standalone.fonts.terminalDescription"),value:e.terminal,options:Oa,onChange:m=>o(Fi(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: ",ka("chat",e.chat.preset)," · Code: ",ka("code",e.code.preset)," · Terminal: ",ka("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[p("standalone.fonts.defaults")," ",ka("chat",An.chat.preset)," / ",ka("code",An.code.preset)]})]}),s.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:s.jsxs("div",{className:"chat-container-content",children:[s.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:s.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[s.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[s.jsx("span",{className:"chat-sender",children:"Hermes"}),s.jsx("span",{className:"chat-time",children:"now"})]}),s.jsxs("div",{className:"chat-markdown",children:[s.jsxs("p",{children:["Readable prose, ",s.jsx("strong",{children:"bold text"}),", and ",s.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),s.jsx("pre",{children:s.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),s.jsxs("div",{className:"chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"▸"}),s.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),s.jsxs("div",{className:"chat-msg-terminal",children:[s.jsx("div",{className:"chat-msg-header",children:"Terminal"}),s.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx(Gs,{type:"button",variant:"primary",size:"sm",onClick:i,disabled:n||!u,children:p(n?"standalone.fonts.saving":"standalone.fonts.saveFontSettings")}),s.jsx(Gs,{type:"button",variant:"secondary",size:"sm",onClick:c,disabled:n||!u,children:p("standalone.fonts.revertToSaved")}),s.jsx(Gs,{type:"button",variant:"secondary",size:"sm",onClick:d,disabled:n,children:p("standalone.fonts.resetToDefaults")})]})]})}function GR(){const{t:e}=ke("common"),{ides:t}=Ss(),n=t.find(O=>O.type==="adhdev-daemon"),a=(n==null?void 0:n.detectedIdes)||[],{sendCommand:r}=St(),{userName:o}=Ss(),[i,c]=l.useState(o||""),[d,p]=l.useState(null),[u,m]=l.useState(null),[f,g]=l.useState(An),[k,h]=l.useState(!1),[b,S]=l.useState(""),[x,y]=l.useState(""),[C,v]=l.useState("127.0.0.1"),[w,j]=l.useState(""),[N,A]=l.useState(""),[T,I]=l.useState(""),[P,M]=l.useState(""),[E,D]=l.useState(""),[W,R]=l.useState(!1),B=async()=>{const Y=await(await Ms("/auth/session")).json();p(Y)},_=async()=>{const Y=await(await Ms("/api/v1/standalone/preferences")).json();m(Y),v(Y.standaloneBindHost);const X=Ps(Y.standaloneFontPreferences);g(X),vn(X),Il(X)};l.useEffect(()=>{o!==void 0&&c(o)},[o]),l.useEffect(()=>{Promise.all([B(),_()]).catch(O=>{M(O instanceof Error?O.message:String(O))})},[]),l.useEffect(()=>{vn(f)},[f]);const H=O=>{const Y=O.target.value.trim();n!=null&&n.id&&Y!==o&&r(n.id,"set_user_name",{userName:Y}).catch(console.error)},[L,F]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),$=O=>{F(O);try{localStorage.setItem("adhdev_sound",O?"1":"0")}catch{}},K=async()=>{S(""),y(""),h(!0);try{const O=Ps(f),Y=await Ms("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:O})}),X=await Y.json();if(!Y.ok)throw new Error((X==null?void 0:X.error)||"Failed to save standalone font preferences");const Q=Ps(X.standaloneFontPreferences);m(X),g(Q),vn(Q),Il(Q),y(e("standalone.settings.fontsSaved"))}catch(O){S(O instanceof Error?O.message:String(O))}finally{h(!1)}},z=()=>{const O=Ps(u==null?void 0:u.standaloneFontPreferences);S(""),y(""),g(O),vn(O)},ne=()=>{S(""),y(""),g(An),vn(An)},ie=async()=>{M(""),D(""),R(!0);try{const O=await Ms("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:C})}),Y=await O.json();if(!O.ok)throw new Error((Y==null?void 0:Y.error)||"Failed to save standalone network preference");m(Y),v(Y.standaloneBindHost),D(Y.standaloneBindHost==="0.0.0.0"?e("standalone.settings.networkSavedAll"):e("standalone.settings.networkSavedLocal"))}catch(O){M(O instanceof Error?O.message:String(O))}finally{R(!1)}},Ce=async()=>{if(M(""),D(""),N.trim().length<4){M(e("standalone.settings.passwordTooShort"));return}if(N!==T){M(e("standalone.settings.passwordMismatch"));return}R(!0);try{const O=await Ms("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:w,newPassword:N})}),Y=await O.json();if(!O.ok)throw new Error((Y==null?void 0:Y.error)||"Failed to save password");p(Y),await _(),j(""),A(""),I(""),D(d!=null&&d.hasPasswordAuth?e("standalone.settings.passwordUpdated"):e("standalone.settings.passwordEnabled")),fg()}catch(O){M(O instanceof Error?O.message:String(O))}finally{R(!1)}},me=async()=>{M(""),D(""),R(!0);try{const O=await Ms("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:w,clear:!0})}),Y=await O.json();if(!O.ok)throw new Error((Y==null?void 0:Y.error)||"Failed to clear password");p(Y),await _(),j(""),A(""),I(""),D(e("standalone.settings.passwordDisabled"))}catch(O){M(O instanceof Error?O.message:String(O))}finally{R(!1)}};return s.jsxs(Ja,{icon:s.jsx(Ua,{className:"text-text-primary"}),title:e("standalone.settings.title"),subtitle:e("standalone.settings.subtitle"),widthClassName:"max-w-5xl",children:[s.jsx(Mt,{variant:"info",children:e("standalone.settings.infoNotice")}),(d==null?void 0:d.publicHostWarning)&&s.jsx(Mt,{variant:"warning",children:e("standalone.settings.publicHostWarning")}),s.jsx(xt,{title:e("standalone.settings.daemonSection"),description:e("standalone.settings.daemonDescription"),children:s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.versionLabel")}),s.jsxs("span",{className:"font-mono text-xs text-text-primary",children:["v","1.0.56"]})]}),s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.statusLabel")}),s.jsx("span",{className:`text-xs font-medium ${n?"text-green-400":"text-yellow-400"}`,children:e(n?"standalone.settings.statusRunning":"standalone.settings.statusNotConnected")})]}),s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.currentBindLabel")}),s.jsx("span",{className:"font-mono text-xs text-text-primary",children:(u==null?void 0:u.currentBindHost)||(d==null?void 0:d.boundHost)||"127.0.0.1"})]}),s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.defaultBindLabel")}),s.jsx("span",{className:"font-mono text-xs text-text-primary",children:(u==null?void 0:u.standaloneBindHost)||"127.0.0.1"})]}),s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.authLabel")}),s.jsx("span",{className:"text-xs text-text-primary",children:d!=null&&d.hasPasswordAuth?e("standalone.settings.authPassword"):d!=null&&d.hasTokenAuth?e("standalone.settings.authToken"):e("standalone.settings.authNone")})]})]})}),s.jsx(xt,{title:e("standalone.settings.networkSection"),description:e("standalone.settings.networkDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:e("standalone.settings.networkHint")}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:C==="127.0.0.1",onChange:()=>v("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:e("standalone.settings.localhostLabel")}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:e("standalone.settings.localhostHint")})]})]}),s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:C==="0.0.0.0",onChange:()=>v("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:e("standalone.settings.allInterfacesLabel")}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:e("standalone.settings.allInterfacesHint")})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx(Gs,{type:"button",variant:"primary",size:"sm",onClick:()=>{ie()},disabled:W,children:e(W?"standalone.settings.saving":"standalone.settings.saveNetworkMode")}),s.jsx("span",{className:"text-xs text-text-muted",children:e("standalone.settings.networkRestartHint",{host:(u==null?void 0:u.currentBindHost)||(d==null?void 0:d.boundHost)||"127.0.0.1"})})]})]})}),s.jsx(xt,{title:e("standalone.settings.securitySection"),description:e("standalone.settings.securityDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:d!=null&&d.hasPasswordAuth?e("standalone.settings.passwordSet"):e("standalone.settings.passwordNotSet")}),P&&s.jsx(Mt,{variant:"error",children:P}),E&&s.jsx(Mt,{variant:"success",children:E}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx(xs,{type:"password",placeholder:d!=null&&d.hasPasswordAuth?e("standalone.settings.currentPasswordPlaceholder"):e("standalone.settings.currentPasswordFirstTimePlaceholder"),value:w,onChange:O=>j(O.target.value)}),s.jsx(xs,{type:"password",placeholder:d!=null&&d.hasPasswordAuth?e("standalone.settings.newPasswordPlaceholder"):e("standalone.settings.newPasswordFirstTimePlaceholder"),value:N,onChange:O=>A(O.target.value)}),s.jsx(xs,{type:"password",className:"md:col-span-2",placeholder:e("standalone.settings.confirmPasswordPlaceholder"),value:T,onChange:O=>I(O.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Gs,{type:"button",variant:"primary",size:"sm",onClick:()=>{Ce()},disabled:W,children:W?e("standalone.settings.saving"):d!=null&&d.hasPasswordAuth?e("standalone.settings.updatePassword"):e("standalone.settings.enablePassword")}),(d==null?void 0:d.hasPasswordAuth)&&s.jsx(Gs,{type:"button",variant:"danger",size:"sm",onClick:()=>{me()},disabled:W,children:e("standalone.settings.disablePassword")})]})]})}),s.jsx(xt,{title:e("standalone.settings.detectedIdesSection"),description:e("standalone.settings.detectedIdesDescription"),children:a.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:e("standalone.settings.noIdesDetected")}):s.jsx("div",{className:"flex flex-col gap-2",children:a.map(O=>s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${O.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium text-text-primary",children:O.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:O.type})]},O.type))})}),s.jsx(xt,{title:e("standalone.settings.machineSection"),description:e("standalone.settings.machineDescription"),children:s.jsx(A1,{ides:t,emptyMessage:e("standalone.settings.daemonNotConnected")})}),s.jsx(xt,{title:e("standalone.settings.appearanceSection"),description:e("standalone.settings.appearanceDescription"),children:s.jsx(q1,{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(UR,{value:f,savedValue:Ps(u==null?void 0:u.standaloneFontPreferences),saving:k,error:b,notice:x,onChange:g,onSave:()=>{K()},onResetToSaved:z,onResetToDefaults:ne})]})})}),s.jsx(xt,{title:e("standalone.settings.notificationsSection"),description:e("standalone.settings.notificationsDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(k1,{}),s.jsx(xn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(jb,{size:15})," ",e("standalone.settings.soundEffectsLabel")]}),description:e("standalone.settings.soundEffectsDescription"),checked:L,onChange:$})]})}),s.jsx(xt,{title:e("standalone.settings.profileSection"),description:e("standalone.settings.profileDescription"),children:s.jsx("div",{className:"flex flex-col gap-3",children:s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[s.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[s.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[s.jsx(hb,{size:16,className:"text-text-secondary"})," ",e("standalone.settings.displayNameLabel")]}),s.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:e("standalone.settings.displayNameHint")})]}),s.jsx(xs,{type:"text",className:"w-48 text-right",placeholder:e("standalone.settings.displayNamePlaceholder"),value:i,onChange:O=>c(O.target.value),onBlur:H,onKeyDown:O=>{O.key==="Enter"&&O.currentTarget.blur()}})]})})})]})}const qR=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],Na="adhdev_onboarding_done",zR=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],KR={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function VR({onDone:e}){const{t}=ke("common"),[n,a]=l.useState([]),[r,o]=l.useState(new Set(qR)),[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 w=!1;return fetch("https://api.adhf.dev/api/v1/registry/providers?sort=popular&limit=100").then(async N=>{if(!N.ok)throw new Error(`HTTP ${N.status}`);const A=await N.text();try{return JSON.parse(A)}catch{throw new Error(`unexpected non-JSON response (${N.headers.get("content-type")??"unknown content type"})`)}}).then(N=>{w||a(N.providers??[])}).catch(N=>{w||p(N instanceof Error?N.message:String(N))}).finally(()=>{w||c(!1)}),()=>{w=!0}},[]);const b=n.filter(w=>k==="all"||w.category===k),S=["cli","ide","extension","acp"].map(w=>({category:w,items:b.filter(j=>j.category===w)})).filter(w=>w.items.length>0),x=l.useCallback(w=>{o(j=>{const N=new Set(j);return N.has(w)?N.delete(w):N.add(w),N})},[]),y=l.useCallback(async()=>{if(r.size===0){localStorage.setItem(Na,"1"),e();return}m(!0);const w=[];for(const j of r)try{const A=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:j})})).json().catch(()=>({}));w.push({type:j,ok:!!A.success,error:A.error})}catch(N){w.push({type:j,ok:!1,error:N instanceof Error?N.message:String(N)})}g(w),m(!1),w.every(j=>j.ok)&&localStorage.setItem(Na,"1")},[r,e]),C=l.useCallback(()=>{localStorage.setItem(Na,"1"),e()},[e]),v=l.useCallback(()=>{f&&f.every(w=>w.ok)?e():u||C()},[f,u,e,C]);return s.jsx(Cm,{open:!0,onClose:v,size:"lg",contentClassName:"max-w-2xl",title:t("standalone.onboarding.title"),footer:s.jsxs("div",{className:"flex w-full items-center gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:t(r.size!==1?"standalone.onboarding.selectedCount_other":"standalone.onboarding.selectedCount_one",{count:r.size})}),s.jsxs("div",{className:"ml-auto flex gap-2",children:[s.jsx(Gs,{variant:"secondary",size:"sm",onClick:C,disabled:u,children:t("standalone.onboarding.skip")}),s.jsx(Gs,{variant:"primary",size:"sm",onClick:()=>{f?(localStorage.setItem(Na,"1"),e()):y()},disabled:u||!f&&r.size===0,children:u?t("standalone.onboarding.installing"):f?t("standalone.onboarding.done"):t("standalone.onboarding.installCount",{count:r.size})})]})]}),children:s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsx("div",{className:"text-[12px] text-text-muted",children:t("standalone.onboarding.intro")}),!i&&!d&&n.length>0&&s.jsx("div",{className:"flex gap-1 flex-wrap border-b border-border-subtle pb-2",children:zR.map(w=>{const j=w.key==="all"?n.length:n.filter(N=>N.category===w.key).length;return j===0&&w.key!=="all"?null:s.jsxs("button",{onClick:()=>h(w.key),className:`machine-btn text-[10px] px-2 py-0.5 ${k===w.key?"bg-accent-primary/12 border-accent-primary/40 text-accent-primary":""}`,children:[w.label," ",s.jsxs("span",{className:"opacity-60",children:["(",j,")"]})]},w.key)})}),i&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.loadingRegistry")}),!i&&d&&s.jsx(Mt,{variant:"error",children:t("standalone.onboarding.loadError",{error:d})}),!i&&!d&&b.length===0&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.noProviders")}),!i&&!d&&b.length>0&&s.jsx("div",{className:"flex flex-col gap-4",children:S.map(w=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:KR[w.category]??w.category}),s.jsx("div",{className:"grid gap-1.5",children:w.items.map(j=>{var I;const N=r.has(j.type),A=f==null?void 0:f.find(P=>P.type===j.type),T=((I=j.manifest)==null?void 0:I.details)??"";return s.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${N?"bg-accent-primary/[0.06] border-accent-primary/30":"bg-bg-glass border-border-subtle hover:bg-bg-glass-hover"}`,children:[s.jsx("input",{type:"checkbox",checked:N,onChange:()=>x(j.type),disabled:u,className:"shrink-0"}),s.jsx(Qa,{type:j.type,label:j.displayName??j.type,size:18,className:"shrink-0"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[13px] font-medium text-text-primary truncate",children:j.displayName}),T&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:T})]}),A&&s.jsx("span",{className:`text-[10px] font-semibold ${A.ok?"text-status-online":"text-status-error"}`,children:A.ok?t("standalone.onboarding.installed"):t("standalone.onboarding.installFailed",{error:A.error??"failed"})})]},j.type)})})]},w.category))})]})})}function YR(){try{return localStorage.getItem(Na)==="1"}catch{return!1}}s1();H1();T0();_R();const QR=jp({baseUrl:"",getToken:Ic});function JR({children:e}){const{t}=ke("common"),[n,a]=l.useState(null),[r,o]=l.useState(!0),[i,c]=l.useState(""),[d,p]=l.useState(""),[u,m]=l.useState(!1),f=async()=>{o(!0),p("");try{const h=await(await Ms("/auth/session")).json();a(h)}catch(k){p(k instanceof Error?k.message:String(k))}finally{o(!1)}};l.useEffect(()=>{f()},[]),l.useEffect(()=>{if(!n||n.required&&!n.authenticated)return;let k=!1;return(async()=>{try{const h=await Ms("/api/v1/standalone/preferences");if(!h.ok)return;const b=await h.json();if(k)return;const S=Ps(b.standaloneFontPreferences);vn(S),Il(S)}catch{}})(),()=>{k=!0}},[n==null?void 0:n.authenticated,n==null?void 0:n.required]);const g=async k=>{k.preventDefault(),m(!0),p("");try{const h=await Ms("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),b=await h.json();if(!h.ok)throw new Error((b==null?void 0:b.error)||"Login failed");a(b),c(""),fg()}catch(h){p(h instanceof Error?h.message:String(h))}finally{m(!1)}};return r?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:t("standalone.auth.loading")}):n?!n.required||n.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:t("standalone.auth.signInTitle")}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:n.hasPasswordAuth?t("standalone.auth.passwordProtected"):t("standalone.auth.tokenProtected")})]}),n.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:g,children:[s.jsx(xs,{type:"password",value:i,onChange:k=>c(k.target.value),placeholder:t("standalone.auth.passwordPlaceholder"),autoFocus:!0}),s.jsx(Gs,{type:"submit",variant:"primary",disabled:u||!i,className:"justify-center",children:t(u?"standalone.auth.signingIn":"standalone.auth.unlock")})]}):s.jsx(Mt,{variant:"warning",children:t("standalone.auth.noPasswordEnabled")}),d&&s.jsx(Mt,{variant:"error",children:d})]})}):s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:t("standalone.auth.loadError",{error:d||"unknown error"})})}function pp(){const{t:e}=ke("common"),{ides:t,initialLoaded:n}=Ss();if(!n)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:e("standalone.machine.loading")});const a=t.find(r=>r.daemonMode||r.type==="adhdev-daemon");return a?s.jsx(Ui,{to:`/machines/${a.id}`,replace:!0}):s.jsx(Ui,{to:"/dashboard",replace:!0})}function XR(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let n=!1;if(!YR())return fetch("/api/v1/providers/installed").then(a=>a.ok?a.json():{providers:[]}).then(a=>{n||(a.providers??[]).length===0&&t(!0)}).catch(()=>{}),()=>{n=!0}},[]),e?s.jsx(VR,{onDone:()=>t(!1)}):null}function ZR(){const{t:e}=ke("common"),{ides:t}=Ss(),n=l.useMemo(()=>{for(const u of t)if(u.activeInteractivePrompt)return u.instanceId??u.id;return null},[t]),{promptSession:a,hasActivePrompt:r,responseError:o,isSubmitting:i,submit:c,cancel:d,reopen:p}=Dh(n);return r?s.jsxs("div",{className:"relative",children:[!a&&s.jsx("button",{type:"button",onClick:p,className:"fixed bottom-4 right-4 z-[79] btn btn-primary btn-sm shadow-lg",children:e("standalone.machine.awaitingInput")}),s.jsx(Xp,{promptSession:a,isSubmitting:i,error:o,onSubmit:c,onCancel:d})]}):null}function eE(){const e=l.useMemo(()=>({sendCommand:Ra,sendData:Dl,sendPtyInput:gg}),[]);return s.jsx(Og,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(lb,{client:QR,children:s.jsx(JR,{children:s.jsx(DR,{children:s.jsx(db,{value:e,children:s.jsxs(Hb,{sendDaemonCommand:Ra,children:[s.jsx(ZR,{}),s.jsxs(HR,{children:[s.jsx(XR,{}),s.jsxs(Ug,{children:[s.jsx(Ws,{path:"/dashboard",element:s.jsx(TI,{})}),s.jsx(Ws,{path:"/machine",element:s.jsx(pp,{})}),s.jsx(Ws,{path:"/machines/:id",element:s.jsx(WL,{})}),s.jsx(Ws,{path:"/machines",element:s.jsx(pp,{})}),s.jsx(Ws,{path:"/about",element:s.jsx(OR,{})}),s.jsx(Ws,{path:"/settings",element:s.jsx(GR,{})}),s.jsx(Ws,{path:"/mesh",element:s.jsx(bR,{children:s.jsx(fR,{})})}),s.jsx(Ws,{path:"/setup",element:s.jsx($R,{})}),s.jsx(Ws,{path:"*",element:s.jsx(Ui,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}UC({connectionManager:Ts});Gg(document.getElementById("root")).render(s.jsx(eE,{}));
|
|
121
|
+
Node removal cleanup policy: ${be}`))return;const we=e.__sourceDaemonId||n;try{const U=await o(we,"remove_mesh_node",{meshId:e.id,nodeId:ce}),Ne=i(U);if((Ne==null?void 0:Ne.success)===!1)throw new Error(Ne.error||"Remove failed");h===ce&&b(null),await m(),g||await f(t)}catch(U){k((U==null?void 0:U.message)||"Remove node failed")}}async function V(ce){if(!e)return;const Ae={...Ml(e),...ce},be=e.__sourceDaemonId||n;try{K(!0),k(null);const we=await o(be,"update_mesh",{meshId:e.id,policy:Ae}),_e=i(we);if((_e==null?void 0:_e.success)===!1)throw new Error(_e.error||"Policy update failed");await m()}catch(we){k((we==null?void 0:we.message)||"Policy update failed")}finally{K(!1)}}const[q,ee]=l.useState(null);async function pe(ce,Ae){if(!t)return;const be=(e==null?void 0:e.__sourceDaemonId)||n;try{ee(ce.id),k(null);const we=await o(be,"update_mesh_node",{meshId:t,nodeId:ce.id,policy:{slots:Ae}}),_e=i(we);if((_e==null?void 0:_e.success)===!1){k(_e.error||"Node slots update failed");return}await m()}catch(we){k((we==null?void 0:we.message)||"Node slots update failed")}finally{ee(null)}}const[le,se]=l.useState(null);async function te(ce,Ae){if(!t)return;const be=(e==null?void 0:e.__sourceDaemonId)||n,we=Ae.map(_e=>_e.trim()).filter(Boolean);try{se(ce.id),k(null);const _e=await o(be,"update_mesh_node",{meshId:t,nodeId:ce.id,capabilities:we}),U=i(_e);if((U==null?void 0:U.success)===!1){k(U.error||"Node tag update failed");return}await m()}catch(_e){k((_e==null?void 0:_e.message)||"Node tag update failed")}finally{se(null)}}async function ue(){if(!n||!t)return;const Ae={...(e==null?void 0:e.coordinator)||{}};z.override.trim()?Ae.systemPromptOverride=z.override:delete Ae.systemPromptOverride,z.append.trim()?Ae.systemPromptAppend=z.append:delete Ae.systemPromptAppend,delete Ae.systemPromptSuffix;try{Ce(!0),k(null);const be=await o(n,"update_mesh",{meshId:t,coordinator:Ae}),we=i(be);if((we==null?void 0:we.success)===!1){k(we.error||"Coordinator prompt save failed");return}await m()}catch(be){k((be==null?void 0:be.message)||"Coordinator prompt save failed")}finally{Ce(!1)}}async function ye(ce){if(!n||!t)return;const Ae=(me[ce.id]||"").trim();try{X(ce.id),k(null);const be=await o(n,"update_mesh_node",{meshId:t,nodeId:ce.id,systemPrompt:Ae}),we=i(be);if((we==null?void 0:we.success)===!1){k(we.error||"Node instruction save failed");return}await m()}catch(be){k((be==null?void 0:be.message)||"Node instruction save failed")}finally{X(null)}}async function Me(ce){if(!(!e||!ce)){k(null),F(null);try{H(!0);const Ae=(e.nodes||[]).find(_e=>en(String(_e.daemon_id||_e.daemonId||""),ce)),be=await o(ce,"set_mesh_host",{meshId:e.id,hostDaemonId:ce,...Ae!=null&&Ae.id?{hostNodeId:Ae.id}:{}}),we=i(be);if((we==null?void 0:we.success)===!1){k(we.error||"Setting the mesh host failed");return}await m()}catch(Ae){k((Ae==null?void 0:Ae.message)||"Setting the mesh host failed")}finally{H(!1)}}}async function re(){if(e){k(null),F(null);try{B(!0);const ce=c?await c(a,e.id,e):null,Ae=d(a,e.id,e,e.nodes||[],ce);if("error"in Ae)throw new Error(Ae.error);const be=await p(Ae.targetDaemonId,{meshId:e.id,inlineMesh:Ae.inlineMesh,coordinatorNodeId:Ae.coordinatorNodeId,cliType:D.trim()||void 0});F(be.message)}catch(ce){k((ce==null?void 0:ce.message)||"Coordinator launch failed")}finally{B(!1)}}}return{selectedNodeId:h,setSelectedNodeId:b,showAddNode:S,setShowAddNode:x,nodeWorkspace:y,setNodeWorkspace:C,nodeProviderPriority:v,setNodeProviderPriority:w,nodeDaemonId:j,setNodeDaemonId:N,nodeCustomPath:A,setNodeCustomPath:T,nodePickerWorkspaces:ve,nodePickerProviders:he,nodeOnboardingPlan:I,nodePlanLoading:M,coordinatorCliType:D,setCoordinatorCliType:W,launchingCoordinator:R,launchResult:L,settingMeshHost:_,savingPolicy:$,coordinatorPromptDraft:z,setCoordinatorPromptDraft:ne,savingCoordinatorPrompt:ie,nodeSystemPromptDrafts:me,setNodeSystemPromptDrafts:O,savingNodeSystemPromptId:Y,savingNodeSlotsId:q,savingNodeCapabilitiesId:le,handleAddNode:Z,handleRemoveNode:fe,handleUpdatePolicy:V,handleUpdateNodeSlots:pe,handleUpdateNodeCapabilities:te,handleSaveCoordinatorPrompt:ue,handleSaveNodeSystemPrompt:ye,handleLaunchCoordinator:re,handleSetMeshHost:Me}}function tR(e){const t=e.filter(a=>a.status==="pending"||a.status==="assigned"),n=e.filter(a=>a.status==="completed"||a.status==="failed"||a.status==="cancelled");return{active:t.length,historical:n.length,activeCounts:{pending:t.filter(a=>a.status==="pending").length,assigned:t.filter(a=>a.status==="assigned").length},historicalCounts:{completed:n.filter(a=>a.status==="completed").length,failed:n.filter(a=>a.status==="failed").length},counts:{pending:e.filter(a=>a.status==="pending").length,assigned:e.filter(a=>a.status==="assigned").length,completed:e.filter(a=>a.status==="completed").length,failed:e.filter(a=>a.status==="failed").length},staleAssignedCount:e.filter(a=>a.staleAssigned).length,recent:e.slice(0,20)}}function sR({primaryDaemonId:e,activeDaemonId:t,sendCommand:n,unwrapResult:a,loadLiveMesh:r,resolveCommandTarget:o}){const[i,c]=l.useState([]),[d,p]=l.useState(null),[u,m]=l.useState(!1),[f,g]=l.useState(null),k=l.useCallback(async b=>{if(!e||!b){c([]);return}try{const S=await n(e,"get_mesh_queue",{meshId:b});c(S!=null&&S.success?Array.isArray(S.queue)?S.queue:[]:[])}catch{c([])}},[e,n]);async function h(b){var S,x;if(b){m(!0),g(null);try{const y=r?await r(t,b.id,b):null,C=o(t,b.id,b,b.nodes||[],y);if("error"in C)throw new Error(C.error);const v=await n(C.targetDaemonId,"get_mesh_queue",{meshId:b.id}),w=a(v);if((w==null?void 0:w.success)===!1)throw new Error(w.error||"Queue load failed");const j=Array.isArray(((S=w==null?void 0:w.result)==null?void 0:S.rows)??(w==null?void 0:w.rows)??(w==null?void 0:w.queue))?((x=w==null?void 0:w.result)==null?void 0:x.rows)??(w==null?void 0:w.rows)??(w==null?void 0:w.queue):[];p(tR(j))}catch(y){g((y==null?void 0:y.message)||"Queue load failed")}finally{m(!1)}}}return{meshQueue:i,setMeshQueue:c,queueSummary:d,queueLoading:u,queueError:f,loadQueue:k,handleLoadQueue:h}}function nR(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}const mg=new Map;function hg(e){return e?mg.get(e)??null:null}function aR(e,t){!e||!t||mg.set(e,t)}function rR({selectedMeshId:e,loadMeshStatus:t,extractStatus:n,normalizeNode:a,gateIncompleteGraph:r}){const[o,i]=l.useState(()=>hg(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 b(S,x=e,y=!1){if(!(!S||!x))try{d(!y&&o===null),f(y?"settling":"first_paint"),u(null);const C=await t(S,x,{refresh:y,retryProfile:y?"settled":"interactive"});k(nR(C));const v=n(C),w=a&&v?{...v,nodes:(v.nodes??[]).map(j=>a(j,v.meshId??x,""))}:v;if(w){if(r&&!y&&o!==null&&!yM(Pf(w))){f("settling"),h.current||(h.current=!0,Promise.resolve().then(()=>b(S,x,!0)).finally(()=>{h.current=!1}));return}i(w),aR(x,w),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:b}}function cp(e){return!e||e.hostSynthesized?{hostDaemonId:"",hostNodeId:""}:{hostDaemonId:String(e.hostDaemonId||""),hostNodeId:String(e.hostNodeId||"")}}function oR(e,t,n,a,r){if(!e.length)return"";const o=String(r||"");if(o){const d=e.find(p=>en(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=>en(p.id,c));if(d)return d.id}return""}function iR(e){var r;if(!e)return"null";const t=[...e.nodes??[]].map(o=>{var i,c,d,p,u,m;return[o.nodeId,o.health,((i=o.git)==null?void 0:i.branch)??"",((c=o.git)==null?void 0:c.headCommit)??"",(d=o.git)!=null&&d.dirty?"1":"0",((p=o.git)==null?void 0:p.ahead)??0,((u=o.git)==null?void 0:u.behind)??0,(m=o.git)!=null&&m.hasConflicts?"1":"0",[...o.activeSessions??[]].sort().join(",")].join("|")}).sort().join(";"),n=(r=e.queue)==null?void 0:r.summary,a=n?[n.pending,n.assigned,n.completed,n.failed,n.cancelled].join(","):"";return`${t}::${a}`}const lR=4,cR=3e4;function dR(){return{lastFingerprint:null,stableTicks:0,backedOff:!1}}function Pl(e){e.stableTicks=0,e.backedOff=!1}function uR(e,t){const n=iR(t);return e.lastFingerprint===null?(e.lastFingerprint=n,e.backedOff):n!==e.lastFingerprint?(e.lastFingerprint=n,Pl(e),!1):(e.stableTicks+=1,e.stableTicks>=lR&&(e.backedOff=!0),e.backedOff)}function pR(e,t){return e.backedOff?Math.max(t,cR):t}const mR=7e3,hR=45e3;function fR(){const e=UL(),{sendCommand:t,sendData:n,daemons:a,userName:r,loadMeshStatus:o,launchCoordinator:i,loadLiveMesh:c,extractStatus:d,unwrapResult:p,normalizeMesh:u,normalizeNode:m,resolveCommandTarget:f,features:g,gateIncompleteGraph:k}=e,h=da(),b=a[0],S=(b==null?void 0:b.id)||"",x=l.useMemo(()=>((b==null?void 0:b.availableProviders)||[]).filter(lt=>lt.category==="cli").map(lt=>({id:lt.type||lt.id,name:lt.displayName||lt.name||lt.type,meshCoordinator:lt.meshCoordinator})),[b]),y=l.useMemo(()=>cn((b==null?void 0:b.availableProviders)||[]),[b]),{meshes:C,selectedMeshId:v,setSelectedMeshId:w,loading:j,error:N,setError:A,showCreate:T,setShowCreate:I,createName:P,setCreateName:M,createRepoIdentity:E,setCreateRepoIdentity:D,createRepoRemoteUrl:W,setCreateRepoRemoteUrl:R,newMeshDaemonId:B,setNewMeshDaemonId:_,newMeshWorkspace:H,setNewMeshWorkspace:L,createPickerWorkspaces:F,createOnboardingPlan:$,createPlanLoading:K,creating:z,createWarning:ne,setCreateWarning:ie,loadMeshes:Ce,handleCreate:me,handleDelete:O,cancelCreate:Y}=pg({daemons:a,primaryDaemonId:S,sendCommand:t,unwrapResult:p,normalizeMesh:u,features:g,loadDaemonMetadata:h}),X=C.find(Oe=>Oe.id===v)||null,{meshGraphStatus:Q,setMeshGraphStatus:ve,graphLoading:he,graphError:Z,setGraphError:fe,loadGraph:V}=rR({selectedMeshId:v,loadMeshStatus:o,extractStatus:d,normalizeNode:m,gateIncompleteGraph:k}),[q,ee]=l.useState(""),[pe,le]=l.useState(""),se=g.meshHostDaemonSection?q:S,{meshQueue:te,loadQueue:ue}=sR({primaryDaemonId:S,activeDaemonId:se,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:f}),{selectedNodeId:ye,setSelectedNodeId:Me,showAddNode:re,setShowAddNode:ce,nodeWorkspace:Ae,setNodeWorkspace:be,nodeProviderPriority:we,setNodeProviderPriority:_e,nodeDaemonId:U,setNodeDaemonId:Ne,nodeCustomPath:Ie,setNodeCustomPath:We,nodePickerWorkspaces:Xe,nodePickerProviders:et,nodeOnboardingPlan:J,nodePlanLoading:Le,coordinatorCliType:$e,savingPolicy:at,coordinatorPromptDraft:rt,setCoordinatorPromptDraft:G,savingCoordinatorPrompt:oe,nodeSystemPromptDrafts:de,setNodeSystemPromptDrafts:xe,savingNodeSystemPromptId:Se,savingNodeSlotsId:Pe,savingNodeCapabilitiesId:He,handleAddNode:Ee,handleRemoveNode:Je,handleUpdatePolicy:st,handleUpdateNodeSlots:Ze,handleUpdateNodeCapabilities:Ue,handleSaveCoordinatorPrompt:Qe,handleSaveNodeSystemPrompt:nt,settingMeshHost:Be,handleSetMeshHost:ge}=eR({selectedMesh:X,selectedMeshId:v,primaryDaemonId:S,activeDaemonId:se,daemons:a,availableCliProviders:y,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:f,launchCoordinator:i,features:{addNodeDaemonPicker:g.addNodeDaemonPicker},loadMeshes:Ce,loadQueue:ue,queueSection:g.queueSection,setError:A}),je=l.useMemo(()=>a.find(Oe=>Oe.id===se)||b,[a,se,b]),Te=l.useMemo(()=>new Set(((X==null?void 0:X.nodes)||[]).map(Oe=>String(Oe.daemon_id||Oe.daemonId||""))),[X]),Fe=l.useMemo(()=>a.filter(Oe=>Oe.id&&!Te.has(Oe.id)&&!am(Oe)),[a,Te]),Ge=(X==null?void 0:X.nodes)||[],dt=l.useMemo(()=>Ge.find(Oe=>en(String(Oe.daemon_id||Oe.daemonId||""),q)),[Ge,q]),Ve=g.meshHostDaemonSection?!!dt:!0,ut=l.useMemo(()=>{if(!g.meshHostDaemonSection||!X)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const Oe=X.meshHost,lt=Q!=null&&Q.meshId&&String(Q.meshId)===String(X.id??"")?Q.meshHost:void 0,es=lt!=null&<.hostDaemonId?lt:Oe??lt,ns=cp(es),js=ns.hostDaemonId,Qs=Ge.find(Bs=>Bs.role==="host"),dn=ns.hostNodeId||String((Qs==null?void 0:Qs.id)||""),ae=dn?Ge.find(Bs=>String(Bs.id)===dn):void 0,Ke=String((ae==null?void 0:ae.daemon_id)||(ae==null?void 0:ae.daemonId)||""),qe=js||Ke;if(!qe)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const Nt=a.find(Bs=>js&&en(Bs.id,js))||(Ke?a.find(Bs=>en(Bs.id,Ke)):void 0);if(Nt)return{pinned:!0,daemonId:Nt.id,label:gR(Nt),online:!0,hostNode:ae};const un=String((ae==null?void 0:ae.machineLabel)||"")||String((ae==null?void 0:ae.workspace)||"")||qe;return{pinned:!0,daemonId:qe,label:un,online:!1,hostNode:ae}},[X,Ge,a,Q,g.meshHostDaemonSection]),Kt=ut.daemonId,Et=ut.online,ps=ut.pinned?ut.hostNode:dt,Zt=l.useMemo(()=>!g.meshHostDaemonSection||!ut.pinned?"":!Et&&pe&&a.some(Oe=>Oe.id===pe)?pe:Kt,[g.meshHostDaemonSection,ut.pinned,Et,pe,a,Kt]),Hs=l.useMemo(()=>Q?[...new Set((Q.nodes??[]).map(Oe=>String(Oe.daemonId||Oe.daemon_id||"")).filter(Boolean))]:[],[Q]),Re=Xf({status:Q,daemonId:se||null,extraDaemonIds:Hs,meshId:v,sendData:n});l.useEffect(()=>{const Oe=(X==null?void 0:X.coordinator)||{};G({override:typeof Oe.systemPromptOverride=="string"?Oe.systemPromptOverride:"",append:typeof Oe.systemPromptAppend=="string"?Oe.systemPromptAppend:typeof Oe.systemPromptSuffix=="string"?Oe.systemPromptSuffix:""}),xe(Object.fromEntries(((X==null?void 0:X.nodes)||[]).map(lt=>[lt.id,typeof lt.systemPrompt=="string"?lt.systemPrompt:""])))},[X]),l.useEffect(()=>{const Oe=g.addNodeDaemonPicker?Dn(et):Dn(y);re&&we.length===0&&Oe.length>0&&_e(Oe)},[re,y,et,we.length,g.addNodeDaemonPicker]),l.useEffect(()=>{const Oe=new Set(((X==null?void 0:X.nodes)||[]).map(lt=>lt.id));ye&&!Oe.has(ye)&&Me(null)},[X,ye]);const tt=l.useMemo(()=>{if(!(!(Q!=null&&Q.meshId)||String(Q.meshId)!==String((X==null?void 0:X.id)??"")))return cp(Q.meshHost).hostDaemonId||void 0},[Q,X]),It=l.useMemo(()=>oR(a,Ge,se,S,tt),[a,Ge,se,S,tt]);l.useEffect(()=>{if(!g.meshHostDaemonSection)return;if(!a.length&&!ut.pinned){ee("");return}const Oe=ut.pinned?Zt:It;Oe&&!en(Oe,q)&&ee(Oe)},[a,q,ut.pinned,Zt,It,g.meshHostDaemonSection]),l.useEffect(()=>{pe&&(Et||!a.some(Oe=>Oe.id===pe))&&le("")},[Et,pe,a]),l.useEffect(()=>{if(g.createDaemonPicker){if(!a.length){_("");return}(!B||!a.some(Oe=>Oe.id===B))&&_(a[0].id)}},[a,B,g.createDaemonPicker]),l.useEffect(()=>{var Oe;if(!g.createDaemonPicker||!B){L("");return}if(!F.length){L("");return}F.some(lt=>lt.path===H)||L(((Oe=F[0])==null?void 0:Oe.path)||"")},[B,H,F,g.createDaemonPicker]);const pt=l.useRef(null),Yt=l.useRef(dR()),_t=g.meshStatePushRefresh?hR:mR,[Qt,Cs]=l.useState(_t);l.useEffect(()=>{if(!v)return;const Oe=pt.current!==v;if(pt.current=v,Oe){Pl(Yt.current),Cs(_t);const lt=hg(v);ve(lt),fe(null),V(se,v,lt!==null)}else fe(null),V(se,v,!0)},[v,se]);const $s=l.useRef(V);$s.current=V;const ms=l.useRef(!1),ss=l.useRef(()=>{});ss.current=()=>{ms.current||!v||!se||(ms.current=!0,Promise.resolve($s.current(se,v,!0)).finally(()=>{ms.current=!1}))},l.useEffect(()=>{uR(Yt.current,Q),Cs(pR(Yt.current,_t))},[Q,_t]),OL({daemonIds:l.useMemo(()=>[se,...Hs].filter(Boolean),[se,Hs]),meshId:v,sendData:n,onRevisionAdvance:()=>{typeof document<"u"&&document.visibilityState!=="visible"||ss.current()}}),l.useEffect(()=>{if(!v||!se||typeof document>"u")return;let Oe=null;const lt=()=>{document.visibilityState==="visible"&&ss.current()},es=()=>{Oe===null&&(Oe=setInterval(lt,Qt))},ns=()=>{Oe!==null&&(clearInterval(Oe),Oe=null)},js=()=>{document.visibilityState==="visible"?es():ns()};return document.visibilityState==="visible"&&es(),document.addEventListener("visibilitychange",js),()=>{ns(),document.removeEventListener("visibilitychange",js)}},[v,se,Qt]),l.useEffect(()=>{g.queueSection||ue(v)},[v,g.queueSection]);const Ys=l.useMemo(()=>a.map(Oe=>Oe.id).filter(Boolean).sort().join(","),[a]),Fs=l.useRef(!1);return l.useEffect(()=>{Ce(Fs.current),Fs.current=!0},[Ys]),S?X?s.jsx(Z2,{selectedMesh:X,error:N,onDismissError:()=>A(null),onBack:()=>{w(null),ve(null)},onDelete:O,displayedMeshStatus:Re,graphLoading:he,graphError:Z,onRefreshGraph:()=>{Pl(Yt.current),V(se,v,!0)},savingPolicy:at,onUpdatePolicy:st,coordinatorPromptDraft:rt,onCoordinatorPromptDraftChange:G,savingCoordinatorPrompt:oe,onSaveCoordinatorPrompt:Qe,daemons:a,coordinatorDaemonId:q,onCoordinatorDaemonIdChange:ee,coordinatorCliType:$e,isHostNodeAttached:Ve,selectedHostNode:ps,hostPinned:ut.pinned,hostLabel:ut.label,hostOnline:Et,hostRebindDaemonId:pe,onHostRebindDaemonIdChange:Oe=>le(Oe),settingMeshHost:Be,onSetMeshHost:ge,activeDaemon:je,activeDaemonId:se,meshQueue:te,userName:r,availableCliProviders:y,savingNodeSlotsId:Pe,onUpdateNodeSlots:Ze,savingNodeCapabilitiesId:He,onUpdateNodeCapabilities:Ue,nodeSystemPromptDrafts:de,onNodeSystemPromptDraftChange:(Oe,lt)=>xe(es=>({...es,[Oe]:lt})),savingNodeSystemPromptId:Se,onSaveNodeSystemPrompt:nt,selectedNodeId:ye,onSelectNode:Me,showAddNode:re,onShowAddNode:()=>ce(!0),onCancelAddNode:()=>ce(!1),nodeWorkspace:Ae,onNodeWorkspaceChange:be,nodeProviderPriority:we,onNodeProviderPriorityChange:_e,nodeDaemonId:U,onNodeDaemonIdChange:Ne,nodeCustomPath:Ie,onNodeCustomPathChange:We,nodePickerWorkspaces:Xe,nodePickerProviders:et,nodeOnboardingPlan:J,nodePlanLoading:Le,attachableDaemons:Fe,onAddNode:Ee,onRemoveNode:Je,availableCliAgents:x,features:{coordinatorPrompt:g.coordinatorPrompt,meshHostDaemonSection:g.meshHostDaemonSection,hermesMcpConfig:g.hermesMcpConfig,addNodeDaemonPicker:g.addNodeDaemonPicker,nodeInstruction:g.nodeInstruction},sendCommand:t}):s.jsx(JL,{meshes:C,loading:j,error:N,onDismissError:()=>A(null),daemons:a,features:{createDaemonPicker:g.createDaemonPicker,maxMeshes:g.maxMeshes},showCreate:T,onToggleCreate:()=>I(!T),createName:P,onCreateNameChange:M,createRepoIdentity:E,onCreateRepoIdentityChange:D,createRepoRemoteUrl:W,onCreateRepoRemoteUrlChange:R,newMeshDaemonId:B,onNewMeshDaemonIdChange:_,newMeshWorkspace:H,onNewMeshWorkspaceChange:L,createPickerWorkspaces:F,createOnboardingPlan:$,createPlanLoading:K,creating:z,createWarning:ne,onDismissCreateWarning:()=>ie(null),onSelectMesh:w,onCreate:me,onCancelCreate:Y}):s.jsx(Ja,{icon:s.jsx(cs,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})})}function gR(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function bR({children:e}){const{sendCommand:t,sendData:n}=St(),{ides:a}=Ss(),r=l.useMemo(()=>a.filter(i=>i.daemonMode||i.type==="adhdev-daemon").map(i=>i),[a]),o=l.useMemo(()=>({sendCommand:t,sendData:n,daemons:r,userName:void 0,loadMeshStatus:async(i,c)=>t(i,"mesh_status",{meshId:c}),launchCoordinator:async(i,c)=>{var f;const d={meshId:c.meshId};c.cliType&&(d.cliType=c.cliType);const p=await t(i,"launch_mesh_coordinator",d),u=(p==null?void 0:p.result)??p;if((u==null?void 0:u.success)===!1)throw new Error(u.error||"Coordinator launch failed");const m=(u==null?void 0:u.sessionId)||((f=u==null?void 0:u.session)==null?void 0:f.id)||(u==null?void 0:u.targetSessionId);return{sessionId:m,message:m?`Coordinator launched (${m})`:"Coordinator launch command sent"}},loadLiveMesh:void 0,extractStatus:Xl,unwrapResult:i=>i,normalizeMesh:(i,c)=>i,normalizeNode:(i,c,d)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:rg}),[t,n,r]);return s.jsx(og.Provider,{value:o,children:e})}function xR(e){const{daemons:t,features:n,meshes:a,meshesLoading:r,selectedMeshId:o,onSelectMesh:i,createMode:c,onCreateModeChange:d,createName:p,onCreateNameChange:u,createDaemonId:m,onCreateDaemonIdChange:f,createWorkspace:g,onCreateWorkspaceChange:k,createPickerWorkspaces:h,createPlan:b,createPlanLoading:S,creating:x,createWarning:y,onCreate:C,createRepoRemoteUrl:v,onCreateRepoRemoteUrlChange:w,createRepoIdentity:j,onCreateRepoIdentityChange:N,createManualOpen:A,onCreateManualOpenChange:T,nodes:I,attachableDaemons:P,attachDaemonId:M,onAttachDaemonIdChange:E,attachWorkspace:D,onAttachWorkspaceChange:W,attachPickerWorkspaces:R,attachPlan:B,attachPlanLoading:_,attaching:H,onAttach:L,renderInstallOnboarding:F,nodeLabel:$,daemonLabel:K}=e,{t:z}=ke("common");if(t.length===0)return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:z("setupWizard.machines.title")}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-text-muted",children:z("setupWizard.machines.noMachinesDescription")})]}),F?F():s.jsx("p",{className:"text-[11px] text-text-muted",children:z("setupWizard.machines.noMachinesFallback")})]});const ne=H||_||(B==null?void 0:B.success)===!1||!D.trim()||n.addNodeDaemonPicker&&!M;return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:z("setupWizard.machines.title")}),s.jsx("p",{className:"mt-1 text-[11px] leading-relaxed text-text-muted",children:z("setupWizard.machines.description")})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[a.map(ie=>{const Ce=!c&&o===ie.id;return s.jsx("button",{type:"button",onClick:()=>{d(!1),i(ie.id)},className:`flex items-center gap-2 rounded-lg border px-3 py-2 text-left transition-colors ${Ce?"border-accent-primary/60 bg-accent-primary/10":"border-border-subtle bg-bg-secondary/60 hover:border-border-default"}`,children:s.jsxs("span",{className:"min-w-0",children:[s.jsx("span",{className:"block truncate text-sm text-text-primary",children:ie.name}),s.jsxs("span",{className:"block truncate text-[11px] text-text-muted",children:[ie.repoIdentity||ie.repoRemoteUrl||""," · ",z("setupWizard.machines.nodeCount",{count:(ie.nodes||[]).length})]})]})},ie.id)}),s.jsx("button",{type:"button",onClick:()=>d(!0),className:`flex items-center gap-2 rounded-lg border px-3 py-2 text-left transition-colors ${c?"border-accent-primary/60 bg-accent-primary/10":"border-dashed border-border-subtle bg-bg-secondary/40 hover:border-border-default"}`,children:s.jsxs("span",{className:"text-sm text-text-primary",children:["+ ",z("setupWizard.machines.createNew")]})}),r&&a.length===0&&s.jsx("p",{className:"text-[11px] text-text-muted",children:z("setupWizard.machines.loadingMeshes")})]}),c&&s.jsx(cg,{variant:"wizard",showDaemonPicker:n.createDaemonPicker,daemons:t,daemonLabel:K,name:p,onNameChange:u,daemonId:m,onDaemonIdChange:f,workspace:g,onWorkspaceChange:k,workspaces:h,plan:b,planLoading:S,repoRemoteUrl:v,onRepoRemoteUrlChange:w,repoIdentity:j,onRepoIdentityChange:N,manualOpen:A,onManualOpenChange:T,creating:x,warning:y,onCreate:C}),!c&&o&&s.jsxs("div",{className:"flex flex-col gap-2.5 rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2.5",children:[I.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5",children:I.map(ie=>s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] text-text-secondary",children:$(ie)},ie.id))}),s.jsx("span",{className:"text-[11px] font-medium text-text-secondary",children:z("setupWizard.machines.attachTitle")}),n.addNodeDaemonPicker&&(P.length>0?s.jsx("div",{className:"flex flex-wrap gap-1.5",children:P.map(ie=>{const Ce=M===ie.id;return s.jsx("button",{type:"button",onClick:()=>E(ie.id),className:`rounded-full border px-2.5 py-1 text-[11px] transition-colors ${Ce?"border-accent-primary/60 bg-accent-primary/10 text-text-primary":"border-border-subtle bg-bg-secondary text-text-secondary hover:border-border-default"}`,children:K(ie)},ie.id)})}):s.jsx("p",{className:"text-[11px] text-text-muted",children:z("setupWizard.machines.allMachinesAttached")})),(!n.addNodeDaemonPicker||M)&&s.jsxs(s.Fragment,{children:[s.jsx(Cl,{workspaces:R,value:D,onChange:W}),s.jsx(lg,{plan:B,loading:_}),s.jsx("div",{className:"flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:L,disabled:ne,children:z(H?"setupWizard.machines.attaching":"setupWizard.machines.addMachine")})})]})]})]})}function vR(e){var t;return e.machineNickname||e.nickname||e.hostname||((t=e.user)==null?void 0:t.name)||e.id}function yR(e){const t=e;return t.machine_label||t.machineLabel||t.hostname||String(e.workspace||"").split(/[\\/]/).filter(Boolean).pop()||e.id}function wR({daemons:e,features:t,sendCommand:n,unwrapResult:a,normalizeMesh:r,loadDaemonMetadata:o,initialMeshId:i,onClose:c,renderInstallOnboarding:d}){var Ae,be;const{t:p}=ke("common"),u=((Ae=e[0])==null?void 0:Ae.id)||"",{meshes:m,loading:f,error:g,setError:k,loadMeshes:h,selectedMeshId:b,setSelectedMeshId:S}=pg({daemons:e,primaryDaemonId:u,sendCommand:n,unwrapResult:a,normalizeMesh:r,features:{createDaemonPicker:t.createDaemonPicker,addNodeDaemonPicker:t.addNodeDaemonPicker},loadDaemonMetadata:o});l.useEffect(()=>{h()},[h]);const x=l.useRef(m);x.current=m;const y=l.useMemo(()=>m.map(we=>we.id).sort().join(","),[m]),C=l.useRef(n);C.current=n;const v=l.useRef(a);v.current=a,l.useEffect(()=>{b||m.length===0||(i&&m.some(we=>we.id===i)?S(i):m.length===1&&S(m[0].id))},[m,b,i,S]);const w=l.useMemo(()=>m.find(we=>we.id===b)??null,[m,b]),j=l.useMemo(()=>(w==null?void 0:w.nodes)||[],[w]),N=l.useCallback(we=>(we==null?void 0:we.__sourceDaemonId)||u,[u]),[A,T]=l.useState(!1),[I,P]=l.useState(""),[M,E]=l.useState(""),[D,W]=l.useState(""),[R,B]=l.useState(null),[_,H]=l.useState(!1),[L,F]=l.useState(!1),[$,K]=l.useState(null),[z,ne]=l.useState(""),[ie,Ce]=l.useState(""),[me,O]=l.useState(!1),Y=t.createDaemonPicker&&M||u,X=l.useMemo(()=>e.find(we=>we.id===Y),[e,Y]),Q=(X==null?void 0:X.workspaces)||[];l.useEffect(()=>{if(!A||!Y||!D.trim()){B(null),H(!1);return}let we=!1;const _e=setTimeout(()=>{we||(H(!0),C.current(Y,"plan_mesh_onboarding",{workspace:D.trim(),operation:"auto",meshInventory:x.current}).then(U=>{if(we)return;const Ne=v.current(U);B(Ne),Ne!=null&&Ne.success&&(P(Ie=>{var We,Xe;return Ie||`${String(((We=Ne.discovery)==null?void 0:We.repoIdentity)||((Xe=Ne.discovery)==null?void 0:Xe.repoRoot)||"").split(/[\\/]/).filter(Boolean).pop()||"repo"}-mesh`}),Ce(Ie=>{var We;return Ie||((We=Ne.discovery)==null?void 0:We.repoIdentity)||""}),ne(Ie=>{var We,Xe,et,J,Le,$e;return Ie||((et=(Xe=(We=Ne.discovery)==null?void 0:We.origin)==null?void 0:Xe.urls)==null?void 0:et[0])||(($e=(Le=(J=Ne.discovery)==null?void 0:J.upstream)==null?void 0:Le.urls)==null?void 0:$e[0])||""}))}).catch(U=>{we||B({success:!1,error:(U==null?void 0:U.message)||"Git discovery failed"})}).finally(()=>{we||H(!1)}))},300);return()=>{we=!0,clearTimeout(_e)}},[A,Y,D,y]);const ve=l.useCallback(async()=>{const we=Y,_e=D.trim(),U=z.trim(),Ne=ie.trim();if(!(!we||!I.trim()||L)&&!(!_e&&!U&&!Ne)){F(!0),K(null),k(null);try{const Ie=await ug({targetDaemonId:we,name:I,repoRemoteUrl:U,repoIdentity:Ne,workspace:_e,attachWorkspace:!!_e,machineId:X==null?void 0:X.machineId,providerPriority:Dn(cn((X==null?void 0:X.availableProviders)||[])),meshInventory:m,sendCommand:n,unwrapResult:a});if(Ie.warning&&K(Ie.warning),!Ie.meshCreated){k(Ie.error||p("setupWizard.machines.createFailed"));return}await h(!0),Ie.meshId&&S(Ie.meshId),T(!1)}finally{F(!1)}}},[Y,I,D,z,ie,L,X,m,n,a,h,S,k,p]),[he,Z]=l.useState(""),[fe,V]=l.useState(""),[q,ee]=l.useState(null),[pe,le]=l.useState(!1),[se,te]=l.useState(!1),ue=l.useMemo(()=>{if(!t.addNodeDaemonPicker)return[];const we=new Set(j.map(_e=>String(_e.daemon_id||_e.daemonId||"")));return e.filter(_e=>_e.id&&!we.has(_e.id)&&!am(_e))},[t.addNodeDaemonPicker,j,e]),ye=l.useMemo(()=>e.find(we=>we.id===he),[e,he]),Me=t.addNodeDaemonPicker?(ye==null?void 0:ye.workspaces)||[]:((be=e.find(we=>we.id===u))==null?void 0:be.workspaces)||[];l.useEffect(()=>{if(A||!b||!fe.trim()){ee(null);return}const we=t.addNodeDaemonPicker?he:N(w);if(!we)return;let _e=!1;return le(!0),n(we,"plan_mesh_onboarding",{workspace:fe.trim(),meshId:b,inlineMesh:w,operation:"add_existing"}).then(U=>{_e||ee(a(U))}).catch(U=>{_e||ee({success:!1,error:(U==null?void 0:U.message)||"Git discovery failed"})}).finally(()=>{_e||le(!1)}),()=>{_e=!0}},[A,b,w,fe,he,t.addNodeDaemonPicker,N,n,a]);const re=l.useCallback(async()=>{var U,Ne,Ie,We;const we=N(w);if(!b||!we||se)return;const _e=fe.trim();if(_e){te(!0),k(null);try{const Xe=t.addNodeDaemonPicker?he:we,et=await n(Xe,"plan_mesh_onboarding",{workspace:_e,meshId:b,inlineMesh:w,operation:"add_existing"}),J=a(et);if(ee(J),(J==null?void 0:J.success)===!1)throw new Error(`${J.code||"onboarding_blocked"}: ${J.error}${J.action?` ${J.action}`:""}`);const Le={meshId:b,workspace:((U=J==null?void 0:J.discovery)==null?void 0:U.repoRoot)||_e,repoRoot:(Ne=J==null?void 0:J.discovery)==null?void 0:Ne.repoRoot,isLocalWorktree:((Ie=J==null?void 0:J.discovery)==null?void 0:Ie.isLinkedWorktree)===!0};t.addNodeDaemonPicker&&he&&(Le.daemonId=he,Le.machineId=ye==null?void 0:ye.machineId),Le.providerPriority=Dn(cn(((We=t.addNodeDaemonPicker?ye:e[0])==null?void 0:We.availableProviders)||[]));const $e=await n(we,"add_mesh_node",Le),at=a($e);if((at==null?void 0:at.success)===!1)throw new Error(at.error||"Add node failed");V(""),ee(null),await h(!0)}catch(Xe){k((Xe==null?void 0:Xe.message)||"Add node failed")}finally{te(!1)}}},[w,b,fe,he,ye,se,t.addNodeDaemonPicker,N,e,n,a,h,k]),ce=!A&&!!w&&j.length>0;return s.jsxs("div",{className:"mx-auto flex w-full max-w-2xl flex-col gap-4 p-4",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-base font-semibold text-text-primary",children:p("setupWizard.title")}),s.jsx("p",{className:"mt-1.5 text-[11px] text-text-muted",children:p("setupWizard.machines.description")})]}),g&&s.jsx("p",{className:"text-[11px] text-red-400",children:g}),s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary p-4",children:s.jsx(xR,{daemons:e,features:t,meshes:m,meshesLoading:f,selectedMeshId:b,onSelectMesh:we=>{S(we),V(""),Z("")},createMode:A,onCreateModeChange:T,createName:I,onCreateNameChange:P,createDaemonId:M,onCreateDaemonIdChange:E,createWorkspace:D,onCreateWorkspaceChange:W,createPickerWorkspaces:Q,createPlan:R,createPlanLoading:_,creating:L,createWarning:$,onCreate:ve,createRepoRemoteUrl:z,onCreateRepoRemoteUrlChange:ne,createRepoIdentity:ie,onCreateRepoIdentityChange:Ce,createManualOpen:me,onCreateManualOpenChange:O,nodes:j,attachableDaemons:ue,attachDaemonId:he,onAttachDaemonIdChange:we=>{Z(we),V("")},attachWorkspace:fe,onAttachWorkspaceChange:V,attachPickerWorkspaces:Me,attachPlan:q,attachPlanLoading:pe,attaching:se,onAttach:re,renderInstallOnboarding:d,nodeLabel:yR,daemonLabel:vR})}),s.jsx("div",{className:"flex items-center gap-2",children:s.jsx("div",{className:"ml-auto flex items-center gap-2",children:s.jsx("button",{type:"button",className:ce?"btn btn-primary btn-sm":"btn btn-secondary btn-sm",onClick:c,children:p(ce?"setupWizard.continueToMesh":"setupWizard.close")})})})]})}function Ic(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function kR(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=Ic();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 Ms(e,t){return await fetch(kR(e),{credentials:"same-origin",...t})}function fg(){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 SR{constructor(){it(this,"adapters",new Map);it(this,"states",new Map);it(this,"runtimeListeners",new Map);it(this,"screenshotCallbacks",new Map);it(this,"statusCallbacks",new Set);it(this,"stateChangeCallbacks",new Set);it(this,"ptyInputSender",null)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const n of this.adapters.keys())if(n.startsWith("standalone"))return n}return null}register(t,n){this.adapters.set(t,n),this.states.set(t,n.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,n){this.states.set(t,n);const a=this.resolveDaemonId(t)||t;this.stateChangeCallbacks.forEach(r=>r(a,n))}onStateChange(t){return this.stateChangeCallbacks.add(t),()=>{this.stateChangeCallbacks.delete(t)}}retryConnection(t){}get(t){const n=this.resolveDaemonId(t);return n?this.adapters.get(n):void 0}getState(t){const n=this.resolveDaemonId(t);return n&&this.states.get(n)||"disconnected"}registerPtyInputSender(t){this.ptyInputSender=t}sendData(t,n){return!1}sendPtyInput(t,n,a){return this.ptyInputSender?this.ptyInputSender(t,n,a):!1}onScreenshot(t,n){return this.screenshotCallbacks.set(t,n),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,n){this.screenshotCallbacks.forEach(a=>a(t,n))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,n){this.statusCallbacks.forEach(a=>a(t,n))}emitRuntimeSnapshot(t,n,a=0,r=!1,o,i){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:a,text:n,truncated:r,cols:o,rows:i})}emitSessionOutput(t,n,a){!t||typeof n!="string"||!n||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof a=="number"?{seq:a}:{},data:n})}onRuntimeEvent(t,n){const a=this.runtimeListeners.get(t)||new Set;return a.add(n),this.runtimeListeners.set(t,a),()=>{const r=this.runtimeListeners.get(t);r&&(r.delete(n),r.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,n,a){if(!n)return{success:!1,error:"sessionId is required"};const r=new URL(`/api/v1/runtime/${encodeURIComponent(n)}/snapshot`,window.location.origin);typeof(a==null?void 0:a.sinceSeq)=="number"&&r.searchParams.set("sinceSeq",String(a.sinceSeq));const o=await Ms(`${r.pathname}${r.search}`);if(!o.ok){let c=`Runtime snapshot unavailable (${o.status})`;try{const d=await o.json();d!=null&&d.error&&(c=d.error)}catch{}return{success:!1,error:c}}const i=await o.json();return this.emitRuntimeEvent(n,{type:"runtime_snapshot",sessionId:n,seq:typeof i.seq=="number"?i.seq:0,text:typeof i.text=="string"?i.text:"",truncated:!!i.truncated,cols:typeof i.cols=="number"?i.cols:void 0,rows:typeof i.rows=="number"?i.rows:void 0,force:!!(a!=null&&a.force)}),{success:!0}}emitRuntimeEvent(t,n){var a;(a=this.runtimeListeners.get(t))==null||a.forEach(r=>r(n))}}const Ts=new SR;function CR(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,n=Ic();return n?`${t}?token=${encodeURIComponent(n)}`:t}const Cr=CR(),dp=3e3,jR=3e4;let gs=null,NR=0;const lo=new Map;let bn=null,La=null;function up(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function wa(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function AR(e){return e==="connected"?"connected":e}async function Ra(e,t,n){const a=xh(e,n||{}),r=gs;if(r&&r.readyState===WebSocket.OPEN){const o=`req_${++NR}_${Date.now()}`;return new Promise((i,c)=>{const d=setTimeout(()=>{lo.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);lo.set(o,{resolve:p=>{clearTimeout(d),i(p)},reject:p=>{clearTimeout(d),c(p)}}),r.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:a.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function Dl(e,t){const n=gs;if(!n||n.readyState!==WebSocket.OPEN||!t||t.type!=="subscribe"&&t.type!=="unsubscribe")return!1;try{return n.send(JSON.stringify(t)),!0}catch{return!1}}function gg(e,t,n){const a=gs;if(!a||a.readyState!==WebSocket.OPEN)return!1;const r=xh(e,{sessionId:t,targetSessionId:t,data:n});try{return a.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:r.payload}})),!0}catch{return!1}}Ts.registerPtyInputSender(gg);class TR{constructor(t){it(this,"daemonId");it(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(gs==null?void 0:gs.readyState)===WebSocket.OPEN}get connectionState(){return(gs==null?void 0:gs.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,n){return Ra(this.daemonId,t,n)}async sendInput(t,n){return Ra(this.daemonId,"cdp_remote_action",{action:t,params:n,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,bn&&(clearInterval(bn),bn=null);const n=async()=>{if(this.hasCommandChannel)try{const a=await Ra(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(a!=null&&a.success&&(a!=null&&a.base64)){const r=await fetch(`data:image/jpeg;base64,${a.base64}`).then(o=>o.blob());Ts.emitScreenshot(this.daemonId,r)}}catch{}};n(),bn=setInterval(n,2e3)}stopScreenshots(t){bn&&(clearInterval(bn),bn=null)}}let rs=null;function MR(e){return(!rs||rs.daemonId!==e)&&(rs=new TR(e)),rs}function PR({children:e}){const t=l.useRef(Ea()),n=Ea();t.current=n;const{setUserName:a}=Ss(),r=l.useRef(a);r.current=a;const o=l.useRef(null),i=l.useRef(null),[,c]=l.useState("disconnected"),d=l.useCallback((h,b)=>{c(h),La==null||La(h,b)},[]),p=l.useRef(null),u=l.useRef(),m=l.useRef(dp),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 x,y;if(!f.current||((x=p.current)==null?void 0:x.readyState)===WebSocket.OPEN||((y=p.current)==null?void 0:y.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${Cr}...`),wa("connect_attempt",{url:Cr,reason:k.current,delayMs:m.current});let S;try{S=new WebSocket(Cr)}catch(C){console.error("[Standalone WS] Failed to create WebSocket:",C),b();return}p.current=S,S.onopen=()=>{if(!f.current){S.close();return}d("connected"),m.current=dp,wa("open",{url:Cr,reason:k.current}),ys.resubscribeAll({sendData:Dl}),console.log("[Standalone WS] Connected")},gs=S,S.onmessage=C=>{var v,w;try{const j=JSON.parse(C.data);if((j.type==="command_result"||j.type==="error")&&j.requestId){const N=lo.get(j.requestId);N&&(lo.delete(j.requestId),j.type==="error"?N.reject(new Error(((v=j.data)==null?void 0:v.message)||"Command failed")):N.resolve(j.data));return}if(j.type==="session_output"){const N=j.sessionId||j.cliId||j.cliType;N&&Ts.emitSessionOutput(N,typeof j.data=="string"?j.data:"",typeof j.seq=="number"?j.seq:void 0);return}if(j.type==="runtime_snapshot"){Ts.emitRuntimeSnapshot(j.sessionId,typeof j.text=="string"?j.text:"",typeof j.seq=="number"?j.seq:0,!!j.truncated,typeof j.cols=="number"?j.cols:void 0,typeof j.rows=="number"?j.rows:void 0);return}if(j.type==="topic_update"){const N=j.update;N&&ys.publish(N);return}if(j.type==="status"||j.type==="initial_state"){const N=j.data;if(!N)return;const{injectEntries:A,markLoaded:T,getIdes:I}=t.current,P=N.instanceId||"standalone",M=I().find(W=>W.id===P),E=MR(P);Ts.register(P,E),Ts.setState(P,"connected"),d("connected",P),Ts.emitStatus(P,N);const D=Or(N,{daemonId:P,existingDaemon:M,existingEntries:I()});up("ws_status",{type:j.type,daemonId:P,sessions:(N.sessions||[]).map(W=>({id:W.id,parentId:W.parentId,providerType:W.providerType,kind:W.kind,transport:W.transport,unread:W.unread,inboxBucket:W.inboxBucket,lastSeenAt:W.lastSeenAt,lastUpdated:W.lastUpdated,title:W.title})),recentLaunches:(N.recentLaunches||[]).map(W=>({id:W.id,providerType:W.providerType,kind:W.kind,workspace:W.workspace,lastLaunchedAt:W.lastLaunchedAt}))}),up("entries",{daemonId:P,entries:D.filter(W=>W.type!=="adhdev-daemon").map(W=>({id:W.id,type:W.type,unread:W.unread,inboxBucket:W.inboxBucket,lastSeenAt:W.lastSeenAt,lastUpdated:W.lastUpdated,sessionId:W.sessionId}))}),D.length>0&&A(D,{authoritativeDaemonIds:[P]}),T(),i.current!==P&&((w=o.current)==null||w.call(o),i.current=P,o.current=ys.subscribe({sendData:Dl},P,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${P}`,params:{includeSessions:!0}},W=>{if(W.topic!=="daemon.metadata")return;const R=t.current.getIdes(),B=R.find(H=>H.id===P),_=Or(W.status,{daemonId:P,existingDaemon:B,existingEntries:R,timestamp:W.timestamp});_.length>0&&t.current.injectEntries(_,{authoritativeDaemonIds:[P]}),W.userName&&r.current&&r.current(W.userName)}))}}catch(j){console.error("[Standalone WS] Parse error:",j)}},S.onclose=C=>{f.current&&(rs==null||rs.stopScreenshots(),rs&&Ts.setState(rs.daemonId,"disconnected"),d("disconnected"),p.current=null,k.current=`close:${C.code}${C.wasClean?":clean":":unclean"}`,wa("close",{code:C.code,reason:C.reason||"",wasClean:C.wasClean}),b())},S.onerror=C=>{g.current||!f.current||(k.current="error",wa("error",{message:C instanceof Event?"event":String(C),readyState:S.readyState}),console.warn("[Standalone WS] Error, will reconnect:",C))}}function b(){if(!f.current)return;clearTimeout(u.current);const S=m.current;console.log(`[Standalone WS] Reconnecting in ${S}ms...`),wa("schedule_reconnect",{reason:k.current,delayMs:S}),u.current=setTimeout(()=>{m.current=Math.min(m.current*1.5,jR),h()},S)}return h(),()=>{var S;f.current=!1,g.current=!0,(S=o.current)==null||S.call(o),o.current=null,i.current=null,clearTimeout(u.current),p.current&&(p.current.onerror=null,p.current.onclose=null,p.current.close(),p.current=null,gs=null),rs&&(rs.stopScreenshots(),Ts.unregister(rs.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function DR({children:e}){const[t,n]=l.useState("disconnected"),[a,r]=l.useState(null);l.useEffect(()=>(La=(i,c)=>{n(i),c&&r(c)},()=>{La=null}),[]);const o=l.useMemo(()=>{const i=t==="connected",c=AR(t),d={};return a&&(d[a]=c),d.standalone=c,{wsStatus:t,isConnected:i,connectionStates:d,usesP2P:!1}},[t,a]);return s.jsx(rb,{connectionOverrides:o,children:s.jsx(PR,{children:e})})}const bg="adhdev_standalone_font_preferences",An={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Eo=[{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"}],Oa=[{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"}],IR=new Set(Eo.map(e=>e.id)),LR=new Set(Oa.map(e=>e.id));function Ps(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Er("chat",t.chat),code:Er("code",t.code),terminal:Er("terminal",t.terminal)}}function Er(e,t){const n=An[e],a=t&&typeof t=="object"&&!Array.isArray(t)?t:{},r=typeof a.preset=="string"?a.preset.trim():"",o=typeof a.customFamily=="string"?a.customFamily.trim():"";return(e==="chat"?IR:LR).has(r)?r==="custom"?o?{preset:"custom",customFamily:o}:n:{preset:r}:n}function _r(e,t){var r;const n=Er(e,t);if(n.preset==="custom"&&n.customFamily)return n.customFamily;const a=e==="chat"?Eo:Oa;return((r=a.find(o=>o.id===n.preset))==null?void 0:r.family)||a[0].family}function RR(e){const t=Ps(e),n=_r("chat",t.chat),a=_r("code",t.code),r=_r("terminal",t.terminal);return{"--chat-font-family":n,"--chat-code-font-family":a,"--chat-terminal-font-family":r,"--chat-tool-font-family":r}}function vn(e,t=document.documentElement){const n=Ps(e),a=RR(n);t.setAttribute("data-standalone-fonts","custom");for(const[r,o]of Object.entries(a))t.style.setProperty(r,o);return n}function Il(e){const t=Ps(e);try{localStorage.setItem(bg,JSON.stringify(t))}catch{}return t}function ER(){try{const e=localStorage.getItem(bg);if(e)return Ps(JSON.parse(e))}catch{}return An}function _R(){return vn(ER())}function ka(e,t){var a;const n=e==="chat"?Eo:Oa;return((a=n.find(r=>r.id===t))==null?void 0:a.label)||n[0].label}function HR({children:e}){const t=ia(),n=Rl(),{t:a}=ke("common"),r=l.useMemo(()=>[{id:"dashboard",path:"/dashboard",icon:s.jsx(Tp,{}),label:a("nav.dashboard"),active:n.pathname.startsWith("/dashboard"),onSelect:()=>t("/dashboard")},{id:"machine",path:"/machines",icon:s.jsx(nn,{}),label:a("nav.machines"),active:n.pathname.startsWith("/machines"),onSelect:()=>t("/machines")},{id:"mesh",path:"/mesh",icon:s.jsx(cs,{}),label:a("nav.mesh"),active:n.pathname.startsWith("/mesh")||n.pathname.startsWith("/setup"),onSelect:()=>t("/mesh")},{id:"settings",path:"/settings",icon:s.jsx(Ua,{}),label:a("nav.settings"),active:n.pathname.startsWith("/settings"),onSelect:()=>t("/settings")}],[n.pathname,t,a]),o=l.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:a("nav.docs")}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(Mp,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:a("nav.docs")},{id:"about",label:a("nav.about"),icon:s.jsx(uo,{}),active:n.pathname==="/about",onSelect:()=>t("/about"),title:a("nav.about")}],[n.pathname,t,a]);return s.jsx(m1,{brand:({collapsed:i})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&s.jsx("span",{children:"ADHDev"})]}),navItems:r,footerItems:o,footerInfo:({collapsed:i})=>i?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","1.0.57"]}),footerActions:({collapsed:i,toggleCollapsed:c})=>s.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:c,title:a(i?"standalone.layout.expandSidebar":"standalone.layout.collapseSidebar"),children:[s.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&s.jsx("span",{className:"text-xs",children:a("standalone.layout.collapse")})]}),children:e})}function $R(){const e=ia(),{sendCommand:t}=St(),{ides:n}=Ss(),a=l.useMemo(()=>n.filter(r=>r.daemonMode||r.type==="adhdev-daemon").map(r=>r),[n]);return s.jsx(wR,{daemons:a,features:rg,sendCommand:t,unwrapResult:r=>r,normalizeMesh:r=>r,onClose:()=>e("/mesh")})}const FR=[{icon:s.jsx(nn,{size:16}),key:"localFirst"},{icon:s.jsx(Is,{size:16}),key:"chatRelay"},{icon:s.jsx(Fl,{size:16}),key:"screenshots"},{icon:s.jsx(us,{size:16}),key:"remoteControl"},{icon:s.jsx(_a,{size:16}),key:"multiIde"},{icon:s.jsx(Mp,{size:16}),key:"cliAcp"}],BR=[{icon:s.jsx(ho,{size:16}),key:"anywhere"},{icon:s.jsx(Tp,{size:16}),key:"p2pStream"},{icon:s.jsx(la,{size:16}),key:"mobileNotifications"},{icon:s.jsx(fb,{size:16}),key:"restApi"},{icon:s.jsx(bb,{size:16}),key:"enterpriseControls"}],WR=[{key:"chatRelay",selfhost:!0,cloud:!0},{key:"screenshots",selfhost:!0,cloud:!0},{key:"remoteControl",selfhost:!0,cloud:!0},{key:"multiIde",selfhost:!0,cloud:!0},{key:"extensionCli",selfhost:!0,cloud:!0},{key:"anyNetwork",selfhost:!1,cloud:!0},{key:"webrtc",selfhost:!1,cloud:!0},{key:"mobilePush",selfhost:!1,cloud:!0},{key:"restApi",selfhost:!1,cloud:!0},{key:"multiMachineDashboards",selfhost:!1,cloud:!0},{key:"ssoRbacAuditLogs",selfhost:!1,cloud:!0}];function OR(){const{t:e}=ke("common");return s.jsxs(Ja,{icon:s.jsx(uo,{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.57"]}),children:[s.jsx(xt,{children:s.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[s.jsxs("div",{className:"max-w-2xl",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:e("standalone.about.selfHostedEdition")}),s.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:e("standalone.about.headline")}),s.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:e("standalone.about.description")})]}),s.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.docs")}),s.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.github")}),s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.tryCloud")})]})]})}),s.jsx(xt,{title:e("standalone.about.includedSection"),description:e("standalone.about.includedDescription"),children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:FR.map(t=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:t.icon}),e("standalone.about.features."+t.key+".title")]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e("standalone.about.features."+t.key+".desc")})]},t.key))})}),s.jsx(xt,{title:e("standalone.about.inventorySection"),description:e("standalone.about.inventoryDescription"),children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:vh.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:wh.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:yh.map(t=>`${t.icon} ${t.name}`)}].map(t=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[s.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:t.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:t.items.map(n=>s.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:n},n))})]},t.label))})}),s.jsx(xt,{title:e("standalone.about.cloudExtrasSection"),description:e("standalone.about.cloudExtrasDescription"),children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:BR.map(t=>s.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:t.icon}),e("standalone.about.extras."+t.key+".title")]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e("standalone.about.extras."+t.key+".desc")})]},t.key))})}),s.jsx(xt,{title:e("standalone.about.comparisonSection"),description:e("standalone.about.comparisonDescription"),children:s.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:s.jsxs("table",{className:"w-full text-[13px]",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"bg-bg-secondary",children:[s.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:e("standalone.about.featureHeader")}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:e("standalone.about.selfhostHeader")}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:e("standalone.about.cloudHeader")})]})}),s.jsx("tbody",{children:WR.map((t,n)=>s.jsxs("tr",{className:n%2===0?"bg-bg-glass":"bg-transparent",children:[s.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e("standalone.about.comparison."+t.key)}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:t.selfhost?s.jsx("span",{className:"text-emerald-500",children:"✓"}):s.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:s.jsx("span",{className:"text-emerald-500",children:"✓"})})]},t.key))})]})})}),s.jsx(Xa,{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(Nb,{size:14,className:"mr-1"}),e("standalone.about.discord")]})]})})]})}function Fi(e,t,n){return{...e,[t]:n}}function Bi({surface:e,title:t,description:n,value:a,options:r,onChange:o}){const{t:i}=ke("common");return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:n})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(b1,{value:a.preset,onChange:c=>{const d=c.target.value;o(d==="custom"?{preset:"custom",customFamily:a.customFamily||""}:{preset:d})},children:r.map(c=>s.jsx("option",{value:c.id,children:c.label},c.id))}),a.preset==="custom"&&s.jsx(xs,{type:"text",className:"font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:a.customFamily||"",onChange:c=>o({preset:"custom",customFamily:c.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:i("standalone.fonts.resolvedStack")})," ",s.jsx("span",{className:"font-mono break-all",children:_r(e,a)})]})]})]})}function UR({value:e,savedValue:t,saving:n=!1,error:a,notice:r,onChange:o,onSave:i,onResetToSaved:c,onResetToDefaults:d}){const{t:p}=ke("common"),u=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:p("standalone.fonts.fontOverridesNotice")}),a&&s.jsx(Mt,{variant:"error",children:a}),r&&s.jsx(Mt,{variant:"success",children:r}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(Bi,{surface:"chat",title:p("standalone.fonts.chat"),description:p("standalone.fonts.chatDescription"),value:e.chat,options:Eo,onChange:m=>o(Fi(e,"chat",m))}),s.jsx(Bi,{surface:"code",title:p("standalone.fonts.code"),description:p("standalone.fonts.codeDescription"),value:e.code,options:Oa,onChange:m=>o(Fi(e,"code",m))}),s.jsx(Bi,{surface:"terminal",title:p("standalone.fonts.terminal"),description:p("standalone.fonts.terminalDescription"),value:e.terminal,options:Oa,onChange:m=>o(Fi(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: ",ka("chat",e.chat.preset)," · Code: ",ka("code",e.code.preset)," · Terminal: ",ka("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[p("standalone.fonts.defaults")," ",ka("chat",An.chat.preset)," / ",ka("code",An.code.preset)]})]}),s.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:s.jsxs("div",{className:"chat-container-content",children:[s.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:s.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[s.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[s.jsx("span",{className:"chat-sender",children:"Hermes"}),s.jsx("span",{className:"chat-time",children:"now"})]}),s.jsxs("div",{className:"chat-markdown",children:[s.jsxs("p",{children:["Readable prose, ",s.jsx("strong",{children:"bold text"}),", and ",s.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),s.jsx("pre",{children:s.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),s.jsxs("div",{className:"chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"▸"}),s.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),s.jsxs("div",{className:"chat-msg-terminal",children:[s.jsx("div",{className:"chat-msg-header",children:"Terminal"}),s.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx(Gs,{type:"button",variant:"primary",size:"sm",onClick:i,disabled:n||!u,children:p(n?"standalone.fonts.saving":"standalone.fonts.saveFontSettings")}),s.jsx(Gs,{type:"button",variant:"secondary",size:"sm",onClick:c,disabled:n||!u,children:p("standalone.fonts.revertToSaved")}),s.jsx(Gs,{type:"button",variant:"secondary",size:"sm",onClick:d,disabled:n,children:p("standalone.fonts.resetToDefaults")})]})]})}function GR(){const{t:e}=ke("common"),{ides:t}=Ss(),n=t.find(O=>O.type==="adhdev-daemon"),a=(n==null?void 0:n.detectedIdes)||[],{sendCommand:r}=St(),{userName:o}=Ss(),[i,c]=l.useState(o||""),[d,p]=l.useState(null),[u,m]=l.useState(null),[f,g]=l.useState(An),[k,h]=l.useState(!1),[b,S]=l.useState(""),[x,y]=l.useState(""),[C,v]=l.useState("127.0.0.1"),[w,j]=l.useState(""),[N,A]=l.useState(""),[T,I]=l.useState(""),[P,M]=l.useState(""),[E,D]=l.useState(""),[W,R]=l.useState(!1),B=async()=>{const Y=await(await Ms("/auth/session")).json();p(Y)},_=async()=>{const Y=await(await Ms("/api/v1/standalone/preferences")).json();m(Y),v(Y.standaloneBindHost);const X=Ps(Y.standaloneFontPreferences);g(X),vn(X),Il(X)};l.useEffect(()=>{o!==void 0&&c(o)},[o]),l.useEffect(()=>{Promise.all([B(),_()]).catch(O=>{M(O instanceof Error?O.message:String(O))})},[]),l.useEffect(()=>{vn(f)},[f]);const H=O=>{const Y=O.target.value.trim();n!=null&&n.id&&Y!==o&&r(n.id,"set_user_name",{userName:Y}).catch(console.error)},[L,F]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),$=O=>{F(O);try{localStorage.setItem("adhdev_sound",O?"1":"0")}catch{}},K=async()=>{S(""),y(""),h(!0);try{const O=Ps(f),Y=await Ms("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:O})}),X=await Y.json();if(!Y.ok)throw new Error((X==null?void 0:X.error)||"Failed to save standalone font preferences");const Q=Ps(X.standaloneFontPreferences);m(X),g(Q),vn(Q),Il(Q),y(e("standalone.settings.fontsSaved"))}catch(O){S(O instanceof Error?O.message:String(O))}finally{h(!1)}},z=()=>{const O=Ps(u==null?void 0:u.standaloneFontPreferences);S(""),y(""),g(O),vn(O)},ne=()=>{S(""),y(""),g(An),vn(An)},ie=async()=>{M(""),D(""),R(!0);try{const O=await Ms("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:C})}),Y=await O.json();if(!O.ok)throw new Error((Y==null?void 0:Y.error)||"Failed to save standalone network preference");m(Y),v(Y.standaloneBindHost),D(Y.standaloneBindHost==="0.0.0.0"?e("standalone.settings.networkSavedAll"):e("standalone.settings.networkSavedLocal"))}catch(O){M(O instanceof Error?O.message:String(O))}finally{R(!1)}},Ce=async()=>{if(M(""),D(""),N.trim().length<4){M(e("standalone.settings.passwordTooShort"));return}if(N!==T){M(e("standalone.settings.passwordMismatch"));return}R(!0);try{const O=await Ms("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:w,newPassword:N})}),Y=await O.json();if(!O.ok)throw new Error((Y==null?void 0:Y.error)||"Failed to save password");p(Y),await _(),j(""),A(""),I(""),D(d!=null&&d.hasPasswordAuth?e("standalone.settings.passwordUpdated"):e("standalone.settings.passwordEnabled")),fg()}catch(O){M(O instanceof Error?O.message:String(O))}finally{R(!1)}},me=async()=>{M(""),D(""),R(!0);try{const O=await Ms("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:w,clear:!0})}),Y=await O.json();if(!O.ok)throw new Error((Y==null?void 0:Y.error)||"Failed to clear password");p(Y),await _(),j(""),A(""),I(""),D(e("standalone.settings.passwordDisabled"))}catch(O){M(O instanceof Error?O.message:String(O))}finally{R(!1)}};return s.jsxs(Ja,{icon:s.jsx(Ua,{className:"text-text-primary"}),title:e("standalone.settings.title"),subtitle:e("standalone.settings.subtitle"),widthClassName:"max-w-5xl",children:[s.jsx(Mt,{variant:"info",children:e("standalone.settings.infoNotice")}),(d==null?void 0:d.publicHostWarning)&&s.jsx(Mt,{variant:"warning",children:e("standalone.settings.publicHostWarning")}),s.jsx(xt,{title:e("standalone.settings.daemonSection"),description:e("standalone.settings.daemonDescription"),children:s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.versionLabel")}),s.jsxs("span",{className:"font-mono text-xs text-text-primary",children:["v","1.0.57"]})]}),s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.statusLabel")}),s.jsx("span",{className:`text-xs font-medium ${n?"text-green-400":"text-yellow-400"}`,children:e(n?"standalone.settings.statusRunning":"standalone.settings.statusNotConnected")})]}),s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.currentBindLabel")}),s.jsx("span",{className:"font-mono text-xs text-text-primary",children:(u==null?void 0:u.currentBindHost)||(d==null?void 0:d.boundHost)||"127.0.0.1"})]}),s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.defaultBindLabel")}),s.jsx("span",{className:"font-mono text-xs text-text-primary",children:(u==null?void 0:u.standaloneBindHost)||"127.0.0.1"})]}),s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsx("span",{className:"text-sm text-text-muted",children:e("standalone.settings.authLabel")}),s.jsx("span",{className:"text-xs text-text-primary",children:d!=null&&d.hasPasswordAuth?e("standalone.settings.authPassword"):d!=null&&d.hasTokenAuth?e("standalone.settings.authToken"):e("standalone.settings.authNone")})]})]})}),s.jsx(xt,{title:e("standalone.settings.networkSection"),description:e("standalone.settings.networkDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:e("standalone.settings.networkHint")}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:C==="127.0.0.1",onChange:()=>v("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:e("standalone.settings.localhostLabel")}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:e("standalone.settings.localhostHint")})]})]}),s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:C==="0.0.0.0",onChange:()=>v("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:e("standalone.settings.allInterfacesLabel")}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:e("standalone.settings.allInterfacesHint")})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx(Gs,{type:"button",variant:"primary",size:"sm",onClick:()=>{ie()},disabled:W,children:e(W?"standalone.settings.saving":"standalone.settings.saveNetworkMode")}),s.jsx("span",{className:"text-xs text-text-muted",children:e("standalone.settings.networkRestartHint",{host:(u==null?void 0:u.currentBindHost)||(d==null?void 0:d.boundHost)||"127.0.0.1"})})]})]})}),s.jsx(xt,{title:e("standalone.settings.securitySection"),description:e("standalone.settings.securityDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:d!=null&&d.hasPasswordAuth?e("standalone.settings.passwordSet"):e("standalone.settings.passwordNotSet")}),P&&s.jsx(Mt,{variant:"error",children:P}),E&&s.jsx(Mt,{variant:"success",children:E}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx(xs,{type:"password",placeholder:d!=null&&d.hasPasswordAuth?e("standalone.settings.currentPasswordPlaceholder"):e("standalone.settings.currentPasswordFirstTimePlaceholder"),value:w,onChange:O=>j(O.target.value)}),s.jsx(xs,{type:"password",placeholder:d!=null&&d.hasPasswordAuth?e("standalone.settings.newPasswordPlaceholder"):e("standalone.settings.newPasswordFirstTimePlaceholder"),value:N,onChange:O=>A(O.target.value)}),s.jsx(xs,{type:"password",className:"md:col-span-2",placeholder:e("standalone.settings.confirmPasswordPlaceholder"),value:T,onChange:O=>I(O.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Gs,{type:"button",variant:"primary",size:"sm",onClick:()=>{Ce()},disabled:W,children:W?e("standalone.settings.saving"):d!=null&&d.hasPasswordAuth?e("standalone.settings.updatePassword"):e("standalone.settings.enablePassword")}),(d==null?void 0:d.hasPasswordAuth)&&s.jsx(Gs,{type:"button",variant:"danger",size:"sm",onClick:()=>{me()},disabled:W,children:e("standalone.settings.disablePassword")})]})]})}),s.jsx(xt,{title:e("standalone.settings.detectedIdesSection"),description:e("standalone.settings.detectedIdesDescription"),children:a.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:e("standalone.settings.noIdesDetected")}):s.jsx("div",{className:"flex flex-col gap-2",children:a.map(O=>s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-3 bg-bg-glass rounded-xl border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${O.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium text-text-primary",children:O.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:O.type})]},O.type))})}),s.jsx(xt,{title:e("standalone.settings.machineSection"),description:e("standalone.settings.machineDescription"),children:s.jsx(A1,{ides:t,emptyMessage:e("standalone.settings.daemonNotConnected")})}),s.jsx(xt,{title:e("standalone.settings.appearanceSection"),description:e("standalone.settings.appearanceDescription"),children:s.jsx(q1,{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(UR,{value:f,savedValue:Ps(u==null?void 0:u.standaloneFontPreferences),saving:k,error:b,notice:x,onChange:g,onSave:()=>{K()},onResetToSaved:z,onResetToDefaults:ne})]})})}),s.jsx(xt,{title:e("standalone.settings.notificationsSection"),description:e("standalone.settings.notificationsDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(k1,{}),s.jsx(xn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(jb,{size:15})," ",e("standalone.settings.soundEffectsLabel")]}),description:e("standalone.settings.soundEffectsDescription"),checked:L,onChange:$})]})}),s.jsx(xt,{title:e("standalone.settings.profileSection"),description:e("standalone.settings.profileDescription"),children:s.jsx("div",{className:"flex flex-col gap-3",children:s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[s.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[s.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[s.jsx(hb,{size:16,className:"text-text-secondary"})," ",e("standalone.settings.displayNameLabel")]}),s.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:e("standalone.settings.displayNameHint")})]}),s.jsx(xs,{type:"text",className:"w-48 text-right",placeholder:e("standalone.settings.displayNamePlaceholder"),value:i,onChange:O=>c(O.target.value),onBlur:H,onKeyDown:O=>{O.key==="Enter"&&O.currentTarget.blur()}})]})})})]})}const qR=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],Na="adhdev_onboarding_done",zR=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],KR={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function VR({onDone:e}){const{t}=ke("common"),[n,a]=l.useState([]),[r,o]=l.useState(new Set(qR)),[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 w=!1;return fetch("https://api.adhf.dev/api/v1/registry/providers?sort=popular&limit=100").then(async N=>{if(!N.ok)throw new Error(`HTTP ${N.status}`);const A=await N.text();try{return JSON.parse(A)}catch{throw new Error(`unexpected non-JSON response (${N.headers.get("content-type")??"unknown content type"})`)}}).then(N=>{w||a(N.providers??[])}).catch(N=>{w||p(N instanceof Error?N.message:String(N))}).finally(()=>{w||c(!1)}),()=>{w=!0}},[]);const b=n.filter(w=>k==="all"||w.category===k),S=["cli","ide","extension","acp"].map(w=>({category:w,items:b.filter(j=>j.category===w)})).filter(w=>w.items.length>0),x=l.useCallback(w=>{o(j=>{const N=new Set(j);return N.has(w)?N.delete(w):N.add(w),N})},[]),y=l.useCallback(async()=>{if(r.size===0){localStorage.setItem(Na,"1"),e();return}m(!0);const w=[];for(const j of r)try{const A=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:j})})).json().catch(()=>({}));w.push({type:j,ok:!!A.success,error:A.error})}catch(N){w.push({type:j,ok:!1,error:N instanceof Error?N.message:String(N)})}g(w),m(!1),w.every(j=>j.ok)&&localStorage.setItem(Na,"1")},[r,e]),C=l.useCallback(()=>{localStorage.setItem(Na,"1"),e()},[e]),v=l.useCallback(()=>{f&&f.every(w=>w.ok)?e():u||C()},[f,u,e,C]);return s.jsx(Cm,{open:!0,onClose:v,size:"lg",contentClassName:"max-w-2xl",title:t("standalone.onboarding.title"),footer:s.jsxs("div",{className:"flex w-full items-center gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:t(r.size!==1?"standalone.onboarding.selectedCount_other":"standalone.onboarding.selectedCount_one",{count:r.size})}),s.jsxs("div",{className:"ml-auto flex gap-2",children:[s.jsx(Gs,{variant:"secondary",size:"sm",onClick:C,disabled:u,children:t("standalone.onboarding.skip")}),s.jsx(Gs,{variant:"primary",size:"sm",onClick:()=>{f?(localStorage.setItem(Na,"1"),e()):y()},disabled:u||!f&&r.size===0,children:u?t("standalone.onboarding.installing"):f?t("standalone.onboarding.done"):t("standalone.onboarding.installCount",{count:r.size})})]})]}),children:s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsx("div",{className:"text-[12px] text-text-muted",children:t("standalone.onboarding.intro")}),!i&&!d&&n.length>0&&s.jsx("div",{className:"flex gap-1 flex-wrap border-b border-border-subtle pb-2",children:zR.map(w=>{const j=w.key==="all"?n.length:n.filter(N=>N.category===w.key).length;return j===0&&w.key!=="all"?null:s.jsxs("button",{onClick:()=>h(w.key),className:`machine-btn text-[10px] px-2 py-0.5 ${k===w.key?"bg-accent-primary/12 border-accent-primary/40 text-accent-primary":""}`,children:[w.label," ",s.jsxs("span",{className:"opacity-60",children:["(",j,")"]})]},w.key)})}),i&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.loadingRegistry")}),!i&&d&&s.jsx(Mt,{variant:"error",children:t("standalone.onboarding.loadError",{error:d})}),!i&&!d&&b.length===0&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.noProviders")}),!i&&!d&&b.length>0&&s.jsx("div",{className:"flex flex-col gap-4",children:S.map(w=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:KR[w.category]??w.category}),s.jsx("div",{className:"grid gap-1.5",children:w.items.map(j=>{var I;const N=r.has(j.type),A=f==null?void 0:f.find(P=>P.type===j.type),T=((I=j.manifest)==null?void 0:I.details)??"";return s.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${N?"bg-accent-primary/[0.06] border-accent-primary/30":"bg-bg-glass border-border-subtle hover:bg-bg-glass-hover"}`,children:[s.jsx("input",{type:"checkbox",checked:N,onChange:()=>x(j.type),disabled:u,className:"shrink-0"}),s.jsx(Qa,{type:j.type,label:j.displayName??j.type,size:18,className:"shrink-0"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[13px] font-medium text-text-primary truncate",children:j.displayName}),T&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:T})]}),A&&s.jsx("span",{className:`text-[10px] font-semibold ${A.ok?"text-status-online":"text-status-error"}`,children:A.ok?t("standalone.onboarding.installed"):t("standalone.onboarding.installFailed",{error:A.error??"failed"})})]},j.type)})})]},w.category))})]})})}function YR(){try{return localStorage.getItem(Na)==="1"}catch{return!1}}s1();H1();T0();_R();const QR=jp({baseUrl:"",getToken:Ic});function JR({children:e}){const{t}=ke("common"),[n,a]=l.useState(null),[r,o]=l.useState(!0),[i,c]=l.useState(""),[d,p]=l.useState(""),[u,m]=l.useState(!1),f=async()=>{o(!0),p("");try{const h=await(await Ms("/auth/session")).json();a(h)}catch(k){p(k instanceof Error?k.message:String(k))}finally{o(!1)}};l.useEffect(()=>{f()},[]),l.useEffect(()=>{if(!n||n.required&&!n.authenticated)return;let k=!1;return(async()=>{try{const h=await Ms("/api/v1/standalone/preferences");if(!h.ok)return;const b=await h.json();if(k)return;const S=Ps(b.standaloneFontPreferences);vn(S),Il(S)}catch{}})(),()=>{k=!0}},[n==null?void 0:n.authenticated,n==null?void 0:n.required]);const g=async k=>{k.preventDefault(),m(!0),p("");try{const h=await Ms("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),b=await h.json();if(!h.ok)throw new Error((b==null?void 0:b.error)||"Login failed");a(b),c(""),fg()}catch(h){p(h instanceof Error?h.message:String(h))}finally{m(!1)}};return r?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:t("standalone.auth.loading")}):n?!n.required||n.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:t("standalone.auth.signInTitle")}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:n.hasPasswordAuth?t("standalone.auth.passwordProtected"):t("standalone.auth.tokenProtected")})]}),n.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:g,children:[s.jsx(xs,{type:"password",value:i,onChange:k=>c(k.target.value),placeholder:t("standalone.auth.passwordPlaceholder"),autoFocus:!0}),s.jsx(Gs,{type:"submit",variant:"primary",disabled:u||!i,className:"justify-center",children:t(u?"standalone.auth.signingIn":"standalone.auth.unlock")})]}):s.jsx(Mt,{variant:"warning",children:t("standalone.auth.noPasswordEnabled")}),d&&s.jsx(Mt,{variant:"error",children:d})]})}):s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:t("standalone.auth.loadError",{error:d||"unknown error"})})}function pp(){const{t:e}=ke("common"),{ides:t,initialLoaded:n}=Ss();if(!n)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:e("standalone.machine.loading")});const a=t.find(r=>r.daemonMode||r.type==="adhdev-daemon");return a?s.jsx(Ui,{to:`/machines/${a.id}`,replace:!0}):s.jsx(Ui,{to:"/dashboard",replace:!0})}function XR(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let n=!1;if(!YR())return fetch("/api/v1/providers/installed").then(a=>a.ok?a.json():{providers:[]}).then(a=>{n||(a.providers??[]).length===0&&t(!0)}).catch(()=>{}),()=>{n=!0}},[]),e?s.jsx(VR,{onDone:()=>t(!1)}):null}function ZR(){const{t:e}=ke("common"),{ides:t}=Ss(),n=l.useMemo(()=>{for(const u of t)if(u.activeInteractivePrompt)return u.instanceId??u.id;return null},[t]),{promptSession:a,hasActivePrompt:r,responseError:o,isSubmitting:i,submit:c,cancel:d,reopen:p}=Dh(n);return r?s.jsxs("div",{className:"relative",children:[!a&&s.jsx("button",{type:"button",onClick:p,className:"fixed bottom-4 right-4 z-[79] btn btn-primary btn-sm shadow-lg",children:e("standalone.machine.awaitingInput")}),s.jsx(Xp,{promptSession:a,isSubmitting:i,error:o,onSubmit:c,onCancel:d})]}):null}function eE(){const e=l.useMemo(()=>({sendCommand:Ra,sendData:Dl,sendPtyInput:gg}),[]);return s.jsx(Og,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(lb,{client:QR,children:s.jsx(JR,{children:s.jsx(DR,{children:s.jsx(db,{value:e,children:s.jsxs(Hb,{sendDaemonCommand:Ra,children:[s.jsx(ZR,{}),s.jsxs(HR,{children:[s.jsx(XR,{}),s.jsxs(Ug,{children:[s.jsx(Ws,{path:"/dashboard",element:s.jsx(TI,{})}),s.jsx(Ws,{path:"/machine",element:s.jsx(pp,{})}),s.jsx(Ws,{path:"/machines/:id",element:s.jsx(WL,{})}),s.jsx(Ws,{path:"/machines",element:s.jsx(pp,{})}),s.jsx(Ws,{path:"/about",element:s.jsx(OR,{})}),s.jsx(Ws,{path:"/settings",element:s.jsx(GR,{})}),s.jsx(Ws,{path:"/mesh",element:s.jsx(bR,{children:s.jsx(fR,{})})}),s.jsx(Ws,{path:"/setup",element:s.jsx($R,{})}),s.jsx(Ws,{path:"*",element:s.jsx(Ui,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}UC({connectionManager:Ts});Gg(document.getElementById("root")).render(s.jsx(eE,{}));
|