@adhdev/daemon-standalone 1.0.42-rc.2 → 1.0.42
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-AzE_9AKX.js → index-B0peupbj.js} +5 -5
- package/public/index.html +1 -1
- package/vendor/mcp-server/index.js +1 -1
- package/vendor/mcp-server/index.js.map +1 -1
- package/vendor/mcp-server/package.json +1 -1
- package/vendor/session-host-daemon/index.js +0 -0
- package/vendor/session-host-daemon/index.mjs +0 -0
|
@@ -55,7 +55,7 @@ ${JSON.stringify(t,null,2)}
|
|
|
55
55
|
`),Z=((Ne=se[0])==null?void 0:Ne.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:()=>U(B),children:[s.jsx("span",{className:"text-[10px] text-text-muted w-3",children:Y?"▾":"▸"}),s.jsx("span",{className:"font-mono text-accent-primary w-20 shrink-0 text-[11px]",children:B}),!Y&&s.jsx("span",{className:"text-text-secondary truncate font-mono text-[11px]",children:Z}),s.jsxs("span",{className:"ml-auto text-text-muted text-[10px] shrink-0",children:[se.length,"L"]})]}),Y&&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:O||"(empty)"})]},B)})})]}),s.jsx(Ya,{}),z.nativeSource&&s.jsxs("div",{children:[s.jsx(Nn,{children:"State History"}),s.jsx("div",{className:"text-text-muted text-[11px] italic px-1",children:"N/A (native-source provider — no state-machine rules)"})]}),!z.nativeSource&&z.stateHistory&&z.stateHistory.length>0&&s.jsxs("div",{children:[s.jsxs(Nn,{children:["State History (",z.stateHistory.length,")"]}),s.jsx("div",{className:"space-y-px",children:[...z.stateHistory].reverse().slice(0,20).map((B,O)=>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 ${Io(B.stateId)}`,children:B.stateId}),s.jsx("span",{className:"text-text-secondary text-[11px] shrink-0 tabular-nums",children:ra(B.at)}),B.durationMs>0&&s.jsxs("span",{className:"text-text-muted text-[11px]",children:["held ",s.jsx("span",{className:"text-text-secondary",children:ed(B.durationMs)})]}),B.reason&&s.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-mono shrink-0 ${OS[String(B.reason)]??"text-text-secondary bg-bg-glass border border-border-default"}`,children:String(B.reason)}),B.debounceKind&&String(B.debounceKind)!=="none"&&s.jsxs("span",{className:"text-text-muted text-[10px] font-mono",children:["debounce:",String(B.debounceKind)]}),B.matchedStateId&&String(B.matchedStateId)!==B.stateId&&s.jsxs("span",{className:"text-text-muted text-[10px] font-mono",children:["eval→",s.jsx("span",{className:"text-text-secondary",children:String(B.matchedStateId)})]})]}),B.matchedRules&&B.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:[B.matchedRules.slice(0,3).map((Y,se)=>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 Y=="string"?Y:JSON.stringify(Y)},se)),B.matchedRules.length>3&&s.jsxs("span",{className:"text-[10px] text-text-muted",children:["+",B.matchedRules.length-3," more"]})]})]},O))})]}),s.jsx(Ya,{}),(()=>{const B=z.messages??z.committedMessages??[];if(B.length===0)return null;const O=B.filter(Z=>Z.role==="user").length,Y=B.filter(Z=>Z.role==="assistant").length,se=[...B].reverse().find(Z=>Z.role==="assistant");return s.jsxs("div",{children:[s.jsxs(Nn,{children:["Transcript (",B.length," — ",O,"u / ",Y,"a)"]}),se&&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 ",se.receivedAt?ra(se.receivedAt):""]}),s.jsxs("div",{className:"text-text-secondary font-mono whitespace-pre-wrap line-clamp-4 break-all",children:[se.content.slice(0,400),se.content.length>400?"…":""]})]})]})})(),z.specPath&&s.jsx("div",{className:"text-[10px] text-text-muted font-mono truncate border-t border-border-default pt-2 mt-1",title:z.specPath,children:z.specPath}),s.jsxs("div",{children:[s.jsxs("button",{type:"button",className:"text-[11px] text-text-secondary hover:text-text-primary transition-colors flex items-center gap-1.5",onClick:()=>d(B=>!B),children:[s.jsx("span",{className:"text-text-muted",children:p?"▾":"▸"}),s.jsxs("span",{children:["Raw screen (",z.screen?z.screen.split(`
|
|
56
56
|
`).length:0," lines)"]})]}),p&&s.jsx("pre",{className:"mt-1.5 px-3 py-2 font-mono text-[11px] text-text-secondary whitespace-pre bg-bg-secondary rounded-md border border-border-default max-h-64 overflow-auto",children:z.screen||"(empty)"})]})]})]})]})})})}function zS({activeConv:e,clearToken:t=0,terminalRef:n,handleSendChat:a,isSendingChat:r=!1,sendFeedbackMessage:o=null,isVisible:i=!0,isInputActive:c=!0}){var We;const{t:u}=Ce("common");Ms();const{sendPtyInput:p}=kt(),[d,m]=l.useState(!1),h=l.useRef(!1);h.current=d;const[g,k]=l.useState("Runtime terminal unavailable"),[f,x]=l.useState(!1),[w,b]=l.useState(null),[S,N]=l.useState(!1),[v,y]=l.useState(!1),[j,C]=l.useState(1),[A,T]=l.useState(!1),[D,I]=l.useState(!1),[M,P]=l.useState(!1),[$,L]=l.useState(!1),[R,F]=l.useState(!1),[E,H]=l.useState({width:0,height:0}),[_,G]=l.useState({width:0,height:0}),[W,K]=l.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[V,te]=l.useState(null),le=l.useRef(null),de=l.useRef(null),ee=l.useRef(!1),z=l.useRef(!1),X=l.useRef(i),U=l.useRef(0),Q=l.useRef(!1),ke=l.useRef(""),ve=l.useRef(null),ge=l.useRef(!1),me=l.useRef(!1),B=l.useRef(null),O=l.useRef(null),Y=l.useRef(null),se=32*1024,Z=()=>{var ue,we,Se,Be;return((we=(ue=le.current)==null?void 0:ue.ownerDocument)==null?void 0:we.defaultView)||((Be=(Se=de.current)==null?void 0:Se.ownerDocument)==null?void 0:Be.defaultView)||window},Ne=ue=>{const we=Z();return{ownerWindow:we,frameId:we.requestAnimationFrame(ue)}},pe=()=>{const ue=B.current;if(ue){try{ue.ownerWindow.cancelAnimationFrame(ue.frameId)}catch{}B.current=null}},fe=()=>{const ue=O.current;if(ue){try{ue.ownerWindow.clearTimeout(ue.timeoutId)}catch{}O.current=null}},Me=()=>{const ue=Y.current;if(ue){try{ue.ownerWindow.clearTimeout(ue.timeoutId)}catch{}Y.current=null}},Ee=()=>{i&&B.current===null&&(B.current=Ne(()=>{ne()}))},q=e.tabKey,oe=e.sessionId||"",Ie=e.daemonId||((We=e.routeId)==null?void 0:We.split(":")[0])||e.routeId||"",xe=Sl(e),he=d?xe?Ep:o:g,Ze=d&&o||null,Ae=SS,_e=CS,ie=.05,je=()=>{const ue=_.width,we=_.height;if(!Number.isFinite(E.width)||E.width<=0||!Number.isFinite(E.height)||E.height<=0||!Number.isFinite(ue)||ue<=0||!Number.isFinite(we)||we<=0)return 1;const Se=E.width/ue,Be=E.height/we;return Number(Math.min(_e,Math.max(Ae,Math.min(Se,Be))).toFixed(2))},De=je(),qe=ee.current&&j>De,ye=Number.isFinite(_.width)&&_.width>0?Math.max(E.width,Math.round(_.width*j)):E.width,Fe=Number.isFinite(_.height)&&_.height>0?Math.max(E.height,Math.round(_.height*j)):E.height,ut=()=>{Ne(()=>{const ue=de.current;ue&&(ue.scrollLeft=0,ue.scrollTop=ue.scrollHeight-ue.clientHeight)})},it=()=>{var ue,we;U.current=0,Q.current=!1,ke.current="",ve.current=null,ge.current=!1,me.current=!1,ee.current||(z.current=!1,C(1)),B.current!==null&&pe(),m(!1),k("Runtime terminal unavailable"),Me(),fe(),b(null),te(null),T(!1),x(!1),N(!1),y(!1),(we=(ue=n.current)==null?void 0:ue.reset)==null||we.call(ue)},mt=()=>{var ue,we;U.current=0,Q.current=!1,ke.current="",ve.current=null,ge.current=!1,me.current=!1,B.current!==null&&pe(),m(!0),k(""),Me(),fe(),b(null),te(null),T(!1),x(!1),N(!1),y(!1),(we=(ue=n.current)==null?void 0:ue.reset)==null||we.call(ue)},J=()=>{me.current&&(me.current=!1,Ne(()=>{var ue,we;(we=(ue=n.current)==null?void 0:ue.scrollToTop)==null||we.call(ue)}))},ne=()=>{if(B.current=null,!i)return;const ue=ke.current;if(!ue)return;const we=ue.slice(0,se);ke.current=ue.slice(we.length);const Se=n.current;if(!Se){ke.current=we+ke.current,Ee();return}Se.write(we,()=>{if(ke.current.length>0){Ee();return}J()})},ce=ue=>{ue&&(ke.current+=ue,Ee())},be=(ue,we=0,Se,Be,Xe={})=>{var Ve,yt,Gt,At;const lt=!!Xe.force;!lt&&we>0&&U.current>=we||!lt&&we===0&&Q.current||(U.current=we,we>0&&N(!0),m(!0),k(""),typeof Se=="number"&&typeof Be=="number"&&Se>0&&Be>0&&((yt=(Ve=n.current)==null?void 0:Ve.resize)==null||yt.call(Ve,Se,Be)),ke.current="",(At=(Gt=n.current)==null?void 0:Gt.reset)==null||At.call(Gt),ue?ce(ue):J())};l.useEffect(()=>{it()},[oe]),l.useEffect(()=>{var we;if(!oe)return;const ue=((we=Ct.onRuntimeEvent)==null?void 0:we.call(Ct,oe,Se=>{if(!(!Se||Se.sessionId!==oe)){if(Se.type==="runtime_snapshot"){if(!i){ve.current={text:Se.text||"",seq:Se.seq||0,cols:Se.cols,rows:Se.rows,force:!!Se.force};return}be(Se.text||"",Se.seq||0,Se.cols,Se.rows,{force:!!Se.force});return}if(Se.type==="session_output"){Q.current=!0,typeof Se.seq=="number"&&(U.current=Math.max(U.current,Se.seq),Se.seq>0&&N(!0)),h.current||m(!0),h.current||k(""),typeof Se.data=="string"&&ce(Se.data);return}if(Se.type==="session_cleared"){if(!i){ge.current=!0,ke.current="",ve.current=null;return}mt();return}if(Se.type==="session_io_error"){const Be=typeof Se.error=="string"&&Se.error?Se.error:typeof Se.reason=="string"&&Se.reason?Se.reason:"unknown error";m(!1),k(`Runtime input failed: ${Be}`);return}}},Ie))||(()=>{});return()=>{ue()}},[Ie,oe,n,i]);const re=async(ue={})=>{var we;if(!Ie||!oe)return{success:!1,error:"daemonId and sessionId are required"};ue.preserveStatus||k(ue.loadingMessage||"Loading runtime terminal...");try{const Se=await((we=Ct.requestRuntimeSnapshot)==null?void 0:we.call(Ct,Ie,oe,{sinceSeq:ue.sinceSeq,force:ue.force}));return Se&&Se.success===!1?(ue.preserveStatus||(m(!1),k(`Runtime terminal unavailable: ${Se.error}`)),Se):Se||{success:!0}}catch(Se){const Be=(Se==null?void 0:Se.message)||String(Se);return ue.preserveStatus||(m(!1),k(`Runtime terminal unavailable: ${Be}`)),{success:!1,error:Be}}},Te=async ue=>{var lt,Ve;const we=((lt=le.current)==null?void 0:lt.ownerDocument)||document,Se=we.defaultView||window,Be=(Ve=Se.navigator)==null?void 0:Ve.clipboard;if(Be!=null&&Be.writeText&&Se.isSecureContext)try{return await Be.writeText(ue),!0}catch{}let Xe=null;try{return Xe=we.createElement("textarea"),Xe.value=ue,Xe.setAttribute("readonly","true"),Xe.style.position="fixed",Xe.style.left="-9999px",Xe.style.top="0",we.body.appendChild(Xe),Xe.focus(),Xe.select(),we.execCommand("copy")}catch{return!1}finally{Xe==null||Xe.remove()}},He=ue=>{fe(),te(ue);const we=Z();O.current={ownerWindow:we,timeoutId:we.setTimeout(()=>{O.current=null,te(Se=>Se===ue?null:Se)},2200)}},Pe=ue=>{Me(),b(ue);const we=Z();Y.current={ownerWindow:we,timeoutId:we.setTimeout(()=>{Y.current=null,b(Se=>Se===ue?null:Se)},2200)}},Ge=async()=>{var Xe,lt,Ve,yt;const ue=((lt=(Xe=n.current)==null?void 0:Xe.getSelection)==null?void 0:lt.call(Xe))||"",we=((yt=(Ve=n.current)==null?void 0:Ve.getVisibleText)==null?void 0:yt.call(Ve))||"",Se=ue.trimEnd()||we.trimEnd();if(!Se){He("Nothing to copy");return}if(!await Te(Se)){He("Copy failed");return}He(ue.trimEnd()?"Copied selection":"Copied visible terminal")},ze=ue=>{if(!d||!i)return;((p==null?void 0:p(Ie,oe,ue))??!1)||He("Terminal input failed")},Je=ue=>{ze(NS({ctrl:D,alt:M,shift:$},ue)),I(!1),P(!1),L(!1)},Ue=async()=>{if(f)return;x(!0),b("Loading older terminal output..."),me.current=!0;const ue=await re({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:d});if(x(!1),(ue==null?void 0:ue.success)===!1){me.current=!1,b(`Older terminal output unavailable: ${ue.error}`);return}y(!0),Pe("Older terminal output loaded"),Ne(()=>{var we;(we=n.current)==null||we.bumpResize()})};l.useEffect(()=>{var we,Se;if(!oe)return;Ie&&((we=Ct.getState)==null?void 0:we.call(Ct,Ie))==="connected"&&re();const ue=(Se=Ct.onStateChange)==null?void 0:Se.call(Ct,(Be,Xe)=>{Be!==Ie||Xe!=="connected"||re()});return()=>{ue==null||ue()}},[Ie,oe,n]),l.useEffect(()=>{t&&it()},[t,q,n]),l.useEffect(()=>{var Be,Xe;const ue=le.current,we=(Xe=(Be=ue==null?void 0:ue.ownerDocument)==null?void 0:Be.defaultView)==null?void 0:Xe.ResizeObserver;if(!ue||!we)return;const Se=new we(lt=>{const Ve=lt[0];if(!Ve)return;const{width:yt,height:Gt}=Ve.contentRect;H(At=>{const Xt=Math.round(yt),Zt=Math.round(Gt);return At.width===Xt&&At.height===Zt?At:{width:Xt,height:Zt}})});return Se.observe(ue),()=>Se.disconnect()},[]),l.useEffect(()=>{if(ee.current)return;const ue=je();!Number.isFinite(ue)||ue<=0||C(we=>z.current?ue<we-ie?ue:we:(z.current=!0,ue))},[_.height,_.width,E.height,E.width]),l.useEffect(()=>{qe&&ut()},[qe,Fe,ye]),l.useEffect(()=>{var Se;const ue=X.current;if(X.current=i,!i)return;ue||y(!1),ge.current&&(ge.current=!1,mt());const we=ve.current;we&&(ve.current=null,be(we.text,we.seq,we.cols,we.rows,{force:!!we.force})),Ie&&oe&&((Se=Ct.getState)==null?void 0:Se.call(Ct,Ie))==="connected"&&re(),ke.current&&B.current===null&&Ee(),Ne(()=>{var Be;(Be=n.current)==null||Be.bumpResize()})},[Ie,i,oe]),l.useEffect(()=>()=>{B.current!==null&&pe(),fe(),Me()},[]),l.useEffect(()=>{const ue=Be=>{var lt;const Xe=Be.detail;Xe!=null&&Xe.sessionId&&Xe.sessionId!==oe||d&&((lt=n.current)==null||lt.bumpResize())},we=Z(),Se=we===window?[window]:[window,we];for(const Be of Se)Be.addEventListener("adhdev:fit-cli-terminal",ue);return()=>{for(const Be of Se)Be.removeEventListener("adhdev:fit-cli-terminal",ue)}},[d,oe,n]);const st=d&&S&&!v&&(W.atTop||!W.canScroll)||f||!!w;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:le,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[st&&s.jsxs("div",{className:"absolute left-3 top-3 z-10 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-medium text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{Ue()},disabled:!oe||f,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:u(f?"terminal.loadingOlder":"terminal.loadOlderOutput")}),w&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:w})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[V&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:V}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>F(ue=>!ue),title:"Spec debug — inspect current state, sections, and transition history",children:u("terminal.debug")}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{Ge()},disabled:!d,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:u("terminal.copy")}),s.jsxs("div",{className:"relative",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>T(ue=>!ue),disabled:!d,"aria-label":u(A?"terminal.closeControlKeys":"terminal.openControlKeys"),"aria-expanded":A,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),A&&s.jsxs("div",{id:"terminal-control-keys-popover",role:"dialog","aria-label":u("terminal.openControlKeys"),className:"absolute right-0 top-10 w-72 rounded-2xl border border-white/10 bg-[#0b0d12]/95 p-3 text-white/85 shadow-2xl shadow-black/40 backdrop-blur-md",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Terminal keys"}),s.jsx("button",{type:"button",className:"rounded-full px-2 py-0.5 text-[11px] text-white/55 transition-colors hover:bg-white/10 hover:text-white/85",onClick:()=>T(!1),"aria-label":u("terminal.closeControlKeys"),children:"×"})]}),s.jsx("div",{className:"mb-2 grid grid-cols-3 gap-1.5",children:[["Ctrl",D,I],["Alt",M,P],["Shift",$,L]].map(([ue,we,Se])=>s.jsx("button",{type:"button","aria-pressed":we,className:`h-9 rounded-lg border text-[12px] font-semibold transition-colors ${we?"border-sky-400/50 bg-sky-400/25 text-white":"border-white/10 bg-white/[0.06] hover:bg-white/[0.12]"}`,onClick:()=>Se(Be=>!Be),children:ue},ue))}),s.jsx("div",{className:"my-2 h-px bg-white/10"}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Je("Escape"),children:"Esc"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Je("Tab"),children:"Tab"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Je("Enter"),children:"Enter"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Je("ArrowUp"),"aria-label":"Arrow up",children:"↑"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Je("ArrowLeft"),"aria-label":"Arrow left",children:"←"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Je("ArrowDown"),"aria-label":"Arrow down",children:"↓"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Je("ArrowRight"),"aria-label":"Arrow right",children:"→"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>ze(""),title:"Send SIGINT (Ctrl-C)",children:"Ctrl-C"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Je("Space"),children:"Space"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Je("Backspace"),children:"Bksp"})]})]})]}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{ee.current=!0,C(ue=>{const we=Math.max(De,Number((ue-.1).toFixed(2)));return we>De&&ut(),we})},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:()=>{ee.current=!0,C(ue=>{const we=Math.min(_e,Number((ue+.1).toFixed(2)));return we>De&&ut(),we})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:de,className:qe?"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:ye>0?`${ye}px`:"100%",height:Fe>0?`${Fe}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:_.width>0?`${_.width}px`:"100%",height:_.height>0?`${_.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:j},children:s.jsx(Xu,{ref:n,readOnly:!d||!i,sizingMode:"measured",onViewportMetrics:G,onScrollMetrics:K,onInput:ue=>{!d||(p==null||p(Ie,oe,ue))}})})})}),!d&&s.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:g})]}),s.jsx(yp,{contextKey:e.tabKey,panelLabel:wt(e),isSending:r,isBusy:!!xe,statusMessage:he,inlineStatusMessage:Ze,onSend:async ue=>xe?!1:a(ue),isActive:c&&i,showControlsToggle:!1,animateVisibility:!1}),R&&s.jsx(GS,{activeConv:e,onClose:()=>F(!1)})]})}const KS=5e3,VS=12e3;function YS(e){return e==="disconnected"||e==="reconnecting"}function QS({wsStatus:e,showReconnected:t,loginUrl:n,onReconnect:a,reconnectDelayMs:r=KS,reconnectActionDelayMs:o=VS}){const{t:i}=Ce(),c=YS(e),[u,p]=l.useState(()=>!c||r<=0),[d,m]=l.useState(()=>!c||o<=0),h=l.useRef(!1);l.useEffect(()=>{if(!c){p(!1);return}if(h.current=!1,r<=0){h.current=!0,p(!0);return}p(!1);const y=setTimeout(()=>{h.current=!0,p(!0)},r);return()=>clearTimeout(y)},[r,c]),l.useEffect(()=>{if(!c){m(!1);return}if(o<=0){m(!0);return}m(!1);const y=setTimeout(()=>{m(!0)},o);return()=>clearTimeout(y)},[o,c]);const g=c?u:e==="offline"||e==="auth_failed",k=!!(a&&e!=="auth_failed"&&(!c||d)),f=l.useMemo(()=>!t||e!=="connected"?!1:r<=0||h.current,[r,t,e]),x=e==="auth_failed"?"red":e==="offline"?"orange":"accent",w={red:"linear-gradient(90deg, rgba(239,68,68,0.12), rgba(239,68,68,0.04))",orange:"linear-gradient(90deg, rgba(255,107,53,0.12), rgba(255,107,53,0.04))",accent:"linear-gradient(90deg, color-mix(in srgb, var(--accent-primary) 18%, transparent), color-mix(in srgb, var(--accent-primary) 6%, transparent))"},b={red:"1px solid rgba(239,68,68,0.2)",orange:"1px solid rgba(255,107,53,0.2)",accent:"1px solid color-mix(in srgb, var(--accent-primary) 28%, transparent)"},S={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},N="fixed left-1/2 top-[calc(env(safe-area-inset-top,0px)+64px)] sm:top-[calc(env(safe-area-inset-top,0px)+16px)] z-[var(--z-toast)] flex items-center justify-center pointer-events-none",v={transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[g&&s.jsx("div",{className:N,style:v,children:s.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-3 py-2.5 sm:px-4 sm:py-3 text-[13px] font-semibold flex flex-wrap items-center gap-x-2.5 gap-y-2 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:w[x],border:b[x],color:S[x]},children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5 shrink-0",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),s.jsxs("span",{className:"min-w-0 text-center whitespace-nowrap",children:[e==="offline"&&i("connection.networkOffline"),e==="disconnected"&&i("connection.reconnecting"),e==="reconnecting"&&i("connection.reconnecting"),e==="auth_failed"&&(n?s.jsxs(s.Fragment,{children:[i("connection.sessionExpired")," ",s.jsx("a",{href:n,className:"text-inherit underline",children:i("connection.logInAgain")})]}):i("connection.connectionFailed"))]}),k&&s.jsx("button",{type:"button",className:"basis-full sm:basis-auto mx-auto sm:mx-0 sm:ml-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-[12px] font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>a==null?void 0:a(),disabled:e==="offline",children:i("connection.reconnectNow")})]})}),f&&s.jsx("div",{className:N,style:v,children:s.jsxs("div",{className:"pointer-events-none rounded-2xl border px-4 py-2 text-xs font-semibold flex items-center gap-2 justify-center bg-gradient-to-r from-green-500/[0.12] to-green-500/[0.04] text-green-400 border-green-500/15 shadow-[0_18px_40px_rgba(2,6,23,0.2)] backdrop-blur-xl animate-[fadeIn_0.3s_ease]",children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),i("connection.connected")]})})]})}function im({mode:e,onChange:t,compact:n=!1}){const{t:a}=Ce("common"),r=n?14:15;return s.jsx("button",{type:"button",onClick:()=>t(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:a(e==="chat"?"cliView.switchToTerminal":"cliView.switchToChat"),children:e==="chat"?s.jsx(ll,{size:r}):s.jsx(kn,{size:r})})}function JS(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 XS(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 ZS(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 Pr({git:e,className:t="",compact:n=!1}){const a=JS(e),r=XS(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 ${ZS(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 eC({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 td({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function sd({notification:e,shortcutIndex:t,onOpen:n,onMarkRead:a,onMarkUnread:r,onDelete:o}){const{t:i}=Ce(),c=Kr(e.updatedAt),u=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${u?"is-attention":""}`.trim(),children:[s.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:n,children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[t?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",t]}):null,[e.type==="needs_attention"?i("notification.actionNeeded"):i("notification.taskComplete"),c].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[u?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:p=>{p.stopPropagation(),a()},children:i("notification.markRead")}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:p=>{p.stopPropagation(),r()},children:i("notification.markUnread")}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:p=>{p.stopPropagation(),o()},children:i("notification.delete")})]})]})}function tC({activeConv:e,wsStatus:t,isConnected:n,conversations:a,onOpenHistory:r,onOpenRemote:o,onStopCli:i,activeCliViewMode:c,onSetCliViewMode:u,onHideConversation:p,hiddenConversations:d=[],onShowConversation:m,onShowAllHidden:h,onResetPanelsToMain:g,inboxOpen:k,onInboxOpenChange:f,hiddenOpen:x,onHiddenOpenChange:w,onOpenNewSession:b,onOpenDashboardGuide:S,guideNudgeVisible:N=!1,actionShortcuts:v,notifications:y,notificationUnreadCount:j,onOpenNotification:C,onMarkNotificationRead:A,onMarkNotificationUnread:T,onDeleteNotification:D,onOpenGitDialog:I,onOpenMeshGraph:M}){var se;const{t:P}=Ce(),{ides:$,p2pStates:L={},usesP2P:R=!0}=Ms(),F=!!e&&ft(e)&&!pt(e),E=!!e&&pt(e),H=!!(e!=null&&e.daemonId)&&!!((se=e==null?void 0:e.coordinator)!=null&&se.meshId),_=c||(e?Mp(e)?"terminal":"chat":null),[G,W]=l.useState(!1),[K,V]=l.useState(!1),te=l.useRef(null),le=l.useRef(null),de=l.useRef(null),ee=$.filter(Z=>Z.type==="adhdev-daemon"),z=eC({wsStatus:t,isConnected:n,daemonCount:ee.length,p2pStates:L,usesP2P:R}),X=P(z.titleKey),U=z.subtitleKey?P(z.subtitleKey,z.subtitleParams):null,Q=z.tone==="connected"?"#22c55e":z.tone==="limited"?"#eab308":"#ef4444",ke=z.tone==="connected"?"0 0 4px #22c55e80":z.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",ve=l.useMemo(()=>y.filter(Z=>!Z.readAt),[y]),ge=l.useMemo(()=>y.filter(Z=>!!Z.readAt),[y]),me=l.useMemo(()=>ve.slice(0,9),[ve]),B=j;l.useEffect(()=>{if(!k)return;const Z=Ne=>{var pe;(pe=le.current)!=null&&pe.contains(Ne.target)||f(!1)};return document.addEventListener("mousedown",Z),()=>document.removeEventListener("mousedown",Z)},[k,f]),l.useEffect(()=>{if(!x)return;const Z=Ne=>{var pe;(pe=de.current)!=null&&pe.contains(Ne.target)||w(!1)};return document.addEventListener("mousedown",Z),()=>document.removeEventListener("mousedown",Z)},[x,w]),l.useEffect(()=>{if(!x&&!k)return;const Z=Ne=>{if(!Ne.altKey)return;const pe=Ne.code.match(/^Digit([1-9])$/);if(!pe)return;const fe=Number(pe[1])-1,Me=x?d[fe]:void 0,Ee=k?me[fe]:void 0;if(!(!Me&&!Ee)){if(Ne.preventDefault(),Ne.stopPropagation(),Me){m==null||m(Me),w(!1);return}Ee&&(C(Ee),f(!1))}};return window.addEventListener("keydown",Z,!0),()=>window.removeEventListener("keydown",Z,!0)},[d,x,k,me,w,f,C,m]),l.useEffect(()=>{const Z=d.length;if(te.current===null){te.current=Z;return}Z>te.current&&V(!0),te.current=Z},[d.length]);const O=()=>V(!1),Y=Z=>{if(!Z)return;const Ne=a.find(pe=>pe.tabKey===Z);Ne&&(p==null||p(Ne))};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(kn,{size:18}),s.jsx("span",{className:"header-title-desktop",children:P("dashboard.header.title")}),s.jsx("span",{className:"header-title-mobile",children:e?wt(e):P("dashboard.header.title")}),s.jsx("span",{title:X,"aria-label":X,className:"header-title-status-dot",style:{background:Q,boxShadow:ke}}),s.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:s.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:Q,boxShadow:ke}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[U&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",U]}),b&&s.jsx("button",{type:"button",onClick:b,className:"btn btn-secondary btn-sm ml-2",title:`${P("paneGroup.newSession")}${v!=null&&v.openNewSession?` (${v.openNewSession})`:""}`,"aria-label":P("paneGroup.newSession"),children:s.jsx(cl,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[S&&s.jsxs("button",{type:"button",onClick:S,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:P("dashboard.header.guide"),"aria-label":P("dashboard.header.guideOpen"),children:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),N&&s.jsx("span",{children:P("dashboard.header.guideShort")})]}),e&&(F||E||!pt(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:On(e)||wt(e),children:wt(e)}),I&&e.git&&e.daemonId&&e.workspacePath?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:P("dashboard.header.openGitStatus"),onClick:()=>I(e.daemonId,e.workspacePath),children:s.jsx(Pr,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(Pr,{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:P("dashboard.header.openMeshGraph"),children:[s.jsx(as,{size:14}),s.jsx("span",{className:"hidden lg:inline",children:P("dashboard.header.meshGraph")})]}),(F||E)&&i&&s.jsxs(s.Fragment,{children:[F&&u&&_&&s.jsx(im,{mode:_,onChange:u,compact:!0}),s.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:P(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(Pt,{size:14})})]}),!pt(e)&&s.jsx("button",{onClick:()=>r(e),className:"btn btn-secondary btn-sm",title:P("dashboard.header.chatHistory"),children:s.jsx(ol,{size:14})}),!F&&!pt(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:P("dashboard.header.remoteControl"),children:s.jsx(gs,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:le,children:[s.jsxs("div",{className:`dashboard-header-hidden${G?" is-drop-target":""}${K?" hidden-spawn-flash":""}${(d??[]).some(Aa)?" hidden-generating-spin":""}`,onAnimationEnd:O,ref:de,onDragEnter:Z=>{Z.dataTransfer.types.includes("text/tab-key")&&(Z.preventDefault(),W(!0))},onDragOver:Z=>{Z.dataTransfer.types.includes("text/tab-key")&&(Z.preventDefault(),Z.dataTransfer.dropEffect="move",W(!0))},onDragLeave:Z=>{Z.currentTarget.contains(Z.relatedTarget)||W(!1)},onDrop:Z=>{const Ne=Z.dataTransfer.getData("text/tab-key");Z.preventDefault(),W(!1),Y(Ne)},children:[s.jsxs("button",{type:"button",onClick:()=>w(!x),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`${P("dashboard.hidden.title")}${v!=null&&v.toggleHiddenTabs?` (${v.toggleHiddenTabs})`:""}. ${P("dashboard.hidden.dragHint")}`,children:[s.jsx(il,{size:16}),d.length>0&&s.jsx("span",{className:`dashboard-header-hidden-badge${K?" hidden-badge-pop":""}`,children:d.length})]}),x&&s.jsxs("div",{className:"dashboard-header-hidden-popover",children:[s.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:P("dashboard.hidden.title")}),s.jsx(td,{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:P("dashboard.hidden.resetPanels")}),d.length>0&&h&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{h(),w(!1)},children:P("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:P("dashboard.hidden.hideCurrentTab")}),s.jsx(td,{value:v==null?void 0:v.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:wt(e)})]}),d.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:d.map(Z=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{m==null||m(Z),w(!1)},children:[s.jsxs("span",{className:"dashboard-header-inbox-item-title",children:[Aa(Z)&&s.jsx("span",{className:"tab-spinner dashboard-header-inbox-item-spinner","aria-label":P("dashboard.header.generating")}),wt(Z)]}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[d.indexOf(Z)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",d.indexOf(Z)+1]}):null,On(Z)]})]},Z.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:P("dashboard.hidden.empty")})]})]}),s.jsxs("button",{type:"button",onClick:()=>f(!k),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:P("dashboard.header.activityInbox"),children:[s.jsx(Vn,{size:16}),B>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:B})]}),k&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[ve.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:P("dashboard.inbox.unread")}),ve.map(Z=>s.jsx(sd,{notification:Z,shortcutIndex:me.indexOf(Z)>=0?me.indexOf(Z)+1:void 0,onOpen:()=>C(Z),onMarkRead:()=>A(Z.id),onMarkUnread:()=>T(Z.id),onDelete:()=>D(Z.id)},Z.id))]}),ge.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:P("dashboard.inbox.read")}),ge.map(Z=>s.jsx(sd,{notification:Z,onOpen:()=>C(Z),onMarkRead:()=>A(Z.id),onMarkUnread:()=>T(Z.id),onDelete:()=>D(Z.id)},Z.id))]}),y.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:P("dashboard.inbox.empty")})]})]})]})]})}function Ut(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function sC(e,t){return String(e||"")!==String(t||"")}function nC(e,t={}){const n=String(t.textQuery||"").trim().toLowerCase(),a=String(t.workspaceQuery||"").trim().toLowerCase(),r=String(t.modelQuery||"").trim().toLowerCase(),o=!!t.resumableOnly;return!n&&!a&&!r&&!o?e:e.filter(i=>!(o&&!i.canResume||n&&![i.title,i.preview].map(u=>String(u||"").toLowerCase()).join(`
|
|
57
57
|
`).includes(n)||a&&!String(i.workspace||"").toLowerCase().includes(a)||r&&!hp(i.summaryMetadata).map(u=>u.toLowerCase()).join(`
|
|
58
|
-
`).includes(r)))}function aC(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 lm(e,t={}){return aC(nC(e,t),t.sortMode||"recent")}function Fi(e,t){return typeof e=="function"?e(t??!1?"launch.resumeSavedHistory":"launch.startFresh"):e?"Resume saved history":"Start fresh"}function cm(e,t){return typeof e=="function"?e(t??!1?"launch.resumingSavedHistory":"launch.startingFresh"):e?"Resuming saved history…":"Starting fresh…"}function rC(e){return e?e("launch.startFresh"):"Start fresh"}function oC(e){return e?e("launch.hostedRuntimeRecoveryDescription"):"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function iC(e){return e?e("launch.openSavedHistory"):"Open saved history"}function lC(e){return e?e("launch.savedHistoryTitle"):"Saved History"}function Al(e){return e?e("launch.savedHistoryHelper"):"Use saved history when you want continuity in the same provider conversation."}function cC(e){return e?e("launch.savedHistoryEmpty"):"No saved history found yet."}function dC(e){return e?e("launch.refreshSavedHistory"):"Refresh saved history"}function uC(e){return e?e("launch.refreshingSavedHistory"):"Refreshing saved history…"}function Ir(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 Lr(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 Rr(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartFresh":"launch.confirmRestart"):e==="start-fresh"?"Start fresh":"Restart"}function Er(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartingFresh":"launch.confirmRestarting"):e==="start-fresh"?"Starting fresh…":"Restarting…"}function dm(e,t){return typeof e=="function"?e("launch.resumeWith",{label:t}):`Resume saved history with ${e}?`}function um(e){return e?e("launch.resumeReview"):"Review or change the target workspace before resuming saved history."}function nd(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 pm({activeConv:e,ides:t,isCreatingChat:n,isRefreshingHistory:a,savedSessions:r=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:c,missingWorkspaceResumePath:u,onSavedHistoryFiltersChange:p,onClose:d,onNewChat:m,onSwitchSession:h,onRefreshHistory:g,onResumeSavedSession:k}){var P;const{t:f}=Ce("common"),x=t.find($=>$.id===e.routeId),w=(x==null?void 0:x.chats)||[],b=(P=x==null?void 0:x.activeChat)==null?void 0:P.id,S=ft(e)&&!pt(e),[N,v]=l.useState(()=>Ut()),[y,j]=l.useState(null),C=c||N,A=String(u||"").trim(),T=$=>{if(p){p($);return}v($)},D=l.useMemo(()=>r.map($=>{const L=String($.workspace||"").trim();return $.canResume||L||!A?$:{...$,workspace:A,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[A,r]),I=l.useMemo(()=>lm(D,{textQuery:C.textQuery,workspaceQuery:C.workspaceQuery,modelQuery:C.modelQuery,resumableOnly:C.resumableOnly,sortMode:C.sortMode}),[D,C.modelQuery,C.resumableOnly,C.sortMode,C.textQuery,C.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:d,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:S?lC(f):f("historyModal.chatHistory")}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:PS(e)}),S&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Al(f)})]}),s.jsx("button",{onClick:d,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(Pt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!S&&s.jsx("button",{onClick:m,disabled:n,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:f(n?"historyModal.creating":"historyModal.startNewChat")}),S?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:C.textQuery,onChange:$=>T({...C,textQuery:$.target.value}),placeholder:f("historyModal.searchPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:C.workspaceQuery,onChange:$=>T({...C,workspaceQuery:$.target.value}),placeholder:f("historyModal.filterWorkspace"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:C.modelQuery,onChange:$=>T({...C,modelQuery:$.target.value}),placeholder:f("historyModal.filterModel"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsxs("select",{value:C.sortMode,onChange:$=>T({...C,sortMode:$.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:f("historyModal.sortRecent")}),s.jsx("option",{value:"oldest",children:f("historyModal.sortOldest")}),s.jsx("option",{value:"messages",children:f("historyModal.sortMessages")})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:C.resumableOnly,onChange:$=>T({...C,resumableOnly:$.target.checked})}),f("historyModal.resumeReadyOnly")]})]}),I.map($=>{const L=e.providerSessionId===$.providerSessionId,R=L||!$.canResume||!!i,F=$.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{R||!k||j({kind:"saved",session:$})},disabled:R,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${L?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${R?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${L?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:$.title||f("historyModal.untitledSession")}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:$.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:nd($.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:$.preview||f("historyModal.noSavedPreview")}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[$.workspace||f("historyModal.workspaceUnknown"),F?f("historyModal.selectedWorkspaceSuffix"):"",xn($.summaryMetadata)?` · ${xn($.summaryMetadata)}`:"",$.messageCount>0?` · ${f("historyModal.msgCount",{count:$.messageCount})}`:""]}),s.jsx("div",{className:"shrink-0",children:L?f("historyModal.statusActive"):$.canResume?F?f("historyModal.statusResumeSelectedWorkspace"):i===$.providerSessionId?f("historyModal.statusResuming"):f("historyModal.statusResume"):f("historyModal.statusMissingWorkspace")})]})]},$.id)})]}):w.map($=>s.jsxs("div",{onClick:()=>{$.id!==b&&j({kind:"chat",id:$.id,title:$.title||f("historyModal.untitledSession")})},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${b===$.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[s.jsx("div",{className:`font-bold text-sm mb-1 ${b===$.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:$.title||f("historyModal.untitledSession")}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[$.id.substring(0,12),"..."]}),b===$.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:f("historyModal.statusActive")})]})]},$.id)),(S&&!o&&I.length===0||!S&&w.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(Mb,{size:32})}),s.jsx("div",{className:"text-[13px]",children:S?r.length>0?f("historyModal.noMatchingHistory"):cC(f):f("historyModal.noRecentChats")})]}),S&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:uC(f)})})]}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:s.jsx("button",{onClick:g,disabled:a||o,className:"btn btn-secondary btn-sm rounded-[10px]",children:a||o?f("historyModal.refreshing"):s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(zr,{size:13})," ",S?dC(f):f("historyModal.refreshHistory")]})})})]}),y&&s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center p-4",children:[s.jsx("div",{onClick:()=>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:f("historyModal.confirmSwitchTitle")}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:f("historyModal.confirmSwitchDescription",{target:y.kind==="chat"?y.title:y.session.title||f("historyModal.untitledSession")})}),y.kind==="saved"&&s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted font-mono truncate",children:[y.session.workspace||f("historyModal.workspaceUnknown"),y.session.lastMessageAt?` · ${nd(y.session.lastMessageAt)}`:""]})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[s.jsx("button",{onClick:()=>{const $=y;j(null),$.kind==="chat"?(h(e.routeId,$.id),d()):k&&k($.session)},className:"btn btn-primary w-full justify-center min-h-[42px]",children:f("historyModal.confirmSwitchAction")}),s.jsx("button",{onClick:()=>j(null),className:"btn btn-secondary w-full justify-center min-h-[42px]",children:f("common.cancel")})]})]})]})]});return typeof document>"u"?M:Fs.createPortal(M,document.body)}const ad={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 mm({toasts:e,onDismiss:t,onClickToast:n}){const{t:a}=Ce();return s.jsx("div",{className:"fixed right-4 top-[calc(env(safe-area-inset-top,0px)+64px)] z-[var(--z-toast)] flex flex-col gap-2 pointer-events-none sm:top-[calc(env(safe-area-inset-top,0px)+16px)]",children:e.map(r=>{const o=ad[r.type]||ad.info;return s.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var i;(i=r.actions)!=null&&i.length||n&&n(r)},children:[s.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${o.accent}, color-mix(in srgb, ${o.accent} 55%, transparent))`}}),s.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:i=>{i.stopPropagation(),t(r.id)},"aria-label":a("toast.dismiss"),children:s.jsx(Pt,{size:14})}),s.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[s.jsx("div",{className:"flex items-center gap-2 pr-8",children:s.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:o.chipBg,color:o.chipText,border:`1px solid color-mix(in srgb, ${o.accent} 22%, transparent)`},children:a(o.labelKey)})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:r.message}),r.actions&&r.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:r.actions.map((i,c)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:i.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:u=>{u.stopPropagation(),i.onClick(),t(r.id)},children:i.label},c))})]})]},r.id)})})}const pC=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function mC(e){const t=e.workspace||"";if(!t)return"";const n=t.split(/[/\\]/).filter(Boolean);return n.length>0?n[n.length-1]:t}function hC(e,t){return hm(e)||t}function hm(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 fC(e){return hm(e)||void 0}function bC(e){return e.sessionId||e.instanceId||e.agentType}function fm(e=[]){const t={};for(const n of e)n.type==="adhdev-daemon"&&(t[n.id]=rs(n,{fallbackId:n.id}));return t}function bm(e,t={}){var a;const n=e.daemonId||((a=e.id)==null?void 0:a.split(":")[0])||e.id;return{machineName:Tw(e,t.machineNames),connectionState:t.connectionStates?t.connectionStates[n]||t.defaultConnectionState||"new":t.defaultConnectionState}}function Tl(e,t={}){return gC(e,bm(e,t))}function gC(e,t={}){var h,g,k,f,x,w,b,S,N;const n=[],a=t.machineName,r=t.connectionState,o=mC(e),i=e.workspace||"",c=Rw(e.type,{agentName:e.cliName}),u=ft(e)||pt(e)?c:Bt(e.type),p=hC(e,u),d=Array.isArray(e.childSessions)?e.childSessions.map(v=>{var y,j,C;return{sessionId:v.id,instanceId:v.id,providerSessionId:v.providerSessionId,activeChatId:(y=v.activeChat)==null?void 0:y.id,transport:v.transport,sessionCapabilities:v.capabilities,agentType:v.providerType,agentName:v.providerName||Bt(v.providerType),model:fC(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:((C=v.activeChat)==null?void 0:C.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=pC(e);if(m){const v=e.sessionId||e.instanceId,y=(h=e.settings)==null?void 0:h.meshCoordinatorFor,j=((g=e.settings)==null?void 0:g.meshNodeFor)||!((k=e.settings)!=null&&k.meshCoordinatorFor)&&((f=e.settings)==null?void 0:f.launchedByCoordinator),C=y?" (Coordinator)":j?" (Mesh Node)":"",A=c+C,T=(x=e.activeChat)==null?void 0:x.activeModal,D=T&&Array.isArray(T.buttons)&&T.buttons.length>0,I=Ew(e.activeChat,[{status:e.status,activeModal:(w=e.activeChat)==null?void 0:w.activeModal}],e.agents||[]),M=e.activeChat||{title:"",messages:[]};let P=M.title&&String(M.title).trim()?String(M.title).trim():"";const $=(b=e.activeChat)==null?void 0:b.id,L=e.chats;if($&&Array.isArray(L)&&L.length>0){const K=L.find(V=>V.id===$||V.id&&String(V.id)===String($));K!=null&&K.title&&String(K.title).trim()&&(P=String(K.title).trim())}const R=(ft(e)||pt(e),e.type),F=(ft(e)||pt(e))&&Nc(P,A,R)?"":P,E=M.messages||[],H=typeof $=="string"?$.trim():"",_=(ft(e)||pt(e))&&H===String(e.type||"").trim(),G=H&&!_?H:e.providerSessionId,W=e.coordinator||(typeof((S=e.settings)==null?void 0:S.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:v,providerSessionId:e.providerSessionId,historySessionId:G,nativeSessionId:v,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:ft(e)&&e.mode||"chat",agentName:A,agentType:R,status:I,title:F,messages:E,resume:e.resume,hostIdeType:!ft(e)&&!pt(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||F||(ft(e)?e.mode==="chat"?A:`Terminal${C}`: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:D?T.buttons:void 0,modalMessage:D?T.message:void 0,streamSource:"native",tabKey:So(v,e.id),machineName:a,connectionState:r,settings:e.settings,coordinator:W,messageInput:e.messageInput})}if(m&&(ft(e)||pt(e)))return n;for(const v of d){const y=v.activeModal&&Array.isArray(v.activeModal.buttons)&&v.activeModal.buttons.length>0,j=_w(v),C=bC(v),A=`${e.id}:${C}`,T=v.title&&String(v.title).trim()||"",D=Nc(T,v.agentName,v.agentType)?"":T,I=v.messages||[];if(!(v.transport==="cdp-webview"||!!v.sessionId||!!v.providerSessionId||I.length>0||y||!!D||!["idle","panel_hidden","disconnected","not_monitored"].includes(j)))continue;const P=v.coordinator||(typeof((N=v.settings)==null?void 0:N.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:D,messages:I,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:v.git||e.git,displayPrimary:o||D||v.agentName||u,displaySecondary:v.model&&v.model.trim()?v.model.trim():`${u} · ${v.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,lastUpdated:v.lastUpdated||e.lastUpdated,inboxBucket:v.inboxBucket,completionMarker:v.completionMarker,modalButtons:y?v.activeModal.buttons:void 0,modalMessage:y?v.activeModal.message:void 0,streamSource:"agent-stream",tabKey:So(v.sessionId||v.instanceId,A),machineName:a,connectionState:r,settings:v.settings,coordinator:P,messageInput:v.messageInput})}return n.length===0&&n.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:c,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||u,displaySecondary:p,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:So(e.sessionId||e.instanceId,e.id),connectionState:r,settings:e.settings,messageInput:e.messageInput}),n}function gm(e){return String(e.type||e.id||"").trim()}function _r(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()).map(t=>t.trim()):[]}function xC(e,t){const n=(t||"").trim();if(!n)return[];const a=(e||[]).find(r=>r.type===n);return _r(a==null?void 0:a.modelOptions)}function vC(e,t){const n=(t||"").trim();if(!n)return[];const a=(e||[]).find(r=>r.type===n);return _r(a==null?void 0:a.thinkingLevelOptions)}function xm(e){const t=new Map;for(const n of e||[])n!=null&&n.type&&t.set(n.type,{models:_r(n.modelOptions),thinking:_r(n.thinkingLevelOptions)});return t}function yC(e){var t;return e.category!=="cli"||!gm(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 Un(e){var a;const t=new Set,n=[];for(const r of e||[]){if(!yC(r))continue;const o=gm(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 qn(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 Pa(e){return e.map(t=>t.type)}function wC(e,t){const n=qn(e),a=t.trim();return!a||n.includes(a)?n:[...n,a]}function kC(e,t){return qn(e).filter(n=>n!==t)}function rd(e,t,n){const a=qn(e),r=a.indexOf(t);if(r<0)return a;const o=a.filter(c=>c!==t);if(n==="top")return[t,...o];if(n==="bottom")return[...o,t];const i=n==="up"?Math.max(0,r-1):Math.min(o.length,r+1);return o.splice(i,0,t),o}function od({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 SC({value:e,availableProviders:t,onChange:n,disabled:a=!1,saveButton:r}){const{t:o}=Ce("common"),[i,c]=l.useState(""),u=l.useMemo(()=>new Map(t.map(g=>[g.type,g])),[t]),p=l.useMemo(()=>qn(e),[e]),d=p.filter(g=>!u.has(g)).length,m=t.filter(g=>!p.includes(g.type)),h=()=>{i&&(n(wC(p,i)),c(""))};return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[s.jsx("div",{className:"flex flex-col gap-2",children:p.length===0?s.jsx("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:"No provider priority configured. Launches without an explicit CLI provider will fail closed."}):p.map((g,k)=>{const f=u.get(g),x=!!f;return s.jsxs("div",{className:`flex flex-col gap-2 rounded-md border border-border-subtle px-3 py-2 sm:flex-row sm:items-center sm:justify-between ${x?"bg-bg-primary":"bg-bg-primary/40"}`,children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("span",{className:"text-[10px] font-semibold text-text-muted",children:["#",k+1]}),(f==null?void 0:f.icon)&&s.jsx("span",{"aria-hidden":"true",children:f.icon}),s.jsx("span",{className:`font-mono text-[12px] ${x?"text-text-primary":"text-text-muted"}`,children:g}),x?s.jsx("span",{className:"rounded border border-green-500/20 bg-green-500/10 px-1.5 py-px text-[9px] font-semibold text-green-400",children:o("settings.providerPriority.available")}):s.jsx("span",{className:"rounded border border-amber-500/25 bg-amber-500/10 px-1.5 py-px text-[9px] font-semibold text-amber-400",children:o("settings.providerPriority.notOnMachine")})]}),s.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:f?`${f.label} · ${f.statusLabel}`:"Kept in order; skipped at launch until detected here."})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move up",disabled:a||k===0,title:"Move up",onClick:()=>n(rd(p,g,"up")),children:s.jsx(od,{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(rd(p,g,"down")),children:s.jsx(od,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:a,onClick:()=>n(kC(p,g)),children:o("settings.providerPriority.remove")})]})]},g)})}),s.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-end",children:[s.jsxs("label",{className:"flex-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"mb-1 block font-medium text-text-primary",children:o("settings.providerPriority.addCliLabel")}),s.jsxs("select",{className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-sm text-text-primary",value:i,onChange:g=>c(g.target.value),disabled:a||m.length===0,children:[s.jsx("option",{value:"",children:m.length?"Select provider…":"No additional detected CLI providers"}),m.map(g=>s.jsxs("option",{value:g.type,children:[g.label," (",g.type,")"]},g.type))]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:a||!i,onClick:h,children:o("settings.providerPriority.addProvider")}),r]}),s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:["Launches use this order, top to bottom.",d>0?` ${d} provider${d===1?"":"s"} not detected here — kept in order, skipped until available.`:""]})]})}function CC(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 vm(e,t){const n=CC(e);return{daemonId:n.daemonId,payload:{...t,...n.targetSessionId&&!t.targetSessionId?{targetSessionId:n.targetSessionId}:{}}}}const ym=[{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:"🏄"}],wm=[{id:"antigravity-cli",name:"Antigravity CLI",icon:"🪐"},{id:"claude-cli",name:"Claude Code",icon:"🟠"},{id:"codex-cli",name:"Codex CLI",icon:"📦"},{id:"cursor-cli",name:"Cursor CLI",icon:"⚡"},{id:"hermes-cli",name:"Hermes",icon:"⚕️"},{id:"kimi",name:"Kimi",icon:"🌙"},{id:"opencode",name:"OpenCode CLI",icon:"◆"}],km=[{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:"🟠"}],jC=ym,NC=wm,AC=km;function TC({icon:e,title:t,subtitle:n,badge:a,actions:r,className:o}){return s.jsxs("div",{className:Wt("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 Fa({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(TC,{icon:e,title:t,subtitle:n,badge:a,actions:r}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Wt("mx-auto flex w-full flex-col gap-4",o,i),children:c})})]})}const Bi="adhdev:themechange";function MC(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function Pn(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function In(e){return e==="system"?MC():e}function Sm(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function hr(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(Bi,{detail:{preference:e,theme:t}}))}function DC(){const e=Pn(),t=In(e);Sm(t),hr(e,t)}function en(){const[e,t]=l.useState(Pn),[n,a]=l.useState(()=>In(Pn()));l.useEffect(()=>{Sm(n)},[n]),l.useEffect(()=>{const i=window.matchMedia("(prefers-color-scheme: light)"),c=u=>{if(e==="system"){const p=u.matches?"light":"dark";a(p),hr("system",p)}};return i.addEventListener("change",c),()=>i.removeEventListener("change",c)},[e]),l.useEffect(()=>{const i=u=>{const p=u.detail||{},d=p.preference,m=p.theme;t(d==="dark"||d==="light"||d==="system"?d:Pn()),a(m==="dark"||m==="light"?m:In(Pn()))},c=u=>{if(u.key!=="theme")return;const p=Pn(),d=In(p);t(p),a(d)};return window.addEventListener(Bi,i),window.addEventListener("storage",c),()=>{window.removeEventListener(Bi,i),window.removeEventListener("storage",c)}},[]);const r=l.useCallback(i=>{const c=In(i);t(i),a(c);try{localStorage.setItem("theme",i)}catch{}hr(i,c)},[]),o=l.useCallback(()=>{t(i=>{const c=i==="dark"?"light":i==="light"?"system":"dark",u=In(c);a(u);try{localStorage.setItem("theme",c)}catch{}return hr(c,u),c})},[]);return{theme:n,preference:e,setPreference:r,cycleTheme:o,isDark:n==="dark"}}const id={dark:"Dark",light:"Light",system:"System"};function PC({collapsed:e}){const{preference:t,cycleTheme:n}=en(),a=t==="dark"?s.jsx(Pb,{size:16}):t==="light"?s.jsx(Db,{size:16}):s.jsx(Ib,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:n,title:`Theme: ${id[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:a}),!e&&s.jsx("span",{className:"text-xs",children:id[t]})]})}const Wi="adhdev:langchange";function IC(){const e=St.language;return Rn(e)?e:op()}function LC(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(Wi,{detail:{language:e}}))}function RC(){const[e,t]=l.useState(IC);l.useEffect(()=>{const a=i=>{Rn(i)&&t(i)},r=i=>{const c=i.detail||{};Rn(c.language)&&t(c.language)},o=i=>{if(i.key!==ji)return;const c=i.newValue;Rn(c)&&c!==St.language&&(St.changeLanguage(c),Ni(c))};return St.on("languageChanged",a),window.addEventListener(Wi,r),window.addEventListener("storage",o),()=>{St.off("languageChanged",a),window.removeEventListener(Wi,r),window.removeEventListener("storage",o)}},[]);const n=l.useCallback(a=>{if(Rn(a)){t(a);try{localStorage.setItem(ji,a)}catch{}St.changeLanguage(a),Ni(a),LC(a)}},[]);return{language:e,setLanguage:n}}function EC({trigger:e,viewport:t,menu:n,variant:a,gap:r=6,margin:o=8}){const i=e.top-o,c=t.height-e.bottom-o,u=a==="sidebar";let p=u;u&&i<n.height&&c>i&&(p=!1),!u&&c<n.height&&i>c&&(p=!0);const d=p?i:c,m=Math.max(80,Math.min(n.height,d));let h;p?h=e.top-r-m:h=e.bottom+r,h=ld(h,o,Math.max(o,t.height-m-o));const g=ld(e.left,o,Math.max(o,t.width-n.width-o));return{top:h,left:g,maxHeight:m}}function ld(e,t,n){return Math.min(Math.max(e,t),n)}function _C({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 HC({collapsed:e,variant:t="sidebar"}){const{language:n,setLanguage:a}=RC(),{t:r}=Ce("common"),[o,i]=l.useState(!1),[c,u]=l.useState(0),p=l.useRef(null),d=l.useRef(null),m=l.useRef(null),h=l.useId(),[g,k]=l.useState(null),f=l.useCallback(()=>{const I=d.current;if(!I)return;const M=I.getBoundingClientRect(),P=m.current,$=Math.max((P==null?void 0:P.offsetWidth)??0,168),L=(P==null?void 0:P.scrollHeight)??sn.length*36+12;k(EC({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:$,height:L},variant:t}))},[t]),x=Math.max(0,sn.findIndex(I=>I.code===n)),w=sn[x]??sn[0],b=r("language.label",{defaultValue:"Language"}),S=r("language.select",{defaultValue:"Select language"}),N=I=>`${h}-opt-${I}`,v=l.useCallback(()=>{u(x),i(!0)},[x]),y=l.useCallback((I=!0)=>{var M;i(!1),I&&((M=d.current)==null||M.focus())},[]),j=l.useCallback(I=>{const M=sn[I];M&&a(M.code),y()},[a,y]);l.useEffect(()=>{if(!o)return;const I=$=>{var L,R;return!!((L=p.current)!=null&&L.contains($)||(R=m.current)!=null&&R.contains($))},M=$=>{I($.target)||i(!1)},P=$=>{I($.target)||i(!1)};return document.addEventListener("pointerdown",M,!0),document.addEventListener("focusin",P,!0),()=>{document.removeEventListener("pointerdown",M,!0),document.removeEventListener("focusin",P,!0)}},[o]),l.useLayoutEffect(()=>{if(!o){k(null);return}f();const I=()=>f();return window.addEventListener("resize",I),window.addEventListener("scroll",I,!0),()=>{window.removeEventListener("resize",I),window.removeEventListener("scroll",I,!0)}},[o,f]),l.useEffect(()=>{var I;o&&g&&((I=m.current)==null||I.focus())},[o,g]);const C=I=>{const M=sn.length-1;switch(I.key){case"ArrowDown":I.preventDefault(),u(P=>P>=M?0:P+1);break;case"ArrowUp":I.preventDefault(),u(P=>P<=0?M:P-1);break;case"Home":I.preventDefault(),u(0);break;case"End":I.preventDefault(),u(M);break;case"Enter":case" ":I.preventDefault(),j(c);break;case"Escape":I.preventDefault(),y();break;case"Tab":i(!1);break}},A=I=>{o||(I.key==="ArrowDown"||I.key==="ArrowUp"||I.key==="Enter"||I.key===" ")&&(I.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":""}`,D=t==="landing"||!e;return s.jsxs("div",{ref:p,className:"lang-switch",children:[s.jsxs("button",{ref:d,type:"button",className:T,"aria-haspopup":"listbox","aria-expanded":o,"aria-label":`${b}: ${w.label}`,title:`${b}: ${w.label}`,onClick:()=>o?y(!1):v(),onKeyDown:A,children:[s.jsx("span",{className:"nav-icon lang-switch-icon",children:s.jsx(Wb,{size:16})}),D&&s.jsx("span",{className:"lang-switch-label text-xs",children:w.label}),D&&s.jsx(_C,{open:o})]}),o&&typeof document<"u"&&Fs.createPortal(s.jsx("ul",{ref:m,role:"listbox",tabIndex:-1,"aria-label":S,"aria-activedescendant":N(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:C,children:sn.map((I,M)=>{const P=I.code===w.code,$=M===c;return s.jsxs("li",{id:N(M),role:"option","aria-selected":P,className:`lang-switch-option${$?" is-active":""}${P?" is-selected":""}`,onMouseEnter:()=>u(M),onClick:()=>j(M),children:[s.jsx("span",{className:"lang-switch-check","aria-hidden":"true",children:P?s.jsx(Bu,{size:14}):null}),s.jsx("span",{className:"lang-switch-option-label",children:I.label})]},I.code)})}),document.body)]})}const $C=[],FC=[];function Lo(e,t){return e?typeof e=="function"?e(t):e:null}const BC=l.memo(function({renderState:t,brand:n,navItems:a,sidebarSections:r,footerItems:o,footerInfo:i,footerActions:c,closeMobileMenu:u}){const{t:p}=Ce("common"),{collapsed:d,mobileMenuOpen:m}=t,h=k=>`nav-item${k.active?" active":""} cursor-pointer ${d?"justify-center py-2.5 px-0":""}${k.className?` ${k.className}`:""}`,g=k=>s.jsxs("div",{className:h(k),id:`nav-${k.id}`,onClick:()=>{k.onSelect(),u()},title:d?k.title??(typeof k.label=="string"?k.label:void 0):k.title,children:[s.jsx("span",{className:"nav-icon",children:k.icon}),!d&&k.label]},k.id);return s.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${d?"justify-center gap-0":""}`,children:Lo(n,t)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":p("app.closeMenu"),onClick:u,children:s.jsx(Pt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:a.map(g)}),r.map(k=>s.jsxs("div",{className:k.className??"border-t border-border-subtle pt-2 mt-2",children:[!d&&k.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:k.title}):null,k.items.map(g)]},k.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[o.map(g),Lo(i,t),s.jsx(PC,{collapsed:d}),s.jsx(HC,{collapsed:d}),Lo(c,t)]})]})});function WC({children:e,brand:t,navItems:n,sidebarSections:a=$C,footerItems:r=FC,footerInfo:o,footerActions:i,preMainContent:c,collapsedStorageKey:u="sidebar-collapsed"}){const{t:p}=Ce("common"),[d,m]=l.useState(!1),[h,g]=l.useState(()=>{try{return localStorage.getItem(u)==="1"}catch{return!1}}),k=l.useCallback(()=>m(!0),[]),f=l.useCallback(()=>m(!1),[]),x=l.useCallback(()=>{g(b=>{const S=!b;try{localStorage.setItem(u,S?"1":"0")}catch{}return S})},[u]),w=l.useMemo(()=>({collapsed:h,mobileMenuOpen:d,openMobileMenu:k,closeMobileMenu:f,toggleCollapsed:x}),[h,d,k,f,x]);return s.jsxs("div",{className:`app-layout${d?" mobile-menu-open":""}${h?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":p("app.openMenu"),onClick:k,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),d&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":p("app.closeMenu"),onClick:f,onKeyDown:b=>b.key==="Escape"&&f()}),s.jsx(BC,{renderState:w,brand:t,navItems:n,sidebarSections:a,footerItems:r,footerInfo:o,footerActions:i,closeMobileMenu:f}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function gt({title:e,icon:t,description:n,accentColor:a,className:r,collapsible:o,defaultOpen:i=!0,badge:c,children:u}){const[p,d]=l.useState(i),m=o?p:!0,h=(e||n)&&s.jsxs("div",{className:Wt("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:Wt("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:Wt("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",a&&"border-l-[3px]",r),style:a?{borderLeftColor:a}:void 0,children:[o&&h?s.jsx("button",{type:"button",className:"w-full bg-transparent border-none p-0 text-left cursor-pointer",onClick:()=>d(g=>!g),"aria-expanded":m,children:h}):h,m&&u]})}function so({icon:e,title:t,description:n,action:a,className:r}){return s.jsxs("div",{className:Wt("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 OC={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"},UC={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Dt({variant:e,children:t,onDismiss:n,className:a}){return s.jsxs("div",{className:Wt("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",OC[e],a),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:UC[e]}),s.jsx("span",{children:t})]}),n&&s.jsx("button",{onClick:n,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}function Nt({label:e,hint:t,children:n,className:a}){return s.jsxs("div",{className:Wt("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 ps(e){const{className:t,...n}=e;return s.jsx("input",{...n,className:Wt("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 qC={primary:"btn-primary",secondary:"btn-secondary",warning:"btn-warning",danger:"btn-danger",ghost:"btn-ghost"},Hs=l.forwardRef(function({variant:t="secondary",size:n="md",type:a,className:r,...o},i){return s.jsx("button",{ref:i,type:a??"button",className:Wt("btn",qC[t],n==="sm"&&"btn-sm",r),...o})}),GC=l.forwardRef(function({options:t,children:n,className:a,...r},o){return s.jsx("select",{ref:o,className:Wt("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)))})}),zC={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"},KC={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function VC({status:e,label:t,className:n}){const a=t||e;return s.jsxs("span",{className:Wt("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",zC[e],n),children:[s.jsx("span",{className:Wt("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",KC[e])}),a]})}function ln({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 YC({onPrefChange:e}){const{t}=Ce("common"),[n,a]=zw(),[r,o]=l.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);l.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){o("unsupported");return}o(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,u)=>{a({[c]:u}),e==null||e(c,u)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(ln,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Vn,{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(ln,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(gs,{size:15})," ",t("notifications.browserNotificationsLabel")]}),description:t("notifications.browserNotificationsDesc"),checked:n.browserNotifications,onChange:c=>i("browserNotifications",c)}),n.globalEnabled&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:t("notifications.standaloneBackgroundInfo")}),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:()=>{gp().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(ln,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Gu,{size:15})," ",t("notifications.completionAlertsLabel")]}),description:t("notifications.completionAlertsDesc"),checked:n.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(ln,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Lb,{size:15})," ",t("notifications.approvalAlertsLabel")]}),description:t("notifications.approvalAlertsDesc"),checked:n.approvalAlert,onChange:c=>i("approvalAlert",c)}),s.jsx(ln,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Na,{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 Hr(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 cd(e){var t;return((t=Hr(e))==null?void 0:t.base)??null}function Cm(e,t){const n=Hr(e),a=Hr(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 no(e,t){const n=e.version||null;return!n||!t||e.versionMismatch===!0&&!Hr(t)?!1:Cm(n,t)}function wa(e,t){if(e.versionUpdateRequired===!0)return!0;const n=e.version||null;if(!n||!t||!Cm(n,t))return!1;const a=cd(n),r=cd(t);return!a||!r?!1:a[0]!==r[0]||a[1]!==r[1]}function Ro(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 QC(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 ha(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function Ml(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},n=Ro(t.channel)||Ro(e.updateChannel)||Ro(e.releaseChannel)||void 0,a=QC(t.npmTag)||(n==="preview"?"next":n==="stable"?"latest":void 0),r=ha(t.targetVersion)||ha(e.serverVersion)||void 0,o=ha(t.minVersion)||void 0,i=ha(t.updateCommand)||(n?"adhdev update":void 0);return{...n?{channel:n}:{},...a?{npmTag:a}:{},...r?{targetVersion:r}:{},...o?{minVersion:o}:{},...i?{updateCommand:i}:{}}}function qs(e,t=null){return Ml(e).targetVersion||t}function JC(e){return Ml(e).channel||null}function ao(e){return!e||!Ml(e).channel?null:{}}function jm(e,t={}){const n=ha(t.targetVersion);return n?`Update to v${n}`:t.fallback||(t.required?"Update now":"Upgrade")}const Nm="Cannot update: node update policy unavailable; refresh and try again";async function XC(e,t,n){var r,o,i,c,u,p;const a=ao(n);if(!a)return{state:"error",message:Nm};try{const d=await e(t,"daemon_upgrade",a);return(r=d==null?void 0:d.result)!=null&&r.alreadyLatest?{state:"done",message:`Already on v${((o=d==null?void 0:d.result)==null?void 0:o.version)||"latest"}.`}:(i=d==null?void 0:d.result)!=null&&i.upgraded||(c=d==null?void 0:d.result)!=null&&c.success?{state:"done",message:`Upgrade to v${((u=d==null?void 0:d.result)==null?void 0:u.version)||"latest"} started. Daemon is restarting…`}:{state:"error",message:((p=d==null?void 0:d.result)==null?void 0:p.error)||"Upgrade failed"}}catch(d){return{state:"error",message:d instanceof Error?d.message:"Upgrade failed"}}}function ZC(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Eo(e,t){return e instanceof Error?e.message:t}function ej({ides:e,emptyMessage:t,sendDaemonCommand:n,onDisconnect:a,onRevokeToken:r}){const{t:o}=Ce("common"),i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?s.jsx(so,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:o("machine.connectedMachines.noMachines"),description:t||o("machine.connectedMachines.defaultDescription")}):s.jsx("div",{className:"flex flex-col gap-2",children:i.map(c=>s.jsx(sj,{ide:c,allIdes:e,sendDaemonCommand:n,onDisconnect:a,onRevokeToken:r},c.id))})}function dd({title:e,message:t,confirmLabel:n,confirmColor:a,onConfirm:r,onCancel:o}){const{t:i}=Ce("common"),c=a==="red"?"bg-status-error/20 text-status-error border-status-error/40 hover:bg-status-error/30":"";return Fs.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:"var(--z-modal)"},onClick:o,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:u=>u.stopPropagation(),children:[s.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),s.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:t}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.jsx("button",{onClick:o,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:i("common.cancel")}),s.jsx("button",{onClick:r,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,style:a==="amber"?{background:"color-mix(in srgb, var(--status-warning) 20%, transparent)",color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"}:void 0,children:n})]})]})}),document.body)}function tj(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),a=[...jC,...NC,...AC].find(r=>r.id===t||t.includes(r.id)||r.id.includes(t));return a?{icon:a.icon,name:a.name}:{icon:"📝",name:e}}function sj({ide:e,allIdes:t,sendDaemonCommand:n,onDisconnect:a,onRevokeToken:r}){var L,R;const{t:o}=Ce("common"),[i,c]=l.useState("idle"),[u,p]=l.useState(""),[d,m]=l.useState(null),[h,g]=l.useState("idle"),[k,f]=l.useState(""),x=e.version||null,w=((L=e.machine)==null?void 0:L.platform)||((R=e.system)==null?void 0:R.platform)||"",b=rs(e,{fallbackId:e.id}),S=w==="win32"?"🪟":w==="darwin"?"🍎":"🐧",N=t.filter(F=>F.daemonId===e.id&&F.transport==="cdp-page"),v=t.filter(F=>F.daemonId===e.id&&F.transport==="pty"),y=t.filter(F=>F.daemonId===e.id&&F.transport==="acp"),j=e.p2p,C=async()=>{if(!n)return;const F=ao(e);if(!F){c("error"),p(Nm);return}c("upgrading"),p(o("machine.connectedMachines.startingUpgrade"));try{const E=ZC(await n(e.id,"daemon_upgrade",F));E.alreadyLatest?(c("done"),p(`Already on v${E.version||"latest"}.`)):E.upgraded||E.success?(c("done"),p(`Upgrade to v${E.version||"latest"} started. Daemon is restarting...`)):(c("error"),p(E.error||"Upgrade failed"))}catch(E){c("error"),p(Eo(E,"Connection lost during upgrade"))}},A=async()=>{if(m(null),!!a){g("loading");try{await a(e.id),g("done"),f(o("machine.connectedMachines.machineDisconnected"))}catch(F){g("error"),f(Eo(F,o("machine.connectedMachines.failedToDisconnect")))}}},T=async()=>{if(m(null),!!r){g("loading");try{await r(e.id),g("done"),f(o("machine.connectedMachines.tokenRevoked"))}catch(F){g("error"),f(Eo(F,o("machine.connectedMachines.failedToRevokeToken")))}}},D="1.0.41",I=qs(e,D),M=no(e,I),P=wa(e,I),$=N.length+v.length+y.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xl",children:S}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:b}),s.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[s.jsxs("span",{children:[e.id.substring(0,12),"…"]}),x&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${M?"":"bg-bg-secondary"}`,style:M?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",x,!M&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[n&&M&&s.jsx("button",{onClick:C,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${D}`,children:i==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," ",o("machine.connectedMachines.upgrading")]}):i==="done"?o("machine.connectedMachines.updated"):P?o("machine.connectedMachines.updateNow"):o("machine.connectedMachines.updateTo",{version:D})}),a&&s.jsx("button",{onClick:()=>m("disconnect"),disabled:h==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:o("machine.connectedMachines.disconnect")}),r&&s.jsx("button",{onClick:()=>m("revoke"),disabled:h==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:o("machine.connectedMachines.remove")}),s.jsx(VC,{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:[j&&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 ${j.state==="connected"?"bg-status-online":"bg-text-muted/30"} ${j.state==="connecting"||j.state==="new"?"animate-pulse":""}`,style:j.state==="connecting"||j.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",j.state==="connected"?"connected":j.state==="connecting"||j.state==="new"?o("machine.connectedMachines.connecting"):j.state||"off"]}),j.peers!==void 0&&j.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",j.peers," peer",j.peers!==1?"s":"",")"]})]}),j&&$>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),$>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[N.map(F=>{const E=tj(F.type),H=F.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:E.icon}),s.jsx("span",{children:E.name}),H!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${H?"bg-status-online":"animate-pulse"}`,style:H?void 0:{background:"var(--status-warning)"},title:o(H?"machine.connectedMachines.cdpConnected":"machine.connectedMachines.cdpConnecting")})]},F.id)}),v.map(F=>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:F.cliName||"CLI"})]},F.id)),y.map(F=>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:F.cliName||"ACP"})]},F.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:o("machine.connectedMachines.noIdesConnected")})]}),(u||k)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||h==="error"?"text-status-error":i==="done"||h==="done"?"text-status-online":"text-text-muted"}`,children:k||u})]}),d==="disconnect"&&s.jsx(dd,{title:o("machine.connectedMachines.disconnectTitle"),message:`Disconnect "${b}" from ADHDev?
|
|
58
|
+
`).includes(r)))}function aC(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 lm(e,t={}){return aC(nC(e,t),t.sortMode||"recent")}function Fi(e,t){return typeof e=="function"?e(t??!1?"launch.resumeSavedHistory":"launch.startFresh"):e?"Resume saved history":"Start fresh"}function cm(e,t){return typeof e=="function"?e(t??!1?"launch.resumingSavedHistory":"launch.startingFresh"):e?"Resuming saved history…":"Starting fresh…"}function rC(e){return e?e("launch.startFresh"):"Start fresh"}function oC(e){return e?e("launch.hostedRuntimeRecoveryDescription"):"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function iC(e){return e?e("launch.openSavedHistory"):"Open saved history"}function lC(e){return e?e("launch.savedHistoryTitle"):"Saved History"}function Al(e){return e?e("launch.savedHistoryHelper"):"Use saved history when you want continuity in the same provider conversation."}function cC(e){return e?e("launch.savedHistoryEmpty"):"No saved history found yet."}function dC(e){return e?e("launch.refreshSavedHistory"):"Refresh saved history"}function uC(e){return e?e("launch.refreshingSavedHistory"):"Refreshing saved history…"}function Ir(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 Lr(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 Rr(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartFresh":"launch.confirmRestart"):e==="start-fresh"?"Start fresh":"Restart"}function Er(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartingFresh":"launch.confirmRestarting"):e==="start-fresh"?"Starting fresh…":"Restarting…"}function dm(e,t){return typeof e=="function"?e("launch.resumeWith",{label:t}):`Resume saved history with ${e}?`}function um(e){return e?e("launch.resumeReview"):"Review or change the target workspace before resuming saved history."}function nd(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 pm({activeConv:e,ides:t,isCreatingChat:n,isRefreshingHistory:a,savedSessions:r=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:c,missingWorkspaceResumePath:u,onSavedHistoryFiltersChange:p,onClose:d,onNewChat:m,onSwitchSession:h,onRefreshHistory:g,onResumeSavedSession:k}){var P;const{t:f}=Ce("common"),x=t.find($=>$.id===e.routeId),w=(x==null?void 0:x.chats)||[],b=(P=x==null?void 0:x.activeChat)==null?void 0:P.id,S=ft(e)&&!pt(e),[N,v]=l.useState(()=>Ut()),[y,j]=l.useState(null),C=c||N,A=String(u||"").trim(),T=$=>{if(p){p($);return}v($)},D=l.useMemo(()=>r.map($=>{const L=String($.workspace||"").trim();return $.canResume||L||!A?$:{...$,workspace:A,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[A,r]),I=l.useMemo(()=>lm(D,{textQuery:C.textQuery,workspaceQuery:C.workspaceQuery,modelQuery:C.modelQuery,resumableOnly:C.resumableOnly,sortMode:C.sortMode}),[D,C.modelQuery,C.resumableOnly,C.sortMode,C.textQuery,C.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:d,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:S?lC(f):f("historyModal.chatHistory")}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:PS(e)}),S&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Al(f)})]}),s.jsx("button",{onClick:d,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(Pt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!S&&s.jsx("button",{onClick:m,disabled:n,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:f(n?"historyModal.creating":"historyModal.startNewChat")}),S?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:C.textQuery,onChange:$=>T({...C,textQuery:$.target.value}),placeholder:f("historyModal.searchPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:C.workspaceQuery,onChange:$=>T({...C,workspaceQuery:$.target.value}),placeholder:f("historyModal.filterWorkspace"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:C.modelQuery,onChange:$=>T({...C,modelQuery:$.target.value}),placeholder:f("historyModal.filterModel"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsxs("select",{value:C.sortMode,onChange:$=>T({...C,sortMode:$.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:f("historyModal.sortRecent")}),s.jsx("option",{value:"oldest",children:f("historyModal.sortOldest")}),s.jsx("option",{value:"messages",children:f("historyModal.sortMessages")})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:C.resumableOnly,onChange:$=>T({...C,resumableOnly:$.target.checked})}),f("historyModal.resumeReadyOnly")]})]}),I.map($=>{const L=e.providerSessionId===$.providerSessionId,R=L||!$.canResume||!!i,F=$.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{R||!k||j({kind:"saved",session:$})},disabled:R,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${L?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${R?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${L?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:$.title||f("historyModal.untitledSession")}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:$.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:nd($.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:$.preview||f("historyModal.noSavedPreview")}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[$.workspace||f("historyModal.workspaceUnknown"),F?f("historyModal.selectedWorkspaceSuffix"):"",xn($.summaryMetadata)?` · ${xn($.summaryMetadata)}`:"",$.messageCount>0?` · ${f("historyModal.msgCount",{count:$.messageCount})}`:""]}),s.jsx("div",{className:"shrink-0",children:L?f("historyModal.statusActive"):$.canResume?F?f("historyModal.statusResumeSelectedWorkspace"):i===$.providerSessionId?f("historyModal.statusResuming"):f("historyModal.statusResume"):f("historyModal.statusMissingWorkspace")})]})]},$.id)})]}):w.map($=>s.jsxs("div",{onClick:()=>{$.id!==b&&j({kind:"chat",id:$.id,title:$.title||f("historyModal.untitledSession")})},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${b===$.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[s.jsx("div",{className:`font-bold text-sm mb-1 ${b===$.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:$.title||f("historyModal.untitledSession")}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[$.id.substring(0,12),"..."]}),b===$.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:f("historyModal.statusActive")})]})]},$.id)),(S&&!o&&I.length===0||!S&&w.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(Mb,{size:32})}),s.jsx("div",{className:"text-[13px]",children:S?r.length>0?f("historyModal.noMatchingHistory"):cC(f):f("historyModal.noRecentChats")})]}),S&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:uC(f)})})]}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:s.jsx("button",{onClick:g,disabled:a||o,className:"btn btn-secondary btn-sm rounded-[10px]",children:a||o?f("historyModal.refreshing"):s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(zr,{size:13})," ",S?dC(f):f("historyModal.refreshHistory")]})})})]}),y&&s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center p-4",children:[s.jsx("div",{onClick:()=>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:f("historyModal.confirmSwitchTitle")}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:f("historyModal.confirmSwitchDescription",{target:y.kind==="chat"?y.title:y.session.title||f("historyModal.untitledSession")})}),y.kind==="saved"&&s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted font-mono truncate",children:[y.session.workspace||f("historyModal.workspaceUnknown"),y.session.lastMessageAt?` · ${nd(y.session.lastMessageAt)}`:""]})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[s.jsx("button",{onClick:()=>{const $=y;j(null),$.kind==="chat"?(h(e.routeId,$.id),d()):k&&k($.session)},className:"btn btn-primary w-full justify-center min-h-[42px]",children:f("historyModal.confirmSwitchAction")}),s.jsx("button",{onClick:()=>j(null),className:"btn btn-secondary w-full justify-center min-h-[42px]",children:f("common.cancel")})]})]})]})]});return typeof document>"u"?M:Fs.createPortal(M,document.body)}const ad={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 mm({toasts:e,onDismiss:t,onClickToast:n}){const{t:a}=Ce();return s.jsx("div",{className:"fixed right-4 top-[calc(env(safe-area-inset-top,0px)+64px)] z-[var(--z-toast)] flex flex-col gap-2 pointer-events-none sm:top-[calc(env(safe-area-inset-top,0px)+16px)]",children:e.map(r=>{const o=ad[r.type]||ad.info;return s.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var i;(i=r.actions)!=null&&i.length||n&&n(r)},children:[s.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${o.accent}, color-mix(in srgb, ${o.accent} 55%, transparent))`}}),s.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:i=>{i.stopPropagation(),t(r.id)},"aria-label":a("toast.dismiss"),children:s.jsx(Pt,{size:14})}),s.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[s.jsx("div",{className:"flex items-center gap-2 pr-8",children:s.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:o.chipBg,color:o.chipText,border:`1px solid color-mix(in srgb, ${o.accent} 22%, transparent)`},children:a(o.labelKey)})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:r.message}),r.actions&&r.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:r.actions.map((i,c)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:i.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:u=>{u.stopPropagation(),i.onClick(),t(r.id)},children:i.label},c))})]})]},r.id)})})}const pC=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function mC(e){const t=e.workspace||"";if(!t)return"";const n=t.split(/[/\\]/).filter(Boolean);return n.length>0?n[n.length-1]:t}function hC(e,t){return hm(e)||t}function hm(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 fC(e){return hm(e)||void 0}function bC(e){return e.sessionId||e.instanceId||e.agentType}function fm(e=[]){const t={};for(const n of e)n.type==="adhdev-daemon"&&(t[n.id]=rs(n,{fallbackId:n.id}));return t}function bm(e,t={}){var a;const n=e.daemonId||((a=e.id)==null?void 0:a.split(":")[0])||e.id;return{machineName:Tw(e,t.machineNames),connectionState:t.connectionStates?t.connectionStates[n]||t.defaultConnectionState||"new":t.defaultConnectionState}}function Tl(e,t={}){return gC(e,bm(e,t))}function gC(e,t={}){var h,g,k,f,x,w,b,S,N;const n=[],a=t.machineName,r=t.connectionState,o=mC(e),i=e.workspace||"",c=Rw(e.type,{agentName:e.cliName}),u=ft(e)||pt(e)?c:Bt(e.type),p=hC(e,u),d=Array.isArray(e.childSessions)?e.childSessions.map(v=>{var y,j,C;return{sessionId:v.id,instanceId:v.id,providerSessionId:v.providerSessionId,activeChatId:(y=v.activeChat)==null?void 0:y.id,transport:v.transport,sessionCapabilities:v.capabilities,agentType:v.providerType,agentName:v.providerName||Bt(v.providerType),model:fC(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:((C=v.activeChat)==null?void 0:C.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=pC(e);if(m){const v=e.sessionId||e.instanceId,y=(h=e.settings)==null?void 0:h.meshCoordinatorFor,j=((g=e.settings)==null?void 0:g.meshNodeFor)||!((k=e.settings)!=null&&k.meshCoordinatorFor)&&((f=e.settings)==null?void 0:f.launchedByCoordinator),C=y?" (Coordinator)":j?" (Mesh Node)":"",A=c+C,T=(x=e.activeChat)==null?void 0:x.activeModal,D=T&&Array.isArray(T.buttons)&&T.buttons.length>0,I=Ew(e.activeChat,[{status:e.status,activeModal:(w=e.activeChat)==null?void 0:w.activeModal}],e.agents||[]),M=e.activeChat||{title:"",messages:[]};let P=M.title&&String(M.title).trim()?String(M.title).trim():"";const $=(b=e.activeChat)==null?void 0:b.id,L=e.chats;if($&&Array.isArray(L)&&L.length>0){const K=L.find(V=>V.id===$||V.id&&String(V.id)===String($));K!=null&&K.title&&String(K.title).trim()&&(P=String(K.title).trim())}const R=(ft(e)||pt(e),e.type),F=(ft(e)||pt(e))&&Nc(P,A,R)?"":P,E=M.messages||[],H=typeof $=="string"?$.trim():"",_=(ft(e)||pt(e))&&H===String(e.type||"").trim(),G=H&&!_?H:e.providerSessionId,W=e.coordinator||(typeof((S=e.settings)==null?void 0:S.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:v,providerSessionId:e.providerSessionId,historySessionId:G,nativeSessionId:v,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:ft(e)&&e.mode||"chat",agentName:A,agentType:R,status:I,title:F,messages:E,resume:e.resume,hostIdeType:!ft(e)&&!pt(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||F||(ft(e)?e.mode==="chat"?A:`Terminal${C}`: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:D?T.buttons:void 0,modalMessage:D?T.message:void 0,streamSource:"native",tabKey:So(v,e.id),machineName:a,connectionState:r,settings:e.settings,coordinator:W,messageInput:e.messageInput})}if(m&&(ft(e)||pt(e)))return n;for(const v of d){const y=v.activeModal&&Array.isArray(v.activeModal.buttons)&&v.activeModal.buttons.length>0,j=_w(v),C=bC(v),A=`${e.id}:${C}`,T=v.title&&String(v.title).trim()||"",D=Nc(T,v.agentName,v.agentType)?"":T,I=v.messages||[];if(!(v.transport==="cdp-webview"||!!v.sessionId||!!v.providerSessionId||I.length>0||y||!!D||!["idle","panel_hidden","disconnected","not_monitored"].includes(j)))continue;const P=v.coordinator||(typeof((N=v.settings)==null?void 0:N.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:D,messages:I,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:v.git||e.git,displayPrimary:o||D||v.agentName||u,displaySecondary:v.model&&v.model.trim()?v.model.trim():`${u} · ${v.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,lastUpdated:v.lastUpdated||e.lastUpdated,inboxBucket:v.inboxBucket,completionMarker:v.completionMarker,modalButtons:y?v.activeModal.buttons:void 0,modalMessage:y?v.activeModal.message:void 0,streamSource:"agent-stream",tabKey:So(v.sessionId||v.instanceId,A),machineName:a,connectionState:r,settings:v.settings,coordinator:P,messageInput:v.messageInput})}return n.length===0&&n.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:c,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||u,displaySecondary:p,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:So(e.sessionId||e.instanceId,e.id),connectionState:r,settings:e.settings,messageInput:e.messageInput}),n}function gm(e){return String(e.type||e.id||"").trim()}function _r(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()).map(t=>t.trim()):[]}function xC(e,t){const n=(t||"").trim();if(!n)return[];const a=(e||[]).find(r=>r.type===n);return _r(a==null?void 0:a.modelOptions)}function vC(e,t){const n=(t||"").trim();if(!n)return[];const a=(e||[]).find(r=>r.type===n);return _r(a==null?void 0:a.thinkingLevelOptions)}function xm(e){const t=new Map;for(const n of e||[])n!=null&&n.type&&t.set(n.type,{models:_r(n.modelOptions),thinking:_r(n.thinkingLevelOptions)});return t}function yC(e){var t;return e.category!=="cli"||!gm(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 Un(e){var a;const t=new Set,n=[];for(const r of e||[]){if(!yC(r))continue;const o=gm(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 qn(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 Pa(e){return e.map(t=>t.type)}function wC(e,t){const n=qn(e),a=t.trim();return!a||n.includes(a)?n:[...n,a]}function kC(e,t){return qn(e).filter(n=>n!==t)}function rd(e,t,n){const a=qn(e),r=a.indexOf(t);if(r<0)return a;const o=a.filter(c=>c!==t);if(n==="top")return[t,...o];if(n==="bottom")return[...o,t];const i=n==="up"?Math.max(0,r-1):Math.min(o.length,r+1);return o.splice(i,0,t),o}function od({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 SC({value:e,availableProviders:t,onChange:n,disabled:a=!1,saveButton:r}){const{t:o}=Ce("common"),[i,c]=l.useState(""),u=l.useMemo(()=>new Map(t.map(g=>[g.type,g])),[t]),p=l.useMemo(()=>qn(e),[e]),d=p.filter(g=>!u.has(g)).length,m=t.filter(g=>!p.includes(g.type)),h=()=>{i&&(n(wC(p,i)),c(""))};return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[s.jsx("div",{className:"flex flex-col gap-2",children:p.length===0?s.jsx("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:"No provider priority configured. Launches without an explicit CLI provider will fail closed."}):p.map((g,k)=>{const f=u.get(g),x=!!f;return s.jsxs("div",{className:`flex flex-col gap-2 rounded-md border border-border-subtle px-3 py-2 sm:flex-row sm:items-center sm:justify-between ${x?"bg-bg-primary":"bg-bg-primary/40"}`,children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("span",{className:"text-[10px] font-semibold text-text-muted",children:["#",k+1]}),(f==null?void 0:f.icon)&&s.jsx("span",{"aria-hidden":"true",children:f.icon}),s.jsx("span",{className:`font-mono text-[12px] ${x?"text-text-primary":"text-text-muted"}`,children:g}),x?s.jsx("span",{className:"rounded border border-green-500/20 bg-green-500/10 px-1.5 py-px text-[9px] font-semibold text-green-400",children:o("settings.providerPriority.available")}):s.jsx("span",{className:"rounded border border-amber-500/25 bg-amber-500/10 px-1.5 py-px text-[9px] font-semibold text-amber-400",children:o("settings.providerPriority.notOnMachine")})]}),s.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:f?`${f.label} · ${f.statusLabel}`:"Kept in order; skipped at launch until detected here."})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move up",disabled:a||k===0,title:"Move up",onClick:()=>n(rd(p,g,"up")),children:s.jsx(od,{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(rd(p,g,"down")),children:s.jsx(od,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:a,onClick:()=>n(kC(p,g)),children:o("settings.providerPriority.remove")})]})]},g)})}),s.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-end",children:[s.jsxs("label",{className:"flex-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"mb-1 block font-medium text-text-primary",children:o("settings.providerPriority.addCliLabel")}),s.jsxs("select",{className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-sm text-text-primary",value:i,onChange:g=>c(g.target.value),disabled:a||m.length===0,children:[s.jsx("option",{value:"",children:m.length?"Select provider…":"No additional detected CLI providers"}),m.map(g=>s.jsxs("option",{value:g.type,children:[g.label," (",g.type,")"]},g.type))]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:a||!i,onClick:h,children:o("settings.providerPriority.addProvider")}),r]}),s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:["Launches use this order, top to bottom.",d>0?` ${d} provider${d===1?"":"s"} not detected here — kept in order, skipped until available.`:""]})]})}function CC(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 vm(e,t){const n=CC(e);return{daemonId:n.daemonId,payload:{...t,...n.targetSessionId&&!t.targetSessionId?{targetSessionId:n.targetSessionId}:{}}}}const ym=[{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:"🏄"}],wm=[{id:"antigravity-cli",name:"Antigravity CLI",icon:"🪐"},{id:"claude-cli",name:"Claude Code",icon:"🟠"},{id:"codex-cli",name:"Codex CLI",icon:"📦"},{id:"cursor-cli",name:"Cursor CLI",icon:"⚡"},{id:"hermes-cli",name:"Hermes",icon:"⚕️"},{id:"kimi",name:"Kimi",icon:"🌙"},{id:"opencode",name:"OpenCode CLI",icon:"◆"}],km=[{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:"🟠"}],jC=ym,NC=wm,AC=km;function TC({icon:e,title:t,subtitle:n,badge:a,actions:r,className:o}){return s.jsxs("div",{className:Wt("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 Fa({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(TC,{icon:e,title:t,subtitle:n,badge:a,actions:r}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Wt("mx-auto flex w-full flex-col gap-4",o,i),children:c})})]})}const Bi="adhdev:themechange";function MC(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function Pn(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function In(e){return e==="system"?MC():e}function Sm(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function hr(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(Bi,{detail:{preference:e,theme:t}}))}function DC(){const e=Pn(),t=In(e);Sm(t),hr(e,t)}function en(){const[e,t]=l.useState(Pn),[n,a]=l.useState(()=>In(Pn()));l.useEffect(()=>{Sm(n)},[n]),l.useEffect(()=>{const i=window.matchMedia("(prefers-color-scheme: light)"),c=u=>{if(e==="system"){const p=u.matches?"light":"dark";a(p),hr("system",p)}};return i.addEventListener("change",c),()=>i.removeEventListener("change",c)},[e]),l.useEffect(()=>{const i=u=>{const p=u.detail||{},d=p.preference,m=p.theme;t(d==="dark"||d==="light"||d==="system"?d:Pn()),a(m==="dark"||m==="light"?m:In(Pn()))},c=u=>{if(u.key!=="theme")return;const p=Pn(),d=In(p);t(p),a(d)};return window.addEventListener(Bi,i),window.addEventListener("storage",c),()=>{window.removeEventListener(Bi,i),window.removeEventListener("storage",c)}},[]);const r=l.useCallback(i=>{const c=In(i);t(i),a(c);try{localStorage.setItem("theme",i)}catch{}hr(i,c)},[]),o=l.useCallback(()=>{t(i=>{const c=i==="dark"?"light":i==="light"?"system":"dark",u=In(c);a(u);try{localStorage.setItem("theme",c)}catch{}return hr(c,u),c})},[]);return{theme:n,preference:e,setPreference:r,cycleTheme:o,isDark:n==="dark"}}const id={dark:"Dark",light:"Light",system:"System"};function PC({collapsed:e}){const{preference:t,cycleTheme:n}=en(),a=t==="dark"?s.jsx(Pb,{size:16}):t==="light"?s.jsx(Db,{size:16}):s.jsx(Ib,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:n,title:`Theme: ${id[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:a}),!e&&s.jsx("span",{className:"text-xs",children:id[t]})]})}const Wi="adhdev:langchange";function IC(){const e=St.language;return Rn(e)?e:op()}function LC(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(Wi,{detail:{language:e}}))}function RC(){const[e,t]=l.useState(IC);l.useEffect(()=>{const a=i=>{Rn(i)&&t(i)},r=i=>{const c=i.detail||{};Rn(c.language)&&t(c.language)},o=i=>{if(i.key!==ji)return;const c=i.newValue;Rn(c)&&c!==St.language&&(St.changeLanguage(c),Ni(c))};return St.on("languageChanged",a),window.addEventListener(Wi,r),window.addEventListener("storage",o),()=>{St.off("languageChanged",a),window.removeEventListener(Wi,r),window.removeEventListener("storage",o)}},[]);const n=l.useCallback(a=>{if(Rn(a)){t(a);try{localStorage.setItem(ji,a)}catch{}St.changeLanguage(a),Ni(a),LC(a)}},[]);return{language:e,setLanguage:n}}function EC({trigger:e,viewport:t,menu:n,variant:a,gap:r=6,margin:o=8}){const i=e.top-o,c=t.height-e.bottom-o,u=a==="sidebar";let p=u;u&&i<n.height&&c>i&&(p=!1),!u&&c<n.height&&i>c&&(p=!0);const d=p?i:c,m=Math.max(80,Math.min(n.height,d));let h;p?h=e.top-r-m:h=e.bottom+r,h=ld(h,o,Math.max(o,t.height-m-o));const g=ld(e.left,o,Math.max(o,t.width-n.width-o));return{top:h,left:g,maxHeight:m}}function ld(e,t,n){return Math.min(Math.max(e,t),n)}function _C({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 HC({collapsed:e,variant:t="sidebar"}){const{language:n,setLanguage:a}=RC(),{t:r}=Ce("common"),[o,i]=l.useState(!1),[c,u]=l.useState(0),p=l.useRef(null),d=l.useRef(null),m=l.useRef(null),h=l.useId(),[g,k]=l.useState(null),f=l.useCallback(()=>{const I=d.current;if(!I)return;const M=I.getBoundingClientRect(),P=m.current,$=Math.max((P==null?void 0:P.offsetWidth)??0,168),L=(P==null?void 0:P.scrollHeight)??sn.length*36+12;k(EC({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:$,height:L},variant:t}))},[t]),x=Math.max(0,sn.findIndex(I=>I.code===n)),w=sn[x]??sn[0],b=r("language.label",{defaultValue:"Language"}),S=r("language.select",{defaultValue:"Select language"}),N=I=>`${h}-opt-${I}`,v=l.useCallback(()=>{u(x),i(!0)},[x]),y=l.useCallback((I=!0)=>{var M;i(!1),I&&((M=d.current)==null||M.focus())},[]),j=l.useCallback(I=>{const M=sn[I];M&&a(M.code),y()},[a,y]);l.useEffect(()=>{if(!o)return;const I=$=>{var L,R;return!!((L=p.current)!=null&&L.contains($)||(R=m.current)!=null&&R.contains($))},M=$=>{I($.target)||i(!1)},P=$=>{I($.target)||i(!1)};return document.addEventListener("pointerdown",M,!0),document.addEventListener("focusin",P,!0),()=>{document.removeEventListener("pointerdown",M,!0),document.removeEventListener("focusin",P,!0)}},[o]),l.useLayoutEffect(()=>{if(!o){k(null);return}f();const I=()=>f();return window.addEventListener("resize",I),window.addEventListener("scroll",I,!0),()=>{window.removeEventListener("resize",I),window.removeEventListener("scroll",I,!0)}},[o,f]),l.useEffect(()=>{var I;o&&g&&((I=m.current)==null||I.focus())},[o,g]);const C=I=>{const M=sn.length-1;switch(I.key){case"ArrowDown":I.preventDefault(),u(P=>P>=M?0:P+1);break;case"ArrowUp":I.preventDefault(),u(P=>P<=0?M:P-1);break;case"Home":I.preventDefault(),u(0);break;case"End":I.preventDefault(),u(M);break;case"Enter":case" ":I.preventDefault(),j(c);break;case"Escape":I.preventDefault(),y();break;case"Tab":i(!1);break}},A=I=>{o||(I.key==="ArrowDown"||I.key==="ArrowUp"||I.key==="Enter"||I.key===" ")&&(I.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":""}`,D=t==="landing"||!e;return s.jsxs("div",{ref:p,className:"lang-switch",children:[s.jsxs("button",{ref:d,type:"button",className:T,"aria-haspopup":"listbox","aria-expanded":o,"aria-label":`${b}: ${w.label}`,title:`${b}: ${w.label}`,onClick:()=>o?y(!1):v(),onKeyDown:A,children:[s.jsx("span",{className:"nav-icon lang-switch-icon",children:s.jsx(Wb,{size:16})}),D&&s.jsx("span",{className:"lang-switch-label text-xs",children:w.label}),D&&s.jsx(_C,{open:o})]}),o&&typeof document<"u"&&Fs.createPortal(s.jsx("ul",{ref:m,role:"listbox",tabIndex:-1,"aria-label":S,"aria-activedescendant":N(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:C,children:sn.map((I,M)=>{const P=I.code===w.code,$=M===c;return s.jsxs("li",{id:N(M),role:"option","aria-selected":P,className:`lang-switch-option${$?" is-active":""}${P?" is-selected":""}`,onMouseEnter:()=>u(M),onClick:()=>j(M),children:[s.jsx("span",{className:"lang-switch-check","aria-hidden":"true",children:P?s.jsx(Bu,{size:14}):null}),s.jsx("span",{className:"lang-switch-option-label",children:I.label})]},I.code)})}),document.body)]})}const $C=[],FC=[];function Lo(e,t){return e?typeof e=="function"?e(t):e:null}const BC=l.memo(function({renderState:t,brand:n,navItems:a,sidebarSections:r,footerItems:o,footerInfo:i,footerActions:c,closeMobileMenu:u}){const{t:p}=Ce("common"),{collapsed:d,mobileMenuOpen:m}=t,h=k=>`nav-item${k.active?" active":""} cursor-pointer ${d?"justify-center py-2.5 px-0":""}${k.className?` ${k.className}`:""}`,g=k=>s.jsxs("div",{className:h(k),id:`nav-${k.id}`,onClick:()=>{k.onSelect(),u()},title:d?k.title??(typeof k.label=="string"?k.label:void 0):k.title,children:[s.jsx("span",{className:"nav-icon",children:k.icon}),!d&&k.label]},k.id);return s.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${d?"justify-center gap-0":""}`,children:Lo(n,t)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":p("app.closeMenu"),onClick:u,children:s.jsx(Pt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:a.map(g)}),r.map(k=>s.jsxs("div",{className:k.className??"border-t border-border-subtle pt-2 mt-2",children:[!d&&k.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:k.title}):null,k.items.map(g)]},k.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[o.map(g),Lo(i,t),s.jsx(PC,{collapsed:d}),s.jsx(HC,{collapsed:d}),Lo(c,t)]})]})});function WC({children:e,brand:t,navItems:n,sidebarSections:a=$C,footerItems:r=FC,footerInfo:o,footerActions:i,preMainContent:c,collapsedStorageKey:u="sidebar-collapsed"}){const{t:p}=Ce("common"),[d,m]=l.useState(!1),[h,g]=l.useState(()=>{try{return localStorage.getItem(u)==="1"}catch{return!1}}),k=l.useCallback(()=>m(!0),[]),f=l.useCallback(()=>m(!1),[]),x=l.useCallback(()=>{g(b=>{const S=!b;try{localStorage.setItem(u,S?"1":"0")}catch{}return S})},[u]),w=l.useMemo(()=>({collapsed:h,mobileMenuOpen:d,openMobileMenu:k,closeMobileMenu:f,toggleCollapsed:x}),[h,d,k,f,x]);return s.jsxs("div",{className:`app-layout${d?" mobile-menu-open":""}${h?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":p("app.openMenu"),onClick:k,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),d&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":p("app.closeMenu"),onClick:f,onKeyDown:b=>b.key==="Escape"&&f()}),s.jsx(BC,{renderState:w,brand:t,navItems:n,sidebarSections:a,footerItems:r,footerInfo:o,footerActions:i,closeMobileMenu:f}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function gt({title:e,icon:t,description:n,accentColor:a,className:r,collapsible:o,defaultOpen:i=!0,badge:c,children:u}){const[p,d]=l.useState(i),m=o?p:!0,h=(e||n)&&s.jsxs("div",{className:Wt("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:Wt("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:Wt("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",a&&"border-l-[3px]",r),style:a?{borderLeftColor:a}:void 0,children:[o&&h?s.jsx("button",{type:"button",className:"w-full bg-transparent border-none p-0 text-left cursor-pointer",onClick:()=>d(g=>!g),"aria-expanded":m,children:h}):h,m&&u]})}function so({icon:e,title:t,description:n,action:a,className:r}){return s.jsxs("div",{className:Wt("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 OC={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"},UC={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Dt({variant:e,children:t,onDismiss:n,className:a}){return s.jsxs("div",{className:Wt("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",OC[e],a),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:UC[e]}),s.jsx("span",{children:t})]}),n&&s.jsx("button",{onClick:n,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}function Nt({label:e,hint:t,children:n,className:a}){return s.jsxs("div",{className:Wt("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 ps(e){const{className:t,...n}=e;return s.jsx("input",{...n,className:Wt("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 qC={primary:"btn-primary",secondary:"btn-secondary",warning:"btn-warning",danger:"btn-danger",ghost:"btn-ghost"},Hs=l.forwardRef(function({variant:t="secondary",size:n="md",type:a,className:r,...o},i){return s.jsx("button",{ref:i,type:a??"button",className:Wt("btn",qC[t],n==="sm"&&"btn-sm",r),...o})}),GC=l.forwardRef(function({options:t,children:n,className:a,...r},o){return s.jsx("select",{ref:o,className:Wt("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)))})}),zC={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"},KC={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function VC({status:e,label:t,className:n}){const a=t||e;return s.jsxs("span",{className:Wt("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",zC[e],n),children:[s.jsx("span",{className:Wt("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",KC[e])}),a]})}function ln({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 YC({onPrefChange:e}){const{t}=Ce("common"),[n,a]=zw(),[r,o]=l.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);l.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){o("unsupported");return}o(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,u)=>{a({[c]:u}),e==null||e(c,u)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(ln,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Vn,{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(ln,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(gs,{size:15})," ",t("notifications.browserNotificationsLabel")]}),description:t("notifications.browserNotificationsDesc"),checked:n.browserNotifications,onChange:c=>i("browserNotifications",c)}),n.globalEnabled&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:t("notifications.standaloneBackgroundInfo")}),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:()=>{gp().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(ln,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Gu,{size:15})," ",t("notifications.completionAlertsLabel")]}),description:t("notifications.completionAlertsDesc"),checked:n.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(ln,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Lb,{size:15})," ",t("notifications.approvalAlertsLabel")]}),description:t("notifications.approvalAlertsDesc"),checked:n.approvalAlert,onChange:c=>i("approvalAlert",c)}),s.jsx(ln,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Na,{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 Hr(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 cd(e){var t;return((t=Hr(e))==null?void 0:t.base)??null}function Cm(e,t){const n=Hr(e),a=Hr(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 no(e,t){const n=e.version||null;return!n||!t||e.versionMismatch===!0&&!Hr(t)?!1:Cm(n,t)}function wa(e,t){if(e.versionUpdateRequired===!0)return!0;const n=e.version||null;if(!n||!t||!Cm(n,t))return!1;const a=cd(n),r=cd(t);return!a||!r?!1:a[0]!==r[0]||a[1]!==r[1]}function Ro(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 QC(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 ha(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function Ml(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},n=Ro(t.channel)||Ro(e.updateChannel)||Ro(e.releaseChannel)||void 0,a=QC(t.npmTag)||(n==="preview"?"next":n==="stable"?"latest":void 0),r=ha(t.targetVersion)||ha(e.serverVersion)||void 0,o=ha(t.minVersion)||void 0,i=ha(t.updateCommand)||(n?"adhdev update":void 0);return{...n?{channel:n}:{},...a?{npmTag:a}:{},...r?{targetVersion:r}:{},...o?{minVersion:o}:{},...i?{updateCommand:i}:{}}}function qs(e,t=null){return Ml(e).targetVersion||t}function JC(e){return Ml(e).channel||null}function ao(e){return!e||!Ml(e).channel?null:{}}function jm(e,t={}){const n=ha(t.targetVersion);return n?`Update to v${n}`:t.fallback||(t.required?"Update now":"Upgrade")}const Nm="Cannot update: node update policy unavailable; refresh and try again";async function XC(e,t,n){var r,o,i,c,u,p;const a=ao(n);if(!a)return{state:"error",message:Nm};try{const d=await e(t,"daemon_upgrade",a);return(r=d==null?void 0:d.result)!=null&&r.alreadyLatest?{state:"done",message:`Already on v${((o=d==null?void 0:d.result)==null?void 0:o.version)||"latest"}.`}:(i=d==null?void 0:d.result)!=null&&i.upgraded||(c=d==null?void 0:d.result)!=null&&c.success?{state:"done",message:`Upgrade to v${((u=d==null?void 0:d.result)==null?void 0:u.version)||"latest"} started. Daemon is restarting…`}:{state:"error",message:((p=d==null?void 0:d.result)==null?void 0:p.error)||"Upgrade failed"}}catch(d){return{state:"error",message:d instanceof Error?d.message:"Upgrade failed"}}}function ZC(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Eo(e,t){return e instanceof Error?e.message:t}function ej({ides:e,emptyMessage:t,sendDaemonCommand:n,onDisconnect:a,onRevokeToken:r}){const{t:o}=Ce("common"),i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?s.jsx(so,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:o("machine.connectedMachines.noMachines"),description:t||o("machine.connectedMachines.defaultDescription")}):s.jsx("div",{className:"flex flex-col gap-2",children:i.map(c=>s.jsx(sj,{ide:c,allIdes:e,sendDaemonCommand:n,onDisconnect:a,onRevokeToken:r},c.id))})}function dd({title:e,message:t,confirmLabel:n,confirmColor:a,onConfirm:r,onCancel:o}){const{t:i}=Ce("common"),c=a==="red"?"bg-status-error/20 text-status-error border-status-error/40 hover:bg-status-error/30":"";return Fs.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:"var(--z-modal)"},onClick:o,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:u=>u.stopPropagation(),children:[s.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),s.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:t}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.jsx("button",{onClick:o,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:i("common.cancel")}),s.jsx("button",{onClick:r,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,style:a==="amber"?{background:"color-mix(in srgb, var(--status-warning) 20%, transparent)",color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"}:void 0,children:n})]})]})}),document.body)}function tj(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),a=[...jC,...NC,...AC].find(r=>r.id===t||t.includes(r.id)||r.id.includes(t));return a?{icon:a.icon,name:a.name}:{icon:"📝",name:e}}function sj({ide:e,allIdes:t,sendDaemonCommand:n,onDisconnect:a,onRevokeToken:r}){var L,R;const{t:o}=Ce("common"),[i,c]=l.useState("idle"),[u,p]=l.useState(""),[d,m]=l.useState(null),[h,g]=l.useState("idle"),[k,f]=l.useState(""),x=e.version||null,w=((L=e.machine)==null?void 0:L.platform)||((R=e.system)==null?void 0:R.platform)||"",b=rs(e,{fallbackId:e.id}),S=w==="win32"?"🪟":w==="darwin"?"🍎":"🐧",N=t.filter(F=>F.daemonId===e.id&&F.transport==="cdp-page"),v=t.filter(F=>F.daemonId===e.id&&F.transport==="pty"),y=t.filter(F=>F.daemonId===e.id&&F.transport==="acp"),j=e.p2p,C=async()=>{if(!n)return;const F=ao(e);if(!F){c("error"),p(Nm);return}c("upgrading"),p(o("machine.connectedMachines.startingUpgrade"));try{const E=ZC(await n(e.id,"daemon_upgrade",F));E.alreadyLatest?(c("done"),p(`Already on v${E.version||"latest"}.`)):E.upgraded||E.success?(c("done"),p(`Upgrade to v${E.version||"latest"} started. Daemon is restarting...`)):(c("error"),p(E.error||"Upgrade failed"))}catch(E){c("error"),p(Eo(E,"Connection lost during upgrade"))}},A=async()=>{if(m(null),!!a){g("loading");try{await a(e.id),g("done"),f(o("machine.connectedMachines.machineDisconnected"))}catch(F){g("error"),f(Eo(F,o("machine.connectedMachines.failedToDisconnect")))}}},T=async()=>{if(m(null),!!r){g("loading");try{await r(e.id),g("done"),f(o("machine.connectedMachines.tokenRevoked"))}catch(F){g("error"),f(Eo(F,o("machine.connectedMachines.failedToRevokeToken")))}}},D="1.0.42",I=qs(e,D),M=no(e,I),P=wa(e,I),$=N.length+v.length+y.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xl",children:S}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:b}),s.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[s.jsxs("span",{children:[e.id.substring(0,12),"…"]}),x&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${M?"":"bg-bg-secondary"}`,style:M?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",x,!M&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[n&&M&&s.jsx("button",{onClick:C,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${D}`,children:i==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," ",o("machine.connectedMachines.upgrading")]}):i==="done"?o("machine.connectedMachines.updated"):P?o("machine.connectedMachines.updateNow"):o("machine.connectedMachines.updateTo",{version:D})}),a&&s.jsx("button",{onClick:()=>m("disconnect"),disabled:h==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:o("machine.connectedMachines.disconnect")}),r&&s.jsx("button",{onClick:()=>m("revoke"),disabled:h==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:o("machine.connectedMachines.remove")}),s.jsx(VC,{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:[j&&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 ${j.state==="connected"?"bg-status-online":"bg-text-muted/30"} ${j.state==="connecting"||j.state==="new"?"animate-pulse":""}`,style:j.state==="connecting"||j.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",j.state==="connected"?"connected":j.state==="connecting"||j.state==="new"?o("machine.connectedMachines.connecting"):j.state||"off"]}),j.peers!==void 0&&j.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",j.peers," peer",j.peers!==1?"s":"",")"]})]}),j&&$>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),$>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[N.map(F=>{const E=tj(F.type),H=F.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:E.icon}),s.jsx("span",{children:E.name}),H!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${H?"bg-status-online":"animate-pulse"}`,style:H?void 0:{background:"var(--status-warning)"},title:o(H?"machine.connectedMachines.cdpConnected":"machine.connectedMachines.cdpConnecting")})]},F.id)}),v.map(F=>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:F.cliName||"CLI"})]},F.id)),y.map(F=>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:F.cliName||"ACP"})]},F.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:o("machine.connectedMachines.noIdesConnected")})]}),(u||k)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||h==="error"?"text-status-error":i==="done"||h==="done"?"text-status-online":"text-text-muted"}`,children:k||u})]}),d==="disconnect"&&s.jsx(dd,{title:o("machine.connectedMachines.disconnectTitle"),message:`Disconnect "${b}" from ADHDev?
|
|
59
59
|
|
|
60
60
|
This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
|
|
61
61
|
|
|
@@ -66,8 +66,8 @@ This will:
|
|
|
66
66
|
• Delete the machine registration
|
|
67
67
|
• Require running \`adhdev setup\` again on that machine
|
|
68
68
|
|
|
69
|
-
The machine's IDE, workspace and provider settings are kept.`,confirmLabel:o("machine.connectedMachines.remove"),confirmColor:"red",onConfirm:T,onCancel:()=>m(null)})]})}const nj=["default","claude-cli","codex-cli","antigravity-cli","hermes-cli","gemini-cli"];function aj({daemonId:e,knownCliTypes:t=nj}){const{t:n}=Ce("common"),{sendCommand:a}=kt(),[r,o]=l.useState({}),[i,c]=l.useState({}),[u,p]=l.useState(!0),[d,m]=l.useState(null),[h,g]=l.useState(null),[k,f]=l.useState(""),x=l.useCallback(async()=>{if(e){p(!0),g(null);try{const S=await a(e,"list_coordinator_prompts",{}),N=S!=null&&S.result&&typeof S.result=="object"?S.result:S;if(!(N!=null&&N.success)){g((N==null?void 0:N.error)||"Failed to load");return}const v=N.entries||{};f(N.dir||"");const y={};for(const j of t)y[j]=v[j]||{override:"",append:""};for(const j of Object.keys(v))y[j]||(y[j]=v[j]);o(y),c(JSON.parse(JSON.stringify(y)))}catch(S){g((S==null?void 0:S.message)||String(S))}finally{p(!1)}}},[a,e,t]);l.useEffect(()=>{x()},[x]);const w=l.useCallback(async(S,N)=>{var v;if(e){m(`${S}:${N}`),g(null);try{const y=((v=r[S])==null?void 0:v[N])||"",j=await a(e,"write_coordinator_prompt",{key:S,kind:N,content:y}),C=j!=null&&j.result&&typeof j.result=="object"?j.result:j;if(!(C!=null&&C.success)){g((C==null?void 0:C.error)||"Save failed");return}c(A=>({...A,[S]:{...A[S]||{override:"",append:""},[N]:y}}))}catch(y){g((y==null?void 0:y.message)||String(y))}finally{m(null)}}},[a,e,r]),b=l.useMemo(()=>(S,N)=>{var v,y;return(((v=r[S])==null?void 0:v[N])||"")!==(((y=i[S])==null?void 0:y[N])||"")},[r,i]);return e?s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{className:"text-[12px] text-text-muted",children:[s.jsxs("p",{children:["Customize the coordinator prompt this daemon's mesh coordinator sessions get. ",s.jsx("span",{className:"font-mono text-[11px]",children:k||"~/.adhdev/coordinator-prompts/"})]}),s.jsxs("p",{className:"mt-1",children:[s.jsx(gi,{i18nKey:"settings.coordinatorPrompts.overrideDesc",ns:"common",components:{strong:s.jsx("strong",{})}})," ",s.jsx(gi,{i18nKey:"settings.coordinatorPrompts.appendDesc",ns:"common",components:{strong:s.jsx("strong",{})}}),"Leave a field empty + Save to remove it (reset to default). Supports placeholders: ","{{meshName}}",", ","{{repo}}",", ","{{nodes}}",", ","{{rules}}",", etc."]})]}),h&&s.jsx("div",{className:"text-[12px] text-status-error bg-status-error/10 border border-status-error/40 rounded px-3 py-2",children:h}),u&&s.jsx("div",{className:"text-[12px] text-text-muted",children:"Loading…"}),s.jsx("div",{className:"flex flex-col gap-6",children:Object.entries(r).map(([S,N])=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 p-3",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-2",children:S}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:n("settings.coordinatorPrompts.overrideLabel")}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:4,value:N.override,onChange:v=>o(y=>({...y,[S]:{...y[S],override:v.target.value}})),placeholder:"(empty — use daemon default base prompt)",disabled:d===`${S}:override`}),s.jsx("div",{className:"mt-1 mb-3 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void w(S,"override"),disabled:d===`${S}:override`||!b(S,"override"),children:d===`${S}:override`?"Saving…":b(S,"override")?"Save override":"Saved"})}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:n("settings.coordinatorPrompts.appendLabel")}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:3,value:N.append,onChange:v=>o(y=>({...y,[S]:{...y[S],append:v.target.value}})),placeholder:"(empty — nothing appended at this layer)",disabled:d===`${S}:append`}),s.jsx("div",{className:"mt-1 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void w(S,"append"),disabled:d===`${S}:append`||!b(S,"append"),children:d===`${S}:append`?"Saving…":b(S,"append")?"Save append":"Saved"})})]},S))})]}):s.jsx("div",{className:"text-[12px] text-text-muted",children:"Connect a daemon to edit coordinator prompts."})}const rj=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function oj(){const{preference:e,setPreference:t}=en();return s.jsx("div",{className:"flex gap-2",children:rj.map(n=>s.jsxs("button",{onClick:()=>t(n.id),className:`px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors flex items-center gap-1.5 ${e===n.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:e===n.id?{color:"var(--accent-on-primary)"}:void 0,children:[s.jsx("span",{children:n.icon}),n.label]},n.id))})}function ij(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 lj(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function _o(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function ud(e){const{r:t,g:n,b:a}=lj(e);return .2126*_o(t)+.7152*_o(n)+.0722*_o(a)}function pd(e,t){const n=ud(e),a=ud(t),r=Math.max(n,a),o=Math.min(n,a);return(r+.05)/(o+.05)}function Am(e){const t=ij(e);if(!t)return"#111827";const n="#111827",a="#ffffff";return pd(t,n)>=pd(t,a)?n:a}const Oi={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},Ui={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},cj=[{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"}}}],Tm="adhdev-chat-theme",Mm="adhdev-chat-theme-custom";function fr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Tm)||"ember"}catch{return"ember"}}function us(e){try{const t=localStorage.getItem(Mm);if(t){const n=JSON.parse(t);return{...e==="dark"?Oi:Ui,...n[e]}}}catch{}return e==="dark"?Oi:Ui}function Qa(e,t){try{localStorage.setItem(Mm,JSON.stringify({dark:e,light:t}))}catch{}}function ts(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 $r(e,t){const n=Math.min(255,parseInt(e.slice(1,3),16)+t),a=Math.min(255,parseInt(e.slice(3,5),16)+t),r=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}`}const dj={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function ka(e,t){var r;const n=(r=dj[e])==null?void 0:r[t];if(!n)return;const a=document.documentElement;a.style.setProperty("--accent-primary",n),a.style.setProperty("--accent-primary-light",$r(n,24)),a.style.setProperty("--accent-on-primary",Am(n)),a.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${n}, ${$r(n,18)})`),a.style.setProperty("--border-accent",ts(n,.35)),a.style.setProperty("--nav-active-bg",ts(n,.1)),a.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${n}, 0 0 12px ${ts(n,.06)}`)}function mn(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",ts(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",ts(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",ts(e.borderSubtle,.25)),t.style.setProperty("--text-primary",e.textPrimary),t.style.setProperty("--text-secondary",e.textSecondary),t.style.setProperty("--text-muted",e.textMuted),t.style.setProperty("--border-subtle",ts(e.borderSubtle,.5)),t.style.setProperty("--border-default",ts(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",$r(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Am(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${$r(e.accentColor,40)})`),t.style.setProperty("--border-accent",ts(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",ts(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${ts(e.accentColor,.06)}`),t.style.setProperty("--chat-user-bg",e.userBubble),t.style.setProperty("--chat-user-color",e.userText),t.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),t.style.setProperty("--chat-assistant-bg",e.assistantBubble),t.style.setProperty("--chat-assistant-color",e.assistantText),t.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),t.style.setProperty("--chat-assistant-border",`1px solid ${ts(e.accentColor,.12)}`),t.style.setProperty("--chat-container-bg",e.containerBg),t.style.setProperty("--dashboard-pane-bg",e.containerBg),t.style.setProperty("--chat-thought-accent",e.accentColor),t.style.setProperty("--chat-tool-accent",e.accentColor),t.style.setProperty("--chat-action-color",e.accentColor),t.style.setProperty("--chat-send-bg",e.sendButton),t.style.setProperty("--chat-input-border",e.inputBorder)}function Dl(){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 uj(e){try{localStorage.setItem(Tm,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=hn()?"dark":"light";mn(us(t))}else Dl(),ka(e,hn()?"dark":"light")}function pj(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=fr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=hn()?"dark":"light";mn(us(t))}else Dl(),ka(e,hn()?"dark":"light")}function hn(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Ot({label:e,value:t,onChange:n}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[s.jsx("input",{type:"color",value:t,onChange: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 oa({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 mj({dark:e,onColorsChange:t}){const{t:n}=Ce("common"),a=e?"dark":"light",[r,o]=l.useState(()=>us(a));l.useEffect(()=>{o(us(a))},[a]);const i=l.useCallback((c,u)=>{o(p=>{const d={...p,[c]:u},h=us(a==="dark"?"light":"dark");return a==="dark"?Qa(d,h):Qa(h,d),mn(d),t(d),d})},[a,t]);return s.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[s.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[n("settings.theme.customEditorTitle"),s.jsx("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:n(e?"settings.theme.darkMode":"settings.theme.lightMode")})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs(oa,{title:n("settings.theme.sectionAppBackground"),children:[s.jsx(Ot,{label:n("settings.theme.colorBackground"),value:r.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(Ot,{label:n("settings.theme.colorSurface"),value:r.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(Ot,{label:n("settings.theme.colorCard"),value:r.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(oa,{title:n("settings.theme.sectionAppText"),children:[s.jsx(Ot,{label:n("settings.theme.colorPrimary"),value:r.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(Ot,{label:n("settings.theme.colorSecondary"),value:r.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(Ot,{label:n("settings.theme.colorMuted"),value:r.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(oa,{title:n("settings.theme.sectionBordersAccent"),children:[s.jsx(Ot,{label:n("settings.theme.colorBorderSubtle"),value:r.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(Ot,{label:n("settings.theme.colorBorderDefault"),value:r.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(Ot,{label:n("settings.theme.colorAccent"),value:r.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(oa,{title:n("settings.theme.sectionChatBubbles"),children:[s.jsx(Ot,{label:n("settings.theme.colorUserBubble"),value:r.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(Ot,{label:n("settings.theme.colorUserText"),value:r.userText,onChange:c=>i("userText",c)}),s.jsx(Ot,{label:n("settings.theme.colorAgentBubble"),value:r.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(Ot,{label:n("settings.theme.colorAgentText"),value:r.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(oa,{title:n("settings.theme.sectionChatLayout"),children:[s.jsx(Ot,{label:n("settings.theme.colorChatBg"),value:r.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(Ot,{label:n("settings.theme.colorSendButton"),value:r.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(Ot,{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?Oi:Ui,p=us(e?"light":"dark");e?Qa(c,p):Qa(p,c),o(c),mn(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 hj(){const{t:e}=Ce("common"),[t,n]=l.useState(fr),[a,r]=l.useState(!0),[o,i]=l.useState(()=>us("dark"));l.useEffect(()=>{r(hn());const p=new MutationObserver(()=>{const h=hn();r(h);const g=fr();g==="custom"?mn(us(h?"dark":"light")):ka(g,h?"dark":"light")});p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const d=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const h=hn();r(h);const g=fr();g==="custom"?mn(us(h?"dark":"light")):ka(g,h?"dark":"light")};return d.addEventListener("change",m),()=>{p.disconnect(),d.removeEventListener("change",m)}},[]),l.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?mn(us(a?"dark":"light")):(Dl(),ka(t,a?"dark":"light"))},[t,a]),l.useEffect(()=>{i(us(a?"dark":"light"))},[a]);const c=p=>{n(p),uj(p)},u=[...cj,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText},light:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:u.map(p=>{const d=t===p.id,m=a?p.preview.dark:p.preview.light,h=p.id==="honey"||p.id==="ember"?"#1a1a1a":p.id==="custom"?o.userText:"#fff";return s.jsxs("button",{onClick:()=>c(p.id),className:"text-left rounded-xl p-3 transition-all",style:{background:d?"var(--bg-glass-hover)":"var(--bg-glass)",border:d?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:d?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:m.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:e("settings.theme.helloHelp")}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.userBubble,color:h},children:e("settings.theme.fixBug")}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:e("settings.theme.onIt")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[d&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:p.id==="custom"?e("settings.theme.customLabel"):p.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:p.description})]})]})]},p.id)})}),t==="custom"&&s.jsx(mj,{dark:a,onColorsChange:p=>i(p)})]})}const Pl="adhdev_mobileDashboardMode_v1",qi="adhdev:mobile-dashboard-mode-change";function Il(){try{return localStorage.getItem(Pl)==="workspace"?"workspace":"chat"}catch{return"chat"}}function fj(e){if(typeof window>"u")return()=>{};const t=r=>{e(r??Il())},n=r=>{const o=r.detail;t(o)},a=r=>{r.key&&r.key!==Pl||t()};return window.addEventListener(qi,n),window.addEventListener("storage",a),()=>{window.removeEventListener(qi,n),window.removeEventListener("storage",a)}}function bj(e){try{localStorage.setItem(Pl,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(qi,{detail:e}))}function gj(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(Il()==="chat")},[]),s.jsx(ln,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(kn,{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),bj(n?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const xj="Choose a preset or create a fully custom theme. Custom themes control the entire app — backgrounds, text, borders, and chat bubbles.",vj="Choose whether the dashboard opens like a chat app on phones or keeps the full workspace layout.";function yj({themeDescription:e=xj,mobileDescription:t=vj,fontsSlot:n}){const{t:a}=Ce("common");return s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:a("settings.appearance.modeLabel")}),s.jsx(oj,{})]}),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(hj,{})]}),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(gj,{})]})]})}const Ho=new Map,md=new Map;function wj(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 kj(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 Dm(){const{sendCommand:e}=kt(),{injectEntries:t,getIdes:n}=ja();return l.useCallback(async(a,r)=>{if(!a)return;const o=(r==null?void 0:r.minFreshMs)??Mk,i=md.get(a)||0;if(!(r!=null&&r.force)&&i>0&&Date.now()-i<o)return;const c=Ho.get(a);if(c)return c;const u=(async()=>{const p=await e(a,"get_machine_runtime_stats"),d=wj(p);if(!d)return;const m=n().find(g=>g.id===a),h=kj(m,a,d.machine,d.timestamp||Date.now());t([h]),md.set(a,Date.now())})().finally(()=>{Ho.delete(a)});return Ho.set(a,u),u},[n,t,e])}function Sj(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 Cj(e,t){const{sendData:n}=kt(),{injectEntries:a,getIdes:r}=ja(),o=Array.from(new Set(e.filter(Boolean))).join("|");l.useEffect(()=>{if(!(t!=null&&t.enabled)||!n)return;const i=o?o.split("|"):[];if(i.length===0)return;const c=i.map(u=>hs.subscribe({sendData:n},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:t==null?void 0:t.intervalMs}},d=>{const m=r().find(g=>g.id===u),h=Sj(m,u,d);a([h])}));return()=>{c.forEach(u=>u())}},[o,r,a,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,n])}function jj(e,t){const{sendData:n}=kt(),[a,r]=l.useState(null),[o,i]=l.useState(!1);return l.useEffect(()=>{if(!e){r(null),i(!1);return}if(!(t!=null&&t.enabled)||!n){i(!1);return}r(null),i(!0);let c=null;const u=hs.subscribe({sendData:n},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},p=>{c&&(clearTimeout(c),c=null),r(p.diagnostics),i(!1)});return u.initialSendAccepted?c=setTimeout(()=>{i(!1)},Ik):i(!1),()=>{c&&clearTimeout(c),u()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,n]),{diagnostics:a,loading:o,applyDiagnostics:r}}function Nj(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Pm(e){const{sendData:t}=kt(),[n,a]=l.useState({});return l.useEffect(()=>{const r=Nj(e);if(!r||!e.sessionId||!t){a({});return}const o=hs.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}),$n.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 Aj(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function Tj(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 Mj(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 Dj({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(!Aj(o))throw new Error(Tj(o));return}await Mj(e.sessionId,t,r)}function Im(e){const{ides:t,isP2PActive:n,p2pStates:a}=Ms(),{sendCommand:r}=kt(),[o,i]=l.useState(null),[c,u]=l.useState(!1),[p,d]=l.useState(null),m=l.useRef(!1),h=l.useMemo(()=>gg(t,e),[t,e]),g=!!h,k=l.useMemo(()=>h?h.prompt.promptId===o?null:h:null,[o,h]),f=l.useCallback(async b=>{if(!k||m.current)return;m.current=!0;const S=ep(k.prompt,b);u(!0),d(null);try{const N=(a==null?void 0:a[k.daemonId])==="connected"||n===!0;await Dj({promptSession:k,response:S,useP2PCommand:N,sendCommand:r}),i(k.prompt.promptId)}catch(N){throw d(N instanceof Error?N.message:String(N)),N}finally{u(!1),m.current=!1}},[n,a,k,r]),x=l.useCallback(()=>{k&&i(k.prompt.promptId)},[k]),w=l.useCallback(()=>{i(null),d(null)},[]);return{promptSession:k,hasActivePrompt:g,responseError:p,isSubmitting:c,submit:f,cancel:x,reopen:w}}function Lm(e){return e instanceof Error?e.message:String(e||"")}function Pj(e){const t=Lm(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 Ij(e){const t=Lm(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Rm({conversation:e,mode:t,ides:n,sendDaemonCommand:a,setCliViewModeOverrides:r}){if(!e||!ft(e)||pt(e))return;const o=Yn(e);if(o===t)return;const i=e.sessionId;i&&r(c=>({...c,[i]:t}));try{await a(Bs(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Ts(e),mode:t})}catch(c){const u=Ij(c);i&&!u&&r(p=>{const d={...p};return o===Rj(n,i)?delete d[i]:d[i]=o,d}),Pj(c)?console.warn(u?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",c instanceof Error?c.message:String(c)):console.error("Failed to switch CLI view mode:",c)}}function hd(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 Lj(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=hd(r,t),i=Array.isArray(r.childSessions)?r.childSessions.map(u=>hd(u,t)):r.childSessions,c=i!==r.childSessions;return o!==r||c?(n=!0,{...o,...c?{childSessions:i}:{}}):r});return n?a:e}function Rj(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 Ej({visibleConversations:e,clearedTabs:t,setClearedTabs:n,setActionLogs:a,isConversationMuted:r}){l.useEffect(()=>{gp()},[]);const o=l.useMemo(()=>e.map(i=>({id:i.tabKey,name:am(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 Qw(o),l.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{n(u=>{const p=Date.now(),d={};for(const[m,h]of Object.entries(u))p-h<5e3&&(d[m]=h);return Object.keys(d).length===Object.keys(u).length?u:d})},5500);return()=>clearTimeout(c)},[t,n]),l.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;a(u=>{const p=u.filter(d=>d.timestamp>c).slice(-100);return p.length===u.length?u:p})},6e4);return()=>clearInterval(i)},[a]),null}function fd(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 fn(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=fd(t==null?void 0:t.receivedAt)||fd(t==null?void 0:t.timestamp)||0;return Math.max(n,a)}function Gi(e,t=0){return fn(e)||e.lastUpdated||t||0}function Em(e){return fn(e)||e.lastUpdated||0}function _m(e,t,n=Em){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 zi(e){var n;const t=ns(e.status,{activeModal:(n=e.modalButtons)!=null&&n.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function _j(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!zi(e)&&!e.title.trim()}function Hj(e){return e.length===0?null:[...e].sort((t,n)=>{const a=Number(zi(n))-Number(zi(t));if(a!==0)return a;const r=n.messages.length-t.messages.length;return r!==0?r:_m(t,n)})[0]||null}function fs(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=Hj(r);return a?o&&_j(a)?o:a:o||n[0]||null}function $j(e){const t=e.filter(r=>r.type!=="adhdev-daemon"),n=new Set;for(const r of t){if(!Pi(r))continue;const o=up(r);o&&n.add(o)}const a=new Map;for(const r of t){const o=Aw(r,n),i=a.get(o);if(!i){a.set(o,r);continue}const c=m=>(m.workspace?1:0)+(m.activeChat?1:0)+(m.lastMessagePreview?1:0),u=c(i),p=c(r),d=p>u||p===u&&(r.timestamp||0)>(i.timestamp||0)?r:i;a.set(o,Fj(d,d===r?i:r))}return Array.from(a.values())}function Fj(e,t){const n=Pi(t),a=Pi(e);if(!n&&!a)return e;const r=a?n?void 0:t:e,o=a?e:n?t:void 0,i=r&&String(r.daemonId||"").trim()||String(e.ownerDaemonId||"").trim()||String(t.ownerDaemonId||"").trim()||void 0,c=String(e.ownerMachineName||"").trim()||String(t.ownerMachineName||"").trim()||void 0,u=o==null?void 0:o.settings;return{...e,...i&&{ownerDaemonId:i},...c&&!e.ownerMachineName&&{ownerMachineName:c},...u&&!a&&{settings:{...u,...e.settings??{}}}}}function $o(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 Bj(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 bd(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],n=t[t.length-1],a=n?Bj(Fn(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 Wj(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||""),bd(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||""),bd(n.activeChat)].join(":"))].join("|")}function Oj(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 Uj(e,t){const n=new Map;for(const a of e){const r=t.get(a.routeId)||a;for(const o of xa({routeId:a.routeId}))n.set(o,r);for(const o of xa({providerSessionId:a.providerSessionId,sessionId:a.sessionId}))n.set(o,a.streamSource==="native"?r:a);for(const o of xa({tabKey:a.tabKey}))n.set(o,a)}return n}function qj(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Gj(e){const t=qj(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=Fn(t.content).slice(0,240);return`${e.messages.length}:${n}:${a}`}function zj({ides:e,connectionStates:t,clearedTabs:n}){const a=l.useMemo(()=>$j(e),[e]),r=l.useMemo(()=>np(e),[e]),o=l.useMemo(()=>fm(e),[e]),i=l.useRef([]),c=l.useRef([]),u=l.useRef([]),p=l.useRef(new Map),d=l.useRef(new Map),m=l.useMemo(()=>{const N=new Map,v=[];for(const A of a){const{connectionState:T="new",machineName:D}=bm(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),I=Wj(A),M=p.current.get(A.id);if(M&&M.ide===A&&M.sourceSignature===I&&M.connectionState===T&&M.machineName===D){N.set(A.id,M),v.push(...M.conversations);continue}const P=Tl(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),$={ide:A,sourceSignature:I,connectionState:T,machineName:D,conversations:P};N.set(A.id,$),v.push(...P)}p.current=N;const y=new Map,j=A=>{const T=Gj(A),D=d.current.get(A.tabKey);if(D&&D.signature===T)return y.set(A.tabKey,D),D.timestamp;const I={signature:T,timestamp:Em(A)||(D==null?void 0:D.timestamp)||0};return y.set(A.tabKey,I),I.timestamp},C=[...v].sort((A,T)=>_m(A,T,j));return d.current=y,C},[a,t,o]),h=l.useMemo(()=>{const N=Oj(m,n);return $o(i.current,N)?i.current:(i.current=N,N)},[m,n]),g=l.useMemo(()=>{const N=new Map,v=Array.from(new Set(h.map(y=>y.routeId)));for(const y of v){const j=fs(h,y);j&&N.set(y,j)}return N},[h]),k=l.useMemo(()=>{const N=new Map;for(const v of h){const y=g.get(v.routeId),j=v.streamSource==="native"&&y?y:v;for(const C of xa({providerSessionId:v.providerSessionId,sessionId:v.sessionId,tabKey:v.tabKey}))N.set(C,j)}return N},[h,g]),f=l.useMemo(()=>Uj(h,g),[h,g]),x=l.useCallback(N=>{if(N)return k.get(N)},[k]),w=l.useCallback(N=>{if(N)return f.get(N)},[f]),b=l.useMemo(()=>{const N=h.filter(v=>!Js(v,r).surfaceHidden);return $o(c.current,N)?c.current:(c.current=N,N)},[h,r]),S=l.useMemo(()=>{const N=b.map(v=>v.tabKey);return $o(u.current,N)?u.current:(u.current=N,N)},[b]);return{chatIdes:a,conversations:h,visibleConversations:b,visibleTabKeys:S,resolveConversationBySessionId:x,resolveConversationByTarget:w}}function Kj({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:n,setSearchParams:a}){const r=l.useMemo(()=>{var c;return e||!t?null:((c=n(t))==null?void 0:c.tabKey)??null},[e,n,t]),o=l.useMemo(()=>{var c;return!e||!t?null:((c=n(t))==null?void 0:c.tabKey)??null},[e,n,t]),i=l.useCallback(()=>{t&&a(c=>{const u=new URLSearchParams(c);return u.delete("activeTab"),u},{replace:!0})},[a,t]);return{requestedDesktopTabKey:r,requestedMobileTabKey:o,consumeRequestedActiveTab:i}}function Vj({ides:e,sendDaemonCommand:t,setToasts:n,resolveConversationByTarget:a}){l.useEffect(()=>{bt.setIdes(e)},[e]),l.useEffect(()=>{bt.setResolveAction((r,o,i)=>{t(r,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const r=bt.onToast(o=>{n(c=>c.some(p=>p.message===o.message&&o.timestamp-p.timestamp<3e3)?c:[...c.slice(-4),{id:o.id,message:o.message,type:o.type,timestamp:o.timestamp,targetKey:o.targetKey,actions:o.actions}]);const i=o.duration||5e3;setTimeout(()=>n(c=>c.filter(u=>u.id!==o.id)),i)});return()=>{r()}},[n]),l.useEffect(()=>{const r=em.on("status_event",o=>{bt.handleRawEvent(o,"ws")});return()=>{r()}},[]),l.useEffect(()=>{var o;const r=i=>{var f;const c=i.data;if((c==null?void 0:c.type)!=="notification_action"||typeof c.action!="string"||!c.action.startsWith("approval_")||!(c.daemonId||c.targetSessionId||c.targetKey))return;const u=c.targetSessionId||c.targetKey||c.daemonId,p=a(u),d=(p==null?void 0:p.routeId)||c.daemonId;if(!d)return;const m=Number(c.buttonIndex),h=c.button||((f=p==null?void 0:p.modalButtons)==null?void 0:f[m])||"Approve",g=String(h).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),k=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(g);t(d,"resolve_action",{action:k?"approve":"reject",button:h,...Number.isFinite(m)&&{buttonIndex:m},...(p==null?void 0:p.sessionId)&&{targetSessionId:p.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(x=>console.error("[SW Action] approval failed:",x))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",r),()=>{var i;return(i=navigator.serviceWorker)==null?void 0:i.removeEventListener("message",r)}},[a,t])}const Yj="adhdev_dashboardLayout_v1",Qj="adhdev_dashboardDockview_v1",Jj="adhdev_dashboardDockviewHiddenRestore_v1",ia={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Ll(e,t){try{const n=localStorage.getItem(e);return n?JSON.parse(n):t}catch{return t}}function Xj(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Hm(e){return`${Yj}:${e}`}function Zj(e){const t=Hm(e);return Ll(t,null)}function e1(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=Hm(e);if(n){localStorage.removeItem(a);return}localStorage.setItem(a,JSON.stringify(t))}catch{}}function $m(e){return`${Qj}:${e}`}function t1(e){const t=$m(e);return Ll(t,null)}function s1(e,t){try{const n=$m(e);if(!t){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Fm(e){return`${Jj}:${e}`}function n1(e){const t=Fm(e);return Ll(t,{})}function a1(e,t){try{const n=Fm(e);if(Object.keys(t).length===0){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function r1(){return{groupAssignments:[...ia.groupAssignments],focusedGroup:ia.focusedGroup,groupActiveTabIds:{...ia.groupActiveTabIds},groupTabOrders:{...ia.groupTabOrders},groupSizes:[...ia.groupSizes]}}function o1(e,t){return e?e.length===t.length&&e.every((n,a)=>n===t[a]):t.length===0}function i1(){const[e]=l.useState(()=>Xj(typeof window<"u"?window.innerWidth:1280)),[t,n]=l.useState(()=>new Map),[a,r]=l.useState(0),[o,i]=l.useState({}),[c,u]=l.useState({}),[p,d]=l.useState([]),[m,h]=l.useState(()=>typeof window<"u"&&window.innerWidth<768),[g,k]=l.useState(!1),f=l.useCallback(()=>{if(g)return;const A=Zj(e)??r1();n(new Map(A.groupAssignments)),r(A.focusedGroup),i(A.groupActiveTabIds),u(A.groupTabOrders),d(A.groupSizes),k(!0)},[g,e]);l.useEffect(()=>{g&&e1(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=D=>h(D.matches);return A.addEventListener("change",T),()=>A.removeEventListener("change",T)},[]);const x=l.useCallback(A=>{n(A)},[]),w=l.useCallback(A=>{r(A)},[]),b=l.useCallback(A=>{i(A)},[]),S=l.useCallback(A=>{u(A)},[]),N=l.useCallback(A=>{d(A)},[]),v=l.useCallback(A=>{w(A)},[w]),y=l.useCallback((A,T)=>{i(D=>(D[A]??null)===(T??null)?D:{...D,[A]:T})},[]),j=l.useCallback((A,T)=>{u(D=>{const I=D[A];return o1(I,T)?D:{...D,[A]:T}})},[]),C=l.useCallback((A,T)=>{const D=T.get(A)??0;return y(D,A),v(D),D},[v,y]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:x,focusedGroup:a,updateFocusedGroup:w,focusGroup:v,groupActiveTabIds:o,updateGroupActiveTabIds:b,setGroupActiveTab:y,groupTabOrders:c,updateGroupTabOrders:S,setGroupTabOrder:j,groupSizes:p,updateGroupSizes:N,isMobile:m,hasHydratedStoredLayout:g,hydrateStoredLayout:f,focusConversationTab:C}}function l1(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0],a=Yr(t);return typeof(n==null?void 0:n.id)=="string"&&a.includes(n.id)}function c1({urlActiveTab:e,conversations:t,resolveConversationBySessionId:n,normalizedGroupAssignments:a,hasHydratedStoredLayout:r,hydrateStoredLayout:o,focusConversationTab:i,setSearchParams:c,historyModalOpen:u,activeConv:p,isRefreshingHistory:d,ides:m,handleRefreshHistory:h}){const g=l.useRef(!1),k=l.useRef(!1),f=l.useRef(null),x=l.useRef(!1);l.useEffect(()=>{if(!e||g.current||t.length===0)return;if(!r){o();return}const w=n(e);w&&(i(w.tabKey,a),g.current=!0,k.current=!0,f.current!=null&&(window.clearTimeout(f.current),f.current=null),c(b=>{const S=new URLSearchParams(b);return S.delete("activeTab"),S},{replace:!0}))},[e,t,n,a,r,o,i,c]),l.useEffect(()=>{if(!(k.current||r)&&t.length!==0){if(!e){o(),k.current=!0;return}if(g.current){k.current=!0;return}if(f.current==null)return f.current=window.setTimeout(()=>{f.current=null,!(k.current||r)&&(o(),k.current=!0)},1500),()=>{f.current!=null&&(window.clearTimeout(f.current),f.current=null)}}},[e,t.length,r,o]),l.useEffect(()=>{if(!u){x.current=!1;return}if(!p||x.current||d)return;const w=m.find(b=>b.id===p.routeId);w&&(!w.chats||w.chats.length===0||l1(w.chats,p))&&(x.current=!0,h())},[u,p,d,m,h])}function Fo(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=Yr(t);return typeof(n==null?void 0:n.id)=="string"&&a.includes(n.id)}function Bm({sendDaemonCommand:e,activeConv:t,chats:n,updateRouteChats:a,setToasts:r,setClearedTabs:o}){const[i,c]=l.useState(!1),[u,p]=l.useState(!1),d=l.useCallback(async k=>{try{await e("standalone","launch_ide",{ideType:k,enableCdp:!0})}catch(f){console.error("Launch failed",f)}},[e]),m=l.useCallback(async(k,f)=>{try{const x=k||(t==null?void 0:t.daemonId)||"",w=await e(x,"switch_chat",{id:f,sessionId:f,...dn(t)}),b=w==null?void 0:w.result;if((w==null?void 0:w.success)===!0||b==="switched"||b==="switched-by-title")return;b===!1||b==="not_found"?Dn(r,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?Dn(r,`⚠️ Switch error: ${b}`):Dn(r,"⚠️ Session switch failed")}catch(x){console.error("Switch failed",x),Dn(r,`❌ Switch failed: ${x.message||"connection error"}`)}},[t,e,r]),h=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const k=un(t);await e(k,"new_chat",{...dn(t)}),Jk(k,t.sessionId,Yr(t)[0]),o(f=>({...f,[t.tabKey]:Date.now()}))}catch(k){console.error("New chat failed",k)}finally{c(!1)}}},[t,i,e,o]),g=l.useCallback(async()=>{var k,f;if(!(!t||u)){p(!0);try{const x=un(t),w=async()=>e(x,"list_chats",{forceExpand:!0,...dn(t)});let b=await w(),S=(b==null?void 0:b.chats)||((k=b==null?void 0:b.result)==null?void 0:k.chats);Fo(S,t)&&(await new Promise(N=>setTimeout(N,450)),b=await w(),S=(b==null?void 0:b.chats)||((f=b==null?void 0:b.result)==null?void 0:f.chats)),b!=null&&b.success&&Array.isArray(S)&&(a(t.routeId,S),Fo(S,t)&&!Fo(n,t)&&Dn(r,"⚠️ History dialog did not fully open — try once more"))}catch(x){console.error("Refresh history failed",x)}finally{p(!1)}}},[t,n,u,e,a,r]);return{isCreatingChat:i,isRefreshingHistory:u,handleLaunchIde:d,handleSwitchSession:m,handleNewChat:h,handleRefreshHistory:g}}function d1(e,t){if(e.size!==t.size)return!1;for(const[n,a]of e)if(t.get(n)!==a)return!1;return!0}function u1(e,t){return e.length!==t.length?!1:e.every((n,a)=>n===t[a])}function gd(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 Ja(e,t){const n=new Set(t),a=t.length>0?[0]:[];for(const[i,c]of e)!n.has(i)||c<=0||a.includes(c)||a.push(c);a.sort((i,c)=>i-c);const r={};a.forEach((i,c)=>{r[i]=c}),a.length===0&&(r[0]=0);const o=new Map;for(const[i,c]of e){if(!n.has(i)||c<=0)continue;const u=r[c];typeof u=="number"&&u>0&&o.set(i,u)}return{assignments:o,groupCount:Math.max(1,a.length),mapping:r,usedGroups:a}}function xd(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 p1(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 m1(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 vd(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 yd(e){return Array(e).fill(100/e)}function h1({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:n,updateGroupActiveTabIds:a,updateGroupTabOrders:r,groupSizes:o,updateGroupSizes:i,isMobile:c,visibleConversations:u,visibleTabKeys:p}){const d=l.useRef(null),m=l.useMemo(()=>Ja(e,p),[e,p]),h=m.assignments,g=l.useMemo(()=>c?1:m.groupCount,[m.groupCount,c]),k=g>1,f=l.useCallback((v,y)=>{t(j=>{const C=new Map(Ja(j,p).assignments);return y===0?C.delete(v):C.set(v,y),C}),a(j=>({...j,[y]:v})),n(y)},[t,p,a,n]),x=l.useCallback(v=>{t(y=>{const j=Ja(y,p).assignments,C=new Map;for(const[A,T]of j)T!==v&&(T>v?C.set(A,T-1):C.set(A,T));return C}),i(y=>{if(y.length<=1)return[];const j=[...y];j.splice(v,1);const C=j.reduce((A,T)=>A+T,0);return C>0?j.map(A=>A/C*100):[]}),n(0)},[t,p,i,n]),w=l.useCallback((v,y)=>{y.preventDefault();const j=d.current;if(!j)return;const C=y.clientX,A=j.offsetWidth,T=o.length===g?[...o]:yd(g),D=M=>{const $=(M.clientX-C)/A*100,L=[...T];L[v]=Math.max(15,T[v]+$),L[v+1]=Math.max(15,T[v+1]-$),i(L)},I=()=>{document.removeEventListener("mousemove",D),document.removeEventListener("mouseup",I),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",D),document.addEventListener("mouseup",I)},[o,g,i]),b=l.useCallback((v,y,j)=>{if(g>=4)return;const C=j==="left"?y:y+1;t(A=>{const T=Ja(A,p).assignments,D=new Map;for(const I of u){const M=T.get(I.tabKey)??0,P=M>=C?M+1:M;P>0&&D.set(I.tabKey,P)}return C>0&&D.set(v,C),D}),i(A=>{const T=A.length===g?[...A]:yd(g),D=T[y]??100/g,I=Math.max(15,D/2),M=Math.max(15,D/2),P=[...T];P[y]=I,P.splice(C,0,M);const $=P.reduce((L,R)=>L+R,0);return P.map(L=>L/$*100)}),a(A=>{const T=vd(A,C);return T[C]=v,T}),r(A=>{const T=vd(A,C);return T[C]=[v],T}),n(C)},[g,t,p,u,i,a,r,n]);l.useEffect(()=>{d1(e,h)||t(h)},[e,h,t]),l.useEffect(()=>{const{mapping:v,usedGroups:y}=m;a(j=>{const C=xd(j,v);return gd(j,C)?j:C}),r(j=>{const C=xd(j,v);return gd(j,C)?j:C}),n(j=>{const C=c?0:p1(j,y,v);return j===C?j:C}),i(j=>{const C=c?[]:m1(j,y,m.groupCount);return u1(j,C)?j:C})},[m,c,a,r,n,i]);const S=l.useMemo(()=>{const v=Array.from({length:g},()=>[]);for(const y of u){const j=h.get(y.tabKey)??0,C=Math.min(j,g-1);v[C].push(y)}return v},[u,h,g]),N=l.useCallback(()=>{t(new Map),n(0)},[t,n]);return{containerRef:d,normalizedGroupAssignments:h,numGroups:g,isSplitMode:k,groupedConvs:S,moveTabToGroup:f,closeGroup:x,handleResizeStart:w,splitTabRelative:b,clearAllSplits:N}}function f1({ides:e,sendDaemonCommand:t}){const n="1.0.41",a=l.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:no(m,qs(m,n))).sort((m,h)=>Number(wa(h,qs(h,n)))-Number(wa(m,qs(m,n)))),[n,e]),r=l.useMemo(()=>a.some(m=>wa(m,qs(m,n))),[n,a]),o=l.useMemo(()=>a.map(m=>qs(m,n)).find(m=>typeof m=="string"&&m.trim().length>0)||n,[n,a]),[i,c]=l.useState(!1),[u,p]=l.useState({}),d=l.useCallback(async m=>{var k,f;const h=e.find(x=>x.id===m);if(!h)return;p(x=>({...x,[m]:"upgrading"}));const g=ao(h);if(!g){p(x=>({...x,[m]:"error"}));return}try{const x=await t(m,"daemon_upgrade",g);(k=x==null?void 0:x.result)!=null&&k.upgraded||(f=x==null?void 0:x.result)!=null&&f.success?p(w=>({...w,[m]:"done"})):p(w=>({...w,[m]:"error"}))}catch{p(x=>({...x,[m]:"error"}))}},[e,t]);return{versionMismatchDaemons:a,hasRequiredVersionDaemons:r,targetVersion:o,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:u,handleBannerUpgrade:d}}const Wm=80;function br(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function b1(e){return{...e,createdAt:br(e.createdAt),updatedAt:br(e.updatedAt,e.createdAt),lastEventAt:br(e.lastEventAt,e.updatedAt||e.createdAt)}}function g1(e){const t=dp(e);return t==="unknown:"?e.id:t}function x1(e){return[e.type,cp(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function v1(e,t=Wm){const n=new Map;for(const a of e){if(a.deletedAt)continue;const r=g1(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 y1(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=Vr(r,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const u=br(r.lastMessageAt||(o==null?void 0:o.lastUpdated)||r.lastUpdated,n),p=x1({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(b1({id:p,dedupKey:p,type:c,routeId:r.routeId,machineId:r.daemonId||r.routeId,sessionId:r.sessionId,providerSessionId:r.providerSessionId,tabKey:r.tabKey,title:Pp(r),preview:ck(r),createdAt:u,updatedAt:u,lastEventAt:u}))}return v1(a)}function w1(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function k1(e){const{conversations:t,liveSessionInboxState:n,maxItems:a=Wm}=e,r=l.useMemo(()=>y1(t,n).slice(0,Math.max(0,a)),[t,n,a]),o=l.useMemo(()=>w1(r),[r]);return{notifications:r,unreadCount:o}}function S1({notifications:e,sendDaemonCommand:t}){const n=l.useCallback(o=>{const i=e.find(u=>u.id===o),c=Math.max(Date.now(),(i==null?void 0:i.updatedAt)||0);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_session_seen",{sessionId:i.sessionId,seenAt:c}).catch(()=>{})},[e,t]),a=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_notification_unread",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]),r=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"delete_notification",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:n,handleMarkDashboardNotificationUnread:a,handleDeleteDashboardNotification:r}}function Rl(...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 C1(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 El(e,t=[]){if(e==="win32"){for(const n of t){if(typeof n!="string")continue;const a=C1(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 j1(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 N1(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function _l(e,t,n){const a=await e(t,"file_list_browse",{path:n}),r=N1(a);if(!(r!=null&&r.success))throw new Error((r==null?void 0:r.error)||(a==null?void 0:a.error)||"Could not browse folder");const o=typeof(r==null?void 0:r.path)=="string"?r.path:n,i=o.includes("\\")?"\\":"/",c=(p,d)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${d}`:p==="/"||p==="\\"?`${i}${d}`:`${p.replace(/[\\/]+$/,"")}${i}${d}`,u=Array.isArray(r==null?void 0:r.files)?r.files.filter(p=>(p==null?void 0:p.type)==="directory"&&typeof(p==null?void 0:p.name)=="string").map(p=>({name:p.name,path:typeof(p==null?void 0:p.path)=="string"&&p.path.trim()?p.path:c(o,p.name)})).sort((p,d)=>p.name.localeCompare(d.name)):[];return{path:o,directories:u}}function wd(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 Om(e,t={}){const n=e==null?void 0:e.mcpConfig;if((n==null?void 0:n.mode)!=="manual")return null;const r=wd(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"}).trim();return!r.includes(`
|
|
70
|
-
`)&&!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:wd(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"})}}function A1(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 Ia(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Um(e){return Qr(e)||e.tabKey||e.routeId||null}function qm(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=fs(e.conversations,a)||e.conversations.find(i=>i.routeId===a);if(o!=null&&o.tabKey)return o.tabKey}return t||n||a||null}function Gs(e){return String(e||"").trim()}function Gm(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Fr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function T1(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function M1(e,t){const n=Gs(e.providerSessionId),a=Gs(e.targetSessionId),r=t.find(o=>{const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(Gs).filter(Boolean);return!!(n&&i.includes(n)||a&&i.includes(a))});return r?r.tabKey:a||n||null}function D1(e,t,n){if(t.event!=="agent:generating_completed")return null;const a=Gm(t.daemonId);if(a&&a!==e.machineId)return null;const r=Gs(t.providerType);if(e.providerType&&r!==e.providerType)return null;const o=Gs(e.resumeSessionId),i=Gs(e.launchedSessionId),c=Gs(t.providerSessionId),u=Gs(t.targetSessionId);if(o&&o!==c&&o!==u||i&&i!==c&&i!==u)return null;const p=Fr(e.workspacePath);if(p){const d=Fr(t.workspaceName);if(d&&!T1(d,p))return null}return M1(t,n)}function kd(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function P1({ides:e,conversations:t,onOpenSession:n}){const[a,r]=l.useState(null),o=l.useRef(null),i=l.useCallback(()=>{o.current=null,r(null)},[]),c=l.useCallback(u=>{o.current=u,r(u)},[]);return l.useEffect(()=>{if(!a)return;const u=Fr(a.workspacePath),p=e.find(m=>{var x,w,b,S;if(!m||m.type==="adhdev-daemon"||Gm(m.daemonId||m.id)!==a.machineId||(Ma(m)?"cli":_n(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 N=String(a.launchedSessionId||"");return[m.providerSessionId,m.sessionId,m.instanceId,m.id].map(y=>String(y||"")).filter(Boolean).includes(N)}if(u){const N=Fr(m.workspace||m.runtimeWorkspaceLabel);return N?N===u:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((S=(b=(w=(x=m.activeChat)==null?void 0:x.messages)==null?void 0:w.at)==null?void 0:b.call(w,-1))==null?void 0:S.timestamp)||0)>=a.startedAt-5e3});if(!p)return;const d=qm({entrySessionId:p.sessionId,entryInstanceId:p.instanceId,entryRouteId:p.id,conversations:t});d&&(i(),n(d))},[i,t,e,n,a]),l.useEffect(()=>bt.onStatusEvent(u=>{const p=o.current;if(!p)return;const d=D1(p,u,t);d&&(i(),n(d))}),[i,t,n]),l.useEffect(()=>{if(!a)return;const u=window.setTimeout(()=>{r(p=>!p||p.startedAt!==a.startedAt?p:(o.current=null,null))},45e3);return()=>window.clearTimeout(u)},[a]),{trackPendingLaunch:c}}function I1(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 L1(e,t,n){var i,c,u,p;const a={meshId:e.trim()};t.trim()&&(a.cliType=t.trim());const r=(i=n==null?void 0:n.initialModel)==null?void 0:i.trim(),o=(c=n==null?void 0:n.initialThinkingLevel)==null?void 0:c.trim();return r&&(a.initialModel=r),o&&(a.initialThinkingLevel=o),(u=n==null?void 0:n.settings)!=null&&u.autoApproveMode?a.autoApproveMode=n.settings.autoApproveMode:typeof((p=n==null?void 0:n.settings)==null?void 0:p.autoApprove)=="boolean"&&(a.autoApprove=n.settings.autoApprove),a}function R1({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:n,activeConv:a,ides:r,setCliViewModeOverrides:o}){const i=gl(),{launchCli:c}=qr(),u=l.useCallback(async(x,w)=>_l(e,x,w),[e]),p=l.useCallback(async(x,w)=>{if(!w.trim())return{ok:!1,error:"Choose a workspace path first."};try{const b=await e(x,"workspace_add",{path:w.trim()});return b!=null&&b.success?{ok:!0}:{ok:!1,error:(b==null?void 0:b.error)||"Could not save workspace"}}catch(b){return{ok:!1,error:b instanceof Error?b.message:"Could not save workspace"}}},[e]),d=l.useCallback(async(x,w,b)=>{var S;try{const N={ideType:w,enableCdp:!0};(S=b==null?void 0:b.workspacePath)!=null&&S.trim()&&(N.workspace=b.workspacePath.trim());const v=await e(x,"launch_ide",N);return!(v!=null&&v.success)&&(v==null?void 0:v.success)!==void 0?{ok:!1,error:(v==null?void 0:v.error)||"Could not launch IDE"}:(t({machineId:x,kind:"ide",providerType:w,workspacePath:(b==null?void 0:b.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(N){return{ok:!1,error:N instanceof Error?N.message:"Could not launch IDE"}}},[e,t]),m=l.useCallback(async(x,w,b,S)=>{const N=Date.now();try{const v=I1(b,S),y=await c(x,v),j=(y==null?void 0:y.result)||y,C=(j==null?void 0:j.sessionId)||(j==null?void 0:j.id);return y!=null&&y.success&&C?(t({machineId:x,kind:w,providerType:b,workspacePath:(S==null?void 0:S.workspacePath)||null,resumeSessionId:(S==null?void 0:S.resumeSessionId)||null,launchedSessionId:C,startedAt:N}),{ok:!0}):y!=null&&y.success?(t({machineId:x,kind:w,providerType:b,workspacePath:(S==null?void 0:S.workspacePath)||null,resumeSessionId:(S==null?void 0:S.resumeSessionId)||null,startedAt:N}),{ok:!0}):{ok:!1,error:(y==null?void 0:y.error)||(j==null?void 0:j.error)||`Could not launch ${w.toUpperCase()} session`,code:(y==null?void 0:y.code)||(j==null?void 0:j.code)||void 0}}catch(v){return kd(v)?(t({machineId:x,kind:w,providerType:b,workspacePath:(S==null?void 0:S.workspacePath)||null,resumeSessionId:(S==null?void 0:S.resumeSessionId)||null,startedAt:N}),{ok:!0}):{ok:!1,error:v instanceof Error?v.message:`Could not launch ${w.toUpperCase()} session`}}},[c,e,t]),h=l.useCallback(async x=>{var w;if(i!=null&&i.listMeshes)return i.listMeshes(x);if(!x)return[];try{const b=await e(x,"list_meshes",{}),S=(b==null?void 0:b.result)??b;if((S==null?void 0:S.success)===!1)throw new Error((S==null?void 0:S.error)||"Could not load meshes");return(Array.isArray(S==null?void 0:S.meshes)?S.meshes:Array.isArray((w=S==null?void 0:S.result)==null?void 0:w.meshes)?S.result.meshes:[]).map(v=>{var y;return{id:String((v==null?void 0:v.id)||""),name:String((v==null?void 0:v.name)||(v==null?void 0:v.id)||"Untitled mesh"),repoIdentity:(v==null?void 0:v.repoIdentity)||(v==null?void 0:v.repo_identity)||null,workspace:Array.isArray(v==null?void 0:v.nodes)&&v.nodes.length>0?String(((y=v.nodes[0])==null?void 0:y.workspace)||""):null,nodesCount:Array.isArray(v==null?void 0:v.nodes)?v.nodes.length:void 0,status:(v==null?void 0:v.status)||null}}).filter(v=>v.id)}catch(b){throw console.error("List meshes failed",b),b}},[i,e]),g=l.useCallback(async(x,w,b,S)=>{if(!w.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(x,w,b,S);const N=Date.now();try{const v=L1(w,b,S),y=await e(x,"launch_mesh_coordinator",v),j=(y==null?void 0:y.result)??y;if((j==null?void 0:j.success)===!1||(y==null?void 0:y.success)===!1){const A=String((j==null?void 0:j.code)||(y==null?void 0:y.code)||""),T=A1((j==null?void 0:j.meshCoordinatorSetup)||(j==null?void 0:j.manualSetup)||(y==null?void 0:y.meshCoordinatorSetup)||(y==null?void 0:y.manualSetup));return{ok:!1,error:(j==null?void 0:j.error)||(y==null?void 0:y.error)||"Could not launch mesh coordinator",code:A||void 0,manualSetup:T}}const C=(j==null?void 0:j.sessionId)||(j==null?void 0:j.id);return C?n(C):t({machineId:x,kind:"cli",providerType:(j==null?void 0:j.cliType)||b.trim()||void 0,workspacePath:(j==null?void 0:j.workspace)||null,startedAt:N}),{ok:!0}}catch(v){return kd(v)?(t({machineId:x,kind:"cli",providerType:b.trim()||void 0,startedAt:N}),{ok:!0}):{ok:!1,error:v instanceof Error?v.message:"Could not launch mesh coordinator"}}},[i,n,e,t]),k=l.useCallback(async(x,w)=>{if(!x||!w)return[];try{const b=await e(x,"list_saved_sessions",{providerType:w,kind:"cli",limit:30}),S=(b==null?void 0:b.result)??b;return Array.isArray(S==null?void 0:S.sessions)?S.sessions:[]}catch(b){return console.error("List saved sessions failed",b),[]}},[e]),f=l.useCallback(async x=>{await Rm({conversation:a,mode:x,ides:r,sendDaemonCommand:e,setCliViewModeOverrides:o})},[a,r,e,o]);return{handleBrowseMachineDirectory:u,handleSaveMachineWorkspace:p,handleLaunchMachineIde:d,handleLaunchMachineProvider:m,handleListMachineMeshes:h,handleLaunchMeshCoordinator:g,handleListMachineSavedSessions:k,setActiveCliViewMode:f}}function E1(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 _1(e,t,n=Date.now()){return!e||!E1(t)?null:{tabKey:e,nonce:n}}function H1({isMobile:e,conversations:t,visibleConversations:n,groupActiveTabIds:a,focusedGroup:r,groupedConvs:o,setSearchParams:i}){const[c,u]=l.useState(null),[p,d]=l.useState(null),m=l.useMemo(()=>{var x,w;if(!e){if(c){const b=t.find(S=>S.tabKey===c);if(b)return b}return n[0]}const f=a[r];if(f){const b=t.find(S=>S.tabKey===f);if(b)return b}return((x=o[r])==null?void 0:x[0])||((w=o[0])==null?void 0:w[0])},[t,c,r,a,o,e,n]),h=l.useCallback(f=>{u(f)},[]),g=l.useCallback(f=>{u(f.tabKey),i(x=>{const w=new URLSearchParams(x),b=uk(f);return b?w.set("activeTab",b):w.delete("activeTab"),w},{replace:!0})},[i]),k=l.useCallback((f,x)=>{const w=_1(f,x);w&&d(w)},[]);return{activeConv:m,openDesktopConversation:g,requestScrollToBottom:k,scrollToBottomRequest:p,setDesktopActiveTab:h}}function $1(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 F1(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 B1({activeConv:e,isMobile:t,liveSessionInboxState:n,sendDaemonCommand:a}){const r=l.useRef(null),o=l.useRef(null),i=l.useRef(null),c=l.useRef(null),u=l.useRef(null);l.useEffect(()=>{const p=()=>{i.current&&(clearTimeout(i.current),i.current=null),c.current&&(clearTimeout(c.current),c.current=null),u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null),o.current=null};if(t){p(),r.current=null;return}if(!(e!=null&&e.sessionId)){p(),r.current=null;return}const d=Js(e,n),m=F1({tabKey:e.tabKey,historySessionId:Qr(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:fn(e),liveState:d}),h=m.autoReadKey,g=$1({autoReadKey:h,shouldMarkSeen:m.shouldMarkSeen,completedKey:r.current,pendingKey:o.current});if(!m.shouldMarkSeen){g.shouldCancelPending&&p(),r.current=h;return}if(!g.shouldSchedule)return;g.shouldCancelPending&&p();const k=()=>{if(document.visibilityState!=="visible"||r.current===h)return;r.current=h,o.current=null,i.current=null,c.current=null,u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null);const x=m.readAt;a(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:x,completionMarker:m.completionMarker}).catch(()=>{})};if(o.current=g.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(k,1500);const x=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};u.current=x,document.addEventListener("visibilitychange",x);return}const f=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(k,800),u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null))};u.current=f,document.addEventListener("visibilitychange",f)},[e,t,n,a]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current),c.current&&clearTimeout(c.current),u.current&&document.removeEventListener("visibilitychange",u.current)},[])}function Bo(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 W1({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:n,ides:a,sendDaemonCommand:r,updateRouteChats:o,setToasts:i,setClearedTabs:c,setSearchParams:u}){var F;const{launchCli:p}=qr(),[d,m]=l.useState(!1),[h,g]=l.useState([]),[k,f]=l.useState(()=>Ut()),[x,w]=l.useState(!1),[b,S]=l.useState(null),N=l.useRef(null),v=l.useMemo(()=>n||t||e,[e,n,t]),y=!!v&&ft(v)&&!pt(v),j=l.useMemo(()=>{if(!v||!y)return null;const E=v.daemonId||v.routeId||"",H=Ts(v),_=Bo(v);return`${E}:${H}:${v.providerSessionId||""}:${_}`},[v,y]),C=l.useMemo(()=>!v||!y?"":Bo(v),[v,y]),{isCreatingChat:A,isRefreshingHistory:T,handleSwitchSession:D,handleNewChat:I,handleRefreshHistory:M}=Bm({sendDaemonCommand:r,activeConv:v,chats:(F=a.find(E=>E.id===(v==null?void 0:v.routeId)))==null?void 0:F.chats,updateRouteChats:o,setToasts:i,setClearedTabs:c}),P=l.useCallback(()=>{m(!0)},[]),$=l.useCallback(()=>{m(!1)},[]),L=l.useCallback(async()=>{if(!(!v||!y||x)){w(!0);try{const E=v.daemonId||v.routeId,H=Ts(v),_=Bo(v),G=await r(E,"list_saved_sessions",{agentType:H,providerType:H,kind:"cli",limit:50,...v.providerSessionId?{providerSessionId:v.providerSessionId}:{},..._?{workspace:_}:{}}),W=(G==null?void 0:G.result)??G;g(Array.isArray(W==null?void 0:W.sessions)?W.sessions:[])}catch(E){console.error("Refresh saved sessions failed",E),g([])}finally{w(!1)}}},[v,x,y,r]);l.useEffect(()=>{if(!d){N.current=null;return}if(!y){N.current=null,g([]),w(!1);return}!j||x||N.current!==j&&(N.current=j,L())},[L,d,x,y,j]);const R=l.useCallback(async E=>{if(!v||!y||!E.providerSessionId||!E.workspace)return;const H=v.daemonId||v.routeId,_=Ts(v);try{S(E.providerSessionId);const G=await p(H,{cliType:_,dir:E.workspace,resumeSessionId:E.providerSessionId,initialModel:fp(E.summaryMetadata,"model",{preferShortValue:!0})||void 0}),W=(G==null?void 0:G.result)??G,K=typeof(W==null?void 0:W.sessionId)=="string"?W.sessionId:typeof(W==null?void 0:W.id)=="string"?W.id:"";K&&u(V=>{const te=new URLSearchParams(V);return te.set("activeTab",K),te},{replace:!0}),$()}catch(G){console.error("Resume saved session failed",G)}finally{S(null)}},[$,v,y,r,u]);return{historyModalOpen:d,openHistoryModal:P,closeHistoryModal:$,historyTargetConv:v,isSavedSessionHistoryTarget:y,isHistoryCreatingChat:A,isHistoryRefreshingHistory:T,handleHistorySwitchSession:D,handleHistoryNewChat:I,handleHistoryRefresh:M,savedHistorySessions:h,savedHistoryFilters:k,setSavedHistoryFilters:f,missingWorkspaceResumePath:C,isSavedHistoryLoading:x,resumingSavedHistorySessionId:b,handleRefreshSavedHistory:L,handleResumeSavedHistorySession:R}}function O1({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c}){const[u,p]=l.useState(null),[d,m]=l.useState(null),h=l.useMemo(()=>{if(e||!a)return null;const w=c(a);return w&&!ft(w)&&!pt(w)?w:null},[e,a,c]),g=l.useMemo(()=>{const w=u==null?void 0:u.routeId;if(!w)return null;const b=u!=null&&u.tabKey?o.find(S=>S.tabKey===u.tabKey):r?o.find(S=>S.tabKey===r):null;return(b==null?void 0:b.routeId)===w?b:fs(o,w)},[o,u,r]),k=l.useMemo(()=>{if(g)return i.find(w=>w.id===g.routeId)},[i,g]);l.useEffect(()=>{h&&(p({routeId:h.routeId,tabKey:Rc(h)}),m(h),n({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,n,h]);const f=l.useCallback(w=>{w&&(p({routeId:w.routeId,tabKey:Rc(w)}),m(w))},[]),x=l.useCallback(()=>{p(null),m(null)},[]);return{remoteDialogConv:g,remoteDialogIdeEntry:k,remoteDialogActiveConv:d,setRemoteDialogActiveConv:m,openRemoteDialog:f,closeRemoteDialog:x}}function U1({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c,activeConv:u,sendDaemonCommand:p}){const{remoteDialogConv:d,remoteDialogIdeEntry:m,remoteDialogActiveConv:h,setRemoteDialogActiveConv:g,openRemoteDialog:k,closeRemoteDialog:f}=O1({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c}),[x,w]=l.useState(!1),[b,S]=l.useState(null),N=l.useCallback(async j=>{const C=j||u;!C||!ft(C)&&!pt(C)||(S(C),w(!0))},[u]),v=l.useCallback(()=>{w(!1),S(null)},[]),y=l.useCallback(async j=>{const C=b||u;if(!C||!ft(C)&&!pt(C)){v();return}w(!1);try{const A=Ts(C),T=C.routeId||C.daemonId||"";await p(T,"stop_cli",{cliType:A,targetSessionId:C.sessionId,mode:j,...Zr(C)})}catch(A){console.error("Stop CLI failed:",A)}finally{S(null)}},[u,v,b,p]);return{remoteDialogConv:d,remoteDialogIdeEntry:m,remoteDialogActiveConv:h,setRemoteDialogActiveConv:g,openRemoteDialog:k,closeRemoteDialog:f,cliStopDialogOpen:x,cliStopTargetConv:b,requestCliStop:N,cancelCliStop:v,confirmCliStop:y}}function Wo(e,t=!0){return(e??!0)&&t}const Hl=l.memo(function({activeConv:t,clearToken:n,isCliTerminal:a,ideEntry:r,terminalRef:o,handleModalButton:i,handleRelaunch:c,handleSendChat:u,handleForceSendChat:p,isSendingChat:d,sendFeedbackMessage:m=null,handleFocusAgent:h,isFocusingAgent:g,actionLogs:k,userName:f,scrollToBottomRequestNonce:x,isInputActive:w=!0,isVisible:b=!0}){const S=a,N=!a,v=Wo(b,S),y=Wo(b,N),j=Wo(b),C=Pm(t),A=C.status||C.modalMessage||C.modalButtons?{...t,...C.status?{status:C.status}:{},...C.modalMessage!==void 0?{modalMessage:C.modalMessage}:{},...C.modalButtons!==void 0?{modalButtons:C.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(ap,{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(gn,{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:S?"visible":"hidden",pointerEvents:S?"auto":"none"},children:s.jsx(zS,{activeConv:A,clearToken:n,terminalRef:o,handleSendChat:u,isSendingChat:d,sendFeedbackMessage:m,isVisible:v,isInputActive:w&&v})}),s.jsx("div",{"aria-hidden":a,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:N?"visible":"hidden",pointerEvents:N?"auto":"none"},children:s.jsx($i,{activeConv:A,ideEntry:r,handleSendChat:u,isSendingChat:d,sendFeedbackMessage:m,handleFocusAgent:h,isFocusingAgent:g,actionLogs:k,userName:f,scrollToBottomRequestNonce:x,isInputActive:w&&y,isVisible:y})})]}):s.jsx($i,{activeConv:A,ideEntry:r,handleSendChat:u,handleForceSendChat:p,isSendingChat:d,sendFeedbackMessage:m,handleFocusAgent:h,isFocusingAgent:g,actionLogs:k,userName:f,scrollToBottomRequestNonce:x,isInputActive:w&&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 q1({conversation:e,className:t="",onOpenNativeConversation:n,onOpenMachine:a,interactive:r=!0,meshOnly:o=!1}){var N,v,y;const{t:i}=Ce("common"),c=Ea(),u=Bs(e),p=o?null:Dp(e),d=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),m=!o&&e.streamSource==="agent-stream"&&!!e.agentName,h=!o&&!m&&(e.transport==="pty"||e.transport==="acp"),g=Wn(e),k=dk(e),f=(N=e.settings)==null?void 0:N.meshNodeFor,x=e.meshQueueStats,w=((v=e.coordinator)==null?void 0:v.meshId)||((y=e.settings)==null?void 0:y.meshCoordinatorFor),b=l.useCallback(()=>{if(a){a();return}u&&c("/dashboard",{state:{openMachineId:u}})},[u,c,a]),S=l.useCallback(()=>{if(n){n();return}const j=Um(e);j&&c(Ia(j))},[e,c,n]);return!d&&!m&&!h&&!p&&!f&&!x?null:s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[d&&(r?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:S,title:k,children:[s.jsx(gs,{size:12}),s.jsx("span",{children:k})]}):s.jsxs("span",{className:"conversation-meta-chip",title:k,children:[s.jsx(gs,{size:12}),s.jsx("span",{children:k})]})),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(Na,{size:12}),s.jsx("span",{children:g})]}),h&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(Na,{size:12}),s.jsx("span",{children:g})]}),p&&(r?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:b,title:p,children:[s.jsx(Ys,{size:12}),s.jsx("span",{children:p})]}):s.jsxs("span",{className:"conversation-meta-chip",title:p,children:[s.jsx(Ys,{size:12}),s.jsx("span",{children:p})]})),f&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(Ys,{size:12}),s.jsx("span",{children:i("dashboard.metaChips.meshNode")})]}),w&&x&&s.jsxs("span",{className:`conversation-meta-chip ${x.pending>0?"is-active":""}`,style:x.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${x.pending} pending, ${x.assigned} assigned, ${x.completed} completed, ${x.failed} failed`,children:[s.jsx(Sb,{size:12}),s.jsxs("span",{children:[x.pending," Pending"]})]})]})}function G1({selectedConversation:e,isAcp:t,isStandalone:n,selectedIdeEntry:a,actionLogs:r,userName:o,isSendingChat:i,sendFeedbackMessage:c=null,isFocusingAgent:u,onBack:p,onOpenNativeConversation:d,onOpenMachine:m,onOpenHistory:h,onOpenRemote:g,onOpenMeshGraph:k,onStopCli:f,cliViewMode:x,onSetCliViewMode:w,handleSendChat:b,handleForceSendChat:S,handleFocusAgent:N,handleModalButton:v,handleRelaunch:y}){var I,M;const j=l.useRef(null),C=ft(e)&&!t,A=C&&x==="terminal",T=!!e.daemonId&&!!((I=e.coordinator)!=null&&I.meshId||(M=e.settings)!=null&&M.meshCoordinatorFor),D=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 ${D} 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(al,{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:wt(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(q1,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>d(e),onOpenMachine:()=>m(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[C&&x&&s.jsx(im,{mode:x,onChange:w,compact:!0}),C&&f&&s.jsx("button",{onClick:()=>{f(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(Pt,{size:14})}),T&&k&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>k(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(as,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>h(e),type:"button",children:s.jsx(ol,{size:14})}),!t&&!C&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",children:s.jsx(gs,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(Hl,{activeConv:e,clearToken:0,isCliTerminal:A,ideEntry:a,terminalRef:j,handleModalButton:v,handleRelaunch:y,handleSendChat:b,handleForceSendChat:S,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:N,isFocusingAgent:u,actionLogs:r,userName:o})})]})}const Oo={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 z1(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function zm(){const[e,t]=l.useState("unix"),[n,a]=l.useState("powershell"),[r,o]=l.useState(!1),i=e==="unix"?"unix":n;l.useEffect(()=>{t(z1())},[]);const c=l.useCallback(()=>{navigator.clipboard.writeText(Oo[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:Oo[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:Oo[i].cmd}),s.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:r?"✓":"📋"})]}),s.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",s.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function Km({section:e,onSectionChange:t}){const n=[{key:"machines",label:"Machines",icon:gs},{key:"chats",label:"Chats",icon:kn}];return s.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:s.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:n.map(({key:a,label:r,icon:o})=>{const i=e===a;return s.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${i?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:i?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>t(a),type:"button","aria-pressed":i,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${i?"text-accent-primary":"bg-transparent text-current"}`,style:i?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:s.jsx(o,{size:15})}),s.jsx("span",{children:r})]},a)})})})}function Xa({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 An({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 an({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 K1({conversation:e,onCancel:t,onConfirm:n}){const{t:a}=Ce(),r=wt(e);return s.jsx(Yt,{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 Za({item:e,type:t,getAvatarText:n,onOpenConversation:a,onRequestHideConversation:r,onRequestStopCli:o,onOpenMeshGraph:i,onCollectChatDebugBundle:c,isMuted:u,onToggleMute:p}){const{t:d}=Ce(),m=t==="needs_attention"||t==="task_complete",h=t==="working",g=t==="earlier",k=t==="task_complete",{isReconnecting:f,isConnecting:x}=Sn(e.conversation),w=wt(e.conversation),b=On(e.conversation),S=nm(e.conversation,{requiresAction:t==="needs_attention"}),N=m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":h?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":g?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",v=m?"bg-accent-primary shadow-glow":h?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":g?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",y=g?"text-text-secondary":"text-text-primary",j=g?"text-text-muted":"text-text-secondary",C=g?"text-text-secondary opacity-80":"text-text-muted",A=g?"text-text-muted opacity-80":"text-text-muted",T=!h&&!k,D=tm(e.conversation),I="text-[color:var(--status-warning)]",M=P=>{if(!c)return;P.preventDefault(),P.stopPropagation();const $=c==null?void 0:c(e.conversation);Promise.resolve($).catch(L=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",L)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${N}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[m||h?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${v}`,style:m?{color:"var(--accent-on-primary)"}:void 0,children:n(w)}),D&&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:P=>{P.preventDefault(),P.stopPropagation(),i(e.conversation)},"aria-label":d("mobileInbox.openMeshGraphFor",{title:w}),title:d("mobileInbox.openLiveMeshGraph"),children:s.jsx(as,{size:13})})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>a(e.conversation),onContextMenu:M,type:"button",children:[s.jsx("div",{className:"flex items-center gap-2 pr-[124px]",children:s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${y}`,children:w})}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${j}`,children:[s.jsx("span",{className:"truncate",children:b}),s.jsx(Pr,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),f?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${I} animate-pulse`,children:d("mobileInbox.reconnectingItem")})]}):x?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:d("mobileInbox.connectingItem")})]}):S==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:I,children:d("mobileInbox.actionNeeded")})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${C}`,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:sp(e.timestamp)}),k&&s.jsx("span",{className:"rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:d("mobileInbox.done")}),p&&s.jsx("button",{type:"button",className:`mobile-inbox-mute-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border transition-colors ${u?"border-amber-500/60 bg-amber-500 text-white hover:bg-amber-600":"border-border-subtle bg-bg-primary/70 text-text-muted hover:border-border-default hover:text-text-primary"}`,onClick:P=>{P.preventDefault(),P.stopPropagation(),p()},"aria-label":u?d("mobileInbox.unmute",{title:w}):d("mobileInbox.mute",{title:w}),title:d(u?"mobileInbox.mutedTitle":"mobileInbox.muteNotifications"),children:u?s.jsx(qu,{size:13}):s.jsx(Vn,{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:P=>{P.preventDefault(),P.stopPropagation(),r()},"aria-label":d("mobileInbox.hideConversationAria",{title:w}),title:d("mobileInbox.hideConversationTitle"),children:s.jsx(il,{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:P=>{P.preventDefault(),P.stopPropagation(),o()},"aria-label":d("mobileInbox.stopSessionAria",{title:w}),title:d("mobileInbox.stopSessionTitle"),children:s.jsx(Pt,{size:13})})]})]})},e.conversation.tabKey)}function er({size:e=32}){return s.jsx("div",{className:"flex flex-col items-center gap-2.5",children:s.jsx("div",{className:"rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light",style:{width:e,height:e}})})}function Sd({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 V1({section:e,attentionItems:t,unreadItems:n,workingItems:a,completedItems:r,hiddenConversations:o,machineCards:i,getAvatarText:c,actionLogs:u,sendDaemonCommand:p,onOpenConversation:d,onShowAllHidden:m,onHideConversation:h,onOpenMeshGraph:g,onStopCli:k,onOpenNewSession:f,onOpenMachine:x,onOpenSettings:w,onSectionChange:b,wsStatus:S="connected",initialDataLoaded:N=!0,conversationsLoaded:v,isStandalone:y=!1,onCollectChatDebugBundle:j,isConversationMuted:C,onToggleMuteConversation:A}){const{t:T}=Ce(),[D,I]=l.useState(null),M=S==="disconnected"||S==="reconnecting"||S==="offline"||S==="auth_failed",P=!M&&!N,$=!M&&!(v??N),L=i.length>0,R=t.length>0||n.length>0||a.length>0||r.length>0,F=T(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),E=y?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",H=y?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",_=l.useCallback(async K=>{const V=un(K);if(!V)return;const te=Array.isArray(K.messages)?K.messages:[],le=Hp({activeConv:K,visibleMessages:te,actionLogs:u,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:te.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),de=await p(V,"get_chat_debug_bundle",{...dn(K),delivery:"daemon_file",frontendSnapshot:le}),ee=ya(de),z=Bp(ee),X=await Fp(z);X==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),bt.showToast($p(ee,{locatorCopyStatus:X}),X==="failed"?"warning":"success")},[u,p]),G=j||_,W=l.useCallback(()=>{D&&(h==null||h(D),I(null))},[D,h]);return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${E}`,children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:F}),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(Vn,{size:13}),s.jsx("span",{children:t.length+n.length})]}),s.jsx("button",{onClick:w,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:s.jsx(Gr,{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(an,{icon:s.jsx(er,{}),title:T(S==="offline"?"mobileInbox.networkOffline":S==="auth_failed"?"mobileInbox.sessionExpired":"mobileInbox.reconnecting"),subtitle:T(S==="offline"?"mobileInbox.waitingForNetwork":S==="auth_failed"?"mobileInbox.pleaseLogInAgain":"mobileInbox.restoringConnection")}):P?s.jsx(an,{icon:s.jsx(er,{}),title:T("mobileInbox.loading"),subtitle:T("mobileInbox.loadingSubtitle")}):i.length===0?s.jsx(an,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:T(y?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:T(y?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!y&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(zm,{})})}):s.jsx(An,{children:i.map((K,V)=>s.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${V>0?"border-t border-border-subtle/70":""}`,onClick:()=>x(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(Sd,{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(Xa,{title:T("mobileInbox.needsAttention"),className:"mb-0"}),s.jsx(An,{children:t.map((K,V)=>s.jsx("div",{className:V>0?"border-t border-border-subtle/70":"",children:s.jsx(Za,{item:K,type:"needs_attention",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:h?()=>I(K.conversation):void 0,onRequestStopCli:k?()=>k(K.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:G,isMuted:C==null?void 0:C(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(Xa,{title:T("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),s.jsx(An,{children:n.map((K,V)=>s.jsx("div",{className:V>0?"border-t border-border-subtle/70":"",children:s.jsx(Za,{item:K,type:"task_complete",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:h?()=>I(K.conversation):void 0,onRequestStopCli:k?()=>k(K.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:G,isMuted:C==null?void 0:C(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(Xa,{title:T("mobileInbox.workingNow"),className:"mb-0 mt-2"}),s.jsx(An,{children:a.map((K,V)=>s.jsx("div",{className:V>0?"border-t border-border-subtle/70":"",children:s.jsx(Za,{item:K,type:"working",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:h?()=>I(K.conversation):void 0,onRequestStopCli:k?()=>k(K.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:G,isMuted:C==null?void 0:C(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(Xa,{title:T("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),r.length>0?s.jsx(An,{children:r.map((K,V)=>s.jsx("div",{className:V>0?"border-t border-border-subtle/70":"",children:s.jsx(Za,{item:K,type:"earlier",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:h?()=>I(K.conversation):void 0,onRequestStopCli:k?()=>k(K.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:G,isMuted:C==null?void 0:C(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(an,{icon:s.jsx(er,{size:28}),title:T("mobileInbox.connecting"),subtitle:T("mobileInbox.connectingSubtitle")}):$?s.jsx(an,{icon:s.jsx(er,{size:28}),title:T("mobileInbox.loading"),subtitle:T("mobileInbox.loadingSubtitle")}):L?s.jsx(an,{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(kn,{size:20})}),title:T("mobileInbox.noConversations"),subtitle:T("paneGroup.newSessionDescription"),children:f&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:f,"aria-label":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(an,{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=Sg(o);return s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(An,{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(Sd,{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"&&f&&R&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:f,"aria-label":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"})]})}),D&&s.jsx(K1,{conversation:D,onCancel:()=>I(null),onConfirm:W}),s.jsx(Km,{section:e,onSectionChange:b})]})}function Y1(e){if(!e)return"";try{return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(e))}catch{return new Date(e).toLocaleString()}}function Vm(e){const t=[e.workspace||"Workspace unknown"],n=xn(e.summaryMetadata);n&&t.push(n),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const a=Y1(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:a?`Updated ${a}`:"",preview:(e.preview||"").trim()}}function $l({title:e,description:t,currentPath:n,directories:a,busy:r=!1,error:o="",confirmLabel:i="Use this folder",onClose:c,onNavigate:u,onConfirm:p}){const[d,m]=l.useState(n),{t:h}=Ce("common");l.useEffect(()=>{m(n)},[n]);const g=j1(n),k=d.trim();return s.jsx(Yt,{children:s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:s.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:c,"aria-label":"Close folder browser",children:s.jsx(Pt,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!g||r||u(g)},disabled:!g||r,children:[s.jsx(al,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:h("machine.workspaceBrowse.currentFolder")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:d,onChange:f=>m(f.target.value),onKeyDown:f=>{f.key!=="Enter"||!k||r||(f.preventDefault(),u(k))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!k||r||u(k)},disabled:!k||r,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:r?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):o?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:o}):a.length===0?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):s.jsx("div",{className:"p-3",children:a.map(f=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>u(f.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Bn,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:f.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:f.path})]})]},f.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:c,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>p(k||n),disabled:!k&&!n||r,children:i})]})]})})})}function ro({title:e,description:t,details:n,workspaceOptions:a,selectedWorkspaceKey:r,onWorkspaceChange:o,confirmLabel:i,busyLabel:c,busy:u=!1,showArgsInput:p,argsValue:d,onArgsChange:m,showModelInput:h,modelValue:g,onModelChange:k,historyProviderNode:f,onConfirm:x,onCancel:w}){const{t:b}=Ce("common"),S=i??b("machine.launchConfirm.launch"),N=c??b("machine.launchConfirm.launching"),v=a==null?void 0:a.find(j=>j.key===r),y=s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:w,"aria-label":b("machine.launchConfirm.closeAria"),children:s.jsx(Pt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[a&&a.length>0&&o&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.workspace")}),s.jsx("select",{value:r||"",onChange:j=>o(j.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:u,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})]}),f,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}`)),h&&k&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.languageModel")}),s.jsx("input",{type:"text",value:g||"",onChange:j=>k(j.target.value),placeholder:b("machine.launchConfirm.autoDetect"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]}),p&&m&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.cliArgs")}),s.jsx("input",{type:"text",value:d||"",onChange:j=>m(j.target.value),placeholder:b("machine.launchConfirm.cliArgsPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:w,disabled:u,children:b("machine.launchConfirm.cancel")}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:x,disabled:u,children:[s.jsx(Uu,{size:14}),u?N:S]})]})]})});return typeof document>"u"?y:Fs.createPortal(y,document.body)}function Cd(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function Ym(e){const{machine:t,currentWorkspacePath:n,currentWorkspaceId:a,includeHome:r=!0,homeLabel:o="Home directory",homeDescription:i="Launch without a workspace"}=e,c=[];r&&c.push({key:"__home__",label:o,description:i,workspaceId:null,workspacePath:null});for(const d of t.workspaces||[])c.push({key:`saved:${d.id}`,label:`${d.id===t.defaultWorkspaceId?"⭐ ":""}${Cd(d.path,d.label)}`,description:d.path,workspaceId:d.id,workspacePath:d.path});const u=(n==null?void 0:n.trim())||"",p=u?(t.workspaces||[]).find(d=>d.path===u):null;if(u&&!p&&c.push({key:`custom:${u}`,label:Cd(u),description:u,workspaceId:null,workspacePath:u}),a){const d=`saved:${a}`;if(c.some(m=>m.key===d))return{options:c,selectedKey:d}}return p?{options:c,selectedKey:`saved:${p.id}`}:u?{options:c,selectedKey:`custom:${u}`}:{options:c,selectedKey:"__home__"}}function Q1(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function J1(e){return[Q1(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function X1(e){return e.lastLaunchedAt?Kr(e.lastLaunchedAt):""}function Qm(e){return{metaText:J1(e),updatedLabel:X1(e)}}function Uo(e,t,n){return e?"ide":t>0?"cli":n>0?"acp":null}function Z1({selectedMachineEntry:e,cliProviders:t,acpProviders:n,machineAction:a,onBrowseDirectory:r,onListSavedSessions:o}){var ie,je,De,qe;const i=Qn(),[c,u]=l.useState(!1),p=(((ie=e.detectedIdes)==null?void 0:ie.length)||0)>0,d=l.useMemo(()=>(e.workspaces||[]).map(ye=>({id:ye.id,path:ye.path,label:ye.label})),[e]),m=e.defaultWorkspaceId||null,[h,g]=l.useState(m||((je=d[0])==null?void 0:je.id)||""),[k,f]=l.useState(""),[x,w]=l.useState(""),[b,S]=l.useState([]),[N,v]=l.useState(!1),[y,j]=l.useState(""),[C,A]=l.useState(!1),[T,D]=l.useState(Uo(p,t.length,n.length)),I=l.useRef(null),[M,P]=l.useState(null),$=l.useRef("__home__"),[L,R]=l.useState("__home__"),[F,E]=l.useState(""),[H,_]=l.useState(""),[G,W]=l.useState(""),[K,V]=l.useState([]),[te,le]=l.useState(()=>Ut().textQuery),[de,ee]=l.useState(()=>Ut().workspaceQuery),[z,X]=l.useState(()=>Ut().modelQuery),[U,Q]=l.useState(()=>Ut().resumableOnly),[ke,ve]=l.useState(()=>Ut().sortMode),[ge,me]=l.useState(!1),[B,O]=l.useState(!1),Y=l.useRef(null),se=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const Z=h==="__custom__"?k.trim():((De=d.find(ye=>ye.id===h))==null?void 0:De.path)||"",Ne=h==="__custom__"&&!!Z&&a.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(a.message),pe=h!=="__custom__"&&((qe=d.find(ye=>ye.id===h))==null?void 0:qe.path)||"",fe=l.useMemo(()=>(e.recentLaunches||[]).map(ye=>ye.workspace),[e]),Me=l.useCallback(async ye=>{v(!0),j("");try{const Fe=await r(ye);w(Fe.path),f(Fe.path),S(Fe.directories)}catch(Fe){j(Fe instanceof Error?Fe.message:"Could not load folder")}finally{v(!1)}},[r]),Ee=l.useCallback(()=>{var Fe;g("__custom__"),A(!0);const ye=El(e.platform,Rl(k.trim(),pe,fe,e.defaultWorkspacePath,(Fe=d.find(ut=>ut.id===m))==null?void 0:Fe.path,d.map(ut=>ut.path)));Me(ye)},[k,m,Me,fe,pe,e.platform,d]),q=l.useCallback(ye=>{if(ye!=null&&ye.workspaceId){g(ye.workspaceId),f("");return}if(ye!=null&&ye.workspacePath){g("__custom__"),f(ye.workspacePath);return}g(""),f("")},[]),oe=l.useCallback(ye=>{if(g(ye),ye==="__custom__"){Ee();return}f("")},[Ee]),Ie=l.useCallback(ye=>{g("__custom__"),f(ye)},[]),xe=l.useCallback((ye,Fe)=>{I.current=Fe,$.current=ye.selectedWorkspaceKey||"__home__",R(ye.selectedWorkspaceKey||"__home__"),E(ye.initialArgs||""),_(ye.initialModel||""),W(""),V([]);const ut=ye.providerType?`${e.id}:${ye.providerType}`:null;if(sC(se.current,ut)){const it=Ut();le(it.textQuery),ee(it.workspaceQuery),X(it.modelQuery),Q(it.resumableOnly),ve(it.sortMode)}se.current=ut,P(ye),ye.providerType&&o&&(me(!0),o(ye.providerType).then(it=>V(it||[])).catch(it=>console.warn("Failed to load saved sessions",it)).finally(()=>me(!1)))},[o,e.id]),he=l.useMemo(()=>lm(K,{textQuery:te,workspaceQuery:de,modelQuery:z,resumableOnly:U,sortMode:ke}),[z,U,K,ke,te,de]);l.useEffect(()=>{G&&(he.some(ye=>ye.providerSessionId===G)||W(""))},[he,G]);const Ze=l.useCallback(()=>{I.current&&(O(!0),I.current().finally(()=>{I.current=null,O(!1),P(null)}))},[]),Ae=l.useCallback(()=>{I.current=null,P(null)},[]),_e=l.useCallback(ye=>{$.current=ye,R(ye)},[]);return l.useEffect(()=>{var ye;Y.current!==e.id&&(Y.current=e.id,g(m||((ye=d[0])==null?void 0:ye.id)||"__custom__"),f(""),w(""),S([]),j(""),A(!1),le(Ut().textQuery),ee(Ut().workspaceQuery),X(Ut().modelQuery),Q(Ut().resumableOnly),ve(Ut().sortMode),se.current=null,D(Uo(p,t.length,n.length)))},[n.length,t.length,m,p,e.id,d]),l.useEffect(()=>{var ye;h!=="__custom__"&&(h&&d.some(Fe=>Fe.id===h)||g(m||((ye=d[0])==null?void 0:ye.id)||"__custom__"))},[m,h,d]),l.useEffect(()=>{T==="ide"&&p||T==="cli"&&t.length>0||T==="acp"&&n.length>0||D(Uo(p,t.length,n.length))},[T,n.length,t.length,p]),{showAllRecent:c,setShowAllRecent:u,hasIdeOptions:p,workspaceRows:d,defaultWorkspaceId:m,workspaceChoice:h,customWorkspacePath:k,browseCurrentPath:x,browseDirectories:b,browseBusy:N,browseError:y,browseDialogOpen:C,activeLauncherKind:T,launchConfirm:M,launchConfirmWorkspaceKeyRef:$,launchConfirmWorkspaceKey:L,launchConfirmArgs:F,launchConfirmModel:H,launchConfirmResumeId:G,launchConfirmSavedSessions:K,launchConfirmTextFilter:te,launchConfirmWorkspaceFilter:de,launchConfirmModelFilter:z,launchConfirmResumableOnly:U,launchConfirmSortMode:ke,filteredLaunchConfirmSavedSessions:he,launchConfirmSessionsLoading:ge,launchConfirmBusy:B,resolvedWorkspacePath:Z,canCreateMissingWorkspace:Ne,openBrowseDialog:Ee,loadBrowsePath:Me,handleWorkspaceChoiceChange:oe,chooseCustomWorkspacePath:Ie,setCustomWorkspacePath:f,setBrowseDialogOpen:A,setActiveLauncherKind:D,openLaunchConfirm:xe,handleConfirmLaunch:Ze,closeLaunchConfirm:Ae,setWorkspaceSelectionFromOption:q,setLaunchConfirmWorkspaceKeyAndSync:_e,setLaunchConfirmArgs:E,setLaunchConfirmModel:_,setLaunchConfirmResumeId:W,setLaunchConfirmTextFilter:le,setLaunchConfirmWorkspaceFilter:ee,setLaunchConfirmModelFilter:X,setLaunchConfirmResumableOnly:Q,setLaunchConfirmSortMode:ve}}function eN({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:n,cliProviders:a,acpProviders:r,selectedMachineNeedsUpgrade:o,appVersion:i,machineAction:c,isStandalone:u,section:p,showBottomNav:d,onBack:m,onSectionChange:h,onOpenConversation:g,onOpenRecent:k,onOpenMachineDetails:f,onMachineUpgrade:x,onLaunchDetectedIde:w,onAddWorkspace:b,onBrowseDirectory:S,onLaunchWorkspaceProvider:N,onListSavedSessions:v}){const{t:y}=Ce("common"),j=R=>R==="ide"?"IDE":R==="cli"?"CLI":"ACP",C=n.slice(0,4),A=t.slice(0,3),T=Z1({selectedMachineEntry:e,cliProviders:a,acpProviders:r,machineAction:c,onBrowseDirectory:S,onListSavedSessions:v}),D=l.useMemo(()=>C.map(R=>{const{metaText:F,updatedLabel:E}=Qm(R);return{key:`recent-launch:${R.id}`,primary:R.label,secondary:F,updatedLabel:E,onClick:()=>{const{options:H,selectedKey:_}=Ym({machine:{workspaces:T.workspaceRows,defaultWorkspaceId:T.defaultWorkspaceId},currentWorkspacePath:R.workspace,homeLabel:y("newSession.homeDirectory"),homeDescription:y("newSession.launchWithoutWorkspace")});T.openLaunchConfirm({title:R.kind==="ide"?Ir(y,"restart-ide",R.label):R.providerSessionId?dm(y,R.label):Ir(y,"start-fresh",R.label),description:R.kind==="ide"?Lr(y,"restart-ide"):R.providerSessionId?um(y):Lr(y,"start-fresh"),confirmLabel:R.kind==="ide"?Rr(y,"restart-ide"):R.providerSessionId?Fi(y,!0):Rr(y,"start-fresh"),busyLabel:R.kind==="ide"?Er(y,"restart-ide"):R.providerSessionId?cm(y,!0):Er(y,"start-fresh"),workspaceOptions:H,selectedWorkspaceKey:_,details:[{label:"Mode",value:j(R.kind)},...R.providerType?[{label:"Provider",value:R.providerType}]:[]]},async()=>{const G=H.find(W=>W.key===T.launchConfirmWorkspaceKeyRef.current);T.setWorkspaceSelectionFromOption(G),await k({...R,workspace:(G==null?void 0:G.workspacePath)??null})})}}}),[T,k,C,y]),I=l.useMemo(()=>A.map(R=>({key:`recent-chat:${R.conversation.tabKey}`,primary:wt(R.conversation),secondary:MS(R.conversation,{timestampLabel:R.timestamp?sp(R.timestamp):null}),unread:R.unread,onClick:()=>g(R.conversation)})),[g,A]),M=T.showAllRecent?D:D.slice(0,4),P=D.length>0,$=I.length>0,L=u?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${L} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:m,type:"button","aria-label":"Back",children:s.jsx(al,{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:rs(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:[$&&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:I.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))})]}),P&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"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))}),D.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 ${D.length-4} more`})})]}),!1,s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[o&&s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:x,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",i]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:f,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),T.browseDialogOpen&&s.jsx($l,{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(ro,{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?Fi(y,!!T.launchConfirmResumeId):T.launchConfirm.confirmLabel,busyLabel:T.launchConfirm.providerType?void 0:T.launchConfirm.busyLabel,busy:T.launchConfirmBusy,showArgsInput:T.launchConfirm.showArgsInput,argsValue:T.launchConfirmArgs,onArgsChange:T.setLaunchConfirmArgs,showModelInput:T.launchConfirm.showModelInput,modelValue:T.launchConfirmModel,onModelChange:T.setLaunchConfirmModel,historyProviderNode:T.launchConfirm.providerType&&(T.launchConfirmSessionsLoading||T.launchConfirmSavedSessions.length>0)&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),T.launchConfirmSessionsLoading&&s.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:Al(y)}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:T.launchConfirmTextFilter,onChange:R=>T.setLaunchConfirmTextFilter(R.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:T.launchConfirmWorkspaceFilter,onChange:R=>T.setLaunchConfirmWorkspaceFilter(R.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:T.launchConfirmModelFilter,onChange:R=>T.setLaunchConfirmModelFilter(R.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsxs("select",{value:T.launchConfirmSortMode,onChange:R=>T.setLaunchConfirmSortMode(R.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:T.launchConfirmResumableOnly,onChange:R=>T.setLaunchConfirmResumableOnly(R.target.checked),disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:T.launchConfirmResumeId,onChange:R=>T.setLaunchConfirmResumeId(R.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:rC(y)}),T.filteredLaunchConfirmSavedSessions.map(R=>s.jsxs("option",{value:R.providerSessionId,disabled:!R.canResume,children:[R.title||R.providerSessionId," ",R.canResume?"":"(workspace missing)"]},R.providerSessionId))]}),!T.launchConfirmSessionsLoading&&T.launchConfirmSavedSessions.length>0&&T.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),T.launchConfirmResumeId&&(()=>{const R=T.filteredLaunchConfirmSavedSessions.find(E=>E.providerSessionId===T.launchConfirmResumeId);if(!R)return null;const F=Vm(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:F.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:F.providerSessionId}),s.jsx("div",{className:"mt-1",children:F.metaLine}),F.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:F.updatedLabel}),F.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:F.preview})]})})()]}),onConfirm:T.handleConfirmLaunch,onCancel:T.closeLaunchConfirm}),d&&s.jsx(Km,{section:p,onSectionChange:h})]})}const jd=8e3;function tN(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 Jm(e,t,n){const a=l.useRef(new Map),[,r]=l.useState(0),o=l.useCallback(()=>r(g=>g+1),[]);l.useEffect(()=>{const g=a.current;if(g.size===0)return;const k=Date.now();let f=!1;for(const[x,w]of g){const b=e.get(x),S=w.muted===void 0||(b?b.muted===w.muted:!1),N=w.hidden===void 0||(b?b.surfaceHidden===w.hidden:!1),v=k-w.at>jd;(S&&N||v)&&(g.delete(x),f=!0)}f&&o()},[e,o]),l.useEffect(()=>{if(a.current.size===0)return;const g=setInterval(()=>{const k=a.current,f=Date.now();let x=!1;for(const[w,b]of k)f-b.at>jd&&(k.delete(w),x=!0);x&&o(),k.size===0&&clearInterval(g)},1e3);return()=>clearInterval(g)});const i=l.useCallback((g,k)=>{const f=a.current.get(g);a.current.set(g,{...f,...k,at:Date.now()}),o()},[o]),c=l.useCallback(g=>{const k=g.sessionId,f=k?a.current.get(k):void 0;return(f==null?void 0:f.muted)!==void 0?f.muted:Js(g,e).muted??!1},[e]),u=l.useCallback(g=>{const k=g.sessionId,f=k?a.current.get(k):void 0;return(f==null?void 0:f.hidden)!==void 0?f.hidden:Js(g,e).surfaceHidden??!1},[e]),p=l.useCallback((g,k)=>{const f=Bs(g),x=g.sessionId;!f||!x||(i(x,k),t(f,"set_conversation_prefs",{sessionId:x,...k,...Zr(g)}).then(w=>{const b=tN(w);b.confirmed||(console.warn("[conversation-prefs] set_conversation_prefs not confirmed",b.reason),a.current.delete(x),o(),n==null||n(`Couldn't update conversation — ${b.reason}`))}).catch(w=>{console.warn("[conversation-prefs] set_conversation_prefs failed",w),a.current.delete(x),o();const b=w instanceof Error?w.message:String(w??"the daemon is unreachable");n==null||n(`Couldn't update conversation — ${b}`)}))},[t,i,o,n]),d=l.useCallback(g=>{p(g,{muted:!c(g)})},[p,c]),m=l.useCallback((g,k)=>{p(g,{hidden:k})},[p]),h=l.useCallback(g=>{p(g,{hidden:!u(g)})},[p,u]);return{isMuted:c,isHidden:u,toggleMute:d,setHidden:m,toggleHidden:h}}function gr(e){return[...e].sort((t,n)=>{const a=n.timestamp-t.timestamp;return a!==0?a:t.conversation.tabKey.localeCompare(n.conversation.tabKey)})}function sN(e,t=[]){const n=new Map(e.map(r=>[r.conversation.tabKey,r])),a=t.map(r=>n.get(r)).filter(r=>!!r);return a.length===e.length?a:gr(e)}function nN(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:gr(n),unreadItems:gr(a),workingItems:sN(r,t),completedItems:gr(o)}}function oo(e,t){if(!t)return!1;const n=e.filter(a=>a.type==="adhdev-daemon"&&Xm(a)==="Connected");return n.length===0?!0:n.every(a=>a._sessionListAuthoritative===!0)}function Xm(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 aN(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:xn(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=Ma(a)?"cli":_n(a)?"acp":"ide",o=xn(a.summaryMetadata);return{id:`${r}:${a.type}:${a.workspace||""}`,label:((i=a.activeChat)==null?void 0:i.title)||(Ma(a)?a.cliName||a.type:_n(a)&&a.cliName||a.type),kind:r,providerType:a.type,providerSessionId:a.providerSessionId,subtitle:_n(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 rN(e,t,n=[]){const a=new Map;for(const o of t){const i=Bs(o.conversation),c=a.get(i);c?c.push(o):a.set(i,[o])}const r=new Map;for(const o of n){const i=Bs(o),c=r.get(i);c?c.push(o):r.set(i,[o])}return e.map(o=>{const i=a.get(o.id)||[],c=r.get(o.id)||[],u=[...i].sort((f,x)=>x.timestamp-f.timestamp)[0]||null,p=(u==null?void 0:u.conversation)||null,d=Ii(o),m=i.filter(f=>f.unread||f.requiresAction).length,h=i.filter(f=>Aa(f.conversation)).length+c.filter(Aa).length,g=Xm(o),k=[o.platform||"machine",g].filter(Boolean);return{id:o.id,label:rs(o,{fallbackId:o.id}),subtitle:k.join(" · "),unread:m,total:i.length,generatingCount:h,latestConversation:p,latestTimestamp:(u==null?void 0:u.timestamp)||0,fallbackActivityAt:d,preview:p?DS(p,Yp(p)):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((o,i)=>{const c=o.latestTimestamp||o.fallbackActivityAt||0,u=i.latestTimestamp||i.fallbackActivityAt||0;return u!==c?u-c:o.label.localeCompare(i.label)})}function oN(e){return e==="chat"}function tr(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 iN({conversations:e,machineEntries:t,items:n,selectedConversation:a,selectedTabKey:r,screen:o,liveSessionInboxState:i,sendDaemonCommand:c,requestedActiveTabKey:u,onRequestedActiveTabConsumed:p,requestedMachineId:d,onRequestedMachineConsumed:m,requestedMobileSection:h,onRequestedMobileSectionConsumed:g,setSelectedTabKey:k,setScreen:f,setSelectedMachineId:x,setSection:w,setMachineBackTarget:b,resetMachineAction:S}){const N=l.useRef(null),v=l.useCallback(y=>{if(!(y!=null&&y.sessionId))return;const j=Js(y,i),C=Math.max(Date.now(),fn(y),j.lastUpdated||0);tr("mark_read:start",{tabKey:y.tabKey,sessionId:y.sessionId,displayPrimary:wt(y),inboxBucket:j.inboxBucket,unread:j.unread,lastSeenAt:j.lastSeenAt,lastUpdated:j.lastUpdated,activityAt:fn(y),readAt:C}),c(Bs(y)||y.routeId,"mark_session_seen",{sessionId:y.sessionId,providerSessionId:y.providerSessionId,seenAt:C,completionMarker:j.completionMarker}).then(A=>{tr("mark_read:result",{tabKey:y.tabKey,sessionId:y.sessionId,result:A})}).catch(A=>{tr("mark_read:error",{tabKey:y.tabKey,sessionId:y.sessionId,error:A instanceof Error?A.message:String(A)})})},[i,c]);return l.useEffect(()=>{var j;if(!a){oN(o)&&f("inbox"),k(((j=e[0])==null?void 0:j.tabKey)||null),N.current=null;return}if(o!=="chat"){N.current=null;return}const y=`${a.tabKey}:${a.sessionId||""}`;N.current!==y&&(N.current=y,v(a))},[e,v,o,a,f,k]),l.useEffect(()=>{if(!u)return;const y=e.find(j=>j.tabKey===u);y&&(k(y.tabKey),f("chat"),p==null||p())},[e,p,u,f,k]),l.useEffect(()=>{if(!d)return;const y=t.find(j=>j.id===d);y&&(x(y.id),S(),w("machines"),b("inbox"),f("machine"),m==null||m())},[t,m,d,S,b,f,w,x]),l.useEffect(()=>{h&&(w(h),f("inbox"),g==null||g())},[g,h,f,w]),l.useEffect(()=>{const y=n.filter(j=>j.inboxBucket==="task_complete"||j.unread);y.length!==0&&tr("inbox_state",{screen:o,selectedTabKey:r,items:y.map(j=>{const C=Js(j.conversation,i);return{liveState:C,tabKey:j.conversation.tabKey,sessionId:j.conversation.sessionId,displayPrimary:wt(j.conversation),serverBucket:C.inboxBucket,computedBucket:j.inboxBucket,serverUnread:C.unread,computedUnread:j.unread,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,activityAt:fn(j.conversation)}})})},[n,i,o,r]),{markConversationRead:v}}function lN(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Nd(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function cN(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function dN({sendDaemonCommand:e,navigate:t,ides:n,conversations:a}){const{launchCli:r}=qr(),[o,i]=l.useState("idle"),[c,u]=l.useState(""),[p,d]=l.useState(null),m=l.useCallback(()=>{i("idle"),u(""),d(null)},[]),h=l.useCallback(async(S,N,v)=>{var y;try{i("loading"),u(`Launching ${N}…`);const j={ideType:N,enableCdp:!0};(y=v==null?void 0:v.workspacePath)!=null&&y.trim()&&(j.workspace=v.workspacePath.trim()),await e(S,"launch_ide",j),i("done"),u(`${N} launch requested`)}catch(j){i("error"),u(j instanceof Error?j.message:"Launch IDE failed"),console.error("Launch IDE failed",j)}},[e]),g=l.useCallback(async(S,N,v)=>{if(N.trim())try{i("loading"),u(v!=null&&v.createIfMissing?"Creating folder…":"Saving workspace…");const y=await e(S,"workspace_add",{path:N.trim(),createIfMissing:(v==null?void 0:v.createIfMissing)===!0});if(y!=null&&y.success){i("done"),u(v!=null&&v.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),u((y==null?void 0:y.error)||"Could not save workspace")}catch(y){i("error"),u(y instanceof Error?y.message:"Could not save workspace")}},[e]),k=l.useCallback(async S=>{i("loading"),u("Starting daemon upgrade…");const N=n.find(y=>y.id===S||y.daemonId===S),v=await XC(e,S,N);i(v.state),u(v.message)},[n,e]),f=l.useCallback(async(S,N,v,y)=>{var A,T,D;const j=Date.now(),C={machineId:S,kind:N,providerType:v,workspaceId:(y==null?void 0:y.workspaceId)||null,workspacePath:(y==null?void 0:y.workspacePath)||null,resumeSessionId:(y==null?void 0:y.resumeSessionId)||null,startedAt:j};try{i("loading"),u(`Launching ${v}…`),d(C);const I={cliType:v};(A=y==null?void 0:y.workspacePath)!=null&&A.trim()?I.dir=y.workspacePath.trim():y!=null&&y.workspaceId?I.workspaceId=y.workspaceId:y!=null&&y.useHome&&(I.useHome=!0),y!=null&&y.resumeSessionId&&(I.resumeSessionId=y.resumeSessionId),(T=y==null?void 0:y.args)!=null&&T.trim()&&(I.cliArgs=y.args.trim().split(/\s+/).filter(Boolean)),(D=y==null?void 0:y.model)!=null&&D.trim()&&(I.initialModel=y.model.trim());const M=await r(S,I),P=(M==null?void 0:M.result)||M,$=(P==null?void 0:P.sessionId)||(P==null?void 0:P.id);if(M!=null&&M.success&&$){d(null),i("done"),u(`${v} launched`),t(Ia($));return}if(M!=null&&M.success){i("loading"),u(`${v} launch requested — waiting for session…`);return}d(null),i("error"),u((M==null?void 0:M.error)||(P==null?void 0:P.error)||`Could not launch ${N.toUpperCase()} workspace`)}catch(I){if(cN(I)){i("loading"),u(`${v} launch requested — waiting for session…`);return}d(null),i("error"),u(I instanceof Error?I.message:`Could not launch ${N.toUpperCase()} workspace`)}},[t,e]),x=l.useCallback(async(S,N)=>{try{const v=await e(S,"list_saved_sessions",{providerType:N,kind:"cli",limit:30}),y=(v==null?void 0:v.result)??v;return Array.isArray(y==null?void 0:y.sessions)?y.sessions:[]}catch(v){return console.error("Failed to list saved sessions on mobile:",v),[]}},[e]),w=l.useCallback(async(S,N)=>_l(e,S,N),[e]);l.useEffect(()=>{if(!p)return;const S=Nd(p.workspacePath),N=n.find(y=>{var I,M,P,$;if(!y||y.type==="adhdev-daemon"||lN(y.daemonId||y.id)!==p.machineId||(y.transport==="acp"?"acp":y.transport==="pty"?"cli":null)!==p.kind||String(y.agentType||y.type||"")!==p.providerType)return!1;const T=String(y.providerSessionId||"");if(p.resumeSessionId&&T)return T===p.resumeSessionId;if(S){const L=Nd(y.workspace||y.runtimeWorkspaceLabel);return L?L===S:!1}return Number(y.lastUpdated||y._lastUpdate||y.timestamp||(($=(P=(M=(I=y.activeChat)==null?void 0:I.messages)==null?void 0:M.at)==null?void 0:P.call(M,-1))==null?void 0:$.timestamp)||0)>=p.startedAt-5e3});if(!N)return;const v=qm({entrySessionId:N.sessionId,entryInstanceId:N.instanceId,entryRouteId:N.id,conversations:a});v&&(d(null),i("done"),u(`${p.providerType} launched`),t(Ia(v)))},[a,n,t,p]),l.useEffect(()=>{if(!p)return;const S=window.setTimeout(()=>{d(N=>!N||N.startedAt!==p.startedAt?N:(i("error"),u("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(S)},[p]);const b=l.useCallback(async(S,N)=>{var v;if(N.kind==="ide"&&N.providerType){await h(S,N.providerType,{workspacePath:N.workspace||null});return}if((N.kind==="cli"||N.kind==="acp")&&N.providerType){const y=((v=N.workspace)==null?void 0:v.trim())||"";await f(S,N.kind,N.providerType,{workspacePath:y||null,useHome:!y,resumeSessionId:N.providerSessionId||null})}},[h,f]);return{machineAction:{state:o,message:c},resetMachineAction:m,handleLaunchDetectedIde:h,handleAddWorkspace:g,handleMachineUpgrade:k,handleLaunchWorkspaceProvider:f,handleListSavedSessions:x,handleBrowseDirectory:w,handleOpenRecent:b}}function uN({conversations:e,selectedConversation:t,machineBackTarget:n,markConversationRead:a,resetMachineAction:r,setSelectedTabKey:o,setScreen:i,setSelectedMachineId:c,setSection:u,setMachineBackTarget:p}){const d=l.useCallback(w=>{o(w.tabKey),i("chat"),a(w)},[a,i,o]),m=l.useCallback(w=>{const b=e.find(S=>S.routeId===w.routeId&&S.streamSource==="native");b&&(o(b.tabKey),i("chat"),a(b))},[e,a,i,o]),h=l.useCallback(()=>{a(t),i("inbox")},[a,t,i]),g=l.useCallback((w,b="inbox")=>{c(w),r(),u("machines"),p(b),i("machine")},[r,p,i,u,c]),k=l.useCallback(w=>{const b=Bs(w);b&&g(b,"chat")},[g]),f=l.useCallback(()=>{r(),i(n)},[n,r,i]),x=l.useCallback(w=>{u(w),i("inbox")},[i,u]);return{openConversation:d,openNativeConversation:m,backFromConversation:h,openMachine:g,openConversationMachine:k,backFromMachine:f,changeMachineSection:x}}function Gn(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function pN(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function mN({conversations:e,hiddenConversations:t,ides:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,userName:c,requestedActiveTabKey:u,onRequestedActiveTabConsumed:p,requestedMachineId:d,onRequestedMachineConsumed:m,requestedMobileSection:h,onRequestedMobileSectionConsumed:g,onOpenHistory:k,onOpenRemote:f,onStopCli:x,wsStatus:w,isConnected:b,initialDataLoaded:S=!0,onShowAllHiddenConversations:N,onHideConversation:v,onOpenMeshGraph:y,onOpenNewSession:j,liveSessionInboxState:C,setCliViewModeOverrides:A}){const[T,D]=l.useState(()=>{var oe;return((oe=e[0])==null?void 0:oe.tabKey)||null}),[I,M]=l.useState(()=>e[0]?"chat":"inbox"),[P,$]=l.useState("chats"),[L,R]=l.useState(null),[F,E]=l.useState("inbox"),H=l.useRef([]),_=Ea(),G="1.0.41",W=l.useMemo(()=>e.find(oe=>oe.tabKey===T)||e[0]||null,[e,T]),K=l.useMemo(()=>W?n.find(oe=>oe.id===W.routeId):void 0,[n,W]),V=l.useMemo(()=>!W||pt(W)||!ft(W)?null:Yn(W),[W]),te=l.useMemo(()=>n.filter(oe=>oe.type==="adhdev-daemon").sort(hl),[n]),le=l.useMemo(()=>te.find(oe=>oe.id===L)||null,[te,L]),de=eo({sendDaemonCommand:r,activeConv:W||void 0,setActionLogs:o,isStandalone:i}),ee=dN({sendDaemonCommand:r,navigate:_,ides:n,conversations:e}),z=rS(e),X=l.useMemo(()=>e.map(oe=>{const Ie=I==="chat"&&(W==null?void 0:W.tabKey)===oe.tabKey,xe=Vr(oe,C,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Ie}),he=fn(oe),Ze=Yp(oe),Ae=sm(oe,Ze);return{conversation:oe,timestamp:he,preview:Ae,unread:xe.unread,requiresAction:xe.requiresAction,isWorking:xe.isWorking,inboxBucket:xe.inboxBucket}}),[e,C,I,W,z]),{markConversationRead:U}=iN({conversations:e,machineEntries:te,items:X,selectedConversation:W,selectedTabKey:T,screen:I,liveSessionInboxState:C,sendDaemonCommand:r,requestedActiveTabKey:u,onRequestedActiveTabConsumed:p,requestedMachineId:d,onRequestedMachineConsumed:m,requestedMobileSection:h,onRequestedMobileSectionConsumed:g,setSelectedTabKey:D,setScreen:M,setSelectedMachineId:R,setSection:$,setMachineBackTarget:E,resetMachineAction:ee.resetMachineAction}),Q=uN({conversations:e,selectedConversation:W,machineBackTarget:F,markConversationRead:U,resetMachineAction:ee.resetMachineAction,setSelectedTabKey:D,setScreen:M,setSelectedMachineId:R,setSection:$,setMachineBackTarget:E}),{isMuted:ke,toggleMute:ve}=Jm(C,r),{attentionItems:ge,unreadItems:me,workingItems:B,completedItems:O}=l.useMemo(()=>nN(X,H.current),[X]);l.useEffect(()=>{H.current=B.map(oe=>oe.conversation.tabKey)},[B]);const Y=l.useMemo(()=>le?X.filter(oe=>Bs(oe.conversation)===le.id):[],[X,le]),se=l.useMemo(()=>aN(le,n),[n,le]),Z=!!le&&no(le,qs(le,G)),Ne=l.useMemo(()=>(le==null?void 0:le.availableProviders)||[],[le]),pe=l.useMemo(()=>Ne.filter(oe=>Gn(oe,"cli")).map(oe=>({type:oe.type,displayName:oe.displayName||oe.type,icon:oe.icon})),[Ne]),fe=l.useMemo(()=>Ne.filter(oe=>Gn(oe,"acp")).map(oe=>({type:oe.type,displayName:oe.displayName||oe.type,icon:oe.icon})),[Ne]),Me=l.useMemo(()=>rN(te,X,t),[X,te,t]),Ee=l.useMemo(()=>oo(n,S),[n,S]),q=l.useCallback(async oe=>{le&&await ee.handleOpenRecent(le.id,oe)},[ee,le]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:I==="chat"&&W?s.jsx(G1,{selectedConversation:W,isAcp:pt(W),isStandalone:i,selectedIdeEntry:K,actionLogs:a,userName:c,isSendingChat:de.isSendingChat,sendFeedbackMessage:de.sendFeedbackMessage,isFocusingAgent:de.isFocusingAgent,handleModalButton:de.handleModalButton,handleRelaunch:de.handleRelaunch,onBack:Q.backFromConversation,onOpenNativeConversation:Q.openNativeConversation,onOpenMachine:Q.openConversationMachine,onOpenHistory:k,onOpenRemote:f,onOpenMeshGraph:y,onStopCli:x,cliViewMode:V,onSetCliViewMode:async oe=>{await Rm({conversation:W,mode:oe,ides:n,sendDaemonCommand:r,setCliViewModeOverrides:A})},handleSendChat:de.handleSendChat,handleForceSendChat:de.handleForceSendChat,handleFocusAgent:de.handleFocusAgent}):I==="machine"&&le?s.jsx(eN,{selectedMachineEntry:le,selectedMachineConversations:Y,selectedMachineRecentLaunches:se,cliProviders:pe,acpProviders:fe,selectedMachineNeedsUpgrade:Z,appVersion:G,machineAction:ee.machineAction,isStandalone:i,section:P,showBottomNav:F==="inbox",onBack:Q.backFromMachine,onSectionChange:Q.changeMachineSection,onOpenConversation:Q.openConversation,onOpenRecent:q,onOpenMachineDetails:()=>_(`/machines/${le.id}`),onMachineUpgrade:()=>ee.handleMachineUpgrade(le.id),onLaunchDetectedIde:(oe,Ie)=>ee.handleLaunchDetectedIde(le.id,oe,Ie),onAddWorkspace:(oe,Ie)=>ee.handleAddWorkspace(le.id,oe,Ie),onBrowseDirectory:oe=>ee.handleBrowseDirectory(le.id,oe),onLaunchWorkspaceProvider:(oe,Ie,xe)=>ee.handleLaunchWorkspaceProvider(le.id,oe,Ie,xe),onListSavedSessions:oe=>ee.handleListSavedSessions(le.id,oe)}):s.jsx(V1,{section:P,attentionItems:ge,unreadItems:me,workingItems:B,completedItems:O,hiddenConversations:t,machineCards:Me,getAvatarText:pN,actionLogs:a,sendDaemonCommand:r,onOpenConversation:Q.openConversation,onShowAllHidden:N,onHideConversation:v,onOpenMeshGraph:y,onStopCli:x,onOpenNewSession:j,onOpenMachine:Q.openMachine,onOpenSettings:()=>_("/settings"),onSectionChange:$,wsStatus:w,isConnected:b,initialDataLoaded:S,conversationsLoaded:Ee,isStandalone:i,isConversationMuted:ke,onToggleMuteConversation:ve})})}function qo(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function hN({conversations:e,numGroups:t,onMoveTab:n,onReceiveTab:a,onOwnTabDrop:r,onClearPreviewOrder:o}){const i=l.useRef(0),[c,u]=l.useState(!1),[p,d]=l.useState(null),m=l.useCallback(()=>{i.current=0,u(!1),d(null)},[]);l.useEffect(()=>(window.addEventListener("dragend",m),window.addEventListener("drop",m),()=>{window.removeEventListener("dragend",m),window.removeEventListener("drop",m)}),[m]);const h=l.useCallback(x=>{x.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,u(!0))},[]),g=l.useCallback(x=>{if(!x.dataTransfer.types.includes("text/tab-key"))return;if(x.preventDefault(),!qo(t,n)){d("merge");return}const w=x.currentTarget.getBoundingClientRect(),b=x.clientX-w.left,S=w.width/3;b<S?d("split-left"):b>S*2?d("split-right"):d("merge")},[t,n]),k=l.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,u(!1),d(null))},[]),f=l.useCallback(x=>{i.current=0,u(!1);const w=x.dataTransfer.getData("text/tab-key"),b=w?e.some(N=>N.tabKey===w):!1,S=p;if(d(null),o(),!!w){if(x.preventDefault(),S==="split-left"&&qo(t,n)){n==null||n(w,"split-left");return}if(S==="split-right"&&qo(t,n)){n==null||n(w,"split-right");return}if(b){r(w);return}a==null||a(w)}},[e,p,t,n,a,r,o]);return{dragOver:c,dropAction:p,resetDragState:m,handleDragEnter:h,handleDragOver:g,handleDragLeave:k,handleDrop:f}}function fN(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 bN({conversations:e,initialActiveTabId:t,initialTabOrder:n,onActiveTabChange:a,onTabOrderChange:r}){const[o,i]=l.useState(t??null),[c,u]=l.useState(n??[]),[p,d]=l.useState(null),m=l.useRef(null),h=l.useRef(null),g=l.useRef(a),k=l.useRef(r);l.useEffect(()=>{g.current=a},[a]),l.useEffect(()=>{k.current=r},[r]),l.useEffect(()=>{t&&t!==o&&i(t)},[t,o]),l.useEffect(()=>{u(j=>{const C=fN(j,e);return C.length===j.length&&C.every((A,T)=>A===j[T])?j:C})},[e]);const f=l.useMemo(()=>{const j=p??c;if(j.length===0)return e;const C=new Map(j.map((A,T)=>[A,T]));return[...e].sort((A,T)=>{const D=C.get(A.tabKey)??999,I=C.get(T.tabKey)??999;return D-I})},[e,p,c]);l.useEffect(()=>{var C,A;if(f.length===0){o!==null&&(i(null),(C=g.current)==null||C.call(g,null));return}if(o&&f.some(T=>T.tabKey===o))return;const j=f[0].tabKey;j!==o&&(i(j),(A=g.current)==null||A.call(g,j))},[f,o]);const x=l.useMemo(()=>f.find(j=>j.tabKey===o),[f,o]),w=l.useCallback(j=>{var C;i(j),(C=g.current)==null||C.call(g,j)},[]),b=l.useCallback((j,C,A)=>{u(T=>{var P;const D=T.filter($=>$!==j),I=D.indexOf(C);if(I<0)return T;const M=A==="left"?I:I+1;return D.splice(M,0,j),(P=k.current)==null||P.call(k,D),D}),d(null)},[]),S=l.useCallback((j,C,A)=>{const D=(c.length>0?c:e.map(P=>P.tabKey)).filter(P=>P!==j),I=D.indexOf(C);if(I<0)return;const M=A==="left"?I:I+1;D.splice(M,0,j),m.current=D,d(D)},[c,e]),N=l.useCallback(()=>{var C;const j=m.current;j&&(u(j),(C=k.current)==null||C.call(k,j))},[]),v=l.useCallback(()=>{m.current=null,d(null)},[]),y=l.useCallback(j=>{u(C=>{var T;const A=C.filter(D=>D!==j);return A.push(j),(T=k.current)==null||T.call(k,A),A})},[]);return{activeTabId:o,activeConv:x,sortedConversations:f,previewOrderRef:m,draggingTabRef:h,selectTab:w,handleTabReorder:b,updatePreviewOrder:S,commitPreviewOrder:N,clearPreviewOrder:v,moveTabToEnd:y,setDraggingTabKey:j=>{h.current=j}}}function gN({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 Fl({conversationsCount:e,isSplitMode:t,isStandalone:n,hasRegisteredMachines:a=!1,suppressGuide:r=!1,onOpenNewSession:o,isLoading:i=!1}){const{t:c}=Ce("common");if(r)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});if(i)return s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center gap-3 -mt-8 text-text-muted",children:[s.jsx("div",{className:"w-7 h-7 rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light","aria-hidden":"true"}),s.jsx("p",{className:"text-sm",children:c("paneGroup.loadingSessions")})]});const u=!n&&!a,p=a&&!!o,d=c(a?"paneGroup.noConversations":n?"paneGroup.waitingForDaemon":"paneGroup.connectYourMachines"),m=c(a?"paneGroup.newSessionDescription":n?"paneGroup.daemonDescription":"paneGroup.installDescription");return e===0&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:d}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:m}),p&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:o,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:c("paneGroup.newSession"),"aria-label":c("paneGroup.newSession"),children:[s.jsx(cl,{size:14}),s.jsx("span",{children:c("paneGroup.newSession")})]})}),u&&s.jsx(zm,{}),u&&s.jsx("div",{className:"mt-8",children:s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:"📚 Read the documentation →"})})]})]}):s.jsx("div",{className:"text-sm text-text-muted opacity-50",children:t?"Move a tab here to view":"No active agent"})}const Zm="adhdev-tab-shortcuts";function eh(){try{return JSON.parse(localStorage.getItem(Zm)||"{}")}catch{return{}}}function th({enabled:e=!0,sortedTabKeys:t,onFocus:n,onSelectTab:a}){const r=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>eh()),[c,u]=l.useState(null),p=l.useCallback(m=>{const h=[];return m.metaKey&&h.push(r?"⌘":"Meta"),m.ctrlKey&&h.push("Ctrl"),m.altKey&&h.push(r?"⌥":"Alt"),m.shiftKey&&h.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(m.key)?null:(h.push(m.key.length===1?m.key.toUpperCase():m.key),h.join("+"))},[r]),d=l.useCallback(m=>{i(m);try{localStorage.setItem(Zm,JSON.stringify(m))}catch{}},[]);return l.useEffect(()=>{if(!e||!c)return;const m=h=>{if(h.preventDefault(),h.stopPropagation(),h.key==="Escape"){u(null);return}const g=p(h);if(!g)return;const k={...o};for(const[f,x]of Object.entries(k))x===g&&delete k[f];k[c]=g,d(k),u(null)};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[e,c,o,d,p]),l.useEffect(()=>{if(!e)return;const m=h=>{if(!(!h.ctrlKey&&!h.metaKey&&!h.altKey)){for(const[g,k]of Object.entries(o))if(t.includes(g)&&p(h)===k){h.preventDefault(),n(),a(g);return}}};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[e,o,t,n,a,p]),{isMac:r,tabShortcuts:o,shortcutListening:c,setShortcutListening:u,saveShortcuts:d}}const Go=e=>{e.preventDefault()},xN=l.memo(function({conv:t,isActive:n,isDraggedTab:a,isTaskCompleteUnread:r,shortcut:o,conversationKeys:i,draggingTabRef:c,onFocus:u,onSelectTab:p,onConversationActivated:d,onPreviewReorder:m,onReorderTab:h,onCommitPreviewOrder:g,onClearPreviewOrder:k,onDragStateReset:f,onDragTabKeyChange:x,onReceiveTab:w,onOpenContextMenu:b,longPressTimer:S,isGroupActive:N}){const v=Sn(t),y=v.isGenerating?"agent-tab-generating":v.isWaiting?"agent-tab-waiting":"",j=v.isReconnecting,C=AS(t),A=TS(t),T=tm(t),D=l.useCallback(H=>{c.current=t.tabKey,x(t.tabKey),H.dataTransfer.setData("text/tab-key",t.tabKey),H.dataTransfer.effectAllowed="move"},[t.tabKey,c,x]),I=l.useCallback(()=>{c.current=null,x(null),g(),k(),f()},[c,x,g,k,f]),M=l.useCallback(H=>{const _=c.current;if(!(!_||_===t.tabKey)&&H.dataTransfer.types.includes("text/tab-key")){H.preventDefault(),H.stopPropagation();const G=H.currentTarget.getBoundingClientRect(),W=H.clientX<G.left+G.width/2?"left":"right";m(_,t.tabKey,W)}},[t.tabKey,c,m]),P=l.useCallback(H=>{H.preventDefault(),H.stopPropagation();const _=H.dataTransfer.getData("text/tab-key");if(_&&_!==t.tabKey){const G=H.currentTarget.getBoundingClientRect(),W=H.clientX<G.left+G.width/2?"left":"right";i.includes(_)?h(_,t.tabKey,W):w&&w(_)}k()},[t.tabKey,i,h,w,k]),$=l.useCallback(H=>{H.stopPropagation(),u(),p(t.tabKey),d(t)},[t,d,u,p]),L=l.useCallback(H=>{H.preventDefault(),b(H.clientX,H.clientY,t.tabKey)},[t.tabKey,b]),R=l.useCallback(H=>{const _=H.touches[0];S.current=setTimeout(()=>{b(_.clientX,_.clientY,t.tabKey)},600)},[t.tabKey,S,b]),F=l.useCallback(()=>{S.current&&clearTimeout(S.current)},[S]),E=["adhdev-dockview-tab",y,n&&"is-active",N&&"is-group-active",j&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:E,draggable:!0,onDragStart:D,onDragEnd:I,onDragOver:M,onDrop:P,onClick:$,onContextMenu:L,onTouchStart:R,onTouchEnd:F,onTouchMove:F,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(as,{size:11})}),r&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:v.isGenerating?s.jsx("div",{className:"tab-spinner"}):v.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):j?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):v.isConnecting?s.jsx("div",{className:"tab-connecting-spinner"}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),C.length>0&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-role",title:A,"aria-label":A||C.join(" · "),children:C.join(" · ")}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:wt(t),children:wt(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:pn(t)}):v.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[pn(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:pn(t)}),s.jsx(Pr,{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 vN({conversations:e,activeTabId:t,groupIndex:n,unreadTabKeys:a,draggingTabRef:r,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:d,onClearPreviewOrder:m,onDragStateReset:h,onDragTabKeyChange:g,onReceiveTab:k,onHideTab:f,isGroupActive:x,allowTabShortcuts:w=!0}){const{t:b}=Ce("common"),[S,N]=l.useState(null),v=l.useRef(null),y=l.useRef(null),j=l.useMemo(()=>e.map(P=>P.tabKey),[e]);_a("PaneGroupTabBar",{groupIndex:n,activeTabId:t,tabCount:e.length,ctxMenuTab:(S==null?void 0:S.tabKey)||null});const{isMac:C,tabShortcuts:A,shortcutListening:T,setShortcutListening:D,saveShortcuts:I}=th({enabled:w,sortedTabKeys:e.map(P=>P.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!S)return;const P=$=>{const L=document.querySelector("[data-pane-context-menu]");L&&L.contains($.target)||N(null)};return window.addEventListener("mousedown",P,!0),()=>window.removeEventListener("mousedown",P,!0)},[S]),l.useEffect(()=>{const P=y.current;if(!P)return;const $=L=>{Math.abs(L.deltaY)<=Math.abs(L.deltaX)||(L.preventDefault(),P.scrollLeft+=L.deltaY)};return P.addEventListener("wheel",$,{passive:!1}),()=>P.removeEventListener("wheel",$)},[]);const M=l.useCallback((P,$,L)=>{N({x:P,y:$,tabKey:L})},[]);return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:s.jsxs("div",{ref:y,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(P=>s.jsx(xN,{conv:P,isActive:t===P.tabKey,isDraggedTab:r.current===P.tabKey,isTaskCompleteUnread:a.has(P.tabKey),shortcut:w?A[P.tabKey]:void 0,conversationKeys:j,draggingTabRef:r,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:d,onClearPreviewOrder:m,onDragStateReset:h,onDragTabKeyChange:g,onReceiveTab:k,onOpenContextMenu:M,longPressTimer:v,isGroupActive:x},P.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:b("paneGroup.noTabsInGroup")})]})}),S&&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:S.x,top:S.y},children:[w&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:Go,onClick:P=>{P.stopPropagation(),D(S.tabKey),N(null)},children:["⌨ ",A[S.tabKey]?`Change shortcut (${A[S.tabKey]})`:"Set shortcut"]}),A[S.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:Go,onClick:()=>{const P={...A};delete P[S.tabKey],I(P),N(null)},children:"✕ Remove shortcut"})]}),f&&s.jsxs(s.Fragment,{children:[w&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onMouseDown:Go,onClick:()=>{f(S.tabKey),N(null)},children:"🚫 Hide from Dashboard"})]})]}),w&&T&&s.jsx(Yt,{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:()=>D(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:P=>P.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. ",C?"⌘+1":"Ctrl+1",", ",C?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:b("paneGroup.pressEscToCancel")})]})})})]})}function yN({conversations:e,ides:t,clearedTabs:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:u=!0,userName:p,groupIndex:d,onFocus:m,isSplitMode:h,numGroups:g,onMoveTab:k,onReceiveTab:f,style:x,onActiveTabChange:w,initialActiveTabId:b,initialTabOrder:S,onTabOrderChange:N,onHideTab:v,isFocused:y,allowTabShortcuts:j=!0,onOpenNewSession:C,liveSessionInboxState:A}){const{sendCommand:T}=kt(),D=l.useRef(null),{activeTabId:I,activeConv:M,sortedConversations:P,draggingTabRef:$,selectTab:L,handleTabReorder:R,updatePreviewOrder:F,commitPreviewOrder:E,clearPreviewOrder:H,moveTabToEnd:_,setDraggingTabKey:G}=bN({conversations:e,initialActiveTabId:b,initialTabOrder:S,onActiveTabChange:w,onTabOrderChange:N}),W=eo({sendDaemonCommand:r,activeConv:M,setActionLogs:o,isStandalone:i}),{dragOver:K,dropAction:V,resetDragState:te,handleDragEnter:le,handleDragOver:de,handleDragLeave:ee,handleDrop:z}=hN({conversations:e,numGroups:g,onMoveTab:k,onReceiveTab:f,onOwnTabDrop:_,onClearPreviewOrder:H}),X=M&&!pt(M)&&Yn(M)==="terminal",U=l.useMemo(()=>M?t.find(ge=>ge.id===M.routeId):void 0,[t,M]),Q=l.useMemo(()=>M?a.filter(ge=>ge.routeId===M.tabKey):[],[a,M]),ke=l.useMemo(()=>new Set(P.filter(ge=>jg(ge,A,{isOpenConversation:ge.tabKey===I})).map(ge=>ge.tabKey)),[I,A,P]);_a("PaneGroup",{groupIndex:d,conversationCount:e.length,activeTabId:I,dragOver:K});const ve=l.useCallback(ge=>{ge.streamSource==="agent-stream"&&ge.agentType&&T(ge.routeId,_p(),{agentType:ge.agentType,...ge.sessionId&&{targetSessionId:ge.sessionId}}).catch(()=>{})},[T]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:m,style:{...x,outline:K?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(vN,{conversations:P,activeTabId:I,groupIndex:d,numGroups:g,unreadTabKeys:ke,draggingTabRef:$,onFocus:m,onSelectTab:L,onConversationActivated:ve,onPreviewReorder:F,onReorderTab:R,onCommitPreviewOrder:E,onClearPreviewOrder:H,onDragStateReset:te,onDragTabKeyChange:G,onMoveTab:k,onReceiveTab:f,onHideTab:v,isGroupActive:y??!1,allowTabShortcuts:j}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:le,onDragOver:de,onDragLeave:ee,onDrop:z,children:[K&&s.jsx(gN,{dropAction:V,canSplit:!!(g<4&&k)}),M?s.jsx(Hl,{activeConv:M,clearToken:n[M.tabKey]||0,isCliTerminal:!!X,ideEntry:U,terminalRef:D,handleModalButton:W.handleModalButton,handleRelaunch:W.handleRelaunch,handleSendChat:W.handleSendChat,handleForceSendChat:W.handleForceSendChat,isSendingChat:W.isSendingChat,sendFeedbackMessage:W.sendFeedbackMessage,handleFocusAgent:W.handleFocusAgent,isFocusingAgent:W.isFocusingAgent,actionLogs:Q,userName:p,isInputActive:!h||!!y}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(Fl,{conversationsCount:e.length,isSplitMode:h,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:C,isLoading:!oo(t,u)})})]})]})}function wN({containerRef:e,isSplitMode:t,numGroups:n,groupSizes:a,groupedConvs:r,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:u,setActionLogs:p,isStandalone:d,hasRegisteredMachines:m,initialDataLoaded:h,userName:g,focusedGroup:k,focusGroup:f,moveTabToGroup:x,splitTabRelative:w,closeGroup:b,handleResizeStart:S,groupActiveTabIds:N,setGroupActiveTab:v,groupTabOrders:y,setGroupTabOrder:j,toggleHiddenTab:C,onOpenNewSession:A,allowTabShortcuts:T=!0,liveSessionInboxState:D}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:r.map((I,M)=>{const P=t&&a.length===n?`${a[M]}%`:void 0;return s.jsxs(Lt.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:$=>S(M-1,$),onDoubleClick:()=>b(M),title:"Drag to resize · Double-click to merge",children:s.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),s.jsx(yN,{style:t?{flexBasis:P??`${100/n}%`,flexGrow:P?0:1,flexShrink:P?0:1}:void 0,conversations:I,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:u,setActionLogs:p,isStandalone:d,hasRegisteredMachines:m,initialDataLoaded:h,userName:g,groupIndex:M,isFocused:t&&k===M,onFocus:()=>f(M),isSplitMode:t,numGroups:n,onMoveTab:($,L)=>{L==="left"&&M>0?x($,M-1):L==="right"&&M<n-1?x($,M+1):L==="split-left"&&n<4?w($,M,"left"):L==="split-right"&&n<4&&w($,M,"right")},onReceiveTab:$=>x($,M),onActiveTabChange:$=>v(M,$),initialActiveTabId:N[M],initialTabOrder:y[M],onTabOrderChange:$=>j(M,$),onHideTab:C,onOpenNewSession:A,allowTabShortcuts:T,liveSessionInboxState:D})]},M)})})}const sh="adhdev-dashboard-action-shortcuts",kN=1200,SN=[["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 CN(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function ht(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 nh(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:ht("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:ht("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:ht("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:ht("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:ht("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:ht("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:ht("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:ht("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:ht("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:ht("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:ht("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:ht("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:ht("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:ht("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:ht("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:ht("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:ht("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:ht("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:ht("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:ht("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:ht("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:ht("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:ht("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:ht("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:ht("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:ht("toggleCliView",e)}]}function Ki(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function Br(e){const t=Object.fromEntries(nh(e).map(n=>[n.id,n.defaultShortcut]));try{const n=JSON.parse(localStorage.getItem(sh)||"{}"),a={...t,...n};for(const[r,o]of SN)a[r]===o&&(a[r]=t[r]);return a}catch{return t}}function ah(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function jN({enabled:e=!0,onTrigger:t}){const n=CN(),[a,r]=l.useState(()=>Br(n)),[o,i]=l.useState(null),[c,u]=l.useState([]),p=l.useRef({parts:[],timer:null}),d=l.useCallback(f=>{const x=[];return f.metaKey&&x.push(n?"⌘":"Meta"),f.ctrlKey&&x.push("Ctrl"),f.altKey&&x.push(n?"⌥":"Alt"),f.shiftKey&&f.key.length!==1&&x.push(n?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(x.push(ah(f.key)),x.join("+"))},[n]),m=l.useCallback(f=>{r(f);try{localStorage.setItem(sh,JSON.stringify(f))}catch{}},[]);l.useEffect(()=>{const f=Br(n),x=Object.entries(a),w=Object.entries(f);x.length===w.length&&x.every(([b,S])=>f[b]===S)||m(f)},[a,n,m]);const h=l.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),g=l.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},kN))},[]);l.useEffect(()=>{if(!o)return;const f=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){i(null),u([]);return}const w=d(x);if(!w)return;const S=!(x.metaKey||x.ctrlKey||x.altKey)&&/^[A-Z0-9]$/.test(w);if(c.length===0&&S){u([w]);return}const v=[...c,w].slice(0,2).join(" "),y={...a};for(const[j,C]of Object.entries(y))C===v&&delete y[j];y[o]=v,m(y),i(null),u([])};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[a,d,m,o,c]),l.useEffect(()=>{if(!e||o)return;const f=x=>{if(x.defaultPrevented)return;const w=d(x);if(!w)return;const b=x.metaKey||x.ctrlKey||x.altKey;if(Ki(x.target))return;const S=p.current.parts,N=b?[w]:[...S.slice(-1),w].slice(-2),v=N.join(" "),y=N[N.length-1],j=Object.entries(a).filter(([,I])=>!!I),C=j.find(([,I])=>I===v);if(C){x.preventDefault(),h(),t(C[0]);return}if(j.some(([,I])=>I.startsWith(`${v} `))){x.preventDefault(),p.current.parts=N,g();return}const T=j.find(([,I])=>I===y);if(T){x.preventDefault(),h(),t(T[0]);return}if(j.some(([,I])=>I.startsWith(`${y} `))){x.preventDefault(),p.current.parts=[y],g();return}h()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[a,g,e,d,t,h,o]),l.useEffect(()=>()=>h(),[h]);const k=l.useMemo(()=>nh(n),[n]);return{isMac:n,actionDefinitions:k,actionShortcuts:a,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:u,saveShortcuts:m}}function NN({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 rh(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function Ad({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:n,ides:a}){return!e||n>0?!1:t?!rh(a):!0}function AN({previousVisibleConversationCount:e,visibleConversationCount:t,ides:n}){return t>0||e<=0?!1:rh(n)}const oh=1e3,TN=4;function Td(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function Md(e,t,n){return Math.abs(t.clientX-e.clientX)>n||Math.abs(t.clientY-e.clientY)>n}function MN({detachDelayMs:e=oh,stillnessThresholdPx:t=TN,onDetach:n,setTimeoutFn:a=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:r=globalThis.clearTimeout.bind(globalThis)}){let o=null,i=null,c=null,u=null,p=null,d=!1;const m=()=>{p!=null&&(r(p),p=null)},h=()=>{m(),c=null},g=()=>{m(),o=null,i=null,c=null,u=null,d=!1},k=()=>{!o||!c||!u||d||p!=null||(p=a(()=>{p=null,!(!o||!c||!u||d)&&Td(u,i)&&(Md(c,u,t)||(d=!0,n({panelId:o,clientX:u.clientX,clientY:u.clientY})))},e))},f=w=>{if(!(!o||d)){if(!Td(w,i)){u={clientX:w.clientX,clientY:w.clientY},h();return}(!c||Md(c,w,t))&&(m(),c={clientX:w.clientX,clientY:w.clientY}),u={clientX:w.clientX,clientY:w.clientY},k()}},x=w=>{!o||d||(w&&(u={clientX:w.clientX,clientY:w.clientY}),h())};return{startDrag:w=>{m(),o=w.panelId,i=w.selfPanelBounds??null,c=null,u={clientX:w.clientX,clientY:w.clientY},d=!1},markSelfPanel:f,markNonSelfPanel:x,markNoDropTarget:x,markDockTarget:x,endDrag:g,isDragging:()=>o!=null,hasDetached:()=>d,dispose:g}}function DN(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function xr(e){return wt(e)||e.tabKey}function PN(e){return`remote:${e}`}function ls(e){return e.startsWith("remote:")}function Dd(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function zo(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 Ko(e,t){e.classList.remove(xi.className,vi.className),e.classList.add(t==="light"?xi.className:vi.className)}function Pd(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 IN(e,t,n){var i;const a=[t];let r;for(const c of a){let u;for(const p of c){const d=e.addPanel({id:p.tabKey,component:"conversation",title:xr(p),params:{kind:"conversation",tabKey:p.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:r?{position:{referencePanel:r,direction:"right"},inactive:!0}:{}});u||(u=d.id)}r=u??r}return n??((i=t[0])==null?void 0:i.tabKey)??null}function Id(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])ls(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!==xr(r)&&o.api.setTitle(xr(r));continue}e.addPanel({id:r.tabKey,component:"conversation",title:xr(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 Ld(e,t,n){var u,p;const a=n?PN(n):null;for(const d of[...e.panels])ls(d.id)&&(!a||d.id!==a)&&e.removePanel(d);if(!n||!a)return;const r=fs(t,n);if(!r&&e.totalPanels===0)return;const o=e.getPanel(a),i=rm(r);if(o){o.title!==i&&o.api.setTitle(i);return}const c=(r==null?void 0:r.tabKey)??((u=e.activePanel)==null?void 0:u.id)??((p=e.panels.find(d=>!ls(d.id)))==null?void 0:p.id);e.addPanel({id:a,component:"remote",title:i,params:{kind:"remote",routeId:n},...c?{position:{referencePanel:c,direction:"right"},inactive:!0}:{}})}function ih({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",(d,m)=>{if(d!==e)return;const h=new FileReader;h.onload=()=>o(h.result),h.readAsDataURL(m)}):void 0,[e]),l.useEffect(()=>{n!=="connected"&&o(null)},[n]),l.useEffect(()=>{var d;return e?((d=Ct.onStatus)==null?void 0:d.call(Ct,(m,h)=>{m===e&&h!=null&&h.screenshotUsage&&c(h.screenshotUsage)}))||(()=>{}):void 0},[e]),l.useEffect(()=>{o(null)},[e,t]),l.useEffect(()=>{const p=e?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 u=l.useCallback(async(p,d)=>{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,d,t)},[e,n,t]);return{connScreenshot:r,screenshotUsage:i,handleRemoteAction:u}}const lh=l.createContext(null);function io(){const e=l.useContext(lh);if(!e)throw new Error("DashboardDockviewContext missing");return e}function LN(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 RN({params:e}){var u;const t=io(),n=l.useMemo(()=>fs([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),a=l.useMemo(()=>t.ides.find(p=>p.id===e.routeId),[t.ides,e.routeId]),r=(n==null?void 0:n.daemonId)||((u=n==null?void 0:n.routeId)==null?void 0:u.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:i,handleRemoteAction:c}=ih({doId:r,targetSessionId:n?Rp(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(Zu,{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 EN(){const e=io();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(Fl,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels,isLoading:!oo(e.ides,e.initialDataLoaded)})})}function _N(e){var b,S;LN(e);const t=io(),n=l.useCallback(N=>{"button"in N&&N.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(N=>cS(N),[]),i=l.useCallback(()=>lS(r),[r]),c=l.useSyncExternalStore(o,i,i);if(e.params.kind==="remote"){const N=fs([...t.conversationsByTabKey.values()],e.params.routeId),v=((b=e.api.group.activePanel)==null?void 0:b.id)===e.api.id,y=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${v?" is-active":""}${y?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(N==null?void 0:N.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:N!=null&&N.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:N.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const u=t.conversationsByTabKey.get(e.params.tabKey);if(!u)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const p=((S=e.api.group.activePanel)==null?void 0:S.id)===e.api.id,d=e.api.isGroupActive,m=Vr(u,t.liveSessionInboxState,{isOpenConversation:p}),h=m.isReconnecting,g=m.isConnecting,k=m.isGenerating||c,f=m.isWaiting,x=m.unread,w=t.tabShortcuts[u.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${p?" is-active":""}${d?" is-group-active":""}${h?" is-reconnecting":""}`,title:wt(u),"data-tab-key":e.params.tabKey,onMouseDown:n,onTouchStart:n,onContextMenu:N=>{var v;N.preventDefault(),n(N),t.openTabContextMenu({x:N.clientX,y:N.clientY,tabKey:u.tabKey,sourceDocument:((v=N.target)==null?void 0:v.ownerDocument)??document})},children:[x&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:k?s.jsx("div",{className:"tab-spinner"}):f?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):h?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):g?s.jsx("div",{className:"tab-connecting-spinner"}):u.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:wt(u)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:h?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:pn(u)}):g?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:pn(u)}):s.jsx("span",{children:pn(u)})})]}),w&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:w,children:w})]})}function sr(e){return e.isActive}function Rd(e){return e.isVisible}function HN(e){e.preventDefault()}function $N({params:e,api:t}){var g;const n=io(),a=l.useRef(null),[r,o]=l.useState(()=>sr(t)),[i,c]=l.useState(()=>Rd(t)),u=n.conversationsByTabKey.get(e.tabKey),p=eo({sendDaemonCommand:n.sendDaemonCommand,activeConv:u,setActionLogs:n.setActionLogs,isStandalone:n.isStandalone});l.useEffect(()=>{o(sr(t)),c(Rd(t));const k=[t.onDidActiveChange(f=>o(f.isActive)),t.onDidActiveGroupChange(f=>{if(!sr(t)&&!f.isActive){o(!1);return}o(sr(t))}),t.onDidVisibilityChange(f=>c(f.isVisible))];return()=>{for(const f of k)f.dispose()}},[t]);const d=l.useMemo(()=>u?n.ides.find(k=>k.id===u.routeId):void 0,[n.ides,u]),m=l.useMemo(()=>u?n.actionLogs.filter(k=>k.routeId===u.tabKey):[],[n.actionLogs,u]);if(!u)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(Fl,{conversationsCount:0,isSplitMode:!1,isStandalone:n.isStandalone,hasRegisteredMachines:n.hasRegisteredMachines,onOpenNewSession:n.onOpenNewSession,suppressGuide:n.hasDetachedConversationPanels,isLoading:!oo(n.ides,n.initialDataLoaded)})});const h=!pt(u)&&Yn(u)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(Hl,{activeConv:u,clearToken:n.clearedTabs[u.tabKey]||0,isCliTerminal:h,ideEntry:d,terminalRef:a,handleModalButton:p.handleModalButton,handleRelaunch:p.handleRelaunch,handleSendChat:p.handleSendChat,handleForceSendChat:p.handleForceSendChat,isSendingChat:p.isSendingChat,handleFocusAgent:p.handleFocusAgent,isFocusingAgent:p.isFocusingAgent,actionLogs:m,userName:n.userName,scrollToBottomRequestNonce:((g=n.scrollToBottomRequest)==null?void 0:g.tabKey)===u.tabKey?n.scrollToBottomRequest.nonce:void 0,isInputActive:r,isVisible:i})})}function FN({visibleConversations:e,clearedTabs:t,ides:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:u,userName:p,toggleHiddenTab:d,actionShortcuts:m,registerActionHandlers:h,onActiveTabChange:g,onOpenNewSession:k,onRequestScrollToBottom:f,requestedActiveTabKey:x,requestedRemoteIdeId:w,onRequestedActiveTabConsumed:b,scrollToBottomRequest:S,liveSessionInboxState:N,layoutProfile:v}){var ut,it,mt;const{theme:y}=en(),{sendCommand:j}=kt(),C=l.useRef(null),A=l.useRef(null),T=l.useRef(null),D=l.useRef(!1),I=l.useRef(!1),M=l.useRef(!1),P=l.useRef(null),$=l.useRef([]),[L,R]=l.useState(null),[F,E]=l.useState(0),H=l.useRef(typeof window>"u"?{}:n1(v)),_=l.useMemo(()=>new Map(e.map(J=>[J.tabKey,J])),[e]),G=l.useMemo(()=>{const J=C.current;return J?J.groups.some(ne=>{try{const ce=ne.model.location.type;return ce!=="floating"&&ce!=="popout"?!1:ne.panels.some(be=>_.has(be.id))}catch{return!1}}):!1},[_,F,e]),W=l.useCallback(()=>{var J;(J=C.current)==null||J.focus()},[]),K=l.useCallback((J,ne)=>{f==null||f(J,ne)},[f]),V=l.useCallback(J=>{const ne=document,ce=J.document;for(const Pe of ne.querySelectorAll('link[rel="stylesheet"]')){const Ge=ce.createElement("link");Ge.rel="stylesheet",Ge.href=Pe.href,Pe.crossOrigin&&(Ge.crossOrigin=Pe.crossOrigin),ce.head.appendChild(Ge)}for(const Pe of ne.querySelectorAll("style")){const Ge=ce.createElement("style");Ge.textContent=Pe.textContent,ce.head.appendChild(Ge)}const be=[];for(const Pe of ne.styleSheets)try{for(const Ge of Pe.cssRules)Ge instanceof CSSStyleRule&&(Ge.selectorText===":root"||Ge.selectorText==="html")&&be.push(Ge.cssText)}catch{}if(be.length>0){const Pe=ce.createElement("style");Pe.textContent=be.join(`
|
|
69
|
+
The machine's IDE, workspace and provider settings are kept.`,confirmLabel:o("machine.connectedMachines.remove"),confirmColor:"red",onConfirm:T,onCancel:()=>m(null)})]})}const nj=["default","claude-cli","codex-cli","antigravity-cli","hermes-cli","gemini-cli"];function aj({daemonId:e,knownCliTypes:t=nj}){const{t:n}=Ce("common"),{sendCommand:a}=kt(),[r,o]=l.useState({}),[i,c]=l.useState({}),[u,p]=l.useState(!0),[d,m]=l.useState(null),[h,g]=l.useState(null),[k,f]=l.useState(""),x=l.useCallback(async()=>{if(e){p(!0),g(null);try{const S=await a(e,"list_coordinator_prompts",{}),N=S!=null&&S.result&&typeof S.result=="object"?S.result:S;if(!(N!=null&&N.success)){g((N==null?void 0:N.error)||"Failed to load");return}const v=N.entries||{};f(N.dir||"");const y={};for(const j of t)y[j]=v[j]||{override:"",append:""};for(const j of Object.keys(v))y[j]||(y[j]=v[j]);o(y),c(JSON.parse(JSON.stringify(y)))}catch(S){g((S==null?void 0:S.message)||String(S))}finally{p(!1)}}},[a,e,t]);l.useEffect(()=>{x()},[x]);const w=l.useCallback(async(S,N)=>{var v;if(e){m(`${S}:${N}`),g(null);try{const y=((v=r[S])==null?void 0:v[N])||"",j=await a(e,"write_coordinator_prompt",{key:S,kind:N,content:y}),C=j!=null&&j.result&&typeof j.result=="object"?j.result:j;if(!(C!=null&&C.success)){g((C==null?void 0:C.error)||"Save failed");return}c(A=>({...A,[S]:{...A[S]||{override:"",append:""},[N]:y}}))}catch(y){g((y==null?void 0:y.message)||String(y))}finally{m(null)}}},[a,e,r]),b=l.useMemo(()=>(S,N)=>{var v,y;return(((v=r[S])==null?void 0:v[N])||"")!==(((y=i[S])==null?void 0:y[N])||"")},[r,i]);return e?s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{className:"text-[12px] text-text-muted",children:[s.jsxs("p",{children:["Customize the coordinator prompt this daemon's mesh coordinator sessions get. ",s.jsx("span",{className:"font-mono text-[11px]",children:k||"~/.adhdev/coordinator-prompts/"})]}),s.jsxs("p",{className:"mt-1",children:[s.jsx(gi,{i18nKey:"settings.coordinatorPrompts.overrideDesc",ns:"common",components:{strong:s.jsx("strong",{})}})," ",s.jsx(gi,{i18nKey:"settings.coordinatorPrompts.appendDesc",ns:"common",components:{strong:s.jsx("strong",{})}}),"Leave a field empty + Save to remove it (reset to default). Supports placeholders: ","{{meshName}}",", ","{{repo}}",", ","{{nodes}}",", ","{{rules}}",", etc."]})]}),h&&s.jsx("div",{className:"text-[12px] text-status-error bg-status-error/10 border border-status-error/40 rounded px-3 py-2",children:h}),u&&s.jsx("div",{className:"text-[12px] text-text-muted",children:"Loading…"}),s.jsx("div",{className:"flex flex-col gap-6",children:Object.entries(r).map(([S,N])=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 p-3",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-2",children:S}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:n("settings.coordinatorPrompts.overrideLabel")}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:4,value:N.override,onChange:v=>o(y=>({...y,[S]:{...y[S],override:v.target.value}})),placeholder:"(empty — use daemon default base prompt)",disabled:d===`${S}:override`}),s.jsx("div",{className:"mt-1 mb-3 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void w(S,"override"),disabled:d===`${S}:override`||!b(S,"override"),children:d===`${S}:override`?"Saving…":b(S,"override")?"Save override":"Saved"})}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:n("settings.coordinatorPrompts.appendLabel")}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:3,value:N.append,onChange:v=>o(y=>({...y,[S]:{...y[S],append:v.target.value}})),placeholder:"(empty — nothing appended at this layer)",disabled:d===`${S}:append`}),s.jsx("div",{className:"mt-1 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void w(S,"append"),disabled:d===`${S}:append`||!b(S,"append"),children:d===`${S}:append`?"Saving…":b(S,"append")?"Save append":"Saved"})})]},S))})]}):s.jsx("div",{className:"text-[12px] text-text-muted",children:"Connect a daemon to edit coordinator prompts."})}const rj=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function oj(){const{preference:e,setPreference:t}=en();return s.jsx("div",{className:"flex gap-2",children:rj.map(n=>s.jsxs("button",{onClick:()=>t(n.id),className:`px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors flex items-center gap-1.5 ${e===n.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:e===n.id?{color:"var(--accent-on-primary)"}:void 0,children:[s.jsx("span",{children:n.icon}),n.label]},n.id))})}function ij(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 lj(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function _o(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function ud(e){const{r:t,g:n,b:a}=lj(e);return .2126*_o(t)+.7152*_o(n)+.0722*_o(a)}function pd(e,t){const n=ud(e),a=ud(t),r=Math.max(n,a),o=Math.min(n,a);return(r+.05)/(o+.05)}function Am(e){const t=ij(e);if(!t)return"#111827";const n="#111827",a="#ffffff";return pd(t,n)>=pd(t,a)?n:a}const Oi={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},Ui={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},cj=[{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"}}}],Tm="adhdev-chat-theme",Mm="adhdev-chat-theme-custom";function fr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Tm)||"ember"}catch{return"ember"}}function us(e){try{const t=localStorage.getItem(Mm);if(t){const n=JSON.parse(t);return{...e==="dark"?Oi:Ui,...n[e]}}}catch{}return e==="dark"?Oi:Ui}function Qa(e,t){try{localStorage.setItem(Mm,JSON.stringify({dark:e,light:t}))}catch{}}function ts(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 $r(e,t){const n=Math.min(255,parseInt(e.slice(1,3),16)+t),a=Math.min(255,parseInt(e.slice(3,5),16)+t),r=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}`}const dj={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function ka(e,t){var r;const n=(r=dj[e])==null?void 0:r[t];if(!n)return;const a=document.documentElement;a.style.setProperty("--accent-primary",n),a.style.setProperty("--accent-primary-light",$r(n,24)),a.style.setProperty("--accent-on-primary",Am(n)),a.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${n}, ${$r(n,18)})`),a.style.setProperty("--border-accent",ts(n,.35)),a.style.setProperty("--nav-active-bg",ts(n,.1)),a.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${n}, 0 0 12px ${ts(n,.06)}`)}function mn(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",ts(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",ts(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",ts(e.borderSubtle,.25)),t.style.setProperty("--text-primary",e.textPrimary),t.style.setProperty("--text-secondary",e.textSecondary),t.style.setProperty("--text-muted",e.textMuted),t.style.setProperty("--border-subtle",ts(e.borderSubtle,.5)),t.style.setProperty("--border-default",ts(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",$r(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Am(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${$r(e.accentColor,40)})`),t.style.setProperty("--border-accent",ts(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",ts(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${ts(e.accentColor,.06)}`),t.style.setProperty("--chat-user-bg",e.userBubble),t.style.setProperty("--chat-user-color",e.userText),t.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),t.style.setProperty("--chat-assistant-bg",e.assistantBubble),t.style.setProperty("--chat-assistant-color",e.assistantText),t.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),t.style.setProperty("--chat-assistant-border",`1px solid ${ts(e.accentColor,.12)}`),t.style.setProperty("--chat-container-bg",e.containerBg),t.style.setProperty("--dashboard-pane-bg",e.containerBg),t.style.setProperty("--chat-thought-accent",e.accentColor),t.style.setProperty("--chat-tool-accent",e.accentColor),t.style.setProperty("--chat-action-color",e.accentColor),t.style.setProperty("--chat-send-bg",e.sendButton),t.style.setProperty("--chat-input-border",e.inputBorder)}function Dl(){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 uj(e){try{localStorage.setItem(Tm,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=hn()?"dark":"light";mn(us(t))}else Dl(),ka(e,hn()?"dark":"light")}function pj(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=fr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=hn()?"dark":"light";mn(us(t))}else Dl(),ka(e,hn()?"dark":"light")}function hn(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Ot({label:e,value:t,onChange:n}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[s.jsx("input",{type:"color",value:t,onChange: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 oa({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 mj({dark:e,onColorsChange:t}){const{t:n}=Ce("common"),a=e?"dark":"light",[r,o]=l.useState(()=>us(a));l.useEffect(()=>{o(us(a))},[a]);const i=l.useCallback((c,u)=>{o(p=>{const d={...p,[c]:u},h=us(a==="dark"?"light":"dark");return a==="dark"?Qa(d,h):Qa(h,d),mn(d),t(d),d})},[a,t]);return s.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[s.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[n("settings.theme.customEditorTitle"),s.jsx("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:n(e?"settings.theme.darkMode":"settings.theme.lightMode")})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs(oa,{title:n("settings.theme.sectionAppBackground"),children:[s.jsx(Ot,{label:n("settings.theme.colorBackground"),value:r.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(Ot,{label:n("settings.theme.colorSurface"),value:r.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(Ot,{label:n("settings.theme.colorCard"),value:r.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(oa,{title:n("settings.theme.sectionAppText"),children:[s.jsx(Ot,{label:n("settings.theme.colorPrimary"),value:r.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(Ot,{label:n("settings.theme.colorSecondary"),value:r.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(Ot,{label:n("settings.theme.colorMuted"),value:r.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(oa,{title:n("settings.theme.sectionBordersAccent"),children:[s.jsx(Ot,{label:n("settings.theme.colorBorderSubtle"),value:r.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(Ot,{label:n("settings.theme.colorBorderDefault"),value:r.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(Ot,{label:n("settings.theme.colorAccent"),value:r.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(oa,{title:n("settings.theme.sectionChatBubbles"),children:[s.jsx(Ot,{label:n("settings.theme.colorUserBubble"),value:r.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(Ot,{label:n("settings.theme.colorUserText"),value:r.userText,onChange:c=>i("userText",c)}),s.jsx(Ot,{label:n("settings.theme.colorAgentBubble"),value:r.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(Ot,{label:n("settings.theme.colorAgentText"),value:r.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(oa,{title:n("settings.theme.sectionChatLayout"),children:[s.jsx(Ot,{label:n("settings.theme.colorChatBg"),value:r.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(Ot,{label:n("settings.theme.colorSendButton"),value:r.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(Ot,{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?Oi:Ui,p=us(e?"light":"dark");e?Qa(c,p):Qa(p,c),o(c),mn(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 hj(){const{t:e}=Ce("common"),[t,n]=l.useState(fr),[a,r]=l.useState(!0),[o,i]=l.useState(()=>us("dark"));l.useEffect(()=>{r(hn());const p=new MutationObserver(()=>{const h=hn();r(h);const g=fr();g==="custom"?mn(us(h?"dark":"light")):ka(g,h?"dark":"light")});p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const d=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const h=hn();r(h);const g=fr();g==="custom"?mn(us(h?"dark":"light")):ka(g,h?"dark":"light")};return d.addEventListener("change",m),()=>{p.disconnect(),d.removeEventListener("change",m)}},[]),l.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?mn(us(a?"dark":"light")):(Dl(),ka(t,a?"dark":"light"))},[t,a]),l.useEffect(()=>{i(us(a?"dark":"light"))},[a]);const c=p=>{n(p),uj(p)},u=[...cj,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText},light:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:u.map(p=>{const d=t===p.id,m=a?p.preview.dark:p.preview.light,h=p.id==="honey"||p.id==="ember"?"#1a1a1a":p.id==="custom"?o.userText:"#fff";return s.jsxs("button",{onClick:()=>c(p.id),className:"text-left rounded-xl p-3 transition-all",style:{background:d?"var(--bg-glass-hover)":"var(--bg-glass)",border:d?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:d?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:m.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:e("settings.theme.helloHelp")}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.userBubble,color:h},children:e("settings.theme.fixBug")}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:e("settings.theme.onIt")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[d&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:p.id==="custom"?e("settings.theme.customLabel"):p.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:p.description})]})]})]},p.id)})}),t==="custom"&&s.jsx(mj,{dark:a,onColorsChange:p=>i(p)})]})}const Pl="adhdev_mobileDashboardMode_v1",qi="adhdev:mobile-dashboard-mode-change";function Il(){try{return localStorage.getItem(Pl)==="workspace"?"workspace":"chat"}catch{return"chat"}}function fj(e){if(typeof window>"u")return()=>{};const t=r=>{e(r??Il())},n=r=>{const o=r.detail;t(o)},a=r=>{r.key&&r.key!==Pl||t()};return window.addEventListener(qi,n),window.addEventListener("storage",a),()=>{window.removeEventListener(qi,n),window.removeEventListener("storage",a)}}function bj(e){try{localStorage.setItem(Pl,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(qi,{detail:e}))}function gj(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(Il()==="chat")},[]),s.jsx(ln,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(kn,{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),bj(n?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const xj="Choose a preset or create a fully custom theme. Custom themes control the entire app — backgrounds, text, borders, and chat bubbles.",vj="Choose whether the dashboard opens like a chat app on phones or keeps the full workspace layout.";function yj({themeDescription:e=xj,mobileDescription:t=vj,fontsSlot:n}){const{t:a}=Ce("common");return s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:a("settings.appearance.modeLabel")}),s.jsx(oj,{})]}),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(hj,{})]}),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(gj,{})]})]})}const Ho=new Map,md=new Map;function wj(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 kj(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 Dm(){const{sendCommand:e}=kt(),{injectEntries:t,getIdes:n}=ja();return l.useCallback(async(a,r)=>{if(!a)return;const o=(r==null?void 0:r.minFreshMs)??Mk,i=md.get(a)||0;if(!(r!=null&&r.force)&&i>0&&Date.now()-i<o)return;const c=Ho.get(a);if(c)return c;const u=(async()=>{const p=await e(a,"get_machine_runtime_stats"),d=wj(p);if(!d)return;const m=n().find(g=>g.id===a),h=kj(m,a,d.machine,d.timestamp||Date.now());t([h]),md.set(a,Date.now())})().finally(()=>{Ho.delete(a)});return Ho.set(a,u),u},[n,t,e])}function Sj(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 Cj(e,t){const{sendData:n}=kt(),{injectEntries:a,getIdes:r}=ja(),o=Array.from(new Set(e.filter(Boolean))).join("|");l.useEffect(()=>{if(!(t!=null&&t.enabled)||!n)return;const i=o?o.split("|"):[];if(i.length===0)return;const c=i.map(u=>hs.subscribe({sendData:n},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:t==null?void 0:t.intervalMs}},d=>{const m=r().find(g=>g.id===u),h=Sj(m,u,d);a([h])}));return()=>{c.forEach(u=>u())}},[o,r,a,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,n])}function jj(e,t){const{sendData:n}=kt(),[a,r]=l.useState(null),[o,i]=l.useState(!1);return l.useEffect(()=>{if(!e){r(null),i(!1);return}if(!(t!=null&&t.enabled)||!n){i(!1);return}r(null),i(!0);let c=null;const u=hs.subscribe({sendData:n},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},p=>{c&&(clearTimeout(c),c=null),r(p.diagnostics),i(!1)});return u.initialSendAccepted?c=setTimeout(()=>{i(!1)},Ik):i(!1),()=>{c&&clearTimeout(c),u()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,n]),{diagnostics:a,loading:o,applyDiagnostics:r}}function Nj(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Pm(e){const{sendData:t}=kt(),[n,a]=l.useState({});return l.useEffect(()=>{const r=Nj(e);if(!r||!e.sessionId||!t){a({});return}const o=hs.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}),$n.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 Aj(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function Tj(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 Mj(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 Dj({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(!Aj(o))throw new Error(Tj(o));return}await Mj(e.sessionId,t,r)}function Im(e){const{ides:t,isP2PActive:n,p2pStates:a}=Ms(),{sendCommand:r}=kt(),[o,i]=l.useState(null),[c,u]=l.useState(!1),[p,d]=l.useState(null),m=l.useRef(!1),h=l.useMemo(()=>gg(t,e),[t,e]),g=!!h,k=l.useMemo(()=>h?h.prompt.promptId===o?null:h:null,[o,h]),f=l.useCallback(async b=>{if(!k||m.current)return;m.current=!0;const S=ep(k.prompt,b);u(!0),d(null);try{const N=(a==null?void 0:a[k.daemonId])==="connected"||n===!0;await Dj({promptSession:k,response:S,useP2PCommand:N,sendCommand:r}),i(k.prompt.promptId)}catch(N){throw d(N instanceof Error?N.message:String(N)),N}finally{u(!1),m.current=!1}},[n,a,k,r]),x=l.useCallback(()=>{k&&i(k.prompt.promptId)},[k]),w=l.useCallback(()=>{i(null),d(null)},[]);return{promptSession:k,hasActivePrompt:g,responseError:p,isSubmitting:c,submit:f,cancel:x,reopen:w}}function Lm(e){return e instanceof Error?e.message:String(e||"")}function Pj(e){const t=Lm(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 Ij(e){const t=Lm(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Rm({conversation:e,mode:t,ides:n,sendDaemonCommand:a,setCliViewModeOverrides:r}){if(!e||!ft(e)||pt(e))return;const o=Yn(e);if(o===t)return;const i=e.sessionId;i&&r(c=>({...c,[i]:t}));try{await a(Bs(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Ts(e),mode:t})}catch(c){const u=Ij(c);i&&!u&&r(p=>{const d={...p};return o===Rj(n,i)?delete d[i]:d[i]=o,d}),Pj(c)?console.warn(u?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",c instanceof Error?c.message:String(c)):console.error("Failed to switch CLI view mode:",c)}}function hd(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 Lj(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=hd(r,t),i=Array.isArray(r.childSessions)?r.childSessions.map(u=>hd(u,t)):r.childSessions,c=i!==r.childSessions;return o!==r||c?(n=!0,{...o,...c?{childSessions:i}:{}}):r});return n?a:e}function Rj(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 Ej({visibleConversations:e,clearedTabs:t,setClearedTabs:n,setActionLogs:a,isConversationMuted:r}){l.useEffect(()=>{gp()},[]);const o=l.useMemo(()=>e.map(i=>({id:i.tabKey,name:am(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 Qw(o),l.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{n(u=>{const p=Date.now(),d={};for(const[m,h]of Object.entries(u))p-h<5e3&&(d[m]=h);return Object.keys(d).length===Object.keys(u).length?u:d})},5500);return()=>clearTimeout(c)},[t,n]),l.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;a(u=>{const p=u.filter(d=>d.timestamp>c).slice(-100);return p.length===u.length?u:p})},6e4);return()=>clearInterval(i)},[a]),null}function fd(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 fn(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=fd(t==null?void 0:t.receivedAt)||fd(t==null?void 0:t.timestamp)||0;return Math.max(n,a)}function Gi(e,t=0){return fn(e)||e.lastUpdated||t||0}function Em(e){return fn(e)||e.lastUpdated||0}function _m(e,t,n=Em){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 zi(e){var n;const t=ns(e.status,{activeModal:(n=e.modalButtons)!=null&&n.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function _j(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!zi(e)&&!e.title.trim()}function Hj(e){return e.length===0?null:[...e].sort((t,n)=>{const a=Number(zi(n))-Number(zi(t));if(a!==0)return a;const r=n.messages.length-t.messages.length;return r!==0?r:_m(t,n)})[0]||null}function fs(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=Hj(r);return a?o&&_j(a)?o:a:o||n[0]||null}function $j(e){const t=e.filter(r=>r.type!=="adhdev-daemon"),n=new Set;for(const r of t){if(!Pi(r))continue;const o=up(r);o&&n.add(o)}const a=new Map;for(const r of t){const o=Aw(r,n),i=a.get(o);if(!i){a.set(o,r);continue}const c=m=>(m.workspace?1:0)+(m.activeChat?1:0)+(m.lastMessagePreview?1:0),u=c(i),p=c(r),d=p>u||p===u&&(r.timestamp||0)>(i.timestamp||0)?r:i;a.set(o,Fj(d,d===r?i:r))}return Array.from(a.values())}function Fj(e,t){const n=Pi(t),a=Pi(e);if(!n&&!a)return e;const r=a?n?void 0:t:e,o=a?e:n?t:void 0,i=r&&String(r.daemonId||"").trim()||String(e.ownerDaemonId||"").trim()||String(t.ownerDaemonId||"").trim()||void 0,c=String(e.ownerMachineName||"").trim()||String(t.ownerMachineName||"").trim()||void 0,u=o==null?void 0:o.settings;return{...e,...i&&{ownerDaemonId:i},...c&&!e.ownerMachineName&&{ownerMachineName:c},...u&&!a&&{settings:{...u,...e.settings??{}}}}}function $o(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 Bj(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 bd(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],n=t[t.length-1],a=n?Bj(Fn(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 Wj(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||""),bd(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||""),bd(n.activeChat)].join(":"))].join("|")}function Oj(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 Uj(e,t){const n=new Map;for(const a of e){const r=t.get(a.routeId)||a;for(const o of xa({routeId:a.routeId}))n.set(o,r);for(const o of xa({providerSessionId:a.providerSessionId,sessionId:a.sessionId}))n.set(o,a.streamSource==="native"?r:a);for(const o of xa({tabKey:a.tabKey}))n.set(o,a)}return n}function qj(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Gj(e){const t=qj(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=Fn(t.content).slice(0,240);return`${e.messages.length}:${n}:${a}`}function zj({ides:e,connectionStates:t,clearedTabs:n}){const a=l.useMemo(()=>$j(e),[e]),r=l.useMemo(()=>np(e),[e]),o=l.useMemo(()=>fm(e),[e]),i=l.useRef([]),c=l.useRef([]),u=l.useRef([]),p=l.useRef(new Map),d=l.useRef(new Map),m=l.useMemo(()=>{const N=new Map,v=[];for(const A of a){const{connectionState:T="new",machineName:D}=bm(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),I=Wj(A),M=p.current.get(A.id);if(M&&M.ide===A&&M.sourceSignature===I&&M.connectionState===T&&M.machineName===D){N.set(A.id,M),v.push(...M.conversations);continue}const P=Tl(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),$={ide:A,sourceSignature:I,connectionState:T,machineName:D,conversations:P};N.set(A.id,$),v.push(...P)}p.current=N;const y=new Map,j=A=>{const T=Gj(A),D=d.current.get(A.tabKey);if(D&&D.signature===T)return y.set(A.tabKey,D),D.timestamp;const I={signature:T,timestamp:Em(A)||(D==null?void 0:D.timestamp)||0};return y.set(A.tabKey,I),I.timestamp},C=[...v].sort((A,T)=>_m(A,T,j));return d.current=y,C},[a,t,o]),h=l.useMemo(()=>{const N=Oj(m,n);return $o(i.current,N)?i.current:(i.current=N,N)},[m,n]),g=l.useMemo(()=>{const N=new Map,v=Array.from(new Set(h.map(y=>y.routeId)));for(const y of v){const j=fs(h,y);j&&N.set(y,j)}return N},[h]),k=l.useMemo(()=>{const N=new Map;for(const v of h){const y=g.get(v.routeId),j=v.streamSource==="native"&&y?y:v;for(const C of xa({providerSessionId:v.providerSessionId,sessionId:v.sessionId,tabKey:v.tabKey}))N.set(C,j)}return N},[h,g]),f=l.useMemo(()=>Uj(h,g),[h,g]),x=l.useCallback(N=>{if(N)return k.get(N)},[k]),w=l.useCallback(N=>{if(N)return f.get(N)},[f]),b=l.useMemo(()=>{const N=h.filter(v=>!Js(v,r).surfaceHidden);return $o(c.current,N)?c.current:(c.current=N,N)},[h,r]),S=l.useMemo(()=>{const N=b.map(v=>v.tabKey);return $o(u.current,N)?u.current:(u.current=N,N)},[b]);return{chatIdes:a,conversations:h,visibleConversations:b,visibleTabKeys:S,resolveConversationBySessionId:x,resolveConversationByTarget:w}}function Kj({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:n,setSearchParams:a}){const r=l.useMemo(()=>{var c;return e||!t?null:((c=n(t))==null?void 0:c.tabKey)??null},[e,n,t]),o=l.useMemo(()=>{var c;return!e||!t?null:((c=n(t))==null?void 0:c.tabKey)??null},[e,n,t]),i=l.useCallback(()=>{t&&a(c=>{const u=new URLSearchParams(c);return u.delete("activeTab"),u},{replace:!0})},[a,t]);return{requestedDesktopTabKey:r,requestedMobileTabKey:o,consumeRequestedActiveTab:i}}function Vj({ides:e,sendDaemonCommand:t,setToasts:n,resolveConversationByTarget:a}){l.useEffect(()=>{bt.setIdes(e)},[e]),l.useEffect(()=>{bt.setResolveAction((r,o,i)=>{t(r,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const r=bt.onToast(o=>{n(c=>c.some(p=>p.message===o.message&&o.timestamp-p.timestamp<3e3)?c:[...c.slice(-4),{id:o.id,message:o.message,type:o.type,timestamp:o.timestamp,targetKey:o.targetKey,actions:o.actions}]);const i=o.duration||5e3;setTimeout(()=>n(c=>c.filter(u=>u.id!==o.id)),i)});return()=>{r()}},[n]),l.useEffect(()=>{const r=em.on("status_event",o=>{bt.handleRawEvent(o,"ws")});return()=>{r()}},[]),l.useEffect(()=>{var o;const r=i=>{var f;const c=i.data;if((c==null?void 0:c.type)!=="notification_action"||typeof c.action!="string"||!c.action.startsWith("approval_")||!(c.daemonId||c.targetSessionId||c.targetKey))return;const u=c.targetSessionId||c.targetKey||c.daemonId,p=a(u),d=(p==null?void 0:p.routeId)||c.daemonId;if(!d)return;const m=Number(c.buttonIndex),h=c.button||((f=p==null?void 0:p.modalButtons)==null?void 0:f[m])||"Approve",g=String(h).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),k=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(g);t(d,"resolve_action",{action:k?"approve":"reject",button:h,...Number.isFinite(m)&&{buttonIndex:m},...(p==null?void 0:p.sessionId)&&{targetSessionId:p.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(x=>console.error("[SW Action] approval failed:",x))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",r),()=>{var i;return(i=navigator.serviceWorker)==null?void 0:i.removeEventListener("message",r)}},[a,t])}const Yj="adhdev_dashboardLayout_v1",Qj="adhdev_dashboardDockview_v1",Jj="adhdev_dashboardDockviewHiddenRestore_v1",ia={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Ll(e,t){try{const n=localStorage.getItem(e);return n?JSON.parse(n):t}catch{return t}}function Xj(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Hm(e){return`${Yj}:${e}`}function Zj(e){const t=Hm(e);return Ll(t,null)}function e1(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=Hm(e);if(n){localStorage.removeItem(a);return}localStorage.setItem(a,JSON.stringify(t))}catch{}}function $m(e){return`${Qj}:${e}`}function t1(e){const t=$m(e);return Ll(t,null)}function s1(e,t){try{const n=$m(e);if(!t){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Fm(e){return`${Jj}:${e}`}function n1(e){const t=Fm(e);return Ll(t,{})}function a1(e,t){try{const n=Fm(e);if(Object.keys(t).length===0){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function r1(){return{groupAssignments:[...ia.groupAssignments],focusedGroup:ia.focusedGroup,groupActiveTabIds:{...ia.groupActiveTabIds},groupTabOrders:{...ia.groupTabOrders},groupSizes:[...ia.groupSizes]}}function o1(e,t){return e?e.length===t.length&&e.every((n,a)=>n===t[a]):t.length===0}function i1(){const[e]=l.useState(()=>Xj(typeof window<"u"?window.innerWidth:1280)),[t,n]=l.useState(()=>new Map),[a,r]=l.useState(0),[o,i]=l.useState({}),[c,u]=l.useState({}),[p,d]=l.useState([]),[m,h]=l.useState(()=>typeof window<"u"&&window.innerWidth<768),[g,k]=l.useState(!1),f=l.useCallback(()=>{if(g)return;const A=Zj(e)??r1();n(new Map(A.groupAssignments)),r(A.focusedGroup),i(A.groupActiveTabIds),u(A.groupTabOrders),d(A.groupSizes),k(!0)},[g,e]);l.useEffect(()=>{g&&e1(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=D=>h(D.matches);return A.addEventListener("change",T),()=>A.removeEventListener("change",T)},[]);const x=l.useCallback(A=>{n(A)},[]),w=l.useCallback(A=>{r(A)},[]),b=l.useCallback(A=>{i(A)},[]),S=l.useCallback(A=>{u(A)},[]),N=l.useCallback(A=>{d(A)},[]),v=l.useCallback(A=>{w(A)},[w]),y=l.useCallback((A,T)=>{i(D=>(D[A]??null)===(T??null)?D:{...D,[A]:T})},[]),j=l.useCallback((A,T)=>{u(D=>{const I=D[A];return o1(I,T)?D:{...D,[A]:T}})},[]),C=l.useCallback((A,T)=>{const D=T.get(A)??0;return y(D,A),v(D),D},[v,y]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:x,focusedGroup:a,updateFocusedGroup:w,focusGroup:v,groupActiveTabIds:o,updateGroupActiveTabIds:b,setGroupActiveTab:y,groupTabOrders:c,updateGroupTabOrders:S,setGroupTabOrder:j,groupSizes:p,updateGroupSizes:N,isMobile:m,hasHydratedStoredLayout:g,hydrateStoredLayout:f,focusConversationTab:C}}function l1(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0],a=Yr(t);return typeof(n==null?void 0:n.id)=="string"&&a.includes(n.id)}function c1({urlActiveTab:e,conversations:t,resolveConversationBySessionId:n,normalizedGroupAssignments:a,hasHydratedStoredLayout:r,hydrateStoredLayout:o,focusConversationTab:i,setSearchParams:c,historyModalOpen:u,activeConv:p,isRefreshingHistory:d,ides:m,handleRefreshHistory:h}){const g=l.useRef(!1),k=l.useRef(!1),f=l.useRef(null),x=l.useRef(!1);l.useEffect(()=>{if(!e||g.current||t.length===0)return;if(!r){o();return}const w=n(e);w&&(i(w.tabKey,a),g.current=!0,k.current=!0,f.current!=null&&(window.clearTimeout(f.current),f.current=null),c(b=>{const S=new URLSearchParams(b);return S.delete("activeTab"),S},{replace:!0}))},[e,t,n,a,r,o,i,c]),l.useEffect(()=>{if(!(k.current||r)&&t.length!==0){if(!e){o(),k.current=!0;return}if(g.current){k.current=!0;return}if(f.current==null)return f.current=window.setTimeout(()=>{f.current=null,!(k.current||r)&&(o(),k.current=!0)},1500),()=>{f.current!=null&&(window.clearTimeout(f.current),f.current=null)}}},[e,t.length,r,o]),l.useEffect(()=>{if(!u){x.current=!1;return}if(!p||x.current||d)return;const w=m.find(b=>b.id===p.routeId);w&&(!w.chats||w.chats.length===0||l1(w.chats,p))&&(x.current=!0,h())},[u,p,d,m,h])}function Fo(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=Yr(t);return typeof(n==null?void 0:n.id)=="string"&&a.includes(n.id)}function Bm({sendDaemonCommand:e,activeConv:t,chats:n,updateRouteChats:a,setToasts:r,setClearedTabs:o}){const[i,c]=l.useState(!1),[u,p]=l.useState(!1),d=l.useCallback(async k=>{try{await e("standalone","launch_ide",{ideType:k,enableCdp:!0})}catch(f){console.error("Launch failed",f)}},[e]),m=l.useCallback(async(k,f)=>{try{const x=k||(t==null?void 0:t.daemonId)||"",w=await e(x,"switch_chat",{id:f,sessionId:f,...dn(t)}),b=w==null?void 0:w.result;if((w==null?void 0:w.success)===!0||b==="switched"||b==="switched-by-title")return;b===!1||b==="not_found"?Dn(r,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?Dn(r,`⚠️ Switch error: ${b}`):Dn(r,"⚠️ Session switch failed")}catch(x){console.error("Switch failed",x),Dn(r,`❌ Switch failed: ${x.message||"connection error"}`)}},[t,e,r]),h=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const k=un(t);await e(k,"new_chat",{...dn(t)}),Jk(k,t.sessionId,Yr(t)[0]),o(f=>({...f,[t.tabKey]:Date.now()}))}catch(k){console.error("New chat failed",k)}finally{c(!1)}}},[t,i,e,o]),g=l.useCallback(async()=>{var k,f;if(!(!t||u)){p(!0);try{const x=un(t),w=async()=>e(x,"list_chats",{forceExpand:!0,...dn(t)});let b=await w(),S=(b==null?void 0:b.chats)||((k=b==null?void 0:b.result)==null?void 0:k.chats);Fo(S,t)&&(await new Promise(N=>setTimeout(N,450)),b=await w(),S=(b==null?void 0:b.chats)||((f=b==null?void 0:b.result)==null?void 0:f.chats)),b!=null&&b.success&&Array.isArray(S)&&(a(t.routeId,S),Fo(S,t)&&!Fo(n,t)&&Dn(r,"⚠️ History dialog did not fully open — try once more"))}catch(x){console.error("Refresh history failed",x)}finally{p(!1)}}},[t,n,u,e,a,r]);return{isCreatingChat:i,isRefreshingHistory:u,handleLaunchIde:d,handleSwitchSession:m,handleNewChat:h,handleRefreshHistory:g}}function d1(e,t){if(e.size!==t.size)return!1;for(const[n,a]of e)if(t.get(n)!==a)return!1;return!0}function u1(e,t){return e.length!==t.length?!1:e.every((n,a)=>n===t[a])}function gd(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 Ja(e,t){const n=new Set(t),a=t.length>0?[0]:[];for(const[i,c]of e)!n.has(i)||c<=0||a.includes(c)||a.push(c);a.sort((i,c)=>i-c);const r={};a.forEach((i,c)=>{r[i]=c}),a.length===0&&(r[0]=0);const o=new Map;for(const[i,c]of e){if(!n.has(i)||c<=0)continue;const u=r[c];typeof u=="number"&&u>0&&o.set(i,u)}return{assignments:o,groupCount:Math.max(1,a.length),mapping:r,usedGroups:a}}function xd(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 p1(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 m1(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 vd(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 yd(e){return Array(e).fill(100/e)}function h1({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:n,updateGroupActiveTabIds:a,updateGroupTabOrders:r,groupSizes:o,updateGroupSizes:i,isMobile:c,visibleConversations:u,visibleTabKeys:p}){const d=l.useRef(null),m=l.useMemo(()=>Ja(e,p),[e,p]),h=m.assignments,g=l.useMemo(()=>c?1:m.groupCount,[m.groupCount,c]),k=g>1,f=l.useCallback((v,y)=>{t(j=>{const C=new Map(Ja(j,p).assignments);return y===0?C.delete(v):C.set(v,y),C}),a(j=>({...j,[y]:v})),n(y)},[t,p,a,n]),x=l.useCallback(v=>{t(y=>{const j=Ja(y,p).assignments,C=new Map;for(const[A,T]of j)T!==v&&(T>v?C.set(A,T-1):C.set(A,T));return C}),i(y=>{if(y.length<=1)return[];const j=[...y];j.splice(v,1);const C=j.reduce((A,T)=>A+T,0);return C>0?j.map(A=>A/C*100):[]}),n(0)},[t,p,i,n]),w=l.useCallback((v,y)=>{y.preventDefault();const j=d.current;if(!j)return;const C=y.clientX,A=j.offsetWidth,T=o.length===g?[...o]:yd(g),D=M=>{const $=(M.clientX-C)/A*100,L=[...T];L[v]=Math.max(15,T[v]+$),L[v+1]=Math.max(15,T[v+1]-$),i(L)},I=()=>{document.removeEventListener("mousemove",D),document.removeEventListener("mouseup",I),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",D),document.addEventListener("mouseup",I)},[o,g,i]),b=l.useCallback((v,y,j)=>{if(g>=4)return;const C=j==="left"?y:y+1;t(A=>{const T=Ja(A,p).assignments,D=new Map;for(const I of u){const M=T.get(I.tabKey)??0,P=M>=C?M+1:M;P>0&&D.set(I.tabKey,P)}return C>0&&D.set(v,C),D}),i(A=>{const T=A.length===g?[...A]:yd(g),D=T[y]??100/g,I=Math.max(15,D/2),M=Math.max(15,D/2),P=[...T];P[y]=I,P.splice(C,0,M);const $=P.reduce((L,R)=>L+R,0);return P.map(L=>L/$*100)}),a(A=>{const T=vd(A,C);return T[C]=v,T}),r(A=>{const T=vd(A,C);return T[C]=[v],T}),n(C)},[g,t,p,u,i,a,r,n]);l.useEffect(()=>{d1(e,h)||t(h)},[e,h,t]),l.useEffect(()=>{const{mapping:v,usedGroups:y}=m;a(j=>{const C=xd(j,v);return gd(j,C)?j:C}),r(j=>{const C=xd(j,v);return gd(j,C)?j:C}),n(j=>{const C=c?0:p1(j,y,v);return j===C?j:C}),i(j=>{const C=c?[]:m1(j,y,m.groupCount);return u1(j,C)?j:C})},[m,c,a,r,n,i]);const S=l.useMemo(()=>{const v=Array.from({length:g},()=>[]);for(const y of u){const j=h.get(y.tabKey)??0,C=Math.min(j,g-1);v[C].push(y)}return v},[u,h,g]),N=l.useCallback(()=>{t(new Map),n(0)},[t,n]);return{containerRef:d,normalizedGroupAssignments:h,numGroups:g,isSplitMode:k,groupedConvs:S,moveTabToGroup:f,closeGroup:x,handleResizeStart:w,splitTabRelative:b,clearAllSplits:N}}function f1({ides:e,sendDaemonCommand:t}){const n="1.0.42",a=l.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:no(m,qs(m,n))).sort((m,h)=>Number(wa(h,qs(h,n)))-Number(wa(m,qs(m,n)))),[n,e]),r=l.useMemo(()=>a.some(m=>wa(m,qs(m,n))),[n,a]),o=l.useMemo(()=>a.map(m=>qs(m,n)).find(m=>typeof m=="string"&&m.trim().length>0)||n,[n,a]),[i,c]=l.useState(!1),[u,p]=l.useState({}),d=l.useCallback(async m=>{var k,f;const h=e.find(x=>x.id===m);if(!h)return;p(x=>({...x,[m]:"upgrading"}));const g=ao(h);if(!g){p(x=>({...x,[m]:"error"}));return}try{const x=await t(m,"daemon_upgrade",g);(k=x==null?void 0:x.result)!=null&&k.upgraded||(f=x==null?void 0:x.result)!=null&&f.success?p(w=>({...w,[m]:"done"})):p(w=>({...w,[m]:"error"}))}catch{p(x=>({...x,[m]:"error"}))}},[e,t]);return{versionMismatchDaemons:a,hasRequiredVersionDaemons:r,targetVersion:o,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:u,handleBannerUpgrade:d}}const Wm=80;function br(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function b1(e){return{...e,createdAt:br(e.createdAt),updatedAt:br(e.updatedAt,e.createdAt),lastEventAt:br(e.lastEventAt,e.updatedAt||e.createdAt)}}function g1(e){const t=dp(e);return t==="unknown:"?e.id:t}function x1(e){return[e.type,cp(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function v1(e,t=Wm){const n=new Map;for(const a of e){if(a.deletedAt)continue;const r=g1(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 y1(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=Vr(r,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const u=br(r.lastMessageAt||(o==null?void 0:o.lastUpdated)||r.lastUpdated,n),p=x1({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(b1({id:p,dedupKey:p,type:c,routeId:r.routeId,machineId:r.daemonId||r.routeId,sessionId:r.sessionId,providerSessionId:r.providerSessionId,tabKey:r.tabKey,title:Pp(r),preview:ck(r),createdAt:u,updatedAt:u,lastEventAt:u}))}return v1(a)}function w1(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function k1(e){const{conversations:t,liveSessionInboxState:n,maxItems:a=Wm}=e,r=l.useMemo(()=>y1(t,n).slice(0,Math.max(0,a)),[t,n,a]),o=l.useMemo(()=>w1(r),[r]);return{notifications:r,unreadCount:o}}function S1({notifications:e,sendDaemonCommand:t}){const n=l.useCallback(o=>{const i=e.find(u=>u.id===o),c=Math.max(Date.now(),(i==null?void 0:i.updatedAt)||0);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_session_seen",{sessionId:i.sessionId,seenAt:c}).catch(()=>{})},[e,t]),a=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_notification_unread",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]),r=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"delete_notification",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:n,handleMarkDashboardNotificationUnread:a,handleDeleteDashboardNotification:r}}function Rl(...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 C1(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 El(e,t=[]){if(e==="win32"){for(const n of t){if(typeof n!="string")continue;const a=C1(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 j1(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 N1(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function _l(e,t,n){const a=await e(t,"file_list_browse",{path:n}),r=N1(a);if(!(r!=null&&r.success))throw new Error((r==null?void 0:r.error)||(a==null?void 0:a.error)||"Could not browse folder");const o=typeof(r==null?void 0:r.path)=="string"?r.path:n,i=o.includes("\\")?"\\":"/",c=(p,d)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${d}`:p==="/"||p==="\\"?`${i}${d}`:`${p.replace(/[\\/]+$/,"")}${i}${d}`,u=Array.isArray(r==null?void 0:r.files)?r.files.filter(p=>(p==null?void 0:p.type)==="directory"&&typeof(p==null?void 0:p.name)=="string").map(p=>({name:p.name,path:typeof(p==null?void 0:p.path)=="string"&&p.path.trim()?p.path:c(o,p.name)})).sort((p,d)=>p.name.localeCompare(d.name)):[];return{path:o,directories:u}}function wd(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 Om(e,t={}){const n=e==null?void 0:e.mcpConfig;if((n==null?void 0:n.mode)!=="manual")return null;const r=wd(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"}).trim();return!r.includes(`
|
|
70
|
+
`)&&!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:wd(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"})}}function A1(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 Ia(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Um(e){return Qr(e)||e.tabKey||e.routeId||null}function qm(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=fs(e.conversations,a)||e.conversations.find(i=>i.routeId===a);if(o!=null&&o.tabKey)return o.tabKey}return t||n||a||null}function Gs(e){return String(e||"").trim()}function Gm(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Fr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function T1(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function M1(e,t){const n=Gs(e.providerSessionId),a=Gs(e.targetSessionId),r=t.find(o=>{const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(Gs).filter(Boolean);return!!(n&&i.includes(n)||a&&i.includes(a))});return r?r.tabKey:a||n||null}function D1(e,t,n){if(t.event!=="agent:generating_completed")return null;const a=Gm(t.daemonId);if(a&&a!==e.machineId)return null;const r=Gs(t.providerType);if(e.providerType&&r!==e.providerType)return null;const o=Gs(e.resumeSessionId),i=Gs(e.launchedSessionId),c=Gs(t.providerSessionId),u=Gs(t.targetSessionId);if(o&&o!==c&&o!==u||i&&i!==c&&i!==u)return null;const p=Fr(e.workspacePath);if(p){const d=Fr(t.workspaceName);if(d&&!T1(d,p))return null}return M1(t,n)}function kd(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function P1({ides:e,conversations:t,onOpenSession:n}){const[a,r]=l.useState(null),o=l.useRef(null),i=l.useCallback(()=>{o.current=null,r(null)},[]),c=l.useCallback(u=>{o.current=u,r(u)},[]);return l.useEffect(()=>{if(!a)return;const u=Fr(a.workspacePath),p=e.find(m=>{var x,w,b,S;if(!m||m.type==="adhdev-daemon"||Gm(m.daemonId||m.id)!==a.machineId||(Ma(m)?"cli":_n(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 N=String(a.launchedSessionId||"");return[m.providerSessionId,m.sessionId,m.instanceId,m.id].map(y=>String(y||"")).filter(Boolean).includes(N)}if(u){const N=Fr(m.workspace||m.runtimeWorkspaceLabel);return N?N===u:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((S=(b=(w=(x=m.activeChat)==null?void 0:x.messages)==null?void 0:w.at)==null?void 0:b.call(w,-1))==null?void 0:S.timestamp)||0)>=a.startedAt-5e3});if(!p)return;const d=qm({entrySessionId:p.sessionId,entryInstanceId:p.instanceId,entryRouteId:p.id,conversations:t});d&&(i(),n(d))},[i,t,e,n,a]),l.useEffect(()=>bt.onStatusEvent(u=>{const p=o.current;if(!p)return;const d=D1(p,u,t);d&&(i(),n(d))}),[i,t,n]),l.useEffect(()=>{if(!a)return;const u=window.setTimeout(()=>{r(p=>!p||p.startedAt!==a.startedAt?p:(o.current=null,null))},45e3);return()=>window.clearTimeout(u)},[a]),{trackPendingLaunch:c}}function I1(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 L1(e,t,n){var i,c,u,p;const a={meshId:e.trim()};t.trim()&&(a.cliType=t.trim());const r=(i=n==null?void 0:n.initialModel)==null?void 0:i.trim(),o=(c=n==null?void 0:n.initialThinkingLevel)==null?void 0:c.trim();return r&&(a.initialModel=r),o&&(a.initialThinkingLevel=o),(u=n==null?void 0:n.settings)!=null&&u.autoApproveMode?a.autoApproveMode=n.settings.autoApproveMode:typeof((p=n==null?void 0:n.settings)==null?void 0:p.autoApprove)=="boolean"&&(a.autoApprove=n.settings.autoApprove),a}function R1({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:n,activeConv:a,ides:r,setCliViewModeOverrides:o}){const i=gl(),{launchCli:c}=qr(),u=l.useCallback(async(x,w)=>_l(e,x,w),[e]),p=l.useCallback(async(x,w)=>{if(!w.trim())return{ok:!1,error:"Choose a workspace path first."};try{const b=await e(x,"workspace_add",{path:w.trim()});return b!=null&&b.success?{ok:!0}:{ok:!1,error:(b==null?void 0:b.error)||"Could not save workspace"}}catch(b){return{ok:!1,error:b instanceof Error?b.message:"Could not save workspace"}}},[e]),d=l.useCallback(async(x,w,b)=>{var S;try{const N={ideType:w,enableCdp:!0};(S=b==null?void 0:b.workspacePath)!=null&&S.trim()&&(N.workspace=b.workspacePath.trim());const v=await e(x,"launch_ide",N);return!(v!=null&&v.success)&&(v==null?void 0:v.success)!==void 0?{ok:!1,error:(v==null?void 0:v.error)||"Could not launch IDE"}:(t({machineId:x,kind:"ide",providerType:w,workspacePath:(b==null?void 0:b.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(N){return{ok:!1,error:N instanceof Error?N.message:"Could not launch IDE"}}},[e,t]),m=l.useCallback(async(x,w,b,S)=>{const N=Date.now();try{const v=I1(b,S),y=await c(x,v),j=(y==null?void 0:y.result)||y,C=(j==null?void 0:j.sessionId)||(j==null?void 0:j.id);return y!=null&&y.success&&C?(t({machineId:x,kind:w,providerType:b,workspacePath:(S==null?void 0:S.workspacePath)||null,resumeSessionId:(S==null?void 0:S.resumeSessionId)||null,launchedSessionId:C,startedAt:N}),{ok:!0}):y!=null&&y.success?(t({machineId:x,kind:w,providerType:b,workspacePath:(S==null?void 0:S.workspacePath)||null,resumeSessionId:(S==null?void 0:S.resumeSessionId)||null,startedAt:N}),{ok:!0}):{ok:!1,error:(y==null?void 0:y.error)||(j==null?void 0:j.error)||`Could not launch ${w.toUpperCase()} session`,code:(y==null?void 0:y.code)||(j==null?void 0:j.code)||void 0}}catch(v){return kd(v)?(t({machineId:x,kind:w,providerType:b,workspacePath:(S==null?void 0:S.workspacePath)||null,resumeSessionId:(S==null?void 0:S.resumeSessionId)||null,startedAt:N}),{ok:!0}):{ok:!1,error:v instanceof Error?v.message:`Could not launch ${w.toUpperCase()} session`}}},[c,e,t]),h=l.useCallback(async x=>{var w;if(i!=null&&i.listMeshes)return i.listMeshes(x);if(!x)return[];try{const b=await e(x,"list_meshes",{}),S=(b==null?void 0:b.result)??b;if((S==null?void 0:S.success)===!1)throw new Error((S==null?void 0:S.error)||"Could not load meshes");return(Array.isArray(S==null?void 0:S.meshes)?S.meshes:Array.isArray((w=S==null?void 0:S.result)==null?void 0:w.meshes)?S.result.meshes:[]).map(v=>{var y;return{id:String((v==null?void 0:v.id)||""),name:String((v==null?void 0:v.name)||(v==null?void 0:v.id)||"Untitled mesh"),repoIdentity:(v==null?void 0:v.repoIdentity)||(v==null?void 0:v.repo_identity)||null,workspace:Array.isArray(v==null?void 0:v.nodes)&&v.nodes.length>0?String(((y=v.nodes[0])==null?void 0:y.workspace)||""):null,nodesCount:Array.isArray(v==null?void 0:v.nodes)?v.nodes.length:void 0,status:(v==null?void 0:v.status)||null}}).filter(v=>v.id)}catch(b){throw console.error("List meshes failed",b),b}},[i,e]),g=l.useCallback(async(x,w,b,S)=>{if(!w.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(x,w,b,S);const N=Date.now();try{const v=L1(w,b,S),y=await e(x,"launch_mesh_coordinator",v),j=(y==null?void 0:y.result)??y;if((j==null?void 0:j.success)===!1||(y==null?void 0:y.success)===!1){const A=String((j==null?void 0:j.code)||(y==null?void 0:y.code)||""),T=A1((j==null?void 0:j.meshCoordinatorSetup)||(j==null?void 0:j.manualSetup)||(y==null?void 0:y.meshCoordinatorSetup)||(y==null?void 0:y.manualSetup));return{ok:!1,error:(j==null?void 0:j.error)||(y==null?void 0:y.error)||"Could not launch mesh coordinator",code:A||void 0,manualSetup:T}}const C=(j==null?void 0:j.sessionId)||(j==null?void 0:j.id);return C?n(C):t({machineId:x,kind:"cli",providerType:(j==null?void 0:j.cliType)||b.trim()||void 0,workspacePath:(j==null?void 0:j.workspace)||null,startedAt:N}),{ok:!0}}catch(v){return kd(v)?(t({machineId:x,kind:"cli",providerType:b.trim()||void 0,startedAt:N}),{ok:!0}):{ok:!1,error:v instanceof Error?v.message:"Could not launch mesh coordinator"}}},[i,n,e,t]),k=l.useCallback(async(x,w)=>{if(!x||!w)return[];try{const b=await e(x,"list_saved_sessions",{providerType:w,kind:"cli",limit:30}),S=(b==null?void 0:b.result)??b;return Array.isArray(S==null?void 0:S.sessions)?S.sessions:[]}catch(b){return console.error("List saved sessions failed",b),[]}},[e]),f=l.useCallback(async x=>{await Rm({conversation:a,mode:x,ides:r,sendDaemonCommand:e,setCliViewModeOverrides:o})},[a,r,e,o]);return{handleBrowseMachineDirectory:u,handleSaveMachineWorkspace:p,handleLaunchMachineIde:d,handleLaunchMachineProvider:m,handleListMachineMeshes:h,handleLaunchMeshCoordinator:g,handleListMachineSavedSessions:k,setActiveCliViewMode:f}}function E1(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 _1(e,t,n=Date.now()){return!e||!E1(t)?null:{tabKey:e,nonce:n}}function H1({isMobile:e,conversations:t,visibleConversations:n,groupActiveTabIds:a,focusedGroup:r,groupedConvs:o,setSearchParams:i}){const[c,u]=l.useState(null),[p,d]=l.useState(null),m=l.useMemo(()=>{var x,w;if(!e){if(c){const b=t.find(S=>S.tabKey===c);if(b)return b}return n[0]}const f=a[r];if(f){const b=t.find(S=>S.tabKey===f);if(b)return b}return((x=o[r])==null?void 0:x[0])||((w=o[0])==null?void 0:w[0])},[t,c,r,a,o,e,n]),h=l.useCallback(f=>{u(f)},[]),g=l.useCallback(f=>{u(f.tabKey),i(x=>{const w=new URLSearchParams(x),b=uk(f);return b?w.set("activeTab",b):w.delete("activeTab"),w},{replace:!0})},[i]),k=l.useCallback((f,x)=>{const w=_1(f,x);w&&d(w)},[]);return{activeConv:m,openDesktopConversation:g,requestScrollToBottom:k,scrollToBottomRequest:p,setDesktopActiveTab:h}}function $1(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 F1(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 B1({activeConv:e,isMobile:t,liveSessionInboxState:n,sendDaemonCommand:a}){const r=l.useRef(null),o=l.useRef(null),i=l.useRef(null),c=l.useRef(null),u=l.useRef(null);l.useEffect(()=>{const p=()=>{i.current&&(clearTimeout(i.current),i.current=null),c.current&&(clearTimeout(c.current),c.current=null),u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null),o.current=null};if(t){p(),r.current=null;return}if(!(e!=null&&e.sessionId)){p(),r.current=null;return}const d=Js(e,n),m=F1({tabKey:e.tabKey,historySessionId:Qr(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:fn(e),liveState:d}),h=m.autoReadKey,g=$1({autoReadKey:h,shouldMarkSeen:m.shouldMarkSeen,completedKey:r.current,pendingKey:o.current});if(!m.shouldMarkSeen){g.shouldCancelPending&&p(),r.current=h;return}if(!g.shouldSchedule)return;g.shouldCancelPending&&p();const k=()=>{if(document.visibilityState!=="visible"||r.current===h)return;r.current=h,o.current=null,i.current=null,c.current=null,u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null);const x=m.readAt;a(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:x,completionMarker:m.completionMarker}).catch(()=>{})};if(o.current=g.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(k,1500);const x=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};u.current=x,document.addEventListener("visibilitychange",x);return}const f=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(k,800),u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null))};u.current=f,document.addEventListener("visibilitychange",f)},[e,t,n,a]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current),c.current&&clearTimeout(c.current),u.current&&document.removeEventListener("visibilitychange",u.current)},[])}function Bo(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 W1({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:n,ides:a,sendDaemonCommand:r,updateRouteChats:o,setToasts:i,setClearedTabs:c,setSearchParams:u}){var F;const{launchCli:p}=qr(),[d,m]=l.useState(!1),[h,g]=l.useState([]),[k,f]=l.useState(()=>Ut()),[x,w]=l.useState(!1),[b,S]=l.useState(null),N=l.useRef(null),v=l.useMemo(()=>n||t||e,[e,n,t]),y=!!v&&ft(v)&&!pt(v),j=l.useMemo(()=>{if(!v||!y)return null;const E=v.daemonId||v.routeId||"",H=Ts(v),_=Bo(v);return`${E}:${H}:${v.providerSessionId||""}:${_}`},[v,y]),C=l.useMemo(()=>!v||!y?"":Bo(v),[v,y]),{isCreatingChat:A,isRefreshingHistory:T,handleSwitchSession:D,handleNewChat:I,handleRefreshHistory:M}=Bm({sendDaemonCommand:r,activeConv:v,chats:(F=a.find(E=>E.id===(v==null?void 0:v.routeId)))==null?void 0:F.chats,updateRouteChats:o,setToasts:i,setClearedTabs:c}),P=l.useCallback(()=>{m(!0)},[]),$=l.useCallback(()=>{m(!1)},[]),L=l.useCallback(async()=>{if(!(!v||!y||x)){w(!0);try{const E=v.daemonId||v.routeId,H=Ts(v),_=Bo(v),G=await r(E,"list_saved_sessions",{agentType:H,providerType:H,kind:"cli",limit:50,...v.providerSessionId?{providerSessionId:v.providerSessionId}:{},..._?{workspace:_}:{}}),W=(G==null?void 0:G.result)??G;g(Array.isArray(W==null?void 0:W.sessions)?W.sessions:[])}catch(E){console.error("Refresh saved sessions failed",E),g([])}finally{w(!1)}}},[v,x,y,r]);l.useEffect(()=>{if(!d){N.current=null;return}if(!y){N.current=null,g([]),w(!1);return}!j||x||N.current!==j&&(N.current=j,L())},[L,d,x,y,j]);const R=l.useCallback(async E=>{if(!v||!y||!E.providerSessionId||!E.workspace)return;const H=v.daemonId||v.routeId,_=Ts(v);try{S(E.providerSessionId);const G=await p(H,{cliType:_,dir:E.workspace,resumeSessionId:E.providerSessionId,initialModel:fp(E.summaryMetadata,"model",{preferShortValue:!0})||void 0}),W=(G==null?void 0:G.result)??G,K=typeof(W==null?void 0:W.sessionId)=="string"?W.sessionId:typeof(W==null?void 0:W.id)=="string"?W.id:"";K&&u(V=>{const te=new URLSearchParams(V);return te.set("activeTab",K),te},{replace:!0}),$()}catch(G){console.error("Resume saved session failed",G)}finally{S(null)}},[$,v,y,r,u]);return{historyModalOpen:d,openHistoryModal:P,closeHistoryModal:$,historyTargetConv:v,isSavedSessionHistoryTarget:y,isHistoryCreatingChat:A,isHistoryRefreshingHistory:T,handleHistorySwitchSession:D,handleHistoryNewChat:I,handleHistoryRefresh:M,savedHistorySessions:h,savedHistoryFilters:k,setSavedHistoryFilters:f,missingWorkspaceResumePath:C,isSavedHistoryLoading:x,resumingSavedHistorySessionId:b,handleRefreshSavedHistory:L,handleResumeSavedHistorySession:R}}function O1({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c}){const[u,p]=l.useState(null),[d,m]=l.useState(null),h=l.useMemo(()=>{if(e||!a)return null;const w=c(a);return w&&!ft(w)&&!pt(w)?w:null},[e,a,c]),g=l.useMemo(()=>{const w=u==null?void 0:u.routeId;if(!w)return null;const b=u!=null&&u.tabKey?o.find(S=>S.tabKey===u.tabKey):r?o.find(S=>S.tabKey===r):null;return(b==null?void 0:b.routeId)===w?b:fs(o,w)},[o,u,r]),k=l.useMemo(()=>{if(g)return i.find(w=>w.id===g.routeId)},[i,g]);l.useEffect(()=>{h&&(p({routeId:h.routeId,tabKey:Rc(h)}),m(h),n({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,n,h]);const f=l.useCallback(w=>{w&&(p({routeId:w.routeId,tabKey:Rc(w)}),m(w))},[]),x=l.useCallback(()=>{p(null),m(null)},[]);return{remoteDialogConv:g,remoteDialogIdeEntry:k,remoteDialogActiveConv:d,setRemoteDialogActiveConv:m,openRemoteDialog:f,closeRemoteDialog:x}}function U1({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c,activeConv:u,sendDaemonCommand:p}){const{remoteDialogConv:d,remoteDialogIdeEntry:m,remoteDialogActiveConv:h,setRemoteDialogActiveConv:g,openRemoteDialog:k,closeRemoteDialog:f}=O1({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:a,requestedDesktopTabKey:r,conversations:o,ides:i,resolveConversationByTarget:c}),[x,w]=l.useState(!1),[b,S]=l.useState(null),N=l.useCallback(async j=>{const C=j||u;!C||!ft(C)&&!pt(C)||(S(C),w(!0))},[u]),v=l.useCallback(()=>{w(!1),S(null)},[]),y=l.useCallback(async j=>{const C=b||u;if(!C||!ft(C)&&!pt(C)){v();return}w(!1);try{const A=Ts(C),T=C.routeId||C.daemonId||"";await p(T,"stop_cli",{cliType:A,targetSessionId:C.sessionId,mode:j,...Zr(C)})}catch(A){console.error("Stop CLI failed:",A)}finally{S(null)}},[u,v,b,p]);return{remoteDialogConv:d,remoteDialogIdeEntry:m,remoteDialogActiveConv:h,setRemoteDialogActiveConv:g,openRemoteDialog:k,closeRemoteDialog:f,cliStopDialogOpen:x,cliStopTargetConv:b,requestCliStop:N,cancelCliStop:v,confirmCliStop:y}}function Wo(e,t=!0){return(e??!0)&&t}const Hl=l.memo(function({activeConv:t,clearToken:n,isCliTerminal:a,ideEntry:r,terminalRef:o,handleModalButton:i,handleRelaunch:c,handleSendChat:u,handleForceSendChat:p,isSendingChat:d,sendFeedbackMessage:m=null,handleFocusAgent:h,isFocusingAgent:g,actionLogs:k,userName:f,scrollToBottomRequestNonce:x,isInputActive:w=!0,isVisible:b=!0}){const S=a,N=!a,v=Wo(b,S),y=Wo(b,N),j=Wo(b),C=Pm(t),A=C.status||C.modalMessage||C.modalButtons?{...t,...C.status?{status:C.status}:{},...C.modalMessage!==void 0?{modalMessage:C.modalMessage}:{},...C.modalButtons!==void 0?{modalButtons:C.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(ap,{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(gn,{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:S?"visible":"hidden",pointerEvents:S?"auto":"none"},children:s.jsx(zS,{activeConv:A,clearToken:n,terminalRef:o,handleSendChat:u,isSendingChat:d,sendFeedbackMessage:m,isVisible:v,isInputActive:w&&v})}),s.jsx("div",{"aria-hidden":a,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:N?"visible":"hidden",pointerEvents:N?"auto":"none"},children:s.jsx($i,{activeConv:A,ideEntry:r,handleSendChat:u,isSendingChat:d,sendFeedbackMessage:m,handleFocusAgent:h,isFocusingAgent:g,actionLogs:k,userName:f,scrollToBottomRequestNonce:x,isInputActive:w&&y,isVisible:y})})]}):s.jsx($i,{activeConv:A,ideEntry:r,handleSendChat:u,handleForceSendChat:p,isSendingChat:d,sendFeedbackMessage:m,handleFocusAgent:h,isFocusingAgent:g,actionLogs:k,userName:f,scrollToBottomRequestNonce:x,isInputActive:w&&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 q1({conversation:e,className:t="",onOpenNativeConversation:n,onOpenMachine:a,interactive:r=!0,meshOnly:o=!1}){var N,v,y;const{t:i}=Ce("common"),c=Ea(),u=Bs(e),p=o?null:Dp(e),d=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),m=!o&&e.streamSource==="agent-stream"&&!!e.agentName,h=!o&&!m&&(e.transport==="pty"||e.transport==="acp"),g=Wn(e),k=dk(e),f=(N=e.settings)==null?void 0:N.meshNodeFor,x=e.meshQueueStats,w=((v=e.coordinator)==null?void 0:v.meshId)||((y=e.settings)==null?void 0:y.meshCoordinatorFor),b=l.useCallback(()=>{if(a){a();return}u&&c("/dashboard",{state:{openMachineId:u}})},[u,c,a]),S=l.useCallback(()=>{if(n){n();return}const j=Um(e);j&&c(Ia(j))},[e,c,n]);return!d&&!m&&!h&&!p&&!f&&!x?null:s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[d&&(r?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:S,title:k,children:[s.jsx(gs,{size:12}),s.jsx("span",{children:k})]}):s.jsxs("span",{className:"conversation-meta-chip",title:k,children:[s.jsx(gs,{size:12}),s.jsx("span",{children:k})]})),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(Na,{size:12}),s.jsx("span",{children:g})]}),h&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(Na,{size:12}),s.jsx("span",{children:g})]}),p&&(r?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:b,title:p,children:[s.jsx(Ys,{size:12}),s.jsx("span",{children:p})]}):s.jsxs("span",{className:"conversation-meta-chip",title:p,children:[s.jsx(Ys,{size:12}),s.jsx("span",{children:p})]})),f&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(Ys,{size:12}),s.jsx("span",{children:i("dashboard.metaChips.meshNode")})]}),w&&x&&s.jsxs("span",{className:`conversation-meta-chip ${x.pending>0?"is-active":""}`,style:x.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${x.pending} pending, ${x.assigned} assigned, ${x.completed} completed, ${x.failed} failed`,children:[s.jsx(Sb,{size:12}),s.jsxs("span",{children:[x.pending," Pending"]})]})]})}function G1({selectedConversation:e,isAcp:t,isStandalone:n,selectedIdeEntry:a,actionLogs:r,userName:o,isSendingChat:i,sendFeedbackMessage:c=null,isFocusingAgent:u,onBack:p,onOpenNativeConversation:d,onOpenMachine:m,onOpenHistory:h,onOpenRemote:g,onOpenMeshGraph:k,onStopCli:f,cliViewMode:x,onSetCliViewMode:w,handleSendChat:b,handleForceSendChat:S,handleFocusAgent:N,handleModalButton:v,handleRelaunch:y}){var I,M;const j=l.useRef(null),C=ft(e)&&!t,A=C&&x==="terminal",T=!!e.daemonId&&!!((I=e.coordinator)!=null&&I.meshId||(M=e.settings)!=null&&M.meshCoordinatorFor),D=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 ${D} 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(al,{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:wt(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(q1,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>d(e),onOpenMachine:()=>m(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[C&&x&&s.jsx(im,{mode:x,onChange:w,compact:!0}),C&&f&&s.jsx("button",{onClick:()=>{f(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(Pt,{size:14})}),T&&k&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>k(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(as,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>h(e),type:"button",children:s.jsx(ol,{size:14})}),!t&&!C&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",children:s.jsx(gs,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(Hl,{activeConv:e,clearToken:0,isCliTerminal:A,ideEntry:a,terminalRef:j,handleModalButton:v,handleRelaunch:y,handleSendChat:b,handleForceSendChat:S,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:N,isFocusingAgent:u,actionLogs:r,userName:o})})]})}const Oo={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 z1(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function zm(){const[e,t]=l.useState("unix"),[n,a]=l.useState("powershell"),[r,o]=l.useState(!1),i=e==="unix"?"unix":n;l.useEffect(()=>{t(z1())},[]);const c=l.useCallback(()=>{navigator.clipboard.writeText(Oo[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:Oo[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:Oo[i].cmd}),s.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:r?"✓":"📋"})]}),s.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",s.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function Km({section:e,onSectionChange:t}){const n=[{key:"machines",label:"Machines",icon:gs},{key:"chats",label:"Chats",icon:kn}];return s.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:s.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:n.map(({key:a,label:r,icon:o})=>{const i=e===a;return s.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${i?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:i?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>t(a),type:"button","aria-pressed":i,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${i?"text-accent-primary":"bg-transparent text-current"}`,style:i?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:s.jsx(o,{size:15})}),s.jsx("span",{children:r})]},a)})})})}function Xa({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 An({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 an({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 K1({conversation:e,onCancel:t,onConfirm:n}){const{t:a}=Ce(),r=wt(e);return s.jsx(Yt,{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 Za({item:e,type:t,getAvatarText:n,onOpenConversation:a,onRequestHideConversation:r,onRequestStopCli:o,onOpenMeshGraph:i,onCollectChatDebugBundle:c,isMuted:u,onToggleMute:p}){const{t:d}=Ce(),m=t==="needs_attention"||t==="task_complete",h=t==="working",g=t==="earlier",k=t==="task_complete",{isReconnecting:f,isConnecting:x}=Sn(e.conversation),w=wt(e.conversation),b=On(e.conversation),S=nm(e.conversation,{requiresAction:t==="needs_attention"}),N=m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":h?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":g?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",v=m?"bg-accent-primary shadow-glow":h?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":g?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",y=g?"text-text-secondary":"text-text-primary",j=g?"text-text-muted":"text-text-secondary",C=g?"text-text-secondary opacity-80":"text-text-muted",A=g?"text-text-muted opacity-80":"text-text-muted",T=!h&&!k,D=tm(e.conversation),I="text-[color:var(--status-warning)]",M=P=>{if(!c)return;P.preventDefault(),P.stopPropagation();const $=c==null?void 0:c(e.conversation);Promise.resolve($).catch(L=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",L)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${N}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[m||h?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${v}`,style:m?{color:"var(--accent-on-primary)"}:void 0,children:n(w)}),D&&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:P=>{P.preventDefault(),P.stopPropagation(),i(e.conversation)},"aria-label":d("mobileInbox.openMeshGraphFor",{title:w}),title:d("mobileInbox.openLiveMeshGraph"),children:s.jsx(as,{size:13})})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>a(e.conversation),onContextMenu:M,type:"button",children:[s.jsx("div",{className:"flex items-center gap-2 pr-[124px]",children:s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${y}`,children:w})}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${j}`,children:[s.jsx("span",{className:"truncate",children:b}),s.jsx(Pr,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),f?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${I} animate-pulse`,children:d("mobileInbox.reconnectingItem")})]}):x?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:d("mobileInbox.connectingItem")})]}):S==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:I,children:d("mobileInbox.actionNeeded")})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${C}`,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:sp(e.timestamp)}),k&&s.jsx("span",{className:"rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:d("mobileInbox.done")}),p&&s.jsx("button",{type:"button",className:`mobile-inbox-mute-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border transition-colors ${u?"border-amber-500/60 bg-amber-500 text-white hover:bg-amber-600":"border-border-subtle bg-bg-primary/70 text-text-muted hover:border-border-default hover:text-text-primary"}`,onClick:P=>{P.preventDefault(),P.stopPropagation(),p()},"aria-label":u?d("mobileInbox.unmute",{title:w}):d("mobileInbox.mute",{title:w}),title:d(u?"mobileInbox.mutedTitle":"mobileInbox.muteNotifications"),children:u?s.jsx(qu,{size:13}):s.jsx(Vn,{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:P=>{P.preventDefault(),P.stopPropagation(),r()},"aria-label":d("mobileInbox.hideConversationAria",{title:w}),title:d("mobileInbox.hideConversationTitle"),children:s.jsx(il,{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:P=>{P.preventDefault(),P.stopPropagation(),o()},"aria-label":d("mobileInbox.stopSessionAria",{title:w}),title:d("mobileInbox.stopSessionTitle"),children:s.jsx(Pt,{size:13})})]})]})},e.conversation.tabKey)}function er({size:e=32}){return s.jsx("div",{className:"flex flex-col items-center gap-2.5",children:s.jsx("div",{className:"rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light",style:{width:e,height:e}})})}function Sd({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 V1({section:e,attentionItems:t,unreadItems:n,workingItems:a,completedItems:r,hiddenConversations:o,machineCards:i,getAvatarText:c,actionLogs:u,sendDaemonCommand:p,onOpenConversation:d,onShowAllHidden:m,onHideConversation:h,onOpenMeshGraph:g,onStopCli:k,onOpenNewSession:f,onOpenMachine:x,onOpenSettings:w,onSectionChange:b,wsStatus:S="connected",initialDataLoaded:N=!0,conversationsLoaded:v,isStandalone:y=!1,onCollectChatDebugBundle:j,isConversationMuted:C,onToggleMuteConversation:A}){const{t:T}=Ce(),[D,I]=l.useState(null),M=S==="disconnected"||S==="reconnecting"||S==="offline"||S==="auth_failed",P=!M&&!N,$=!M&&!(v??N),L=i.length>0,R=t.length>0||n.length>0||a.length>0||r.length>0,F=T(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),E=y?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",H=y?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",_=l.useCallback(async K=>{const V=un(K);if(!V)return;const te=Array.isArray(K.messages)?K.messages:[],le=Hp({activeConv:K,visibleMessages:te,actionLogs:u,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:te.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),de=await p(V,"get_chat_debug_bundle",{...dn(K),delivery:"daemon_file",frontendSnapshot:le}),ee=ya(de),z=Bp(ee),X=await Fp(z);X==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),bt.showToast($p(ee,{locatorCopyStatus:X}),X==="failed"?"warning":"success")},[u,p]),G=j||_,W=l.useCallback(()=>{D&&(h==null||h(D),I(null))},[D,h]);return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${E}`,children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:F}),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(Vn,{size:13}),s.jsx("span",{children:t.length+n.length})]}),s.jsx("button",{onClick:w,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:s.jsx(Gr,{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(an,{icon:s.jsx(er,{}),title:T(S==="offline"?"mobileInbox.networkOffline":S==="auth_failed"?"mobileInbox.sessionExpired":"mobileInbox.reconnecting"),subtitle:T(S==="offline"?"mobileInbox.waitingForNetwork":S==="auth_failed"?"mobileInbox.pleaseLogInAgain":"mobileInbox.restoringConnection")}):P?s.jsx(an,{icon:s.jsx(er,{}),title:T("mobileInbox.loading"),subtitle:T("mobileInbox.loadingSubtitle")}):i.length===0?s.jsx(an,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:T(y?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:T(y?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!y&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(zm,{})})}):s.jsx(An,{children:i.map((K,V)=>s.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${V>0?"border-t border-border-subtle/70":""}`,onClick:()=>x(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(Sd,{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(Xa,{title:T("mobileInbox.needsAttention"),className:"mb-0"}),s.jsx(An,{children:t.map((K,V)=>s.jsx("div",{className:V>0?"border-t border-border-subtle/70":"",children:s.jsx(Za,{item:K,type:"needs_attention",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:h?()=>I(K.conversation):void 0,onRequestStopCli:k?()=>k(K.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:G,isMuted:C==null?void 0:C(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(Xa,{title:T("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),s.jsx(An,{children:n.map((K,V)=>s.jsx("div",{className:V>0?"border-t border-border-subtle/70":"",children:s.jsx(Za,{item:K,type:"task_complete",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:h?()=>I(K.conversation):void 0,onRequestStopCli:k?()=>k(K.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:G,isMuted:C==null?void 0:C(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(Xa,{title:T("mobileInbox.workingNow"),className:"mb-0 mt-2"}),s.jsx(An,{children:a.map((K,V)=>s.jsx("div",{className:V>0?"border-t border-border-subtle/70":"",children:s.jsx(Za,{item:K,type:"working",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:h?()=>I(K.conversation):void 0,onRequestStopCli:k?()=>k(K.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:G,isMuted:C==null?void 0:C(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(Xa,{title:T("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),r.length>0?s.jsx(An,{children:r.map((K,V)=>s.jsx("div",{className:V>0?"border-t border-border-subtle/70":"",children:s.jsx(Za,{item:K,type:"earlier",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:h?()=>I(K.conversation):void 0,onRequestStopCli:k?()=>k(K.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:G,isMuted:C==null?void 0:C(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(an,{icon:s.jsx(er,{size:28}),title:T("mobileInbox.connecting"),subtitle:T("mobileInbox.connectingSubtitle")}):$?s.jsx(an,{icon:s.jsx(er,{size:28}),title:T("mobileInbox.loading"),subtitle:T("mobileInbox.loadingSubtitle")}):L?s.jsx(an,{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(kn,{size:20})}),title:T("mobileInbox.noConversations"),subtitle:T("paneGroup.newSessionDescription"),children:f&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:f,"aria-label":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(an,{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=Sg(o);return s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(An,{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(Sd,{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"&&f&&R&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:f,"aria-label":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"})]})}),D&&s.jsx(K1,{conversation:D,onCancel:()=>I(null),onConfirm:W}),s.jsx(Km,{section:e,onSectionChange:b})]})}function Y1(e){if(!e)return"";try{return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(e))}catch{return new Date(e).toLocaleString()}}function Vm(e){const t=[e.workspace||"Workspace unknown"],n=xn(e.summaryMetadata);n&&t.push(n),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const a=Y1(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:a?`Updated ${a}`:"",preview:(e.preview||"").trim()}}function $l({title:e,description:t,currentPath:n,directories:a,busy:r=!1,error:o="",confirmLabel:i="Use this folder",onClose:c,onNavigate:u,onConfirm:p}){const[d,m]=l.useState(n),{t:h}=Ce("common");l.useEffect(()=>{m(n)},[n]);const g=j1(n),k=d.trim();return s.jsx(Yt,{children:s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:s.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:c,"aria-label":"Close folder browser",children:s.jsx(Pt,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!g||r||u(g)},disabled:!g||r,children:[s.jsx(al,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:h("machine.workspaceBrowse.currentFolder")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:d,onChange:f=>m(f.target.value),onKeyDown:f=>{f.key!=="Enter"||!k||r||(f.preventDefault(),u(k))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!k||r||u(k)},disabled:!k||r,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:r?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):o?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:o}):a.length===0?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):s.jsx("div",{className:"p-3",children:a.map(f=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>u(f.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Bn,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:f.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:f.path})]})]},f.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:c,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>p(k||n),disabled:!k&&!n||r,children:i})]})]})})})}function ro({title:e,description:t,details:n,workspaceOptions:a,selectedWorkspaceKey:r,onWorkspaceChange:o,confirmLabel:i,busyLabel:c,busy:u=!1,showArgsInput:p,argsValue:d,onArgsChange:m,showModelInput:h,modelValue:g,onModelChange:k,historyProviderNode:f,onConfirm:x,onCancel:w}){const{t:b}=Ce("common"),S=i??b("machine.launchConfirm.launch"),N=c??b("machine.launchConfirm.launching"),v=a==null?void 0:a.find(j=>j.key===r),y=s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:w,"aria-label":b("machine.launchConfirm.closeAria"),children:s.jsx(Pt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[a&&a.length>0&&o&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.workspace")}),s.jsx("select",{value:r||"",onChange:j=>o(j.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:u,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})]}),f,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}`)),h&&k&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.languageModel")}),s.jsx("input",{type:"text",value:g||"",onChange:j=>k(j.target.value),placeholder:b("machine.launchConfirm.autoDetect"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]}),p&&m&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.cliArgs")}),s.jsx("input",{type:"text",value:d||"",onChange:j=>m(j.target.value),placeholder:b("machine.launchConfirm.cliArgsPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:w,disabled:u,children:b("machine.launchConfirm.cancel")}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:x,disabled:u,children:[s.jsx(Uu,{size:14}),u?N:S]})]})]})});return typeof document>"u"?y:Fs.createPortal(y,document.body)}function Cd(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function Ym(e){const{machine:t,currentWorkspacePath:n,currentWorkspaceId:a,includeHome:r=!0,homeLabel:o="Home directory",homeDescription:i="Launch without a workspace"}=e,c=[];r&&c.push({key:"__home__",label:o,description:i,workspaceId:null,workspacePath:null});for(const d of t.workspaces||[])c.push({key:`saved:${d.id}`,label:`${d.id===t.defaultWorkspaceId?"⭐ ":""}${Cd(d.path,d.label)}`,description:d.path,workspaceId:d.id,workspacePath:d.path});const u=(n==null?void 0:n.trim())||"",p=u?(t.workspaces||[]).find(d=>d.path===u):null;if(u&&!p&&c.push({key:`custom:${u}`,label:Cd(u),description:u,workspaceId:null,workspacePath:u}),a){const d=`saved:${a}`;if(c.some(m=>m.key===d))return{options:c,selectedKey:d}}return p?{options:c,selectedKey:`saved:${p.id}`}:u?{options:c,selectedKey:`custom:${u}`}:{options:c,selectedKey:"__home__"}}function Q1(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function J1(e){return[Q1(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function X1(e){return e.lastLaunchedAt?Kr(e.lastLaunchedAt):""}function Qm(e){return{metaText:J1(e),updatedLabel:X1(e)}}function Uo(e,t,n){return e?"ide":t>0?"cli":n>0?"acp":null}function Z1({selectedMachineEntry:e,cliProviders:t,acpProviders:n,machineAction:a,onBrowseDirectory:r,onListSavedSessions:o}){var ie,je,De,qe;const i=Qn(),[c,u]=l.useState(!1),p=(((ie=e.detectedIdes)==null?void 0:ie.length)||0)>0,d=l.useMemo(()=>(e.workspaces||[]).map(ye=>({id:ye.id,path:ye.path,label:ye.label})),[e]),m=e.defaultWorkspaceId||null,[h,g]=l.useState(m||((je=d[0])==null?void 0:je.id)||""),[k,f]=l.useState(""),[x,w]=l.useState(""),[b,S]=l.useState([]),[N,v]=l.useState(!1),[y,j]=l.useState(""),[C,A]=l.useState(!1),[T,D]=l.useState(Uo(p,t.length,n.length)),I=l.useRef(null),[M,P]=l.useState(null),$=l.useRef("__home__"),[L,R]=l.useState("__home__"),[F,E]=l.useState(""),[H,_]=l.useState(""),[G,W]=l.useState(""),[K,V]=l.useState([]),[te,le]=l.useState(()=>Ut().textQuery),[de,ee]=l.useState(()=>Ut().workspaceQuery),[z,X]=l.useState(()=>Ut().modelQuery),[U,Q]=l.useState(()=>Ut().resumableOnly),[ke,ve]=l.useState(()=>Ut().sortMode),[ge,me]=l.useState(!1),[B,O]=l.useState(!1),Y=l.useRef(null),se=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const Z=h==="__custom__"?k.trim():((De=d.find(ye=>ye.id===h))==null?void 0:De.path)||"",Ne=h==="__custom__"&&!!Z&&a.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(a.message),pe=h!=="__custom__"&&((qe=d.find(ye=>ye.id===h))==null?void 0:qe.path)||"",fe=l.useMemo(()=>(e.recentLaunches||[]).map(ye=>ye.workspace),[e]),Me=l.useCallback(async ye=>{v(!0),j("");try{const Fe=await r(ye);w(Fe.path),f(Fe.path),S(Fe.directories)}catch(Fe){j(Fe instanceof Error?Fe.message:"Could not load folder")}finally{v(!1)}},[r]),Ee=l.useCallback(()=>{var Fe;g("__custom__"),A(!0);const ye=El(e.platform,Rl(k.trim(),pe,fe,e.defaultWorkspacePath,(Fe=d.find(ut=>ut.id===m))==null?void 0:Fe.path,d.map(ut=>ut.path)));Me(ye)},[k,m,Me,fe,pe,e.platform,d]),q=l.useCallback(ye=>{if(ye!=null&&ye.workspaceId){g(ye.workspaceId),f("");return}if(ye!=null&&ye.workspacePath){g("__custom__"),f(ye.workspacePath);return}g(""),f("")},[]),oe=l.useCallback(ye=>{if(g(ye),ye==="__custom__"){Ee();return}f("")},[Ee]),Ie=l.useCallback(ye=>{g("__custom__"),f(ye)},[]),xe=l.useCallback((ye,Fe)=>{I.current=Fe,$.current=ye.selectedWorkspaceKey||"__home__",R(ye.selectedWorkspaceKey||"__home__"),E(ye.initialArgs||""),_(ye.initialModel||""),W(""),V([]);const ut=ye.providerType?`${e.id}:${ye.providerType}`:null;if(sC(se.current,ut)){const it=Ut();le(it.textQuery),ee(it.workspaceQuery),X(it.modelQuery),Q(it.resumableOnly),ve(it.sortMode)}se.current=ut,P(ye),ye.providerType&&o&&(me(!0),o(ye.providerType).then(it=>V(it||[])).catch(it=>console.warn("Failed to load saved sessions",it)).finally(()=>me(!1)))},[o,e.id]),he=l.useMemo(()=>lm(K,{textQuery:te,workspaceQuery:de,modelQuery:z,resumableOnly:U,sortMode:ke}),[z,U,K,ke,te,de]);l.useEffect(()=>{G&&(he.some(ye=>ye.providerSessionId===G)||W(""))},[he,G]);const Ze=l.useCallback(()=>{I.current&&(O(!0),I.current().finally(()=>{I.current=null,O(!1),P(null)}))},[]),Ae=l.useCallback(()=>{I.current=null,P(null)},[]),_e=l.useCallback(ye=>{$.current=ye,R(ye)},[]);return l.useEffect(()=>{var ye;Y.current!==e.id&&(Y.current=e.id,g(m||((ye=d[0])==null?void 0:ye.id)||"__custom__"),f(""),w(""),S([]),j(""),A(!1),le(Ut().textQuery),ee(Ut().workspaceQuery),X(Ut().modelQuery),Q(Ut().resumableOnly),ve(Ut().sortMode),se.current=null,D(Uo(p,t.length,n.length)))},[n.length,t.length,m,p,e.id,d]),l.useEffect(()=>{var ye;h!=="__custom__"&&(h&&d.some(Fe=>Fe.id===h)||g(m||((ye=d[0])==null?void 0:ye.id)||"__custom__"))},[m,h,d]),l.useEffect(()=>{T==="ide"&&p||T==="cli"&&t.length>0||T==="acp"&&n.length>0||D(Uo(p,t.length,n.length))},[T,n.length,t.length,p]),{showAllRecent:c,setShowAllRecent:u,hasIdeOptions:p,workspaceRows:d,defaultWorkspaceId:m,workspaceChoice:h,customWorkspacePath:k,browseCurrentPath:x,browseDirectories:b,browseBusy:N,browseError:y,browseDialogOpen:C,activeLauncherKind:T,launchConfirm:M,launchConfirmWorkspaceKeyRef:$,launchConfirmWorkspaceKey:L,launchConfirmArgs:F,launchConfirmModel:H,launchConfirmResumeId:G,launchConfirmSavedSessions:K,launchConfirmTextFilter:te,launchConfirmWorkspaceFilter:de,launchConfirmModelFilter:z,launchConfirmResumableOnly:U,launchConfirmSortMode:ke,filteredLaunchConfirmSavedSessions:he,launchConfirmSessionsLoading:ge,launchConfirmBusy:B,resolvedWorkspacePath:Z,canCreateMissingWorkspace:Ne,openBrowseDialog:Ee,loadBrowsePath:Me,handleWorkspaceChoiceChange:oe,chooseCustomWorkspacePath:Ie,setCustomWorkspacePath:f,setBrowseDialogOpen:A,setActiveLauncherKind:D,openLaunchConfirm:xe,handleConfirmLaunch:Ze,closeLaunchConfirm:Ae,setWorkspaceSelectionFromOption:q,setLaunchConfirmWorkspaceKeyAndSync:_e,setLaunchConfirmArgs:E,setLaunchConfirmModel:_,setLaunchConfirmResumeId:W,setLaunchConfirmTextFilter:le,setLaunchConfirmWorkspaceFilter:ee,setLaunchConfirmModelFilter:X,setLaunchConfirmResumableOnly:Q,setLaunchConfirmSortMode:ve}}function eN({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:n,cliProviders:a,acpProviders:r,selectedMachineNeedsUpgrade:o,appVersion:i,machineAction:c,isStandalone:u,section:p,showBottomNav:d,onBack:m,onSectionChange:h,onOpenConversation:g,onOpenRecent:k,onOpenMachineDetails:f,onMachineUpgrade:x,onLaunchDetectedIde:w,onAddWorkspace:b,onBrowseDirectory:S,onLaunchWorkspaceProvider:N,onListSavedSessions:v}){const{t:y}=Ce("common"),j=R=>R==="ide"?"IDE":R==="cli"?"CLI":"ACP",C=n.slice(0,4),A=t.slice(0,3),T=Z1({selectedMachineEntry:e,cliProviders:a,acpProviders:r,machineAction:c,onBrowseDirectory:S,onListSavedSessions:v}),D=l.useMemo(()=>C.map(R=>{const{metaText:F,updatedLabel:E}=Qm(R);return{key:`recent-launch:${R.id}`,primary:R.label,secondary:F,updatedLabel:E,onClick:()=>{const{options:H,selectedKey:_}=Ym({machine:{workspaces:T.workspaceRows,defaultWorkspaceId:T.defaultWorkspaceId},currentWorkspacePath:R.workspace,homeLabel:y("newSession.homeDirectory"),homeDescription:y("newSession.launchWithoutWorkspace")});T.openLaunchConfirm({title:R.kind==="ide"?Ir(y,"restart-ide",R.label):R.providerSessionId?dm(y,R.label):Ir(y,"start-fresh",R.label),description:R.kind==="ide"?Lr(y,"restart-ide"):R.providerSessionId?um(y):Lr(y,"start-fresh"),confirmLabel:R.kind==="ide"?Rr(y,"restart-ide"):R.providerSessionId?Fi(y,!0):Rr(y,"start-fresh"),busyLabel:R.kind==="ide"?Er(y,"restart-ide"):R.providerSessionId?cm(y,!0):Er(y,"start-fresh"),workspaceOptions:H,selectedWorkspaceKey:_,details:[{label:"Mode",value:j(R.kind)},...R.providerType?[{label:"Provider",value:R.providerType}]:[]]},async()=>{const G=H.find(W=>W.key===T.launchConfirmWorkspaceKeyRef.current);T.setWorkspaceSelectionFromOption(G),await k({...R,workspace:(G==null?void 0:G.workspacePath)??null})})}}}),[T,k,C,y]),I=l.useMemo(()=>A.map(R=>({key:`recent-chat:${R.conversation.tabKey}`,primary:wt(R.conversation),secondary:MS(R.conversation,{timestampLabel:R.timestamp?sp(R.timestamp):null}),unread:R.unread,onClick:()=>g(R.conversation)})),[g,A]),M=T.showAllRecent?D:D.slice(0,4),P=D.length>0,$=I.length>0,L=u?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${L} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:m,type:"button","aria-label":"Back",children:s.jsx(al,{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:rs(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:[$&&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:I.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))})]}),P&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"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))}),D.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 ${D.length-4} more`})})]}),!1,s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[o&&s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:x,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",i]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:f,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),T.browseDialogOpen&&s.jsx($l,{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(ro,{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?Fi(y,!!T.launchConfirmResumeId):T.launchConfirm.confirmLabel,busyLabel:T.launchConfirm.providerType?void 0:T.launchConfirm.busyLabel,busy:T.launchConfirmBusy,showArgsInput:T.launchConfirm.showArgsInput,argsValue:T.launchConfirmArgs,onArgsChange:T.setLaunchConfirmArgs,showModelInput:T.launchConfirm.showModelInput,modelValue:T.launchConfirmModel,onModelChange:T.setLaunchConfirmModel,historyProviderNode:T.launchConfirm.providerType&&(T.launchConfirmSessionsLoading||T.launchConfirmSavedSessions.length>0)&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),T.launchConfirmSessionsLoading&&s.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:Al(y)}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:T.launchConfirmTextFilter,onChange:R=>T.setLaunchConfirmTextFilter(R.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:T.launchConfirmWorkspaceFilter,onChange:R=>T.setLaunchConfirmWorkspaceFilter(R.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:T.launchConfirmModelFilter,onChange:R=>T.setLaunchConfirmModelFilter(R.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsxs("select",{value:T.launchConfirmSortMode,onChange:R=>T.setLaunchConfirmSortMode(R.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:T.launchConfirmResumableOnly,onChange:R=>T.setLaunchConfirmResumableOnly(R.target.checked),disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:T.launchConfirmResumeId,onChange:R=>T.setLaunchConfirmResumeId(R.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:rC(y)}),T.filteredLaunchConfirmSavedSessions.map(R=>s.jsxs("option",{value:R.providerSessionId,disabled:!R.canResume,children:[R.title||R.providerSessionId," ",R.canResume?"":"(workspace missing)"]},R.providerSessionId))]}),!T.launchConfirmSessionsLoading&&T.launchConfirmSavedSessions.length>0&&T.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),T.launchConfirmResumeId&&(()=>{const R=T.filteredLaunchConfirmSavedSessions.find(E=>E.providerSessionId===T.launchConfirmResumeId);if(!R)return null;const F=Vm(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:F.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:F.providerSessionId}),s.jsx("div",{className:"mt-1",children:F.metaLine}),F.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:F.updatedLabel}),F.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:F.preview})]})})()]}),onConfirm:T.handleConfirmLaunch,onCancel:T.closeLaunchConfirm}),d&&s.jsx(Km,{section:p,onSectionChange:h})]})}const jd=8e3;function tN(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 Jm(e,t,n){const a=l.useRef(new Map),[,r]=l.useState(0),o=l.useCallback(()=>r(g=>g+1),[]);l.useEffect(()=>{const g=a.current;if(g.size===0)return;const k=Date.now();let f=!1;for(const[x,w]of g){const b=e.get(x),S=w.muted===void 0||(b?b.muted===w.muted:!1),N=w.hidden===void 0||(b?b.surfaceHidden===w.hidden:!1),v=k-w.at>jd;(S&&N||v)&&(g.delete(x),f=!0)}f&&o()},[e,o]),l.useEffect(()=>{if(a.current.size===0)return;const g=setInterval(()=>{const k=a.current,f=Date.now();let x=!1;for(const[w,b]of k)f-b.at>jd&&(k.delete(w),x=!0);x&&o(),k.size===0&&clearInterval(g)},1e3);return()=>clearInterval(g)});const i=l.useCallback((g,k)=>{const f=a.current.get(g);a.current.set(g,{...f,...k,at:Date.now()}),o()},[o]),c=l.useCallback(g=>{const k=g.sessionId,f=k?a.current.get(k):void 0;return(f==null?void 0:f.muted)!==void 0?f.muted:Js(g,e).muted??!1},[e]),u=l.useCallback(g=>{const k=g.sessionId,f=k?a.current.get(k):void 0;return(f==null?void 0:f.hidden)!==void 0?f.hidden:Js(g,e).surfaceHidden??!1},[e]),p=l.useCallback((g,k)=>{const f=Bs(g),x=g.sessionId;!f||!x||(i(x,k),t(f,"set_conversation_prefs",{sessionId:x,...k,...Zr(g)}).then(w=>{const b=tN(w);b.confirmed||(console.warn("[conversation-prefs] set_conversation_prefs not confirmed",b.reason),a.current.delete(x),o(),n==null||n(`Couldn't update conversation — ${b.reason}`))}).catch(w=>{console.warn("[conversation-prefs] set_conversation_prefs failed",w),a.current.delete(x),o();const b=w instanceof Error?w.message:String(w??"the daemon is unreachable");n==null||n(`Couldn't update conversation — ${b}`)}))},[t,i,o,n]),d=l.useCallback(g=>{p(g,{muted:!c(g)})},[p,c]),m=l.useCallback((g,k)=>{p(g,{hidden:k})},[p]),h=l.useCallback(g=>{p(g,{hidden:!u(g)})},[p,u]);return{isMuted:c,isHidden:u,toggleMute:d,setHidden:m,toggleHidden:h}}function gr(e){return[...e].sort((t,n)=>{const a=n.timestamp-t.timestamp;return a!==0?a:t.conversation.tabKey.localeCompare(n.conversation.tabKey)})}function sN(e,t=[]){const n=new Map(e.map(r=>[r.conversation.tabKey,r])),a=t.map(r=>n.get(r)).filter(r=>!!r);return a.length===e.length?a:gr(e)}function nN(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:gr(n),unreadItems:gr(a),workingItems:sN(r,t),completedItems:gr(o)}}function oo(e,t){if(!t)return!1;const n=e.filter(a=>a.type==="adhdev-daemon"&&Xm(a)==="Connected");return n.length===0?!0:n.every(a=>a._sessionListAuthoritative===!0)}function Xm(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 aN(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:xn(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=Ma(a)?"cli":_n(a)?"acp":"ide",o=xn(a.summaryMetadata);return{id:`${r}:${a.type}:${a.workspace||""}`,label:((i=a.activeChat)==null?void 0:i.title)||(Ma(a)?a.cliName||a.type:_n(a)&&a.cliName||a.type),kind:r,providerType:a.type,providerSessionId:a.providerSessionId,subtitle:_n(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 rN(e,t,n=[]){const a=new Map;for(const o of t){const i=Bs(o.conversation),c=a.get(i);c?c.push(o):a.set(i,[o])}const r=new Map;for(const o of n){const i=Bs(o),c=r.get(i);c?c.push(o):r.set(i,[o])}return e.map(o=>{const i=a.get(o.id)||[],c=r.get(o.id)||[],u=[...i].sort((f,x)=>x.timestamp-f.timestamp)[0]||null,p=(u==null?void 0:u.conversation)||null,d=Ii(o),m=i.filter(f=>f.unread||f.requiresAction).length,h=i.filter(f=>Aa(f.conversation)).length+c.filter(Aa).length,g=Xm(o),k=[o.platform||"machine",g].filter(Boolean);return{id:o.id,label:rs(o,{fallbackId:o.id}),subtitle:k.join(" · "),unread:m,total:i.length,generatingCount:h,latestConversation:p,latestTimestamp:(u==null?void 0:u.timestamp)||0,fallbackActivityAt:d,preview:p?DS(p,Yp(p)):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((o,i)=>{const c=o.latestTimestamp||o.fallbackActivityAt||0,u=i.latestTimestamp||i.fallbackActivityAt||0;return u!==c?u-c:o.label.localeCompare(i.label)})}function oN(e){return e==="chat"}function tr(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 iN({conversations:e,machineEntries:t,items:n,selectedConversation:a,selectedTabKey:r,screen:o,liveSessionInboxState:i,sendDaemonCommand:c,requestedActiveTabKey:u,onRequestedActiveTabConsumed:p,requestedMachineId:d,onRequestedMachineConsumed:m,requestedMobileSection:h,onRequestedMobileSectionConsumed:g,setSelectedTabKey:k,setScreen:f,setSelectedMachineId:x,setSection:w,setMachineBackTarget:b,resetMachineAction:S}){const N=l.useRef(null),v=l.useCallback(y=>{if(!(y!=null&&y.sessionId))return;const j=Js(y,i),C=Math.max(Date.now(),fn(y),j.lastUpdated||0);tr("mark_read:start",{tabKey:y.tabKey,sessionId:y.sessionId,displayPrimary:wt(y),inboxBucket:j.inboxBucket,unread:j.unread,lastSeenAt:j.lastSeenAt,lastUpdated:j.lastUpdated,activityAt:fn(y),readAt:C}),c(Bs(y)||y.routeId,"mark_session_seen",{sessionId:y.sessionId,providerSessionId:y.providerSessionId,seenAt:C,completionMarker:j.completionMarker}).then(A=>{tr("mark_read:result",{tabKey:y.tabKey,sessionId:y.sessionId,result:A})}).catch(A=>{tr("mark_read:error",{tabKey:y.tabKey,sessionId:y.sessionId,error:A instanceof Error?A.message:String(A)})})},[i,c]);return l.useEffect(()=>{var j;if(!a){oN(o)&&f("inbox"),k(((j=e[0])==null?void 0:j.tabKey)||null),N.current=null;return}if(o!=="chat"){N.current=null;return}const y=`${a.tabKey}:${a.sessionId||""}`;N.current!==y&&(N.current=y,v(a))},[e,v,o,a,f,k]),l.useEffect(()=>{if(!u)return;const y=e.find(j=>j.tabKey===u);y&&(k(y.tabKey),f("chat"),p==null||p())},[e,p,u,f,k]),l.useEffect(()=>{if(!d)return;const y=t.find(j=>j.id===d);y&&(x(y.id),S(),w("machines"),b("inbox"),f("machine"),m==null||m())},[t,m,d,S,b,f,w,x]),l.useEffect(()=>{h&&(w(h),f("inbox"),g==null||g())},[g,h,f,w]),l.useEffect(()=>{const y=n.filter(j=>j.inboxBucket==="task_complete"||j.unread);y.length!==0&&tr("inbox_state",{screen:o,selectedTabKey:r,items:y.map(j=>{const C=Js(j.conversation,i);return{liveState:C,tabKey:j.conversation.tabKey,sessionId:j.conversation.sessionId,displayPrimary:wt(j.conversation),serverBucket:C.inboxBucket,computedBucket:j.inboxBucket,serverUnread:C.unread,computedUnread:j.unread,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,activityAt:fn(j.conversation)}})})},[n,i,o,r]),{markConversationRead:v}}function lN(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Nd(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function cN(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function dN({sendDaemonCommand:e,navigate:t,ides:n,conversations:a}){const{launchCli:r}=qr(),[o,i]=l.useState("idle"),[c,u]=l.useState(""),[p,d]=l.useState(null),m=l.useCallback(()=>{i("idle"),u(""),d(null)},[]),h=l.useCallback(async(S,N,v)=>{var y;try{i("loading"),u(`Launching ${N}…`);const j={ideType:N,enableCdp:!0};(y=v==null?void 0:v.workspacePath)!=null&&y.trim()&&(j.workspace=v.workspacePath.trim()),await e(S,"launch_ide",j),i("done"),u(`${N} launch requested`)}catch(j){i("error"),u(j instanceof Error?j.message:"Launch IDE failed"),console.error("Launch IDE failed",j)}},[e]),g=l.useCallback(async(S,N,v)=>{if(N.trim())try{i("loading"),u(v!=null&&v.createIfMissing?"Creating folder…":"Saving workspace…");const y=await e(S,"workspace_add",{path:N.trim(),createIfMissing:(v==null?void 0:v.createIfMissing)===!0});if(y!=null&&y.success){i("done"),u(v!=null&&v.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),u((y==null?void 0:y.error)||"Could not save workspace")}catch(y){i("error"),u(y instanceof Error?y.message:"Could not save workspace")}},[e]),k=l.useCallback(async S=>{i("loading"),u("Starting daemon upgrade…");const N=n.find(y=>y.id===S||y.daemonId===S),v=await XC(e,S,N);i(v.state),u(v.message)},[n,e]),f=l.useCallback(async(S,N,v,y)=>{var A,T,D;const j=Date.now(),C={machineId:S,kind:N,providerType:v,workspaceId:(y==null?void 0:y.workspaceId)||null,workspacePath:(y==null?void 0:y.workspacePath)||null,resumeSessionId:(y==null?void 0:y.resumeSessionId)||null,startedAt:j};try{i("loading"),u(`Launching ${v}…`),d(C);const I={cliType:v};(A=y==null?void 0:y.workspacePath)!=null&&A.trim()?I.dir=y.workspacePath.trim():y!=null&&y.workspaceId?I.workspaceId=y.workspaceId:y!=null&&y.useHome&&(I.useHome=!0),y!=null&&y.resumeSessionId&&(I.resumeSessionId=y.resumeSessionId),(T=y==null?void 0:y.args)!=null&&T.trim()&&(I.cliArgs=y.args.trim().split(/\s+/).filter(Boolean)),(D=y==null?void 0:y.model)!=null&&D.trim()&&(I.initialModel=y.model.trim());const M=await r(S,I),P=(M==null?void 0:M.result)||M,$=(P==null?void 0:P.sessionId)||(P==null?void 0:P.id);if(M!=null&&M.success&&$){d(null),i("done"),u(`${v} launched`),t(Ia($));return}if(M!=null&&M.success){i("loading"),u(`${v} launch requested — waiting for session…`);return}d(null),i("error"),u((M==null?void 0:M.error)||(P==null?void 0:P.error)||`Could not launch ${N.toUpperCase()} workspace`)}catch(I){if(cN(I)){i("loading"),u(`${v} launch requested — waiting for session…`);return}d(null),i("error"),u(I instanceof Error?I.message:`Could not launch ${N.toUpperCase()} workspace`)}},[t,e]),x=l.useCallback(async(S,N)=>{try{const v=await e(S,"list_saved_sessions",{providerType:N,kind:"cli",limit:30}),y=(v==null?void 0:v.result)??v;return Array.isArray(y==null?void 0:y.sessions)?y.sessions:[]}catch(v){return console.error("Failed to list saved sessions on mobile:",v),[]}},[e]),w=l.useCallback(async(S,N)=>_l(e,S,N),[e]);l.useEffect(()=>{if(!p)return;const S=Nd(p.workspacePath),N=n.find(y=>{var I,M,P,$;if(!y||y.type==="adhdev-daemon"||lN(y.daemonId||y.id)!==p.machineId||(y.transport==="acp"?"acp":y.transport==="pty"?"cli":null)!==p.kind||String(y.agentType||y.type||"")!==p.providerType)return!1;const T=String(y.providerSessionId||"");if(p.resumeSessionId&&T)return T===p.resumeSessionId;if(S){const L=Nd(y.workspace||y.runtimeWorkspaceLabel);return L?L===S:!1}return Number(y.lastUpdated||y._lastUpdate||y.timestamp||(($=(P=(M=(I=y.activeChat)==null?void 0:I.messages)==null?void 0:M.at)==null?void 0:P.call(M,-1))==null?void 0:$.timestamp)||0)>=p.startedAt-5e3});if(!N)return;const v=qm({entrySessionId:N.sessionId,entryInstanceId:N.instanceId,entryRouteId:N.id,conversations:a});v&&(d(null),i("done"),u(`${p.providerType} launched`),t(Ia(v)))},[a,n,t,p]),l.useEffect(()=>{if(!p)return;const S=window.setTimeout(()=>{d(N=>!N||N.startedAt!==p.startedAt?N:(i("error"),u("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(S)},[p]);const b=l.useCallback(async(S,N)=>{var v;if(N.kind==="ide"&&N.providerType){await h(S,N.providerType,{workspacePath:N.workspace||null});return}if((N.kind==="cli"||N.kind==="acp")&&N.providerType){const y=((v=N.workspace)==null?void 0:v.trim())||"";await f(S,N.kind,N.providerType,{workspacePath:y||null,useHome:!y,resumeSessionId:N.providerSessionId||null})}},[h,f]);return{machineAction:{state:o,message:c},resetMachineAction:m,handleLaunchDetectedIde:h,handleAddWorkspace:g,handleMachineUpgrade:k,handleLaunchWorkspaceProvider:f,handleListSavedSessions:x,handleBrowseDirectory:w,handleOpenRecent:b}}function uN({conversations:e,selectedConversation:t,machineBackTarget:n,markConversationRead:a,resetMachineAction:r,setSelectedTabKey:o,setScreen:i,setSelectedMachineId:c,setSection:u,setMachineBackTarget:p}){const d=l.useCallback(w=>{o(w.tabKey),i("chat"),a(w)},[a,i,o]),m=l.useCallback(w=>{const b=e.find(S=>S.routeId===w.routeId&&S.streamSource==="native");b&&(o(b.tabKey),i("chat"),a(b))},[e,a,i,o]),h=l.useCallback(()=>{a(t),i("inbox")},[a,t,i]),g=l.useCallback((w,b="inbox")=>{c(w),r(),u("machines"),p(b),i("machine")},[r,p,i,u,c]),k=l.useCallback(w=>{const b=Bs(w);b&&g(b,"chat")},[g]),f=l.useCallback(()=>{r(),i(n)},[n,r,i]),x=l.useCallback(w=>{u(w),i("inbox")},[i,u]);return{openConversation:d,openNativeConversation:m,backFromConversation:h,openMachine:g,openConversationMachine:k,backFromMachine:f,changeMachineSection:x}}function Gn(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function pN(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function mN({conversations:e,hiddenConversations:t,ides:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,userName:c,requestedActiveTabKey:u,onRequestedActiveTabConsumed:p,requestedMachineId:d,onRequestedMachineConsumed:m,requestedMobileSection:h,onRequestedMobileSectionConsumed:g,onOpenHistory:k,onOpenRemote:f,onStopCli:x,wsStatus:w,isConnected:b,initialDataLoaded:S=!0,onShowAllHiddenConversations:N,onHideConversation:v,onOpenMeshGraph:y,onOpenNewSession:j,liveSessionInboxState:C,setCliViewModeOverrides:A}){const[T,D]=l.useState(()=>{var oe;return((oe=e[0])==null?void 0:oe.tabKey)||null}),[I,M]=l.useState(()=>e[0]?"chat":"inbox"),[P,$]=l.useState("chats"),[L,R]=l.useState(null),[F,E]=l.useState("inbox"),H=l.useRef([]),_=Ea(),G="1.0.42",W=l.useMemo(()=>e.find(oe=>oe.tabKey===T)||e[0]||null,[e,T]),K=l.useMemo(()=>W?n.find(oe=>oe.id===W.routeId):void 0,[n,W]),V=l.useMemo(()=>!W||pt(W)||!ft(W)?null:Yn(W),[W]),te=l.useMemo(()=>n.filter(oe=>oe.type==="adhdev-daemon").sort(hl),[n]),le=l.useMemo(()=>te.find(oe=>oe.id===L)||null,[te,L]),de=eo({sendDaemonCommand:r,activeConv:W||void 0,setActionLogs:o,isStandalone:i}),ee=dN({sendDaemonCommand:r,navigate:_,ides:n,conversations:e}),z=rS(e),X=l.useMemo(()=>e.map(oe=>{const Ie=I==="chat"&&(W==null?void 0:W.tabKey)===oe.tabKey,xe=Vr(oe,C,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Ie}),he=fn(oe),Ze=Yp(oe),Ae=sm(oe,Ze);return{conversation:oe,timestamp:he,preview:Ae,unread:xe.unread,requiresAction:xe.requiresAction,isWorking:xe.isWorking,inboxBucket:xe.inboxBucket}}),[e,C,I,W,z]),{markConversationRead:U}=iN({conversations:e,machineEntries:te,items:X,selectedConversation:W,selectedTabKey:T,screen:I,liveSessionInboxState:C,sendDaemonCommand:r,requestedActiveTabKey:u,onRequestedActiveTabConsumed:p,requestedMachineId:d,onRequestedMachineConsumed:m,requestedMobileSection:h,onRequestedMobileSectionConsumed:g,setSelectedTabKey:D,setScreen:M,setSelectedMachineId:R,setSection:$,setMachineBackTarget:E,resetMachineAction:ee.resetMachineAction}),Q=uN({conversations:e,selectedConversation:W,machineBackTarget:F,markConversationRead:U,resetMachineAction:ee.resetMachineAction,setSelectedTabKey:D,setScreen:M,setSelectedMachineId:R,setSection:$,setMachineBackTarget:E}),{isMuted:ke,toggleMute:ve}=Jm(C,r),{attentionItems:ge,unreadItems:me,workingItems:B,completedItems:O}=l.useMemo(()=>nN(X,H.current),[X]);l.useEffect(()=>{H.current=B.map(oe=>oe.conversation.tabKey)},[B]);const Y=l.useMemo(()=>le?X.filter(oe=>Bs(oe.conversation)===le.id):[],[X,le]),se=l.useMemo(()=>aN(le,n),[n,le]),Z=!!le&&no(le,qs(le,G)),Ne=l.useMemo(()=>(le==null?void 0:le.availableProviders)||[],[le]),pe=l.useMemo(()=>Ne.filter(oe=>Gn(oe,"cli")).map(oe=>({type:oe.type,displayName:oe.displayName||oe.type,icon:oe.icon})),[Ne]),fe=l.useMemo(()=>Ne.filter(oe=>Gn(oe,"acp")).map(oe=>({type:oe.type,displayName:oe.displayName||oe.type,icon:oe.icon})),[Ne]),Me=l.useMemo(()=>rN(te,X,t),[X,te,t]),Ee=l.useMemo(()=>oo(n,S),[n,S]),q=l.useCallback(async oe=>{le&&await ee.handleOpenRecent(le.id,oe)},[ee,le]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:I==="chat"&&W?s.jsx(G1,{selectedConversation:W,isAcp:pt(W),isStandalone:i,selectedIdeEntry:K,actionLogs:a,userName:c,isSendingChat:de.isSendingChat,sendFeedbackMessage:de.sendFeedbackMessage,isFocusingAgent:de.isFocusingAgent,handleModalButton:de.handleModalButton,handleRelaunch:de.handleRelaunch,onBack:Q.backFromConversation,onOpenNativeConversation:Q.openNativeConversation,onOpenMachine:Q.openConversationMachine,onOpenHistory:k,onOpenRemote:f,onOpenMeshGraph:y,onStopCli:x,cliViewMode:V,onSetCliViewMode:async oe=>{await Rm({conversation:W,mode:oe,ides:n,sendDaemonCommand:r,setCliViewModeOverrides:A})},handleSendChat:de.handleSendChat,handleForceSendChat:de.handleForceSendChat,handleFocusAgent:de.handleFocusAgent}):I==="machine"&&le?s.jsx(eN,{selectedMachineEntry:le,selectedMachineConversations:Y,selectedMachineRecentLaunches:se,cliProviders:pe,acpProviders:fe,selectedMachineNeedsUpgrade:Z,appVersion:G,machineAction:ee.machineAction,isStandalone:i,section:P,showBottomNav:F==="inbox",onBack:Q.backFromMachine,onSectionChange:Q.changeMachineSection,onOpenConversation:Q.openConversation,onOpenRecent:q,onOpenMachineDetails:()=>_(`/machines/${le.id}`),onMachineUpgrade:()=>ee.handleMachineUpgrade(le.id),onLaunchDetectedIde:(oe,Ie)=>ee.handleLaunchDetectedIde(le.id,oe,Ie),onAddWorkspace:(oe,Ie)=>ee.handleAddWorkspace(le.id,oe,Ie),onBrowseDirectory:oe=>ee.handleBrowseDirectory(le.id,oe),onLaunchWorkspaceProvider:(oe,Ie,xe)=>ee.handleLaunchWorkspaceProvider(le.id,oe,Ie,xe),onListSavedSessions:oe=>ee.handleListSavedSessions(le.id,oe)}):s.jsx(V1,{section:P,attentionItems:ge,unreadItems:me,workingItems:B,completedItems:O,hiddenConversations:t,machineCards:Me,getAvatarText:pN,actionLogs:a,sendDaemonCommand:r,onOpenConversation:Q.openConversation,onShowAllHidden:N,onHideConversation:v,onOpenMeshGraph:y,onStopCli:x,onOpenNewSession:j,onOpenMachine:Q.openMachine,onOpenSettings:()=>_("/settings"),onSectionChange:$,wsStatus:w,isConnected:b,initialDataLoaded:S,conversationsLoaded:Ee,isStandalone:i,isConversationMuted:ke,onToggleMuteConversation:ve})})}function qo(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function hN({conversations:e,numGroups:t,onMoveTab:n,onReceiveTab:a,onOwnTabDrop:r,onClearPreviewOrder:o}){const i=l.useRef(0),[c,u]=l.useState(!1),[p,d]=l.useState(null),m=l.useCallback(()=>{i.current=0,u(!1),d(null)},[]);l.useEffect(()=>(window.addEventListener("dragend",m),window.addEventListener("drop",m),()=>{window.removeEventListener("dragend",m),window.removeEventListener("drop",m)}),[m]);const h=l.useCallback(x=>{x.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,u(!0))},[]),g=l.useCallback(x=>{if(!x.dataTransfer.types.includes("text/tab-key"))return;if(x.preventDefault(),!qo(t,n)){d("merge");return}const w=x.currentTarget.getBoundingClientRect(),b=x.clientX-w.left,S=w.width/3;b<S?d("split-left"):b>S*2?d("split-right"):d("merge")},[t,n]),k=l.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,u(!1),d(null))},[]),f=l.useCallback(x=>{i.current=0,u(!1);const w=x.dataTransfer.getData("text/tab-key"),b=w?e.some(N=>N.tabKey===w):!1,S=p;if(d(null),o(),!!w){if(x.preventDefault(),S==="split-left"&&qo(t,n)){n==null||n(w,"split-left");return}if(S==="split-right"&&qo(t,n)){n==null||n(w,"split-right");return}if(b){r(w);return}a==null||a(w)}},[e,p,t,n,a,r,o]);return{dragOver:c,dropAction:p,resetDragState:m,handleDragEnter:h,handleDragOver:g,handleDragLeave:k,handleDrop:f}}function fN(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 bN({conversations:e,initialActiveTabId:t,initialTabOrder:n,onActiveTabChange:a,onTabOrderChange:r}){const[o,i]=l.useState(t??null),[c,u]=l.useState(n??[]),[p,d]=l.useState(null),m=l.useRef(null),h=l.useRef(null),g=l.useRef(a),k=l.useRef(r);l.useEffect(()=>{g.current=a},[a]),l.useEffect(()=>{k.current=r},[r]),l.useEffect(()=>{t&&t!==o&&i(t)},[t,o]),l.useEffect(()=>{u(j=>{const C=fN(j,e);return C.length===j.length&&C.every((A,T)=>A===j[T])?j:C})},[e]);const f=l.useMemo(()=>{const j=p??c;if(j.length===0)return e;const C=new Map(j.map((A,T)=>[A,T]));return[...e].sort((A,T)=>{const D=C.get(A.tabKey)??999,I=C.get(T.tabKey)??999;return D-I})},[e,p,c]);l.useEffect(()=>{var C,A;if(f.length===0){o!==null&&(i(null),(C=g.current)==null||C.call(g,null));return}if(o&&f.some(T=>T.tabKey===o))return;const j=f[0].tabKey;j!==o&&(i(j),(A=g.current)==null||A.call(g,j))},[f,o]);const x=l.useMemo(()=>f.find(j=>j.tabKey===o),[f,o]),w=l.useCallback(j=>{var C;i(j),(C=g.current)==null||C.call(g,j)},[]),b=l.useCallback((j,C,A)=>{u(T=>{var P;const D=T.filter($=>$!==j),I=D.indexOf(C);if(I<0)return T;const M=A==="left"?I:I+1;return D.splice(M,0,j),(P=k.current)==null||P.call(k,D),D}),d(null)},[]),S=l.useCallback((j,C,A)=>{const D=(c.length>0?c:e.map(P=>P.tabKey)).filter(P=>P!==j),I=D.indexOf(C);if(I<0)return;const M=A==="left"?I:I+1;D.splice(M,0,j),m.current=D,d(D)},[c,e]),N=l.useCallback(()=>{var C;const j=m.current;j&&(u(j),(C=k.current)==null||C.call(k,j))},[]),v=l.useCallback(()=>{m.current=null,d(null)},[]),y=l.useCallback(j=>{u(C=>{var T;const A=C.filter(D=>D!==j);return A.push(j),(T=k.current)==null||T.call(k,A),A})},[]);return{activeTabId:o,activeConv:x,sortedConversations:f,previewOrderRef:m,draggingTabRef:h,selectTab:w,handleTabReorder:b,updatePreviewOrder:S,commitPreviewOrder:N,clearPreviewOrder:v,moveTabToEnd:y,setDraggingTabKey:j=>{h.current=j}}}function gN({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 Fl({conversationsCount:e,isSplitMode:t,isStandalone:n,hasRegisteredMachines:a=!1,suppressGuide:r=!1,onOpenNewSession:o,isLoading:i=!1}){const{t:c}=Ce("common");if(r)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});if(i)return s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center gap-3 -mt-8 text-text-muted",children:[s.jsx("div",{className:"w-7 h-7 rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light","aria-hidden":"true"}),s.jsx("p",{className:"text-sm",children:c("paneGroup.loadingSessions")})]});const u=!n&&!a,p=a&&!!o,d=c(a?"paneGroup.noConversations":n?"paneGroup.waitingForDaemon":"paneGroup.connectYourMachines"),m=c(a?"paneGroup.newSessionDescription":n?"paneGroup.daemonDescription":"paneGroup.installDescription");return e===0&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:d}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:m}),p&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:o,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:c("paneGroup.newSession"),"aria-label":c("paneGroup.newSession"),children:[s.jsx(cl,{size:14}),s.jsx("span",{children:c("paneGroup.newSession")})]})}),u&&s.jsx(zm,{}),u&&s.jsx("div",{className:"mt-8",children:s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:"📚 Read the documentation →"})})]})]}):s.jsx("div",{className:"text-sm text-text-muted opacity-50",children:t?"Move a tab here to view":"No active agent"})}const Zm="adhdev-tab-shortcuts";function eh(){try{return JSON.parse(localStorage.getItem(Zm)||"{}")}catch{return{}}}function th({enabled:e=!0,sortedTabKeys:t,onFocus:n,onSelectTab:a}){const r=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>eh()),[c,u]=l.useState(null),p=l.useCallback(m=>{const h=[];return m.metaKey&&h.push(r?"⌘":"Meta"),m.ctrlKey&&h.push("Ctrl"),m.altKey&&h.push(r?"⌥":"Alt"),m.shiftKey&&h.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(m.key)?null:(h.push(m.key.length===1?m.key.toUpperCase():m.key),h.join("+"))},[r]),d=l.useCallback(m=>{i(m);try{localStorage.setItem(Zm,JSON.stringify(m))}catch{}},[]);return l.useEffect(()=>{if(!e||!c)return;const m=h=>{if(h.preventDefault(),h.stopPropagation(),h.key==="Escape"){u(null);return}const g=p(h);if(!g)return;const k={...o};for(const[f,x]of Object.entries(k))x===g&&delete k[f];k[c]=g,d(k),u(null)};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[e,c,o,d,p]),l.useEffect(()=>{if(!e)return;const m=h=>{if(!(!h.ctrlKey&&!h.metaKey&&!h.altKey)){for(const[g,k]of Object.entries(o))if(t.includes(g)&&p(h)===k){h.preventDefault(),n(),a(g);return}}};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[e,o,t,n,a,p]),{isMac:r,tabShortcuts:o,shortcutListening:c,setShortcutListening:u,saveShortcuts:d}}const Go=e=>{e.preventDefault()},xN=l.memo(function({conv:t,isActive:n,isDraggedTab:a,isTaskCompleteUnread:r,shortcut:o,conversationKeys:i,draggingTabRef:c,onFocus:u,onSelectTab:p,onConversationActivated:d,onPreviewReorder:m,onReorderTab:h,onCommitPreviewOrder:g,onClearPreviewOrder:k,onDragStateReset:f,onDragTabKeyChange:x,onReceiveTab:w,onOpenContextMenu:b,longPressTimer:S,isGroupActive:N}){const v=Sn(t),y=v.isGenerating?"agent-tab-generating":v.isWaiting?"agent-tab-waiting":"",j=v.isReconnecting,C=AS(t),A=TS(t),T=tm(t),D=l.useCallback(H=>{c.current=t.tabKey,x(t.tabKey),H.dataTransfer.setData("text/tab-key",t.tabKey),H.dataTransfer.effectAllowed="move"},[t.tabKey,c,x]),I=l.useCallback(()=>{c.current=null,x(null),g(),k(),f()},[c,x,g,k,f]),M=l.useCallback(H=>{const _=c.current;if(!(!_||_===t.tabKey)&&H.dataTransfer.types.includes("text/tab-key")){H.preventDefault(),H.stopPropagation();const G=H.currentTarget.getBoundingClientRect(),W=H.clientX<G.left+G.width/2?"left":"right";m(_,t.tabKey,W)}},[t.tabKey,c,m]),P=l.useCallback(H=>{H.preventDefault(),H.stopPropagation();const _=H.dataTransfer.getData("text/tab-key");if(_&&_!==t.tabKey){const G=H.currentTarget.getBoundingClientRect(),W=H.clientX<G.left+G.width/2?"left":"right";i.includes(_)?h(_,t.tabKey,W):w&&w(_)}k()},[t.tabKey,i,h,w,k]),$=l.useCallback(H=>{H.stopPropagation(),u(),p(t.tabKey),d(t)},[t,d,u,p]),L=l.useCallback(H=>{H.preventDefault(),b(H.clientX,H.clientY,t.tabKey)},[t.tabKey,b]),R=l.useCallback(H=>{const _=H.touches[0];S.current=setTimeout(()=>{b(_.clientX,_.clientY,t.tabKey)},600)},[t.tabKey,S,b]),F=l.useCallback(()=>{S.current&&clearTimeout(S.current)},[S]),E=["adhdev-dockview-tab",y,n&&"is-active",N&&"is-group-active",j&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:E,draggable:!0,onDragStart:D,onDragEnd:I,onDragOver:M,onDrop:P,onClick:$,onContextMenu:L,onTouchStart:R,onTouchEnd:F,onTouchMove:F,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(as,{size:11})}),r&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:v.isGenerating?s.jsx("div",{className:"tab-spinner"}):v.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):j?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):v.isConnecting?s.jsx("div",{className:"tab-connecting-spinner"}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),C.length>0&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-role",title:A,"aria-label":A||C.join(" · "),children:C.join(" · ")}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:wt(t),children:wt(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:pn(t)}):v.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[pn(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:pn(t)}),s.jsx(Pr,{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 vN({conversations:e,activeTabId:t,groupIndex:n,unreadTabKeys:a,draggingTabRef:r,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:d,onClearPreviewOrder:m,onDragStateReset:h,onDragTabKeyChange:g,onReceiveTab:k,onHideTab:f,isGroupActive:x,allowTabShortcuts:w=!0}){const{t:b}=Ce("common"),[S,N]=l.useState(null),v=l.useRef(null),y=l.useRef(null),j=l.useMemo(()=>e.map(P=>P.tabKey),[e]);_a("PaneGroupTabBar",{groupIndex:n,activeTabId:t,tabCount:e.length,ctxMenuTab:(S==null?void 0:S.tabKey)||null});const{isMac:C,tabShortcuts:A,shortcutListening:T,setShortcutListening:D,saveShortcuts:I}=th({enabled:w,sortedTabKeys:e.map(P=>P.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!S)return;const P=$=>{const L=document.querySelector("[data-pane-context-menu]");L&&L.contains($.target)||N(null)};return window.addEventListener("mousedown",P,!0),()=>window.removeEventListener("mousedown",P,!0)},[S]),l.useEffect(()=>{const P=y.current;if(!P)return;const $=L=>{Math.abs(L.deltaY)<=Math.abs(L.deltaX)||(L.preventDefault(),P.scrollLeft+=L.deltaY)};return P.addEventListener("wheel",$,{passive:!1}),()=>P.removeEventListener("wheel",$)},[]);const M=l.useCallback((P,$,L)=>{N({x:P,y:$,tabKey:L})},[]);return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:s.jsxs("div",{ref:y,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(P=>s.jsx(xN,{conv:P,isActive:t===P.tabKey,isDraggedTab:r.current===P.tabKey,isTaskCompleteUnread:a.has(P.tabKey),shortcut:w?A[P.tabKey]:void 0,conversationKeys:j,draggingTabRef:r,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:d,onClearPreviewOrder:m,onDragStateReset:h,onDragTabKeyChange:g,onReceiveTab:k,onOpenContextMenu:M,longPressTimer:v,isGroupActive:x},P.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:b("paneGroup.noTabsInGroup")})]})}),S&&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:S.x,top:S.y},children:[w&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:Go,onClick:P=>{P.stopPropagation(),D(S.tabKey),N(null)},children:["⌨ ",A[S.tabKey]?`Change shortcut (${A[S.tabKey]})`:"Set shortcut"]}),A[S.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:Go,onClick:()=>{const P={...A};delete P[S.tabKey],I(P),N(null)},children:"✕ Remove shortcut"})]}),f&&s.jsxs(s.Fragment,{children:[w&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onMouseDown:Go,onClick:()=>{f(S.tabKey),N(null)},children:"🚫 Hide from Dashboard"})]})]}),w&&T&&s.jsx(Yt,{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:()=>D(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:P=>P.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. ",C?"⌘+1":"Ctrl+1",", ",C?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:b("paneGroup.pressEscToCancel")})]})})})]})}function yN({conversations:e,ides:t,clearedTabs:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:u=!0,userName:p,groupIndex:d,onFocus:m,isSplitMode:h,numGroups:g,onMoveTab:k,onReceiveTab:f,style:x,onActiveTabChange:w,initialActiveTabId:b,initialTabOrder:S,onTabOrderChange:N,onHideTab:v,isFocused:y,allowTabShortcuts:j=!0,onOpenNewSession:C,liveSessionInboxState:A}){const{sendCommand:T}=kt(),D=l.useRef(null),{activeTabId:I,activeConv:M,sortedConversations:P,draggingTabRef:$,selectTab:L,handleTabReorder:R,updatePreviewOrder:F,commitPreviewOrder:E,clearPreviewOrder:H,moveTabToEnd:_,setDraggingTabKey:G}=bN({conversations:e,initialActiveTabId:b,initialTabOrder:S,onActiveTabChange:w,onTabOrderChange:N}),W=eo({sendDaemonCommand:r,activeConv:M,setActionLogs:o,isStandalone:i}),{dragOver:K,dropAction:V,resetDragState:te,handleDragEnter:le,handleDragOver:de,handleDragLeave:ee,handleDrop:z}=hN({conversations:e,numGroups:g,onMoveTab:k,onReceiveTab:f,onOwnTabDrop:_,onClearPreviewOrder:H}),X=M&&!pt(M)&&Yn(M)==="terminal",U=l.useMemo(()=>M?t.find(ge=>ge.id===M.routeId):void 0,[t,M]),Q=l.useMemo(()=>M?a.filter(ge=>ge.routeId===M.tabKey):[],[a,M]),ke=l.useMemo(()=>new Set(P.filter(ge=>jg(ge,A,{isOpenConversation:ge.tabKey===I})).map(ge=>ge.tabKey)),[I,A,P]);_a("PaneGroup",{groupIndex:d,conversationCount:e.length,activeTabId:I,dragOver:K});const ve=l.useCallback(ge=>{ge.streamSource==="agent-stream"&&ge.agentType&&T(ge.routeId,_p(),{agentType:ge.agentType,...ge.sessionId&&{targetSessionId:ge.sessionId}}).catch(()=>{})},[T]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:m,style:{...x,outline:K?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(vN,{conversations:P,activeTabId:I,groupIndex:d,numGroups:g,unreadTabKeys:ke,draggingTabRef:$,onFocus:m,onSelectTab:L,onConversationActivated:ve,onPreviewReorder:F,onReorderTab:R,onCommitPreviewOrder:E,onClearPreviewOrder:H,onDragStateReset:te,onDragTabKeyChange:G,onMoveTab:k,onReceiveTab:f,onHideTab:v,isGroupActive:y??!1,allowTabShortcuts:j}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:le,onDragOver:de,onDragLeave:ee,onDrop:z,children:[K&&s.jsx(gN,{dropAction:V,canSplit:!!(g<4&&k)}),M?s.jsx(Hl,{activeConv:M,clearToken:n[M.tabKey]||0,isCliTerminal:!!X,ideEntry:U,terminalRef:D,handleModalButton:W.handleModalButton,handleRelaunch:W.handleRelaunch,handleSendChat:W.handleSendChat,handleForceSendChat:W.handleForceSendChat,isSendingChat:W.isSendingChat,sendFeedbackMessage:W.sendFeedbackMessage,handleFocusAgent:W.handleFocusAgent,isFocusingAgent:W.isFocusingAgent,actionLogs:Q,userName:p,isInputActive:!h||!!y}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(Fl,{conversationsCount:e.length,isSplitMode:h,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:C,isLoading:!oo(t,u)})})]})]})}function wN({containerRef:e,isSplitMode:t,numGroups:n,groupSizes:a,groupedConvs:r,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:u,setActionLogs:p,isStandalone:d,hasRegisteredMachines:m,initialDataLoaded:h,userName:g,focusedGroup:k,focusGroup:f,moveTabToGroup:x,splitTabRelative:w,closeGroup:b,handleResizeStart:S,groupActiveTabIds:N,setGroupActiveTab:v,groupTabOrders:y,setGroupTabOrder:j,toggleHiddenTab:C,onOpenNewSession:A,allowTabShortcuts:T=!0,liveSessionInboxState:D}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:r.map((I,M)=>{const P=t&&a.length===n?`${a[M]}%`:void 0;return s.jsxs(Lt.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:$=>S(M-1,$),onDoubleClick:()=>b(M),title:"Drag to resize · Double-click to merge",children:s.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),s.jsx(yN,{style:t?{flexBasis:P??`${100/n}%`,flexGrow:P?0:1,flexShrink:P?0:1}:void 0,conversations:I,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:u,setActionLogs:p,isStandalone:d,hasRegisteredMachines:m,initialDataLoaded:h,userName:g,groupIndex:M,isFocused:t&&k===M,onFocus:()=>f(M),isSplitMode:t,numGroups:n,onMoveTab:($,L)=>{L==="left"&&M>0?x($,M-1):L==="right"&&M<n-1?x($,M+1):L==="split-left"&&n<4?w($,M,"left"):L==="split-right"&&n<4&&w($,M,"right")},onReceiveTab:$=>x($,M),onActiveTabChange:$=>v(M,$),initialActiveTabId:N[M],initialTabOrder:y[M],onTabOrderChange:$=>j(M,$),onHideTab:C,onOpenNewSession:A,allowTabShortcuts:T,liveSessionInboxState:D})]},M)})})}const sh="adhdev-dashboard-action-shortcuts",kN=1200,SN=[["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 CN(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function ht(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 nh(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:ht("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:ht("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:ht("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:ht("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:ht("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:ht("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:ht("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:ht("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:ht("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:ht("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:ht("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:ht("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:ht("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:ht("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:ht("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:ht("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:ht("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:ht("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:ht("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:ht("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:ht("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:ht("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:ht("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:ht("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:ht("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:ht("toggleCliView",e)}]}function Ki(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function Br(e){const t=Object.fromEntries(nh(e).map(n=>[n.id,n.defaultShortcut]));try{const n=JSON.parse(localStorage.getItem(sh)||"{}"),a={...t,...n};for(const[r,o]of SN)a[r]===o&&(a[r]=t[r]);return a}catch{return t}}function ah(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function jN({enabled:e=!0,onTrigger:t}){const n=CN(),[a,r]=l.useState(()=>Br(n)),[o,i]=l.useState(null),[c,u]=l.useState([]),p=l.useRef({parts:[],timer:null}),d=l.useCallback(f=>{const x=[];return f.metaKey&&x.push(n?"⌘":"Meta"),f.ctrlKey&&x.push("Ctrl"),f.altKey&&x.push(n?"⌥":"Alt"),f.shiftKey&&f.key.length!==1&&x.push(n?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(x.push(ah(f.key)),x.join("+"))},[n]),m=l.useCallback(f=>{r(f);try{localStorage.setItem(sh,JSON.stringify(f))}catch{}},[]);l.useEffect(()=>{const f=Br(n),x=Object.entries(a),w=Object.entries(f);x.length===w.length&&x.every(([b,S])=>f[b]===S)||m(f)},[a,n,m]);const h=l.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),g=l.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},kN))},[]);l.useEffect(()=>{if(!o)return;const f=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){i(null),u([]);return}const w=d(x);if(!w)return;const S=!(x.metaKey||x.ctrlKey||x.altKey)&&/^[A-Z0-9]$/.test(w);if(c.length===0&&S){u([w]);return}const v=[...c,w].slice(0,2).join(" "),y={...a};for(const[j,C]of Object.entries(y))C===v&&delete y[j];y[o]=v,m(y),i(null),u([])};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[a,d,m,o,c]),l.useEffect(()=>{if(!e||o)return;const f=x=>{if(x.defaultPrevented)return;const w=d(x);if(!w)return;const b=x.metaKey||x.ctrlKey||x.altKey;if(Ki(x.target))return;const S=p.current.parts,N=b?[w]:[...S.slice(-1),w].slice(-2),v=N.join(" "),y=N[N.length-1],j=Object.entries(a).filter(([,I])=>!!I),C=j.find(([,I])=>I===v);if(C){x.preventDefault(),h(),t(C[0]);return}if(j.some(([,I])=>I.startsWith(`${v} `))){x.preventDefault(),p.current.parts=N,g();return}const T=j.find(([,I])=>I===y);if(T){x.preventDefault(),h(),t(T[0]);return}if(j.some(([,I])=>I.startsWith(`${y} `))){x.preventDefault(),p.current.parts=[y],g();return}h()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[a,g,e,d,t,h,o]),l.useEffect(()=>()=>h(),[h]);const k=l.useMemo(()=>nh(n),[n]);return{isMac:n,actionDefinitions:k,actionShortcuts:a,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:u,saveShortcuts:m}}function NN({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 rh(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function Ad({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:n,ides:a}){return!e||n>0?!1:t?!rh(a):!0}function AN({previousVisibleConversationCount:e,visibleConversationCount:t,ides:n}){return t>0||e<=0?!1:rh(n)}const oh=1e3,TN=4;function Td(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function Md(e,t,n){return Math.abs(t.clientX-e.clientX)>n||Math.abs(t.clientY-e.clientY)>n}function MN({detachDelayMs:e=oh,stillnessThresholdPx:t=TN,onDetach:n,setTimeoutFn:a=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:r=globalThis.clearTimeout.bind(globalThis)}){let o=null,i=null,c=null,u=null,p=null,d=!1;const m=()=>{p!=null&&(r(p),p=null)},h=()=>{m(),c=null},g=()=>{m(),o=null,i=null,c=null,u=null,d=!1},k=()=>{!o||!c||!u||d||p!=null||(p=a(()=>{p=null,!(!o||!c||!u||d)&&Td(u,i)&&(Md(c,u,t)||(d=!0,n({panelId:o,clientX:u.clientX,clientY:u.clientY})))},e))},f=w=>{if(!(!o||d)){if(!Td(w,i)){u={clientX:w.clientX,clientY:w.clientY},h();return}(!c||Md(c,w,t))&&(m(),c={clientX:w.clientX,clientY:w.clientY}),u={clientX:w.clientX,clientY:w.clientY},k()}},x=w=>{!o||d||(w&&(u={clientX:w.clientX,clientY:w.clientY}),h())};return{startDrag:w=>{m(),o=w.panelId,i=w.selfPanelBounds??null,c=null,u={clientX:w.clientX,clientY:w.clientY},d=!1},markSelfPanel:f,markNonSelfPanel:x,markNoDropTarget:x,markDockTarget:x,endDrag:g,isDragging:()=>o!=null,hasDetached:()=>d,dispose:g}}function DN(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function xr(e){return wt(e)||e.tabKey}function PN(e){return`remote:${e}`}function ls(e){return e.startsWith("remote:")}function Dd(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function zo(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 Ko(e,t){e.classList.remove(xi.className,vi.className),e.classList.add(t==="light"?xi.className:vi.className)}function Pd(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 IN(e,t,n){var i;const a=[t];let r;for(const c of a){let u;for(const p of c){const d=e.addPanel({id:p.tabKey,component:"conversation",title:xr(p),params:{kind:"conversation",tabKey:p.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:r?{position:{referencePanel:r,direction:"right"},inactive:!0}:{}});u||(u=d.id)}r=u??r}return n??((i=t[0])==null?void 0:i.tabKey)??null}function Id(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])ls(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!==xr(r)&&o.api.setTitle(xr(r));continue}e.addPanel({id:r.tabKey,component:"conversation",title:xr(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 Ld(e,t,n){var u,p;const a=n?PN(n):null;for(const d of[...e.panels])ls(d.id)&&(!a||d.id!==a)&&e.removePanel(d);if(!n||!a)return;const r=fs(t,n);if(!r&&e.totalPanels===0)return;const o=e.getPanel(a),i=rm(r);if(o){o.title!==i&&o.api.setTitle(i);return}const c=(r==null?void 0:r.tabKey)??((u=e.activePanel)==null?void 0:u.id)??((p=e.panels.find(d=>!ls(d.id)))==null?void 0:p.id);e.addPanel({id:a,component:"remote",title:i,params:{kind:"remote",routeId:n},...c?{position:{referencePanel:c,direction:"right"},inactive:!0}:{}})}function ih({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",(d,m)=>{if(d!==e)return;const h=new FileReader;h.onload=()=>o(h.result),h.readAsDataURL(m)}):void 0,[e]),l.useEffect(()=>{n!=="connected"&&o(null)},[n]),l.useEffect(()=>{var d;return e?((d=Ct.onStatus)==null?void 0:d.call(Ct,(m,h)=>{m===e&&h!=null&&h.screenshotUsage&&c(h.screenshotUsage)}))||(()=>{}):void 0},[e]),l.useEffect(()=>{o(null)},[e,t]),l.useEffect(()=>{const p=e?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 u=l.useCallback(async(p,d)=>{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,d,t)},[e,n,t]);return{connScreenshot:r,screenshotUsage:i,handleRemoteAction:u}}const lh=l.createContext(null);function io(){const e=l.useContext(lh);if(!e)throw new Error("DashboardDockviewContext missing");return e}function LN(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 RN({params:e}){var u;const t=io(),n=l.useMemo(()=>fs([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),a=l.useMemo(()=>t.ides.find(p=>p.id===e.routeId),[t.ides,e.routeId]),r=(n==null?void 0:n.daemonId)||((u=n==null?void 0:n.routeId)==null?void 0:u.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:i,handleRemoteAction:c}=ih({doId:r,targetSessionId:n?Rp(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(Zu,{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 EN(){const e=io();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(Fl,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels,isLoading:!oo(e.ides,e.initialDataLoaded)})})}function _N(e){var b,S;LN(e);const t=io(),n=l.useCallback(N=>{"button"in N&&N.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(N=>cS(N),[]),i=l.useCallback(()=>lS(r),[r]),c=l.useSyncExternalStore(o,i,i);if(e.params.kind==="remote"){const N=fs([...t.conversationsByTabKey.values()],e.params.routeId),v=((b=e.api.group.activePanel)==null?void 0:b.id)===e.api.id,y=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${v?" is-active":""}${y?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(N==null?void 0:N.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:N!=null&&N.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:N.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const u=t.conversationsByTabKey.get(e.params.tabKey);if(!u)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const p=((S=e.api.group.activePanel)==null?void 0:S.id)===e.api.id,d=e.api.isGroupActive,m=Vr(u,t.liveSessionInboxState,{isOpenConversation:p}),h=m.isReconnecting,g=m.isConnecting,k=m.isGenerating||c,f=m.isWaiting,x=m.unread,w=t.tabShortcuts[u.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${p?" is-active":""}${d?" is-group-active":""}${h?" is-reconnecting":""}`,title:wt(u),"data-tab-key":e.params.tabKey,onMouseDown:n,onTouchStart:n,onContextMenu:N=>{var v;N.preventDefault(),n(N),t.openTabContextMenu({x:N.clientX,y:N.clientY,tabKey:u.tabKey,sourceDocument:((v=N.target)==null?void 0:v.ownerDocument)??document})},children:[x&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:k?s.jsx("div",{className:"tab-spinner"}):f?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):h?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):g?s.jsx("div",{className:"tab-connecting-spinner"}):u.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:wt(u)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:h?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:pn(u)}):g?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:pn(u)}):s.jsx("span",{children:pn(u)})})]}),w&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:w,children:w})]})}function sr(e){return e.isActive}function Rd(e){return e.isVisible}function HN(e){e.preventDefault()}function $N({params:e,api:t}){var g;const n=io(),a=l.useRef(null),[r,o]=l.useState(()=>sr(t)),[i,c]=l.useState(()=>Rd(t)),u=n.conversationsByTabKey.get(e.tabKey),p=eo({sendDaemonCommand:n.sendDaemonCommand,activeConv:u,setActionLogs:n.setActionLogs,isStandalone:n.isStandalone});l.useEffect(()=>{o(sr(t)),c(Rd(t));const k=[t.onDidActiveChange(f=>o(f.isActive)),t.onDidActiveGroupChange(f=>{if(!sr(t)&&!f.isActive){o(!1);return}o(sr(t))}),t.onDidVisibilityChange(f=>c(f.isVisible))];return()=>{for(const f of k)f.dispose()}},[t]);const d=l.useMemo(()=>u?n.ides.find(k=>k.id===u.routeId):void 0,[n.ides,u]),m=l.useMemo(()=>u?n.actionLogs.filter(k=>k.routeId===u.tabKey):[],[n.actionLogs,u]);if(!u)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(Fl,{conversationsCount:0,isSplitMode:!1,isStandalone:n.isStandalone,hasRegisteredMachines:n.hasRegisteredMachines,onOpenNewSession:n.onOpenNewSession,suppressGuide:n.hasDetachedConversationPanels,isLoading:!oo(n.ides,n.initialDataLoaded)})});const h=!pt(u)&&Yn(u)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(Hl,{activeConv:u,clearToken:n.clearedTabs[u.tabKey]||0,isCliTerminal:h,ideEntry:d,terminalRef:a,handleModalButton:p.handleModalButton,handleRelaunch:p.handleRelaunch,handleSendChat:p.handleSendChat,handleForceSendChat:p.handleForceSendChat,isSendingChat:p.isSendingChat,handleFocusAgent:p.handleFocusAgent,isFocusingAgent:p.isFocusingAgent,actionLogs:m,userName:n.userName,scrollToBottomRequestNonce:((g=n.scrollToBottomRequest)==null?void 0:g.tabKey)===u.tabKey?n.scrollToBottomRequest.nonce:void 0,isInputActive:r,isVisible:i})})}function FN({visibleConversations:e,clearedTabs:t,ides:n,actionLogs:a,sendDaemonCommand:r,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:u,userName:p,toggleHiddenTab:d,actionShortcuts:m,registerActionHandlers:h,onActiveTabChange:g,onOpenNewSession:k,onRequestScrollToBottom:f,requestedActiveTabKey:x,requestedRemoteIdeId:w,onRequestedActiveTabConsumed:b,scrollToBottomRequest:S,liveSessionInboxState:N,layoutProfile:v}){var ut,it,mt;const{theme:y}=en(),{sendCommand:j}=kt(),C=l.useRef(null),A=l.useRef(null),T=l.useRef(null),D=l.useRef(!1),I=l.useRef(!1),M=l.useRef(!1),P=l.useRef(null),$=l.useRef([]),[L,R]=l.useState(null),[F,E]=l.useState(0),H=l.useRef(typeof window>"u"?{}:n1(v)),_=l.useMemo(()=>new Map(e.map(J=>[J.tabKey,J])),[e]),G=l.useMemo(()=>{const J=C.current;return J?J.groups.some(ne=>{try{const ce=ne.model.location.type;return ce!=="floating"&&ce!=="popout"?!1:ne.panels.some(be=>_.has(be.id))}catch{return!1}}):!1},[_,F,e]),W=l.useCallback(()=>{var J;(J=C.current)==null||J.focus()},[]),K=l.useCallback((J,ne)=>{f==null||f(J,ne)},[f]),V=l.useCallback(J=>{const ne=document,ce=J.document;for(const Pe of ne.querySelectorAll('link[rel="stylesheet"]')){const Ge=ce.createElement("link");Ge.rel="stylesheet",Ge.href=Pe.href,Pe.crossOrigin&&(Ge.crossOrigin=Pe.crossOrigin),ce.head.appendChild(Ge)}for(const Pe of ne.querySelectorAll("style")){const Ge=ce.createElement("style");Ge.textContent=Pe.textContent,ce.head.appendChild(Ge)}const be=[];for(const Pe of ne.styleSheets)try{for(const Ge of Pe.cssRules)Ge instanceof CSSStyleRule&&(Ge.selectorText===":root"||Ge.selectorText==="html")&&be.push(Ge.cssText)}catch{}if(be.length>0){const Pe=ce.createElement("style");Pe.textContent=be.join(`
|
|
71
71
|
`),ce.head.appendChild(Pe)}const re=ne.documentElement.getAttribute("data-theme");re&&ce.documentElement.setAttribute("data-theme",re),ce.documentElement.style.colorScheme=re==="light"?"light":"dark",ce.body.className=ne.body.className;const Te=ne.documentElement.getAttribute("style");Te&&ce.documentElement.setAttribute("style",Te);const He=ce.getElementById("dv-popout-window");He instanceof HTMLElement&&(He.classList.add("adhdev-dockview"),Ko(He,y))},[y]),te=l.useCallback(()=>{var ne;const J=C.current;if(J)for(const ce of J.groups)try{const be=(ne=ce.element)==null?void 0:ne.ownerDocument;if(!be||be===document)continue;const re=be.getElementById("dv-popout-window");re instanceof HTMLElement&&(re.classList.add("adhdev-dockview"),Ko(re,y));const Te=document.documentElement.getAttribute("data-theme");Te&&be.documentElement.setAttribute("data-theme",Te),be.documentElement.style.colorScheme=Te==="light"?"light":"dark",be.body.className=document.body.className;const He=document.documentElement.getAttribute("style");He?be.documentElement.setAttribute("style",He):be.documentElement.removeAttribute("style")}catch{}},[y]),le=l.useCallback(J=>{const ne=C.current;if(!ne)return;const ce=ne.getPanel(J);ce&&ne.addPopoutGroup(ce,{popoutUrl:"/popout.html",onDidOpen:({window:be})=>{V(be),ge();const re=_.get(J);be.document.title=re?`${wt(re)} — ADHDev`:"ADHDev — Popout"}})},[_,V]),de=l.useCallback(J=>{const ne=C.current,ce=ne==null?void 0:ne.getPanel(J);if(!ne||!ce)return;const be=ne.groups.filter(re=>{var Te;try{return((Te=re.element)==null?void 0:Te.ownerDocument)===document}catch{return!0}});be.length>0?ce.api.moveTo({group:be[0],position:"center"}):ce.api.moveTo({position:"center"}),ce.api.setActive()},[]),ee=l.useCallback(J=>{var be;const ne=C.current;if(!ne)return!1;const ce=ne.getPanel(J);if(!ce)return!1;try{return((be=ce.group.element)==null?void 0:be.ownerDocument)!==document}catch{return!1}},[]),z=l.useCallback(J=>{ee(J)&&de(J),d(J)},[ee,de,d]),X=l.useCallback(J=>{const ne=C.current,ce=ne==null?void 0:ne.getPanel(J);!ne||!ce||ne.addFloatingGroup(ce,{width:600,height:500})},[]),U=l.useCallback(J=>{var ce;const ne=(ce=C.current)==null?void 0:ce.getPanel(J);if(!ne)return!1;try{return ne.group.model.location.type==="floating"}catch{return!1}},[]),Q=l.useCallback(()=>{var ne,ce;const J=(ce=(ne=C.current)==null?void 0:ne.activePanel)==null?void 0:ce.id;return!J||ls(J)?null:_.has(J)?J:null},[_]),ke=l.useCallback(J=>{const ne=C.current,ce=ne==null?void 0:ne.getPanel(J);if(!ne||!ce)return;const be=ne.groups.filter(re=>{try{return re.model.location.type==="grid"}catch{return!0}});be.length>0?ce.api.moveTo({group:be[0],position:"center"}):ce.api.moveTo({position:"center"}),ce.api.setActive()},[]),ve=l.useCallback(()=>{var Te;const J=C.current;if(!J)return;const ce=J.groups.filter(He=>{var Pe;try{return((Pe=He.element)==null?void 0:Pe.ownerDocument)===document&&He.model.location.type==="grid"}catch{return!1}})[0]||null,be=[...J.panels];for(const He of be){const Pe=(Te=He.group.element)==null?void 0:Te.ownerDocument,Ge=He.group.model.location.type;Pe===document&&Ge==="grid"||(ce&&ce.id!==He.group.id?He.api.moveTo({group:ce,position:"center"}):He.api.moveTo({position:"center"}))}const re=J.activePanel;re&&(re.group.model.openPanel(re),re.api.setActive()),zo(document)},[]),ge=l.useCallback(()=>{var ne,ce;const J=C.current;if(J)for(const be of J.groups){const re=(ne=be.element)==null?void 0:ne.ownerDocument;if(!re||re===document)continue;const Te=re.getElementById("dv-popout-window");if(!(Te instanceof HTMLElement))continue;let He=null,Pe=re.title||"ADHDev",Ge="Popout workspace";const ze=be.activePanel;if(ze)if(He=ze.id,ls(ze.id)){const We=((ce=ze.params)==null?void 0:ce.routeId)||ze.id.slice(7),ue=fs([..._.values()],We);Pe=rm(ue),Ge=ue!=null&&ue.machineName?`Remote view · ${ue.machineName}`:"Remote view"}else{const We=_.get(ze.id);Pe=We?wt(We):ze.title||ze.id,Ge=We?pn(We):"Dockview panel"}re.title=`${Pe} — ADHDev`;const Je=Array.from(re.querySelectorAll("#adhdev-popout-header"));for(const We of Je)We.remove();const Ue=re.createElement("div");Ue.id="adhdev-popout-header",re.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=`
|
|
72
72
|
<div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
|
|
73
73
|
<div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
|
|
@@ -111,11 +111,11 @@ This will disconnect CDP and optionally kill the process.`))try{const _=await n(
|
|
|
111
111
|
|
|
112
112
|
`)}function pP(e,t){return t==="issues"?e.filter(n=>n.level==="warn"||n.level==="error"):t==="info"?e.filter(n=>n.level!=="debug"):e}function mP(e,t){return t==="issues"?e.filter(n=>n.level==="warn"||n.level==="error"):t==="info"?e.filter(n=>n.level!=="debug"):e}function hP({daemonLogs:e,daemonRawText:t,daemonLogKind:n,debugTrace:a,webEvents:r,traceCategory:o,quickFilter:i,searchQuery:c,daemonLoading:u,traceLoading:p,daemonFetchError:d,traceFetchError:m}){const h=qD(a,o),g=KD(e,c),k=QD(t,c),f=JD(h,c),x=XD(r,c),w=pP(g,i),b=i==="all"?k:[],S=mP(f,i),N=i==="issues"?[]:x,v=ZD({daemonLogs:g,daemonRawLines:k,trace:f,webEvents:x}),y=iP({daemonLogs:w,daemonRawLines:b,trace:S,webEvents:N}),j=cP(y),C=sP({daemonLoading:u,traceLoading:p,daemonFetchError:d,traceFetchError:m,daemonLogKind:n,daemonLogsCount:g.length,daemonRawLineCount:k.length,traceCount:f.length,webEventCount:x.length});return{filteredDaemonLogs:g,filteredDaemonRawLines:k,filteredTraceEntries:f,filteredWebEvents:x,visibleDaemonLogs:w,visibleDaemonRawLines:b,visibleTraceEntries:S,visibleWebEvents:N,quickFilterCounts:v,diagnosticEvents:y,diagnosticsSummary:j,sourceStates:C}}function fP(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Jh(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function Yi(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 li(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 Yl(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function bP({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Yi(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:Jh(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:Yl(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 gP({quickFilter:e,quickFilterCounts:t,searchQuery:n,autoRefresh:a,onQuickFilterChange:r,onSearchQueryChange:o,onCopyDiagnostics:i,onCopyVisible:c,onToggleAutoRefresh:u,onRefresh:p,onClear:d}){return s.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"View"}),s.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${t.info})`},{id:"issues",label:`Issues (${t.issues})`},{id:"all",label:`All (${t.all})`}].map(m=>s.jsx("button",{type:"button",onClick:()=>r(m.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===m.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:m.label},m.id))}),s.jsx("input",{value:n,onChange:m=>o(m.target.value),placeholder:"Search diagnostics…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{onClick:i,className:"machine-btn",children:"Copy diagnostics"}),s.jsx("button",{onClick:c,className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:u,className:`machine-btn ${a?"text-green-500 border-green-500/30":""}`,children:a?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:p,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:d,className:"machine-btn",children:"Clear"})]})]})}function xP({logLevel:e,traceCategory:t,onLogLevelChange:n,onTraceCategoryChange:a}){return s.jsx(ms,{padding:"sm",children:s.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wider text-text-muted font-semibold",children:"Advanced source scope"}),["debug","info","warn","error"].map(r=>s.jsxs("button",{onClick:()=>n(r),className:`machine-btn text-[10px] px-2 py-0.5 ${e===r?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:["Daemon ",r.toUpperCase(),"+"]},r))]}),s.jsx("div",{className:"flex flex-wrap gap-2 items-center",children:OD.map(r=>s.jsx("button",{onClick:()=>a(r.value),className:`machine-btn text-[10px] px-2 py-0.5 ${t===r.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:r.label},r.value))})]})})}function vP({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:n,searchQuery:a,lastUpdatedAt:r,autoRefresh:o,daemonFetchError:i,traceFetchError:c}){var d,m;const u=((d=e.latestIssue)==null?void 0:d.severity)==="error"?"danger":((m=e.latestIssue)==null?void 0:m.severity)==="warn"?"warning":"good",p=i||c?"danger":o?"good":"neutral";return s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${li(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 ${li(u)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Latest issue"}),e.latestIssue?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[Yl(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:Jh(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 ${li(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: ",fP(r)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:n.map(h=>s.jsxs("div",{children:[h.label,": ",h.status]},h.id))})]})]})}function yP({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()," · ",Yl(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function wP({streams:e,sectionsOpen:t,setSectionsOpen:n,diagnosticEvents:a,visibleDaemonLogs:r,visibleDaemonRawLines:o,visibleTraceEntries:i,visibleWebEvents:c,quickFilter:u,searchQuery:p}){return s.jsxs("div",{className:"grid gap-3",children:[s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>n(d=>({...d,timeline:!d.timeline})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Unified timeline"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[a.length," visible diagnostic event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.timeline?"Hide":"Show"})]}),t.timeline&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[180px] max-h-[440px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[(e.daemonLoading||e.traceLoading)&&a.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&a.length===0&&s.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&s.jsxs("div",{children:["Daemon logs: ",e.daemonFetchError]}),e.traceFetchError&&s.jsxs("div",{children:["Daemon trace: ",e.traceFetchError]})]}),!e.daemonLoading&&!e.traceLoading&&a.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),a.map(d=>s.jsx(bP,{event:d},d.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>n(d=>({...d,daemon:!d.daemon})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · daemon logs"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:e.daemonLogKind==="text"?`${o.length} visible raw line(s) from file fallback`:`${r.length} visible structured line(s)`})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.daemon?"Hide":"Show"})]}),t.daemon&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.daemonLoading&&r.length===0&&o.length===0&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),e.daemonLogKind==="text"&&o.length===0&&e.daemonRawText&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:u==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),e.daemonLogKind==="structured"&&r.length===0&&e.daemonLogs.length>0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),e.daemonLogKind==="text"&&o.map((d,m)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:d},`raw-${m}`)),e.daemonLogKind!=="text"&&r.map((d,m)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${Yi(d.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(d.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:d.level==="error"?"ERR":d.level==="warn"?"WRN":d.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:d.message})]},`log-${m}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>n(d=>({...d,trace:!d.trace})),children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Raw source · daemon trace",e.traceCategory==="session_host"?" · session_host only":""]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[i.length," visible trace event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.trace?"Hide":"Show"})]}),t.trace&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.traceLoading&&i.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&i.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&i.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:p.trim()?"No trace entries match the current search.":e.traceCategory==="session_host"?"No session_host trace entries yet. This filter uses get_debug_trace(category=session_host).":"No trace entries yet. Run daemon with --dev or --trace."}),i.map(d=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Yi(d.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(d.ts).toLocaleTimeString()}),s.jsx("span",{children:d.level.toUpperCase()}),s.jsxs("span",{children:[d.category,".",d.stage]}),d.interactionId&&s.jsxs("span",{children:["ix=",d.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Kn(d.payload,360)||"No payload"})]},d.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>n(d=>({...d,web:!d.web})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · browser debug events"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[c.length," visible browser event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.web?"Hide":"Show"})]}),t.web&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[c.length===0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:p.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),c.map(d=>s.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(d.ts).toLocaleTimeString()}),s.jsx("span",{children:d.kind}),d.topic&&s.jsxs("span",{children:["topic=",d.topic]}),d.interactionId&&s.jsxs("span",{children:["ix=",d.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Kn(d.payload,360)||"No payload"})]},d.id))]})]})]})}function kP({machineId:e,sendDaemonCommand:t}){const n=tP({machineId:e,sendDaemonCommand:t}),[a,r]=l.useState("info"),[o,i]=l.useState(""),[c,u]=l.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),p=l.useRef(null),d=l.useRef(!1),m=l.useMemo(()=>hP({daemonLogs:n.daemonLogs,daemonRawText:n.daemonRawText,daemonLogKind:n.daemonLogKind,debugTrace:n.debugTrace,webEvents:n.webEvents,traceCategory:n.traceCategory,quickFilter:a,searchQuery:o,daemonLoading:n.daemonLoading,traceLoading:n.traceLoading,daemonFetchError:n.daemonFetchError,traceFetchError:n.traceFetchError}),[a,o,n.daemonFetchError,n.daemonLoading,n.daemonLogKind,n.daemonLogs,n.daemonRawText,n.debugTrace,n.traceCategory,n.traceFetchError,n.traceLoading,n.webEvents]);l.useEffect(()=>{if(n.autoRefresh&&m.diagnosticEvents.length>0){const k=d.current?"smooth":"instant";setTimeout(()=>{var f;(f=p.current)==null||f.scrollIntoView({behavior:k}),d.current=!0},50)}},[m.diagnosticEvents.length,n.autoRefresh]);const h=l.useCallback(async()=>{var f;const k=eP({daemonLogs:m.visibleDaemonLogs,daemonRawLines:m.visibleDaemonRawLines,trace:m.visibleTraceEntries,webEvents:m.visibleWebEvents});if(!k.trim()){bt.showToast("No visible logs to copy.","info");return}try{await((f=navigator.clipboard)==null?void 0:f.writeText(k)),bt.showToast("Copied visible logs to clipboard.","success")}catch(x){bt.showToast(x instanceof Error?x.message:"Could not copy visible logs","warning")}},[m.visibleDaemonLogs,m.visibleDaemonRawLines,m.visibleTraceEntries,m.visibleWebEvents]),g=l.useCallback(async()=>{var f;const k=uP({events:m.diagnosticEvents,summary:m.diagnosticsSummary,sources:m.sourceStates});try{await((f=navigator.clipboard)==null?void 0:f.writeText(k)),bt.showToast("Copied diagnostic bundle to clipboard.","success")}catch(x){bt.showToast(x instanceof Error?x.message:"Could not copy diagnostic bundle","warning")}},[m.diagnosticEvents,m.diagnosticsSummary,m.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(gP,{quickFilter:a,quickFilterCounts:m.quickFilterCounts,searchQuery:o,autoRefresh:n.autoRefresh,onQuickFilterChange:r,onSearchQueryChange:i,onCopyDiagnostics:()=>{g()},onCopyVisible:()=>{h()},onToggleAutoRefresh:()=>n.setAutoRefresh(k=>!k),onRefresh:n.refresh,onClear:n.clear}),s.jsx(xP,{logLevel:n.logLevel,traceCategory:n.traceCategory,onLogLevelChange:n.setLogLevel,onTraceCategoryChange:n.setTraceCategory}),s.jsx(vP,{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(yP,{patterns:m.diagnosticsSummary.repeatedPatterns}),s.jsx(wP,{streams:n,sectionsOpen:c,setSectionsOpen:u,diagnosticEvents:m.diagnosticEvents,visibleDaemonLogs:m.visibleDaemonLogs,visibleDaemonRawLines:m.visibleDaemonRawLines,visibleTraceEntries:m.visibleTraceEntries,visibleWebEvents:m.visibleWebEvents,quickFilter:a,searchQuery:o}),s.jsx("div",{ref:p})]})}function SP(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 Xh(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 CP(e){var r;const t=[],n=[],a=[];for(const o of e||[]){const i=String((o==null?void 0:o.lifecycle)||"").trim(),c=Xh((o==null?void 0:o.meta)||void 0),u=((r=o==null?void 0:o.meta)==null?void 0:r.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(i)?t.push(o):(i==="stopped"||i==="failed")&&(u||c)?n.push(o):a.push(o)}return{liveRuntimes:t,recoverySnapshots:n,inactiveRecords:a}}function jP(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function ci(e){return e==="live"?"These runtimes are live now and are the only attachable targets.":e==="recovery"?"These records were restored from session-host state and are not live attach targets until you explicitly recover or restart them.":"These inactive records are shown for reference and usually need restart before they are useful again."}function di(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function ui(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function du(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 NP(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function AP(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 TP(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 MP({machineId:e,cliSessions:t,sendDaemonCommand:n}){const[a,r]=l.useState(""),[o,i]=l.useState(null),[c,u]=l.useState(!1),p=jj(e,{enabled:!!e,includeSessions:!0,limit:Bc,intervalMs:Pk}),d=p.diagnostics,m=p.loading,h=p.applyDiagnostics,g=l.useMemo(()=>SP({diagnostics:d,loading:m,refreshing:c,error:a}),[d,m,c,a]),k=l.useMemo(()=>new Map(t.map(D=>[D.sessionId||D.id,D])),[t]),f=l.useCallback(async()=>{if(e){u(!0);try{const D=await n(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Bc}),I=di(D);if(!(I!=null&&I.success))throw new Error((I==null?void 0:I.error)||"Could not load hosted runtime diagnostics");h(I.diagnostics||I.result||null),r("")}catch(D){const I=D instanceof Error?D.message:"Could not load hosted runtime diagnostics";r(I)}finally{u(!1)}}},[h,e,n]);l.useEffect(()=>{!e||d||m||c||f()},[d,m,e,f,c]);const x=l.useCallback(async(D,I)=>{const M=`${D}:${I.sessionId}`;if(!(D==="session_host_stop_session"&&!window.confirm(`Stop ${I.displayName}?
|
|
113
113
|
This will terminate the hosted runtime.`))){i(M);try{const P=await n(e,D,{sessionId:I.sessionId}),$=di(P);if(!($!=null&&$.success))throw new Error(($==null?void 0:$.error)||"Session host action failed");const L=D==="session_host_resume_session"?"resumed":D==="session_host_restart_session"?"restarted":"stopped";bt.showToast(`Session host ${L}: ${I.displayName}`,"success"),await f()}catch(P){const $=P instanceof Error?P.message:"Session host action failed";bt.showToast($,"warning"),r($)}finally{i(P=>P===M?null:P)}}},[e,f,n]),w=l.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
|
|
114
|
-
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){i("session_host_prune_duplicate_sessions");try{const I=await n(e,"session_host_prune_duplicate_sessions",{}),M=di(I);if(!(M!=null&&M.success))throw new Error((M==null?void 0:M.error)||"Duplicate prune failed");const P=M.result||{},$=Array.isArray(P.prunedSessionIds)?P.prunedSessionIds.length:0,L=typeof P.duplicateGroupCount=="number"?P.duplicateGroupCount:0;bt.showToast(`Pruned ${$} duplicate runtime(s) across ${L} group(s)`,"success"),await f()}catch(I){const M=I instanceof Error?I.message:"Duplicate prune failed";bt.showToast(M,"warning"),r(M)}finally{i(I=>I==="session_host_prune_duplicate_sessions"?null:I)}}},[e,f,n]),b=l.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((D,I)=>(I.lastActivityAt||0)-(D.lastActivityAt||0)),[d==null?void 0:d.sessions]),S=l.useMemo(()=>d!=null&&d.liveRuntimes||d!=null&&d.recoverySnapshots||d!=null&&d.inactiveRecords?{liveRuntimes:(d==null?void 0:d.liveRuntimes)||[],recoverySnapshots:(d==null?void 0:d.recoverySnapshots)||[],inactiveRecords:(d==null?void 0:d.inactiveRecords)||[]}:CP(b),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,b]),N=S.liveRuntimes,v=S.recoverySnapshots,y=S.inactiveRecords,j=l.useMemo(()=>TP(N),[N]),C=l.useMemo(()=>[...(d==null?void 0:d.recentTransitions)||[]].slice(-6).reverse(),[d==null?void 0:d.recentTransitions]),A=l.useMemo(()=>[...(d==null?void 0:d.recentLogs)||[]].reverse().find(D=>D.level==="warn"||D.level==="error")||null,[d==null?void 0:d.recentLogs]),T=(D,I)=>{var _;const M=o===`session_host_resume_session:${D.sessionId}`,P=o===`session_host_restart_session:${D.sessionId}`,$=o===`session_host_stop_session:${D.sessionId}`,L=Xh(D.meta),R=k.get(D.sessionId),F=D.attachedClients.length===1?"1 client":`${D.attachedClients.length} clients`,E=I==="recovery"?"Recover":"Resume",H=jP(I);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:D.displayName||(R==null?void 0:R.cliName)||D.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${AP(D.lifecycle)}`,children:D.lifecycle}),L&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:L})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:D.workspaceLabel||(R==null?void 0:R.runtimeWorkspaceLabel)||D.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:D.runtimeKey}),D.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",D.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((_=D.writeOwner)==null?void 0:_.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:NP(D.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(Hu,{size:11})," ",F]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",du(D.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:[I==="recovery"&&(D.lifecycle==="interrupted"||D.lifecycle==="failed"||D.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{x("session_host_resume_session",D)},children:M?`${E}ing…`:E}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{x("session_host_restart_session",D)},children:P?"Restarting…":"Restart"}),I==="live"&&(D.lifecycle==="running"||D.lifecycle==="starting"||D.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!o,onClick:()=>{x("session_host_stop_session",D)},children:$?"Stopping…":"Stop"})]})]})},D.sessionId)};return s.jsxs(ms,{padding:"lg",className:"mb-5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(Ys,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:oC()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[j>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{w()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${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:()=>{f()},disabled:m||c,children:[s.jsx(zr,{size:13}),m||c?"Refreshing…":"Refresh"]})]})]}),a&&!d&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(gn,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:a})]})]})}),d&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:d.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:v.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:d.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:du(d.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:ui(d.hostStartedAt)})]})]}),A&&s.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[s.jsx(gn,{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:[ui(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(ll,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ci("live")}),N.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:N.map(D=>T(D,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(Ys,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ci("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(D=>T(D,"recovery"))})]}),y.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ci("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:y.map(D=>T(D,"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"}),C.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:C.map(D=>{var M;const I=b.find(P=>P.sessionId===D.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:(I==null?void 0:I.displayName)||((M=k.get(D.sessionId))==null?void 0:M.cliName)||D.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[D.action,D.lifecycle?` · ${D.lifecycle}`:"",D.detail?` · ${D.detail}`:"",D.error?` · ${D.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${D.success===!1?"text-red-300":"text-text-secondary"}`,children:ui(D.timestamp)})]},`${D.sessionId}:${D.timestamp}:${D.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:d.endpoint||"unknown"}),a?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",a]}):null]})]})]})}function DP({machine:e,launchPick:t,actions:n}){const{t:a}=Ce("common"),{runLaunchCliCore:r,setLaunchPick:o}=n;return l.useEffect(()=>{const i=c=>{c.key==="Escape"&&o(null)};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[o]),s.jsx(Yt,{children:s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",onClick:()=>o(null),children:s.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",onClick:i=>i.stopPropagation(),children:[s.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),s.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),s.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?s.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(i=>s.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{o(null),r({cliType:t.cliType,workspaceId:i.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{o(null),r({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:a("newSession.defaultWorkspace")}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{o(null),r({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:a("newSession.homeDirectory")}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>o(null),children:"Cancel"})]})]})})})}function PP(e,t){const n=JC(e),a=qs(e,t),r=no(e,a),o=wa(e,a),i=jm(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 pi({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 mi({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 IP({machineEntry:e,providers:t,recentLaunches:n,currentConversations:a,onUpgradeDaemon:r,onOpenRecent:o,onOpenConversation:i}){const{t:c}=Ce("common"),u=a.slice(0,6),p=n.slice(0,4),m=PP(e,"1.0.41");return s.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[u.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(pi,{icon:s.jsx(kn,{size:13}),children:c("machine.commandCenter.currentChats")}),s.jsx(mi,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(h=>{const g=Gi(h);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>i(h),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:wt(h)}),g>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Kr(g)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:On(h)})]},h.tabKey)})})})]}),p.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(pi,{icon:s.jsx(Ou,{size:13}),children:c("machine.commandCenter.recentLaunches")}),s.jsx(mi,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:p.map(h=>{const{metaText:g,updatedLabel:k}=Qm(h);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>o(h),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:h.label}),k&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:k})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:g})]},h.id)})})})]}),m.visible&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(pi,{icon:s.jsx(gn,{size:13}),children:c("machine.commandCenter.daemonUpdate")}),s.jsx(mi,{className:m.tone==="good"?"border-emerald-500/20 bg-emerald-500/5":m.tone==="info"?"border-sky-500/20 bg-sky-500/5":"border-amber-500/20 bg-amber-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:m.title}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[m.description,m.targetVersion&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",m.targetVersion,m.channel?` (${m.channel})`:""]})]}),m.showButton?s.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:r,children:[s.jsx(zr,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:m.buttonLabel})]}):s.jsx("div",{className:m.tone==="good"?"text-xs font-medium text-emerald-300":"text-xs font-medium text-sky-300",children:"No preview update action is needed."})]})})]})]})}function LP({machineId:e,machine:t,ideSessions:n,cliSessions:a,acpSessions:r,actions:o,sendDaemonCommand:i}){const{workspaceBusy:c,handleWorkspaceAdd:u,handleWorkspaceRemove:p,handleWorkspaceSetDefault:d}=o,{t:m}=Ce("common"),[h,g]=l.useState(!1),[k,f]=l.useState(""),[x,w]=l.useState([]),[b,S]=l.useState(!1),[N,v]=l.useState(""),y=l.useCallback(async C=>{S(!0),v("");try{const A=await _l(i,e,C);f(A.path),w(A.directories)}catch(A){v(A instanceof Error?A.message:"Could not load folder")}finally{S(!1)}},[e,i]),j=l.useCallback(()=>{g(!0);const C=[...n.map(T=>T.workspace),...a.map(T=>T.workspace),...r.map(T=>T.workspace)],A=El(t.platform,Rl(C,t.defaultWorkspacePath,(t.workspaces||[]).map(T=>T.path)));y(A)},[r,a,n,y,t.defaultWorkspacePath,t.platform,t.workspaces]);return s.jsxs(s.Fragment,{children:[s.jsxs(ms,{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(Bn,{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(C=>{const A=C.id===t.defaultWorkspaceId;return s.jsxs("li",{className:`flex items-start gap-2 text-[11px] rounded-lg border px-2.5 py-2 transition-colors ${A?"border-yellow-500/30 bg-yellow-500/[0.05]":"border-border-subtle bg-bg-primary"}`,children:[s.jsx("button",{type:"button",title:A?"Default workspace — click to unset":"Set as default workspace",disabled:c,onClick:()=>void d(A?null:C.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:pp(C.path,C.label)}),s.jsx("div",{className:"font-mono text-text-muted truncate text-[10px]",title:C.path,children:C.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void p(C.id),children:m("machine.managedWorkspaces.remove")})]},C.id)})})]}),h&&s.jsx($l,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:k,directories:x,busy:b,error:N,confirmLabel:"Add workspace",onClose:()=>g(!1),onNavigate:C=>{y(C)},onConfirm:C=>{(async()=>{if(!C)return;await u(C)&&g(!1)})()}})]})}function RP({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(LP,{machineId:t,machine:e,ideSessions:n,cliSessions:a,acpSessions:r,actions:o,sendDaemonCommand:i})]})}function EP({onNicknameSynced:e}={}){var me,B,O,Y,se,Z,Ne,pe,fe,Me,Ee;const{t}=Ce("common"),{id:n}=If(),a=Ea(),r=tl(),{sendCommand:o}=kt(),i=Qn(),c=Dm(),u=Zp(),p=u.ides||[],d=u.initialLoaded??!0,m=p.find(q=>q.id===n&&q.type==="adhdev-daemon"),h=p.some(q=>q.type==="adhdev-daemon"),g=n?(me=u.connectionRetryStatuses)==null?void 0:me[n]:void 0,k=!!(g!=null&&g.blocked),[f,x]=l.useState("workspace"),[w,b]=l.useState(null),[S,N]=l.useState(null);l.useCallback((q,oe)=>{N({daemonId:q,workspace:oe})},[]);const[,v]=l.useState("ide"),y=l.useRef(null),[j,C]=l.useState(null),A=l.useRef("__home__"),[T,D]=l.useState("__home__"),[I,M]=l.useState(!1),P=l.useRef(null);l.useEffect(()=>{!n||!m||!(!m.workspaces||!m.availableProviders||!m.detectedIdes||!m.recentLaunches)||i(n,{minFreshMs:3e4}).catch(()=>{})},[i,m,n]),l.useEffect(()=>{if(!n||!m)return;let q=!1;return(async()=>{try{const oe=await o(n,"get_status_metadata"),Ie=oe&&typeof oe=="object"&&"result"in oe?oe.result:oe,xe=Ie==null?void 0:Ie.providerChannelStaleness;!q&&xe&&!xe.error&&b({staleTypes:Array.isArray(xe.staleTypes)?xe.staleTypes:[],newTypes:Array.isArray(xe.newTypes)?xe.newTypes:[]})}catch{}})(),()=>{q=!0}},[n,m==null?void 0:m.id,o]),l.useEffect(()=>{if(!n||!m||f!=="overview"&&f!=="providers")return;const q=m.machine;(typeof(q==null?void 0:q.cpus)!="number"||typeof(q==null?void 0:q.totalMem)!="number"||typeof(q==null?void 0:q.arch)!="string"||typeof(q==null?void 0:q.release)!="string"||f==="providers"&&!(q!=null&&q.quota))&&c(n,{minFreshMs:3e4}).catch(()=>{})},[f,c,m,n]),Cj(n&&f==="overview"?[n]:[],{enabled:f==="overview",intervalMs:Tk});const $=()=>{if(h){a("/dashboard",{state:{mobileSection:"machines"}});return}a("/machines")},L=AD({machineId:n,registeredMachineId:(m==null?void 0:m.machineId)||null,sendDaemonCommand:o,onNicknameSynced:e,logsEndRef:P});l.useEffect(()=>bt.onToast(oe=>{u.setToasts(xe=>{if(xe.some(Ae=>Ae.message===oe.message&&oe.timestamp-Ae.timestamp<3e3))return xe;const Ze={id:oe.id,message:oe.message,type:oe.type,timestamp:oe.timestamp,targetKey:oe.targetKey,actions:oe.actions};return[...xe.slice(-4),Ze]});const Ie=oe.duration||5e3;setTimeout(()=>u.setToasts(xe=>xe.filter(he=>he.id!==oe.id)),Ie)}),[u]);const R=(m==null?void 0:m.availableProviders)||[],F={};for(const q of R)F[q.type]=q.icon;const E=m?{id:m.id,hostname:mp(m,{fallbackId:m.id}),platform:((B=m.machine)==null?void 0:B.platform)||"unknown",arch:((O=m.machine)==null?void 0:O.arch)||"",cpus:((Y=m.machine)==null?void 0:Y.cpus)||0,totalMem:((se=m.machine)==null?void 0:se.totalMem)||0,freeMem:(Z=m.machine)==null?void 0:Z.freeMem,availableMem:(Ne=m.machine)==null?void 0:Ne.availableMem,loadavg:(pe=m.machine)==null?void 0:pe.loadavg,uptime:(fe=m.machine)==null?void 0:fe.uptime,release:((Me=m.machine)==null?void 0:Me.release)||"",cdpConnected:!!m.cdpConnected,machineNickname:m.machineNickname||null,...(Ee=m.machine)!=null&&Ee.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,H=p.filter(q=>q.daemonId===n&&q.type!=="adhdev-daemon").filter(q=>!Ma(q)&&!_n(q)).map(q=>({id:q.id,sessionId:q.sessionId,type:q.type,version:q.version||"",instanceId:q.instanceId||"",status:q.status,workspace:q.workspace||null,terminals:q.terminals||0,aiAgents:Hw(q.aiAgents||(q.agents||[]).map(oe=>({id:oe.name,name:oe.name,status:oe.status,version:oe.version}))),activeChat:q.activeChat||null,chats:q.chats||[],childSessions:q.childSessions||[],cdpConnected:q.cdpConnected||!1,daemonId:n,lastMessageAt:q.lastMessageAt})),_=p.filter(q=>q.daemonId===n&&Ma(q)).map(q=>({id:q.id,sessionId:q.sessionId,type:q.type,cliName:q.cliName||q.type,status:q.status,workspace:q.workspace||"",activeChat:q.activeChat||null,providerSessionId:q.providerSessionId,mode:q.mode,runtimeKey:q.runtimeKey,runtimeDisplayName:q.runtimeDisplayName,runtimeWorkspaceLabel:q.runtimeWorkspaceLabel,runtimeWriteOwner:q.runtimeWriteOwner||null,runtimeAttachedClients:q.runtimeAttachedClients||[],daemonId:n,lastMessageAt:q.lastMessageAt})),G=p.filter(q=>q.daemonId===n&&_n(q)).map(q=>({id:q.id,sessionId:q.sessionId,type:q.type,acpName:q.cliName||q.type,status:q.status,workspace:q.workspace||"",activeChat:q.activeChat||null,providerSessionId:q.providerSessionId,daemonId:n,lastMessageAt:q.lastMessageAt})),W=m?rs(m,{fallbackId:n}):"",K="workspace",V=r.state,te=V==null?void 0:V.initialMachineTab,le=V==null?void 0:V.initialWorkspaceCategory;V==null||V.initialWorkspaceId,V==null||V.initialWorkspacePath;const de=te==="ides"||te==="clis"||te==="acps"?"workspace":te||K,ee=te==="ides"?"ide":te==="clis"?"cli":te==="acps"?"acp":le,z=[...H.map(q=>{var oe;return{id:`ide:${q.type}:${q.workspace||""}`,label:((oe=q.activeChat)==null?void 0:oe.title)||q.type,kind:"ide",providerType:q.type,subtitle:q.workspace||void 0,workspace:q.workspace||void 0,lastLaunchedAt:q.lastMessageAt||0}}),..._.map(q=>{var oe;return{id:`cli:${q.type}:${q.workspace||""}`,label:((oe=q.activeChat)==null?void 0:oe.title)||q.cliName,kind:"cli",providerType:q.type,providerSessionId:q.providerSessionId,subtitle:q.workspace||void 0,workspace:q.workspace||void 0,lastLaunchedAt:q.lastMessageAt||0}}),...G.map(q=>{var oe;return{id:`acp:${q.type}:${q.workspace||""}`,label:((oe=q.activeChat)==null?void 0:oe.title)||q.acpName,kind:"acp",providerType:q.type,providerSessionId:q.providerSessionId,subtitle:xn(q.summaryMetadata)||q.workspace||void 0,workspace:q.workspace||void 0,lastLaunchedAt:q.lastMessageAt||0}})].sort((q,oe)=>(oe.lastLaunchedAt||0)-(q.lastLaunchedAt||0)),X=((m==null?void 0:m.recentLaunches)||[]).length>0?((m==null?void 0:m.recentLaunches)||[]).map(q=>({id:q.id,label:q.title||q.providerName||q.providerType,kind:q.kind,providerType:q.providerType,providerSessionId:q.providerSessionId,subtitle:xn(q.summaryMetadata)||q.workspace||void 0,workspace:q.workspace,summaryMetadata:q.summaryMetadata,lastLaunchedAt:q.lastLaunchedAt})):z,U=l.useMemo(()=>{var oe;const q=((oe=u.connectionStates)==null?void 0:oe[n||""])||void 0;return p.filter(Ie=>Ie.daemonId===n&&Ie.type!=="adhdev-daemon").flatMap(Ie=>Tl(Ie,{connectionStates:n&&q?{[n]:q}:void 0,defaultConnectionState:q})).filter(Ie=>!(Ie.transport==="pty"&&Ie.mode==="terminal")).sort((Ie,xe)=>Gi(xe)-Gi(Ie))},[p,u.connectionStates,n]),Q=l.useCallback(q=>{const oe=Um(q);oe&&a(Ia(oe))},[a]),ke=l.useCallback(()=>{y.current&&(M(!0),y.current().finally(()=>{y.current=null,M(!1),C(null)}))},[]),ve=l.useCallback(q=>{if(!E)return;const{options:oe,selectedKey:Ie}=Ym({machine:E,currentWorkspacePath:q.workspace,homeLabel:t("newSession.homeDirectory"),homeDescription:t("newSession.launchWithoutWorkspace")}),xe=async()=>{v(q.kind),x("workspace")};y.current=async()=>{const he=oe.find(_e=>_e.key===A.current),Ze=(he==null?void 0:he.workspacePath)??null,Ae=(he==null?void 0:he.workspaceId)??null;if(q.kind==="ide"&&q.providerType){await L.handleLaunchIde(q.providerType,Ze?{workspace:Ze}:void 0);return}if((q.kind==="cli"||q.kind==="acp")&&q.providerType){await L.runLaunchCliCore({cliType:q.providerType,dir:Ae?void 0:Ze||"",workspaceId:Ae||void 0,model:q.kind==="acp"&&fp(q.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:q.providerSessionId});return}await xe()},A.current=Ie,D(Ie),C({title:q.kind==="ide"?Ir(t,"restart-ide",q.label):q.providerSessionId?dm(t,q.label):Ir(t,"start-fresh",q.label),description:q.kind==="ide"?Lr(t,"restart-ide"):q.providerSessionId?um(t):Lr(t,"start-fresh"),confirmLabel:q.kind==="ide"?Rr(t,"restart-ide"):q.providerSessionId?Fi(t,!0):Rr(t,"start-fresh"),busyLabel:q.kind==="ide"?Er(t,"restart-ide"):q.providerSessionId?cm(t,!0):Er(t,"start-fresh"),workspaceOptions:oe,details:[{label:"Mode",value:q.kind.toUpperCase()},...q.providerType?[{label:"Provider",value:q.providerType}]:[]]})},[L,E]);if(l.useEffect(()=>{x(de)},[K,de,n]),l.useEffect(()=>{ee&&v(ee)},[ee,n]),!E)return d?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:t("machine.detail.notFound")}),s.jsx("p",{className:"mt-3",children:t("machine.detail.offlineHint")}),s.jsx("button",{onClick:$,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 ge=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(gs,{size:14})," ",t("machine.detail.tabWorkspace")]}),count:H.length+_.length+G.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ys,{size:14})," ",t("machine.detail.tabHostedRuntimes")]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Gr,{size:14})," ",t("machine.detail.tabProviders")]}),...w&&w.staleTypes.length+w.newTypes.length>0?{count:w.staleTypes.length+w.newTypes.length}:{}},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Cb,{size:14})," ",t("machine.detail.tabSystem")]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Fu,{size:14})," ",t("machine.detail.tabLogs")]})}];return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[s.jsx("div",{className:"flex items-center justify-between w-full",children:s.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[s.jsx("button",{onClick:$,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[L.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:L.nicknameInput,onChange:q=>L.setNicknameInput(q.target.value),onKeyDown:q=>{q.key==="Enter"&&L.handleSaveNickname(),q.key==="Escape"&&L.setEditingNickname(!1)},placeholder:t("machine.detail.nicknamePlaceholder"),className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:L.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:t("machine.detail.save")}),s.jsx("button",{onClick:()=>L.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:t("machine.detail.cancel")})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{L.setEditingNickname(!0),L.setNicknameInput(E.machineNickname||"")},title:t("machine.detail.clickToSetNickname"),children:W}),k?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),u.retryConnection&&n&&s.jsx("button",{onClick:()=>u.retryConnection(n),className:"px-2.5 py-0.5 rounded text-[11px] font-semibold bg-red-500/10 border border-red-500/20 text-red-400 hover:bg-red-500/20 transition-colors",children:t("machine.detail.reconnect")})]}):s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[s.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[E.platform," · ",E.arch]}),s.jsx("span",{children:t("machine.detail.coresCount",{count:E.cpus})}),(m==null?void 0:m.version)&&s.jsxs("span",{children:["v",m.version]}),E.p2p.available&&s.jsx("span",{children:t("machine.detail.p2pState",{state:E.p2p.state==="connected"?t("machine.detail.p2pConnected"):E.p2p.state})}),E.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:E.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:ge.map(q=>s.jsxs("button",{onClick:()=>x(q.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${f===q.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[q.label,q.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${f===q.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:q.count})]},q.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[f==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(IP,{machineEntry:m,providers:R,recentLaunches:X,currentConversations:U,onUpgradeDaemon:async()=>{const q=ao(m);if(q)try{await o(n,"daemon_upgrade",q)}catch{}},onOpenRecent:ve,onOpenConversation:Q}),s.jsx(RP,{machine:E,machineId:n,ideSessions:H,cliSessions:_,acpSessions:G,actions:L,sendDaemonCommand:o})]}),f==="providers"&&s.jsx(WD,{machineId:n,providers:R,sendDaemonCommand:o,quota:E.quota}),f==="overview"&&s.jsx(MD,{machine:E,ideSessions:H,cliSessions:_,acpSessions:G}),f==="session-host"&&s.jsx(MP,{machineId:n,cliSessions:_,sendDaemonCommand:o}),f==="logs"&&s.jsx(kP,{machineId:n,sendDaemonCommand:o})]})})}),L.launchPick&&E&&s.jsx(DP,{machine:E,launchPick:L.launchPick,actions:L}),j&&s.jsx(ro,{title:j.title,description:j.description,details:j.details,workspaceOptions:j.workspaceOptions,selectedWorkspaceKey:T,onWorkspaceChange:q=>{A.current=q,D(q)},confirmLabel:j.confirmLabel,busyLabel:j.busyLabel,busy:I,onConfirm:ke,onCancel:()=>{y.current=null,C(null)}}),S&&s.jsx(Qh,{daemonId:S.daemonId,workspace:S.workspace,onClose:()=>N(null)}),s.jsx(mm,{toasts:u.toasts||[],onDismiss:q=>u.setToasts(oe=>oe.filter(Ie=>Ie.id!==q)),onClickToast:q=>{q.targetKey&&a(Ia(q.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 I=await n(e,"session_host_prune_duplicate_sessions",{}),M=di(I);if(!(M!=null&&M.success))throw new Error((M==null?void 0:M.error)||"Duplicate prune failed");const P=M.result||{},$=Array.isArray(P.prunedSessionIds)?P.prunedSessionIds.length:0,L=typeof P.duplicateGroupCount=="number"?P.duplicateGroupCount:0;bt.showToast(`Pruned ${$} duplicate runtime(s) across ${L} group(s)`,"success"),await f()}catch(I){const M=I instanceof Error?I.message:"Duplicate prune failed";bt.showToast(M,"warning"),r(M)}finally{i(I=>I==="session_host_prune_duplicate_sessions"?null:I)}}},[e,f,n]),b=l.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((D,I)=>(I.lastActivityAt||0)-(D.lastActivityAt||0)),[d==null?void 0:d.sessions]),S=l.useMemo(()=>d!=null&&d.liveRuntimes||d!=null&&d.recoverySnapshots||d!=null&&d.inactiveRecords?{liveRuntimes:(d==null?void 0:d.liveRuntimes)||[],recoverySnapshots:(d==null?void 0:d.recoverySnapshots)||[],inactiveRecords:(d==null?void 0:d.inactiveRecords)||[]}:CP(b),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,b]),N=S.liveRuntimes,v=S.recoverySnapshots,y=S.inactiveRecords,j=l.useMemo(()=>TP(N),[N]),C=l.useMemo(()=>[...(d==null?void 0:d.recentTransitions)||[]].slice(-6).reverse(),[d==null?void 0:d.recentTransitions]),A=l.useMemo(()=>[...(d==null?void 0:d.recentLogs)||[]].reverse().find(D=>D.level==="warn"||D.level==="error")||null,[d==null?void 0:d.recentLogs]),T=(D,I)=>{var _;const M=o===`session_host_resume_session:${D.sessionId}`,P=o===`session_host_restart_session:${D.sessionId}`,$=o===`session_host_stop_session:${D.sessionId}`,L=Xh(D.meta),R=k.get(D.sessionId),F=D.attachedClients.length===1?"1 client":`${D.attachedClients.length} clients`,E=I==="recovery"?"Recover":"Resume",H=jP(I);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:D.displayName||(R==null?void 0:R.cliName)||D.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${AP(D.lifecycle)}`,children:D.lifecycle}),L&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:L})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:D.workspaceLabel||(R==null?void 0:R.runtimeWorkspaceLabel)||D.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:D.runtimeKey}),D.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",D.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((_=D.writeOwner)==null?void 0:_.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:NP(D.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(Hu,{size:11})," ",F]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",du(D.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:[I==="recovery"&&(D.lifecycle==="interrupted"||D.lifecycle==="failed"||D.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{x("session_host_resume_session",D)},children:M?`${E}ing…`:E}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{x("session_host_restart_session",D)},children:P?"Restarting…":"Restart"}),I==="live"&&(D.lifecycle==="running"||D.lifecycle==="starting"||D.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!o,onClick:()=>{x("session_host_stop_session",D)},children:$?"Stopping…":"Stop"})]})]})},D.sessionId)};return s.jsxs(ms,{padding:"lg",className:"mb-5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(Ys,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:oC()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[j>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{w()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${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:()=>{f()},disabled:m||c,children:[s.jsx(zr,{size:13}),m||c?"Refreshing…":"Refresh"]})]})]}),a&&!d&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(gn,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:a})]})]})}),d&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:d.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:v.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:d.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:du(d.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:ui(d.hostStartedAt)})]})]}),A&&s.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[s.jsx(gn,{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:[ui(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(ll,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ci("live")}),N.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:N.map(D=>T(D,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(Ys,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ci("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(D=>T(D,"recovery"))})]}),y.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ci("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:y.map(D=>T(D,"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"}),C.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:C.map(D=>{var M;const I=b.find(P=>P.sessionId===D.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:(I==null?void 0:I.displayName)||((M=k.get(D.sessionId))==null?void 0:M.cliName)||D.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[D.action,D.lifecycle?` · ${D.lifecycle}`:"",D.detail?` · ${D.detail}`:"",D.error?` · ${D.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${D.success===!1?"text-red-300":"text-text-secondary"}`,children:ui(D.timestamp)})]},`${D.sessionId}:${D.timestamp}:${D.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:d.endpoint||"unknown"}),a?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",a]}):null]})]})]})}function DP({machine:e,launchPick:t,actions:n}){const{t:a}=Ce("common"),{runLaunchCliCore:r,setLaunchPick:o}=n;return l.useEffect(()=>{const i=c=>{c.key==="Escape"&&o(null)};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[o]),s.jsx(Yt,{children:s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",onClick:()=>o(null),children:s.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",onClick:i=>i.stopPropagation(),children:[s.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),s.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),s.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?s.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(i=>s.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{o(null),r({cliType:t.cliType,workspaceId:i.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{o(null),r({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:a("newSession.defaultWorkspace")}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{o(null),r({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:a("newSession.homeDirectory")}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>o(null),children:"Cancel"})]})]})})})}function PP(e,t){const n=JC(e),a=qs(e,t),r=no(e,a),o=wa(e,a),i=jm(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 pi({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 mi({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 IP({machineEntry:e,providers:t,recentLaunches:n,currentConversations:a,onUpgradeDaemon:r,onOpenRecent:o,onOpenConversation:i}){const{t:c}=Ce("common"),u=a.slice(0,6),p=n.slice(0,4),m=PP(e,"1.0.42");return s.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[u.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(pi,{icon:s.jsx(kn,{size:13}),children:c("machine.commandCenter.currentChats")}),s.jsx(mi,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(h=>{const g=Gi(h);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>i(h),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:wt(h)}),g>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Kr(g)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:On(h)})]},h.tabKey)})})})]}),p.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(pi,{icon:s.jsx(Ou,{size:13}),children:c("machine.commandCenter.recentLaunches")}),s.jsx(mi,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:p.map(h=>{const{metaText:g,updatedLabel:k}=Qm(h);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>o(h),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:h.label}),k&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:k})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:g})]},h.id)})})})]}),m.visible&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(pi,{icon:s.jsx(gn,{size:13}),children:c("machine.commandCenter.daemonUpdate")}),s.jsx(mi,{className:m.tone==="good"?"border-emerald-500/20 bg-emerald-500/5":m.tone==="info"?"border-sky-500/20 bg-sky-500/5":"border-amber-500/20 bg-amber-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:m.title}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[m.description,m.targetVersion&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",m.targetVersion,m.channel?` (${m.channel})`:""]})]}),m.showButton?s.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:r,children:[s.jsx(zr,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:m.buttonLabel})]}):s.jsx("div",{className:m.tone==="good"?"text-xs font-medium text-emerald-300":"text-xs font-medium text-sky-300",children:"No preview update action is needed."})]})})]})]})}function LP({machineId:e,machine:t,ideSessions:n,cliSessions:a,acpSessions:r,actions:o,sendDaemonCommand:i}){const{workspaceBusy:c,handleWorkspaceAdd:u,handleWorkspaceRemove:p,handleWorkspaceSetDefault:d}=o,{t:m}=Ce("common"),[h,g]=l.useState(!1),[k,f]=l.useState(""),[x,w]=l.useState([]),[b,S]=l.useState(!1),[N,v]=l.useState(""),y=l.useCallback(async C=>{S(!0),v("");try{const A=await _l(i,e,C);f(A.path),w(A.directories)}catch(A){v(A instanceof Error?A.message:"Could not load folder")}finally{S(!1)}},[e,i]),j=l.useCallback(()=>{g(!0);const C=[...n.map(T=>T.workspace),...a.map(T=>T.workspace),...r.map(T=>T.workspace)],A=El(t.platform,Rl(C,t.defaultWorkspacePath,(t.workspaces||[]).map(T=>T.path)));y(A)},[r,a,n,y,t.defaultWorkspacePath,t.platform,t.workspaces]);return s.jsxs(s.Fragment,{children:[s.jsxs(ms,{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(Bn,{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(C=>{const A=C.id===t.defaultWorkspaceId;return s.jsxs("li",{className:`flex items-start gap-2 text-[11px] rounded-lg border px-2.5 py-2 transition-colors ${A?"border-yellow-500/30 bg-yellow-500/[0.05]":"border-border-subtle bg-bg-primary"}`,children:[s.jsx("button",{type:"button",title:A?"Default workspace — click to unset":"Set as default workspace",disabled:c,onClick:()=>void d(A?null:C.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:pp(C.path,C.label)}),s.jsx("div",{className:"font-mono text-text-muted truncate text-[10px]",title:C.path,children:C.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void p(C.id),children:m("machine.managedWorkspaces.remove")})]},C.id)})})]}),h&&s.jsx($l,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:k,directories:x,busy:b,error:N,confirmLabel:"Add workspace",onClose:()=>g(!1),onNavigate:C=>{y(C)},onConfirm:C=>{(async()=>{if(!C)return;await u(C)&&g(!1)})()}})]})}function RP({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(LP,{machineId:t,machine:e,ideSessions:n,cliSessions:a,acpSessions:r,actions:o,sendDaemonCommand:i})]})}function EP({onNicknameSynced:e}={}){var me,B,O,Y,se,Z,Ne,pe,fe,Me,Ee;const{t}=Ce("common"),{id:n}=If(),a=Ea(),r=tl(),{sendCommand:o}=kt(),i=Qn(),c=Dm(),u=Zp(),p=u.ides||[],d=u.initialLoaded??!0,m=p.find(q=>q.id===n&&q.type==="adhdev-daemon"),h=p.some(q=>q.type==="adhdev-daemon"),g=n?(me=u.connectionRetryStatuses)==null?void 0:me[n]:void 0,k=!!(g!=null&&g.blocked),[f,x]=l.useState("workspace"),[w,b]=l.useState(null),[S,N]=l.useState(null);l.useCallback((q,oe)=>{N({daemonId:q,workspace:oe})},[]);const[,v]=l.useState("ide"),y=l.useRef(null),[j,C]=l.useState(null),A=l.useRef("__home__"),[T,D]=l.useState("__home__"),[I,M]=l.useState(!1),P=l.useRef(null);l.useEffect(()=>{!n||!m||!(!m.workspaces||!m.availableProviders||!m.detectedIdes||!m.recentLaunches)||i(n,{minFreshMs:3e4}).catch(()=>{})},[i,m,n]),l.useEffect(()=>{if(!n||!m)return;let q=!1;return(async()=>{try{const oe=await o(n,"get_status_metadata"),Ie=oe&&typeof oe=="object"&&"result"in oe?oe.result:oe,xe=Ie==null?void 0:Ie.providerChannelStaleness;!q&&xe&&!xe.error&&b({staleTypes:Array.isArray(xe.staleTypes)?xe.staleTypes:[],newTypes:Array.isArray(xe.newTypes)?xe.newTypes:[]})}catch{}})(),()=>{q=!0}},[n,m==null?void 0:m.id,o]),l.useEffect(()=>{if(!n||!m||f!=="overview"&&f!=="providers")return;const q=m.machine;(typeof(q==null?void 0:q.cpus)!="number"||typeof(q==null?void 0:q.totalMem)!="number"||typeof(q==null?void 0:q.arch)!="string"||typeof(q==null?void 0:q.release)!="string"||f==="providers"&&!(q!=null&&q.quota))&&c(n,{minFreshMs:3e4}).catch(()=>{})},[f,c,m,n]),Cj(n&&f==="overview"?[n]:[],{enabled:f==="overview",intervalMs:Tk});const $=()=>{if(h){a("/dashboard",{state:{mobileSection:"machines"}});return}a("/machines")},L=AD({machineId:n,registeredMachineId:(m==null?void 0:m.machineId)||null,sendDaemonCommand:o,onNicknameSynced:e,logsEndRef:P});l.useEffect(()=>bt.onToast(oe=>{u.setToasts(xe=>{if(xe.some(Ae=>Ae.message===oe.message&&oe.timestamp-Ae.timestamp<3e3))return xe;const Ze={id:oe.id,message:oe.message,type:oe.type,timestamp:oe.timestamp,targetKey:oe.targetKey,actions:oe.actions};return[...xe.slice(-4),Ze]});const Ie=oe.duration||5e3;setTimeout(()=>u.setToasts(xe=>xe.filter(he=>he.id!==oe.id)),Ie)}),[u]);const R=(m==null?void 0:m.availableProviders)||[],F={};for(const q of R)F[q.type]=q.icon;const E=m?{id:m.id,hostname:mp(m,{fallbackId:m.id}),platform:((B=m.machine)==null?void 0:B.platform)||"unknown",arch:((O=m.machine)==null?void 0:O.arch)||"",cpus:((Y=m.machine)==null?void 0:Y.cpus)||0,totalMem:((se=m.machine)==null?void 0:se.totalMem)||0,freeMem:(Z=m.machine)==null?void 0:Z.freeMem,availableMem:(Ne=m.machine)==null?void 0:Ne.availableMem,loadavg:(pe=m.machine)==null?void 0:pe.loadavg,uptime:(fe=m.machine)==null?void 0:fe.uptime,release:((Me=m.machine)==null?void 0:Me.release)||"",cdpConnected:!!m.cdpConnected,machineNickname:m.machineNickname||null,...(Ee=m.machine)!=null&&Ee.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,H=p.filter(q=>q.daemonId===n&&q.type!=="adhdev-daemon").filter(q=>!Ma(q)&&!_n(q)).map(q=>({id:q.id,sessionId:q.sessionId,type:q.type,version:q.version||"",instanceId:q.instanceId||"",status:q.status,workspace:q.workspace||null,terminals:q.terminals||0,aiAgents:Hw(q.aiAgents||(q.agents||[]).map(oe=>({id:oe.name,name:oe.name,status:oe.status,version:oe.version}))),activeChat:q.activeChat||null,chats:q.chats||[],childSessions:q.childSessions||[],cdpConnected:q.cdpConnected||!1,daemonId:n,lastMessageAt:q.lastMessageAt})),_=p.filter(q=>q.daemonId===n&&Ma(q)).map(q=>({id:q.id,sessionId:q.sessionId,type:q.type,cliName:q.cliName||q.type,status:q.status,workspace:q.workspace||"",activeChat:q.activeChat||null,providerSessionId:q.providerSessionId,mode:q.mode,runtimeKey:q.runtimeKey,runtimeDisplayName:q.runtimeDisplayName,runtimeWorkspaceLabel:q.runtimeWorkspaceLabel,runtimeWriteOwner:q.runtimeWriteOwner||null,runtimeAttachedClients:q.runtimeAttachedClients||[],daemonId:n,lastMessageAt:q.lastMessageAt})),G=p.filter(q=>q.daemonId===n&&_n(q)).map(q=>({id:q.id,sessionId:q.sessionId,type:q.type,acpName:q.cliName||q.type,status:q.status,workspace:q.workspace||"",activeChat:q.activeChat||null,providerSessionId:q.providerSessionId,daemonId:n,lastMessageAt:q.lastMessageAt})),W=m?rs(m,{fallbackId:n}):"",K="workspace",V=r.state,te=V==null?void 0:V.initialMachineTab,le=V==null?void 0:V.initialWorkspaceCategory;V==null||V.initialWorkspaceId,V==null||V.initialWorkspacePath;const de=te==="ides"||te==="clis"||te==="acps"?"workspace":te||K,ee=te==="ides"?"ide":te==="clis"?"cli":te==="acps"?"acp":le,z=[...H.map(q=>{var oe;return{id:`ide:${q.type}:${q.workspace||""}`,label:((oe=q.activeChat)==null?void 0:oe.title)||q.type,kind:"ide",providerType:q.type,subtitle:q.workspace||void 0,workspace:q.workspace||void 0,lastLaunchedAt:q.lastMessageAt||0}}),..._.map(q=>{var oe;return{id:`cli:${q.type}:${q.workspace||""}`,label:((oe=q.activeChat)==null?void 0:oe.title)||q.cliName,kind:"cli",providerType:q.type,providerSessionId:q.providerSessionId,subtitle:q.workspace||void 0,workspace:q.workspace||void 0,lastLaunchedAt:q.lastMessageAt||0}}),...G.map(q=>{var oe;return{id:`acp:${q.type}:${q.workspace||""}`,label:((oe=q.activeChat)==null?void 0:oe.title)||q.acpName,kind:"acp",providerType:q.type,providerSessionId:q.providerSessionId,subtitle:xn(q.summaryMetadata)||q.workspace||void 0,workspace:q.workspace||void 0,lastLaunchedAt:q.lastMessageAt||0}})].sort((q,oe)=>(oe.lastLaunchedAt||0)-(q.lastLaunchedAt||0)),X=((m==null?void 0:m.recentLaunches)||[]).length>0?((m==null?void 0:m.recentLaunches)||[]).map(q=>({id:q.id,label:q.title||q.providerName||q.providerType,kind:q.kind,providerType:q.providerType,providerSessionId:q.providerSessionId,subtitle:xn(q.summaryMetadata)||q.workspace||void 0,workspace:q.workspace,summaryMetadata:q.summaryMetadata,lastLaunchedAt:q.lastLaunchedAt})):z,U=l.useMemo(()=>{var oe;const q=((oe=u.connectionStates)==null?void 0:oe[n||""])||void 0;return p.filter(Ie=>Ie.daemonId===n&&Ie.type!=="adhdev-daemon").flatMap(Ie=>Tl(Ie,{connectionStates:n&&q?{[n]:q}:void 0,defaultConnectionState:q})).filter(Ie=>!(Ie.transport==="pty"&&Ie.mode==="terminal")).sort((Ie,xe)=>Gi(xe)-Gi(Ie))},[p,u.connectionStates,n]),Q=l.useCallback(q=>{const oe=Um(q);oe&&a(Ia(oe))},[a]),ke=l.useCallback(()=>{y.current&&(M(!0),y.current().finally(()=>{y.current=null,M(!1),C(null)}))},[]),ve=l.useCallback(q=>{if(!E)return;const{options:oe,selectedKey:Ie}=Ym({machine:E,currentWorkspacePath:q.workspace,homeLabel:t("newSession.homeDirectory"),homeDescription:t("newSession.launchWithoutWorkspace")}),xe=async()=>{v(q.kind),x("workspace")};y.current=async()=>{const he=oe.find(_e=>_e.key===A.current),Ze=(he==null?void 0:he.workspacePath)??null,Ae=(he==null?void 0:he.workspaceId)??null;if(q.kind==="ide"&&q.providerType){await L.handleLaunchIde(q.providerType,Ze?{workspace:Ze}:void 0);return}if((q.kind==="cli"||q.kind==="acp")&&q.providerType){await L.runLaunchCliCore({cliType:q.providerType,dir:Ae?void 0:Ze||"",workspaceId:Ae||void 0,model:q.kind==="acp"&&fp(q.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:q.providerSessionId});return}await xe()},A.current=Ie,D(Ie),C({title:q.kind==="ide"?Ir(t,"restart-ide",q.label):q.providerSessionId?dm(t,q.label):Ir(t,"start-fresh",q.label),description:q.kind==="ide"?Lr(t,"restart-ide"):q.providerSessionId?um(t):Lr(t,"start-fresh"),confirmLabel:q.kind==="ide"?Rr(t,"restart-ide"):q.providerSessionId?Fi(t,!0):Rr(t,"start-fresh"),busyLabel:q.kind==="ide"?Er(t,"restart-ide"):q.providerSessionId?cm(t,!0):Er(t,"start-fresh"),workspaceOptions:oe,details:[{label:"Mode",value:q.kind.toUpperCase()},...q.providerType?[{label:"Provider",value:q.providerType}]:[]]})},[L,E]);if(l.useEffect(()=>{x(de)},[K,de,n]),l.useEffect(()=>{ee&&v(ee)},[ee,n]),!E)return d?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:t("machine.detail.notFound")}),s.jsx("p",{className:"mt-3",children:t("machine.detail.offlineHint")}),s.jsx("button",{onClick:$,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 ge=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(gs,{size:14})," ",t("machine.detail.tabWorkspace")]}),count:H.length+_.length+G.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ys,{size:14})," ",t("machine.detail.tabHostedRuntimes")]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Gr,{size:14})," ",t("machine.detail.tabProviders")]}),...w&&w.staleTypes.length+w.newTypes.length>0?{count:w.staleTypes.length+w.newTypes.length}:{}},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Cb,{size:14})," ",t("machine.detail.tabSystem")]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Fu,{size:14})," ",t("machine.detail.tabLogs")]})}];return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[s.jsx("div",{className:"flex items-center justify-between w-full",children:s.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[s.jsx("button",{onClick:$,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[L.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:L.nicknameInput,onChange:q=>L.setNicknameInput(q.target.value),onKeyDown:q=>{q.key==="Enter"&&L.handleSaveNickname(),q.key==="Escape"&&L.setEditingNickname(!1)},placeholder:t("machine.detail.nicknamePlaceholder"),className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:L.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:t("machine.detail.save")}),s.jsx("button",{onClick:()=>L.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:t("machine.detail.cancel")})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{L.setEditingNickname(!0),L.setNicknameInput(E.machineNickname||"")},title:t("machine.detail.clickToSetNickname"),children:W}),k?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),u.retryConnection&&n&&s.jsx("button",{onClick:()=>u.retryConnection(n),className:"px-2.5 py-0.5 rounded text-[11px] font-semibold bg-red-500/10 border border-red-500/20 text-red-400 hover:bg-red-500/20 transition-colors",children:t("machine.detail.reconnect")})]}):s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[s.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[E.platform," · ",E.arch]}),s.jsx("span",{children:t("machine.detail.coresCount",{count:E.cpus})}),(m==null?void 0:m.version)&&s.jsxs("span",{children:["v",m.version]}),E.p2p.available&&s.jsx("span",{children:t("machine.detail.p2pState",{state:E.p2p.state==="connected"?t("machine.detail.p2pConnected"):E.p2p.state})}),E.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:E.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:ge.map(q=>s.jsxs("button",{onClick:()=>x(q.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${f===q.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[q.label,q.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${f===q.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:q.count})]},q.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[f==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(IP,{machineEntry:m,providers:R,recentLaunches:X,currentConversations:U,onUpgradeDaemon:async()=>{const q=ao(m);if(q)try{await o(n,"daemon_upgrade",q)}catch{}},onOpenRecent:ve,onOpenConversation:Q}),s.jsx(RP,{machine:E,machineId:n,ideSessions:H,cliSessions:_,acpSessions:G,actions:L,sendDaemonCommand:o})]}),f==="providers"&&s.jsx(WD,{machineId:n,providers:R,sendDaemonCommand:o,quota:E.quota}),f==="overview"&&s.jsx(MD,{machine:E,ideSessions:H,cliSessions:_,acpSessions:G}),f==="session-host"&&s.jsx(MP,{machineId:n,cliSessions:_,sendDaemonCommand:o}),f==="logs"&&s.jsx(kP,{machineId:n,sendDaemonCommand:o})]})})}),L.launchPick&&E&&s.jsx(DP,{machine:E,launchPick:L.launchPick,actions:L}),j&&s.jsx(ro,{title:j.title,description:j.description,details:j.details,workspaceOptions:j.workspaceOptions,selectedWorkspaceKey:T,onWorkspaceChange:q=>{A.current=q,D(q)},confirmLabel:j.confirmLabel,busyLabel:j.busyLabel,busy:I,onConfirm:ke,onCancel:()=>{y.current=null,C(null)}}),S&&s.jsx(Qh,{daemonId:S.daemonId,workspace:S.workspace,onClose:()=>N(null)}),s.jsx(mm,{toasts:u.toasts||[],onDismiss:q=>u.setToasts(oe=>oe.filter(Ie=>Ie.id!==q)),onClickToast:q=>{q.targetKey&&a(Ia(q.targetKey))}}),s.jsx("style",{children:`
|
|
115
115
|
@keyframes toast-in {
|
|
116
116
|
from { opacity: 0; transform: translateX(40px); }
|
|
117
117
|
to { opacity: 1; transform: translateX(0); }
|
|
118
118
|
}
|
|
119
119
|
`})]})}function _P({daemonIds:e,meshId:t,sendData:n,onRevisionAdvance:a}){const r=l.useRef(new Map),o=l.useRef(a);o.current=a;const i=[...new Set(e.filter(Boolean))].sort().join(",");l.useEffect(()=>{r.current=new Map},[i,t]),l.useEffect(()=>{if(!t||!n)return;const c=[...new Set(e.filter(Boolean))];if(c.length===0)return;const u=c.map(p=>hs.subscribe({sendData:n},p,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${p}`,params:{includeSessions:!0}},d=>{if(d.topic!=="daemon.metadata")return;const m=d.meshStateRevisions;if(!m)return;const h=m[t]??m["*"];if(typeof h!="number")return;const g=r.current.get(p);r.current.set(p,h),g!==void 0&&h>g&&o.current()}));return()=>{for(const p of u)p()}},[i,t,n])}const HP={meshHostDaemonSection:!1,createDaemonPicker:!1,addNodeDaemonPicker:!1,queueSection:!0,coordinatorPrompt:!0,nodeInstruction:!0,hermesMcpConfig:!0,reviewInbox:!0},Zh=l.createContext(null);function $P(){const e=l.useContext(Zh);if(!e)throw new Error("useRepoMeshContext must be used inside RepoMeshProvider");return e}function FP({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 BP({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),s.jsx("circle",{cx:"18",cy:"6",r:"3"}),s.jsx("circle",{cx:"6",cy:"18",r:"3"}),s.jsx("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}function WP({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("polyline",{points:"3 6 5 6 21 6"}),s.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]})}function OP({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function UP({status:e}){const n={online:{color:"#22c55e",label:"Online"},dirty:{color:"#f59e0b",label:"Dirty",title:"Workspace has uncommitted changes"},offline:{color:"#6b7280",label:"Offline"},degraded:{color:"#ef4444",label:"Degraded",title:"P2P connection to this node is down or timed out — often transient. Wait and retry, or re-establish the node's connection."},enabled:{color:"#22c55e",label:"Enabled"},pending:{color:"#a855f7",label:"Pending"},assigned:{color:"#3b82f6",label:"Assigned"},completed:{color:"#22c55e",label:"Completed"},failed:{color:"#ef4444",label:"Failed"},unknown:{color:"#6b7280",label:"Unknown"}}[e]||{color:"#6b7280",label:e};return s.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] font-semibold px-2 py-0.5 rounded-md",style:{background:n.color+"15",color:n.color,border:`1px solid ${n.color}25`},title:n.title,children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full",style:{background:n.color}}),n.label]})}function qP(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function GP({meshes:e,loading:t,error:n,onDismissError:a,daemons:r,features:o,showCreate:i,onToggleCreate:c,createName:u,onCreateNameChange:p,createRepoIdentity:d,onCreateRepoIdentityChange:m,createRepoRemoteUrl:h,onCreateRepoRemoteUrlChange:g,newMeshDaemonId:k,onNewMeshDaemonIdChange:f,newMeshWorkspace:x,onNewMeshWorkspaceChange:w,createPickerWorkspaces:b,createOnboardingPlan:S,createPlanLoading:N,creating:v,createWarning:y,onDismissCreateWarning:j,onSelectMesh:C,onCreate:A,onCancelCreate:T}){var L,R;const{t:D}=Ce("common"),I=o.maxMeshes!=null&&e.length>=o.maxMeshes,[M,P]=l.useState(!1),$=M||!!d.trim();return s.jsxs(Fa,{icon:s.jsx(as,{}),title:D("repoMesh.list.title"),subtitle:D("repoMesh.list.count",{count:e.length}),widthClassName:"max-w-5xl",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:c,disabled:I,title:I?D("repoMesh.list.meshLimitReached",{max:o.maxMeshes}):void 0,children:D("repoMesh.list.createMesh")}),children:[I&&s.jsx(Dt,{variant:"info",className:"mb-4",children:D("repoMesh.list.meshLimitBanner",{max:o.maxMeshes})}),n&&s.jsx(Dt,{variant:"error",onDismiss:a,className:"mb-4",children:n}),y&&s.jsx(Dt,{variant:"warning",onDismiss:j,className:"mb-4",children:y}),i&&s.jsxs(gt,{className:"mb-5 border-accent/40 animate-[fadeIn_0.3s_ease-out]",children:[s.jsx("h3",{className:"text-base font-bold mb-4",children:D("repoMesh.list.createTitle")}),o.createDaemonPicker&&s.jsx(Nt,{label:D("repoMesh.list.createOnMachine"),hint:D("repoMesh.list.createOnMachineHint"),children:s.jsx("select",{className:"input w-full",value:k,onChange:F=>f(F.target.value),disabled:!r.length,children:r.length===0?s.jsx("option",{value:"",children:D("repoMesh.list.noConnectedDaemon")}):r.map(F=>s.jsx("option",{value:F.id,children:qP(F)},F.id))})}),o.createDaemonPicker&&(N||S)&&s.jsx(Dt,{variant:(S==null?void 0:S.success)===!1?"error":"info",className:"mb-4",children:N?"Inspecting Git repository (read-only)…":S!=null&&S.success?`${((L=S.plan)==null?void 0:L.summary)||"Git repository detected."} No changes will be made until you click Create.`:`${(S==null?void 0:S.code)||"onboarding_blocked"}: ${(S==null?void 0:S.error)||"Git discovery failed"} ${(S==null?void 0:S.action)||""}`}),o.createDaemonPicker&&s.jsx(Nt,{label:D("repoMesh.list.workspace"),hint:D("repoMesh.list.workspaceHint"),children:s.jsx("select",{className:"input w-full",value:x,onChange:F=>w(F.target.value),disabled:!k||!b.length,children:k?b.length===0?s.jsx("option",{value:"",children:D("repoMesh.list.noRegisteredWorkspaces")}):b.map(F=>s.jsx("option",{value:F.path,children:F.label?`${F.label} · ${F.path}`:F.path},F.id||F.path)):s.jsx("option",{value:"",children:D("repoMesh.list.selectMachineFirst")})})}),s.jsx(Nt,{label:D("repoMesh.list.name"),children:s.jsx(ps,{value:u,onChange:F=>p(F.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(Nt,{label:D("repoMesh.list.remoteUrl"),hint:D("repoMesh.list.remoteUrlHint"),children:s.jsx(ps,{value:h,onChange:F=>g(F.target.value),placeholder:"https://github.com/user/repo"})}),$?s.jsx(Nt,{label:D("repoMesh.list.repoIdentity"),hint:D("repoMesh.list.repoIdentityHint"),children:s.jsx(ps,{value:d,onChange:F=>m(F.target.value),placeholder:"github.com/user/repo"})}):s.jsx("button",{type:"button",className:"text-xs text-text-muted hover:text-text-primary underline underline-offset-2 mb-5",onClick:()=>P(!0),children:D("repoMesh.list.advancedIdentityToggle")}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:A,disabled:v||N||(S==null?void 0:S.success)===!1||(S==null?void 0:S.success)===!0&&((R=S==null?void 0:S.plan)==null?void 0:R.kind)!=="create_mesh_and_onboard"||!u.trim()||!h.trim()&&!d.trim()||o.createDaemonPicker&&(!k||!x),children:D(v?"repoMesh.list.creating":"repoMesh.list.create")}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:T,disabled:v,children:D("repoMesh.list.cancel")})]})]}),t?s.jsx("div",{className:"text-sm text-text-muted p-4",children:D("repoMesh.list.loading")}):e.length===0?s.jsx(so,{icon:s.jsx(as,{}),title:D("repoMesh.list.emptyTitle"),description:r.length>0?D("repoMesh.list.emptyWithDaemons"):D("repoMesh.list.emptyNoDaemons"),action:s.jsx("button",{className:"btn btn-primary btn-sm",disabled:!r.length,onClick:c,children:D("repoMesh.list.createFirst")})}):s.jsx("div",{className:"flex flex-col gap-2.5",children:e.map(F=>{var E;return s.jsx("button",{type:"button",onClick:()=>C(F.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(as,{size:16}),s.jsx("span",{className:"font-bold text-sm",children:F.name})]}),s.jsxs("div",{className:"text-[12px] text-text-muted flex items-center gap-2",children:[s.jsx("span",{className:"font-mono",children:F.repoIdentity||F.repo_identity||D("repoMesh.list.noRepoIdentity")}),(F.defaultBranch||F.default_branch)&&s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(BP,{size:11}),F.defaultBranch||F.default_branch]})]})]}),s.jsxs("div",{className:"text-right text-[11px] text-text-muted shrink-0 ml-4",children:[s.jsx("div",{children:new Date(F.createdAt||F.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})}),s.jsxs("div",{className:"text-text-muted/60",children:[((E=F.nodes)==null?void 0:E.length)??F.nodeCount??0," ",D("repoMesh.list.nodesSuffix")]})]})]})},F.id)})})]})}function zP({tabs:e,defaultTabKey:t,ariaLabel:n,className:a}){var i;const[r,o]=l.useState(t??((i=e[0])==null?void 0:i.key));return s.jsxs("div",{className:a,children:[s.jsx("div",{className:"mb-5 inline-flex w-full flex-wrap items-center gap-1 rounded-xl border border-border-subtle bg-bg-secondary/60 p-1 sm:w-fit",role:"tablist","aria-label":n,children:e.map(c=>{const u=c.key===r;return s.jsx("button",{type:"button",role:"tab","aria-selected":u,className:Wt("flex-1 rounded-lg px-3.5 py-1.5 text-[13px] font-medium transition-colors sm:flex-none",u?"bg-bg-card text-text-primary shadow-sm border border-border-default":"text-text-muted border border-transparent hover:text-text-secondary hover:bg-white/[0.03]"),onClick:()=>o(c.key),children:c.label},c.key)})}),e.map(c=>s.jsx("div",{className:c.key===r?"flex flex-col gap-4":"hidden",children:c.content},c.key))]})}const KP=["","low","medium","high"],VP={easy:"Easy",medium:"Medium",difficult:"Difficult",freeform:"Freeform"};function uu(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 pu(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 YP(){return{provider:"",model:"",thinkingLevel:"",difficulty:[],capability:[],maxParallel:""}}const rn="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function QP({slots:e,availableProviders:t,saving:n,onSave:a}){const{t:r}=Ce("common"),[o,i]=l.useState(()=>e.map(uu)),c=l.useMemo(()=>JSON.stringify(e),[e]);l.useEffect(()=>{i(e.map(uu))},[c]);const u=l.useMemo(()=>[...new Set(t.map(b=>b.type).filter(Boolean))],[t]),p=l.useMemo(()=>xm(t),[t]),d=l.useMemo(()=>{const b=o.map(pu).filter(Boolean);return JSON.stringify(b)!==JSON.stringify(e)},[o,e]),m=(b,S)=>i(N=>N.map((v,y)=>y===b?{...v,...S}:v)),h=(b,S)=>i(N=>N.map((v,y)=>{var A;if(y!==b)return v;const j=((A=p.get(S))==null?void 0:A.models)??[],C=!v.model||j.length===0||j.includes(v.model);return{...v,provider:S,...C?{}:{model:""}}})),g=b=>i(S=>S.filter((N,v)=>v!==b)),k=()=>i(b=>[...b,YP()]),f=(b,S)=>i(N=>{const v=b+S;if(v<0||v>=N.length)return N;const y=[...N];return[y[b],y[v]]=[y[v],y[b]],y}),x=(b,S)=>i(N=>N.map((v,y)=>{if(y!==b)return v;const j=v.difficulty.includes(S);return{...v,difficulty:j?v.difficulty.filter(C=>C!==S):[...v.difficulty,S]}})),w=()=>a(o.map(pu).filter(Boolean));return s.jsxs("div",{className:"flex flex-col gap-2",onClick:b=>b.stopPropagation(),children:[o.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:r("repoMesh.slotEditor.empty")}),o.map((b,S)=>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:["#",S+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:S===0,onClick:()=>f(S,-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:S===o.length-1,onClick:()=>f(S,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(S),"aria-label":r("repoMesh.slotEditor.removeSlot"),children:s.jsx(Pt,{size:12})})]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.provider")}),u.length>0?s.jsxs("select",{className:rn,value:b.provider,onChange:N=>h(S,N.target.value),children:[s.jsx("option",{value:"",children:r("repoMesh.slotEditor.select")}),u.map(N=>s.jsx("option",{value:N,children:N},N)),b.provider&&!u.includes(b.provider)&&s.jsx("option",{value:b.provider,children:b.provider})]}):s.jsx("input",{className:rn,value:b.provider,placeholder:"claude-cli",onChange:N=>m(S,{provider:N.target.value})})]}),(()=>{var C;const N=p.get(b.provider),v=(N==null?void 0:N.models)??[],y=(C=N==null?void 0:N.thinking)!=null&&C.length?["",...N.thinking]:KP,j=!!b.model&&v.length>0&&!v.includes(b.model);return s.jsxs(s.Fragment,{children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.model")}),v.length>0&&!j?s.jsxs("select",{className:rn,value:v.includes(b.model)?b.model:"",onChange:A=>m(S,{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:rn,value:b.model.trim(),placeholder:b.provider?`${b.provider} model`:r("repoMesh.slotEditor.modelPlaceholder"),onChange:A=>m(S,{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(S,{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:rn,value:b.thinkingLevel,onChange:A=>m(S,{thinkingLevel:A.target.value}),children:y.map(A=>s.jsx("option",{value:A,children:A||r("repoMesh.slotEditor.thinkingDefault")},A||"_default"))})]})]})})()]}),s.jsxs("div",{className:"mt-2",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:r("repoMesh.slotEditor.difficulty")}),s.jsx("div",{className:"mt-1 flex flex-wrap gap-1.5",children:lp.map(N=>{const v=b.difficulty.includes(N);return s.jsx("button",{type:"button",className:`rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors ${v?"border-accent-primary/60 bg-accent-primary/15 text-accent-primary":"border-border-subtle bg-bg-primary/60 text-text-muted hover:text-text-primary"}`,onClick:()=>x(S,N),children:VP[N]},N)})})]}),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:rn,value:b.capability.join(", "),placeholder:"worktree, os=darwin",onChange:N=>m(S,{capability:N.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:rn,value:b.maxParallel,placeholder:r("repoMesh.slotEditor.maxParallelPlaceholder"),onChange:N=>m(S,{maxParallel:N.target.value})})]})]})]},S)),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(cl,{size:13})," ",r("repoMesh.slotEditor.addSlot")]}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm ml-auto",onClick:w,disabled:!!n||!d,children:r(n?"repoMesh.slotEditor.saving":"repoMesh.slotEditor.saveSlots")})]})]})}function JP(e){const t=new Map;for(const n of e)n!=null&&n.id&&t.set(n.id,Un(n.availableProviders||[]));return t}function XP(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 ZP(e,t){const n=new Map;for(const c of t)c!=null&&c.id&&n.set(c.id,Array.isArray(c.availableProviders)?c.availableProviders:[]);const a=new Set,r=[];let o=0,i=0;for(const c of Array.isArray(e)?e:[]){const u=String((c==null?void 0:c.daemon_id)||(c==null?void 0:c.daemonId)||""),p=u?n.get(u):n.size===1?[...n.values()][0]:void 0;if(!p||p.length===0){i++;continue}o++;for(const d of p){const m=String((d==null?void 0:d.type)||(d==null?void 0:d.id)||"").trim();!m||a.has(m)||(a.add(m),r.push(d))}}return r.sort((c,u)=>String((c==null?void 0:c.type)||(c==null?void 0:c.id)||"").localeCompare(String((u==null?void 0:u.type)||(u==null?void 0:u.id)||""))),{providers:r,reportedNodeCount:o,unreportedNodeCount:i}}function eI(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 Cw(t.slots))r(o.provider);if(Array.isArray(t.providerPriority))for(const o of t.providerPriority)r(o);return a}function tI(e){var u,p;const t=e,n=[],a=Array.isArray(t.capabilities)?t.capabilities:[];for(const d of a){const m=typeof d=="string"?d.trim():"";m&&n.push({tag:m,custom:!0})}const r=(((u=t.userOverrides)==null?void 0:u.platform)||t.reportedPlatform||"").toString().trim(),o=(((p=t.userOverrides)==null?void 0:p.arch)||t.reportedArch||"").toString().trim();r&&n.push({tag:`os=${r}`,custom:!1}),o&&n.push({tag:`arch=${o}`,custom:!1});for(const d of eI(t.policy))n.push({tag:`provider=${d}`,custom:!1});const i=typeof t.worktreeBranch=="string"?t.worktreeBranch.trim():"";t.isLocalWorktree===!0&&i&&n.push({tag:`worktree=${i}`,custom:!1});const c=new Set;return n.filter(d=>c.has(d.tag)?!1:(c.add(d.tag),!0))}function sI(e){const t=e.capabilities;return Array.isArray(t)?t.map(n=>typeof n=="string"?n.trim():"").filter(Boolean):[]}const nI=["os=","arch=","provider=","worktree=","converge="];function aI({node:e,saving:t,onSave:n}){const{t:a}=Ce("common"),r=l.useMemo(()=>tI(e).filter(f=>!f.custom),[e]),o=l.useMemo(()=>sI(e),[e]),[i,c]=l.useState(o),[u,p]=l.useState(""),d=JSON.stringify(i)!==JSON.stringify(o),h=(f=>{const x=f.trim();return x?/\s/.test(x)?a("repoMesh.tagEditor.noSpaces"):nI.some(w=>x.toLowerCase().startsWith(w))?a("repoMesh.tagEditor.reservedPrefix"):i.includes(x)?a("repoMesh.tagEditor.alreadyAdded"):null:null})(u);function g(){const f=u.trim();!f||h||(c(x=>[...x,f]),p(""))}function k(f){c(x=>x.filter(w=>w!==f))}return s.jsxs("div",{className:"mt-2",onClick:f=>f.stopPropagation(),children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wide text-text-muted mr-1",children:a("repoMesh.tagEditor.routingTags")}),r.map(f=>s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-1.5 py-0.5 font-mono text-[10px] text-text-muted",title:a("repoMesh.tagEditor.autoDerivedTitle"),children:f.tag},f.tag)),i.map(f=>s.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 font-mono text-[10px] text-accent-primary",title:a("repoMesh.tagEditor.customTagTitle"),children:[f,s.jsx("button",{type:"button",className:"text-accent-primary/70 hover:text-accent-primary bg-transparent border-none cursor-pointer p-0 leading-none",onClick:()=>k(f),disabled:t,"aria-label":a("repoMesh.tagEditor.remove",{tag:f}),children:"×"})]},f))]}),s.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-2",children:[s.jsx("input",{type:"text",value:u,onChange:f=>p(f.target.value),onKeyDown:f=>{f.key==="Enter"&&(f.preventDefault(),g())},placeholder:a("repoMesh.tagEditor.addPlaceholder"),disabled:t,className:"min-w-[12rem] flex-1 px-2 py-1 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-primary"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:g,disabled:t||!u.trim()||!!h,children:a("repoMesh.tagEditor.add")}),d&&s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>n(i),disabled:t,children:a(t?"repoMesh.tagEditor.saving":"repoMesh.tagEditor.saveTags")})]}),h&&s.jsx("div",{className:"mt-1 text-[11px] text-amber-400",children:h}),i.length===0&&r.length===0&&s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:a("repoMesh.tagEditor.empty")})]})}function rI(e,t){return t.filter(n=>n.status!=="assigned"?!1:(n.assignedNodeId||n.nodeId)===e.id)}function oI(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 iI(e){var a;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((a=e.policy)==null?void 0:a.providerPriority)?e.policy.providerPriority:[],n=new Set;return t.map(r=>typeof r=="string"?r.trim():"").filter(Boolean).filter(r=>n.has(r)?!1:(n.add(r),!0))}function lI(e){const t=iI(e);return t.length?{configured:!0,label:t.join(" → ")}:{configured:!1,label:"not configured",launchBlockedMessage:"No provider detected on this node — task launch is blocked until a provider is selected or installed. (Empty capability slots alone do not block launch; this means no provider was found.)"}}function Qi(e){return e.isLocalWorktree===!0}function cI(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 mu(e){return e&&(e.machineNickname||e.nickname||e.hostname||(e.id?qh(e.id):void 0))||"Unknown"}function dI(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 uI({nodes:e,meshQueue:t,activeDaemon:n,daemons:a,selectedMeshId:r,userName:o,features:i,coordinatorDaemonId:c,availableCliProviders:u,savingNodeSlotsId:p,onUpdateNodeSlots:d,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:h,nodeSystemPromptDrafts:g,onNodeSystemPromptDraftChange:k,savingNodeSystemPromptId:f,onSaveNodeSystemPrompt:x,selectedNodeId:w,onSelectNode:b,showAddNode:S,onShowAddNode:N,onCancelAddNode:v,nodeWorkspace:y,onNodeWorkspaceChange:j,nodeProviderPriority:C,onNodeProviderPriorityChange:A,nodeDaemonId:T,onNodeDaemonIdChange:D,nodeCustomPath:I,onNodeCustomPathChange:M,nodePickerWorkspaces:P,nodePickerProviders:$,nodeOnboardingPlan:L,nodePlanLoading:R,attachableDaemons:F,onAddNode:E,onRemoveNode:H}){var K;const{t:_}=Ce("common"),G=l.useMemo(()=>JP(a),[a]),W=l.useMemo(()=>e.filter(V=>!Qi(V)),[e]);return s.jsxs(gt,{title:i.addNodeDaemonPicker?_("repoMesh.nodeList.title",{count:W.length}):_("repoMesh.nodeList.titleNoCount"),description:i.addNodeDaemonPicker?_("repoMesh.nodeList.descriptionCloud"):_("repoMesh.nodeList.descriptionStandalone"),children:[i.addNodeDaemonPicker&&s.jsxs("div",{className:"mb-4 rounded-xl border border-border-subtle bg-bg-secondary/60 p-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:_("repoMesh.nodeList.daemonCandidates")}),s.jsx("div",{className:"text-[12px] text-text-muted",children:_("repoMesh.nodeList.daemonCandidatesHint")})]}),s.jsx("span",{className:"text-[11px] text-text-muted",children:_("repoMesh.nodeList.available",{count:F.length})})]}),a.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:_("repoMesh.nodeList.noDaemonsAvailable")}):F.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:_("repoMesh.nodeList.allDaemonsAttached")}):s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:F.map(V=>s.jsxs("button",{type:"button",className:`text-left rounded-lg border px-3 py-2 transition-colors ${V.id===c?"border-accent-primary/50 bg-accent-primary/10":"border-border-subtle bg-bg-primary hover:border-border-default"}`,onClick:()=>{D(V.id),j(""),M(!1),A(Pa(Un(V.availableProviders||[]))),N()},children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-sm font-medium truncate",children:mu(V)}),V.id===c&&s.jsx("span",{className:"text-[10px] text-accent-primary",children:_("repoMesh.nodeList.selectedHost")})]}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted font-mono truncate",children:V.id}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:_("repoMesh.nodeList.workspacesDetected",{count:(V.workspaces||[]).length})})]},V.id))})]}),!S&&s.jsxs("button",{className:"btn btn-primary btn-sm mb-4 inline-flex items-center gap-1.5",onClick:N,children:[s.jsx(OP,{size:13})," ",i.addNodeDaemonPicker?_("repoMesh.nodeList.attachMachine"):_("repoMesh.nodeList.addNode")]}),S&&s.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass animate-[fadeIn_0.3s_ease-out]",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h4",{className:"text-sm font-bold",children:i.addNodeDaemonPicker?_("repoMesh.nodeList.attachMachineTitle"):_("repoMesh.nodeList.addNodeTitle")}),s.jsx("button",{onClick:()=>{v(),D(""),M(!1)},className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(Pt,{size:16})})]}),i.addNodeDaemonPicker&&s.jsx(Nt,{label:_("repoMesh.nodeList.machine"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:T,onChange:V=>{var te;D(V.target.value),j(""),M(!1),A(Pa(Un(((te=a.find(le=>le.id===V.target.value))==null?void 0:te.availableProviders)||[])))},children:[s.jsx("option",{value:"",children:_("repoMesh.nodeList.selectMachine")}),a.map(V=>s.jsx("option",{value:V.id,children:mu(V)},V.id))]})}),(i.addNodeDaemonPicker?T:!0)&&s.jsx(Nt,{label:_("repoMesh.nodeList.workspacePath"),children:i.addNodeDaemonPicker&&!I&&P.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex flex-col gap-1.5 mb-2",children:P.map(V=>s.jsxs("button",{type:"button",className:`text-left text-xs px-3 py-2 rounded-lg border transition-colors ${y===V.path?"border-accent-primary bg-accent-primary/10 text-text-primary":"border-border-subtle bg-bg-primary hover:bg-violet-500/10 text-text-primary"}`,onClick:()=>j(V.path),children:[s.jsx("span",{className:"font-medium block truncate",children:V.label||V.path.split("/").pop()}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:V.path})]},V.id||V.path))}),s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{M(!0),j("")},children:_("repoMesh.nodeList.enterCustomPath")})]}):s.jsx(s.Fragment,{children:i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[s.jsx(ps,{value:y,onChange:V=>j(V.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:V=>{V.key==="Enter"&&E()}}),P.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:_("repoMesh.nodeList.pickFromSaved")})]}):(()=>{var le;const V=Array.isArray(n==null?void 0:n.workspaces)?n.workspaces:[],te=`mesh-add-node-workspaces-${r||"new"}`;return s.jsxs(s.Fragment,{children:[s.jsx(ps,{value:y,onChange:de=>j(de.target.value),placeholder:((le=V[0])==null?void 0:le.path)||"/Users/dev/projects/myapp",list:V.length>0?te:void 0,autoFocus:!0}),V.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("datalist",{id:te,children:V.map(de=>s.jsx("option",{value:de.path,children:de.label||de.path},de.id||de.path))}),s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:V.slice(0,6).map(de=>s.jsx("button",{type:"button",onClick:()=>j(de.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:de.path,children:de.label||de.path.split("/").filter(Boolean).pop()||de.path},de.id||de.path))})]})]})})()})}),(R||L)&&s.jsx(Dt,{variant:(L==null?void 0:L.success)===!1?"error":"info",className:"mb-4",children:R?"Inspecting Git repository (read-only)…":L!=null&&L.success?`${((K=L.plan)==null?void 0:K.summary)||"Compatible Git workspace detected."} Adding remains an explicit action.`:`${(L==null?void 0:L.code)||"onboarding_blocked"}: ${(L==null?void 0:L.error)||"Git discovery failed"} ${(L==null?void 0:L.action)||""}`}),s.jsx(Nt,{label:_("repoMesh.nodeList.preferredTools"),hint:_("repoMesh.nodeList.preferredToolsHint"),children:s.jsx(SC,{value:C,availableProviders:i.addNodeDaemonPicker?$:u,onChange:A})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:E,disabled:R||(L==null?void 0:L.success)===!1||!y.trim()||i.addNodeDaemonPicker&&!T,className:"btn btn-primary btn-sm",children:_("repoMesh.nodeList.add")}),s.jsx("button",{onClick:()=>{v(),D(""),M(!1)},className:"btn btn-secondary btn-sm",children:_("repoMesh.nodeList.cancel")})]})]}),W.length===0?s.jsx(so,{icon:s.jsx(Bn,{}),title:_("repoMesh.nodeList.emptyTitle"),description:_("repoMesh.nodeList.emptyDescription")}):s.jsx("div",{className:"flex flex-col gap-2",children:W.map(V=>{var X;const te=lI(V),le=rI(V,t),de=cI(V,n),ee=w===V.id,z=V.status||V.machine_status||(le.length>0||de.length>0?"active":"enabled");return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary transition-colors ${i.addNodeDaemonPicker?"bg-bg-glass border-border-subtle rounded-xl px-5 py-4":`cursor-pointer ${ee?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`}`,role:i.addNodeDaemonPicker?void 0:"button",tabIndex:i.addNodeDaemonPicker?void 0:0,onClick:i.addNodeDaemonPicker?void 0:()=>b(ee?null:V.id),onKeyDown:i.addNodeDaemonPicker?void 0:U=>{(U.key==="Enter"||U.key===" ")&&(U.preventDefault(),b(ee?null:V.id))},children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.addNodeDaemonPicker?s.jsx("span",{className:"font-semibold text-sm text-text-primary truncate",children:V.machine_label||V.machine_nickname||V.hostname||V.workspace}):s.jsx("span",{className:"text-sm font-medium",children:V.workspace.split("/").pop()}),i.addNodeDaemonPicker&&s.jsx(UP,{status:z}),i.addNodeDaemonPicker&&s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:_("repoMesh.nodeList.setupInventory")})]}),i.addNodeDaemonPicker&&s.jsx("div",{className:"text-[11px] text-text-muted",children:_("repoMesh.nodeList.ownerMachine",{owner:dI(a.find(U=>U.id===String(V.daemon_id||"")),o),machine:V.machine_label||V.daemon_id||V.workspace})}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:V.workspace}),s.jsx(aI,{node:V,saving:m===V.id,onSave:U=>h(V,U)}),i.addNodeDaemonPicker&&s.jsx("div",{className:"mt-2 text-[11px] text-amber-300",children:_("repoMesh.nodeList.liveDetailGraphOwned")}),s.jsxs("div",{className:"mt-3 max-w-2xl",onClick:U=>U.stopPropagation(),children:[s.jsx(Nt,{label:_("repoMesh.nodeList.slotsLabel"),hint:_("repoMesh.nodeList.slotsHint"),children:s.jsx(QP,{slots:Array.isArray((X=V.policy)==null?void 0:X.slots)?V.policy.slots:[],availableProviders:XP(V,G),saving:p===V.id,onSave:U=>d(V,U)})}),i.nodeInstruction&&s.jsxs(Nt,{label:_("repoMesh.nodeList.nodeInstruction"),hint:_("repoMesh.nodeList.nodeInstructionHint"),children:[s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:3,value:g[V.id]??"",onChange:U=>{const Q=U.target.value;k(V.id,Q)},onClick:U=>U.stopPropagation(),disabled:f===V.id,placeholder:_("repoMesh.nodeList.nodeInstructionPlaceholder")}),s.jsx("div",{className:"mt-2 flex items-center gap-2",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:U=>{U.stopPropagation(),x(V)},disabled:f===V.id,children:f===V.id?_("repoMesh.nodeList.saving"):_("repoMesh.nodeList.saveInstruction")})})]})]})]}),s.jsx("button",{className:`transition-colors bg-transparent border-none cursor-pointer ${i.addNodeDaemonPicker?"btn btn-sm text-text-muted hover:text-red-400":"text-text-muted hover:text-red-400"}`,onClick:U=>{U.stopPropagation(),H(V.id)},title:_("repoMesh.nodeList.removeNode"),children:s.jsx(WP,{size:14})})]}),s.jsxs("details",{className:"mt-3 group",onClick:U=>U.stopPropagation(),children:[s.jsxs("summary",{className:"cursor-pointer select-none text-[12px] text-text-muted hover:text-text-secondary inline-flex items-center gap-1",children:[s.jsx("span",{className:"transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"})," ",_("repoMesh.nodeList.details")]}),s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary/60 p-3 text-[12px] text-text-muted",children:[s.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:_("repoMesh.nodeList.nodeId")})," ",s.jsx("span",{className:"font-mono break-all",children:V.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:_("repoMesh.nodeList.launchReady")})," ",s.jsx("span",{className:te.configured?"text-green-400":"text-amber-400",children:te.configured?_("repoMesh.nodeList.launchReadyYes"):_("repoMesh.nodeList.launchReadyNo")})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:_("repoMesh.nodeList.repoRoot")})," ",s.jsx("span",{className:"font-mono break-all",children:V.repoRoot||V.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:_("repoMesh.nodeList.activeSessionsLabel")})," ",de.length]}),i.addNodeDaemonPicker&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:_("repoMesh.nodeList.added")})," ",new Date(V.created_at||V.createdAt||Date.now()).toLocaleDateString()]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:_("repoMesh.nodeList.activeQueueAssignments")}),le.length===0?s.jsx("div",{children:_("repoMesh.nodeList.noActiveAssignment")}):s.jsx("ul",{className:"m-0 pl-4",children:le.map(U=>s.jsx("li",{className:"font-mono",children:oI(U)},U.id))})]}),de.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:_("repoMesh.nodeList.activeSessions")}),s.jsx("ul",{className:"m-0 pl-4",children:de.map(U=>s.jsxs("li",{className:"font-mono",children:[U.provider," / ",U.status," / ",U.id]},U.id))})]})]})]})]},V.id)})})]})}const pI=["claude-cli","codex-cli","gemini-cli","hermes-cli","antigravity-cli"],mI=[{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 hI(){return{nodeId:"",provider:"",model:"",n:""}}function hu(e){var t;return(t=e.providers)!=null&&t.length?e.providers.filter(Boolean):(e.providerPriority??[]).filter(Boolean)}function fI(e){return{nodeId:e.nodeId??"",provider:e.provider??"",model:e.model??"",n:e.n!=null?String(e.n):""}}function bI(e){const t=[];for(let n=0;n<e.length;n++){const a=e[n],r=a.provider.trim();if(!r)return{error:{code:"provider_required",slot:n+1}};const o=a.nodeId.trim(),i=a.model.trim(),c=a.n.trim();let u;if(c){const p=Number(c);if(!Number.isFinite(p)||p<1)return{error:{code:"replica_min",slot:n+1}};u=Math.floor(p)}t.push({provider:r,...o?{nodeId:o}:{},...i?{model:i}:{},...u!==void 0?{n:u}:{}})}return t.length===0?{error:{code:"no_slot"}}:{slots:t}}function gI({status:e,daemonId:t,sendDaemonCommand:n,availableProviders:a}){const{t:r}=Ce(),{theme:o}=en(),i=l.useMemo(()=>tn(o),[o]),c=l.useMemo(()=>xm(a),[a]),[u,p]=l.useState({}),[d,m]=l.useState(!1),[h,g]=l.useState(null),[k,f]=l.useState({}),[x,w]=l.useState(null),b=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(W=>({nodeId:W.nodeId,machineLabel:W.machineLabel,providers:W.providers,providerPriority:W.providerPriority,isLocalWorktree:W.isLocalWorktree,worktreeBranch:W.worktreeBranch})),[e==null?void 0:e.nodes]),S=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(W=>W.nodeId),[e==null?void 0:e.nodes]),N=l.useMemo(()=>new Set(b.filter(Qi).map(W=>W.nodeId)),[b]),v=l.useMemo(()=>Object.fromEntries(b.filter(Qi).map(W=>[W.nodeId,W.worktreeBranch])),[b]),y=l.useMemo(()=>Object.fromEntries(((e==null?void 0:e.nodes)??[]).map(W=>[W.nodeId,W.machineLabel||W.nodeId])),[e==null?void 0:e.nodes]),j=l.useMemo(()=>{const W={};for(const K of b)W[K.nodeId]=hu(K);return W},[b]),C=l.useMemo(()=>{const W=[...new Set(b.flatMap(hu).filter(Boolean))];return[...new Set([...W,...pI])].sort()},[b]),A=!!t&&!!n,T=W=>W&&typeof W=="object"&&"result"in W?W.result:W,D=e==null?void 0:e.meshId,I=l.useCallback(async()=>{if(!(!t||!n)){m(!0),g(null);try{const W=await n(t,"magi_kind_panel_list",{...D?{meshId:D}:{}}),K=T(W);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:{}),f({})}catch(W){g((W==null?void 0:W.message)||r("meshGraph.magiKind.errorLoad"))}finally{m(!1)}}},[t,n,D,r]);l.useEffect(()=>{I()},[I]);const M=l.useCallback(W=>{if(k[W])return k[W];const K=u[W];return K?K.map(fI):[]},[k,u]),P=(W,K)=>{f(V=>({...V,[W]:K}))},$=(W,K,V)=>{const te=M(W);P(W,te.map((le,de)=>de===K?{...le,...V}:le))},L=W=>{P(W,[...M(W),hI()])},R=(W,K)=>{P(W,M(W).filter((V,te)=>te!==K))},F=l.useCallback(async W=>{if(!t||!n)return;const K=bI(M(W));if("error"in K){const V=K.error,te=V.code==="provider_required"?r("meshGraph.magiKind.errorSlotProvider",{slot:V.slot}):V.code==="replica_min"?r("meshGraph.magiKind.errorSlotReplica",{slot:V.slot}):r("meshGraph.magiKind.errorNoSlot");g(`${W}: ${te}`);return}w(W),g(null);try{const V=await n(t,"magi_kind_panel_set",{kind:W,slots:K.slots,...D?{meshId:D}:{}}),te=T(V);if((te==null?void 0:te.success)===!1)throw new Error(te.error||r("meshGraph.magiKind.errorSave"));await I()}catch(V){g((V==null?void 0:V.message)||r("meshGraph.magiKind.errorSave"))}finally{w(null)}},[t,n,M,I,D,r]),E=l.useCallback(async W=>{if(!(!t||!n)&&confirm(r("meshGraph.magiKind.removeConfirm",{kind:W}))){w(W),g(null);try{const K=await n(t,"magi_kind_panel_remove",{kind:W,...D?{meshId:D}:{}}),V=T(K);if((V==null?void 0:V.success)===!1)throw new Error(V.error||r("meshGraph.magiKind.errorRemove"));await I()}catch(K){g((K==null?void 0:K.message)||r("meshGraph.magiKind.errorRemove"))}finally{w(null)}}},[t,n,I,D,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"}`,_="btn btn-primary btn-sm",G="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:G,onClick:()=>void I(),disabled:d||!A,children:r(d?"meshGraph.magiKind.loading":"meshGraph.magiKind.refresh")})})]}),!A&&s.jsx("div",{className:`rounded-xl border p-3 text-[12px] ${i.textSecondary} ${i.isDark?"border-white/10":"border-slate-200"}`,children:r("meshGraph.magiKind.connectPrompt")}),h&&s.jsx("div",{className:"rounded-xl border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-[12px] text-rose-300",children:h}),s.jsx("div",{className:"flex flex-col gap-3",children:mI.map(({kind:W,labelKey:K,hint:V})=>{const te=M(W),le=!!u[W],de=x===W;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:V}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${le?"border-emerald-400/30 bg-emerald-500/10 text-emerald-300":"border-slate-400/20 bg-slate-500/10 text-slate-300"}`,children:le?r("meshGraph.magiKind.agentCount",{count:u[W].length}):r("meshGraph.magiKind.off")})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[te.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")}),te.map((ee,z)=>{const X=ee.nodeId?j[ee.nodeId]??[]:[],U=ee.nodeId&&X.length?X:C;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:ee.nodeId,onChange:Q=>$(W,z,{nodeId:Q.target.value}),title:r("meshGraph.magiKind.machineTitle"),children:[s.jsx("option",{value:"",children:r("meshGraph.magiKind.anyMachine")}),S.map(Q=>{const ke=N.has(Q),ve=ke?r("meshGraph.magiKind.worktreeSuffix",{label:y[Q]??Q,branch:v[Q]||r("meshGraph.magiKind.worktreeUnknownBranch")}):y[Q]??Q;return s.jsx("option",{value:Q,disabled:ke,title:ke?r("meshGraph.magiKind.worktreeDisabledTitle"):void 0,children:ve},Q)}),ee.nodeId&&!S.includes(ee.nodeId)&&s.jsx("option",{value:ee.nodeId,children:r("meshGraph.magiKind.offlineSuffix",{label:y[ee.nodeId]??ee.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:ee.provider,onChange:Q=>$(W,z,{provider:Q.target.value}),title:r("meshGraph.magiKind.providerTitle"),children:[s.jsx("option",{value:"",children:r("meshGraph.magiKind.selectProvider")}),U.map(Q=>s.jsx("option",{value:Q,children:Q},Q)),ee.provider&&!U.includes(ee.provider)&&s.jsx("option",{value:ee.provider,children:ee.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 ve;const Q=(ee.provider?(ve=c.get(ee.provider))==null?void 0:ve.models:void 0)??[],ke=!!ee.model&&Q.length>0&&!Q.includes(ee.model);return Q.length>0&&!ke?s.jsxs("select",{className:H,value:Q.includes(ee.model)?ee.model:"",title:r("meshGraph.magiKind.modelTitle"),onChange:ge=>$(W,z,{model:ge.target.value==="__custom__"?" ":ge.target.value}),children:[s.jsx("option",{value:"",children:r("meshGraph.magiKind.modelDefault")}),Q.map(ge=>s.jsx("option",{value:ge,children:ge},ge)),s.jsx("option",{value:"__custom__",children:r("meshGraph.magiKind.modelCustom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:H,value:ee.model.trim(),placeholder:r("meshGraph.magiKind.modelDefault"),title:r("meshGraph.magiKind.modelTitle"),onChange:ge=>$(W,z,{model:ge.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:()=>$(W,z,{model:""}),children:r("meshGraph.magiKind.backToModelList")})]})})()]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:r("meshGraph.magiKind.copies")}),s.jsx("input",{className:`${H} sm:w-16`,value:ee.n,placeholder:"1",inputMode:"numeric",title:r("meshGraph.magiKind.copiesTitle"),onChange:Q=>$(W,z,{n:Q.target.value})})]}),s.jsx("button",{type:"button",className:`${G} sm:mt-[18px] inline-flex h-8 w-8 items-center justify-center p-0`,onClick:()=>R(W,z),"aria-label":r("meshGraph.magiKind.removeAgent"),title:r("meshGraph.magiKind.removeAgent"),children:"✕"})]},z)}),s.jsx("div",{children:s.jsx("button",{type:"button",className:G,onClick:()=>L(W),disabled:!A,children:r("meshGraph.magiKind.addAgent")})})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:_,onClick:()=>void F(W),disabled:de||!A,children:r(de?"meshGraph.magiKind.saving":"meshGraph.magiKind.save")}),s.jsx("button",{type:"button",className:G,onClick:()=>void E(W),disabled:de||!A||!le,title:r(le?"meshGraph.magiKind.removeBindingTitle":"meshGraph.magiKind.removeBindingDisabledTitle"),children:r("meshGraph.magiKind.removeBinding")})]})]},W)})})]})}function xI({daemonId:e,meshId:t,cliType:n,sendCommand:a}){const{t:r}=Ce(),[o,i]=l.useState(!1),[c,u]=l.useState(!1),[p,d]=l.useState(null),[m,h]=l.useState(null),[g,k]=l.useState(null),f=l.useCallback(async()=>{if(!e||!t){d(r("repoMesh.promptPreview.connectPrompt"));return}u(!0),d(null);try{const w=await a(e,"coordinator_prompt_preview",{meshId:t,cliType:n}),b=w!=null&&w.result&&typeof w.result=="object"?w.result:w;if(!(b!=null&&b.success)){d((b==null?void 0:b.error)||r("repoMesh.promptPreview.errorRender"));return}h(typeof b.prompt=="string"?b.prompt:""),k(typeof b.bytes=="number"?b.bytes:null)}catch(w){d((w==null?void 0:w.message)||String(w))}finally{u(!1)}},[e,t,n,a,r]),x=l.useCallback(()=>{const w=!o;i(w),w&&m===null&&!c&&f()},[o,m,c,f]);return s.jsxs("div",{className:"mt-2",children:[s.jsxs("button",{type:"button",onClick:x,className:"inline-flex items-center gap-1 text-[12px] text-accent-primary bg-transparent border-none cursor-pointer p-0",children:[s.jsx("span",{className:`transition-transform ${o?"rotate-90":""}`,"aria-hidden":!0,children:"▸"}),r(o?"repoMesh.promptPreview.hide":"repoMesh.promptPreview.view"),s.jsxs("span",{className:"text-text-muted",children:["(",n,")"]})]}),o&&s.jsxs("div",{className:"mt-2",children:[c&&s.jsx("div",{className:"text-[12px] text-text-muted",children:r("repoMesh.promptPreview.rendering")}),p&&s.jsxs("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:[p,s.jsx("button",{type:"button",onClick:()=>void f(),className:"ml-2 underline bg-transparent border-none cursor-pointer text-amber-300",children:r("repoMesh.promptPreview.retry")})]}),!c&&!p&&m!==null&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between text-[11px] text-text-muted",children:[s.jsx("span",{children:r("repoMesh.promptPreview.info")}),g!==null&&s.jsxs("span",{children:[(g/1024).toFixed(1)," KB"]})]}),s.jsx("textarea",{readOnly:!0,value:m,rows:14,className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-secondary font-mono",onFocus:w=>w.currentTarget.select()})]})]})]})}const vI=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function yI(e){const t=vI(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function wI(e){const t=e==null?void 0:e.missions;return Array.isArray(t)?t:[]}function kI(e){return typeof e.goal=="string"&&e.goal?{text:e.goal,truncated:!1}:{text:e.goalPreview??"",truncated:e.goalTruncated===!0}}const SI=["active","paused","completed","abandoned"];function fu(e){return(e.status||"active").toLowerCase()}const CI=8;function jI({status:e,daemonId:t,meshId:n,sendCommand:a}){const{t:r}=Ce("common"),o=l.useMemo(()=>wI(e),[e]),[i,c]=l.useState({}),[u,p]=l.useState({}),[d,m]=l.useState(!1),[h,g]=l.useState(null),[k,f]=l.useState("active"),[x,w]=l.useState(!1),b=l.useMemo(()=>{const A={};for(const T of o){const D=fu(T);A[D]=(A[D]||0)+1}return A},[o]),S=l.useMemo(()=>k==="all"?o:o.filter(A=>fu(A)===k),[o,k]),N=x?S:S.slice(0,CI),v=S.length-N.length,y=!!t&&o.length>0,j=l.useCallback(async()=>{if(t){m(!0),g(null);try{const A=await a(t,"mesh_status",{meshId:n,verbose:!0}),T=yI(A),D=Array.isArray(T==null?void 0:T.missions)?T.missions:[],I={};for(const M of D)M.id&&typeof M.goal=="string"&&M.goal&&(I[M.id]=M.goal);c(M=>({...M,...I}))}catch(A){g(A instanceof Error?A.message:r("repoMesh.missions.errorFetch"))}finally{m(!1)}}},[t,n,a,r]),C=l.useCallback(A=>{p(T=>({...T,[A]:!T[A]})),!u[A]&&!i[A]&&j()},[u,i,j]);return o.length===0?null:s.jsxs(gt,{title:r("repoMesh.missions.title"),description:r("repoMesh.missions.description"),children:[h&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400",children:h}),s.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-1.5",children:[SI.filter(A=>(b[A]||0)>0).map(A=>s.jsxs("button",{type:"button",onClick:()=>{f(A),w(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] capitalize transition-colors ${k===A?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:[A," ",b[A]]},A)),s.jsxs("button",{type:"button",onClick:()=>{f("all"),w(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] transition-colors ${k==="all"?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:["All ",o.length]})]}),S.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:N.map(A=>{var L;const T=u[A.id]===!0,D=i[A.id],I=kI(A),M=T&&D?D:I.text,P=T&&!D&&I.truncated,$=((L=A.tasks)==null?void 0:L.total)??0;return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 px-3 py-2.5",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-text-primary",title:A.title,children:A.title||A.id}),A.status&&s.jsx("span",{className:"shrink-0 rounded-full border border-border-subtle px-2 py-0.5 text-[10px] uppercase tracking-wide text-text-muted",children:A.status}),$>0&&s.jsx("span",{className:"shrink-0 text-[11px] text-text-muted",children:r("repoMesh.missions.taskCount",{count:$})})]}),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,P&&s.jsx("span",{className:"text-text-muted",children:r("repoMesh.missions.goalUnavailable")})]}),(I.truncated||D)&&y&&s.jsx("button",{type:"button",className:"mt-1.5 text-[12px] text-accent-primary hover:underline disabled:opacity-50",onClick:()=>C(A.id),disabled:d,children:r(T?"repoMesh.missions.showLess":d&&!D?"repoMesh.missions.loading":"repoMesh.missions.showFullGoal")})]},A.id)})}),v>0&&s.jsx("button",{type:"button",className:"mt-2 text-[12px] text-accent-primary hover:underline",onClick:()=>w(!0),children:r("repoMesh.missions.showMore",{count:v})})]})}function bu(e,t){if(t)return e.modes.find(n=>n.id===t)}function NI(e){return e.modes.find(t=>t.strategy==="pty-parse-default"&&$s(t)!=="dangerous")}function AI({config:e,requestedModeId:t,machineAutoApproveEnabled:n,machineDangerousAllowed:a}){const r=bu(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=bu(e,i),u=!!i&&!c,p=c??r;if(!p||p.strategy==="post-boot-command")return{status:"none",requestedModeId:i,providerDefaultModeId:o,requestedModeUnknown:u,downgraded:!1};if($s(p)==="dangerous"&&!a){const d=NI(e);return{status:d?"downgraded":"none",requestedModeId:i,providerDefaultModeId:o,effectiveMode:d,requestedModeUnknown:u,downgraded:!0}}return{status:u?"invalid_fallback":"requested",requestedModeId:i,providerDefaultModeId:o,effectiveMode:p,requestedModeUnknown:u,downgraded:!1}}function TI(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 MI({hostDaemonId:e,hostOnline:t,hostWorkspace:n,meshProviders:a,unreportedNodeCount:r=0,machineAutoApproveEnabled:o,machineDangerousAllowed:i,onUpdatePolicy:c,savingPolicy:u,sendCommand:p}){const{t:d}=Ce("common"),m=l.useMemo(()=>TI(a),[a]),[h,g]=l.useState({}),[k,f]=l.useState(!1),[x,w]=l.useState(null),[b,S]=l.useState(!1),[N,v]=l.useState(null),[y,j]=l.useState(!1),[C,A]=l.useState(null),[T,D]=l.useState(!1),I=!!e&&t&&!!n,M=!!c&&!u,P=l.useCallback(async()=>{var E,H,_;if(I){f(!0),w(null);try{const G=await p(e,"read_mesh_json_config",{workspace:n}),W=(G==null?void 0:G.result)??G,K=((E=W==null?void 0:W.providerDefaults)==null?void 0:E.autoApproveModes)||((_=(H=W==null?void 0:W.config)==null?void 0:H.providerDefaults)==null?void 0:_.autoApproveModes),V={};if(K&&typeof K=="object")for(const[te,le]of Object.entries(K))typeof le=="string"&&le.trim()&&(V[te]=le.trim());g(V)}catch(G){w((G==null?void 0:G.message)||d("repoMesh.providerAutoApprove.loadError"))}finally{f(!1)}}},[I,e,n,p,d]);l.useEffect(()=>{P()},[P]);const $=l.useCallback((E,H)=>{j(!1),g(_=>{const G={..._};return H&&H.trim()?G[E]=H.trim():delete G[E],G})},[]),L=l.useCallback((E,H)=>{if($s(H)==="dangerous"){A({type:E,mode:H});return}$(E,H.id)},[$]),R=l.useCallback(()=>{C&&$(C.type,C.mode.id),A(null)},[$,C]),F=l.useCallback(async()=>{if(I){S(!0),v(null),j(!1);try{const E=await p(e,"set_mesh_provider_defaults",{workspace:n,autoApproveModes:h,merge:!1,write:!0}),H=(E==null?void 0:E.result)??E;if((H==null?void 0:H.success)===!1)throw new Error((H==null?void 0:H.error)||d("repoMesh.providerAutoApprove.saveError"));j(!0),await P()}catch(E){v((E==null?void 0:E.message)||d("repoMesh.providerAutoApprove.saveError"))}finally{S(!1)}}},[I,e,n,P,h,p,d]);return s.jsxs(gt,{title:d("repoMesh.providerAutoApprove.title"),description:d("repoMesh.providerAutoApprove.subtitle"),collapsible:!0,defaultOpen:!1,children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/40 p-3.5",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:d("repoMesh.providerAutoApprove.machineSection.title")}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:d("repoMesh.providerAutoApprove.machineSection.hint")}),s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2 text-[11px]",children:[s.jsx("span",{className:`rounded-full border px-2 py-0.5 font-semibold ${o?"border-status-online/25 bg-status-online/10 text-status-online":"border-border-subtle bg-bg-tertiary/40 text-text-muted"}`,children:d(o?"repoMesh.providerAutoApprove.machineSection.autoApproveOn":"repoMesh.providerAutoApprove.machineSection.autoApproveOff")}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 font-semibold ${i?"border-status-error/30 bg-status-error/10 text-status-error":"border-border-subtle bg-bg-tertiary/40 text-text-muted"}`,children:d(i?"repoMesh.providerAutoApprove.machineSection.dangerousOn":"repoMesh.providerAutoApprove.machineSection.dangerousOff")})]}),s.jsxs("div",{className:"mt-3 space-y-2",children:[s.jsx(gu,{label:d("repoMesh.providerAutoApprove.machineSection.autoApproveToggleLabel"),hint:d("repoMesh.providerAutoApprove.machineSection.autoApproveToggleHint"),checked:o,disabled:!M,onChange:E=>c==null?void 0:c({delegatedWorkerAutoApprove:E})}),s.jsx(gu,{label:d("repoMesh.providerAutoApprove.machineSection.dangerousToggleLabel"),hint:d(o?"repoMesh.providerAutoApprove.machineSection.dangerousToggleHint":"repoMesh.providerAutoApprove.machineSection.dangerousDisabledHint"),checked:i,disabled:!M||!o,onChange:E=>{E?D(!0):c==null||c({delegatedWorkerDangerousModeAllow:!1})}})]})]}),I?k?s.jsx("div",{className:"text-[13px] text-text-muted",children:d("repoMesh.providerAutoApprove.loading")}):m.length===0?s.jsx("div",{className:"text-[13px] text-text-muted",children:r>0?d("repoMesh.providerAutoApprove.awaitingNodes",{count:r}):d("repoMesh.providerAutoApprove.noProviders")}):s.jsxs("div",{className:"space-y-6",children:[x&&s.jsx(Dt,{variant:"error",onDismiss:()=>w(null),children:x}),r>0&&s.jsx("div",{className:"text-[11px] text-text-muted",children:d("repoMesh.providerAutoApprove.partialInventory",{count:r})}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:d("repoMesh.providerAutoApprove.repoSection.title")}),s.jsx("div",{className:"text-[11px] text-text-muted",children:d("repoMesh.providerAutoApprove.repoSection.hint")})]}),s.jsx("div",{className:"space-y-5",children:m.map(E=>{const H=h[E.type],_=AI({config:E.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:E.label}),s.jsx("button",{type:"button",className:"text-[11px] text-text-muted underline decoration-dotted hover:text-text-primary disabled:opacity-40",onClick:()=>$(E.type,void 0),disabled:!H||b,children:d("repoMesh.providerAutoApprove.repoSection.clear")})]}),s.jsx(hh,{config:E.autoApproveModes,selectedModeId:H||"",disabled:b,onSelectMode:G=>L(E.type,G)}),!H&&s.jsx("div",{className:"mt-1.5 text-[11px] text-text-muted",children:d("repoMesh.providerAutoApprove.repoSection.usesProviderDefault")}),s.jsx(DI,{effective:_,config:E.autoApproveModes})]},E.type)})}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:d("repoMesh.providerAutoApprove.effectiveSection.title")}),s.jsx("div",{className:"text-[11px] text-text-muted",children:d("repoMesh.providerAutoApprove.effectiveSection.hint")})]}),N&&s.jsx(Dt,{variant:"error",onDismiss:()=>v(null),children:N}),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 F(),disabled:b,children:d(b?"repoMesh.providerAutoApprove.saving":"repoMesh.providerAutoApprove.save")}),y&&s.jsx("span",{className:"text-[12px] text-status-online",children:d("repoMesh.providerAutoApprove.saved")})]})]}):s.jsx("div",{className:"text-[13px] text-text-muted",children:d("repoMesh.providerAutoApprove.noHostDaemon")}),T&&s.jsx(ro,{title:d("repoMesh.providerAutoApprove.machineSection.confirmTitle"),description:d("repoMesh.providerAutoApprove.machineSection.confirmDescription"),details:[{label:d("repoMesh.providerAutoApprove.machineSection.confirmScopeLabel"),value:d("repoMesh.providerAutoApprove.machineSection.confirmScopeValue")},{label:d("repoMesh.providerAutoApprove.machineSection.confirmEffectLabel"),value:d("repoMesh.providerAutoApprove.machineSection.confirmEffectValue")}],confirmLabel:d("repoMesh.providerAutoApprove.machineSection.confirmConfirm"),onConfirm:()=>{D(!1),c==null||c({delegatedWorkerDangerousModeAllow:!0})},onCancel:()=>D(!1)}),C&&s.jsx(fh,{mode:C.mode,onConfirm:R,onCancel:()=>A(null)}),C&&s.jsx("div",{className:"fixed inset-x-0 bottom-6 z-[60] mx-auto max-w-lg px-4",children:s.jsxs("div",{className:"rounded-xl border border-status-error/40 bg-bg-primary p-3.5 shadow-lg",children:[s.jsx("div",{className:"text-sm font-semibold text-status-error",children:d("repoMesh.providerAutoApprove.dangerous.sharedWarningTitle")}),s.jsx("div",{className:"mt-1 text-[12px] text-text-muted",children:d("repoMesh.providerAutoApprove.dangerous.sharedWarning")})]})})]})}function DI({effective:e,config:t}){var c,u,p;const{t:n}=Ce("common"),a=d=>{var m;return(d?(m=t.modes.find(h=>h.id===d))==null?void 0:m.label:void 0)||d||""};let r,o="ok";switch(e.status){case"requested":r=n("repoMesh.providerAutoApprove.effectiveSection.statusRequested",{mode:((c=e.effectiveMode)==null?void 0:c.label)||""});break;case"invalid_fallback":r=n("repoMesh.providerAutoApprove.effectiveSection.statusInvalidFallback",{mode:((u=e.effectiveMode)==null?void 0:u.label)||""}),o="warn";break;case"downgraded":r=n("repoMesh.providerAutoApprove.effectiveSection.statusDowngraded",{requested:a(e.requestedModeId)||a(e.providerDefaultModeId),mode:((p=e.effectiveMode)==null?void 0:p.label)||""}),o="warn";break;case"disabled":r=n("repoMesh.providerAutoApprove.effectiveSection.statusDisabled"),o="muted";break;default:r=n("repoMesh.providerAutoApprove.effectiveSection.statusNone"),o="muted"}const i=o==="ok"?"border-status-online/25 bg-status-online/5 text-text-secondary":o==="warn"?"border-status-warning/30 bg-status-warning/5 text-status-warning":"border-border-subtle bg-bg-tertiary/30 text-text-muted";return s.jsxs("div",{className:`mt-3 flex items-center gap-2 rounded-lg border px-3 py-2 text-[12px] ${i}`,children:[e.effectiveMode&&s.jsx(mh,{risk:$s(e.effectiveMode)}),s.jsx("span",{className:"min-w-0",children:r})]})}function gu({label:e,hint:t,checked:n,disabled:a=!1,onChange:r}){return s.jsxs("button",{type:"button",role:"switch","aria-checked":n,className:"flex w-full items-center justify-between gap-3 rounded-xl border border-border-subtle bg-bg-primary/60 px-3.5 py-2.5 text-left disabled:opacity-50",onClick:()=>r(!n),disabled:a,children:[s.jsxs("span",{children:[s.jsx("span",{className:"block text-[13px] font-semibold text-text-primary",children:e}),s.jsx("span",{className:"mt-0.5 block text-[11px] text-text-muted",children:t})]}),s.jsx("span",{className:`relative h-6 w-11 shrink-0 rounded-full transition-colors ${n?"bg-accent-primary":"bg-bg-tertiary"}`,children:s.jsx("span",{className:`absolute top-0.5 h-5 w-5 rounded-full bg-white shadow transition-transform ${n?"translate-x-5":"translate-x-0.5"}`})})]})}function lr(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function PI({daemons:e,coordinatorDaemonId:t,onCoordinatorDaemonIdChange:n,coordinatorCliType:a,onCoordinatorCliTypeChange:r,launchingCoordinator:o,launchResult:i,isHostNodeAttached:c,selectedHostNode:u,hostPinned:p,hostLabel:d,hostOnline:m,hostRebindDaemonId:h,onHostRebindDaemonIdChange:g,onLaunchCoordinator:k,settingMeshHost:f,onSetMeshHost:x}){const{t:w}=Ce("common"),b=s.jsx(Nt,{label:w("repoMesh.host.coordinatorProvider"),hint:w("repoMesh.host.coordinatorProviderHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:a,onChange:y=>r(y.target.value),children:[s.jsx("option",{value:"",children:w("repoMesh.host.useNodePriority")}),s.jsx("option",{value:"claude-cli",children:"Claude Code"}),s.jsx("option",{value:"codex-cli",children:"Codex"}),s.jsx("option",{value:"gemini-cli",children:"Gemini"}),s.jsx("option",{value:"hermes-cli",children:"Hermes"})]})}),S=i&&s.jsx("div",{className:"mt-3 text-[12px] text-green-400 bg-green-500/10 border border-green-500/20 rounded-lg px-3 py-2",children:i});if(p)return s.jsxs(gt,{title:w("repoMesh.host.title"),description:w("repoMesh.host.descriptionSet"),children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsxs("span",{className:`inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-[13px] text-text-primary ${m?"border-accent-primary/40 bg-accent-primary/10":"border-amber-500/40 bg-amber-500/10"}`,children:[s.jsx("span",{className:"text-text-muted",children:w("repoMesh.host.hostLabel")}),s.jsx("span",{className:"font-medium",children:d||w("repoMesh.host.unknown")}),s.jsxs("span",{className:m?"text-text-muted":"text-amber-400",children:["· ",w(m?"repoMesh.host.online":"repoMesh.host.offline")]})]}),(u==null?void 0:u.workspace)&&s.jsxs("span",{className:"text-[12px] text-text-muted",children:[w("repoMesh.host.hostNode")," ",s.jsx("span",{className:"font-mono text-text-secondary",children:u.workspace})]})]}),!m&&s.jsxs("div",{className:"mt-4",children:[s.jsxs(Dt,{variant:"warning",className:"mb-3",children:[s.jsx("strong",{children:w("repoMesh.host.hostOffline")})," ",w("repoMesh.host.hostOfflineText")]}),e.length>0?s.jsx(Nt,{label:w("repoMesh.host.reconnectToCommand"),hint:w("repoMesh.host.reconnectToCommandHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:h,onChange:y=>g(y.target.value),children:[s.jsx("option",{value:"",children:w("repoMesh.host.waitForHost")}),e.map(y=>s.jsx("option",{value:y.id,children:lr(y)},y.id))]})}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:w("repoMesh.host.noDaemonsToRoute")})]}),s.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-[180px_auto] items-end",children:[b,s.jsx("button",{className:"btn btn-primary btn-sm",onClick:k,disabled:o||!t,title:t?void 0:w("repoMesh.host.noCommandTarget"),children:w(o?"repoMesh.host.launching":"repoMesh.host.launchHost")})]}),S]});const N=e.find(y=>y.id===t),v=x&&t?s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>x(t),disabled:!!f,children:w(f?"repoMesh.host.settingHost":"repoMesh.host.setHostAction")}):null;return s.jsxs(gt,{title:w("repoMesh.host.title"),description:w("repoMesh.host.descriptionUnset"),children:[s.jsxs(Dt,{variant:"info",className:"mb-4",children:[s.jsx("strong",{children:w("repoMesh.host.setHostBanner")})," ",w("repoMesh.host.setHostBannerText")]}),e.length>0?s.jsxs(s.Fragment,{children:[t?s.jsx("div",{className:"mb-3 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:c?s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:lr(N)}),u!=null&&u.workspace?s.jsxs(s.Fragment,{children:[" · setup node ",s.jsx("span",{className:"font-mono text-text-secondary",children:u.workspace})]}):null,". ",w("repoMesh.host.confirmSetsHost")]}):s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:lr(N)}),". ",w("repoMesh.host.attachNodeThenSetHost")]})}):s.jsx(Nt,{label:w("repoMesh.host.hostDaemon"),hint:w("repoMesh.host.hostDaemonHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:"",onChange:y=>n(y.target.value),children:[s.jsx("option",{value:"",children:w("repoMesh.host.resolvingHost")}),e.map(y=>s.jsx("option",{value:y.id,children:lr(y)},y.id))]})}),v&&s.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[v,s.jsx("span",{className:"text-[12px] text-text-muted",children:w("repoMesh.host.setHostActionHint")})]}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-[180px_auto] items-end mt-3",children:[b,s.jsx("button",{className:`btn btn-sm ${v?"btn-secondary":"btn-primary"}`,onClick:k,disabled:!t||!c||o,title:t?c?void 0:w("repoMesh.host.attachNodeFirst"):w("repoMesh.host.pickHostFirst"),children:w(o?"repoMesh.host.launching":"repoMesh.host.launchHostSetsHost")})]})]}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:w("repoMesh.host.noDaemonsToHost")}),S]})}function II({meshId:e,availableCliAgents:t}){const{t:n}=Ce(),a=t.find(o=>{const i=o.id.toLowerCase();return i==="hermes-cli"||i.includes("hermes")||o.name.toLowerCase().includes("hermes")}),r=Om(a==null?void 0:a.meshCoordinator,{meshId:e});return r?s.jsx(gt,{title:n("repoMesh.hermesMcp.title"),description:n("repoMesh.hermesMcp.description"),children:s.jsx(ph,{setup:r,providerName:(a==null?void 0:a.name)||n("repoMesh.hermesMcp.fallbackProvider")})}):null}const hi=[{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."}],LI=[{value:"smart",label:"Smart",description:"Match each task to the node whose capability slot best fits it (task difficulty + capability tags), then load-spread among ties. Auto-enabled when any node has capability slots."},{value:"spread",label:"Spread",description:"Distribute work evenly across eligible nodes (prefers the least-loaded, rotating ties fairly). Set a per-node priority below to bias the order."},{value:"in_order",label:"In order",description:"Assign to nodes in the order they were added — the first eligible node takes the work. No load-spreading."}];function RI(e){return e==="smart"?"fitness":e==="spread"?"least_loaded":"first_eligible"}function EI(e,t){const n=e||"first_eligible";return n==="fitness"?"smart":n==="first_eligible"?"in_order":n==="priority_only"?t!=null&&t.priorityConfigured?"spread":"in_order":n==="least_loaded"||n==="round_robin"?"spread":"in_order"}const _I={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,schedulingStrategy:"first_eligible",sessionCleanupOnNodeRemove:"preserve"};function Ji(e){return{..._I,...(e==null?void 0:e.policy)||{}}}function HI(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 $I({selectedMesh:e,error:t,onDismissError:n,onBack:a,onDelete:r,displayedMeshStatus:o,graphLoading:i,graphError:c,onRefreshGraph:u,savingPolicy:p,onUpdatePolicy:d,coordinatorPromptDraft:m,onCoordinatorPromptDraftChange:h,savingCoordinatorPrompt:g,onSaveCoordinatorPrompt:k,daemons:f,coordinatorDaemonId:x,onCoordinatorDaemonIdChange:w,coordinatorCliType:b,onCoordinatorCliTypeChange:S,launchingCoordinator:N,launchResult:v,isHostNodeAttached:y,selectedHostNode:j,hostPinned:C,hostLabel:A,hostOnline:T,hostRebindDaemonId:D,onHostRebindDaemonIdChange:I,onLaunchCoordinator:M,settingMeshHost:P,onSetMeshHost:$,activeDaemon:L,activeDaemonId:R,meshQueue:F,userName:E,availableCliProviders:H,savingNodeSlotsId:_,onUpdateNodeSlots:G,savingNodeCapabilitiesId:W,onUpdateNodeCapabilities:K,nodeSystemPromptDrafts:V,onNodeSystemPromptDraftChange:te,savingNodeSystemPromptId:le,onSaveNodeSystemPrompt:de,selectedNodeId:ee,onSelectNode:z,showAddNode:X,onShowAddNode:U,onCancelAddNode:Q,nodeWorkspace:ke,onNodeWorkspaceChange:ve,nodeProviderPriority:ge,onNodeProviderPriorityChange:me,nodeDaemonId:B,onNodeDaemonIdChange:O,nodeCustomPath:Y,onNodeCustomPathChange:se,nodePickerWorkspaces:Z,nodePickerProviders:Ne,nodeOnboardingPlan:pe,nodePlanLoading:fe,attachableDaemons:Me,onAddNode:Ee,onRemoveNode:q,availableCliAgents:oe,features:Ie,sendCommand:xe}){const{t:he}=Ce("common"),Ze=Ji(e),Ae=e.nodes||[],_e=l.useMemo(()=>ZP(Ae,f),[Ae,f]),ie=Ae.some(it=>{var J;const mt=Number((J=it.policy)==null?void 0:J.schedulingPriority);return Number.isFinite(mt)&&mt!==0}),je=!Ze.schedulingStrategy,De=l.useMemo(()=>Ae.some(it=>{var mt;return Array.isArray((mt=it.policy)==null?void 0:mt.slots)&&it.policy.slots.length>0}),[Ae]),qe=je?De?"smart":Ae.length>=2?"spread":null:null,[ye,Fe]=l.useState(!1),ut=!!R&&!!e.id;return s.jsxs(Fa,{icon:s.jsx(as,{}),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:he("repoMesh.detail.back")}),s.jsxs("button",{className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:()=>u(!0),disabled:i,children:[s.jsx(FP,{size:13}),he(i?"repoMesh.detail.probing":"repoMesh.detail.refresh")]}),s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>r(e.id),children:he("repoMesh.detail.delete")})]}),children:[t&&s.jsx(Dt,{variant:"error",onDismiss:n,className:"mb-4",children:t}),(()=>{var be;const it=s.jsxs(s.Fragment,{children:[Ie.meshHostDaemonSection&&s.jsx(PI,{daemons:f,coordinatorDaemonId:x,onCoordinatorDaemonIdChange:w,coordinatorCliType:b,onCoordinatorCliTypeChange:S,launchingCoordinator:N,launchResult:v,isHostNodeAttached:y,selectedHostNode:j,hostPinned:C,hostLabel:A,hostOnline:T,hostRebindDaemonId:D,onHostRebindDaemonIdChange:re=>{I(re),u()},onLaunchCoordinator:M,settingMeshHost:P,onSetMeshHost:$}),s.jsxs(gt,{title:he("repoMesh.detail.observabilityTitle"),description:he("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:()=>Fe(!0),disabled:!ut,title:he(ut?"repoMesh.detail.observabilityOpenTitle":"repoMesh.detail.observabilityDisabledTitle"),children:[s.jsx(as,{size:14}),he("repoMesh.detail.observabilityOpen")]}),s.jsx("span",{className:"text-[12px] text-text-muted",children:he("repoMesh.detail.observabilityHint")})]})]}),s.jsx(uI,{nodes:Ae,meshQueue:F,activeDaemon:L,daemons:f,selectedMeshId:e.id,userName:E,features:{addNodeDaemonPicker:Ie.addNodeDaemonPicker,nodeInstruction:Ie.nodeInstruction},coordinatorDaemonId:x,availableCliProviders:H,savingNodeSlotsId:_,onUpdateNodeSlots:G,savingNodeCapabilitiesId:W,onUpdateNodeCapabilities:K,nodeSystemPromptDrafts:V,onNodeSystemPromptDraftChange:te,savingNodeSystemPromptId:le,onSaveNodeSystemPrompt:de,selectedNodeId:ee,onSelectNode:z,showAddNode:X,onShowAddNode:U,onCancelAddNode:Q,nodeWorkspace:ke,onNodeWorkspaceChange:ve,nodeProviderPriority:ge,onNodeProviderPriorityChange:me,nodeDaemonId:B,onNodeDaemonIdChange:O,nodeCustomPath:Y,onNodeCustomPathChange:se,nodePickerWorkspaces:Z,nodePickerProviders:Ne,nodeOnboardingPlan:pe,nodePlanLoading:fe,attachableDaemons:Me,onAddNode:Ee,onRemoveNode:q})]}),mt=s.jsxs(s.Fragment,{children:[s.jsxs(gt,{title:he("repoMesh.detail.schedulingTitle"),description:he("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:he("repoMesh.detail.distribution")}),s.jsx("div",{className:"flex flex-col gap-2",children:LI.map(re=>{const He=EI(Ze.schedulingStrategy,{priorityConfigured:ie})===re.value;return s.jsxs("label",{className:`flex items-start gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${He?"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:re.value,checked:He,disabled:p,onChange:()=>d({schedulingStrategy:RI(re.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.label,qe===re.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:he("repoMesh.detail.recommended")})]}),s.jsx("span",{className:"block text-[12px] text-text-muted",children:re.description})]})]},re.value)})})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:he("repoMesh.detail.saving")})]}),s.jsx(gt,{title:he("repoMesh.detail.visibilityTitle"),description:he("repoMesh.detail.visibilityDescription"),children:s.jsx(Nt,{label:he("repoMesh.detail.visibilityLabel"),hint:he("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:Ze.spawnedSessionVisibility==="visible"?"visible":"hidden",onChange:re=>d({spawnedSessionVisibility:re.target.value==="visible"?"visible":"hidden"}),disabled:p,children:[s.jsx("option",{value:"hidden",children:he("repoMesh.detail.visibilityHidden")}),s.jsx("option",{value:"visible",children:he("repoMesh.detail.visibilityVisible")})]})})}),o&&s.jsx(gt,{title:he("repoMesh.detail.magiTitle"),description:he("repoMesh.detail.magiDescription"),children:s.jsx(gI,{status:o,daemonId:R,sendDaemonCommand:xe,availableProviders:H})}),s.jsx(MI,{hostDaemonId:x,hostOnline:T,hostWorkspace:(j==null?void 0:j.workspace)||"",meshProviders:_e.providers,unreportedNodeCount:_e.unreportedNodeCount,machineAutoApproveEnabled:Ze.delegatedWorkerAutoApprove!==!1,machineDangerousAllowed:Ze.delegatedWorkerDangerousModeAllow===!0,onUpdatePolicy:d,savingPolicy:p,sendCommand:xe})]}),J=s.jsx(s.Fragment,{children:Ie.coordinatorPrompt&&s.jsxs(gt,{title:he("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:he("repoMesh.detail.advanced")}),description:he("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:he("repoMesh.detail.thisMesh")}),s.jsx("p",{className:"text-[12px] text-text-muted mb-3",children:he("repoMesh.detail.thisMeshHint",{name:e.name})}),s.jsxs(Nt,{label:he("repoMesh.detail.overrideLabel"),hint:he("repoMesh.detail.overrideHint"),children:[s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:6,value:m.override,onChange:re=>h({...m,override:re.target.value}),disabled:g,placeholder:he("repoMesh.detail.overridePlaceholder")}),s.jsx(xI,{daemonId:R,meshId:e.id,cliType:b,sendCommand:xe})]}),s.jsx(Nt,{label:he("repoMesh.detail.appendLabel"),hint:he("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:re=>h({...m,append:re.target.value}),disabled:g,placeholder:he("repoMesh.detail.appendPlaceholder")})}),s.jsxs("details",{className:"mt-2 text-[12px] text-text-muted",children:[s.jsx("summary",{className:"cursor-pointer select-none",children:he("repoMesh.detail.availablePlaceholders")}),s.jsx("p",{className:"mt-1 font-mono break-words",children:"{{meshName}}, {{repo}}, {{defaultBranch}}, {{cliType}}, {{nodes}}, {{policy}}, {{tools}}, {{workflow}}, {{rules}}, {{toolExposurePreflight}}"})]}),s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:k,disabled:g,children:he(g?"repoMesh.detail.saving":"repoMesh.detail.saveCoordinatorPrompt")}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>h({override:"",append:""}),disabled:g,title:he("repoMesh.detail.clearTitle"),children:he("repoMesh.detail.clear")})]})]}),s.jsxs("div",{className:"mt-5 border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-1",children:he("repoMesh.detail.userLevel")}),s.jsx("p",{className:"text-[12px] text-text-muted mb-3",children:he("repoMesh.detail.userLevelDescription")}),s.jsx(aj,{daemonId:R||void 0})]})]})}),ne=s.jsxs(s.Fragment,{children:[s.jsx(jI,{status:o,daemonId:R,meshId:e.id,sendCommand:xe}),s.jsxs(gt,{title:he("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:he("repoMesh.detail.advanced")}),description:he("repoMesh.detail.safetyDescription"),children:[s.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:[{label:he("repoMesh.detail.checkpointBefore"),key:"requirePreTaskCheckpoint",opts:[["no","No"],["yes","Yes"]],val:re=>re?"yes":"no",parse:re=>re==="yes"},{label:he("repoMesh.detail.checkpointAfter"),key:"requirePostTaskCheckpoint",opts:[["yes","Yes"],["no","No"]],val:re=>re?"yes":"no",parse:re=>re==="yes"},{label:he("repoMesh.detail.pushApproval"),key:"requireApprovalForPush",opts:[["required",he("repoMesh.detail.requireApprovalBeforePush")],["not_required",he("repoMesh.detail.doNotRequireApproval")]],val:re=>re?"required":"not_required",parse:re=>re==="required"},{label:he("repoMesh.detail.destructiveGitApproval"),key:"requireApprovalForDestructiveGit",opts:[["required",he("repoMesh.detail.requireApproval")],["not_required",he("repoMesh.detail.doNotRequireApproval")]],val:re=>re?"required":"not_required",parse:re=>re==="required"},{label:he("repoMesh.detail.uncommittedChanges"),key:"dirtyWorkspaceBehavior",opts:[["warn",he("repoMesh.detail.warnAndContinue")],["block",he("repoMesh.detail.blockTask")],["checkpoint_then_continue",he("repoMesh.detail.checkpointThenContinue")]],val:re=>re||"warn",parse:re=>re},{label:he("repoMesh.detail.autoPublishSubmodule"),key:"allowAutoPublishSubmoduleMainCommits",opts:[["disabled",he("repoMesh.detail.requireExplicitApproval")],["enabled",he("repoMesh.detail.allowRefineryPublish")]],val:re=>re?"enabled":"disabled",parse:re=>re==="enabled"}].map(({label:re,key:Te,opts:He,val:Pe,parse:Ge})=>s.jsx(Nt,{label:re,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:Pe(Ze[Te]),onChange:ze=>d({[Te]:Ge(ze.target.value)}),disabled:p,children:He.map(([ze,Je])=>s.jsx("option",{value:ze,children:Je},ze))})},Te))}),(()=>{const re=Ze.autoFastForward&&typeof Ze.autoFastForward=="object"?Ze.autoFastForward:{},Te=re.enabled!==!1,He=re.remoteNodes===!0,Pe=re.mode==="continuous"?"continuous":"idle",Ge=ze=>d({autoFastForward:{...re,...ze}});return s.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[s.jsx(Nt,{label:he("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:Te?"enabled":"disabled",onChange:ze=>Ge({enabled:ze.target.value==="enabled"}),disabled:p,children:[s.jsx("option",{value:"enabled",children:he("repoMesh.detail.ffEnabled")}),s.jsx("option",{value:"disabled",children:he("repoMesh.detail.ffDisabled")})]})}),s.jsx(Nt,{label:he("repoMesh.detail.includeRemoteNodes"),hint:he("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:He?"yes":"no",onChange:ze=>Ge({remoteNodes:ze.target.value==="yes"}),disabled:p||!Te,children:[s.jsx("option",{value:"no",children:he("repoMesh.detail.remoteNo")}),s.jsx("option",{value:"yes",children:he("repoMesh.detail.remoteYes")})]})}),s.jsx(Nt,{label:he("repoMesh.detail.detectionMode"),hint:he("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:Pe,onChange:ze=>Ge({mode:ze.target.value==="continuous"?"continuous":"idle"}),disabled:p||!Te||!He,children:[s.jsx("option",{value:"idle",children:he("repoMesh.detail.idleEdgeOnly")}),s.jsx("option",{value:"continuous",children:he("repoMesh.detail.continuousScan")})]})})]})})(),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(Nt,{label:he("repoMesh.detail.sessionCleanupLabel"),hint:he("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:Ze.sessionCleanupOnNodeRemove||"preserve",onChange:re=>d({sessionCleanupOnNodeRemove:re.target.value}),disabled:p,children:hi.map(re=>s.jsx("option",{value:re.value,children:re.label},re.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((be=hi.find(re=>re.value===Ze.sessionCleanupOnNodeRemove))==null?void 0:be.description)||hi[0].description})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:he("repoMesh.detail.saving")})]})]}),ce=[{key:"nodes",label:he("repoMesh.detail.tabNodes"),content:it},{key:"scheduling",label:he("repoMesh.detail.tabScheduling"),content:mt},{key:"prompts",label:he("repoMesh.detail.tabPrompts"),content:s.jsxs(s.Fragment,{children:[J,Ie.hermesMcpConfig&&s.jsx(II,{meshId:e.id,availableCliAgents:oe}),Ie.meshHostDaemonSection&&s.jsxs(Dt,{variant:"info",className:"mt-4",children:[s.jsx("strong",{children:"MCP Mode:"})," ",s.jsxs("code",{className:"bg-bg-secondary px-1 rounded text-xs",children:["adhdev mcp --repo-mesh ",e.id]})," · The mesh MCP server can be used directly from your CLI agent."]})]})},{key:"advanced",label:he("repoMesh.detail.tabAdvanced"),content:ne}];return s.jsxs(s.Fragment,{children:[s.jsx(zP,{tabs:ce,ariaLabel:he("repoMesh.detail.tabsAriaLabel"),className:"flex flex-col gap-4"}),ye&&ut&&s.jsx(Vh,{activeConv:HI({meshId:e.id,daemonId:R,meshName:e.name}),sendDaemonCommand:xe,onClose:()=>Fe(!1)})]})})()]})}const ca=new Map;async function FI(e){var r,o,i,c,u,p,d,m,h,g,k;const{sendCommand:t,unwrapResult:n}=e,a={meshCreated:!1,meshId:"",error:null,warning:null,plan:null};try{const f=await t(e.targetDaemonId,"plan_mesh_onboarding",{workspace:e.workspace||void 0,operation:"auto",meshInventory:e.meshInventory}),x=n(f);if(a.plan=x,(x==null?void 0:x.success)===!1)return{...a,error:`${x.code||"onboarding_blocked"}: ${x.error}${x.action?` ${x.action}`:""}`};if(((r=x==null?void 0:x.plan)==null?void 0:r.kind)!=="create_mesh_and_onboard")return{...a,error:((o=x==null?void 0:x.plan)==null?void 0:o.summary)||"A compatible mesh already exists; add this workspace to it instead of creating a duplicate mesh."};const w={name:e.name.trim()};(e.repoRemoteUrl||(u=(c=(i=x==null?void 0:x.discovery)==null?void 0:i.origin)==null?void 0:c.urls)!=null&&u[0])&&(w.repoRemoteUrl=e.repoRemoteUrl||x.discovery.origin.urls[0]),(e.repoIdentity||(p=x==null?void 0:x.discovery)!=null&&p.repoIdentity)&&(w.repoIdentity=e.repoIdentity||x.discovery.repoIdentity),(d=x==null?void 0:x.discovery)!=null&&d.defaultBranch&&(w.defaultBranch=x.discovery.defaultBranch);const b=await t(e.targetDaemonId,"create_mesh",w),S=n(b);if((S==null?void 0:S.success)===!1)return{...a,error:S.error||"Create failed"};const N=typeof((m=S==null?void 0:S.mesh)==null?void 0:m.id)=="string"?S.mesh.id:"",v={...a,meshCreated:!0,meshId:N};if(!N||!e.attachWorkspace||!e.workspace)return v;try{const y=await t(e.targetDaemonId,"add_mesh_node",{meshId:N,daemonId:e.targetDaemonId,machineId:e.machineId,workspace:((h=x==null?void 0:x.discovery)==null?void 0:h.repoRoot)||e.workspace,repoRoot:(g=x==null?void 0:x.discovery)==null?void 0:g.repoRoot,isLocalWorktree:((k=x==null?void 0:x.discovery)==null?void 0:k.isLinkedWorktree)===!0,role:"host",providerPriority:e.providerPriority}),j=n(y);return(j==null?void 0:j.success)===!1?{...v,warning:xu(j.error||"add_mesh_node failed")}:v}catch(y){return{...v,warning:xu((y==null?void 0:y.message)||"add_mesh_node failed")}}}catch(f){return{...a,error:(f==null?void 0:f.message)||"Create failed"}}}function xu(e){return`Mesh created, but attaching the workspace failed: ${e}. Add the workspace from the mesh's node list.`}function BI({daemons:e,primaryDaemonId:t,sendCommand:n,unwrapResult:a,normalizeMesh:r,features:o,loadDaemonMetadata:i}){const c=e.map(de=>de.id).filter(Boolean).sort().join(","),[u,p]=l.useState(()=>ca.get(c)??[]),[d,m]=l.useState(null),[h,g]=l.useState(()=>!ca.has(c)),[k,f]=l.useState(null),[x,w]=l.useState(!1),[b,S]=l.useState(!1),[N,v]=l.useState(null),[y,j]=l.useState(""),[C,A]=l.useState(""),[T,D]=l.useState(""),[I,M]=l.useState(""),[P,$]=l.useState(""),[L,R]=l.useState(null),[F,E]=l.useState(!1),H=l.useMemo(()=>e.find(de=>de.id===I),[e,I]),_=(H==null?void 0:H.workspaces)||[],G=l.useMemo(()=>Un((H==null?void 0:H.availableProviders)||[]),[H]);l.useEffect(()=>{!o.createDaemonPicker||!i||!I||!H||!(!H.workspaces||!H.availableProviders)||Promise.resolve(i(I,{minFreshMs:3e4})).catch(()=>{})},[o.createDaemonPicker,i,I,H]),l.useEffect(()=>{if(!x||!I||!P){R(null);return}let de=!1;return E(!0),n(I,"plan_mesh_onboarding",{workspace:P,operation:"auto",meshInventory:u}).then(ee=>{if(de)return;const z=a(ee);R(z),z!=null&&z.success&&(A(X=>{var U;return X||((U=z.discovery)==null?void 0:U.repoIdentity)||""}),D(X=>{var U,Q,ke,ve,ge,me;return X||((ke=(Q=(U=z.discovery)==null?void 0:U.origin)==null?void 0:Q.urls)==null?void 0:ke[0])||((me=(ge=(ve=z.discovery)==null?void 0:ve.upstream)==null?void 0:ge.urls)==null?void 0:me[0])||""}),j(X=>{var U,Q;return X||`${String(((U=z.discovery)==null?void 0:U.repoIdentity)||((Q=z.discovery)==null?void 0:Q.repoRoot)||"").split(/[\\/]/).filter(Boolean).pop()||"repo"}-mesh`}))}).catch(ee=>{de||R({success:!1,error:(ee==null?void 0:ee.message)||"Git discovery failed"})}).finally(()=>{de||E(!1)}),()=>{de=!0}},[x,I,P,u,n,a]);const W=l.useMemo(()=>e.map(de=>de.id).filter(Boolean).sort().join(","),[e]),K=l.useCallback(async(de=!1)=>{const ee=de||ca.has(W);g(z=>ee?z:!0);try{if(o.createDaemonPicker){const z=await Promise.allSettled(e.map(async Q=>{if(!Q.id)return[];const ke=await n(Q.id,"list_meshes",{}),ve=a(ke);if((ve==null?void 0:ve.success)===!1)throw new Error(ve.error||"Failed to load meshes");return(Array.isArray(ve==null?void 0:ve.meshes)?ve.meshes:[]).map(ge=>r(ge,Q.id)).filter(ge=>ge.id)})),X=new Map;for(const Q of z)if(Q.status==="fulfilled")for(const ke of Q.value)X.has(ke.id)||X.set(ke.id,ke);const U=Array.from(X.values());p(U),ca.set(W,U),f(null)}else{if(!t)return;const z=await n(t,"list_meshes");if(z!=null&&z.success){const X=(z.meshes||[]).map(U=>r(U,t));p(X),ca.set(W,X),f(null)}else f((z==null?void 0:z.error)||"Failed to load meshes")}}catch(z){f((z==null?void 0:z.message)||"Failed to load meshes")}finally{g(!1)}},[W,t,n,a,r,o.createDaemonPicker]);async function V(){const de=o.createDaemonPicker?I:t;if(!de||!y.trim())return;const ee=T.trim(),z=C.trim();if(!(!ee&&!z)&&!b){S(!0),v(null);try{const X=await FI({targetDaemonId:de,name:y,repoRemoteUrl:ee,repoIdentity:z,workspace:P,attachWorkspace:o.createDaemonPicker,machineId:H==null?void 0:H.machineId,providerPriority:Pa(G),meshInventory:u,sendCommand:n,unwrapResult:a});if(X.plan!==null&&R(X.plan),X.warning&&v(X.warning),!X.meshCreated){f(X.error||"Create failed");return}w(!1),j(""),A(""),D(""),$(""),await K(),X.meshId&&m(X.meshId)}finally{S(!1)}}}async function te(de){var z;if(!confirm("Delete this mesh? This cannot be undone."))return;const ee=((z=u.find(X=>X.id===de))==null?void 0:z.__sourceDaemonId)||t;try{const X=await n(ee,"delete_mesh",{meshId:de}),U=a(X);if((U==null?void 0:U.success)===!1)throw new Error(U.error||"Failed to delete");d===de&&m(null),await K()}catch(X){f((X==null?void 0:X.message)||"Delete failed")}}function le(){w(!1),j(""),A(""),D(""),v(null)}return{meshes:u,setMeshes:p,selectedMeshId:d,setSelectedMeshId:m,loading:h,error:k,setError:f,showCreate:x,setShowCreate:w,creating:b,createWarning:N,setCreateWarning:v,createName:y,setCreateName:j,createRepoIdentity:C,setCreateRepoIdentity:A,createRepoRemoteUrl:T,setCreateRepoRemoteUrl:D,newMeshDaemonId:I,setNewMeshDaemonId:M,newMeshWorkspace:P,setNewMeshWorkspace:$,createPickerWorkspaces:_,createPickerProviders:G,createOnboardingPlan:L,createPlanLoading:F,loadMeshes:K,handleCreate:V,handleDelete:te,cancelCreate:le}}function WI({selectedMesh:e,selectedMeshId:t,primaryDaemonId:n,activeDaemonId:a,daemons:r,sendCommand:o,unwrapResult:i,loadLiveMesh:c,resolveCommandTarget:u,launchCoordinator:p,features:d,loadMeshes:m,loadQueue:h,queueSection:g,setError:k}){const[f,x]=l.useState({}),[w,b]=l.useState(null),[S,N]=l.useState(null),[v,y]=l.useState(!1),[j,C]=l.useState(""),[A,T]=l.useState([]),[D,I]=l.useState(""),[M,P]=l.useState(!1),[$,L]=l.useState(null),[R,F]=l.useState(!1),[E,H]=l.useState(""),[_,G]=l.useState(!1),[W,K]=l.useState(!1),[V,te]=l.useState(null),[le,de]=l.useState(!1),[ee,z]=l.useState({override:"",append:""}),[X,U]=l.useState(!1),[Q,ke]=l.useState({}),[ve,ge]=l.useState(null),me=l.useMemo(()=>r.find(Ae=>Ae.id===D),[r,D]),B=(me==null?void 0:me.workspaces)||[],O=l.useMemo(()=>Un((me==null?void 0:me.availableProviders)||[]),[me]);l.useEffect(()=>{if(!v||!t||!j.trim()){L(null);return}const Ae=d.addNodeDaemonPicker?D:(e==null?void 0:e.__sourceDaemonId)||n;if(!Ae)return;let _e=!1;return F(!0),o(Ae,"plan_mesh_onboarding",{workspace:j.trim(),meshId:t,inlineMesh:e,operation:"add_existing"}).then(ie=>{_e||L(i(ie))}).catch(ie=>{_e||L({success:!1,error:(ie==null?void 0:ie.message)||"Git discovery failed"})}).finally(()=>{_e||F(!1)}),()=>{_e=!0}},[v,t,e,j,D,n,d.addNodeDaemonPicker,o,i]);async function Y(){var ie,je,De;const Ae=(e==null?void 0:e.__sourceDaemonId)||n;if(!t||!Ae)return;const _e=j.trim();if(_e)try{const qe=d.addNodeDaemonPicker?D:Ae,ye=await o(qe,"plan_mesh_onboarding",{workspace:_e,meshId:t,inlineMesh:e,operation:"add_existing"}),Fe=i(ye);if(L(Fe),(Fe==null?void 0:Fe.success)===!1)throw new Error(`${Fe.code||"onboarding_blocked"}: ${Fe.error}${Fe.action?` ${Fe.action}`:""}`);const ut={meshId:t,workspace:((ie=Fe==null?void 0:Fe.discovery)==null?void 0:ie.repoRoot)||_e,repoRoot:(je=Fe==null?void 0:Fe.discovery)==null?void 0:je.repoRoot,isLocalWorktree:((De=Fe==null?void 0:Fe.discovery)==null?void 0:De.isLinkedWorktree)===!0};d.addNodeDaemonPicker&&D&&(ut.daemonId=D,ut.machineId=me==null?void 0:me.machineId),ut.providerPriority=qn(A);const it=await o(Ae,"add_mesh_node",ut),mt=i(it);if((mt==null?void 0:mt.success)===!1)throw new Error(mt.error||"Add node failed");y(!1),C(""),T([]),I(""),P(!1),await m(),g||await h(t)}catch(qe){k((qe==null?void 0:qe.message)||"Add node failed")}}async function se(Ae){var De;if(!e)return;const _e=Ji(e),ie=((De=[{value:"preserve",label:"Preserve history and runtimes"},{value:"stop",label:"Stop live runtimes only"},{value:"delete_stopped",label:"Delete stopped sessions only"},{value:"stop_and_delete",label:"Stop and delete sessions"}].find(qe=>qe.value===_e.sessionCleanupOnNodeRemove))==null?void 0:De.label)||"Preserve history and runtimes";if(!confirm(`Remove this node?
|
|
120
120
|
|
|
121
|
-
Node removal cleanup policy: ${ie}`))return;const je=e.__sourceDaemonId||n;try{const qe=await o(je,"remove_mesh_node",{meshId:e.id,nodeId:Ae}),ye=i(qe);if((ye==null?void 0:ye.success)===!1)throw new Error(ye.error||"Remove failed");S===Ae&&N(null),await m(),g||await h(t)}catch(qe){k((qe==null?void 0:qe.message)||"Remove node failed")}}async function Z(Ae){if(!e)return;const _e={...Ji(e),...Ae},ie=e.__sourceDaemonId||n;try{de(!0),k(null);const je=await o(ie,"update_mesh",{meshId:e.id,policy:_e}),De=i(je);if((De==null?void 0:De.success)===!1)throw new Error(De.error||"Policy update failed");await m()}catch(je){k((je==null?void 0:je.message)||"Policy update failed")}finally{de(!1)}}async function Ne(Ae){if(!t)return;const _e=(e==null?void 0:e.__sourceDaemonId)||n,ie=f[Ae.id]||OI(Ae),je=qn(ie),De={...Ae.policy||{}};delete De.provider_priority,je.length?De.providerPriority=je:delete De.providerPriority;try{b(Ae.id),k(null);const qe=await o(_e,"update_mesh_node",{meshId:t,nodeId:Ae.id,policy:De,providerPriority:je}),ye=i(qe);if((ye==null?void 0:ye.success)===!1){k(ye.error||"Node policy update failed");return}await m()}catch(qe){k((qe==null?void 0:qe.message)||"Node policy update failed")}finally{b(null)}}const[pe,fe]=l.useState(null);async function Me(Ae,_e){if(!t)return;const ie=(e==null?void 0:e.__sourceDaemonId)||n;try{fe(Ae.id),k(null);const je=await o(ie,"update_mesh_node",{meshId:t,nodeId:Ae.id,policy:{slots:_e}}),De=i(je);if((De==null?void 0:De.success)===!1){k(De.error||"Node slots update failed");return}await m()}catch(je){k((je==null?void 0:je.message)||"Node slots update failed")}finally{fe(null)}}const[Ee,q]=l.useState(null);async function oe(Ae,_e){if(!t)return;const ie=(e==null?void 0:e.__sourceDaemonId)||n,je=_e.map(De=>De.trim()).filter(Boolean);try{q(Ae.id),k(null);const De=await o(ie,"update_mesh_node",{meshId:t,nodeId:Ae.id,capabilities:je}),qe=i(De);if((qe==null?void 0:qe.success)===!1){k(qe.error||"Node tag update failed");return}await m()}catch(De){k((De==null?void 0:De.message)||"Node tag update failed")}finally{q(null)}}async function Ie(){if(!n||!t)return;const _e={...(e==null?void 0:e.coordinator)||{}};ee.override.trim()?_e.systemPromptOverride=ee.override:delete _e.systemPromptOverride,ee.append.trim()?_e.systemPromptAppend=ee.append:delete _e.systemPromptAppend,delete _e.systemPromptSuffix;try{U(!0),k(null);const ie=await o(n,"update_mesh",{meshId:t,coordinator:_e}),je=i(ie);if((je==null?void 0:je.success)===!1){k(je.error||"Coordinator prompt save failed");return}await m()}catch(ie){k((ie==null?void 0:ie.message)||"Coordinator prompt save failed")}finally{U(!1)}}async function xe(Ae){if(!n||!t)return;const _e=(Q[Ae.id]||"").trim();try{ge(Ae.id),k(null);const ie=await o(n,"update_mesh_node",{meshId:t,nodeId:Ae.id,systemPrompt:_e}),je=i(ie);if((je==null?void 0:je.success)===!1){k(je.error||"Node instruction save failed");return}await m()}catch(ie){k((ie==null?void 0:ie.message)||"Node instruction save failed")}finally{ge(null)}}async function he(Ae){if(!(!e||!Ae)){k(null),te(null);try{K(!0);const _e=(e.nodes||[]).find(De=>zs(String(De.daemon_id||De.daemonId||""),Ae)),ie=await o(Ae,"set_mesh_host",{meshId:e.id,hostDaemonId:Ae,..._e!=null&&_e.id?{hostNodeId:_e.id}:{}}),je=i(ie);if((je==null?void 0:je.success)===!1){k(je.error||"Setting the mesh host failed");return}await m()}catch(_e){k((_e==null?void 0:_e.message)||"Setting the mesh host failed")}finally{K(!1)}}}async function Ze(){if(e){k(null),te(null);try{G(!0);const Ae=c?await c(a,e.id,e):null,_e=u(a,e.id,e,e.nodes||[],Ae);if("error"in _e)throw new Error(_e.error);const ie=await p(_e.targetDaemonId,{meshId:e.id,inlineMesh:_e.inlineMesh,coordinatorNodeId:_e.coordinatorNodeId,cliType:E.trim()||void 0});te(ie.message)}catch(Ae){k((Ae==null?void 0:Ae.message)||"Coordinator launch failed")}finally{G(!1)}}}return{nodeProviderPriorityDrafts:f,setNodeProviderPriorityDrafts:x,savingNodePolicyId:w,selectedNodeId:S,setSelectedNodeId:N,showAddNode:v,setShowAddNode:y,nodeWorkspace:j,setNodeWorkspace:C,nodeProviderPriority:A,setNodeProviderPriority:T,nodeDaemonId:D,setNodeDaemonId:I,nodeCustomPath:M,setNodeCustomPath:P,nodePickerWorkspaces:B,nodePickerProviders:O,nodeOnboardingPlan:$,nodePlanLoading:R,coordinatorCliType:E,setCoordinatorCliType:H,launchingCoordinator:_,launchResult:V,settingMeshHost:W,savingPolicy:le,coordinatorPromptDraft:ee,setCoordinatorPromptDraft:z,savingCoordinatorPrompt:X,nodeSystemPromptDrafts:Q,setNodeSystemPromptDrafts:ke,savingNodeSystemPromptId:ve,savingNodeSlotsId:pe,savingNodeCapabilitiesId:Ee,handleAddNode:Y,handleRemoveNode:se,handleUpdatePolicy:Z,handleUpdateNodeProviderPriority:Ne,handleUpdateNodeSlots:Me,handleUpdateNodeCapabilities:oe,handleSaveCoordinatorPrompt:Ie,handleSaveNodeSystemPrompt:xe,handleLaunchCoordinator:Ze,handleSetMeshHost:he}}function OI(e){var a;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((a=e.policy)==null?void 0:a.providerPriority)?e.policy.providerPriority:[],n=new Set;return t.map(r=>typeof r=="string"?r.trim():"").filter(Boolean).filter(r=>n.has(r)?!1:(n.add(r),!0))}function UI(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 qI({primaryDaemonId:e,activeDaemonId:t,sendCommand:n,unwrapResult:a,loadLiveMesh:r,resolveCommandTarget:o}){const[i,c]=l.useState([]),[u,p]=l.useState(null),[d,m]=l.useState(!1),[h,g]=l.useState(null),k=l.useCallback(async x=>{if(!e||!x){c([]);return}try{const w=await n(e,"get_mesh_queue",{meshId:x});c(w!=null&&w.success?Array.isArray(w.queue)?w.queue:[]:[])}catch{c([])}},[e,n]);async function f(x){var w,b;if(x){m(!0),g(null);try{const S=r?await r(t,x.id,x):null,N=o(t,x.id,x,x.nodes||[],S);if("error"in N)throw new Error(N.error);const v=await n(N.targetDaemonId,"get_mesh_queue",{meshId:x.id}),y=a(v);if((y==null?void 0:y.success)===!1)throw new Error(y.error||"Queue load failed");const j=Array.isArray(((w=y==null?void 0:y.result)==null?void 0:w.rows)??(y==null?void 0:y.rows)??(y==null?void 0:y.queue))?((b=y==null?void 0:y.result)==null?void 0:b.rows)??(y==null?void 0:y.rows)??(y==null?void 0:y.queue):[];p(UI(j))}catch(S){g((S==null?void 0:S.message)||"Queue load failed")}finally{m(!1)}}}return{meshQueue:i,setMeshQueue:c,queueSummary:u,queueLoading:d,queueError:h,loadQueue:k,handleLoadQueue:f}}function GI(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}const ef=new Map;function tf(e){return e?ef.get(e)??null:null}function zI(e,t){!e||!t||ef.set(e,t)}function KI({selectedMeshId:e,loadMeshStatus:t,extractStatus:n,normalizeNode:a,gateIncompleteGraph:r}){const[o,i]=l.useState(()=>tf(e)),[c,u]=l.useState(!1),[p,d]=l.useState(null),[m,h]=l.useState("idle"),[g,k]=l.useState(!1),f=l.useRef(!1);async function x(w,b=e,S=!1){if(!(!w||!b))try{u(!S&&o===null),h(S?"settling":"first_paint"),d(null);const N=await t(w,b,{refresh:S,retryProfile:S?"settled":"interactive"});k(GI(N));const v=n(N),y=a&&v?{...v,nodes:(v.nodes??[]).map(j=>a(j,v.meshId??b,""))}:v;if(y){if(r&&!S&&o!==null&&!zA(Dh(y))){h("settling"),f.current||(f.current=!0,Promise.resolve().then(()=>x(w,b,!0)).finally(()=>{f.current=!1}));return}i(y),zI(b,y),h("settled")}else i(null),d("mesh_status returned an unexpected payload."),h("idle")}catch(N){o||i(null),d((N==null?void 0:N.message)||"Failed to load mesh graph"),h("idle")}finally{u(!1)}}return{meshGraphStatus:o,setMeshGraphStatus:i,graphLoading:c,graphError:p,setGraphError:d,graphProvenance:m,graphBootstrapFallback:g,loadGraph:x}}function vu(e){return!e||e.hostSynthesized?{hostDaemonId:"",hostNodeId:""}:{hostDaemonId:String(e.hostDaemonId||""),hostNodeId:String(e.hostNodeId||"")}}function VI(e,t,n,a,r){if(!e.length)return"";const o=String(r||"");if(o){const u=e.find(p=>zs(p.id,o));return u?u.id:o}const i=t.find(u=>u.role==="host"),c=String((i==null?void 0:i.daemon_id)||(i==null?void 0:i.daemonId)||"");if(c){const u=e.find(p=>zs(p.id,c));if(u)return u.id}return""}const YI=7e3,QI=45e3;function JI(){const e=$P(),{sendCommand:t,sendData:n,daemons:a,userName:r,loadMeshStatus:o,launchCoordinator:i,loadLiveMesh:c,extractStatus:u,unwrapResult:p,normalizeMesh:d,normalizeNode:m,resolveCommandTarget:h,features:g,gateIncompleteGraph:k}=e,f=Qn(),x=a[0],w=(x==null?void 0:x.id)||"",b=l.useMemo(()=>((x==null?void 0:x.availableProviders)||[]).filter(rt=>rt.category==="cli").map(rt=>({id:rt.type||rt.id,name:rt.displayName||rt.name||rt.type,meshCoordinator:rt.meshCoordinator})),[x]),S=l.useMemo(()=>Un((x==null?void 0:x.availableProviders)||[]),[x]),{meshes:N,selectedMeshId:v,setSelectedMeshId:y,loading:j,error:C,setError:A,showCreate:T,setShowCreate:D,createName:I,setCreateName:M,createRepoIdentity:P,setCreateRepoIdentity:$,createRepoRemoteUrl:L,setCreateRepoRemoteUrl:R,newMeshDaemonId:F,setNewMeshDaemonId:E,newMeshWorkspace:H,setNewMeshWorkspace:_,createPickerWorkspaces:G,createOnboardingPlan:W,createPlanLoading:K,creating:V,createWarning:te,setCreateWarning:le,loadMeshes:de,handleCreate:ee,handleDelete:z,cancelCreate:X}=BI({daemons:a,primaryDaemonId:w,sendCommand:t,unwrapResult:p,normalizeMesh:d,features:g,loadDaemonMetadata:f}),U=N.find(Oe=>Oe.id===v)||null,{meshGraphStatus:Q,setMeshGraphStatus:ke,graphLoading:ve,graphError:ge,setGraphError:me,loadGraph:B}=KI({selectedMeshId:v,loadMeshStatus:o,extractStatus:u,normalizeNode:m,gateIncompleteGraph:k}),[O,Y]=l.useState(""),[se,Z]=l.useState(""),Ne=g.meshHostDaemonSection?O:w,{meshQueue:pe,loadQueue:fe}=qI({primaryDaemonId:w,activeDaemonId:Ne,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:h}),{setNodeProviderPriorityDrafts:Me,selectedNodeId:Ee,setSelectedNodeId:q,showAddNode:oe,setShowAddNode:Ie,nodeWorkspace:xe,setNodeWorkspace:he,nodeProviderPriority:Ze,setNodeProviderPriority:Ae,nodeDaemonId:_e,setNodeDaemonId:ie,nodeCustomPath:je,setNodeCustomPath:De,nodePickerWorkspaces:qe,nodePickerProviders:ye,nodeOnboardingPlan:Fe,nodePlanLoading:ut,coordinatorCliType:it,setCoordinatorCliType:mt,launchingCoordinator:J,launchResult:ne,savingPolicy:ce,coordinatorPromptDraft:be,setCoordinatorPromptDraft:re,savingCoordinatorPrompt:Te,nodeSystemPromptDrafts:He,setNodeSystemPromptDrafts:Pe,savingNodeSystemPromptId:Ge,savingNodeSlotsId:ze,savingNodeCapabilitiesId:Je,handleAddNode:Ue,handleRemoveNode:Qe,handleUpdatePolicy:st,handleUpdateNodeSlots:We,handleUpdateNodeCapabilities:ue,handleSaveCoordinatorPrompt:we,handleSaveNodeSystemPrompt:Se,handleLaunchCoordinator:Be,settingMeshHost:Xe,handleSetMeshHost:lt}=WI({selectedMesh:U,selectedMeshId:v,primaryDaemonId:w,activeDaemonId:Ne,daemons:a,availableCliProviders:S,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:h,launchCoordinator:i,features:{addNodeDaemonPicker:g.addNodeDaemonPicker},loadMeshes:de,loadQueue:fe,queueSection:g.queueSection,setError:A}),Ve=l.useMemo(()=>a.find(Oe=>Oe.id===Ne)||x,[a,Ne,x]),yt=l.useMemo(()=>new Set(((U==null?void 0:U.nodes)||[]).map(Oe=>String(Oe.daemon_id||Oe.daemonId||""))),[U]),Gt=l.useMemo(()=>a.filter(Oe=>Oe.id&&!yt.has(Oe.id)),[a,yt]),At=(U==null?void 0:U.nodes)||[],Xt=l.useMemo(()=>At.find(Oe=>zs(String(Oe.daemon_id||Oe.daemonId||""),O)),[At,O]),Zt=g.meshHostDaemonSection?!!Xt:!0,$t=l.useMemo(()=>{if(!g.meshHostDaemonSection||!U)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const Oe=U.meshHost,rt=Q!=null&&Q.meshId&&String(Q.meshId)===String(U.id??"")?Q.meshHost:void 0,ks=rt!=null&&rt.hostDaemonId?rt:Oe??rt,Ss=vu(ks),os=Ss.hostDaemonId,ae=At.find(Rs=>Rs.role==="host"),Ye=Ss.hostNodeId||String((ae==null?void 0:ae.id)||""),$e=Ye?At.find(Rs=>String(Rs.id)===Ye):void 0,Tt=String(($e==null?void 0:$e.daemon_id)||($e==null?void 0:$e.daemonId)||""),Ls=os||Tt;if(!Ls)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const Jn=a.find(Rs=>os&&zs(Rs.id,os))||(Tt?a.find(Rs=>zs(Rs.id,Tt)):void 0);if(Jn)return{pinned:!0,daemonId:Jn.id,label:XI(Jn),online:!0,hostNode:$e};const fo=String(($e==null?void 0:$e.machineLabel)||"")||String(($e==null?void 0:$e.workspace)||"")||Ls;return{pinned:!0,daemonId:Ls,label:fo,online:!1,hostNode:$e}},[U,At,a,Q,g.meshHostDaemonSection]),Le=$t.daemonId,et=$t.online,Rt=$t.pinned?$t.hostNode:Xt,ct=l.useMemo(()=>!g.meshHostDaemonSection||!$t.pinned?"":!et&&se&&a.some(Oe=>Oe.id===se)?se:Le,[g.meshHostDaemonSection,$t.pinned,et,se,a,Le]),Qt=l.useMemo(()=>Q?[...new Set((Q.nodes??[]).map(Oe=>String(Oe.daemonId||Oe.daemon_id||"")).filter(Boolean))]:[],[Q]),qt=Kh({status:Q,daemonId:Ne||null,extraDaemonIds:Qt,meshId:v,sendData:n});l.useEffect(()=>{Me(Object.fromEntries(((U==null?void 0:U.nodes)||[]).map(Oe=>[Oe.id,ZI(Oe)])))},[U]),l.useEffect(()=>{const Oe=(U==null?void 0:U.coordinator)||{};re({override:typeof Oe.systemPromptOverride=="string"?Oe.systemPromptOverride:"",append:typeof Oe.systemPromptAppend=="string"?Oe.systemPromptAppend:typeof Oe.systemPromptSuffix=="string"?Oe.systemPromptSuffix:""}),Pe(Object.fromEntries(((U==null?void 0:U.nodes)||[]).map(rt=>[rt.id,typeof rt.systemPrompt=="string"?rt.systemPrompt:""])))},[U]),l.useEffect(()=>{const Oe=g.addNodeDaemonPicker?Pa(ye):Pa(S);oe&&Ze.length===0&&Oe.length>0&&Ae(Oe)},[oe,S,ye,Ze.length,g.addNodeDaemonPicker]),l.useEffect(()=>{const Oe=new Set(((U==null?void 0:U.nodes)||[]).map(rt=>rt.id));Ee&&!Oe.has(Ee)&&q(null)},[U,Ee]);const zt=l.useMemo(()=>{if(!(!(Q!=null&&Q.meshId)||String(Q.meshId)!==String((U==null?void 0:U.id)??"")))return vu(Q.meshHost).hostDaemonId||void 0},[Q,U]),xs=l.useMemo(()=>VI(a,At,Ne,w,zt),[a,At,Ne,w,zt]);l.useEffect(()=>{if(!g.meshHostDaemonSection)return;if(!a.length&&!$t.pinned){Y("");return}const Oe=$t.pinned?ct:xs;Oe&&!zs(Oe,O)&&Y(Oe)},[a,O,$t.pinned,ct,xs,g.meshHostDaemonSection]),l.useEffect(()=>{se&&(et||!a.some(Oe=>Oe.id===se))&&Z("")},[et,se,a]),l.useEffect(()=>{if(g.createDaemonPicker){if(!a.length){E("");return}(!F||!a.some(Oe=>Oe.id===F))&&E(a[0].id)}},[a,F,g.createDaemonPicker]),l.useEffect(()=>{var Oe;if(!g.createDaemonPicker||!F){_("");return}if(!G.length){_("");return}G.some(rt=>rt.path===H)||_(((Oe=G[0])==null?void 0:Oe.path)||"")},[F,H,G,g.createDaemonPicker]);const Ps=l.useRef(null);l.useEffect(()=>{if(!v)return;const Oe=Ps.current!==v;if(Ps.current=v,Oe){const rt=tf(v);ke(rt),me(null),B(Ne,v,rt!==null)}else me(null),B(Ne,v,!0)},[v,Ne]);const vs=l.useRef(B);vs.current=B;const es=l.useRef(!1),ys=l.useRef(()=>{});ys.current=()=>{es.current||!v||!Ne||(es.current=!0,Promise.resolve(vs.current(Ne,v,!0)).finally(()=>{es.current=!1}))};const Is=g.meshStatePushRefresh?QI:YI;_P({daemonIds:l.useMemo(()=>[Ne,...Qt].filter(Boolean),[Ne,Qt]),meshId:v,sendData:n,onRevisionAdvance:()=>{typeof document<"u"&&document.visibilityState!=="visible"||ys.current()}}),l.useEffect(()=>{if(!v||!Ne||typeof document>"u")return;let Oe=null;const rt=()=>{document.visibilityState==="visible"&&ys.current()},ks=()=>{Oe===null&&(Oe=setInterval(rt,Is))},Ss=()=>{Oe!==null&&(clearInterval(Oe),Oe=null)},os=()=>{document.visibilityState==="visible"?ks():Ss()};return document.visibilityState==="visible"&&ks(),document.addEventListener("visibilitychange",os),()=>{Ss(),document.removeEventListener("visibilitychange",os)}},[v,Ne,Is]),l.useEffect(()=>{g.queueSection||fe(v)},[v,g.queueSection]);const Ws=l.useMemo(()=>a.map(Oe=>Oe.id).filter(Boolean).sort().join(","),[a]),ws=l.useRef(!1);return l.useEffect(()=>{de(ws.current),ws.current=!0},[Ws]),w?U?s.jsx($I,{selectedMesh:U,error:C,onDismissError:()=>A(null),onBack:()=>{y(null),ke(null)},onDelete:z,displayedMeshStatus:qt,graphLoading:ve,graphError:ge,onRefreshGraph:()=>B(Ne,v,!0),savingPolicy:ce,onUpdatePolicy:st,coordinatorPromptDraft:be,onCoordinatorPromptDraftChange:re,savingCoordinatorPrompt:Te,onSaveCoordinatorPrompt:we,daemons:a,coordinatorDaemonId:O,onCoordinatorDaemonIdChange:Y,coordinatorCliType:it,onCoordinatorCliTypeChange:mt,launchingCoordinator:J,launchResult:ne,isHostNodeAttached:Zt,selectedHostNode:Rt,hostPinned:$t.pinned,hostLabel:$t.label,hostOnline:et,hostRebindDaemonId:se,onHostRebindDaemonIdChange:Oe=>Z(Oe),onLaunchCoordinator:Be,settingMeshHost:Xe,onSetMeshHost:lt,activeDaemon:Ve,activeDaemonId:Ne,meshQueue:pe,userName:r,availableCliProviders:S,savingNodeSlotsId:ze,onUpdateNodeSlots:We,savingNodeCapabilitiesId:Je,onUpdateNodeCapabilities:ue,nodeSystemPromptDrafts:He,onNodeSystemPromptDraftChange:(Oe,rt)=>Pe(ks=>({...ks,[Oe]:rt})),savingNodeSystemPromptId:Ge,onSaveNodeSystemPrompt:Se,selectedNodeId:Ee,onSelectNode:q,showAddNode:oe,onShowAddNode:()=>Ie(!0),onCancelAddNode:()=>Ie(!1),nodeWorkspace:xe,onNodeWorkspaceChange:he,nodeProviderPriority:Ze,onNodeProviderPriorityChange:Ae,nodeDaemonId:_e,onNodeDaemonIdChange:ie,nodeCustomPath:je,onNodeCustomPathChange:De,nodePickerWorkspaces:qe,nodePickerProviders:ye,nodeOnboardingPlan:Fe,nodePlanLoading:ut,attachableDaemons:Gt,onAddNode:Ue,onRemoveNode:Qe,availableCliAgents:b,features:{coordinatorPrompt:g.coordinatorPrompt,meshHostDaemonSection:g.meshHostDaemonSection,hermesMcpConfig:g.hermesMcpConfig,addNodeDaemonPicker:g.addNodeDaemonPicker,nodeInstruction:g.nodeInstruction},sendCommand:t}):s.jsx(GP,{meshes:N,loading:j,error:C,onDismissError:()=>A(null),daemons:a,features:{createDaemonPicker:g.createDaemonPicker,maxMeshes:g.maxMeshes},showCreate:T,onToggleCreate:()=>D(!T),createName:I,onCreateNameChange:M,createRepoIdentity:P,onCreateRepoIdentityChange:$,createRepoRemoteUrl:L,onCreateRepoRemoteUrlChange:R,newMeshDaemonId:F,onNewMeshDaemonIdChange:E,newMeshWorkspace:H,onNewMeshWorkspaceChange:_,createPickerWorkspaces:G,createOnboardingPlan:W,createPlanLoading:K,creating:V,createWarning:te,onDismissCreateWarning:()=>le(null),onSelectMesh:y,onCreate:ee,onCancelCreate:X}):s.jsx(Fa,{icon:s.jsx(as,{}),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 XI(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function ZI(e){var a;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((a=e.policy)==null?void 0:a.providerPriority)?e.policy.providerPriority:[],n=new Set;return t.map(r=>typeof r=="string"?r.trim():"").filter(Boolean).filter(r=>n.has(r)?!1:(n.add(r),!0))}function eL({children:e}){const{sendCommand:t,sendData:n}=kt(),{ides:a}=Ms(),r=l.useMemo(()=>a.filter(i=>i.daemonMode||i.type==="adhdev-daemon").map(i=>i),[a]),o=l.useMemo(()=>({sendCommand:t,sendData:n,daemons:r,userName:void 0,loadMeshStatus:async(i,c)=>t(i,"mesh_status",{meshId:c}),launchCoordinator:async(i,c)=>{var h;const u={meshId:c.meshId};c.cliType&&(u.cliType=c.cliType);const p=await t(i,"launch_mesh_coordinator",u),d=(p==null?void 0:p.result)??p;if((d==null?void 0:d.success)===!1)throw new Error(d.error||"Coordinator launch failed");const m=(d==null?void 0:d.sessionId)||((h=d==null?void 0:d.session)==null?void 0:h.id)||(d==null?void 0:d.targetSessionId);return{sessionId:m,message:m?`Coordinator launched (${m})`:"Coordinator launch command sent"}},loadLiveMesh:void 0,extractStatus:vl,unwrapResult:i=>i,normalizeMesh:(i,c)=>i,normalizeNode:(i,c,u)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:HP}),[t,n,r]);return s.jsx(Zh.Provider,{value:o,children:e})}function Ql(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function tL(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=Ql();return n&&!t.searchParams.has("token")&&t.searchParams.set("token",n),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function Ns(e,t){return await fetch(tL(e),{credentials:"same-origin",...t})}function sf(){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 sL{constructor(){at(this,"adapters",new Map);at(this,"states",new Map);at(this,"runtimeListeners",new Map);at(this,"screenshotCallbacks",new Map);at(this,"statusCallbacks",new Set);at(this,"stateChangeCallbacks",new Set);at(this,"ptyInputSender",null)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const n of this.adapters.keys())if(n.startsWith("standalone"))return n}return null}register(t,n){this.adapters.set(t,n),this.states.set(t,n.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,n){this.states.set(t,n);const a=this.resolveDaemonId(t)||t;this.stateChangeCallbacks.forEach(r=>r(a,n))}onStateChange(t){return this.stateChangeCallbacks.add(t),()=>{this.stateChangeCallbacks.delete(t)}}retryConnection(t){}get(t){const n=this.resolveDaemonId(t);return n?this.adapters.get(n):void 0}getState(t){const n=this.resolveDaemonId(t);return n&&this.states.get(n)||"disconnected"}registerPtyInputSender(t){this.ptyInputSender=t}sendData(t,n){return!1}sendPtyInput(t,n,a){return this.ptyInputSender?this.ptyInputSender(t,n,a):!1}onScreenshot(t,n){return this.screenshotCallbacks.set(t,n),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,n){this.screenshotCallbacks.forEach(a=>a(t,n))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,n){this.statusCallbacks.forEach(a=>a(t,n))}emitRuntimeSnapshot(t,n,a=0,r=!1,o,i){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:a,text:n,truncated:r,cols:o,rows:i})}emitSessionOutput(t,n,a){!t||typeof n!="string"||!n||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof a=="number"?{seq:a}:{},data:n})}onRuntimeEvent(t,n){const a=this.runtimeListeners.get(t)||new Set;return a.add(n),this.runtimeListeners.set(t,a),()=>{const r=this.runtimeListeners.get(t);r&&(r.delete(n),r.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,n,a){if(!n)return{success:!1,error:"sessionId is required"};const r=new URL(`/api/v1/runtime/${encodeURIComponent(n)}/snapshot`,window.location.origin);typeof(a==null?void 0:a.sinceSeq)=="number"&&r.searchParams.set("sinceSeq",String(a.sinceSeq));const o=await Ns(`${r.pathname}${r.search}`);if(!o.ok){let c=`Runtime snapshot unavailable (${o.status})`;try{const u=await o.json();u!=null&&u.error&&(c=u.error)}catch{}return{success:!1,error:c}}const i=await o.json();return this.emitRuntimeEvent(n,{type:"runtime_snapshot",sessionId:n,seq:typeof i.seq=="number"?i.seq:0,text:typeof i.text=="string"?i.text:"",truncated:!!i.truncated,cols:typeof i.cols=="number"?i.cols:void 0,rows:typeof i.rows=="number"?i.rows:void 0,force:!!(a!=null&&a.force)}),{success:!0}}emitRuntimeEvent(t,n){var a;(a=this.runtimeListeners.get(t))==null||a.forEach(r=>r(n))}}const js=new sL;function nL(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,n=Ql();return n?`${t}?token=${encodeURIComponent(n)}`:t}const cr=nL(),yu=3e3,aL=3e4;let cs=null,rL=0;const Ur=new Map;let on=null,Sa=null;function wu(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function da(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function oL(e){return e==="connected"?"connected":e}async function Ca(e,t,n){const a=vm(e,n||{}),r=cs;if(r&&r.readyState===WebSocket.OPEN){const o=`req_${++rL}_${Date.now()}`;return new Promise((i,c)=>{const u=setTimeout(()=>{Ur.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);Ur.set(o,{resolve:p=>{clearTimeout(u),i(p)},reject:p=>{clearTimeout(u),c(p)}}),r.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:a.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function Xi(e,t){const n=cs;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 nf(e,t,n){const a=cs;if(!a||a.readyState!==WebSocket.OPEN)return!1;const r=vm(e,{sessionId:t,targetSessionId:t,data:n});try{return a.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:r.payload}})),!0}catch{return!1}}js.registerPtyInputSender(nf);class iL{constructor(t){at(this,"daemonId");at(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(cs==null?void 0:cs.readyState)===WebSocket.OPEN}get connectionState(){return(cs==null?void 0:cs.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,n){return Ca(this.daemonId,t,n)}async sendInput(t,n){return Ca(this.daemonId,"cdp_remote_action",{action:t,params:n,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,on&&(clearInterval(on),on=null);const n=async()=>{if(this.hasCommandChannel)try{const a=await Ca(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(a!=null&&a.success&&(a!=null&&a.base64)){const r=await fetch(`data:image/jpeg;base64,${a.base64}`).then(o=>o.blob());js.emitScreenshot(this.daemonId,r)}}catch{}};n(),on=setInterval(n,2e3)}stopScreenshots(t){on&&(clearInterval(on),on=null)}}let ss=null;function lL(e){return(!ss||ss.daemonId!==e)&&(ss=new iL(e)),ss}function cL({children:e}){const t=l.useRef(ja()),n=ja();t.current=n;const{setUserName:a}=Ms(),r=l.useRef(a);r.current=a;const o=l.useRef(null),i=l.useRef(null),[,c]=l.useState("disconnected"),u=l.useCallback((f,x)=>{c(f),Sa==null||Sa(f,x)},[]),p=l.useRef(null),d=l.useRef(),m=l.useRef(yu),h=l.useRef(!0),g=l.useRef(!1),k=l.useRef("initial_connect");return l.useEffect(()=>{h.current=!0,g.current=!1;function f(){var b,S;if(!h.current||((b=p.current)==null?void 0:b.readyState)===WebSocket.OPEN||((S=p.current)==null?void 0:S.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${cr}...`),da("connect_attempt",{url:cr,reason:k.current,delayMs:m.current});let w;try{w=new WebSocket(cr)}catch(N){console.error("[Standalone WS] Failed to create WebSocket:",N),x();return}p.current=w,w.onopen=()=>{if(!h.current){w.close();return}u("connected"),m.current=yu,da("open",{url:cr,reason:k.current}),hs.resubscribeAll({sendData:Xi}),console.log("[Standalone WS] Connected")},cs=w,w.onmessage=N=>{var v,y;try{const j=JSON.parse(N.data);if((j.type==="command_result"||j.type==="error")&&j.requestId){const C=Ur.get(j.requestId);C&&(Ur.delete(j.requestId),j.type==="error"?C.reject(new Error(((v=j.data)==null?void 0:v.message)||"Command failed")):C.resolve(j.data));return}if(j.type==="session_output"){const C=j.sessionId||j.cliId||j.cliType;C&&js.emitSessionOutput(C,typeof j.data=="string"?j.data:"",typeof j.seq=="number"?j.seq:void 0);return}if(j.type==="runtime_snapshot"){js.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 C=j.update;C&&hs.publish(C);return}if(j.type==="status"||j.type==="initial_state"){const C=j.data;if(!C)return;const{injectEntries:A,markLoaded:T,getIdes:D}=t.current,I=C.instanceId||"standalone",M=D().find(L=>L.id===I),P=lL(I);js.register(I,P),js.setState(I,"connected"),u("connected",I),js.emitStatus(I,C);const $=Tr(C,{daemonId:I,existingDaemon:M,existingEntries:D()});wu("ws_status",{type:j.type,daemonId:I,sessions:(C.sessions||[]).map(L=>({id:L.id,parentId:L.parentId,providerType:L.providerType,kind:L.kind,transport:L.transport,unread:L.unread,inboxBucket:L.inboxBucket,lastSeenAt:L.lastSeenAt,lastUpdated:L.lastUpdated,title:L.title})),recentLaunches:(C.recentLaunches||[]).map(L=>({id:L.id,providerType:L.providerType,kind:L.kind,workspace:L.workspace,lastLaunchedAt:L.lastLaunchedAt}))}),wu("entries",{daemonId:I,entries:$.filter(L=>L.type!=="adhdev-daemon").map(L=>({id:L.id,type:L.type,unread:L.unread,inboxBucket:L.inboxBucket,lastSeenAt:L.lastSeenAt,lastUpdated:L.lastUpdated,sessionId:L.sessionId}))}),$.length>0&&A($,{authoritativeDaemonIds:[I]}),T(),i.current!==I&&((y=o.current)==null||y.call(o),i.current=I,o.current=hs.subscribe({sendData:Xi},I,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${I}`,params:{includeSessions:!0}},L=>{if(L.topic!=="daemon.metadata")return;const R=t.current.getIdes(),F=R.find(H=>H.id===I),E=Tr(L.status,{daemonId:I,existingDaemon:F,existingEntries:R,timestamp:L.timestamp});E.length>0&&t.current.injectEntries(E,{authoritativeDaemonIds:[I]}),L.userName&&r.current&&r.current(L.userName)}))}}catch(j){console.error("[Standalone WS] Parse error:",j)}},w.onclose=N=>{h.current&&(ss==null||ss.stopScreenshots(),ss&&js.setState(ss.daemonId,"disconnected"),u("disconnected"),p.current=null,k.current=`close:${N.code}${N.wasClean?":clean":":unclean"}`,da("close",{code:N.code,reason:N.reason||"",wasClean:N.wasClean}),x())},w.onerror=N=>{g.current||!h.current||(k.current="error",da("error",{message:N instanceof Event?"event":String(N),readyState:w.readyState}),console.warn("[Standalone WS] Error, will reconnect:",N))}}function x(){if(!h.current)return;clearTimeout(d.current);const w=m.current;console.log(`[Standalone WS] Reconnecting in ${w}ms...`),da("schedule_reconnect",{reason:k.current,delayMs:w}),d.current=setTimeout(()=>{m.current=Math.min(m.current*1.5,aL),f()},w)}return f(),()=>{var w;h.current=!1,g.current=!0,(w=o.current)==null||w.call(o),o.current=null,i.current=null,clearTimeout(d.current),p.current&&(p.current.onerror=null,p.current.onclose=null,p.current.close(),p.current=null,cs=null),ss&&(ss.stopScreenshots(),js.unregister(ss.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function dL({children:e}){const[t,n]=l.useState("disconnected"),[a,r]=l.useState(null);l.useEffect(()=>(Sa=(i,c)=>{n(i),c&&r(c)},()=>{Sa=null}),[]);const o=l.useMemo(()=>{const i=t==="connected",c=oL(t),u={};return a&&(u[a]=c),u.standalone=c,{wsStatus:t,isConnected:i,connectionStates:u,usesP2P:!1}},[t,a]);return s.jsx(Qf,{connectionOverrides:o,children:s.jsx(cL,{children:e})})}const af="adhdev_standalone_font_preferences",bn={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},ho=[{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"}],Ra=[{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"}],uL=new Set(ho.map(e=>e.id)),pL=new Set(Ra.map(e=>e.id));function As(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:wr("chat",t.chat),code:wr("code",t.code),terminal:wr("terminal",t.terminal)}}function wr(e,t){const n=bn[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"?uL:pL).has(r)?r==="custom"?o?{preset:"custom",customFamily:o}:n:{preset:r}:n}function kr(e,t){var r;const n=wr(e,t);if(n.preset==="custom"&&n.customFamily)return n.customFamily;const a=e==="chat"?ho:Ra;return((r=a.find(o=>o.id===n.preset))==null?void 0:r.family)||a[0].family}function mL(e){const t=As(e),n=kr("chat",t.chat),a=kr("code",t.code),r=kr("terminal",t.terminal);return{"--chat-font-family":n,"--chat-code-font-family":a,"--chat-terminal-font-family":r,"--chat-tool-font-family":r}}function cn(e,t=document.documentElement){const n=As(e),a=mL(n);t.setAttribute("data-standalone-fonts","custom");for(const[r,o]of Object.entries(a))t.style.setProperty(r,o);return n}function Zi(e){const t=As(e);try{localStorage.setItem(af,JSON.stringify(t))}catch{}return t}function hL(){try{const e=localStorage.getItem(af);if(e)return As(JSON.parse(e))}catch{}return bn}function fL(){return cn(hL())}function ua(e,t){var a;const n=e==="chat"?ho:Ra;return((a=n.find(r=>r.id===t))==null?void 0:a.label)||n[0].label}function bL({children:e}){const t=Ea(),n=tl(),{t:a}=Ce("common"),r=l.useMemo(()=>[{id:"dashboard",path:"/dashboard",icon:s.jsx(_u,{}),label:a("standalone.nav.dashboard"),active:n.pathname.startsWith("/dashboard"),onSelect:()=>t("/dashboard")},{id:"machine",path:"/machines",icon:s.jsx(Ys,{}),label:"Burrow",active:n.pathname.startsWith("/machines"),onSelect:()=>t("/machines")},{id:"mesh",path:"/mesh",icon:s.jsx(as,{}),label:"Mesh",active:n.pathname.startsWith("/mesh"),onSelect:()=>t("/mesh")},{id:"settings",path:"/settings",icon:s.jsx(Gr,{}),label:a("standalone.nav.settings"),active:n.pathname.startsWith("/settings"),onSelect:()=>t("/settings")}],[n.pathname,t,a]),o=l.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:a("standalone.nav.docs")}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx($u,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:a("standalone.nav.docs")},{id:"about",label:a("standalone.nav.about"),icon:s.jsx(rl,{}),active:n.pathname==="/about",onSelect:()=>t("/about"),title:a("standalone.nav.about")}],[n.pathname,t,a]);return s.jsx(WC,{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.41"]}),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})}const gL=[{icon:s.jsx(Ys,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(kn,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Wu,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(gs,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(Na,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx($u,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],xL=[{icon:s.jsx(Nb,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(_u,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Vn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(yb,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(Hu,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(kb,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],vL=[{feature:"Agent chat relay",selfhost:!0,cloud:!0},{feature:"Live IDE screenshots",selfhost:!0,cloud:!0},{feature:"Remote IDE control",selfhost:!0,cloud:!0},{feature:"Multi-IDE monitoring",selfhost:!0,cloud:!0},{feature:"Extension and CLI agents",selfhost:!0,cloud:!0},{feature:"Access from any network",selfhost:!1,cloud:!0},{feature:"WebRTC P2P streaming",selfhost:!1,cloud:!0},{feature:"Mobile push notifications",selfhost:!1,cloud:!0},{feature:"REST API and webhooks",selfhost:!1,cloud:!0},{feature:"Team collaboration",selfhost:!1,cloud:!0},{feature:"Multi-machine burrows",selfhost:!1,cloud:!0},{feature:"SSO, RBAC, audit logs",selfhost:!1,cloud:!0}];function yL(){const{t:e}=Ce("common");return s.jsxs(Fa,{icon:s.jsx(rl,{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.41"]}),children:[s.jsx(gt,{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(gt,{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:gL.map(t=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:t.icon}),t.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:t.desc})]},t.title))})}),s.jsx(gt,{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:ym.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:km.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:wm.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(gt,{title:e("standalone.about.cloudExtrasSection"),description:e("standalone.about.cloudExtrasDescription"),children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:xL.map(t=>s.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:t.icon}),t.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:t.desc})]},t.title))})}),s.jsx(gt,{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:vL.map((t,n)=>s.jsxs("tr",{className:n%2===0?"bg-bg-glass":"bg-transparent",children:[s.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:t.feature}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:t.selfhost?s.jsx("span",{className:"text-emerald-500",children:"✓"}):s.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:s.jsx("span",{className:"text-emerald-500",children:"✓"})})]},t.feature))})]})})}),s.jsx(so,{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(Eb,{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}=Ce("common");return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:n})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(GC,{value:a.preset,onChange:c=>{const u=c.target.value;o(u==="custom"?{preset:"custom",customFamily:a.customFamily||""}:{preset:u})},children:r.map(c=>s.jsx("option",{value:c.id,children:c.label},c.id))}),a.preset==="custom"&&s.jsx(ps,{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:kr(e,a)})]})]})]})}function wL({value:e,savedValue:t,saving:n=!1,error:a,notice:r,onChange:o,onSave:i,onResetToSaved:c,onResetToDefaults:u}){const{t:p}=Ce("common"),d=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:p("standalone.fonts.fontOverridesNotice")}),a&&s.jsx(Dt,{variant:"error",children:a}),r&&s.jsx(Dt,{variant:"success",children:r}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(bi,{surface:"chat",title:p("standalone.fonts.chat"),description:p("standalone.fonts.chatDescription"),value:e.chat,options:ho,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:Ra,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:Ra,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: ",ua("chat",e.chat.preset)," · Code: ",ua("code",e.code.preset)," · Terminal: ",ua("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[p("standalone.fonts.defaults")," ",ua("chat",bn.chat.preset)," / ",ua("code",bn.code.preset)]})]}),s.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:s.jsxs("div",{className:"chat-container-content",children:[s.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:s.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[s.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[s.jsx("span",{className:"chat-sender",children:"Hermes"}),s.jsx("span",{className:"chat-time",children:"now"})]}),s.jsxs("div",{className:"chat-markdown",children:[s.jsxs("p",{children:["Readable prose, ",s.jsx("strong",{children:"bold text"}),", and ",s.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),s.jsx("pre",{children:s.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),s.jsxs("div",{className:"chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"▸"}),s.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),s.jsxs("div",{className:"chat-msg-terminal",children:[s.jsx("div",{className:"chat-msg-header",children:"Terminal"}),s.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx(Hs,{type:"button",variant:"primary",size:"sm",onClick:i,disabled:n||!d,children:p(n?"standalone.fonts.saving":"standalone.fonts.saveFontSettings")}),s.jsx(Hs,{type:"button",variant:"secondary",size:"sm",onClick:c,disabled:n||!d,children:p("standalone.fonts.revertToSaved")}),s.jsx(Hs,{type:"button",variant:"secondary",size:"sm",onClick:u,disabled:n,children:p("standalone.fonts.resetToDefaults")})]})]})}function kL(){const{t:e}=Ce("common"),{ides:t}=Ms(),n=t.find(z=>z.type==="adhdev-daemon"),a=(n==null?void 0:n.detectedIdes)||[],{sendCommand:r}=kt(),{userName:o}=Ms(),[i,c]=l.useState(o||""),[u,p]=l.useState(null),[d,m]=l.useState(null),[h,g]=l.useState(bn),[k,f]=l.useState(!1),[x,w]=l.useState(""),[b,S]=l.useState(""),[N,v]=l.useState("127.0.0.1"),[y,j]=l.useState(""),[C,A]=l.useState(""),[T,D]=l.useState(""),[I,M]=l.useState(""),[P,$]=l.useState(""),[L,R]=l.useState(!1),F=async()=>{const X=await(await Ns("/auth/session")).json();p(X)},E=async()=>{const X=await(await Ns("/api/v1/standalone/preferences")).json();m(X),v(X.standaloneBindHost);const U=As(X.standaloneFontPreferences);g(U),cn(U),Zi(U)};l.useEffect(()=>{o!==void 0&&c(o)},[o]),l.useEffect(()=>{Promise.all([F(),E()]).catch(z=>{M(z instanceof Error?z.message:String(z))})},[]),l.useEffect(()=>{cn(h)},[h]);const H=z=>{const X=z.target.value.trim();n!=null&&n.id&&X!==o&&r(n.id,"set_user_name",{userName:X}).catch(console.error)},[_,G]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),W=z=>{G(z);try{localStorage.setItem("adhdev_sound",z?"1":"0")}catch{}},K=async()=>{w(""),S(""),f(!0);try{const z=As(h),X=await Ns("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:z})}),U=await X.json();if(!X.ok)throw new Error((U==null?void 0:U.error)||"Failed to save standalone font preferences");const Q=As(U.standaloneFontPreferences);m(U),g(Q),cn(Q),Zi(Q),S(e("standalone.settings.fontsSaved"))}catch(z){w(z instanceof Error?z.message:String(z))}finally{f(!1)}},V=()=>{const z=As(d==null?void 0:d.standaloneFontPreferences);w(""),S(""),g(z),cn(z)},te=()=>{w(""),S(""),g(bn),cn(bn)},le=async()=>{M(""),$(""),R(!0);try{const z=await Ns("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:N})}),X=await z.json();if(!z.ok)throw new Error((X==null?void 0:X.error)||"Failed to save standalone network preference");m(X),v(X.standaloneBindHost),$(X.standaloneBindHost==="0.0.0.0"?e("standalone.settings.networkSavedAll"):e("standalone.settings.networkSavedLocal"))}catch(z){M(z instanceof Error?z.message:String(z))}finally{R(!1)}},de=async()=>{if(M(""),$(""),C.trim().length<4){M(e("standalone.settings.passwordTooShort"));return}if(C!==T){M(e("standalone.settings.passwordMismatch"));return}R(!0);try{const z=await Ns("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,newPassword:C})}),X=await z.json();if(!z.ok)throw new Error((X==null?void 0:X.error)||"Failed to save password");p(X),await E(),j(""),A(""),D(""),$(u!=null&&u.hasPasswordAuth?e("standalone.settings.passwordUpdated"):e("standalone.settings.passwordEnabled")),sf()}catch(z){M(z instanceof Error?z.message:String(z))}finally{R(!1)}},ee=async()=>{M(""),$(""),R(!0);try{const z=await Ns("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,clear:!0})}),X=await z.json();if(!z.ok)throw new Error((X==null?void 0:X.error)||"Failed to clear password");p(X),await E(),j(""),A(""),D(""),$(e("standalone.settings.passwordDisabled"))}catch(z){M(z instanceof Error?z.message:String(z))}finally{R(!1)}};return s.jsxs(Fa,{icon:s.jsx(Gr,{className:"text-text-primary"}),title:e("standalone.settings.title"),subtitle:e("standalone.settings.subtitle"),widthClassName:"max-w-5xl",children:[s.jsx(Dt,{variant:"info",children:e("standalone.settings.infoNotice")}),(u==null?void 0:u.publicHostWarning)&&s.jsx(Dt,{variant:"warning",children:e("standalone.settings.publicHostWarning")}),s.jsx(gt,{title:e("standalone.settings.daemonSection"),description:e("standalone.settings.daemonDescription"),children:s.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.versionLabel")}),s.jsxs("span",{className:"font-mono text-xs",children:["v","1.0.41"]}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.statusLabel")}),s.jsx("span",{className:n?"text-green-400":"text-yellow-400",children:e(n?"standalone.settings.statusRunning":"standalone.settings.statusNotConnected")}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.currentBindLabel")}),s.jsx("span",{className:"font-mono text-xs",children:(d==null?void 0:d.currentBindHost)||(u==null?void 0:u.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.defaultBindLabel")}),s.jsx("span",{className:"font-mono text-xs",children:(d==null?void 0:d.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.authLabel")}),s.jsx("span",{className:"text-xs",children:u!=null&&u.hasPasswordAuth?e("standalone.settings.authPassword"):u!=null&&u.hasTokenAuth?e("standalone.settings.authToken"):e("standalone.settings.authNone")})]})}),s.jsx(gt,{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:N==="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:N==="0.0.0.0",onChange:()=>v("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:e("standalone.settings.allInterfacesLabel")}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:e("standalone.settings.allInterfacesHint")})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx(Hs,{type:"button",variant:"primary",size:"sm",onClick:()=>{le()},disabled:L,children:e(L?"standalone.settings.saving":"standalone.settings.saveNetworkMode")}),s.jsx("span",{className:"text-xs text-text-muted",children:e("standalone.settings.networkRestartHint",{host:(d==null?void 0:d.currentBindHost)||(u==null?void 0:u.boundHost)||"127.0.0.1"})})]})]})}),s.jsx(gt,{title:e("standalone.settings.securitySection"),description:e("standalone.settings.securityDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:u!=null&&u.hasPasswordAuth?e("standalone.settings.passwordSet"):e("standalone.settings.passwordNotSet")}),I&&s.jsx(Dt,{variant:"error",children:I}),P&&s.jsx(Dt,{variant:"success",children:P}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx(ps,{type:"password",placeholder:u!=null&&u.hasPasswordAuth?e("standalone.settings.currentPasswordPlaceholder"):e("standalone.settings.currentPasswordFirstTimePlaceholder"),value:y,onChange:z=>j(z.target.value)}),s.jsx(ps,{type:"password",placeholder:u!=null&&u.hasPasswordAuth?e("standalone.settings.newPasswordPlaceholder"):e("standalone.settings.newPasswordFirstTimePlaceholder"),value:C,onChange:z=>A(z.target.value)}),s.jsx(ps,{type:"password",className:"md:col-span-2",placeholder:e("standalone.settings.confirmPasswordPlaceholder"),value:T,onChange:z=>D(z.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Hs,{type:"button",variant:"primary",size:"sm",onClick:()=>{de()},disabled:L,children:L?e("standalone.settings.saving"):u!=null&&u.hasPasswordAuth?e("standalone.settings.updatePassword"):e("standalone.settings.enablePassword")}),(u==null?void 0:u.hasPasswordAuth)&&s.jsx(Hs,{type:"button",variant:"danger",size:"sm",onClick:()=>{ee()},disabled:L,children:e("standalone.settings.disablePassword")})]})]})}),s.jsx(gt,{title:e("standalone.settings.detectedIdesSection"),description:e("standalone.settings.detectedIdesDescription"),children:a.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:e("standalone.settings.noIdesDetected")}):s.jsx("div",{className:"flex flex-col gap-1.5",children:a.map(z=>s.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${z.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:z.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:z.type})]},z.type))})}),s.jsx(gt,{title:e("standalone.settings.machineSection"),description:e("standalone.settings.machineDescription"),children:s.jsx(ej,{ides:t,emptyMessage:e("standalone.settings.daemonNotConnected")})}),s.jsx(gt,{title:e("standalone.settings.appearanceSection"),description:e("standalone.settings.appearanceDescription"),children:s.jsx(yj,{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(wL,{value:h,savedValue:As(d==null?void 0:d.standaloneFontPreferences),saving:k,error:x,notice:b,onChange:g,onSave:()=>{K()},onResetToSaved:V,onResetToDefaults:te})]})})}),s.jsx(gt,{title:e("standalone.settings.notificationsSection"),description:e("standalone.settings.notificationsDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(YC,{}),s.jsx(ln,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Rb,{size:15})," ",e("standalone.settings.soundEffectsLabel")]}),description:e("standalone.settings.soundEffectsDescription"),checked:_,onChange:W})]})}),s.jsx(gt,{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(vb,{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(ps,{type:"text",className:"w-48 text-right",placeholder:e("standalone.settings.displayNamePlaceholder"),value:i,onChange:z=>c(z.target.value),onBlur:H,onKeyDown:z=>{z.key==="Enter"&&z.currentTarget.blur()}})]})})})]})}const SL=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],fa="adhdev_onboarding_done",CL=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],jL={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function NL({onDone:e}){const{t}=Ce("common"),[n,a]=l.useState([]),[r,o]=l.useState(new Set(SL)),[i,c]=l.useState(!0),[u,p]=l.useState(null),[d,m]=l.useState(!1),[h,g]=l.useState(null),[k,f]=l.useState("all");l.useEffect(()=>{let y=!1;const j=window.location.hostname==="localhost"?"/registry":"https://api.adhf.dev/api/v1/registry";return fetch(`${j}/providers?sort=popular&limit=100`).then(C=>{if(!C.ok)throw new Error(`HTTP ${C.status}`);return C.json()}).then(C=>{y||a(C.providers??[])}).catch(C=>{y||p(C instanceof Error?C.message:String(C))}).finally(()=>{y||c(!1)}),()=>{y=!0}},[]);const x=n.filter(y=>k==="all"||y.category===k),w=["cli","ide","extension","acp"].map(y=>({category:y,items:x.filter(j=>j.category===y)})).filter(y=>y.items.length>0),b=l.useCallback(y=>{o(j=>{const C=new Set(j);return C.has(y)?C.delete(y):C.add(y),C})},[]),S=l.useCallback(async()=>{if(r.size===0){localStorage.setItem(fa,"1"),e();return}m(!0);const y=[];for(const j of r)try{const A=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:j})})).json().catch(()=>({}));y.push({type:j,ok:!!A.success,error:A.error})}catch(C){y.push({type:j,ok:!1,error:C instanceof Error?C.message:String(C)})}g(y),m(!1),y.every(j=>j.ok)&&localStorage.setItem(fa,"1")},[r,e]),N=l.useCallback(()=>{localStorage.setItem(fa,"1"),e()},[e]),v=l.useCallback(()=>{h&&h.every(y=>y.ok)?e():d||N()},[h,d,e,N]);return s.jsx(jp,{open:!0,onClose:v,size:"lg",contentClassName:"max-w-2xl",title:t("standalone.onboarding.title"),footer:s.jsxs("div",{className:"flex w-full items-center gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:t(r.size!==1?"standalone.onboarding.selectedCount_other":"standalone.onboarding.selectedCount_one",{count:r.size})}),s.jsxs("div",{className:"ml-auto flex gap-2",children:[s.jsx(Hs,{variant:"secondary",size:"sm",onClick:N,disabled:d,children:t("standalone.onboarding.skip")}),s.jsx(Hs,{variant:"primary",size:"sm",onClick:()=>{h?(localStorage.setItem(fa,"1"),e()):S()},disabled:d||!h&&r.size===0,children:d?t("standalone.onboarding.installing"):h?t("standalone.onboarding.done"):t("standalone.onboarding.installCount",{count:r.size})})]})]}),children:s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsx("div",{className:"text-[12px] text-text-muted",children:t("standalone.onboarding.intro")}),!i&&!u&&n.length>0&&s.jsx("div",{className:"flex gap-1 flex-wrap border-b border-border-subtle pb-2",children:CL.map(y=>{const j=y.key==="all"?n.length:n.filter(C=>C.category===y.key).length;return j===0&&y.key!=="all"?null:s.jsxs("button",{onClick:()=>f(y.key),className:`machine-btn text-[10px] px-2 py-0.5 ${k===y.key?"bg-accent-primary/12 border-accent-primary/40 text-accent-primary":""}`,children:[y.label," ",s.jsxs("span",{className:"opacity-60",children:["(",j,")"]})]},y.key)})}),i&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.loadingRegistry")}),!i&&u&&s.jsx(Dt,{variant:"error",children:t("standalone.onboarding.loadError",{error:u})}),!i&&!u&&x.length===0&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.noProviders")}),!i&&!u&&x.length>0&&s.jsx("div",{className:"flex flex-col gap-4",children:w.map(y=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:jL[y.category]??y.category}),s.jsx("div",{className:"grid gap-1.5",children:y.items.map(j=>{var I,M;const C=r.has(j.type),A=h==null?void 0:h.find(P=>P.type===j.type),T=((I=j.manifest)==null?void 0:I.icon)??"📦",D=((M=j.manifest)==null?void 0:M.details)??"";return s.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${C?"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:C,onChange:()=>b(j.type),disabled:d,className:"shrink-0"}),s.jsx("span",{className:"text-base shrink-0",children:T}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[13px] font-medium text-text-primary truncate",children:j.displayName}),D&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:D})]}),A&&s.jsx("span",{className:`text-[10px] font-semibold ${A.ok?"text-status-online":"text-status-error"}`,children:A.ok?t("standalone.onboarding.installed"):t("standalone.onboarding.installFailed",{error:A.error??"failed"})})]},j.type)})})]},y.category))})]})})}function AL(){try{return localStorage.getItem(fa)==="1"}catch{return!1}}DC();pj();dw();fL();const TL=Mu({baseUrl:"",getToken:Ql});function ML({children:e}){const{t}=Ce("common"),[n,a]=l.useState(null),[r,o]=l.useState(!0),[i,c]=l.useState(""),[u,p]=l.useState(""),[d,m]=l.useState(!1),h=async()=>{o(!0),p("");try{const f=await(await Ns("/auth/session")).json();a(f)}catch(k){p(k instanceof Error?k.message:String(k))}finally{o(!1)}};l.useEffect(()=>{h()},[]),l.useEffect(()=>{if(!n||n.required&&!n.authenticated)return;let k=!1;return(async()=>{try{const f=await Ns("/api/v1/standalone/preferences");if(!f.ok)return;const x=await f.json();if(k)return;const w=As(x.standaloneFontPreferences);cn(w),Zi(w)}catch{}})(),()=>{k=!0}},[n==null?void 0:n.authenticated,n==null?void 0:n.required]);const g=async k=>{k.preventDefault(),m(!0),p("");try{const f=await Ns("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),x=await f.json();if(!f.ok)throw new Error((x==null?void 0:x.error)||"Login failed");a(x),c(""),sf()}catch(f){p(f instanceof Error?f.message:String(f))}finally{m(!1)}};return r?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:t("standalone.auth.loading")}):n?!n.required||n.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:t("standalone.auth.signInTitle")}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:n.hasPasswordAuth?t("standalone.auth.passwordProtected"):t("standalone.auth.tokenProtected")})]}),n.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:g,children:[s.jsx(ps,{type:"password",value:i,onChange:k=>c(k.target.value),placeholder:t("standalone.auth.passwordPlaceholder"),autoFocus:!0}),s.jsx(Hs,{type:"submit",variant:"primary",disabled:d||!i,className:"justify-center",children:t(d?"standalone.auth.signingIn":"standalone.auth.unlock")})]}):s.jsx(Dt,{variant:"warning",children:t("standalone.auth.noPasswordEnabled")}),u&&s.jsx(Dt,{variant:"error",children:u})]})}):s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:t("standalone.auth.loadError",{error:u||"unknown error"})})}function ku(){const{t:e}=Ce("common"),{ides:t,initialLoaded:n}=Ms();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(yi,{to:`/machines/${a.id}`,replace:!0}):s.jsx(yi,{to:"/dashboard",replace:!0})}function DL(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let n=!1;if(!AL())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(NL,{onDone:()=>t(!1)}):null}function PL(){const{t:e}=Ce("common"),{ides:t}=Ms(),n=l.useMemo(()=>{for(const d of t)if(d.activeInteractivePrompt)return d.instanceId??d.id;return null},[t]),{promptSession:a,hasActivePrompt:r,responseError:o,isSubmitting:i,submit:c,cancel:u,reopen:p}=Im(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(tp,{promptSession:a,isSubmitting:i,error:o,onSubmit:c,onCancel:u})]}):null}function IL(){const e=l.useMemo(()=>({sendCommand:Ca,sendData:Xi,sendPtyInput:nf}),[]);return s.jsx(Lf,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Zf,{client:TL,children:s.jsx(ML,{children:s.jsx(dL,{children:s.jsx(tb,{value:e,children:s.jsxs(rb,{sendDaemonCommand:Ca,children:[s.jsx(PL,{}),s.jsxs(bL,{children:[s.jsx(DL,{}),s.jsxs(Rf,{children:[s.jsx(Us,{path:"/dashboard",element:s.jsx(ND,{})}),s.jsx(Us,{path:"/machine",element:s.jsx(ku,{})}),s.jsx(Us,{path:"/machines/:id",element:s.jsx(EP,{})}),s.jsx(Us,{path:"/machines",element:s.jsx(ku,{})}),s.jsx(Us,{path:"/about",element:s.jsx(yL,{})}),s.jsx(Us,{path:"/settings",element:s.jsx(kL,{})}),s.jsx(Us,{path:"/mesh",element:s.jsx(eL,{children:s.jsx(JI,{})})}),s.jsx(Us,{path:"*",element:s.jsx(yi,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}kS({connectionManager:js});Ef(document.getElementById("root")).render(s.jsx(IL,{}));
|
|
121
|
+
Node removal cleanup policy: ${ie}`))return;const je=e.__sourceDaemonId||n;try{const qe=await o(je,"remove_mesh_node",{meshId:e.id,nodeId:Ae}),ye=i(qe);if((ye==null?void 0:ye.success)===!1)throw new Error(ye.error||"Remove failed");S===Ae&&N(null),await m(),g||await h(t)}catch(qe){k((qe==null?void 0:qe.message)||"Remove node failed")}}async function Z(Ae){if(!e)return;const _e={...Ji(e),...Ae},ie=e.__sourceDaemonId||n;try{de(!0),k(null);const je=await o(ie,"update_mesh",{meshId:e.id,policy:_e}),De=i(je);if((De==null?void 0:De.success)===!1)throw new Error(De.error||"Policy update failed");await m()}catch(je){k((je==null?void 0:je.message)||"Policy update failed")}finally{de(!1)}}async function Ne(Ae){if(!t)return;const _e=(e==null?void 0:e.__sourceDaemonId)||n,ie=f[Ae.id]||OI(Ae),je=qn(ie),De={...Ae.policy||{}};delete De.provider_priority,je.length?De.providerPriority=je:delete De.providerPriority;try{b(Ae.id),k(null);const qe=await o(_e,"update_mesh_node",{meshId:t,nodeId:Ae.id,policy:De,providerPriority:je}),ye=i(qe);if((ye==null?void 0:ye.success)===!1){k(ye.error||"Node policy update failed");return}await m()}catch(qe){k((qe==null?void 0:qe.message)||"Node policy update failed")}finally{b(null)}}const[pe,fe]=l.useState(null);async function Me(Ae,_e){if(!t)return;const ie=(e==null?void 0:e.__sourceDaemonId)||n;try{fe(Ae.id),k(null);const je=await o(ie,"update_mesh_node",{meshId:t,nodeId:Ae.id,policy:{slots:_e}}),De=i(je);if((De==null?void 0:De.success)===!1){k(De.error||"Node slots update failed");return}await m()}catch(je){k((je==null?void 0:je.message)||"Node slots update failed")}finally{fe(null)}}const[Ee,q]=l.useState(null);async function oe(Ae,_e){if(!t)return;const ie=(e==null?void 0:e.__sourceDaemonId)||n,je=_e.map(De=>De.trim()).filter(Boolean);try{q(Ae.id),k(null);const De=await o(ie,"update_mesh_node",{meshId:t,nodeId:Ae.id,capabilities:je}),qe=i(De);if((qe==null?void 0:qe.success)===!1){k(qe.error||"Node tag update failed");return}await m()}catch(De){k((De==null?void 0:De.message)||"Node tag update failed")}finally{q(null)}}async function Ie(){if(!n||!t)return;const _e={...(e==null?void 0:e.coordinator)||{}};ee.override.trim()?_e.systemPromptOverride=ee.override:delete _e.systemPromptOverride,ee.append.trim()?_e.systemPromptAppend=ee.append:delete _e.systemPromptAppend,delete _e.systemPromptSuffix;try{U(!0),k(null);const ie=await o(n,"update_mesh",{meshId:t,coordinator:_e}),je=i(ie);if((je==null?void 0:je.success)===!1){k(je.error||"Coordinator prompt save failed");return}await m()}catch(ie){k((ie==null?void 0:ie.message)||"Coordinator prompt save failed")}finally{U(!1)}}async function xe(Ae){if(!n||!t)return;const _e=(Q[Ae.id]||"").trim();try{ge(Ae.id),k(null);const ie=await o(n,"update_mesh_node",{meshId:t,nodeId:Ae.id,systemPrompt:_e}),je=i(ie);if((je==null?void 0:je.success)===!1){k(je.error||"Node instruction save failed");return}await m()}catch(ie){k((ie==null?void 0:ie.message)||"Node instruction save failed")}finally{ge(null)}}async function he(Ae){if(!(!e||!Ae)){k(null),te(null);try{K(!0);const _e=(e.nodes||[]).find(De=>zs(String(De.daemon_id||De.daemonId||""),Ae)),ie=await o(Ae,"set_mesh_host",{meshId:e.id,hostDaemonId:Ae,..._e!=null&&_e.id?{hostNodeId:_e.id}:{}}),je=i(ie);if((je==null?void 0:je.success)===!1){k(je.error||"Setting the mesh host failed");return}await m()}catch(_e){k((_e==null?void 0:_e.message)||"Setting the mesh host failed")}finally{K(!1)}}}async function Ze(){if(e){k(null),te(null);try{G(!0);const Ae=c?await c(a,e.id,e):null,_e=u(a,e.id,e,e.nodes||[],Ae);if("error"in _e)throw new Error(_e.error);const ie=await p(_e.targetDaemonId,{meshId:e.id,inlineMesh:_e.inlineMesh,coordinatorNodeId:_e.coordinatorNodeId,cliType:E.trim()||void 0});te(ie.message)}catch(Ae){k((Ae==null?void 0:Ae.message)||"Coordinator launch failed")}finally{G(!1)}}}return{nodeProviderPriorityDrafts:f,setNodeProviderPriorityDrafts:x,savingNodePolicyId:w,selectedNodeId:S,setSelectedNodeId:N,showAddNode:v,setShowAddNode:y,nodeWorkspace:j,setNodeWorkspace:C,nodeProviderPriority:A,setNodeProviderPriority:T,nodeDaemonId:D,setNodeDaemonId:I,nodeCustomPath:M,setNodeCustomPath:P,nodePickerWorkspaces:B,nodePickerProviders:O,nodeOnboardingPlan:$,nodePlanLoading:R,coordinatorCliType:E,setCoordinatorCliType:H,launchingCoordinator:_,launchResult:V,settingMeshHost:W,savingPolicy:le,coordinatorPromptDraft:ee,setCoordinatorPromptDraft:z,savingCoordinatorPrompt:X,nodeSystemPromptDrafts:Q,setNodeSystemPromptDrafts:ke,savingNodeSystemPromptId:ve,savingNodeSlotsId:pe,savingNodeCapabilitiesId:Ee,handleAddNode:Y,handleRemoveNode:se,handleUpdatePolicy:Z,handleUpdateNodeProviderPriority:Ne,handleUpdateNodeSlots:Me,handleUpdateNodeCapabilities:oe,handleSaveCoordinatorPrompt:Ie,handleSaveNodeSystemPrompt:xe,handleLaunchCoordinator:Ze,handleSetMeshHost:he}}function OI(e){var a;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((a=e.policy)==null?void 0:a.providerPriority)?e.policy.providerPriority:[],n=new Set;return t.map(r=>typeof r=="string"?r.trim():"").filter(Boolean).filter(r=>n.has(r)?!1:(n.add(r),!0))}function UI(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 qI({primaryDaemonId:e,activeDaemonId:t,sendCommand:n,unwrapResult:a,loadLiveMesh:r,resolveCommandTarget:o}){const[i,c]=l.useState([]),[u,p]=l.useState(null),[d,m]=l.useState(!1),[h,g]=l.useState(null),k=l.useCallback(async x=>{if(!e||!x){c([]);return}try{const w=await n(e,"get_mesh_queue",{meshId:x});c(w!=null&&w.success?Array.isArray(w.queue)?w.queue:[]:[])}catch{c([])}},[e,n]);async function f(x){var w,b;if(x){m(!0),g(null);try{const S=r?await r(t,x.id,x):null,N=o(t,x.id,x,x.nodes||[],S);if("error"in N)throw new Error(N.error);const v=await n(N.targetDaemonId,"get_mesh_queue",{meshId:x.id}),y=a(v);if((y==null?void 0:y.success)===!1)throw new Error(y.error||"Queue load failed");const j=Array.isArray(((w=y==null?void 0:y.result)==null?void 0:w.rows)??(y==null?void 0:y.rows)??(y==null?void 0:y.queue))?((b=y==null?void 0:y.result)==null?void 0:b.rows)??(y==null?void 0:y.rows)??(y==null?void 0:y.queue):[];p(UI(j))}catch(S){g((S==null?void 0:S.message)||"Queue load failed")}finally{m(!1)}}}return{meshQueue:i,setMeshQueue:c,queueSummary:u,queueLoading:d,queueError:h,loadQueue:k,handleLoadQueue:f}}function GI(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}const ef=new Map;function tf(e){return e?ef.get(e)??null:null}function zI(e,t){!e||!t||ef.set(e,t)}function KI({selectedMeshId:e,loadMeshStatus:t,extractStatus:n,normalizeNode:a,gateIncompleteGraph:r}){const[o,i]=l.useState(()=>tf(e)),[c,u]=l.useState(!1),[p,d]=l.useState(null),[m,h]=l.useState("idle"),[g,k]=l.useState(!1),f=l.useRef(!1);async function x(w,b=e,S=!1){if(!(!w||!b))try{u(!S&&o===null),h(S?"settling":"first_paint"),d(null);const N=await t(w,b,{refresh:S,retryProfile:S?"settled":"interactive"});k(GI(N));const v=n(N),y=a&&v?{...v,nodes:(v.nodes??[]).map(j=>a(j,v.meshId??b,""))}:v;if(y){if(r&&!S&&o!==null&&!zA(Dh(y))){h("settling"),f.current||(f.current=!0,Promise.resolve().then(()=>x(w,b,!0)).finally(()=>{f.current=!1}));return}i(y),zI(b,y),h("settled")}else i(null),d("mesh_status returned an unexpected payload."),h("idle")}catch(N){o||i(null),d((N==null?void 0:N.message)||"Failed to load mesh graph"),h("idle")}finally{u(!1)}}return{meshGraphStatus:o,setMeshGraphStatus:i,graphLoading:c,graphError:p,setGraphError:d,graphProvenance:m,graphBootstrapFallback:g,loadGraph:x}}function vu(e){return!e||e.hostSynthesized?{hostDaemonId:"",hostNodeId:""}:{hostDaemonId:String(e.hostDaemonId||""),hostNodeId:String(e.hostNodeId||"")}}function VI(e,t,n,a,r){if(!e.length)return"";const o=String(r||"");if(o){const u=e.find(p=>zs(p.id,o));return u?u.id:o}const i=t.find(u=>u.role==="host"),c=String((i==null?void 0:i.daemon_id)||(i==null?void 0:i.daemonId)||"");if(c){const u=e.find(p=>zs(p.id,c));if(u)return u.id}return""}const YI=7e3,QI=45e3;function JI(){const e=$P(),{sendCommand:t,sendData:n,daemons:a,userName:r,loadMeshStatus:o,launchCoordinator:i,loadLiveMesh:c,extractStatus:u,unwrapResult:p,normalizeMesh:d,normalizeNode:m,resolveCommandTarget:h,features:g,gateIncompleteGraph:k}=e,f=Qn(),x=a[0],w=(x==null?void 0:x.id)||"",b=l.useMemo(()=>((x==null?void 0:x.availableProviders)||[]).filter(rt=>rt.category==="cli").map(rt=>({id:rt.type||rt.id,name:rt.displayName||rt.name||rt.type,meshCoordinator:rt.meshCoordinator})),[x]),S=l.useMemo(()=>Un((x==null?void 0:x.availableProviders)||[]),[x]),{meshes:N,selectedMeshId:v,setSelectedMeshId:y,loading:j,error:C,setError:A,showCreate:T,setShowCreate:D,createName:I,setCreateName:M,createRepoIdentity:P,setCreateRepoIdentity:$,createRepoRemoteUrl:L,setCreateRepoRemoteUrl:R,newMeshDaemonId:F,setNewMeshDaemonId:E,newMeshWorkspace:H,setNewMeshWorkspace:_,createPickerWorkspaces:G,createOnboardingPlan:W,createPlanLoading:K,creating:V,createWarning:te,setCreateWarning:le,loadMeshes:de,handleCreate:ee,handleDelete:z,cancelCreate:X}=BI({daemons:a,primaryDaemonId:w,sendCommand:t,unwrapResult:p,normalizeMesh:d,features:g,loadDaemonMetadata:f}),U=N.find(Oe=>Oe.id===v)||null,{meshGraphStatus:Q,setMeshGraphStatus:ke,graphLoading:ve,graphError:ge,setGraphError:me,loadGraph:B}=KI({selectedMeshId:v,loadMeshStatus:o,extractStatus:u,normalizeNode:m,gateIncompleteGraph:k}),[O,Y]=l.useState(""),[se,Z]=l.useState(""),Ne=g.meshHostDaemonSection?O:w,{meshQueue:pe,loadQueue:fe}=qI({primaryDaemonId:w,activeDaemonId:Ne,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:h}),{setNodeProviderPriorityDrafts:Me,selectedNodeId:Ee,setSelectedNodeId:q,showAddNode:oe,setShowAddNode:Ie,nodeWorkspace:xe,setNodeWorkspace:he,nodeProviderPriority:Ze,setNodeProviderPriority:Ae,nodeDaemonId:_e,setNodeDaemonId:ie,nodeCustomPath:je,setNodeCustomPath:De,nodePickerWorkspaces:qe,nodePickerProviders:ye,nodeOnboardingPlan:Fe,nodePlanLoading:ut,coordinatorCliType:it,setCoordinatorCliType:mt,launchingCoordinator:J,launchResult:ne,savingPolicy:ce,coordinatorPromptDraft:be,setCoordinatorPromptDraft:re,savingCoordinatorPrompt:Te,nodeSystemPromptDrafts:He,setNodeSystemPromptDrafts:Pe,savingNodeSystemPromptId:Ge,savingNodeSlotsId:ze,savingNodeCapabilitiesId:Je,handleAddNode:Ue,handleRemoveNode:Qe,handleUpdatePolicy:st,handleUpdateNodeSlots:We,handleUpdateNodeCapabilities:ue,handleSaveCoordinatorPrompt:we,handleSaveNodeSystemPrompt:Se,handleLaunchCoordinator:Be,settingMeshHost:Xe,handleSetMeshHost:lt}=WI({selectedMesh:U,selectedMeshId:v,primaryDaemonId:w,activeDaemonId:Ne,daemons:a,availableCliProviders:S,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:h,launchCoordinator:i,features:{addNodeDaemonPicker:g.addNodeDaemonPicker},loadMeshes:de,loadQueue:fe,queueSection:g.queueSection,setError:A}),Ve=l.useMemo(()=>a.find(Oe=>Oe.id===Ne)||x,[a,Ne,x]),yt=l.useMemo(()=>new Set(((U==null?void 0:U.nodes)||[]).map(Oe=>String(Oe.daemon_id||Oe.daemonId||""))),[U]),Gt=l.useMemo(()=>a.filter(Oe=>Oe.id&&!yt.has(Oe.id)),[a,yt]),At=(U==null?void 0:U.nodes)||[],Xt=l.useMemo(()=>At.find(Oe=>zs(String(Oe.daemon_id||Oe.daemonId||""),O)),[At,O]),Zt=g.meshHostDaemonSection?!!Xt:!0,$t=l.useMemo(()=>{if(!g.meshHostDaemonSection||!U)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const Oe=U.meshHost,rt=Q!=null&&Q.meshId&&String(Q.meshId)===String(U.id??"")?Q.meshHost:void 0,ks=rt!=null&&rt.hostDaemonId?rt:Oe??rt,Ss=vu(ks),os=Ss.hostDaemonId,ae=At.find(Rs=>Rs.role==="host"),Ye=Ss.hostNodeId||String((ae==null?void 0:ae.id)||""),$e=Ye?At.find(Rs=>String(Rs.id)===Ye):void 0,Tt=String(($e==null?void 0:$e.daemon_id)||($e==null?void 0:$e.daemonId)||""),Ls=os||Tt;if(!Ls)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const Jn=a.find(Rs=>os&&zs(Rs.id,os))||(Tt?a.find(Rs=>zs(Rs.id,Tt)):void 0);if(Jn)return{pinned:!0,daemonId:Jn.id,label:XI(Jn),online:!0,hostNode:$e};const fo=String(($e==null?void 0:$e.machineLabel)||"")||String(($e==null?void 0:$e.workspace)||"")||Ls;return{pinned:!0,daemonId:Ls,label:fo,online:!1,hostNode:$e}},[U,At,a,Q,g.meshHostDaemonSection]),Le=$t.daemonId,et=$t.online,Rt=$t.pinned?$t.hostNode:Xt,ct=l.useMemo(()=>!g.meshHostDaemonSection||!$t.pinned?"":!et&&se&&a.some(Oe=>Oe.id===se)?se:Le,[g.meshHostDaemonSection,$t.pinned,et,se,a,Le]),Qt=l.useMemo(()=>Q?[...new Set((Q.nodes??[]).map(Oe=>String(Oe.daemonId||Oe.daemon_id||"")).filter(Boolean))]:[],[Q]),qt=Kh({status:Q,daemonId:Ne||null,extraDaemonIds:Qt,meshId:v,sendData:n});l.useEffect(()=>{Me(Object.fromEntries(((U==null?void 0:U.nodes)||[]).map(Oe=>[Oe.id,ZI(Oe)])))},[U]),l.useEffect(()=>{const Oe=(U==null?void 0:U.coordinator)||{};re({override:typeof Oe.systemPromptOverride=="string"?Oe.systemPromptOverride:"",append:typeof Oe.systemPromptAppend=="string"?Oe.systemPromptAppend:typeof Oe.systemPromptSuffix=="string"?Oe.systemPromptSuffix:""}),Pe(Object.fromEntries(((U==null?void 0:U.nodes)||[]).map(rt=>[rt.id,typeof rt.systemPrompt=="string"?rt.systemPrompt:""])))},[U]),l.useEffect(()=>{const Oe=g.addNodeDaemonPicker?Pa(ye):Pa(S);oe&&Ze.length===0&&Oe.length>0&&Ae(Oe)},[oe,S,ye,Ze.length,g.addNodeDaemonPicker]),l.useEffect(()=>{const Oe=new Set(((U==null?void 0:U.nodes)||[]).map(rt=>rt.id));Ee&&!Oe.has(Ee)&&q(null)},[U,Ee]);const zt=l.useMemo(()=>{if(!(!(Q!=null&&Q.meshId)||String(Q.meshId)!==String((U==null?void 0:U.id)??"")))return vu(Q.meshHost).hostDaemonId||void 0},[Q,U]),xs=l.useMemo(()=>VI(a,At,Ne,w,zt),[a,At,Ne,w,zt]);l.useEffect(()=>{if(!g.meshHostDaemonSection)return;if(!a.length&&!$t.pinned){Y("");return}const Oe=$t.pinned?ct:xs;Oe&&!zs(Oe,O)&&Y(Oe)},[a,O,$t.pinned,ct,xs,g.meshHostDaemonSection]),l.useEffect(()=>{se&&(et||!a.some(Oe=>Oe.id===se))&&Z("")},[et,se,a]),l.useEffect(()=>{if(g.createDaemonPicker){if(!a.length){E("");return}(!F||!a.some(Oe=>Oe.id===F))&&E(a[0].id)}},[a,F,g.createDaemonPicker]),l.useEffect(()=>{var Oe;if(!g.createDaemonPicker||!F){_("");return}if(!G.length){_("");return}G.some(rt=>rt.path===H)||_(((Oe=G[0])==null?void 0:Oe.path)||"")},[F,H,G,g.createDaemonPicker]);const Ps=l.useRef(null);l.useEffect(()=>{if(!v)return;const Oe=Ps.current!==v;if(Ps.current=v,Oe){const rt=tf(v);ke(rt),me(null),B(Ne,v,rt!==null)}else me(null),B(Ne,v,!0)},[v,Ne]);const vs=l.useRef(B);vs.current=B;const es=l.useRef(!1),ys=l.useRef(()=>{});ys.current=()=>{es.current||!v||!Ne||(es.current=!0,Promise.resolve(vs.current(Ne,v,!0)).finally(()=>{es.current=!1}))};const Is=g.meshStatePushRefresh?QI:YI;_P({daemonIds:l.useMemo(()=>[Ne,...Qt].filter(Boolean),[Ne,Qt]),meshId:v,sendData:n,onRevisionAdvance:()=>{typeof document<"u"&&document.visibilityState!=="visible"||ys.current()}}),l.useEffect(()=>{if(!v||!Ne||typeof document>"u")return;let Oe=null;const rt=()=>{document.visibilityState==="visible"&&ys.current()},ks=()=>{Oe===null&&(Oe=setInterval(rt,Is))},Ss=()=>{Oe!==null&&(clearInterval(Oe),Oe=null)},os=()=>{document.visibilityState==="visible"?ks():Ss()};return document.visibilityState==="visible"&&ks(),document.addEventListener("visibilitychange",os),()=>{Ss(),document.removeEventListener("visibilitychange",os)}},[v,Ne,Is]),l.useEffect(()=>{g.queueSection||fe(v)},[v,g.queueSection]);const Ws=l.useMemo(()=>a.map(Oe=>Oe.id).filter(Boolean).sort().join(","),[a]),ws=l.useRef(!1);return l.useEffect(()=>{de(ws.current),ws.current=!0},[Ws]),w?U?s.jsx($I,{selectedMesh:U,error:C,onDismissError:()=>A(null),onBack:()=>{y(null),ke(null)},onDelete:z,displayedMeshStatus:qt,graphLoading:ve,graphError:ge,onRefreshGraph:()=>B(Ne,v,!0),savingPolicy:ce,onUpdatePolicy:st,coordinatorPromptDraft:be,onCoordinatorPromptDraftChange:re,savingCoordinatorPrompt:Te,onSaveCoordinatorPrompt:we,daemons:a,coordinatorDaemonId:O,onCoordinatorDaemonIdChange:Y,coordinatorCliType:it,onCoordinatorCliTypeChange:mt,launchingCoordinator:J,launchResult:ne,isHostNodeAttached:Zt,selectedHostNode:Rt,hostPinned:$t.pinned,hostLabel:$t.label,hostOnline:et,hostRebindDaemonId:se,onHostRebindDaemonIdChange:Oe=>Z(Oe),onLaunchCoordinator:Be,settingMeshHost:Xe,onSetMeshHost:lt,activeDaemon:Ve,activeDaemonId:Ne,meshQueue:pe,userName:r,availableCliProviders:S,savingNodeSlotsId:ze,onUpdateNodeSlots:We,savingNodeCapabilitiesId:Je,onUpdateNodeCapabilities:ue,nodeSystemPromptDrafts:He,onNodeSystemPromptDraftChange:(Oe,rt)=>Pe(ks=>({...ks,[Oe]:rt})),savingNodeSystemPromptId:Ge,onSaveNodeSystemPrompt:Se,selectedNodeId:Ee,onSelectNode:q,showAddNode:oe,onShowAddNode:()=>Ie(!0),onCancelAddNode:()=>Ie(!1),nodeWorkspace:xe,onNodeWorkspaceChange:he,nodeProviderPriority:Ze,onNodeProviderPriorityChange:Ae,nodeDaemonId:_e,onNodeDaemonIdChange:ie,nodeCustomPath:je,onNodeCustomPathChange:De,nodePickerWorkspaces:qe,nodePickerProviders:ye,nodeOnboardingPlan:Fe,nodePlanLoading:ut,attachableDaemons:Gt,onAddNode:Ue,onRemoveNode:Qe,availableCliAgents:b,features:{coordinatorPrompt:g.coordinatorPrompt,meshHostDaemonSection:g.meshHostDaemonSection,hermesMcpConfig:g.hermesMcpConfig,addNodeDaemonPicker:g.addNodeDaemonPicker,nodeInstruction:g.nodeInstruction},sendCommand:t}):s.jsx(GP,{meshes:N,loading:j,error:C,onDismissError:()=>A(null),daemons:a,features:{createDaemonPicker:g.createDaemonPicker,maxMeshes:g.maxMeshes},showCreate:T,onToggleCreate:()=>D(!T),createName:I,onCreateNameChange:M,createRepoIdentity:P,onCreateRepoIdentityChange:$,createRepoRemoteUrl:L,onCreateRepoRemoteUrlChange:R,newMeshDaemonId:F,onNewMeshDaemonIdChange:E,newMeshWorkspace:H,onNewMeshWorkspaceChange:_,createPickerWorkspaces:G,createOnboardingPlan:W,createPlanLoading:K,creating:V,createWarning:te,onDismissCreateWarning:()=>le(null),onSelectMesh:y,onCreate:ee,onCancelCreate:X}):s.jsx(Fa,{icon:s.jsx(as,{}),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 XI(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function ZI(e){var a;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((a=e.policy)==null?void 0:a.providerPriority)?e.policy.providerPriority:[],n=new Set;return t.map(r=>typeof r=="string"?r.trim():"").filter(Boolean).filter(r=>n.has(r)?!1:(n.add(r),!0))}function eL({children:e}){const{sendCommand:t,sendData:n}=kt(),{ides:a}=Ms(),r=l.useMemo(()=>a.filter(i=>i.daemonMode||i.type==="adhdev-daemon").map(i=>i),[a]),o=l.useMemo(()=>({sendCommand:t,sendData:n,daemons:r,userName:void 0,loadMeshStatus:async(i,c)=>t(i,"mesh_status",{meshId:c}),launchCoordinator:async(i,c)=>{var h;const u={meshId:c.meshId};c.cliType&&(u.cliType=c.cliType);const p=await t(i,"launch_mesh_coordinator",u),d=(p==null?void 0:p.result)??p;if((d==null?void 0:d.success)===!1)throw new Error(d.error||"Coordinator launch failed");const m=(d==null?void 0:d.sessionId)||((h=d==null?void 0:d.session)==null?void 0:h.id)||(d==null?void 0:d.targetSessionId);return{sessionId:m,message:m?`Coordinator launched (${m})`:"Coordinator launch command sent"}},loadLiveMesh:void 0,extractStatus:vl,unwrapResult:i=>i,normalizeMesh:(i,c)=>i,normalizeNode:(i,c,u)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:HP}),[t,n,r]);return s.jsx(Zh.Provider,{value:o,children:e})}function Ql(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function tL(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=Ql();return n&&!t.searchParams.has("token")&&t.searchParams.set("token",n),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function Ns(e,t){return await fetch(tL(e),{credentials:"same-origin",...t})}function sf(){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 sL{constructor(){at(this,"adapters",new Map);at(this,"states",new Map);at(this,"runtimeListeners",new Map);at(this,"screenshotCallbacks",new Map);at(this,"statusCallbacks",new Set);at(this,"stateChangeCallbacks",new Set);at(this,"ptyInputSender",null)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const n of this.adapters.keys())if(n.startsWith("standalone"))return n}return null}register(t,n){this.adapters.set(t,n),this.states.set(t,n.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,n){this.states.set(t,n);const a=this.resolveDaemonId(t)||t;this.stateChangeCallbacks.forEach(r=>r(a,n))}onStateChange(t){return this.stateChangeCallbacks.add(t),()=>{this.stateChangeCallbacks.delete(t)}}retryConnection(t){}get(t){const n=this.resolveDaemonId(t);return n?this.adapters.get(n):void 0}getState(t){const n=this.resolveDaemonId(t);return n&&this.states.get(n)||"disconnected"}registerPtyInputSender(t){this.ptyInputSender=t}sendData(t,n){return!1}sendPtyInput(t,n,a){return this.ptyInputSender?this.ptyInputSender(t,n,a):!1}onScreenshot(t,n){return this.screenshotCallbacks.set(t,n),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,n){this.screenshotCallbacks.forEach(a=>a(t,n))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,n){this.statusCallbacks.forEach(a=>a(t,n))}emitRuntimeSnapshot(t,n,a=0,r=!1,o,i){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:a,text:n,truncated:r,cols:o,rows:i})}emitSessionOutput(t,n,a){!t||typeof n!="string"||!n||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof a=="number"?{seq:a}:{},data:n})}onRuntimeEvent(t,n){const a=this.runtimeListeners.get(t)||new Set;return a.add(n),this.runtimeListeners.set(t,a),()=>{const r=this.runtimeListeners.get(t);r&&(r.delete(n),r.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,n,a){if(!n)return{success:!1,error:"sessionId is required"};const r=new URL(`/api/v1/runtime/${encodeURIComponent(n)}/snapshot`,window.location.origin);typeof(a==null?void 0:a.sinceSeq)=="number"&&r.searchParams.set("sinceSeq",String(a.sinceSeq));const o=await Ns(`${r.pathname}${r.search}`);if(!o.ok){let c=`Runtime snapshot unavailable (${o.status})`;try{const u=await o.json();u!=null&&u.error&&(c=u.error)}catch{}return{success:!1,error:c}}const i=await o.json();return this.emitRuntimeEvent(n,{type:"runtime_snapshot",sessionId:n,seq:typeof i.seq=="number"?i.seq:0,text:typeof i.text=="string"?i.text:"",truncated:!!i.truncated,cols:typeof i.cols=="number"?i.cols:void 0,rows:typeof i.rows=="number"?i.rows:void 0,force:!!(a!=null&&a.force)}),{success:!0}}emitRuntimeEvent(t,n){var a;(a=this.runtimeListeners.get(t))==null||a.forEach(r=>r(n))}}const js=new sL;function nL(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,n=Ql();return n?`${t}?token=${encodeURIComponent(n)}`:t}const cr=nL(),yu=3e3,aL=3e4;let cs=null,rL=0;const Ur=new Map;let on=null,Sa=null;function wu(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function da(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function oL(e){return e==="connected"?"connected":e}async function Ca(e,t,n){const a=vm(e,n||{}),r=cs;if(r&&r.readyState===WebSocket.OPEN){const o=`req_${++rL}_${Date.now()}`;return new Promise((i,c)=>{const u=setTimeout(()=>{Ur.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);Ur.set(o,{resolve:p=>{clearTimeout(u),i(p)},reject:p=>{clearTimeout(u),c(p)}}),r.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:a.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function Xi(e,t){const n=cs;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 nf(e,t,n){const a=cs;if(!a||a.readyState!==WebSocket.OPEN)return!1;const r=vm(e,{sessionId:t,targetSessionId:t,data:n});try{return a.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:r.payload}})),!0}catch{return!1}}js.registerPtyInputSender(nf);class iL{constructor(t){at(this,"daemonId");at(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(cs==null?void 0:cs.readyState)===WebSocket.OPEN}get connectionState(){return(cs==null?void 0:cs.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,n){return Ca(this.daemonId,t,n)}async sendInput(t,n){return Ca(this.daemonId,"cdp_remote_action",{action:t,params:n,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,on&&(clearInterval(on),on=null);const n=async()=>{if(this.hasCommandChannel)try{const a=await Ca(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(a!=null&&a.success&&(a!=null&&a.base64)){const r=await fetch(`data:image/jpeg;base64,${a.base64}`).then(o=>o.blob());js.emitScreenshot(this.daemonId,r)}}catch{}};n(),on=setInterval(n,2e3)}stopScreenshots(t){on&&(clearInterval(on),on=null)}}let ss=null;function lL(e){return(!ss||ss.daemonId!==e)&&(ss=new iL(e)),ss}function cL({children:e}){const t=l.useRef(ja()),n=ja();t.current=n;const{setUserName:a}=Ms(),r=l.useRef(a);r.current=a;const o=l.useRef(null),i=l.useRef(null),[,c]=l.useState("disconnected"),u=l.useCallback((f,x)=>{c(f),Sa==null||Sa(f,x)},[]),p=l.useRef(null),d=l.useRef(),m=l.useRef(yu),h=l.useRef(!0),g=l.useRef(!1),k=l.useRef("initial_connect");return l.useEffect(()=>{h.current=!0,g.current=!1;function f(){var b,S;if(!h.current||((b=p.current)==null?void 0:b.readyState)===WebSocket.OPEN||((S=p.current)==null?void 0:S.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${cr}...`),da("connect_attempt",{url:cr,reason:k.current,delayMs:m.current});let w;try{w=new WebSocket(cr)}catch(N){console.error("[Standalone WS] Failed to create WebSocket:",N),x();return}p.current=w,w.onopen=()=>{if(!h.current){w.close();return}u("connected"),m.current=yu,da("open",{url:cr,reason:k.current}),hs.resubscribeAll({sendData:Xi}),console.log("[Standalone WS] Connected")},cs=w,w.onmessage=N=>{var v,y;try{const j=JSON.parse(N.data);if((j.type==="command_result"||j.type==="error")&&j.requestId){const C=Ur.get(j.requestId);C&&(Ur.delete(j.requestId),j.type==="error"?C.reject(new Error(((v=j.data)==null?void 0:v.message)||"Command failed")):C.resolve(j.data));return}if(j.type==="session_output"){const C=j.sessionId||j.cliId||j.cliType;C&&js.emitSessionOutput(C,typeof j.data=="string"?j.data:"",typeof j.seq=="number"?j.seq:void 0);return}if(j.type==="runtime_snapshot"){js.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 C=j.update;C&&hs.publish(C);return}if(j.type==="status"||j.type==="initial_state"){const C=j.data;if(!C)return;const{injectEntries:A,markLoaded:T,getIdes:D}=t.current,I=C.instanceId||"standalone",M=D().find(L=>L.id===I),P=lL(I);js.register(I,P),js.setState(I,"connected"),u("connected",I),js.emitStatus(I,C);const $=Tr(C,{daemonId:I,existingDaemon:M,existingEntries:D()});wu("ws_status",{type:j.type,daemonId:I,sessions:(C.sessions||[]).map(L=>({id:L.id,parentId:L.parentId,providerType:L.providerType,kind:L.kind,transport:L.transport,unread:L.unread,inboxBucket:L.inboxBucket,lastSeenAt:L.lastSeenAt,lastUpdated:L.lastUpdated,title:L.title})),recentLaunches:(C.recentLaunches||[]).map(L=>({id:L.id,providerType:L.providerType,kind:L.kind,workspace:L.workspace,lastLaunchedAt:L.lastLaunchedAt}))}),wu("entries",{daemonId:I,entries:$.filter(L=>L.type!=="adhdev-daemon").map(L=>({id:L.id,type:L.type,unread:L.unread,inboxBucket:L.inboxBucket,lastSeenAt:L.lastSeenAt,lastUpdated:L.lastUpdated,sessionId:L.sessionId}))}),$.length>0&&A($,{authoritativeDaemonIds:[I]}),T(),i.current!==I&&((y=o.current)==null||y.call(o),i.current=I,o.current=hs.subscribe({sendData:Xi},I,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${I}`,params:{includeSessions:!0}},L=>{if(L.topic!=="daemon.metadata")return;const R=t.current.getIdes(),F=R.find(H=>H.id===I),E=Tr(L.status,{daemonId:I,existingDaemon:F,existingEntries:R,timestamp:L.timestamp});E.length>0&&t.current.injectEntries(E,{authoritativeDaemonIds:[I]}),L.userName&&r.current&&r.current(L.userName)}))}}catch(j){console.error("[Standalone WS] Parse error:",j)}},w.onclose=N=>{h.current&&(ss==null||ss.stopScreenshots(),ss&&js.setState(ss.daemonId,"disconnected"),u("disconnected"),p.current=null,k.current=`close:${N.code}${N.wasClean?":clean":":unclean"}`,da("close",{code:N.code,reason:N.reason||"",wasClean:N.wasClean}),x())},w.onerror=N=>{g.current||!h.current||(k.current="error",da("error",{message:N instanceof Event?"event":String(N),readyState:w.readyState}),console.warn("[Standalone WS] Error, will reconnect:",N))}}function x(){if(!h.current)return;clearTimeout(d.current);const w=m.current;console.log(`[Standalone WS] Reconnecting in ${w}ms...`),da("schedule_reconnect",{reason:k.current,delayMs:w}),d.current=setTimeout(()=>{m.current=Math.min(m.current*1.5,aL),f()},w)}return f(),()=>{var w;h.current=!1,g.current=!0,(w=o.current)==null||w.call(o),o.current=null,i.current=null,clearTimeout(d.current),p.current&&(p.current.onerror=null,p.current.onclose=null,p.current.close(),p.current=null,cs=null),ss&&(ss.stopScreenshots(),js.unregister(ss.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function dL({children:e}){const[t,n]=l.useState("disconnected"),[a,r]=l.useState(null);l.useEffect(()=>(Sa=(i,c)=>{n(i),c&&r(c)},()=>{Sa=null}),[]);const o=l.useMemo(()=>{const i=t==="connected",c=oL(t),u={};return a&&(u[a]=c),u.standalone=c,{wsStatus:t,isConnected:i,connectionStates:u,usesP2P:!1}},[t,a]);return s.jsx(Qf,{connectionOverrides:o,children:s.jsx(cL,{children:e})})}const af="adhdev_standalone_font_preferences",bn={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},ho=[{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"}],Ra=[{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"}],uL=new Set(ho.map(e=>e.id)),pL=new Set(Ra.map(e=>e.id));function As(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:wr("chat",t.chat),code:wr("code",t.code),terminal:wr("terminal",t.terminal)}}function wr(e,t){const n=bn[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"?uL:pL).has(r)?r==="custom"?o?{preset:"custom",customFamily:o}:n:{preset:r}:n}function kr(e,t){var r;const n=wr(e,t);if(n.preset==="custom"&&n.customFamily)return n.customFamily;const a=e==="chat"?ho:Ra;return((r=a.find(o=>o.id===n.preset))==null?void 0:r.family)||a[0].family}function mL(e){const t=As(e),n=kr("chat",t.chat),a=kr("code",t.code),r=kr("terminal",t.terminal);return{"--chat-font-family":n,"--chat-code-font-family":a,"--chat-terminal-font-family":r,"--chat-tool-font-family":r}}function cn(e,t=document.documentElement){const n=As(e),a=mL(n);t.setAttribute("data-standalone-fonts","custom");for(const[r,o]of Object.entries(a))t.style.setProperty(r,o);return n}function Zi(e){const t=As(e);try{localStorage.setItem(af,JSON.stringify(t))}catch{}return t}function hL(){try{const e=localStorage.getItem(af);if(e)return As(JSON.parse(e))}catch{}return bn}function fL(){return cn(hL())}function ua(e,t){var a;const n=e==="chat"?ho:Ra;return((a=n.find(r=>r.id===t))==null?void 0:a.label)||n[0].label}function bL({children:e}){const t=Ea(),n=tl(),{t:a}=Ce("common"),r=l.useMemo(()=>[{id:"dashboard",path:"/dashboard",icon:s.jsx(_u,{}),label:a("standalone.nav.dashboard"),active:n.pathname.startsWith("/dashboard"),onSelect:()=>t("/dashboard")},{id:"machine",path:"/machines",icon:s.jsx(Ys,{}),label:"Burrow",active:n.pathname.startsWith("/machines"),onSelect:()=>t("/machines")},{id:"mesh",path:"/mesh",icon:s.jsx(as,{}),label:"Mesh",active:n.pathname.startsWith("/mesh"),onSelect:()=>t("/mesh")},{id:"settings",path:"/settings",icon:s.jsx(Gr,{}),label:a("standalone.nav.settings"),active:n.pathname.startsWith("/settings"),onSelect:()=>t("/settings")}],[n.pathname,t,a]),o=l.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:a("standalone.nav.docs")}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx($u,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:a("standalone.nav.docs")},{id:"about",label:a("standalone.nav.about"),icon:s.jsx(rl,{}),active:n.pathname==="/about",onSelect:()=>t("/about"),title:a("standalone.nav.about")}],[n.pathname,t,a]);return s.jsx(WC,{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.42"]}),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})}const gL=[{icon:s.jsx(Ys,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(kn,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Wu,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(gs,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(Na,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx($u,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],xL=[{icon:s.jsx(Nb,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(_u,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Vn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(yb,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(Hu,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(kb,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],vL=[{feature:"Agent chat relay",selfhost:!0,cloud:!0},{feature:"Live IDE screenshots",selfhost:!0,cloud:!0},{feature:"Remote IDE control",selfhost:!0,cloud:!0},{feature:"Multi-IDE monitoring",selfhost:!0,cloud:!0},{feature:"Extension and CLI agents",selfhost:!0,cloud:!0},{feature:"Access from any network",selfhost:!1,cloud:!0},{feature:"WebRTC P2P streaming",selfhost:!1,cloud:!0},{feature:"Mobile push notifications",selfhost:!1,cloud:!0},{feature:"REST API and webhooks",selfhost:!1,cloud:!0},{feature:"Team collaboration",selfhost:!1,cloud:!0},{feature:"Multi-machine burrows",selfhost:!1,cloud:!0},{feature:"SSO, RBAC, audit logs",selfhost:!1,cloud:!0}];function yL(){const{t:e}=Ce("common");return s.jsxs(Fa,{icon:s.jsx(rl,{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.42"]}),children:[s.jsx(gt,{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(gt,{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:gL.map(t=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:t.icon}),t.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:t.desc})]},t.title))})}),s.jsx(gt,{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:ym.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:km.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:wm.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(gt,{title:e("standalone.about.cloudExtrasSection"),description:e("standalone.about.cloudExtrasDescription"),children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:xL.map(t=>s.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:t.icon}),t.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:t.desc})]},t.title))})}),s.jsx(gt,{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:vL.map((t,n)=>s.jsxs("tr",{className:n%2===0?"bg-bg-glass":"bg-transparent",children:[s.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:t.feature}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:t.selfhost?s.jsx("span",{className:"text-emerald-500",children:"✓"}):s.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:s.jsx("span",{className:"text-emerald-500",children:"✓"})})]},t.feature))})]})})}),s.jsx(so,{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(Eb,{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}=Ce("common");return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:n})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(GC,{value:a.preset,onChange:c=>{const u=c.target.value;o(u==="custom"?{preset:"custom",customFamily:a.customFamily||""}:{preset:u})},children:r.map(c=>s.jsx("option",{value:c.id,children:c.label},c.id))}),a.preset==="custom"&&s.jsx(ps,{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:kr(e,a)})]})]})]})}function wL({value:e,savedValue:t,saving:n=!1,error:a,notice:r,onChange:o,onSave:i,onResetToSaved:c,onResetToDefaults:u}){const{t:p}=Ce("common"),d=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:p("standalone.fonts.fontOverridesNotice")}),a&&s.jsx(Dt,{variant:"error",children:a}),r&&s.jsx(Dt,{variant:"success",children:r}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(bi,{surface:"chat",title:p("standalone.fonts.chat"),description:p("standalone.fonts.chatDescription"),value:e.chat,options:ho,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:Ra,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:Ra,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: ",ua("chat",e.chat.preset)," · Code: ",ua("code",e.code.preset)," · Terminal: ",ua("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[p("standalone.fonts.defaults")," ",ua("chat",bn.chat.preset)," / ",ua("code",bn.code.preset)]})]}),s.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:s.jsxs("div",{className:"chat-container-content",children:[s.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:s.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[s.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[s.jsx("span",{className:"chat-sender",children:"Hermes"}),s.jsx("span",{className:"chat-time",children:"now"})]}),s.jsxs("div",{className:"chat-markdown",children:[s.jsxs("p",{children:["Readable prose, ",s.jsx("strong",{children:"bold text"}),", and ",s.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),s.jsx("pre",{children:s.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),s.jsxs("div",{className:"chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"▸"}),s.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),s.jsxs("div",{className:"chat-msg-terminal",children:[s.jsx("div",{className:"chat-msg-header",children:"Terminal"}),s.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx(Hs,{type:"button",variant:"primary",size:"sm",onClick:i,disabled:n||!d,children:p(n?"standalone.fonts.saving":"standalone.fonts.saveFontSettings")}),s.jsx(Hs,{type:"button",variant:"secondary",size:"sm",onClick:c,disabled:n||!d,children:p("standalone.fonts.revertToSaved")}),s.jsx(Hs,{type:"button",variant:"secondary",size:"sm",onClick:u,disabled:n,children:p("standalone.fonts.resetToDefaults")})]})]})}function kL(){const{t:e}=Ce("common"),{ides:t}=Ms(),n=t.find(z=>z.type==="adhdev-daemon"),a=(n==null?void 0:n.detectedIdes)||[],{sendCommand:r}=kt(),{userName:o}=Ms(),[i,c]=l.useState(o||""),[u,p]=l.useState(null),[d,m]=l.useState(null),[h,g]=l.useState(bn),[k,f]=l.useState(!1),[x,w]=l.useState(""),[b,S]=l.useState(""),[N,v]=l.useState("127.0.0.1"),[y,j]=l.useState(""),[C,A]=l.useState(""),[T,D]=l.useState(""),[I,M]=l.useState(""),[P,$]=l.useState(""),[L,R]=l.useState(!1),F=async()=>{const X=await(await Ns("/auth/session")).json();p(X)},E=async()=>{const X=await(await Ns("/api/v1/standalone/preferences")).json();m(X),v(X.standaloneBindHost);const U=As(X.standaloneFontPreferences);g(U),cn(U),Zi(U)};l.useEffect(()=>{o!==void 0&&c(o)},[o]),l.useEffect(()=>{Promise.all([F(),E()]).catch(z=>{M(z instanceof Error?z.message:String(z))})},[]),l.useEffect(()=>{cn(h)},[h]);const H=z=>{const X=z.target.value.trim();n!=null&&n.id&&X!==o&&r(n.id,"set_user_name",{userName:X}).catch(console.error)},[_,G]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),W=z=>{G(z);try{localStorage.setItem("adhdev_sound",z?"1":"0")}catch{}},K=async()=>{w(""),S(""),f(!0);try{const z=As(h),X=await Ns("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:z})}),U=await X.json();if(!X.ok)throw new Error((U==null?void 0:U.error)||"Failed to save standalone font preferences");const Q=As(U.standaloneFontPreferences);m(U),g(Q),cn(Q),Zi(Q),S(e("standalone.settings.fontsSaved"))}catch(z){w(z instanceof Error?z.message:String(z))}finally{f(!1)}},V=()=>{const z=As(d==null?void 0:d.standaloneFontPreferences);w(""),S(""),g(z),cn(z)},te=()=>{w(""),S(""),g(bn),cn(bn)},le=async()=>{M(""),$(""),R(!0);try{const z=await Ns("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:N})}),X=await z.json();if(!z.ok)throw new Error((X==null?void 0:X.error)||"Failed to save standalone network preference");m(X),v(X.standaloneBindHost),$(X.standaloneBindHost==="0.0.0.0"?e("standalone.settings.networkSavedAll"):e("standalone.settings.networkSavedLocal"))}catch(z){M(z instanceof Error?z.message:String(z))}finally{R(!1)}},de=async()=>{if(M(""),$(""),C.trim().length<4){M(e("standalone.settings.passwordTooShort"));return}if(C!==T){M(e("standalone.settings.passwordMismatch"));return}R(!0);try{const z=await Ns("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,newPassword:C})}),X=await z.json();if(!z.ok)throw new Error((X==null?void 0:X.error)||"Failed to save password");p(X),await E(),j(""),A(""),D(""),$(u!=null&&u.hasPasswordAuth?e("standalone.settings.passwordUpdated"):e("standalone.settings.passwordEnabled")),sf()}catch(z){M(z instanceof Error?z.message:String(z))}finally{R(!1)}},ee=async()=>{M(""),$(""),R(!0);try{const z=await Ns("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:y,clear:!0})}),X=await z.json();if(!z.ok)throw new Error((X==null?void 0:X.error)||"Failed to clear password");p(X),await E(),j(""),A(""),D(""),$(e("standalone.settings.passwordDisabled"))}catch(z){M(z instanceof Error?z.message:String(z))}finally{R(!1)}};return s.jsxs(Fa,{icon:s.jsx(Gr,{className:"text-text-primary"}),title:e("standalone.settings.title"),subtitle:e("standalone.settings.subtitle"),widthClassName:"max-w-5xl",children:[s.jsx(Dt,{variant:"info",children:e("standalone.settings.infoNotice")}),(u==null?void 0:u.publicHostWarning)&&s.jsx(Dt,{variant:"warning",children:e("standalone.settings.publicHostWarning")}),s.jsx(gt,{title:e("standalone.settings.daemonSection"),description:e("standalone.settings.daemonDescription"),children:s.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.versionLabel")}),s.jsxs("span",{className:"font-mono text-xs",children:["v","1.0.42"]}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.statusLabel")}),s.jsx("span",{className:n?"text-green-400":"text-yellow-400",children:e(n?"standalone.settings.statusRunning":"standalone.settings.statusNotConnected")}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.currentBindLabel")}),s.jsx("span",{className:"font-mono text-xs",children:(d==null?void 0:d.currentBindHost)||(u==null?void 0:u.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.defaultBindLabel")}),s.jsx("span",{className:"font-mono text-xs",children:(d==null?void 0:d.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.authLabel")}),s.jsx("span",{className:"text-xs",children:u!=null&&u.hasPasswordAuth?e("standalone.settings.authPassword"):u!=null&&u.hasTokenAuth?e("standalone.settings.authToken"):e("standalone.settings.authNone")})]})}),s.jsx(gt,{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:N==="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:N==="0.0.0.0",onChange:()=>v("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:e("standalone.settings.allInterfacesLabel")}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:e("standalone.settings.allInterfacesHint")})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx(Hs,{type:"button",variant:"primary",size:"sm",onClick:()=>{le()},disabled:L,children:e(L?"standalone.settings.saving":"standalone.settings.saveNetworkMode")}),s.jsx("span",{className:"text-xs text-text-muted",children:e("standalone.settings.networkRestartHint",{host:(d==null?void 0:d.currentBindHost)||(u==null?void 0:u.boundHost)||"127.0.0.1"})})]})]})}),s.jsx(gt,{title:e("standalone.settings.securitySection"),description:e("standalone.settings.securityDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:u!=null&&u.hasPasswordAuth?e("standalone.settings.passwordSet"):e("standalone.settings.passwordNotSet")}),I&&s.jsx(Dt,{variant:"error",children:I}),P&&s.jsx(Dt,{variant:"success",children:P}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx(ps,{type:"password",placeholder:u!=null&&u.hasPasswordAuth?e("standalone.settings.currentPasswordPlaceholder"):e("standalone.settings.currentPasswordFirstTimePlaceholder"),value:y,onChange:z=>j(z.target.value)}),s.jsx(ps,{type:"password",placeholder:u!=null&&u.hasPasswordAuth?e("standalone.settings.newPasswordPlaceholder"):e("standalone.settings.newPasswordFirstTimePlaceholder"),value:C,onChange:z=>A(z.target.value)}),s.jsx(ps,{type:"password",className:"md:col-span-2",placeholder:e("standalone.settings.confirmPasswordPlaceholder"),value:T,onChange:z=>D(z.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Hs,{type:"button",variant:"primary",size:"sm",onClick:()=>{de()},disabled:L,children:L?e("standalone.settings.saving"):u!=null&&u.hasPasswordAuth?e("standalone.settings.updatePassword"):e("standalone.settings.enablePassword")}),(u==null?void 0:u.hasPasswordAuth)&&s.jsx(Hs,{type:"button",variant:"danger",size:"sm",onClick:()=>{ee()},disabled:L,children:e("standalone.settings.disablePassword")})]})]})}),s.jsx(gt,{title:e("standalone.settings.detectedIdesSection"),description:e("standalone.settings.detectedIdesDescription"),children:a.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:e("standalone.settings.noIdesDetected")}):s.jsx("div",{className:"flex flex-col gap-1.5",children:a.map(z=>s.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${z.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:z.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:z.type})]},z.type))})}),s.jsx(gt,{title:e("standalone.settings.machineSection"),description:e("standalone.settings.machineDescription"),children:s.jsx(ej,{ides:t,emptyMessage:e("standalone.settings.daemonNotConnected")})}),s.jsx(gt,{title:e("standalone.settings.appearanceSection"),description:e("standalone.settings.appearanceDescription"),children:s.jsx(yj,{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(wL,{value:h,savedValue:As(d==null?void 0:d.standaloneFontPreferences),saving:k,error:x,notice:b,onChange:g,onSave:()=>{K()},onResetToSaved:V,onResetToDefaults:te})]})})}),s.jsx(gt,{title:e("standalone.settings.notificationsSection"),description:e("standalone.settings.notificationsDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(YC,{}),s.jsx(ln,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Rb,{size:15})," ",e("standalone.settings.soundEffectsLabel")]}),description:e("standalone.settings.soundEffectsDescription"),checked:_,onChange:W})]})}),s.jsx(gt,{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(vb,{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(ps,{type:"text",className:"w-48 text-right",placeholder:e("standalone.settings.displayNamePlaceholder"),value:i,onChange:z=>c(z.target.value),onBlur:H,onKeyDown:z=>{z.key==="Enter"&&z.currentTarget.blur()}})]})})})]})}const SL=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],fa="adhdev_onboarding_done",CL=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],jL={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function NL({onDone:e}){const{t}=Ce("common"),[n,a]=l.useState([]),[r,o]=l.useState(new Set(SL)),[i,c]=l.useState(!0),[u,p]=l.useState(null),[d,m]=l.useState(!1),[h,g]=l.useState(null),[k,f]=l.useState("all");l.useEffect(()=>{let y=!1;const j=window.location.hostname==="localhost"?"/registry":"https://api.adhf.dev/api/v1/registry";return fetch(`${j}/providers?sort=popular&limit=100`).then(C=>{if(!C.ok)throw new Error(`HTTP ${C.status}`);return C.json()}).then(C=>{y||a(C.providers??[])}).catch(C=>{y||p(C instanceof Error?C.message:String(C))}).finally(()=>{y||c(!1)}),()=>{y=!0}},[]);const x=n.filter(y=>k==="all"||y.category===k),w=["cli","ide","extension","acp"].map(y=>({category:y,items:x.filter(j=>j.category===y)})).filter(y=>y.items.length>0),b=l.useCallback(y=>{o(j=>{const C=new Set(j);return C.has(y)?C.delete(y):C.add(y),C})},[]),S=l.useCallback(async()=>{if(r.size===0){localStorage.setItem(fa,"1"),e();return}m(!0);const y=[];for(const j of r)try{const A=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:j})})).json().catch(()=>({}));y.push({type:j,ok:!!A.success,error:A.error})}catch(C){y.push({type:j,ok:!1,error:C instanceof Error?C.message:String(C)})}g(y),m(!1),y.every(j=>j.ok)&&localStorage.setItem(fa,"1")},[r,e]),N=l.useCallback(()=>{localStorage.setItem(fa,"1"),e()},[e]),v=l.useCallback(()=>{h&&h.every(y=>y.ok)?e():d||N()},[h,d,e,N]);return s.jsx(jp,{open:!0,onClose:v,size:"lg",contentClassName:"max-w-2xl",title:t("standalone.onboarding.title"),footer:s.jsxs("div",{className:"flex w-full items-center gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:t(r.size!==1?"standalone.onboarding.selectedCount_other":"standalone.onboarding.selectedCount_one",{count:r.size})}),s.jsxs("div",{className:"ml-auto flex gap-2",children:[s.jsx(Hs,{variant:"secondary",size:"sm",onClick:N,disabled:d,children:t("standalone.onboarding.skip")}),s.jsx(Hs,{variant:"primary",size:"sm",onClick:()=>{h?(localStorage.setItem(fa,"1"),e()):S()},disabled:d||!h&&r.size===0,children:d?t("standalone.onboarding.installing"):h?t("standalone.onboarding.done"):t("standalone.onboarding.installCount",{count:r.size})})]})]}),children:s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsx("div",{className:"text-[12px] text-text-muted",children:t("standalone.onboarding.intro")}),!i&&!u&&n.length>0&&s.jsx("div",{className:"flex gap-1 flex-wrap border-b border-border-subtle pb-2",children:CL.map(y=>{const j=y.key==="all"?n.length:n.filter(C=>C.category===y.key).length;return j===0&&y.key!=="all"?null:s.jsxs("button",{onClick:()=>f(y.key),className:`machine-btn text-[10px] px-2 py-0.5 ${k===y.key?"bg-accent-primary/12 border-accent-primary/40 text-accent-primary":""}`,children:[y.label," ",s.jsxs("span",{className:"opacity-60",children:["(",j,")"]})]},y.key)})}),i&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.loadingRegistry")}),!i&&u&&s.jsx(Dt,{variant:"error",children:t("standalone.onboarding.loadError",{error:u})}),!i&&!u&&x.length===0&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.noProviders")}),!i&&!u&&x.length>0&&s.jsx("div",{className:"flex flex-col gap-4",children:w.map(y=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:jL[y.category]??y.category}),s.jsx("div",{className:"grid gap-1.5",children:y.items.map(j=>{var I,M;const C=r.has(j.type),A=h==null?void 0:h.find(P=>P.type===j.type),T=((I=j.manifest)==null?void 0:I.icon)??"📦",D=((M=j.manifest)==null?void 0:M.details)??"";return s.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${C?"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:C,onChange:()=>b(j.type),disabled:d,className:"shrink-0"}),s.jsx("span",{className:"text-base shrink-0",children:T}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[13px] font-medium text-text-primary truncate",children:j.displayName}),D&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:D})]}),A&&s.jsx("span",{className:`text-[10px] font-semibold ${A.ok?"text-status-online":"text-status-error"}`,children:A.ok?t("standalone.onboarding.installed"):t("standalone.onboarding.installFailed",{error:A.error??"failed"})})]},j.type)})})]},y.category))})]})})}function AL(){try{return localStorage.getItem(fa)==="1"}catch{return!1}}DC();pj();dw();fL();const TL=Mu({baseUrl:"",getToken:Ql});function ML({children:e}){const{t}=Ce("common"),[n,a]=l.useState(null),[r,o]=l.useState(!0),[i,c]=l.useState(""),[u,p]=l.useState(""),[d,m]=l.useState(!1),h=async()=>{o(!0),p("");try{const f=await(await Ns("/auth/session")).json();a(f)}catch(k){p(k instanceof Error?k.message:String(k))}finally{o(!1)}};l.useEffect(()=>{h()},[]),l.useEffect(()=>{if(!n||n.required&&!n.authenticated)return;let k=!1;return(async()=>{try{const f=await Ns("/api/v1/standalone/preferences");if(!f.ok)return;const x=await f.json();if(k)return;const w=As(x.standaloneFontPreferences);cn(w),Zi(w)}catch{}})(),()=>{k=!0}},[n==null?void 0:n.authenticated,n==null?void 0:n.required]);const g=async k=>{k.preventDefault(),m(!0),p("");try{const f=await Ns("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),x=await f.json();if(!f.ok)throw new Error((x==null?void 0:x.error)||"Login failed");a(x),c(""),sf()}catch(f){p(f instanceof Error?f.message:String(f))}finally{m(!1)}};return r?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:t("standalone.auth.loading")}):n?!n.required||n.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:t("standalone.auth.signInTitle")}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:n.hasPasswordAuth?t("standalone.auth.passwordProtected"):t("standalone.auth.tokenProtected")})]}),n.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:g,children:[s.jsx(ps,{type:"password",value:i,onChange:k=>c(k.target.value),placeholder:t("standalone.auth.passwordPlaceholder"),autoFocus:!0}),s.jsx(Hs,{type:"submit",variant:"primary",disabled:d||!i,className:"justify-center",children:t(d?"standalone.auth.signingIn":"standalone.auth.unlock")})]}):s.jsx(Dt,{variant:"warning",children:t("standalone.auth.noPasswordEnabled")}),u&&s.jsx(Dt,{variant:"error",children:u})]})}):s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:t("standalone.auth.loadError",{error:u||"unknown error"})})}function ku(){const{t:e}=Ce("common"),{ides:t,initialLoaded:n}=Ms();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(yi,{to:`/machines/${a.id}`,replace:!0}):s.jsx(yi,{to:"/dashboard",replace:!0})}function DL(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let n=!1;if(!AL())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(NL,{onDone:()=>t(!1)}):null}function PL(){const{t:e}=Ce("common"),{ides:t}=Ms(),n=l.useMemo(()=>{for(const d of t)if(d.activeInteractivePrompt)return d.instanceId??d.id;return null},[t]),{promptSession:a,hasActivePrompt:r,responseError:o,isSubmitting:i,submit:c,cancel:u,reopen:p}=Im(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(tp,{promptSession:a,isSubmitting:i,error:o,onSubmit:c,onCancel:u})]}):null}function IL(){const e=l.useMemo(()=>({sendCommand:Ca,sendData:Xi,sendPtyInput:nf}),[]);return s.jsx(Lf,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Zf,{client:TL,children:s.jsx(ML,{children:s.jsx(dL,{children:s.jsx(tb,{value:e,children:s.jsxs(rb,{sendDaemonCommand:Ca,children:[s.jsx(PL,{}),s.jsxs(bL,{children:[s.jsx(DL,{}),s.jsxs(Rf,{children:[s.jsx(Us,{path:"/dashboard",element:s.jsx(ND,{})}),s.jsx(Us,{path:"/machine",element:s.jsx(ku,{})}),s.jsx(Us,{path:"/machines/:id",element:s.jsx(EP,{})}),s.jsx(Us,{path:"/machines",element:s.jsx(ku,{})}),s.jsx(Us,{path:"/about",element:s.jsx(yL,{})}),s.jsx(Us,{path:"/settings",element:s.jsx(kL,{})}),s.jsx(Us,{path:"/mesh",element:s.jsx(eL,{children:s.jsx(JI,{})})}),s.jsx(Us,{path:"*",element:s.jsx(yi,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}kS({connectionManager:js});Ef(document.getElementById("root")).render(s.jsx(IL,{}));
|