@adhdev/daemon-standalone 1.0.18 → 1.0.20
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 +6 -4
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/public/assets/{index-CCYDqcVX.js → index-Ck0QqnBH.js} +5 -5
- package/public/index.html +1 -1
- package/vendor/mcp-server/index.js +1 -1
- package/vendor/mcp-server/index.js.map +1 -1
- package/vendor/mcp-server/package.json +1 -1
|
@@ -55,7 +55,7 @@ ${JSON.stringify(t,null,2)}
|
|
|
55
55
|
`),fe=((Me=Y[0])==null?void 0:Me.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:()=>K(U),children:[s.jsx("span",{className:"text-[10px] text-text-muted w-3",children:Z?"▾":"▸"}),s.jsx("span",{className:"font-mono text-accent-primary w-20 shrink-0 text-[11px]",children:U}),!Z&&s.jsx("span",{className:"text-text-secondary truncate font-mono text-[11px]",children:fe}),s.jsxs("span",{className:"ml-auto text-text-muted text-[10px] shrink-0",children:[Y.length,"L"]})]}),Z&&s.jsx("pre",{className:"px-3 pb-2.5 pt-1 font-mono text-[11px] text-text-secondary whitespace-pre-wrap break-all bg-bg-secondary max-h-40 overflow-y-auto border-t border-border-default",children:q||"(empty)"})]},U)})})]}),s.jsx(Hr,{}),B.stateHistory&&B.stateHistory.length>0&&s.jsxs("div",{children:[s.jsxs($r,{children:["State History (",B.stateHistory.length,")"]}),s.jsx("div",{className:"space-y-px",children:[...B.stateHistory].reverse().slice(0,20).map((U,q)=>s.jsxs("div",{className:"rounded px-2 py-1 hover:bg-bg-glass-hover transition-colors",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:`font-mono text-[11px] font-semibold px-1.5 py-0.5 rounded shrink-0 ${fo(U.stateId)}`,children:U.stateId}),s.jsx("span",{className:"text-text-secondary text-[11px] shrink-0 tabular-nums",children:zn(U.at)}),U.durationMs>0&&s.jsxs("span",{className:"text-text-muted text-[11px]",children:["held ",s.jsx("span",{className:"text-text-secondary",children:Pc(U.durationMs)})]}),U.reason&&s.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-mono shrink-0 ${qk[String(U.reason)]??"text-text-secondary bg-bg-glass border border-border-default"}`,children:String(U.reason)}),U.debounceKind&&String(U.debounceKind)!=="none"&&s.jsxs("span",{className:"text-text-muted text-[10px] font-mono",children:["debounce:",String(U.debounceKind)]}),U.matchedStateId&&String(U.matchedStateId)!==U.stateId&&s.jsxs("span",{className:"text-text-muted text-[10px] font-mono",children:["eval→",s.jsx("span",{className:"text-text-secondary",children:String(U.matchedStateId)})]})]}),U.matchedRules&&U.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:[U.matchedRules.slice(0,3).map((Z,Y)=>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 Z=="string"?Z:JSON.stringify(Z)},Y)),U.matchedRules.length>3&&s.jsxs("span",{className:"text-[10px] text-text-muted",children:["+",U.matchedRules.length-3," more"]})]})]},q))})]}),s.jsx(Hr,{}),(()=>{const U=B.messages??B.committedMessages??[];if(U.length===0)return null;const q=U.filter(fe=>fe.role==="user").length,Z=U.filter(fe=>fe.role==="assistant").length,Y=[...U].reverse().find(fe=>fe.role==="assistant");return s.jsxs("div",{children:[s.jsxs($r,{children:["Transcript (",U.length," — ",q,"u / ",Z,"a)"]}),Y&&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 ",Y.receivedAt?zn(Y.receivedAt):""]}),s.jsxs("div",{className:"text-text-secondary font-mono whitespace-pre-wrap line-clamp-4 break-all",children:[Y.content.slice(0,400),Y.content.length>400?"…":""]})]})]})})(),B.specPath&&s.jsx("div",{className:"text-[10px] text-text-muted font-mono truncate border-t border-border-default pt-2 mt-1",title:B.specPath,children:B.specPath}),s.jsxs("div",{children:[s.jsxs("button",{type:"button",className:"text-[11px] text-text-secondary hover:text-text-primary transition-colors flex items-center gap-1.5",onClick:()=>u(U=>!U),children:[s.jsx("span",{className:"text-text-muted",children:p?"▾":"▸"}),s.jsxs("span",{children:["Raw screen (",B.screen?B.screen.split(`
|
|
56
56
|
`).length:0," lines)"]})]}),p&&s.jsx("pre",{className:"mt-1.5 px-3 py-2 font-mono text-[11px] text-text-secondary whitespace-pre bg-bg-secondary rounded-md border border-border-default max-h-64 overflow-auto",children:B.screen||"(empty)"})]})]})]})]})})}function Yk({activeConv:e,clearToken:t=0,terminalRef:n,handleSendChat:r,isSendingChat:a=!1,sendFeedbackMessage:o=null,isVisible:i=!0,isInputActive:c=!0}){var Je;const{t:d}=Se("common");Ss();const{sendPtyInput:p}=vt(),[u,m]=l.useState(!1),f=l.useRef(!1);f.current=u;const[g,k]=l.useState("Runtime terminal unavailable"),[h,v]=l.useState(!1),[w,b]=l.useState(null),[j,C]=l.useState(!1),[y,x]=l.useState(!1),[N,S]=l.useState(1),[A,M]=l.useState(!1),[P,D]=l.useState(!1),[I,_]=l.useState(!1),[W,H]=l.useState(!1),[L,O]=l.useState(!1),[E,T]=l.useState({width:0,height:0}),[$,R]=l.useState({width:0,height:0}),[G,Q]=l.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[re,J]=l.useState(null),X=l.useRef(null),ue=l.useRef(null),se=l.useRef(!1),B=l.useRef(!1),ie=l.useRef(i),K=l.useRef(0),le=l.useRef(!1),je=l.useRef(""),we=l.useRef(null),ke=l.useRef(!1),he=l.useRef(!1),U=l.useRef(null),q=l.useRef(null),Z=l.useRef(null),Y=32*1024,fe=()=>{var te,xe,ye,$e;return((xe=(te=X.current)==null?void 0:te.ownerDocument)==null?void 0:xe.defaultView)||(($e=(ye=ue.current)==null?void 0:ye.ownerDocument)==null?void 0:$e.defaultView)||window},Me=te=>{const xe=fe();return{ownerWindow:xe,frameId:xe.requestAnimationFrame(te)}},de=()=>{const te=U.current;if(te){try{te.ownerWindow.cancelAnimationFrame(te.frameId)}catch{}U.current=null}},F=()=>{const te=q.current;if(te){try{te.ownerWindow.clearTimeout(te.timeoutId)}catch{}q.current=null}},me=()=>{const te=Z.current;if(te){try{te.ownerWindow.clearTimeout(te.timeoutId)}catch{}Z.current=null}},ce=()=>{i&&U.current===null&&(U.current=Me(()=>{V()}))},z=e.tabKey,ge=e.sessionId||"",Ce=e.daemonId||((Je=e.routeId)==null?void 0:Je.split(":")[0])||e.routeId||"",Ne=el(e),He=u?o||Ne:g,Ze=Tk,Ye=Ik,ot=.05,be=()=>{const te=$.width,xe=$.height;if(!Number.isFinite(E.width)||E.width<=0||!Number.isFinite(E.height)||E.height<=0||!Number.isFinite(te)||te<=0||!Number.isFinite(xe)||xe<=0)return 1;const ye=E.width/te,$e=E.height/xe;return Number(Math.min(Ye,Math.max(Ze,Math.min(ye,$e))).toFixed(2))},Pe=be(),Be=se.current&&N>Pe,it=Number.isFinite($.width)&&$.width>0?Math.max(E.width,Math.round($.width*N)):E.width,ae=Number.isFinite($.height)&&$.height>0?Math.max(E.height,Math.round($.height*N)):E.height,_e=()=>{Me(()=>{const te=ue.current;te&&(te.scrollLeft=0,te.scrollTop=te.scrollHeight-te.clientHeight)})},lt=()=>{var te,xe;K.current=0,le.current=!1,je.current="",we.current=null,ke.current=!1,he.current=!1,se.current||(B.current=!1,S(1)),U.current!==null&&de(),m(!1),k("Runtime terminal unavailable"),me(),F(),b(null),J(null),M(!1),v(!1),C(!1),x(!1),(xe=(te=n.current)==null?void 0:te.reset)==null||xe.call(te)},ct=()=>{var te,xe;K.current=0,le.current=!1,je.current="",we.current=null,ke.current=!1,he.current=!1,U.current!==null&&de(),m(!0),k(""),me(),F(),b(null),J(null),M(!1),v(!1),C(!1),x(!1),(xe=(te=n.current)==null?void 0:te.reset)==null||xe.call(te)},Nt=()=>{he.current&&(he.current=!1,Me(()=>{var te,xe;(xe=(te=n.current)==null?void 0:te.scrollToTop)==null||xe.call(te)}))},V=()=>{if(U.current=null,!i)return;const te=je.current;if(!te)return;const xe=te.slice(0,Y);je.current=te.slice(xe.length);const ye=n.current;if(!ye){je.current=xe+je.current,ce();return}ye.write(xe,()=>{if(je.current.length>0){ce();return}Nt()})},ee=te=>{te&&(je.current+=te,ce())},oe=(te,xe=0,ye,$e,Re={})=>{var tt,Ke,kt,zt;const et=!!Re.force;!et&&xe>0&&K.current>=xe||!et&&xe===0&&le.current||(K.current=xe,xe>0&&C(!0),m(!0),k(""),typeof ye=="number"&&typeof $e=="number"&&ye>0&&$e>0&&((Ke=(tt=n.current)==null?void 0:tt.resize)==null||Ke.call(tt,ye,$e)),je.current="",(zt=(kt=n.current)==null?void 0:kt.reset)==null||zt.call(kt),te?ee(te):Nt())};l.useEffect(()=>{lt()},[ge]),l.useEffect(()=>{var xe;if(!ge)return;const te=((xe=wt.onRuntimeEvent)==null?void 0:xe.call(wt,ge,ye=>{if(!(!ye||ye.sessionId!==ge)){if(ye.type==="runtime_snapshot"){if(!i){we.current={text:ye.text||"",seq:ye.seq||0,cols:ye.cols,rows:ye.rows,force:!!ye.force};return}oe(ye.text||"",ye.seq||0,ye.cols,ye.rows,{force:!!ye.force});return}if(ye.type==="session_output"){le.current=!0,typeof ye.seq=="number"&&(K.current=Math.max(K.current,ye.seq),ye.seq>0&&C(!0)),f.current||m(!0),f.current||k(""),typeof ye.data=="string"&&ee(ye.data);return}if(ye.type==="session_cleared"){if(!i){ke.current=!0,je.current="",we.current=null;return}ct();return}if(ye.type==="session_io_error"){const $e=typeof ye.error=="string"&&ye.error?ye.error:typeof ye.reason=="string"&&ye.reason?ye.reason:"unknown error";m(!1),k(`Runtime input failed: ${$e}`);return}}},Ce))||(()=>{});return()=>{te()}},[Ce,ge,n,i]);const pe=async(te={})=>{var xe;if(!Ce||!ge)return{success:!1,error:"daemonId and sessionId are required"};te.preserveStatus||k(te.loadingMessage||"Loading runtime terminal...");try{const ye=await((xe=wt.requestRuntimeSnapshot)==null?void 0:xe.call(wt,Ce,ge,{sinceSeq:te.sinceSeq,force:te.force}));return ye&&ye.success===!1?(te.preserveStatus||(m(!1),k(`Runtime terminal unavailable: ${ye.error}`)),ye):ye||{success:!0}}catch(ye){const $e=(ye==null?void 0:ye.message)||String(ye);return te.preserveStatus||(m(!1),k(`Runtime terminal unavailable: ${$e}`)),{success:!1,error:$e}}},ve=async te=>{var et,tt;const xe=((et=X.current)==null?void 0:et.ownerDocument)||document,ye=xe.defaultView||window,$e=(tt=ye.navigator)==null?void 0:tt.clipboard;if($e!=null&&$e.writeText&&ye.isSecureContext)try{return await $e.writeText(te),!0}catch{}let Re=null;try{return Re=xe.createElement("textarea"),Re.value=te,Re.setAttribute("readonly","true"),Re.style.position="fixed",Re.style.left="-9999px",Re.style.top="0",xe.body.appendChild(Re),Re.focus(),Re.select(),xe.execCommand("copy")}catch{return!1}finally{Re==null||Re.remove()}},Te=te=>{F(),J(te);const xe=fe();q.current={ownerWindow:xe,timeoutId:xe.setTimeout(()=>{q.current=null,J(ye=>ye===te?null:ye)},2200)}},Ee=te=>{me(),b(te);const xe=fe();Z.current={ownerWindow:xe,timeoutId:xe.setTimeout(()=>{Z.current=null,b(ye=>ye===te?null:ye)},2200)}},De=async()=>{var Re,et,tt,Ke;const te=((et=(Re=n.current)==null?void 0:Re.getSelection)==null?void 0:et.call(Re))||"",xe=((Ke=(tt=n.current)==null?void 0:tt.getVisibleText)==null?void 0:Ke.call(tt))||"",ye=te.trimEnd()||xe.trimEnd();if(!ye){Te("Nothing to copy");return}if(!await ve(ye)){Te("Copy failed");return}Te(te.trimEnd()?"Copied selection":"Copied visible terminal")},Ue=te=>{if(!u||!i)return;((p==null?void 0:p(Ce,ge,te))??!1)||Te("Terminal input failed")},Ge=te=>{Ue(Pk({ctrl:P,alt:I,shift:W},te)),D(!1),_(!1),H(!1)},Xe=async()=>{if(h)return;v(!0),b("Loading older terminal output..."),he.current=!0;const te=await pe({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:u});if(v(!1),(te==null?void 0:te.success)===!1){he.current=!1,b(`Older terminal output unavailable: ${te.error}`);return}x(!0),Ee("Older terminal output loaded"),Me(()=>{var xe;(xe=n.current)==null||xe.bumpResize()})};l.useEffect(()=>{var xe,ye;if(!ge)return;Ce&&((xe=wt.getState)==null?void 0:xe.call(wt,Ce))==="connected"&&pe();const te=(ye=wt.onStateChange)==null?void 0:ye.call(wt,($e,Re)=>{$e!==Ce||Re!=="connected"||pe()});return()=>{te==null||te()}},[Ce,ge,n]),l.useEffect(()=>{t&<()},[t,z,n]),l.useEffect(()=>{var $e,Re;const te=X.current,xe=(Re=($e=te==null?void 0:te.ownerDocument)==null?void 0:$e.defaultView)==null?void 0:Re.ResizeObserver;if(!te||!xe)return;const ye=new xe(et=>{const tt=et[0];if(!tt)return;const{width:Ke,height:kt}=tt.contentRect;T(zt=>{const ns=Math.round(Ke),Ae=Math.round(kt);return zt.width===ns&&zt.height===Ae?zt:{width:ns,height:Ae}})});return ye.observe(te),()=>ye.disconnect()},[]),l.useEffect(()=>{if(se.current)return;const te=be();!Number.isFinite(te)||te<=0||S(xe=>B.current?te<xe-ot?te:xe:(B.current=!0,te))},[$.height,$.width,E.height,E.width]),l.useEffect(()=>{Be&&_e()},[Be,ae,it]),l.useEffect(()=>{var ye;const te=ie.current;if(ie.current=i,!i)return;te||x(!1),ke.current&&(ke.current=!1,ct());const xe=we.current;xe&&(we.current=null,oe(xe.text,xe.seq,xe.cols,xe.rows,{force:!!xe.force})),Ce&&ge&&((ye=wt.getState)==null?void 0:ye.call(wt,Ce))==="connected"&&pe(),je.current&&U.current===null&&ce(),Me(()=>{var $e;($e=n.current)==null||$e.bumpResize()})},[Ce,i,ge]),l.useEffect(()=>()=>{U.current!==null&&de(),F(),me()},[]),l.useEffect(()=>{const te=$e=>{var et;const Re=$e.detail;Re!=null&&Re.sessionId&&Re.sessionId!==ge||u&&((et=n.current)==null||et.bumpResize())},xe=fe(),ye=xe===window?[window]:[window,xe];for(const $e of ye)$e.addEventListener("adhdev:fit-cli-terminal",te);return()=>{for(const $e of ye)$e.removeEventListener("adhdev:fit-cli-terminal",te)}},[u,ge,n]);const Oe=u&&j&&!y&&(G.atTop||!G.canScroll)||h||!!w;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:X,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[Oe&&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:()=>{Xe()},disabled:!ge||h,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:d(h?"terminal.loadingOlder":"terminal.loadOlderOutput")}),w&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:w})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[re&&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:re}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>O(te=>!te),title:"Spec debug — inspect current state, sections, and transition history",children:d("terminal.debug")}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{De()},disabled:!u,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:d("terminal.copy")}),s.jsxs("div",{className:"relative",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>M(te=>!te),disabled:!u,"aria-label":d(A?"terminal.closeControlKeys":"terminal.openControlKeys"),"aria-expanded":A,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),A&&s.jsxs("div",{id:"terminal-control-keys-popover",role:"dialog","aria-label":d("terminal.openControlKeys"),className:"absolute right-0 top-10 w-72 rounded-2xl border border-white/10 bg-[#0b0d12]/95 p-3 text-white/85 shadow-2xl shadow-black/40 backdrop-blur-md",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Terminal keys"}),s.jsx("button",{type:"button",className:"rounded-full px-2 py-0.5 text-[11px] text-white/55 transition-colors hover:bg-white/10 hover:text-white/85",onClick:()=>M(!1),"aria-label":d("terminal.closeControlKeys"),children:"×"})]}),s.jsx("div",{className:"mb-2 grid grid-cols-3 gap-1.5",children:[["Ctrl",P,D],["Alt",I,_],["Shift",W,H]].map(([te,xe,ye])=>s.jsx("button",{type:"button","aria-pressed":xe,className:`h-9 rounded-lg border text-[12px] font-semibold transition-colors ${xe?"border-sky-400/50 bg-sky-400/25 text-white":"border-white/10 bg-white/[0.06] hover:bg-white/[0.12]"}`,onClick:()=>ye($e=>!$e),children:te},te))}),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:()=>Ge("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:()=>Ge("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:()=>Ge("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:()=>Ge("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:()=>Ge("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:()=>Ge("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:()=>Ge("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:()=>Ue(""),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:()=>Ge("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:()=>Ge("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:()=>{se.current=!0,S(te=>{const xe=Math.max(Pe,Number((te-.1).toFixed(2)));return xe>Pe&&_e(),xe})},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:()=>{se.current=!0,S(te=>{const xe=Math.min(Ye,Number((te+.1).toFixed(2)));return xe>Pe&&_e(),xe})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:ue,className:Be?"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:it>0?`${it}px`:"100%",height:ae>0?`${ae}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:$.width>0?`${$.width}px`:"100%",height:$.height>0?`${$.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:N},children:s.jsx(Cu,{ref:n,readOnly:!u||!i,sizingMode:"measured",onViewportMetrics:R,onScrollMetrics:Q,onInput:te=>{!u||(p==null||p(Ce,ge,te))}})})})}),!u&&s.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:g})]}),s.jsx(Gu,{contextKey:e.tabKey,panelLabel:xt(e),isSending:a,isBusy:!!Ne,statusMessage:He,inlineStatusMessage:He,onSend:async te=>Ne?!1:r(te),isActive:c&&i,showControlsToggle:!1,animateVisibility:!1}),L&&s.jsx(Vk,{activeConv:e,onClose:()=>O(!1)})]})}const Jk=5e3,Qk=12e3;function Xk(e){return e==="disconnected"||e==="reconnecting"}function Zk({wsStatus:e,showReconnected:t,loginUrl:n,onReconnect:r,reconnectDelayMs:a=Jk,reconnectActionDelayMs:o=Qk}){const{t:i}=Se(),c=Xk(e),[d,p]=l.useState(()=>!c||a<=0),[u,m]=l.useState(()=>!c||o<=0),f=l.useRef(!1);l.useEffect(()=>{if(!c){p(!1);return}if(f.current=!1,a<=0){f.current=!0,p(!0);return}p(!1);const x=setTimeout(()=>{f.current=!0,p(!0)},a);return()=>clearTimeout(x)},[a,c]),l.useEffect(()=>{if(!c){m(!1);return}if(o<=0){m(!0);return}m(!1);const x=setTimeout(()=>{m(!0)},o);return()=>clearTimeout(x)},[o,c]);const g=c?d:e==="offline"||e==="auth_failed",k=!!(r&&e!=="auth_failed"&&(!c||u)),h=l.useMemo(()=>!t||e!=="connected"?!1:a<=0||f.current,[a,t,e]),v=e==="auth_failed"?"red":e==="offline"?"orange":"accent",w={red:"linear-gradient(90deg, rgba(239,68,68,0.12), rgba(239,68,68,0.04))",orange:"linear-gradient(90deg, rgba(255,107,53,0.12), rgba(255,107,53,0.04))",accent:"linear-gradient(90deg, color-mix(in srgb, var(--accent-primary) 18%, transparent), color-mix(in srgb, var(--accent-primary) 6%, transparent))"},b={red:"1px solid rgba(239,68,68,0.2)",orange:"1px solid rgba(255,107,53,0.2)",accent:"1px solid color-mix(in srgb, var(--accent-primary) 28%, transparent)"},j={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},C="fixed left-1/2 top-4 z-[var(--z-toast)] flex items-center justify-center pointer-events-none",y={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[g&&s.jsx("div",{className:C,style:y,children:s.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-3 py-2.5 sm:px-4 sm:py-3 text-[13px] font-semibold flex flex-wrap items-center gap-x-2.5 gap-y-2 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:w[v],border:b[v],color:j[v]},children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5 shrink-0",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),s.jsxs("span",{className:"min-w-0 text-center whitespace-nowrap",children:[e==="offline"&&i("connection.networkOffline"),e==="disconnected"&&i("connection.reconnecting"),e==="reconnecting"&&i("connection.reconnecting"),e==="auth_failed"&&(n?s.jsxs(s.Fragment,{children:[i("connection.sessionExpired")," ",s.jsx("a",{href:n,className:"text-inherit underline",children:i("connection.logInAgain")})]}):i("connection.connectionFailed"))]}),k&&s.jsx("button",{type:"button",className:"basis-full sm:basis-auto mx-auto sm:mx-0 sm:ml-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-[12px] font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>r==null?void 0:r(),disabled:e==="offline",children:i("connection.reconnectNow")})]})}),h&&s.jsx("div",{className:C,style:y,children:s.jsxs("div",{className:"pointer-events-none rounded-2xl border px-4 py-2 text-xs font-semibold flex items-center gap-2 justify-center bg-gradient-to-r from-green-500/[0.12] to-green-500/[0.04] text-green-400 border-green-500/15 shadow-[0_18px_40px_rgba(2,6,23,0.2)] backdrop-blur-xl animate-[fadeIn_0.3s_ease]",children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),i("connection.connected")]})})]})}function Tp({mode:e,onChange:t,compact:n=!1}){const{t:r}=Se("common"),a=n?14:15;return s.jsx("button",{type:"button",onClick:()=>t(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:r(e==="chat"?"cliView.switchToTerminal":"cliView.switchToChat"),children:e==="chat"?s.jsx(Oi,{size:a}):s.jsx(ln,{size:a})})}function eS(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 tS(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 sS(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 ya({git:e,className:t="",compact:n=!1}){const r=eS(e),a=tS(e);if(!r||!a)return null;const o=[e!=null&&e.branch?`Branch: ${e.branch}`:null,e!=null&&e.changedFiles?`Changed files: ${e.changedFiles}`:null,e!=null&&e.ahead?`Ahead: ${e.ahead}`:null,e!=null&&e.behind?`Behind: ${e.behind}`:null,e!=null&&e.hasConflicts?"Conflicts detected":null,e!=null&&e.error?`Git error: ${e.error}`:null].filter(Boolean);return s.jsxs("span",{className:`inline-flex min-w-0 max-w-[12rem] items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-semibold leading-none ${sS(a)} ${t}`.trim(),title:o.join(" · ")||r,"data-git-tone":a,children:[s.jsx("span",{"aria-hidden":"true",children:"⑂"}),s.jsx("span",{className:"truncate",children:r})]})}function nS({wsStatus:e,isConnected:t,daemonCount:n,p2pStates:r={}}){if(e!=="connected")return{tone:"disconnected",titleKey:"connection.disconnected",subtitleKey:null};const a=Object.values(r),o=a.filter(c=>c==="connected").length,i=a.filter(c=>c==="connecting"||c==="new"||c==="checking").length;return n>0&&i>0&&o===0?{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:"connection.connectingToMachine"}:t?{tone:"connected",titleKey:"connection.connected",subtitleKey:null}:{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:null}}function Lc({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Rc({notification:e,shortcutIndex:t,onOpen:n,onMarkRead:r,onMarkUnread:a,onDelete:o}){const{t:i}=Se(),c=Ea(e.updatedAt),d=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${d?"is-attention":""}`.trim(),children:[s.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:n,children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[t?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",t]}):null,[e.type==="needs_attention"?i("notification.actionNeeded"):i("notification.taskComplete"),c].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[d?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:p=>{p.stopPropagation(),r()},children:i("notification.markRead")}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:p=>{p.stopPropagation(),a()},children:i("notification.markUnread")}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:p=>{p.stopPropagation(),o()},children:i("notification.delete")})]})]})}function rS({activeConv:e,wsStatus:t,isConnected:n,conversations:r,onOpenHistory:a,onOpenRemote:o,onStopCli:i,activeCliViewMode:c,onSetCliViewMode:d,onHideConversation:p,hiddenConversations:u=[],onShowConversation:m,onShowAllHidden:f,onResetPanelsToMain:g,inboxOpen:k,onInboxOpenChange:h,hiddenOpen:v,onHiddenOpenChange:w,onOpenNewSession:b,onOpenDashboardGuide:j,guideNudgeVisible:C=!1,actionShortcuts:y,notifications:x,notificationUnreadCount:N,onOpenNotification:S,onMarkNotificationRead:A,onMarkNotificationUnread:M,onDeleteNotification:P,onOpenGitDialog:D,onOpenMeshGraph:I}){var Z;const{t:_}=Se(),{ides:W,p2pStates:H={}}=Ss(),L=!!e&&ut(e)&&!dt(e),O=!!e&&dt(e),E=!!(e!=null&&e.daemonId)&&!!((Z=e==null?void 0:e.coordinator)!=null&&Z.meshId),T=c||(e?Xu(e)?"terminal":"chat":null),[$,R]=l.useState(!1),[G,Q]=l.useState(!1),re=l.useRef(null),J=l.useRef(null),X=l.useRef(null),ue=W.filter(Y=>Y.type==="adhdev-daemon"),se=nS({wsStatus:t,isConnected:n,daemonCount:ue.length,p2pStates:H}),B=_(se.titleKey),ie=se.subtitleKey?_(se.subtitleKey):null,K=se.tone==="connected"?"#22c55e":se.tone==="limited"?"#eab308":"#ef4444",le=se.tone==="connected"?"0 0 4px #22c55e80":se.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",je=l.useMemo(()=>x.filter(Y=>!Y.readAt),[x]),we=l.useMemo(()=>x.filter(Y=>!!Y.readAt),[x]),ke=l.useMemo(()=>je.slice(0,9),[je]),he=N;l.useEffect(()=>{if(!k)return;const Y=fe=>{var Me;(Me=J.current)!=null&&Me.contains(fe.target)||h(!1)};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[k,h]),l.useEffect(()=>{if(!v)return;const Y=fe=>{var Me;(Me=X.current)!=null&&Me.contains(fe.target)||w(!1)};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[v,w]),l.useEffect(()=>{if(!v&&!k)return;const Y=fe=>{if(!fe.altKey)return;const Me=fe.code.match(/^Digit([1-9])$/);if(!Me)return;const de=Number(Me[1])-1,F=v?u[de]:void 0,me=k?ke[de]:void 0;if(!(!F&&!me)){if(fe.preventDefault(),fe.stopPropagation(),F){m==null||m(F),w(!1);return}me&&(S(me),h(!1))}};return window.addEventListener("keydown",Y,!0),()=>window.removeEventListener("keydown",Y,!0)},[u,v,k,ke,w,h,S,m]),l.useEffect(()=>{const Y=u.length;if(re.current===null){re.current=Y;return}Y>re.current&&Q(!0),re.current=Y},[u.length]);const U=()=>Q(!1),q=Y=>{if(!Y)return;const fe=r.find(Me=>Me.tabKey===Y);fe&&(p==null||p(fe))};return s.jsxs("div",{className:"dashboard-header",children:[s.jsx("div",{className:"flex items-center gap-3",children:s.jsx("div",{className:"header-title-block",children:s.jsxs("div",{className:"header-title-row",children:[s.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[s.jsx(ln,{size:18}),s.jsx("span",{className:"header-title-desktop",children:_("dashboard.header.title")}),s.jsx("span",{className:"header-title-mobile",children:e?xt(e):_("dashboard.header.title")}),s.jsx("span",{title:B,"aria-label":B,className:"header-title-status-dot",style:{background:K,boxShadow:le}}),s.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:s.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:K,boxShadow:le}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[ie&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",ie]}),b&&s.jsx("button",{type:"button",onClick:b,className:"btn btn-secondary btn-sm ml-2",title:`${_("paneGroup.newSession")}${y!=null&&y.openNewSession?` (${y.openNewSession})`:""}`,"aria-label":_("paneGroup.newSession"),children:s.jsx(Wi,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[j&&s.jsxs("button",{type:"button",onClick:j,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:_("dashboard.header.guide"),"aria-label":_("dashboard.header.guideOpen"),children:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),C&&s.jsx("span",{children:_("dashboard.header.guideShort")})]}),e&&(L||O||!dt(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:Mn(e)||xt(e),children:xt(e)}),D&&e.git&&e.daemonId&&e.workspacePath?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:_("dashboard.header.openGitStatus"),onClick:()=>D(e.daemonId,e.workspacePath),children:s.jsx(ya,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(ya,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),E&&I&&s.jsxs("button",{type:"button",onClick:()=>I(e),className:"btn btn-secondary btn-sm dashboard-header-mesh-button",title:_("dashboard.header.openMeshGraph"),children:[s.jsx(ts,{size:14}),s.jsx("span",{className:"hidden lg:inline",children:_("dashboard.header.meshGraph")})]}),(L||O)&&i&&s.jsxs(s.Fragment,{children:[L&&d&&T&&s.jsx(Tp,{mode:T,onChange:d,compact:!0}),s.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:_(O?"dashboard.header.stopAcpSession":"dashboard.header.stopCliProcess"),style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(Mt,{size:14})})]}),!dt(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:_("dashboard.header.chatHistory"),children:s.jsx(Fi,{size:14})}),!L&&!dt(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:_("dashboard.header.remoteControl"),children:s.jsx(hs,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:J,children:[s.jsxs("div",{className:`dashboard-header-hidden${$?" is-drop-target":""}${G?" hidden-spawn-flash":""}${(u??[]).some(hr)?" hidden-generating-spin":""}`,onAnimationEnd:U,ref:X,onDragEnter:Y=>{Y.dataTransfer.types.includes("text/tab-key")&&(Y.preventDefault(),R(!0))},onDragOver:Y=>{Y.dataTransfer.types.includes("text/tab-key")&&(Y.preventDefault(),Y.dataTransfer.dropEffect="move",R(!0))},onDragLeave:Y=>{Y.currentTarget.contains(Y.relatedTarget)||R(!1)},onDrop:Y=>{const fe=Y.dataTransfer.getData("text/tab-key");Y.preventDefault(),R(!1),q(fe)},children:[s.jsxs("button",{type:"button",onClick:()=>w(!v),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`${_("dashboard.hidden.title")}${y!=null&&y.toggleHiddenTabs?` (${y.toggleHiddenTabs})`:""}. ${_("dashboard.hidden.dragHint")}`,children:[s.jsx(Bi,{size:16}),u.length>0&&s.jsx("span",{className:`dashboard-header-hidden-badge${G?" hidden-badge-pop":""}`,children:u.length})]}),v&&s.jsxs("div",{className:"dashboard-header-hidden-popover",children:[s.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:_("dashboard.hidden.title")}),s.jsx(Lc,{value:y==null?void 0:y.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[g&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:g,children:_("dashboard.hidden.resetPanels")}),u.length>0&&f&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{f(),w(!1)},children:_("dashboard.hidden.restoreAll")})]})]}),e&&p&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>p(e),children:[s.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[s.jsx("span",{className:"dashboard-header-hidden-current-label",children:_("dashboard.hidden.hideCurrentTab")}),s.jsx(Lc,{value:y==null?void 0:y.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:xt(e)})]}),u.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(Y=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{m==null||m(Y),w(!1)},children:[s.jsxs("span",{className:"dashboard-header-inbox-item-title",children:[hr(Y)&&s.jsx("span",{className:"tab-spinner dashboard-header-inbox-item-spinner","aria-label":_("dashboard.header.generating")}),xt(Y)]}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(Y)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(Y)+1]}):null,Mn(Y)]})]},Y.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:_("dashboard.hidden.empty")})]})]}),s.jsxs("button",{type:"button",onClick:()=>h(!k),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:_("dashboard.header.activityInbox"),children:[s.jsx(Rn,{size:16}),he>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:he})]}),k&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[je.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:_("dashboard.inbox.unread")}),je.map(Y=>s.jsx(Rc,{notification:Y,shortcutIndex:ke.indexOf(Y)>=0?ke.indexOf(Y)+1:void 0,onOpen:()=>S(Y),onMarkRead:()=>A(Y.id),onMarkUnread:()=>M(Y.id),onDelete:()=>P(Y.id)},Y.id))]}),we.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:_("dashboard.inbox.read")}),we.map(Y=>s.jsx(Rc,{notification:Y,onOpen:()=>S(Y),onMarkRead:()=>A(Y.id),onMarkUnread:()=>M(Y.id),onDelete:()=>P(Y.id)},Y.id))]}),x.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:_("dashboard.inbox.empty")})]})]})]})]})}function Wt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function aS(e,t){return String(e||"")!==String(t||"")}function oS(e,t={}){const n=String(t.textQuery||"").trim().toLowerCase(),r=String(t.workspaceQuery||"").trim().toLowerCase(),a=String(t.modelQuery||"").trim().toLowerCase(),o=!!t.resumableOnly;return!n&&!r&&!a&&!o?e:e.filter(i=>!(o&&!i.canResume||n&&![i.title,i.preview].map(d=>String(d||"").toLowerCase()).join(`
|
|
57
57
|
`).includes(n)||r&&!String(i.workspace||"").toLowerCase().includes(r)||a&&!Hu(i.summaryMetadata).map(d=>d.toLowerCase()).join(`
|
|
58
|
-
`).includes(a)))}function iS(e,t="recent"){const n=e.slice();return n.sort((r,a)=>{if(t==="oldest")return(Number(r.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(t==="messages"){const o=(Number(a.messageCount)||0)-(Number(r.messageCount)||0);if(o!==0)return o}return(Number(a.lastMessageAt)||0)-(Number(r.lastMessageAt)||0)}),n}function Ip(e,t={}){return iS(oS(e,t),t.sortMode||"recent")}function gi(e,t){return typeof e=="function"?e(t??!1?"launch.resumeSavedHistory":"launch.startFresh"):e?"Resume saved history":"Start fresh"}function Dp(e,t){return typeof e=="function"?e(t??!1?"launch.resumingSavedHistory":"launch.startingFresh"):e?"Resuming saved history…":"Starting fresh…"}function lS(e){return e?e("launch.startFresh"):"Start fresh"}function cS(e){return e?e("launch.hostedRuntimeRecoveryDescription"):"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function dS(e){return e?e("launch.openSavedHistory"):"Open saved history"}function uS(e){return e?e("launch.savedHistoryTitle"):"Saved History"}function rl(e){return e?e("launch.savedHistoryHelper"):"Use saved history when you want continuity in the same provider conversation."}function pS(e){return e?e("launch.savedHistoryEmpty"):"No saved history found yet."}function mS(e){return e?e("launch.refreshSavedHistory"):"Refresh saved history"}function hS(e){return e?e("launch.refreshingSavedHistory"):"Refreshing saved history…"}function wa(e,t,n){if(typeof e=="function"){const o=t,i=n;return o==="start-fresh"?e("launch.startFreshWith",{label:i}):e("launch.restart",{label:i})}const r=e,a=t;return r==="start-fresh"?`Start fresh with ${a}?`:`Restart ${a}?`}function ka(e,t){if(typeof e=="function"){const r=t;return e(r==="start-fresh"?"launch.startFreshReview":r==="restart-ide"?"launch.restartIdeReview":"launch.restartStoppedReview")}const n=e;return n==="start-fresh"?"Review the provider and target folder before starting fresh.":n==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function Sa(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartFresh":"launch.confirmRestart"):e==="start-fresh"?"Start fresh":"Restart"}function Ca(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartingFresh":"launch.confirmRestarting"):e==="start-fresh"?"Starting fresh…":"Restarting…"}function Pp(e,t){return typeof e=="function"?e("launch.resumeWith",{label:t}):`Resume saved history with ${e}?`}function Lp(e){return e?e("launch.resumeReview"):"Review or change the target workspace before resuming saved history."}function fS(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 Rp({activeConv:e,ides:t,isCreatingChat:n,isRefreshingHistory:r,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:c,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:p,onClose:u,onNewChat:m,onSwitchSession:f,onRefreshHistory:g,onResumeSavedSession:k}){var D;const{t:h}=Se("common"),v=t.find(I=>I.id===e.routeId),w=(v==null?void 0:v.chats)||[],b=(D=v==null?void 0:v.activeChat)==null?void 0:D.id,j=ut(e)&&!dt(e),[C,y]=l.useState(()=>Wt()),x=c||C,N=String(d||"").trim(),S=I=>{if(p){p(I);return}y(I)},A=l.useMemo(()=>a.map(I=>{const _=String(I.workspace||"").trim();return I.canResume||_||!N?I:{...I,workspace:N,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[N,a]),M=l.useMemo(()=>Ip(A,{textQuery:x.textQuery,workspaceQuery:x.workspaceQuery,modelQuery:x.modelQuery,resumableOnly:x.resumableOnly,sortMode:x.sortMode}),[A,x.modelQuery,x.resumableOnly,x.sortMode,x.textQuery,x.workspaceQuery]),P=s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:u,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:j?uS(h):h("historyModal.chatHistory")}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:$k(e)}),j&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:rl(h)})]}),s.jsx("button",{onClick:u,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(Mt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!j&&s.jsx("button",{onClick:m,disabled:n,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:h(n?"historyModal.creating":"historyModal.startNewChat")}),j?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[s.jsx("input",{type:"text",value:x.textQuery,onChange:I=>S({...x,textQuery:I.target.value}),placeholder:h("historyModal.searchPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:x.workspaceQuery,onChange:I=>S({...x,workspaceQuery:I.target.value}),placeholder:h("historyModal.filterWorkspace"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:x.modelQuery,onChange:I=>S({...x,modelQuery:I.target.value}),placeholder:h("historyModal.filterModel"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsxs("select",{value:x.sortMode,onChange:I=>S({...x,sortMode:I.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:h("historyModal.sortRecent")}),s.jsx("option",{value:"oldest",children:h("historyModal.sortOldest")}),s.jsx("option",{value:"messages",children:h("historyModal.sortMessages")})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:x.resumableOnly,onChange:I=>S({...x,resumableOnly:I.target.checked})}),h("historyModal.resumeReadyOnly")]})]}),M.map(I=>{const _=e.providerSessionId===I.providerSessionId,W=_||!I.canResume||!!i,H=I.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{W||!k||k(I)},disabled:W,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${_?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${W?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${_?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:I.title||h("historyModal.untitledSession")}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:I.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:fS(I.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:I.preview||h("historyModal.noSavedPreview")}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[I.workspace||h("historyModal.workspaceUnknown"),H?h("historyModal.selectedWorkspaceSuffix"):"",rn(I.summaryMetadata)?` · ${rn(I.summaryMetadata)}`:"",I.messageCount>0?` · ${h("historyModal.msgCount",{count:I.messageCount})}`:""]}),s.jsx("div",{className:"shrink-0",children:_?h("historyModal.statusActive"):I.canResume?H?h("historyModal.statusResumeSelectedWorkspace"):i===I.providerSessionId?h("historyModal.statusResuming"):h("historyModal.statusResume"):h("historyModal.statusMissingWorkspace")})]})]},I.id)})]}):w.map(I=>s.jsxs("div",{onClick:()=>{f(e.routeId,I.id),u()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${b===I.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===I.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:I.title||h("historyModal.untitledSession")}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[I.id.substring(0,12),"..."]}),b===I.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:h("historyModal.statusActive")})]})]},I.id)),(j&&!o&&M.length===0||!j&&w.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(Qf,{size:32})}),s.jsx("div",{className:"text-[13px]",children:j?a.length>0?h("historyModal.noMatchingHistory"):pS(h):h("historyModal.noRecentChats")})]}),j&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:hS(h)})})]}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:s.jsx("button",{onClick:g,disabled:r||o,className:"btn btn-secondary btn-sm rounded-[10px]",children:r||o?h("historyModal.refreshing"):s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ra,{size:13})," ",j?mS(h):h("historyModal.refreshHistory")]})})})]})]});return typeof document>"u"?P:sn.createPortal(P,document.body)}const Ec={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 Ep({toasts:e,onDismiss:t,onClickToast:n}){const{t:r}=Se();return s.jsx("div",{className:"fixed right-4 z-[var(--z-toast)] flex flex-col gap-2 pointer-events-none",style:{top:"calc(env(safe-area-inset-top, 0px) + 16px)"},children:e.map(a=>{const o=Ec[a.type]||Ec.info;return s.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var i;(i=a.actions)!=null&&i.length||n&&n(a)},children:[s.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${o.accent}, color-mix(in srgb, ${o.accent} 55%, transparent))`}}),s.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:i=>{i.stopPropagation(),t(a.id)},"aria-label":r("toast.dismiss"),children:s.jsx(Mt,{size:14})}),s.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[s.jsx("div",{className:"flex items-center gap-2 pr-8",children:s.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:o.chipBg,color:o.chipText,border:`1px solid color-mix(in srgb, ${o.accent} 22%, transparent)`},children:r(o.labelKey)})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:a.message}),a.actions&&a.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:a.actions.map((i,c)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:i.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:d=>{d.stopPropagation(),i.onClick(),t(a.id)},children:i.label},c))})]})]},a.id)})})}const bS=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function gS(e){const t=e.workspace||"";if(!t)return"";const n=t.split(/[/\\]/).filter(Boolean);return n.length>0?n[n.length-1]:t}function xS(e,t){return _p(e)||t}function _p(e){var a,o,i;const t=(o=(a=e.summaryMetadata)==null?void 0:a.items)==null?void 0:o.find(c=>(c==null?void 0:c.id)==="model"),n=((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim();if(n)return n;const r=(i=e.controlValues)==null?void 0:i.model;return typeof r=="string"&&r.trim()?r.trim():""}function vS(e){return _p(e)||void 0}function yS(e){return e.sessionId||e.instanceId||e.agentType}function $p(e=[]){const t={};for(const n of e)n.type==="adhdev-daemon"&&(t[n.id]=ss(n,{fallbackId:n.id}));return t}function Hp(e,t={}){var r;const n=e.daemonId||((r=e.id)==null?void 0:r.split(":")[0])||e.id;return{machineName:By(e,t.machineNames),connectionState:t.connectionStates?t.connectionStates[n]||t.defaultConnectionState||"new":t.defaultConnectionState}}function al(e,t={}){return wS(e,Hp(e,t))}function wS(e,t={}){var f,g,k,h,v,w,b,j,C;const n=[],r=t.machineName,a=t.connectionState,o=gS(e),i=e.workspace||"",c=zy(e.type,{agentName:e.cliName}),d=ut(e)||dt(e)?c:$t(e.type),p=xS(e,d),u=Array.isArray(e.childSessions)?e.childSessions.map(y=>{var x,N,S;return{sessionId:y.id,instanceId:y.id,providerSessionId:y.providerSessionId,activeChatId:(x=y.activeChat)==null?void 0:x.id,transport:y.transport,sessionCapabilities:y.capabilities,agentType:y.providerType,agentName:y.providerName||$t(y.providerType),model:vS(y),status:y.status,title:y.title,lastMessagePreview:y.lastMessagePreview,lastMessageRole:y.lastMessageRole,lastMessageAt:y.lastMessageAt,lastMessageHash:y.lastMessageHash,messages:((N=y.activeChat)==null?void 0:N.messages)||[],activeModal:((S=y.activeChat)==null?void 0:S.activeModal)||void 0,unread:y.unread,lastSeenAt:y.lastSeenAt,lastUpdated:y.lastUpdated,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,surfaceHidden:y.surfaceHidden,muted:y.muted,git:y.git,settings:y.settings,coordinator:y.coordinator,messageInput:y.messageInput}}):[],m=bS(e);if(m){const y=e.sessionId||e.instanceId,x=(f=e.settings)==null?void 0:f.meshCoordinatorFor,N=((g=e.settings)==null?void 0:g.meshNodeFor)||!((k=e.settings)!=null&&k.meshCoordinatorFor)&&((h=e.settings)==null?void 0:h.launchedByCoordinator),S=x?" (Coordinator)":N?" (Mesh Node)":"",A=c+S,M=(v=e.activeChat)==null?void 0:v.activeModal,P=M&&Array.isArray(M.buttons)&&M.buttons.length>0,D=Ky(e.activeChat,[{status:e.status,activeModal:(w=e.activeChat)==null?void 0:w.activeModal}],e.agents||[]),I=e.activeChat||{title:"",messages:[]};let _=I.title&&String(I.title).trim()?String(I.title).trim():"";const W=(b=e.activeChat)==null?void 0:b.id,H=e.chats;if(W&&Array.isArray(H)&&H.length>0){const Q=H.find(re=>re.id===W||re.id&&String(re.id)===String(W));Q!=null&&Q.title&&String(Q.title).trim()&&(_=String(Q.title).trim())}const L=(ut(e)||dt(e),e.type),O=(ut(e)||dt(e))&&ac(_,A,L)?"":_,E=I.messages||[],T=typeof W=="string"?W.trim():"",$=(ut(e)||dt(e))&&T===String(e.type||"").trim(),R=T&&!$?T:e.providerSessionId,G=e.coordinator||(typeof((j=e.settings)==null?void 0:j.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:y,providerSessionId:e.providerSessionId,historySessionId:R,nativeSessionId:y,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:ut(e)&&e.mode||"chat",agentName:A,agentType:L,status:D,title:O,messages:E,resume:e.resume,hostIdeType:!ut(e)&&!dt(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||O||(ut(e)?e.mode==="chat"?A:`Terminal${S}`:A),displaySecondary:p,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,inboxBucket:e.inboxBucket,completionMarker:e.completionMarker,modalButtons:P?M.buttons:void 0,modalMessage:P?M.message:void 0,streamSource:"native",tabKey:oo(y,e.id),machineName:r,connectionState:a,settings:e.settings,coordinator:G,messageInput:e.messageInput})}if(m&&(ut(e)||dt(e)))return n;for(const y of u){const x=y.activeModal&&Array.isArray(y.activeModal.buttons)&&y.activeModal.buttons.length>0,N=Vy(y),S=yS(y),A=`${e.id}:${S}`,M=y.title&&String(y.title).trim()||"",P=ac(M,y.agentName,y.agentType)?"":M,D=y.messages||[];if(!(y.transport==="cdp-webview"||!!y.sessionId||!!y.providerSessionId||D.length>0||x||!!P||!["idle","panel_hidden","disconnected","not_monitored"].includes(N)))continue;const _=y.coordinator||(typeof((C=y.settings)==null?void 0:C.meshCoordinatorFor)=="string"&&y.settings.meshCoordinatorFor?{meshId:y.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:y.sessionId||y.instanceId,providerSessionId:y.providerSessionId,historySessionId:y.activeChatId||y.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:y.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:y.sessionCapabilities,mode:"chat",agentName:y.agentName,agentType:y.agentType,status:N,title:P,messages:D,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:y.git||e.git,displayPrimary:o||P||y.agentName||d,displaySecondary:y.model&&y.model.trim()?y.model.trim():`${d} · ${y.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:y.lastMessagePreview,lastMessageRole:y.lastMessageRole,lastMessageAt:y.lastMessageAt,lastMessageHash:y.lastMessageHash,lastUpdated:y.lastUpdated||e.lastUpdated,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,modalButtons:x?y.activeModal.buttons:void 0,modalMessage:x?y.activeModal.message:void 0,streamSource:"agent-stream",tabKey:oo(y.sessionId||y.instanceId,A),machineName:r,connectionState:a,settings:y.settings,coordinator:_,messageInput:y.messageInput})}return n.length===0&&n.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:c,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||d,displaySecondary:p,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:oo(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings,messageInput:e.messageInput}),n}function Fp(e){return String(e.type||e.id||"").trim()}function ja(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()).map(t=>t.trim()):[]}function kS(e,t){const n=(t||"").trim();if(!n)return[];const r=(e||[]).find(a=>a.type===n);return ja(r==null?void 0:r.modelOptions)}function SS(e,t){const n=(t||"").trim();if(!n)return[];const r=(e||[]).find(a=>a.type===n);return ja(r==null?void 0:r.thinkingLevelOptions)}function Bp(e){const t=new Map;for(const n of e||[])n!=null&&n.type&&t.set(n.type,{models:ja(n.modelOptions),thinking:ja(n.thinkingLevelOptions)});return t}function CS(e){var t;return e.category!=="cli"||!Fp(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 Tn(e){var r;const t=new Set,n=[];for(const a of e||[]){if(!CS(a))continue;const o=Fp(a);if(!o||t.has(o))continue;t.add(o);const i=String(a.displayName||a.name||o),c=a.detectedPath||((r=a.lastDetection)==null?void 0:r.path)||null;n.push({type:o,label:i,icon:a.icon,statusLabel:c?`Detected at ${c}`:"Detected on this machine",detectedPath:c,...Array.isArray(a.modelOptions)&&a.modelOptions.length?{modelOptions:a.modelOptions}:{},...Array.isArray(a.thinkingLevelOptions)&&a.thinkingLevelOptions.length?{thinkingLevelOptions:a.thinkingLevelOptions}:{}})}return n}function In(e){const t=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],n=new Set,r=[];for(const a of t){const o=typeof a=="string"?a.trim():"";!o||n.has(o)||(n.add(o),r.push(o))}return r}function gr(e){return e.map(t=>t.type)}function jS(e,t){const n=In(e),r=t.trim();return!r||n.includes(r)?n:[...n,r]}function NS(e,t){return In(e).filter(n=>n!==t)}function _c(e,t,n){const r=In(e),a=r.indexOf(t);if(a<0)return r;const o=r.filter(c=>c!==t);if(n==="top")return[t,...o];if(n==="bottom")return[...o,t];const i=n==="up"?Math.max(0,a-1):Math.min(o.length,a+1);return o.splice(i,0,t),o}function $c({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 AS({value:e,availableProviders:t,onChange:n,disabled:r=!1,saveButton:a}){const{t:o}=Se("common"),[i,c]=l.useState(""),d=l.useMemo(()=>new Map(t.map(g=>[g.type,g])),[t]),p=l.useMemo(()=>In(e),[e]),u=p.filter(g=>!d.has(g)).length,m=t.filter(g=>!p.includes(g.type)),f=()=>{i&&(n(jS(p,i)),c(""))};return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[s.jsx("div",{className:"flex flex-col gap-2",children:p.length===0?s.jsx("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:"No provider priority configured. Launches without an explicit CLI provider will fail closed."}):p.map((g,k)=>{const h=d.get(g),v=!!h;return s.jsxs("div",{className:`flex flex-col gap-2 rounded-md border border-border-subtle px-3 py-2 sm:flex-row sm:items-center sm:justify-between ${v?"bg-bg-primary":"bg-bg-primary/40"}`,children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("span",{className:"text-[10px] font-semibold text-text-muted",children:["#",k+1]}),(h==null?void 0:h.icon)&&s.jsx("span",{"aria-hidden":"true",children:h.icon}),s.jsx("span",{className:`font-mono text-[12px] ${v?"text-text-primary":"text-text-muted"}`,children:g}),v?s.jsx("span",{className:"rounded border border-green-500/20 bg-green-500/10 px-1.5 py-px text-[9px] font-semibold text-green-400",children:o("settings.providerPriority.available")}):s.jsx("span",{className:"rounded border border-amber-500/25 bg-amber-500/10 px-1.5 py-px text-[9px] font-semibold text-amber-400",children:o("settings.providerPriority.notOnMachine")})]}),s.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:h?`${h.label} · ${h.statusLabel}`:"Kept in order; skipped at launch until detected here."})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move up",disabled:r||k===0,title:"Move up",onClick:()=>n(_c(p,g,"up")),children:s.jsx($c,{direction:"up"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move down",disabled:r||k===p.length-1,title:"Move down",onClick:()=>n(_c(p,g,"down")),children:s.jsx($c,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:r,onClick:()=>n(NS(p,g)),children:o("settings.providerPriority.remove")})]})]},g)})}),s.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-end",children:[s.jsxs("label",{className:"flex-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"mb-1 block font-medium text-text-primary",children:o("settings.providerPriority.addCliLabel")}),s.jsxs("select",{className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-sm text-text-primary",value:i,onChange:g=>c(g.target.value),disabled:r||m.length===0,children:[s.jsx("option",{value:"",children:m.length?"Select provider…":"No additional detected CLI providers"}),m.map(g=>s.jsxs("option",{value:g.type,children:[g.label," (",g.type,")"]},g.type))]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:r||!i,onClick:f,children:o("settings.providerPriority.addProvider")}),a]}),s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:["Launches use this order, top to bottom.",u>0?` ${u} provider${u===1?"":"s"} not detected here — kept in order, skipped until available.`:""]})]})}function MS(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 Op(e,t){const n=MS(e);return{daemonId:n.daemonId,payload:{...t,...n.targetSessionId&&!t.targetSessionId?{targetSessionId:n.targetSessionId}:{}}}}const Wp=[{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:"🏄"}],Up=[{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:"◆"}],Gp=[{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:"🟠"}],TS=Wp,IS=Up,DS=Gp;function PS({icon:e,title:t,subtitle:n,badge:r,actions:a,className:o}){return s.jsxs("div",{className:Ut("dashboard-header",o),children:[s.jsxs("div",{children:[s.jsxs("h1",{className:"header-title flex items-center gap-2",children:[s.jsx("span",{className:"flex items-center text-lg",children:e})," ",t,r&&s.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[r.count!==void 0?r.count:""," ",r.text]})]}),n&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:n})]}),a&&s.jsx("div",{className:"flex gap-2",children:a})]})}function jr({icon:e,title:t,subtitle:n,badge:r,actions:a,widthClassName:o="max-w-6xl",contentClassName:i,children:c}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(PS,{icon:e,title:t,subtitle:n,badge:r,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Ut("mx-auto flex w-full flex-col gap-4",o,i),children:c})})]})}const xi="adhdev:themechange";function LS(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function bn(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function gn(e){return e==="system"?LS():e}function qp(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function na(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(xi,{detail:{preference:e,theme:t}}))}function RS(){const e=bn(),t=gn(e);qp(t),na(e,t)}function Fs(){const[e,t]=l.useState(bn),[n,r]=l.useState(()=>gn(bn()));l.useEffect(()=>{qp(n)},[n]),l.useEffect(()=>{const i=window.matchMedia("(prefers-color-scheme: light)"),c=d=>{if(e==="system"){const p=d.matches?"light":"dark";r(p),na("system",p)}};return i.addEventListener("change",c),()=>i.removeEventListener("change",c)},[e]),l.useEffect(()=>{const i=d=>{const p=d.detail||{},u=p.preference,m=p.theme;t(u==="dark"||u==="light"||u==="system"?u:bn()),r(m==="dark"||m==="light"?m:gn(bn()))},c=d=>{if(d.key!=="theme")return;const p=bn(),u=gn(p);t(p),r(u)};return window.addEventListener(xi,i),window.addEventListener("storage",c),()=>{window.removeEventListener(xi,i),window.removeEventListener("storage",c)}},[]);const a=l.useCallback(i=>{const c=gn(i);t(i),r(c);try{localStorage.setItem("theme",i)}catch{}na(i,c)},[]),o=l.useCallback(()=>{t(i=>{const c=i==="dark"?"light":i==="light"?"system":"dark",d=gn(c);r(d);try{localStorage.setItem("theme",c)}catch{}return na(c,d),c})},[]);return{theme:n,preference:e,setPreference:a,cycleTheme:o,isDark:n==="dark"}}const Hc={dark:"Dark",light:"Light",system:"System"};function ES({collapsed:e}){const{preference:t,cycleTheme:n}=Fs(),r=t==="dark"?s.jsx(Zf,{size:16}):t==="light"?s.jsx(Xf,{size:16}):s.jsx(eb,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:n,title:`Theme: ${Hc[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:r}),!e&&s.jsx("span",{className:"text-xs",children:Hc[t]})]})}const vi="adhdev:langchange";function _S(){const e=yt.language;return yn(e)?e:Pu()}function $S(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(vi,{detail:{language:e}}))}function HS(){const[e,t]=l.useState(_S);l.useEffect(()=>{const r=i=>{yn(i)&&t(i)},a=i=>{const c=i.detail||{};yn(c.language)&&t(c.language)},o=i=>{if(i.key!==ri)return;const c=i.newValue;yn(c)&&c!==yt.language&&(yt.changeLanguage(c),ai(c))};return yt.on("languageChanged",r),window.addEventListener(vi,a),window.addEventListener("storage",o),()=>{yt.off("languageChanged",r),window.removeEventListener(vi,a),window.removeEventListener("storage",o)}},[]);const n=l.useCallback(r=>{if(yn(r)){t(r);try{localStorage.setItem(ri,r)}catch{}yt.changeLanguage(r),ai(r),$S(r)}},[]);return{language:e,setLanguage:n}}function FS({trigger:e,viewport:t,menu:n,variant:r,gap:a=6,margin:o=8}){const i=e.top-o,c=t.height-e.bottom-o,d=r==="sidebar";let p=d;d&&i<n.height&&c>i&&(p=!1),!d&&c<n.height&&i>c&&(p=!0);const u=p?i:c,m=Math.max(80,Math.min(n.height,u));let f;p?f=e.top-a-m:f=e.bottom+a,f=Fc(f,o,Math.max(o,t.height-m-o));const g=Fc(e.left,o,Math.max(o,t.width-n.width-o));return{top:f,left:g,maxHeight:m}}function Fc(e,t,n){return Math.min(Math.max(e,t),n)}function BS({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 OS({collapsed:e,variant:t="sidebar"}){const{language:n,setLanguage:r}=HS(),{t:a}=Se("common"),[o,i]=l.useState(!1),[c,d]=l.useState(0),p=l.useRef(null),u=l.useRef(null),m=l.useRef(null),f=l.useId(),[g,k]=l.useState(null),h=l.useCallback(()=>{const D=u.current;if(!D)return;const I=D.getBoundingClientRect(),_=m.current,W=Math.max((_==null?void 0:_.offsetWidth)??0,168),H=(_==null?void 0:_.scrollHeight)??Ws.length*36+12;k(FS({trigger:{top:I.top,left:I.left,right:I.right,bottom:I.bottom,width:I.width,height:I.height},viewport:{width:window.innerWidth,height:window.innerHeight},menu:{width:W,height:H},variant:t}))},[t]),v=Math.max(0,Ws.findIndex(D=>D.code===n)),w=Ws[v]??Ws[0],b=a("language.label",{defaultValue:"Language"}),j=a("language.select",{defaultValue:"Select language"}),C=D=>`${f}-opt-${D}`,y=l.useCallback(()=>{d(v),i(!0)},[v]),x=l.useCallback((D=!0)=>{var I;i(!1),D&&((I=u.current)==null||I.focus())},[]),N=l.useCallback(D=>{const I=Ws[D];I&&r(I.code),x()},[r,x]);l.useEffect(()=>{if(!o)return;const D=W=>{var H,L;return!!((H=p.current)!=null&&H.contains(W)||(L=m.current)!=null&&L.contains(W))},I=W=>{D(W.target)||i(!1)},_=W=>{D(W.target)||i(!1)};return document.addEventListener("pointerdown",I,!0),document.addEventListener("focusin",_,!0),()=>{document.removeEventListener("pointerdown",I,!0),document.removeEventListener("focusin",_,!0)}},[o]),l.useLayoutEffect(()=>{if(!o){k(null);return}h();const D=()=>h();return window.addEventListener("resize",D),window.addEventListener("scroll",D,!0),()=>{window.removeEventListener("resize",D),window.removeEventListener("scroll",D,!0)}},[o,h]),l.useEffect(()=>{var D;o&&g&&((D=m.current)==null||D.focus())},[o,g]);const S=D=>{const I=Ws.length-1;switch(D.key){case"ArrowDown":D.preventDefault(),d(_=>_>=I?0:_+1);break;case"ArrowUp":D.preventDefault(),d(_=>_<=0?I:_-1);break;case"Home":D.preventDefault(),d(0);break;case"End":D.preventDefault(),d(I);break;case"Enter":case" ":D.preventDefault(),N(c);break;case"Escape":D.preventDefault(),x();break;case"Tab":i(!1);break}},A=D=>{o||(D.key==="ArrowDown"||D.key==="ArrowUp"||D.key==="Enter"||D.key===" ")&&(D.preventDefault(),y())},M=t==="landing"?"lang-switch-trigger lang-switch-trigger--landing":`lang-switch-trigger lang-switch-trigger--sidebar nav-item cursor-pointer${e?" justify-center py-2.5 px-0":""}`,P=t==="landing"||!e;return s.jsxs("div",{ref:p,className:"lang-switch",children:[s.jsxs("button",{ref:u,type:"button",className:M,"aria-haspopup":"listbox","aria-expanded":o,"aria-label":`${b}: ${w.label}`,title:`${b}: ${w.label}`,onClick:()=>o?x(!1):y(),onKeyDown:A,children:[s.jsx("span",{className:"nav-icon lang-switch-icon",children:s.jsx(cb,{size:16})}),P&&s.jsx("span",{className:"lang-switch-label text-xs",children:w.label}),P&&s.jsx(BS,{open:o})]}),o&&typeof document<"u"&&sn.createPortal(s.jsx("ul",{ref:m,role:"listbox",tabIndex:-1,"aria-label":j,"aria-activedescendant":C(c),className:`lang-switch-menu lang-switch-menu--${t}`,style:{position:"fixed",top:(g==null?void 0:g.top)??0,left:(g==null?void 0:g.left)??0,maxHeight:g==null?void 0:g.maxHeight,overflowY:"auto",visibility:g?"visible":"hidden"},onKeyDown:S,children:Ws.map((D,I)=>{const _=D.code===w.code,W=I===c;return s.jsxs("li",{id:C(I),role:"option","aria-selected":_,className:`lang-switch-option${W?" is-active":""}${_?" is-selected":""}`,onMouseEnter:()=>d(I),onClick:()=>N(I),children:[s.jsx("span",{className:"lang-switch-check","aria-hidden":"true",children:_?s.jsx(pu,{size:14}):null}),s.jsx("span",{className:"lang-switch-option-label",children:D.label})]},D.code)})}),document.body)]})}const WS=[],US=[];function bo(e,t){return e?typeof e=="function"?e(t):e:null}const GS=l.memo(function({renderState:t,brand:n,navItems:r,sidebarSections:a,footerItems:o,footerInfo:i,footerActions:c,closeMobileMenu:d}){const{t:p}=Se("common"),{collapsed:u,mobileMenuOpen:m}=t,f=k=>`nav-item${k.active?" active":""} cursor-pointer ${u?"justify-center py-2.5 px-0":""}${k.className?` ${k.className}`:""}`,g=k=>s.jsxs("div",{className:f(k),id:`nav-${k.id}`,onClick:()=>{k.onSelect(),d()},title:u?k.title??(typeof k.label=="string"?k.label:void 0):k.title,children:[s.jsx("span",{className:"nav-icon",children:k.icon}),!u&&k.label]},k.id);return s.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${u?"justify-center gap-0":""}`,children:bo(n,t)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":p("app.closeMenu"),onClick:d,children:s.jsx(Mt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(g)}),a.map(k=>s.jsxs("div",{className:k.className??"border-t border-border-subtle pt-2 mt-2",children:[!u&&k.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:k.title}):null,k.items.map(g)]},k.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[o.map(g),bo(i,t),s.jsx(ES,{collapsed:u}),s.jsx(OS,{collapsed:u}),bo(c,t)]})]})});function qS({children:e,brand:t,navItems:n,sidebarSections:r=WS,footerItems:a=US,footerInfo:o,footerActions:i,preMainContent:c,collapsedStorageKey:d="sidebar-collapsed"}){const{t:p}=Se("common"),[u,m]=l.useState(!1),[f,g]=l.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),k=l.useCallback(()=>m(!0),[]),h=l.useCallback(()=>m(!1),[]),v=l.useCallback(()=>{g(b=>{const j=!b;try{localStorage.setItem(d,j?"1":"0")}catch{}return j})},[d]),w=l.useMemo(()=>({collapsed:f,mobileMenuOpen:u,openMobileMenu:k,closeMobileMenu:h,toggleCollapsed:v}),[f,u,k,h,v]);return s.jsxs("div",{className:`app-layout${u?" mobile-menu-open":""}${f?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":p("app.openMenu"),onClick:k,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),u&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":p("app.closeMenu"),onClick:h,onKeyDown:b=>b.key==="Escape"&&h()}),s.jsx(GS,{renderState:w,brand:t,navItems:n,sidebarSections:r,footerItems:a,footerInfo:o,footerActions:i,closeMobileMenu:h}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function ht({title:e,icon:t,description:n,accentColor:r,className:a,collapsible:o,defaultOpen:i=!0,badge:c,children:d}){const[p,u]=l.useState(i),m=o?p:!0,f=(e||n)&&s.jsxs("div",{className:Ut("flex items-start justify-between gap-3",m&&"mb-4"),children:[s.jsxs("div",{className:"min-w-0",children:[e&&s.jsxs("h3",{className:"text-base font-semibold text-text-primary flex items-center gap-1.5",children:[t&&s.jsx("span",{children:t}),s.jsx("span",{children:e}),c]}),n&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:n})]}),o&&s.jsx("span",{className:Ut("mt-0.5 shrink-0 text-text-muted transition-transform select-none",m?"rotate-90":"rotate-0"),"aria-hidden":!0,children:"▸"})]});return s.jsxs("div",{className:Ut("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",r&&"border-l-[3px]",a),style:r?{borderLeftColor:r}:void 0,children:[o&&f?s.jsx("button",{type:"button",className:"w-full bg-transparent border-none p-0 text-left cursor-pointer",onClick:()=>u(g=>!g),"aria-expanded":m,children:f}):f,m&&d]})}function Ga({icon:e,title:t,description:n,action:r,className:a}){return s.jsxs("div",{className:Ut("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[s.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),s.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:t}),s.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:n}),r]})}const zS={error:"bg-red-500/10 border-red-500/30 text-red-400",warning:"bg-yellow-500/10 border-yellow-500/30 text-yellow-400",success:"bg-green-500/10 border-green-500/30 text-green-400",info:"bg-indigo-500/10 border-indigo-500/30 text-indigo-400"},KS={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Ht({variant:e,children:t,onDismiss:n,className:r}){return s.jsxs("div",{className:Ut("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",zS[e],r),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:KS[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 jt({label:e,hint:t,children:n,className:r}){return s.jsxs("div",{className:Ut("mb-5",r),children:[s.jsx("label",{className:"block text-xs font-semibold text-text-muted uppercase tracking-wider mb-2",children:e}),n,t&&s.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:t})]})}function ds(e){const{className:t,...n}=e;return s.jsx("input",{...n,className:Ut("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none","focus:border-accent transition-colors",t)})}const VS={primary:"btn-primary",secondary:"btn-secondary",warning:"btn-warning",danger:"btn-danger",ghost:"btn-ghost"},Ns=l.forwardRef(function({variant:t="secondary",size:n="md",type:r,className:a,...o},i){return s.jsx("button",{ref:i,type:r??"button",className:Ut("btn",VS[t],n==="sm"&&"btn-sm",a),...o})}),YS=l.forwardRef(function({options:t,children:n,className:r,...a},o){return s.jsx("select",{ref:o,className:Ut("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none cursor-pointer","focus:border-accent transition-colors",r),...a,children:n??(t==null?void 0:t.map(i=>s.jsx("option",{value:i.value,disabled:i.disabled,children:i.label},i.value)))})}),JS={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"},QS={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function XS({status:e,label:t,className:n}){const r=t||e;return s.jsxs("span",{className:Ut("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",JS[e],n),children:[s.jsx("span",{className:Ut("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",QS[e])}),r]})}function zs({label:e,description:t,checked:n,disabled:r,onChange:a,extra:o}){return s.jsxs("div",{className:`flex justify-between items-center ${r?"opacity-60":""}`,children:[s.jsxs("div",{className:"pr-4",children:[s.jsx("div",{className:"font-medium text-sm",children:e}),s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:t})]}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[o,s.jsxs("button",{type:"button",role:"switch","aria-checked":n,"aria-disabled":r,disabled:r,onClick:()=>a(!n),className:`relative inline-flex items-center ${r?"cursor-not-allowed":"cursor-pointer"}`,children:[s.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:n?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),s.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${n?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function ZS({onPrefChange:e}){const{t}=Se("common"),[n,r]=rw(),[a,o]=l.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);l.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){o("unsupported");return}o(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,d)=>{r({[c]:d}),e==null||e(c,d)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(zs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Rn,{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(zs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(hs,{size:15})," ",t("notifications.browserNotificationsLabel")]}),description:t("notifications.browserNotificationsDesc"),checked:n.browserNotifications,onChange:c=>i("browserNotifications",c)}),n.globalEnabled&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:t("notifications.standaloneBackgroundInfo")}),a==="default"&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-status-warning",children:[s.jsx("span",{children:t("notifications.standalonePermissionDefault")}),s.jsx("button",{onClick:()=>{Ou().then(o)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:t("notifications.allowNotifications")})]}),a==="denied"&&s.jsx("div",{className:"text-[11px] text-status-warning",children:t("notifications.permissionDenied")}),a==="unsupported"&&s.jsx("div",{className:"text-[11px] text-status-warning",children:t("notifications.standalonePermissionUnsupported")})]}),n.globalEnabled&&n.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(zs,{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(zs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(tb,{size:15})," ",t("notifications.approvalAlertsLabel")]}),description:t("notifications.approvalAlertsDesc"),checked:n.approvalAlert,onChange:c=>i("approvalAlert",c)}),s.jsx(zs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(mr,{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 yi(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/);if(!t)return null;const n=t[4]??null;let r=null;if(n){const a=n.match(/(?:^|\.)(\d+)$/);r=a?Number(a[1]):null}return{base:[Number(t[1]),Number(t[2]),Number(t[3])],prereleaseNumber:r,isPrerelease:n!==null}}function Na(e){var t;return((t=yi(e))==null?void 0:t.base)??null}function eC(e,t){const n=Na(e),r=Na(t);if(!n||!r)return e.localeCompare(t);for(let a=0;a<3;a+=1){if(n[a]<r[a])return-1;if(n[a]>r[a])return 1}return 0}function tC(e,t){const n=yi(e),r=yi(t);if(!n||!r)return e!==t;for(let a=0;a<3;a+=1){if(n.base[a]<r.base[a])return!0;if(n.base[a]>r.base[a])return!1}return n.isPrerelease&&r.isPrerelease?n.prereleaseNumber===null||r.prereleaseNumber===null?!1:n.prereleaseNumber<r.prereleaseNumber:!1}function ol(e,t){const n=e.version||null;return e.versionMismatch===!0?!0:!n||!t?!1:tC(n,t)}function lr(e,t){if(e.versionUpdateRequired===!0)return!0;const n=e.version||null;if(!n||!t||n===t||eC(n,t)>=0)return!1;const r=Na(n),a=Na(t);return!r||!a?!1:r[0]!==a[0]||r[1]!==a[1]}function sC(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function go(e,t){return e instanceof Error?e.message:t}function nC({ides:e,emptyMessage:t,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:a}){const{t:o}=Se("common"),i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?s.jsx(Ga,{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(aC,{ide:c,allIdes:e,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:a},c.id))})}function Bc({title:e,message:t,confirmLabel:n,confirmColor:r,onConfirm:a,onCancel:o}){const{t:i}=Se("common"),c=r==="red"?"bg-status-error/20 text-status-error border-status-error/40 hover:bg-status-error/30":"";return sn.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:"var(--z-modal)"},onClick:o,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:d=>d.stopPropagation(),children:[s.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),s.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:t}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.jsx("button",{onClick:o,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:i("common.cancel")}),s.jsx("button",{onClick:a,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,style:r==="amber"?{background:"color-mix(in srgb, var(--status-warning) 20%, transparent)",color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"}:void 0,children:n})]})]})}),document.body)}function rC(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),r=[...TS,...IS,...DS].find(a=>a.id===t||t.includes(a.id)||a.id.includes(t));return r?{icon:r.icon,name:r.name}:{icon:"📝",name:e}}function aC({ide:e,allIdes:t,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:a}){var W,H;const{t:o}=Se("common"),[i,c]=l.useState("idle"),[d,p]=l.useState(""),[u,m]=l.useState(null),[f,g]=l.useState("idle"),[k,h]=l.useState(""),v=e.version||null,w=((W=e.machine)==null?void 0:W.platform)||((H=e.system)==null?void 0:H.platform)||"",b=ss(e,{fallbackId:e.id}),j=w==="win32"?"🪟":w==="darwin"?"🍎":"🐧",C=t.filter(L=>L.daemonId===e.id&&L.transport==="cdp-page"),y=t.filter(L=>L.daemonId===e.id&&L.transport==="pty"),x=t.filter(L=>L.daemonId===e.id&&L.transport==="acp"),N=e.p2p,S=async()=>{if(n){c("upgrading"),p(o("machine.connectedMachines.startingUpgrade"));try{const L=sC(await n(e.id,"daemon_upgrade",{}));L.alreadyLatest?(c("done"),p(`Already on v${L.version||"latest"}.`)):L.upgraded||L.success?(c("done"),p(`Upgrade to v${L.version||"latest"} started. Daemon is restarting...`)):(c("error"),p(L.error||"Upgrade failed"))}catch(L){c("error"),p(go(L,"Connection lost during upgrade"))}}},A=async()=>{if(m(null),!!r){g("loading");try{await r(e.id),g("done"),h(o("machine.connectedMachines.machineDisconnected"))}catch(L){g("error"),h(go(L,o("machine.connectedMachines.failedToDisconnect")))}}},M=async()=>{if(m(null),!!a){g("loading");try{await a(e.id),g("done"),h(o("machine.connectedMachines.tokenRevoked"))}catch(L){g("error"),h(go(L,o("machine.connectedMachines.failedToRevokeToken")))}}},P="1.0.18",D=ol(e,P),I=lr(e,P),_=C.length+y.length+x.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xl",children:j}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:b}),s.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[s.jsxs("span",{children:[e.id.substring(0,12),"…"]}),v&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${D?"":"bg-bg-secondary"}`,style:D?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",v,!D&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[n&&D&&s.jsx("button",{onClick:S,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${P}`,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"):I?o("machine.connectedMachines.updateNow"):o("machine.connectedMachines.updateTo",{version:P})}),r&&s.jsx("button",{onClick:()=>m("disconnect"),disabled:f==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:o("machine.connectedMachines.disconnect")}),a&&s.jsx("button",{onClick:()=>m("revoke"),disabled:f==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:o("machine.connectedMachines.remove")}),s.jsx(XS,{status:e.status==="online"?"online":"error"})]})]}),s.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[N&&s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${N.state==="connected"?"bg-status-online":"bg-text-muted/30"} ${N.state==="connecting"||N.state==="new"?"animate-pulse":""}`,style:N.state==="connecting"||N.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",N.state==="connected"?"connected":N.state==="connecting"||N.state==="new"?o("machine.connectedMachines.connecting"):N.state||"off"]}),N.peers!==void 0&&N.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",N.peers," peer",N.peers!==1?"s":"",")"]})]}),N&&_>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),_>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[C.map(L=>{const O=rC(L.type),E=L.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:O.icon}),s.jsx("span",{children:O.name}),E!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${E?"bg-status-online":"animate-pulse"}`,style:E?void 0:{background:"var(--status-warning)"},title:o(E?"machine.connectedMachines.cdpConnected":"machine.connectedMachines.cdpConnecting")})]},L.id)}),y.map(L=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"⌨️"}),s.jsx("span",{children:L.cliName||"CLI"})]},L.id)),x.map(L=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"🔗"}),s.jsx("span",{children:L.cliName||"ACP"})]},L.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:o("machine.connectedMachines.noIdesConnected")})]}),(d||k)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||f==="error"?"text-status-error":i==="done"||f==="done"?"text-status-online":"text-text-muted"}`,children:k||d})]}),u==="disconnect"&&s.jsx(Bc,{title:o("machine.connectedMachines.disconnectTitle"),message:`Disconnect "${b}" from ADHDev?
|
|
58
|
+
`).includes(a)))}function iS(e,t="recent"){const n=e.slice();return n.sort((r,a)=>{if(t==="oldest")return(Number(r.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(t==="messages"){const o=(Number(a.messageCount)||0)-(Number(r.messageCount)||0);if(o!==0)return o}return(Number(a.lastMessageAt)||0)-(Number(r.lastMessageAt)||0)}),n}function Ip(e,t={}){return iS(oS(e,t),t.sortMode||"recent")}function gi(e,t){return typeof e=="function"?e(t??!1?"launch.resumeSavedHistory":"launch.startFresh"):e?"Resume saved history":"Start fresh"}function Dp(e,t){return typeof e=="function"?e(t??!1?"launch.resumingSavedHistory":"launch.startingFresh"):e?"Resuming saved history…":"Starting fresh…"}function lS(e){return e?e("launch.startFresh"):"Start fresh"}function cS(e){return e?e("launch.hostedRuntimeRecoveryDescription"):"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function dS(e){return e?e("launch.openSavedHistory"):"Open saved history"}function uS(e){return e?e("launch.savedHistoryTitle"):"Saved History"}function rl(e){return e?e("launch.savedHistoryHelper"):"Use saved history when you want continuity in the same provider conversation."}function pS(e){return e?e("launch.savedHistoryEmpty"):"No saved history found yet."}function mS(e){return e?e("launch.refreshSavedHistory"):"Refresh saved history"}function hS(e){return e?e("launch.refreshingSavedHistory"):"Refreshing saved history…"}function wa(e,t,n){if(typeof e=="function"){const o=t,i=n;return o==="start-fresh"?e("launch.startFreshWith",{label:i}):e("launch.restart",{label:i})}const r=e,a=t;return r==="start-fresh"?`Start fresh with ${a}?`:`Restart ${a}?`}function ka(e,t){if(typeof e=="function"){const r=t;return e(r==="start-fresh"?"launch.startFreshReview":r==="restart-ide"?"launch.restartIdeReview":"launch.restartStoppedReview")}const n=e;return n==="start-fresh"?"Review the provider and target folder before starting fresh.":n==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function Sa(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartFresh":"launch.confirmRestart"):e==="start-fresh"?"Start fresh":"Restart"}function Ca(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartingFresh":"launch.confirmRestarting"):e==="start-fresh"?"Starting fresh…":"Restarting…"}function Pp(e,t){return typeof e=="function"?e("launch.resumeWith",{label:t}):`Resume saved history with ${e}?`}function Lp(e){return e?e("launch.resumeReview"):"Review or change the target workspace before resuming saved history."}function fS(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 Rp({activeConv:e,ides:t,isCreatingChat:n,isRefreshingHistory:r,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:c,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:p,onClose:u,onNewChat:m,onSwitchSession:f,onRefreshHistory:g,onResumeSavedSession:k}){var D;const{t:h}=Se("common"),v=t.find(I=>I.id===e.routeId),w=(v==null?void 0:v.chats)||[],b=(D=v==null?void 0:v.activeChat)==null?void 0:D.id,j=ut(e)&&!dt(e),[C,y]=l.useState(()=>Wt()),x=c||C,N=String(d||"").trim(),S=I=>{if(p){p(I);return}y(I)},A=l.useMemo(()=>a.map(I=>{const _=String(I.workspace||"").trim();return I.canResume||_||!N?I:{...I,workspace:N,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[N,a]),M=l.useMemo(()=>Ip(A,{textQuery:x.textQuery,workspaceQuery:x.workspaceQuery,modelQuery:x.modelQuery,resumableOnly:x.resumableOnly,sortMode:x.sortMode}),[A,x.modelQuery,x.resumableOnly,x.sortMode,x.textQuery,x.workspaceQuery]),P=s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:u,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:j?uS(h):h("historyModal.chatHistory")}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:$k(e)}),j&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:rl(h)})]}),s.jsx("button",{onClick:u,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(Mt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!j&&s.jsx("button",{onClick:m,disabled:n,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:h(n?"historyModal.creating":"historyModal.startNewChat")}),j?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[s.jsx("input",{type:"text",value:x.textQuery,onChange:I=>S({...x,textQuery:I.target.value}),placeholder:h("historyModal.searchPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:x.workspaceQuery,onChange:I=>S({...x,workspaceQuery:I.target.value}),placeholder:h("historyModal.filterWorkspace"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:x.modelQuery,onChange:I=>S({...x,modelQuery:I.target.value}),placeholder:h("historyModal.filterModel"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsxs("select",{value:x.sortMode,onChange:I=>S({...x,sortMode:I.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:h("historyModal.sortRecent")}),s.jsx("option",{value:"oldest",children:h("historyModal.sortOldest")}),s.jsx("option",{value:"messages",children:h("historyModal.sortMessages")})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:x.resumableOnly,onChange:I=>S({...x,resumableOnly:I.target.checked})}),h("historyModal.resumeReadyOnly")]})]}),M.map(I=>{const _=e.providerSessionId===I.providerSessionId,W=_||!I.canResume||!!i,H=I.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{W||!k||k(I)},disabled:W,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${_?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${W?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${_?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:I.title||h("historyModal.untitledSession")}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:I.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:fS(I.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:I.preview||h("historyModal.noSavedPreview")}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[I.workspace||h("historyModal.workspaceUnknown"),H?h("historyModal.selectedWorkspaceSuffix"):"",rn(I.summaryMetadata)?` · ${rn(I.summaryMetadata)}`:"",I.messageCount>0?` · ${h("historyModal.msgCount",{count:I.messageCount})}`:""]}),s.jsx("div",{className:"shrink-0",children:_?h("historyModal.statusActive"):I.canResume?H?h("historyModal.statusResumeSelectedWorkspace"):i===I.providerSessionId?h("historyModal.statusResuming"):h("historyModal.statusResume"):h("historyModal.statusMissingWorkspace")})]})]},I.id)})]}):w.map(I=>s.jsxs("div",{onClick:()=>{f(e.routeId,I.id),u()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${b===I.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===I.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:I.title||h("historyModal.untitledSession")}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[I.id.substring(0,12),"..."]}),b===I.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:h("historyModal.statusActive")})]})]},I.id)),(j&&!o&&M.length===0||!j&&w.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(Qf,{size:32})}),s.jsx("div",{className:"text-[13px]",children:j?a.length>0?h("historyModal.noMatchingHistory"):pS(h):h("historyModal.noRecentChats")})]}),j&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:hS(h)})})]}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:s.jsx("button",{onClick:g,disabled:r||o,className:"btn btn-secondary btn-sm rounded-[10px]",children:r||o?h("historyModal.refreshing"):s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ra,{size:13})," ",j?mS(h):h("historyModal.refreshHistory")]})})})]})]});return typeof document>"u"?P:sn.createPortal(P,document.body)}const Ec={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 Ep({toasts:e,onDismiss:t,onClickToast:n}){const{t:r}=Se();return s.jsx("div",{className:"fixed right-4 z-[var(--z-toast)] flex flex-col gap-2 pointer-events-none",style:{top:"calc(env(safe-area-inset-top, 0px) + 16px)"},children:e.map(a=>{const o=Ec[a.type]||Ec.info;return s.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var i;(i=a.actions)!=null&&i.length||n&&n(a)},children:[s.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${o.accent}, color-mix(in srgb, ${o.accent} 55%, transparent))`}}),s.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:i=>{i.stopPropagation(),t(a.id)},"aria-label":r("toast.dismiss"),children:s.jsx(Mt,{size:14})}),s.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[s.jsx("div",{className:"flex items-center gap-2 pr-8",children:s.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:o.chipBg,color:o.chipText,border:`1px solid color-mix(in srgb, ${o.accent} 22%, transparent)`},children:r(o.labelKey)})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:a.message}),a.actions&&a.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:a.actions.map((i,c)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:i.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:d=>{d.stopPropagation(),i.onClick(),t(a.id)},children:i.label},c))})]})]},a.id)})})}const bS=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function gS(e){const t=e.workspace||"";if(!t)return"";const n=t.split(/[/\\]/).filter(Boolean);return n.length>0?n[n.length-1]:t}function xS(e,t){return _p(e)||t}function _p(e){var a,o,i;const t=(o=(a=e.summaryMetadata)==null?void 0:a.items)==null?void 0:o.find(c=>(c==null?void 0:c.id)==="model"),n=((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim();if(n)return n;const r=(i=e.controlValues)==null?void 0:i.model;return typeof r=="string"&&r.trim()?r.trim():""}function vS(e){return _p(e)||void 0}function yS(e){return e.sessionId||e.instanceId||e.agentType}function $p(e=[]){const t={};for(const n of e)n.type==="adhdev-daemon"&&(t[n.id]=ss(n,{fallbackId:n.id}));return t}function Hp(e,t={}){var r;const n=e.daemonId||((r=e.id)==null?void 0:r.split(":")[0])||e.id;return{machineName:By(e,t.machineNames),connectionState:t.connectionStates?t.connectionStates[n]||t.defaultConnectionState||"new":t.defaultConnectionState}}function al(e,t={}){return wS(e,Hp(e,t))}function wS(e,t={}){var f,g,k,h,v,w,b,j,C;const n=[],r=t.machineName,a=t.connectionState,o=gS(e),i=e.workspace||"",c=zy(e.type,{agentName:e.cliName}),d=ut(e)||dt(e)?c:$t(e.type),p=xS(e,d),u=Array.isArray(e.childSessions)?e.childSessions.map(y=>{var x,N,S;return{sessionId:y.id,instanceId:y.id,providerSessionId:y.providerSessionId,activeChatId:(x=y.activeChat)==null?void 0:x.id,transport:y.transport,sessionCapabilities:y.capabilities,agentType:y.providerType,agentName:y.providerName||$t(y.providerType),model:vS(y),status:y.status,title:y.title,lastMessagePreview:y.lastMessagePreview,lastMessageRole:y.lastMessageRole,lastMessageAt:y.lastMessageAt,lastMessageHash:y.lastMessageHash,messages:((N=y.activeChat)==null?void 0:N.messages)||[],activeModal:((S=y.activeChat)==null?void 0:S.activeModal)||void 0,unread:y.unread,lastSeenAt:y.lastSeenAt,lastUpdated:y.lastUpdated,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,surfaceHidden:y.surfaceHidden,muted:y.muted,git:y.git,settings:y.settings,coordinator:y.coordinator,messageInput:y.messageInput}}):[],m=bS(e);if(m){const y=e.sessionId||e.instanceId,x=(f=e.settings)==null?void 0:f.meshCoordinatorFor,N=((g=e.settings)==null?void 0:g.meshNodeFor)||!((k=e.settings)!=null&&k.meshCoordinatorFor)&&((h=e.settings)==null?void 0:h.launchedByCoordinator),S=x?" (Coordinator)":N?" (Mesh Node)":"",A=c+S,M=(v=e.activeChat)==null?void 0:v.activeModal,P=M&&Array.isArray(M.buttons)&&M.buttons.length>0,D=Ky(e.activeChat,[{status:e.status,activeModal:(w=e.activeChat)==null?void 0:w.activeModal}],e.agents||[]),I=e.activeChat||{title:"",messages:[]};let _=I.title&&String(I.title).trim()?String(I.title).trim():"";const W=(b=e.activeChat)==null?void 0:b.id,H=e.chats;if(W&&Array.isArray(H)&&H.length>0){const Q=H.find(re=>re.id===W||re.id&&String(re.id)===String(W));Q!=null&&Q.title&&String(Q.title).trim()&&(_=String(Q.title).trim())}const L=(ut(e)||dt(e),e.type),O=(ut(e)||dt(e))&&ac(_,A,L)?"":_,E=I.messages||[],T=typeof W=="string"?W.trim():"",$=(ut(e)||dt(e))&&T===String(e.type||"").trim(),R=T&&!$?T:e.providerSessionId,G=e.coordinator||(typeof((j=e.settings)==null?void 0:j.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:y,providerSessionId:e.providerSessionId,historySessionId:R,nativeSessionId:y,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:ut(e)&&e.mode||"chat",agentName:A,agentType:L,status:D,title:O,messages:E,resume:e.resume,hostIdeType:!ut(e)&&!dt(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||O||(ut(e)?e.mode==="chat"?A:`Terminal${S}`:A),displaySecondary:p,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,inboxBucket:e.inboxBucket,completionMarker:e.completionMarker,modalButtons:P?M.buttons:void 0,modalMessage:P?M.message:void 0,streamSource:"native",tabKey:oo(y,e.id),machineName:r,connectionState:a,settings:e.settings,coordinator:G,messageInput:e.messageInput})}if(m&&(ut(e)||dt(e)))return n;for(const y of u){const x=y.activeModal&&Array.isArray(y.activeModal.buttons)&&y.activeModal.buttons.length>0,N=Vy(y),S=yS(y),A=`${e.id}:${S}`,M=y.title&&String(y.title).trim()||"",P=ac(M,y.agentName,y.agentType)?"":M,D=y.messages||[];if(!(y.transport==="cdp-webview"||!!y.sessionId||!!y.providerSessionId||D.length>0||x||!!P||!["idle","panel_hidden","disconnected","not_monitored"].includes(N)))continue;const _=y.coordinator||(typeof((C=y.settings)==null?void 0:C.meshCoordinatorFor)=="string"&&y.settings.meshCoordinatorFor?{meshId:y.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:y.sessionId||y.instanceId,providerSessionId:y.providerSessionId,historySessionId:y.activeChatId||y.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:y.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:y.sessionCapabilities,mode:"chat",agentName:y.agentName,agentType:y.agentType,status:N,title:P,messages:D,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:y.git||e.git,displayPrimary:o||P||y.agentName||d,displaySecondary:y.model&&y.model.trim()?y.model.trim():`${d} · ${y.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:y.lastMessagePreview,lastMessageRole:y.lastMessageRole,lastMessageAt:y.lastMessageAt,lastMessageHash:y.lastMessageHash,lastUpdated:y.lastUpdated||e.lastUpdated,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,modalButtons:x?y.activeModal.buttons:void 0,modalMessage:x?y.activeModal.message:void 0,streamSource:"agent-stream",tabKey:oo(y.sessionId||y.instanceId,A),machineName:r,connectionState:a,settings:y.settings,coordinator:_,messageInput:y.messageInput})}return n.length===0&&n.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:c,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||d,displaySecondary:p,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:oo(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings,messageInput:e.messageInput}),n}function Fp(e){return String(e.type||e.id||"").trim()}function ja(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()).map(t=>t.trim()):[]}function kS(e,t){const n=(t||"").trim();if(!n)return[];const r=(e||[]).find(a=>a.type===n);return ja(r==null?void 0:r.modelOptions)}function SS(e,t){const n=(t||"").trim();if(!n)return[];const r=(e||[]).find(a=>a.type===n);return ja(r==null?void 0:r.thinkingLevelOptions)}function Bp(e){const t=new Map;for(const n of e||[])n!=null&&n.type&&t.set(n.type,{models:ja(n.modelOptions),thinking:ja(n.thinkingLevelOptions)});return t}function CS(e){var t;return e.category!=="cli"||!Fp(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 Tn(e){var r;const t=new Set,n=[];for(const a of e||[]){if(!CS(a))continue;const o=Fp(a);if(!o||t.has(o))continue;t.add(o);const i=String(a.displayName||a.name||o),c=a.detectedPath||((r=a.lastDetection)==null?void 0:r.path)||null;n.push({type:o,label:i,icon:a.icon,statusLabel:c?`Detected at ${c}`:"Detected on this machine",detectedPath:c,...Array.isArray(a.modelOptions)&&a.modelOptions.length?{modelOptions:a.modelOptions}:{},...Array.isArray(a.thinkingLevelOptions)&&a.thinkingLevelOptions.length?{thinkingLevelOptions:a.thinkingLevelOptions}:{}})}return n}function In(e){const t=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],n=new Set,r=[];for(const a of t){const o=typeof a=="string"?a.trim():"";!o||n.has(o)||(n.add(o),r.push(o))}return r}function gr(e){return e.map(t=>t.type)}function jS(e,t){const n=In(e),r=t.trim();return!r||n.includes(r)?n:[...n,r]}function NS(e,t){return In(e).filter(n=>n!==t)}function _c(e,t,n){const r=In(e),a=r.indexOf(t);if(a<0)return r;const o=r.filter(c=>c!==t);if(n==="top")return[t,...o];if(n==="bottom")return[...o,t];const i=n==="up"?Math.max(0,a-1):Math.min(o.length,a+1);return o.splice(i,0,t),o}function $c({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 AS({value:e,availableProviders:t,onChange:n,disabled:r=!1,saveButton:a}){const{t:o}=Se("common"),[i,c]=l.useState(""),d=l.useMemo(()=>new Map(t.map(g=>[g.type,g])),[t]),p=l.useMemo(()=>In(e),[e]),u=p.filter(g=>!d.has(g)).length,m=t.filter(g=>!p.includes(g.type)),f=()=>{i&&(n(jS(p,i)),c(""))};return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[s.jsx("div",{className:"flex flex-col gap-2",children:p.length===0?s.jsx("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:"No provider priority configured. Launches without an explicit CLI provider will fail closed."}):p.map((g,k)=>{const h=d.get(g),v=!!h;return s.jsxs("div",{className:`flex flex-col gap-2 rounded-md border border-border-subtle px-3 py-2 sm:flex-row sm:items-center sm:justify-between ${v?"bg-bg-primary":"bg-bg-primary/40"}`,children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("span",{className:"text-[10px] font-semibold text-text-muted",children:["#",k+1]}),(h==null?void 0:h.icon)&&s.jsx("span",{"aria-hidden":"true",children:h.icon}),s.jsx("span",{className:`font-mono text-[12px] ${v?"text-text-primary":"text-text-muted"}`,children:g}),v?s.jsx("span",{className:"rounded border border-green-500/20 bg-green-500/10 px-1.5 py-px text-[9px] font-semibold text-green-400",children:o("settings.providerPriority.available")}):s.jsx("span",{className:"rounded border border-amber-500/25 bg-amber-500/10 px-1.5 py-px text-[9px] font-semibold text-amber-400",children:o("settings.providerPriority.notOnMachine")})]}),s.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:h?`${h.label} · ${h.statusLabel}`:"Kept in order; skipped at launch until detected here."})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move up",disabled:r||k===0,title:"Move up",onClick:()=>n(_c(p,g,"up")),children:s.jsx($c,{direction:"up"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move down",disabled:r||k===p.length-1,title:"Move down",onClick:()=>n(_c(p,g,"down")),children:s.jsx($c,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:r,onClick:()=>n(NS(p,g)),children:o("settings.providerPriority.remove")})]})]},g)})}),s.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-end",children:[s.jsxs("label",{className:"flex-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"mb-1 block font-medium text-text-primary",children:o("settings.providerPriority.addCliLabel")}),s.jsxs("select",{className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-sm text-text-primary",value:i,onChange:g=>c(g.target.value),disabled:r||m.length===0,children:[s.jsx("option",{value:"",children:m.length?"Select provider…":"No additional detected CLI providers"}),m.map(g=>s.jsxs("option",{value:g.type,children:[g.label," (",g.type,")"]},g.type))]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:r||!i,onClick:f,children:o("settings.providerPriority.addProvider")}),a]}),s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:["Launches use this order, top to bottom.",u>0?` ${u} provider${u===1?"":"s"} not detected here — kept in order, skipped until available.`:""]})]})}function MS(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 Op(e,t){const n=MS(e);return{daemonId:n.daemonId,payload:{...t,...n.targetSessionId&&!t.targetSessionId?{targetSessionId:n.targetSessionId}:{}}}}const Wp=[{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:"🏄"}],Up=[{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:"◆"}],Gp=[{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:"🟠"}],TS=Wp,IS=Up,DS=Gp;function PS({icon:e,title:t,subtitle:n,badge:r,actions:a,className:o}){return s.jsxs("div",{className:Ut("dashboard-header",o),children:[s.jsxs("div",{children:[s.jsxs("h1",{className:"header-title flex items-center gap-2",children:[s.jsx("span",{className:"flex items-center text-lg",children:e})," ",t,r&&s.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[r.count!==void 0?r.count:""," ",r.text]})]}),n&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:n})]}),a&&s.jsx("div",{className:"flex gap-2",children:a})]})}function jr({icon:e,title:t,subtitle:n,badge:r,actions:a,widthClassName:o="max-w-6xl",contentClassName:i,children:c}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(PS,{icon:e,title:t,subtitle:n,badge:r,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Ut("mx-auto flex w-full flex-col gap-4",o,i),children:c})})]})}const xi="adhdev:themechange";function LS(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function bn(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function gn(e){return e==="system"?LS():e}function qp(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function na(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(xi,{detail:{preference:e,theme:t}}))}function RS(){const e=bn(),t=gn(e);qp(t),na(e,t)}function Fs(){const[e,t]=l.useState(bn),[n,r]=l.useState(()=>gn(bn()));l.useEffect(()=>{qp(n)},[n]),l.useEffect(()=>{const i=window.matchMedia("(prefers-color-scheme: light)"),c=d=>{if(e==="system"){const p=d.matches?"light":"dark";r(p),na("system",p)}};return i.addEventListener("change",c),()=>i.removeEventListener("change",c)},[e]),l.useEffect(()=>{const i=d=>{const p=d.detail||{},u=p.preference,m=p.theme;t(u==="dark"||u==="light"||u==="system"?u:bn()),r(m==="dark"||m==="light"?m:gn(bn()))},c=d=>{if(d.key!=="theme")return;const p=bn(),u=gn(p);t(p),r(u)};return window.addEventListener(xi,i),window.addEventListener("storage",c),()=>{window.removeEventListener(xi,i),window.removeEventListener("storage",c)}},[]);const a=l.useCallback(i=>{const c=gn(i);t(i),r(c);try{localStorage.setItem("theme",i)}catch{}na(i,c)},[]),o=l.useCallback(()=>{t(i=>{const c=i==="dark"?"light":i==="light"?"system":"dark",d=gn(c);r(d);try{localStorage.setItem("theme",c)}catch{}return na(c,d),c})},[]);return{theme:n,preference:e,setPreference:a,cycleTheme:o,isDark:n==="dark"}}const Hc={dark:"Dark",light:"Light",system:"System"};function ES({collapsed:e}){const{preference:t,cycleTheme:n}=Fs(),r=t==="dark"?s.jsx(Zf,{size:16}):t==="light"?s.jsx(Xf,{size:16}):s.jsx(eb,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:n,title:`Theme: ${Hc[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:r}),!e&&s.jsx("span",{className:"text-xs",children:Hc[t]})]})}const vi="adhdev:langchange";function _S(){const e=yt.language;return yn(e)?e:Pu()}function $S(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(vi,{detail:{language:e}}))}function HS(){const[e,t]=l.useState(_S);l.useEffect(()=>{const r=i=>{yn(i)&&t(i)},a=i=>{const c=i.detail||{};yn(c.language)&&t(c.language)},o=i=>{if(i.key!==ri)return;const c=i.newValue;yn(c)&&c!==yt.language&&(yt.changeLanguage(c),ai(c))};return yt.on("languageChanged",r),window.addEventListener(vi,a),window.addEventListener("storage",o),()=>{yt.off("languageChanged",r),window.removeEventListener(vi,a),window.removeEventListener("storage",o)}},[]);const n=l.useCallback(r=>{if(yn(r)){t(r);try{localStorage.setItem(ri,r)}catch{}yt.changeLanguage(r),ai(r),$S(r)}},[]);return{language:e,setLanguage:n}}function FS({trigger:e,viewport:t,menu:n,variant:r,gap:a=6,margin:o=8}){const i=e.top-o,c=t.height-e.bottom-o,d=r==="sidebar";let p=d;d&&i<n.height&&c>i&&(p=!1),!d&&c<n.height&&i>c&&(p=!0);const u=p?i:c,m=Math.max(80,Math.min(n.height,u));let f;p?f=e.top-a-m:f=e.bottom+a,f=Fc(f,o,Math.max(o,t.height-m-o));const g=Fc(e.left,o,Math.max(o,t.width-n.width-o));return{top:f,left:g,maxHeight:m}}function Fc(e,t,n){return Math.min(Math.max(e,t),n)}function BS({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 OS({collapsed:e,variant:t="sidebar"}){const{language:n,setLanguage:r}=HS(),{t:a}=Se("common"),[o,i]=l.useState(!1),[c,d]=l.useState(0),p=l.useRef(null),u=l.useRef(null),m=l.useRef(null),f=l.useId(),[g,k]=l.useState(null),h=l.useCallback(()=>{const D=u.current;if(!D)return;const I=D.getBoundingClientRect(),_=m.current,W=Math.max((_==null?void 0:_.offsetWidth)??0,168),H=(_==null?void 0:_.scrollHeight)??Ws.length*36+12;k(FS({trigger:{top:I.top,left:I.left,right:I.right,bottom:I.bottom,width:I.width,height:I.height},viewport:{width:window.innerWidth,height:window.innerHeight},menu:{width:W,height:H},variant:t}))},[t]),v=Math.max(0,Ws.findIndex(D=>D.code===n)),w=Ws[v]??Ws[0],b=a("language.label",{defaultValue:"Language"}),j=a("language.select",{defaultValue:"Select language"}),C=D=>`${f}-opt-${D}`,y=l.useCallback(()=>{d(v),i(!0)},[v]),x=l.useCallback((D=!0)=>{var I;i(!1),D&&((I=u.current)==null||I.focus())},[]),N=l.useCallback(D=>{const I=Ws[D];I&&r(I.code),x()},[r,x]);l.useEffect(()=>{if(!o)return;const D=W=>{var H,L;return!!((H=p.current)!=null&&H.contains(W)||(L=m.current)!=null&&L.contains(W))},I=W=>{D(W.target)||i(!1)},_=W=>{D(W.target)||i(!1)};return document.addEventListener("pointerdown",I,!0),document.addEventListener("focusin",_,!0),()=>{document.removeEventListener("pointerdown",I,!0),document.removeEventListener("focusin",_,!0)}},[o]),l.useLayoutEffect(()=>{if(!o){k(null);return}h();const D=()=>h();return window.addEventListener("resize",D),window.addEventListener("scroll",D,!0),()=>{window.removeEventListener("resize",D),window.removeEventListener("scroll",D,!0)}},[o,h]),l.useEffect(()=>{var D;o&&g&&((D=m.current)==null||D.focus())},[o,g]);const S=D=>{const I=Ws.length-1;switch(D.key){case"ArrowDown":D.preventDefault(),d(_=>_>=I?0:_+1);break;case"ArrowUp":D.preventDefault(),d(_=>_<=0?I:_-1);break;case"Home":D.preventDefault(),d(0);break;case"End":D.preventDefault(),d(I);break;case"Enter":case" ":D.preventDefault(),N(c);break;case"Escape":D.preventDefault(),x();break;case"Tab":i(!1);break}},A=D=>{o||(D.key==="ArrowDown"||D.key==="ArrowUp"||D.key==="Enter"||D.key===" ")&&(D.preventDefault(),y())},M=t==="landing"?"lang-switch-trigger lang-switch-trigger--landing":`lang-switch-trigger lang-switch-trigger--sidebar nav-item cursor-pointer${e?" justify-center py-2.5 px-0":""}`,P=t==="landing"||!e;return s.jsxs("div",{ref:p,className:"lang-switch",children:[s.jsxs("button",{ref:u,type:"button",className:M,"aria-haspopup":"listbox","aria-expanded":o,"aria-label":`${b}: ${w.label}`,title:`${b}: ${w.label}`,onClick:()=>o?x(!1):y(),onKeyDown:A,children:[s.jsx("span",{className:"nav-icon lang-switch-icon",children:s.jsx(cb,{size:16})}),P&&s.jsx("span",{className:"lang-switch-label text-xs",children:w.label}),P&&s.jsx(BS,{open:o})]}),o&&typeof document<"u"&&sn.createPortal(s.jsx("ul",{ref:m,role:"listbox",tabIndex:-1,"aria-label":j,"aria-activedescendant":C(c),className:`lang-switch-menu lang-switch-menu--${t}`,style:{position:"fixed",top:(g==null?void 0:g.top)??0,left:(g==null?void 0:g.left)??0,maxHeight:g==null?void 0:g.maxHeight,overflowY:"auto",visibility:g?"visible":"hidden"},onKeyDown:S,children:Ws.map((D,I)=>{const _=D.code===w.code,W=I===c;return s.jsxs("li",{id:C(I),role:"option","aria-selected":_,className:`lang-switch-option${W?" is-active":""}${_?" is-selected":""}`,onMouseEnter:()=>d(I),onClick:()=>N(I),children:[s.jsx("span",{className:"lang-switch-check","aria-hidden":"true",children:_?s.jsx(pu,{size:14}):null}),s.jsx("span",{className:"lang-switch-option-label",children:D.label})]},D.code)})}),document.body)]})}const WS=[],US=[];function bo(e,t){return e?typeof e=="function"?e(t):e:null}const GS=l.memo(function({renderState:t,brand:n,navItems:r,sidebarSections:a,footerItems:o,footerInfo:i,footerActions:c,closeMobileMenu:d}){const{t:p}=Se("common"),{collapsed:u,mobileMenuOpen:m}=t,f=k=>`nav-item${k.active?" active":""} cursor-pointer ${u?"justify-center py-2.5 px-0":""}${k.className?` ${k.className}`:""}`,g=k=>s.jsxs("div",{className:f(k),id:`nav-${k.id}`,onClick:()=>{k.onSelect(),d()},title:u?k.title??(typeof k.label=="string"?k.label:void 0):k.title,children:[s.jsx("span",{className:"nav-icon",children:k.icon}),!u&&k.label]},k.id);return s.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${u?"justify-center gap-0":""}`,children:bo(n,t)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":p("app.closeMenu"),onClick:d,children:s.jsx(Mt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(g)}),a.map(k=>s.jsxs("div",{className:k.className??"border-t border-border-subtle pt-2 mt-2",children:[!u&&k.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:k.title}):null,k.items.map(g)]},k.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[o.map(g),bo(i,t),s.jsx(ES,{collapsed:u}),s.jsx(OS,{collapsed:u}),bo(c,t)]})]})});function qS({children:e,brand:t,navItems:n,sidebarSections:r=WS,footerItems:a=US,footerInfo:o,footerActions:i,preMainContent:c,collapsedStorageKey:d="sidebar-collapsed"}){const{t:p}=Se("common"),[u,m]=l.useState(!1),[f,g]=l.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),k=l.useCallback(()=>m(!0),[]),h=l.useCallback(()=>m(!1),[]),v=l.useCallback(()=>{g(b=>{const j=!b;try{localStorage.setItem(d,j?"1":"0")}catch{}return j})},[d]),w=l.useMemo(()=>({collapsed:f,mobileMenuOpen:u,openMobileMenu:k,closeMobileMenu:h,toggleCollapsed:v}),[f,u,k,h,v]);return s.jsxs("div",{className:`app-layout${u?" mobile-menu-open":""}${f?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":p("app.openMenu"),onClick:k,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),u&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":p("app.closeMenu"),onClick:h,onKeyDown:b=>b.key==="Escape"&&h()}),s.jsx(GS,{renderState:w,brand:t,navItems:n,sidebarSections:r,footerItems:a,footerInfo:o,footerActions:i,closeMobileMenu:h}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function ht({title:e,icon:t,description:n,accentColor:r,className:a,collapsible:o,defaultOpen:i=!0,badge:c,children:d}){const[p,u]=l.useState(i),m=o?p:!0,f=(e||n)&&s.jsxs("div",{className:Ut("flex items-start justify-between gap-3",m&&"mb-4"),children:[s.jsxs("div",{className:"min-w-0",children:[e&&s.jsxs("h3",{className:"text-base font-semibold text-text-primary flex items-center gap-1.5",children:[t&&s.jsx("span",{children:t}),s.jsx("span",{children:e}),c]}),n&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:n})]}),o&&s.jsx("span",{className:Ut("mt-0.5 shrink-0 text-text-muted transition-transform select-none",m?"rotate-90":"rotate-0"),"aria-hidden":!0,children:"▸"})]});return s.jsxs("div",{className:Ut("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",r&&"border-l-[3px]",a),style:r?{borderLeftColor:r}:void 0,children:[o&&f?s.jsx("button",{type:"button",className:"w-full bg-transparent border-none p-0 text-left cursor-pointer",onClick:()=>u(g=>!g),"aria-expanded":m,children:f}):f,m&&d]})}function Ga({icon:e,title:t,description:n,action:r,className:a}){return s.jsxs("div",{className:Ut("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[s.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),s.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:t}),s.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:n}),r]})}const zS={error:"bg-red-500/10 border-red-500/30 text-red-400",warning:"bg-yellow-500/10 border-yellow-500/30 text-yellow-400",success:"bg-green-500/10 border-green-500/30 text-green-400",info:"bg-indigo-500/10 border-indigo-500/30 text-indigo-400"},KS={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Ht({variant:e,children:t,onDismiss:n,className:r}){return s.jsxs("div",{className:Ut("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",zS[e],r),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:KS[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 jt({label:e,hint:t,children:n,className:r}){return s.jsxs("div",{className:Ut("mb-5",r),children:[s.jsx("label",{className:"block text-xs font-semibold text-text-muted uppercase tracking-wider mb-2",children:e}),n,t&&s.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:t})]})}function ds(e){const{className:t,...n}=e;return s.jsx("input",{...n,className:Ut("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none","focus:border-accent transition-colors",t)})}const VS={primary:"btn-primary",secondary:"btn-secondary",warning:"btn-warning",danger:"btn-danger",ghost:"btn-ghost"},Ns=l.forwardRef(function({variant:t="secondary",size:n="md",type:r,className:a,...o},i){return s.jsx("button",{ref:i,type:r??"button",className:Ut("btn",VS[t],n==="sm"&&"btn-sm",a),...o})}),YS=l.forwardRef(function({options:t,children:n,className:r,...a},o){return s.jsx("select",{ref:o,className:Ut("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none cursor-pointer","focus:border-accent transition-colors",r),...a,children:n??(t==null?void 0:t.map(i=>s.jsx("option",{value:i.value,disabled:i.disabled,children:i.label},i.value)))})}),JS={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"},QS={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function XS({status:e,label:t,className:n}){const r=t||e;return s.jsxs("span",{className:Ut("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",JS[e],n),children:[s.jsx("span",{className:Ut("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",QS[e])}),r]})}function zs({label:e,description:t,checked:n,disabled:r,onChange:a,extra:o}){return s.jsxs("div",{className:`flex justify-between items-center ${r?"opacity-60":""}`,children:[s.jsxs("div",{className:"pr-4",children:[s.jsx("div",{className:"font-medium text-sm",children:e}),s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:t})]}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[o,s.jsxs("button",{type:"button",role:"switch","aria-checked":n,"aria-disabled":r,disabled:r,onClick:()=>a(!n),className:`relative inline-flex items-center ${r?"cursor-not-allowed":"cursor-pointer"}`,children:[s.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:n?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),s.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${n?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function ZS({onPrefChange:e}){const{t}=Se("common"),[n,r]=rw(),[a,o]=l.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);l.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){o("unsupported");return}o(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,d)=>{r({[c]:d}),e==null||e(c,d)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(zs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Rn,{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(zs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(hs,{size:15})," ",t("notifications.browserNotificationsLabel")]}),description:t("notifications.browserNotificationsDesc"),checked:n.browserNotifications,onChange:c=>i("browserNotifications",c)}),n.globalEnabled&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:t("notifications.standaloneBackgroundInfo")}),a==="default"&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-status-warning",children:[s.jsx("span",{children:t("notifications.standalonePermissionDefault")}),s.jsx("button",{onClick:()=>{Ou().then(o)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:t("notifications.allowNotifications")})]}),a==="denied"&&s.jsx("div",{className:"text-[11px] text-status-warning",children:t("notifications.permissionDenied")}),a==="unsupported"&&s.jsx("div",{className:"text-[11px] text-status-warning",children:t("notifications.standalonePermissionUnsupported")})]}),n.globalEnabled&&n.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(zs,{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(zs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(tb,{size:15})," ",t("notifications.approvalAlertsLabel")]}),description:t("notifications.approvalAlertsDesc"),checked:n.approvalAlert,onChange:c=>i("approvalAlert",c)}),s.jsx(zs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(mr,{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 yi(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/);if(!t)return null;const n=t[4]??null;let r=null;if(n){const a=n.match(/(?:^|\.)(\d+)$/);r=a?Number(a[1]):null}return{base:[Number(t[1]),Number(t[2]),Number(t[3])],prereleaseNumber:r,isPrerelease:n!==null}}function Na(e){var t;return((t=yi(e))==null?void 0:t.base)??null}function eC(e,t){const n=Na(e),r=Na(t);if(!n||!r)return e.localeCompare(t);for(let a=0;a<3;a+=1){if(n[a]<r[a])return-1;if(n[a]>r[a])return 1}return 0}function tC(e,t){const n=yi(e),r=yi(t);if(!n||!r)return e!==t;for(let a=0;a<3;a+=1){if(n.base[a]<r.base[a])return!0;if(n.base[a]>r.base[a])return!1}return n.isPrerelease&&r.isPrerelease?n.prereleaseNumber===null||r.prereleaseNumber===null?!1:n.prereleaseNumber<r.prereleaseNumber:!1}function ol(e,t){const n=e.version||null;return e.versionMismatch===!0?!0:!n||!t?!1:tC(n,t)}function lr(e,t){if(e.versionUpdateRequired===!0)return!0;const n=e.version||null;if(!n||!t||n===t||eC(n,t)>=0)return!1;const r=Na(n),a=Na(t);return!r||!a?!1:r[0]!==a[0]||r[1]!==a[1]}function sC(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function go(e,t){return e instanceof Error?e.message:t}function nC({ides:e,emptyMessage:t,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:a}){const{t:o}=Se("common"),i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?s.jsx(Ga,{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(aC,{ide:c,allIdes:e,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:a},c.id))})}function Bc({title:e,message:t,confirmLabel:n,confirmColor:r,onConfirm:a,onCancel:o}){const{t:i}=Se("common"),c=r==="red"?"bg-status-error/20 text-status-error border-status-error/40 hover:bg-status-error/30":"";return sn.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:"var(--z-modal)"},onClick:o,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:d=>d.stopPropagation(),children:[s.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),s.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:t}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.jsx("button",{onClick:o,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:i("common.cancel")}),s.jsx("button",{onClick:a,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,style:r==="amber"?{background:"color-mix(in srgb, var(--status-warning) 20%, transparent)",color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"}:void 0,children:n})]})]})}),document.body)}function rC(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),r=[...TS,...IS,...DS].find(a=>a.id===t||t.includes(a.id)||a.id.includes(t));return r?{icon:r.icon,name:r.name}:{icon:"📝",name:e}}function aC({ide:e,allIdes:t,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:a}){var W,H;const{t:o}=Se("common"),[i,c]=l.useState("idle"),[d,p]=l.useState(""),[u,m]=l.useState(null),[f,g]=l.useState("idle"),[k,h]=l.useState(""),v=e.version||null,w=((W=e.machine)==null?void 0:W.platform)||((H=e.system)==null?void 0:H.platform)||"",b=ss(e,{fallbackId:e.id}),j=w==="win32"?"🪟":w==="darwin"?"🍎":"🐧",C=t.filter(L=>L.daemonId===e.id&&L.transport==="cdp-page"),y=t.filter(L=>L.daemonId===e.id&&L.transport==="pty"),x=t.filter(L=>L.daemonId===e.id&&L.transport==="acp"),N=e.p2p,S=async()=>{if(n){c("upgrading"),p(o("machine.connectedMachines.startingUpgrade"));try{const L=sC(await n(e.id,"daemon_upgrade",{}));L.alreadyLatest?(c("done"),p(`Already on v${L.version||"latest"}.`)):L.upgraded||L.success?(c("done"),p(`Upgrade to v${L.version||"latest"} started. Daemon is restarting...`)):(c("error"),p(L.error||"Upgrade failed"))}catch(L){c("error"),p(go(L,"Connection lost during upgrade"))}}},A=async()=>{if(m(null),!!r){g("loading");try{await r(e.id),g("done"),h(o("machine.connectedMachines.machineDisconnected"))}catch(L){g("error"),h(go(L,o("machine.connectedMachines.failedToDisconnect")))}}},M=async()=>{if(m(null),!!a){g("loading");try{await a(e.id),g("done"),h(o("machine.connectedMachines.tokenRevoked"))}catch(L){g("error"),h(go(L,o("machine.connectedMachines.failedToRevokeToken")))}}},P="1.0.20",D=ol(e,P),I=lr(e,P),_=C.length+y.length+x.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xl",children:j}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:b}),s.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[s.jsxs("span",{children:[e.id.substring(0,12),"…"]}),v&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${D?"":"bg-bg-secondary"}`,style:D?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",v,!D&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[n&&D&&s.jsx("button",{onClick:S,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${P}`,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"):I?o("machine.connectedMachines.updateNow"):o("machine.connectedMachines.updateTo",{version:P})}),r&&s.jsx("button",{onClick:()=>m("disconnect"),disabled:f==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:o("machine.connectedMachines.disconnect")}),a&&s.jsx("button",{onClick:()=>m("revoke"),disabled:f==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:o("machine.connectedMachines.remove")}),s.jsx(XS,{status:e.status==="online"?"online":"error"})]})]}),s.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[N&&s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${N.state==="connected"?"bg-status-online":"bg-text-muted/30"} ${N.state==="connecting"||N.state==="new"?"animate-pulse":""}`,style:N.state==="connecting"||N.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",N.state==="connected"?"connected":N.state==="connecting"||N.state==="new"?o("machine.connectedMachines.connecting"):N.state||"off"]}),N.peers!==void 0&&N.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",N.peers," peer",N.peers!==1?"s":"",")"]})]}),N&&_>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),_>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[C.map(L=>{const O=rC(L.type),E=L.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:O.icon}),s.jsx("span",{children:O.name}),E!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${E?"bg-status-online":"animate-pulse"}`,style:E?void 0:{background:"var(--status-warning)"},title:o(E?"machine.connectedMachines.cdpConnected":"machine.connectedMachines.cdpConnecting")})]},L.id)}),y.map(L=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"⌨️"}),s.jsx("span",{children:L.cliName||"CLI"})]},L.id)),x.map(L=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"🔗"}),s.jsx("span",{children:L.cliName||"ACP"})]},L.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:o("machine.connectedMachines.noIdesConnected")})]}),(d||k)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||f==="error"?"text-status-error":i==="done"||f==="done"?"text-status-online":"text-text-muted"}`,children:k||d})]}),u==="disconnect"&&s.jsx(Bc,{title:o("machine.connectedMachines.disconnectTitle"),message:`Disconnect "${b}" from ADHDev?
|
|
59
59
|
|
|
60
60
|
This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
|
|
61
61
|
|
|
@@ -66,8 +66,8 @@ This will:
|
|
|
66
66
|
• Delete the machine registration
|
|
67
67
|
• Require restarting ADHDev on that machine
|
|
68
68
|
|
|
69
|
-
Use this if you want to permanently remove a machine.`,confirmLabel:o("machine.connectedMachines.remove"),confirmColor:"red",onConfirm:M,onCancel:()=>m(null)})]})}const oC=["default","claude-cli","codex-cli","antigravity-cli","hermes-cli","gemini-cli"];function iC({daemonId:e,knownCliTypes:t=oC}){const{t:n}=Se("common"),{sendCommand:r}=vt(),[a,o]=l.useState({}),[i,c]=l.useState({}),[d,p]=l.useState(!0),[u,m]=l.useState(null),[f,g]=l.useState(null),[k,h]=l.useState(""),v=l.useCallback(async()=>{if(e){p(!0),g(null);try{const j=await r(e,"list_coordinator_prompts",{}),C=j!=null&&j.result&&typeof j.result=="object"?j.result:j;if(!(C!=null&&C.success)){g((C==null?void 0:C.error)||"Failed to load");return}const y=C.entries||{};h(C.dir||"");const x={};for(const N of t)x[N]=y[N]||{override:"",append:""};for(const N of Object.keys(y))x[N]||(x[N]=y[N]);o(x),c(JSON.parse(JSON.stringify(x)))}catch(j){g((j==null?void 0:j.message)||String(j))}finally{p(!1)}}},[r,e,t]);l.useEffect(()=>{v()},[v]);const w=l.useCallback(async(j,C)=>{var y;if(e){m(`${j}:${C}`),g(null);try{const x=((y=a[j])==null?void 0:y[C])||"",N=await r(e,"write_coordinator_prompt",{key:j,kind:C,content:x}),S=N!=null&&N.result&&typeof N.result=="object"?N.result:N;if(!(S!=null&&S.success)){g((S==null?void 0:S.error)||"Save failed");return}c(A=>({...A,[j]:{...A[j]||{override:"",append:""},[C]:x}}))}catch(x){g((x==null?void 0:x.message)||String(x))}finally{m(null)}}},[r,e,a]),b=l.useMemo(()=>(j,C)=>{var y,x;return(((y=a[j])==null?void 0:y[C])||"")!==(((x=i[j])==null?void 0:x[C])||"")},[a,i]);return e?s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{className:"text-[12px] text-text-muted",children:[s.jsxs("p",{children:["Customize the coordinator prompt this daemon's mesh coordinator sessions get. ",s.jsx("span",{className:"font-mono text-[11px]",children:k||"~/.adhdev/coordinator-prompts/"})]}),s.jsxs("p",{className:"mt-1",children:[s.jsx(Jo,{i18nKey:"settings.coordinatorPrompts.overrideDesc",ns:"common",components:{strong:s.jsx("strong",{})}})," ",s.jsx(Jo,{i18nKey:"settings.coordinatorPrompts.appendDesc",ns:"common",components:{strong:s.jsx("strong",{})}}),"Leave a field empty + Save to remove it (reset to default). Supports placeholders: ","{{meshName}}",", ","{{repo}}",", ","{{nodes}}",", ","{{rules}}",", etc."]})]}),f&&s.jsx("div",{className:"text-[12px] text-status-error bg-status-error/10 border border-status-error/40 rounded px-3 py-2",children:f}),d&&s.jsx("div",{className:"text-[12px] text-text-muted",children:"Loading…"}),s.jsx("div",{className:"flex flex-col gap-6",children:Object.entries(a).map(([j,C])=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 p-3",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-2",children:j}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:n("settings.coordinatorPrompts.overrideLabel")}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:4,value:C.override,onChange:y=>o(x=>({...x,[j]:{...x[j],override:y.target.value}})),placeholder:"(empty — use daemon default base prompt)",disabled:u===`${j}:override`}),s.jsx("div",{className:"mt-1 mb-3 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void w(j,"override"),disabled:u===`${j}:override`||!b(j,"override"),children:u===`${j}:override`?"Saving…":b(j,"override")?"Save override":"Saved"})}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:n("settings.coordinatorPrompts.appendLabel")}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:3,value:C.append,onChange:y=>o(x=>({...x,[j]:{...x[j],append:y.target.value}})),placeholder:"(empty — nothing appended at this layer)",disabled:u===`${j}:append`}),s.jsx("div",{className:"mt-1 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void w(j,"append"),disabled:u===`${j}:append`||!b(j,"append"),children:u===`${j}:append`?"Saving…":b(j,"append")?"Save append":"Saved"})})]},j))})]}):s.jsx("div",{className:"text-[12px] text-text-muted",children:"Connect a daemon to edit coordinator prompts."})}const lC=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function cC(){const{preference:e,setPreference:t}=Fs();return s.jsx("div",{className:"flex gap-2",children:lC.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 dC(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 uC(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function xo(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Oc(e){const{r:t,g:n,b:r}=uC(e);return .2126*xo(t)+.7152*xo(n)+.0722*xo(r)}function Wc(e,t){const n=Oc(e),r=Oc(t),a=Math.max(n,r),o=Math.min(n,r);return(a+.05)/(o+.05)}function zp(e){const t=dC(e);if(!t)return"#111827";const n="#111827",r="#ffffff";return Wc(t,n)>=Wc(t,r)?n:r}const wi={bgPrimary:"#0a0e1a",bgSecondary:"#0f1320",surfacePrimary:"#111726",textPrimary:"#f0f0f5",textSecondary:"#9ca3af",textMuted:"#6b7280",borderSubtle:"#1d2536",borderDefault:"#313c52",accentColor:"#d97706",userBubble:"#f59e0b",userText:"#1a1a1a",assistantBubble:"#111726",assistantText:"#f0f0f5",containerBg:"#0f1320",sendButton:"#d97706",inputBorder:"#313c52",bubbleRadius:16},ki={bgPrimary:"#fff8ee",bgSecondary:"#fff1de",surfacePrimary:"#ffffff",textPrimary:"#24160f",textSecondary:"#6f6255",textMuted:"#938374",borderSubtle:"#e7d3ba",borderDefault:"#d7b892",accentColor:"#d97706",userBubble:"#f59e0b",userText:"#1a1a1a",assistantBubble:"#fffaf4",assistantText:"#24160f",containerBg:"#fff8ee",sendButton:"#d97706",inputBorder:"#d7b892",bubbleRadius:16},pC=[{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"}}}],Kp="adhdev-chat-theme",Vp="adhdev-chat-theme-custom";function ra(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Kp)||"ember"}catch{return"ember"}}function cs(e){try{const t=localStorage.getItem(Vp);if(t){const n=JSON.parse(t);return{...e==="dark"?wi:ki,...n[e]}}}catch{}return e==="dark"?wi:ki}function Fr(e,t){try{localStorage.setItem(Vp,JSON.stringify({dark:e,light:t}))}catch{}}function Xt(e,t){const n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),a=parseInt(e.slice(5,7),16);return`rgba(${n}, ${r}, ${a}, ${t})`}function Aa(e,t){const n=Math.min(255,parseInt(e.slice(1,3),16)+t),r=Math.min(255,parseInt(e.slice(3,5),16)+t),a=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${n.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const mC={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function cr(e,t){var a;const n=(a=mC[e])==null?void 0:a[t];if(!n)return;const r=document.documentElement;r.style.setProperty("--accent-primary",n),r.style.setProperty("--accent-primary-light",Aa(n,24)),r.style.setProperty("--accent-on-primary",zp(n)),r.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${n}, ${Aa(n,18)})`),r.style.setProperty("--border-accent",Xt(n,.35)),r.style.setProperty("--nav-active-bg",Xt(n,.1)),r.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${n}, 0 0 12px ${Xt(n,.06)}`)}function Xs(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",Xt(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Xt(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Xt(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",Xt(e.borderSubtle,.5)),t.style.setProperty("--border-default",Xt(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",Aa(e.accentColor,30)),t.style.setProperty("--accent-on-primary",zp(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Aa(e.accentColor,40)})`),t.style.setProperty("--border-accent",Xt(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",Xt(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Xt(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 ${Xt(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 il(){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 hC(e){try{localStorage.setItem(Kp,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=Zs()?"dark":"light";Xs(cs(t))}else il(),cr(e,Zs()?"dark":"light")}function fC(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=ra();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=Zs()?"dark":"light";Xs(cs(t))}else il(),cr(e,Zs()?"dark":"light")}function Zs(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Ot({label:e,value:t,onChange:n}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[s.jsx("input",{type:"color",value:t,onChange:r=>n(r.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),s.jsx("input",{type:"text",value:t,onChange:r=>{/^#[0-9a-fA-F]{0,6}$/.test(r.target.value)&&n(r.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function Kn({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 bC({dark:e,onColorsChange:t}){const{t:n}=Se("common"),r=e?"dark":"light",[a,o]=l.useState(()=>cs(r));l.useEffect(()=>{o(cs(r))},[r]);const i=l.useCallback((c,d)=>{o(p=>{const u={...p,[c]:d},f=cs(r==="dark"?"light":"dark");return r==="dark"?Fr(u,f):Fr(f,u),Xs(u),t(u),u})},[r,t]);return s.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[s.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[n("settings.theme.customEditorTitle"),s.jsx("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:n(e?"settings.theme.darkMode":"settings.theme.lightMode")})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs(Kn,{title:n("settings.theme.sectionAppBackground"),children:[s.jsx(Ot,{label:n("settings.theme.colorBackground"),value:a.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(Ot,{label:n("settings.theme.colorSurface"),value:a.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(Ot,{label:n("settings.theme.colorCard"),value:a.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(Kn,{title:n("settings.theme.sectionAppText"),children:[s.jsx(Ot,{label:n("settings.theme.colorPrimary"),value:a.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(Ot,{label:n("settings.theme.colorSecondary"),value:a.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(Ot,{label:n("settings.theme.colorMuted"),value:a.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(Kn,{title:n("settings.theme.sectionBordersAccent"),children:[s.jsx(Ot,{label:n("settings.theme.colorBorderSubtle"),value:a.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(Ot,{label:n("settings.theme.colorBorderDefault"),value:a.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(Ot,{label:n("settings.theme.colorAccent"),value:a.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(Kn,{title:n("settings.theme.sectionChatBubbles"),children:[s.jsx(Ot,{label:n("settings.theme.colorUserBubble"),value:a.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(Ot,{label:n("settings.theme.colorUserText"),value:a.userText,onChange:c=>i("userText",c)}),s.jsx(Ot,{label:n("settings.theme.colorAgentBubble"),value:a.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(Ot,{label:n("settings.theme.colorAgentText"),value:a.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(Kn,{title:n("settings.theme.sectionChatLayout"),children:[s.jsx(Ot,{label:n("settings.theme.colorChatBg"),value:a.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(Ot,{label:n("settings.theme.colorSendButton"),value:a.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(Ot,{label:n("settings.theme.colorInputBorder"),value:a.inputBorder,onChange:c=>i("inputBorder",c)}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:n("settings.theme.labelBubbleRadius")}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[s.jsx("input",{type:"range",min:4,max:24,value:a.bubbleRadius,onChange:c=>i("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),s.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[a.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const c=e?wi:ki,p=cs(e?"light":"dark");e?Fr(c,p):Fr(p,c),o(c),Xs(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 gC(){const{t:e}=Se("common"),[t,n]=l.useState(ra),[r,a]=l.useState(!0),[o,i]=l.useState(()=>cs("dark"));l.useEffect(()=>{a(Zs());const p=new MutationObserver(()=>{const f=Zs();a(f);const g=ra();g==="custom"?Xs(cs(f?"dark":"light")):cr(g,f?"dark":"light")});p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const u=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const f=Zs();a(f);const g=ra();g==="custom"?Xs(cs(f?"dark":"light")):cr(g,f?"dark":"light")};return u.addEventListener("change",m),()=>{p.disconnect(),u.removeEventListener("change",m)}},[]),l.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?Xs(cs(r?"dark":"light")):(il(),cr(t,r?"dark":"light"))},[t,r]),l.useEffect(()=>{i(cs(r?"dark":"light"))},[r]);const c=p=>{n(p),hC(p)},d=[...pC,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText},light:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:d.map(p=>{const u=t===p.id,m=r?p.preview.dark:p.preview.light,f=p.id==="honey"||p.id==="ember"?"#1a1a1a":p.id==="custom"?o.userText:"#fff";return s.jsxs("button",{onClick:()=>c(p.id),className:"text-left rounded-xl p-3 transition-all",style:{background:u?"var(--bg-glass-hover)":"var(--bg-glass)",border:u?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:u?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:m.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:e("settings.theme.helloHelp")}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.userBubble,color:f},children:e("settings.theme.fixBug")}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:e("settings.theme.onIt")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[u&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:p.id==="custom"?e("settings.theme.customLabel"):p.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:p.description})]})]})]},p.id)})}),t==="custom"&&s.jsx(bC,{dark:r,onColorsChange:p=>i(p)})]})}const ll="adhdev_mobileDashboardMode_v1",Si="adhdev:mobile-dashboard-mode-change";function cl(){try{return localStorage.getItem(ll)==="workspace"?"workspace":"chat"}catch{return"chat"}}function xC(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??cl())},n=a=>{const o=a.detail;t(o)},r=a=>{a.key&&a.key!==ll||t()};return window.addEventListener(Si,n),window.addEventListener("storage",r),()=>{window.removeEventListener(Si,n),window.removeEventListener("storage",r)}}function vC(e){try{localStorage.setItem(ll,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Si,{detail:e}))}function yC(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(cl()==="chat")},[]),s.jsx(zs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ln,{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),vC(n?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const wC="Choose a preset or create a fully custom theme. Custom themes control the entire app — backgrounds, text, borders, and chat bubbles.",kC="Choose whether the dashboard opens like a chat app on phones or keeps the full workspace layout.";function SC({themeDescription:e=wC,mobileDescription:t=kC,fontsSlot:n}){const{t:r}=Se("common");return s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:r("settings.appearance.modeLabel")}),s.jsx(cC,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:r("settings.appearance.themeLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:e}),s.jsx(gC,{})]}),n,s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:r("settings.appearance.mobileLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:t}),s.jsx(yC,{})]})]})}const vo=new Map,Uc=new Map;function CC(e){if(!e||typeof e!="object")return null;const t=e,n=t.result&&typeof t.result=="object"?t.result:t,r=n.machine;return!r||typeof r!="object"?null:{machine:r,timestamp:typeof n.timestamp=="number"?n.timestamp:void 0}}function jC(e,t,n,r){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:r,platform:n.platform,machine:n}}function Yp(){const{sendCommand:e}=vt(),{injectEntries:t,getIdes:n}=pr();return l.useCallback(async(r,a)=>{if(!r)return;const o=(a==null?void 0:a.minFreshMs)??E0,i=Uc.get(r)||0;if(!(a!=null&&a.force)&&i>0&&Date.now()-i<o)return;const c=vo.get(r);if(c)return c;const d=(async()=>{const p=await e(r,"get_machine_runtime_stats"),u=CC(p);if(!u)return;const m=n().find(g=>g.id===r),f=jC(m,r,u.machine,u.timestamp||Date.now());t([f]),Uc.set(r,Date.now())})().finally(()=>{vo.delete(r)});return vo.set(r,d),d},[n,t,e])}function NC(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 AC(e,t){const{sendData:n}=vt(),{injectEntries:r,getIdes:a}=pr(),o=Array.from(new Set(e.filter(Boolean))).join("|");l.useEffect(()=>{if(!(t!=null&&t.enabled)||!n)return;const i=o?o.split("|"):[];if(i.length===0)return;const c=i.map(d=>us.subscribe({sendData:n},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const m=a().find(g=>g.id===d),f=NC(m,d,u);r([f])}));return()=>{c.forEach(d=>d())}},[o,a,r,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,n])}function MC(e,t){const{sendData:n}=vt(),[r,a]=l.useState(null),[o,i]=l.useState(!1);return l.useEffect(()=>{if(!e){a(null),i(!1);return}if(!(t!=null&&t.enabled)||!n){i(!1);return}a(null),i(!0);let c=null;const d=us.subscribe({sendData:n},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},p=>{c&&(clearTimeout(c),c=null),a(p.diagnostics),i(!1)});return d.initialSendAccepted?c=setTimeout(()=>{i(!1)},H0):i(!1),()=>{c&&clearTimeout(c),d()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,n]),{diagnostics:r,loading:o,applyDiagnostics:a}}function TC(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Jp(e){const{sendData:t}=vt(),[n,r]=l.useState({});return l.useEffect(()=>{const a=TC(e);if(!a||!e.sessionId||!t){r({});return}const o=us.subscribe({sendData:t},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},i=>{r({status:i.status,modalMessage:i.modalMessage,modalButtons:i.modalButtons}),Cn.record({interactionId:i.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:i.status,modalButtonCount:Array.isArray(i.modalButtons)?i.modalButtons.length:0}})});return o.initialSendAccepted||r({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,t]),n}function IC(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function DC(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 PC(e,t,n){const r=await n(`/api/v1/sessions/${encodeURIComponent(e)}/interactive-prompt/resolve`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let a=`HTTP ${r.status}`;try{const o=await r.json();typeof(o==null?void 0:o.error)=="string"&&(a=o.error)}catch{}throw new Error(a)}}async function LC({promptSession:e,response:t,useP2PCommand:n,sendCommand:r,fetchImpl:a=fetch}){if(n){const o=await r(e.routeId,"interactive_prompt_response",{targetSessionId:e.sessionId,sessionId:e.sessionId,response:t});if(!IC(o))throw new Error(DC(o));return}await PC(e.sessionId,t,a)}function Qp(e){const{ides:t,isP2PActive:n,p2pStates:r}=Ss(),{sendCommand:a}=vt(),[o,i]=l.useState(null),[c,d]=l.useState(!1),[p,u]=l.useState(null),m=l.useRef(!1),f=l.useMemo(()=>Fb(t,e),[t,e]),g=!!f,k=l.useMemo(()=>f?f.prompt.promptId===o?null:f:null,[o,f]),h=l.useCallback(async b=>{if(!k||m.current)return;m.current=!0;const j=Nu(k.prompt,b);d(!0),u(null);try{const C=(r==null?void 0:r[k.daemonId])==="connected"||n===!0;await LC({promptSession:k,response:j,useP2PCommand:C,sendCommand:a}),i(k.prompt.promptId)}catch(C){throw u(C instanceof Error?C.message:String(C)),C}finally{d(!1),m.current=!1}},[n,r,k,a]),v=l.useCallback(()=>{k&&i(k.prompt.promptId)},[k]),w=l.useCallback(()=>{i(null),u(null)},[]);return{promptSession:k,hasActivePrompt:g,responseError:p,isSubmitting:c,submit:h,cancel:v,reopen:w}}function Xp(e){return e instanceof Error?e.message:String(e||"")}function RC(e){const t=Xp(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 EC(e){const t=Xp(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Zp({conversation:e,mode:t,ides:n,sendDaemonCommand:r,setCliViewModeOverrides:a}){if(!e||!ut(e)||dt(e))return;const o=En(e);if(o===t)return;const i=e.sessionId;i&&a(c=>({...c,[i]:t}));try{await r(Ts(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:ks(e),mode:t})}catch(c){const d=EC(c);i&&!d&&a(p=>{const u={...p};return o===$C(n,i)?delete u[i]:u[i]=o,u}),RC(c)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",c instanceof Error?c.message:String(c)):console.error("Failed to switch CLI view mode:",c)}}function Gc(e,t){const n=typeof e.sessionId=="string"&&e.sessionId?e.sessionId:typeof e.id=="string"?e.id:"";if(!n||e.transport!=="pty")return e;const r=t[n];return!r||e.mode===r?e:{...e,mode:r}}function _C(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let n=!1;const r=e.map(a=>{const o=Gc(a,t),i=Array.isArray(a.childSessions)?a.childSessions.map(d=>Gc(d,t)):a.childSessions,c=i!==a.childSessions;return o!==a||c?(n=!0,{...o,...c?{childSessions:i}:{}}):a});return n?r:e}function $C(e,t){if(!t)return null;for(const n of e){if(n.sessionId===t&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal";for(const r of n.childSessions||[])if(r.id===t&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal"}return null}function HC({visibleConversations:e,clearedTabs:t,setClearedTabs:n,setActionLogs:r,isConversationMuted:a}){l.useEffect(()=>{Ou()},[]);const o=l.useMemo(()=>e.map(i=>({id:i.tabKey,name:Np(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null,target:{providerSessionId:i.providerSessionId,sessionId:i.sessionId,tabKey:i.tabKey,routeId:i.routeId},muted:a?a(i):!1})),[e,a]);return lw(o),l.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{n(d=>{const p=Date.now(),u={};for(const[m,f]of Object.entries(d))p-f<5e3&&(u[m]=f);return Object.keys(u).length===Object.keys(d).length?d:u})},5500);return()=>clearTimeout(c)},[t,n]),l.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;r(d=>{const p=d.filter(u=>u.timestamp>c).slice(-100);return p.length===d.length?d:p})},6e4);return()=>clearInterval(i)},[r]),null}function qc(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 en(e){const t=[...e.messages].reverse().find(a=>!(a!=null&&a._localId))||e.messages[e.messages.length-1],n=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,r=qc(t==null?void 0:t.receivedAt)||qc(t==null?void 0:t.timestamp)||0;return Math.max(n,r)}function Ci(e,t=0){return en(e)||e.lastUpdated||t||0}function em(e){return en(e)||e.lastUpdated||0}function tm(e,t,n=em){const r=n(t)-n(e);if(r!==0)return r;const a=(e.machineName||"").localeCompare(t.machineName||"");if(a!==0)return a;const o=e.displayPrimary.localeCompare(t.displayPrimary);if(o!==0)return o;const i=e.displaySecondary.localeCompare(t.displaySecondary);return i!==0?i:e.tabKey.localeCompare(t.tabKey)}function ji(e){var n;const t=es(e.status,{activeModal:(n=e.modalButtons)!=null&&n.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function FC(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!ji(e)&&!e.title.trim()}function BC(e){return e.length===0?null:[...e].sort((t,n)=>{const r=Number(ji(n))-Number(ji(t));if(r!==0)return r;const a=n.messages.length-t.messages.length;return a!==0?a:tm(t,n)})[0]||null}function ps(e,t){const n=e.filter(i=>i.routeId===t);if(n.length===0)return null;const r=n.find(i=>i.streamSource==="native")||null,a=n.filter(i=>i.streamSource==="agent-stream"),o=BC(a);return r?o&&FC(r)?o:r:o||n[0]||null}function OC(e){const t=e.filter(a=>a.type!=="adhdev-daemon"),n=new Set;for(const a of t){if(!ci(a))continue;const o=Eu(a);o&&n.add(o)}const r=new Map;for(const a of t){const o=Fy(a,n),i=r.get(o);if(!i){r.set(o,a);continue}const c=m=>(m.workspace?1:0)+(m.activeChat?1:0)+(m.lastMessagePreview?1:0),d=c(i),p=c(a),u=p>d||p===d&&(a.timestamp||0)>(i.timestamp||0)?a:i;r.set(o,WC(u,u===a?i:a))}return Array.from(r.values())}function WC(e,t){const n=ci(t),r=ci(e);if(!n&&!r)return e;const a=r?n?void 0:t:e,o=r?e:n?t:void 0,i=a&&String(a.daemonId||"").trim()||String(e.ownerDaemonId||"").trim()||String(t.ownerDaemonId||"").trim()||void 0,c=String(e.ownerMachineName||"").trim()||String(t.ownerMachineName||"").trim()||void 0,d=o==null?void 0:o.settings;return{...e,...i&&{ownerDaemonId:i},...c&&!e.ownerMachineName&&{ownerMachineName:c},...d&&!r&&{settings:{...d,...e.settings??{}}}}}function yo(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 UC(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 zc(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],n=t[t.length-1],r=n?UC(jn(n.content)):"";return[e.id||"",e.title||"",e.status||"",t.length,String((n==null?void 0:n.id)||""),String((n==null?void 0:n.index)??""),String((n==null?void 0:n.receivedAt)??(n==null?void 0:n.timestamp)??""),r].join(":")}function GC(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||""),zc(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||""),zc(n.activeChat)].join(":"))].join("|")}function qC(e,t){const n=Date.now();return e.map(r=>{const a=t[r.tabKey];return a&&n-a<5e3?{...r,messages:[],title:""}:r})}function zC(e,t){const n=new Map;for(const r of e){const a=t.get(r.routeId)||r;for(const o of ar({routeId:r.routeId}))n.set(o,a);for(const o of ar({providerSessionId:r.providerSessionId,sessionId:r.sessionId}))n.set(o,r.streamSource==="native"?a:r);for(const o of ar({tabKey:r.tabKey}))n.set(o,r)}return n}function KC(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function VC(e){const t=KC(e);if(!t)return`empty:${e.messages.length}`;if(t.id)return`id:${String(t.id)}`;if(t._localId)return`local:${String(t._localId)}`;const n=String(t.role||""),r=jn(t.content).slice(0,240);return`${e.messages.length}:${n}:${r}`}function YC({ides:e,connectionStates:t,clearedTabs:n}){const r=l.useMemo(()=>OC(e),[e]),a=l.useMemo(()=>Tu(e),[e]),o=l.useMemo(()=>$p(e),[e]),i=l.useRef([]),c=l.useRef([]),d=l.useRef([]),p=l.useRef(new Map),u=l.useRef(new Map),m=l.useMemo(()=>{const C=new Map,y=[];for(const A of r){const{connectionState:M="new",machineName:P}=Hp(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),D=GC(A),I=p.current.get(A.id);if(I&&I.ide===A&&I.sourceSignature===D&&I.connectionState===M&&I.machineName===P){C.set(A.id,I),y.push(...I.conversations);continue}const _=al(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),W={ide:A,sourceSignature:D,connectionState:M,machineName:P,conversations:_};C.set(A.id,W),y.push(..._)}p.current=C;const x=new Map,N=A=>{const M=VC(A),P=u.current.get(A.tabKey);if(P&&P.signature===M)return x.set(A.tabKey,P),P.timestamp;const D={signature:M,timestamp:em(A)||(P==null?void 0:P.timestamp)||0};return x.set(A.tabKey,D),D.timestamp},S=[...y].sort((A,M)=>tm(A,M,N));return u.current=x,S},[r,t,o]),f=l.useMemo(()=>{const C=qC(m,n);return yo(i.current,C)?i.current:(i.current=C,C)},[m,n]),g=l.useMemo(()=>{const C=new Map,y=Array.from(new Set(f.map(x=>x.routeId)));for(const x of y){const N=ps(f,x);N&&C.set(x,N)}return C},[f]),k=l.useMemo(()=>{const C=new Map;for(const y of f){const x=g.get(y.routeId),N=y.streamSource==="native"&&x?x:y;for(const S of ar({providerSessionId:y.providerSessionId,sessionId:y.sessionId,tabKey:y.tabKey}))C.set(S,N)}return C},[f,g]),h=l.useMemo(()=>zC(f,g),[f,g]),v=l.useCallback(C=>{if(C)return k.get(C)},[k]),w=l.useCallback(C=>{if(C)return h.get(C)},[h]),b=l.useMemo(()=>{const C=f.filter(y=>!Hs(y,a).surfaceHidden);return yo(c.current,C)?c.current:(c.current=C,C)},[f,a]),j=l.useMemo(()=>{const C=b.map(y=>y.tabKey);return yo(d.current,C)?d.current:(d.current=C,C)},[b]);return{chatIdes:r,conversations:f,visibleConversations:b,visibleTabKeys:j,resolveConversationBySessionId:v,resolveConversationByTarget:w}}function JC({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:n,setSearchParams:r}){const a=l.useMemo(()=>{var c;return e||!t?null:((c=n(t))==null?void 0:c.tabKey)??null},[e,n,t]),o=l.useMemo(()=>{var c;return!e||!t?null:((c=n(t))==null?void 0:c.tabKey)??null},[e,n,t]),i=l.useCallback(()=>{t&&r(c=>{const d=new URLSearchParams(c);return d.delete("activeTab"),d},{replace:!0})},[r,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:o,consumeRequestedActiveTab:i}}function QC({ides:e,sendDaemonCommand:t,setToasts:n,resolveConversationByTarget:r}){l.useEffect(()=>{pt.setIdes(e)},[e]),l.useEffect(()=>{pt.setResolveAction((a,o,i)=>{t(a,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const a=pt.onToast(o=>{n(c=>c.some(p=>p.message===o.message&&o.timestamp-p.timestamp<3e3)?c:[...c.slice(-4),{id:o.id,message:o.message,type:o.type,timestamp:o.timestamp,targetKey:o.targetKey,actions:o.actions}]);const i=o.duration||5e3;setTimeout(()=>n(c=>c.filter(d=>d.id!==o.id)),i)});return()=>{a()}},[n]),l.useEffect(()=>{const a=kp.on("status_event",o=>{pt.handleRawEvent(o,"ws")});return()=>{a()}},[]),l.useEffect(()=>{var o;const a=i=>{var h;const c=i.data;if((c==null?void 0:c.type)!=="notification_action"||typeof c.action!="string"||!c.action.startsWith("approval_")||!(c.daemonId||c.targetSessionId||c.targetKey))return;const d=c.targetSessionId||c.targetKey||c.daemonId,p=r(d),u=(p==null?void 0:p.routeId)||c.daemonId;if(!u)return;const m=Number(c.buttonIndex),f=c.button||((h=p==null?void 0:p.modalButtons)==null?void 0:h[m])||"Approve",g=String(f).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),k=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(g);t(u,"resolve_action",{action:k?"approve":"reject",button:f,...Number.isFinite(m)&&{buttonIndex:m},...(p==null?void 0:p.sessionId)&&{targetSessionId:p.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(v=>console.error("[SW Action] approval failed:",v))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",a),()=>{var i;return(i=navigator.serviceWorker)==null?void 0:i.removeEventListener("message",a)}},[r,t])}const XC="adhdev_dashboardLayout_v1",ZC="adhdev_dashboardDockview_v1",ej="adhdev_dashboardDockviewHiddenRestore_v1",Vn={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function dl(e,t){try{const n=localStorage.getItem(e);return n?JSON.parse(n):t}catch{return t}}function tj(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function sm(e){return`${XC}:${e}`}function sj(e){const t=sm(e);return dl(t,null)}function nj(e,t){try{const n=t.groupAssignments.length===0&&t.focusedGroup===0&&Object.keys(t.groupActiveTabIds).length===0&&Object.keys(t.groupTabOrders).length===0&&t.groupSizes.length===0,r=sm(e);if(n){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function nm(e){return`${ZC}:${e}`}function rj(e){const t=nm(e);return dl(t,null)}function aj(e,t){try{const n=nm(e);if(!t){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function rm(e){return`${ej}:${e}`}function oj(e){const t=rm(e);return dl(t,{})}function ij(e,t){try{const n=rm(e);if(Object.keys(t).length===0){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function lj(){return{groupAssignments:[...Vn.groupAssignments],focusedGroup:Vn.focusedGroup,groupActiveTabIds:{...Vn.groupActiveTabIds},groupTabOrders:{...Vn.groupTabOrders},groupSizes:[...Vn.groupSizes]}}function cj(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):t.length===0}function dj(){const[e]=l.useState(()=>tj(typeof window<"u"?window.innerWidth:1280)),[t,n]=l.useState(()=>new Map),[r,a]=l.useState(0),[o,i]=l.useState({}),[c,d]=l.useState({}),[p,u]=l.useState([]),[m,f]=l.useState(()=>typeof window<"u"&&window.innerWidth<768),[g,k]=l.useState(!1),h=l.useCallback(()=>{if(g)return;const A=sj(e)??lj();n(new Map(A.groupAssignments)),a(A.focusedGroup),i(A.groupActiveTabIds),d(A.groupTabOrders),u(A.groupSizes),k(!0)},[g,e]);l.useEffect(()=>{g&&nj(e,{groupAssignments:[...t.entries()],focusedGroup:r,groupActiveTabIds:o,groupTabOrders:c,groupSizes:p})},[g,e,t,r,o,c,p]),l.useEffect(()=>{const A=window.matchMedia("(max-width: 767px)"),M=P=>f(P.matches);return A.addEventListener("change",M),()=>A.removeEventListener("change",M)},[]);const v=l.useCallback(A=>{n(A)},[]),w=l.useCallback(A=>{a(A)},[]),b=l.useCallback(A=>{i(A)},[]),j=l.useCallback(A=>{d(A)},[]),C=l.useCallback(A=>{u(A)},[]),y=l.useCallback(A=>{w(A)},[w]),x=l.useCallback((A,M)=>{i(P=>(P[A]??null)===(M??null)?P:{...P,[A]:M})},[]),N=l.useCallback((A,M)=>{d(P=>{const D=P[A];return cj(D,M)?P:{...P,[A]:M}})},[]),S=l.useCallback((A,M)=>{const P=M.get(A)??0;return x(P,A),y(P),P},[y,x]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:v,focusedGroup:r,updateFocusedGroup:w,focusGroup:y,groupActiveTabIds:o,updateGroupActiveTabIds:b,setGroupActiveTab:x,groupTabOrders:c,updateGroupTabOrders:j,setGroupTabOrder:N,groupSizes:p,updateGroupSizes:C,isMobile:m,hasHydratedStoredLayout:g,hydrateStoredLayout:h,focusConversationTab:S}}function uj(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0],r=$a(t);return typeof(n==null?void 0:n.id)=="string"&&r.includes(n.id)}function pj({urlActiveTab:e,conversations:t,resolveConversationBySessionId:n,normalizedGroupAssignments:r,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:i,setSearchParams:c,historyModalOpen:d,activeConv:p,isRefreshingHistory:u,ides:m,handleRefreshHistory:f}){const g=l.useRef(!1),k=l.useRef(!1),h=l.useRef(null),v=l.useRef(!1);l.useEffect(()=>{if(!e||g.current||t.length===0)return;if(!a){o();return}const w=n(e);w&&(i(w.tabKey,r),g.current=!0,k.current=!0,h.current!=null&&(window.clearTimeout(h.current),h.current=null),c(b=>{const j=new URLSearchParams(b);return j.delete("activeTab"),j},{replace:!0}))},[e,t,n,r,a,o,i,c]),l.useEffect(()=>{if(!(k.current||a)&&t.length!==0){if(!e){o(),k.current=!0;return}if(g.current){k.current=!0;return}if(h.current==null)return h.current=window.setTimeout(()=>{h.current=null,!(k.current||a)&&(o(),k.current=!0)},1500),()=>{h.current!=null&&(window.clearTimeout(h.current),h.current=null)}}},[e,t.length,a,o]),l.useEffect(()=>{if(!d){v.current=!1;return}if(!p||v.current||u)return;const w=m.find(b=>b.id===p.routeId);w&&(!w.chats||w.chats.length===0||uj(w.chats,p))&&(v.current=!0,f())},[d,p,u,m,f])}function wo(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0];if((n==null?void 0:n.active)===!0)return!0;const r=$a(t);return typeof(n==null?void 0:n.id)=="string"&&r.includes(n.id)}function am({sendDaemonCommand:e,activeConv:t,chats:n,updateRouteChats:r,setToasts:a,setClearedTabs:o}){const[i,c]=l.useState(!1),[d,p]=l.useState(!1),u=l.useCallback(async k=>{try{await e("standalone","launch_ide",{ideType:k,enableCdp:!0})}catch(h){console.error("Launch failed",h)}},[e]),m=l.useCallback(async(k,h)=>{try{const v=k||(t==null?void 0:t.daemonId)||"",w=await e(v,"switch_chat",{id:h,sessionId:h,...Ys(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"?fn(a,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?fn(a,`⚠️ Switch error: ${b}`):fn(a,"⚠️ Session switch failed")}catch(v){console.error("Switch failed",v),fn(a,`❌ Switch failed: ${v.message||"connection error"}`)}},[t,e,a]),f=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const k=Js(t);await e(k,"new_chat",{...Ys(t)}),nk(k,t.sessionId,$a(t)[0]),o(h=>({...h,[t.tabKey]:Date.now()}))}catch(k){console.error("New chat failed",k)}finally{c(!1)}}},[t,i,e,o]),g=l.useCallback(async()=>{var k,h;if(!(!t||d)){p(!0);try{const v=Js(t),w=async()=>e(v,"list_chats",{forceExpand:!0,...Ys(t)});let b=await w(),j=(b==null?void 0:b.chats)||((k=b==null?void 0:b.result)==null?void 0:k.chats);wo(j,t)&&(await new Promise(C=>setTimeout(C,450)),b=await w(),j=(b==null?void 0:b.chats)||((h=b==null?void 0:b.result)==null?void 0:h.chats)),b!=null&&b.success&&Array.isArray(j)&&(r(t.routeId,j),wo(j,t)&&!wo(n,t)&&fn(a,"⚠️ History dialog did not fully open — try once more"))}catch(v){console.error("Refresh history failed",v)}finally{p(!1)}}},[t,n,d,e,r,a]);return{isCreatingChat:i,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:m,handleNewChat:f,handleRefreshHistory:g}}function mj(e,t){if(e.size!==t.size)return!1;for(const[n,r]of e)if(t.get(n)!==r)return!1;return!0}function hj(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function Kc(e,t){const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(a=>t[Number(a)]===e[Number(a)])}function Br(e,t){const n=new Set(t),r=t.length>0?[0]:[];for(const[i,c]of e)!n.has(i)||c<=0||r.includes(c)||r.push(c);r.sort((i,c)=>i-c);const a={};r.forEach((i,c)=>{a[i]=c}),r.length===0&&(a[0]=0);const o=new Map;for(const[i,c]of e){if(!n.has(i)||c<=0)continue;const d=a[c];typeof d=="number"&&d>0&&o.set(i,d)}return{assignments:o,groupCount:Math.max(1,r.length),mapping:a,usedGroups:r}}function Vc(e,t){const n={};for(const[r,a]of Object.entries(e)){const o=t[Number(r)];typeof o=="number"&&(n[o]=a)}return n}function fj(e,t,n){if(t.length===0)return 0;if(typeof n[e]=="number")return n[e];const r=[...t].reverse().find(a=>a<e)??t[0];return n[r]??0}function bj(e,t,n){if(t.length<=1)return[];const r=t.map(i=>e[i]).filter(i=>Number.isFinite(i)),a=r.length===t.length?r:Array(n).fill(100/n),o=a.reduce((i,c)=>i+c,0);return o>0?a.map(i=>i/o*100):Array(n).fill(100/n)}function Yc(e,t){const n={};for(const[r,a]of Object.entries(e)){const o=Number(r);n[o>=t?o+1:o]=a}return n}function Jc(e){return Array(e).fill(100/e)}function gj({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:n,updateGroupActiveTabIds:r,updateGroupTabOrders:a,groupSizes:o,updateGroupSizes:i,isMobile:c,visibleConversations:d,visibleTabKeys:p}){const u=l.useRef(null),m=l.useMemo(()=>Br(e,p),[e,p]),f=m.assignments,g=l.useMemo(()=>c?1:m.groupCount,[m.groupCount,c]),k=g>1,h=l.useCallback((y,x)=>{t(N=>{const S=new Map(Br(N,p).assignments);return x===0?S.delete(y):S.set(y,x),S}),r(N=>({...N,[x]:y})),n(x)},[t,p,r,n]),v=l.useCallback(y=>{t(x=>{const N=Br(x,p).assignments,S=new Map;for(const[A,M]of N)M!==y&&(M>y?S.set(A,M-1):S.set(A,M));return S}),i(x=>{if(x.length<=1)return[];const N=[...x];N.splice(y,1);const S=N.reduce((A,M)=>A+M,0);return S>0?N.map(A=>A/S*100):[]}),n(0)},[t,p,i,n]),w=l.useCallback((y,x)=>{x.preventDefault();const N=u.current;if(!N)return;const S=x.clientX,A=N.offsetWidth,M=o.length===g?[...o]:Jc(g),P=I=>{const W=(I.clientX-S)/A*100,H=[...M];H[y]=Math.max(15,M[y]+W),H[y+1]=Math.max(15,M[y+1]-W),i(H)},D=()=>{document.removeEventListener("mousemove",P),document.removeEventListener("mouseup",D),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",P),document.addEventListener("mouseup",D)},[o,g,i]),b=l.useCallback((y,x,N)=>{if(g>=4)return;const S=N==="left"?x:x+1;t(A=>{const M=Br(A,p).assignments,P=new Map;for(const D of d){const I=M.get(D.tabKey)??0,_=I>=S?I+1:I;_>0&&P.set(D.tabKey,_)}return S>0&&P.set(y,S),P}),i(A=>{const M=A.length===g?[...A]:Jc(g),P=M[x]??100/g,D=Math.max(15,P/2),I=Math.max(15,P/2),_=[...M];_[x]=D,_.splice(S,0,I);const W=_.reduce((H,L)=>H+L,0);return _.map(H=>H/W*100)}),r(A=>{const M=Yc(A,S);return M[S]=y,M}),a(A=>{const M=Yc(A,S);return M[S]=[y],M}),n(S)},[g,t,p,d,i,r,a,n]);l.useEffect(()=>{mj(e,f)||t(f)},[e,f,t]),l.useEffect(()=>{const{mapping:y,usedGroups:x}=m;r(N=>{const S=Vc(N,y);return Kc(N,S)?N:S}),a(N=>{const S=Vc(N,y);return Kc(N,S)?N:S}),n(N=>{const S=c?0:fj(N,x,y);return N===S?N:S}),i(N=>{const S=c?[]:bj(N,x,m.groupCount);return hj(N,S)?N:S})},[m,c,r,a,n,i]);const j=l.useMemo(()=>{const y=Array.from({length:g},()=>[]);for(const x of d){const N=f.get(x.tabKey)??0,S=Math.min(N,g-1);y[S].push(x)}return y},[d,f,g]),C=l.useCallback(()=>{t(new Map),n(0)},[t,n]);return{containerRef:u,normalizedGroupAssignments:f,numGroups:g,isSplitMode:k,groupedConvs:j,moveTabToGroup:h,closeGroup:v,handleResizeStart:w,splitTabRelative:b,clearAllSplits:C}}function ko(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 xj(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 Or(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function ul(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},n=ko(t.channel)||ko(e.updateChannel)||ko(e.releaseChannel)||void 0,r=xj(t.npmTag)||(n==="preview"?"next":n==="stable"?"latest":void 0),a=Or(t.targetVersion)||Or(e.serverVersion)||void 0,o=Or(t.minVersion)||void 0,i=Or(t.updateCommand)||(n?`adhdev update --channel ${n}`:void 0);return{...n?{channel:n}:{},...r?{npmTag:r}:{},...a?{targetVersion:a}:{},...o?{minVersion:o}:{},...i?{updateCommand:i}:{}}}function xn(e,t=null){return ul(e).targetVersion||t}function om(e){return ul(e).channel||null}function im(e){const t=ul(e);return{...t.channel?{channel:t.channel}:{},...t.npmTag?{npmTag:t.npmTag}:{},...t.targetVersion?{targetVersion:t.targetVersion}:{},...Object.keys(t).length>0?{updatePolicy:t}:{}}}function vj({ides:e,sendDaemonCommand:t}){const n="1.0.18",r=l.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:ol(m,xn(m,n))).sort((m,f)=>Number(lr(f,xn(f,n)))-Number(lr(m,xn(m,n)))),[n,e]),a=l.useMemo(()=>r.some(m=>lr(m,xn(m,n))),[n,r]),o=l.useMemo(()=>r.map(m=>xn(m,n)).find(m=>typeof m=="string"&&m.trim().length>0)||n,[n,r]),[i,c]=l.useState(!1),[d,p]=l.useState({}),u=l.useCallback(async m=>{var g,k;const f=e.find(h=>h.id===m);if(f){p(h=>({...h,[m]:"upgrading"}));try{const h=await t(m,"daemon_upgrade",im(f));(g=h==null?void 0:h.result)!=null&&g.upgraded||(k=h==null?void 0:h.result)!=null&&k.success?p(v=>({...v,[m]:"done"})):p(v=>({...v,[m]:"error"}))}catch{p(h=>({...h,[m]:"error"}))}}},[e,t]);return{versionMismatchDaemons:r,hasRequiredVersionDaemons:a,targetVersion:o,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:u}}const lm=80;function aa(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function yj(e){return{...e,createdAt:aa(e.createdAt),updatedAt:aa(e.updatedAt,e.createdAt),lastEventAt:aa(e.lastEventAt,e.updatedAt||e.createdAt)}}function wj(e){const t=Ru(e);return t==="unknown:"?e.id:t}function kj(e){return[e.type,Lu(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Sj(e,t=lm){const n=new Map;for(const r of e){if(r.deletedAt)continue;const a=wj(r),o=n.get(a);if(!o){n.set(a,r);continue}(r.updatedAt>o.updatedAt||r.updatedAt===o.updatedAt&&r.createdAt>o.createdAt)&&n.set(a,r)}return Array.from(n.values()).sort((r,a)=>{const o=a.updatedAt-r.updatedAt;return o!==0?o:a.createdAt-r.createdAt}).slice(0,Math.max(0,t))}function Cj(e,t){const n=Date.now(),r=[];for(const a of e){const o=a.sessionId?t.get(a.sessionId):void 0;if(o!=null&&o.surfaceHidden||o!=null&&o.muted)continue;const i=_a(a,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const d=aa(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,n),p=kj({type:c,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,lastMessageHash:a.lastMessageHash,lastMessageAt:a.lastMessageAt,lastUpdated:(o==null?void 0:o.lastUpdated)||a.lastUpdated});r.push(yj({id:p,dedupKey:p,type:c,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:ep(a),preview:f0(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return Sj(r)}function jj(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function Nj(e){const{conversations:t,liveSessionInboxState:n,maxItems:r=lm}=e,a=l.useMemo(()=>Cj(t,n).slice(0,Math.max(0,r)),[t,n,r]),o=l.useMemo(()=>jj(a),[a]);return{notifications:a,unreadCount:o}}function Aj({notifications:e,sendDaemonCommand:t}){const n=l.useCallback(o=>{const i=e.find(d=>d.id===o),c=Math.max(Date.now(),(i==null?void 0:i.updatedAt)||0);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_session_seen",{sessionId:i.sessionId,seenAt:c}).catch(()=>{})},[e,t]),r=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_notification_unread",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]),a=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"delete_notification",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:n,handleMarkDashboardNotificationUnread:r,handleDeleteDashboardNotification:a}}function pl(...e){const t=new Set,n=[],r=a=>{const o=typeof a=="string"?a.trim():"";if(!o)return;const i=o.toLowerCase();t.has(i)||(t.add(i),n.push(o))};for(const a of e){if(Array.isArray(a)){for(const o of a)r(o);continue}r(a)}return n}function Mj(e){const t=e.trim();if(!t)return null;if(t.startsWith("~"))return t;if(/^[A-Za-z]:$/.test(t))return`${t[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(t))return`${t[0].toUpperCase()}:${t.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(t))return`${t[0].toUpperCase()}:\\${t.slice(2).replace(/[\\/]+/g,"\\")}`;const n=t.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(n){const r=n[1].toUpperCase(),a=(n[2]||"").replace(/[\\/]+/g,"\\");return a?`${r}:\\${a}`:`${r}:\\`}return null}function ml(e,t=[]){if(e==="win32"){for(const n of t){if(typeof n!="string")continue;const r=Mj(n);if(r)return r}return"C:\\"}for(const n of t){const r=typeof n=="string"?n.trim():"";if(r)return r}return"~"}function Tj(e){const t=e.replace(/[\\/]+$/,"");if(!t||t==="/"||/^[A-Za-z]:$/.test(t))return null;const n=t.includes("\\")?"\\":"/",r=t.split(/[\\/]/);return/^[A-Za-z]:$/.test(r[0]||"")?r.length<=2?`${r[0]}\\`:r.slice(0,-1).join("\\"):r.length<=2?n:r.slice(0,-1).join(n)||n}function Ij(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function hl(e,t,n){const r=await e(t,"file_list_browse",{path:n}),a=Ij(r);if(!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||(r==null?void 0:r.error)||"Could not browse folder");const o=typeof(a==null?void 0:a.path)=="string"?a.path:n,i=o.includes("\\")?"\\":"/",c=(p,u)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${u}`:p==="/"||p==="\\"?`${i}${u}`:`${p.replace(/[\\/]+$/,"")}${i}${u}`,d=Array.isArray(a==null?void 0:a.files)?a.files.filter(p=>(p==null?void 0:p.type)==="directory"&&typeof(p==null?void 0:p.name)=="string").map(p=>({name:p.name,path:typeof(p==null?void 0:p.path)=="string"&&p.path.trim()?p.path:c(o,p.name)})).sort((p,u)=>p.name.localeCompare(u.name)):[];return{path:o,directories:d}}function Qc(e,t){const n=t.meshId||"",r={meshId:n,workspace:t.workspace||"",serverName:t.serverName||"adhdev-mesh",adhdevMcpCommand:t.adhdevMcpCommand||"adhdev-mcp",adhdevMcpArgs:t.adhdevMcpArgs||`mcp --mode ipc --repo-mesh ${n}`};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand|adhdevMcpArgs)\s*\}\}/g,(a,o)=>r[o]||"")}function cm(e,t={}){const n=e==null?void 0:e.mcpConfig;if((n==null?void 0:n.mode)!=="manual")return null;const a=Qc(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"}).trim();return!a.includes(`
|
|
70
|
-
`)&&!a.startsWith("{")?null:{serverName:n.serverName||"adhdev-mesh",configFormat:n.format,configPathCommand:n.configPathCommand,requiresRestart:n.requiresRestart===!0,instructions:n.instructions||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:Qc(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"})}}function Dj(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.instructions=="string"?t.instructions:"",r=typeof t.template=="string"?t.template:"";return!n&&!r?null:{serverName:typeof t.serverName=="string"?t.serverName:void 0,configFormat:typeof t.configFormat=="string"?t.configFormat:void 0,configPathCommand:typeof t.configPathCommand=="string"?t.configPathCommand:void 0,requiresRestart:t.requiresRestart===!0,instructions:n||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:r}}function xr(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function dm(e){return Ha(e)||e.tabKey||e.routeId||null}function um(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"",n=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"",r=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"",a=e.conversations.find(o=>{if(r&&o.routeId!==r)return!1;const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey].map(c=>typeof c=="string"?c.trim():"").filter(Boolean);return!!(t&&i.includes(t)||n&&i.includes(n)||r&&o.routeId===r)});if(a!=null&&a.tabKey)return a.tabKey;if(r){const o=ps(e.conversations,r)||e.conversations.find(i=>i.routeId===r);if(o!=null&&o.tabKey)return o.tabKey}return t||n||r||null}function Ls(e){return String(e||"").trim()}function pm(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Ma(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Pj(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function Lj(e,t){const n=Ls(e.providerSessionId),r=Ls(e.targetSessionId),a=t.find(o=>{const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(Ls).filter(Boolean);return!!(n&&i.includes(n)||r&&i.includes(r))});return a?a.tabKey:r||n||null}function Rj(e,t,n){if(t.event!=="agent:generating_completed")return null;const r=pm(t.daemonId);if(r&&r!==e.machineId)return null;const a=Ls(t.providerType);if(e.providerType&&a!==e.providerType)return null;const o=Ls(e.resumeSessionId),i=Ls(e.launchedSessionId),c=Ls(t.providerSessionId),d=Ls(t.targetSessionId);if(o&&o!==c&&o!==d||i&&i!==c&&i!==d)return null;const p=Ma(e.workspacePath);if(p){const u=Ma(t.workspaceName);if(u&&!Pj(u,p))return null}return Lj(t,n)}function Xc(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Ej({ides:e,conversations:t,onOpenSession:n}){const[r,a]=l.useState(null),o=l.useRef(null),i=l.useCallback(()=>{o.current=null,a(null)},[]),c=l.useCallback(d=>{o.current=d,a(d)},[]);return l.useEffect(()=>{if(!r)return;const d=Ma(r.workspacePath),p=e.find(m=>{var v,w,b,j;if(!m||m.type==="adhdev-daemon"||pm(m.daemonId||m.id)!==r.machineId||(fr(m)?"cli":kn(m)?"acp":"ide")!==r.kind)return!1;const k=String(m.agentType||m.type||"");if(r.providerType&&k!==r.providerType)return!1;if(r.resumeSessionId)return String(m.providerSessionId||"")===r.resumeSessionId;if(r.launchedSessionId){const C=String(r.launchedSessionId||"");return[m.providerSessionId,m.sessionId,m.instanceId,m.id].map(x=>String(x||"")).filter(Boolean).includes(C)}if(d){const C=Ma(m.workspace||m.runtimeWorkspaceLabel);return C?C===d:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((j=(b=(w=(v=m.activeChat)==null?void 0:v.messages)==null?void 0:w.at)==null?void 0:b.call(w,-1))==null?void 0:j.timestamp)||0)>=r.startedAt-5e3});if(!p)return;const u=um({entrySessionId:p.sessionId,entryInstanceId:p.instanceId,entryRouteId:p.id,conversations:t});u&&(i(),n(u))},[i,t,e,n,r]),l.useEffect(()=>pt.onStatusEvent(d=>{const p=o.current;if(!p)return;const u=Rj(p,d,t);u&&(i(),n(u))}),[i,t,n]),l.useEffect(()=>{if(!r)return;const d=window.setTimeout(()=>{a(p=>!p||p.startedAt!==r.startedAt?p:(o.current=null,null))},45e3);return()=>window.clearTimeout(d)},[r]),{trackPendingLaunch:c}}function _j(e,t){var r,a,o,i;const n={cliType:e};return(r=t==null?void 0:t.workspacePath)!=null&&r.trim()?n.dir=t.workspacePath.trim():t!=null&&t.workspaceId?n.workspaceId=t.workspaceId:t!=null&&t.useHome&&(n.useHome=!0),(a=t==null?void 0:t.resumeSessionId)!=null&&a.trim()&&(n.resumeSessionId=t.resumeSessionId.trim()),Array.isArray(t==null?void 0:t.cliArgs)&&t.cliArgs.length>0&&(n.cliArgs=t.cliArgs),(o=t==null?void 0:t.initialModel)!=null&&o.trim()&&(n.initialModel=t.initialModel.trim()),(i=t==null?void 0:t.initialThinkingLevel)!=null&&i.trim()&&(n.initialThinkingLevel=t.initialThinkingLevel.trim()),t!=null&&t.settings&&(n.settings=t.settings),n}function $j({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:n,activeConv:r,ides:a,setCliViewModeOverrides:o}){const i=Ji(),{launchCli:c}=Pa(),d=l.useCallback(async(v,w)=>hl(e,v,w),[e]),p=l.useCallback(async(v,w)=>{if(!w.trim())return{ok:!1,error:"Choose a workspace path first."};try{const b=await e(v,"workspace_add",{path:w.trim()});return b!=null&&b.success?{ok:!0}:{ok:!1,error:(b==null?void 0:b.error)||"Could not save workspace"}}catch(b){return{ok:!1,error:b instanceof Error?b.message:"Could not save workspace"}}},[e]),u=l.useCallback(async(v,w,b)=>{var j;try{const C={ideType:w,enableCdp:!0};(j=b==null?void 0:b.workspacePath)!=null&&j.trim()&&(C.workspace=b.workspacePath.trim());const y=await e(v,"launch_ide",C);return!(y!=null&&y.success)&&(y==null?void 0:y.success)!==void 0?{ok:!1,error:(y==null?void 0:y.error)||"Could not launch IDE"}:(t({machineId:v,kind:"ide",providerType:w,workspacePath:(b==null?void 0:b.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(C){return{ok:!1,error:C instanceof Error?C.message:"Could not launch IDE"}}},[e,t]),m=l.useCallback(async(v,w,b,j)=>{const C=Date.now();try{const y=_j(b,j),x=await c(v,y),N=(x==null?void 0:x.result)||x,S=(N==null?void 0:N.sessionId)||(N==null?void 0:N.id);return x!=null&&x.success&&S?(t({machineId:v,kind:w,providerType:b,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,launchedSessionId:S,startedAt:C}),{ok:!0}):x!=null&&x.success?(t({machineId:v,kind:w,providerType:b,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:(x==null?void 0:x.error)||(N==null?void 0:N.error)||`Could not launch ${w.toUpperCase()} session`,code:(x==null?void 0:x.code)||(N==null?void 0:N.code)||void 0}}catch(y){return Xc(y)?(t({machineId:v,kind:w,providerType:b,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:y instanceof Error?y.message:`Could not launch ${w.toUpperCase()} session`}}},[c,e,t]),f=l.useCallback(async v=>{var w;if(i!=null&&i.listMeshes)return i.listMeshes(v);if(!v)return[];try{const b=await e(v,"list_meshes",{}),j=(b==null?void 0:b.result)??b;if((j==null?void 0:j.success)===!1)throw new Error((j==null?void 0:j.error)||"Could not load meshes");return(Array.isArray(j==null?void 0:j.meshes)?j.meshes:Array.isArray((w=j==null?void 0:j.result)==null?void 0:w.meshes)?j.result.meshes:[]).map(y=>{var x;return{id:String((y==null?void 0:y.id)||""),name:String((y==null?void 0:y.name)||(y==null?void 0:y.id)||"Untitled mesh"),repoIdentity:(y==null?void 0:y.repoIdentity)||(y==null?void 0:y.repo_identity)||null,workspace:Array.isArray(y==null?void 0:y.nodes)&&y.nodes.length>0?String(((x=y.nodes[0])==null?void 0:x.workspace)||""):null,nodesCount:Array.isArray(y==null?void 0:y.nodes)?y.nodes.length:void 0,status:(y==null?void 0:y.status)||null}}).filter(y=>y.id)}catch(b){throw console.error("List meshes failed",b),b}},[i,e]),g=l.useCallback(async(v,w,b,j)=>{var y,x;if(!w.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(v,w,b,j);const C=Date.now();try{const N={meshId:w.trim()};b.trim()&&(N.cliType=b.trim());const S=(y=j==null?void 0:j.initialModel)==null?void 0:y.trim(),A=(x=j==null?void 0:j.initialThinkingLevel)==null?void 0:x.trim();S&&(N.initialModel=S),A&&(N.initialThinkingLevel=A);const M=await e(v,"launch_mesh_coordinator",N),P=(M==null?void 0:M.result)??M;if((P==null?void 0:P.success)===!1||(M==null?void 0:M.success)===!1){const I=String((P==null?void 0:P.code)||(M==null?void 0:M.code)||""),_=Dj((P==null?void 0:P.meshCoordinatorSetup)||(P==null?void 0:P.manualSetup)||(M==null?void 0:M.meshCoordinatorSetup)||(M==null?void 0:M.manualSetup));return{ok:!1,error:(P==null?void 0:P.error)||(M==null?void 0:M.error)||"Could not launch mesh coordinator",code:I||void 0,manualSetup:_}}const D=(P==null?void 0:P.sessionId)||(P==null?void 0:P.id);return D?n(D):t({machineId:v,kind:"cli",providerType:(P==null?void 0:P.cliType)||b.trim()||void 0,workspacePath:(P==null?void 0:P.workspace)||null,startedAt:C}),{ok:!0}}catch(N){return Xc(N)?(t({machineId:v,kind:"cli",providerType:b.trim()||void 0,startedAt:C}),{ok:!0}):{ok:!1,error:N instanceof Error?N.message:"Could not launch mesh coordinator"}}},[i,n,e,t]),k=l.useCallback(async(v,w)=>{if(!v||!w)return[];try{const b=await e(v,"list_saved_sessions",{providerType:w,kind:"cli",limit:30}),j=(b==null?void 0:b.result)??b;return Array.isArray(j==null?void 0:j.sessions)?j.sessions:[]}catch(b){return console.error("List saved sessions failed",b),[]}},[e]),h=l.useCallback(async v=>{await Zp({conversation:r,mode:v,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[r,a,e,o]);return{handleBrowseMachineDirectory:d,handleSaveMachineWorkspace:p,handleLaunchMachineIde:u,handleLaunchMachineProvider:m,handleListMachineMeshes:f,handleLaunchMeshCoordinator:g,handleListMachineSavedSessions:k,setActiveCliViewMode:h}}function Hj(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 Fj(e,t,n=Date.now()){return!e||!Hj(t)?null:{tabKey:e,nonce:n}}function Bj({isMobile:e,conversations:t,visibleConversations:n,groupActiveTabIds:r,focusedGroup:a,groupedConvs:o,setSearchParams:i}){const[c,d]=l.useState(null),[p,u]=l.useState(null),m=l.useMemo(()=>{var v,w;if(!e){if(c){const b=t.find(j=>j.tabKey===c);if(b)return b}return n[0]}const h=r[a];if(h){const b=t.find(j=>j.tabKey===h);if(b)return b}return((v=o[a])==null?void 0:v[0])||((w=o[0])==null?void 0:w[0])},[t,c,a,r,o,e,n]),f=l.useCallback(h=>{d(h)},[]),g=l.useCallback(h=>{d(h.tabKey),i(v=>{const w=new URLSearchParams(v),b=g0(h);return b?w.set("activeTab",b):w.delete("activeTab"),w},{replace:!0})},[i]),k=l.useCallback((h,v)=>{const w=Fj(h,v);w&&u(w)},[]);return{activeConv:m,openDesktopConversation:g,requestScrollToBottom:k,scrollToBottomRequest:p,setDesktopActiveTab:f}}function Oj(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 Wj(e){const t=String(e.liveState.completionMarker||""),n=String(e.liveState.seenCompletionMarker||""),r=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,o=[e.tabKey,e.historySessionId||"",t,n,r,a?"1":"0"].join(":");return{shouldMarkSeen:!!(r==="task_complete"&&a&&(!t||t!==n)),autoReadKey:o,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function Uj({activeConv:e,isMobile:t,liveSessionInboxState:n,sendDaemonCommand:r}){const a=l.useRef(null),o=l.useRef(null),i=l.useRef(null),c=l.useRef(null),d=l.useRef(null);l.useEffect(()=>{const p=()=>{i.current&&(clearTimeout(i.current),i.current=null),c.current&&(clearTimeout(c.current),c.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),o.current=null};if(t){p(),a.current=null;return}if(!(e!=null&&e.sessionId)){p(),a.current=null;return}const u=Hs(e,n),m=Wj({tabKey:e.tabKey,historySessionId:Ha(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:en(e),liveState:u}),f=m.autoReadKey,g=Oj({autoReadKey:f,shouldMarkSeen:m.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!m.shouldMarkSeen){g.shouldCancelPending&&p(),a.current=f;return}if(!g.shouldSchedule)return;g.shouldCancelPending&&p();const k=()=>{if(document.visibilityState!=="visible"||a.current===f)return;a.current=f,o.current=null,i.current=null,c.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const v=m.readAt;r(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:v,completionMarker:m.completionMarker}).catch(()=>{})};if(o.current=g.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(k,1500);const v=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};d.current=v,document.addEventListener("visibilitychange",v);return}const h=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(k,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=h,document.addEventListener("visibilitychange",h)},[e,t,n,r]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current),c.current&&clearTimeout(c.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function So(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 Gj({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:n,ides:r,sendDaemonCommand:a,updateRouteChats:o,setToasts:i,setClearedTabs:c,setSearchParams:d}){var O;const{launchCli:p}=Pa(),[u,m]=l.useState(!1),[f,g]=l.useState([]),[k,h]=l.useState(()=>Wt()),[v,w]=l.useState(!1),[b,j]=l.useState(null),C=l.useRef(null),y=l.useMemo(()=>n||t||e,[e,n,t]),x=!!y&&ut(y)&&!dt(y),N=l.useMemo(()=>{if(!y||!x)return null;const E=y.daemonId||y.routeId||"",T=ks(y),$=So(y);return`${E}:${T}:${y.providerSessionId||""}:${$}`},[y,x]),S=l.useMemo(()=>!y||!x?"":So(y),[y,x]),{isCreatingChat:A,isRefreshingHistory:M,handleSwitchSession:P,handleNewChat:D,handleRefreshHistory:I}=am({sendDaemonCommand:a,activeConv:y,chats:(O=r.find(E=>E.id===(y==null?void 0:y.routeId)))==null?void 0:O.chats,updateRouteChats:o,setToasts:i,setClearedTabs:c}),_=l.useCallback(()=>{m(!0)},[]),W=l.useCallback(()=>{m(!1)},[]),H=l.useCallback(async()=>{if(!(!y||!x||v)){w(!0);try{const E=y.daemonId||y.routeId,T=ks(y),$=So(y),R=await a(E,"list_saved_sessions",{agentType:T,providerType:T,kind:"cli",limit:50,...y.providerSessionId?{providerSessionId:y.providerSessionId}:{},...$?{workspace:$}:{}}),G=(R==null?void 0:R.result)??R;g(Array.isArray(G==null?void 0:G.sessions)?G.sessions:[])}catch(E){console.error("Refresh saved sessions failed",E),g([])}finally{w(!1)}}},[y,v,x,a]);l.useEffect(()=>{if(!u){C.current=null;return}if(!x){C.current=null,g([]),w(!1);return}!N||v||C.current!==N&&(C.current=N,H())},[H,u,v,x,N]);const L=l.useCallback(async E=>{if(!y||!x||!E.providerSessionId||!E.workspace)return;const T=y.daemonId||y.routeId,$=ks(y);try{j(E.providerSessionId);const R=await p(T,{cliType:$,dir:E.workspace,resumeSessionId:E.providerSessionId,initialModel:Fu(E.summaryMetadata,"model",{preferShortValue:!0})||void 0}),G=(R==null?void 0:R.result)??R,Q=typeof(G==null?void 0:G.sessionId)=="string"?G.sessionId:typeof(G==null?void 0:G.id)=="string"?G.id:"";Q&&d(re=>{const J=new URLSearchParams(re);return J.set("activeTab",Q),J},{replace:!0}),W()}catch(R){console.error("Resume saved session failed",R)}finally{j(null)}},[W,y,x,a,d]);return{historyModalOpen:u,openHistoryModal:_,closeHistoryModal:W,historyTargetConv:y,isSavedSessionHistoryTarget:x,isHistoryCreatingChat:A,isHistoryRefreshingHistory:M,handleHistorySwitchSession:P,handleHistoryNewChat:D,handleHistoryRefresh:I,savedHistorySessions:f,savedHistoryFilters:k,setSavedHistoryFilters:h,missingWorkspaceResumePath:S,isSavedHistoryLoading:v,resumingSavedHistorySessionId:b,handleRefreshSavedHistory:H,handleResumeSavedHistorySession:L}}function qj({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}){const[d,p]=l.useState(null),[u,m]=l.useState(null),f=l.useMemo(()=>{if(e||!r)return null;const w=c(r);return w&&!ut(w)&&!dt(w)?w:null},[e,r,c]),g=l.useMemo(()=>{const w=d==null?void 0:d.routeId;if(!w)return null;const b=d!=null&&d.tabKey?o.find(j=>j.tabKey===d.tabKey):a?o.find(j=>j.tabKey===a):null;return(b==null?void 0:b.routeId)===w?b:ps(o,w)},[o,d,a]),k=l.useMemo(()=>{if(g)return i.find(w=>w.id===g.routeId)},[i,g]);l.useEffect(()=>{f&&(p({routeId:f.routeId,tabKey:mc(f)}),m(f),n({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,n,f]);const h=l.useCallback(w=>{w&&(p({routeId:w.routeId,tabKey:mc(w)}),m(w))},[]),v=l.useCallback(()=>{p(null),m(null)},[]);return{remoteDialogConv:g,remoteDialogIdeEntry:k,remoteDialogActiveConv:u,setRemoteDialogActiveConv:m,openRemoteDialog:h,closeRemoteDialog:v}}function zj({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c,activeConv:d,sendDaemonCommand:p}){const{remoteDialogConv:u,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:g,openRemoteDialog:k,closeRemoteDialog:h}=qj({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}),[v,w]=l.useState(!1),[b,j]=l.useState(null),C=l.useCallback(async N=>{const S=N||d;!S||!ut(S)&&!dt(S)||(j(S),w(!0))},[d]),y=l.useCallback(()=>{w(!1),j(null)},[]),x=l.useCallback(async N=>{const S=b||d;if(!S||!ut(S)&&!dt(S)){y();return}w(!1);try{const A=ks(S),M=S.routeId||S.daemonId||"";await p(M,"stop_cli",{cliType:A,targetSessionId:S.sessionId,mode:N,...Oa(S)})}catch(A){console.error("Stop CLI failed:",A)}finally{j(null)}},[d,y,b,p]);return{remoteDialogConv:u,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:g,openRemoteDialog:k,closeRemoteDialog:h,cliStopDialogOpen:v,cliStopTargetConv:b,requestCliStop:C,cancelCliStop:y,confirmCliStop:x}}function Co(e,t=!0){return(e??!0)&&t}const fl=l.memo(function({activeConv:t,clearToken:n,isCliTerminal:r,ideEntry:a,terminalRef:o,handleModalButton:i,handleRelaunch:c,handleSendChat:d,handleForceSendChat:p,isSendingChat:u,sendFeedbackMessage:m=null,handleFocusAgent:f,isFocusingAgent:g,actionLogs:k,userName:h,scrollToBottomRequestNonce:v,isInputActive:w=!0,isVisible:b=!0}){const j=r,C=!r,y=Co(b,j),x=Co(b,C),N=Co(b),S=Jp(t),A=S.status||S.modalMessage||S.modalButtons?{...t,...S.status?{status:S.status}:{},...S.modalMessage!==void 0?{modalMessage:S.modalMessage}:{},...S.modalButtons!==void 0?{modalButtons:S.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(Iu,{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(nn,{size:14})}),s.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),s.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:c,children:"Relaunch with CDP"})]})}):null,A.transport==="pty"?s.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[s.jsx("div",{"aria-hidden":!r,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:j?"visible":"hidden",pointerEvents:j?"auto":"none"},children:s.jsx(Yk,{activeConv:A,clearToken:n,terminalRef:o,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:m,isVisible:y,isInputActive:w&&y})}),s.jsx("div",{"aria-hidden":r,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:C?"visible":"hidden",pointerEvents:C?"auto":"none"},children:s.jsx(bi,{activeConv:A,ideEntry:a,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:k,userName:h,scrollToBottomRequestNonce:v,isInputActive:w&&x,isVisible:x})})]}):s.jsx(bi,{activeConv:A,ideEntry:a,handleSendChat:d,handleForceSendChat:p,isSendingChat:u,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:k,userName:h,scrollToBottomRequestNonce:v,isInputActive:w&&N,isVisible:N})]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.handleModalButton===t.handleModalButton&&e.handleRelaunch===t.handleRelaunch&&e.handleSendChat===t.handleSendChat&&e.handleForceSendChat===t.handleForceSendChat&&e.isSendingChat===t.isSendingChat&&e.sendFeedbackMessage===t.sendFeedbackMessage&&e.handleFocusAgent===t.handleFocusAgent&&e.isFocusingAgent===t.isFocusingAgent&&e.actionLogs===t.actionLogs&&e.userName===t.userName&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isInputActive===t.isInputActive&&e.isVisible===t.isVisible);function Kj({conversation:e,className:t="",onOpenNativeConversation:n,onOpenMachine:r,interactive:a=!0,meshOnly:o=!1}){var C,y,x;const{t:i}=Se("common"),c=wr(),d=Ts(e),p=o?null:Zu(e),u=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),m=!o&&e.streamSource==="agent-stream"&&!!e.agentName,f=!o&&!m&&(e.transport==="pty"||e.transport==="acp"),g=An(e),k=b0(e),h=(C=e.settings)==null?void 0:C.meshNodeFor,v=e.meshQueueStats,w=((y=e.coordinator)==null?void 0:y.meshId)||((x=e.settings)==null?void 0:x.meshCoordinatorFor),b=l.useCallback(()=>{if(r){r();return}d&&c("/dashboard",{state:{openMachineId:d}})},[d,c,r]),j=l.useCallback(()=>{if(n){n();return}const N=dm(e);N&&c(xr(N))},[e,c,n]);return!u&&!m&&!f&&!p&&!h&&!v?null:s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[u&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:j,title:k,children:[s.jsx(hs,{size:12}),s.jsx("span",{children:k})]}):s.jsxs("span",{className:"conversation-meta-chip",title:k,children:[s.jsx(hs,{size:12}),s.jsx("span",{children:k})]})),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(mr,{size:12}),s.jsx("span",{children:g})]}),f&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(mr,{size:12}),s.jsx("span",{children:g})]}),p&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:b,title:p,children:[s.jsx(_s,{size:12}),s.jsx("span",{children:p})]}):s.jsxs("span",{className:"conversation-meta-chip",title:p,children:[s.jsx(_s,{size:12}),s.jsx("span",{children:p})]})),h&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(_s,{size:12}),s.jsx("span",{children:i("dashboard.metaChips.meshNode")})]}),w&&v&&s.jsxs("span",{className:`conversation-meta-chip ${v.pending>0?"is-active":""}`,style:v.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${v.pending} pending, ${v.assigned} assigned, ${v.completed} completed, ${v.failed} failed`,children:[s.jsx(qf,{size:12}),s.jsxs("span",{children:[v.pending," Pending"]})]})]})}function Vj({selectedConversation:e,isAcp:t,isStandalone:n,selectedIdeEntry:r,actionLogs:a,userName:o,isSendingChat:i,sendFeedbackMessage:c=null,isFocusingAgent:d,onBack:p,onOpenNativeConversation:u,onOpenMachine:m,onOpenHistory:f,onOpenRemote:g,onOpenMeshGraph:k,onStopCli:h,cliViewMode:v,onSetCliViewMode:w,handleSendChat:b,handleForceSendChat:j,handleFocusAgent:C,handleModalButton:y,handleRelaunch:x}){var D,I;const N=l.useRef(null),S=ut(e)&&!t,A=S&&v==="terminal",M=!!e.daemonId&&!!((D=e.coordinator)!=null&&D.meshId||(I=e.settings)!=null&&I.meshCoordinatorFor),P=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 ${P} 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($i,{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:xt(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(Kj,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>m(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[S&&v&&s.jsx(Tp,{mode:v,onChange:w,compact:!0}),S&&h&&s.jsx("button",{onClick:()=>{h(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(Mt,{size:14})}),M&&k&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>k(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(ts,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",children:s.jsx(Fi,{size:14})}),!t&&!S&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",children:s.jsx(hs,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(fl,{activeConv:e,clearToken:0,isCliTerminal:A,ideEntry:r,terminalRef:N,handleModalButton:y,handleRelaunch:x,handleSendChat:b,handleForceSendChat:j,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:C,isFocusingAgent:d,actionLogs:a,userName:o})})]})}const jo={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 Yj(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function mm(){const[e,t]=l.useState("unix"),[n,r]=l.useState("powershell"),[a,o]=l.useState(!1),i=e==="unix"?"unix":n;l.useEffect(()=>{t(Yj())},[]);const c=l.useCallback(()=>{navigator.clipboard.writeText(jo[i].cmd).catch(()=>{}),o(!0),setTimeout(()=>o(!1),2e3)},[i]);return s.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("unix"),children:"🍎🐧 macOS / Linux"}),s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("windows"),children:"🪟 Windows"})]}),e==="windows"&&s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${n==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>r("powershell"),children:"⚡ PowerShell"}),s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${n==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>r("cmd"),children:">_ CMD"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:c,title:"Click to copy",children:[s.jsx("span",{className:"text-text-muted select-none",children:jo[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:jo[i].cmd}),s.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:a?"✓":"📋"})]}),s.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",s.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function hm({section:e,onSectionChange:t}){const n=[{key:"machines",label:"Machines",icon:hs},{key:"chats",label:"Chats",icon:ln}];return s.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:s.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:n.map(({key:r,label:a,icon:o})=>{const i=e===r;return s.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${i?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:i?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>t(r),type:"button","aria-pressed":i,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${i?"text-accent-primary":"bg-transparent text-current"}`,style:i?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:s.jsx(o,{size:15})}),s.jsx("span",{children:a})]},r)})})})}function Wr({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 pn({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 Yn({icon:e,title:t,subtitle:n,children:r}){return s.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[s.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),s.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:t}),s.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:n}),r]})}function Jj({conversation:e,onCancel:t,onConfirm:n}){const{t:r}=Se(),a=xt(e);return s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:t,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"mobile-hide-confirm-title",className:"card fade-in mobile-compact-dialog relative w-full sm:w-[min(92vw,420px)] md:w-[92%] md:max-w-[420px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-bg-primary",children:[s.jsx("h3",{id:"mobile-hide-confirm-title",className:"m-0 text-base md:text-lg font-extrabold",children:r("mobileInbox.hideTitle",{title:a})}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:r("mobileInbox.hideDescription")})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[s.jsx("button",{onClick:n,className:"btn btn-primary w-full justify-center min-h-[42px]",children:r("mobileInbox.hide")}),s.jsx("button",{onClick:t,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:r("common.cancel")})]})]})]})}function Ur({item:e,type:t,getAvatarText:n,onOpenConversation:r,onRequestHideConversation:a,onRequestStopCli:o,onOpenMeshGraph:i,onCollectChatDebugBundle:c,isMuted:d,onToggleMute:p}){const{t:u}=Se(),m=t==="needs_attention"||t==="task_complete",f=t==="working",g=t==="earlier",k=t==="task_complete",{isReconnecting:h,isConnecting:v}=cn(e.conversation),w=xt(e.conversation),b=Mn(e.conversation),j=jp(e.conversation,{requiresAction:t==="needs_attention"}),C=m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":f?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":g?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",y=m?"bg-accent-primary shadow-glow":f?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":g?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",x=g?"text-text-secondary":"text-text-primary",N=g?"text-text-muted":"text-text-secondary",S=g?"text-text-secondary opacity-80":"text-text-muted",A=g?"text-text-muted opacity-80":"text-text-muted",M=!f&&!k,P=Sp(e.conversation),D="text-[color:var(--status-warning)]",I=_=>{if(!c)return;_.preventDefault(),_.stopPropagation();const W=c==null?void 0:c(e.conversation);Promise.resolve(W).catch(H=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",H)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${C}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[m||f?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${y}`,style:m?{color:"var(--accent-on-primary)"}:void 0,children:n(w)}),P&&i&&s.jsx("button",{type:"button",className:"mobile-inbox-mesh-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:_=>{_.preventDefault(),_.stopPropagation(),i(e.conversation)},"aria-label":u("mobileInbox.openMeshGraphFor",{title:w}),title:u("mobileInbox.openLiveMeshGraph"),children:s.jsx(ts,{size:13})})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>r(e.conversation),onContextMenu:I,type:"button",children:[s.jsx("div",{className:"flex items-center gap-2 pr-[124px]",children:s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${x}`,children:w})}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${N}`,children:[s.jsx("span",{className:"truncate",children:b}),s.jsx(ya,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),h?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${D} animate-pulse`,children:u("mobileInbox.reconnectingItem")})]}):v?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:u("mobileInbox.connectingItem")})]}):j==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:D,children:u("mobileInbox.actionNeeded")})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${S}`,children:e.preview})]}),s.jsxs("div",{className:"mobile-inbox-corner-actions absolute top-3 right-3 flex items-center gap-1.5",children:[M&&s.jsx("span",{className:`mr-0.5 text-[11px] font-medium shrink-0 ${A}`,children:Mu(e.timestamp)}),k&&s.jsx("span",{className:"rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:u("mobileInbox.done")}),p&&s.jsx("button",{type:"button",className:`mobile-inbox-mute-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border transition-colors ${d?"border-amber-500/60 bg-amber-500 text-white hover:bg-amber-600":"border-border-subtle bg-bg-primary/70 text-text-muted hover:border-border-default hover:text-text-primary"}`,onClick:_=>{_.preventDefault(),_.stopPropagation(),p()},"aria-label":d?u("mobileInbox.unmute",{title:w}):u("mobileInbox.mute",{title:w}),title:u(d?"mobileInbox.mutedTitle":"mobileInbox.muteNotifications"),children:d?s.jsx(bu,{size:13}):s.jsx(Rn,{size:13})}),a&&s.jsx("button",{type:"button",className:"mobile-inbox-hide-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:_=>{_.preventDefault(),_.stopPropagation(),a()},"aria-label":u("mobileInbox.hideConversationAria",{title:w}),title:u("mobileInbox.hideConversationTitle"),children:s.jsx(Bi,{size:13})}),o&&s.jsx("button",{type:"button",className:"mobile-inbox-stop-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-status-error/30 bg-bg-primary/70 text-status-error transition-colors hover:border-status-error/60 hover:bg-status-error/10",onClick:_=>{_.preventDefault(),_.stopPropagation(),o()},"aria-label":u("mobileInbox.stopSessionAria",{title:w}),title:u("mobileInbox.stopSessionTitle"),children:s.jsx(Mt,{size:13})})]})]})},e.conversation.tabKey)}function Zc({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 ed({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 Qj({section:e,attentionItems:t,unreadItems:n,workingItems:r,completedItems:a,hiddenConversations:o,machineCards:i,getAvatarText:c,actionLogs:d,sendDaemonCommand:p,onOpenConversation:u,onShowAllHidden:m,onHideConversation:f,onOpenMeshGraph:g,onStopCli:k,onOpenNewSession:h,onOpenMachine:v,onOpenSettings:w,onSectionChange:b,wsStatus:j="connected",isStandalone:C=!1,onCollectChatDebugBundle:y,isConversationMuted:x,onToggleMuteConversation:N}){const{t:S}=Se(),[A,M]=l.useState(null),P=j==="disconnected"||j==="reconnecting"||j==="offline"||j==="auth_failed",D=i.length>0,I=t.length>0||n.length>0||r.length>0||a.length>0,_=S(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),W=C?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",H=C?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",L=l.useCallback(async T=>{const $=Js(T);if(!$)return;const R=Array.isArray(T.messages)?T.messages:[],G=ap({activeConv:T,visibleMessages:R,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:R.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),Q=await p($,"get_chat_debug_bundle",{...Ys(T),delivery:"daemon_file",frontendSnapshot:G}),re=ir(Q),J=lp(re),X=await ip(J);X==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),pt.showToast(op(re,{locatorCopyStatus:X}),X==="failed"?"warning":"success")},[d,p]),O=y||L,E=l.useCallback(()=>{A&&(f==null||f(A),M(null))},[A,f]);return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${W}`,children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:_}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||n.length>0)&&s.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[s.jsx(Rn,{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(La,{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:P?s.jsx(Yn,{icon:s.jsx(Zc,{}),title:S(j==="offline"?"mobileInbox.networkOffline":j==="auth_failed"?"mobileInbox.sessionExpired":"mobileInbox.reconnecting"),subtitle:S(j==="offline"?"mobileInbox.waitingForNetwork":j==="auth_failed"?"mobileInbox.pleaseLogInAgain":"mobileInbox.restoringConnection")}):i.length===0?s.jsx(Yn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:S(C?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:S(C?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!C&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(mm,{})})}):s.jsx(pn,{children:i.map((T,$)=>s.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${$>0?"border-t border-border-subtle/70":""}`,onClick:()=>v(T.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(T.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:T.label}),s.jsxs("span",{className:"flex items-center gap-2 text-[11px] font-medium text-text-muted shrink-0",children:[s.jsx(ed,{count:T.generatingCount,label:S("mobileInbox.generatingCount",{count:T.generatingCount})}),T.unread>0?s.jsx("span",{className:"text-accent-primary",children:S("mobileInbox.newCount",{count:T.unread})}):T.total>0?S("mobileInbox.chatCount",{count:T.total}):S("mobileInbox.idle")]})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:T.subtitle}),T.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[S("mobileInbox.chatCount",{count:T.total}),T.unread>0?S("mobileInbox.unreadSuffix",{count:T.unread}):"",T.generatingCount>0?S("mobileInbox.collapsedGeneratingSuffix",{count:T.generatingCount}):""]}):T.generatingCount>0?s.jsx("div",{className:"text-[13px] text-accent-primary mt-0.5 font-medium",children:S("mobileInbox.generatingCount",{count:T.generatingCount})}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:S("mobileInbox.noActiveChats")})]})]},T.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(Wr,{title:S("mobileInbox.needsAttention"),className:"mb-0"}),s.jsx(pn,{children:t.map((T,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Ur,{item:T,type:"needs_attention",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>M(T.conversation):void 0,onRequestStopCli:k?()=>k(T.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:O,isMuted:x==null?void 0:x(T.conversation),onToggleMute:N?()=>N(T.conversation):void 0})},T.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(Wr,{title:S("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),s.jsx(pn,{children:n.map((T,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Ur,{item:T,type:"task_complete",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>M(T.conversation):void 0,onRequestStopCli:k?()=>k(T.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:O,isMuted:x==null?void 0:x(T.conversation),onToggleMute:N?()=>N(T.conversation):void 0})},T.conversation.tabKey))})]}),e==="chats"&&r.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(Wr,{title:S("mobileInbox.workingNow"),className:"mb-0 mt-2"}),s.jsx(pn,{children:r.map((T,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Ur,{item:T,type:"working",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>M(T.conversation):void 0,onRequestStopCli:k?()=>k(T.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:O,isMuted:x==null?void 0:x(T.conversation),onToggleMute:N?()=>N(T.conversation):void 0})},T.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&s.jsx(Wr,{title:S("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(pn,{children:a.map((T,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Ur,{item:T,type:"earlier",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>M(T.conversation):void 0,onRequestStopCli:k?()=>k(T.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:O,isMuted:x==null?void 0:x(T.conversation),onToggleMute:N?()=>N(T.conversation):void 0})},T.conversation.tabKey))}):I?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:S("mobileInbox.allCaughtUp")}):P?s.jsx(Yn,{icon:s.jsx(Zc,{size:28}),title:S("mobileInbox.connecting"),subtitle:S("mobileInbox.connectingSubtitle")}):D?s.jsx(Yn,{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(ln,{size:20})}),title:S("mobileInbox.noConversations"),subtitle:S("paneGroup.newSessionDescription"),children:h&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:h,"aria-label":S("paneGroup.newSession"),title:S("paneGroup.newSession"),children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s.jsx("span",{children:S("paneGroup.newSession")})]})}):s.jsx(Yn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:S("mobileInbox.noMachinesConnected"),subtitle:S("mobileInbox.noMachinesSubtitle")})]}),e==="chats"&&o.length>0&&(()=>{const T=Ub(o);return s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(pn,{className:"mt-4 border-dashed bg-bg-secondary/20",children:s.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:S("mobileInbox.hiddenTabs")}),s.jsx(ed,{count:T,label:S("mobileInbox.generatingCount",{count:T})})]}),s.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[S("mobileInbox.collapsedCount",{count:o.length}),T>0?S("mobileInbox.collapsedGeneratingSuffix",{count:T}):""]})]}),s.jsx("button",{type:"button",className:"shrink-0 rounded-full border border-border-subtle bg-bg-primary/70 px-3 py-1.5 text-[12px] font-semibold text-accent-primary hover:border-border-default",onClick:m,children:S("mobileInbox.restoreAll")})]})})})})()]}),e==="chats"&&h&&I&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:h,"aria-label":S("paneGroup.newSession"),title:S("paneGroup.newSession"),children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),A&&s.jsx(Jj,{conversation:A,onCancel:()=>M(null),onConfirm:E}),s.jsx(hm,{section:e,onSectionChange:b})]})}function Xj(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 fm(e){const t=[e.workspace||"Workspace unknown"],n=rn(e.summaryMetadata);n&&t.push(n),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const r=Xj(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:r?`Updated ${r}`:"",preview:(e.preview||"").trim()}}function bl({title:e,description:t,currentPath:n,directories:r,busy:a=!1,error:o="",confirmLabel:i="Use this folder",onClose:c,onNavigate:d,onConfirm:p}){const[u,m]=l.useState(n),{t:f}=Se("common");l.useEffect(()=>{m(n)},[n]);const g=Tj(n),k=u.trim();return s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:s.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:c,"aria-label":"Close folder browser",children:s.jsx(Mt,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!g||a||d(g)},disabled:!g||a,children:[s.jsx($i,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:f("machine.workspaceBrowse.currentFolder")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:u,onChange:h=>m(h.target.value),onKeyDown:h=>{h.key!=="Enter"||!k||a||(h.preventDefault(),d(k))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!k||a||d(k)},disabled:!k||a,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):o?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:o}):r.length===0?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):s.jsx("div",{className:"p-3",children:r.map(h=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>d(h.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Nn,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:h.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:h.path})]})]},h.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:c,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>p(k||n),disabled:!k&&!n||a,children:i})]})]})})}function gl({title:e,description:t,details:n,workspaceOptions:r,selectedWorkspaceKey:a,onWorkspaceChange:o,confirmLabel:i,busyLabel:c,busy:d=!1,showArgsInput:p,argsValue:u,onArgsChange:m,showModelInput:f,modelValue:g,onModelChange:k,historyProviderNode:h,onConfirm:v,onCancel:w}){const{t:b}=Se("common"),j=i??b("machine.launchConfirm.launch"),C=c??b("machine.launchConfirm.launching"),y=r==null?void 0:r.find(x=>x.key===a);return s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:w,"aria-label":b("machine.launchConfirm.closeAria"),children:s.jsx(Mt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[r&&r.length>0&&o&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.workspace")}),s.jsx("select",{value:a||"",onChange:x=>o(x.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:d,children:r.map(x=>s.jsx("option",{value:x.key,children:x.label},x.key))}),(y==null?void 0:y.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:y.description})]}),h,n.map(x=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:x.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:x.value})]},`${x.label}:${x.value}`)),f&&k&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.languageModel")}),s.jsx("input",{type:"text",value:g||"",onChange:x=>k(x.target.value),placeholder:b("machine.launchConfirm.autoDetect"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]}),p&&m&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.cliArgs")}),s.jsx("input",{type:"text",value:u||"",onChange:x=>m(x.target.value),placeholder:b("machine.launchConfirm.cliArgsPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:w,disabled:d,children:b("machine.launchConfirm.cancel")}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:v,disabled:d,children:[s.jsx(fu,{size:14}),d?C:j]})]})]})})}function td(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function bm(e){const{machine:t,currentWorkspacePath:n,currentWorkspaceId:r,includeHome:a=!0,homeLabel:o="Home directory",homeDescription:i="Launch without a workspace"}=e,c=[];a&&c.push({key:"__home__",label:o,description:i,workspaceId:null,workspacePath:null});for(const u of t.workspaces||[])c.push({key:`saved:${u.id}`,label:`${u.id===t.defaultWorkspaceId?"⭐ ":""}${td(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const d=(n==null?void 0:n.trim())||"",p=d?(t.workspaces||[]).find(u=>u.path===d):null;if(d&&!p&&c.push({key:`custom:${d}`,label:td(d),description:d,workspaceId:null,workspacePath:d}),r){const u=`saved:${r}`;if(c.some(m=>m.key===u))return{options:c,selectedKey:u}}return p?{options:c,selectedKey:`saved:${p.id}`}:d?{options:c,selectedKey:`custom:${d}`}:{options:c,selectedKey:"__home__"}}function Zj(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function e1(e){return[Zj(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function t1(e){return e.lastLaunchedAt?Ea(e.lastLaunchedAt):""}function gm(e){return{metaText:e1(e),updatedLabel:t1(e)}}function No(e,t,n){return e?"ide":t>0?"cli":n>0?"acp":null}function s1({selectedMachineEntry:e,cliProviders:t,acpProviders:n,machineAction:r,onBrowseDirectory:a,onListSavedSessions:o}){var be,Pe,Be,it;const i=_n(),[c,d]=l.useState(!1),p=(((be=e.detectedIdes)==null?void 0:be.length)||0)>0,u=l.useMemo(()=>(e.workspaces||[]).map(ae=>({id:ae.id,path:ae.path,label:ae.label})),[e]),m=e.defaultWorkspaceId||null,[f,g]=l.useState(m||((Pe=u[0])==null?void 0:Pe.id)||""),[k,h]=l.useState(""),[v,w]=l.useState(""),[b,j]=l.useState([]),[C,y]=l.useState(!1),[x,N]=l.useState(""),[S,A]=l.useState(!1),[M,P]=l.useState(No(p,t.length,n.length)),D=l.useRef(null),[I,_]=l.useState(null),W=l.useRef("__home__"),[H,L]=l.useState("__home__"),[O,E]=l.useState(""),[T,$]=l.useState(""),[R,G]=l.useState(""),[Q,re]=l.useState([]),[J,X]=l.useState(()=>Wt().textQuery),[ue,se]=l.useState(()=>Wt().workspaceQuery),[B,ie]=l.useState(()=>Wt().modelQuery),[K,le]=l.useState(()=>Wt().resumableOnly),[je,we]=l.useState(()=>Wt().sortMode),[ke,he]=l.useState(!1),[U,q]=l.useState(!1),Z=l.useRef(null),Y=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const fe=f==="__custom__"?k.trim():((Be=u.find(ae=>ae.id===f))==null?void 0:Be.path)||"",Me=f==="__custom__"&&!!fe&&r.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(r.message),de=f!=="__custom__"&&((it=u.find(ae=>ae.id===f))==null?void 0:it.path)||"",F=l.useMemo(()=>(e.recentLaunches||[]).map(ae=>ae.workspace),[e]),me=l.useCallback(async ae=>{y(!0),N("");try{const _e=await a(ae);w(_e.path),h(_e.path),j(_e.directories)}catch(_e){N(_e instanceof Error?_e.message:"Could not load folder")}finally{y(!1)}},[a]),ce=l.useCallback(()=>{var _e;g("__custom__"),A(!0);const ae=ml(e.platform,pl(k.trim(),de,F,e.defaultWorkspacePath,(_e=u.find(lt=>lt.id===m))==null?void 0:_e.path,u.map(lt=>lt.path)));me(ae)},[k,m,me,F,de,e.platform,u]),z=l.useCallback(ae=>{if(ae!=null&&ae.workspaceId){g(ae.workspaceId),h("");return}if(ae!=null&&ae.workspacePath){g("__custom__"),h(ae.workspacePath);return}g(""),h("")},[]),ge=l.useCallback(ae=>{if(g(ae),ae==="__custom__"){ce();return}h("")},[ce]),Ce=l.useCallback(ae=>{g("__custom__"),h(ae)},[]),Ne=l.useCallback((ae,_e)=>{D.current=_e,W.current=ae.selectedWorkspaceKey||"__home__",L(ae.selectedWorkspaceKey||"__home__"),E(ae.initialArgs||""),$(ae.initialModel||""),G(""),re([]);const lt=ae.providerType?`${e.id}:${ae.providerType}`:null;if(aS(Y.current,lt)){const ct=Wt();X(ct.textQuery),se(ct.workspaceQuery),ie(ct.modelQuery),le(ct.resumableOnly),we(ct.sortMode)}Y.current=lt,_(ae),ae.providerType&&o&&(he(!0),o(ae.providerType).then(ct=>re(ct||[])).catch(ct=>console.warn("Failed to load saved sessions",ct)).finally(()=>he(!1)))},[o,e.id]),He=l.useMemo(()=>Ip(Q,{textQuery:J,workspaceQuery:ue,modelQuery:B,resumableOnly:K,sortMode:je}),[B,K,Q,je,J,ue]);l.useEffect(()=>{R&&(He.some(ae=>ae.providerSessionId===R)||G(""))},[He,R]);const Ze=l.useCallback(()=>{D.current&&(q(!0),D.current().finally(()=>{D.current=null,q(!1),_(null)}))},[]),Ye=l.useCallback(()=>{D.current=null,_(null)},[]),ot=l.useCallback(ae=>{W.current=ae,L(ae)},[]);return l.useEffect(()=>{var ae;Z.current!==e.id&&(Z.current=e.id,g(m||((ae=u[0])==null?void 0:ae.id)||"__custom__"),h(""),w(""),j([]),N(""),A(!1),X(Wt().textQuery),se(Wt().workspaceQuery),ie(Wt().modelQuery),le(Wt().resumableOnly),we(Wt().sortMode),Y.current=null,P(No(p,t.length,n.length)))},[n.length,t.length,m,p,e.id,u]),l.useEffect(()=>{var ae;f!=="__custom__"&&(f&&u.some(_e=>_e.id===f)||g(m||((ae=u[0])==null?void 0:ae.id)||"__custom__"))},[m,f,u]),l.useEffect(()=>{M==="ide"&&p||M==="cli"&&t.length>0||M==="acp"&&n.length>0||P(No(p,t.length,n.length))},[M,n.length,t.length,p]),{showAllRecent:c,setShowAllRecent:d,hasIdeOptions:p,workspaceRows:u,defaultWorkspaceId:m,workspaceChoice:f,customWorkspacePath:k,browseCurrentPath:v,browseDirectories:b,browseBusy:C,browseError:x,browseDialogOpen:S,activeLauncherKind:M,launchConfirm:I,launchConfirmWorkspaceKeyRef:W,launchConfirmWorkspaceKey:H,launchConfirmArgs:O,launchConfirmModel:T,launchConfirmResumeId:R,launchConfirmSavedSessions:Q,launchConfirmTextFilter:J,launchConfirmWorkspaceFilter:ue,launchConfirmModelFilter:B,launchConfirmResumableOnly:K,launchConfirmSortMode:je,filteredLaunchConfirmSavedSessions:He,launchConfirmSessionsLoading:ke,launchConfirmBusy:U,resolvedWorkspacePath:fe,canCreateMissingWorkspace:Me,openBrowseDialog:ce,loadBrowsePath:me,handleWorkspaceChoiceChange:ge,chooseCustomWorkspacePath:Ce,setCustomWorkspacePath:h,setBrowseDialogOpen:A,setActiveLauncherKind:P,openLaunchConfirm:Ne,handleConfirmLaunch:Ze,closeLaunchConfirm:Ye,setWorkspaceSelectionFromOption:z,setLaunchConfirmWorkspaceKeyAndSync:ot,setLaunchConfirmArgs:E,setLaunchConfirmModel:$,setLaunchConfirmResumeId:G,setLaunchConfirmTextFilter:X,setLaunchConfirmWorkspaceFilter:se,setLaunchConfirmModelFilter:ie,setLaunchConfirmResumableOnly:le,setLaunchConfirmSortMode:we}}function n1({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:n,cliProviders:r,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:i,machineAction:c,isStandalone:d,section:p,showBottomNav:u,onBack:m,onSectionChange:f,onOpenConversation:g,onOpenRecent:k,onOpenMachineDetails:h,onMachineUpgrade:v,onLaunchDetectedIde:w,onAddWorkspace:b,onBrowseDirectory:j,onLaunchWorkspaceProvider:C,onListSavedSessions:y}){const{t:x}=Se("common"),N=L=>L==="ide"?"IDE":L==="cli"?"CLI":"ACP",S=n.slice(0,4),A=t.slice(0,3),M=s1({selectedMachineEntry:e,cliProviders:r,acpProviders:a,machineAction:c,onBrowseDirectory:j,onListSavedSessions:y}),P=l.useMemo(()=>S.map(L=>{const{metaText:O,updatedLabel:E}=gm(L);return{key:`recent-launch:${L.id}`,primary:L.label,secondary:O,updatedLabel:E,onClick:()=>{const{options:T,selectedKey:$}=bm({machine:{workspaces:M.workspaceRows,defaultWorkspaceId:M.defaultWorkspaceId},currentWorkspacePath:L.workspace,homeLabel:x("newSession.homeDirectory"),homeDescription:x("newSession.launchWithoutWorkspace")});M.openLaunchConfirm({title:L.kind==="ide"?wa(x,"restart-ide",L.label):L.providerSessionId?Pp(x,L.label):wa(x,"start-fresh",L.label),description:L.kind==="ide"?ka(x,"restart-ide"):L.providerSessionId?Lp(x):ka(x,"start-fresh"),confirmLabel:L.kind==="ide"?Sa(x,"restart-ide"):L.providerSessionId?gi(x,!0):Sa(x,"start-fresh"),busyLabel:L.kind==="ide"?Ca(x,"restart-ide"):L.providerSessionId?Dp(x,!0):Ca(x,"start-fresh"),workspaceOptions:T,selectedWorkspaceKey:$,details:[{label:"Mode",value:N(L.kind)},...L.providerType?[{label:"Provider",value:L.providerType}]:[]]},async()=>{const R=T.find(G=>G.key===M.launchConfirmWorkspaceKeyRef.current);M.setWorkspaceSelectionFromOption(R),await k({...L,workspace:(R==null?void 0:R.workspacePath)??null})})}}}),[M,k,S,x]),D=l.useMemo(()=>A.map(L=>({key:`recent-chat:${L.conversation.tabKey}`,primary:xt(L.conversation),secondary:Ek(L.conversation,{timestampLabel:L.timestamp?Mu(L.timestamp):null}),unread:L.unread,onClick:()=>g(L.conversation)})),[g,A]),I=M.showAllRecent?P:P.slice(0,4),_=P.length>0,W=D.length>0,H=d?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${H} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:m,type:"button","aria-label":"Back",children:s.jsx($i,{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:ss(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:[W&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:D.map(L=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${L.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:L.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:L.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:L.secondary})]},L.key))})]}),_&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:I.map(L=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:L.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:L.primary}),L.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:L.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:L.secondary})]},L.key))}),P.length>4&&s.jsx("div",{className:"flex justify-center px-4 pt-2",children:s.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>M.setShowAllRecent(L=>!L),children:M.showAllRecent?"Show fewer":`Show ${P.length-4} more`})})]}),!1,s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[o&&s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:v,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",i]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:h,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),M.browseDialogOpen&&s.jsx(bl,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:M.browseCurrentPath,directories:M.browseDirectories,busy:M.browseBusy,error:M.browseError,confirmLabel:"Use this folder",onClose:()=>M.setBrowseDialogOpen(!1),onNavigate:L=>{M.loadBrowsePath(L)},onConfirm:L=>{M.chooseCustomWorkspacePath(L),M.setBrowseDialogOpen(!1)}}),M.launchConfirm&&s.jsx(gl,{title:M.launchConfirm.title,description:M.launchConfirm.description,details:M.launchConfirm.details,workspaceOptions:M.launchConfirm.workspaceOptions,selectedWorkspaceKey:M.launchConfirmWorkspaceKey,onWorkspaceChange:M.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:M.launchConfirm.providerType?gi(x,!!M.launchConfirmResumeId):M.launchConfirm.confirmLabel,busyLabel:M.launchConfirm.providerType?void 0:M.launchConfirm.busyLabel,busy:M.launchConfirmBusy,showArgsInput:M.launchConfirm.showArgsInput,argsValue:M.launchConfirmArgs,onArgsChange:M.setLaunchConfirmArgs,showModelInput:M.launchConfirm.showModelInput,modelValue:M.launchConfirmModel,onModelChange:M.setLaunchConfirmModel,historyProviderNode:M.launchConfirm.providerType&&(M.launchConfirmSessionsLoading||M.launchConfirmSavedSessions.length>0)&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),M.launchConfirmSessionsLoading&&s.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:rl(x)}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:M.launchConfirmTextFilter,onChange:L=>M.setLaunchConfirmTextFilter(L.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:M.launchConfirmBusy||M.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:M.launchConfirmWorkspaceFilter,onChange:L=>M.setLaunchConfirmWorkspaceFilter(L.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:M.launchConfirmBusy||M.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:M.launchConfirmModelFilter,onChange:L=>M.setLaunchConfirmModelFilter(L.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:M.launchConfirmBusy||M.launchConfirmSessionsLoading}),s.jsxs("select",{value:M.launchConfirmSortMode,onChange:L=>M.setLaunchConfirmSortMode(L.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:M.launchConfirmBusy||M.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:M.launchConfirmResumableOnly,onChange:L=>M.setLaunchConfirmResumableOnly(L.target.checked),disabled:M.launchConfirmBusy||M.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:M.launchConfirmResumeId,onChange:L=>M.setLaunchConfirmResumeId(L.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:M.launchConfirmBusy||M.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:lS(x)}),M.filteredLaunchConfirmSavedSessions.map(L=>s.jsxs("option",{value:L.providerSessionId,disabled:!L.canResume,children:[L.title||L.providerSessionId," ",L.canResume?"":"(workspace missing)"]},L.providerSessionId))]}),!M.launchConfirmSessionsLoading&&M.launchConfirmSavedSessions.length>0&&M.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),M.launchConfirmResumeId&&(()=>{const L=M.filteredLaunchConfirmSavedSessions.find(E=>E.providerSessionId===M.launchConfirmResumeId);if(!L)return null;const O=fm(L);return s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:O.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:O.providerSessionId}),s.jsx("div",{className:"mt-1",children:O.metaLine}),O.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:O.updatedLabel}),O.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:O.preview})]})})()]}),onConfirm:M.handleConfirmLaunch,onCancel:M.closeLaunchConfirm}),u&&s.jsx(hm,{section:p,onSectionChange:f})]})}const sd=8e3;function r1(e){const t=e&&typeof e=="object"&&"result"in e?e.result:e,n=t&&typeof t=="object",r=n&&t.success===!1,a=n&&t.mirrorStale===!0;return!r&&!a?{confirmed:!0}:{confirmed:!1,reason:r&&typeof t.error=="string"?t.error:a?"the coordinator did not confirm the change":"command was rejected"}}function xm(e,t,n){const r=l.useRef(new Map),[,a]=l.useState(0),o=l.useCallback(()=>a(g=>g+1),[]);l.useEffect(()=>{const g=r.current;if(g.size===0)return;const k=Date.now();let h=!1;for(const[v,w]of g){const b=e.get(v),j=w.muted===void 0||(b?b.muted===w.muted:!1),C=w.hidden===void 0||(b?b.surfaceHidden===w.hidden:!1),y=k-w.at>sd;(j&&C||y)&&(g.delete(v),h=!0)}h&&o()},[e,o]),l.useEffect(()=>{if(r.current.size===0)return;const g=setInterval(()=>{const k=r.current,h=Date.now();let v=!1;for(const[w,b]of k)h-b.at>sd&&(k.delete(w),v=!0);v&&o(),k.size===0&&clearInterval(g)},1e3);return()=>clearInterval(g)});const i=l.useCallback((g,k)=>{const h=r.current.get(g);r.current.set(g,{...h,...k,at:Date.now()}),o()},[o]),c=l.useCallback(g=>{const k=g.sessionId,h=k?r.current.get(k):void 0;return(h==null?void 0:h.muted)!==void 0?h.muted:Hs(g,e).muted??!1},[e]),d=l.useCallback(g=>{const k=g.sessionId,h=k?r.current.get(k):void 0;return(h==null?void 0:h.hidden)!==void 0?h.hidden:Hs(g,e).surfaceHidden??!1},[e]),p=l.useCallback((g,k)=>{const h=Ts(g),v=g.sessionId;!h||!v||(i(v,k),t(h,"set_conversation_prefs",{sessionId:v,...k,...Oa(g)}).then(w=>{const b=r1(w);b.confirmed||(console.warn("[conversation-prefs] set_conversation_prefs not confirmed",b.reason),r.current.delete(v),o(),n==null||n(`Couldn't update conversation — ${b.reason}`))}).catch(w=>{console.warn("[conversation-prefs] set_conversation_prefs failed",w),r.current.delete(v),o();const b=w instanceof Error?w.message:String(w??"the daemon is unreachable");n==null||n(`Couldn't update conversation — ${b}`)}))},[t,i,o,n]),u=l.useCallback(g=>{p(g,{muted:!c(g)})},[p,c]),m=l.useCallback((g,k)=>{p(g,{hidden:k})},[p]),f=l.useCallback(g=>{p(g,{hidden:!d(g)})},[p,d]);return{isMuted:c,isHidden:d,toggleMute:u,setHidden:m,toggleHidden:f}}function oa(e){return[...e].sort((t,n)=>{const r=n.timestamp-t.timestamp;return r!==0?r:t.conversation.tabKey.localeCompare(n.conversation.tabKey)})}function a1(e,t=[]){const n=new Map(e.map(a=>[a.conversation.tabKey,a])),r=t.map(a=>n.get(a)).filter(a=>!!a);return r.length===e.length?r:oa(e)}function o1(e,t=[]){const n=e.filter(i=>i.requiresAction),r=e.filter(i=>i.unread&&!i.requiresAction),a=e.filter(i=>!i.unread&&!i.requiresAction&&i.isWorking),o=e.filter(i=>!i.unread&&!i.requiresAction&&!i.isWorking);return{attentionItems:oa(n),unreadItems:oa(r),workingItems:a1(a,t),completedItems:oa(o)}}function i1(e){var r,a,o;const t=((r=e.p2p)==null?void 0:r.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":!(!!((a=e.p2p)!=null&&a.available)||!!((o=e.p2p)!=null&&o.state))&&e.status&&e.status!=="offline"?"Connected":"Offline"}function l1(e,t){if(!e)return[];const n=e.recentLaunches||[];return n.length>0?n.map(r=>({id:r.id,label:r.title||r.providerName||r.providerType,kind:r.kind,providerType:r.providerType,providerSessionId:r.providerSessionId,subtitle:rn(r.summaryMetadata)||r.workspace||void 0,workspace:r.workspace,summaryMetadata:r.summaryMetadata})):t.filter(r=>r.type!=="adhdev-daemon"&&r.daemonId===e.id).map(r=>{var i;const a=fr(r)?"cli":kn(r)?"acp":"ide",o=rn(r.summaryMetadata);return{id:`${a}:${r.type}:${r.workspace||""}`,label:((i=r.activeChat)==null?void 0:i.title)||(fr(r)?r.cliName||r.type:kn(r)&&r.cliName||r.type),kind:a,providerType:r.type,providerSessionId:r.providerSessionId,subtitle:kn(r)?o||r.workspace||void 0:r.workspace||void 0,workspace:r.workspace||void 0,timestamp:r.lastMessageAt||0}}).sort((r,a)=>a.timestamp-r.timestamp).map(({timestamp:r,...a})=>a)}function c1(e,t,n=[]){const r=new Map;for(const o of t){const i=Ts(o.conversation),c=r.get(i);c?c.push(o):r.set(i,[o])}const a=new Map;for(const o of n){const i=Ts(o),c=a.get(i);c?c.push(o):a.set(i,[o])}return e.map(o=>{const i=r.get(o.id)||[],c=a.get(o.id)||[],d=[...i].sort((h,v)=>v.timestamp-h.timestamp)[0]||null,p=(d==null?void 0:d.conversation)||null,u=di(o),m=i.filter(h=>h.unread||h.requiresAction).length,f=i.filter(h=>hr(h.conversation)).length+c.filter(hr).length,g=i1(o),k=[o.platform||"machine",g].filter(Boolean);return{id:o.id,label:ss(o,{fallbackId:o.id}),subtitle:k.join(" · "),unread:m,total:i.length,generatingCount:f,latestConversation:p,latestTimestamp:(d==null?void 0:d.timestamp)||0,fallbackActivityAt:u,preview:p?_k(p,gp(p)):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((o,i)=>{const c=o.latestTimestamp||o.fallbackActivityAt||0,d=i.latestTimestamp||i.fallbackActivityAt||0;return d!==c?d-c:o.label.localeCompare(i.label)})}function d1(e){return e==="chat"}function Gr(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 u1({conversations:e,machineEntries:t,items:n,selectedConversation:r,selectedTabKey:a,screen:o,liveSessionInboxState:i,sendDaemonCommand:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,setSelectedTabKey:k,setScreen:h,setSelectedMachineId:v,setSection:w,setMachineBackTarget:b,resetMachineAction:j}){const C=l.useRef(null),y=l.useCallback(x=>{if(!(x!=null&&x.sessionId))return;const N=Hs(x,i),S=Math.max(Date.now(),en(x),N.lastUpdated||0);Gr("mark_read:start",{tabKey:x.tabKey,sessionId:x.sessionId,displayPrimary:xt(x),inboxBucket:N.inboxBucket,unread:N.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:en(x),readAt:S}),c(Ts(x)||x.routeId,"mark_session_seen",{sessionId:x.sessionId,providerSessionId:x.providerSessionId,seenAt:S,completionMarker:N.completionMarker}).then(A=>{Gr("mark_read:result",{tabKey:x.tabKey,sessionId:x.sessionId,result:A})}).catch(A=>{Gr("mark_read:error",{tabKey:x.tabKey,sessionId:x.sessionId,error:A instanceof Error?A.message:String(A)})})},[i,c]);return l.useEffect(()=>{var N;if(!r){d1(o)&&h("inbox"),k(((N=e[0])==null?void 0:N.tabKey)||null),C.current=null;return}if(o!=="chat"){C.current=null;return}const x=`${r.tabKey}:${r.sessionId||""}`;C.current!==x&&(C.current=x,y(r))},[e,y,o,r,h,k]),l.useEffect(()=>{if(!d)return;const x=e.find(N=>N.tabKey===d);x&&(k(x.tabKey),h("chat"),p==null||p())},[e,p,d,h,k]),l.useEffect(()=>{if(!u)return;const x=t.find(N=>N.id===u);x&&(v(x.id),j(),w("machines"),b("inbox"),h("machine"),m==null||m())},[t,m,u,j,b,h,w,v]),l.useEffect(()=>{f&&(w(f),h("inbox"),g==null||g())},[g,f,h,w]),l.useEffect(()=>{const x=n.filter(N=>N.inboxBucket==="task_complete"||N.unread);x.length!==0&&Gr("inbox_state",{screen:o,selectedTabKey:a,items:x.map(N=>{const S=Hs(N.conversation,i);return{liveState:S,tabKey:N.conversation.tabKey,sessionId:N.conversation.sessionId,displayPrimary:xt(N.conversation),serverBucket:S.inboxBucket,computedBucket:N.inboxBucket,serverUnread:S.unread,computedUnread:N.unread,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,activityAt:en(N.conversation)}})})},[n,i,o,a]),{markConversationRead:y}}function p1(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 m1(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function h1({sendDaemonCommand:e,navigate:t,ides:n,conversations:r}){const{launchCli:a}=Pa(),[o,i]=l.useState("idle"),[c,d]=l.useState(""),[p,u]=l.useState(null),m=l.useCallback(()=>{i("idle"),d(""),u(null)},[]),f=l.useCallback(async(j,C,y)=>{var x;try{i("loading"),d(`Launching ${C}…`);const N={ideType:C,enableCdp:!0};(x=y==null?void 0:y.workspacePath)!=null&&x.trim()&&(N.workspace=y.workspacePath.trim()),await e(j,"launch_ide",N),i("done"),d(`${C} launch requested`)}catch(N){i("error"),d(N instanceof Error?N.message:"Launch IDE failed"),console.error("Launch IDE failed",N)}},[e]),g=l.useCallback(async(j,C,y)=>{if(C.trim())try{i("loading"),d(y!=null&&y.createIfMissing?"Creating folder…":"Saving workspace…");const x=await e(j,"workspace_add",{path:C.trim(),createIfMissing:(y==null?void 0:y.createIfMissing)===!0});if(x!=null&&x.success){i("done"),d(y!=null&&y.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),d((x==null?void 0:x.error)||"Could not save workspace")}catch(x){i("error"),d(x instanceof Error?x.message:"Could not save workspace")}},[e]),k=l.useCallback(async j=>{var C,y,x,N,S,A;try{i("loading"),d("Starting daemon upgrade…");const M=await e(j,"daemon_upgrade",{});if((C=M==null?void 0:M.result)!=null&&C.alreadyLatest){i("done"),d(`Already on v${((y=M==null?void 0:M.result)==null?void 0:y.version)||"latest"}.`);return}if((x=M==null?void 0:M.result)!=null&&x.upgraded||(N=M==null?void 0:M.result)!=null&&N.success){i("done"),d(`Upgrade to v${((S=M==null?void 0:M.result)==null?void 0:S.version)||"latest"} started. Daemon is restarting…`);return}i("error"),d(((A=M==null?void 0:M.result)==null?void 0:A.error)||"Upgrade failed")}catch(M){i("error"),d(M instanceof Error?M.message:"Upgrade failed")}},[e]),h=l.useCallback(async(j,C,y,x)=>{var A,M,P;const N=Date.now(),S={machineId:j,kind:C,providerType:y,workspaceId:(x==null?void 0:x.workspaceId)||null,workspacePath:(x==null?void 0:x.workspacePath)||null,resumeSessionId:(x==null?void 0:x.resumeSessionId)||null,startedAt:N};try{i("loading"),d(`Launching ${y}…`),u(S);const D={cliType:y};(A=x==null?void 0:x.workspacePath)!=null&&A.trim()?D.dir=x.workspacePath.trim():x!=null&&x.workspaceId?D.workspaceId=x.workspaceId:x!=null&&x.useHome&&(D.useHome=!0),x!=null&&x.resumeSessionId&&(D.resumeSessionId=x.resumeSessionId),(M=x==null?void 0:x.args)!=null&&M.trim()&&(D.cliArgs=x.args.trim().split(/\s+/).filter(Boolean)),(P=x==null?void 0:x.model)!=null&&P.trim()&&(D.initialModel=x.model.trim());const I=await a(j,D),_=(I==null?void 0:I.result)||I,W=(_==null?void 0:_.sessionId)||(_==null?void 0:_.id);if(I!=null&&I.success&&W){u(null),i("done"),d(`${y} launched`),t(xr(W));return}if(I!=null&&I.success){i("loading"),d(`${y} launch requested — waiting for session…`);return}u(null),i("error"),d((I==null?void 0:I.error)||(_==null?void 0:_.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(D){if(m1(D)){i("loading"),d(`${y} launch requested — waiting for session…`);return}u(null),i("error"),d(D instanceof Error?D.message:`Could not launch ${C.toUpperCase()} workspace`)}},[t,e]),v=l.useCallback(async(j,C)=>{try{const y=await e(j,"list_saved_sessions",{providerType:C,kind:"cli",limit:30}),x=(y==null?void 0:y.result)??y;return Array.isArray(x==null?void 0:x.sessions)?x.sessions:[]}catch(y){return console.error("Failed to list saved sessions on mobile:",y),[]}},[e]),w=l.useCallback(async(j,C)=>hl(e,j,C),[e]);l.useEffect(()=>{if(!p)return;const j=nd(p.workspacePath),C=n.find(x=>{var D,I,_,W;if(!x||x.type==="adhdev-daemon"||p1(x.daemonId||x.id)!==p.machineId||(x.transport==="acp"?"acp":x.transport==="pty"?"cli":null)!==p.kind||String(x.agentType||x.type||"")!==p.providerType)return!1;const M=String(x.providerSessionId||"");if(p.resumeSessionId&&M)return M===p.resumeSessionId;if(j){const H=nd(x.workspace||x.runtimeWorkspaceLabel);return H?H===j:!1}return Number(x.lastUpdated||x._lastUpdate||x.timestamp||((W=(_=(I=(D=x.activeChat)==null?void 0:D.messages)==null?void 0:I.at)==null?void 0:_.call(I,-1))==null?void 0:W.timestamp)||0)>=p.startedAt-5e3});if(!C)return;const y=um({entrySessionId:C.sessionId,entryInstanceId:C.instanceId,entryRouteId:C.id,conversations:r});y&&(u(null),i("done"),d(`${p.providerType} launched`),t(xr(y)))},[r,n,t,p]),l.useEffect(()=>{if(!p)return;const j=window.setTimeout(()=>{u(C=>!C||C.startedAt!==p.startedAt?C:(i("error"),d("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(j)},[p]);const b=l.useCallback(async(j,C)=>{var y;if(C.kind==="ide"&&C.providerType){await f(j,C.providerType,{workspacePath:C.workspace||null});return}if((C.kind==="cli"||C.kind==="acp")&&C.providerType){const x=((y=C.workspace)==null?void 0:y.trim())||"";await h(j,C.kind,C.providerType,{workspacePath:x||null,useHome:!x,resumeSessionId:C.providerSessionId||null})}},[f,h]);return{machineAction:{state:o,message:c},resetMachineAction:m,handleLaunchDetectedIde:f,handleAddWorkspace:g,handleMachineUpgrade:k,handleLaunchWorkspaceProvider:h,handleListSavedSessions:v,handleBrowseDirectory:w,handleOpenRecent:b}}function f1({conversations:e,selectedConversation:t,machineBackTarget:n,markConversationRead:r,resetMachineAction:a,setSelectedTabKey:o,setScreen:i,setSelectedMachineId:c,setSection:d,setMachineBackTarget:p}){const u=l.useCallback(w=>{o(w.tabKey),i("chat"),r(w)},[r,i,o]),m=l.useCallback(w=>{const b=e.find(j=>j.routeId===w.routeId&&j.streamSource==="native");b&&(o(b.tabKey),i("chat"),r(b))},[e,r,i,o]),f=l.useCallback(()=>{r(t),i("inbox")},[r,t,i]),g=l.useCallback((w,b="inbox")=>{c(w),a(),d("machines"),p(b),i("machine")},[a,p,i,d,c]),k=l.useCallback(w=>{const b=Ts(w);b&&g(b,"chat")},[g]),h=l.useCallback(()=>{a(),i(n)},[n,a,i]),v=l.useCallback(w=>{d(w),i("inbox")},[i,d]);return{openConversation:u,openNativeConversation:m,backFromConversation:f,openMachine:g,openConversationMachine:k,backFromMachine:h,changeMachineSection:v}}function Dn(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function b1(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function g1({conversations:e,hiddenConversations:t,ides:n,actionLogs:r,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,userName:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,onOpenHistory:k,onOpenRemote:h,onStopCli:v,wsStatus:w,isConnected:b,onShowAllHiddenConversations:j,onHideConversation:C,onOpenMeshGraph:y,onOpenNewSession:x,liveSessionInboxState:N,setCliViewModeOverrides:S}){const[A,M]=l.useState(()=>{var z;return((z=e[0])==null?void 0:z.tabKey)||null}),[P,D]=l.useState(()=>e[0]?"chat":"inbox"),[I,_]=l.useState("chats"),[W,H]=l.useState(null),[L,O]=l.useState("inbox"),E=l.useRef([]),T=wr(),$="1.0.18",R=l.useMemo(()=>e.find(z=>z.tabKey===A)||e[0]||null,[e,A]),G=l.useMemo(()=>R?n.find(z=>z.id===R.routeId):void 0,[n,R]),Q=l.useMemo(()=>!R||dt(R)||!ut(R)?null:En(R),[R]),re=l.useMemo(()=>n.filter(z=>z.type==="adhdev-daemon").sort(Ki),[n]),J=l.useMemo(()=>re.find(z=>z.id===W)||null,[re,W]),X=Wa({sendDaemonCommand:a,activeConv:R||void 0,setActionLogs:o,isStandalone:i}),ue=h1({sendDaemonCommand:a,navigate:T,ides:n,conversations:e}),se=uk(e),B=l.useMemo(()=>e.map(z=>{const ge=P==="chat"&&(R==null?void 0:R.tabKey)===z.tabKey,Ce=_a(z,N,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ge}),Ne=en(z),He=gp(z),Ze=Cp(z,He);return{conversation:z,timestamp:Ne,preview:Ze,unread:Ce.unread,requiresAction:Ce.requiresAction,isWorking:Ce.isWorking,inboxBucket:Ce.inboxBucket}}),[e,N,P,R,se]),{markConversationRead:ie}=u1({conversations:e,machineEntries:re,items:B,selectedConversation:R,selectedTabKey:A,screen:P,liveSessionInboxState:N,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,setSelectedTabKey:M,setScreen:D,setSelectedMachineId:H,setSection:_,setMachineBackTarget:O,resetMachineAction:ue.resetMachineAction}),K=f1({conversations:e,selectedConversation:R,machineBackTarget:L,markConversationRead:ie,resetMachineAction:ue.resetMachineAction,setSelectedTabKey:M,setScreen:D,setSelectedMachineId:H,setSection:_,setMachineBackTarget:O}),{isMuted:le,toggleMute:je}=xm(N,a),{attentionItems:we,unreadItems:ke,workingItems:he,completedItems:U}=l.useMemo(()=>o1(B,E.current),[B]);l.useEffect(()=>{E.current=he.map(z=>z.conversation.tabKey)},[he]);const q=l.useMemo(()=>J?B.filter(z=>Ts(z.conversation)===J.id):[],[B,J]),Z=l.useMemo(()=>l1(J,n),[n,J]),Y=(J==null?void 0:J.version)||null,fe=!!J&&!!Y&&!0&&Y!==$,Me=l.useMemo(()=>(J==null?void 0:J.availableProviders)||[],[J]),de=l.useMemo(()=>Me.filter(z=>Dn(z,"cli")).map(z=>({type:z.type,displayName:z.displayName||z.type,icon:z.icon})),[Me]),F=l.useMemo(()=>Me.filter(z=>Dn(z,"acp")).map(z=>({type:z.type,displayName:z.displayName||z.type,icon:z.icon})),[Me]),me=l.useMemo(()=>c1(re,B,t),[B,re,t]),ce=l.useCallback(async z=>{J&&await ue.handleOpenRecent(J.id,z)},[ue,J]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:P==="chat"&&R?s.jsx(Vj,{selectedConversation:R,isAcp:dt(R),isStandalone:i,selectedIdeEntry:G,actionLogs:r,userName:c,isSendingChat:X.isSendingChat,sendFeedbackMessage:X.sendFeedbackMessage,isFocusingAgent:X.isFocusingAgent,handleModalButton:X.handleModalButton,handleRelaunch:X.handleRelaunch,onBack:K.backFromConversation,onOpenNativeConversation:K.openNativeConversation,onOpenMachine:K.openConversationMachine,onOpenHistory:k,onOpenRemote:h,onOpenMeshGraph:y,onStopCli:v,cliViewMode:Q,onSetCliViewMode:async z=>{await Zp({conversation:R,mode:z,ides:n,sendDaemonCommand:a,setCliViewModeOverrides:S})},handleSendChat:X.handleSendChat,handleForceSendChat:X.handleForceSendChat,handleFocusAgent:X.handleFocusAgent}):P==="machine"&&J?s.jsx(n1,{selectedMachineEntry:J,selectedMachineConversations:q,selectedMachineRecentLaunches:Z,cliProviders:de,acpProviders:F,selectedMachineNeedsUpgrade:fe,appVersion:$,machineAction:ue.machineAction,isStandalone:i,section:I,showBottomNav:L==="inbox",onBack:K.backFromMachine,onSectionChange:K.changeMachineSection,onOpenConversation:K.openConversation,onOpenRecent:ce,onOpenMachineDetails:()=>T(`/machines/${J.id}`),onMachineUpgrade:()=>ue.handleMachineUpgrade(J.id),onLaunchDetectedIde:(z,ge)=>ue.handleLaunchDetectedIde(J.id,z,ge),onAddWorkspace:(z,ge)=>ue.handleAddWorkspace(J.id,z,ge),onBrowseDirectory:z=>ue.handleBrowseDirectory(J.id,z),onLaunchWorkspaceProvider:(z,ge,Ce)=>ue.handleLaunchWorkspaceProvider(J.id,z,ge,Ce),onListSavedSessions:z=>ue.handleListSavedSessions(J.id,z)}):s.jsx(Qj,{section:I,attentionItems:we,unreadItems:ke,workingItems:he,completedItems:U,hiddenConversations:t,machineCards:me,getAvatarText:b1,actionLogs:r,sendDaemonCommand:a,onOpenConversation:K.openConversation,onShowAllHidden:j,onHideConversation:C,onOpenMeshGraph:y,onStopCli:v,onOpenNewSession:x,onOpenMachine:K.openMachine,onOpenSettings:()=>T("/settings"),onSectionChange:_,wsStatus:w,isConnected:b,isStandalone:i,isConversationMuted:le,onToggleMuteConversation:je})})}function Ao(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function x1({conversations:e,numGroups:t,onMoveTab:n,onReceiveTab:r,onOwnTabDrop:a,onClearPreviewOrder:o}){const i=l.useRef(0),[c,d]=l.useState(!1),[p,u]=l.useState(null),m=l.useCallback(()=>{i.current=0,d(!1),u(null)},[]);l.useEffect(()=>(window.addEventListener("dragend",m),window.addEventListener("drop",m),()=>{window.removeEventListener("dragend",m),window.removeEventListener("drop",m)}),[m]);const f=l.useCallback(v=>{v.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,d(!0))},[]),g=l.useCallback(v=>{if(!v.dataTransfer.types.includes("text/tab-key"))return;if(v.preventDefault(),!Ao(t,n)){u("merge");return}const w=v.currentTarget.getBoundingClientRect(),b=v.clientX-w.left,j=w.width/3;b<j?u("split-left"):b>j*2?u("split-right"):u("merge")},[t,n]),k=l.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,d(!1),u(null))},[]),h=l.useCallback(v=>{i.current=0,d(!1);const w=v.dataTransfer.getData("text/tab-key"),b=w?e.some(C=>C.tabKey===w):!1,j=p;if(u(null),o(),!!w){if(v.preventDefault(),j==="split-left"&&Ao(t,n)){n==null||n(w,"split-left");return}if(j==="split-right"&&Ao(t,n)){n==null||n(w,"split-right");return}if(b){a(w);return}r==null||r(w)}},[e,p,t,n,r,a,o]);return{dragOver:c,dropAction:p,resetDragState:m,handleDragEnter:f,handleDragOver:g,handleDragLeave:k,handleDrop:h}}function v1(e,t){const n=new Set(t.map(o=>o.tabKey)),r=e.filter(o=>n.has(o)),a=t.filter(o=>!e.includes(o.tabKey)).map(o=>o.tabKey);return[...r,...a]}function y1({conversations:e,initialActiveTabId:t,initialTabOrder:n,onActiveTabChange:r,onTabOrderChange:a}){const[o,i]=l.useState(t??null),[c,d]=l.useState(n??[]),[p,u]=l.useState(null),m=l.useRef(null),f=l.useRef(null),g=l.useRef(r),k=l.useRef(a);l.useEffect(()=>{g.current=r},[r]),l.useEffect(()=>{k.current=a},[a]),l.useEffect(()=>{t&&t!==o&&i(t)},[t,o]),l.useEffect(()=>{d(N=>{const S=v1(N,e);return S.length===N.length&&S.every((A,M)=>A===N[M])?N:S})},[e]);const h=l.useMemo(()=>{const N=p??c;if(N.length===0)return e;const S=new Map(N.map((A,M)=>[A,M]));return[...e].sort((A,M)=>{const P=S.get(A.tabKey)??999,D=S.get(M.tabKey)??999;return P-D})},[e,p,c]);l.useEffect(()=>{var S,A;if(h.length===0){o!==null&&(i(null),(S=g.current)==null||S.call(g,null));return}if(o&&h.some(M=>M.tabKey===o))return;const N=h[0].tabKey;N!==o&&(i(N),(A=g.current)==null||A.call(g,N))},[h,o]);const v=l.useMemo(()=>h.find(N=>N.tabKey===o),[h,o]),w=l.useCallback(N=>{var S;i(N),(S=g.current)==null||S.call(g,N)},[]),b=l.useCallback((N,S,A)=>{d(M=>{var _;const P=M.filter(W=>W!==N),D=P.indexOf(S);if(D<0)return M;const I=A==="left"?D:D+1;return P.splice(I,0,N),(_=k.current)==null||_.call(k,P),P}),u(null)},[]),j=l.useCallback((N,S,A)=>{const P=(c.length>0?c:e.map(_=>_.tabKey)).filter(_=>_!==N),D=P.indexOf(S);if(D<0)return;const I=A==="left"?D:D+1;P.splice(I,0,N),m.current=P,u(P)},[c,e]),C=l.useCallback(()=>{var S;const N=m.current;N&&(d(N),(S=k.current)==null||S.call(k,N))},[]),y=l.useCallback(()=>{m.current=null,u(null)},[]),x=l.useCallback(N=>{d(S=>{var M;const A=S.filter(P=>P!==N);return A.push(N),(M=k.current)==null||M.call(k,A),A})},[]);return{activeTabId:o,activeConv:v,sortedConversations:h,previewOrderRef:m,draggingTabRef:f,selectTab:w,handleTabReorder:b,updatePreviewOrder:j,commitPreviewOrder:C,clearPreviewOrder:y,moveTabToEnd:x,setDraggingTabKey:N=>{f.current=N}}}function w1({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 xl({conversationsCount:e,isSplitMode:t,isStandalone:n,hasRegisteredMachines:r=!1,suppressGuide:a=!1,onOpenNewSession:o}){const{t:i}=Se("common");if(a)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const c=!n&&!r,d=r&&!!o,p=i(r?"paneGroup.noConversations":n?"paneGroup.waitingForDaemon":"paneGroup.connectYourMachines"),u=i(r?"paneGroup.newSessionDescription":n?"paneGroup.daemonDescription":"paneGroup.installDescription");return e===0&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:p}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:u}),d&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:o,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:i("paneGroup.newSession"),"aria-label":i("paneGroup.newSession"),children:[s.jsx(Wi,{size:14}),s.jsx("span",{children:i("paneGroup.newSession")})]})}),c&&s.jsx(mm,{}),c&&s.jsx("div",{className:"mt-8",children:s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:"📚 Read the documentation →"})})]})]}):s.jsx("div",{className:"text-sm text-text-muted opacity-50",children:t?"Move a tab here to view":"No active agent"})}const vm="adhdev-tab-shortcuts";function ym(){try{return JSON.parse(localStorage.getItem(vm)||"{}")}catch{return{}}}function wm({enabled:e=!0,sortedTabKeys:t,onFocus:n,onSelectTab:r}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>ym()),[c,d]=l.useState(null),p=l.useCallback(m=>{const f=[];return m.metaKey&&f.push(a?"⌘":"Meta"),m.ctrlKey&&f.push("Ctrl"),m.altKey&&f.push(a?"⌥":"Alt"),m.shiftKey&&f.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(m.key)?null:(f.push(m.key.length===1?m.key.toUpperCase():m.key),f.join("+"))},[a]),u=l.useCallback(m=>{i(m);try{localStorage.setItem(vm,JSON.stringify(m))}catch{}},[]);return l.useEffect(()=>{if(!e||!c)return;const m=f=>{if(f.preventDefault(),f.stopPropagation(),f.key==="Escape"){d(null);return}const g=p(f);if(!g)return;const k={...o};for(const[h,v]of Object.entries(k))v===g&&delete k[h];k[c]=g,u(k),d(null)};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[e,c,o,u,p]),l.useEffect(()=>{if(!e)return;const m=f=>{if(!(!f.ctrlKey&&!f.metaKey&&!f.altKey)){for(const[g,k]of Object.entries(o))if(t.includes(g)&&p(f)===k){f.preventDefault(),n(),r(g);return}}};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[e,o,t,n,r,p]),{isMac:a,tabShortcuts:o,shortcutListening:c,setShortcutListening:d,saveShortcuts:u}}const Mo=e=>{e.preventDefault()},k1=l.memo(function({conv:t,isActive:n,isDraggedTab:r,isTaskCompleteUnread:a,shortcut:o,conversationKeys:i,draggingTabRef:c,onFocus:d,onSelectTab:p,onConversationActivated:u,onPreviewReorder:m,onReorderTab:f,onCommitPreviewOrder:g,onClearPreviewOrder:k,onDragStateReset:h,onDragTabKeyChange:v,onReceiveTab:w,onOpenContextMenu:b,longPressTimer:j,isGroupActive:C}){const y=cn(t),x=y.isGenerating?"agent-tab-generating":y.isWaiting?"agent-tab-waiting":"",N=y.isReconnecting,S=Lk(t),A=Rk(t),M=Sp(t),P=l.useCallback(T=>{c.current=t.tabKey,v(t.tabKey),T.dataTransfer.setData("text/tab-key",t.tabKey),T.dataTransfer.effectAllowed="move"},[t.tabKey,c,v]),D=l.useCallback(()=>{c.current=null,v(null),g(),k(),h()},[c,v,g,k,h]),I=l.useCallback(T=>{const $=c.current;if(!(!$||$===t.tabKey)&&T.dataTransfer.types.includes("text/tab-key")){T.preventDefault(),T.stopPropagation();const R=T.currentTarget.getBoundingClientRect(),G=T.clientX<R.left+R.width/2?"left":"right";m($,t.tabKey,G)}},[t.tabKey,c,m]),_=l.useCallback(T=>{T.preventDefault(),T.stopPropagation();const $=T.dataTransfer.getData("text/tab-key");if($&&$!==t.tabKey){const R=T.currentTarget.getBoundingClientRect(),G=T.clientX<R.left+R.width/2?"left":"right";i.includes($)?f($,t.tabKey,G):w&&w($)}k()},[t.tabKey,i,f,w,k]),W=l.useCallback(T=>{T.stopPropagation(),d(),p(t.tabKey),u(t)},[t,u,d,p]),H=l.useCallback(T=>{T.preventDefault(),b(T.clientX,T.clientY,t.tabKey)},[t.tabKey,b]),L=l.useCallback(T=>{const $=T.touches[0];j.current=setTimeout(()=>{b($.clientX,$.clientY,t.tabKey)},600)},[t.tabKey,j,b]),O=l.useCallback(()=>{j.current&&clearTimeout(j.current)},[j]),E=["adhdev-dockview-tab",x,n&&"is-active",C&&"is-group-active",N&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:E,draggable:!0,onDragStart:P,onDragEnd:D,onDragOver:I,onDrop:_,onClick:W,onContextMenu:H,onTouchStart:L,onTouchEnd:O,onTouchMove:O,style:{position:"relative",cursor:"pointer",opacity:r?.4:void 0},children:[M&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-badge pointer-events-none absolute top-0.5 right-0.5 text-text-muted",title:"Mesh chat","aria-label":"Mesh chat",children:s.jsx(ts,{size:11})}),a&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:y.isGenerating?s.jsx("div",{className:"tab-spinner"}):y.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):N?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):y.isConnecting?s.jsx("div",{className:"tab-connecting-spinner"}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),S.length>0&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-role",title:A,"aria-label":A||S.join(" · "),children:S.join(" · ")}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:xt(t),children:xt(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[N?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:Qs(t)}):y.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[Qs(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:Qs(t)}),s.jsx(ya,{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 S1({conversations:e,activeTabId:t,groupIndex:n,unreadTabKeys:r,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:m,onDragStateReset:f,onDragTabKeyChange:g,onReceiveTab:k,onHideTab:h,isGroupActive:v,allowTabShortcuts:w=!0}){const{t:b}=Se("common"),[j,C]=l.useState(null),y=l.useRef(null),x=l.useRef(null),N=l.useMemo(()=>e.map(_=>_.tabKey),[e]);kr("PaneGroupTabBar",{groupIndex:n,activeTabId:t,tabCount:e.length,ctxMenuTab:(j==null?void 0:j.tabKey)||null});const{isMac:S,tabShortcuts:A,shortcutListening:M,setShortcutListening:P,saveShortcuts:D}=wm({enabled:w,sortedTabKeys:e.map(_=>_.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!j)return;const _=W=>{const H=document.querySelector("[data-pane-context-menu]");H&&H.contains(W.target)||C(null)};return window.addEventListener("mousedown",_,!0),()=>window.removeEventListener("mousedown",_,!0)},[j]),l.useEffect(()=>{const _=x.current;if(!_)return;const W=H=>{Math.abs(H.deltaY)<=Math.abs(H.deltaX)||(H.preventDefault(),_.scrollLeft+=H.deltaY)};return _.addEventListener("wheel",W,{passive:!1}),()=>_.removeEventListener("wheel",W)},[]);const I=l.useCallback((_,W,H)=>{C({x:_,y:W,tabKey:H})},[]);return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:s.jsxs("div",{ref:x,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(_=>s.jsx(k1,{conv:_,isActive:t===_.tabKey,isDraggedTab:a.current===_.tabKey,isTaskCompleteUnread:r.has(_.tabKey),shortcut:w?A[_.tabKey]:void 0,conversationKeys:N,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:m,onDragStateReset:f,onDragTabKeyChange:g,onReceiveTab:k,onOpenContextMenu:I,longPressTimer:y,isGroupActive:v},_.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:b("paneGroup.noTabsInGroup")})]})}),j&&s.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:j.x,top:j.y},children:[w&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:Mo,onClick:_=>{_.stopPropagation(),P(j.tabKey),C(null)},children:["⌨ ",A[j.tabKey]?`Change shortcut (${A[j.tabKey]})`:"Set shortcut"]}),A[j.tabKey]&&s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onMouseDown:Mo,onClick:()=>{const _={...A};delete _[j.tabKey],D(_),C(null)},children:"✕ Remove shortcut"})]}),h&&s.jsxs(s.Fragment,{children:[w&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onMouseDown:Mo,onClick:()=>{h(j.tabKey),C(null)},children:"🚫 Hide from Dashboard"})]})]}),w&&M&&s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:()=>P(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:_=>_.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",S?"⌘+1":"Ctrl+1",", ",S?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:b("paneGroup.pressEscToCancel")})]})})]})}function C1({conversations:e,ides:t,clearedTabs:n,actionLogs:r,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,userName:d,groupIndex:p,onFocus:u,isSplitMode:m,numGroups:f,onMoveTab:g,onReceiveTab:k,style:h,onActiveTabChange:v,initialActiveTabId:w,initialTabOrder:b,onTabOrderChange:j,onHideTab:C,isFocused:y,allowTabShortcuts:x=!0,onOpenNewSession:N,liveSessionInboxState:S}){const{sendCommand:A}=vt(),M=l.useRef(null),{activeTabId:P,activeConv:D,sortedConversations:I,draggingTabRef:_,selectTab:W,handleTabReorder:H,updatePreviewOrder:L,commitPreviewOrder:O,clearPreviewOrder:E,moveTabToEnd:T,setDraggingTabKey:$}=y1({conversations:e,initialActiveTabId:w,initialTabOrder:b,onActiveTabChange:v,onTabOrderChange:j}),R=Wa({sendDaemonCommand:a,activeConv:D,setActionLogs:o,isStandalone:i}),{dragOver:G,dropAction:Q,resetDragState:re,handleDragEnter:J,handleDragOver:X,handleDragLeave:ue,handleDrop:se}=x1({conversations:e,numGroups:f,onMoveTab:g,onReceiveTab:k,onOwnTabDrop:T,onClearPreviewOrder:E}),B=D&&!dt(D)&&En(D)==="terminal",ie=l.useMemo(()=>D?t.find(we=>we.id===D.routeId):void 0,[t,D]),K=l.useMemo(()=>D?r.filter(we=>we.routeId===D.tabKey):[],[r,D]),le=l.useMemo(()=>new Set(I.filter(we=>Gb(we,S,{isOpenConversation:we.tabKey===P})).map(we=>we.tabKey)),[P,S,I]);kr("PaneGroup",{groupIndex:p,conversationCount:e.length,activeTabId:P,dragOver:G});const je=l.useCallback(we=>{we.streamSource==="agent-stream"&&we.agentType&&A(we.routeId,rp(),{agentType:we.agentType,...we.sessionId&&{targetSessionId:we.sessionId}}).catch(()=>{})},[A]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:u,style:{...h,outline:G?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(S1,{conversations:I,activeTabId:P,groupIndex:p,numGroups:f,unreadTabKeys:le,draggingTabRef:_,onFocus:u,onSelectTab:W,onConversationActivated:je,onPreviewReorder:L,onReorderTab:H,onCommitPreviewOrder:O,onClearPreviewOrder:E,onDragStateReset:re,onDragTabKeyChange:$,onMoveTab:g,onReceiveTab:k,onHideTab:C,isGroupActive:y??!1,allowTabShortcuts:x}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:J,onDragOver:X,onDragLeave:ue,onDrop:se,children:[G&&s.jsx(w1,{dropAction:Q,canSplit:!!(f<4&&g)}),D?s.jsx(fl,{activeConv:D,clearToken:n[D.tabKey]||0,isCliTerminal:!!B,ideEntry:ie,terminalRef:M,handleModalButton:R.handleModalButton,handleRelaunch:R.handleRelaunch,handleSendChat:R.handleSendChat,handleForceSendChat:R.handleForceSendChat,isSendingChat:R.isSendingChat,sendFeedbackMessage:R.sendFeedbackMessage,handleFocusAgent:R.handleFocusAgent,isFocusingAgent:R.isFocusingAgent,actionLogs:K,userName:d,isInputActive:!m||!!y}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(xl,{conversationsCount:e.length,isSplitMode:m,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:N})})]})]})}function j1({containerRef:e,isSplitMode:t,numGroups:n,groupSizes:r,groupedConvs:a,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:p,isStandalone:u,hasRegisteredMachines:m,userName:f,focusedGroup:g,focusGroup:k,moveTabToGroup:h,splitTabRelative:v,closeGroup:w,handleResizeStart:b,groupActiveTabIds:j,setGroupActiveTab:C,groupTabOrders:y,setGroupTabOrder:x,toggleHiddenTab:N,onOpenNewSession:S,allowTabShortcuts:A=!0,liveSessionInboxState:M}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((P,D)=>{const I=t&&r.length===n?`${r[D]}%`:void 0;return s.jsxs(Rt.Fragment,{children:[t&&D>0&&s.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:_=>b(D-1,_),onDoubleClick:()=>w(D),title:"Drag to resize · Double-click to merge",children:s.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),s.jsx(C1,{style:t?{flexBasis:I??`${100/n}%`,flexGrow:I?0:1,flexShrink:I?0:1}:void 0,conversations:P,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:p,isStandalone:u,hasRegisteredMachines:m,userName:f,groupIndex:D,isFocused:t&&g===D,onFocus:()=>k(D),isSplitMode:t,numGroups:n,onMoveTab:(_,W)=>{W==="left"&&D>0?h(_,D-1):W==="right"&&D<n-1?h(_,D+1):W==="split-left"&&n<4?v(_,D,"left"):W==="split-right"&&n<4&&v(_,D,"right")},onReceiveTab:_=>h(_,D),onActiveTabChange:_=>C(D,_),initialActiveTabId:j[D],initialTabOrder:y[D],onTabOrderChange:_=>x(D,_),onHideTab:N,onOpenNewSession:S,allowTabShortcuts:A,liveSessionInboxState:M})]},D)})})}const km="adhdev-dashboard-action-shortcuts",N1=1200,A1=[["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 M1(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function mt(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 Sm(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:mt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:mt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:mt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:mt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:mt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:mt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:mt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:mt("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:mt("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:mt("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:mt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:mt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:mt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:mt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:mt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:mt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:mt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:mt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:mt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:mt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:mt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:mt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:mt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:mt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:mt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:mt("toggleCliView",e)}]}function Ni(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function Ta(e){const t=Object.fromEntries(Sm(e).map(n=>[n.id,n.defaultShortcut]));try{const n=JSON.parse(localStorage.getItem(km)||"{}"),r={...t,...n};for(const[a,o]of A1)r[a]===o&&(r[a]=t[a]);return r}catch{return t}}function Cm(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function T1({enabled:e=!0,onTrigger:t}){const n=M1(),[r,a]=l.useState(()=>Ta(n)),[o,i]=l.useState(null),[c,d]=l.useState([]),p=l.useRef({parts:[],timer:null}),u=l.useCallback(h=>{const v=[];return h.metaKey&&v.push(n?"⌘":"Meta"),h.ctrlKey&&v.push("Ctrl"),h.altKey&&v.push(n?"⌥":"Alt"),h.shiftKey&&h.key.length!==1&&v.push(n?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(v.push(Cm(h.key)),v.join("+"))},[n]),m=l.useCallback(h=>{a(h);try{localStorage.setItem(km,JSON.stringify(h))}catch{}},[]);l.useEffect(()=>{const h=Ta(n),v=Object.entries(r),w=Object.entries(h);v.length===w.length&&v.every(([b,j])=>h[b]===j)||m(h)},[r,n,m]);const f=l.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),g=l.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},N1))},[]);l.useEffect(()=>{if(!o)return;const h=v=>{if(v.preventDefault(),v.stopPropagation(),v.key==="Escape"){i(null),d([]);return}const w=u(v);if(!w)return;const j=!(v.metaKey||v.ctrlKey||v.altKey)&&/^[A-Z0-9]$/.test(w);if(c.length===0&&j){d([w]);return}const y=[...c,w].slice(0,2).join(" "),x={...r};for(const[N,S]of Object.entries(x))S===y&&delete x[N];x[o]=y,m(x),i(null),d([])};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[r,u,m,o,c]),l.useEffect(()=>{if(!e||o)return;const h=v=>{if(v.defaultPrevented)return;const w=u(v);if(!w)return;const b=v.metaKey||v.ctrlKey||v.altKey;if(Ni(v.target))return;const j=p.current.parts,C=b?[w]:[...j.slice(-1),w].slice(-2),y=C.join(" "),x=C[C.length-1],N=Object.entries(r).filter(([,D])=>!!D),S=N.find(([,D])=>D===y);if(S){v.preventDefault(),f(),t(S[0]);return}if(N.some(([,D])=>D.startsWith(`${y} `))){v.preventDefault(),p.current.parts=C,g();return}const M=N.find(([,D])=>D===x);if(M){v.preventDefault(),f(),t(M[0]);return}if(N.some(([,D])=>D.startsWith(`${x} `))){v.preventDefault(),p.current.parts=[x],g();return}f()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[r,g,e,u,t,f,o]),l.useEffect(()=>()=>f(),[f]);const k=l.useMemo(()=>Sm(n),[n]);return{isMac:n,actionDefinitions:k,actionShortcuts:r,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:d,saveShortcuts:m}}function I1({isTabInPopout:e,isTabFloating:t,tabShortcut:n,actionShortcuts:r}){const a=[];return e?(t&&a.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:r.dockActiveTab}),a.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:r.dockActiveTab})):t?a.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:r.dockActiveTab}):a.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:r.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:r.popoutActiveTab}),a.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:n?`Change shortcut (${n})`:"Set shortcut",shortcut:r.setActiveTabShortcut}),n&&a.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),a.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:r.hideCurrentTab,tone:"muted"}),a}function jm(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function rd({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:n,ides:r}){return!e||n>0?!1:t?!jm(r):!0}function D1({previousVisibleConversationCount:e,visibleConversationCount:t,ides:n}){return t>0||e<=0?!1:jm(n)}const Nm=1e3,P1=4;function ad(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function od(e,t,n){return Math.abs(t.clientX-e.clientX)>n||Math.abs(t.clientY-e.clientY)>n}function L1({detachDelayMs:e=Nm,stillnessThresholdPx:t=P1,onDetach:n,setTimeoutFn:r=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let o=null,i=null,c=null,d=null,p=null,u=!1;const m=()=>{p!=null&&(a(p),p=null)},f=()=>{m(),c=null},g=()=>{m(),o=null,i=null,c=null,d=null,u=!1},k=()=>{!o||!c||!d||u||p!=null||(p=r(()=>{p=null,!(!o||!c||!d||u)&&ad(d,i)&&(od(c,d,t)||(u=!0,n({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},h=w=>{if(!(!o||u)){if(!ad(w,i)){d={clientX:w.clientX,clientY:w.clientY},f();return}(!c||od(c,w,t))&&(m(),c={clientX:w.clientX,clientY:w.clientY}),d={clientX:w.clientX,clientY:w.clientY},k()}},v=w=>{!o||u||(w&&(d={clientX:w.clientX,clientY:w.clientY}),f())};return{startDrag:w=>{m(),o=w.panelId,i=w.selfPanelBounds??null,c=null,d={clientX:w.clientX,clientY:w.clientY},u=!1},markSelfPanel:h,markNonSelfPanel:v,markNoDropTarget:v,markDockTarget:v,endDrag:g,isDragging:()=>o!=null,hasDetached:()=>u,dispose:g}}function R1(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function ia(e){return xt(e)||e.tabKey}function E1(e){return`remote:${e}`}function is(e){return e.startsWith("remote:")}function id(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function To(e){var r;const t=e==null?void 0:e.defaultView;if(!t)return;const n=a=>{if(a)try{a.focus({preventScroll:!0})}catch{try{a.focus()}catch{}}};try{t.focus(),n(e==null?void 0:e.body),n(e==null?void 0:e.documentElement),(r=t.requestAnimationFrame)==null||r.call(t,()=>{try{t.focus(),n(e==null?void 0:e.body)}catch{}})}catch{}}function Io(e,t){e.classList.remove(Qo.className,Xo.className),e.classList.add(t==="light"?Qo.className:Xo.className)}function ld(e){return e?Array.from(new Set(e.groups.map(t=>{var n,r;return(r=(n=t.element)==null?void 0:n.ownerDocument)==null?void 0:r.defaultView}).filter(t=>!!t&&t!==window))):[]}function _1(e,t,n){var i;const r=[t];let a;for(const c of r){let d;for(const p of c){const u=e.addPanel({id:p.tabKey,component:"conversation",title:ia(p),params:{kind:"conversation",tabKey:p.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});d||(d=u.id)}a=d??a}return n??((i=t[0])==null?void 0:i.tabKey)??null}function cd(e,t){const n=new Set(t.map(a=>a.tabKey)),r=new Map;for(const a of t)r.set(a.tabKey,(r.get(a.tabKey)||0)+1);for(const a of[...e.panels])is(a.id)||n.has(a.id)||e.removePanel(a);for(const a of t){const o=e.getPanel(a.tabKey);if(o){(r.get(a.tabKey)||0)>1&&console.warn("[dashboard-conversations] Dockview panel already exists for duplicate tabKey",{tabKey:a.tabKey,daemonId:a.daemonId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,panelId:o.id}),o.update({params:{tabKey:a.tabKey}}),o.title!==ia(a)&&o.api.setTitle(ia(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:ia(a),params:{kind:"conversation",tabKey:a.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function dd(e,t,n){var d,p;const r=n?E1(n):null;for(const u of[...e.panels])is(u.id)&&(!r||u.id!==r)&&e.removePanel(u);if(!n||!r)return;const a=ps(t,n);if(!a&&e.totalPanels===0)return;const o=e.getPanel(r),i=Ap(a);if(o){o.title!==i&&o.api.setTitle(i);return}const c=(a==null?void 0:a.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((p=e.panels.find(u=>!is(u.id)))==null?void 0:p.id);e.addPanel({id:r,component:"remote",title:i,params:{kind:"remote",routeId:n},...c?{position:{referencePanel:c,direction:"right"},inactive:!0}:{}})}function Am({doId:e,targetSessionId:t,connState:n,viewMode:r}){const[a,o]=l.useState(null),[i,c]=l.useState(null);l.useEffect(()=>e?wt.onScreenshot("ide-page",(u,m)=>{if(u!==e)return;const f=new FileReader;f.onload=()=>o(f.result),f.readAsDataURL(m)}):void 0,[e]),l.useEffect(()=>{n!=="connected"&&o(null)},[n]),l.useEffect(()=>{var u;return e?((u=wt.onStatus)==null?void 0:u.call(wt,(m,f)=>{m===e&&f!=null&&f.screenshotUsage&&c(f.screenshotUsage)}))||(()=>{}):void 0},[e]),l.useEffect(()=>{o(null)},[e,t]),l.useEffect(()=>{const p=e?wt.get(e):null;if(!(!p||n!=="connected"))return r!=="chat"&&t?p.startScreenshots(t):p.stopScreenshots(t),()=>{p.stopScreenshots(t)}},[r,n,t,e]);const d=l.useCallback(async(p,u)=>{const m=e?wt.get(e):null;return!m||n!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):m.sendInput(p,u,t)},[e,n,t]);return{connScreenshot:a,screenshotUsage:i,handleRemoteAction:d}}const Mm=l.createContext(null);function qa(){const e=l.useContext(Mm);if(!e)throw new Error("DashboardDockviewContext missing");return e}function $1(e){const[,t]=l.useState(0);l.useEffect(()=>{const n=()=>t(a=>a+1),r=[e.api.onDidActiveGroupChange(n),e.api.onDidTitleChange(n),e.api.onDidGroupChange(n),e.containerApi.onDidActivePanelChange(n)];return()=>{for(const a of r)a.dispose()}},[e.api,e.containerApi])}function H1({params:e}){var d;const t=qa(),n=l.useMemo(()=>ps([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),r=l.useMemo(()=>t.ides.find(p=>p.id===e.routeId),[t.ides,e.routeId]),a=(n==null?void 0:n.daemonId)||((d=n==null?void 0:n.routeId)==null?void 0:d.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:i,handleRemoteAction:c}=Am({doId:a,targetSessionId:n?np(n):(r==null?void 0:r.sessionId)||(r==null?void 0:r.instanceId),connState:(n==null?void 0:n.connectionState)||"new",viewMode:"remote"});return n?s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:s.jsx(ju,{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 F1(){const e=qa();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(xl,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function B1(e){var b,j;$1(e);const t=qa(),n=l.useCallback(C=>{"button"in C&&C.button!==0||e.api.setActive()},[e.api]),r=e.params.kind==="remote"?void 0:t.conversationsByTabKey.get(e.params.tabKey),a=r==null?void 0:r.sessionId,o=l.useCallback(C=>fk(C),[]),i=l.useCallback(()=>hk(a),[a]),c=l.useSyncExternalStore(o,i,i);if(e.params.kind==="remote"){const C=ps([...t.conversationsByTabKey.values()],e.params.routeId),y=((b=e.api.group.activePanel)==null?void 0:b.id)===e.api.id,x=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${y?" is-active":""}${x?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(C==null?void 0:C.tabKey)||"",onMouseDown:n,onTouchStart:n,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:C!=null&&C.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:C.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const d=t.conversationsByTabKey.get(e.params.tabKey);if(!d)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const p=((j=e.api.group.activePanel)==null?void 0:j.id)===e.api.id,u=e.api.isGroupActive,m=_a(d,t.liveSessionInboxState,{isOpenConversation:p}),f=m.isReconnecting,g=m.isConnecting,k=m.isGenerating||c,h=m.isWaiting,v=m.unread,w=t.tabShortcuts[d.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${p?" is-active":""}${u?" is-group-active":""}${f?" is-reconnecting":""}`,title:xt(d),"data-tab-key":e.params.tabKey,onMouseDown:n,onTouchStart:n,onContextMenu:C=>{var y;C.preventDefault(),n(C),t.openTabContextMenu({x:C.clientX,y:C.clientY,tabKey:d.tabKey,sourceDocument:((y=C.target)==null?void 0:y.ownerDocument)??document})},children:[v&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:k?s.jsx("div",{className:"tab-spinner"}):h?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):f?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):g?s.jsx("div",{className:"tab-connecting-spinner"}):d.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:xt(d)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:f?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Qs(d)}):g?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Qs(d)}):s.jsx("span",{children:Qs(d)})})]}),w&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:w,children:w})]})}function qr(e){return e.isActive}function ud(e){return e.isVisible}function O1(e){e.preventDefault()}function W1({params:e,api:t}){var g;const n=qa(),r=l.useRef(null),[a,o]=l.useState(()=>qr(t)),[i,c]=l.useState(()=>ud(t)),d=n.conversationsByTabKey.get(e.tabKey),p=Wa({sendDaemonCommand:n.sendDaemonCommand,activeConv:d,setActionLogs:n.setActionLogs,isStandalone:n.isStandalone});l.useEffect(()=>{o(qr(t)),c(ud(t));const k=[t.onDidActiveChange(h=>o(h.isActive)),t.onDidActiveGroupChange(h=>{if(!qr(t)&&!h.isActive){o(!1);return}o(qr(t))}),t.onDidVisibilityChange(h=>c(h.isVisible))];return()=>{for(const h of k)h.dispose()}},[t]);const u=l.useMemo(()=>d?n.ides.find(k=>k.id===d.routeId):void 0,[n.ides,d]),m=l.useMemo(()=>d?n.actionLogs.filter(k=>k.routeId===d.tabKey):[],[n.actionLogs,d]);if(!d)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(xl,{conversationsCount:0,isSplitMode:!1,isStandalone:n.isStandalone,hasRegisteredMachines:n.hasRegisteredMachines,onOpenNewSession:n.onOpenNewSession,suppressGuide:n.hasDetachedConversationPanels})});const f=!dt(d)&&En(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(fl,{activeConv:d,clearToken:n.clearedTabs[d.tabKey]||0,isCliTerminal:f,ideEntry:u,terminalRef:r,handleModalButton:p.handleModalButton,handleRelaunch:p.handleRelaunch,handleSendChat:p.handleSendChat,handleForceSendChat:p.handleForceSendChat,isSendingChat:p.isSendingChat,handleFocusAgent:p.handleFocusAgent,isFocusingAgent:p.isFocusingAgent,actionLogs:m,userName:n.userName,scrollToBottomRequestNonce:((g=n.scrollToBottomRequest)==null?void 0:g.tabKey)===d.tabKey?n.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:i})})}function U1({visibleConversations:e,clearedTabs:t,ides:n,actionLogs:r,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:d,userName:p,toggleHiddenTab:u,actionShortcuts:m,registerActionHandlers:f,onActiveTabChange:g,onOpenNewSession:k,onRequestScrollToBottom:h,requestedActiveTabKey:v,requestedRemoteIdeId:w,onRequestedActiveTabConsumed:b,scrollToBottomRequest:j,liveSessionInboxState:C,layoutProfile:y}){var lt,ct,Nt;const{theme:x}=Fs(),{sendCommand:N}=vt(),S=l.useRef(null),A=l.useRef(null),M=l.useRef(null),P=l.useRef(!1),D=l.useRef(!1),I=l.useRef(!1),_=l.useRef(null),W=l.useRef([]),[H,L]=l.useState(null),[O,E]=l.useState(0),T=l.useRef(typeof window>"u"?{}:oj(y)),$=l.useMemo(()=>new Map(e.map(V=>[V.tabKey,V])),[e]),R=l.useMemo(()=>{const V=S.current;return V?V.groups.some(ee=>{try{const oe=ee.model.location.type;return oe!=="floating"&&oe!=="popout"?!1:ee.panels.some(pe=>$.has(pe.id))}catch{return!1}}):!1},[$,O,e]),G=l.useCallback(()=>{var V;(V=S.current)==null||V.focus()},[]),Q=l.useCallback((V,ee)=>{h==null||h(V,ee)},[h]),re=l.useCallback(V=>{const ee=document,oe=V.document;for(const De of ee.querySelectorAll('link[rel="stylesheet"]')){const Ue=oe.createElement("link");Ue.rel="stylesheet",Ue.href=De.href,De.crossOrigin&&(Ue.crossOrigin=De.crossOrigin),oe.head.appendChild(Ue)}for(const De of ee.querySelectorAll("style")){const Ue=oe.createElement("style");Ue.textContent=De.textContent,oe.head.appendChild(Ue)}const pe=[];for(const De of ee.styleSheets)try{for(const Ue of De.cssRules)Ue instanceof CSSStyleRule&&(Ue.selectorText===":root"||Ue.selectorText==="html")&&pe.push(Ue.cssText)}catch{}if(pe.length>0){const De=oe.createElement("style");De.textContent=pe.join(`
|
|
69
|
+
Use this if you want to permanently remove a machine.`,confirmLabel:o("machine.connectedMachines.remove"),confirmColor:"red",onConfirm:M,onCancel:()=>m(null)})]})}const oC=["default","claude-cli","codex-cli","antigravity-cli","hermes-cli","gemini-cli"];function iC({daemonId:e,knownCliTypes:t=oC}){const{t:n}=Se("common"),{sendCommand:r}=vt(),[a,o]=l.useState({}),[i,c]=l.useState({}),[d,p]=l.useState(!0),[u,m]=l.useState(null),[f,g]=l.useState(null),[k,h]=l.useState(""),v=l.useCallback(async()=>{if(e){p(!0),g(null);try{const j=await r(e,"list_coordinator_prompts",{}),C=j!=null&&j.result&&typeof j.result=="object"?j.result:j;if(!(C!=null&&C.success)){g((C==null?void 0:C.error)||"Failed to load");return}const y=C.entries||{};h(C.dir||"");const x={};for(const N of t)x[N]=y[N]||{override:"",append:""};for(const N of Object.keys(y))x[N]||(x[N]=y[N]);o(x),c(JSON.parse(JSON.stringify(x)))}catch(j){g((j==null?void 0:j.message)||String(j))}finally{p(!1)}}},[r,e,t]);l.useEffect(()=>{v()},[v]);const w=l.useCallback(async(j,C)=>{var y;if(e){m(`${j}:${C}`),g(null);try{const x=((y=a[j])==null?void 0:y[C])||"",N=await r(e,"write_coordinator_prompt",{key:j,kind:C,content:x}),S=N!=null&&N.result&&typeof N.result=="object"?N.result:N;if(!(S!=null&&S.success)){g((S==null?void 0:S.error)||"Save failed");return}c(A=>({...A,[j]:{...A[j]||{override:"",append:""},[C]:x}}))}catch(x){g((x==null?void 0:x.message)||String(x))}finally{m(null)}}},[r,e,a]),b=l.useMemo(()=>(j,C)=>{var y,x;return(((y=a[j])==null?void 0:y[C])||"")!==(((x=i[j])==null?void 0:x[C])||"")},[a,i]);return e?s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{className:"text-[12px] text-text-muted",children:[s.jsxs("p",{children:["Customize the coordinator prompt this daemon's mesh coordinator sessions get. ",s.jsx("span",{className:"font-mono text-[11px]",children:k||"~/.adhdev/coordinator-prompts/"})]}),s.jsxs("p",{className:"mt-1",children:[s.jsx(Jo,{i18nKey:"settings.coordinatorPrompts.overrideDesc",ns:"common",components:{strong:s.jsx("strong",{})}})," ",s.jsx(Jo,{i18nKey:"settings.coordinatorPrompts.appendDesc",ns:"common",components:{strong:s.jsx("strong",{})}}),"Leave a field empty + Save to remove it (reset to default). Supports placeholders: ","{{meshName}}",", ","{{repo}}",", ","{{nodes}}",", ","{{rules}}",", etc."]})]}),f&&s.jsx("div",{className:"text-[12px] text-status-error bg-status-error/10 border border-status-error/40 rounded px-3 py-2",children:f}),d&&s.jsx("div",{className:"text-[12px] text-text-muted",children:"Loading…"}),s.jsx("div",{className:"flex flex-col gap-6",children:Object.entries(a).map(([j,C])=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 p-3",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-2",children:j}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:n("settings.coordinatorPrompts.overrideLabel")}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:4,value:C.override,onChange:y=>o(x=>({...x,[j]:{...x[j],override:y.target.value}})),placeholder:"(empty — use daemon default base prompt)",disabled:u===`${j}:override`}),s.jsx("div",{className:"mt-1 mb-3 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void w(j,"override"),disabled:u===`${j}:override`||!b(j,"override"),children:u===`${j}:override`?"Saving…":b(j,"override")?"Save override":"Saved"})}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:n("settings.coordinatorPrompts.appendLabel")}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:3,value:C.append,onChange:y=>o(x=>({...x,[j]:{...x[j],append:y.target.value}})),placeholder:"(empty — nothing appended at this layer)",disabled:u===`${j}:append`}),s.jsx("div",{className:"mt-1 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void w(j,"append"),disabled:u===`${j}:append`||!b(j,"append"),children:u===`${j}:append`?"Saving…":b(j,"append")?"Save append":"Saved"})})]},j))})]}):s.jsx("div",{className:"text-[12px] text-text-muted",children:"Connect a daemon to edit coordinator prompts."})}const lC=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function cC(){const{preference:e,setPreference:t}=Fs();return s.jsx("div",{className:"flex gap-2",children:lC.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 dC(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 uC(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function xo(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Oc(e){const{r:t,g:n,b:r}=uC(e);return .2126*xo(t)+.7152*xo(n)+.0722*xo(r)}function Wc(e,t){const n=Oc(e),r=Oc(t),a=Math.max(n,r),o=Math.min(n,r);return(a+.05)/(o+.05)}function zp(e){const t=dC(e);if(!t)return"#111827";const n="#111827",r="#ffffff";return Wc(t,n)>=Wc(t,r)?n:r}const wi={bgPrimary:"#0a0e1a",bgSecondary:"#0f1320",surfacePrimary:"#111726",textPrimary:"#f0f0f5",textSecondary:"#9ca3af",textMuted:"#6b7280",borderSubtle:"#1d2536",borderDefault:"#313c52",accentColor:"#d97706",userBubble:"#f59e0b",userText:"#1a1a1a",assistantBubble:"#111726",assistantText:"#f0f0f5",containerBg:"#0f1320",sendButton:"#d97706",inputBorder:"#313c52",bubbleRadius:16},ki={bgPrimary:"#fff8ee",bgSecondary:"#fff1de",surfacePrimary:"#ffffff",textPrimary:"#24160f",textSecondary:"#6f6255",textMuted:"#938374",borderSubtle:"#e7d3ba",borderDefault:"#d7b892",accentColor:"#d97706",userBubble:"#f59e0b",userText:"#1a1a1a",assistantBubble:"#fffaf4",assistantText:"#24160f",containerBg:"#fff8ee",sendButton:"#d97706",inputBorder:"#d7b892",bubbleRadius:16},pC=[{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"}}}],Kp="adhdev-chat-theme",Vp="adhdev-chat-theme-custom";function ra(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Kp)||"ember"}catch{return"ember"}}function cs(e){try{const t=localStorage.getItem(Vp);if(t){const n=JSON.parse(t);return{...e==="dark"?wi:ki,...n[e]}}}catch{}return e==="dark"?wi:ki}function Fr(e,t){try{localStorage.setItem(Vp,JSON.stringify({dark:e,light:t}))}catch{}}function Xt(e,t){const n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),a=parseInt(e.slice(5,7),16);return`rgba(${n}, ${r}, ${a}, ${t})`}function Aa(e,t){const n=Math.min(255,parseInt(e.slice(1,3),16)+t),r=Math.min(255,parseInt(e.slice(3,5),16)+t),a=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${n.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const mC={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function cr(e,t){var a;const n=(a=mC[e])==null?void 0:a[t];if(!n)return;const r=document.documentElement;r.style.setProperty("--accent-primary",n),r.style.setProperty("--accent-primary-light",Aa(n,24)),r.style.setProperty("--accent-on-primary",zp(n)),r.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${n}, ${Aa(n,18)})`),r.style.setProperty("--border-accent",Xt(n,.35)),r.style.setProperty("--nav-active-bg",Xt(n,.1)),r.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${n}, 0 0 12px ${Xt(n,.06)}`)}function Xs(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",Xt(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Xt(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Xt(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",Xt(e.borderSubtle,.5)),t.style.setProperty("--border-default",Xt(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",Aa(e.accentColor,30)),t.style.setProperty("--accent-on-primary",zp(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Aa(e.accentColor,40)})`),t.style.setProperty("--border-accent",Xt(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",Xt(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Xt(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 ${Xt(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 il(){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 hC(e){try{localStorage.setItem(Kp,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=Zs()?"dark":"light";Xs(cs(t))}else il(),cr(e,Zs()?"dark":"light")}function fC(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=ra();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=Zs()?"dark":"light";Xs(cs(t))}else il(),cr(e,Zs()?"dark":"light")}function Zs(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Ot({label:e,value:t,onChange:n}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[s.jsx("input",{type:"color",value:t,onChange:r=>n(r.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),s.jsx("input",{type:"text",value:t,onChange:r=>{/^#[0-9a-fA-F]{0,6}$/.test(r.target.value)&&n(r.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function Kn({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 bC({dark:e,onColorsChange:t}){const{t:n}=Se("common"),r=e?"dark":"light",[a,o]=l.useState(()=>cs(r));l.useEffect(()=>{o(cs(r))},[r]);const i=l.useCallback((c,d)=>{o(p=>{const u={...p,[c]:d},f=cs(r==="dark"?"light":"dark");return r==="dark"?Fr(u,f):Fr(f,u),Xs(u),t(u),u})},[r,t]);return s.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[s.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[n("settings.theme.customEditorTitle"),s.jsx("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:n(e?"settings.theme.darkMode":"settings.theme.lightMode")})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs(Kn,{title:n("settings.theme.sectionAppBackground"),children:[s.jsx(Ot,{label:n("settings.theme.colorBackground"),value:a.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(Ot,{label:n("settings.theme.colorSurface"),value:a.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(Ot,{label:n("settings.theme.colorCard"),value:a.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(Kn,{title:n("settings.theme.sectionAppText"),children:[s.jsx(Ot,{label:n("settings.theme.colorPrimary"),value:a.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(Ot,{label:n("settings.theme.colorSecondary"),value:a.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(Ot,{label:n("settings.theme.colorMuted"),value:a.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(Kn,{title:n("settings.theme.sectionBordersAccent"),children:[s.jsx(Ot,{label:n("settings.theme.colorBorderSubtle"),value:a.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(Ot,{label:n("settings.theme.colorBorderDefault"),value:a.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(Ot,{label:n("settings.theme.colorAccent"),value:a.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(Kn,{title:n("settings.theme.sectionChatBubbles"),children:[s.jsx(Ot,{label:n("settings.theme.colorUserBubble"),value:a.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(Ot,{label:n("settings.theme.colorUserText"),value:a.userText,onChange:c=>i("userText",c)}),s.jsx(Ot,{label:n("settings.theme.colorAgentBubble"),value:a.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(Ot,{label:n("settings.theme.colorAgentText"),value:a.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(Kn,{title:n("settings.theme.sectionChatLayout"),children:[s.jsx(Ot,{label:n("settings.theme.colorChatBg"),value:a.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(Ot,{label:n("settings.theme.colorSendButton"),value:a.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(Ot,{label:n("settings.theme.colorInputBorder"),value:a.inputBorder,onChange:c=>i("inputBorder",c)}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:n("settings.theme.labelBubbleRadius")}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[s.jsx("input",{type:"range",min:4,max:24,value:a.bubbleRadius,onChange:c=>i("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),s.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[a.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const c=e?wi:ki,p=cs(e?"light":"dark");e?Fr(c,p):Fr(p,c),o(c),Xs(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 gC(){const{t:e}=Se("common"),[t,n]=l.useState(ra),[r,a]=l.useState(!0),[o,i]=l.useState(()=>cs("dark"));l.useEffect(()=>{a(Zs());const p=new MutationObserver(()=>{const f=Zs();a(f);const g=ra();g==="custom"?Xs(cs(f?"dark":"light")):cr(g,f?"dark":"light")});p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const u=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const f=Zs();a(f);const g=ra();g==="custom"?Xs(cs(f?"dark":"light")):cr(g,f?"dark":"light")};return u.addEventListener("change",m),()=>{p.disconnect(),u.removeEventListener("change",m)}},[]),l.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?Xs(cs(r?"dark":"light")):(il(),cr(t,r?"dark":"light"))},[t,r]),l.useEffect(()=>{i(cs(r?"dark":"light"))},[r]);const c=p=>{n(p),hC(p)},d=[...pC,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText},light:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:d.map(p=>{const u=t===p.id,m=r?p.preview.dark:p.preview.light,f=p.id==="honey"||p.id==="ember"?"#1a1a1a":p.id==="custom"?o.userText:"#fff";return s.jsxs("button",{onClick:()=>c(p.id),className:"text-left rounded-xl p-3 transition-all",style:{background:u?"var(--bg-glass-hover)":"var(--bg-glass)",border:u?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:u?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:m.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:e("settings.theme.helloHelp")}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.userBubble,color:f},children:e("settings.theme.fixBug")}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:e("settings.theme.onIt")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[u&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:p.id==="custom"?e("settings.theme.customLabel"):p.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:p.description})]})]})]},p.id)})}),t==="custom"&&s.jsx(bC,{dark:r,onColorsChange:p=>i(p)})]})}const ll="adhdev_mobileDashboardMode_v1",Si="adhdev:mobile-dashboard-mode-change";function cl(){try{return localStorage.getItem(ll)==="workspace"?"workspace":"chat"}catch{return"chat"}}function xC(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??cl())},n=a=>{const o=a.detail;t(o)},r=a=>{a.key&&a.key!==ll||t()};return window.addEventListener(Si,n),window.addEventListener("storage",r),()=>{window.removeEventListener(Si,n),window.removeEventListener("storage",r)}}function vC(e){try{localStorage.setItem(ll,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Si,{detail:e}))}function yC(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(cl()==="chat")},[]),s.jsx(zs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ln,{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),vC(n?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const wC="Choose a preset or create a fully custom theme. Custom themes control the entire app — backgrounds, text, borders, and chat bubbles.",kC="Choose whether the dashboard opens like a chat app on phones or keeps the full workspace layout.";function SC({themeDescription:e=wC,mobileDescription:t=kC,fontsSlot:n}){const{t:r}=Se("common");return s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:r("settings.appearance.modeLabel")}),s.jsx(cC,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:r("settings.appearance.themeLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:e}),s.jsx(gC,{})]}),n,s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:r("settings.appearance.mobileLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:t}),s.jsx(yC,{})]})]})}const vo=new Map,Uc=new Map;function CC(e){if(!e||typeof e!="object")return null;const t=e,n=t.result&&typeof t.result=="object"?t.result:t,r=n.machine;return!r||typeof r!="object"?null:{machine:r,timestamp:typeof n.timestamp=="number"?n.timestamp:void 0}}function jC(e,t,n,r){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:r,platform:n.platform,machine:n}}function Yp(){const{sendCommand:e}=vt(),{injectEntries:t,getIdes:n}=pr();return l.useCallback(async(r,a)=>{if(!r)return;const o=(a==null?void 0:a.minFreshMs)??E0,i=Uc.get(r)||0;if(!(a!=null&&a.force)&&i>0&&Date.now()-i<o)return;const c=vo.get(r);if(c)return c;const d=(async()=>{const p=await e(r,"get_machine_runtime_stats"),u=CC(p);if(!u)return;const m=n().find(g=>g.id===r),f=jC(m,r,u.machine,u.timestamp||Date.now());t([f]),Uc.set(r,Date.now())})().finally(()=>{vo.delete(r)});return vo.set(r,d),d},[n,t,e])}function NC(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 AC(e,t){const{sendData:n}=vt(),{injectEntries:r,getIdes:a}=pr(),o=Array.from(new Set(e.filter(Boolean))).join("|");l.useEffect(()=>{if(!(t!=null&&t.enabled)||!n)return;const i=o?o.split("|"):[];if(i.length===0)return;const c=i.map(d=>us.subscribe({sendData:n},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const m=a().find(g=>g.id===d),f=NC(m,d,u);r([f])}));return()=>{c.forEach(d=>d())}},[o,a,r,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,n])}function MC(e,t){const{sendData:n}=vt(),[r,a]=l.useState(null),[o,i]=l.useState(!1);return l.useEffect(()=>{if(!e){a(null),i(!1);return}if(!(t!=null&&t.enabled)||!n){i(!1);return}a(null),i(!0);let c=null;const d=us.subscribe({sendData:n},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},p=>{c&&(clearTimeout(c),c=null),a(p.diagnostics),i(!1)});return d.initialSendAccepted?c=setTimeout(()=>{i(!1)},H0):i(!1),()=>{c&&clearTimeout(c),d()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,n]),{diagnostics:r,loading:o,applyDiagnostics:a}}function TC(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Jp(e){const{sendData:t}=vt(),[n,r]=l.useState({});return l.useEffect(()=>{const a=TC(e);if(!a||!e.sessionId||!t){r({});return}const o=us.subscribe({sendData:t},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},i=>{r({status:i.status,modalMessage:i.modalMessage,modalButtons:i.modalButtons}),Cn.record({interactionId:i.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:i.status,modalButtonCount:Array.isArray(i.modalButtons)?i.modalButtons.length:0}})});return o.initialSendAccepted||r({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,t]),n}function IC(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function DC(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 PC(e,t,n){const r=await n(`/api/v1/sessions/${encodeURIComponent(e)}/interactive-prompt/resolve`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let a=`HTTP ${r.status}`;try{const o=await r.json();typeof(o==null?void 0:o.error)=="string"&&(a=o.error)}catch{}throw new Error(a)}}async function LC({promptSession:e,response:t,useP2PCommand:n,sendCommand:r,fetchImpl:a=fetch}){if(n){const o=await r(e.routeId,"interactive_prompt_response",{targetSessionId:e.sessionId,sessionId:e.sessionId,response:t});if(!IC(o))throw new Error(DC(o));return}await PC(e.sessionId,t,a)}function Qp(e){const{ides:t,isP2PActive:n,p2pStates:r}=Ss(),{sendCommand:a}=vt(),[o,i]=l.useState(null),[c,d]=l.useState(!1),[p,u]=l.useState(null),m=l.useRef(!1),f=l.useMemo(()=>Fb(t,e),[t,e]),g=!!f,k=l.useMemo(()=>f?f.prompt.promptId===o?null:f:null,[o,f]),h=l.useCallback(async b=>{if(!k||m.current)return;m.current=!0;const j=Nu(k.prompt,b);d(!0),u(null);try{const C=(r==null?void 0:r[k.daemonId])==="connected"||n===!0;await LC({promptSession:k,response:j,useP2PCommand:C,sendCommand:a}),i(k.prompt.promptId)}catch(C){throw u(C instanceof Error?C.message:String(C)),C}finally{d(!1),m.current=!1}},[n,r,k,a]),v=l.useCallback(()=>{k&&i(k.prompt.promptId)},[k]),w=l.useCallback(()=>{i(null),u(null)},[]);return{promptSession:k,hasActivePrompt:g,responseError:p,isSubmitting:c,submit:h,cancel:v,reopen:w}}function Xp(e){return e instanceof Error?e.message:String(e||"")}function RC(e){const t=Xp(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 EC(e){const t=Xp(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Zp({conversation:e,mode:t,ides:n,sendDaemonCommand:r,setCliViewModeOverrides:a}){if(!e||!ut(e)||dt(e))return;const o=En(e);if(o===t)return;const i=e.sessionId;i&&a(c=>({...c,[i]:t}));try{await r(Ts(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:ks(e),mode:t})}catch(c){const d=EC(c);i&&!d&&a(p=>{const u={...p};return o===$C(n,i)?delete u[i]:u[i]=o,u}),RC(c)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",c instanceof Error?c.message:String(c)):console.error("Failed to switch CLI view mode:",c)}}function Gc(e,t){const n=typeof e.sessionId=="string"&&e.sessionId?e.sessionId:typeof e.id=="string"?e.id:"";if(!n||e.transport!=="pty")return e;const r=t[n];return!r||e.mode===r?e:{...e,mode:r}}function _C(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let n=!1;const r=e.map(a=>{const o=Gc(a,t),i=Array.isArray(a.childSessions)?a.childSessions.map(d=>Gc(d,t)):a.childSessions,c=i!==a.childSessions;return o!==a||c?(n=!0,{...o,...c?{childSessions:i}:{}}):a});return n?r:e}function $C(e,t){if(!t)return null;for(const n of e){if(n.sessionId===t&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal";for(const r of n.childSessions||[])if(r.id===t&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal"}return null}function HC({visibleConversations:e,clearedTabs:t,setClearedTabs:n,setActionLogs:r,isConversationMuted:a}){l.useEffect(()=>{Ou()},[]);const o=l.useMemo(()=>e.map(i=>({id:i.tabKey,name:Np(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null,target:{providerSessionId:i.providerSessionId,sessionId:i.sessionId,tabKey:i.tabKey,routeId:i.routeId},muted:a?a(i):!1})),[e,a]);return lw(o),l.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{n(d=>{const p=Date.now(),u={};for(const[m,f]of Object.entries(d))p-f<5e3&&(u[m]=f);return Object.keys(u).length===Object.keys(d).length?d:u})},5500);return()=>clearTimeout(c)},[t,n]),l.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;r(d=>{const p=d.filter(u=>u.timestamp>c).slice(-100);return p.length===d.length?d:p})},6e4);return()=>clearInterval(i)},[r]),null}function qc(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 en(e){const t=[...e.messages].reverse().find(a=>!(a!=null&&a._localId))||e.messages[e.messages.length-1],n=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,r=qc(t==null?void 0:t.receivedAt)||qc(t==null?void 0:t.timestamp)||0;return Math.max(n,r)}function Ci(e,t=0){return en(e)||e.lastUpdated||t||0}function em(e){return en(e)||e.lastUpdated||0}function tm(e,t,n=em){const r=n(t)-n(e);if(r!==0)return r;const a=(e.machineName||"").localeCompare(t.machineName||"");if(a!==0)return a;const o=e.displayPrimary.localeCompare(t.displayPrimary);if(o!==0)return o;const i=e.displaySecondary.localeCompare(t.displaySecondary);return i!==0?i:e.tabKey.localeCompare(t.tabKey)}function ji(e){var n;const t=es(e.status,{activeModal:(n=e.modalButtons)!=null&&n.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function FC(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!ji(e)&&!e.title.trim()}function BC(e){return e.length===0?null:[...e].sort((t,n)=>{const r=Number(ji(n))-Number(ji(t));if(r!==0)return r;const a=n.messages.length-t.messages.length;return a!==0?a:tm(t,n)})[0]||null}function ps(e,t){const n=e.filter(i=>i.routeId===t);if(n.length===0)return null;const r=n.find(i=>i.streamSource==="native")||null,a=n.filter(i=>i.streamSource==="agent-stream"),o=BC(a);return r?o&&FC(r)?o:r:o||n[0]||null}function OC(e){const t=e.filter(a=>a.type!=="adhdev-daemon"),n=new Set;for(const a of t){if(!ci(a))continue;const o=Eu(a);o&&n.add(o)}const r=new Map;for(const a of t){const o=Fy(a,n),i=r.get(o);if(!i){r.set(o,a);continue}const c=m=>(m.workspace?1:0)+(m.activeChat?1:0)+(m.lastMessagePreview?1:0),d=c(i),p=c(a),u=p>d||p===d&&(a.timestamp||0)>(i.timestamp||0)?a:i;r.set(o,WC(u,u===a?i:a))}return Array.from(r.values())}function WC(e,t){const n=ci(t),r=ci(e);if(!n&&!r)return e;const a=r?n?void 0:t:e,o=r?e:n?t:void 0,i=a&&String(a.daemonId||"").trim()||String(e.ownerDaemonId||"").trim()||String(t.ownerDaemonId||"").trim()||void 0,c=String(e.ownerMachineName||"").trim()||String(t.ownerMachineName||"").trim()||void 0,d=o==null?void 0:o.settings;return{...e,...i&&{ownerDaemonId:i},...c&&!e.ownerMachineName&&{ownerMachineName:c},...d&&!r&&{settings:{...d,...e.settings??{}}}}}function yo(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 UC(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 zc(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],n=t[t.length-1],r=n?UC(jn(n.content)):"";return[e.id||"",e.title||"",e.status||"",t.length,String((n==null?void 0:n.id)||""),String((n==null?void 0:n.index)??""),String((n==null?void 0:n.receivedAt)??(n==null?void 0:n.timestamp)??""),r].join(":")}function GC(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||""),zc(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||""),zc(n.activeChat)].join(":"))].join("|")}function qC(e,t){const n=Date.now();return e.map(r=>{const a=t[r.tabKey];return a&&n-a<5e3?{...r,messages:[],title:""}:r})}function zC(e,t){const n=new Map;for(const r of e){const a=t.get(r.routeId)||r;for(const o of ar({routeId:r.routeId}))n.set(o,a);for(const o of ar({providerSessionId:r.providerSessionId,sessionId:r.sessionId}))n.set(o,r.streamSource==="native"?a:r);for(const o of ar({tabKey:r.tabKey}))n.set(o,r)}return n}function KC(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function VC(e){const t=KC(e);if(!t)return`empty:${e.messages.length}`;if(t.id)return`id:${String(t.id)}`;if(t._localId)return`local:${String(t._localId)}`;const n=String(t.role||""),r=jn(t.content).slice(0,240);return`${e.messages.length}:${n}:${r}`}function YC({ides:e,connectionStates:t,clearedTabs:n}){const r=l.useMemo(()=>OC(e),[e]),a=l.useMemo(()=>Tu(e),[e]),o=l.useMemo(()=>$p(e),[e]),i=l.useRef([]),c=l.useRef([]),d=l.useRef([]),p=l.useRef(new Map),u=l.useRef(new Map),m=l.useMemo(()=>{const C=new Map,y=[];for(const A of r){const{connectionState:M="new",machineName:P}=Hp(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),D=GC(A),I=p.current.get(A.id);if(I&&I.ide===A&&I.sourceSignature===D&&I.connectionState===M&&I.machineName===P){C.set(A.id,I),y.push(...I.conversations);continue}const _=al(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),W={ide:A,sourceSignature:D,connectionState:M,machineName:P,conversations:_};C.set(A.id,W),y.push(..._)}p.current=C;const x=new Map,N=A=>{const M=VC(A),P=u.current.get(A.tabKey);if(P&&P.signature===M)return x.set(A.tabKey,P),P.timestamp;const D={signature:M,timestamp:em(A)||(P==null?void 0:P.timestamp)||0};return x.set(A.tabKey,D),D.timestamp},S=[...y].sort((A,M)=>tm(A,M,N));return u.current=x,S},[r,t,o]),f=l.useMemo(()=>{const C=qC(m,n);return yo(i.current,C)?i.current:(i.current=C,C)},[m,n]),g=l.useMemo(()=>{const C=new Map,y=Array.from(new Set(f.map(x=>x.routeId)));for(const x of y){const N=ps(f,x);N&&C.set(x,N)}return C},[f]),k=l.useMemo(()=>{const C=new Map;for(const y of f){const x=g.get(y.routeId),N=y.streamSource==="native"&&x?x:y;for(const S of ar({providerSessionId:y.providerSessionId,sessionId:y.sessionId,tabKey:y.tabKey}))C.set(S,N)}return C},[f,g]),h=l.useMemo(()=>zC(f,g),[f,g]),v=l.useCallback(C=>{if(C)return k.get(C)},[k]),w=l.useCallback(C=>{if(C)return h.get(C)},[h]),b=l.useMemo(()=>{const C=f.filter(y=>!Hs(y,a).surfaceHidden);return yo(c.current,C)?c.current:(c.current=C,C)},[f,a]),j=l.useMemo(()=>{const C=b.map(y=>y.tabKey);return yo(d.current,C)?d.current:(d.current=C,C)},[b]);return{chatIdes:r,conversations:f,visibleConversations:b,visibleTabKeys:j,resolveConversationBySessionId:v,resolveConversationByTarget:w}}function JC({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:n,setSearchParams:r}){const a=l.useMemo(()=>{var c;return e||!t?null:((c=n(t))==null?void 0:c.tabKey)??null},[e,n,t]),o=l.useMemo(()=>{var c;return!e||!t?null:((c=n(t))==null?void 0:c.tabKey)??null},[e,n,t]),i=l.useCallback(()=>{t&&r(c=>{const d=new URLSearchParams(c);return d.delete("activeTab"),d},{replace:!0})},[r,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:o,consumeRequestedActiveTab:i}}function QC({ides:e,sendDaemonCommand:t,setToasts:n,resolveConversationByTarget:r}){l.useEffect(()=>{pt.setIdes(e)},[e]),l.useEffect(()=>{pt.setResolveAction((a,o,i)=>{t(a,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const a=pt.onToast(o=>{n(c=>c.some(p=>p.message===o.message&&o.timestamp-p.timestamp<3e3)?c:[...c.slice(-4),{id:o.id,message:o.message,type:o.type,timestamp:o.timestamp,targetKey:o.targetKey,actions:o.actions}]);const i=o.duration||5e3;setTimeout(()=>n(c=>c.filter(d=>d.id!==o.id)),i)});return()=>{a()}},[n]),l.useEffect(()=>{const a=kp.on("status_event",o=>{pt.handleRawEvent(o,"ws")});return()=>{a()}},[]),l.useEffect(()=>{var o;const a=i=>{var h;const c=i.data;if((c==null?void 0:c.type)!=="notification_action"||typeof c.action!="string"||!c.action.startsWith("approval_")||!(c.daemonId||c.targetSessionId||c.targetKey))return;const d=c.targetSessionId||c.targetKey||c.daemonId,p=r(d),u=(p==null?void 0:p.routeId)||c.daemonId;if(!u)return;const m=Number(c.buttonIndex),f=c.button||((h=p==null?void 0:p.modalButtons)==null?void 0:h[m])||"Approve",g=String(f).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),k=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(g);t(u,"resolve_action",{action:k?"approve":"reject",button:f,...Number.isFinite(m)&&{buttonIndex:m},...(p==null?void 0:p.sessionId)&&{targetSessionId:p.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(v=>console.error("[SW Action] approval failed:",v))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",a),()=>{var i;return(i=navigator.serviceWorker)==null?void 0:i.removeEventListener("message",a)}},[r,t])}const XC="adhdev_dashboardLayout_v1",ZC="adhdev_dashboardDockview_v1",ej="adhdev_dashboardDockviewHiddenRestore_v1",Vn={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function dl(e,t){try{const n=localStorage.getItem(e);return n?JSON.parse(n):t}catch{return t}}function tj(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function sm(e){return`${XC}:${e}`}function sj(e){const t=sm(e);return dl(t,null)}function nj(e,t){try{const n=t.groupAssignments.length===0&&t.focusedGroup===0&&Object.keys(t.groupActiveTabIds).length===0&&Object.keys(t.groupTabOrders).length===0&&t.groupSizes.length===0,r=sm(e);if(n){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function nm(e){return`${ZC}:${e}`}function rj(e){const t=nm(e);return dl(t,null)}function aj(e,t){try{const n=nm(e);if(!t){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function rm(e){return`${ej}:${e}`}function oj(e){const t=rm(e);return dl(t,{})}function ij(e,t){try{const n=rm(e);if(Object.keys(t).length===0){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function lj(){return{groupAssignments:[...Vn.groupAssignments],focusedGroup:Vn.focusedGroup,groupActiveTabIds:{...Vn.groupActiveTabIds},groupTabOrders:{...Vn.groupTabOrders},groupSizes:[...Vn.groupSizes]}}function cj(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):t.length===0}function dj(){const[e]=l.useState(()=>tj(typeof window<"u"?window.innerWidth:1280)),[t,n]=l.useState(()=>new Map),[r,a]=l.useState(0),[o,i]=l.useState({}),[c,d]=l.useState({}),[p,u]=l.useState([]),[m,f]=l.useState(()=>typeof window<"u"&&window.innerWidth<768),[g,k]=l.useState(!1),h=l.useCallback(()=>{if(g)return;const A=sj(e)??lj();n(new Map(A.groupAssignments)),a(A.focusedGroup),i(A.groupActiveTabIds),d(A.groupTabOrders),u(A.groupSizes),k(!0)},[g,e]);l.useEffect(()=>{g&&nj(e,{groupAssignments:[...t.entries()],focusedGroup:r,groupActiveTabIds:o,groupTabOrders:c,groupSizes:p})},[g,e,t,r,o,c,p]),l.useEffect(()=>{const A=window.matchMedia("(max-width: 767px)"),M=P=>f(P.matches);return A.addEventListener("change",M),()=>A.removeEventListener("change",M)},[]);const v=l.useCallback(A=>{n(A)},[]),w=l.useCallback(A=>{a(A)},[]),b=l.useCallback(A=>{i(A)},[]),j=l.useCallback(A=>{d(A)},[]),C=l.useCallback(A=>{u(A)},[]),y=l.useCallback(A=>{w(A)},[w]),x=l.useCallback((A,M)=>{i(P=>(P[A]??null)===(M??null)?P:{...P,[A]:M})},[]),N=l.useCallback((A,M)=>{d(P=>{const D=P[A];return cj(D,M)?P:{...P,[A]:M}})},[]),S=l.useCallback((A,M)=>{const P=M.get(A)??0;return x(P,A),y(P),P},[y,x]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:v,focusedGroup:r,updateFocusedGroup:w,focusGroup:y,groupActiveTabIds:o,updateGroupActiveTabIds:b,setGroupActiveTab:x,groupTabOrders:c,updateGroupTabOrders:j,setGroupTabOrder:N,groupSizes:p,updateGroupSizes:C,isMobile:m,hasHydratedStoredLayout:g,hydrateStoredLayout:h,focusConversationTab:S}}function uj(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0],r=$a(t);return typeof(n==null?void 0:n.id)=="string"&&r.includes(n.id)}function pj({urlActiveTab:e,conversations:t,resolveConversationBySessionId:n,normalizedGroupAssignments:r,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:i,setSearchParams:c,historyModalOpen:d,activeConv:p,isRefreshingHistory:u,ides:m,handleRefreshHistory:f}){const g=l.useRef(!1),k=l.useRef(!1),h=l.useRef(null),v=l.useRef(!1);l.useEffect(()=>{if(!e||g.current||t.length===0)return;if(!a){o();return}const w=n(e);w&&(i(w.tabKey,r),g.current=!0,k.current=!0,h.current!=null&&(window.clearTimeout(h.current),h.current=null),c(b=>{const j=new URLSearchParams(b);return j.delete("activeTab"),j},{replace:!0}))},[e,t,n,r,a,o,i,c]),l.useEffect(()=>{if(!(k.current||a)&&t.length!==0){if(!e){o(),k.current=!0;return}if(g.current){k.current=!0;return}if(h.current==null)return h.current=window.setTimeout(()=>{h.current=null,!(k.current||a)&&(o(),k.current=!0)},1500),()=>{h.current!=null&&(window.clearTimeout(h.current),h.current=null)}}},[e,t.length,a,o]),l.useEffect(()=>{if(!d){v.current=!1;return}if(!p||v.current||u)return;const w=m.find(b=>b.id===p.routeId);w&&(!w.chats||w.chats.length===0||uj(w.chats,p))&&(v.current=!0,f())},[d,p,u,m,f])}function wo(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0];if((n==null?void 0:n.active)===!0)return!0;const r=$a(t);return typeof(n==null?void 0:n.id)=="string"&&r.includes(n.id)}function am({sendDaemonCommand:e,activeConv:t,chats:n,updateRouteChats:r,setToasts:a,setClearedTabs:o}){const[i,c]=l.useState(!1),[d,p]=l.useState(!1),u=l.useCallback(async k=>{try{await e("standalone","launch_ide",{ideType:k,enableCdp:!0})}catch(h){console.error("Launch failed",h)}},[e]),m=l.useCallback(async(k,h)=>{try{const v=k||(t==null?void 0:t.daemonId)||"",w=await e(v,"switch_chat",{id:h,sessionId:h,...Ys(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"?fn(a,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?fn(a,`⚠️ Switch error: ${b}`):fn(a,"⚠️ Session switch failed")}catch(v){console.error("Switch failed",v),fn(a,`❌ Switch failed: ${v.message||"connection error"}`)}},[t,e,a]),f=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const k=Js(t);await e(k,"new_chat",{...Ys(t)}),nk(k,t.sessionId,$a(t)[0]),o(h=>({...h,[t.tabKey]:Date.now()}))}catch(k){console.error("New chat failed",k)}finally{c(!1)}}},[t,i,e,o]),g=l.useCallback(async()=>{var k,h;if(!(!t||d)){p(!0);try{const v=Js(t),w=async()=>e(v,"list_chats",{forceExpand:!0,...Ys(t)});let b=await w(),j=(b==null?void 0:b.chats)||((k=b==null?void 0:b.result)==null?void 0:k.chats);wo(j,t)&&(await new Promise(C=>setTimeout(C,450)),b=await w(),j=(b==null?void 0:b.chats)||((h=b==null?void 0:b.result)==null?void 0:h.chats)),b!=null&&b.success&&Array.isArray(j)&&(r(t.routeId,j),wo(j,t)&&!wo(n,t)&&fn(a,"⚠️ History dialog did not fully open — try once more"))}catch(v){console.error("Refresh history failed",v)}finally{p(!1)}}},[t,n,d,e,r,a]);return{isCreatingChat:i,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:m,handleNewChat:f,handleRefreshHistory:g}}function mj(e,t){if(e.size!==t.size)return!1;for(const[n,r]of e)if(t.get(n)!==r)return!1;return!0}function hj(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function Kc(e,t){const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(a=>t[Number(a)]===e[Number(a)])}function Br(e,t){const n=new Set(t),r=t.length>0?[0]:[];for(const[i,c]of e)!n.has(i)||c<=0||r.includes(c)||r.push(c);r.sort((i,c)=>i-c);const a={};r.forEach((i,c)=>{a[i]=c}),r.length===0&&(a[0]=0);const o=new Map;for(const[i,c]of e){if(!n.has(i)||c<=0)continue;const d=a[c];typeof d=="number"&&d>0&&o.set(i,d)}return{assignments:o,groupCount:Math.max(1,r.length),mapping:a,usedGroups:r}}function Vc(e,t){const n={};for(const[r,a]of Object.entries(e)){const o=t[Number(r)];typeof o=="number"&&(n[o]=a)}return n}function fj(e,t,n){if(t.length===0)return 0;if(typeof n[e]=="number")return n[e];const r=[...t].reverse().find(a=>a<e)??t[0];return n[r]??0}function bj(e,t,n){if(t.length<=1)return[];const r=t.map(i=>e[i]).filter(i=>Number.isFinite(i)),a=r.length===t.length?r:Array(n).fill(100/n),o=a.reduce((i,c)=>i+c,0);return o>0?a.map(i=>i/o*100):Array(n).fill(100/n)}function Yc(e,t){const n={};for(const[r,a]of Object.entries(e)){const o=Number(r);n[o>=t?o+1:o]=a}return n}function Jc(e){return Array(e).fill(100/e)}function gj({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:n,updateGroupActiveTabIds:r,updateGroupTabOrders:a,groupSizes:o,updateGroupSizes:i,isMobile:c,visibleConversations:d,visibleTabKeys:p}){const u=l.useRef(null),m=l.useMemo(()=>Br(e,p),[e,p]),f=m.assignments,g=l.useMemo(()=>c?1:m.groupCount,[m.groupCount,c]),k=g>1,h=l.useCallback((y,x)=>{t(N=>{const S=new Map(Br(N,p).assignments);return x===0?S.delete(y):S.set(y,x),S}),r(N=>({...N,[x]:y})),n(x)},[t,p,r,n]),v=l.useCallback(y=>{t(x=>{const N=Br(x,p).assignments,S=new Map;for(const[A,M]of N)M!==y&&(M>y?S.set(A,M-1):S.set(A,M));return S}),i(x=>{if(x.length<=1)return[];const N=[...x];N.splice(y,1);const S=N.reduce((A,M)=>A+M,0);return S>0?N.map(A=>A/S*100):[]}),n(0)},[t,p,i,n]),w=l.useCallback((y,x)=>{x.preventDefault();const N=u.current;if(!N)return;const S=x.clientX,A=N.offsetWidth,M=o.length===g?[...o]:Jc(g),P=I=>{const W=(I.clientX-S)/A*100,H=[...M];H[y]=Math.max(15,M[y]+W),H[y+1]=Math.max(15,M[y+1]-W),i(H)},D=()=>{document.removeEventListener("mousemove",P),document.removeEventListener("mouseup",D),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",P),document.addEventListener("mouseup",D)},[o,g,i]),b=l.useCallback((y,x,N)=>{if(g>=4)return;const S=N==="left"?x:x+1;t(A=>{const M=Br(A,p).assignments,P=new Map;for(const D of d){const I=M.get(D.tabKey)??0,_=I>=S?I+1:I;_>0&&P.set(D.tabKey,_)}return S>0&&P.set(y,S),P}),i(A=>{const M=A.length===g?[...A]:Jc(g),P=M[x]??100/g,D=Math.max(15,P/2),I=Math.max(15,P/2),_=[...M];_[x]=D,_.splice(S,0,I);const W=_.reduce((H,L)=>H+L,0);return _.map(H=>H/W*100)}),r(A=>{const M=Yc(A,S);return M[S]=y,M}),a(A=>{const M=Yc(A,S);return M[S]=[y],M}),n(S)},[g,t,p,d,i,r,a,n]);l.useEffect(()=>{mj(e,f)||t(f)},[e,f,t]),l.useEffect(()=>{const{mapping:y,usedGroups:x}=m;r(N=>{const S=Vc(N,y);return Kc(N,S)?N:S}),a(N=>{const S=Vc(N,y);return Kc(N,S)?N:S}),n(N=>{const S=c?0:fj(N,x,y);return N===S?N:S}),i(N=>{const S=c?[]:bj(N,x,m.groupCount);return hj(N,S)?N:S})},[m,c,r,a,n,i]);const j=l.useMemo(()=>{const y=Array.from({length:g},()=>[]);for(const x of d){const N=f.get(x.tabKey)??0,S=Math.min(N,g-1);y[S].push(x)}return y},[d,f,g]),C=l.useCallback(()=>{t(new Map),n(0)},[t,n]);return{containerRef:u,normalizedGroupAssignments:f,numGroups:g,isSplitMode:k,groupedConvs:j,moveTabToGroup:h,closeGroup:v,handleResizeStart:w,splitTabRelative:b,clearAllSplits:C}}function ko(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 xj(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 Or(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function ul(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},n=ko(t.channel)||ko(e.updateChannel)||ko(e.releaseChannel)||void 0,r=xj(t.npmTag)||(n==="preview"?"next":n==="stable"?"latest":void 0),a=Or(t.targetVersion)||Or(e.serverVersion)||void 0,o=Or(t.minVersion)||void 0,i=Or(t.updateCommand)||(n?`adhdev update --channel ${n}`:void 0);return{...n?{channel:n}:{},...r?{npmTag:r}:{},...a?{targetVersion:a}:{},...o?{minVersion:o}:{},...i?{updateCommand:i}:{}}}function xn(e,t=null){return ul(e).targetVersion||t}function om(e){return ul(e).channel||null}function im(e){const t=ul(e);return{...t.channel?{channel:t.channel}:{},...t.npmTag?{npmTag:t.npmTag}:{},...t.targetVersion?{targetVersion:t.targetVersion}:{},...Object.keys(t).length>0?{updatePolicy:t}:{}}}function vj({ides:e,sendDaemonCommand:t}){const n="1.0.20",r=l.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:ol(m,xn(m,n))).sort((m,f)=>Number(lr(f,xn(f,n)))-Number(lr(m,xn(m,n)))),[n,e]),a=l.useMemo(()=>r.some(m=>lr(m,xn(m,n))),[n,r]),o=l.useMemo(()=>r.map(m=>xn(m,n)).find(m=>typeof m=="string"&&m.trim().length>0)||n,[n,r]),[i,c]=l.useState(!1),[d,p]=l.useState({}),u=l.useCallback(async m=>{var g,k;const f=e.find(h=>h.id===m);if(f){p(h=>({...h,[m]:"upgrading"}));try{const h=await t(m,"daemon_upgrade",im(f));(g=h==null?void 0:h.result)!=null&&g.upgraded||(k=h==null?void 0:h.result)!=null&&k.success?p(v=>({...v,[m]:"done"})):p(v=>({...v,[m]:"error"}))}catch{p(h=>({...h,[m]:"error"}))}}},[e,t]);return{versionMismatchDaemons:r,hasRequiredVersionDaemons:a,targetVersion:o,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:u}}const lm=80;function aa(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function yj(e){return{...e,createdAt:aa(e.createdAt),updatedAt:aa(e.updatedAt,e.createdAt),lastEventAt:aa(e.lastEventAt,e.updatedAt||e.createdAt)}}function wj(e){const t=Ru(e);return t==="unknown:"?e.id:t}function kj(e){return[e.type,Lu(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Sj(e,t=lm){const n=new Map;for(const r of e){if(r.deletedAt)continue;const a=wj(r),o=n.get(a);if(!o){n.set(a,r);continue}(r.updatedAt>o.updatedAt||r.updatedAt===o.updatedAt&&r.createdAt>o.createdAt)&&n.set(a,r)}return Array.from(n.values()).sort((r,a)=>{const o=a.updatedAt-r.updatedAt;return o!==0?o:a.createdAt-r.createdAt}).slice(0,Math.max(0,t))}function Cj(e,t){const n=Date.now(),r=[];for(const a of e){const o=a.sessionId?t.get(a.sessionId):void 0;if(o!=null&&o.surfaceHidden||o!=null&&o.muted)continue;const i=_a(a,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const d=aa(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,n),p=kj({type:c,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,lastMessageHash:a.lastMessageHash,lastMessageAt:a.lastMessageAt,lastUpdated:(o==null?void 0:o.lastUpdated)||a.lastUpdated});r.push(yj({id:p,dedupKey:p,type:c,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:ep(a),preview:f0(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return Sj(r)}function jj(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function Nj(e){const{conversations:t,liveSessionInboxState:n,maxItems:r=lm}=e,a=l.useMemo(()=>Cj(t,n).slice(0,Math.max(0,r)),[t,n,r]),o=l.useMemo(()=>jj(a),[a]);return{notifications:a,unreadCount:o}}function Aj({notifications:e,sendDaemonCommand:t}){const n=l.useCallback(o=>{const i=e.find(d=>d.id===o),c=Math.max(Date.now(),(i==null?void 0:i.updatedAt)||0);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_session_seen",{sessionId:i.sessionId,seenAt:c}).catch(()=>{})},[e,t]),r=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_notification_unread",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]),a=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"delete_notification",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:n,handleMarkDashboardNotificationUnread:r,handleDeleteDashboardNotification:a}}function pl(...e){const t=new Set,n=[],r=a=>{const o=typeof a=="string"?a.trim():"";if(!o)return;const i=o.toLowerCase();t.has(i)||(t.add(i),n.push(o))};for(const a of e){if(Array.isArray(a)){for(const o of a)r(o);continue}r(a)}return n}function Mj(e){const t=e.trim();if(!t)return null;if(t.startsWith("~"))return t;if(/^[A-Za-z]:$/.test(t))return`${t[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(t))return`${t[0].toUpperCase()}:${t.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(t))return`${t[0].toUpperCase()}:\\${t.slice(2).replace(/[\\/]+/g,"\\")}`;const n=t.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(n){const r=n[1].toUpperCase(),a=(n[2]||"").replace(/[\\/]+/g,"\\");return a?`${r}:\\${a}`:`${r}:\\`}return null}function ml(e,t=[]){if(e==="win32"){for(const n of t){if(typeof n!="string")continue;const r=Mj(n);if(r)return r}return"C:\\"}for(const n of t){const r=typeof n=="string"?n.trim():"";if(r)return r}return"~"}function Tj(e){const t=e.replace(/[\\/]+$/,"");if(!t||t==="/"||/^[A-Za-z]:$/.test(t))return null;const n=t.includes("\\")?"\\":"/",r=t.split(/[\\/]/);return/^[A-Za-z]:$/.test(r[0]||"")?r.length<=2?`${r[0]}\\`:r.slice(0,-1).join("\\"):r.length<=2?n:r.slice(0,-1).join(n)||n}function Ij(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function hl(e,t,n){const r=await e(t,"file_list_browse",{path:n}),a=Ij(r);if(!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||(r==null?void 0:r.error)||"Could not browse folder");const o=typeof(a==null?void 0:a.path)=="string"?a.path:n,i=o.includes("\\")?"\\":"/",c=(p,u)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${u}`:p==="/"||p==="\\"?`${i}${u}`:`${p.replace(/[\\/]+$/,"")}${i}${u}`,d=Array.isArray(a==null?void 0:a.files)?a.files.filter(p=>(p==null?void 0:p.type)==="directory"&&typeof(p==null?void 0:p.name)=="string").map(p=>({name:p.name,path:typeof(p==null?void 0:p.path)=="string"&&p.path.trim()?p.path:c(o,p.name)})).sort((p,u)=>p.name.localeCompare(u.name)):[];return{path:o,directories:d}}function Qc(e,t){const n=t.meshId||"",r={meshId:n,workspace:t.workspace||"",serverName:t.serverName||"adhdev-mesh",adhdevMcpCommand:t.adhdevMcpCommand||"adhdev-mcp",adhdevMcpArgs:t.adhdevMcpArgs||`mcp --mode ipc --repo-mesh ${n}`};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand|adhdevMcpArgs)\s*\}\}/g,(a,o)=>r[o]||"")}function cm(e,t={}){const n=e==null?void 0:e.mcpConfig;if((n==null?void 0:n.mode)!=="manual")return null;const a=Qc(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"}).trim();return!a.includes(`
|
|
70
|
+
`)&&!a.startsWith("{")?null:{serverName:n.serverName||"adhdev-mesh",configFormat:n.format,configPathCommand:n.configPathCommand,requiresRestart:n.requiresRestart===!0,instructions:n.instructions||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:Qc(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"})}}function Dj(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.instructions=="string"?t.instructions:"",r=typeof t.template=="string"?t.template:"";return!n&&!r?null:{serverName:typeof t.serverName=="string"?t.serverName:void 0,configFormat:typeof t.configFormat=="string"?t.configFormat:void 0,configPathCommand:typeof t.configPathCommand=="string"?t.configPathCommand:void 0,requiresRestart:t.requiresRestart===!0,instructions:n||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:r}}function xr(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function dm(e){return Ha(e)||e.tabKey||e.routeId||null}function um(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"",n=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"",r=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"",a=e.conversations.find(o=>{if(r&&o.routeId!==r)return!1;const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey].map(c=>typeof c=="string"?c.trim():"").filter(Boolean);return!!(t&&i.includes(t)||n&&i.includes(n)||r&&o.routeId===r)});if(a!=null&&a.tabKey)return a.tabKey;if(r){const o=ps(e.conversations,r)||e.conversations.find(i=>i.routeId===r);if(o!=null&&o.tabKey)return o.tabKey}return t||n||r||null}function Ls(e){return String(e||"").trim()}function pm(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Ma(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Pj(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function Lj(e,t){const n=Ls(e.providerSessionId),r=Ls(e.targetSessionId),a=t.find(o=>{const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(Ls).filter(Boolean);return!!(n&&i.includes(n)||r&&i.includes(r))});return a?a.tabKey:r||n||null}function Rj(e,t,n){if(t.event!=="agent:generating_completed")return null;const r=pm(t.daemonId);if(r&&r!==e.machineId)return null;const a=Ls(t.providerType);if(e.providerType&&a!==e.providerType)return null;const o=Ls(e.resumeSessionId),i=Ls(e.launchedSessionId),c=Ls(t.providerSessionId),d=Ls(t.targetSessionId);if(o&&o!==c&&o!==d||i&&i!==c&&i!==d)return null;const p=Ma(e.workspacePath);if(p){const u=Ma(t.workspaceName);if(u&&!Pj(u,p))return null}return Lj(t,n)}function Xc(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Ej({ides:e,conversations:t,onOpenSession:n}){const[r,a]=l.useState(null),o=l.useRef(null),i=l.useCallback(()=>{o.current=null,a(null)},[]),c=l.useCallback(d=>{o.current=d,a(d)},[]);return l.useEffect(()=>{if(!r)return;const d=Ma(r.workspacePath),p=e.find(m=>{var v,w,b,j;if(!m||m.type==="adhdev-daemon"||pm(m.daemonId||m.id)!==r.machineId||(fr(m)?"cli":kn(m)?"acp":"ide")!==r.kind)return!1;const k=String(m.agentType||m.type||"");if(r.providerType&&k!==r.providerType)return!1;if(r.resumeSessionId)return String(m.providerSessionId||"")===r.resumeSessionId;if(r.launchedSessionId){const C=String(r.launchedSessionId||"");return[m.providerSessionId,m.sessionId,m.instanceId,m.id].map(x=>String(x||"")).filter(Boolean).includes(C)}if(d){const C=Ma(m.workspace||m.runtimeWorkspaceLabel);return C?C===d:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((j=(b=(w=(v=m.activeChat)==null?void 0:v.messages)==null?void 0:w.at)==null?void 0:b.call(w,-1))==null?void 0:j.timestamp)||0)>=r.startedAt-5e3});if(!p)return;const u=um({entrySessionId:p.sessionId,entryInstanceId:p.instanceId,entryRouteId:p.id,conversations:t});u&&(i(),n(u))},[i,t,e,n,r]),l.useEffect(()=>pt.onStatusEvent(d=>{const p=o.current;if(!p)return;const u=Rj(p,d,t);u&&(i(),n(u))}),[i,t,n]),l.useEffect(()=>{if(!r)return;const d=window.setTimeout(()=>{a(p=>!p||p.startedAt!==r.startedAt?p:(o.current=null,null))},45e3);return()=>window.clearTimeout(d)},[r]),{trackPendingLaunch:c}}function _j(e,t){var r,a,o,i;const n={cliType:e};return(r=t==null?void 0:t.workspacePath)!=null&&r.trim()?n.dir=t.workspacePath.trim():t!=null&&t.workspaceId?n.workspaceId=t.workspaceId:t!=null&&t.useHome&&(n.useHome=!0),(a=t==null?void 0:t.resumeSessionId)!=null&&a.trim()&&(n.resumeSessionId=t.resumeSessionId.trim()),Array.isArray(t==null?void 0:t.cliArgs)&&t.cliArgs.length>0&&(n.cliArgs=t.cliArgs),(o=t==null?void 0:t.initialModel)!=null&&o.trim()&&(n.initialModel=t.initialModel.trim()),(i=t==null?void 0:t.initialThinkingLevel)!=null&&i.trim()&&(n.initialThinkingLevel=t.initialThinkingLevel.trim()),t!=null&&t.settings&&(n.settings=t.settings),n}function $j({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:n,activeConv:r,ides:a,setCliViewModeOverrides:o}){const i=Ji(),{launchCli:c}=Pa(),d=l.useCallback(async(v,w)=>hl(e,v,w),[e]),p=l.useCallback(async(v,w)=>{if(!w.trim())return{ok:!1,error:"Choose a workspace path first."};try{const b=await e(v,"workspace_add",{path:w.trim()});return b!=null&&b.success?{ok:!0}:{ok:!1,error:(b==null?void 0:b.error)||"Could not save workspace"}}catch(b){return{ok:!1,error:b instanceof Error?b.message:"Could not save workspace"}}},[e]),u=l.useCallback(async(v,w,b)=>{var j;try{const C={ideType:w,enableCdp:!0};(j=b==null?void 0:b.workspacePath)!=null&&j.trim()&&(C.workspace=b.workspacePath.trim());const y=await e(v,"launch_ide",C);return!(y!=null&&y.success)&&(y==null?void 0:y.success)!==void 0?{ok:!1,error:(y==null?void 0:y.error)||"Could not launch IDE"}:(t({machineId:v,kind:"ide",providerType:w,workspacePath:(b==null?void 0:b.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(C){return{ok:!1,error:C instanceof Error?C.message:"Could not launch IDE"}}},[e,t]),m=l.useCallback(async(v,w,b,j)=>{const C=Date.now();try{const y=_j(b,j),x=await c(v,y),N=(x==null?void 0:x.result)||x,S=(N==null?void 0:N.sessionId)||(N==null?void 0:N.id);return x!=null&&x.success&&S?(t({machineId:v,kind:w,providerType:b,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,launchedSessionId:S,startedAt:C}),{ok:!0}):x!=null&&x.success?(t({machineId:v,kind:w,providerType:b,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:(x==null?void 0:x.error)||(N==null?void 0:N.error)||`Could not launch ${w.toUpperCase()} session`,code:(x==null?void 0:x.code)||(N==null?void 0:N.code)||void 0}}catch(y){return Xc(y)?(t({machineId:v,kind:w,providerType:b,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,startedAt:C}),{ok:!0}):{ok:!1,error:y instanceof Error?y.message:`Could not launch ${w.toUpperCase()} session`}}},[c,e,t]),f=l.useCallback(async v=>{var w;if(i!=null&&i.listMeshes)return i.listMeshes(v);if(!v)return[];try{const b=await e(v,"list_meshes",{}),j=(b==null?void 0:b.result)??b;if((j==null?void 0:j.success)===!1)throw new Error((j==null?void 0:j.error)||"Could not load meshes");return(Array.isArray(j==null?void 0:j.meshes)?j.meshes:Array.isArray((w=j==null?void 0:j.result)==null?void 0:w.meshes)?j.result.meshes:[]).map(y=>{var x;return{id:String((y==null?void 0:y.id)||""),name:String((y==null?void 0:y.name)||(y==null?void 0:y.id)||"Untitled mesh"),repoIdentity:(y==null?void 0:y.repoIdentity)||(y==null?void 0:y.repo_identity)||null,workspace:Array.isArray(y==null?void 0:y.nodes)&&y.nodes.length>0?String(((x=y.nodes[0])==null?void 0:x.workspace)||""):null,nodesCount:Array.isArray(y==null?void 0:y.nodes)?y.nodes.length:void 0,status:(y==null?void 0:y.status)||null}}).filter(y=>y.id)}catch(b){throw console.error("List meshes failed",b),b}},[i,e]),g=l.useCallback(async(v,w,b,j)=>{var y,x;if(!w.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(v,w,b,j);const C=Date.now();try{const N={meshId:w.trim()};b.trim()&&(N.cliType=b.trim());const S=(y=j==null?void 0:j.initialModel)==null?void 0:y.trim(),A=(x=j==null?void 0:j.initialThinkingLevel)==null?void 0:x.trim();S&&(N.initialModel=S),A&&(N.initialThinkingLevel=A);const M=await e(v,"launch_mesh_coordinator",N),P=(M==null?void 0:M.result)??M;if((P==null?void 0:P.success)===!1||(M==null?void 0:M.success)===!1){const I=String((P==null?void 0:P.code)||(M==null?void 0:M.code)||""),_=Dj((P==null?void 0:P.meshCoordinatorSetup)||(P==null?void 0:P.manualSetup)||(M==null?void 0:M.meshCoordinatorSetup)||(M==null?void 0:M.manualSetup));return{ok:!1,error:(P==null?void 0:P.error)||(M==null?void 0:M.error)||"Could not launch mesh coordinator",code:I||void 0,manualSetup:_}}const D=(P==null?void 0:P.sessionId)||(P==null?void 0:P.id);return D?n(D):t({machineId:v,kind:"cli",providerType:(P==null?void 0:P.cliType)||b.trim()||void 0,workspacePath:(P==null?void 0:P.workspace)||null,startedAt:C}),{ok:!0}}catch(N){return Xc(N)?(t({machineId:v,kind:"cli",providerType:b.trim()||void 0,startedAt:C}),{ok:!0}):{ok:!1,error:N instanceof Error?N.message:"Could not launch mesh coordinator"}}},[i,n,e,t]),k=l.useCallback(async(v,w)=>{if(!v||!w)return[];try{const b=await e(v,"list_saved_sessions",{providerType:w,kind:"cli",limit:30}),j=(b==null?void 0:b.result)??b;return Array.isArray(j==null?void 0:j.sessions)?j.sessions:[]}catch(b){return console.error("List saved sessions failed",b),[]}},[e]),h=l.useCallback(async v=>{await Zp({conversation:r,mode:v,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[r,a,e,o]);return{handleBrowseMachineDirectory:d,handleSaveMachineWorkspace:p,handleLaunchMachineIde:u,handleLaunchMachineProvider:m,handleListMachineMeshes:f,handleLaunchMeshCoordinator:g,handleListMachineSavedSessions:k,setActiveCliViewMode:h}}function Hj(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 Fj(e,t,n=Date.now()){return!e||!Hj(t)?null:{tabKey:e,nonce:n}}function Bj({isMobile:e,conversations:t,visibleConversations:n,groupActiveTabIds:r,focusedGroup:a,groupedConvs:o,setSearchParams:i}){const[c,d]=l.useState(null),[p,u]=l.useState(null),m=l.useMemo(()=>{var v,w;if(!e){if(c){const b=t.find(j=>j.tabKey===c);if(b)return b}return n[0]}const h=r[a];if(h){const b=t.find(j=>j.tabKey===h);if(b)return b}return((v=o[a])==null?void 0:v[0])||((w=o[0])==null?void 0:w[0])},[t,c,a,r,o,e,n]),f=l.useCallback(h=>{d(h)},[]),g=l.useCallback(h=>{d(h.tabKey),i(v=>{const w=new URLSearchParams(v),b=g0(h);return b?w.set("activeTab",b):w.delete("activeTab"),w},{replace:!0})},[i]),k=l.useCallback((h,v)=>{const w=Fj(h,v);w&&u(w)},[]);return{activeConv:m,openDesktopConversation:g,requestScrollToBottom:k,scrollToBottomRequest:p,setDesktopActiveTab:f}}function Oj(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 Wj(e){const t=String(e.liveState.completionMarker||""),n=String(e.liveState.seenCompletionMarker||""),r=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,o=[e.tabKey,e.historySessionId||"",t,n,r,a?"1":"0"].join(":");return{shouldMarkSeen:!!(r==="task_complete"&&a&&(!t||t!==n)),autoReadKey:o,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function Uj({activeConv:e,isMobile:t,liveSessionInboxState:n,sendDaemonCommand:r}){const a=l.useRef(null),o=l.useRef(null),i=l.useRef(null),c=l.useRef(null),d=l.useRef(null);l.useEffect(()=>{const p=()=>{i.current&&(clearTimeout(i.current),i.current=null),c.current&&(clearTimeout(c.current),c.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),o.current=null};if(t){p(),a.current=null;return}if(!(e!=null&&e.sessionId)){p(),a.current=null;return}const u=Hs(e,n),m=Wj({tabKey:e.tabKey,historySessionId:Ha(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:en(e),liveState:u}),f=m.autoReadKey,g=Oj({autoReadKey:f,shouldMarkSeen:m.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!m.shouldMarkSeen){g.shouldCancelPending&&p(),a.current=f;return}if(!g.shouldSchedule)return;g.shouldCancelPending&&p();const k=()=>{if(document.visibilityState!=="visible"||a.current===f)return;a.current=f,o.current=null,i.current=null,c.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const v=m.readAt;r(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:v,completionMarker:m.completionMarker}).catch(()=>{})};if(o.current=g.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(k,1500);const v=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};d.current=v,document.addEventListener("visibilitychange",v);return}const h=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(k,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=h,document.addEventListener("visibilitychange",h)},[e,t,n,r]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current),c.current&&clearTimeout(c.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function So(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 Gj({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:n,ides:r,sendDaemonCommand:a,updateRouteChats:o,setToasts:i,setClearedTabs:c,setSearchParams:d}){var O;const{launchCli:p}=Pa(),[u,m]=l.useState(!1),[f,g]=l.useState([]),[k,h]=l.useState(()=>Wt()),[v,w]=l.useState(!1),[b,j]=l.useState(null),C=l.useRef(null),y=l.useMemo(()=>n||t||e,[e,n,t]),x=!!y&&ut(y)&&!dt(y),N=l.useMemo(()=>{if(!y||!x)return null;const E=y.daemonId||y.routeId||"",T=ks(y),$=So(y);return`${E}:${T}:${y.providerSessionId||""}:${$}`},[y,x]),S=l.useMemo(()=>!y||!x?"":So(y),[y,x]),{isCreatingChat:A,isRefreshingHistory:M,handleSwitchSession:P,handleNewChat:D,handleRefreshHistory:I}=am({sendDaemonCommand:a,activeConv:y,chats:(O=r.find(E=>E.id===(y==null?void 0:y.routeId)))==null?void 0:O.chats,updateRouteChats:o,setToasts:i,setClearedTabs:c}),_=l.useCallback(()=>{m(!0)},[]),W=l.useCallback(()=>{m(!1)},[]),H=l.useCallback(async()=>{if(!(!y||!x||v)){w(!0);try{const E=y.daemonId||y.routeId,T=ks(y),$=So(y),R=await a(E,"list_saved_sessions",{agentType:T,providerType:T,kind:"cli",limit:50,...y.providerSessionId?{providerSessionId:y.providerSessionId}:{},...$?{workspace:$}:{}}),G=(R==null?void 0:R.result)??R;g(Array.isArray(G==null?void 0:G.sessions)?G.sessions:[])}catch(E){console.error("Refresh saved sessions failed",E),g([])}finally{w(!1)}}},[y,v,x,a]);l.useEffect(()=>{if(!u){C.current=null;return}if(!x){C.current=null,g([]),w(!1);return}!N||v||C.current!==N&&(C.current=N,H())},[H,u,v,x,N]);const L=l.useCallback(async E=>{if(!y||!x||!E.providerSessionId||!E.workspace)return;const T=y.daemonId||y.routeId,$=ks(y);try{j(E.providerSessionId);const R=await p(T,{cliType:$,dir:E.workspace,resumeSessionId:E.providerSessionId,initialModel:Fu(E.summaryMetadata,"model",{preferShortValue:!0})||void 0}),G=(R==null?void 0:R.result)??R,Q=typeof(G==null?void 0:G.sessionId)=="string"?G.sessionId:typeof(G==null?void 0:G.id)=="string"?G.id:"";Q&&d(re=>{const J=new URLSearchParams(re);return J.set("activeTab",Q),J},{replace:!0}),W()}catch(R){console.error("Resume saved session failed",R)}finally{j(null)}},[W,y,x,a,d]);return{historyModalOpen:u,openHistoryModal:_,closeHistoryModal:W,historyTargetConv:y,isSavedSessionHistoryTarget:x,isHistoryCreatingChat:A,isHistoryRefreshingHistory:M,handleHistorySwitchSession:P,handleHistoryNewChat:D,handleHistoryRefresh:I,savedHistorySessions:f,savedHistoryFilters:k,setSavedHistoryFilters:h,missingWorkspaceResumePath:S,isSavedHistoryLoading:v,resumingSavedHistorySessionId:b,handleRefreshSavedHistory:H,handleResumeSavedHistorySession:L}}function qj({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}){const[d,p]=l.useState(null),[u,m]=l.useState(null),f=l.useMemo(()=>{if(e||!r)return null;const w=c(r);return w&&!ut(w)&&!dt(w)?w:null},[e,r,c]),g=l.useMemo(()=>{const w=d==null?void 0:d.routeId;if(!w)return null;const b=d!=null&&d.tabKey?o.find(j=>j.tabKey===d.tabKey):a?o.find(j=>j.tabKey===a):null;return(b==null?void 0:b.routeId)===w?b:ps(o,w)},[o,d,a]),k=l.useMemo(()=>{if(g)return i.find(w=>w.id===g.routeId)},[i,g]);l.useEffect(()=>{f&&(p({routeId:f.routeId,tabKey:mc(f)}),m(f),n({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,n,f]);const h=l.useCallback(w=>{w&&(p({routeId:w.routeId,tabKey:mc(w)}),m(w))},[]),v=l.useCallback(()=>{p(null),m(null)},[]);return{remoteDialogConv:g,remoteDialogIdeEntry:k,remoteDialogActiveConv:u,setRemoteDialogActiveConv:m,openRemoteDialog:h,closeRemoteDialog:v}}function zj({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c,activeConv:d,sendDaemonCommand:p}){const{remoteDialogConv:u,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:g,openRemoteDialog:k,closeRemoteDialog:h}=qj({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}),[v,w]=l.useState(!1),[b,j]=l.useState(null),C=l.useCallback(async N=>{const S=N||d;!S||!ut(S)&&!dt(S)||(j(S),w(!0))},[d]),y=l.useCallback(()=>{w(!1),j(null)},[]),x=l.useCallback(async N=>{const S=b||d;if(!S||!ut(S)&&!dt(S)){y();return}w(!1);try{const A=ks(S),M=S.routeId||S.daemonId||"";await p(M,"stop_cli",{cliType:A,targetSessionId:S.sessionId,mode:N,...Oa(S)})}catch(A){console.error("Stop CLI failed:",A)}finally{j(null)}},[d,y,b,p]);return{remoteDialogConv:u,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:g,openRemoteDialog:k,closeRemoteDialog:h,cliStopDialogOpen:v,cliStopTargetConv:b,requestCliStop:C,cancelCliStop:y,confirmCliStop:x}}function Co(e,t=!0){return(e??!0)&&t}const fl=l.memo(function({activeConv:t,clearToken:n,isCliTerminal:r,ideEntry:a,terminalRef:o,handleModalButton:i,handleRelaunch:c,handleSendChat:d,handleForceSendChat:p,isSendingChat:u,sendFeedbackMessage:m=null,handleFocusAgent:f,isFocusingAgent:g,actionLogs:k,userName:h,scrollToBottomRequestNonce:v,isInputActive:w=!0,isVisible:b=!0}){const j=r,C=!r,y=Co(b,j),x=Co(b,C),N=Co(b),S=Jp(t),A=S.status||S.modalMessage||S.modalButtons?{...t,...S.status?{status:S.status}:{},...S.modalMessage!==void 0?{modalMessage:S.modalMessage}:{},...S.modalButtons!==void 0?{modalButtons:S.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(Iu,{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(nn,{size:14})}),s.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),s.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:c,children:"Relaunch with CDP"})]})}):null,A.transport==="pty"?s.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[s.jsx("div",{"aria-hidden":!r,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:j?"visible":"hidden",pointerEvents:j?"auto":"none"},children:s.jsx(Yk,{activeConv:A,clearToken:n,terminalRef:o,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:m,isVisible:y,isInputActive:w&&y})}),s.jsx("div",{"aria-hidden":r,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:C?"visible":"hidden",pointerEvents:C?"auto":"none"},children:s.jsx(bi,{activeConv:A,ideEntry:a,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:k,userName:h,scrollToBottomRequestNonce:v,isInputActive:w&&x,isVisible:x})})]}):s.jsx(bi,{activeConv:A,ideEntry:a,handleSendChat:d,handleForceSendChat:p,isSendingChat:u,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:k,userName:h,scrollToBottomRequestNonce:v,isInputActive:w&&N,isVisible:N})]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.handleModalButton===t.handleModalButton&&e.handleRelaunch===t.handleRelaunch&&e.handleSendChat===t.handleSendChat&&e.handleForceSendChat===t.handleForceSendChat&&e.isSendingChat===t.isSendingChat&&e.sendFeedbackMessage===t.sendFeedbackMessage&&e.handleFocusAgent===t.handleFocusAgent&&e.isFocusingAgent===t.isFocusingAgent&&e.actionLogs===t.actionLogs&&e.userName===t.userName&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isInputActive===t.isInputActive&&e.isVisible===t.isVisible);function Kj({conversation:e,className:t="",onOpenNativeConversation:n,onOpenMachine:r,interactive:a=!0,meshOnly:o=!1}){var C,y,x;const{t:i}=Se("common"),c=wr(),d=Ts(e),p=o?null:Zu(e),u=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),m=!o&&e.streamSource==="agent-stream"&&!!e.agentName,f=!o&&!m&&(e.transport==="pty"||e.transport==="acp"),g=An(e),k=b0(e),h=(C=e.settings)==null?void 0:C.meshNodeFor,v=e.meshQueueStats,w=((y=e.coordinator)==null?void 0:y.meshId)||((x=e.settings)==null?void 0:x.meshCoordinatorFor),b=l.useCallback(()=>{if(r){r();return}d&&c("/dashboard",{state:{openMachineId:d}})},[d,c,r]),j=l.useCallback(()=>{if(n){n();return}const N=dm(e);N&&c(xr(N))},[e,c,n]);return!u&&!m&&!f&&!p&&!h&&!v?null:s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[u&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:j,title:k,children:[s.jsx(hs,{size:12}),s.jsx("span",{children:k})]}):s.jsxs("span",{className:"conversation-meta-chip",title:k,children:[s.jsx(hs,{size:12}),s.jsx("span",{children:k})]})),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(mr,{size:12}),s.jsx("span",{children:g})]}),f&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(mr,{size:12}),s.jsx("span",{children:g})]}),p&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:b,title:p,children:[s.jsx(_s,{size:12}),s.jsx("span",{children:p})]}):s.jsxs("span",{className:"conversation-meta-chip",title:p,children:[s.jsx(_s,{size:12}),s.jsx("span",{children:p})]})),h&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(_s,{size:12}),s.jsx("span",{children:i("dashboard.metaChips.meshNode")})]}),w&&v&&s.jsxs("span",{className:`conversation-meta-chip ${v.pending>0?"is-active":""}`,style:v.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${v.pending} pending, ${v.assigned} assigned, ${v.completed} completed, ${v.failed} failed`,children:[s.jsx(qf,{size:12}),s.jsxs("span",{children:[v.pending," Pending"]})]})]})}function Vj({selectedConversation:e,isAcp:t,isStandalone:n,selectedIdeEntry:r,actionLogs:a,userName:o,isSendingChat:i,sendFeedbackMessage:c=null,isFocusingAgent:d,onBack:p,onOpenNativeConversation:u,onOpenMachine:m,onOpenHistory:f,onOpenRemote:g,onOpenMeshGraph:k,onStopCli:h,cliViewMode:v,onSetCliViewMode:w,handleSendChat:b,handleForceSendChat:j,handleFocusAgent:C,handleModalButton:y,handleRelaunch:x}){var D,I;const N=l.useRef(null),S=ut(e)&&!t,A=S&&v==="terminal",M=!!e.daemonId&&!!((D=e.coordinator)!=null&&D.meshId||(I=e.settings)!=null&&I.meshCoordinatorFor),P=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 ${P} 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($i,{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:xt(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(Kj,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>m(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[S&&v&&s.jsx(Tp,{mode:v,onChange:w,compact:!0}),S&&h&&s.jsx("button",{onClick:()=>{h(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(Mt,{size:14})}),M&&k&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>k(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(ts,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",children:s.jsx(Fi,{size:14})}),!t&&!S&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",children:s.jsx(hs,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(fl,{activeConv:e,clearToken:0,isCliTerminal:A,ideEntry:r,terminalRef:N,handleModalButton:y,handleRelaunch:x,handleSendChat:b,handleForceSendChat:j,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:C,isFocusingAgent:d,actionLogs:a,userName:o})})]})}const jo={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 Yj(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function mm(){const[e,t]=l.useState("unix"),[n,r]=l.useState("powershell"),[a,o]=l.useState(!1),i=e==="unix"?"unix":n;l.useEffect(()=>{t(Yj())},[]);const c=l.useCallback(()=>{navigator.clipboard.writeText(jo[i].cmd).catch(()=>{}),o(!0),setTimeout(()=>o(!1),2e3)},[i]);return s.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("unix"),children:"🍎🐧 macOS / Linux"}),s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("windows"),children:"🪟 Windows"})]}),e==="windows"&&s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${n==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>r("powershell"),children:"⚡ PowerShell"}),s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${n==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>r("cmd"),children:">_ CMD"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:c,title:"Click to copy",children:[s.jsx("span",{className:"text-text-muted select-none",children:jo[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:jo[i].cmd}),s.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:a?"✓":"📋"})]}),s.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",s.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function hm({section:e,onSectionChange:t}){const n=[{key:"machines",label:"Machines",icon:hs},{key:"chats",label:"Chats",icon:ln}];return s.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:s.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:n.map(({key:r,label:a,icon:o})=>{const i=e===r;return s.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${i?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:i?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>t(r),type:"button","aria-pressed":i,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${i?"text-accent-primary":"bg-transparent text-current"}`,style:i?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:s.jsx(o,{size:15})}),s.jsx("span",{children:a})]},r)})})})}function Wr({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 pn({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 Yn({icon:e,title:t,subtitle:n,children:r}){return s.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[s.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),s.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:t}),s.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:n}),r]})}function Jj({conversation:e,onCancel:t,onConfirm:n}){const{t:r}=Se(),a=xt(e);return s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:t,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"mobile-hide-confirm-title",className:"card fade-in mobile-compact-dialog relative w-full sm:w-[min(92vw,420px)] md:w-[92%] md:max-w-[420px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-bg-primary",children:[s.jsx("h3",{id:"mobile-hide-confirm-title",className:"m-0 text-base md:text-lg font-extrabold",children:r("mobileInbox.hideTitle",{title:a})}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:r("mobileInbox.hideDescription")})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[s.jsx("button",{onClick:n,className:"btn btn-primary w-full justify-center min-h-[42px]",children:r("mobileInbox.hide")}),s.jsx("button",{onClick:t,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:r("common.cancel")})]})]})]})}function Ur({item:e,type:t,getAvatarText:n,onOpenConversation:r,onRequestHideConversation:a,onRequestStopCli:o,onOpenMeshGraph:i,onCollectChatDebugBundle:c,isMuted:d,onToggleMute:p}){const{t:u}=Se(),m=t==="needs_attention"||t==="task_complete",f=t==="working",g=t==="earlier",k=t==="task_complete",{isReconnecting:h,isConnecting:v}=cn(e.conversation),w=xt(e.conversation),b=Mn(e.conversation),j=jp(e.conversation,{requiresAction:t==="needs_attention"}),C=m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":f?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":g?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",y=m?"bg-accent-primary shadow-glow":f?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":g?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",x=g?"text-text-secondary":"text-text-primary",N=g?"text-text-muted":"text-text-secondary",S=g?"text-text-secondary opacity-80":"text-text-muted",A=g?"text-text-muted opacity-80":"text-text-muted",M=!f&&!k,P=Sp(e.conversation),D="text-[color:var(--status-warning)]",I=_=>{if(!c)return;_.preventDefault(),_.stopPropagation();const W=c==null?void 0:c(e.conversation);Promise.resolve(W).catch(H=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",H)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${C}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[m||f?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${y}`,style:m?{color:"var(--accent-on-primary)"}:void 0,children:n(w)}),P&&i&&s.jsx("button",{type:"button",className:"mobile-inbox-mesh-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:_=>{_.preventDefault(),_.stopPropagation(),i(e.conversation)},"aria-label":u("mobileInbox.openMeshGraphFor",{title:w}),title:u("mobileInbox.openLiveMeshGraph"),children:s.jsx(ts,{size:13})})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>r(e.conversation),onContextMenu:I,type:"button",children:[s.jsx("div",{className:"flex items-center gap-2 pr-[124px]",children:s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${x}`,children:w})}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${N}`,children:[s.jsx("span",{className:"truncate",children:b}),s.jsx(ya,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),h?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${D} animate-pulse`,children:u("mobileInbox.reconnectingItem")})]}):v?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:u("mobileInbox.connectingItem")})]}):j==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:D,children:u("mobileInbox.actionNeeded")})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${S}`,children:e.preview})]}),s.jsxs("div",{className:"mobile-inbox-corner-actions absolute top-3 right-3 flex items-center gap-1.5",children:[M&&s.jsx("span",{className:`mr-0.5 text-[11px] font-medium shrink-0 ${A}`,children:Mu(e.timestamp)}),k&&s.jsx("span",{className:"rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:u("mobileInbox.done")}),p&&s.jsx("button",{type:"button",className:`mobile-inbox-mute-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border transition-colors ${d?"border-amber-500/60 bg-amber-500 text-white hover:bg-amber-600":"border-border-subtle bg-bg-primary/70 text-text-muted hover:border-border-default hover:text-text-primary"}`,onClick:_=>{_.preventDefault(),_.stopPropagation(),p()},"aria-label":d?u("mobileInbox.unmute",{title:w}):u("mobileInbox.mute",{title:w}),title:u(d?"mobileInbox.mutedTitle":"mobileInbox.muteNotifications"),children:d?s.jsx(bu,{size:13}):s.jsx(Rn,{size:13})}),a&&s.jsx("button",{type:"button",className:"mobile-inbox-hide-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:_=>{_.preventDefault(),_.stopPropagation(),a()},"aria-label":u("mobileInbox.hideConversationAria",{title:w}),title:u("mobileInbox.hideConversationTitle"),children:s.jsx(Bi,{size:13})}),o&&s.jsx("button",{type:"button",className:"mobile-inbox-stop-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-status-error/30 bg-bg-primary/70 text-status-error transition-colors hover:border-status-error/60 hover:bg-status-error/10",onClick:_=>{_.preventDefault(),_.stopPropagation(),o()},"aria-label":u("mobileInbox.stopSessionAria",{title:w}),title:u("mobileInbox.stopSessionTitle"),children:s.jsx(Mt,{size:13})})]})]})},e.conversation.tabKey)}function Zc({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 ed({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 Qj({section:e,attentionItems:t,unreadItems:n,workingItems:r,completedItems:a,hiddenConversations:o,machineCards:i,getAvatarText:c,actionLogs:d,sendDaemonCommand:p,onOpenConversation:u,onShowAllHidden:m,onHideConversation:f,onOpenMeshGraph:g,onStopCli:k,onOpenNewSession:h,onOpenMachine:v,onOpenSettings:w,onSectionChange:b,wsStatus:j="connected",isStandalone:C=!1,onCollectChatDebugBundle:y,isConversationMuted:x,onToggleMuteConversation:N}){const{t:S}=Se(),[A,M]=l.useState(null),P=j==="disconnected"||j==="reconnecting"||j==="offline"||j==="auth_failed",D=i.length>0,I=t.length>0||n.length>0||r.length>0||a.length>0,_=S(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),W=C?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",H=C?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",L=l.useCallback(async T=>{const $=Js(T);if(!$)return;const R=Array.isArray(T.messages)?T.messages:[],G=ap({activeConv:T,visibleMessages:R,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:R.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),Q=await p($,"get_chat_debug_bundle",{...Ys(T),delivery:"daemon_file",frontendSnapshot:G}),re=ir(Q),J=lp(re),X=await ip(J);X==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),pt.showToast(op(re,{locatorCopyStatus:X}),X==="failed"?"warning":"success")},[d,p]),O=y||L,E=l.useCallback(()=>{A&&(f==null||f(A),M(null))},[A,f]);return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${W}`,children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:_}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||n.length>0)&&s.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[s.jsx(Rn,{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(La,{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:P?s.jsx(Yn,{icon:s.jsx(Zc,{}),title:S(j==="offline"?"mobileInbox.networkOffline":j==="auth_failed"?"mobileInbox.sessionExpired":"mobileInbox.reconnecting"),subtitle:S(j==="offline"?"mobileInbox.waitingForNetwork":j==="auth_failed"?"mobileInbox.pleaseLogInAgain":"mobileInbox.restoringConnection")}):i.length===0?s.jsx(Yn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:S(C?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:S(C?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!C&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(mm,{})})}):s.jsx(pn,{children:i.map((T,$)=>s.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${$>0?"border-t border-border-subtle/70":""}`,onClick:()=>v(T.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(T.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:T.label}),s.jsxs("span",{className:"flex items-center gap-2 text-[11px] font-medium text-text-muted shrink-0",children:[s.jsx(ed,{count:T.generatingCount,label:S("mobileInbox.generatingCount",{count:T.generatingCount})}),T.unread>0?s.jsx("span",{className:"text-accent-primary",children:S("mobileInbox.newCount",{count:T.unread})}):T.total>0?S("mobileInbox.chatCount",{count:T.total}):S("mobileInbox.idle")]})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:T.subtitle}),T.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[S("mobileInbox.chatCount",{count:T.total}),T.unread>0?S("mobileInbox.unreadSuffix",{count:T.unread}):"",T.generatingCount>0?S("mobileInbox.collapsedGeneratingSuffix",{count:T.generatingCount}):""]}):T.generatingCount>0?s.jsx("div",{className:"text-[13px] text-accent-primary mt-0.5 font-medium",children:S("mobileInbox.generatingCount",{count:T.generatingCount})}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:S("mobileInbox.noActiveChats")})]})]},T.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(Wr,{title:S("mobileInbox.needsAttention"),className:"mb-0"}),s.jsx(pn,{children:t.map((T,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Ur,{item:T,type:"needs_attention",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>M(T.conversation):void 0,onRequestStopCli:k?()=>k(T.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:O,isMuted:x==null?void 0:x(T.conversation),onToggleMute:N?()=>N(T.conversation):void 0})},T.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(Wr,{title:S("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),s.jsx(pn,{children:n.map((T,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Ur,{item:T,type:"task_complete",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>M(T.conversation):void 0,onRequestStopCli:k?()=>k(T.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:O,isMuted:x==null?void 0:x(T.conversation),onToggleMute:N?()=>N(T.conversation):void 0})},T.conversation.tabKey))})]}),e==="chats"&&r.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(Wr,{title:S("mobileInbox.workingNow"),className:"mb-0 mt-2"}),s.jsx(pn,{children:r.map((T,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Ur,{item:T,type:"working",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>M(T.conversation):void 0,onRequestStopCli:k?()=>k(T.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:O,isMuted:x==null?void 0:x(T.conversation),onToggleMute:N?()=>N(T.conversation):void 0})},T.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&s.jsx(Wr,{title:S("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(pn,{children:a.map((T,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Ur,{item:T,type:"earlier",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>M(T.conversation):void 0,onRequestStopCli:k?()=>k(T.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:O,isMuted:x==null?void 0:x(T.conversation),onToggleMute:N?()=>N(T.conversation):void 0})},T.conversation.tabKey))}):I?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:S("mobileInbox.allCaughtUp")}):P?s.jsx(Yn,{icon:s.jsx(Zc,{size:28}),title:S("mobileInbox.connecting"),subtitle:S("mobileInbox.connectingSubtitle")}):D?s.jsx(Yn,{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(ln,{size:20})}),title:S("mobileInbox.noConversations"),subtitle:S("paneGroup.newSessionDescription"),children:h&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:h,"aria-label":S("paneGroup.newSession"),title:S("paneGroup.newSession"),children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s.jsx("span",{children:S("paneGroup.newSession")})]})}):s.jsx(Yn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:S("mobileInbox.noMachinesConnected"),subtitle:S("mobileInbox.noMachinesSubtitle")})]}),e==="chats"&&o.length>0&&(()=>{const T=Ub(o);return s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(pn,{className:"mt-4 border-dashed bg-bg-secondary/20",children:s.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:S("mobileInbox.hiddenTabs")}),s.jsx(ed,{count:T,label:S("mobileInbox.generatingCount",{count:T})})]}),s.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[S("mobileInbox.collapsedCount",{count:o.length}),T>0?S("mobileInbox.collapsedGeneratingSuffix",{count:T}):""]})]}),s.jsx("button",{type:"button",className:"shrink-0 rounded-full border border-border-subtle bg-bg-primary/70 px-3 py-1.5 text-[12px] font-semibold text-accent-primary hover:border-border-default",onClick:m,children:S("mobileInbox.restoreAll")})]})})})})()]}),e==="chats"&&h&&I&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:h,"aria-label":S("paneGroup.newSession"),title:S("paneGroup.newSession"),children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),A&&s.jsx(Jj,{conversation:A,onCancel:()=>M(null),onConfirm:E}),s.jsx(hm,{section:e,onSectionChange:b})]})}function Xj(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 fm(e){const t=[e.workspace||"Workspace unknown"],n=rn(e.summaryMetadata);n&&t.push(n),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const r=Xj(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:r?`Updated ${r}`:"",preview:(e.preview||"").trim()}}function bl({title:e,description:t,currentPath:n,directories:r,busy:a=!1,error:o="",confirmLabel:i="Use this folder",onClose:c,onNavigate:d,onConfirm:p}){const[u,m]=l.useState(n),{t:f}=Se("common");l.useEffect(()=>{m(n)},[n]);const g=Tj(n),k=u.trim();return s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:s.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:c,"aria-label":"Close folder browser",children:s.jsx(Mt,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!g||a||d(g)},disabled:!g||a,children:[s.jsx($i,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:f("machine.workspaceBrowse.currentFolder")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:u,onChange:h=>m(h.target.value),onKeyDown:h=>{h.key!=="Enter"||!k||a||(h.preventDefault(),d(k))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!k||a||d(k)},disabled:!k||a,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):o?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:o}):r.length===0?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):s.jsx("div",{className:"p-3",children:r.map(h=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>d(h.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Nn,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:h.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:h.path})]})]},h.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:c,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>p(k||n),disabled:!k&&!n||a,children:i})]})]})})}function gl({title:e,description:t,details:n,workspaceOptions:r,selectedWorkspaceKey:a,onWorkspaceChange:o,confirmLabel:i,busyLabel:c,busy:d=!1,showArgsInput:p,argsValue:u,onArgsChange:m,showModelInput:f,modelValue:g,onModelChange:k,historyProviderNode:h,onConfirm:v,onCancel:w}){const{t:b}=Se("common"),j=i??b("machine.launchConfirm.launch"),C=c??b("machine.launchConfirm.launching"),y=r==null?void 0:r.find(x=>x.key===a);return s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:w,"aria-label":b("machine.launchConfirm.closeAria"),children:s.jsx(Mt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[r&&r.length>0&&o&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.workspace")}),s.jsx("select",{value:a||"",onChange:x=>o(x.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:d,children:r.map(x=>s.jsx("option",{value:x.key,children:x.label},x.key))}),(y==null?void 0:y.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:y.description})]}),h,n.map(x=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:x.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:x.value})]},`${x.label}:${x.value}`)),f&&k&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.languageModel")}),s.jsx("input",{type:"text",value:g||"",onChange:x=>k(x.target.value),placeholder:b("machine.launchConfirm.autoDetect"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]}),p&&m&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.cliArgs")}),s.jsx("input",{type:"text",value:u||"",onChange:x=>m(x.target.value),placeholder:b("machine.launchConfirm.cliArgsPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:w,disabled:d,children:b("machine.launchConfirm.cancel")}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:v,disabled:d,children:[s.jsx(fu,{size:14}),d?C:j]})]})]})})}function td(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function bm(e){const{machine:t,currentWorkspacePath:n,currentWorkspaceId:r,includeHome:a=!0,homeLabel:o="Home directory",homeDescription:i="Launch without a workspace"}=e,c=[];a&&c.push({key:"__home__",label:o,description:i,workspaceId:null,workspacePath:null});for(const u of t.workspaces||[])c.push({key:`saved:${u.id}`,label:`${u.id===t.defaultWorkspaceId?"⭐ ":""}${td(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const d=(n==null?void 0:n.trim())||"",p=d?(t.workspaces||[]).find(u=>u.path===d):null;if(d&&!p&&c.push({key:`custom:${d}`,label:td(d),description:d,workspaceId:null,workspacePath:d}),r){const u=`saved:${r}`;if(c.some(m=>m.key===u))return{options:c,selectedKey:u}}return p?{options:c,selectedKey:`saved:${p.id}`}:d?{options:c,selectedKey:`custom:${d}`}:{options:c,selectedKey:"__home__"}}function Zj(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function e1(e){return[Zj(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function t1(e){return e.lastLaunchedAt?Ea(e.lastLaunchedAt):""}function gm(e){return{metaText:e1(e),updatedLabel:t1(e)}}function No(e,t,n){return e?"ide":t>0?"cli":n>0?"acp":null}function s1({selectedMachineEntry:e,cliProviders:t,acpProviders:n,machineAction:r,onBrowseDirectory:a,onListSavedSessions:o}){var be,Pe,Be,it;const i=_n(),[c,d]=l.useState(!1),p=(((be=e.detectedIdes)==null?void 0:be.length)||0)>0,u=l.useMemo(()=>(e.workspaces||[]).map(ae=>({id:ae.id,path:ae.path,label:ae.label})),[e]),m=e.defaultWorkspaceId||null,[f,g]=l.useState(m||((Pe=u[0])==null?void 0:Pe.id)||""),[k,h]=l.useState(""),[v,w]=l.useState(""),[b,j]=l.useState([]),[C,y]=l.useState(!1),[x,N]=l.useState(""),[S,A]=l.useState(!1),[M,P]=l.useState(No(p,t.length,n.length)),D=l.useRef(null),[I,_]=l.useState(null),W=l.useRef("__home__"),[H,L]=l.useState("__home__"),[O,E]=l.useState(""),[T,$]=l.useState(""),[R,G]=l.useState(""),[Q,re]=l.useState([]),[J,X]=l.useState(()=>Wt().textQuery),[ue,se]=l.useState(()=>Wt().workspaceQuery),[B,ie]=l.useState(()=>Wt().modelQuery),[K,le]=l.useState(()=>Wt().resumableOnly),[je,we]=l.useState(()=>Wt().sortMode),[ke,he]=l.useState(!1),[U,q]=l.useState(!1),Z=l.useRef(null),Y=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const fe=f==="__custom__"?k.trim():((Be=u.find(ae=>ae.id===f))==null?void 0:Be.path)||"",Me=f==="__custom__"&&!!fe&&r.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(r.message),de=f!=="__custom__"&&((it=u.find(ae=>ae.id===f))==null?void 0:it.path)||"",F=l.useMemo(()=>(e.recentLaunches||[]).map(ae=>ae.workspace),[e]),me=l.useCallback(async ae=>{y(!0),N("");try{const _e=await a(ae);w(_e.path),h(_e.path),j(_e.directories)}catch(_e){N(_e instanceof Error?_e.message:"Could not load folder")}finally{y(!1)}},[a]),ce=l.useCallback(()=>{var _e;g("__custom__"),A(!0);const ae=ml(e.platform,pl(k.trim(),de,F,e.defaultWorkspacePath,(_e=u.find(lt=>lt.id===m))==null?void 0:_e.path,u.map(lt=>lt.path)));me(ae)},[k,m,me,F,de,e.platform,u]),z=l.useCallback(ae=>{if(ae!=null&&ae.workspaceId){g(ae.workspaceId),h("");return}if(ae!=null&&ae.workspacePath){g("__custom__"),h(ae.workspacePath);return}g(""),h("")},[]),ge=l.useCallback(ae=>{if(g(ae),ae==="__custom__"){ce();return}h("")},[ce]),Ce=l.useCallback(ae=>{g("__custom__"),h(ae)},[]),Ne=l.useCallback((ae,_e)=>{D.current=_e,W.current=ae.selectedWorkspaceKey||"__home__",L(ae.selectedWorkspaceKey||"__home__"),E(ae.initialArgs||""),$(ae.initialModel||""),G(""),re([]);const lt=ae.providerType?`${e.id}:${ae.providerType}`:null;if(aS(Y.current,lt)){const ct=Wt();X(ct.textQuery),se(ct.workspaceQuery),ie(ct.modelQuery),le(ct.resumableOnly),we(ct.sortMode)}Y.current=lt,_(ae),ae.providerType&&o&&(he(!0),o(ae.providerType).then(ct=>re(ct||[])).catch(ct=>console.warn("Failed to load saved sessions",ct)).finally(()=>he(!1)))},[o,e.id]),He=l.useMemo(()=>Ip(Q,{textQuery:J,workspaceQuery:ue,modelQuery:B,resumableOnly:K,sortMode:je}),[B,K,Q,je,J,ue]);l.useEffect(()=>{R&&(He.some(ae=>ae.providerSessionId===R)||G(""))},[He,R]);const Ze=l.useCallback(()=>{D.current&&(q(!0),D.current().finally(()=>{D.current=null,q(!1),_(null)}))},[]),Ye=l.useCallback(()=>{D.current=null,_(null)},[]),ot=l.useCallback(ae=>{W.current=ae,L(ae)},[]);return l.useEffect(()=>{var ae;Z.current!==e.id&&(Z.current=e.id,g(m||((ae=u[0])==null?void 0:ae.id)||"__custom__"),h(""),w(""),j([]),N(""),A(!1),X(Wt().textQuery),se(Wt().workspaceQuery),ie(Wt().modelQuery),le(Wt().resumableOnly),we(Wt().sortMode),Y.current=null,P(No(p,t.length,n.length)))},[n.length,t.length,m,p,e.id,u]),l.useEffect(()=>{var ae;f!=="__custom__"&&(f&&u.some(_e=>_e.id===f)||g(m||((ae=u[0])==null?void 0:ae.id)||"__custom__"))},[m,f,u]),l.useEffect(()=>{M==="ide"&&p||M==="cli"&&t.length>0||M==="acp"&&n.length>0||P(No(p,t.length,n.length))},[M,n.length,t.length,p]),{showAllRecent:c,setShowAllRecent:d,hasIdeOptions:p,workspaceRows:u,defaultWorkspaceId:m,workspaceChoice:f,customWorkspacePath:k,browseCurrentPath:v,browseDirectories:b,browseBusy:C,browseError:x,browseDialogOpen:S,activeLauncherKind:M,launchConfirm:I,launchConfirmWorkspaceKeyRef:W,launchConfirmWorkspaceKey:H,launchConfirmArgs:O,launchConfirmModel:T,launchConfirmResumeId:R,launchConfirmSavedSessions:Q,launchConfirmTextFilter:J,launchConfirmWorkspaceFilter:ue,launchConfirmModelFilter:B,launchConfirmResumableOnly:K,launchConfirmSortMode:je,filteredLaunchConfirmSavedSessions:He,launchConfirmSessionsLoading:ke,launchConfirmBusy:U,resolvedWorkspacePath:fe,canCreateMissingWorkspace:Me,openBrowseDialog:ce,loadBrowsePath:me,handleWorkspaceChoiceChange:ge,chooseCustomWorkspacePath:Ce,setCustomWorkspacePath:h,setBrowseDialogOpen:A,setActiveLauncherKind:P,openLaunchConfirm:Ne,handleConfirmLaunch:Ze,closeLaunchConfirm:Ye,setWorkspaceSelectionFromOption:z,setLaunchConfirmWorkspaceKeyAndSync:ot,setLaunchConfirmArgs:E,setLaunchConfirmModel:$,setLaunchConfirmResumeId:G,setLaunchConfirmTextFilter:X,setLaunchConfirmWorkspaceFilter:se,setLaunchConfirmModelFilter:ie,setLaunchConfirmResumableOnly:le,setLaunchConfirmSortMode:we}}function n1({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:n,cliProviders:r,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:i,machineAction:c,isStandalone:d,section:p,showBottomNav:u,onBack:m,onSectionChange:f,onOpenConversation:g,onOpenRecent:k,onOpenMachineDetails:h,onMachineUpgrade:v,onLaunchDetectedIde:w,onAddWorkspace:b,onBrowseDirectory:j,onLaunchWorkspaceProvider:C,onListSavedSessions:y}){const{t:x}=Se("common"),N=L=>L==="ide"?"IDE":L==="cli"?"CLI":"ACP",S=n.slice(0,4),A=t.slice(0,3),M=s1({selectedMachineEntry:e,cliProviders:r,acpProviders:a,machineAction:c,onBrowseDirectory:j,onListSavedSessions:y}),P=l.useMemo(()=>S.map(L=>{const{metaText:O,updatedLabel:E}=gm(L);return{key:`recent-launch:${L.id}`,primary:L.label,secondary:O,updatedLabel:E,onClick:()=>{const{options:T,selectedKey:$}=bm({machine:{workspaces:M.workspaceRows,defaultWorkspaceId:M.defaultWorkspaceId},currentWorkspacePath:L.workspace,homeLabel:x("newSession.homeDirectory"),homeDescription:x("newSession.launchWithoutWorkspace")});M.openLaunchConfirm({title:L.kind==="ide"?wa(x,"restart-ide",L.label):L.providerSessionId?Pp(x,L.label):wa(x,"start-fresh",L.label),description:L.kind==="ide"?ka(x,"restart-ide"):L.providerSessionId?Lp(x):ka(x,"start-fresh"),confirmLabel:L.kind==="ide"?Sa(x,"restart-ide"):L.providerSessionId?gi(x,!0):Sa(x,"start-fresh"),busyLabel:L.kind==="ide"?Ca(x,"restart-ide"):L.providerSessionId?Dp(x,!0):Ca(x,"start-fresh"),workspaceOptions:T,selectedWorkspaceKey:$,details:[{label:"Mode",value:N(L.kind)},...L.providerType?[{label:"Provider",value:L.providerType}]:[]]},async()=>{const R=T.find(G=>G.key===M.launchConfirmWorkspaceKeyRef.current);M.setWorkspaceSelectionFromOption(R),await k({...L,workspace:(R==null?void 0:R.workspacePath)??null})})}}}),[M,k,S,x]),D=l.useMemo(()=>A.map(L=>({key:`recent-chat:${L.conversation.tabKey}`,primary:xt(L.conversation),secondary:Ek(L.conversation,{timestampLabel:L.timestamp?Mu(L.timestamp):null}),unread:L.unread,onClick:()=>g(L.conversation)})),[g,A]),I=M.showAllRecent?P:P.slice(0,4),_=P.length>0,W=D.length>0,H=d?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${H} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:m,type:"button","aria-label":"Back",children:s.jsx($i,{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:ss(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:[W&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:D.map(L=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${L.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:L.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:L.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:L.secondary})]},L.key))})]}),_&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:I.map(L=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:L.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:L.primary}),L.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:L.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:L.secondary})]},L.key))}),P.length>4&&s.jsx("div",{className:"flex justify-center px-4 pt-2",children:s.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>M.setShowAllRecent(L=>!L),children:M.showAllRecent?"Show fewer":`Show ${P.length-4} more`})})]}),!1,s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[o&&s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:v,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",i]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:h,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),M.browseDialogOpen&&s.jsx(bl,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:M.browseCurrentPath,directories:M.browseDirectories,busy:M.browseBusy,error:M.browseError,confirmLabel:"Use this folder",onClose:()=>M.setBrowseDialogOpen(!1),onNavigate:L=>{M.loadBrowsePath(L)},onConfirm:L=>{M.chooseCustomWorkspacePath(L),M.setBrowseDialogOpen(!1)}}),M.launchConfirm&&s.jsx(gl,{title:M.launchConfirm.title,description:M.launchConfirm.description,details:M.launchConfirm.details,workspaceOptions:M.launchConfirm.workspaceOptions,selectedWorkspaceKey:M.launchConfirmWorkspaceKey,onWorkspaceChange:M.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:M.launchConfirm.providerType?gi(x,!!M.launchConfirmResumeId):M.launchConfirm.confirmLabel,busyLabel:M.launchConfirm.providerType?void 0:M.launchConfirm.busyLabel,busy:M.launchConfirmBusy,showArgsInput:M.launchConfirm.showArgsInput,argsValue:M.launchConfirmArgs,onArgsChange:M.setLaunchConfirmArgs,showModelInput:M.launchConfirm.showModelInput,modelValue:M.launchConfirmModel,onModelChange:M.setLaunchConfirmModel,historyProviderNode:M.launchConfirm.providerType&&(M.launchConfirmSessionsLoading||M.launchConfirmSavedSessions.length>0)&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),M.launchConfirmSessionsLoading&&s.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:rl(x)}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:M.launchConfirmTextFilter,onChange:L=>M.setLaunchConfirmTextFilter(L.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:M.launchConfirmBusy||M.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:M.launchConfirmWorkspaceFilter,onChange:L=>M.setLaunchConfirmWorkspaceFilter(L.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:M.launchConfirmBusy||M.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:M.launchConfirmModelFilter,onChange:L=>M.setLaunchConfirmModelFilter(L.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:M.launchConfirmBusy||M.launchConfirmSessionsLoading}),s.jsxs("select",{value:M.launchConfirmSortMode,onChange:L=>M.setLaunchConfirmSortMode(L.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:M.launchConfirmBusy||M.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:M.launchConfirmResumableOnly,onChange:L=>M.setLaunchConfirmResumableOnly(L.target.checked),disabled:M.launchConfirmBusy||M.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:M.launchConfirmResumeId,onChange:L=>M.setLaunchConfirmResumeId(L.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:M.launchConfirmBusy||M.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:lS(x)}),M.filteredLaunchConfirmSavedSessions.map(L=>s.jsxs("option",{value:L.providerSessionId,disabled:!L.canResume,children:[L.title||L.providerSessionId," ",L.canResume?"":"(workspace missing)"]},L.providerSessionId))]}),!M.launchConfirmSessionsLoading&&M.launchConfirmSavedSessions.length>0&&M.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),M.launchConfirmResumeId&&(()=>{const L=M.filteredLaunchConfirmSavedSessions.find(E=>E.providerSessionId===M.launchConfirmResumeId);if(!L)return null;const O=fm(L);return s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:O.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:O.providerSessionId}),s.jsx("div",{className:"mt-1",children:O.metaLine}),O.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:O.updatedLabel}),O.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:O.preview})]})})()]}),onConfirm:M.handleConfirmLaunch,onCancel:M.closeLaunchConfirm}),u&&s.jsx(hm,{section:p,onSectionChange:f})]})}const sd=8e3;function r1(e){const t=e&&typeof e=="object"&&"result"in e?e.result:e,n=t&&typeof t=="object",r=n&&t.success===!1,a=n&&t.mirrorStale===!0;return!r&&!a?{confirmed:!0}:{confirmed:!1,reason:r&&typeof t.error=="string"?t.error:a?"the coordinator did not confirm the change":"command was rejected"}}function xm(e,t,n){const r=l.useRef(new Map),[,a]=l.useState(0),o=l.useCallback(()=>a(g=>g+1),[]);l.useEffect(()=>{const g=r.current;if(g.size===0)return;const k=Date.now();let h=!1;for(const[v,w]of g){const b=e.get(v),j=w.muted===void 0||(b?b.muted===w.muted:!1),C=w.hidden===void 0||(b?b.surfaceHidden===w.hidden:!1),y=k-w.at>sd;(j&&C||y)&&(g.delete(v),h=!0)}h&&o()},[e,o]),l.useEffect(()=>{if(r.current.size===0)return;const g=setInterval(()=>{const k=r.current,h=Date.now();let v=!1;for(const[w,b]of k)h-b.at>sd&&(k.delete(w),v=!0);v&&o(),k.size===0&&clearInterval(g)},1e3);return()=>clearInterval(g)});const i=l.useCallback((g,k)=>{const h=r.current.get(g);r.current.set(g,{...h,...k,at:Date.now()}),o()},[o]),c=l.useCallback(g=>{const k=g.sessionId,h=k?r.current.get(k):void 0;return(h==null?void 0:h.muted)!==void 0?h.muted:Hs(g,e).muted??!1},[e]),d=l.useCallback(g=>{const k=g.sessionId,h=k?r.current.get(k):void 0;return(h==null?void 0:h.hidden)!==void 0?h.hidden:Hs(g,e).surfaceHidden??!1},[e]),p=l.useCallback((g,k)=>{const h=Ts(g),v=g.sessionId;!h||!v||(i(v,k),t(h,"set_conversation_prefs",{sessionId:v,...k,...Oa(g)}).then(w=>{const b=r1(w);b.confirmed||(console.warn("[conversation-prefs] set_conversation_prefs not confirmed",b.reason),r.current.delete(v),o(),n==null||n(`Couldn't update conversation — ${b.reason}`))}).catch(w=>{console.warn("[conversation-prefs] set_conversation_prefs failed",w),r.current.delete(v),o();const b=w instanceof Error?w.message:String(w??"the daemon is unreachable");n==null||n(`Couldn't update conversation — ${b}`)}))},[t,i,o,n]),u=l.useCallback(g=>{p(g,{muted:!c(g)})},[p,c]),m=l.useCallback((g,k)=>{p(g,{hidden:k})},[p]),f=l.useCallback(g=>{p(g,{hidden:!d(g)})},[p,d]);return{isMuted:c,isHidden:d,toggleMute:u,setHidden:m,toggleHidden:f}}function oa(e){return[...e].sort((t,n)=>{const r=n.timestamp-t.timestamp;return r!==0?r:t.conversation.tabKey.localeCompare(n.conversation.tabKey)})}function a1(e,t=[]){const n=new Map(e.map(a=>[a.conversation.tabKey,a])),r=t.map(a=>n.get(a)).filter(a=>!!a);return r.length===e.length?r:oa(e)}function o1(e,t=[]){const n=e.filter(i=>i.requiresAction),r=e.filter(i=>i.unread&&!i.requiresAction),a=e.filter(i=>!i.unread&&!i.requiresAction&&i.isWorking),o=e.filter(i=>!i.unread&&!i.requiresAction&&!i.isWorking);return{attentionItems:oa(n),unreadItems:oa(r),workingItems:a1(a,t),completedItems:oa(o)}}function i1(e){var r,a,o;const t=((r=e.p2p)==null?void 0:r.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":!(!!((a=e.p2p)!=null&&a.available)||!!((o=e.p2p)!=null&&o.state))&&e.status&&e.status!=="offline"?"Connected":"Offline"}function l1(e,t){if(!e)return[];const n=e.recentLaunches||[];return n.length>0?n.map(r=>({id:r.id,label:r.title||r.providerName||r.providerType,kind:r.kind,providerType:r.providerType,providerSessionId:r.providerSessionId,subtitle:rn(r.summaryMetadata)||r.workspace||void 0,workspace:r.workspace,summaryMetadata:r.summaryMetadata})):t.filter(r=>r.type!=="adhdev-daemon"&&r.daemonId===e.id).map(r=>{var i;const a=fr(r)?"cli":kn(r)?"acp":"ide",o=rn(r.summaryMetadata);return{id:`${a}:${r.type}:${r.workspace||""}`,label:((i=r.activeChat)==null?void 0:i.title)||(fr(r)?r.cliName||r.type:kn(r)&&r.cliName||r.type),kind:a,providerType:r.type,providerSessionId:r.providerSessionId,subtitle:kn(r)?o||r.workspace||void 0:r.workspace||void 0,workspace:r.workspace||void 0,timestamp:r.lastMessageAt||0}}).sort((r,a)=>a.timestamp-r.timestamp).map(({timestamp:r,...a})=>a)}function c1(e,t,n=[]){const r=new Map;for(const o of t){const i=Ts(o.conversation),c=r.get(i);c?c.push(o):r.set(i,[o])}const a=new Map;for(const o of n){const i=Ts(o),c=a.get(i);c?c.push(o):a.set(i,[o])}return e.map(o=>{const i=r.get(o.id)||[],c=a.get(o.id)||[],d=[...i].sort((h,v)=>v.timestamp-h.timestamp)[0]||null,p=(d==null?void 0:d.conversation)||null,u=di(o),m=i.filter(h=>h.unread||h.requiresAction).length,f=i.filter(h=>hr(h.conversation)).length+c.filter(hr).length,g=i1(o),k=[o.platform||"machine",g].filter(Boolean);return{id:o.id,label:ss(o,{fallbackId:o.id}),subtitle:k.join(" · "),unread:m,total:i.length,generatingCount:f,latestConversation:p,latestTimestamp:(d==null?void 0:d.timestamp)||0,fallbackActivityAt:u,preview:p?_k(p,gp(p)):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((o,i)=>{const c=o.latestTimestamp||o.fallbackActivityAt||0,d=i.latestTimestamp||i.fallbackActivityAt||0;return d!==c?d-c:o.label.localeCompare(i.label)})}function d1(e){return e==="chat"}function Gr(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 u1({conversations:e,machineEntries:t,items:n,selectedConversation:r,selectedTabKey:a,screen:o,liveSessionInboxState:i,sendDaemonCommand:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,setSelectedTabKey:k,setScreen:h,setSelectedMachineId:v,setSection:w,setMachineBackTarget:b,resetMachineAction:j}){const C=l.useRef(null),y=l.useCallback(x=>{if(!(x!=null&&x.sessionId))return;const N=Hs(x,i),S=Math.max(Date.now(),en(x),N.lastUpdated||0);Gr("mark_read:start",{tabKey:x.tabKey,sessionId:x.sessionId,displayPrimary:xt(x),inboxBucket:N.inboxBucket,unread:N.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:en(x),readAt:S}),c(Ts(x)||x.routeId,"mark_session_seen",{sessionId:x.sessionId,providerSessionId:x.providerSessionId,seenAt:S,completionMarker:N.completionMarker}).then(A=>{Gr("mark_read:result",{tabKey:x.tabKey,sessionId:x.sessionId,result:A})}).catch(A=>{Gr("mark_read:error",{tabKey:x.tabKey,sessionId:x.sessionId,error:A instanceof Error?A.message:String(A)})})},[i,c]);return l.useEffect(()=>{var N;if(!r){d1(o)&&h("inbox"),k(((N=e[0])==null?void 0:N.tabKey)||null),C.current=null;return}if(o!=="chat"){C.current=null;return}const x=`${r.tabKey}:${r.sessionId||""}`;C.current!==x&&(C.current=x,y(r))},[e,y,o,r,h,k]),l.useEffect(()=>{if(!d)return;const x=e.find(N=>N.tabKey===d);x&&(k(x.tabKey),h("chat"),p==null||p())},[e,p,d,h,k]),l.useEffect(()=>{if(!u)return;const x=t.find(N=>N.id===u);x&&(v(x.id),j(),w("machines"),b("inbox"),h("machine"),m==null||m())},[t,m,u,j,b,h,w,v]),l.useEffect(()=>{f&&(w(f),h("inbox"),g==null||g())},[g,f,h,w]),l.useEffect(()=>{const x=n.filter(N=>N.inboxBucket==="task_complete"||N.unread);x.length!==0&&Gr("inbox_state",{screen:o,selectedTabKey:a,items:x.map(N=>{const S=Hs(N.conversation,i);return{liveState:S,tabKey:N.conversation.tabKey,sessionId:N.conversation.sessionId,displayPrimary:xt(N.conversation),serverBucket:S.inboxBucket,computedBucket:N.inboxBucket,serverUnread:S.unread,computedUnread:N.unread,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,activityAt:en(N.conversation)}})})},[n,i,o,a]),{markConversationRead:y}}function p1(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 m1(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function h1({sendDaemonCommand:e,navigate:t,ides:n,conversations:r}){const{launchCli:a}=Pa(),[o,i]=l.useState("idle"),[c,d]=l.useState(""),[p,u]=l.useState(null),m=l.useCallback(()=>{i("idle"),d(""),u(null)},[]),f=l.useCallback(async(j,C,y)=>{var x;try{i("loading"),d(`Launching ${C}…`);const N={ideType:C,enableCdp:!0};(x=y==null?void 0:y.workspacePath)!=null&&x.trim()&&(N.workspace=y.workspacePath.trim()),await e(j,"launch_ide",N),i("done"),d(`${C} launch requested`)}catch(N){i("error"),d(N instanceof Error?N.message:"Launch IDE failed"),console.error("Launch IDE failed",N)}},[e]),g=l.useCallback(async(j,C,y)=>{if(C.trim())try{i("loading"),d(y!=null&&y.createIfMissing?"Creating folder…":"Saving workspace…");const x=await e(j,"workspace_add",{path:C.trim(),createIfMissing:(y==null?void 0:y.createIfMissing)===!0});if(x!=null&&x.success){i("done"),d(y!=null&&y.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),d((x==null?void 0:x.error)||"Could not save workspace")}catch(x){i("error"),d(x instanceof Error?x.message:"Could not save workspace")}},[e]),k=l.useCallback(async j=>{var C,y,x,N,S,A;try{i("loading"),d("Starting daemon upgrade…");const M=await e(j,"daemon_upgrade",{});if((C=M==null?void 0:M.result)!=null&&C.alreadyLatest){i("done"),d(`Already on v${((y=M==null?void 0:M.result)==null?void 0:y.version)||"latest"}.`);return}if((x=M==null?void 0:M.result)!=null&&x.upgraded||(N=M==null?void 0:M.result)!=null&&N.success){i("done"),d(`Upgrade to v${((S=M==null?void 0:M.result)==null?void 0:S.version)||"latest"} started. Daemon is restarting…`);return}i("error"),d(((A=M==null?void 0:M.result)==null?void 0:A.error)||"Upgrade failed")}catch(M){i("error"),d(M instanceof Error?M.message:"Upgrade failed")}},[e]),h=l.useCallback(async(j,C,y,x)=>{var A,M,P;const N=Date.now(),S={machineId:j,kind:C,providerType:y,workspaceId:(x==null?void 0:x.workspaceId)||null,workspacePath:(x==null?void 0:x.workspacePath)||null,resumeSessionId:(x==null?void 0:x.resumeSessionId)||null,startedAt:N};try{i("loading"),d(`Launching ${y}…`),u(S);const D={cliType:y};(A=x==null?void 0:x.workspacePath)!=null&&A.trim()?D.dir=x.workspacePath.trim():x!=null&&x.workspaceId?D.workspaceId=x.workspaceId:x!=null&&x.useHome&&(D.useHome=!0),x!=null&&x.resumeSessionId&&(D.resumeSessionId=x.resumeSessionId),(M=x==null?void 0:x.args)!=null&&M.trim()&&(D.cliArgs=x.args.trim().split(/\s+/).filter(Boolean)),(P=x==null?void 0:x.model)!=null&&P.trim()&&(D.initialModel=x.model.trim());const I=await a(j,D),_=(I==null?void 0:I.result)||I,W=(_==null?void 0:_.sessionId)||(_==null?void 0:_.id);if(I!=null&&I.success&&W){u(null),i("done"),d(`${y} launched`),t(xr(W));return}if(I!=null&&I.success){i("loading"),d(`${y} launch requested — waiting for session…`);return}u(null),i("error"),d((I==null?void 0:I.error)||(_==null?void 0:_.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(D){if(m1(D)){i("loading"),d(`${y} launch requested — waiting for session…`);return}u(null),i("error"),d(D instanceof Error?D.message:`Could not launch ${C.toUpperCase()} workspace`)}},[t,e]),v=l.useCallback(async(j,C)=>{try{const y=await e(j,"list_saved_sessions",{providerType:C,kind:"cli",limit:30}),x=(y==null?void 0:y.result)??y;return Array.isArray(x==null?void 0:x.sessions)?x.sessions:[]}catch(y){return console.error("Failed to list saved sessions on mobile:",y),[]}},[e]),w=l.useCallback(async(j,C)=>hl(e,j,C),[e]);l.useEffect(()=>{if(!p)return;const j=nd(p.workspacePath),C=n.find(x=>{var D,I,_,W;if(!x||x.type==="adhdev-daemon"||p1(x.daemonId||x.id)!==p.machineId||(x.transport==="acp"?"acp":x.transport==="pty"?"cli":null)!==p.kind||String(x.agentType||x.type||"")!==p.providerType)return!1;const M=String(x.providerSessionId||"");if(p.resumeSessionId&&M)return M===p.resumeSessionId;if(j){const H=nd(x.workspace||x.runtimeWorkspaceLabel);return H?H===j:!1}return Number(x.lastUpdated||x._lastUpdate||x.timestamp||((W=(_=(I=(D=x.activeChat)==null?void 0:D.messages)==null?void 0:I.at)==null?void 0:_.call(I,-1))==null?void 0:W.timestamp)||0)>=p.startedAt-5e3});if(!C)return;const y=um({entrySessionId:C.sessionId,entryInstanceId:C.instanceId,entryRouteId:C.id,conversations:r});y&&(u(null),i("done"),d(`${p.providerType} launched`),t(xr(y)))},[r,n,t,p]),l.useEffect(()=>{if(!p)return;const j=window.setTimeout(()=>{u(C=>!C||C.startedAt!==p.startedAt?C:(i("error"),d("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(j)},[p]);const b=l.useCallback(async(j,C)=>{var y;if(C.kind==="ide"&&C.providerType){await f(j,C.providerType,{workspacePath:C.workspace||null});return}if((C.kind==="cli"||C.kind==="acp")&&C.providerType){const x=((y=C.workspace)==null?void 0:y.trim())||"";await h(j,C.kind,C.providerType,{workspacePath:x||null,useHome:!x,resumeSessionId:C.providerSessionId||null})}},[f,h]);return{machineAction:{state:o,message:c},resetMachineAction:m,handleLaunchDetectedIde:f,handleAddWorkspace:g,handleMachineUpgrade:k,handleLaunchWorkspaceProvider:h,handleListSavedSessions:v,handleBrowseDirectory:w,handleOpenRecent:b}}function f1({conversations:e,selectedConversation:t,machineBackTarget:n,markConversationRead:r,resetMachineAction:a,setSelectedTabKey:o,setScreen:i,setSelectedMachineId:c,setSection:d,setMachineBackTarget:p}){const u=l.useCallback(w=>{o(w.tabKey),i("chat"),r(w)},[r,i,o]),m=l.useCallback(w=>{const b=e.find(j=>j.routeId===w.routeId&&j.streamSource==="native");b&&(o(b.tabKey),i("chat"),r(b))},[e,r,i,o]),f=l.useCallback(()=>{r(t),i("inbox")},[r,t,i]),g=l.useCallback((w,b="inbox")=>{c(w),a(),d("machines"),p(b),i("machine")},[a,p,i,d,c]),k=l.useCallback(w=>{const b=Ts(w);b&&g(b,"chat")},[g]),h=l.useCallback(()=>{a(),i(n)},[n,a,i]),v=l.useCallback(w=>{d(w),i("inbox")},[i,d]);return{openConversation:u,openNativeConversation:m,backFromConversation:f,openMachine:g,openConversationMachine:k,backFromMachine:h,changeMachineSection:v}}function Dn(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function b1(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function g1({conversations:e,hiddenConversations:t,ides:n,actionLogs:r,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,userName:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,onOpenHistory:k,onOpenRemote:h,onStopCli:v,wsStatus:w,isConnected:b,onShowAllHiddenConversations:j,onHideConversation:C,onOpenMeshGraph:y,onOpenNewSession:x,liveSessionInboxState:N,setCliViewModeOverrides:S}){const[A,M]=l.useState(()=>{var z;return((z=e[0])==null?void 0:z.tabKey)||null}),[P,D]=l.useState(()=>e[0]?"chat":"inbox"),[I,_]=l.useState("chats"),[W,H]=l.useState(null),[L,O]=l.useState("inbox"),E=l.useRef([]),T=wr(),$="1.0.20",R=l.useMemo(()=>e.find(z=>z.tabKey===A)||e[0]||null,[e,A]),G=l.useMemo(()=>R?n.find(z=>z.id===R.routeId):void 0,[n,R]),Q=l.useMemo(()=>!R||dt(R)||!ut(R)?null:En(R),[R]),re=l.useMemo(()=>n.filter(z=>z.type==="adhdev-daemon").sort(Ki),[n]),J=l.useMemo(()=>re.find(z=>z.id===W)||null,[re,W]),X=Wa({sendDaemonCommand:a,activeConv:R||void 0,setActionLogs:o,isStandalone:i}),ue=h1({sendDaemonCommand:a,navigate:T,ides:n,conversations:e}),se=uk(e),B=l.useMemo(()=>e.map(z=>{const ge=P==="chat"&&(R==null?void 0:R.tabKey)===z.tabKey,Ce=_a(z,N,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ge}),Ne=en(z),He=gp(z),Ze=Cp(z,He);return{conversation:z,timestamp:Ne,preview:Ze,unread:Ce.unread,requiresAction:Ce.requiresAction,isWorking:Ce.isWorking,inboxBucket:Ce.inboxBucket}}),[e,N,P,R,se]),{markConversationRead:ie}=u1({conversations:e,machineEntries:re,items:B,selectedConversation:R,selectedTabKey:A,screen:P,liveSessionInboxState:N,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,setSelectedTabKey:M,setScreen:D,setSelectedMachineId:H,setSection:_,setMachineBackTarget:O,resetMachineAction:ue.resetMachineAction}),K=f1({conversations:e,selectedConversation:R,machineBackTarget:L,markConversationRead:ie,resetMachineAction:ue.resetMachineAction,setSelectedTabKey:M,setScreen:D,setSelectedMachineId:H,setSection:_,setMachineBackTarget:O}),{isMuted:le,toggleMute:je}=xm(N,a),{attentionItems:we,unreadItems:ke,workingItems:he,completedItems:U}=l.useMemo(()=>o1(B,E.current),[B]);l.useEffect(()=>{E.current=he.map(z=>z.conversation.tabKey)},[he]);const q=l.useMemo(()=>J?B.filter(z=>Ts(z.conversation)===J.id):[],[B,J]),Z=l.useMemo(()=>l1(J,n),[n,J]),Y=(J==null?void 0:J.version)||null,fe=!!J&&!!Y&&!0&&Y!==$,Me=l.useMemo(()=>(J==null?void 0:J.availableProviders)||[],[J]),de=l.useMemo(()=>Me.filter(z=>Dn(z,"cli")).map(z=>({type:z.type,displayName:z.displayName||z.type,icon:z.icon})),[Me]),F=l.useMemo(()=>Me.filter(z=>Dn(z,"acp")).map(z=>({type:z.type,displayName:z.displayName||z.type,icon:z.icon})),[Me]),me=l.useMemo(()=>c1(re,B,t),[B,re,t]),ce=l.useCallback(async z=>{J&&await ue.handleOpenRecent(J.id,z)},[ue,J]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:P==="chat"&&R?s.jsx(Vj,{selectedConversation:R,isAcp:dt(R),isStandalone:i,selectedIdeEntry:G,actionLogs:r,userName:c,isSendingChat:X.isSendingChat,sendFeedbackMessage:X.sendFeedbackMessage,isFocusingAgent:X.isFocusingAgent,handleModalButton:X.handleModalButton,handleRelaunch:X.handleRelaunch,onBack:K.backFromConversation,onOpenNativeConversation:K.openNativeConversation,onOpenMachine:K.openConversationMachine,onOpenHistory:k,onOpenRemote:h,onOpenMeshGraph:y,onStopCli:v,cliViewMode:Q,onSetCliViewMode:async z=>{await Zp({conversation:R,mode:z,ides:n,sendDaemonCommand:a,setCliViewModeOverrides:S})},handleSendChat:X.handleSendChat,handleForceSendChat:X.handleForceSendChat,handleFocusAgent:X.handleFocusAgent}):P==="machine"&&J?s.jsx(n1,{selectedMachineEntry:J,selectedMachineConversations:q,selectedMachineRecentLaunches:Z,cliProviders:de,acpProviders:F,selectedMachineNeedsUpgrade:fe,appVersion:$,machineAction:ue.machineAction,isStandalone:i,section:I,showBottomNav:L==="inbox",onBack:K.backFromMachine,onSectionChange:K.changeMachineSection,onOpenConversation:K.openConversation,onOpenRecent:ce,onOpenMachineDetails:()=>T(`/machines/${J.id}`),onMachineUpgrade:()=>ue.handleMachineUpgrade(J.id),onLaunchDetectedIde:(z,ge)=>ue.handleLaunchDetectedIde(J.id,z,ge),onAddWorkspace:(z,ge)=>ue.handleAddWorkspace(J.id,z,ge),onBrowseDirectory:z=>ue.handleBrowseDirectory(J.id,z),onLaunchWorkspaceProvider:(z,ge,Ce)=>ue.handleLaunchWorkspaceProvider(J.id,z,ge,Ce),onListSavedSessions:z=>ue.handleListSavedSessions(J.id,z)}):s.jsx(Qj,{section:I,attentionItems:we,unreadItems:ke,workingItems:he,completedItems:U,hiddenConversations:t,machineCards:me,getAvatarText:b1,actionLogs:r,sendDaemonCommand:a,onOpenConversation:K.openConversation,onShowAllHidden:j,onHideConversation:C,onOpenMeshGraph:y,onStopCli:v,onOpenNewSession:x,onOpenMachine:K.openMachine,onOpenSettings:()=>T("/settings"),onSectionChange:_,wsStatus:w,isConnected:b,isStandalone:i,isConversationMuted:le,onToggleMuteConversation:je})})}function Ao(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function x1({conversations:e,numGroups:t,onMoveTab:n,onReceiveTab:r,onOwnTabDrop:a,onClearPreviewOrder:o}){const i=l.useRef(0),[c,d]=l.useState(!1),[p,u]=l.useState(null),m=l.useCallback(()=>{i.current=0,d(!1),u(null)},[]);l.useEffect(()=>(window.addEventListener("dragend",m),window.addEventListener("drop",m),()=>{window.removeEventListener("dragend",m),window.removeEventListener("drop",m)}),[m]);const f=l.useCallback(v=>{v.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,d(!0))},[]),g=l.useCallback(v=>{if(!v.dataTransfer.types.includes("text/tab-key"))return;if(v.preventDefault(),!Ao(t,n)){u("merge");return}const w=v.currentTarget.getBoundingClientRect(),b=v.clientX-w.left,j=w.width/3;b<j?u("split-left"):b>j*2?u("split-right"):u("merge")},[t,n]),k=l.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,d(!1),u(null))},[]),h=l.useCallback(v=>{i.current=0,d(!1);const w=v.dataTransfer.getData("text/tab-key"),b=w?e.some(C=>C.tabKey===w):!1,j=p;if(u(null),o(),!!w){if(v.preventDefault(),j==="split-left"&&Ao(t,n)){n==null||n(w,"split-left");return}if(j==="split-right"&&Ao(t,n)){n==null||n(w,"split-right");return}if(b){a(w);return}r==null||r(w)}},[e,p,t,n,r,a,o]);return{dragOver:c,dropAction:p,resetDragState:m,handleDragEnter:f,handleDragOver:g,handleDragLeave:k,handleDrop:h}}function v1(e,t){const n=new Set(t.map(o=>o.tabKey)),r=e.filter(o=>n.has(o)),a=t.filter(o=>!e.includes(o.tabKey)).map(o=>o.tabKey);return[...r,...a]}function y1({conversations:e,initialActiveTabId:t,initialTabOrder:n,onActiveTabChange:r,onTabOrderChange:a}){const[o,i]=l.useState(t??null),[c,d]=l.useState(n??[]),[p,u]=l.useState(null),m=l.useRef(null),f=l.useRef(null),g=l.useRef(r),k=l.useRef(a);l.useEffect(()=>{g.current=r},[r]),l.useEffect(()=>{k.current=a},[a]),l.useEffect(()=>{t&&t!==o&&i(t)},[t,o]),l.useEffect(()=>{d(N=>{const S=v1(N,e);return S.length===N.length&&S.every((A,M)=>A===N[M])?N:S})},[e]);const h=l.useMemo(()=>{const N=p??c;if(N.length===0)return e;const S=new Map(N.map((A,M)=>[A,M]));return[...e].sort((A,M)=>{const P=S.get(A.tabKey)??999,D=S.get(M.tabKey)??999;return P-D})},[e,p,c]);l.useEffect(()=>{var S,A;if(h.length===0){o!==null&&(i(null),(S=g.current)==null||S.call(g,null));return}if(o&&h.some(M=>M.tabKey===o))return;const N=h[0].tabKey;N!==o&&(i(N),(A=g.current)==null||A.call(g,N))},[h,o]);const v=l.useMemo(()=>h.find(N=>N.tabKey===o),[h,o]),w=l.useCallback(N=>{var S;i(N),(S=g.current)==null||S.call(g,N)},[]),b=l.useCallback((N,S,A)=>{d(M=>{var _;const P=M.filter(W=>W!==N),D=P.indexOf(S);if(D<0)return M;const I=A==="left"?D:D+1;return P.splice(I,0,N),(_=k.current)==null||_.call(k,P),P}),u(null)},[]),j=l.useCallback((N,S,A)=>{const P=(c.length>0?c:e.map(_=>_.tabKey)).filter(_=>_!==N),D=P.indexOf(S);if(D<0)return;const I=A==="left"?D:D+1;P.splice(I,0,N),m.current=P,u(P)},[c,e]),C=l.useCallback(()=>{var S;const N=m.current;N&&(d(N),(S=k.current)==null||S.call(k,N))},[]),y=l.useCallback(()=>{m.current=null,u(null)},[]),x=l.useCallback(N=>{d(S=>{var M;const A=S.filter(P=>P!==N);return A.push(N),(M=k.current)==null||M.call(k,A),A})},[]);return{activeTabId:o,activeConv:v,sortedConversations:h,previewOrderRef:m,draggingTabRef:f,selectTab:w,handleTabReorder:b,updatePreviewOrder:j,commitPreviewOrder:C,clearPreviewOrder:y,moveTabToEnd:x,setDraggingTabKey:N=>{f.current=N}}}function w1({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 xl({conversationsCount:e,isSplitMode:t,isStandalone:n,hasRegisteredMachines:r=!1,suppressGuide:a=!1,onOpenNewSession:o}){const{t:i}=Se("common");if(a)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const c=!n&&!r,d=r&&!!o,p=i(r?"paneGroup.noConversations":n?"paneGroup.waitingForDaemon":"paneGroup.connectYourMachines"),u=i(r?"paneGroup.newSessionDescription":n?"paneGroup.daemonDescription":"paneGroup.installDescription");return e===0&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:p}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:u}),d&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:o,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:i("paneGroup.newSession"),"aria-label":i("paneGroup.newSession"),children:[s.jsx(Wi,{size:14}),s.jsx("span",{children:i("paneGroup.newSession")})]})}),c&&s.jsx(mm,{}),c&&s.jsx("div",{className:"mt-8",children:s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:"📚 Read the documentation →"})})]})]}):s.jsx("div",{className:"text-sm text-text-muted opacity-50",children:t?"Move a tab here to view":"No active agent"})}const vm="adhdev-tab-shortcuts";function ym(){try{return JSON.parse(localStorage.getItem(vm)||"{}")}catch{return{}}}function wm({enabled:e=!0,sortedTabKeys:t,onFocus:n,onSelectTab:r}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>ym()),[c,d]=l.useState(null),p=l.useCallback(m=>{const f=[];return m.metaKey&&f.push(a?"⌘":"Meta"),m.ctrlKey&&f.push("Ctrl"),m.altKey&&f.push(a?"⌥":"Alt"),m.shiftKey&&f.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(m.key)?null:(f.push(m.key.length===1?m.key.toUpperCase():m.key),f.join("+"))},[a]),u=l.useCallback(m=>{i(m);try{localStorage.setItem(vm,JSON.stringify(m))}catch{}},[]);return l.useEffect(()=>{if(!e||!c)return;const m=f=>{if(f.preventDefault(),f.stopPropagation(),f.key==="Escape"){d(null);return}const g=p(f);if(!g)return;const k={...o};for(const[h,v]of Object.entries(k))v===g&&delete k[h];k[c]=g,u(k),d(null)};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[e,c,o,u,p]),l.useEffect(()=>{if(!e)return;const m=f=>{if(!(!f.ctrlKey&&!f.metaKey&&!f.altKey)){for(const[g,k]of Object.entries(o))if(t.includes(g)&&p(f)===k){f.preventDefault(),n(),r(g);return}}};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[e,o,t,n,r,p]),{isMac:a,tabShortcuts:o,shortcutListening:c,setShortcutListening:d,saveShortcuts:u}}const Mo=e=>{e.preventDefault()},k1=l.memo(function({conv:t,isActive:n,isDraggedTab:r,isTaskCompleteUnread:a,shortcut:o,conversationKeys:i,draggingTabRef:c,onFocus:d,onSelectTab:p,onConversationActivated:u,onPreviewReorder:m,onReorderTab:f,onCommitPreviewOrder:g,onClearPreviewOrder:k,onDragStateReset:h,onDragTabKeyChange:v,onReceiveTab:w,onOpenContextMenu:b,longPressTimer:j,isGroupActive:C}){const y=cn(t),x=y.isGenerating?"agent-tab-generating":y.isWaiting?"agent-tab-waiting":"",N=y.isReconnecting,S=Lk(t),A=Rk(t),M=Sp(t),P=l.useCallback(T=>{c.current=t.tabKey,v(t.tabKey),T.dataTransfer.setData("text/tab-key",t.tabKey),T.dataTransfer.effectAllowed="move"},[t.tabKey,c,v]),D=l.useCallback(()=>{c.current=null,v(null),g(),k(),h()},[c,v,g,k,h]),I=l.useCallback(T=>{const $=c.current;if(!(!$||$===t.tabKey)&&T.dataTransfer.types.includes("text/tab-key")){T.preventDefault(),T.stopPropagation();const R=T.currentTarget.getBoundingClientRect(),G=T.clientX<R.left+R.width/2?"left":"right";m($,t.tabKey,G)}},[t.tabKey,c,m]),_=l.useCallback(T=>{T.preventDefault(),T.stopPropagation();const $=T.dataTransfer.getData("text/tab-key");if($&&$!==t.tabKey){const R=T.currentTarget.getBoundingClientRect(),G=T.clientX<R.left+R.width/2?"left":"right";i.includes($)?f($,t.tabKey,G):w&&w($)}k()},[t.tabKey,i,f,w,k]),W=l.useCallback(T=>{T.stopPropagation(),d(),p(t.tabKey),u(t)},[t,u,d,p]),H=l.useCallback(T=>{T.preventDefault(),b(T.clientX,T.clientY,t.tabKey)},[t.tabKey,b]),L=l.useCallback(T=>{const $=T.touches[0];j.current=setTimeout(()=>{b($.clientX,$.clientY,t.tabKey)},600)},[t.tabKey,j,b]),O=l.useCallback(()=>{j.current&&clearTimeout(j.current)},[j]),E=["adhdev-dockview-tab",x,n&&"is-active",C&&"is-group-active",N&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:E,draggable:!0,onDragStart:P,onDragEnd:D,onDragOver:I,onDrop:_,onClick:W,onContextMenu:H,onTouchStart:L,onTouchEnd:O,onTouchMove:O,style:{position:"relative",cursor:"pointer",opacity:r?.4:void 0},children:[M&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-badge pointer-events-none absolute top-0.5 right-0.5 text-text-muted",title:"Mesh chat","aria-label":"Mesh chat",children:s.jsx(ts,{size:11})}),a&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:y.isGenerating?s.jsx("div",{className:"tab-spinner"}):y.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):N?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):y.isConnecting?s.jsx("div",{className:"tab-connecting-spinner"}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),S.length>0&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-role",title:A,"aria-label":A||S.join(" · "),children:S.join(" · ")}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:xt(t),children:xt(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[N?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:Qs(t)}):y.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[Qs(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:Qs(t)}),s.jsx(ya,{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 S1({conversations:e,activeTabId:t,groupIndex:n,unreadTabKeys:r,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:m,onDragStateReset:f,onDragTabKeyChange:g,onReceiveTab:k,onHideTab:h,isGroupActive:v,allowTabShortcuts:w=!0}){const{t:b}=Se("common"),[j,C]=l.useState(null),y=l.useRef(null),x=l.useRef(null),N=l.useMemo(()=>e.map(_=>_.tabKey),[e]);kr("PaneGroupTabBar",{groupIndex:n,activeTabId:t,tabCount:e.length,ctxMenuTab:(j==null?void 0:j.tabKey)||null});const{isMac:S,tabShortcuts:A,shortcutListening:M,setShortcutListening:P,saveShortcuts:D}=wm({enabled:w,sortedTabKeys:e.map(_=>_.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!j)return;const _=W=>{const H=document.querySelector("[data-pane-context-menu]");H&&H.contains(W.target)||C(null)};return window.addEventListener("mousedown",_,!0),()=>window.removeEventListener("mousedown",_,!0)},[j]),l.useEffect(()=>{const _=x.current;if(!_)return;const W=H=>{Math.abs(H.deltaY)<=Math.abs(H.deltaX)||(H.preventDefault(),_.scrollLeft+=H.deltaY)};return _.addEventListener("wheel",W,{passive:!1}),()=>_.removeEventListener("wheel",W)},[]);const I=l.useCallback((_,W,H)=>{C({x:_,y:W,tabKey:H})},[]);return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:s.jsxs("div",{ref:x,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(_=>s.jsx(k1,{conv:_,isActive:t===_.tabKey,isDraggedTab:a.current===_.tabKey,isTaskCompleteUnread:r.has(_.tabKey),shortcut:w?A[_.tabKey]:void 0,conversationKeys:N,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:m,onDragStateReset:f,onDragTabKeyChange:g,onReceiveTab:k,onOpenContextMenu:I,longPressTimer:y,isGroupActive:v},_.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:b("paneGroup.noTabsInGroup")})]})}),j&&s.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:j.x,top:j.y},children:[w&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:Mo,onClick:_=>{_.stopPropagation(),P(j.tabKey),C(null)},children:["⌨ ",A[j.tabKey]?`Change shortcut (${A[j.tabKey]})`:"Set shortcut"]}),A[j.tabKey]&&s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onMouseDown:Mo,onClick:()=>{const _={...A};delete _[j.tabKey],D(_),C(null)},children:"✕ Remove shortcut"})]}),h&&s.jsxs(s.Fragment,{children:[w&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onMouseDown:Mo,onClick:()=>{h(j.tabKey),C(null)},children:"🚫 Hide from Dashboard"})]})]}),w&&M&&s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:()=>P(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:_=>_.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",S?"⌘+1":"Ctrl+1",", ",S?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:b("paneGroup.pressEscToCancel")})]})})]})}function C1({conversations:e,ides:t,clearedTabs:n,actionLogs:r,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,userName:d,groupIndex:p,onFocus:u,isSplitMode:m,numGroups:f,onMoveTab:g,onReceiveTab:k,style:h,onActiveTabChange:v,initialActiveTabId:w,initialTabOrder:b,onTabOrderChange:j,onHideTab:C,isFocused:y,allowTabShortcuts:x=!0,onOpenNewSession:N,liveSessionInboxState:S}){const{sendCommand:A}=vt(),M=l.useRef(null),{activeTabId:P,activeConv:D,sortedConversations:I,draggingTabRef:_,selectTab:W,handleTabReorder:H,updatePreviewOrder:L,commitPreviewOrder:O,clearPreviewOrder:E,moveTabToEnd:T,setDraggingTabKey:$}=y1({conversations:e,initialActiveTabId:w,initialTabOrder:b,onActiveTabChange:v,onTabOrderChange:j}),R=Wa({sendDaemonCommand:a,activeConv:D,setActionLogs:o,isStandalone:i}),{dragOver:G,dropAction:Q,resetDragState:re,handleDragEnter:J,handleDragOver:X,handleDragLeave:ue,handleDrop:se}=x1({conversations:e,numGroups:f,onMoveTab:g,onReceiveTab:k,onOwnTabDrop:T,onClearPreviewOrder:E}),B=D&&!dt(D)&&En(D)==="terminal",ie=l.useMemo(()=>D?t.find(we=>we.id===D.routeId):void 0,[t,D]),K=l.useMemo(()=>D?r.filter(we=>we.routeId===D.tabKey):[],[r,D]),le=l.useMemo(()=>new Set(I.filter(we=>Gb(we,S,{isOpenConversation:we.tabKey===P})).map(we=>we.tabKey)),[P,S,I]);kr("PaneGroup",{groupIndex:p,conversationCount:e.length,activeTabId:P,dragOver:G});const je=l.useCallback(we=>{we.streamSource==="agent-stream"&&we.agentType&&A(we.routeId,rp(),{agentType:we.agentType,...we.sessionId&&{targetSessionId:we.sessionId}}).catch(()=>{})},[A]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:u,style:{...h,outline:G?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(S1,{conversations:I,activeTabId:P,groupIndex:p,numGroups:f,unreadTabKeys:le,draggingTabRef:_,onFocus:u,onSelectTab:W,onConversationActivated:je,onPreviewReorder:L,onReorderTab:H,onCommitPreviewOrder:O,onClearPreviewOrder:E,onDragStateReset:re,onDragTabKeyChange:$,onMoveTab:g,onReceiveTab:k,onHideTab:C,isGroupActive:y??!1,allowTabShortcuts:x}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:J,onDragOver:X,onDragLeave:ue,onDrop:se,children:[G&&s.jsx(w1,{dropAction:Q,canSplit:!!(f<4&&g)}),D?s.jsx(fl,{activeConv:D,clearToken:n[D.tabKey]||0,isCliTerminal:!!B,ideEntry:ie,terminalRef:M,handleModalButton:R.handleModalButton,handleRelaunch:R.handleRelaunch,handleSendChat:R.handleSendChat,handleForceSendChat:R.handleForceSendChat,isSendingChat:R.isSendingChat,sendFeedbackMessage:R.sendFeedbackMessage,handleFocusAgent:R.handleFocusAgent,isFocusingAgent:R.isFocusingAgent,actionLogs:K,userName:d,isInputActive:!m||!!y}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(xl,{conversationsCount:e.length,isSplitMode:m,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:N})})]})]})}function j1({containerRef:e,isSplitMode:t,numGroups:n,groupSizes:r,groupedConvs:a,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:p,isStandalone:u,hasRegisteredMachines:m,userName:f,focusedGroup:g,focusGroup:k,moveTabToGroup:h,splitTabRelative:v,closeGroup:w,handleResizeStart:b,groupActiveTabIds:j,setGroupActiveTab:C,groupTabOrders:y,setGroupTabOrder:x,toggleHiddenTab:N,onOpenNewSession:S,allowTabShortcuts:A=!0,liveSessionInboxState:M}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((P,D)=>{const I=t&&r.length===n?`${r[D]}%`:void 0;return s.jsxs(Rt.Fragment,{children:[t&&D>0&&s.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:_=>b(D-1,_),onDoubleClick:()=>w(D),title:"Drag to resize · Double-click to merge",children:s.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),s.jsx(C1,{style:t?{flexBasis:I??`${100/n}%`,flexGrow:I?0:1,flexShrink:I?0:1}:void 0,conversations:P,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:p,isStandalone:u,hasRegisteredMachines:m,userName:f,groupIndex:D,isFocused:t&&g===D,onFocus:()=>k(D),isSplitMode:t,numGroups:n,onMoveTab:(_,W)=>{W==="left"&&D>0?h(_,D-1):W==="right"&&D<n-1?h(_,D+1):W==="split-left"&&n<4?v(_,D,"left"):W==="split-right"&&n<4&&v(_,D,"right")},onReceiveTab:_=>h(_,D),onActiveTabChange:_=>C(D,_),initialActiveTabId:j[D],initialTabOrder:y[D],onTabOrderChange:_=>x(D,_),onHideTab:N,onOpenNewSession:S,allowTabShortcuts:A,liveSessionInboxState:M})]},D)})})}const km="adhdev-dashboard-action-shortcuts",N1=1200,A1=[["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 M1(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function mt(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 Sm(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:mt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:mt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:mt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:mt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:mt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:mt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:mt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:mt("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:mt("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:mt("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:mt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:mt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:mt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:mt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:mt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:mt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:mt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:mt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:mt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:mt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:mt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:mt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:mt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:mt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:mt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:mt("toggleCliView",e)}]}function Ni(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function Ta(e){const t=Object.fromEntries(Sm(e).map(n=>[n.id,n.defaultShortcut]));try{const n=JSON.parse(localStorage.getItem(km)||"{}"),r={...t,...n};for(const[a,o]of A1)r[a]===o&&(r[a]=t[a]);return r}catch{return t}}function Cm(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function T1({enabled:e=!0,onTrigger:t}){const n=M1(),[r,a]=l.useState(()=>Ta(n)),[o,i]=l.useState(null),[c,d]=l.useState([]),p=l.useRef({parts:[],timer:null}),u=l.useCallback(h=>{const v=[];return h.metaKey&&v.push(n?"⌘":"Meta"),h.ctrlKey&&v.push("Ctrl"),h.altKey&&v.push(n?"⌥":"Alt"),h.shiftKey&&h.key.length!==1&&v.push(n?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(v.push(Cm(h.key)),v.join("+"))},[n]),m=l.useCallback(h=>{a(h);try{localStorage.setItem(km,JSON.stringify(h))}catch{}},[]);l.useEffect(()=>{const h=Ta(n),v=Object.entries(r),w=Object.entries(h);v.length===w.length&&v.every(([b,j])=>h[b]===j)||m(h)},[r,n,m]);const f=l.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),g=l.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},N1))},[]);l.useEffect(()=>{if(!o)return;const h=v=>{if(v.preventDefault(),v.stopPropagation(),v.key==="Escape"){i(null),d([]);return}const w=u(v);if(!w)return;const j=!(v.metaKey||v.ctrlKey||v.altKey)&&/^[A-Z0-9]$/.test(w);if(c.length===0&&j){d([w]);return}const y=[...c,w].slice(0,2).join(" "),x={...r};for(const[N,S]of Object.entries(x))S===y&&delete x[N];x[o]=y,m(x),i(null),d([])};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[r,u,m,o,c]),l.useEffect(()=>{if(!e||o)return;const h=v=>{if(v.defaultPrevented)return;const w=u(v);if(!w)return;const b=v.metaKey||v.ctrlKey||v.altKey;if(Ni(v.target))return;const j=p.current.parts,C=b?[w]:[...j.slice(-1),w].slice(-2),y=C.join(" "),x=C[C.length-1],N=Object.entries(r).filter(([,D])=>!!D),S=N.find(([,D])=>D===y);if(S){v.preventDefault(),f(),t(S[0]);return}if(N.some(([,D])=>D.startsWith(`${y} `))){v.preventDefault(),p.current.parts=C,g();return}const M=N.find(([,D])=>D===x);if(M){v.preventDefault(),f(),t(M[0]);return}if(N.some(([,D])=>D.startsWith(`${x} `))){v.preventDefault(),p.current.parts=[x],g();return}f()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[r,g,e,u,t,f,o]),l.useEffect(()=>()=>f(),[f]);const k=l.useMemo(()=>Sm(n),[n]);return{isMac:n,actionDefinitions:k,actionShortcuts:r,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:d,saveShortcuts:m}}function I1({isTabInPopout:e,isTabFloating:t,tabShortcut:n,actionShortcuts:r}){const a=[];return e?(t&&a.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:r.dockActiveTab}),a.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:r.dockActiveTab})):t?a.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:r.dockActiveTab}):a.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:r.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:r.popoutActiveTab}),a.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:n?`Change shortcut (${n})`:"Set shortcut",shortcut:r.setActiveTabShortcut}),n&&a.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),a.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:r.hideCurrentTab,tone:"muted"}),a}function jm(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function rd({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:n,ides:r}){return!e||n>0?!1:t?!jm(r):!0}function D1({previousVisibleConversationCount:e,visibleConversationCount:t,ides:n}){return t>0||e<=0?!1:jm(n)}const Nm=1e3,P1=4;function ad(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function od(e,t,n){return Math.abs(t.clientX-e.clientX)>n||Math.abs(t.clientY-e.clientY)>n}function L1({detachDelayMs:e=Nm,stillnessThresholdPx:t=P1,onDetach:n,setTimeoutFn:r=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let o=null,i=null,c=null,d=null,p=null,u=!1;const m=()=>{p!=null&&(a(p),p=null)},f=()=>{m(),c=null},g=()=>{m(),o=null,i=null,c=null,d=null,u=!1},k=()=>{!o||!c||!d||u||p!=null||(p=r(()=>{p=null,!(!o||!c||!d||u)&&ad(d,i)&&(od(c,d,t)||(u=!0,n({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},h=w=>{if(!(!o||u)){if(!ad(w,i)){d={clientX:w.clientX,clientY:w.clientY},f();return}(!c||od(c,w,t))&&(m(),c={clientX:w.clientX,clientY:w.clientY}),d={clientX:w.clientX,clientY:w.clientY},k()}},v=w=>{!o||u||(w&&(d={clientX:w.clientX,clientY:w.clientY}),f())};return{startDrag:w=>{m(),o=w.panelId,i=w.selfPanelBounds??null,c=null,d={clientX:w.clientX,clientY:w.clientY},u=!1},markSelfPanel:h,markNonSelfPanel:v,markNoDropTarget:v,markDockTarget:v,endDrag:g,isDragging:()=>o!=null,hasDetached:()=>u,dispose:g}}function R1(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function ia(e){return xt(e)||e.tabKey}function E1(e){return`remote:${e}`}function is(e){return e.startsWith("remote:")}function id(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function To(e){var r;const t=e==null?void 0:e.defaultView;if(!t)return;const n=a=>{if(a)try{a.focus({preventScroll:!0})}catch{try{a.focus()}catch{}}};try{t.focus(),n(e==null?void 0:e.body),n(e==null?void 0:e.documentElement),(r=t.requestAnimationFrame)==null||r.call(t,()=>{try{t.focus(),n(e==null?void 0:e.body)}catch{}})}catch{}}function Io(e,t){e.classList.remove(Qo.className,Xo.className),e.classList.add(t==="light"?Qo.className:Xo.className)}function ld(e){return e?Array.from(new Set(e.groups.map(t=>{var n,r;return(r=(n=t.element)==null?void 0:n.ownerDocument)==null?void 0:r.defaultView}).filter(t=>!!t&&t!==window))):[]}function _1(e,t,n){var i;const r=[t];let a;for(const c of r){let d;for(const p of c){const u=e.addPanel({id:p.tabKey,component:"conversation",title:ia(p),params:{kind:"conversation",tabKey:p.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});d||(d=u.id)}a=d??a}return n??((i=t[0])==null?void 0:i.tabKey)??null}function cd(e,t){const n=new Set(t.map(a=>a.tabKey)),r=new Map;for(const a of t)r.set(a.tabKey,(r.get(a.tabKey)||0)+1);for(const a of[...e.panels])is(a.id)||n.has(a.id)||e.removePanel(a);for(const a of t){const o=e.getPanel(a.tabKey);if(o){(r.get(a.tabKey)||0)>1&&console.warn("[dashboard-conversations] Dockview panel already exists for duplicate tabKey",{tabKey:a.tabKey,daemonId:a.daemonId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,panelId:o.id}),o.update({params:{tabKey:a.tabKey}}),o.title!==ia(a)&&o.api.setTitle(ia(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:ia(a),params:{kind:"conversation",tabKey:a.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function dd(e,t,n){var d,p;const r=n?E1(n):null;for(const u of[...e.panels])is(u.id)&&(!r||u.id!==r)&&e.removePanel(u);if(!n||!r)return;const a=ps(t,n);if(!a&&e.totalPanels===0)return;const o=e.getPanel(r),i=Ap(a);if(o){o.title!==i&&o.api.setTitle(i);return}const c=(a==null?void 0:a.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((p=e.panels.find(u=>!is(u.id)))==null?void 0:p.id);e.addPanel({id:r,component:"remote",title:i,params:{kind:"remote",routeId:n},...c?{position:{referencePanel:c,direction:"right"},inactive:!0}:{}})}function Am({doId:e,targetSessionId:t,connState:n,viewMode:r}){const[a,o]=l.useState(null),[i,c]=l.useState(null);l.useEffect(()=>e?wt.onScreenshot("ide-page",(u,m)=>{if(u!==e)return;const f=new FileReader;f.onload=()=>o(f.result),f.readAsDataURL(m)}):void 0,[e]),l.useEffect(()=>{n!=="connected"&&o(null)},[n]),l.useEffect(()=>{var u;return e?((u=wt.onStatus)==null?void 0:u.call(wt,(m,f)=>{m===e&&f!=null&&f.screenshotUsage&&c(f.screenshotUsage)}))||(()=>{}):void 0},[e]),l.useEffect(()=>{o(null)},[e,t]),l.useEffect(()=>{const p=e?wt.get(e):null;if(!(!p||n!=="connected"))return r!=="chat"&&t?p.startScreenshots(t):p.stopScreenshots(t),()=>{p.stopScreenshots(t)}},[r,n,t,e]);const d=l.useCallback(async(p,u)=>{const m=e?wt.get(e):null;return!m||n!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):m.sendInput(p,u,t)},[e,n,t]);return{connScreenshot:a,screenshotUsage:i,handleRemoteAction:d}}const Mm=l.createContext(null);function qa(){const e=l.useContext(Mm);if(!e)throw new Error("DashboardDockviewContext missing");return e}function $1(e){const[,t]=l.useState(0);l.useEffect(()=>{const n=()=>t(a=>a+1),r=[e.api.onDidActiveGroupChange(n),e.api.onDidTitleChange(n),e.api.onDidGroupChange(n),e.containerApi.onDidActivePanelChange(n)];return()=>{for(const a of r)a.dispose()}},[e.api,e.containerApi])}function H1({params:e}){var d;const t=qa(),n=l.useMemo(()=>ps([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),r=l.useMemo(()=>t.ides.find(p=>p.id===e.routeId),[t.ides,e.routeId]),a=(n==null?void 0:n.daemonId)||((d=n==null?void 0:n.routeId)==null?void 0:d.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:i,handleRemoteAction:c}=Am({doId:a,targetSessionId:n?np(n):(r==null?void 0:r.sessionId)||(r==null?void 0:r.instanceId),connState:(n==null?void 0:n.connectionState)||"new",viewMode:"remote"});return n?s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:s.jsx(ju,{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 F1(){const e=qa();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(xl,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function B1(e){var b,j;$1(e);const t=qa(),n=l.useCallback(C=>{"button"in C&&C.button!==0||e.api.setActive()},[e.api]),r=e.params.kind==="remote"?void 0:t.conversationsByTabKey.get(e.params.tabKey),a=r==null?void 0:r.sessionId,o=l.useCallback(C=>fk(C),[]),i=l.useCallback(()=>hk(a),[a]),c=l.useSyncExternalStore(o,i,i);if(e.params.kind==="remote"){const C=ps([...t.conversationsByTabKey.values()],e.params.routeId),y=((b=e.api.group.activePanel)==null?void 0:b.id)===e.api.id,x=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${y?" is-active":""}${x?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(C==null?void 0:C.tabKey)||"",onMouseDown:n,onTouchStart:n,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:C!=null&&C.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:C.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const d=t.conversationsByTabKey.get(e.params.tabKey);if(!d)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const p=((j=e.api.group.activePanel)==null?void 0:j.id)===e.api.id,u=e.api.isGroupActive,m=_a(d,t.liveSessionInboxState,{isOpenConversation:p}),f=m.isReconnecting,g=m.isConnecting,k=m.isGenerating||c,h=m.isWaiting,v=m.unread,w=t.tabShortcuts[d.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${p?" is-active":""}${u?" is-group-active":""}${f?" is-reconnecting":""}`,title:xt(d),"data-tab-key":e.params.tabKey,onMouseDown:n,onTouchStart:n,onContextMenu:C=>{var y;C.preventDefault(),n(C),t.openTabContextMenu({x:C.clientX,y:C.clientY,tabKey:d.tabKey,sourceDocument:((y=C.target)==null?void 0:y.ownerDocument)??document})},children:[v&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:k?s.jsx("div",{className:"tab-spinner"}):h?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):f?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):g?s.jsx("div",{className:"tab-connecting-spinner"}):d.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:xt(d)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:f?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Qs(d)}):g?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Qs(d)}):s.jsx("span",{children:Qs(d)})})]}),w&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:w,children:w})]})}function qr(e){return e.isActive}function ud(e){return e.isVisible}function O1(e){e.preventDefault()}function W1({params:e,api:t}){var g;const n=qa(),r=l.useRef(null),[a,o]=l.useState(()=>qr(t)),[i,c]=l.useState(()=>ud(t)),d=n.conversationsByTabKey.get(e.tabKey),p=Wa({sendDaemonCommand:n.sendDaemonCommand,activeConv:d,setActionLogs:n.setActionLogs,isStandalone:n.isStandalone});l.useEffect(()=>{o(qr(t)),c(ud(t));const k=[t.onDidActiveChange(h=>o(h.isActive)),t.onDidActiveGroupChange(h=>{if(!qr(t)&&!h.isActive){o(!1);return}o(qr(t))}),t.onDidVisibilityChange(h=>c(h.isVisible))];return()=>{for(const h of k)h.dispose()}},[t]);const u=l.useMemo(()=>d?n.ides.find(k=>k.id===d.routeId):void 0,[n.ides,d]),m=l.useMemo(()=>d?n.actionLogs.filter(k=>k.routeId===d.tabKey):[],[n.actionLogs,d]);if(!d)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(xl,{conversationsCount:0,isSplitMode:!1,isStandalone:n.isStandalone,hasRegisteredMachines:n.hasRegisteredMachines,onOpenNewSession:n.onOpenNewSession,suppressGuide:n.hasDetachedConversationPanels})});const f=!dt(d)&&En(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(fl,{activeConv:d,clearToken:n.clearedTabs[d.tabKey]||0,isCliTerminal:f,ideEntry:u,terminalRef:r,handleModalButton:p.handleModalButton,handleRelaunch:p.handleRelaunch,handleSendChat:p.handleSendChat,handleForceSendChat:p.handleForceSendChat,isSendingChat:p.isSendingChat,handleFocusAgent:p.handleFocusAgent,isFocusingAgent:p.isFocusingAgent,actionLogs:m,userName:n.userName,scrollToBottomRequestNonce:((g=n.scrollToBottomRequest)==null?void 0:g.tabKey)===d.tabKey?n.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:i})})}function U1({visibleConversations:e,clearedTabs:t,ides:n,actionLogs:r,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:d,userName:p,toggleHiddenTab:u,actionShortcuts:m,registerActionHandlers:f,onActiveTabChange:g,onOpenNewSession:k,onRequestScrollToBottom:h,requestedActiveTabKey:v,requestedRemoteIdeId:w,onRequestedActiveTabConsumed:b,scrollToBottomRequest:j,liveSessionInboxState:C,layoutProfile:y}){var lt,ct,Nt;const{theme:x}=Fs(),{sendCommand:N}=vt(),S=l.useRef(null),A=l.useRef(null),M=l.useRef(null),P=l.useRef(!1),D=l.useRef(!1),I=l.useRef(!1),_=l.useRef(null),W=l.useRef([]),[H,L]=l.useState(null),[O,E]=l.useState(0),T=l.useRef(typeof window>"u"?{}:oj(y)),$=l.useMemo(()=>new Map(e.map(V=>[V.tabKey,V])),[e]),R=l.useMemo(()=>{const V=S.current;return V?V.groups.some(ee=>{try{const oe=ee.model.location.type;return oe!=="floating"&&oe!=="popout"?!1:ee.panels.some(pe=>$.has(pe.id))}catch{return!1}}):!1},[$,O,e]),G=l.useCallback(()=>{var V;(V=S.current)==null||V.focus()},[]),Q=l.useCallback((V,ee)=>{h==null||h(V,ee)},[h]),re=l.useCallback(V=>{const ee=document,oe=V.document;for(const De of ee.querySelectorAll('link[rel="stylesheet"]')){const Ue=oe.createElement("link");Ue.rel="stylesheet",Ue.href=De.href,De.crossOrigin&&(Ue.crossOrigin=De.crossOrigin),oe.head.appendChild(Ue)}for(const De of ee.querySelectorAll("style")){const Ue=oe.createElement("style");Ue.textContent=De.textContent,oe.head.appendChild(Ue)}const pe=[];for(const De of ee.styleSheets)try{for(const Ue of De.cssRules)Ue instanceof CSSStyleRule&&(Ue.selectorText===":root"||Ue.selectorText==="html")&&pe.push(Ue.cssText)}catch{}if(pe.length>0){const De=oe.createElement("style");De.textContent=pe.join(`
|
|
71
71
|
`),oe.head.appendChild(De)}const ve=ee.documentElement.getAttribute("data-theme");ve&&oe.documentElement.setAttribute("data-theme",ve),oe.documentElement.style.colorScheme=ve==="light"?"light":"dark",oe.body.className=ee.body.className;const Te=ee.documentElement.getAttribute("style");Te&&oe.documentElement.setAttribute("style",Te);const Ee=oe.getElementById("dv-popout-window");Ee instanceof HTMLElement&&(Ee.classList.add("adhdev-dockview"),Io(Ee,x))},[x]),J=l.useCallback(()=>{var ee;const V=S.current;if(V)for(const oe of V.groups)try{const pe=(ee=oe.element)==null?void 0:ee.ownerDocument;if(!pe||pe===document)continue;const ve=pe.getElementById("dv-popout-window");ve instanceof HTMLElement&&(ve.classList.add("adhdev-dockview"),Io(ve,x));const Te=document.documentElement.getAttribute("data-theme");Te&&pe.documentElement.setAttribute("data-theme",Te),pe.documentElement.style.colorScheme=Te==="light"?"light":"dark",pe.body.className=document.body.className;const Ee=document.documentElement.getAttribute("style");Ee?pe.documentElement.setAttribute("style",Ee):pe.documentElement.removeAttribute("style")}catch{}},[x]),X=l.useCallback(V=>{const ee=S.current;if(!ee)return;const oe=ee.getPanel(V);oe&&ee.addPopoutGroup(oe,{popoutUrl:"/popout.html",onDidOpen:({window:pe})=>{re(pe),ke();const ve=$.get(V);pe.document.title=ve?`${xt(ve)} — ADHDev`:"ADHDev — Popout"}})},[$,re]),ue=l.useCallback(V=>{const ee=S.current,oe=ee==null?void 0:ee.getPanel(V);if(!ee||!oe)return;const pe=ee.groups.filter(ve=>{var Te;try{return((Te=ve.element)==null?void 0:Te.ownerDocument)===document}catch{return!0}});pe.length>0?oe.api.moveTo({group:pe[0],position:"center"}):oe.api.moveTo({position:"center"}),oe.api.setActive()},[]),se=l.useCallback(V=>{var pe;const ee=S.current;if(!ee)return!1;const oe=ee.getPanel(V);if(!oe)return!1;try{return((pe=oe.group.element)==null?void 0:pe.ownerDocument)!==document}catch{return!1}},[]),B=l.useCallback(V=>{se(V)&&ue(V),u(V)},[se,ue,u]),ie=l.useCallback(V=>{const ee=S.current,oe=ee==null?void 0:ee.getPanel(V);!ee||!oe||ee.addFloatingGroup(oe,{width:600,height:500})},[]),K=l.useCallback(V=>{var oe;const ee=(oe=S.current)==null?void 0:oe.getPanel(V);if(!ee)return!1;try{return ee.group.model.location.type==="floating"}catch{return!1}},[]),le=l.useCallback(()=>{var ee,oe;const V=(oe=(ee=S.current)==null?void 0:ee.activePanel)==null?void 0:oe.id;return!V||is(V)?null:$.has(V)?V:null},[$]),je=l.useCallback(V=>{const ee=S.current,oe=ee==null?void 0:ee.getPanel(V);if(!ee||!oe)return;const pe=ee.groups.filter(ve=>{try{return ve.model.location.type==="grid"}catch{return!0}});pe.length>0?oe.api.moveTo({group:pe[0],position:"center"}):oe.api.moveTo({position:"center"}),oe.api.setActive()},[]),we=l.useCallback(()=>{var Te;const V=S.current;if(!V)return;const oe=V.groups.filter(Ee=>{var De;try{return((De=Ee.element)==null?void 0:De.ownerDocument)===document&&Ee.model.location.type==="grid"}catch{return!1}})[0]||null,pe=[...V.panels];for(const Ee of pe){const De=(Te=Ee.group.element)==null?void 0:Te.ownerDocument,Ue=Ee.group.model.location.type;De===document&&Ue==="grid"||(oe&&oe.id!==Ee.group.id?Ee.api.moveTo({group:oe,position:"center"}):Ee.api.moveTo({position:"center"}))}const ve=V.activePanel;ve&&(ve.group.model.openPanel(ve),ve.api.setActive()),To(document)},[]),ke=l.useCallback(()=>{var ee,oe;const V=S.current;if(V)for(const pe of V.groups){const ve=(ee=pe.element)==null?void 0:ee.ownerDocument;if(!ve||ve===document)continue;const Te=ve.getElementById("dv-popout-window");if(!(Te instanceof HTMLElement))continue;let Ee=null,De=ve.title||"ADHDev",Ue="Popout workspace";const Ge=pe.activePanel;if(Ge)if(Ee=Ge.id,is(Ge.id)){const te=((oe=Ge.params)==null?void 0:oe.routeId)||Ge.id.slice(7),xe=ps([...$.values()],te);De=Ap(xe),Ue=xe!=null&&xe.machineName?`Remote view · ${xe.machineName}`:"Remote view"}else{const te=$.get(Ge.id);De=te?xt(te):Ge.title||Ge.id,Ue=te?Qs(te):"Dockview panel"}ve.title=`${De} — ADHDev`;const Xe=Array.from(ve.querySelectorAll("#adhdev-popout-header"));for(const te of Xe)te.remove();const Fe=ve.createElement("div");Fe.id="adhdev-popout-header",ve.body.appendChild(Fe),Fe.setAttribute("style",["position:absolute","top:0","left:0","right:0","height:52px","display:flex","align-items:center","justify-content:space-between","gap:12px","padding:0 14px","box-sizing:border-box","background:var(--surface-secondary)","border-bottom:1px solid var(--border-subtle)","z-index:5","backdrop-filter:blur(14px)"].join(";")),Fe.innerHTML=`
|
|
72
72
|
<div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
|
|
73
73
|
<div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
|
|
@@ -111,11 +111,11 @@ This will disconnect CDP and optionally kill the process.`))try{const $=await n(
|
|
|
111
111
|
|
|
112
112
|
`)}function oI(e,t){return t==="issues"?e.filter(n=>n.level==="warn"||n.level==="error"):t==="info"?e.filter(n=>n.level!=="debug"):e}function iI(e,t){return t==="issues"?e.filter(n=>n.level==="warn"||n.level==="error"):t==="info"?e.filter(n=>n.level!=="debug"):e}function lI({daemonLogs:e,daemonRawText:t,daemonLogKind:n,debugTrace:r,webEvents:a,traceCategory:o,quickFilter:i,searchQuery:c,daemonLoading:d,traceLoading:p,daemonFetchError:u,traceFetchError:m}){const f=HT(r,o),g=OT(e,c),k=GT(t,c),h=qT(f,c),v=zT(a,c),w=oI(g,i),b=i==="all"?k:[],j=iI(h,i),C=i==="issues"?[]:v,y=KT({daemonLogs:g,daemonRawLines:k,trace:h,webEvents:v}),x=tI({daemonLogs:w,daemonRawLines:b,trace:j,webEvents:C}),N=nI(x),S=JT({daemonLoading:d,traceLoading:p,daemonFetchError:u,traceFetchError:m,daemonLogKind:n,daemonLogsCount:g.length,daemonRawLineCount:k.length,traceCount:h.length,webEventCount:v.length});return{filteredDaemonLogs:g,filteredDaemonRawLines:k,filteredTraceEntries:h,filteredWebEvents:v,visibleDaemonLogs:w,visibleDaemonRawLines:b,visibleTraceEntries:j,visibleWebEvents:C,quickFilterCounts:y,diagnosticEvents:x,diagnosticsSummary:N,sourceStates:S}}function cI(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function bh(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function Ti(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 Oo(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 Ml(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function dI({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Ti(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:bh(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:Ml(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 uI({quickFilter:e,quickFilterCounts:t,searchQuery:n,autoRefresh:r,onQuickFilterChange:a,onSearchQueryChange:o,onCopyDiagnostics:i,onCopyVisible:c,onToggleAutoRefresh:d,onRefresh:p,onClear:u}){return s.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"View"}),s.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${t.info})`},{id:"issues",label:`Issues (${t.issues})`},{id:"all",label:`All (${t.all})`}].map(m=>s.jsx("button",{type:"button",onClick:()=>a(m.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===m.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:m.label},m.id))}),s.jsx("input",{value:n,onChange:m=>o(m.target.value),placeholder:"Search diagnostics…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{onClick:i,className:"machine-btn",children:"Copy diagnostics"}),s.jsx("button",{onClick:c,className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:d,className:`machine-btn ${r?"text-green-500 border-green-500/30":""}`,children:r?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:p,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:u,className:"machine-btn",children:"Clear"})]})]})}function pI({logLevel:e,traceCategory:t,onLogLevelChange:n,onTraceCategoryChange:r}){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(a=>s.jsxs("button",{onClick:()=>n(a),className:`machine-btn text-[10px] px-2 py-0.5 ${e===a?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:["Daemon ",a.toUpperCase(),"+"]},a))]}),s.jsx("div",{className:"flex flex-wrap gap-2 items-center",children:_T.map(a=>s.jsx("button",{onClick:()=>r(a.value),className:`machine-btn text-[10px] px-2 py-0.5 ${t===a.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:a.label},a.value))})]})})}function mI({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:n,searchQuery:r,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:i,traceFetchError:c}){var u,m;const d=((u=e.latestIssue)==null?void 0:u.severity)==="error"?"danger":((m=e.latestIssue)==null?void 0:m.severity)==="warn"?"warning":"good",p=i||c?"danger":o?"good":"neutral";return s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${Oo(e.issueCount>0?"warning":"good")}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Diagnostics timeline"}),s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[t," visible event(s) · ",e.issueCount," issue signal(s)"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:r.trim()?`Filtered by “${r.trim()}”`:"Daemon, trace, and browser signals merged by time"})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${Oo(d)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Latest issue"}),e.latestIssue?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[Ml(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:bh(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 ${Oo(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: ",cI(a)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:n.map(f=>s.jsxs("div",{children:[f.label,": ",f.status]},f.id))})]})]})}function hI({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()," · ",Ml(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function fI({streams:e,sectionsOpen:t,setSectionsOpen:n,diagnosticEvents:r,visibleDaemonLogs:a,visibleDaemonRawLines:o,visibleTraceEntries:i,visibleWebEvents:c,quickFilter:d,searchQuery:p}){return s.jsxs("div",{className:"grid gap-3",children:[s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>n(u=>({...u,timeline:!u.timeline})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Unified timeline"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[r.length," visible diagnostic event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.timeline?"Hide":"Show"})]}),t.timeline&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[180px] max-h-[440px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[(e.daemonLoading||e.traceLoading)&&r.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&r.length===0&&s.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&s.jsxs("div",{children:["Daemon logs: ",e.daemonFetchError]}),e.traceFetchError&&s.jsxs("div",{children:["Daemon trace: ",e.traceFetchError]})]}),!e.daemonLoading&&!e.traceLoading&&r.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),r.map(u=>s.jsx(dI,{event:u},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>n(u=>({...u,daemon:!u.daemon})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · daemon logs"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:e.daemonLogKind==="text"?`${o.length} visible raw line(s) from file fallback`:`${a.length} visible structured line(s)`})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.daemon?"Hide":"Show"})]}),t.daemon&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.daemonLoading&&a.length===0&&o.length===0&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),e.daemonLogKind==="text"&&o.length===0&&e.daemonRawText&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:d==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),e.daemonLogKind==="structured"&&a.length===0&&e.daemonLogs.length>0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),e.daemonLogKind==="text"&&o.map((u,m)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:u},`raw-${m}`)),e.daemonLogKind!=="text"&&a.map((u,m)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${Ti(u.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(u.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:u.level==="error"?"ERR":u.level==="warn"?"WRN":u.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:u.message})]},`log-${m}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>n(u=>({...u,trace:!u.trace})),children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Raw source · daemon trace",e.traceCategory==="session_host"?" · session_host only":""]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[i.length," visible trace event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.trace?"Hide":"Show"})]}),t.trace&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.traceLoading&&i.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&i.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&i.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:p.trim()?"No trace entries match the current search.":e.traceCategory==="session_host"?"No session_host trace entries yet. This filter uses get_debug_trace(category=session_host).":"No trace entries yet. Run daemon with --dev or --trace."}),i.map(u=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Ti(u.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),s.jsx("span",{children:u.level.toUpperCase()}),s.jsxs("span",{children:[u.category,".",u.stage]}),u.interactionId&&s.jsxs("span",{children:["ix=",u.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Ln(u.payload,360)||"No payload"})]},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>n(u=>({...u,web:!u.web})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · browser debug events"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[c.length," visible browser event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.web?"Hide":"Show"})]}),t.web&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[c.length===0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:p.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),c.map(u=>s.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),s.jsx("span",{children:u.kind}),u.topic&&s.jsxs("span",{children:["topic=",u.topic]}),u.interactionId&&s.jsxs("span",{children:["ix=",u.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Ln(u.payload,360)||"No payload"})]},u.id))]})]})]})}function bI({machineId:e,sendDaemonCommand:t}){const n=YT({machineId:e,sendDaemonCommand:t}),[r,a]=l.useState("info"),[o,i]=l.useState(""),[c,d]=l.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),p=l.useRef(null),u=l.useRef(!1),m=l.useMemo(()=>lI({daemonLogs:n.daemonLogs,daemonRawText:n.daemonRawText,daemonLogKind:n.daemonLogKind,debugTrace:n.debugTrace,webEvents:n.webEvents,traceCategory:n.traceCategory,quickFilter:r,searchQuery:o,daemonLoading:n.daemonLoading,traceLoading:n.traceLoading,daemonFetchError:n.daemonFetchError,traceFetchError:n.traceFetchError}),[r,o,n.daemonFetchError,n.daemonLoading,n.daemonLogKind,n.daemonLogs,n.daemonRawText,n.debugTrace,n.traceCategory,n.traceFetchError,n.traceLoading,n.webEvents]);l.useEffect(()=>{if(n.autoRefresh&&m.diagnosticEvents.length>0){const k=u.current?"smooth":"instant";setTimeout(()=>{var h;(h=p.current)==null||h.scrollIntoView({behavior:k}),u.current=!0},50)}},[m.diagnosticEvents.length,n.autoRefresh]);const f=l.useCallback(async()=>{var h;const k=VT({daemonLogs:m.visibleDaemonLogs,daemonRawLines:m.visibleDaemonRawLines,trace:m.visibleTraceEntries,webEvents:m.visibleWebEvents});if(!k.trim()){pt.showToast("No visible logs to copy.","info");return}try{await((h=navigator.clipboard)==null?void 0:h.writeText(k)),pt.showToast("Copied visible logs to clipboard.","success")}catch(v){pt.showToast(v instanceof Error?v.message:"Could not copy visible logs","warning")}},[m.visibleDaemonLogs,m.visibleDaemonRawLines,m.visibleTraceEntries,m.visibleWebEvents]),g=l.useCallback(async()=>{var h;const k=aI({events:m.diagnosticEvents,summary:m.diagnosticsSummary,sources:m.sourceStates});try{await((h=navigator.clipboard)==null?void 0:h.writeText(k)),pt.showToast("Copied diagnostic bundle to clipboard.","success")}catch(v){pt.showToast(v instanceof Error?v.message:"Could not copy diagnostic bundle","warning")}},[m.diagnosticEvents,m.diagnosticsSummary,m.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(uI,{quickFilter:r,quickFilterCounts:m.quickFilterCounts,searchQuery:o,autoRefresh:n.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:i,onCopyDiagnostics:()=>{g()},onCopyVisible:()=>{f()},onToggleAutoRefresh:()=>n.setAutoRefresh(k=>!k),onRefresh:n.refresh,onClear:n.clear}),s.jsx(pI,{logLevel:n.logLevel,traceCategory:n.traceCategory,onLogLevelChange:n.setLogLevel,onTraceCategoryChange:n.setTraceCategory}),s.jsx(mI,{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(hI,{patterns:m.diagnosticsSummary.repeatedPatterns}),s.jsx(fI,{streams:n,sectionsOpen:c,setSectionsOpen:d,diagnosticEvents:m.diagnosticEvents,visibleDaemonLogs:m.visibleDaemonLogs,visibleDaemonRawLines:m.visibleDaemonRawLines,visibleTraceEntries:m.visibleTraceEntries,visibleWebEvents:m.visibleWebEvents,quickFilter:r,searchQuery:o}),s.jsx("div",{ref:p})]})}function gI(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 gh(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 xI(e){var a;const t=[],n=[],r=[];for(const o of e||[]){const i=String((o==null?void 0:o.lifecycle)||"").trim(),c=gh((o==null?void 0:o.meta)||void 0),d=((a=o==null?void 0:o.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(i)?t.push(o):(i==="stopped"||i==="failed")&&(d||c)?n.push(o):r.push(o)}return{liveRuntimes:t,recoverySnapshots:n,inactiveRecords:r}}function vI(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Wo(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 Uo(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Go(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Fd(e){if(!e)return"unknown";const t=Date.now()-e,n=Math.max(0,Math.round(t/1e3));if(n<60)return`${n}s ago`;const r=Math.round(n/60);if(r<60)return`${r}m ago`;const a=Math.round(r/60);return a<48?`${a}h ago`:`${Math.round(a/24)}d ago`}function yI(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function wI(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 kI(e){var n;const t=new Map;for(const r of e){if(!["starting","running","stopping","interrupted"].includes(r.lifecycle))continue;const a=typeof((n=r.meta)==null?void 0:n.providerSessionId)=="string"?String(r.meta.providerSessionId).trim():"";if(!a)continue;const o=`${r.providerType}::${r.workspace}::${a}`;t.set(o,(t.get(o)||0)+1)}return Array.from(t.values()).filter(r=>r>1).length}function SI({machineId:e,cliSessions:t,sendDaemonCommand:n}){const[r,a]=l.useState(""),[o,i]=l.useState(null),[c,d]=l.useState(!1),p=MC(e,{enabled:!!e,includeSessions:!0,limit:vc,intervalMs:$0}),u=p.diagnostics,m=p.loading,f=p.applyDiagnostics,g=l.useMemo(()=>gI({diagnostics:u,loading:m,refreshing:c,error:r}),[u,m,c,r]),k=l.useMemo(()=>new Map(t.map(P=>[P.sessionId||P.id,P])),[t]),h=l.useCallback(async()=>{if(e){d(!0);try{const P=await n(e,"session_host_get_diagnostics",{includeSessions:!0,limit:vc}),D=Uo(P);if(!(D!=null&&D.success))throw new Error((D==null?void 0:D.error)||"Could not load hosted runtime diagnostics");f(D.diagnostics||D.result||null),a("")}catch(P){const D=P instanceof Error?P.message:"Could not load hosted runtime diagnostics";a(D)}finally{d(!1)}}},[f,e,n]);l.useEffect(()=>{!e||u||m||c||h()},[u,m,e,h,c]);const v=l.useCallback(async(P,D)=>{const I=`${P}:${D.sessionId}`;if(!(P==="session_host_stop_session"&&!window.confirm(`Stop ${D.displayName}?
|
|
113
113
|
This will terminate the hosted runtime.`))){i(I);try{const _=await n(e,P,{sessionId:D.sessionId}),W=Uo(_);if(!(W!=null&&W.success))throw new Error((W==null?void 0:W.error)||"Session host action failed");const H=P==="session_host_resume_session"?"resumed":P==="session_host_restart_session"?"restarted":"stopped";pt.showToast(`Session host ${H}: ${D.displayName}`,"success"),await h()}catch(_){const W=_ instanceof Error?_.message:"Session host action failed";pt.showToast(W,"warning"),a(W)}finally{i(_=>_===I?null:_)}}},[e,h,n]),w=l.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
|
|
114
|
-
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){i("session_host_prune_duplicate_sessions");try{const D=await n(e,"session_host_prune_duplicate_sessions",{}),I=Uo(D);if(!(I!=null&&I.success))throw new Error((I==null?void 0:I.error)||"Duplicate prune failed");const _=I.result||{},W=Array.isArray(_.prunedSessionIds)?_.prunedSessionIds.length:0,H=typeof _.duplicateGroupCount=="number"?_.duplicateGroupCount:0;pt.showToast(`Pruned ${W} duplicate runtime(s) across ${H} group(s)`,"success"),await h()}catch(D){const I=D instanceof Error?D.message:"Duplicate prune failed";pt.showToast(I,"warning"),a(I)}finally{i(D=>D==="session_host_prune_duplicate_sessions"?null:D)}}},[e,h,n]),b=l.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((P,D)=>(D.lastActivityAt||0)-(P.lastActivityAt||0)),[u==null?void 0:u.sessions]),j=l.useMemo(()=>u!=null&&u.liveRuntimes||u!=null&&u.recoverySnapshots||u!=null&&u.inactiveRecords?{liveRuntimes:(u==null?void 0:u.liveRuntimes)||[],recoverySnapshots:(u==null?void 0:u.recoverySnapshots)||[],inactiveRecords:(u==null?void 0:u.inactiveRecords)||[]}:xI(b),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,b]),C=j.liveRuntimes,y=j.recoverySnapshots,x=j.inactiveRecords,N=l.useMemo(()=>kI(C),[C]),S=l.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),A=l.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(P=>P.level==="warn"||P.level==="error")||null,[u==null?void 0:u.recentLogs]),M=(P,D)=>{var $;const I=o===`session_host_resume_session:${P.sessionId}`,_=o===`session_host_restart_session:${P.sessionId}`,W=o===`session_host_stop_session:${P.sessionId}`,H=gh(P.meta),L=k.get(P.sessionId),O=P.attachedClients.length===1?"1 client":`${P.attachedClients.length} clients`,E=D==="recovery"?"Recover":"Resume",T=vI(D);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:P.displayName||(L==null?void 0:L.cliName)||P.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${wI(P.lifecycle)}`,children:P.lifecycle}),H&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:H})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:P.workspaceLabel||(L==null?void 0:L.runtimeWorkspaceLabel)||P.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:P.runtimeKey}),P.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",P.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:(($=P.writeOwner)==null?void 0:$.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:yI(P.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(cu,{size:11})," ",O]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",Fd(P.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",T]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[D==="recovery"&&(P.lifecycle==="interrupted"||P.lifecycle==="failed"||P.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{v("session_host_resume_session",P)},children:I?`${E}ing…`:E}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{v("session_host_restart_session",P)},children:_?"Restarting…":"Restart"}),D==="live"&&(P.lifecycle==="running"||P.lifecycle==="starting"||P.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!o,onClick:()=>{v("session_host_stop_session",P)},children:W?"Stopping…":"Stop"})]})]})},P.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(_s,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:cS()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[N>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{w()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${N})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${g.toneClass}`,children:g.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{h()},disabled:m||c,children:[s.jsx(Ra,{size:13}),m||c?"Refreshing…":"Refresh"]})]})]}),r&&!u&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(nn,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:r})]})]})}),u&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:y.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:Fd(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Go(u.hostStartedAt)})]})]}),A&&s.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[s.jsx(nn,{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:[Go(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(Oi,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Wo("live")}),C.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):s.jsx("div",{className:"space-y-2",children:C.map(P=>M(P,"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(_s,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Wo("recovery")}),y.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):s.jsx("div",{className:"space-y-2",children:y.map(P=>M(P,"recovery"))})]}),x.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Wo("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:x.map(P=>M(P,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),S.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:S.map(P=>{var I;const D=b.find(_=>_.sessionId===P.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(D==null?void 0:D.displayName)||((I=k.get(P.sessionId))==null?void 0:I.cliName)||P.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[P.action,P.lifecycle?` · ${P.lifecycle}`:"",P.detail?` · ${P.detail}`:"",P.error?` · ${P.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${P.success===!1?"text-red-300":"text-text-secondary"}`,children:Go(P.timestamp)})]},`${P.sessionId}:${P.timestamp}:${P.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:u.endpoint||"unknown"}),r?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",r]}):null]})]})]})}function CI({machine:e,launchPick:t,actions:n}){const{t:r}=Se("common"),{runLaunchCliCore:a,setLaunchPick:o}=n;return s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",children:s.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",children:[s.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),s.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),s.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?s.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(i=>s.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{o(null),a({cliType:t.cliType,workspaceId:i.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{o(null),a({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:r("newSession.defaultWorkspace")}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{o(null),a({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:r("newSession.homeDirectory")}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>o(null),children:"Cancel"})]})]})})}function jI(e,t){const n=om(e),r=xn(e,t),a=ol(e,r),o=lr(e,r),i=n==="preview"?"Update to preview":"Update daemon";return a?{visible:!0,showButton:!0,title:o?"Daemon update required":"Version mismatch detected",description:o?"This machine is on an incompatible daemon version. Update it before starting more sessions.":n==="preview"?"This machine can be upgraded to the current preview daemon without opening a remote shell.":"This machine is running a different daemon version than the current app. Update it before starting more sessions.",buttonLabel:i,targetVersion:r,channel:n,required:o,tone:"warn"}:n==="preview"?{visible:!0,showButton:!1,title:r?"Preview daemon is up to date":"Preview update status unknown",description:r?"This machine is already on the current preview daemon target.":"The app is connected to preview, but the server did not report a preview target version yet.",buttonLabel:i,targetVersion:r,channel:n,required:!1,tone:r?"good":"info"}:{visible:!1,showButton:!1,title:"",description:"",buttonLabel:i,targetVersion:r,channel:n,required:!1,tone:"info"}}function qo({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 zo({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 NI({machineEntry:e,providers:t,recentLaunches:n,currentConversations:r,onUpgradeDaemon:a,onOpenRecent:o,onOpenConversation:i}){const{t:c}=Se("common"),d=r.slice(0,6),p=n.slice(0,4),m=jI(e,"1.0.18");return s.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(qo,{icon:s.jsx(ln,{size:13}),children:c("machine.commandCenter.currentChats")}),s.jsx(zo,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(f=>{const g=Ci(f);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>i(f),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:xt(f)}),g>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Ea(g)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:Mn(f)})]},f.tabKey)})})})]}),p.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(qo,{icon:s.jsx(hu,{size:13}),children:c("machine.commandCenter.recentLaunches")}),s.jsx(zo,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:p.map(f=>{const{metaText:g,updatedLabel:k}=gm(f);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>o(f),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:f.label}),k&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:k})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:g})]},f.id)})})})]}),m.visible&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(qo,{icon:s.jsx(nn,{size:13}),children:c("machine.commandCenter.daemonUpdate")}),s.jsx(zo,{className:m.tone==="good"?"border-emerald-500/20 bg-emerald-500/5":m.tone==="info"?"border-sky-500/20 bg-sky-500/5":"border-amber-500/20 bg-amber-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:m.title}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[m.description,m.targetVersion&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",m.targetVersion,m.channel?` (${m.channel})`:""]})]}),m.showButton?s.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:a,children:[s.jsx(Ra,{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 AI({machineId:e,machine:t,ideSessions:n,cliSessions:r,acpSessions:a,actions:o,sendDaemonCommand:i}){const{workspaceBusy:c,handleWorkspaceAdd:d,handleWorkspaceRemove:p,handleWorkspaceSetDefault:u}=o,{t:m}=Se("common"),[f,g]=l.useState(!1),[k,h]=l.useState(""),[v,w]=l.useState([]),[b,j]=l.useState(!1),[C,y]=l.useState(""),x=l.useCallback(async S=>{j(!0),y("");try{const A=await hl(i,e,S);h(A.path),w(A.directories)}catch(A){y(A instanceof Error?A.message:"Could not load folder")}finally{j(!1)}},[e,i]),N=l.useCallback(()=>{g(!0);const S=[...n.map(M=>M.workspace),...r.map(M=>M.workspace),...a.map(M=>M.workspace)],A=ml(t.platform,pl(S,t.defaultWorkspacePath,(t.workspaces||[]).map(M=>M.path)));x(A)},[a,r,n,x,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(Nn,{size:14})," Workspaces"]}),s.jsx("button",{type:"button",className:"btn bg-bg-glass hover:bg-bg-glass-hover text-text-muted hover:text-text-primary px-3 py-1 rounded transition-colors text-xs",disabled:c,onClick:N,children:"+ Add workspace"})]}),(t.workspaces||[]).length===0?s.jsxs("div",{className:"text-[11px] text-text-muted py-4 text-center",children:["No saved workspaces yet. Click ",s.jsx("span",{className:"text-text-secondary",children:"+ Add workspace"})," to pick a folder."]}):s.jsx("ul",{className:"space-y-1.5 max-h-72 overflow-y-auto",children:(t.workspaces||[]).map(S=>{const A=S.id===t.defaultWorkspaceId;return s.jsxs("li",{className:`flex items-start gap-2 text-[11px] rounded-lg border px-2.5 py-2 transition-colors ${A?"border-yellow-500/30 bg-yellow-500/[0.05]":"border-border-subtle bg-bg-primary"}`,children:[s.jsx("button",{type:"button",title:A?"Default workspace — click to unset":"Set as default workspace",disabled:c,onClick:()=>void u(A?null:S.id),className:`text-base leading-none shrink-0 transition-colors ${A?"text-yellow-400 hover:text-yellow-300":"text-text-muted/40 hover:text-yellow-400"}`,children:"★"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"font-medium text-text-primary truncate",children:_u(S.path,S.label)}),s.jsx("div",{className:"font-mono text-text-muted truncate text-[10px]",title:S.path,children:S.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void p(S.id),children:m("machine.managedWorkspaces.remove")})]},S.id)})})]}),f&&s.jsx(bl,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:k,directories:v,busy:b,error:C,confirmLabel:"Add workspace",onClose:()=>g(!1),onNavigate:S=>{x(S)},onConfirm:S=>{(async()=>{if(!S)return;await d(S)&&g(!1)})()}})]})}function MI({machine:e,machineId:t,ideSessions:n,cliSessions:r,acpSessions:a,actions:o,sendDaemonCommand:i}){return s.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[s.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-border-subtle mb-4",children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspaces"}),s.jsx("div",{className:"text-sm text-text-secondary",children:'Save folders as workspaces on this machine. Use the dashboard "+" button to launch a session.'})]}),i&&s.jsx(AI,{machineId:t,machine:e,ideSessions:n,cliSessions:r,acpSessions:a,actions:o,sendDaemonCommand:i})]})}function TI({onNicknameSynced:e}={}){var we,ke,he,U,q,Z,Y,fe,Me,de;const{t}=Se("common"),{id:n}=Zh(),r=wr(),a=Ri(),{sendCommand:o}=vt(),i=_n(),c=Yp(),d=wp(),p=d.ides||[],u=d.initialLoaded??!0,m=p.find(F=>F.id===n&&F.type==="adhdev-daemon"),f=p.some(F=>F.type==="adhdev-daemon"),g=n?(we=d.connectionRetryStatuses)==null?void 0:we[n]:void 0,k=!!(g!=null&&g.blocked),[h,v]=l.useState("workspace"),[w,b]=l.useState(null);l.useCallback((F,me)=>{b({daemonId:F,workspace:me})},[]);const[,j]=l.useState("ide"),C=l.useRef(null),[y,x]=l.useState(null),N=l.useRef("__home__"),[S,A]=l.useState("__home__"),[M,P]=l.useState(!1),D=l.useRef(null);l.useEffect(()=>{!n||!m||!(!m.workspaces||!m.availableProviders||!m.detectedIdes||!m.recentLaunches)||i(n,{minFreshMs:3e4}).catch(()=>{})},[i,m,n]),l.useEffect(()=>{if(!n||!m||h!=="overview")return;const F=m.machine;(typeof(F==null?void 0:F.cpus)!="number"||typeof(F==null?void 0:F.totalMem)!="number"||typeof(F==null?void 0:F.arch)!="string"||typeof(F==null?void 0:F.release)!="string")&&c(n,{minFreshMs:3e4}).catch(()=>{})},[h,c,m,n]),AC(n&&h==="overview"?[n]:[],{enabled:h==="overview",intervalMs:R0});const I=()=>{if(f){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},_=kT({machineId:n,registeredMachineId:(m==null?void 0:m.machineId)||null,sendDaemonCommand:o,onNicknameSynced:e,logsEndRef:D});l.useEffect(()=>pt.onToast(me=>{d.setToasts(z=>{if(z.some(Ne=>Ne.message===me.message&&me.timestamp-Ne.timestamp<3e3))return z;const Ce={id:me.id,message:me.message,type:me.type,timestamp:me.timestamp,targetKey:me.targetKey,actions:me.actions};return[...z.slice(-4),Ce]});const ce=me.duration||5e3;setTimeout(()=>d.setToasts(z=>z.filter(ge=>ge.id!==me.id)),ce)}),[d]);const W=(m==null?void 0:m.availableProviders)||[],H={};for(const F of W)H[F.type]=F.icon;const L=m?{id:m.id,hostname:$u(m,{fallbackId:m.id}),platform:((ke=m.machine)==null?void 0:ke.platform)||"unknown",arch:((he=m.machine)==null?void 0:he.arch)||"",cpus:((U=m.machine)==null?void 0:U.cpus)||0,totalMem:((q=m.machine)==null?void 0:q.totalMem)||0,freeMem:(Z=m.machine)==null?void 0:Z.freeMem,availableMem:(Y=m.machine)==null?void 0:Y.availableMem,loadavg:(fe=m.machine)==null?void 0:fe.loadavg,uptime:(Me=m.machine)==null?void 0:Me.uptime,release:((de=m.machine)==null?void 0:de.release)||"",cdpConnected:!!m.cdpConnected,machineNickname:m.machineNickname||null,p2p:m.p2p?{screenshotActive:!1,...m.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:m.detectedIdes||[],workspaces:m.workspaces||[],defaultWorkspaceId:m.defaultWorkspaceId??m.activeWorkspaceId??null,defaultWorkspacePath:m.defaultWorkspacePath??m.activeWorkspacePath??null}:null,O=p.filter(F=>F.daemonId===n&&F.type!=="adhdev-daemon").filter(F=>!fr(F)&&!kn(F)).map(F=>({id:F.id,sessionId:F.sessionId,type:F.type,version:F.version||"",instanceId:F.instanceId||"",status:F.status,workspace:F.workspace||null,terminals:F.terminals||0,aiAgents:Yy(F.aiAgents||(F.agents||[]).map(me=>({id:me.name,name:me.name,status:me.status,version:me.version}))),activeChat:F.activeChat||null,chats:F.chats||[],childSessions:F.childSessions||[],cdpConnected:F.cdpConnected||!1,daemonId:n,lastMessageAt:F.lastMessageAt})),E=p.filter(F=>F.daemonId===n&&fr(F)).map(F=>({id:F.id,sessionId:F.sessionId,type:F.type,cliName:F.cliName||F.type,status:F.status,workspace:F.workspace||"",activeChat:F.activeChat||null,providerSessionId:F.providerSessionId,mode:F.mode,runtimeKey:F.runtimeKey,runtimeDisplayName:F.runtimeDisplayName,runtimeWorkspaceLabel:F.runtimeWorkspaceLabel,runtimeWriteOwner:F.runtimeWriteOwner||null,runtimeAttachedClients:F.runtimeAttachedClients||[],daemonId:n,lastMessageAt:F.lastMessageAt})),T=p.filter(F=>F.daemonId===n&&kn(F)).map(F=>({id:F.id,sessionId:F.sessionId,type:F.type,acpName:F.cliName||F.type,status:F.status,workspace:F.workspace||"",activeChat:F.activeChat||null,providerSessionId:F.providerSessionId,daemonId:n,lastMessageAt:F.lastMessageAt})),$=m?ss(m,{fallbackId:n}):"",R="workspace",G=a.state,Q=G==null?void 0:G.initialMachineTab,re=G==null?void 0:G.initialWorkspaceCategory;G==null||G.initialWorkspaceId,G==null||G.initialWorkspacePath;const J=Q==="ides"||Q==="clis"||Q==="acps"?"workspace":Q||R,X=Q==="ides"?"ide":Q==="clis"?"cli":Q==="acps"?"acp":re,ue=[...O.map(F=>{var me;return{id:`ide:${F.type}:${F.workspace||""}`,label:((me=F.activeChat)==null?void 0:me.title)||F.type,kind:"ide",providerType:F.type,subtitle:F.workspace||void 0,workspace:F.workspace||void 0,lastLaunchedAt:F.lastMessageAt||0}}),...E.map(F=>{var me;return{id:`cli:${F.type}:${F.workspace||""}`,label:((me=F.activeChat)==null?void 0:me.title)||F.cliName,kind:"cli",providerType:F.type,providerSessionId:F.providerSessionId,subtitle:F.workspace||void 0,workspace:F.workspace||void 0,lastLaunchedAt:F.lastMessageAt||0}}),...T.map(F=>{var me;return{id:`acp:${F.type}:${F.workspace||""}`,label:((me=F.activeChat)==null?void 0:me.title)||F.acpName,kind:"acp",providerType:F.type,providerSessionId:F.providerSessionId,subtitle:rn(F.summaryMetadata)||F.workspace||void 0,workspace:F.workspace||void 0,lastLaunchedAt:F.lastMessageAt||0}})].sort((F,me)=>(me.lastLaunchedAt||0)-(F.lastLaunchedAt||0)),se=((m==null?void 0:m.recentLaunches)||[]).length>0?((m==null?void 0:m.recentLaunches)||[]).map(F=>({id:F.id,label:F.title||F.providerName||F.providerType,kind:F.kind,providerType:F.providerType,providerSessionId:F.providerSessionId,subtitle:rn(F.summaryMetadata)||F.workspace||void 0,workspace:F.workspace,summaryMetadata:F.summaryMetadata,lastLaunchedAt:F.lastLaunchedAt})):ue,B=l.useMemo(()=>{var me;const F=((me=d.connectionStates)==null?void 0:me[n||""])||void 0;return p.filter(ce=>ce.daemonId===n&&ce.type!=="adhdev-daemon").flatMap(ce=>al(ce,{connectionStates:n&&F?{[n]:F}:void 0,defaultConnectionState:F})).filter(ce=>!(ce.transport==="pty"&&ce.mode==="terminal")).sort((ce,z)=>Ci(z)-Ci(ce))},[p,d.connectionStates,n]),ie=l.useCallback(F=>{const me=dm(F);me&&r(xr(me))},[r]),K=l.useCallback(()=>{C.current&&(P(!0),C.current().finally(()=>{C.current=null,P(!1),x(null)}))},[]),le=l.useCallback(F=>{if(!L)return;const{options:me,selectedKey:ce}=bm({machine:L,currentWorkspacePath:F.workspace,homeLabel:t("newSession.homeDirectory"),homeDescription:t("newSession.launchWithoutWorkspace")}),z=async()=>{j(F.kind),v("workspace")};C.current=async()=>{const ge=me.find(He=>He.key===N.current),Ce=(ge==null?void 0:ge.workspacePath)??null,Ne=(ge==null?void 0:ge.workspaceId)??null;if(F.kind==="ide"&&F.providerType){await _.handleLaunchIde(F.providerType,Ce?{workspace:Ce}:void 0);return}if((F.kind==="cli"||F.kind==="acp")&&F.providerType){await _.runLaunchCliCore({cliType:F.providerType,dir:Ne?void 0:Ce||"",workspaceId:Ne||void 0,model:F.kind==="acp"&&Fu(F.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:F.providerSessionId});return}await z()},N.current=ce,A(ce),x({title:F.kind==="ide"?wa(t,"restart-ide",F.label):F.providerSessionId?Pp(t,F.label):wa(t,"start-fresh",F.label),description:F.kind==="ide"?ka(t,"restart-ide"):F.providerSessionId?Lp(t):ka(t,"start-fresh"),confirmLabel:F.kind==="ide"?Sa(t,"restart-ide"):F.providerSessionId?gi(t,!0):Sa(t,"start-fresh"),busyLabel:F.kind==="ide"?Ca(t,"restart-ide"):F.providerSessionId?Dp(t,!0):Ca(t,"start-fresh"),workspaceOptions:me,details:[{label:"Mode",value:F.kind.toUpperCase()},...F.providerType?[{label:"Provider",value:F.providerType}]:[]]})},[_,L]);if(l.useEffect(()=>{v(J)},[R,J,n]),l.useEffect(()=>{X&&j(X)},[X,n]),!L)return u?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:t("machine.detail.notFound")}),s.jsx("p",{className:"mt-3",children:t("machine.detail.offlineHint")}),s.jsx("button",{onClick:I,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 je=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(hs,{size:14})," ",t("machine.detail.tabWorkspace")]}),count:O.length+E.length+T.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(_s,{size:14})," ",t("machine.detail.tabHostedRuntimes")]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(La,{size:14})," ",t("machine.detail.tabProviders")]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(zf,{size:14})," ",t("machine.detail.tabSystem")]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(uu,{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:I,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[_.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:_.nicknameInput,onChange:F=>_.setNicknameInput(F.target.value),onKeyDown:F=>{F.key==="Enter"&&_.handleSaveNickname(),F.key==="Escape"&&_.setEditingNickname(!1)},placeholder:t("machine.detail.nicknamePlaceholder"),className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:_.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:t("machine.detail.save")}),s.jsx("button",{onClick:()=>_.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:t("machine.detail.cancel")})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{_.setEditingNickname(!0),_.setNicknameInput(L.machineNickname||"")},title:t("machine.detail.clickToSetNickname"),children:$}),k?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),d.retryConnection&&n&&s.jsx("button",{onClick:()=>d.retryConnection(n),className:"px-2.5 py-0.5 rounded text-[11px] font-semibold bg-red-500/10 border border-red-500/20 text-red-400 hover:bg-red-500/20 transition-colors",children:t("machine.detail.reconnect")})]}):s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[s.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[L.platform," · ",L.arch]}),s.jsx("span",{children:t("machine.detail.coresCount",{count:L.cpus})}),(m==null?void 0:m.version)&&s.jsxs("span",{children:["v",m.version]}),L.p2p.available&&s.jsx("span",{children:t("machine.detail.p2pState",{state:L.p2p.state==="connected"?t("machine.detail.p2pConnected"):L.p2p.state})}),L.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:L.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:je.map(F=>s.jsxs("button",{onClick:()=>v(F.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${h===F.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[F.label,F.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${h===F.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:F.count})]},F.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[h==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(NI,{machineEntry:m,providers:W,recentLaunches:se,currentConversations:B,onUpgradeDaemon:async()=>{try{await o(n,"daemon_upgrade",im(m))}catch{}},onOpenRecent:le,onOpenConversation:ie}),s.jsx(MI,{machine:L,machineId:n,ideSessions:O,cliSessions:E,acpSessions:T,actions:_,sendDaemonCommand:o})]}),h==="providers"&&s.jsx(ET,{machineId:n,providers:W,sendDaemonCommand:o}),h==="overview"&&s.jsx(ST,{machine:L,ideSessions:O,cliSessions:E,acpSessions:T}),h==="session-host"&&s.jsx(SI,{machineId:n,cliSessions:E,sendDaemonCommand:o}),h==="logs"&&s.jsx(bI,{machineId:n,sendDaemonCommand:o})]})})}),_.launchPick&&L&&s.jsx(CI,{machine:L,launchPick:_.launchPick,actions:_}),y&&s.jsx(gl,{title:y.title,description:y.description,details:y.details,workspaceOptions:y.workspaceOptions,selectedWorkspaceKey:S,onWorkspaceChange:F=>{N.current=F,A(F)},confirmLabel:y.confirmLabel,busyLabel:y.busyLabel,busy:M,onConfirm:K,onCancel:()=>{C.current=null,x(null)}}),w&&s.jsx(fh,{daemonId:w.daemonId,workspace:w.workspace,onClose:()=>b(null)}),s.jsx(Ep,{toasts:d.toasts||[],onDismiss:F=>d.setToasts(me=>me.filter(ce=>ce.id!==F)),onClickToast:F=>{F.targetKey&&r(xr(F.targetKey))}}),s.jsx("style",{children:`
|
|
114
|
+
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){i("session_host_prune_duplicate_sessions");try{const D=await n(e,"session_host_prune_duplicate_sessions",{}),I=Uo(D);if(!(I!=null&&I.success))throw new Error((I==null?void 0:I.error)||"Duplicate prune failed");const _=I.result||{},W=Array.isArray(_.prunedSessionIds)?_.prunedSessionIds.length:0,H=typeof _.duplicateGroupCount=="number"?_.duplicateGroupCount:0;pt.showToast(`Pruned ${W} duplicate runtime(s) across ${H} group(s)`,"success"),await h()}catch(D){const I=D instanceof Error?D.message:"Duplicate prune failed";pt.showToast(I,"warning"),a(I)}finally{i(D=>D==="session_host_prune_duplicate_sessions"?null:D)}}},[e,h,n]),b=l.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((P,D)=>(D.lastActivityAt||0)-(P.lastActivityAt||0)),[u==null?void 0:u.sessions]),j=l.useMemo(()=>u!=null&&u.liveRuntimes||u!=null&&u.recoverySnapshots||u!=null&&u.inactiveRecords?{liveRuntimes:(u==null?void 0:u.liveRuntimes)||[],recoverySnapshots:(u==null?void 0:u.recoverySnapshots)||[],inactiveRecords:(u==null?void 0:u.inactiveRecords)||[]}:xI(b),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,b]),C=j.liveRuntimes,y=j.recoverySnapshots,x=j.inactiveRecords,N=l.useMemo(()=>kI(C),[C]),S=l.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),A=l.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(P=>P.level==="warn"||P.level==="error")||null,[u==null?void 0:u.recentLogs]),M=(P,D)=>{var $;const I=o===`session_host_resume_session:${P.sessionId}`,_=o===`session_host_restart_session:${P.sessionId}`,W=o===`session_host_stop_session:${P.sessionId}`,H=gh(P.meta),L=k.get(P.sessionId),O=P.attachedClients.length===1?"1 client":`${P.attachedClients.length} clients`,E=D==="recovery"?"Recover":"Resume",T=vI(D);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:P.displayName||(L==null?void 0:L.cliName)||P.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${wI(P.lifecycle)}`,children:P.lifecycle}),H&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:H})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:P.workspaceLabel||(L==null?void 0:L.runtimeWorkspaceLabel)||P.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:P.runtimeKey}),P.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",P.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:(($=P.writeOwner)==null?void 0:$.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:yI(P.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(cu,{size:11})," ",O]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",Fd(P.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",T]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[D==="recovery"&&(P.lifecycle==="interrupted"||P.lifecycle==="failed"||P.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{v("session_host_resume_session",P)},children:I?`${E}ing…`:E}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{v("session_host_restart_session",P)},children:_?"Restarting…":"Restart"}),D==="live"&&(P.lifecycle==="running"||P.lifecycle==="starting"||P.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!o,onClick:()=>{v("session_host_stop_session",P)},children:W?"Stopping…":"Stop"})]})]})},P.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(_s,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:cS()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[N>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{w()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${N})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${g.toneClass}`,children:g.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{h()},disabled:m||c,children:[s.jsx(Ra,{size:13}),m||c?"Refreshing…":"Refresh"]})]})]}),r&&!u&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(nn,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:r})]})]})}),u&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:y.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:Fd(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Go(u.hostStartedAt)})]})]}),A&&s.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[s.jsx(nn,{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:[Go(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(Oi,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Wo("live")}),C.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):s.jsx("div",{className:"space-y-2",children:C.map(P=>M(P,"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(_s,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Wo("recovery")}),y.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):s.jsx("div",{className:"space-y-2",children:y.map(P=>M(P,"recovery"))})]}),x.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Wo("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:x.map(P=>M(P,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),S.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:S.map(P=>{var I;const D=b.find(_=>_.sessionId===P.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(D==null?void 0:D.displayName)||((I=k.get(P.sessionId))==null?void 0:I.cliName)||P.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[P.action,P.lifecycle?` · ${P.lifecycle}`:"",P.detail?` · ${P.detail}`:"",P.error?` · ${P.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${P.success===!1?"text-red-300":"text-text-secondary"}`,children:Go(P.timestamp)})]},`${P.sessionId}:${P.timestamp}:${P.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:u.endpoint||"unknown"}),r?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",r]}):null]})]})]})}function CI({machine:e,launchPick:t,actions:n}){const{t:r}=Se("common"),{runLaunchCliCore:a,setLaunchPick:o}=n;return s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",children:s.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",children:[s.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),s.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),s.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?s.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(i=>s.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{o(null),a({cliType:t.cliType,workspaceId:i.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{o(null),a({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:r("newSession.defaultWorkspace")}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{o(null),a({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:r("newSession.homeDirectory")}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>o(null),children:"Cancel"})]})]})})}function jI(e,t){const n=om(e),r=xn(e,t),a=ol(e,r),o=lr(e,r),i=n==="preview"?"Update to preview":"Update daemon";return a?{visible:!0,showButton:!0,title:o?"Daemon update required":"Version mismatch detected",description:o?"This machine is on an incompatible daemon version. Update it before starting more sessions.":n==="preview"?"This machine can be upgraded to the current preview daemon without opening a remote shell.":"This machine is running a different daemon version than the current app. Update it before starting more sessions.",buttonLabel:i,targetVersion:r,channel:n,required:o,tone:"warn"}:n==="preview"?{visible:!0,showButton:!1,title:r?"Preview daemon is up to date":"Preview update status unknown",description:r?"This machine is already on the current preview daemon target.":"The app is connected to preview, but the server did not report a preview target version yet.",buttonLabel:i,targetVersion:r,channel:n,required:!1,tone:r?"good":"info"}:{visible:!1,showButton:!1,title:"",description:"",buttonLabel:i,targetVersion:r,channel:n,required:!1,tone:"info"}}function qo({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 zo({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 NI({machineEntry:e,providers:t,recentLaunches:n,currentConversations:r,onUpgradeDaemon:a,onOpenRecent:o,onOpenConversation:i}){const{t:c}=Se("common"),d=r.slice(0,6),p=n.slice(0,4),m=jI(e,"1.0.20");return s.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(qo,{icon:s.jsx(ln,{size:13}),children:c("machine.commandCenter.currentChats")}),s.jsx(zo,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(f=>{const g=Ci(f);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>i(f),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:xt(f)}),g>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Ea(g)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:Mn(f)})]},f.tabKey)})})})]}),p.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(qo,{icon:s.jsx(hu,{size:13}),children:c("machine.commandCenter.recentLaunches")}),s.jsx(zo,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:p.map(f=>{const{metaText:g,updatedLabel:k}=gm(f);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>o(f),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:f.label}),k&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:k})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:g})]},f.id)})})})]}),m.visible&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(qo,{icon:s.jsx(nn,{size:13}),children:c("machine.commandCenter.daemonUpdate")}),s.jsx(zo,{className:m.tone==="good"?"border-emerald-500/20 bg-emerald-500/5":m.tone==="info"?"border-sky-500/20 bg-sky-500/5":"border-amber-500/20 bg-amber-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:m.title}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[m.description,m.targetVersion&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",m.targetVersion,m.channel?` (${m.channel})`:""]})]}),m.showButton?s.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:a,children:[s.jsx(Ra,{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 AI({machineId:e,machine:t,ideSessions:n,cliSessions:r,acpSessions:a,actions:o,sendDaemonCommand:i}){const{workspaceBusy:c,handleWorkspaceAdd:d,handleWorkspaceRemove:p,handleWorkspaceSetDefault:u}=o,{t:m}=Se("common"),[f,g]=l.useState(!1),[k,h]=l.useState(""),[v,w]=l.useState([]),[b,j]=l.useState(!1),[C,y]=l.useState(""),x=l.useCallback(async S=>{j(!0),y("");try{const A=await hl(i,e,S);h(A.path),w(A.directories)}catch(A){y(A instanceof Error?A.message:"Could not load folder")}finally{j(!1)}},[e,i]),N=l.useCallback(()=>{g(!0);const S=[...n.map(M=>M.workspace),...r.map(M=>M.workspace),...a.map(M=>M.workspace)],A=ml(t.platform,pl(S,t.defaultWorkspacePath,(t.workspaces||[]).map(M=>M.path)));x(A)},[a,r,n,x,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(Nn,{size:14})," Workspaces"]}),s.jsx("button",{type:"button",className:"btn bg-bg-glass hover:bg-bg-glass-hover text-text-muted hover:text-text-primary px-3 py-1 rounded transition-colors text-xs",disabled:c,onClick:N,children:"+ Add workspace"})]}),(t.workspaces||[]).length===0?s.jsxs("div",{className:"text-[11px] text-text-muted py-4 text-center",children:["No saved workspaces yet. Click ",s.jsx("span",{className:"text-text-secondary",children:"+ Add workspace"})," to pick a folder."]}):s.jsx("ul",{className:"space-y-1.5 max-h-72 overflow-y-auto",children:(t.workspaces||[]).map(S=>{const A=S.id===t.defaultWorkspaceId;return s.jsxs("li",{className:`flex items-start gap-2 text-[11px] rounded-lg border px-2.5 py-2 transition-colors ${A?"border-yellow-500/30 bg-yellow-500/[0.05]":"border-border-subtle bg-bg-primary"}`,children:[s.jsx("button",{type:"button",title:A?"Default workspace — click to unset":"Set as default workspace",disabled:c,onClick:()=>void u(A?null:S.id),className:`text-base leading-none shrink-0 transition-colors ${A?"text-yellow-400 hover:text-yellow-300":"text-text-muted/40 hover:text-yellow-400"}`,children:"★"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"font-medium text-text-primary truncate",children:_u(S.path,S.label)}),s.jsx("div",{className:"font-mono text-text-muted truncate text-[10px]",title:S.path,children:S.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void p(S.id),children:m("machine.managedWorkspaces.remove")})]},S.id)})})]}),f&&s.jsx(bl,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:k,directories:v,busy:b,error:C,confirmLabel:"Add workspace",onClose:()=>g(!1),onNavigate:S=>{x(S)},onConfirm:S=>{(async()=>{if(!S)return;await d(S)&&g(!1)})()}})]})}function MI({machine:e,machineId:t,ideSessions:n,cliSessions:r,acpSessions:a,actions:o,sendDaemonCommand:i}){return s.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[s.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-border-subtle mb-4",children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspaces"}),s.jsx("div",{className:"text-sm text-text-secondary",children:'Save folders as workspaces on this machine. Use the dashboard "+" button to launch a session.'})]}),i&&s.jsx(AI,{machineId:t,machine:e,ideSessions:n,cliSessions:r,acpSessions:a,actions:o,sendDaemonCommand:i})]})}function TI({onNicknameSynced:e}={}){var we,ke,he,U,q,Z,Y,fe,Me,de;const{t}=Se("common"),{id:n}=Zh(),r=wr(),a=Ri(),{sendCommand:o}=vt(),i=_n(),c=Yp(),d=wp(),p=d.ides||[],u=d.initialLoaded??!0,m=p.find(F=>F.id===n&&F.type==="adhdev-daemon"),f=p.some(F=>F.type==="adhdev-daemon"),g=n?(we=d.connectionRetryStatuses)==null?void 0:we[n]:void 0,k=!!(g!=null&&g.blocked),[h,v]=l.useState("workspace"),[w,b]=l.useState(null);l.useCallback((F,me)=>{b({daemonId:F,workspace:me})},[]);const[,j]=l.useState("ide"),C=l.useRef(null),[y,x]=l.useState(null),N=l.useRef("__home__"),[S,A]=l.useState("__home__"),[M,P]=l.useState(!1),D=l.useRef(null);l.useEffect(()=>{!n||!m||!(!m.workspaces||!m.availableProviders||!m.detectedIdes||!m.recentLaunches)||i(n,{minFreshMs:3e4}).catch(()=>{})},[i,m,n]),l.useEffect(()=>{if(!n||!m||h!=="overview")return;const F=m.machine;(typeof(F==null?void 0:F.cpus)!="number"||typeof(F==null?void 0:F.totalMem)!="number"||typeof(F==null?void 0:F.arch)!="string"||typeof(F==null?void 0:F.release)!="string")&&c(n,{minFreshMs:3e4}).catch(()=>{})},[h,c,m,n]),AC(n&&h==="overview"?[n]:[],{enabled:h==="overview",intervalMs:R0});const I=()=>{if(f){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},_=kT({machineId:n,registeredMachineId:(m==null?void 0:m.machineId)||null,sendDaemonCommand:o,onNicknameSynced:e,logsEndRef:D});l.useEffect(()=>pt.onToast(me=>{d.setToasts(z=>{if(z.some(Ne=>Ne.message===me.message&&me.timestamp-Ne.timestamp<3e3))return z;const Ce={id:me.id,message:me.message,type:me.type,timestamp:me.timestamp,targetKey:me.targetKey,actions:me.actions};return[...z.slice(-4),Ce]});const ce=me.duration||5e3;setTimeout(()=>d.setToasts(z=>z.filter(ge=>ge.id!==me.id)),ce)}),[d]);const W=(m==null?void 0:m.availableProviders)||[],H={};for(const F of W)H[F.type]=F.icon;const L=m?{id:m.id,hostname:$u(m,{fallbackId:m.id}),platform:((ke=m.machine)==null?void 0:ke.platform)||"unknown",arch:((he=m.machine)==null?void 0:he.arch)||"",cpus:((U=m.machine)==null?void 0:U.cpus)||0,totalMem:((q=m.machine)==null?void 0:q.totalMem)||0,freeMem:(Z=m.machine)==null?void 0:Z.freeMem,availableMem:(Y=m.machine)==null?void 0:Y.availableMem,loadavg:(fe=m.machine)==null?void 0:fe.loadavg,uptime:(Me=m.machine)==null?void 0:Me.uptime,release:((de=m.machine)==null?void 0:de.release)||"",cdpConnected:!!m.cdpConnected,machineNickname:m.machineNickname||null,p2p:m.p2p?{screenshotActive:!1,...m.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:m.detectedIdes||[],workspaces:m.workspaces||[],defaultWorkspaceId:m.defaultWorkspaceId??m.activeWorkspaceId??null,defaultWorkspacePath:m.defaultWorkspacePath??m.activeWorkspacePath??null}:null,O=p.filter(F=>F.daemonId===n&&F.type!=="adhdev-daemon").filter(F=>!fr(F)&&!kn(F)).map(F=>({id:F.id,sessionId:F.sessionId,type:F.type,version:F.version||"",instanceId:F.instanceId||"",status:F.status,workspace:F.workspace||null,terminals:F.terminals||0,aiAgents:Yy(F.aiAgents||(F.agents||[]).map(me=>({id:me.name,name:me.name,status:me.status,version:me.version}))),activeChat:F.activeChat||null,chats:F.chats||[],childSessions:F.childSessions||[],cdpConnected:F.cdpConnected||!1,daemonId:n,lastMessageAt:F.lastMessageAt})),E=p.filter(F=>F.daemonId===n&&fr(F)).map(F=>({id:F.id,sessionId:F.sessionId,type:F.type,cliName:F.cliName||F.type,status:F.status,workspace:F.workspace||"",activeChat:F.activeChat||null,providerSessionId:F.providerSessionId,mode:F.mode,runtimeKey:F.runtimeKey,runtimeDisplayName:F.runtimeDisplayName,runtimeWorkspaceLabel:F.runtimeWorkspaceLabel,runtimeWriteOwner:F.runtimeWriteOwner||null,runtimeAttachedClients:F.runtimeAttachedClients||[],daemonId:n,lastMessageAt:F.lastMessageAt})),T=p.filter(F=>F.daemonId===n&&kn(F)).map(F=>({id:F.id,sessionId:F.sessionId,type:F.type,acpName:F.cliName||F.type,status:F.status,workspace:F.workspace||"",activeChat:F.activeChat||null,providerSessionId:F.providerSessionId,daemonId:n,lastMessageAt:F.lastMessageAt})),$=m?ss(m,{fallbackId:n}):"",R="workspace",G=a.state,Q=G==null?void 0:G.initialMachineTab,re=G==null?void 0:G.initialWorkspaceCategory;G==null||G.initialWorkspaceId,G==null||G.initialWorkspacePath;const J=Q==="ides"||Q==="clis"||Q==="acps"?"workspace":Q||R,X=Q==="ides"?"ide":Q==="clis"?"cli":Q==="acps"?"acp":re,ue=[...O.map(F=>{var me;return{id:`ide:${F.type}:${F.workspace||""}`,label:((me=F.activeChat)==null?void 0:me.title)||F.type,kind:"ide",providerType:F.type,subtitle:F.workspace||void 0,workspace:F.workspace||void 0,lastLaunchedAt:F.lastMessageAt||0}}),...E.map(F=>{var me;return{id:`cli:${F.type}:${F.workspace||""}`,label:((me=F.activeChat)==null?void 0:me.title)||F.cliName,kind:"cli",providerType:F.type,providerSessionId:F.providerSessionId,subtitle:F.workspace||void 0,workspace:F.workspace||void 0,lastLaunchedAt:F.lastMessageAt||0}}),...T.map(F=>{var me;return{id:`acp:${F.type}:${F.workspace||""}`,label:((me=F.activeChat)==null?void 0:me.title)||F.acpName,kind:"acp",providerType:F.type,providerSessionId:F.providerSessionId,subtitle:rn(F.summaryMetadata)||F.workspace||void 0,workspace:F.workspace||void 0,lastLaunchedAt:F.lastMessageAt||0}})].sort((F,me)=>(me.lastLaunchedAt||0)-(F.lastLaunchedAt||0)),se=((m==null?void 0:m.recentLaunches)||[]).length>0?((m==null?void 0:m.recentLaunches)||[]).map(F=>({id:F.id,label:F.title||F.providerName||F.providerType,kind:F.kind,providerType:F.providerType,providerSessionId:F.providerSessionId,subtitle:rn(F.summaryMetadata)||F.workspace||void 0,workspace:F.workspace,summaryMetadata:F.summaryMetadata,lastLaunchedAt:F.lastLaunchedAt})):ue,B=l.useMemo(()=>{var me;const F=((me=d.connectionStates)==null?void 0:me[n||""])||void 0;return p.filter(ce=>ce.daemonId===n&&ce.type!=="adhdev-daemon").flatMap(ce=>al(ce,{connectionStates:n&&F?{[n]:F}:void 0,defaultConnectionState:F})).filter(ce=>!(ce.transport==="pty"&&ce.mode==="terminal")).sort((ce,z)=>Ci(z)-Ci(ce))},[p,d.connectionStates,n]),ie=l.useCallback(F=>{const me=dm(F);me&&r(xr(me))},[r]),K=l.useCallback(()=>{C.current&&(P(!0),C.current().finally(()=>{C.current=null,P(!1),x(null)}))},[]),le=l.useCallback(F=>{if(!L)return;const{options:me,selectedKey:ce}=bm({machine:L,currentWorkspacePath:F.workspace,homeLabel:t("newSession.homeDirectory"),homeDescription:t("newSession.launchWithoutWorkspace")}),z=async()=>{j(F.kind),v("workspace")};C.current=async()=>{const ge=me.find(He=>He.key===N.current),Ce=(ge==null?void 0:ge.workspacePath)??null,Ne=(ge==null?void 0:ge.workspaceId)??null;if(F.kind==="ide"&&F.providerType){await _.handleLaunchIde(F.providerType,Ce?{workspace:Ce}:void 0);return}if((F.kind==="cli"||F.kind==="acp")&&F.providerType){await _.runLaunchCliCore({cliType:F.providerType,dir:Ne?void 0:Ce||"",workspaceId:Ne||void 0,model:F.kind==="acp"&&Fu(F.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:F.providerSessionId});return}await z()},N.current=ce,A(ce),x({title:F.kind==="ide"?wa(t,"restart-ide",F.label):F.providerSessionId?Pp(t,F.label):wa(t,"start-fresh",F.label),description:F.kind==="ide"?ka(t,"restart-ide"):F.providerSessionId?Lp(t):ka(t,"start-fresh"),confirmLabel:F.kind==="ide"?Sa(t,"restart-ide"):F.providerSessionId?gi(t,!0):Sa(t,"start-fresh"),busyLabel:F.kind==="ide"?Ca(t,"restart-ide"):F.providerSessionId?Dp(t,!0):Ca(t,"start-fresh"),workspaceOptions:me,details:[{label:"Mode",value:F.kind.toUpperCase()},...F.providerType?[{label:"Provider",value:F.providerType}]:[]]})},[_,L]);if(l.useEffect(()=>{v(J)},[R,J,n]),l.useEffect(()=>{X&&j(X)},[X,n]),!L)return u?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:t("machine.detail.notFound")}),s.jsx("p",{className:"mt-3",children:t("machine.detail.offlineHint")}),s.jsx("button",{onClick:I,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 je=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(hs,{size:14})," ",t("machine.detail.tabWorkspace")]}),count:O.length+E.length+T.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(_s,{size:14})," ",t("machine.detail.tabHostedRuntimes")]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(La,{size:14})," ",t("machine.detail.tabProviders")]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(zf,{size:14})," ",t("machine.detail.tabSystem")]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(uu,{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:I,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[_.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:_.nicknameInput,onChange:F=>_.setNicknameInput(F.target.value),onKeyDown:F=>{F.key==="Enter"&&_.handleSaveNickname(),F.key==="Escape"&&_.setEditingNickname(!1)},placeholder:t("machine.detail.nicknamePlaceholder"),className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:_.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:t("machine.detail.save")}),s.jsx("button",{onClick:()=>_.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:t("machine.detail.cancel")})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{_.setEditingNickname(!0),_.setNicknameInput(L.machineNickname||"")},title:t("machine.detail.clickToSetNickname"),children:$}),k?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),d.retryConnection&&n&&s.jsx("button",{onClick:()=>d.retryConnection(n),className:"px-2.5 py-0.5 rounded text-[11px] font-semibold bg-red-500/10 border border-red-500/20 text-red-400 hover:bg-red-500/20 transition-colors",children:t("machine.detail.reconnect")})]}):s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[s.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[L.platform," · ",L.arch]}),s.jsx("span",{children:t("machine.detail.coresCount",{count:L.cpus})}),(m==null?void 0:m.version)&&s.jsxs("span",{children:["v",m.version]}),L.p2p.available&&s.jsx("span",{children:t("machine.detail.p2pState",{state:L.p2p.state==="connected"?t("machine.detail.p2pConnected"):L.p2p.state})}),L.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:L.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:je.map(F=>s.jsxs("button",{onClick:()=>v(F.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${h===F.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[F.label,F.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${h===F.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:F.count})]},F.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[h==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(NI,{machineEntry:m,providers:W,recentLaunches:se,currentConversations:B,onUpgradeDaemon:async()=>{try{await o(n,"daemon_upgrade",im(m))}catch{}},onOpenRecent:le,onOpenConversation:ie}),s.jsx(MI,{machine:L,machineId:n,ideSessions:O,cliSessions:E,acpSessions:T,actions:_,sendDaemonCommand:o})]}),h==="providers"&&s.jsx(ET,{machineId:n,providers:W,sendDaemonCommand:o}),h==="overview"&&s.jsx(ST,{machine:L,ideSessions:O,cliSessions:E,acpSessions:T}),h==="session-host"&&s.jsx(SI,{machineId:n,cliSessions:E,sendDaemonCommand:o}),h==="logs"&&s.jsx(bI,{machineId:n,sendDaemonCommand:o})]})})}),_.launchPick&&L&&s.jsx(CI,{machine:L,launchPick:_.launchPick,actions:_}),y&&s.jsx(gl,{title:y.title,description:y.description,details:y.details,workspaceOptions:y.workspaceOptions,selectedWorkspaceKey:S,onWorkspaceChange:F=>{N.current=F,A(F)},confirmLabel:y.confirmLabel,busyLabel:y.busyLabel,busy:M,onConfirm:K,onCancel:()=>{C.current=null,x(null)}}),w&&s.jsx(fh,{daemonId:w.daemonId,workspace:w.workspace,onClose:()=>b(null)}),s.jsx(Ep,{toasts:d.toasts||[],onDismiss:F=>d.setToasts(me=>me.filter(ce=>ce.id!==F)),onClickToast:F=>{F.targetKey&&r(xr(F.targetKey))}}),s.jsx("style",{children:`
|
|
115
115
|
@keyframes toast-in {
|
|
116
116
|
from { opacity: 0; transform: translateX(40px); }
|
|
117
117
|
to { opacity: 1; transform: translateX(0); }
|
|
118
118
|
}
|
|
119
119
|
`})]})}function II({daemonIds:e,meshId:t,sendData:n,onRevisionAdvance:r}){const a=l.useRef(new Map),o=l.useRef(r);o.current=r;const i=[...new Set(e.filter(Boolean))].sort().join(",");l.useEffect(()=>{a.current=new Map},[i,t]),l.useEffect(()=>{if(!t||!n)return;const c=[...new Set(e.filter(Boolean))];if(c.length===0)return;const d=c.map(p=>us.subscribe({sendData:n},p,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${p}`,params:{includeSessions:!0}},u=>{if(u.topic!=="daemon.metadata")return;const m=u.meshStateRevisions;if(!m)return;const f=m[t]??m["*"];if(typeof f!="number")return;const g=a.current.get(p);a.current.set(p,f),g!==void 0&&f>g&&o.current()}));return()=>{for(const p of d)p()}},[i,t,n])}const DI={meshHostDaemonSection:!1,createDaemonPicker:!1,addNodeDaemonPicker:!1,queueSection:!0,coordinatorPrompt:!0,nodeInstruction:!0,hermesMcpConfig:!0,reviewInbox:!0},xh=l.createContext(null);function PI(){const e=l.useContext(xh);if(!e)throw new Error("useRepoMeshContext must be used inside RepoMeshProvider");return e}function LI({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("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 RI({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 EI({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 _I({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 $I({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 HI(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function FI({meshes:e,loading:t,error:n,onDismissError:r,daemons:a,features:o,showCreate:i,onToggleCreate:c,createName:d,onCreateNameChange:p,createRepoIdentity:u,onCreateRepoIdentityChange:m,createRepoRemoteUrl:f,onCreateRepoRemoteUrlChange:g,newMeshDaemonId:k,onNewMeshDaemonIdChange:h,newMeshWorkspace:v,onNewMeshWorkspaceChange:w,createPickerWorkspaces:b,onSelectMesh:j,onCreate:C,onCancelCreate:y}){const{t:x}=Se("common"),N=o.maxMeshes!=null&&e.length>=o.maxMeshes,[S,A]=l.useState(!1),M=S||!!u.trim();return s.jsxs(jr,{icon:s.jsx(ts,{}),title:x("repoMesh.list.title"),subtitle:x("repoMesh.list.count",{count:e.length}),widthClassName:"max-w-5xl",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:c,disabled:N,title:N?x("repoMesh.list.meshLimitReached",{max:o.maxMeshes}):void 0,children:x("repoMesh.list.createMesh")}),children:[N&&s.jsx(Ht,{variant:"info",className:"mb-4",children:x("repoMesh.list.meshLimitBanner",{max:o.maxMeshes})}),n&&s.jsx(Ht,{variant:"error",onDismiss:r,className:"mb-4",children:n}),i&&s.jsxs(ht,{className:"mb-5 border-accent/40 animate-[fadeIn_0.3s_ease-out]",children:[s.jsx("h3",{className:"text-base font-bold mb-4",children:x("repoMesh.list.createTitle")}),o.createDaemonPicker&&s.jsx(jt,{label:x("repoMesh.list.createOnMachine"),hint:x("repoMesh.list.createOnMachineHint"),children:s.jsx("select",{className:"input w-full",value:k,onChange:P=>h(P.target.value),disabled:!a.length,children:a.length===0?s.jsx("option",{value:"",children:x("repoMesh.list.noConnectedDaemon")}):a.map(P=>s.jsx("option",{value:P.id,children:HI(P)},P.id))})}),o.createDaemonPicker&&s.jsx(jt,{label:x("repoMesh.list.workspace"),hint:x("repoMesh.list.workspaceHint"),children:s.jsx("select",{className:"input w-full",value:v,onChange:P=>w(P.target.value),disabled:!k||!b.length,children:k?b.length===0?s.jsx("option",{value:"",children:x("repoMesh.list.noRegisteredWorkspaces")}):b.map(P=>s.jsx("option",{value:P.path,children:P.label?`${P.label} · ${P.path}`:P.path},P.id||P.path)):s.jsx("option",{value:"",children:x("repoMesh.list.selectMachineFirst")})})}),s.jsx(jt,{label:x("repoMesh.list.name"),children:s.jsx(ds,{value:d,onChange:P=>p(P.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(jt,{label:x("repoMesh.list.remoteUrl"),hint:x("repoMesh.list.remoteUrlHint"),children:s.jsx(ds,{value:f,onChange:P=>g(P.target.value),placeholder:"https://github.com/user/repo"})}),M?s.jsx(jt,{label:x("repoMesh.list.repoIdentity"),hint:x("repoMesh.list.repoIdentityHint"),children:s.jsx(ds,{value:u,onChange:P=>m(P.target.value),placeholder:"github.com/user/repo"})}):s.jsx("button",{type:"button",className:"text-xs text-text-muted hover:text-text-primary underline underline-offset-2 mb-5",onClick:()=>A(!0),children:x("repoMesh.list.advancedIdentityToggle")}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:C,disabled:!d.trim()||!f.trim()&&!u.trim()||o.createDaemonPicker&&(!k||!v),children:x("repoMesh.list.create")}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:y,children:x("repoMesh.list.cancel")})]})]}),t?s.jsx("div",{className:"text-sm text-text-muted p-4",children:x("repoMesh.list.loading")}):e.length===0?s.jsx(Ga,{icon:s.jsx(ts,{}),title:x("repoMesh.list.emptyTitle"),description:a.length>0?x("repoMesh.list.emptyWithDaemons"):x("repoMesh.list.emptyNoDaemons"),action:s.jsx("button",{className:"btn btn-primary btn-sm",disabled:!a.length,onClick:c,children:x("repoMesh.list.createFirst")})}):s.jsx("div",{className:"flex flex-col gap-2.5",children:e.map(P=>{var D;return s.jsx("button",{type:"button",onClick:()=>j(P.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(ts,{size:16}),s.jsx("span",{className:"font-bold text-sm",children:P.name})]}),s.jsxs("div",{className:"text-[12px] text-text-muted flex items-center gap-2",children:[s.jsx("span",{className:"font-mono",children:P.repoIdentity||P.repo_identity||x("repoMesh.list.noRepoIdentity")}),(P.defaultBranch||P.default_branch)&&s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(RI,{size:11}),P.defaultBranch||P.default_branch]})]})]}),s.jsxs("div",{className:"text-right text-[11px] text-text-muted shrink-0 ml-4",children:[s.jsx("div",{children:new Date(P.createdAt||P.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})}),s.jsxs("div",{className:"text-text-muted/60",children:[((D=P.nodes)==null?void 0:D.length)??P.nodeCount??0," ",x("repoMesh.list.nodesSuffix")]})]})]})},P.id)})})]})}const BI=["claude-cli","codex-cli","gemini-cli","hermes-cli","antigravity-cli"],OI=[{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 WI(){return{nodeId:"",provider:"",model:"",n:""}}function Bd(e){var t;return(t=e.providers)!=null&&t.length?e.providers.filter(Boolean):(e.providerPriority??[]).filter(Boolean)}function UI(e){return{nodeId:e.nodeId??"",provider:e.provider??"",model:e.model??"",n:e.n!=null?String(e.n):""}}function GI(e){const t=[];for(let n=0;n<e.length;n++){const r=e[n],a=r.provider.trim();if(!a)return{error:{code:"provider_required",slot:n+1}};const o=r.nodeId.trim(),i=r.model.trim(),c=r.n.trim();let d;if(c){const p=Number(c);if(!Number.isFinite(p)||p<1)return{error:{code:"replica_min",slot:n+1}};d=Math.floor(p)}t.push({provider:a,...o?{nodeId:o}:{},...i?{model:i}:{},...d!==void 0?{n:d}:{}})}return t.length===0?{error:{code:"no_slot"}}:{slots:t}}function qI({status:e,daemonId:t,sendDaemonCommand:n,availableProviders:r}){const{t:a}=Se(),{theme:o}=Fs(),i=l.useMemo(()=>Bs(o),[o]),c=l.useMemo(()=>Bp(r),[r]),[d,p]=l.useState({}),[u,m]=l.useState(!1),[f,g]=l.useState(null),[k,h]=l.useState({}),[v,w]=l.useState(null),b=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(T=>({nodeId:T.nodeId,machineLabel:T.machineLabel,providers:T.providers,providerPriority:T.providerPriority})),[e==null?void 0:e.nodes]),j=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(T=>T.nodeId),[e==null?void 0:e.nodes]),C=l.useMemo(()=>Object.fromEntries(((e==null?void 0:e.nodes)??[]).map(T=>[T.nodeId,T.machineLabel||T.nodeId])),[e==null?void 0:e.nodes]),y=l.useMemo(()=>{const T={};for(const $ of b)T[$.nodeId]=Bd($);return T},[b]),x=l.useMemo(()=>{const T=[...new Set(b.flatMap(Bd).filter(Boolean))];return[...new Set([...T,...BI])].sort()},[b]),N=!!t&&!!n,S=T=>T&&typeof T=="object"&&"result"in T?T.result:T,A=l.useCallback(async()=>{if(!(!t||!n)){m(!0),g(null);try{const T=await n(t,"magi_kind_panel_list",{}),$=S(T);if(($==null?void 0:$.success)===!1)throw new Error($.error||a("meshGraph.magiKind.errorLoad"));p($!=null&&$.kindPanels&&typeof $.kindPanels=="object"?$.kindPanels:{}),h({})}catch(T){g((T==null?void 0:T.message)||a("meshGraph.magiKind.errorLoad"))}finally{m(!1)}}},[t,n,a]);l.useEffect(()=>{A()},[A]);const M=l.useCallback(T=>{if(k[T])return k[T];const $=d[T];return $?$.map(UI):[]},[k,d]),P=(T,$)=>{h(R=>({...R,[T]:$}))},D=(T,$,R)=>{const G=M(T);P(T,G.map((Q,re)=>re===$?{...Q,...R}:Q))},I=T=>{P(T,[...M(T),WI()])},_=(T,$)=>{P(T,M(T).filter((R,G)=>G!==$))},W=l.useCallback(async T=>{if(!t||!n)return;const $=GI(M(T));if("error"in $){const R=$.error,G=R.code==="provider_required"?a("meshGraph.magiKind.errorSlotProvider",{slot:R.slot}):R.code==="replica_min"?a("meshGraph.magiKind.errorSlotReplica",{slot:R.slot}):a("meshGraph.magiKind.errorNoSlot");g(`${T}: ${G}`);return}w(T),g(null);try{const R=await n(t,"magi_kind_panel_set",{kind:T,slots:$.slots}),G=S(R);if((G==null?void 0:G.success)===!1)throw new Error(G.error||a("meshGraph.magiKind.errorSave"));await A()}catch(R){g((R==null?void 0:R.message)||a("meshGraph.magiKind.errorSave"))}finally{w(null)}},[t,n,M,A,a]),H=l.useCallback(async T=>{if(!(!t||!n)&&confirm(a("meshGraph.magiKind.removeConfirm",{kind:T}))){w(T),g(null);try{const $=await n(t,"magi_kind_panel_remove",{kind:T}),R=S($);if((R==null?void 0:R.success)===!1)throw new Error(R.error||a("meshGraph.magiKind.errorRemove"));await A()}catch($){g(($==null?void 0:$.message)||a("meshGraph.magiKind.errorRemove"))}finally{w(null)}}},[t,n,A,a]),L=`w-full rounded-lg border px-2.5 py-1.5 text-xs ${i.isDark?"border-white/10 bg-slate-950/40 text-slate-100 placeholder:text-slate-500":"border-slate-300 bg-white text-slate-900 placeholder:text-slate-400"}`,O="btn btn-primary btn-sm",E="btn btn-secondary btn-sm";return s.jsxs("div",{className:"flex flex-col gap-3 p-1",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("p",{className:`text-[12px] ${i.textSecondary}`,children:a("meshGraph.magiKind.intro")}),s.jsx("div",{className:"ml-auto flex items-center gap-2",children:s.jsx("button",{type:"button",className:E,onClick:()=>void A(),disabled:u||!N,children:a(u?"meshGraph.magiKind.loading":"meshGraph.magiKind.refresh")})})]}),!N&&s.jsx("div",{className:`rounded-xl border p-3 text-[12px] ${i.textSecondary} ${i.isDark?"border-white/10":"border-slate-200"}`,children:a("meshGraph.magiKind.connectPrompt")}),f&&s.jsx("div",{className:"rounded-xl border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-[12px] text-rose-300",children:f}),s.jsx("div",{className:"flex flex-col gap-3",children:OI.map(({kind:T,labelKey:$,hint:R})=>{const G=M(T),Q=!!d[T],re=v===T;return s.jsxs("div",{className:`${i.cardClass} rounded-2xl p-4 flex flex-col gap-3`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[13px] font-semibold ${i.textPrimary}`,children:a($)}),s.jsx("span",{className:`font-mono text-[10px] ${i.textMuted}`,children:R}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${Q?"border-emerald-400/30 bg-emerald-500/10 text-emerald-300":"border-slate-400/20 bg-slate-500/10 text-slate-300"}`,children:Q?a("meshGraph.magiKind.agentCount",{count:d[T].length}):a("meshGraph.magiKind.off")})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[G.length===0&&s.jsx("div",{className:`rounded-xl border p-2.5 text-[11px] ${i.textSecondary} ${i.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:a("meshGraph.magiKind.noAgents")}),G.map((J,X)=>{const ue=J.nodeId?y[J.nodeId]??[]:[],se=J.nodeId&&ue.length?ue:x;return s.jsxs("div",{className:`rounded-xl border p-2.5 grid grid-cols-1 sm:grid-cols-[1fr_1fr_1fr_auto_auto] gap-x-2 gap-y-1 items-start ${i.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:a("meshGraph.magiKind.machine")}),s.jsxs("select",{className:L,value:J.nodeId,onChange:B=>D(T,X,{nodeId:B.target.value}),title:a("meshGraph.magiKind.machineTitle"),children:[s.jsx("option",{value:"",children:a("meshGraph.magiKind.anyMachine")}),j.map(B=>s.jsx("option",{value:B,children:C[B]??B},B)),J.nodeId&&!j.includes(J.nodeId)&&s.jsx("option",{value:J.nodeId,children:a("meshGraph.magiKind.offlineSuffix",{label:C[J.nodeId]??J.nodeId})})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsxs("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:[a("meshGraph.magiKind.provider")," *"]}),s.jsxs("select",{className:L,value:J.provider,onChange:B=>D(T,X,{provider:B.target.value}),title:a("meshGraph.magiKind.providerTitle"),children:[s.jsx("option",{value:"",children:a("meshGraph.magiKind.selectProvider")}),se.map(B=>s.jsx("option",{value:B,children:B},B)),J.provider&&!se.includes(J.provider)&&s.jsx("option",{value:J.provider,children:J.provider})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:a("meshGraph.magiKind.model")}),(()=>{var K;const B=(J.provider?(K=c.get(J.provider))==null?void 0:K.models:void 0)??[],ie=!!J.model&&B.length>0&&!B.includes(J.model);return B.length>0&&!ie?s.jsxs("select",{className:L,value:B.includes(J.model)?J.model:"",title:a("meshGraph.magiKind.modelTitle"),onChange:le=>D(T,X,{model:le.target.value==="__custom__"?" ":le.target.value}),children:[s.jsx("option",{value:"",children:a("meshGraph.magiKind.modelDefault")}),B.map(le=>s.jsx("option",{value:le,children:le},le)),s.jsx("option",{value:"__custom__",children:a("meshGraph.magiKind.modelCustom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:L,value:J.model.trim(),placeholder:a("meshGraph.magiKind.modelDefault"),title:a("meshGraph.magiKind.modelTitle"),onChange:le=>D(T,X,{model:le.target.value})}),B.length>0&&s.jsx("button",{type:"button",className:`self-start bg-transparent border-none cursor-pointer p-0 text-[10px] ${i.textSecondary} hover:underline`,onClick:()=>D(T,X,{model:""}),children:a("meshGraph.magiKind.backToModelList")})]})})()]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:a("meshGraph.magiKind.copies")}),s.jsx("input",{className:`${L} sm:w-16`,value:J.n,placeholder:"1",inputMode:"numeric",title:a("meshGraph.magiKind.copiesTitle"),onChange:B=>D(T,X,{n:B.target.value})})]}),s.jsx("button",{type:"button",className:`${E} sm:mt-[18px] inline-flex h-8 w-8 items-center justify-center p-0`,onClick:()=>_(T,X),"aria-label":a("meshGraph.magiKind.removeAgent"),title:a("meshGraph.magiKind.removeAgent"),children:"✕"})]},X)}),s.jsx("div",{children:s.jsx("button",{type:"button",className:E,onClick:()=>I(T),disabled:!N,children:a("meshGraph.magiKind.addAgent")})})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:O,onClick:()=>void W(T),disabled:re||!N,children:a(re?"meshGraph.magiKind.saving":"meshGraph.magiKind.save")}),s.jsx("button",{type:"button",className:E,onClick:()=>void H(T),disabled:re||!N||!Q,title:a(Q?"meshGraph.magiKind.removeBindingTitle":"meshGraph.magiKind.removeBindingDisabledTitle"),children:a("meshGraph.magiKind.removeBinding")})]})]},T)})})]})}function zI({daemonId:e,meshId:t,cliType:n,sendCommand:r}){const{t:a}=Se(),[o,i]=l.useState(!1),[c,d]=l.useState(!1),[p,u]=l.useState(null),[m,f]=l.useState(null),[g,k]=l.useState(null),h=l.useCallback(async()=>{if(!e||!t){u(a("repoMesh.promptPreview.connectPrompt"));return}d(!0),u(null);try{const w=await r(e,"coordinator_prompt_preview",{meshId:t,cliType:n}),b=w!=null&&w.result&&typeof w.result=="object"?w.result:w;if(!(b!=null&&b.success)){u((b==null?void 0:b.error)||a("repoMesh.promptPreview.errorRender"));return}f(typeof b.prompt=="string"?b.prompt:""),k(typeof b.bytes=="number"?b.bytes:null)}catch(w){u((w==null?void 0:w.message)||String(w))}finally{d(!1)}},[e,t,n,r,a]),v=l.useCallback(()=>{const w=!o;i(w),w&&m===null&&!c&&h()},[o,m,c,h]);return s.jsxs("div",{className:"mt-2",children:[s.jsxs("button",{type:"button",onClick:v,className:"inline-flex items-center gap-1 text-[12px] text-accent-primary bg-transparent border-none cursor-pointer p-0",children:[s.jsx("span",{className:`transition-transform ${o?"rotate-90":""}`,"aria-hidden":!0,children:"▸"}),a(o?"repoMesh.promptPreview.hide":"repoMesh.promptPreview.view"),s.jsxs("span",{className:"text-text-muted",children:["(",n,")"]})]}),o&&s.jsxs("div",{className:"mt-2",children:[c&&s.jsx("div",{className:"text-[12px] text-text-muted",children:a("repoMesh.promptPreview.rendering")}),p&&s.jsxs("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:[p,s.jsx("button",{type:"button",onClick:()=>void h(),className:"ml-2 underline bg-transparent border-none cursor-pointer text-amber-300",children:a("repoMesh.promptPreview.retry")})]}),!c&&!p&&m!==null&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between text-[11px] text-text-muted",children:[s.jsx("span",{children:a("repoMesh.promptPreview.info")}),g!==null&&s.jsxs("span",{children:[(g/1024).toFixed(1)," KB"]})]}),s.jsx("textarea",{readOnly:!0,value:m,rows:14,className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-secondary font-mono",onFocus:w=>w.currentTarget.select()})]})]})]})}const KI=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function VI(e){const t=KI(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function YI(e){const t=e==null?void 0:e.missions;return Array.isArray(t)?t:[]}function JI(e){return typeof e.goal=="string"&&e.goal?{text:e.goal,truncated:!1}:{text:e.goalPreview??"",truncated:e.goalTruncated===!0}}const QI=["active","paused","completed","abandoned"];function Od(e){return(e.status||"active").toLowerCase()}const XI=8;function ZI({status:e,daemonId:t,meshId:n,sendCommand:r}){const{t:a}=Se("common"),o=l.useMemo(()=>YI(e),[e]),[i,c]=l.useState({}),[d,p]=l.useState({}),[u,m]=l.useState(!1),[f,g]=l.useState(null),[k,h]=l.useState("active"),[v,w]=l.useState(!1),b=l.useMemo(()=>{const A={};for(const M of o){const P=Od(M);A[P]=(A[P]||0)+1}return A},[o]),j=l.useMemo(()=>k==="all"?o:o.filter(A=>Od(A)===k),[o,k]),C=v?j:j.slice(0,XI),y=j.length-C.length,x=!!t&&o.length>0,N=l.useCallback(async()=>{if(t){m(!0),g(null);try{const A=await r(t,"mesh_status",{meshId:n,verbose:!0}),M=VI(A),P=Array.isArray(M==null?void 0:M.missions)?M.missions:[],D={};for(const I of P)I.id&&typeof I.goal=="string"&&I.goal&&(D[I.id]=I.goal);c(I=>({...I,...D}))}catch(A){g(A instanceof Error?A.message:a("repoMesh.missions.errorFetch"))}finally{m(!1)}}},[t,n,r,a]),S=l.useCallback(A=>{p(M=>({...M,[A]:!M[A]})),!d[A]&&!i[A]&&N()},[d,i,N]);return o.length===0?null:s.jsxs(ht,{title:a("repoMesh.missions.title"),description:a("repoMesh.missions.description"),children:[f&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400",children:f}),s.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-1.5",children:[QI.filter(A=>(b[A]||0)>0).map(A=>s.jsxs("button",{type:"button",onClick:()=>{h(A),w(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] capitalize transition-colors ${k===A?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:[A," ",b[A]]},A)),s.jsxs("button",{type:"button",onClick:()=>{h("all"),w(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] transition-colors ${k==="all"?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:["All ",o.length]})]}),j.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:a("repoMesh.missions.empty",{status:k})}),s.jsx("div",{className:"flex flex-col gap-2",children:C.map(A=>{var H;const M=d[A.id]===!0,P=i[A.id],D=JI(A),I=M&&P?P:D.text,_=M&&!P&&D.truncated,W=((H=A.tasks)==null?void 0:H.total)??0;return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 px-3 py-2.5",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-text-primary",title:A.title,children:A.title||A.id}),A.status&&s.jsx("span",{className:"shrink-0 rounded-full border border-border-subtle px-2 py-0.5 text-[10px] uppercase tracking-wide text-text-muted",children:A.status}),W>0&&s.jsx("span",{className:"shrink-0 text-[11px] text-text-muted",children:a("repoMesh.missions.taskCount",{count:W})})]}),I&&s.jsxs("div",{className:`mt-1.5 whitespace-pre-wrap text-[12px] leading-5 text-text-secondary ${M?"max-h-72 overflow-y-auto":"line-clamp-2"}`,children:[I,_&&s.jsx("span",{className:"text-text-muted",children:a("repoMesh.missions.goalUnavailable")})]}),(D.truncated||P)&&x&&s.jsx("button",{type:"button",className:"mt-1.5 text-[12px] text-accent-primary hover:underline disabled:opacity-50",onClick:()=>S(A.id),disabled:u,children:a(M?"repoMesh.missions.showLess":u&&!P?"repoMesh.missions.loading":"repoMesh.missions.showFullGoal")})]},A.id)})}),y>0&&s.jsx("button",{type:"button",className:"mt-2 text-[12px] text-accent-primary hover:underline",onClick:()=>w(!0),children:a("repoMesh.missions.showMore",{count:y})})]})}function Wd(e,t){if(t)return e.modes.find(n=>n.id===t)}function eD(e){return e.modes.find(t=>t.strategy==="pty-parse-default"&&As(t)!=="dangerous")}function tD({config:e,requestedModeId:t,machineAutoApproveEnabled:n,machineDangerousAllowed:r}){const a=Wd(e,e.default),o=a==null?void 0:a.id,i=(t==null?void 0:t.trim())||void 0;if(!n)return{status:"disabled",requestedModeId:i,providerDefaultModeId:o,requestedModeUnknown:!1,downgraded:!1};const c=Wd(e,i),d=!!i&&!c,p=c??a;if(!p||p.strategy==="post-boot-command")return{status:"none",requestedModeId:i,providerDefaultModeId:o,requestedModeUnknown:d,downgraded:!1};if(As(p)==="dangerous"&&!r){const u=eD(e);return{status:u?"downgraded":"none",requestedModeId:i,providerDefaultModeId:o,effectiveMode:u,requestedModeUnknown:d,downgraded:!0}}return{status:d?"invalid_fallback":"requested",requestedModeId:i,providerDefaultModeId:o,effectiveMode:p,requestedModeUnknown:d,downgraded:!1}}function sD(e){const t=[];for(const n of e||[]){if(!n||n.category!=="cli")continue;const r=n.autoApproveModes;if(!r||!Array.isArray(r.modes)||r.modes.length===0)continue;const a=String(n.type||n.id||"").trim();a&&t.push({type:a,label:String(n.displayName||n.name||a),autoApproveModes:r})}return t}function nD({hostDaemonId:e,hostOnline:t,hostWorkspace:n,hostProviders:r,machineAutoApproveEnabled:a,machineDangerousAllowed:o,sendCommand:i}){const{t:c}=Se("common"),d=l.useMemo(()=>sD(r),[r]),[p,u]=l.useState({}),[m,f]=l.useState(!1),[g,k]=l.useState(null),[h,v]=l.useState(!1),[w,b]=l.useState(null),[j,C]=l.useState(!1),[y,x]=l.useState(null),N=!!e&&t&&!!n,S=l.useCallback(async()=>{var I,_,W;if(N){f(!0),k(null);try{const H=await i(e,"read_mesh_json_config",{workspace:n}),L=(H==null?void 0:H.result)??H,O=((I=L==null?void 0:L.providerDefaults)==null?void 0:I.autoApproveModes)||((W=(_=L==null?void 0:L.config)==null?void 0:_.providerDefaults)==null?void 0:W.autoApproveModes),E={};if(O&&typeof O=="object")for(const[T,$]of Object.entries(O))typeof $=="string"&&$.trim()&&(E[T]=$.trim());u(E)}catch(H){k((H==null?void 0:H.message)||c("repoMesh.providerAutoApprove.loadError"))}finally{f(!1)}}},[N,e,n,i,c]);l.useEffect(()=>{S()},[S]);const A=l.useCallback((I,_)=>{C(!1),u(W=>{const H={...W};return _&&_.trim()?H[I]=_.trim():delete H[I],H})},[]),M=l.useCallback((I,_)=>{if(As(_)==="dangerous"){x({type:I,mode:_});return}A(I,_.id)},[A]),P=l.useCallback(()=>{y&&A(y.type,y.mode.id),x(null)},[A,y]),D=l.useCallback(async()=>{if(N){v(!0),b(null),C(!1);try{const I=await i(e,"set_mesh_provider_defaults",{workspace:n,autoApproveModes:p,merge:!1,write:!0}),_=(I==null?void 0:I.result)??I;if((_==null?void 0:_.success)===!1)throw new Error((_==null?void 0:_.error)||c("repoMesh.providerAutoApprove.saveError"));C(!0),await S()}catch(I){b((I==null?void 0:I.message)||c("repoMesh.providerAutoApprove.saveError"))}finally{v(!1)}}},[N,e,n,S,p,i,c]);return s.jsxs(ht,{title:c("repoMesh.providerAutoApprove.title"),description:c("repoMesh.providerAutoApprove.subtitle"),collapsible:!0,defaultOpen:!1,children:[N?m?s.jsx("div",{className:"text-[13px] text-text-muted",children:c("repoMesh.providerAutoApprove.loading")}):d.length===0?s.jsx("div",{className:"text-[13px] text-text-muted",children:c("repoMesh.providerAutoApprove.noProviders")}):s.jsxs("div",{className:"space-y-6",children:[g&&s.jsx(Ht,{variant:"error",onDismiss:()=>k(null),children:g}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/40 p-3.5",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:c("repoMesh.providerAutoApprove.machineSection.title")}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:c("repoMesh.providerAutoApprove.machineSection.hint")}),s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2 text-[11px]",children:[s.jsx("span",{className:`rounded-full border px-2 py-0.5 font-semibold ${a?"border-status-online/25 bg-status-online/10 text-status-online":"border-border-subtle bg-bg-tertiary/40 text-text-muted"}`,children:c(a?"repoMesh.providerAutoApprove.machineSection.autoApproveOn":"repoMesh.providerAutoApprove.machineSection.autoApproveOff")}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 font-semibold ${o?"border-status-error/30 bg-status-error/10 text-status-error":"border-border-subtle bg-bg-tertiary/40 text-text-muted"}`,children:c(o?"repoMesh.providerAutoApprove.machineSection.dangerousOn":"repoMesh.providerAutoApprove.machineSection.dangerousOff")})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:c("repoMesh.providerAutoApprove.machineSection.editHint")})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:c("repoMesh.providerAutoApprove.repoSection.title")}),s.jsx("div",{className:"text-[11px] text-text-muted",children:c("repoMesh.providerAutoApprove.repoSection.hint")})]}),s.jsx("div",{className:"space-y-5",children:d.map(I=>{const _=p[I.type],W=tD({config:I.autoApproveModes,requestedModeId:_,machineAutoApproveEnabled:a,machineDangerousAllowed:o});return s.jsxs("div",{className:"rounded-xl border border-border-subtle p-3.5",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary",children:I.label}),s.jsx("button",{type:"button",className:"text-[11px] text-text-muted underline decoration-dotted hover:text-text-primary disabled:opacity-40",onClick:()=>A(I.type,void 0),disabled:!_||h,children:c("repoMesh.providerAutoApprove.repoSection.clear")})]}),s.jsx(Rm,{config:I.autoApproveModes,selectedModeId:_||"",disabled:h,onSelectMode:H=>M(I.type,H)}),!_&&s.jsx("div",{className:"mt-1.5 text-[11px] text-text-muted",children:c("repoMesh.providerAutoApprove.repoSection.usesProviderDefault")}),s.jsx(rD,{effective:W,config:I.autoApproveModes})]},I.type)})}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:c("repoMesh.providerAutoApprove.effectiveSection.title")}),s.jsx("div",{className:"text-[11px] text-text-muted",children:c("repoMesh.providerAutoApprove.effectiveSection.hint")})]}),w&&s.jsx(Ht,{variant:"error",onDismiss:()=>b(null),children:w}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("button",{type:"button",className:"rounded-lg bg-accent-primary px-4 py-2 text-sm font-semibold text-white disabled:opacity-50",onClick:()=>void D(),disabled:h,children:c(h?"repoMesh.providerAutoApprove.saving":"repoMesh.providerAutoApprove.save")}),j&&s.jsx("span",{className:"text-[12px] text-status-online",children:c("repoMesh.providerAutoApprove.saved")})]})]}):s.jsx("div",{className:"text-[13px] text-text-muted",children:c("repoMesh.providerAutoApprove.noHostDaemon")}),y&&s.jsx(Em,{mode:y.mode,onConfirm:P,onCancel:()=>x(null)}),y&&s.jsx("div",{className:"fixed inset-x-0 bottom-6 z-[60] mx-auto max-w-lg px-4",children:s.jsxs("div",{className:"rounded-xl border border-status-error/40 bg-bg-primary p-3.5 shadow-lg",children:[s.jsx("div",{className:"text-sm font-semibold text-status-error",children:c("repoMesh.providerAutoApprove.dangerous.sharedWarningTitle")}),s.jsx("div",{className:"mt-1 text-[12px] text-text-muted",children:c("repoMesh.providerAutoApprove.dangerous.sharedWarning")})]})})]})}function rD({effective:e,config:t}){var c,d,p;const{t:n}=Se("common"),r=u=>{var m;return(u?(m=t.modes.find(f=>f.id===u))==null?void 0:m.label:void 0)||u||""};let a,o="ok";switch(e.status){case"requested":a=n("repoMesh.providerAutoApprove.effectiveSection.statusRequested",{mode:((c=e.effectiveMode)==null?void 0:c.label)||""});break;case"invalid_fallback":a=n("repoMesh.providerAutoApprove.effectiveSection.statusInvalidFallback",{mode:((d=e.effectiveMode)==null?void 0:d.label)||""}),o="warn";break;case"downgraded":a=n("repoMesh.providerAutoApprove.effectiveSection.statusDowngraded",{requested:r(e.requestedModeId)||r(e.providerDefaultModeId),mode:((p=e.effectiveMode)==null?void 0:p.label)||""}),o="warn";break;case"disabled":a=n("repoMesh.providerAutoApprove.effectiveSection.statusDisabled"),o="muted";break;default:a=n("repoMesh.providerAutoApprove.effectiveSection.statusNone"),o="muted"}const i=o==="ok"?"border-status-online/25 bg-status-online/5 text-text-secondary":o==="warn"?"border-status-warning/30 bg-status-warning/5 text-status-warning":"border-border-subtle bg-bg-tertiary/30 text-text-muted";return s.jsxs("div",{className:`mt-3 flex items-center gap-2 rounded-lg border px-3 py-2 text-[12px] ${i}`,children:[e.effectiveMode&&s.jsx(Lm,{risk:As(e.effectiveMode)}),s.jsx("span",{className:"min-w-0",children:a})]})}const aD=["","low","medium","high"],oD={easy:"Easy",medium:"Medium",difficult:"Difficult",freeform:"Freeform"};function Ud(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 Gd(e){const t=e.provider.trim();if(!t)return null;const n=e.model.trim(),r=e.thinkingLevel.trim()||void 0,a=Number(e.maxParallel),o=Number.isFinite(a)&&a>0?Math.floor(a):void 0;return{provider:t,...n?{model:n}:{},...r?{thinkingLevel:r}:{},...e.difficulty.length?{difficulty:e.difficulty}:{},...e.capability.length?{capability:e.capability}:{},...o!==void 0?{maxParallel:o}:{}}}function iD(){return{provider:"",model:"",thinkingLevel:"",difficulty:[],capability:[],maxParallel:""}}const Gs="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function lD({slots:e,availableProviders:t,saving:n,onSave:r}){const{t:a}=Se("common"),[o,i]=l.useState(()=>e.map(Ud)),c=l.useMemo(()=>JSON.stringify(e),[e]);l.useEffect(()=>{i(e.map(Ud))},[c]);const d=l.useMemo(()=>[...new Set(t.map(b=>b.type).filter(Boolean))],[t]),p=l.useMemo(()=>Bp(t),[t]),u=l.useMemo(()=>{const b=o.map(Gd).filter(Boolean);return JSON.stringify(b)!==JSON.stringify(e)},[o,e]),m=(b,j)=>i(C=>C.map((y,x)=>x===b?{...y,...j}:y)),f=(b,j)=>i(C=>C.map((y,x)=>{var A;if(x!==b)return y;const N=((A=p.get(j))==null?void 0:A.models)??[],S=!y.model||N.length===0||N.includes(y.model);return{...y,provider:j,...S?{}:{model:""}}})),g=b=>i(j=>j.filter((C,y)=>y!==b)),k=()=>i(b=>[...b,iD()]),h=(b,j)=>i(C=>{const y=b+j;if(y<0||y>=C.length)return C;const x=[...C];return[x[b],x[y]]=[x[y],x[b]],x}),v=(b,j)=>i(C=>C.map((y,x)=>{if(x!==b)return y;const N=y.difficulty.includes(j);return{...y,difficulty:N?y.difficulty.filter(S=>S!==j):[...y.difficulty,j]}})),w=()=>r(o.map(Gd).filter(Boolean));return s.jsxs("div",{className:"flex flex-col gap-2",onClick:b=>b.stopPropagation(),children:[o.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:a("repoMesh.slotEditor.empty")}),o.map((b,j)=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/40 p-2.5",children:[s.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[s.jsxs("span",{className:"text-[11px] font-semibold text-text-muted",children:["#",j+1]}),s.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:j===0,onClick:()=>h(j,-1),title:a("repoMesh.slotEditor.moveUp"),children:"↑"}),s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:j===o.length-1,onClick:()=>h(j,1),title:a("repoMesh.slotEditor.moveDown"),children:"↓"}),s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-status-error/30 text-status-error hover:bg-status-error/10",onClick:()=>g(j),"aria-label":a("repoMesh.slotEditor.removeSlot"),children:s.jsx(Mt,{size:12})})]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:a("repoMesh.slotEditor.provider")}),d.length>0?s.jsxs("select",{className:Gs,value:b.provider,onChange:C=>f(j,C.target.value),children:[s.jsx("option",{value:"",children:a("repoMesh.slotEditor.select")}),d.map(C=>s.jsx("option",{value:C,children:C},C)),b.provider&&!d.includes(b.provider)&&s.jsx("option",{value:b.provider,children:b.provider})]}):s.jsx("input",{className:Gs,value:b.provider,placeholder:"claude-cli",onChange:C=>m(j,{provider:C.target.value})})]}),(()=>{var S;const C=p.get(b.provider),y=(C==null?void 0:C.models)??[],x=(S=C==null?void 0:C.thinking)!=null&&S.length?["",...C.thinking]:aD,N=!!b.model&&y.length>0&&!y.includes(b.model);return s.jsxs(s.Fragment,{children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:a("repoMesh.slotEditor.model")}),y.length>0&&!N?s.jsxs("select",{className:Gs,value:y.includes(b.model)?b.model:"",onChange:A=>m(j,{model:A.target.value==="__custom__"?" ":A.target.value}),children:[s.jsx("option",{value:"",children:a("repoMesh.slotEditor.providerDefault")}),y.map(A=>s.jsx("option",{value:A,children:A},A)),s.jsx("option",{value:"__custom__",children:a("repoMesh.slotEditor.custom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:Gs,value:b.model.trim(),placeholder:b.provider?`${b.provider} model`:a("repoMesh.slotEditor.modelPlaceholder"),onChange:A=>m(j,{model:A.target.value})}),y.length>0&&s.jsx("button",{type:"button",className:"self-start bg-transparent border-none cursor-pointer p-0 text-[10px] text-text-muted hover:underline",onClick:()=>m(j,{model:""}),children:a("repoMesh.slotEditor.backToModelList")})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:a("repoMesh.slotEditor.thinking")}),s.jsx("select",{className:Gs,value:b.thinkingLevel,onChange:A=>m(j,{thinkingLevel:A.target.value}),children:x.map(A=>s.jsx("option",{value:A,children:A||a("repoMesh.slotEditor.thinkingDefault")},A||"_default"))})]})]})})()]}),s.jsxs("div",{className:"mt-2",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:a("repoMesh.slotEditor.difficulty")}),s.jsx("div",{className:"mt-1 flex flex-wrap gap-1.5",children:_y.map(C=>{const y=b.difficulty.includes(C);return s.jsx("button",{type:"button",className:`rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors ${y?"border-accent-primary/60 bg-accent-primary/15 text-accent-primary":"border-border-subtle bg-bg-primary/60 text-text-muted hover:text-text-primary"}`,onClick:()=>v(j,C),children:oD[C]},C)})})]}),s.jsxs("div",{className:"mt-2 grid grid-cols-1 sm:grid-cols-2 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:a("repoMesh.slotEditor.capabilityTags")}),s.jsx("input",{className:Gs,value:b.capability.join(", "),placeholder:"worktree, os=darwin",onChange:C=>m(j,{capability:C.target.value.split(",").map(y=>y.trim()).filter(Boolean)})})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:a("repoMesh.slotEditor.maxParallel")}),s.jsx("input",{type:"number",inputMode:"numeric",min:1,className:Gs,value:b.maxParallel,placeholder:a("repoMesh.slotEditor.maxParallelPlaceholder"),onChange:C=>m(j,{maxParallel:C.target.value})})]})]})]},j)),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1",onClick:k,children:[s.jsx(Wi,{size:13})," ",a("repoMesh.slotEditor.addSlot")]}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm ml-auto",onClick:w,disabled:!!n||!u,children:a(n?"repoMesh.slotEditor.saving":"repoMesh.slotEditor.saveSlots")})]})]})}function cD(e){const t=new Map;for(const n of e)n!=null&&n.id&&t.set(n.id,Tn(n.availableProviders||[]));return t}function dD(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 uD(e){var d,p,u;const t=e,n=[],r=Array.isArray(t.capabilities)?t.capabilities:[];for(const m of r){const f=typeof m=="string"?m.trim():"";f&&n.push({tag:f,custom:!0})}const a=(((d=t.userOverrides)==null?void 0:d.platform)||t.reportedPlatform||"").toString().trim(),o=(((p=t.userOverrides)==null?void 0:p.arch)||t.reportedArch||"").toString().trim();a&&n.push({tag:`os=${a}`,custom:!1}),o&&n.push({tag:`arch=${o}`,custom:!1});const i=Array.isArray((u=t.policy)==null?void 0:u.providerPriority)?String(t.policy.providerPriority[0]||"").trim():"";i&&n.push({tag:`provider=${i}`,custom:!1});const c=typeof t.worktreeBranch=="string"?t.worktreeBranch.trim():"";return t.isLocalWorktree===!0&&c&&n.push({tag:`worktree=${c}`,custom:!1}),n}function pD(e){const t=e.capabilities;return Array.isArray(t)?t.map(n=>typeof n=="string"?n.trim():"").filter(Boolean):[]}const mD=["os=","arch=","provider=","worktree=","converge="];function hD({node:e,saving:t,onSave:n}){const{t:r}=Se("common"),a=l.useMemo(()=>uD(e).filter(h=>!h.custom),[e]),o=l.useMemo(()=>pD(e),[e]),[i,c]=l.useState(o),[d,p]=l.useState(""),u=JSON.stringify(i)!==JSON.stringify(o),f=(h=>{const v=h.trim();return v?/\s/.test(v)?r("repoMesh.tagEditor.noSpaces"):mD.some(w=>v.toLowerCase().startsWith(w))?r("repoMesh.tagEditor.reservedPrefix"):i.includes(v)?r("repoMesh.tagEditor.alreadyAdded"):null:null})(d);function g(){const h=d.trim();!h||f||(c(v=>[...v,h]),p(""))}function k(h){c(v=>v.filter(w=>w!==h))}return s.jsxs("div",{className:"mt-2",onClick:h=>h.stopPropagation(),children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wide text-text-muted mr-1",children:r("repoMesh.tagEditor.routingTags")}),a.map(h=>s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-1.5 py-0.5 font-mono text-[10px] text-text-muted",title:r("repoMesh.tagEditor.autoDerivedTitle"),children:h.tag},h.tag)),i.map(h=>s.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 font-mono text-[10px] text-accent-primary",title:r("repoMesh.tagEditor.customTagTitle"),children:[h,s.jsx("button",{type:"button",className:"text-accent-primary/70 hover:text-accent-primary bg-transparent border-none cursor-pointer p-0 leading-none",onClick:()=>k(h),disabled:t,"aria-label":r("repoMesh.tagEditor.remove",{tag:h}),children:"×"})]},h))]}),s.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-2",children:[s.jsx("input",{type:"text",value:d,onChange:h=>p(h.target.value),onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),g())},placeholder:r("repoMesh.tagEditor.addPlaceholder"),disabled:t,className:"min-w-[12rem] flex-1 px-2 py-1 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-primary"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:g,disabled:t||!d.trim()||!!f,children:r("repoMesh.tagEditor.add")}),u&&s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>n(i),disabled:t,children:r(t?"repoMesh.tagEditor.saving":"repoMesh.tagEditor.saveTags")})]}),f&&s.jsx("div",{className:"mt-1 text-[11px] text-amber-400",children:f}),i.length===0&&a.length===0&&s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:r("repoMesh.tagEditor.empty")})]})}function fD(e,t){return t.filter(n=>n.status!=="assigned"?!1:(n.assignedNodeId||n.nodeId)===e.id)}function bD(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 gD(e){var r;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>n.has(a)?!1:(n.add(a),!0))}function xD(e){const t=gD(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 vD(e){return e.isLocalWorktree===!0}function yD(e,t){const n=t;return[...Array.isArray(n==null?void 0:n.cliSessions)?n.cliSessions:[],...Array.isArray(n==null?void 0:n.acpSessions)?n.acpSessions:[],...Array.isArray(n==null?void 0:n.sessions)?n.sessions:[]].filter(a=>{var o;return((o=a==null?void 0:a.settings)==null?void 0:o.meshNodeId)===e.id||(a==null?void 0:a.workspace)===e.workspace}).map(a=>{var o;return{id:a.sessionId||a.id||a.instanceId||"unknown",provider:a.providerType||a.cliType||a.acpType||a.type||"unknown",status:a.status||((o=a.activeChat)==null?void 0:o.status)||"unknown"}})}function qd(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function wD(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 kD({nodes:e,meshQueue:t,activeDaemon:n,daemons:r,selectedMeshId:a,userName:o,features:i,coordinatorDaemonId:c,availableCliProviders:d,savingNodeSlotsId:p,onUpdateNodeSlots:u,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:f,nodeSystemPromptDrafts:g,onNodeSystemPromptDraftChange:k,savingNodeSystemPromptId:h,onSaveNodeSystemPrompt:v,selectedNodeId:w,onSelectNode:b,showAddNode:j,onShowAddNode:C,onCancelAddNode:y,nodeWorkspace:x,onNodeWorkspaceChange:N,nodeProviderPriority:S,onNodeProviderPriorityChange:A,nodeDaemonId:M,onNodeDaemonIdChange:P,nodeCustomPath:D,onNodeCustomPathChange:I,nodePickerWorkspaces:_,nodePickerProviders:W,attachableDaemons:H,onAddNode:L,onRemoveNode:O}){const{t:E}=Se("common"),T=l.useMemo(()=>cD(r),[r]),$=l.useMemo(()=>e.filter(R=>!vD(R)),[e]);return s.jsxs(ht,{title:i.addNodeDaemonPicker?E("repoMesh.nodeList.title",{count:$.length}):E("repoMesh.nodeList.titleNoCount"),description:i.addNodeDaemonPicker?E("repoMesh.nodeList.descriptionCloud"):E("repoMesh.nodeList.descriptionStandalone"),children:[i.addNodeDaemonPicker&&s.jsxs("div",{className:"mb-4 rounded-xl border border-border-subtle bg-bg-secondary/60 p-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:E("repoMesh.nodeList.daemonCandidates")}),s.jsx("div",{className:"text-[12px] text-text-muted",children:E("repoMesh.nodeList.daemonCandidatesHint")})]}),s.jsx("span",{className:"text-[11px] text-text-muted",children:E("repoMesh.nodeList.available",{count:H.length})})]}),r.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:E("repoMesh.nodeList.noDaemonsAvailable")}):H.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:E("repoMesh.nodeList.allDaemonsAttached")}):s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:H.map(R=>s.jsxs("button",{type:"button",className:`text-left rounded-lg border px-3 py-2 transition-colors ${R.id===c?"border-accent-primary/50 bg-accent-primary/10":"border-border-subtle bg-bg-primary hover:border-border-default"}`,onClick:()=>{P(R.id),N(""),I(!1),A(gr(Tn(R.availableProviders||[]))),C()},children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-sm font-medium truncate",children:qd(R)}),R.id===c&&s.jsx("span",{className:"text-[10px] text-accent-primary",children:E("repoMesh.nodeList.selectedHost")})]}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted font-mono truncate",children:R.id}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:E("repoMesh.nodeList.workspacesDetected",{count:(R.workspaces||[]).length})})]},R.id))})]}),!j&&s.jsxs("button",{className:"btn btn-primary btn-sm mb-4 inline-flex items-center gap-1.5",onClick:C,children:[s.jsx(_I,{size:13})," ",i.addNodeDaemonPicker?E("repoMesh.nodeList.attachMachine"):E("repoMesh.nodeList.addNode")]}),j&&s.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass animate-[fadeIn_0.3s_ease-out]",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h4",{className:"text-sm font-bold",children:i.addNodeDaemonPicker?E("repoMesh.nodeList.attachMachineTitle"):E("repoMesh.nodeList.addNodeTitle")}),s.jsx("button",{onClick:()=>{y(),P(""),I(!1)},className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(Mt,{size:16})})]}),i.addNodeDaemonPicker&&s.jsx(jt,{label:E("repoMesh.nodeList.machine"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:M,onChange:R=>{var G;P(R.target.value),N(""),I(!1),A(gr(Tn(((G=r.find(Q=>Q.id===R.target.value))==null?void 0:G.availableProviders)||[])))},children:[s.jsx("option",{value:"",children:E("repoMesh.nodeList.selectMachine")}),r.map(R=>s.jsx("option",{value:R.id,children:qd(R)},R.id))]})}),(i.addNodeDaemonPicker?M:!0)&&s.jsx(jt,{label:E("repoMesh.nodeList.workspacePath"),children:i.addNodeDaemonPicker&&!D&&_.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex flex-col gap-1.5 mb-2",children:_.map(R=>s.jsxs("button",{type:"button",className:`text-left text-xs px-3 py-2 rounded-lg border transition-colors ${x===R.path?"border-accent-primary bg-accent-primary/10 text-text-primary":"border-border-subtle bg-bg-primary hover:bg-violet-500/10 text-text-primary"}`,onClick:()=>N(R.path),children:[s.jsx("span",{className:"font-medium block truncate",children:R.label||R.path.split("/").pop()}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:R.path})]},R.id||R.path))}),s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{I(!0),N("")},children:E("repoMesh.nodeList.enterCustomPath")})]}):s.jsx(s.Fragment,{children:i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[s.jsx(ds,{value:x,onChange:R=>N(R.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:R=>{R.key==="Enter"&&L()}}),_.length>0&&s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0 mt-1",onClick:()=>{I(!1),N("")},children:E("repoMesh.nodeList.pickFromSaved")})]}):(()=>{var Q;const R=Array.isArray(n==null?void 0:n.workspaces)?n.workspaces:[],G=`mesh-add-node-workspaces-${a||"new"}`;return s.jsxs(s.Fragment,{children:[s.jsx(ds,{value:x,onChange:re=>N(re.target.value),placeholder:((Q=R[0])==null?void 0:Q.path)||"/Users/dev/projects/myapp",list:R.length>0?G:void 0,autoFocus:!0}),R.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("datalist",{id:G,children:R.map(re=>s.jsx("option",{value:re.path,children:re.label||re.path},re.id||re.path))}),s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:R.slice(0,6).map(re=>s.jsx("button",{type:"button",onClick:()=>N(re.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:re.path,children:re.label||re.path.split("/").filter(Boolean).pop()||re.path},re.id||re.path))})]})]})})()})}),s.jsx(jt,{label:E("repoMesh.nodeList.preferredTools"),hint:E("repoMesh.nodeList.preferredToolsHint"),children:s.jsx(AS,{value:S,availableProviders:i.addNodeDaemonPicker?W:d,onChange:A})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:L,disabled:!x.trim()||i.addNodeDaemonPicker&&!M,className:"btn btn-primary btn-sm",children:E("repoMesh.nodeList.add")}),s.jsx("button",{onClick:()=>{y(),P(""),I(!1)},className:"btn btn-secondary btn-sm",children:E("repoMesh.nodeList.cancel")})]})]}),i.addNodeDaemonPicker&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-300 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:E("repoMesh.nodeList.setupInventoryWarning")}),$.length===0?s.jsx(Ga,{icon:s.jsx(Nn,{}),title:E("repoMesh.nodeList.emptyTitle"),description:E("repoMesh.nodeList.emptyDescription")}):s.jsx("div",{className:"flex flex-col gap-2",children:$.map(R=>{var ue;const G=xD(R),Q=fD(R,t),re=yD(R,n),J=w===R.id,X=R.status||R.machine_status||(Q.length>0||re.length>0?"active":"enabled");return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary transition-colors ${i.addNodeDaemonPicker?"bg-bg-glass border-border-subtle rounded-xl px-5 py-4":`cursor-pointer ${J?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`}`,role:i.addNodeDaemonPicker?void 0:"button",tabIndex:i.addNodeDaemonPicker?void 0:0,onClick:i.addNodeDaemonPicker?void 0:()=>b(J?null:R.id),onKeyDown:i.addNodeDaemonPicker?void 0:se=>{(se.key==="Enter"||se.key===" ")&&(se.preventDefault(),b(J?null:R.id))},children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.addNodeDaemonPicker?s.jsx("span",{className:"font-semibold text-sm text-text-primary truncate",children:R.machine_label||R.machine_nickname||R.hostname||R.workspace}):s.jsx("span",{className:"text-sm font-medium",children:R.workspace.split("/").pop()}),i.addNodeDaemonPicker&&s.jsx($I,{status:X}),i.addNodeDaemonPicker&&s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:E("repoMesh.nodeList.setupInventory")})]}),i.addNodeDaemonPicker&&s.jsx("div",{className:"text-[11px] text-text-muted",children:E("repoMesh.nodeList.ownerMachine",{owner:wD(r.find(se=>se.id===String(R.daemon_id||"")),o),machine:R.machine_label||R.daemon_id||R.workspace})}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:R.workspace}),s.jsx(hD,{node:R,saving:m===R.id,onSave:se=>f(R,se)}),i.addNodeDaemonPicker&&s.jsx("div",{className:"mt-2 text-[11px] text-amber-300",children:E("repoMesh.nodeList.liveDetailGraphOwned")}),s.jsxs("div",{className:"mt-3 max-w-2xl",onClick:se=>se.stopPropagation(),children:[s.jsx(jt,{label:E("repoMesh.nodeList.slotsLabel"),hint:E("repoMesh.nodeList.slotsHint"),children:s.jsx(lD,{slots:Array.isArray((ue=R.policy)==null?void 0:ue.slots)?R.policy.slots:[],availableProviders:dD(R,T),saving:p===R.id,onSave:se=>u(R,se)})}),i.nodeInstruction&&s.jsxs(jt,{label:E("repoMesh.nodeList.nodeInstruction"),hint:E("repoMesh.nodeList.nodeInstructionHint"),children:[s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:3,value:g[R.id]??"",onChange:se=>{const B=se.target.value;k(R.id,B)},onClick:se=>se.stopPropagation(),disabled:h===R.id,placeholder:E("repoMesh.nodeList.nodeInstructionPlaceholder")}),s.jsx("div",{className:"mt-2 flex items-center gap-2",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:se=>{se.stopPropagation(),v(R)},disabled:h===R.id,children:h===R.id?E("repoMesh.nodeList.saving"):E("repoMesh.nodeList.saveInstruction")})})]})]})]}),s.jsx("button",{className:`transition-colors bg-transparent border-none cursor-pointer ${i.addNodeDaemonPicker?"btn btn-sm text-text-muted hover:text-red-400":"text-text-muted hover:text-red-400"}`,onClick:se=>{se.stopPropagation(),O(R.id)},title:E("repoMesh.nodeList.removeNode"),children:s.jsx(EI,{size:14})})]}),s.jsxs("details",{className:"mt-3 group",onClick:se=>se.stopPropagation(),children:[s.jsxs("summary",{className:"cursor-pointer select-none text-[12px] text-text-muted hover:text-text-secondary inline-flex items-center gap-1",children:[s.jsx("span",{className:"transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"})," ",E("repoMesh.nodeList.details")]}),s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary/60 p-3 text-[12px] text-text-muted",children:[s.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:E("repoMesh.nodeList.nodeId")})," ",s.jsx("span",{className:"font-mono break-all",children:R.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:E("repoMesh.nodeList.launchReady")})," ",s.jsx("span",{className:G.configured?"text-green-400":"text-amber-400",children:G.configured?E("repoMesh.nodeList.launchReadyYes"):E("repoMesh.nodeList.launchReadyNo")})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:E("repoMesh.nodeList.repoRoot")})," ",s.jsx("span",{className:"font-mono break-all",children:R.repoRoot||R.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:E("repoMesh.nodeList.activeSessionsLabel")})," ",re.length]}),i.addNodeDaemonPicker&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:E("repoMesh.nodeList.added")})," ",new Date(R.created_at||R.createdAt||Date.now()).toLocaleDateString()]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:E("repoMesh.nodeList.activeQueueAssignments")}),Q.length===0?s.jsx("div",{children:E("repoMesh.nodeList.noActiveAssignment")}):s.jsx("ul",{className:"m-0 pl-4",children:Q.map(se=>s.jsx("li",{className:"font-mono",children:bD(se)},se.id))})]}),re.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:E("repoMesh.nodeList.activeSessions")}),s.jsx("ul",{className:"m-0 pl-4",children:re.map(se=>s.jsxs("li",{className:"font-mono",children:[se.provider," / ",se.status," / ",se.id]},se.id))})]})]})]})]},R.id)})})]})}function Qr(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function SD({daemons:e,coordinatorDaemonId:t,onCoordinatorDaemonIdChange:n,coordinatorCliType:r,onCoordinatorCliTypeChange:a,launchingCoordinator:o,launchResult:i,isHostNodeAttached:c,selectedHostNode:d,hostPinned:p,hostLabel:u,hostOnline:m,hostRebindDaemonId:f,onHostRebindDaemonIdChange:g,onLaunchCoordinator:k}){const{t:h}=Se("common"),v=s.jsx(jt,{label:h("repoMesh.host.coordinatorProvider"),hint:h("repoMesh.host.coordinatorProviderHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:r,onChange:j=>a(j.target.value),children:[s.jsx("option",{value:"",children:h("repoMesh.host.useNodePriority")}),s.jsx("option",{value:"claude-cli",children:"Claude Code"}),s.jsx("option",{value:"codex-cli",children:"Codex"}),s.jsx("option",{value:"gemini-cli",children:"Gemini"}),s.jsx("option",{value:"hermes-cli",children:"Hermes"})]})}),w=i&&s.jsx("div",{className:"mt-3 text-[12px] text-green-400 bg-green-500/10 border border-green-500/20 rounded-lg px-3 py-2",children:i});if(p)return s.jsxs(ht,{title:h("repoMesh.host.title"),description:h("repoMesh.host.descriptionSet"),children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsxs("span",{className:`inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-[13px] text-text-primary ${m?"border-accent-primary/40 bg-accent-primary/10":"border-amber-500/40 bg-amber-500/10"}`,children:[s.jsx("span",{className:"text-text-muted",children:h("repoMesh.host.hostLabel")}),s.jsx("span",{className:"font-medium",children:u||h("repoMesh.host.unknown")}),s.jsxs("span",{className:m?"text-text-muted":"text-amber-400",children:["· ",h(m?"repoMesh.host.online":"repoMesh.host.offline")]})]}),(d==null?void 0:d.workspace)&&s.jsxs("span",{className:"text-[12px] text-text-muted",children:[h("repoMesh.host.hostNode")," ",s.jsx("span",{className:"font-mono text-text-secondary",children:d.workspace})]})]}),!m&&s.jsxs("div",{className:"mt-4",children:[s.jsxs(Ht,{variant:"warning",className:"mb-3",children:[s.jsx("strong",{children:h("repoMesh.host.hostOffline")})," ",h("repoMesh.host.hostOfflineText")]}),e.length>0?s.jsx(jt,{label:h("repoMesh.host.reconnectToCommand"),hint:h("repoMesh.host.reconnectToCommandHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:f,onChange:j=>g(j.target.value),children:[s.jsx("option",{value:"",children:h("repoMesh.host.waitForHost")}),e.map(j=>s.jsx("option",{value:j.id,children:Qr(j)},j.id))]})}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:h("repoMesh.host.noDaemonsToRoute")})]}),s.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-[180px_auto] items-end",children:[v,s.jsx("button",{className:"btn btn-primary btn-sm",onClick:k,disabled:o||!t,title:t?void 0:h("repoMesh.host.noCommandTarget"),children:h(o?"repoMesh.host.launching":"repoMesh.host.launchHost")})]}),w]});const b=e.find(j=>j.id===t);return s.jsxs(ht,{title:h("repoMesh.host.title"),description:h("repoMesh.host.descriptionUnset"),children:[s.jsxs(Ht,{variant:"info",className:"mb-4",children:[s.jsx("strong",{children:h("repoMesh.host.setHostBanner")})," ",h("repoMesh.host.setHostBannerText")]}),e.length>0?s.jsxs(s.Fragment,{children:[t?s.jsx("div",{className:"mb-3 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:c?s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:Qr(b)}),d!=null&&d.workspace?s.jsxs(s.Fragment,{children:[" · setup node ",s.jsx("span",{className:"font-mono text-text-secondary",children:d.workspace})]}):null,". Launching sets this daemon as the mesh host."]}):s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:Qr(b)}),". Attach one of its workspaces as a node first, then launch to set the host."]})}):s.jsx(jt,{label:h("repoMesh.host.hostDaemon"),hint:h("repoMesh.host.hostDaemonHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:"",onChange:j=>n(j.target.value),children:[s.jsx("option",{value:"",children:h("repoMesh.host.resolvingHost")}),e.map(j=>s.jsx("option",{value:j.id,children:Qr(j)},j.id))]})}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-[180px_auto] items-end mt-3",children:[v,s.jsx("button",{className:"btn btn-primary btn-sm",onClick:k,disabled:!t||!c||o,title:t?c?void 0:h("repoMesh.host.attachNodeFirst"):h("repoMesh.host.pickHostFirst"),children:h(o?"repoMesh.host.launching":"repoMesh.host.launchHostSetsHost")})]})]}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:h("repoMesh.host.noDaemonsToHost")}),w]})}function CD({meshId:e,availableCliAgents:t}){const{t:n}=Se(),r=t.find(o=>{const i=o.id.toLowerCase();return i==="hermes-cli"||i.includes("hermes")||o.name.toLowerCase().includes("hermes")}),a=cm(r==null?void 0:r.meshCoordinator,{meshId:e});return a?s.jsx(ht,{title:n("repoMesh.hermesMcp.title"),description:n("repoMesh.hermesMcp.description"),children:s.jsx(Pm,{setup:a,providerName:(r==null?void 0:r.name)||n("repoMesh.hermesMcp.fallbackProvider")})}):null}const Ko=[{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."}],jD=[{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 ND(e){return e==="smart"?"fitness":e==="spread"?"least_loaded":"first_eligible"}function AD(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 MD={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,schedulingStrategy:"first_eligible",sessionCleanupOnNodeRemove:"preserve"};function Ii(e){return{...MD,...(e==null?void 0:e.policy)||{}}}function TD(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 ID({selectedMesh:e,error:t,onDismissError:n,onBack:r,onDelete:a,displayedMeshStatus:o,graphLoading:i,graphError:c,onRefreshGraph:d,savingPolicy:p,onUpdatePolicy:u,coordinatorPromptDraft:m,onCoordinatorPromptDraftChange:f,savingCoordinatorPrompt:g,onSaveCoordinatorPrompt:k,daemons:h,coordinatorDaemonId:v,onCoordinatorDaemonIdChange:w,coordinatorCliType:b,onCoordinatorCliTypeChange:j,launchingCoordinator:C,launchResult:y,isHostNodeAttached:x,selectedHostNode:N,hostPinned:S,hostLabel:A,hostOnline:M,hostRebindDaemonId:P,onHostRebindDaemonIdChange:D,onLaunchCoordinator:I,activeDaemon:_,activeDaemonId:W,meshQueue:H,userName:L,availableCliProviders:O,savingNodeSlotsId:E,onUpdateNodeSlots:T,savingNodeCapabilitiesId:$,onUpdateNodeCapabilities:R,nodeSystemPromptDrafts:G,onNodeSystemPromptDraftChange:Q,savingNodeSystemPromptId:re,onSaveNodeSystemPrompt:J,selectedNodeId:X,onSelectNode:ue,showAddNode:se,onShowAddNode:B,onCancelAddNode:ie,nodeWorkspace:K,onNodeWorkspaceChange:le,nodeProviderPriority:je,onNodeProviderPriorityChange:we,nodeDaemonId:ke,onNodeDaemonIdChange:he,nodeCustomPath:U,onNodeCustomPathChange:q,nodePickerWorkspaces:Z,nodePickerProviders:Y,attachableDaemons:fe,onAddNode:Me,onRemoveNode:de,availableCliAgents:F,features:me,sendCommand:ce}){var Be,it;const{t:z}=Se("common"),ge=Ii(e),Ce=e.nodes||[],Ne=Ce.some(ae=>{var lt;const _e=Number((lt=ae.policy)==null?void 0:lt.schedulingPriority);return Number.isFinite(_e)&&_e!==0}),He=!ge.schedulingStrategy,Ze=l.useMemo(()=>Ce.some(ae=>{var _e;return Array.isArray((_e=ae.policy)==null?void 0:_e.slots)&&ae.policy.slots.length>0}),[Ce]),Ye=He?Ze?"smart":Ce.length>=2?"spread":null:null,[ot,be]=l.useState(!1),Pe=!!W&&!!e.id;return s.jsxs(jr,{icon:s.jsx(ts,{}),title:e.name,subtitle:e.repoIdentity||e.repo_identity||"Repo Mesh",widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:r,children:z("repoMesh.detail.back")}),s.jsxs("button",{className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:()=>d(!0),disabled:i,children:[s.jsx(LI,{size:13}),z(i?"repoMesh.detail.probing":"repoMesh.detail.refresh")]}),s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>a(e.id),children:z("repoMesh.detail.delete")})]}),children:[t&&s.jsx(Ht,{variant:"error",onDismiss:n,className:"mb-4",children:t}),me.meshHostDaemonSection&&s.jsx(SD,{daemons:h,coordinatorDaemonId:v,onCoordinatorDaemonIdChange:w,coordinatorCliType:b,onCoordinatorCliTypeChange:j,launchingCoordinator:C,launchResult:y,isHostNodeAttached:x,selectedHostNode:N,hostPinned:S,hostLabel:A,hostOnline:M,hostRebindDaemonId:P,onHostRebindDaemonIdChange:ae=>{D(ae),d()},onLaunchCoordinator:I}),s.jsxs(ht,{title:z("repoMesh.detail.observabilityTitle"),description:z("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:()=>be(!0),disabled:!Pe,title:z(Pe?"repoMesh.detail.observabilityOpenTitle":"repoMesh.detail.observabilityDisabledTitle"),children:[s.jsx(ts,{size:14}),z("repoMesh.detail.observabilityOpen")]}),s.jsx("span",{className:"text-[12px] text-text-muted",children:z("repoMesh.detail.observabilityHint")})]})]}),s.jsx(kD,{nodes:Ce,meshQueue:H,activeDaemon:_,daemons:h,selectedMeshId:e.id,userName:L,features:{addNodeDaemonPicker:me.addNodeDaemonPicker,nodeInstruction:me.nodeInstruction},coordinatorDaemonId:v,availableCliProviders:O,savingNodeSlotsId:E,onUpdateNodeSlots:T,savingNodeCapabilitiesId:$,onUpdateNodeCapabilities:R,nodeSystemPromptDrafts:G,onNodeSystemPromptDraftChange:Q,savingNodeSystemPromptId:re,onSaveNodeSystemPrompt:J,selectedNodeId:X,onSelectNode:ue,showAddNode:se,onShowAddNode:B,onCancelAddNode:ie,nodeWorkspace:K,onNodeWorkspaceChange:le,nodeProviderPriority:je,onNodeProviderPriorityChange:we,nodeDaemonId:ke,onNodeDaemonIdChange:he,nodeCustomPath:U,onNodeCustomPathChange:q,nodePickerWorkspaces:Z,nodePickerProviders:Y,attachableDaemons:fe,onAddNode:Me,onRemoveNode:de}),s.jsxs(ht,{title:z("repoMesh.detail.schedulingTitle"),description:z("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:z("repoMesh.detail.distribution")}),s.jsx("div",{className:"flex flex-col gap-2",children:jD.map(ae=>{const lt=AD(ge.schedulingStrategy,{priorityConfigured:Ne})===ae.value;return s.jsxs("label",{className:`flex items-start gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${lt?"border-accent-primary/60 bg-accent-primary/10":"border-border-subtle bg-bg-secondary/60 hover:border-border-default"}`,children:[s.jsx("input",{type:"radio",name:"mesh-distribution",className:"mt-0.5 accent-[var(--accent-primary)]",value:ae.value,checked:lt,disabled:p,onChange:()=>u({schedulingStrategy:ND(ae.value)})}),s.jsxs("span",{className:"min-w-0",children:[s.jsxs("span",{className:"flex items-center gap-2 text-sm text-text-primary",children:[ae.label,Ye===ae.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:z("repoMesh.detail.recommended")})]}),s.jsx("span",{className:"block text-[12px] text-text-muted",children:ae.description})]})]},ae.value)})})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:z("repoMesh.detail.saving")})]}),s.jsx(ht,{title:z("repoMesh.detail.visibilityTitle"),description:z("repoMesh.detail.visibilityDescription"),children:s.jsx(jt,{label:z("repoMesh.detail.visibilityLabel"),hint:z("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:ge.spawnedSessionVisibility==="visible"?"visible":"hidden",onChange:ae=>u({spawnedSessionVisibility:ae.target.value==="visible"?"visible":"hidden"}),disabled:p,children:[s.jsx("option",{value:"hidden",children:z("repoMesh.detail.visibilityHidden")}),s.jsx("option",{value:"visible",children:z("repoMesh.detail.visibilityVisible")})]})})}),o&&s.jsx(ht,{title:z("repoMesh.detail.magiTitle"),description:z("repoMesh.detail.magiDescription"),children:s.jsx(qI,{status:o,daemonId:W,sendDaemonCommand:ce,availableProviders:O})}),s.jsx(nD,{hostDaemonId:v,hostOnline:M,hostWorkspace:(N==null?void 0:N.workspace)||"",hostProviders:((Be=h.find(ae=>ae.id===v))==null?void 0:Be.availableProviders)||[],machineAutoApproveEnabled:ge.delegatedWorkerAutoApprove!==!1,machineDangerousAllowed:ge.delegatedWorkerDangerousModeAllow===!0,sendCommand:ce}),s.jsx(ZI,{status:o,daemonId:W,meshId:e.id,sendCommand:ce}),me.coordinatorPrompt&&s.jsxs(ht,{title:z("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:z("repoMesh.detail.advanced")}),description:z("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:z("repoMesh.detail.thisMesh")}),s.jsx("p",{className:"text-[12px] text-text-muted mb-3",children:z("repoMesh.detail.thisMeshHint",{name:e.name})}),s.jsxs(jt,{label:z("repoMesh.detail.overrideLabel"),hint:z("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:ae=>f({...m,override:ae.target.value}),disabled:g,placeholder:z("repoMesh.detail.overridePlaceholder")}),s.jsx(zI,{daemonId:W,meshId:e.id,cliType:b,sendCommand:ce})]}),s.jsx(jt,{label:z("repoMesh.detail.appendLabel"),hint:z("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:ae=>f({...m,append:ae.target.value}),disabled:g,placeholder:z("repoMesh.detail.appendPlaceholder")})}),s.jsxs("details",{className:"mt-2 text-[12px] text-text-muted",children:[s.jsx("summary",{className:"cursor-pointer select-none",children:z("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:z(g?"repoMesh.detail.saving":"repoMesh.detail.saveCoordinatorPrompt")}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>f({override:"",append:""}),disabled:g,title:z("repoMesh.detail.clearTitle"),children:z("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:z("repoMesh.detail.userLevel")}),s.jsx("p",{className:"text-[12px] text-text-muted mb-3",children:z("repoMesh.detail.userLevelDescription")}),s.jsx(iC,{daemonId:W||void 0})]})]}),s.jsxs(ht,{title:z("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:z("repoMesh.detail.advanced")}),description:z("repoMesh.detail.safetyDescription"),children:[s.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:[{label:z("repoMesh.detail.checkpointBefore"),key:"requirePreTaskCheckpoint",opts:[["no","No"],["yes","Yes"]],val:ae=>ae?"yes":"no",parse:ae=>ae==="yes"},{label:z("repoMesh.detail.checkpointAfter"),key:"requirePostTaskCheckpoint",opts:[["yes","Yes"],["no","No"]],val:ae=>ae?"yes":"no",parse:ae=>ae==="yes"},{label:z("repoMesh.detail.pushApproval"),key:"requireApprovalForPush",opts:[["required",z("repoMesh.detail.requireApprovalBeforePush")],["not_required",z("repoMesh.detail.doNotRequireApproval")]],val:ae=>ae?"required":"not_required",parse:ae=>ae==="required"},{label:z("repoMesh.detail.destructiveGitApproval"),key:"requireApprovalForDestructiveGit",opts:[["required",z("repoMesh.detail.requireApproval")],["not_required",z("repoMesh.detail.doNotRequireApproval")]],val:ae=>ae?"required":"not_required",parse:ae=>ae==="required"},{label:z("repoMesh.detail.uncommittedChanges"),key:"dirtyWorkspaceBehavior",opts:[["warn",z("repoMesh.detail.warnAndContinue")],["block",z("repoMesh.detail.blockTask")],["checkpoint_then_continue",z("repoMesh.detail.checkpointThenContinue")]],val:ae=>ae||"warn",parse:ae=>ae},{label:z("repoMesh.detail.autoPublishSubmodule"),key:"allowAutoPublishSubmoduleMainCommits",opts:[["disabled",z("repoMesh.detail.requireExplicitApproval")],["enabled",z("repoMesh.detail.allowRefineryPublish")]],val:ae=>ae?"enabled":"disabled",parse:ae=>ae==="enabled"}].map(({label:ae,key:_e,opts:lt,val:ct,parse:Nt})=>s.jsx(jt,{label:ae,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:ct(ge[_e]),onChange:V=>u({[_e]:Nt(V.target.value)}),disabled:p,children:lt.map(([V,ee])=>s.jsx("option",{value:V,children:ee},V))})},_e))}),(()=>{const ae=ge.autoFastForward&&typeof ge.autoFastForward=="object"?ge.autoFastForward:{},_e=ae.enabled!==!1,lt=ae.remoteNodes===!0,ct=ae.mode==="continuous"?"continuous":"idle",Nt=V=>u({autoFastForward:{...ae,...V}});return s.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[s.jsx(jt,{label:z("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:_e?"enabled":"disabled",onChange:V=>Nt({enabled:V.target.value==="enabled"}),disabled:p,children:[s.jsx("option",{value:"enabled",children:z("repoMesh.detail.ffEnabled")}),s.jsx("option",{value:"disabled",children:z("repoMesh.detail.ffDisabled")})]})}),s.jsx(jt,{label:z("repoMesh.detail.includeRemoteNodes"),hint:z("repoMesh.detail.includeRemoteNodesHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:lt?"yes":"no",onChange:V=>Nt({remoteNodes:V.target.value==="yes"}),disabled:p||!_e,children:[s.jsx("option",{value:"no",children:z("repoMesh.detail.remoteNo")}),s.jsx("option",{value:"yes",children:z("repoMesh.detail.remoteYes")})]})}),s.jsx(jt,{label:z("repoMesh.detail.detectionMode"),hint:z("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:ct,onChange:V=>Nt({mode:V.target.value==="continuous"?"continuous":"idle"}),disabled:p||!_e||!lt,children:[s.jsx("option",{value:"idle",children:z("repoMesh.detail.idleEdgeOnly")}),s.jsx("option",{value:"continuous",children:z("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(jt,{label:z("repoMesh.detail.sessionCleanupLabel"),hint:z("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:ge.sessionCleanupOnNodeRemove||"preserve",onChange:ae=>u({sessionCleanupOnNodeRemove:ae.target.value}),disabled:p,children:Ko.map(ae=>s.jsx("option",{value:ae.value,children:ae.label},ae.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((it=Ko.find(ae=>ae.value===ge.sessionCleanupOnNodeRemove))==null?void 0:it.description)||Ko[0].description})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:z("repoMesh.detail.saving")})]}),me.hermesMcpConfig&&s.jsx(CD,{meshId:e.id,availableCliAgents:F}),me.meshHostDaemonSection&&s.jsxs(Ht,{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."]}),ot&&Pe&&s.jsx(mh,{activeConv:TD({meshId:e.id,daemonId:W,meshName:e.name}),sendDaemonCommand:ce,onClose:()=>be(!1)})]})}const Qn=new Map;function DD({daemons:e,primaryDaemonId:t,sendCommand:n,unwrapResult:r,normalizeMesh:a,features:o,loadDaemonMetadata:i}){const c=e.map(T=>T.id).filter(Boolean).sort().join(","),[d,p]=l.useState(()=>Qn.get(c)??[]),[u,m]=l.useState(null),[f,g]=l.useState(()=>!Qn.has(c)),[k,h]=l.useState(null),[v,w]=l.useState(!1),[b,j]=l.useState(""),[C,y]=l.useState(""),[x,N]=l.useState(""),[S,A]=l.useState(""),[M,P]=l.useState(""),D=l.useMemo(()=>e.find(T=>T.id===S),[e,S]),I=(D==null?void 0:D.workspaces)||[],_=l.useMemo(()=>Tn((D==null?void 0:D.availableProviders)||[]),[D]);l.useEffect(()=>{!o.createDaemonPicker||!i||!S||!D||!(!D.workspaces||!D.availableProviders)||Promise.resolve(i(S,{minFreshMs:3e4})).catch(()=>{})},[o.createDaemonPicker,i,S,D]);const W=l.useMemo(()=>e.map(T=>T.id).filter(Boolean).sort().join(","),[e]),H=l.useCallback(async(T=!1)=>{const $=T||Qn.has(W);g(R=>$?R:!0);try{if(o.createDaemonPicker){const R=await Promise.allSettled(e.map(async re=>{if(!re.id)return[];const J=await n(re.id,"list_meshes",{}),X=r(J);if((X==null?void 0:X.success)===!1)throw new Error(X.error||"Failed to load meshes");return(Array.isArray(X==null?void 0:X.meshes)?X.meshes:[]).map(ue=>a(ue,re.id)).filter(ue=>ue.id)})),G=new Map;for(const re of R)if(re.status==="fulfilled")for(const J of re.value)G.has(J.id)||G.set(J.id,J);const Q=Array.from(G.values());p(Q),Qn.set(W,Q),h(null)}else{if(!t)return;const R=await n(t,"list_meshes");if(R!=null&&R.success){const G=(R.meshes||[]).map(Q=>a(Q,t));p(G),Qn.set(W,G),h(null)}else h((R==null?void 0:R.error)||"Failed to load meshes")}}catch(R){h((R==null?void 0:R.message)||"Failed to load meshes")}finally{g(!1)}},[W,t,n,r,a,o.createDaemonPicker]);async function L(){var G,Q;const T=o.createDaemonPicker?S:t;if(!T||!b.trim())return;const $=x.trim(),R=C.trim();if(!(!$&&!R))try{const re={name:b.trim()};$&&(re.repoRemoteUrl=$),R&&(re.repoIdentity=R);const J=await n(T,"create_mesh",re),X=r(J);if((X==null?void 0:X.success)===!1)throw new Error(X.error||"Create failed");const ue=typeof((G=X==null?void 0:X.mesh)==null?void 0:G.id)=="string"?X.mesh.id:"";if(ue&&o.createDaemonPicker&&M){const se=await n(T,"add_mesh_node",{meshId:ue,daemonId:T,machineId:D==null?void 0:D.machineId,workspace:M,role:"host",providerPriority:gr(_)}),B=r(se);if((B==null?void 0:B.success)===!1)throw new Error(B.error||"Mesh created but failed to attach workspace")}w(!1),j(""),y(""),N(""),P(""),await H(),(Q=X==null?void 0:X.mesh)!=null&&Q.id&&m(X.mesh.id)}catch(re){h((re==null?void 0:re.message)||"Create failed")}}async function O(T){var R;if(!confirm("Delete this mesh? This cannot be undone."))return;const $=((R=d.find(G=>G.id===T))==null?void 0:R.__sourceDaemonId)||t;try{const G=await n($,"delete_mesh",{meshId:T}),Q=r(G);if((Q==null?void 0:Q.success)===!1)throw new Error(Q.error||"Failed to delete");u===T&&m(null),await H()}catch(G){h((G==null?void 0:G.message)||"Delete failed")}}function E(){w(!1),j(""),y(""),N("")}return{meshes:d,setMeshes:p,selectedMeshId:u,setSelectedMeshId:m,loading:f,error:k,setError:h,showCreate:v,setShowCreate:w,createName:b,setCreateName:j,createRepoIdentity:C,setCreateRepoIdentity:y,createRepoRemoteUrl:x,setCreateRepoRemoteUrl:N,newMeshDaemonId:S,setNewMeshDaemonId:A,newMeshWorkspace:M,setNewMeshWorkspace:P,createPickerWorkspaces:I,createPickerProviders:_,loadMeshes:H,handleCreate:L,handleDelete:O,cancelCreate:E}}function PD({selectedMesh:e,selectedMeshId:t,primaryDaemonId:n,activeDaemonId:r,daemons:a,sendCommand:o,unwrapResult:i,loadLiveMesh:c,resolveCommandTarget:d,launchCoordinator:p,features:u,loadMeshes:m,loadQueue:f,queueSection:g,setError:k}){const[h,v]=l.useState({}),[w,b]=l.useState(null),[j,C]=l.useState(null),[y,x]=l.useState(!1),[N,S]=l.useState(""),[A,M]=l.useState([]),[P,D]=l.useState(""),[I,_]=l.useState(!1),[W,H]=l.useState(""),[L,O]=l.useState(!1),[E,T]=l.useState(null),[$,R]=l.useState(!1),[G,Q]=l.useState({override:"",append:""}),[re,J]=l.useState(!1),[X,ue]=l.useState({}),[se,B]=l.useState(null),ie=l.useMemo(()=>a.find(ce=>ce.id===P),[a,P]),K=(ie==null?void 0:ie.workspaces)||[],le=l.useMemo(()=>Tn((ie==null?void 0:ie.availableProviders)||[]),[ie]);async function je(){const ce=(e==null?void 0:e.__sourceDaemonId)||n;if(!t||!ce)return;const z=N.trim();if(z)try{const ge={meshId:t,workspace:z};u.addNodeDaemonPicker&&P&&(ge.daemonId=P,ge.machineId=ie==null?void 0:ie.machineId),ge.providerPriority=In(A);const Ce=await o(ce,"add_mesh_node",ge),Ne=i(Ce);if((Ne==null?void 0:Ne.success)===!1)throw new Error(Ne.error||"Add node failed");x(!1),S(""),M([]),D(""),_(!1),await m(),g||await f(t)}catch(ge){k((ge==null?void 0:ge.message)||"Add node failed")}}async function we(ce){var Ne;if(!e)return;const z=Ii(e),ge=((Ne=[{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(He=>He.value===z.sessionCleanupOnNodeRemove))==null?void 0:Ne.label)||"Preserve history and runtimes";if(!confirm(`Remove this node?
|
|
120
120
|
|
|
121
|
-
Node removal cleanup policy: ${ge}`))return;const Ce=e.__sourceDaemonId||n;try{const He=await o(Ce,"remove_mesh_node",{meshId:e.id,nodeId:ce}),Ze=i(He);if((Ze==null?void 0:Ze.success)===!1)throw new Error(Ze.error||"Remove failed");j===ce&&C(null),await m(),g||await f(t)}catch(He){k((He==null?void 0:He.message)||"Remove node failed")}}async function ke(ce){if(!e)return;const z={...Ii(e),...ce},ge=e.__sourceDaemonId||n;try{R(!0),k(null);const Ce=await o(ge,"update_mesh",{meshId:e.id,policy:z}),Ne=i(Ce);if((Ne==null?void 0:Ne.success)===!1)throw new Error(Ne.error||"Policy update failed");await m()}catch(Ce){k((Ce==null?void 0:Ce.message)||"Policy update failed")}finally{R(!1)}}async function he(ce){if(!t)return;const z=(e==null?void 0:e.__sourceDaemonId)||n,ge=h[ce.id]||LD(ce),Ce=In(ge),Ne={...ce.policy||{}};delete Ne.provider_priority,Ce.length?Ne.providerPriority=Ce:delete Ne.providerPriority;try{b(ce.id),k(null);const He=await o(z,"update_mesh_node",{meshId:t,nodeId:ce.id,policy:Ne,providerPriority:Ce}),Ze=i(He);if((Ze==null?void 0:Ze.success)===!1){k(Ze.error||"Node policy update failed");return}await m()}catch(He){k((He==null?void 0:He.message)||"Node policy update failed")}finally{b(null)}}const[U,q]=l.useState(null);async function Z(ce,z){if(!t)return;const ge=(e==null?void 0:e.__sourceDaemonId)||n;try{q(ce.id),k(null);const Ce=await o(ge,"update_mesh_node",{meshId:t,nodeId:ce.id,policy:{slots:z}}),Ne=i(Ce);if((Ne==null?void 0:Ne.success)===!1){k(Ne.error||"Node slots update failed");return}await m()}catch(Ce){k((Ce==null?void 0:Ce.message)||"Node slots update failed")}finally{q(null)}}const[Y,fe]=l.useState(null);async function Me(ce,z){if(!t)return;const ge=(e==null?void 0:e.__sourceDaemonId)||n,Ce=z.map(Ne=>Ne.trim()).filter(Boolean);try{fe(ce.id),k(null);const Ne=await o(ge,"update_mesh_node",{meshId:t,nodeId:ce.id,capabilities:Ce}),He=i(Ne);if((He==null?void 0:He.success)===!1){k(He.error||"Node tag update failed");return}await m()}catch(Ne){k((Ne==null?void 0:Ne.message)||"Node tag update failed")}finally{fe(null)}}async function de(){if(!n||!t)return;const z={...(e==null?void 0:e.coordinator)||{}};G.override.trim()?z.systemPromptOverride=G.override:delete z.systemPromptOverride,G.append.trim()?z.systemPromptAppend=G.append:delete z.systemPromptAppend,delete z.systemPromptSuffix;try{J(!0),k(null);const ge=await o(n,"update_mesh",{meshId:t,coordinator:z}),Ce=i(ge);if((Ce==null?void 0:Ce.success)===!1){k(Ce.error||"Coordinator prompt save failed");return}await m()}catch(ge){k((ge==null?void 0:ge.message)||"Coordinator prompt save failed")}finally{J(!1)}}async function F(ce){if(!n||!t)return;const z=(X[ce.id]||"").trim();try{B(ce.id),k(null);const ge=await o(n,"update_mesh_node",{meshId:t,nodeId:ce.id,systemPrompt:z}),Ce=i(ge);if((Ce==null?void 0:Ce.success)===!1){k(Ce.error||"Node instruction save failed");return}await m()}catch(ge){k((ge==null?void 0:ge.message)||"Node instruction save failed")}finally{B(null)}}async function me(){if(e){k(null),T(null);try{O(!0);const ce=c?await c(r,e.id,e):null,z=d(r,e.id,e,e.nodes||[],ce);if("error"in z)throw new Error(z.error);const ge=await p(z.targetDaemonId,{meshId:e.id,inlineMesh:z.inlineMesh,coordinatorNodeId:z.coordinatorNodeId,cliType:W.trim()||void 0});T(ge.message)}catch(ce){k((ce==null?void 0:ce.message)||"Coordinator launch failed")}finally{O(!1)}}}return{nodeProviderPriorityDrafts:h,setNodeProviderPriorityDrafts:v,savingNodePolicyId:w,selectedNodeId:j,setSelectedNodeId:C,showAddNode:y,setShowAddNode:x,nodeWorkspace:N,setNodeWorkspace:S,nodeProviderPriority:A,setNodeProviderPriority:M,nodeDaemonId:P,setNodeDaemonId:D,nodeCustomPath:I,setNodeCustomPath:_,nodePickerWorkspaces:K,nodePickerProviders:le,coordinatorCliType:W,setCoordinatorCliType:H,launchingCoordinator:L,launchResult:E,savingPolicy:$,coordinatorPromptDraft:G,setCoordinatorPromptDraft:Q,savingCoordinatorPrompt:re,nodeSystemPromptDrafts:X,setNodeSystemPromptDrafts:ue,savingNodeSystemPromptId:se,savingNodeSlotsId:U,savingNodeCapabilitiesId:Y,handleAddNode:je,handleRemoveNode:we,handleUpdatePolicy:ke,handleUpdateNodeProviderPriority:he,handleUpdateNodeSlots:Z,handleUpdateNodeCapabilities:Me,handleSaveCoordinatorPrompt:de,handleSaveNodeSystemPrompt:F,handleLaunchCoordinator:me}}function LD(e){var r;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>n.has(a)?!1:(n.add(a),!0))}function RD(e){const t=e.filter(r=>r.status==="pending"||r.status==="assigned"),n=e.filter(r=>r.status==="completed"||r.status==="failed"||r.status==="cancelled");return{active:t.length,historical:n.length,activeCounts:{pending:t.filter(r=>r.status==="pending").length,assigned:t.filter(r=>r.status==="assigned").length},historicalCounts:{completed:n.filter(r=>r.status==="completed").length,failed:n.filter(r=>r.status==="failed").length},counts:{pending:e.filter(r=>r.status==="pending").length,assigned:e.filter(r=>r.status==="assigned").length,completed:e.filter(r=>r.status==="completed").length,failed:e.filter(r=>r.status==="failed").length},staleAssignedCount:e.filter(r=>r.staleAssigned).length,recent:e.slice(0,20)}}function ED({primaryDaemonId:e,activeDaemonId:t,sendCommand:n,unwrapResult:r,loadLiveMesh:a,resolveCommandTarget:o}){const[i,c]=l.useState([]),[d,p]=l.useState(null),[u,m]=l.useState(!1),[f,g]=l.useState(null),k=l.useCallback(async v=>{if(!e||!v){c([]);return}try{const w=await n(e,"get_mesh_queue",{meshId:v});c(w!=null&&w.success?Array.isArray(w.queue)?w.queue:[]:[])}catch{c([])}},[e,n]);async function h(v){var w,b;if(v){m(!0),g(null);try{const j=a?await a(t,v.id,v):null,C=o(t,v.id,v,v.nodes||[],j);if("error"in C)throw new Error(C.error);const y=await n(C.targetDaemonId,"get_mesh_queue",{meshId:v.id}),x=r(y);if((x==null?void 0:x.success)===!1)throw new Error(x.error||"Queue load failed");const N=Array.isArray(((w=x==null?void 0:x.result)==null?void 0:w.rows)??(x==null?void 0:x.rows)??(x==null?void 0:x.queue))?((b=x==null?void 0:x.result)==null?void 0:b.rows)??(x==null?void 0:x.rows)??(x==null?void 0:x.queue):[];p(RD(N))}catch(j){g((j==null?void 0:j.message)||"Queue load failed")}finally{m(!1)}}}return{meshQueue:i,setMeshQueue:c,queueSummary:d,queueLoading:u,queueError:f,loadQueue:k,handleLoadQueue:h}}function _D(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}const vh=new Map;function yh(e){return e?vh.get(e)??null:null}function $D(e,t){!e||!t||vh.set(e,t)}function HD({selectedMeshId:e,loadMeshStatus:t,extractStatus:n,normalizeNode:r,gateIncompleteGraph:a}){const[o,i]=l.useState(()=>yh(e)),[c,d]=l.useState(!1),[p,u]=l.useState(null),[m,f]=l.useState("idle"),[g,k]=l.useState(!1),h=l.useRef(!1);async function v(w,b=e,j=!1){if(!(!w||!b))try{d(!j&&o===null),f(j?"settling":"first_paint"),u(null);const C=await t(w,b,{refresh:j,retryProfile:j?"settled":"interactive"});k(_D(C));const y=n(C),x=r&&y?{...y,nodes:(y.nodes??[]).map(N=>r(N,y.meshId??b,""))}:y;if(x){if(a&&!j&&o!==null&&!JN(Jm(x))){f("settling"),h.current||(h.current=!0,Promise.resolve().then(()=>v(w,b,!0)).finally(()=>{h.current=!1}));return}i(x),$D(b,x),f("settled")}else i(null),u("mesh_status returned an unexpected payload."),f("idle")}catch(C){o||i(null),u((C==null?void 0:C.message)||"Failed to load mesh graph"),f("idle")}finally{d(!1)}}return{meshGraphStatus:o,setMeshGraphStatus:i,graphLoading:c,graphError:p,setGraphError:u,graphProvenance:m,graphBootstrapFallback:g,loadGraph:v}}function FD(e,t,n,r,a){if(!e.length)return"";const o=String(a||"");if(o){const d=e.find(p=>Vs(p.id,o));return d?d.id:o}const i=t.find(d=>d.role==="host"),c=String((i==null?void 0:i.daemon_id)||(i==null?void 0:i.daemonId)||"");if(c){const d=e.find(p=>Vs(p.id,c));if(d)return d.id}return""}const BD=7e3,OD=45e3;function WD(){const e=PI(),{sendCommand:t,sendData:n,daemons:r,userName:a,loadMeshStatus:o,launchCoordinator:i,loadLiveMesh:c,extractStatus:d,unwrapResult:p,normalizeMesh:u,normalizeNode:m,resolveCommandTarget:f,features:g,gateIncompleteGraph:k}=e,h=_n(),v=r[0],w=(v==null?void 0:v.id)||"",b=l.useMemo(()=>((v==null?void 0:v.availableProviders)||[]).filter(rt=>rt.category==="cli").map(rt=>({id:rt.type||rt.id,name:rt.displayName||rt.name||rt.type,meshCoordinator:rt.meshCoordinator})),[v]),j=l.useMemo(()=>Tn((v==null?void 0:v.availableProviders)||[]),[v]),{meshes:C,selectedMeshId:y,setSelectedMeshId:x,loading:N,error:S,setError:A,showCreate:M,setShowCreate:P,createName:D,setCreateName:I,createRepoIdentity:_,setCreateRepoIdentity:W,createRepoRemoteUrl:H,setCreateRepoRemoteUrl:L,newMeshDaemonId:O,setNewMeshDaemonId:E,newMeshWorkspace:T,setNewMeshWorkspace:$,createPickerWorkspaces:R,loadMeshes:G,handleCreate:Q,handleDelete:re,cancelCreate:J}=DD({daemons:r,primaryDaemonId:w,sendCommand:t,unwrapResult:p,normalizeMesh:u,features:g,loadDaemonMetadata:h}),X=C.find(Le=>Le.id===y)||null,{meshGraphStatus:ue,setMeshGraphStatus:se,graphLoading:B,graphError:ie,setGraphError:K,loadGraph:le}=HD({selectedMeshId:y,loadMeshStatus:o,extractStatus:d,normalizeNode:m,gateIncompleteGraph:k}),[je,we]=l.useState(""),[ke,he]=l.useState(""),U=g.meshHostDaemonSection&&je||w,{meshQueue:q,loadQueue:Z}=ED({primaryDaemonId:w,activeDaemonId:U,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:f}),{setNodeProviderPriorityDrafts:Y,selectedNodeId:fe,setSelectedNodeId:Me,showAddNode:de,setShowAddNode:F,nodeWorkspace:me,setNodeWorkspace:ce,nodeProviderPriority:z,setNodeProviderPriority:ge,nodeDaemonId:Ce,setNodeDaemonId:Ne,nodeCustomPath:He,setNodeCustomPath:Ze,nodePickerWorkspaces:Ye,nodePickerProviders:ot,coordinatorCliType:be,setCoordinatorCliType:Pe,launchingCoordinator:Be,launchResult:it,savingPolicy:ae,coordinatorPromptDraft:_e,setCoordinatorPromptDraft:lt,savingCoordinatorPrompt:ct,nodeSystemPromptDrafts:Nt,setNodeSystemPromptDrafts:V,savingNodeSystemPromptId:ee,savingNodeSlotsId:oe,savingNodeCapabilitiesId:pe,handleAddNode:ve,handleRemoveNode:Te,handleUpdatePolicy:Ee,handleUpdateNodeSlots:De,handleUpdateNodeCapabilities:Ue,handleSaveCoordinatorPrompt:Ge,handleSaveNodeSystemPrompt:Xe,handleLaunchCoordinator:Fe}=PD({selectedMesh:X,selectedMeshId:y,primaryDaemonId:w,activeDaemonId:U,daemons:r,availableCliProviders:j,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:f,launchCoordinator:i,features:{addNodeDaemonPicker:g.addNodeDaemonPicker},loadMeshes:G,loadQueue:Z,queueSection:g.queueSection,setError:A}),Oe=l.useMemo(()=>r.find(Le=>Le.id===U)||v,[r,U,v]),Je=l.useMemo(()=>new Set(((X==null?void 0:X.nodes)||[]).map(Le=>String(Le.daemon_id||Le.daemonId||""))),[X]),te=l.useMemo(()=>r.filter(Le=>Le.id&&!Je.has(Le.id)),[r,Je]),xe=(X==null?void 0:X.nodes)||[],ye=l.useMemo(()=>xe.find(Le=>Vs(String(Le.daemon_id||Le.daemonId||""),je)),[xe,je]),$e=g.meshHostDaemonSection?!!ye:!0,Re=l.useMemo(()=>{if(!g.meshHostDaemonSection||!X)return{pinned:!1,daemonId:"",label:"",online:!1};const Le=X.meshHost,rt=ue!=null&&ue.meshId&&String(ue.meshId)===String(X.id??"")?ue.meshHost:void 0,Tt=rt!=null&&rt.hostDaemonId?rt:Le??rt,Jt=String((Tt==null?void 0:Tt.hostDaemonId)||""),Kt=xe.find(as=>as.role==="host"),rs=String((Tt==null?void 0:Tt.hostNodeId)||(Kt==null?void 0:Kt.id)||""),It=rs?xe.find(as=>String(as.id)===rs):void 0,bs=String((It==null?void 0:It.daemon_id)||(It==null?void 0:It.daemonId)||""),gs=Jt||bs;if(!gs)return{pinned:!1,daemonId:"",label:"",online:!1};const Is=r.find(as=>Jt&&Vs(as.id,Jt))||(bs?r.find(as=>Vs(as.id,bs)):void 0);if(Is)return{pinned:!0,daemonId:Is.id,label:UD(Is),online:!0};const $n=String((It==null?void 0:It.machineLabel)||"")||String((It==null?void 0:It.workspace)||"")||gs;return{pinned:!0,daemonId:gs,label:$n,online:!1}},[X,xe,r,ue,g.meshHostDaemonSection]),et=Re.daemonId,tt=Re.online,Ke=l.useMemo(()=>!g.meshHostDaemonSection||!Re.pinned?"":!tt&&ke&&r.some(Le=>Le.id===ke)?ke:et,[g.meshHostDaemonSection,Re.pinned,tt,ke,r,et]),kt=l.useMemo(()=>ue?[...new Set((ue.nodes??[]).map(Le=>String(Le.daemonId||Le.daemon_id||"")).filter(Boolean))]:[],[ue]),zt=ph({status:ue,daemonId:U||null,extraDaemonIds:kt,meshId:y,sendData:n});l.useEffect(()=>{Y(Object.fromEntries(((X==null?void 0:X.nodes)||[]).map(Le=>[Le.id,GD(Le)])))},[X]),l.useEffect(()=>{const Le=(X==null?void 0:X.coordinator)||{};lt({override:typeof Le.systemPromptOverride=="string"?Le.systemPromptOverride:"",append:typeof Le.systemPromptAppend=="string"?Le.systemPromptAppend:typeof Le.systemPromptSuffix=="string"?Le.systemPromptSuffix:""}),V(Object.fromEntries(((X==null?void 0:X.nodes)||[]).map(rt=>[rt.id,typeof rt.systemPrompt=="string"?rt.systemPrompt:""])))},[X]),l.useEffect(()=>{const Le=g.addNodeDaemonPicker?gr(ot):gr(j);de&&z.length===0&&Le.length>0&&ge(Le)},[de,j,ot,z.length,g.addNodeDaemonPicker]),l.useEffect(()=>{const Le=new Set(((X==null?void 0:X.nodes)||[]).map(rt=>rt.id));fe&&!Le.has(fe)&&Me(null)},[X,fe]);const ns=l.useMemo(()=>{var Le;if(!(!(ue!=null&&ue.meshId)||String(ue.meshId)!==String((X==null?void 0:X.id)??"")))return(Le=ue.meshHost)==null?void 0:Le.hostDaemonId},[ue,X]),Ae=l.useMemo(()=>FD(r,xe,U,w,ns),[r,xe,U,w,ns]);l.useEffect(()=>{if(!g.meshHostDaemonSection)return;if(!r.length&&!Re.pinned){we("");return}const Le=Re.pinned?Ke:Ae;Le&&!Vs(Le,je)&&we(Le)},[r,je,Re.pinned,Ke,Ae,g.meshHostDaemonSection]),l.useEffect(()=>{ke&&(tt||!r.some(Le=>Le.id===ke))&&he("")},[tt,ke,r]),l.useEffect(()=>{if(g.createDaemonPicker){if(!r.length){E("");return}(!O||!r.some(Le=>Le.id===O))&&E(r[0].id)}},[r,O,g.createDaemonPicker]),l.useEffect(()=>{var Le;if(!g.createDaemonPicker||!O){$("");return}if(!R.length){$("");return}R.some(rt=>rt.path===T)||$(((Le=R[0])==null?void 0:Le.path)||"")},[O,T,R,g.createDaemonPicker]);const Qe=l.useRef(null);l.useEffect(()=>{if(!y)return;const Le=Qe.current!==y;if(Qe.current=y,Le){const rt=yh(y);se(rt),K(null),le(U,y,rt!==null)}else K(null),le(U,y,!0)},[y,U]);const Ft=l.useRef(le);Ft.current=le;const St=l.useRef(!1),Gt=l.useRef(()=>{});Gt.current=()=>{St.current||!y||!U||(St.current=!0,Promise.resolve(Ft.current(U,y,!0)).finally(()=>{St.current=!1}))};const qt=g.meshStatePushRefresh?OD:BD;II({daemonIds:l.useMemo(()=>[U,...kt].filter(Boolean),[U,kt]),meshId:y,sendData:n,onRevisionAdvance:()=>{typeof document<"u"&&document.visibilityState!=="visible"||Gt.current()}}),l.useEffect(()=>{if(!y||!U||typeof document>"u")return;let Le=null;const rt=()=>{document.visibilityState==="visible"&&Gt.current()},Tt=()=>{Le===null&&(Le=setInterval(rt,qt))},Jt=()=>{Le!==null&&(clearInterval(Le),Le=null)},Kt=()=>{document.visibilityState==="visible"?Tt():Jt()};return document.visibilityState==="visible"&&Tt(),document.addEventListener("visibilitychange",Kt),()=>{Jt(),document.removeEventListener("visibilitychange",Kt)}},[y,U,qt]),l.useEffect(()=>{g.queueSection||Z(y)},[y,g.queueSection]);const ft=l.useMemo(()=>r.map(Le=>Le.id).filter(Boolean).sort().join(","),[r]),fs=l.useRef(!1);return l.useEffect(()=>{G(fs.current),fs.current=!0},[ft]),w?X?s.jsx(ID,{selectedMesh:X,error:S,onDismissError:()=>A(null),onBack:()=>{x(null),se(null)},onDelete:re,displayedMeshStatus:zt,graphLoading:B,graphError:ie,onRefreshGraph:()=>le(U,y,!0),savingPolicy:ae,onUpdatePolicy:Ee,coordinatorPromptDraft:_e,onCoordinatorPromptDraftChange:lt,savingCoordinatorPrompt:ct,onSaveCoordinatorPrompt:Ge,daemons:r,coordinatorDaemonId:je,onCoordinatorDaemonIdChange:we,coordinatorCliType:be,onCoordinatorCliTypeChange:Pe,launchingCoordinator:Be,launchResult:it,isHostNodeAttached:$e,selectedHostNode:ye,hostPinned:Re.pinned,hostLabel:Re.label,hostOnline:tt,hostRebindDaemonId:ke,onHostRebindDaemonIdChange:Le=>he(Le),onLaunchCoordinator:Fe,activeDaemon:Oe,activeDaemonId:U,meshQueue:q,userName:a,availableCliProviders:j,savingNodeSlotsId:oe,onUpdateNodeSlots:De,savingNodeCapabilitiesId:pe,onUpdateNodeCapabilities:Ue,nodeSystemPromptDrafts:Nt,onNodeSystemPromptDraftChange:(Le,rt)=>V(Tt=>({...Tt,[Le]:rt})),savingNodeSystemPromptId:ee,onSaveNodeSystemPrompt:Xe,selectedNodeId:fe,onSelectNode:Me,showAddNode:de,onShowAddNode:()=>F(!0),onCancelAddNode:()=>F(!1),nodeWorkspace:me,onNodeWorkspaceChange:ce,nodeProviderPriority:z,onNodeProviderPriorityChange:ge,nodeDaemonId:Ce,onNodeDaemonIdChange:Ne,nodeCustomPath:He,onNodeCustomPathChange:Ze,nodePickerWorkspaces:Ye,nodePickerProviders:ot,attachableDaemons:te,onAddNode:ve,onRemoveNode:Te,availableCliAgents:b,features:{coordinatorPrompt:g.coordinatorPrompt,meshHostDaemonSection:g.meshHostDaemonSection,hermesMcpConfig:g.hermesMcpConfig,addNodeDaemonPicker:g.addNodeDaemonPicker,nodeInstruction:g.nodeInstruction},sendCommand:t}):s.jsx(FI,{meshes:C,loading:N,error:S,onDismissError:()=>A(null),daemons:r,features:{createDaemonPicker:g.createDaemonPicker,maxMeshes:g.maxMeshes},showCreate:M,onToggleCreate:()=>P(!M),createName:D,onCreateNameChange:I,createRepoIdentity:_,onCreateRepoIdentityChange:W,createRepoRemoteUrl:H,onCreateRepoRemoteUrlChange:L,newMeshDaemonId:O,onNewMeshDaemonIdChange:E,newMeshWorkspace:T,onNewMeshWorkspaceChange:$,createPickerWorkspaces:R,onSelectMesh:x,onCreate:Q,onCancelCreate:J}):s.jsx(jr,{icon:s.jsx(ts,{}),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 UD(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function GD(e){var r;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>n.has(a)?!1:(n.add(a),!0))}function qD({children:e}){const{sendCommand:t,sendData:n}=vt(),{ides:r}=Ss(),a=l.useMemo(()=>r.filter(i=>i.daemonMode||i.type==="adhdev-daemon").map(i=>i),[r]),o=l.useMemo(()=>({sendCommand:t,sendData:n,daemons:a,userName:void 0,loadMeshStatus:async(i,c)=>t(i,"mesh_status",{meshId:c}),launchCoordinator:async(i,c)=>{var f;const d={meshId:c.meshId};c.cliType&&(d.cliType=c.cliType);const p=await t(i,"launch_mesh_coordinator",d),u=(p==null?void 0:p.result)??p;if((u==null?void 0:u.success)===!1)throw new Error(u.error||"Coordinator launch failed");const m=(u==null?void 0:u.sessionId)||((f=u==null?void 0:u.session)==null?void 0:f.id)||(u==null?void 0:u.targetSessionId);return{sessionId:m,message:m?`Coordinator launched (${m})`:"Coordinator launch command sent"}},loadLiveMesh:void 0,extractStatus:Xi,unwrapResult:i=>i,normalizeMesh:(i,c)=>i,normalizeNode:(i,c,d)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:DI}),[t,n,a]);return s.jsx(xh.Provider,{value:o,children:e})}function Tl(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function zD(e){if(typeof window>"u")return e;const t=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),n=Tl();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 ys(e,t){return await fetch(zD(e),{credentials:"same-origin",...t})}function wh(){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 KD{constructor(){st(this,"adapters",new Map);st(this,"states",new Map);st(this,"runtimeListeners",new Map);st(this,"screenshotCallbacks",new Map);st(this,"statusCallbacks",new Set);st(this,"stateChangeCallbacks",new Set);st(this,"ptyInputSender",null)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const n of this.adapters.keys())if(n.startsWith("standalone"))return n}return null}register(t,n){this.adapters.set(t,n),this.states.set(t,n.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,n){this.states.set(t,n);const r=this.resolveDaemonId(t)||t;this.stateChangeCallbacks.forEach(a=>a(r,n))}onStateChange(t){return this.stateChangeCallbacks.add(t),()=>{this.stateChangeCallbacks.delete(t)}}retryConnection(t){}get(t){const n=this.resolveDaemonId(t);return n?this.adapters.get(n):void 0}getState(t){const n=this.resolveDaemonId(t);return n&&this.states.get(n)||"disconnected"}registerPtyInputSender(t){this.ptyInputSender=t}sendData(t,n){return!1}sendPtyInput(t,n,r){return this.ptyInputSender?this.ptyInputSender(t,n,r):!1}onScreenshot(t,n){return this.screenshotCallbacks.set(t,n),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,n){this.screenshotCallbacks.forEach(r=>r(t,n))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,n){this.statusCallbacks.forEach(r=>r(t,n))}emitRuntimeSnapshot(t,n,r=0,a=!1,o,i){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:r,text:n,truncated:a,cols:o,rows:i})}emitSessionOutput(t,n,r){!t||typeof n!="string"||!n||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof r=="number"?{seq:r}:{},data:n})}onRuntimeEvent(t,n){const r=this.runtimeListeners.get(t)||new Set;return r.add(n),this.runtimeListeners.set(t,r),()=>{const a=this.runtimeListeners.get(t);a&&(a.delete(n),a.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,n,r){if(!n)return{success:!1,error:"sessionId is required"};const a=new URL(`/api/v1/runtime/${encodeURIComponent(n)}/snapshot`,window.location.origin);typeof(r==null?void 0:r.sinceSeq)=="number"&&a.searchParams.set("sinceSeq",String(r.sinceSeq));const o=await ys(`${a.pathname}${a.search}`);if(!o.ok){let c=`Runtime snapshot unavailable (${o.status})`;try{const d=await o.json();d!=null&&d.error&&(c=d.error)}catch{}return{success:!1,error:c}}const i=await o.json();return this.emitRuntimeEvent(n,{type:"runtime_snapshot",sessionId:n,seq:typeof i.seq=="number"?i.seq:0,text:typeof i.text=="string"?i.text:"",truncated:!!i.truncated,cols:typeof i.cols=="number"?i.cols:void 0,rows:typeof i.rows=="number"?i.rows:void 0,force:!!(r!=null&&r.force)}),{success:!0}}emitRuntimeEvent(t,n){var r;(r=this.runtimeListeners.get(t))==null||r.forEach(a=>a(n))}}const vs=new KD;function VD(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,n=Tl();return n?`${t}?token=${encodeURIComponent(n)}`:t}const Xr=VD(),zd=3e3,YD=3e4;let ls=null,JD=0;const Da=new Map;let qs=null,dr=null;function Kd(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Xn(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function QD(e){return e==="connected"?"connected":e}async function ur(e,t,n){const r=Op(e,n||{}),a=ls;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++JD}_${Date.now()}`;return new Promise((i,c)=>{const d=setTimeout(()=>{Da.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);Da.set(o,{resolve:p=>{clearTimeout(d),i(p)},reject:p=>{clearTimeout(d),c(p)}}),a.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:r.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function Di(e,t){const n=ls;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 kh(e,t,n){const r=ls;if(!r||r.readyState!==WebSocket.OPEN)return!1;const a=Op(e,{sessionId:t,targetSessionId:t,data:n});try{return r.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:a.payload}})),!0}catch{return!1}}vs.registerPtyInputSender(kh);class XD{constructor(t){st(this,"daemonId");st(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(ls==null?void 0:ls.readyState)===WebSocket.OPEN}get connectionState(){return(ls==null?void 0:ls.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,n){return ur(this.daemonId,t,n)}async sendInput(t,n){return ur(this.daemonId,"cdp_remote_action",{action:t,params:n,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,qs&&(clearInterval(qs),qs=null);const n=async()=>{if(this.hasCommandChannel)try{const r=await ur(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(r!=null&&r.success&&(r!=null&&r.base64)){const a=await fetch(`data:image/jpeg;base64,${r.base64}`).then(o=>o.blob());vs.emitScreenshot(this.daemonId,a)}}catch{}};n(),qs=setInterval(n,2e3)}stopScreenshots(t){qs&&(clearInterval(qs),qs=null)}}let Zt=null;function ZD(e){return(!Zt||Zt.daemonId!==e)&&(Zt=new XD(e)),Zt}function eP({children:e}){const t=l.useRef(pr()),n=pr();t.current=n;const{setUserName:r}=Ss(),a=l.useRef(r);a.current=r;const o=l.useRef(null),i=l.useRef(null),[,c]=l.useState("disconnected"),d=l.useCallback((h,v)=>{c(h),dr==null||dr(h,v)},[]),p=l.useRef(null),u=l.useRef(),m=l.useRef(zd),f=l.useRef(!0),g=l.useRef(!1),k=l.useRef("initial_connect");return l.useEffect(()=>{f.current=!0,g.current=!1;function h(){var b,j;if(!f.current||((b=p.current)==null?void 0:b.readyState)===WebSocket.OPEN||((j=p.current)==null?void 0:j.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${Xr}...`),Xn("connect_attempt",{url:Xr,reason:k.current,delayMs:m.current});let w;try{w=new WebSocket(Xr)}catch(C){console.error("[Standalone WS] Failed to create WebSocket:",C),v();return}p.current=w,w.onopen=()=>{if(!f.current){w.close();return}d("connected"),m.current=zd,Xn("open",{url:Xr,reason:k.current}),us.resubscribeAll({sendData:Di}),console.log("[Standalone WS] Connected")},ls=w,w.onmessage=C=>{var y,x;try{const N=JSON.parse(C.data);if((N.type==="command_result"||N.type==="error")&&N.requestId){const S=Da.get(N.requestId);S&&(Da.delete(N.requestId),N.type==="error"?S.reject(new Error(((y=N.data)==null?void 0:y.message)||"Command failed")):S.resolve(N.data));return}if(N.type==="session_output"){const S=N.sessionId||N.cliId||N.cliType;S&&vs.emitSessionOutput(S,typeof N.data=="string"?N.data:"",typeof N.seq=="number"?N.seq:void 0);return}if(N.type==="runtime_snapshot"){vs.emitRuntimeSnapshot(N.sessionId,typeof N.text=="string"?N.text:"",typeof N.seq=="number"?N.seq:0,!!N.truncated,typeof N.cols=="number"?N.cols:void 0,typeof N.rows=="number"?N.rows:void 0);return}if(N.type==="topic_update"){const S=N.update;S&&us.publish(S);return}if(N.type==="status"||N.type==="initial_state"){const S=N.data;if(!S)return;const{injectEntries:A,markLoaded:M,getIdes:P}=t.current,D=S.instanceId||"standalone",I=P().find(H=>H.id===D),_=ZD(D);vs.register(D,_),vs.setState(D,"connected"),d("connected",D),vs.emitStatus(D,S);const W=ga(S,{daemonId:D,existingDaemon:I,existingEntries:P()});Kd("ws_status",{type:N.type,daemonId:D,sessions:(S.sessions||[]).map(H=>({id:H.id,parentId:H.parentId,providerType:H.providerType,kind:H.kind,transport:H.transport,unread:H.unread,inboxBucket:H.inboxBucket,lastSeenAt:H.lastSeenAt,lastUpdated:H.lastUpdated,title:H.title})),recentLaunches:(S.recentLaunches||[]).map(H=>({id:H.id,providerType:H.providerType,kind:H.kind,workspace:H.workspace,lastLaunchedAt:H.lastLaunchedAt}))}),Kd("entries",{daemonId:D,entries:W.filter(H=>H.type!=="adhdev-daemon").map(H=>({id:H.id,type:H.type,unread:H.unread,inboxBucket:H.inboxBucket,lastSeenAt:H.lastSeenAt,lastUpdated:H.lastUpdated,sessionId:H.sessionId}))}),W.length>0&&A(W,{authoritativeDaemonIds:[D]}),M(),i.current!==D&&((x=o.current)==null||x.call(o),i.current=D,o.current=us.subscribe({sendData:Di},D,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${D}`,params:{includeSessions:!0}},H=>{if(H.topic!=="daemon.metadata")return;const L=t.current.getIdes(),O=L.find(T=>T.id===D),E=ga(H.status,{daemonId:D,existingDaemon:O,existingEntries:L,timestamp:H.timestamp});E.length>0&&t.current.injectEntries(E,{authoritativeDaemonIds:[D]}),H.userName&&a.current&&a.current(H.userName)}))}}catch(N){console.error("[Standalone WS] Parse error:",N)}},w.onclose=C=>{f.current&&(Zt==null||Zt.stopScreenshots(),Zt&&vs.setState(Zt.daemonId,"disconnected"),d("disconnected"),p.current=null,k.current=`close:${C.code}${C.wasClean?":clean":":unclean"}`,Xn("close",{code:C.code,reason:C.reason||"",wasClean:C.wasClean}),v())},w.onerror=C=>{g.current||!f.current||(k.current="error",Xn("error",{message:C instanceof Event?"event":String(C),readyState:w.readyState}),console.warn("[Standalone WS] Error, will reconnect:",C))}}function v(){if(!f.current)return;clearTimeout(u.current);const w=m.current;console.log(`[Standalone WS] Reconnecting in ${w}ms...`),Xn("schedule_reconnect",{reason:k.current,delayMs:w}),u.current=setTimeout(()=>{m.current=Math.min(m.current*1.5,YD),h()},w)}return h(),()=>{var w;f.current=!1,g.current=!0,(w=o.current)==null||w.call(o),o.current=null,i.current=null,clearTimeout(u.current),p.current&&(p.current.onerror=null,p.current.onclose=null,p.current.close(),p.current=null,ls=null),Zt&&(Zt.stopScreenshots(),vs.unregister(Zt.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function tP({children:e}){const[t,n]=l.useState("disconnected"),[r,a]=l.useState(null);l.useEffect(()=>(dr=(i,c)=>{n(i),c&&a(c)},()=>{dr=null}),[]);const o=l.useMemo(()=>{const i=t==="connected",c=QD(t),d={};return r&&(d[r]=c),d.standalone=c,{wsStatus:t,isConnected:i,connectionStates:d}},[t,r]);return s.jsx(xf,{connectionOverrides:o,children:s.jsx(eP,{children:e})})}const Sh="adhdev_standalone_font_preferences",tn={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Qa=[{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"}],yr=[{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"}],sP=new Set(Qa.map(e=>e.id)),nP=new Set(yr.map(e=>e.id));function ws(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:da("chat",t.chat),code:da("code",t.code),terminal:da("terminal",t.terminal)}}function da(e,t){const n=tn[e],r=t&&typeof t=="object"&&!Array.isArray(t)?t:{},a=typeof r.preset=="string"?r.preset.trim():"",o=typeof r.customFamily=="string"?r.customFamily.trim():"";return(e==="chat"?sP:nP).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:n:{preset:a}:n}function ua(e,t){var a;const n=da(e,t);if(n.preset==="custom"&&n.customFamily)return n.customFamily;const r=e==="chat"?Qa:yr;return((a=r.find(o=>o.id===n.preset))==null?void 0:a.family)||r[0].family}function rP(e){const t=ws(e),n=ua("chat",t.chat),r=ua("code",t.code),a=ua("terminal",t.terminal);return{"--chat-font-family":n,"--chat-code-font-family":r,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function Ks(e,t=document.documentElement){const n=ws(e),r=rP(n);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(r))t.style.setProperty(a,o);return n}function Pi(e){const t=ws(e);try{localStorage.setItem(Sh,JSON.stringify(t))}catch{}return t}function aP(){try{const e=localStorage.getItem(Sh);if(e)return ws(JSON.parse(e))}catch{}return tn}function oP(){return Ks(aP())}function Zn(e,t){var r;const n=e==="chat"?Qa:yr;return((r=n.find(a=>a.id===t))==null?void 0:r.label)||n[0].label}function iP({children:e}){const t=wr(),n=Ri(),{t:r}=Se("common"),a=l.useMemo(()=>[{id:"dashboard",path:"/dashboard",icon:s.jsx(lu,{}),label:r("standalone.nav.dashboard"),active:n.pathname.startsWith("/dashboard"),onSelect:()=>t("/dashboard")},{id:"machine",path:"/machines",icon:s.jsx(_s,{}),label:"Burrow",active:n.pathname.startsWith("/machines"),onSelect:()=>t("/machines")},{id:"mesh",path:"/mesh",icon:s.jsx(ts,{}),label:"Mesh",active:n.pathname.startsWith("/mesh"),onSelect:()=>t("/mesh")},{id:"settings",path:"/settings",icon:s.jsx(La,{}),label:r("standalone.nav.settings"),active:n.pathname.startsWith("/settings"),onSelect:()=>t("/settings")}],[n.pathname,t,r]),o=l.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:r("standalone.nav.docs")}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(du,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:r("standalone.nav.docs")},{id:"about",label:r("standalone.nav.about"),icon:s.jsx(Hi,{}),active:n.pathname==="/about",onSelect:()=>t("/about"),title:r("standalone.nav.about")}],[n.pathname,t,r]);return s.jsx(qS,{brand:({collapsed:i})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&s.jsx("span",{children:"ADHDev"})]}),navItems:a,footerItems:o,footerInfo:({collapsed:i})=>i?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","1.0.18"]}),footerActions:({collapsed:i,toggleCollapsed:c})=>s.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:c,title:r(i?"standalone.layout.expandSidebar":"standalone.layout.collapseSidebar"),children:[s.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&s.jsx("span",{className:"text-xs",children:r("standalone.layout.collapse")})]}),children:e})}const lP=[{icon:s.jsx(_s,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(ln,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(mu,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(hs,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(mr,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(du,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],cP=[{icon:s.jsx(Vf,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(lu,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Rn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Wf,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(cu,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Gf,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],dP=[{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 uP(){const{t:e}=Se("common");return s.jsxs(jr,{icon:s.jsx(Hi,{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.18"]}),children:[s.jsx(ht,{children:s.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[s.jsxs("div",{className:"max-w-2xl",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:e("standalone.about.selfHostedEdition")}),s.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:e("standalone.about.headline")}),s.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:e("standalone.about.description")})]}),s.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.docs")}),s.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.github")}),s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.tryCloud")})]})]})}),s.jsx(ht,{title:e("standalone.about.includedSection"),description:e("standalone.about.includedDescription"),children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:lP.map(t=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:t.icon}),t.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:t.desc})]},t.title))})}),s.jsx(ht,{title:e("standalone.about.inventorySection"),description:e("standalone.about.inventoryDescription"),children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:Wp.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:Gp.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:Up.map(t=>`${t.icon} ${t.name}`)}].map(t=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[s.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:t.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:t.items.map(n=>s.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:n},n))})]},t.label))})}),s.jsx(ht,{title:e("standalone.about.cloudExtrasSection"),description:e("standalone.about.cloudExtrasDescription"),children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:cP.map(t=>s.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:t.icon}),t.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:t.desc})]},t.title))})}),s.jsx(ht,{title:e("standalone.about.comparisonSection"),description:e("standalone.about.comparisonDescription"),children:s.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:s.jsxs("table",{className:"w-full text-[13px]",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"bg-bg-secondary",children:[s.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:e("standalone.about.featureHeader")}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:e("standalone.about.selfhostHeader")}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:e("standalone.about.cloudHeader")})]})}),s.jsx("tbody",{children:dP.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(Ga,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:e("standalone.about.cloudOptional"),description:e("standalone.about.cloudOptionalDescription"),action:s.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:e("standalone.about.compareCloud")}),s.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[s.jsx(nb,{size:14,className:"mr-1"}),e("standalone.about.discord")]})]})})]})}function Vo(e,t,n){return{...e,[t]:n}}function Yo({surface:e,title:t,description:n,value:r,options:a,onChange:o}){const{t:i}=Se("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(YS,{value:r.preset,onChange:c=>{const d=c.target.value;o(d==="custom"?{preset:"custom",customFamily:r.customFamily||""}:{preset:d})},children:a.map(c=>s.jsx("option",{value:c.id,children:c.label},c.id))}),r.preset==="custom"&&s.jsx(ds,{type:"text",className:"font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:r.customFamily||"",onChange:c=>o({preset:"custom",customFamily:c.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:i("standalone.fonts.resolvedStack")})," ",s.jsx("span",{className:"font-mono break-all",children:ua(e,r)})]})]})]})}function pP({value:e,savedValue:t,saving:n=!1,error:r,notice:a,onChange:o,onSave:i,onResetToSaved:c,onResetToDefaults:d}){const{t:p}=Se("common"),u=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:p("standalone.fonts.fontOverridesNotice")}),r&&s.jsx(Ht,{variant:"error",children:r}),a&&s.jsx(Ht,{variant:"success",children:a}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(Yo,{surface:"chat",title:p("standalone.fonts.chat"),description:p("standalone.fonts.chatDescription"),value:e.chat,options:Qa,onChange:m=>o(Vo(e,"chat",m))}),s.jsx(Yo,{surface:"code",title:p("standalone.fonts.code"),description:p("standalone.fonts.codeDescription"),value:e.code,options:yr,onChange:m=>o(Vo(e,"code",m))}),s.jsx(Yo,{surface:"terminal",title:p("standalone.fonts.terminal"),description:p("standalone.fonts.terminalDescription"),value:e.terminal,options:yr,onChange:m=>o(Vo(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: ",Zn("chat",e.chat.preset)," · Code: ",Zn("code",e.code.preset)," · Terminal: ",Zn("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[p("standalone.fonts.defaults")," ",Zn("chat",tn.chat.preset)," / ",Zn("code",tn.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(Ns,{type:"button",variant:"primary",size:"sm",onClick:i,disabled:n||!u,children:p(n?"standalone.fonts.saving":"standalone.fonts.saveFontSettings")}),s.jsx(Ns,{type:"button",variant:"secondary",size:"sm",onClick:c,disabled:n||!u,children:p("standalone.fonts.revertToSaved")}),s.jsx(Ns,{type:"button",variant:"secondary",size:"sm",onClick:d,disabled:n,children:p("standalone.fonts.resetToDefaults")})]})]})}function mP(){const{t:e}=Se("common"),{ides:t}=Ss(),n=t.find(B=>B.type==="adhdev-daemon"),r=(n==null?void 0:n.detectedIdes)||[],{sendCommand:a}=vt(),{userName:o}=Ss(),[i,c]=l.useState(o||""),[d,p]=l.useState(null),[u,m]=l.useState(null),[f,g]=l.useState(tn),[k,h]=l.useState(!1),[v,w]=l.useState(""),[b,j]=l.useState(""),[C,y]=l.useState("127.0.0.1"),[x,N]=l.useState(""),[S,A]=l.useState(""),[M,P]=l.useState(""),[D,I]=l.useState(""),[_,W]=l.useState(""),[H,L]=l.useState(!1),O=async()=>{const ie=await(await ys("/auth/session")).json();p(ie)},E=async()=>{const ie=await(await ys("/api/v1/standalone/preferences")).json();m(ie),y(ie.standaloneBindHost);const K=ws(ie.standaloneFontPreferences);g(K),Ks(K),Pi(K)};l.useEffect(()=>{o!==void 0&&c(o)},[o]),l.useEffect(()=>{Promise.all([O(),E()]).catch(B=>{I(B instanceof Error?B.message:String(B))})},[]),l.useEffect(()=>{Ks(f)},[f]);const T=B=>{const ie=B.target.value.trim();n!=null&&n.id&&ie!==o&&a(n.id,"set_user_name",{userName:ie}).catch(console.error)},[$,R]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),G=B=>{R(B);try{localStorage.setItem("adhdev_sound",B?"1":"0")}catch{}},Q=async()=>{w(""),j(""),h(!0);try{const B=ws(f),ie=await ys("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:B})}),K=await ie.json();if(!ie.ok)throw new Error((K==null?void 0:K.error)||"Failed to save standalone font preferences");const le=ws(K.standaloneFontPreferences);m(K),g(le),Ks(le),Pi(le),j(e("standalone.settings.fontsSaved"))}catch(B){w(B instanceof Error?B.message:String(B))}finally{h(!1)}},re=()=>{const B=ws(u==null?void 0:u.standaloneFontPreferences);w(""),j(""),g(B),Ks(B)},J=()=>{w(""),j(""),g(tn),Ks(tn)},X=async()=>{I(""),W(""),L(!0);try{const B=await ys("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:C})}),ie=await B.json();if(!B.ok)throw new Error((ie==null?void 0:ie.error)||"Failed to save standalone network preference");m(ie),y(ie.standaloneBindHost),W(ie.standaloneBindHost==="0.0.0.0"?e("standalone.settings.networkSavedAll"):e("standalone.settings.networkSavedLocal"))}catch(B){I(B instanceof Error?B.message:String(B))}finally{L(!1)}},ue=async()=>{if(I(""),W(""),S.trim().length<4){I(e("standalone.settings.passwordTooShort"));return}if(S!==M){I(e("standalone.settings.passwordMismatch"));return}L(!0);try{const B=await ys("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:x,newPassword:S})}),ie=await B.json();if(!B.ok)throw new Error((ie==null?void 0:ie.error)||"Failed to save password");p(ie),await E(),N(""),A(""),P(""),W(d!=null&&d.hasPasswordAuth?e("standalone.settings.passwordUpdated"):e("standalone.settings.passwordEnabled")),wh()}catch(B){I(B instanceof Error?B.message:String(B))}finally{L(!1)}},se=async()=>{I(""),W(""),L(!0);try{const B=await ys("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:x,clear:!0})}),ie=await B.json();if(!B.ok)throw new Error((ie==null?void 0:ie.error)||"Failed to clear password");p(ie),await E(),N(""),A(""),P(""),W(e("standalone.settings.passwordDisabled"))}catch(B){I(B instanceof Error?B.message:String(B))}finally{L(!1)}};return s.jsxs(jr,{icon:s.jsx(La,{className:"text-text-primary"}),title:e("standalone.settings.title"),subtitle:e("standalone.settings.subtitle"),widthClassName:"max-w-5xl",children:[s.jsx(Ht,{variant:"info",children:e("standalone.settings.infoNotice")}),(d==null?void 0:d.publicHostWarning)&&s.jsx(Ht,{variant:"warning",children:e("standalone.settings.publicHostWarning")}),s.jsx(ht,{title:e("standalone.settings.daemonSection"),description:e("standalone.settings.daemonDescription"),children:s.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.versionLabel")}),s.jsxs("span",{className:"font-mono text-xs",children:["v","1.0.18"]}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.statusLabel")}),s.jsx("span",{className:n?"text-green-400":"text-yellow-400",children:e(n?"standalone.settings.statusRunning":"standalone.settings.statusNotConnected")}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.currentBindLabel")}),s.jsx("span",{className:"font-mono text-xs",children:(u==null?void 0:u.currentBindHost)||(d==null?void 0:d.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.defaultBindLabel")}),s.jsx("span",{className:"font-mono text-xs",children:(u==null?void 0:u.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.authLabel")}),s.jsx("span",{className:"text-xs",children:d!=null&&d.hasPasswordAuth?e("standalone.settings.authPassword"):d!=null&&d.hasTokenAuth?e("standalone.settings.authToken"):e("standalone.settings.authNone")})]})}),s.jsx(ht,{title:e("standalone.settings.networkSection"),description:e("standalone.settings.networkDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:e("standalone.settings.networkHint")}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:C==="127.0.0.1",onChange:()=>y("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:e("standalone.settings.localhostLabel")}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:e("standalone.settings.localhostHint")})]})]}),s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:C==="0.0.0.0",onChange:()=>y("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:e("standalone.settings.allInterfacesLabel")}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:e("standalone.settings.allInterfacesHint")})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx(Ns,{type:"button",variant:"primary",size:"sm",onClick:()=>{X()},disabled:H,children:e(H?"standalone.settings.saving":"standalone.settings.saveNetworkMode")}),s.jsx("span",{className:"text-xs text-text-muted",children:e("standalone.settings.networkRestartHint",{host:(u==null?void 0:u.currentBindHost)||(d==null?void 0:d.boundHost)||"127.0.0.1"})})]})]})}),s.jsx(ht,{title:e("standalone.settings.securitySection"),description:e("standalone.settings.securityDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:d!=null&&d.hasPasswordAuth?e("standalone.settings.passwordSet"):e("standalone.settings.passwordNotSet")}),D&&s.jsx(Ht,{variant:"error",children:D}),_&&s.jsx(Ht,{variant:"success",children:_}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx(ds,{type:"password",placeholder:d!=null&&d.hasPasswordAuth?e("standalone.settings.currentPasswordPlaceholder"):e("standalone.settings.currentPasswordFirstTimePlaceholder"),value:x,onChange:B=>N(B.target.value)}),s.jsx(ds,{type:"password",placeholder:d!=null&&d.hasPasswordAuth?e("standalone.settings.newPasswordPlaceholder"):e("standalone.settings.newPasswordFirstTimePlaceholder"),value:S,onChange:B=>A(B.target.value)}),s.jsx(ds,{type:"password",className:"md:col-span-2",placeholder:e("standalone.settings.confirmPasswordPlaceholder"),value:M,onChange:B=>P(B.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ns,{type:"button",variant:"primary",size:"sm",onClick:()=>{ue()},disabled:H,children:H?e("standalone.settings.saving"):d!=null&&d.hasPasswordAuth?e("standalone.settings.updatePassword"):e("standalone.settings.enablePassword")}),(d==null?void 0:d.hasPasswordAuth)&&s.jsx(Ns,{type:"button",variant:"danger",size:"sm",onClick:()=>{se()},disabled:H,children:e("standalone.settings.disablePassword")})]})]})}),s.jsx(ht,{title:e("standalone.settings.detectedIdesSection"),description:e("standalone.settings.detectedIdesDescription"),children:r.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:e("standalone.settings.noIdesDetected")}):s.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(B=>s.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${B.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:B.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:B.type})]},B.type))})}),s.jsx(ht,{title:e("standalone.settings.machineSection"),description:e("standalone.settings.machineDescription"),children:s.jsx(nC,{ides:t,emptyMessage:e("standalone.settings.daemonNotConnected")})}),s.jsx(ht,{title:e("standalone.settings.appearanceSection"),description:e("standalone.settings.appearanceDescription"),children:s.jsx(SC,{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(pP,{value:f,savedValue:ws(u==null?void 0:u.standaloneFontPreferences),saving:k,error:v,notice:b,onChange:g,onSave:()=>{Q()},onResetToSaved:re,onResetToDefaults:J})]})})}),s.jsx(ht,{title:e("standalone.settings.notificationsSection"),description:e("standalone.settings.notificationsDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(ZS,{}),s.jsx(zs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(sb,{size:15})," ",e("standalone.settings.soundEffectsLabel")]}),description:e("standalone.settings.soundEffectsDescription"),checked:$,onChange:G})]})}),s.jsx(ht,{title:e("standalone.settings.profileSection"),description:e("standalone.settings.profileDescription"),children:s.jsx("div",{className:"flex flex-col gap-3",children:s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[s.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[s.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[s.jsx(Of,{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(ds,{type:"text",className:"w-48 text-right",placeholder:e("standalone.settings.displayNamePlaceholder"),value:i,onChange:B=>c(B.target.value),onBlur:T,onKeyDown:B=>{B.key==="Enter"&&B.currentTarget.blur()}})]})})})]})}const hP=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],sr="adhdev_onboarding_done",fP=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],bP={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function gP({onDone:e}){const{t}=Se("common"),[n,r]=l.useState([]),[a,o]=l.useState(new Set(hP)),[i,c]=l.useState(!0),[d,p]=l.useState(null),[u,m]=l.useState(!1),[f,g]=l.useState(null),[k,h]=l.useState("all");l.useEffect(()=>{let x=!1;const N=window.location.hostname==="localhost"?"/registry":"https://api.adhf.dev/api/v1/registry";return fetch(`${N}/providers?sort=popular&limit=100`).then(S=>{if(!S.ok)throw new Error(`HTTP ${S.status}`);return S.json()}).then(S=>{x||r(S.providers??[])}).catch(S=>{x||p(S instanceof Error?S.message:String(S))}).finally(()=>{x||c(!1)}),()=>{x=!0}},[]);const v=n.filter(x=>k==="all"||x.category===k),w=["cli","ide","extension","acp"].map(x=>({category:x,items:v.filter(N=>N.category===x)})).filter(x=>x.items.length>0),b=l.useCallback(x=>{o(N=>{const S=new Set(N);return S.has(x)?S.delete(x):S.add(x),S})},[]),j=l.useCallback(async()=>{if(a.size===0){localStorage.setItem(sr,"1"),e();return}m(!0);const x=[];for(const N of a)try{const A=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:N})})).json().catch(()=>({}));x.push({type:N,ok:!!A.success,error:A.error})}catch(S){x.push({type:N,ok:!1,error:S instanceof Error?S.message:String(S)})}g(x),m(!1),x.every(N=>N.ok)&&localStorage.setItem(sr,"1")},[a,e]),C=l.useCallback(()=>{localStorage.setItem(sr,"1"),e()},[e]),y=l.useCallback(()=>{f&&f.every(x=>x.ok)?e():u||C()},[f,u,e,C]);return s.jsx(Yu,{open:!0,onClose:y,size:"lg",contentClassName:"max-w-2xl",title:t("standalone.onboarding.title"),footer:s.jsxs("div",{className:"flex w-full items-center gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:t(a.size!==1?"standalone.onboarding.selectedCount_other":"standalone.onboarding.selectedCount_one",{count:a.size})}),s.jsxs("div",{className:"ml-auto flex gap-2",children:[s.jsx(Ns,{variant:"secondary",size:"sm",onClick:C,disabled:u,children:t("standalone.onboarding.skip")}),s.jsx(Ns,{variant:"primary",size:"sm",onClick:()=>{f?(localStorage.setItem(sr,"1"),e()):j()},disabled:u||!f&&a.size===0,children:u?t("standalone.onboarding.installing"):f?t("standalone.onboarding.done"):t("standalone.onboarding.installCount",{count:a.size})})]})]}),children:s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsx("div",{className:"text-[12px] text-text-muted",children:t("standalone.onboarding.intro")}),!i&&!d&&n.length>0&&s.jsx("div",{className:"flex gap-1 flex-wrap border-b border-border-subtle pb-2",children:fP.map(x=>{const N=x.key==="all"?n.length:n.filter(S=>S.category===x.key).length;return N===0&&x.key!=="all"?null:s.jsxs("button",{onClick:()=>h(x.key),className:`machine-btn text-[10px] px-2 py-0.5 ${k===x.key?"bg-accent-primary/12 border-accent-primary/40 text-accent-primary":""}`,children:[x.label," ",s.jsxs("span",{className:"opacity-60",children:["(",N,")"]})]},x.key)})}),i&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.loadingRegistry")}),!i&&d&&s.jsx(Ht,{variant:"error",children:t("standalone.onboarding.loadError",{error:d})}),!i&&!d&&v.length===0&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.noProviders")}),!i&&!d&&v.length>0&&s.jsx("div",{className:"flex flex-col gap-4",children:w.map(x=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:bP[x.category]??x.category}),s.jsx("div",{className:"grid gap-1.5",children:x.items.map(N=>{var D,I;const S=a.has(N.type),A=f==null?void 0:f.find(_=>_.type===N.type),M=((D=N.manifest)==null?void 0:D.icon)??"📦",P=((I=N.manifest)==null?void 0:I.details)??"";return s.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${S?"bg-accent-primary/[0.06] border-accent-primary/30":"bg-bg-glass border-border-subtle hover:bg-bg-glass-hover"}`,children:[s.jsx("input",{type:"checkbox",checked:S,onChange:()=>b(N.type),disabled:u,className:"shrink-0"}),s.jsx("span",{className:"text-base shrink-0",children:M}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[13px] font-medium text-text-primary truncate",children:N.displayName}),P&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:P})]}),A&&s.jsx("span",{className:`text-[10px] font-semibold ${A.ok?"text-status-online":"text-status-error"}`,children:A.ok?t("standalone.onboarding.installed"):t("standalone.onboarding.installFailed",{error:A.error??"failed"})})]},N.type)})})]},x.category))})]})})}function xP(){try{return localStorage.getItem(sr)==="1"}catch{return!1}}RS();fC();Cy();oP();const vP=tu({baseUrl:"",getToken:Tl});function yP({children:e}){const{t}=Se("common"),[n,r]=l.useState(null),[a,o]=l.useState(!0),[i,c]=l.useState(""),[d,p]=l.useState(""),[u,m]=l.useState(!1),f=async()=>{o(!0),p("");try{const h=await(await ys("/auth/session")).json();r(h)}catch(k){p(k instanceof Error?k.message:String(k))}finally{o(!1)}};l.useEffect(()=>{f()},[]),l.useEffect(()=>{if(!n||n.required&&!n.authenticated)return;let k=!1;return(async()=>{try{const h=await ys("/api/v1/standalone/preferences");if(!h.ok)return;const v=await h.json();if(k)return;const w=ws(v.standaloneFontPreferences);Ks(w),Pi(w)}catch{}})(),()=>{k=!0}},[n==null?void 0:n.authenticated,n==null?void 0:n.required]);const g=async k=>{k.preventDefault(),m(!0),p("");try{const h=await ys("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),v=await h.json();if(!h.ok)throw new Error((v==null?void 0:v.error)||"Login failed");r(v),c(""),wh()}catch(h){p(h instanceof Error?h.message:String(h))}finally{m(!1)}};return a?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:t("standalone.auth.loading")}):n?!n.required||n.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:t("standalone.auth.signInTitle")}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:n.hasPasswordAuth?t("standalone.auth.passwordProtected"):t("standalone.auth.tokenProtected")})]}),n.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:g,children:[s.jsx(ds,{type:"password",value:i,onChange:k=>c(k.target.value),placeholder:t("standalone.auth.passwordPlaceholder"),autoFocus:!0}),s.jsx(Ns,{type:"submit",variant:"primary",disabled:u||!i,className:"justify-center",children:t(u?"standalone.auth.signingIn":"standalone.auth.unlock")})]}):s.jsx(Ht,{variant:"warning",children:t("standalone.auth.noPasswordEnabled")}),d&&s.jsx(Ht,{variant:"error",children:d})]})}):s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:t("standalone.auth.loadError",{error:d||"unknown error"})})}function Vd(){const{t:e}=Se("common"),{ides:t,initialLoaded:n}=Ss();if(!n)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:e("standalone.machine.loading")});const r=t.find(a=>a.daemonMode||a.type==="adhdev-daemon");return r?s.jsx(Zo,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Zo,{to:"/dashboard",replace:!0})}function wP(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let n=!1;if(!xP())return fetch("/api/v1/providers/installed").then(r=>r.ok?r.json():{providers:[]}).then(r=>{n||(r.providers??[]).length===0&&t(!0)}).catch(()=>{}),()=>{n=!0}},[]),e?s.jsx(gP,{onDone:()=>t(!1)}):null}function kP(){const{t:e}=Se("common"),{ides:t}=Ss(),n=l.useMemo(()=>{for(const u of t)if(u.activeInteractivePrompt)return u.instanceId??u.id;return null},[t]),{promptSession:r,hasActivePrompt:a,responseError:o,isSubmitting:i,submit:c,cancel:d,reopen:p}=Qp(n);return a?s.jsxs("div",{className:"relative",children:[!r&&s.jsx("button",{type:"button",onClick:p,className:"fixed bottom-4 right-4 z-[79] btn btn-primary btn-sm shadow-lg",children:e("standalone.machine.awaitingInput")}),s.jsx(Au,{promptSession:r,isSubmitting:i,error:o,onSubmit:c,onCancel:d})]}):null}function SP(){const e=l.useMemo(()=>({sendCommand:ur,sendData:Di,sendPtyInput:kh}),[]);return s.jsx(ef,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(wf,{client:vP,children:s.jsx(yP,{children:s.jsx(tP,{children:s.jsx(Sf,{value:e,children:s.jsxs(Af,{sendDaemonCommand:ur,children:[s.jsx(kP,{}),s.jsxs(iP,{children:[s.jsx(wP,{}),s.jsxs(tf,{children:[s.jsx(Ps,{path:"/dashboard",element:s.jsx(wT,{})}),s.jsx(Ps,{path:"/machine",element:s.jsx(Vd,{})}),s.jsx(Ps,{path:"/machines/:id",element:s.jsx(TI,{})}),s.jsx(Ps,{path:"/machines",element:s.jsx(Vd,{})}),s.jsx(Ps,{path:"/about",element:s.jsx(uP,{})}),s.jsx(Ps,{path:"/settings",element:s.jsx(mP,{})}),s.jsx(Ps,{path:"/mesh",element:s.jsx(qD,{children:s.jsx(WD,{})})}),s.jsx(Ps,{path:"*",element:s.jsx(Zo,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}Mk({connectionManager:vs});sf(document.getElementById("root")).render(s.jsx(SP,{}));
|
|
121
|
+
Node removal cleanup policy: ${ge}`))return;const Ce=e.__sourceDaemonId||n;try{const He=await o(Ce,"remove_mesh_node",{meshId:e.id,nodeId:ce}),Ze=i(He);if((Ze==null?void 0:Ze.success)===!1)throw new Error(Ze.error||"Remove failed");j===ce&&C(null),await m(),g||await f(t)}catch(He){k((He==null?void 0:He.message)||"Remove node failed")}}async function ke(ce){if(!e)return;const z={...Ii(e),...ce},ge=e.__sourceDaemonId||n;try{R(!0),k(null);const Ce=await o(ge,"update_mesh",{meshId:e.id,policy:z}),Ne=i(Ce);if((Ne==null?void 0:Ne.success)===!1)throw new Error(Ne.error||"Policy update failed");await m()}catch(Ce){k((Ce==null?void 0:Ce.message)||"Policy update failed")}finally{R(!1)}}async function he(ce){if(!t)return;const z=(e==null?void 0:e.__sourceDaemonId)||n,ge=h[ce.id]||LD(ce),Ce=In(ge),Ne={...ce.policy||{}};delete Ne.provider_priority,Ce.length?Ne.providerPriority=Ce:delete Ne.providerPriority;try{b(ce.id),k(null);const He=await o(z,"update_mesh_node",{meshId:t,nodeId:ce.id,policy:Ne,providerPriority:Ce}),Ze=i(He);if((Ze==null?void 0:Ze.success)===!1){k(Ze.error||"Node policy update failed");return}await m()}catch(He){k((He==null?void 0:He.message)||"Node policy update failed")}finally{b(null)}}const[U,q]=l.useState(null);async function Z(ce,z){if(!t)return;const ge=(e==null?void 0:e.__sourceDaemonId)||n;try{q(ce.id),k(null);const Ce=await o(ge,"update_mesh_node",{meshId:t,nodeId:ce.id,policy:{slots:z}}),Ne=i(Ce);if((Ne==null?void 0:Ne.success)===!1){k(Ne.error||"Node slots update failed");return}await m()}catch(Ce){k((Ce==null?void 0:Ce.message)||"Node slots update failed")}finally{q(null)}}const[Y,fe]=l.useState(null);async function Me(ce,z){if(!t)return;const ge=(e==null?void 0:e.__sourceDaemonId)||n,Ce=z.map(Ne=>Ne.trim()).filter(Boolean);try{fe(ce.id),k(null);const Ne=await o(ge,"update_mesh_node",{meshId:t,nodeId:ce.id,capabilities:Ce}),He=i(Ne);if((He==null?void 0:He.success)===!1){k(He.error||"Node tag update failed");return}await m()}catch(Ne){k((Ne==null?void 0:Ne.message)||"Node tag update failed")}finally{fe(null)}}async function de(){if(!n||!t)return;const z={...(e==null?void 0:e.coordinator)||{}};G.override.trim()?z.systemPromptOverride=G.override:delete z.systemPromptOverride,G.append.trim()?z.systemPromptAppend=G.append:delete z.systemPromptAppend,delete z.systemPromptSuffix;try{J(!0),k(null);const ge=await o(n,"update_mesh",{meshId:t,coordinator:z}),Ce=i(ge);if((Ce==null?void 0:Ce.success)===!1){k(Ce.error||"Coordinator prompt save failed");return}await m()}catch(ge){k((ge==null?void 0:ge.message)||"Coordinator prompt save failed")}finally{J(!1)}}async function F(ce){if(!n||!t)return;const z=(X[ce.id]||"").trim();try{B(ce.id),k(null);const ge=await o(n,"update_mesh_node",{meshId:t,nodeId:ce.id,systemPrompt:z}),Ce=i(ge);if((Ce==null?void 0:Ce.success)===!1){k(Ce.error||"Node instruction save failed");return}await m()}catch(ge){k((ge==null?void 0:ge.message)||"Node instruction save failed")}finally{B(null)}}async function me(){if(e){k(null),T(null);try{O(!0);const ce=c?await c(r,e.id,e):null,z=d(r,e.id,e,e.nodes||[],ce);if("error"in z)throw new Error(z.error);const ge=await p(z.targetDaemonId,{meshId:e.id,inlineMesh:z.inlineMesh,coordinatorNodeId:z.coordinatorNodeId,cliType:W.trim()||void 0});T(ge.message)}catch(ce){k((ce==null?void 0:ce.message)||"Coordinator launch failed")}finally{O(!1)}}}return{nodeProviderPriorityDrafts:h,setNodeProviderPriorityDrafts:v,savingNodePolicyId:w,selectedNodeId:j,setSelectedNodeId:C,showAddNode:y,setShowAddNode:x,nodeWorkspace:N,setNodeWorkspace:S,nodeProviderPriority:A,setNodeProviderPriority:M,nodeDaemonId:P,setNodeDaemonId:D,nodeCustomPath:I,setNodeCustomPath:_,nodePickerWorkspaces:K,nodePickerProviders:le,coordinatorCliType:W,setCoordinatorCliType:H,launchingCoordinator:L,launchResult:E,savingPolicy:$,coordinatorPromptDraft:G,setCoordinatorPromptDraft:Q,savingCoordinatorPrompt:re,nodeSystemPromptDrafts:X,setNodeSystemPromptDrafts:ue,savingNodeSystemPromptId:se,savingNodeSlotsId:U,savingNodeCapabilitiesId:Y,handleAddNode:je,handleRemoveNode:we,handleUpdatePolicy:ke,handleUpdateNodeProviderPriority:he,handleUpdateNodeSlots:Z,handleUpdateNodeCapabilities:Me,handleSaveCoordinatorPrompt:de,handleSaveNodeSystemPrompt:F,handleLaunchCoordinator:me}}function LD(e){var r;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>n.has(a)?!1:(n.add(a),!0))}function RD(e){const t=e.filter(r=>r.status==="pending"||r.status==="assigned"),n=e.filter(r=>r.status==="completed"||r.status==="failed"||r.status==="cancelled");return{active:t.length,historical:n.length,activeCounts:{pending:t.filter(r=>r.status==="pending").length,assigned:t.filter(r=>r.status==="assigned").length},historicalCounts:{completed:n.filter(r=>r.status==="completed").length,failed:n.filter(r=>r.status==="failed").length},counts:{pending:e.filter(r=>r.status==="pending").length,assigned:e.filter(r=>r.status==="assigned").length,completed:e.filter(r=>r.status==="completed").length,failed:e.filter(r=>r.status==="failed").length},staleAssignedCount:e.filter(r=>r.staleAssigned).length,recent:e.slice(0,20)}}function ED({primaryDaemonId:e,activeDaemonId:t,sendCommand:n,unwrapResult:r,loadLiveMesh:a,resolveCommandTarget:o}){const[i,c]=l.useState([]),[d,p]=l.useState(null),[u,m]=l.useState(!1),[f,g]=l.useState(null),k=l.useCallback(async v=>{if(!e||!v){c([]);return}try{const w=await n(e,"get_mesh_queue",{meshId:v});c(w!=null&&w.success?Array.isArray(w.queue)?w.queue:[]:[])}catch{c([])}},[e,n]);async function h(v){var w,b;if(v){m(!0),g(null);try{const j=a?await a(t,v.id,v):null,C=o(t,v.id,v,v.nodes||[],j);if("error"in C)throw new Error(C.error);const y=await n(C.targetDaemonId,"get_mesh_queue",{meshId:v.id}),x=r(y);if((x==null?void 0:x.success)===!1)throw new Error(x.error||"Queue load failed");const N=Array.isArray(((w=x==null?void 0:x.result)==null?void 0:w.rows)??(x==null?void 0:x.rows)??(x==null?void 0:x.queue))?((b=x==null?void 0:x.result)==null?void 0:b.rows)??(x==null?void 0:x.rows)??(x==null?void 0:x.queue):[];p(RD(N))}catch(j){g((j==null?void 0:j.message)||"Queue load failed")}finally{m(!1)}}}return{meshQueue:i,setMeshQueue:c,queueSummary:d,queueLoading:u,queueError:f,loadQueue:k,handleLoadQueue:h}}function _D(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}const vh=new Map;function yh(e){return e?vh.get(e)??null:null}function $D(e,t){!e||!t||vh.set(e,t)}function HD({selectedMeshId:e,loadMeshStatus:t,extractStatus:n,normalizeNode:r,gateIncompleteGraph:a}){const[o,i]=l.useState(()=>yh(e)),[c,d]=l.useState(!1),[p,u]=l.useState(null),[m,f]=l.useState("idle"),[g,k]=l.useState(!1),h=l.useRef(!1);async function v(w,b=e,j=!1){if(!(!w||!b))try{d(!j&&o===null),f(j?"settling":"first_paint"),u(null);const C=await t(w,b,{refresh:j,retryProfile:j?"settled":"interactive"});k(_D(C));const y=n(C),x=r&&y?{...y,nodes:(y.nodes??[]).map(N=>r(N,y.meshId??b,""))}:y;if(x){if(a&&!j&&o!==null&&!JN(Jm(x))){f("settling"),h.current||(h.current=!0,Promise.resolve().then(()=>v(w,b,!0)).finally(()=>{h.current=!1}));return}i(x),$D(b,x),f("settled")}else i(null),u("mesh_status returned an unexpected payload."),f("idle")}catch(C){o||i(null),u((C==null?void 0:C.message)||"Failed to load mesh graph"),f("idle")}finally{d(!1)}}return{meshGraphStatus:o,setMeshGraphStatus:i,graphLoading:c,graphError:p,setGraphError:u,graphProvenance:m,graphBootstrapFallback:g,loadGraph:v}}function FD(e,t,n,r,a){if(!e.length)return"";const o=String(a||"");if(o){const d=e.find(p=>Vs(p.id,o));return d?d.id:o}const i=t.find(d=>d.role==="host"),c=String((i==null?void 0:i.daemon_id)||(i==null?void 0:i.daemonId)||"");if(c){const d=e.find(p=>Vs(p.id,c));if(d)return d.id}return""}const BD=7e3,OD=45e3;function WD(){const e=PI(),{sendCommand:t,sendData:n,daemons:r,userName:a,loadMeshStatus:o,launchCoordinator:i,loadLiveMesh:c,extractStatus:d,unwrapResult:p,normalizeMesh:u,normalizeNode:m,resolveCommandTarget:f,features:g,gateIncompleteGraph:k}=e,h=_n(),v=r[0],w=(v==null?void 0:v.id)||"",b=l.useMemo(()=>((v==null?void 0:v.availableProviders)||[]).filter(rt=>rt.category==="cli").map(rt=>({id:rt.type||rt.id,name:rt.displayName||rt.name||rt.type,meshCoordinator:rt.meshCoordinator})),[v]),j=l.useMemo(()=>Tn((v==null?void 0:v.availableProviders)||[]),[v]),{meshes:C,selectedMeshId:y,setSelectedMeshId:x,loading:N,error:S,setError:A,showCreate:M,setShowCreate:P,createName:D,setCreateName:I,createRepoIdentity:_,setCreateRepoIdentity:W,createRepoRemoteUrl:H,setCreateRepoRemoteUrl:L,newMeshDaemonId:O,setNewMeshDaemonId:E,newMeshWorkspace:T,setNewMeshWorkspace:$,createPickerWorkspaces:R,loadMeshes:G,handleCreate:Q,handleDelete:re,cancelCreate:J}=DD({daemons:r,primaryDaemonId:w,sendCommand:t,unwrapResult:p,normalizeMesh:u,features:g,loadDaemonMetadata:h}),X=C.find(Le=>Le.id===y)||null,{meshGraphStatus:ue,setMeshGraphStatus:se,graphLoading:B,graphError:ie,setGraphError:K,loadGraph:le}=HD({selectedMeshId:y,loadMeshStatus:o,extractStatus:d,normalizeNode:m,gateIncompleteGraph:k}),[je,we]=l.useState(""),[ke,he]=l.useState(""),U=g.meshHostDaemonSection&&je||w,{meshQueue:q,loadQueue:Z}=ED({primaryDaemonId:w,activeDaemonId:U,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:f}),{setNodeProviderPriorityDrafts:Y,selectedNodeId:fe,setSelectedNodeId:Me,showAddNode:de,setShowAddNode:F,nodeWorkspace:me,setNodeWorkspace:ce,nodeProviderPriority:z,setNodeProviderPriority:ge,nodeDaemonId:Ce,setNodeDaemonId:Ne,nodeCustomPath:He,setNodeCustomPath:Ze,nodePickerWorkspaces:Ye,nodePickerProviders:ot,coordinatorCliType:be,setCoordinatorCliType:Pe,launchingCoordinator:Be,launchResult:it,savingPolicy:ae,coordinatorPromptDraft:_e,setCoordinatorPromptDraft:lt,savingCoordinatorPrompt:ct,nodeSystemPromptDrafts:Nt,setNodeSystemPromptDrafts:V,savingNodeSystemPromptId:ee,savingNodeSlotsId:oe,savingNodeCapabilitiesId:pe,handleAddNode:ve,handleRemoveNode:Te,handleUpdatePolicy:Ee,handleUpdateNodeSlots:De,handleUpdateNodeCapabilities:Ue,handleSaveCoordinatorPrompt:Ge,handleSaveNodeSystemPrompt:Xe,handleLaunchCoordinator:Fe}=PD({selectedMesh:X,selectedMeshId:y,primaryDaemonId:w,activeDaemonId:U,daemons:r,availableCliProviders:j,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:f,launchCoordinator:i,features:{addNodeDaemonPicker:g.addNodeDaemonPicker},loadMeshes:G,loadQueue:Z,queueSection:g.queueSection,setError:A}),Oe=l.useMemo(()=>r.find(Le=>Le.id===U)||v,[r,U,v]),Je=l.useMemo(()=>new Set(((X==null?void 0:X.nodes)||[]).map(Le=>String(Le.daemon_id||Le.daemonId||""))),[X]),te=l.useMemo(()=>r.filter(Le=>Le.id&&!Je.has(Le.id)),[r,Je]),xe=(X==null?void 0:X.nodes)||[],ye=l.useMemo(()=>xe.find(Le=>Vs(String(Le.daemon_id||Le.daemonId||""),je)),[xe,je]),$e=g.meshHostDaemonSection?!!ye:!0,Re=l.useMemo(()=>{if(!g.meshHostDaemonSection||!X)return{pinned:!1,daemonId:"",label:"",online:!1};const Le=X.meshHost,rt=ue!=null&&ue.meshId&&String(ue.meshId)===String(X.id??"")?ue.meshHost:void 0,Tt=rt!=null&&rt.hostDaemonId?rt:Le??rt,Jt=String((Tt==null?void 0:Tt.hostDaemonId)||""),Kt=xe.find(as=>as.role==="host"),rs=String((Tt==null?void 0:Tt.hostNodeId)||(Kt==null?void 0:Kt.id)||""),It=rs?xe.find(as=>String(as.id)===rs):void 0,bs=String((It==null?void 0:It.daemon_id)||(It==null?void 0:It.daemonId)||""),gs=Jt||bs;if(!gs)return{pinned:!1,daemonId:"",label:"",online:!1};const Is=r.find(as=>Jt&&Vs(as.id,Jt))||(bs?r.find(as=>Vs(as.id,bs)):void 0);if(Is)return{pinned:!0,daemonId:Is.id,label:UD(Is),online:!0};const $n=String((It==null?void 0:It.machineLabel)||"")||String((It==null?void 0:It.workspace)||"")||gs;return{pinned:!0,daemonId:gs,label:$n,online:!1}},[X,xe,r,ue,g.meshHostDaemonSection]),et=Re.daemonId,tt=Re.online,Ke=l.useMemo(()=>!g.meshHostDaemonSection||!Re.pinned?"":!tt&&ke&&r.some(Le=>Le.id===ke)?ke:et,[g.meshHostDaemonSection,Re.pinned,tt,ke,r,et]),kt=l.useMemo(()=>ue?[...new Set((ue.nodes??[]).map(Le=>String(Le.daemonId||Le.daemon_id||"")).filter(Boolean))]:[],[ue]),zt=ph({status:ue,daemonId:U||null,extraDaemonIds:kt,meshId:y,sendData:n});l.useEffect(()=>{Y(Object.fromEntries(((X==null?void 0:X.nodes)||[]).map(Le=>[Le.id,GD(Le)])))},[X]),l.useEffect(()=>{const Le=(X==null?void 0:X.coordinator)||{};lt({override:typeof Le.systemPromptOverride=="string"?Le.systemPromptOverride:"",append:typeof Le.systemPromptAppend=="string"?Le.systemPromptAppend:typeof Le.systemPromptSuffix=="string"?Le.systemPromptSuffix:""}),V(Object.fromEntries(((X==null?void 0:X.nodes)||[]).map(rt=>[rt.id,typeof rt.systemPrompt=="string"?rt.systemPrompt:""])))},[X]),l.useEffect(()=>{const Le=g.addNodeDaemonPicker?gr(ot):gr(j);de&&z.length===0&&Le.length>0&&ge(Le)},[de,j,ot,z.length,g.addNodeDaemonPicker]),l.useEffect(()=>{const Le=new Set(((X==null?void 0:X.nodes)||[]).map(rt=>rt.id));fe&&!Le.has(fe)&&Me(null)},[X,fe]);const ns=l.useMemo(()=>{var Le;if(!(!(ue!=null&&ue.meshId)||String(ue.meshId)!==String((X==null?void 0:X.id)??"")))return(Le=ue.meshHost)==null?void 0:Le.hostDaemonId},[ue,X]),Ae=l.useMemo(()=>FD(r,xe,U,w,ns),[r,xe,U,w,ns]);l.useEffect(()=>{if(!g.meshHostDaemonSection)return;if(!r.length&&!Re.pinned){we("");return}const Le=Re.pinned?Ke:Ae;Le&&!Vs(Le,je)&&we(Le)},[r,je,Re.pinned,Ke,Ae,g.meshHostDaemonSection]),l.useEffect(()=>{ke&&(tt||!r.some(Le=>Le.id===ke))&&he("")},[tt,ke,r]),l.useEffect(()=>{if(g.createDaemonPicker){if(!r.length){E("");return}(!O||!r.some(Le=>Le.id===O))&&E(r[0].id)}},[r,O,g.createDaemonPicker]),l.useEffect(()=>{var Le;if(!g.createDaemonPicker||!O){$("");return}if(!R.length){$("");return}R.some(rt=>rt.path===T)||$(((Le=R[0])==null?void 0:Le.path)||"")},[O,T,R,g.createDaemonPicker]);const Qe=l.useRef(null);l.useEffect(()=>{if(!y)return;const Le=Qe.current!==y;if(Qe.current=y,Le){const rt=yh(y);se(rt),K(null),le(U,y,rt!==null)}else K(null),le(U,y,!0)},[y,U]);const Ft=l.useRef(le);Ft.current=le;const St=l.useRef(!1),Gt=l.useRef(()=>{});Gt.current=()=>{St.current||!y||!U||(St.current=!0,Promise.resolve(Ft.current(U,y,!0)).finally(()=>{St.current=!1}))};const qt=g.meshStatePushRefresh?OD:BD;II({daemonIds:l.useMemo(()=>[U,...kt].filter(Boolean),[U,kt]),meshId:y,sendData:n,onRevisionAdvance:()=>{typeof document<"u"&&document.visibilityState!=="visible"||Gt.current()}}),l.useEffect(()=>{if(!y||!U||typeof document>"u")return;let Le=null;const rt=()=>{document.visibilityState==="visible"&&Gt.current()},Tt=()=>{Le===null&&(Le=setInterval(rt,qt))},Jt=()=>{Le!==null&&(clearInterval(Le),Le=null)},Kt=()=>{document.visibilityState==="visible"?Tt():Jt()};return document.visibilityState==="visible"&&Tt(),document.addEventListener("visibilitychange",Kt),()=>{Jt(),document.removeEventListener("visibilitychange",Kt)}},[y,U,qt]),l.useEffect(()=>{g.queueSection||Z(y)},[y,g.queueSection]);const ft=l.useMemo(()=>r.map(Le=>Le.id).filter(Boolean).sort().join(","),[r]),fs=l.useRef(!1);return l.useEffect(()=>{G(fs.current),fs.current=!0},[ft]),w?X?s.jsx(ID,{selectedMesh:X,error:S,onDismissError:()=>A(null),onBack:()=>{x(null),se(null)},onDelete:re,displayedMeshStatus:zt,graphLoading:B,graphError:ie,onRefreshGraph:()=>le(U,y,!0),savingPolicy:ae,onUpdatePolicy:Ee,coordinatorPromptDraft:_e,onCoordinatorPromptDraftChange:lt,savingCoordinatorPrompt:ct,onSaveCoordinatorPrompt:Ge,daemons:r,coordinatorDaemonId:je,onCoordinatorDaemonIdChange:we,coordinatorCliType:be,onCoordinatorCliTypeChange:Pe,launchingCoordinator:Be,launchResult:it,isHostNodeAttached:$e,selectedHostNode:ye,hostPinned:Re.pinned,hostLabel:Re.label,hostOnline:tt,hostRebindDaemonId:ke,onHostRebindDaemonIdChange:Le=>he(Le),onLaunchCoordinator:Fe,activeDaemon:Oe,activeDaemonId:U,meshQueue:q,userName:a,availableCliProviders:j,savingNodeSlotsId:oe,onUpdateNodeSlots:De,savingNodeCapabilitiesId:pe,onUpdateNodeCapabilities:Ue,nodeSystemPromptDrafts:Nt,onNodeSystemPromptDraftChange:(Le,rt)=>V(Tt=>({...Tt,[Le]:rt})),savingNodeSystemPromptId:ee,onSaveNodeSystemPrompt:Xe,selectedNodeId:fe,onSelectNode:Me,showAddNode:de,onShowAddNode:()=>F(!0),onCancelAddNode:()=>F(!1),nodeWorkspace:me,onNodeWorkspaceChange:ce,nodeProviderPriority:z,onNodeProviderPriorityChange:ge,nodeDaemonId:Ce,onNodeDaemonIdChange:Ne,nodeCustomPath:He,onNodeCustomPathChange:Ze,nodePickerWorkspaces:Ye,nodePickerProviders:ot,attachableDaemons:te,onAddNode:ve,onRemoveNode:Te,availableCliAgents:b,features:{coordinatorPrompt:g.coordinatorPrompt,meshHostDaemonSection:g.meshHostDaemonSection,hermesMcpConfig:g.hermesMcpConfig,addNodeDaemonPicker:g.addNodeDaemonPicker,nodeInstruction:g.nodeInstruction},sendCommand:t}):s.jsx(FI,{meshes:C,loading:N,error:S,onDismissError:()=>A(null),daemons:r,features:{createDaemonPicker:g.createDaemonPicker,maxMeshes:g.maxMeshes},showCreate:M,onToggleCreate:()=>P(!M),createName:D,onCreateNameChange:I,createRepoIdentity:_,onCreateRepoIdentityChange:W,createRepoRemoteUrl:H,onCreateRepoRemoteUrlChange:L,newMeshDaemonId:O,onNewMeshDaemonIdChange:E,newMeshWorkspace:T,onNewMeshWorkspaceChange:$,createPickerWorkspaces:R,onSelectMesh:x,onCreate:Q,onCancelCreate:J}):s.jsx(jr,{icon:s.jsx(ts,{}),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 UD(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function GD(e){var r;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>n.has(a)?!1:(n.add(a),!0))}function qD({children:e}){const{sendCommand:t,sendData:n}=vt(),{ides:r}=Ss(),a=l.useMemo(()=>r.filter(i=>i.daemonMode||i.type==="adhdev-daemon").map(i=>i),[r]),o=l.useMemo(()=>({sendCommand:t,sendData:n,daemons:a,userName:void 0,loadMeshStatus:async(i,c)=>t(i,"mesh_status",{meshId:c}),launchCoordinator:async(i,c)=>{var f;const d={meshId:c.meshId};c.cliType&&(d.cliType=c.cliType);const p=await t(i,"launch_mesh_coordinator",d),u=(p==null?void 0:p.result)??p;if((u==null?void 0:u.success)===!1)throw new Error(u.error||"Coordinator launch failed");const m=(u==null?void 0:u.sessionId)||((f=u==null?void 0:u.session)==null?void 0:f.id)||(u==null?void 0:u.targetSessionId);return{sessionId:m,message:m?`Coordinator launched (${m})`:"Coordinator launch command sent"}},loadLiveMesh:void 0,extractStatus:Xi,unwrapResult:i=>i,normalizeMesh:(i,c)=>i,normalizeNode:(i,c,d)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:DI}),[t,n,a]);return s.jsx(xh.Provider,{value:o,children:e})}function Tl(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function zD(e){if(typeof window>"u")return e;const t=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),n=Tl();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 ys(e,t){return await fetch(zD(e),{credentials:"same-origin",...t})}function wh(){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 KD{constructor(){st(this,"adapters",new Map);st(this,"states",new Map);st(this,"runtimeListeners",new Map);st(this,"screenshotCallbacks",new Map);st(this,"statusCallbacks",new Set);st(this,"stateChangeCallbacks",new Set);st(this,"ptyInputSender",null)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const n of this.adapters.keys())if(n.startsWith("standalone"))return n}return null}register(t,n){this.adapters.set(t,n),this.states.set(t,n.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,n){this.states.set(t,n);const r=this.resolveDaemonId(t)||t;this.stateChangeCallbacks.forEach(a=>a(r,n))}onStateChange(t){return this.stateChangeCallbacks.add(t),()=>{this.stateChangeCallbacks.delete(t)}}retryConnection(t){}get(t){const n=this.resolveDaemonId(t);return n?this.adapters.get(n):void 0}getState(t){const n=this.resolveDaemonId(t);return n&&this.states.get(n)||"disconnected"}registerPtyInputSender(t){this.ptyInputSender=t}sendData(t,n){return!1}sendPtyInput(t,n,r){return this.ptyInputSender?this.ptyInputSender(t,n,r):!1}onScreenshot(t,n){return this.screenshotCallbacks.set(t,n),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,n){this.screenshotCallbacks.forEach(r=>r(t,n))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,n){this.statusCallbacks.forEach(r=>r(t,n))}emitRuntimeSnapshot(t,n,r=0,a=!1,o,i){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:r,text:n,truncated:a,cols:o,rows:i})}emitSessionOutput(t,n,r){!t||typeof n!="string"||!n||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof r=="number"?{seq:r}:{},data:n})}onRuntimeEvent(t,n){const r=this.runtimeListeners.get(t)||new Set;return r.add(n),this.runtimeListeners.set(t,r),()=>{const a=this.runtimeListeners.get(t);a&&(a.delete(n),a.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,n,r){if(!n)return{success:!1,error:"sessionId is required"};const a=new URL(`/api/v1/runtime/${encodeURIComponent(n)}/snapshot`,window.location.origin);typeof(r==null?void 0:r.sinceSeq)=="number"&&a.searchParams.set("sinceSeq",String(r.sinceSeq));const o=await ys(`${a.pathname}${a.search}`);if(!o.ok){let c=`Runtime snapshot unavailable (${o.status})`;try{const d=await o.json();d!=null&&d.error&&(c=d.error)}catch{}return{success:!1,error:c}}const i=await o.json();return this.emitRuntimeEvent(n,{type:"runtime_snapshot",sessionId:n,seq:typeof i.seq=="number"?i.seq:0,text:typeof i.text=="string"?i.text:"",truncated:!!i.truncated,cols:typeof i.cols=="number"?i.cols:void 0,rows:typeof i.rows=="number"?i.rows:void 0,force:!!(r!=null&&r.force)}),{success:!0}}emitRuntimeEvent(t,n){var r;(r=this.runtimeListeners.get(t))==null||r.forEach(a=>a(n))}}const vs=new KD;function VD(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,n=Tl();return n?`${t}?token=${encodeURIComponent(n)}`:t}const Xr=VD(),zd=3e3,YD=3e4;let ls=null,JD=0;const Da=new Map;let qs=null,dr=null;function Kd(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Xn(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function QD(e){return e==="connected"?"connected":e}async function ur(e,t,n){const r=Op(e,n||{}),a=ls;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++JD}_${Date.now()}`;return new Promise((i,c)=>{const d=setTimeout(()=>{Da.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);Da.set(o,{resolve:p=>{clearTimeout(d),i(p)},reject:p=>{clearTimeout(d),c(p)}}),a.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:r.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function Di(e,t){const n=ls;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 kh(e,t,n){const r=ls;if(!r||r.readyState!==WebSocket.OPEN)return!1;const a=Op(e,{sessionId:t,targetSessionId:t,data:n});try{return r.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:a.payload}})),!0}catch{return!1}}vs.registerPtyInputSender(kh);class XD{constructor(t){st(this,"daemonId");st(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(ls==null?void 0:ls.readyState)===WebSocket.OPEN}get connectionState(){return(ls==null?void 0:ls.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,n){return ur(this.daemonId,t,n)}async sendInput(t,n){return ur(this.daemonId,"cdp_remote_action",{action:t,params:n,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,qs&&(clearInterval(qs),qs=null);const n=async()=>{if(this.hasCommandChannel)try{const r=await ur(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(r!=null&&r.success&&(r!=null&&r.base64)){const a=await fetch(`data:image/jpeg;base64,${r.base64}`).then(o=>o.blob());vs.emitScreenshot(this.daemonId,a)}}catch{}};n(),qs=setInterval(n,2e3)}stopScreenshots(t){qs&&(clearInterval(qs),qs=null)}}let Zt=null;function ZD(e){return(!Zt||Zt.daemonId!==e)&&(Zt=new XD(e)),Zt}function eP({children:e}){const t=l.useRef(pr()),n=pr();t.current=n;const{setUserName:r}=Ss(),a=l.useRef(r);a.current=r;const o=l.useRef(null),i=l.useRef(null),[,c]=l.useState("disconnected"),d=l.useCallback((h,v)=>{c(h),dr==null||dr(h,v)},[]),p=l.useRef(null),u=l.useRef(),m=l.useRef(zd),f=l.useRef(!0),g=l.useRef(!1),k=l.useRef("initial_connect");return l.useEffect(()=>{f.current=!0,g.current=!1;function h(){var b,j;if(!f.current||((b=p.current)==null?void 0:b.readyState)===WebSocket.OPEN||((j=p.current)==null?void 0:j.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${Xr}...`),Xn("connect_attempt",{url:Xr,reason:k.current,delayMs:m.current});let w;try{w=new WebSocket(Xr)}catch(C){console.error("[Standalone WS] Failed to create WebSocket:",C),v();return}p.current=w,w.onopen=()=>{if(!f.current){w.close();return}d("connected"),m.current=zd,Xn("open",{url:Xr,reason:k.current}),us.resubscribeAll({sendData:Di}),console.log("[Standalone WS] Connected")},ls=w,w.onmessage=C=>{var y,x;try{const N=JSON.parse(C.data);if((N.type==="command_result"||N.type==="error")&&N.requestId){const S=Da.get(N.requestId);S&&(Da.delete(N.requestId),N.type==="error"?S.reject(new Error(((y=N.data)==null?void 0:y.message)||"Command failed")):S.resolve(N.data));return}if(N.type==="session_output"){const S=N.sessionId||N.cliId||N.cliType;S&&vs.emitSessionOutput(S,typeof N.data=="string"?N.data:"",typeof N.seq=="number"?N.seq:void 0);return}if(N.type==="runtime_snapshot"){vs.emitRuntimeSnapshot(N.sessionId,typeof N.text=="string"?N.text:"",typeof N.seq=="number"?N.seq:0,!!N.truncated,typeof N.cols=="number"?N.cols:void 0,typeof N.rows=="number"?N.rows:void 0);return}if(N.type==="topic_update"){const S=N.update;S&&us.publish(S);return}if(N.type==="status"||N.type==="initial_state"){const S=N.data;if(!S)return;const{injectEntries:A,markLoaded:M,getIdes:P}=t.current,D=S.instanceId||"standalone",I=P().find(H=>H.id===D),_=ZD(D);vs.register(D,_),vs.setState(D,"connected"),d("connected",D),vs.emitStatus(D,S);const W=ga(S,{daemonId:D,existingDaemon:I,existingEntries:P()});Kd("ws_status",{type:N.type,daemonId:D,sessions:(S.sessions||[]).map(H=>({id:H.id,parentId:H.parentId,providerType:H.providerType,kind:H.kind,transport:H.transport,unread:H.unread,inboxBucket:H.inboxBucket,lastSeenAt:H.lastSeenAt,lastUpdated:H.lastUpdated,title:H.title})),recentLaunches:(S.recentLaunches||[]).map(H=>({id:H.id,providerType:H.providerType,kind:H.kind,workspace:H.workspace,lastLaunchedAt:H.lastLaunchedAt}))}),Kd("entries",{daemonId:D,entries:W.filter(H=>H.type!=="adhdev-daemon").map(H=>({id:H.id,type:H.type,unread:H.unread,inboxBucket:H.inboxBucket,lastSeenAt:H.lastSeenAt,lastUpdated:H.lastUpdated,sessionId:H.sessionId}))}),W.length>0&&A(W,{authoritativeDaemonIds:[D]}),M(),i.current!==D&&((x=o.current)==null||x.call(o),i.current=D,o.current=us.subscribe({sendData:Di},D,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${D}`,params:{includeSessions:!0}},H=>{if(H.topic!=="daemon.metadata")return;const L=t.current.getIdes(),O=L.find(T=>T.id===D),E=ga(H.status,{daemonId:D,existingDaemon:O,existingEntries:L,timestamp:H.timestamp});E.length>0&&t.current.injectEntries(E,{authoritativeDaemonIds:[D]}),H.userName&&a.current&&a.current(H.userName)}))}}catch(N){console.error("[Standalone WS] Parse error:",N)}},w.onclose=C=>{f.current&&(Zt==null||Zt.stopScreenshots(),Zt&&vs.setState(Zt.daemonId,"disconnected"),d("disconnected"),p.current=null,k.current=`close:${C.code}${C.wasClean?":clean":":unclean"}`,Xn("close",{code:C.code,reason:C.reason||"",wasClean:C.wasClean}),v())},w.onerror=C=>{g.current||!f.current||(k.current="error",Xn("error",{message:C instanceof Event?"event":String(C),readyState:w.readyState}),console.warn("[Standalone WS] Error, will reconnect:",C))}}function v(){if(!f.current)return;clearTimeout(u.current);const w=m.current;console.log(`[Standalone WS] Reconnecting in ${w}ms...`),Xn("schedule_reconnect",{reason:k.current,delayMs:w}),u.current=setTimeout(()=>{m.current=Math.min(m.current*1.5,YD),h()},w)}return h(),()=>{var w;f.current=!1,g.current=!0,(w=o.current)==null||w.call(o),o.current=null,i.current=null,clearTimeout(u.current),p.current&&(p.current.onerror=null,p.current.onclose=null,p.current.close(),p.current=null,ls=null),Zt&&(Zt.stopScreenshots(),vs.unregister(Zt.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function tP({children:e}){const[t,n]=l.useState("disconnected"),[r,a]=l.useState(null);l.useEffect(()=>(dr=(i,c)=>{n(i),c&&a(c)},()=>{dr=null}),[]);const o=l.useMemo(()=>{const i=t==="connected",c=QD(t),d={};return r&&(d[r]=c),d.standalone=c,{wsStatus:t,isConnected:i,connectionStates:d}},[t,r]);return s.jsx(xf,{connectionOverrides:o,children:s.jsx(eP,{children:e})})}const Sh="adhdev_standalone_font_preferences",tn={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Qa=[{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"}],yr=[{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"}],sP=new Set(Qa.map(e=>e.id)),nP=new Set(yr.map(e=>e.id));function ws(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:da("chat",t.chat),code:da("code",t.code),terminal:da("terminal",t.terminal)}}function da(e,t){const n=tn[e],r=t&&typeof t=="object"&&!Array.isArray(t)?t:{},a=typeof r.preset=="string"?r.preset.trim():"",o=typeof r.customFamily=="string"?r.customFamily.trim():"";return(e==="chat"?sP:nP).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:n:{preset:a}:n}function ua(e,t){var a;const n=da(e,t);if(n.preset==="custom"&&n.customFamily)return n.customFamily;const r=e==="chat"?Qa:yr;return((a=r.find(o=>o.id===n.preset))==null?void 0:a.family)||r[0].family}function rP(e){const t=ws(e),n=ua("chat",t.chat),r=ua("code",t.code),a=ua("terminal",t.terminal);return{"--chat-font-family":n,"--chat-code-font-family":r,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function Ks(e,t=document.documentElement){const n=ws(e),r=rP(n);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(r))t.style.setProperty(a,o);return n}function Pi(e){const t=ws(e);try{localStorage.setItem(Sh,JSON.stringify(t))}catch{}return t}function aP(){try{const e=localStorage.getItem(Sh);if(e)return ws(JSON.parse(e))}catch{}return tn}function oP(){return Ks(aP())}function Zn(e,t){var r;const n=e==="chat"?Qa:yr;return((r=n.find(a=>a.id===t))==null?void 0:r.label)||n[0].label}function iP({children:e}){const t=wr(),n=Ri(),{t:r}=Se("common"),a=l.useMemo(()=>[{id:"dashboard",path:"/dashboard",icon:s.jsx(lu,{}),label:r("standalone.nav.dashboard"),active:n.pathname.startsWith("/dashboard"),onSelect:()=>t("/dashboard")},{id:"machine",path:"/machines",icon:s.jsx(_s,{}),label:"Burrow",active:n.pathname.startsWith("/machines"),onSelect:()=>t("/machines")},{id:"mesh",path:"/mesh",icon:s.jsx(ts,{}),label:"Mesh",active:n.pathname.startsWith("/mesh"),onSelect:()=>t("/mesh")},{id:"settings",path:"/settings",icon:s.jsx(La,{}),label:r("standalone.nav.settings"),active:n.pathname.startsWith("/settings"),onSelect:()=>t("/settings")}],[n.pathname,t,r]),o=l.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:r("standalone.nav.docs")}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(du,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:r("standalone.nav.docs")},{id:"about",label:r("standalone.nav.about"),icon:s.jsx(Hi,{}),active:n.pathname==="/about",onSelect:()=>t("/about"),title:r("standalone.nav.about")}],[n.pathname,t,r]);return s.jsx(qS,{brand:({collapsed:i})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&s.jsx("span",{children:"ADHDev"})]}),navItems:a,footerItems:o,footerInfo:({collapsed:i})=>i?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","1.0.20"]}),footerActions:({collapsed:i,toggleCollapsed:c})=>s.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:c,title:r(i?"standalone.layout.expandSidebar":"standalone.layout.collapseSidebar"),children:[s.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&s.jsx("span",{className:"text-xs",children:r("standalone.layout.collapse")})]}),children:e})}const lP=[{icon:s.jsx(_s,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(ln,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(mu,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(hs,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(mr,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(du,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],cP=[{icon:s.jsx(Vf,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(lu,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Rn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Wf,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(cu,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Gf,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],dP=[{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 uP(){const{t:e}=Se("common");return s.jsxs(jr,{icon:s.jsx(Hi,{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.20"]}),children:[s.jsx(ht,{children:s.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[s.jsxs("div",{className:"max-w-2xl",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:e("standalone.about.selfHostedEdition")}),s.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:e("standalone.about.headline")}),s.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:e("standalone.about.description")})]}),s.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.docs")}),s.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.github")}),s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.tryCloud")})]})]})}),s.jsx(ht,{title:e("standalone.about.includedSection"),description:e("standalone.about.includedDescription"),children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:lP.map(t=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:t.icon}),t.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:t.desc})]},t.title))})}),s.jsx(ht,{title:e("standalone.about.inventorySection"),description:e("standalone.about.inventoryDescription"),children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:Wp.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:Gp.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:Up.map(t=>`${t.icon} ${t.name}`)}].map(t=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[s.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:t.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:t.items.map(n=>s.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:n},n))})]},t.label))})}),s.jsx(ht,{title:e("standalone.about.cloudExtrasSection"),description:e("standalone.about.cloudExtrasDescription"),children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:cP.map(t=>s.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:t.icon}),t.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:t.desc})]},t.title))})}),s.jsx(ht,{title:e("standalone.about.comparisonSection"),description:e("standalone.about.comparisonDescription"),children:s.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:s.jsxs("table",{className:"w-full text-[13px]",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"bg-bg-secondary",children:[s.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:e("standalone.about.featureHeader")}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:e("standalone.about.selfhostHeader")}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:e("standalone.about.cloudHeader")})]})}),s.jsx("tbody",{children:dP.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(Ga,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:e("standalone.about.cloudOptional"),description:e("standalone.about.cloudOptionalDescription"),action:s.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:e("standalone.about.compareCloud")}),s.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[s.jsx(nb,{size:14,className:"mr-1"}),e("standalone.about.discord")]})]})})]})}function Vo(e,t,n){return{...e,[t]:n}}function Yo({surface:e,title:t,description:n,value:r,options:a,onChange:o}){const{t:i}=Se("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(YS,{value:r.preset,onChange:c=>{const d=c.target.value;o(d==="custom"?{preset:"custom",customFamily:r.customFamily||""}:{preset:d})},children:a.map(c=>s.jsx("option",{value:c.id,children:c.label},c.id))}),r.preset==="custom"&&s.jsx(ds,{type:"text",className:"font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:r.customFamily||"",onChange:c=>o({preset:"custom",customFamily:c.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:i("standalone.fonts.resolvedStack")})," ",s.jsx("span",{className:"font-mono break-all",children:ua(e,r)})]})]})]})}function pP({value:e,savedValue:t,saving:n=!1,error:r,notice:a,onChange:o,onSave:i,onResetToSaved:c,onResetToDefaults:d}){const{t:p}=Se("common"),u=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:p("standalone.fonts.fontOverridesNotice")}),r&&s.jsx(Ht,{variant:"error",children:r}),a&&s.jsx(Ht,{variant:"success",children:a}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(Yo,{surface:"chat",title:p("standalone.fonts.chat"),description:p("standalone.fonts.chatDescription"),value:e.chat,options:Qa,onChange:m=>o(Vo(e,"chat",m))}),s.jsx(Yo,{surface:"code",title:p("standalone.fonts.code"),description:p("standalone.fonts.codeDescription"),value:e.code,options:yr,onChange:m=>o(Vo(e,"code",m))}),s.jsx(Yo,{surface:"terminal",title:p("standalone.fonts.terminal"),description:p("standalone.fonts.terminalDescription"),value:e.terminal,options:yr,onChange:m=>o(Vo(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: ",Zn("chat",e.chat.preset)," · Code: ",Zn("code",e.code.preset)," · Terminal: ",Zn("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[p("standalone.fonts.defaults")," ",Zn("chat",tn.chat.preset)," / ",Zn("code",tn.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(Ns,{type:"button",variant:"primary",size:"sm",onClick:i,disabled:n||!u,children:p(n?"standalone.fonts.saving":"standalone.fonts.saveFontSettings")}),s.jsx(Ns,{type:"button",variant:"secondary",size:"sm",onClick:c,disabled:n||!u,children:p("standalone.fonts.revertToSaved")}),s.jsx(Ns,{type:"button",variant:"secondary",size:"sm",onClick:d,disabled:n,children:p("standalone.fonts.resetToDefaults")})]})]})}function mP(){const{t:e}=Se("common"),{ides:t}=Ss(),n=t.find(B=>B.type==="adhdev-daemon"),r=(n==null?void 0:n.detectedIdes)||[],{sendCommand:a}=vt(),{userName:o}=Ss(),[i,c]=l.useState(o||""),[d,p]=l.useState(null),[u,m]=l.useState(null),[f,g]=l.useState(tn),[k,h]=l.useState(!1),[v,w]=l.useState(""),[b,j]=l.useState(""),[C,y]=l.useState("127.0.0.1"),[x,N]=l.useState(""),[S,A]=l.useState(""),[M,P]=l.useState(""),[D,I]=l.useState(""),[_,W]=l.useState(""),[H,L]=l.useState(!1),O=async()=>{const ie=await(await ys("/auth/session")).json();p(ie)},E=async()=>{const ie=await(await ys("/api/v1/standalone/preferences")).json();m(ie),y(ie.standaloneBindHost);const K=ws(ie.standaloneFontPreferences);g(K),Ks(K),Pi(K)};l.useEffect(()=>{o!==void 0&&c(o)},[o]),l.useEffect(()=>{Promise.all([O(),E()]).catch(B=>{I(B instanceof Error?B.message:String(B))})},[]),l.useEffect(()=>{Ks(f)},[f]);const T=B=>{const ie=B.target.value.trim();n!=null&&n.id&&ie!==o&&a(n.id,"set_user_name",{userName:ie}).catch(console.error)},[$,R]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),G=B=>{R(B);try{localStorage.setItem("adhdev_sound",B?"1":"0")}catch{}},Q=async()=>{w(""),j(""),h(!0);try{const B=ws(f),ie=await ys("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:B})}),K=await ie.json();if(!ie.ok)throw new Error((K==null?void 0:K.error)||"Failed to save standalone font preferences");const le=ws(K.standaloneFontPreferences);m(K),g(le),Ks(le),Pi(le),j(e("standalone.settings.fontsSaved"))}catch(B){w(B instanceof Error?B.message:String(B))}finally{h(!1)}},re=()=>{const B=ws(u==null?void 0:u.standaloneFontPreferences);w(""),j(""),g(B),Ks(B)},J=()=>{w(""),j(""),g(tn),Ks(tn)},X=async()=>{I(""),W(""),L(!0);try{const B=await ys("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:C})}),ie=await B.json();if(!B.ok)throw new Error((ie==null?void 0:ie.error)||"Failed to save standalone network preference");m(ie),y(ie.standaloneBindHost),W(ie.standaloneBindHost==="0.0.0.0"?e("standalone.settings.networkSavedAll"):e("standalone.settings.networkSavedLocal"))}catch(B){I(B instanceof Error?B.message:String(B))}finally{L(!1)}},ue=async()=>{if(I(""),W(""),S.trim().length<4){I(e("standalone.settings.passwordTooShort"));return}if(S!==M){I(e("standalone.settings.passwordMismatch"));return}L(!0);try{const B=await ys("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:x,newPassword:S})}),ie=await B.json();if(!B.ok)throw new Error((ie==null?void 0:ie.error)||"Failed to save password");p(ie),await E(),N(""),A(""),P(""),W(d!=null&&d.hasPasswordAuth?e("standalone.settings.passwordUpdated"):e("standalone.settings.passwordEnabled")),wh()}catch(B){I(B instanceof Error?B.message:String(B))}finally{L(!1)}},se=async()=>{I(""),W(""),L(!0);try{const B=await ys("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:x,clear:!0})}),ie=await B.json();if(!B.ok)throw new Error((ie==null?void 0:ie.error)||"Failed to clear password");p(ie),await E(),N(""),A(""),P(""),W(e("standalone.settings.passwordDisabled"))}catch(B){I(B instanceof Error?B.message:String(B))}finally{L(!1)}};return s.jsxs(jr,{icon:s.jsx(La,{className:"text-text-primary"}),title:e("standalone.settings.title"),subtitle:e("standalone.settings.subtitle"),widthClassName:"max-w-5xl",children:[s.jsx(Ht,{variant:"info",children:e("standalone.settings.infoNotice")}),(d==null?void 0:d.publicHostWarning)&&s.jsx(Ht,{variant:"warning",children:e("standalone.settings.publicHostWarning")}),s.jsx(ht,{title:e("standalone.settings.daemonSection"),description:e("standalone.settings.daemonDescription"),children:s.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.versionLabel")}),s.jsxs("span",{className:"font-mono text-xs",children:["v","1.0.20"]}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.statusLabel")}),s.jsx("span",{className:n?"text-green-400":"text-yellow-400",children:e(n?"standalone.settings.statusRunning":"standalone.settings.statusNotConnected")}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.currentBindLabel")}),s.jsx("span",{className:"font-mono text-xs",children:(u==null?void 0:u.currentBindHost)||(d==null?void 0:d.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.defaultBindLabel")}),s.jsx("span",{className:"font-mono text-xs",children:(u==null?void 0:u.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.authLabel")}),s.jsx("span",{className:"text-xs",children:d!=null&&d.hasPasswordAuth?e("standalone.settings.authPassword"):d!=null&&d.hasTokenAuth?e("standalone.settings.authToken"):e("standalone.settings.authNone")})]})}),s.jsx(ht,{title:e("standalone.settings.networkSection"),description:e("standalone.settings.networkDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:e("standalone.settings.networkHint")}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:C==="127.0.0.1",onChange:()=>y("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:e("standalone.settings.localhostLabel")}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:e("standalone.settings.localhostHint")})]})]}),s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:C==="0.0.0.0",onChange:()=>y("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:e("standalone.settings.allInterfacesLabel")}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:e("standalone.settings.allInterfacesHint")})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx(Ns,{type:"button",variant:"primary",size:"sm",onClick:()=>{X()},disabled:H,children:e(H?"standalone.settings.saving":"standalone.settings.saveNetworkMode")}),s.jsx("span",{className:"text-xs text-text-muted",children:e("standalone.settings.networkRestartHint",{host:(u==null?void 0:u.currentBindHost)||(d==null?void 0:d.boundHost)||"127.0.0.1"})})]})]})}),s.jsx(ht,{title:e("standalone.settings.securitySection"),description:e("standalone.settings.securityDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:d!=null&&d.hasPasswordAuth?e("standalone.settings.passwordSet"):e("standalone.settings.passwordNotSet")}),D&&s.jsx(Ht,{variant:"error",children:D}),_&&s.jsx(Ht,{variant:"success",children:_}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx(ds,{type:"password",placeholder:d!=null&&d.hasPasswordAuth?e("standalone.settings.currentPasswordPlaceholder"):e("standalone.settings.currentPasswordFirstTimePlaceholder"),value:x,onChange:B=>N(B.target.value)}),s.jsx(ds,{type:"password",placeholder:d!=null&&d.hasPasswordAuth?e("standalone.settings.newPasswordPlaceholder"):e("standalone.settings.newPasswordFirstTimePlaceholder"),value:S,onChange:B=>A(B.target.value)}),s.jsx(ds,{type:"password",className:"md:col-span-2",placeholder:e("standalone.settings.confirmPasswordPlaceholder"),value:M,onChange:B=>P(B.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ns,{type:"button",variant:"primary",size:"sm",onClick:()=>{ue()},disabled:H,children:H?e("standalone.settings.saving"):d!=null&&d.hasPasswordAuth?e("standalone.settings.updatePassword"):e("standalone.settings.enablePassword")}),(d==null?void 0:d.hasPasswordAuth)&&s.jsx(Ns,{type:"button",variant:"danger",size:"sm",onClick:()=>{se()},disabled:H,children:e("standalone.settings.disablePassword")})]})]})}),s.jsx(ht,{title:e("standalone.settings.detectedIdesSection"),description:e("standalone.settings.detectedIdesDescription"),children:r.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:e("standalone.settings.noIdesDetected")}):s.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(B=>s.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${B.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:B.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:B.type})]},B.type))})}),s.jsx(ht,{title:e("standalone.settings.machineSection"),description:e("standalone.settings.machineDescription"),children:s.jsx(nC,{ides:t,emptyMessage:e("standalone.settings.daemonNotConnected")})}),s.jsx(ht,{title:e("standalone.settings.appearanceSection"),description:e("standalone.settings.appearanceDescription"),children:s.jsx(SC,{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(pP,{value:f,savedValue:ws(u==null?void 0:u.standaloneFontPreferences),saving:k,error:v,notice:b,onChange:g,onSave:()=>{Q()},onResetToSaved:re,onResetToDefaults:J})]})})}),s.jsx(ht,{title:e("standalone.settings.notificationsSection"),description:e("standalone.settings.notificationsDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(ZS,{}),s.jsx(zs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(sb,{size:15})," ",e("standalone.settings.soundEffectsLabel")]}),description:e("standalone.settings.soundEffectsDescription"),checked:$,onChange:G})]})}),s.jsx(ht,{title:e("standalone.settings.profileSection"),description:e("standalone.settings.profileDescription"),children:s.jsx("div",{className:"flex flex-col gap-3",children:s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[s.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[s.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[s.jsx(Of,{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(ds,{type:"text",className:"w-48 text-right",placeholder:e("standalone.settings.displayNamePlaceholder"),value:i,onChange:B=>c(B.target.value),onBlur:T,onKeyDown:B=>{B.key==="Enter"&&B.currentTarget.blur()}})]})})})]})}const hP=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],sr="adhdev_onboarding_done",fP=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],bP={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function gP({onDone:e}){const{t}=Se("common"),[n,r]=l.useState([]),[a,o]=l.useState(new Set(hP)),[i,c]=l.useState(!0),[d,p]=l.useState(null),[u,m]=l.useState(!1),[f,g]=l.useState(null),[k,h]=l.useState("all");l.useEffect(()=>{let x=!1;const N=window.location.hostname==="localhost"?"/registry":"https://api.adhf.dev/api/v1/registry";return fetch(`${N}/providers?sort=popular&limit=100`).then(S=>{if(!S.ok)throw new Error(`HTTP ${S.status}`);return S.json()}).then(S=>{x||r(S.providers??[])}).catch(S=>{x||p(S instanceof Error?S.message:String(S))}).finally(()=>{x||c(!1)}),()=>{x=!0}},[]);const v=n.filter(x=>k==="all"||x.category===k),w=["cli","ide","extension","acp"].map(x=>({category:x,items:v.filter(N=>N.category===x)})).filter(x=>x.items.length>0),b=l.useCallback(x=>{o(N=>{const S=new Set(N);return S.has(x)?S.delete(x):S.add(x),S})},[]),j=l.useCallback(async()=>{if(a.size===0){localStorage.setItem(sr,"1"),e();return}m(!0);const x=[];for(const N of a)try{const A=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:N})})).json().catch(()=>({}));x.push({type:N,ok:!!A.success,error:A.error})}catch(S){x.push({type:N,ok:!1,error:S instanceof Error?S.message:String(S)})}g(x),m(!1),x.every(N=>N.ok)&&localStorage.setItem(sr,"1")},[a,e]),C=l.useCallback(()=>{localStorage.setItem(sr,"1"),e()},[e]),y=l.useCallback(()=>{f&&f.every(x=>x.ok)?e():u||C()},[f,u,e,C]);return s.jsx(Yu,{open:!0,onClose:y,size:"lg",contentClassName:"max-w-2xl",title:t("standalone.onboarding.title"),footer:s.jsxs("div",{className:"flex w-full items-center gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:t(a.size!==1?"standalone.onboarding.selectedCount_other":"standalone.onboarding.selectedCount_one",{count:a.size})}),s.jsxs("div",{className:"ml-auto flex gap-2",children:[s.jsx(Ns,{variant:"secondary",size:"sm",onClick:C,disabled:u,children:t("standalone.onboarding.skip")}),s.jsx(Ns,{variant:"primary",size:"sm",onClick:()=>{f?(localStorage.setItem(sr,"1"),e()):j()},disabled:u||!f&&a.size===0,children:u?t("standalone.onboarding.installing"):f?t("standalone.onboarding.done"):t("standalone.onboarding.installCount",{count:a.size})})]})]}),children:s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsx("div",{className:"text-[12px] text-text-muted",children:t("standalone.onboarding.intro")}),!i&&!d&&n.length>0&&s.jsx("div",{className:"flex gap-1 flex-wrap border-b border-border-subtle pb-2",children:fP.map(x=>{const N=x.key==="all"?n.length:n.filter(S=>S.category===x.key).length;return N===0&&x.key!=="all"?null:s.jsxs("button",{onClick:()=>h(x.key),className:`machine-btn text-[10px] px-2 py-0.5 ${k===x.key?"bg-accent-primary/12 border-accent-primary/40 text-accent-primary":""}`,children:[x.label," ",s.jsxs("span",{className:"opacity-60",children:["(",N,")"]})]},x.key)})}),i&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.loadingRegistry")}),!i&&d&&s.jsx(Ht,{variant:"error",children:t("standalone.onboarding.loadError",{error:d})}),!i&&!d&&v.length===0&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.noProviders")}),!i&&!d&&v.length>0&&s.jsx("div",{className:"flex flex-col gap-4",children:w.map(x=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:bP[x.category]??x.category}),s.jsx("div",{className:"grid gap-1.5",children:x.items.map(N=>{var D,I;const S=a.has(N.type),A=f==null?void 0:f.find(_=>_.type===N.type),M=((D=N.manifest)==null?void 0:D.icon)??"📦",P=((I=N.manifest)==null?void 0:I.details)??"";return s.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${S?"bg-accent-primary/[0.06] border-accent-primary/30":"bg-bg-glass border-border-subtle hover:bg-bg-glass-hover"}`,children:[s.jsx("input",{type:"checkbox",checked:S,onChange:()=>b(N.type),disabled:u,className:"shrink-0"}),s.jsx("span",{className:"text-base shrink-0",children:M}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[13px] font-medium text-text-primary truncate",children:N.displayName}),P&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:P})]}),A&&s.jsx("span",{className:`text-[10px] font-semibold ${A.ok?"text-status-online":"text-status-error"}`,children:A.ok?t("standalone.onboarding.installed"):t("standalone.onboarding.installFailed",{error:A.error??"failed"})})]},N.type)})})]},x.category))})]})})}function xP(){try{return localStorage.getItem(sr)==="1"}catch{return!1}}RS();fC();Cy();oP();const vP=tu({baseUrl:"",getToken:Tl});function yP({children:e}){const{t}=Se("common"),[n,r]=l.useState(null),[a,o]=l.useState(!0),[i,c]=l.useState(""),[d,p]=l.useState(""),[u,m]=l.useState(!1),f=async()=>{o(!0),p("");try{const h=await(await ys("/auth/session")).json();r(h)}catch(k){p(k instanceof Error?k.message:String(k))}finally{o(!1)}};l.useEffect(()=>{f()},[]),l.useEffect(()=>{if(!n||n.required&&!n.authenticated)return;let k=!1;return(async()=>{try{const h=await ys("/api/v1/standalone/preferences");if(!h.ok)return;const v=await h.json();if(k)return;const w=ws(v.standaloneFontPreferences);Ks(w),Pi(w)}catch{}})(),()=>{k=!0}},[n==null?void 0:n.authenticated,n==null?void 0:n.required]);const g=async k=>{k.preventDefault(),m(!0),p("");try{const h=await ys("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),v=await h.json();if(!h.ok)throw new Error((v==null?void 0:v.error)||"Login failed");r(v),c(""),wh()}catch(h){p(h instanceof Error?h.message:String(h))}finally{m(!1)}};return a?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:t("standalone.auth.loading")}):n?!n.required||n.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:t("standalone.auth.signInTitle")}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:n.hasPasswordAuth?t("standalone.auth.passwordProtected"):t("standalone.auth.tokenProtected")})]}),n.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:g,children:[s.jsx(ds,{type:"password",value:i,onChange:k=>c(k.target.value),placeholder:t("standalone.auth.passwordPlaceholder"),autoFocus:!0}),s.jsx(Ns,{type:"submit",variant:"primary",disabled:u||!i,className:"justify-center",children:t(u?"standalone.auth.signingIn":"standalone.auth.unlock")})]}):s.jsx(Ht,{variant:"warning",children:t("standalone.auth.noPasswordEnabled")}),d&&s.jsx(Ht,{variant:"error",children:d})]})}):s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:t("standalone.auth.loadError",{error:d||"unknown error"})})}function Vd(){const{t:e}=Se("common"),{ides:t,initialLoaded:n}=Ss();if(!n)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:e("standalone.machine.loading")});const r=t.find(a=>a.daemonMode||a.type==="adhdev-daemon");return r?s.jsx(Zo,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Zo,{to:"/dashboard",replace:!0})}function wP(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let n=!1;if(!xP())return fetch("/api/v1/providers/installed").then(r=>r.ok?r.json():{providers:[]}).then(r=>{n||(r.providers??[]).length===0&&t(!0)}).catch(()=>{}),()=>{n=!0}},[]),e?s.jsx(gP,{onDone:()=>t(!1)}):null}function kP(){const{t:e}=Se("common"),{ides:t}=Ss(),n=l.useMemo(()=>{for(const u of t)if(u.activeInteractivePrompt)return u.instanceId??u.id;return null},[t]),{promptSession:r,hasActivePrompt:a,responseError:o,isSubmitting:i,submit:c,cancel:d,reopen:p}=Qp(n);return a?s.jsxs("div",{className:"relative",children:[!r&&s.jsx("button",{type:"button",onClick:p,className:"fixed bottom-4 right-4 z-[79] btn btn-primary btn-sm shadow-lg",children:e("standalone.machine.awaitingInput")}),s.jsx(Au,{promptSession:r,isSubmitting:i,error:o,onSubmit:c,onCancel:d})]}):null}function SP(){const e=l.useMemo(()=>({sendCommand:ur,sendData:Di,sendPtyInput:kh}),[]);return s.jsx(ef,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(wf,{client:vP,children:s.jsx(yP,{children:s.jsx(tP,{children:s.jsx(Sf,{value:e,children:s.jsxs(Af,{sendDaemonCommand:ur,children:[s.jsx(kP,{}),s.jsxs(iP,{children:[s.jsx(wP,{}),s.jsxs(tf,{children:[s.jsx(Ps,{path:"/dashboard",element:s.jsx(wT,{})}),s.jsx(Ps,{path:"/machine",element:s.jsx(Vd,{})}),s.jsx(Ps,{path:"/machines/:id",element:s.jsx(TI,{})}),s.jsx(Ps,{path:"/machines",element:s.jsx(Vd,{})}),s.jsx(Ps,{path:"/about",element:s.jsx(uP,{})}),s.jsx(Ps,{path:"/settings",element:s.jsx(mP,{})}),s.jsx(Ps,{path:"/mesh",element:s.jsx(qD,{children:s.jsx(WD,{})})}),s.jsx(Ps,{path:"*",element:s.jsx(Zo,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}Mk({connectionManager:vs});sf(document.getElementById("root")).render(s.jsx(SP,{}));
|